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

//define your token
error_reporting(E_ALL ^ E_NOTICE);
$id=get('id','i');
$data=m('weixin')->getRow(" select * from ".table('weixin')." WHERE id=".$id." ");
if(empty($data)){
	exit('wrong');
}
define("TOKEN", $data['token']);
define("WID",$data['id']);
define("SHOPID",$data['shopid']);
$wechatObj = new wxshopapiControl();
if($data['status']==0){
	$wechatObj->valid();
	exit;
}

$wechatObj->responseMsg();
/*空数据*/
function wx_error($data="抱歉出错了"){
	global $db,$wechatObj;
	$textTpl = "<xml>
								<ToUserName><![CDATA[".$wechatObj->fromUsername."]]></ToUserName>
								<FromUserName><![CDATA[".$wechatObj->toUsername."]]></FromUserName>
								<CreateTime>".time()."</CreateTime>
								<MsgType><![CDATA[text]]></MsgType>
								<Content><![CDATA[".$data."]]></Content>
								<FuncFlag>0</FuncFlag>
								</xml>"; 
		exit($textTpl);
}
/*开始Click命令*/
function wxclick_0(){	
	global $db;
	$data=$db->getRow("SELECT * FROM ".table('weixin_menu')." WHERE wid=".WID." AND w_key='wxclick_0' ");
	if($data['sc_id']){
		wx_sucai($data['sc_id']);	
	}else{
		wx_tuwen($data['content']);
	}
}

function wxclick_1(){
	global $db;
	if(SHOPID){
		$w=" AND shopid=".SHOPID;
	}
	$data=$db->getAll("select * from ".table('cai')." WHERE siteid=".SITEID." AND visible=1 $w ");
	$data=parse_cai($data);
	wx_tuwen($data);
}

