<?php
/**
  * wechat php test
  */

//define your token
error_reporting(E_ALL ^ E_NOTICE);
define("TOKEN", "asdqweqweq");
$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();

$wechatObj->responseMsg();

function wx_tuwen($data,$tousername,$fromusername){
	if(empty($data) or !is_array($data)){
		
		$textTpl = "<xml>
							<ToUserName><![CDATA[".$tousername."]]></ToUserName>
							<FromUserName><![CDATA[".$fromusername."]]></FromUserName>
							<CreateTime>".time()."</CreateTime>
							<MsgType><![CDATA[text]]></MsgType>
							<Content><![CDATA[".$data."]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>"; 
		return $textTpl;
	}
	$textTpl = "<xml>
					<ToUserName><![CDATA[".$tousername."]]></ToUserName>
					<FromUserName><![CDATA[".$fromusername."]]></FromUserName>
					<CreateTime>".time()."</CreateTime>
					<MsgType><![CDATA[news]]></MsgType>
					<ArticleCount>".count($data)."</ArticleCount>
					<Articles>".$content."</Articles>
					<FuncFlag>0</FuncFlag>
				</xml>";
	return $textTpl;
}

class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }
	
	public function post(){
		$textTpl="<xml>
 <ToUserName><![CDATA[%s]]></ToUserName>
 <FromUserName><![CDATA[%s]]></FromUserName> 
 <CreateTime>%s</CreateTime>
 <MsgType><![CDATA[%s]]></MsgType>
 <Content><![CDATA[%s]]></Content>
 <MsgId>0</MsgId>
 </xml>";
	}

    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		//file_put_contents("log.txt",$postStr);
      	//extract post data
		if (!empty($postStr)){
                
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
				$MsgId=$postObj->MsgId;
				$MsgType=$postObj->MsgType;
			//	file_put_contents("log.txt",$postStr."$fromUsername $toUsername $keyword $MsgId $MsgType");
			 
                $time = time();
                $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";             
				if(!empty( $keyword ))
                {
              		$msgType = "text";
					if(substr($keyword,0,3)=='ms '){//模糊搜索
						$keyword=trim(str_replace("ms ","",$keyword));
						$data=$GLOBALS['db']->getAll("select * from ".table('caipu')." WHERE title like '%".addslashes($keyword)."%' limit 10 ");
						if($data){
							$contentStr="找到".$keyword."相关美食:\r\n";
							foreach($data as $k=>$v){
								$contentStr.=($k+1).".".$v['title']."\r\n";
							}
							$contentStr.="请输入 c 美食 查看内容。";
						}else{
							$contentStr = "没有你所要找的美食哦";
						}
					}elseif(substr($keyword,0,2)=='c '){//获取第一条
						$keyword=trim(str_replace("c ","",$keyword));
						$d=$GLOBALS['db']->getRow("select * from ".table('caipu')." WHERE title like '%".addslashes($keyword)."%' limit 1 ");
						if(empty($d)){
							$contentStr = "没有你所要找的美食哦";
						}else{
							
							$contentStr = $d['title']."\n\r".$d['description']."\n\r详情点击： http://".$_SERVER['HTTP_HOST']."/index.php?m=caipu&a=show&id=".$d['id'];
						}
						 
					}elseif(substr($keyword,0,2)=='dc'){
						$contentStr=" 点击网址进入订餐：http://".$_SERVER['HTTP_HOST'];
					}else{
						$contentStr = "欢迎关注挑食客，我会给你们推荐更多美食的哦。 
					帮助说明：
					1.输入ms 猪肉 查找猪肉相关 或者 ms 猪肉  白菜 查找组合美食
					2.输入c 洋葱炒鸡蛋 直接获取洋葱炒鸡蛋的内容 
					3.输入dc 进入订餐";
					}
					
                	
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
					//file_put_contents("log.txt",$resultStr);
                	echo $resultStr;
                }else{
                	echo $contentStr = "欢迎关注挑食客，我会给你们推荐更多美食的哦。 
					帮助说明：
					1.输入ms 猪肉 查找猪肉相关 或者 ms 猪肉  白菜 查找组合美食
					2.输入c 洋葱炒鸡蛋 直接获取洋葱炒鸡蛋的内容 
					3.输入dc 进入订餐";
					
                }

        }else {
        	echo "";
        	exit;
        }
    }
		
	private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}

?>