<?php
namespace Wechat\Controller;
use Think\Controller;
header("Content-Type:text/html;charset=utf-8");
class ConfigController extends Controller {
	public function index()
    {
		define("TOKEN", "weixin");
		if (!isset($_GET['echostr'])) {
		    $this -> responseMsg();
		} else {
		    $this -> valid();
		}
	}
	
   /**
    * 响应消息
    */
	public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $this -> logger("R " . $postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            //消息类型分离
            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this -> receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this -> receiveText($postObj);
                    break;
                default:
                    $result = "unknown msg type";
                    break;
            }
            $this -> logger("T " . $result);
            echo $result;
        }else {
            echo "";
            exit;
        }
    }
	
    /**
     * 接收文本消息
     */
 	private function receiveText($object)
	{
		$content = "xxxx";
		if(is_array($content)){
			if (isset($content[0]['PicUrl'])){
				$result = $this -> transmitNews($object, $content);
			}
		}else{
			$result = $this -> transmitTextSer($object, $content);
		}
		return $result;
	}

    /**
     * 日志记录
     */
    private function logger($log_content)
    {
        if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
            $max_size = 10000;
            $log_filename = "log.xml";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
        }
    }
	
	/**
     * 接收事件消息
     */
    public function receiveEvent($object)
    {
    	
        $content = "欢迎关注xxx";
        switch ($object->Event)
        {
            case "subscribe":
                //==============关注事件===============
                // 获取OpenID
				$openid=trim($object->FromUserName);
                // 获取推广会员ID
				// $upuser = str_replace("qrscene_", "", $object->EventKey);//去掉前缀
                // $content = $object->EventKey;
                break;
            case "unsubscribe":
                //==============取消关注事件===============
                // 放置
                break;
            case "SCAN":
                //==============已关注时从二维码进来===============
                //获取OpenID
                $openid=trim($object->FromUserName);
                //获取推广会员ID
                $upuser=str_replace("qrscene_","",$object->EventKey);//去掉前缀
                if ($upuser!='') {
                    //向用户推送 注册链接
                    $content="请点击链接完成注册\r\nhttp://".$_SERVER['HTTP_HOST'].U("Person/reg", array("uid" => $upuser));
                }
                // $content=$object->EventKey;
                break;
            default:
                // $content = "技术支持 深米科技";
                break;
        }

        if(is_array($content)){
            if (isset($content[0]['PicUrl'])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $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 transmitText($object, $content)
    {
        $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 transmitTextSer($object, $content){
        $xmlTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[transfer_customer_service]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

    /**
     * 验证签名
     */
 	public function valid(){
        $echoStr = $_GET["echostr"];
        $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){
            echo $echoStr;
            exit;
   		}
	}
}