function parse_cai($data){
	if(empty($data)) return false;
	foreach($data as $v){
				$ndata[]=array(
					"title"=>$v['title']." ".$v['price'],
					"imgurl"=>$v['thum_img']?IMG_SITE.$v['thum_img']:(IMG_SITE."images/nologo.gif"),
					"description"=>$v['decription']?$v['decription']:$v['title'],
					"url"=>"http://".$_SERVER['HTTP_HOST']."/index.php?m=cai&a=show&id=".$v['id'],
				);
	}
	return $ndata;
}
/*结束Click命令*/
/*素材显示*/
function wx_sucai($id){
	global $db,$wechatObj;
	$data=$db->getRow("SELECT * FROM ".table('weixin_sucai')." WHERE id=".$id." ");
	file_put_contents(ROOT_PATH."log.txt",serialize($data));
	if($data){
		$child=$db->getAll("SELECT * FROM ".table('weixin_sucai')." WHERE pid=".$id." ");
		$content="<item>
	<Title><![CDATA[".$data['title']."]]></Title> 
	<Description><![CDATA[".$data['description']."]]></Description>
	<PicUrl><![CDATA[".IMG_SITE.$data['imgurl']."]]></PicUrl>
	<Url><![CDATA[".($data['linkurl']?$data['linkurl']:"http://".$_SERVER['HTTP_HOST']."/index.php?m=weixin_sucai&a=show&id=".$data['id'])."]]></Url>
	</item>";
		if($child){
			foreach($child as $r){
				$content.="<item>
	<Title><![CDATA[".$r['title']."]]></Title> 
	<Description><![CDATA[".$r['description']."]]></Description>
	<PicUrl><![CDATA[".IMG_SITE.$r['imgurl']."]]></PicUrl>
	<Url><![CDATA[".($r['linkurl']?$r['linkurl']:"http://".$_SERVER['HTTP_HOST']."/index.php?m=weixin_sucai&a=show&id=".$r['id'])."]]></Url>
	</item>\n";
			}
		}
			$textTpl = "<xml>
					<ToUserName><![CDATA[".$wechatObj->fromUsername."]]></ToUserName>
					<FromUserName><![CDATA[".$wechatObj->toUsername."]]></FromUserName>
					<CreateTime>".time()."</CreateTime>
					<MsgType><![CDATA[news]]></MsgType>
					<ArticleCount>".(count($child)+1)."</ArticleCount>
					<Articles>".$content."</Articles>				 
				</xml>";
		echo $textTpl;
		exit;		
	}else{
		wx_error();
	}
}


/*图文显示*/

function wx_tuwen($data){
	global $wechatObj;
	if(empty($data) or !is_array($data)){
		if(empty($data)){
			$data="无法回复您的问题";
		}
		$textTpl = "<xml>
							<ToUserName><![CDATA[".$wechatObj->fromUsername."]]></ToUserName>
							<FromUserName><![CDATA[".$wechatObj->toUsername."]]></FromUserName>
							<CreateTime>".time()."</CreateTime>
							<MsgType><![CDATA[text]]></MsgType>
							<Content><![CDATA[".$data."]]></Content> 
							<FuncFlag>0</FuncFlag>
							</xml>"; 
		echo  $textTpl;
		exit;
	}
	$content="";
	foreach($data as $r){
			  $content.="<item>
	<Title><![CDATA[".$r['title']."]]></Title> 
	<Description><![CDATA[".$r['description']."]]></Description>
	<PicUrl><![CDATA[".$r['imgurl']."]]></PicUrl>
	<Url><![CDATA[".$r['url']."]]></Url>
	</item>\n";
			}
 
	$textTpl = "<xml>
					<ToUserName><![CDATA[".$wechatObj->fromUsername."]]></ToUserName>
					<FromUserName><![CDATA[".$wechatObj->toUsername."]]></FromUserName>
					<CreateTime>".time()."</CreateTime>
					<MsgType><![CDATA[news]]></MsgType>
					<ArticleCount>".count($data)."</ArticleCount>
					<Articles>".$content."</Articles>				 
				</xml>";
	echo  $textTpl;
	exit;
}

class wxshopapiControl
{
	public $fromUsername;
	public $toUsername;
	public $MsgId;
	public $MsgType;
	public $reply_id=0;
	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()
    {
		global $db;
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		//$postStr="aaa";
		//file_put_contents("log.txt",$postStr);
      	//extract post data
		if (!empty($postStr)){
                
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $this->fromUsername=$fromUsername = $postObj->FromUserName;
                $this->toUsername=$toUsername = $postObj->ToUserName;
                $keyword=$content = trim($postObj->Content);
				$this->MsgId=$MsgId=$postObj->MsgId;
				$this->MsgType=$MsgType=$postObj->MsgType;
				$picurl=$postObj->PicUrl;
				$MediaId=$postObj->MediaId;
				$ThumbMediaId=$postObj->ThumbMediaId;
				$format=$postObj->Format;
				$location_x=$postObj->Location_X;
				$location_y=$postObj->Location_y;
				$scale=$postObj->Scale;
				$label=$postObj->Label;
				$title=$postObj->Title;
				$descripton=$postObj->Description;
				$url=$postObj->Url;
				$event=$postObj->Event;
				$EventKey=$postObj->EventKey;
				//插入响应数据
				$redata=array(
					"openid"=>$toUsername,
					"msgtype"=>$MsgType,
					"content"=>$content,
					"msgid"=>$MsgId,
					"picurl"=>$picurl,
					"mediaid"=>$MediaId,
					"thumbmediaid"=>$ThumbMediaId,
					"format"=>$format,
					"location_x"=>$location_x,
					"location_y"=>$location_y,
					"scale"=>$scale,
					"label"=>$label,
					"title"=>$title,
					"description"=>$descripton,
					"url"=>$url,
					"createtime"=>time(),
					"siteid"=>SITEID,
					"wid"=>WID,
					"fromusername"=>$fromUsername,
					"tousername"=>$toUsername,
					
				);
				$this->reply_id=$db->insert("weixin_reply",$redata);
			//	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>
							[@content@]
							<FuncFlag>0</FuncFlag>
							</xml>"; 
				$user=$db->getRow(" select * from ".table('weixin_user')." WHERE openid='".$toUsername."' AND wid=".WID );
				
				//处理订阅与取消订阅			
				if($MsgType=='event'){
					
					if($event=='subscribe'){
						if($user){
							$db->update("weixin_user",array(
								"openid"=>$toUsername,
								"add_time"=>time(),
								"last_time"=>time(),
								"status"=>1,
							)," AND openid='".$toUsername."' AND wid=".WID);
						}else{
							$db->insert("weixin_user",array(
								"openid"=>$toUsername,
								"dateline"=>time(),
								"add_time"=>time(),
								"last_time"=>time(),
								"status"=>1,
								"siteid"=>SITEID,
								"wid"=>WID
							));
						}
						 
						$this->subscribe();
						
					}elseif($event=='unsubscribe'){
						if($user){
							$db->update("weixin_user",array(
								"openid"=>$toUsername,
								"del_time"=>time(),
								"last_time"=>time(),
								"status"=>0,
							)," AND openid='".$toUsername."' AND wid=".WID);
						}else{
							$db->insert("weixin_user",array(
								"openid"=>$toUsername,
								"dateline"=>time(),
								"del_time"=>time(),
								"last_time"=>time(),
								"status"=>0,
								"siteid"=>SITEID,
								"wid"=>WID
							));
						}
					}elseif($event=='CLICK'){
						
						$this->ClickReply($EventKey);
						
						
					}elseif($event=='SCAN'){//二维码扫描
						$ticket=$postObj->Ticket;
						$this->qrsceneReply($EventKey,$ticket,$fromUsername,$toUsername);				
					} 
					
					$row=$db->selectRow(" SELECT * FROM ".table('weixin_command')." WHERE  type_id=2  AND wid=".WID);
					if($row['sc_id']){
						wx_sucai($row['sc_id']);
					}
					$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $MsgType);
					$contentStr="<MsgType><![CDATA[text]]></MsgType>
						<Content><![CDATA[".$row['content']."]]></Content>";
					echo $resultStr=str_replace("[@content@]",$contentStr,$resultStr);
					exit;
						
				}elseif($MsgType=='location'){
					$lat=$postObj->lat;
					$lng=$postObj->lng;
					$this->locationReply($lat,$lng,$fromUsername,$toUsername);
				}elseif($MsgType=='voice'){
					$this->voiceReply($MediaId,$fromUsername,$toUsername);
				}elseif($MsgType=='video'){
					$this->videoReply($MsgId,$ThumbMediaId,$fromUsername,$toUsername);
				}elseif($MsgType=='picture'){
					$this->pictureReply($picurl,$MediaId,$fromUsername,$toUsername);
				}
				//End
				
				//处理用户
				
				if(empty($user)){
					$db->insert("weixin_user",array(
						"openid"=>$toUsername,
						"dateline"=>time(),
						"last_time"=>time(),
						"reply_num"=>1,
						"wid"=>WID, 
						"siteid"=>SITEID,
					));
				
				}else{
					$db->update("weixin_user",array(
						"last_time"=>time(),
						"reply_num"=>$user['reply_num']+1,
					)," AND openid='".$toUsername."' AND wid=".WID);
				}
				//插入回复
			 	
                $time = time();
                           
				if(!empty( $keyword ))
                {
              		$msgType = "text";
                	$arr = $this->getContent($keyword);
					
					$contentStr=$arr['content'];
					if($arr['error']==0){
						$db->update("weixin_reply",array("status"=>1)," AND id=".$this->reply_id);
					}
					 
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType);
					$resultStr=str_replace("[@content@]",$contentStr,$resultStr);
					$resultStr=str_replace(array("性交","乱伦","性欲望"),"",$resultStr);
					ob_start();
					echo $resultStr;
					$ct=ob_get_contents();
					file_put_contents(ROOT_PATH."log.txt",$ct);
					
					exit;
                }else{
					$row=$db->getRow("SELECT * FROM ".table('weixin_command')." WHERE  type_id=2 AND wid=".WID );
					if($row['sc_id']){
						wx_sucai($row['sc_id']);
					}elseif(empty($row)){
						$row['content']="暂无数据";
					}
					file_put_contents(ROOT_PATH."log.txt","aaaa".date("Y-m-d H:i:s"));
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType);
					$contentStr="<MsgType><![CDATA[text]]></MsgType>
						<Content><![CDATA[".$row['content']."]]></Content>";
					echo $resultStr=str_replace("[@content@]",$contentStr,$resultStr);
					exit;
                }
				
				 

        }else {
        	echo "";
        	exit;
        }
    }
		
	private function checkSignature()
	{
        $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 ){
			return true;
		}else{
			return false;
		}
	}
	
	/*菜单点击事件*/
	public function clickReply($key){
		
		switch($key){
			case "wxclick_0":
					wxclick_0();
				break;
			case "wxclick_1":
					wxclick_1();
				break;
			case "wxclick_2":
					wxclick_2();
				break;
			case "wxclick_3":
					wxclick_3();
				break;
		}
		wx_error();
		exit;
	}
	
	/*图片消息*/
	public function pictureReply($PicUrl,$MediaId,$fromUsername, $toUsername){
		$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>".time()."</CreateTime>
							[@content@]
							<FuncFlag>0</FuncFlag>
							</xml>"; 
		$resultStr = sprintf($textTpl, $fromUsername, $toUsername);
						$contentStr="<MsgType><![CDATA[text]]></MsgType>
							<Content><![CDATA[这是图片消息".$EventKey."]]></Content>";
		echo $resultStr=str_replace("[@content@]",$contentStr,$resultStr);
		exit;
	}
	/*语音*/
	public function voiceReply($MsgID,$fromUsername, $toUsername){
		$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>".time()."</CreateTime>
							[@content@]
							<FuncFlag>0</FuncFlag>
							</xml>"; 
		$resultStr = sprintf($textTpl, $fromUsername, $toUsername);
						$contentStr="<MsgType><![CDATA[text]]></MsgType>
							<Content><![CDATA[这是语音消息".$EventKey."]]></Content>";
		echo $resultStr=str_replace("[@content@]",$contentStr,$resultStr);
		exit;
	}
	
	/*视频*/
	public function videoReply($MsgID,$ThumbMediaId,$fromUsername, $toUsername){
		$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>".time()."</CreateTime>
							[@content@]
							<FuncFlag>0</FuncFlag>
							</xml>"; 
		$resultStr = sprintf($textTpl, $fromUsername, $toUsername);
						$contentStr="<MsgType><![CDATA[text]]></MsgType>
							<Content><![CDATA[这是视频消息".$EventKey."]]></Content>";
		echo $resultStr=str_replace("[@content@]",$contentStr,$resultStr);
		exit;
	}
	
	/*二维码扫描*/
	public function qrsceneReply($EventKey,$Ticket,$fromUsername, $toUsername){
		$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>".time()."</CreateTime>
							[@content@]
							<FuncFlag>0</FuncFlag>
							</xml>"; 
		$resultStr = sprintf($textTpl, $fromUsername, $toUsername);
						$contentStr="<MsgType><![CDATA[text]]></MsgType>
							<Content><![CDATA[这是二维码扫描事件".$EventKey."]]></Content>";
		echo $resultStr=str_replace("[@content@]",$contentStr,$resultStr);
		exit;
	}
	
	/*地理位置事件*/
	public function locationReply($lat,$lng,$fromUsername, $toUsername){
		$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>".time()."</CreateTime>
							[@content@]
							<FuncFlag>0</FuncFlag>
							</xml>"; 
		$resultStr = sprintf($textTpl, $fromUsername, $toUsername);
						$contentStr="<MsgType><![CDATA[text]]></MsgType>
							<Content><![CDATA[这是地理位置事件]]></Content>";
		echo $resultStr=str_replace("[@content@]",$contentStr,$resultStr);
		exit;
	}
	
	public function getContent($keyword){
		global $db;
		$s=explode(":",$keyword);
		$row=$db->getRow(" SELECT * FROM ".table('weixin_command')." WHERE command='".$s[0]."' AND wid=".WID);
		switch($row['type_id']){
			case 3://自定义
					if($row['sc_id']) wx_sucai($row['sc_id']);
					wx_tuwen($row['content']);
				break;
			case 4:
					$this->cai($keyword);
				break;
			case 5:
					$this->caipu($keyword);
				break;
			default:
					$row=$db->getRow(" SELECT * FROM ".table('weixin_command')." WHERE  type_id=2 AND wid=".WID);
					if(empty($row['content'])){
						$row['content']="暂无数据";
					}
					return array(
						"error"=>1,
						"content"=>"<MsgType><![CDATA[text]]></MsgType>
						<Content><![CDATA[".$row['content']."]]></Content>"
					);
				break;
		}
		 
		
	}
	public function cai($wxdata){
		global $db;
		$data=$db->getAll("SELECT * FROM ".table('cai')."  WHERE shopid=".SHOPID." ");
		if($data){
			$db->update("weixin_reply",array("status"=>1)," AND id=".$this->reply_id);
			foreach($data as $v){
				$ndata[]=array(
					"title"=>$v['title']." ".$v['price'],
					"imgurl"=>$v['thum_img']?IMG_SITE.$v['thum_img']:(IMG_SITE."images/nologo.gif"),
					"description"=>$v['decription']?$v['decription']:$v['title'],
					"url"=>"http://".$_SERVER['HTTP_HOST']."/index.php?m=cai&a=show&id=".$v['id'],
				);
			}
		}
		
		wx_tuwen($ndata);
	}
	public function caipu($keyword){
		global $db;
		$data=$db->getAll("SELECT * FROM ".table('caipu')."  ");
		if($data){
			$db->update("weixin_reply",array("status"=>1)," AND id=".$this->reply_id);
			foreach($data as $v){
				$ndata[]=array(
					"title"=>$v['title']." ".$v['price'],
					"imgurl"=>$v['imgurl']?IMG_SITE.$v['imgurl']:(IMG_SITE."images/nologo.gif"),
					"description"=>$v['decription']?$v['decription']:$v['title'],
					"url"=>"http://".$_SERVER['HTTP_HOST']."/index.php?m=caipu&a=show&id=".$v['id'],
				);
			}
		}
		wx_tuwen($data);
	}
	
	public function subscribe(){
		global $db;
		$row=$db->getRow(" SELECT * FROM ".table('weixin_command')." WHERE  type_id=1  AND wid=".WID);
		$db->update("weixin_reply",array("status"=>1)," AND id=".$this->reply_id);
		if($row['sc_id']){
			wx_sucai($row['sc_id']);
		}else{
			$content=!empty($row['content'])?$row['content']:"感谢你的关注";
			echo '<xml>
<ToUserName><![CDATA['.$this->fromUsername.']]></ToUserName>
<FromUserName><![CDATA['.$this->toUsername.']]></FromUserName>
<CreateTime>'.time().'</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA['.$content.']]></Content>
</xml>';
			exit;
		}
	}
	
}

?>