<?php
include('sava/conn.php');
$result = mysql_query('select * from yycms_wx');
$row = mysql_fetch_array($result);
include('sava/simple_html_dom.php');
error_reporting(0); //禁用错误报告
define('TOKEN', $row['wx_token']); //定义常量
define('DOMAIN', $row['wx_url']); //定义常量
define('WEI', '1'); //定义常量
define('GUANZHU', $row['wx_hf']); //定义常量
define('TISHI', $row['wx_ts']); //定义常量
$wechatObj = new wechatCallbackapiTest();//实例化类
if (isset($_GET['echostr'])) { //如果随机字符串存在
$wechatObj->valid(); //执行wechatObj类下的valid函数
}else{
	$wechatObj->responseMsg(); //如果未得到随机字符串，执行wechatObj类下的responseMsg函数
}

class wechatCallbackapiTest  //定义类
{
    //验证签名
    public function valid()
    {
      	header('content-type:text');   
        ob_clean(); 
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            echo $echoStr;
            exit;
        }
    }
  	//响应消息
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        //$postStr = 'huihui';      //调试用
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            // $RX_TYPE = "text";//gnagcai  zhege  meiqudiao
            //消息类型分离
            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                default:
                    $result = "unknown msg type: ".$RX_TYPE;
                    break;
            }
            echo $result;
        }else {
            echo "";
            exit;
        }
    }
//接收事件消息
private function receiveEvent($object)
{
	$content = "";
	global $webname;
        switch ($object->Event)
        {
            //关注公众号事件
            case "subscribe":
                $content = "".GUANZHU."";

                //$content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
                break;
            //取消关注
            case "unsubscribe":
                $content = "取消关注";
                break;
        }

        if(is_array($content)){
            $result = $this->transmitNews($object, $content);
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }
    //接收文本消息
    private function receiveText($object)
    {

        $a = ($object->Content);
        $keyword = trim(addslashes($a));//关键字
        $arr = $this->keywordSearch($keyword);
        $result="";
        if (is_array($arr)) {
            if (isset($arr[0])) {
                $result = $this->transmitNews($object, $arr);
            }
        } else {
            $result = $this->transmitText($object, $arr);
        }
        return $result;
    }
    //接收语音消息
    private function receiveVoice($object)
    {

        $a = ($object->Recognition);
      	 $keyword = trim(addslashes($a));//关键字
        $arr = $this->keywordSearch($keyword);
        $result="";
        if (is_array($arr)) {
            if (isset($arr[0])) {
                $result = $this->transmitNews($object, $arrr);
            }
        } else {
            $result = $this->transmitText($object, $arrr);
        }
        return $result;
    }
    //接收图片消息
    private function receiveImage($object)
    {
        $content = array("MediaId"=>$object->MediaId);
        $result = $this->transmitImage($object, $content);
        return $result;
    }
	    //回复文本消息
    private function transmitText($object, $content)
    {
        if (!isset($content) || empty($content)){
            return "";
        }
        
        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);

        return $result;
    }
	    //回复图文消息
    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return "";
        }
        $itemTpl = "        <item>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
        </item>";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[news]]></MsgType>
                            <ArticleCount>%s</ArticleCount>
                            <Articles>
                        $item_str    </Articles>
                        </xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }

       //回复图片消息
    private function keywordSearch($keyword)
    {
$result = mysql_query('select * from yycms_vod where b_name like "%'.$keyword.'%" order by b_id desc');
$seach=file_get_contents('https://so.360kan.com/index.php?kw='.$keyword);
$szz='#js-playicon" title="(.*?)"\s*data-logger#';
//$szz1='#a href="(.*?)" class="g-playicon js-playicon"#';
$szz2='#<img src="(.*?)" alt="(.*?)" />#';//图片
$szz8='#<p( class="js-m-descwrap")?>(.*)</p>#';//简介

preg_match_all($szz,$seach,$sarr);
//preg_match_all($szz1,$seach,$sarr1);
preg_match_all($szz2,$seach,$sarr2);
preg_match_all($szz8,$seach,$sarr8);
$one=$sarr[1];//标题
$two=$sarr2[1];//图片
//$nine =$sarr1[0];//地址
$ba=$sarr8[0];//简介
if (count($one)>0||mysql_num_rows($result)) {
     $row = mysql_fetch_array($result);
        $tupian=$row['b_tp'];
        $cs=$row['b_name'];
        $jianjie=$row['b_jj'];
        $cc="./qxplay/";
        $dd="./qxplay/";
        $chuandi=$cc.$row['b_id'];  
        if ($row!=false) {
           $arr[] = array(
                    "Title" =>"【".$cs."】官网点击在线观看",
                    "Description" => $jianjie,
                    "PicUrl" => $tupian,
                    "Url" => DOMAIN.$chuandi.".html"
                );
        }
                if (count($arr)==0) {
                    $arr[] = array(
                        "Title" => "《".$keyword."》搜索成功【点击查看搜索结果】",
                        "Description" => str_replace("&nbsp;", "", strip_tags($ba[0])),
                        "PicUrl" => $two[0],
                       "Url" => DOMAIN.'search-'.$keyword.'.html'
                    );
                }
}

        if(count($arr)>0){
                  /* $arr[] = array(
                    "Title" =>"点此分享公众号",
                    "Description" => "分享公众号",
                    "PicUrl" => "http://www.whalefall.net/uploadfile/image/20180414/20180414220347_69191.jpg",
                    "Url" => "http://www.whalefall.net/uploadfile/image/20180414/20180414220347_69191.jpg"
                );*/
            }else{
                $arr =  "".TISHI."";
              /*$arr="【影片解析地址故障，明天修复】

              请点击：<a href='".DOMAIN."'>在线官网</a>观看

              可以在官网里面搜索。给大家带来的不便尽请谅解！";*/
            }
        
        return  $arr;
    }

}
?>