<?php
/**
 * User-Agentに合わせて、適切なテンプレートを読み込むための処理。
 * $Id: TemplateAction.inc,v 1.7 2010/03/31 10:16:30 wanggb Exp $
 * @package jp.fishow.handler
 * @access  public
 * @author  hr_wanggb
 * @version $Revision: 1.7 $
 */

class TemplateAction {
	
	public $channel_no;
	public $is_wechat;
	public $user;

	/**
	 * コンストラクタ。
	 */
	function __construct() {
		//渠道ID
		if(isset($_SESSION['channel_no'])){
			$this->channel_no = $_SESSION['channel_no'];
		} else if(ParamUtil::isRequestSet("channel_no")){
			$this->channel_no =ParamUtil::getRequestString("channel_no");
			$_SESSION['channel_no'] = $this->channel_no;
		}
		//是否是微信打开
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
			$this->is_wechat = 1;
		} else {
			$this->is_wechat = 0;
		}
		//已经登陆的情况下，从session中取出
		if(isset($_SESSION['_user_'])){
			$this->user = $_SESSION['_user_'];
		} else {
			//没有的情况下获取参数
			$mobile = ParamUtil::getRequestString("mobile");
			$tmp_user = null;
			if(!empty($mobile)) {
				$tmp_user = UserHandler::getUserByMobile($mobile);
			}
			//临时数据
			if(!empty($tmp_user)) {
				$tmp_user = new UserMst();
				$tmp_user->channel_no = $$this->channel_no;
				$tmp_user->status = -1;
			}
			$this->user = $tmp_user;
			$_SESSION['_user_'] = $this->user;
		}
	}
	
	/**
	 * 通过微信登录，取和用户基础信息，成功存Session
	 */
	function getWechatSnsapiUserinfo() {
		$wechat_userinfo = null;
		$code = ParamUtil::getRequestString("code");
		$state = ParamUtil::getRequestString("state");
		$redirect_url = "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
		if ($this->getLoginResultUrl() == null) {
			$this->setLoginResultUrl($redirect_url);
		}
		$scope_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . WECHAT_APP_ID ."&redirect_uri="  . urlencode($redirect_url) ."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		if (!empty($code)) {
			//通过code换取网页授权access_token
			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" .WECHAT_APP_ID ."&secret=" . WECHAT_APP_SECRET ."&code=" . $code . "&grant_type=authorization_code";
			$result = json_decode($this->getCurl($url));
			//检验授权凭证（access_token）是否有效
			$access_token = $result->access_token;
			$open_id = $result->openid;
			$re_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token ."&openid=" .$open_id. "&lang=zh_CN";
			$result = json_decode($this->getCurl($re_url));
			if(!empty($result)){
				$wechat_userinfo = new stdClass();
				$wechat_userinfo->openid = $result->openid;
				$wechat_userinfo->nickname = $result->nickname;
				$wechat_userinfo->area = $result->province;
				$wechat_userinfo->sex = ($result->sex == 1 ? 'MALE' : 'FEMALE');
				$wechat_userinfo->direct_pay_enabled = true;
				$_SESSION["wechat_userinfo"] = $wechat_userinfo;
				header("location:" . $this->getLoginResultUrl());
				exit;
			}
		} else {
			if (empty($state)) {
				header("location:" . $scope_url);
				exit;
			}
		}
		
		$page_title = "认证失败";
		$error_message = "微信认证失败。";
		$this->includeTemplate("error.inc");
		exit;
	}
	
	/**
	 * 是否登陆状态
	 */
	function isLogin() {
		$login = false;
		if(!empty($this->user) && $this->user->status != -1 && (strtolower(get_class($_SESSION["_user_"])) == "usermst")) {
			$login = true;
		}
		return $login;
	}

	/**
	 * 指定した名前(ファイル名から拡張子を取ったもの)のテンプレートを読み込み、
	 * includeします。
	 * @param String $page_name テンプレートの名前。
	 */
	function includeTemplate($page_name) {
		include(SCHOOL_TEMPLATE_DIR . "/header.inc");
		include(SCHOOL_TEMPLATE_DIR . "/" . $page_name);
		include(SCHOOL_TEMPLATE_DIR . "/footer.inc");
	}
	
	/**
	 * 指定した名前(ファイル名から拡張子を取ったもの)のテンプレートを読み込み、
	 * includeします。
	 * @param String $page_name テンプレートの名前。
	 */
	function includeTemplatePromotion($page_name) {
		include(SCHOOL_TEMPLATE_DIR . "/header.inc");
		include(SCHOOL_TEMPLATE_DIR . "/" . $page_name);
		include(SCHOOL_TEMPLATE_DIR . "/footer_promotion.inc");
	}
	
	function includeTemplateMy($page_name) {
		include(SCHOOL_TEMPLATE_DIR . "/header_my.inc");
		include(SCHOOL_TEMPLATE_DIR . "/" . $page_name);
		include(SCHOOL_TEMPLATE_DIR . "/footer_my.inc");
	}
	
	function includeTemplateNoFooter($page_name) {
		include(SCHOOL_TEMPLATE_DIR . "/header.inc");
		include(SCHOOL_TEMPLATE_DIR . "/" . $page_name);
		include(SCHOOL_TEMPLATE_DIR . "/footer_blank.inc");
	}
	
	/**
	 * 指定した名前(ファイル名から拡張子を取ったもの)のテンプレートを読み込み、
	 * includeします。
	 * @param String $page_name テンプレートの名前。
	 */
	function includeSSLTemplate($page_name) {
		include(SSL_TEMPLATE_DIR . "/header.inc");
		include(SSL_TEMPLATE_DIR . "/" . $page_name);
		include(SSL_TEMPLATE_DIR . "/footer.inc");
	}
	function includeSSLTemplateNoFooter($page_name) {
		include(SSL_TEMPLATE_DIR . "/header.inc");
		include(SSL_TEMPLATE_DIR . "/" . $page_name);
		include(SSL_TEMPLATE_DIR . "/footer_blank.inc");
	}
	
	/**
	 * CURLでＨｔｔｐ請求
	 * @param unknown $url
	 */
	function getCurl($url) {
		$ch = curl_init();
		$timeout = 5;
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$file_contents = curl_exec($ch);
		curl_close($ch);
	
		return $file_contents;
	}
}