Demo entry 6361484

Base.php 编程语言php 数据库mysql 总行数 337行

   

Submitted by anonymous on May 04, 2017 at 12:57
Language: PHP. Code size: 11.0 kB.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

abstract class Base extends CI_Controller {
    public  $requsttoken="";
	public function __construct(){
		parent::__construct();
        $this->load->library('session');
        $this->load->library('smarty');
		$this->load->helper('common');
		$this->load->helper('weixin');
        $this->load->helper('url');
		$this->load->library('snsclass');
		$this->load->model('User_model');
        $this->load->model('Token_model');
        if(isset($_SESSION["tokenreq"])){
            $this->requsttoken=$_SESSION["tokenreq"];
        }else{
            $this->requsttoken=$this->Token_model->gettoken();
            $_SESSION["tokenreq"]= $this->requsttoken;
        }

	}

	// 测试微信授权
	protected $debug = 1;
	// 当前登录用户
	protected $user_login = null;
	// 跳转地址,分享地址
	protected $redirect_url = '';

    private $auth_type = 0;
    const AUTH_TYPE_NONE = 1;
    const AUTH_TYPE_BASE = 2;
    const AUTH_TYPE_USERINFO = 3;
    // 连续两个流程一块校验
    const AUTH_TYPE_BOTH = 4;

    private function loginTest(){
        // 测试用户,方便在浏览器端调试
        //$this->user_login_test = (object)array('uid'=>6,'pk_user'=>6,'sex'=>1,'is_wefit'=>0,'is_store_manager'=>1,'openid'=>'o9SjKwvhy6tSaMfoBrlJqfYWgYxE','nickname'=>'like','headimgurl'=>'http://wx.qlogo.cn/mmopen/O1dAhMERUwXdhzfogS6BjI4BGgicZzEZNU5n35tDIQhNjjTvej6BlE1DfuJlGKukcRLge2wpeZ4iaFK5V3rAG79w/0');
        if(!empty($this->user_login_test)){
            $this->user_login = $this->user_login_test;
            return true;
        }
        return false;
    }

    /**
     * 需要微信授权
     */
    protected function needWeixinAuth($auth_type = self::AUTH_TYPE_USERINFO){
        $this->auth_type = $auth_type;
        if($this->loginTest()){
            return true;
        }
        // 如果不验证直接返回
        if($auth_type == self::AUTH_TYPE_NONE){
            return true;
        }
		if($this->debug){
			//unset($_SESSION['userid']);unset($_SESSION['openid']);unset($_SESSION['state']);exit('清理session--注释并重来');
			//file_put_contents('/tmp/authorize.like', json_encode(compact('request')), FILE_APPEND);
			log_message('error','网页授权--request_uri='.json_encode($_SERVER['REQUEST_URI']));
		}
        // 判断用户是登录
		if($this->User_model->is_login()){
			$this->setUserInfo();
            return true;
		}
        $this->setRedirectUrl();
        $this->checkWeixinAuth(); 

        $session_state = $this->User_model->get_weixin_auth_state();
        if($auth_type == self::AUTH_TYPE_BASE){
            if($session_state == self::AUTH_TYPE_BASE){
                return true;
            }
            $this->weixinAuthBase();
        }elseif($auth_type == self::AUTH_TYPE_USERINFO){
            if($session_state == self::AUTH_TYPE_USERINFO){
                return true;
            }
            $this->weixinAuthUserinfo();
        }
    }

    private function startWeixinAuth($scope, $state_to_weixin){
        $state = isset($_GET['state'])?$_GET['state']:'';
        if(empty($state)){
            if($this->debug){
                log_message('error','网页授权'.$this->auth_type.'--发起授权--request_uri='.json_encode($_SERVER['REQUEST_URI']));
            }
            // 发起base授权请求
        //   var_dump($this->redirect_url,$scope,$state_to_weixin);
          //  exit();
			$snsapi_url = $this->snsclass->get_snsapi_url($this->redirect_url,$scope,$state_to_weixin);
			header('Location: '.$snsapi_url);
			exit;
        }
    }

    private function getWeixinToken(){
        if($this->debug){
            log_message('error','网页授权'.$this->auth_type.'--接受并处理授权--request_uri='.json_encode($_SERVER['REQUEST_URI']));
        }
        // 处理base返回请求
        $code = isset($_GET['code'])?$_GET['code']:'';
        // 用户未同意
        if(empty($code)){
            return false;
        }
        // 同意之后根据code换取token
        $token = $this->snsclass->get_access_token($code);
        if(empty($token)){
            return false;
        }

        return $token;
    }

    private function weixinAuthUserinfo(){

        $this->startWeixinAuth(WEIXIN_SNSAPI_SCOPE_USERINFO, WEIXIN_SNSAPI_SCOPE_USERINFO);	
        $token = $this->getWeixinToken();
        if(empty($token)){
            return false;
        }

        $this->loginByOpenid($token->openid);
        // 用户授权的时候更新一下用户信息
        // 这里可以相对实时的更新一部分用户的信息
        $user = $this->snsclass->get_userinfo($token->access_token,$token->openid);
        if($user){
            if(empty($this->user_login)){
                $userid = $this->User_model->add(
                    $token->openid,
                    empty($user->unionid)?'':$user->unionid,
                    WEIXIN_APPID,
                    $user->nickname,
                    User_model::STATE_UNSUBSCRIBE,
                    $user->sex,
                    $user->headimgurl,
                    $user->city,
                    $user->country,
                    $user->province,
                    $user->language,
                    empty($_GET['channel'])?'':$_GET['channel'],
                    empty($_GET['root'])?0:$_GET['root'],
                    $this->requsttoken->result->token
                );

                if($userid){
                    $user->pk_user = $userid;
                    $this->user_login = $user;
                    $this->User_model->login($this->user_login);

                    if($this->debug){
                        log_message('Debug','网页授权'.$this->auth_type.'--新增用户ID='.$userid);
                    }
                }else{
                    if($this->debug){
                        log_message('error','网页授权'.$this->auth_type.'--新增用户ID='.$userid);
                    }
                }
            }else{
                /*
                // 授权期限内,用户更新微信信息,这里也抓不到
                $affected = $this->User_model->baseinfo_update(
                    $this->user_login['pk_user'],
                    $user['nickname'],
                    $user['sex'],
                    $user['headimgurl'],
                    $user['city'],
                    $user['country'],
                    $user['province'],
                    $user['language']
                );

                if($affected){
                    $this->user_login['nickname'] = $user['nickname'];
                    $this->user_login['headimgurl'] = $user['headimgurl'];

                    if($this->debug){
                        log_message('debug','网页授权'.$this->auth_type.'--更新用户ID='.$this->user_login['pk_user']);
                    }
                }*/
            }
        }

        $this->User_model->set_weixin_auth_state(self::AUTH_TYPE_USERINFO);

        if($this->debug){
            log_message('error','网页授权'.$this->auth_type.'--处理后重定向到--'.$this->redirect_url.'--user_login='.json_encode($this->user_login));
        }
	
        header('Location: '.$this->redirect_url);
        exit;
    }

    private function weixinAuthBase(){
        $this->startWeixinAuth(WEIXIN_SNSAPI_SCOPE_BASE, WEIXIN_SNSAPI_SCOPE_BASE);	
        $token = $this->getWeixinToken();
        if(empty($token)){
            return false;
        }

        $this->loginByOpenid($token->openid);

        $this->User_model->set_weixin_auth_state(self::AUTH_TYPE_BASE);

        if($this->debug){
            log_message('error','网页授权'.$this->auth_type.'--处理后重定向到--'.$this->redirect_url.'--user_login='.json_encode($this->user_login));
            //exit('网页授权base debug end');
        }
	
        header('Location: '.$this->redirect_url);
        exit;
    }

    private function loginByOpenid($openid){
        $result = $this->User_model->get_by_openid($openid,$this->requsttoken->result->token);
        if (empty($result) or !is_object($result) or $result->error !== 0 ) {
            // 用户不存在,或者获取用户失败
        }else{
            $this->user_login = $result->result;
            if(!empty($this->user_login)){
                $this->User_model->login($this->user_login);
            }
        }
    }

    /**
     * 必须设置redirect url
     */
    abstract function setRedirectUrl();

    private function checkWeixinAuth(){
        if(empty($this->redirect_url)){
            exit('必须设置 redirect_url');
        }
    }

	public function setUserInfo(){
        if($this->loginTest()){
            return true;
        }
        if(isset($_SESSION['openid'])){

            $result = $this->User_model->get_by_openid($_SESSION['openid'],$this->requsttoken->result->token);

            if (empty($result) or
                !is_object($result) or 
                $result->error !== 0
             ) {


            }else{
                $result->result->uid = $result->result->pk_user;
                $this->user_login = $result->result;
            }
        }else{
            log_message('当前openid','网页授权'.$_SESSION['openid']);
        }
	}

    protected function needLogin(){
        $this->setUserInfo();
        if(empty($this->user_login)){
            echo "您还没有登录";
            exit;
        }
    }

    protected function needLoginJson(){
        $this->setUserInfo();
        if(empty($this->user_login)){
            echo json_encode($this->errorInfo('您还没有登陆'));
            exit;
        }
    }

    protected function errorInfo($info, $code = -1){
        return array('error'=> $code, 'info'=>$info);
    }

    protected function isWeixinClient(){
        $useragent = addslashes($_SERVER['HTTP_USER_AGENT']);
        if(strpos($useragent, 'MicroMessenger') === false && strpos($useragent, 'Windows Phone') === false){
            return false;
        }

        return true;
    }

    protected function getWeixinConfig($url){
        $this->load->library('token');
        $jsapi_ticket = $this->token->get_jsapi_ticket(WEIXIN_APPID);
        $jsapi_ticket = $jsapi_ticket->ticket;
        $apis = 'onMenuShareTimeline,onMenuShareAppMessage,scanQRCode';
        $config = wx_jsapi_config($url, $apis, $jsapi_ticket); 
       // var_dump($url, $apis, $jsapi_ticket);
      //  exit();
        return $config;
    }

    protected function formatUrl($url){
        if(null !== $this->input->get('authdo')){
            $url .= "&authdo=".$this->input->get('authdo');
        }
		if(null !== $this->input->get('from')){
			$url .= "&from=".$this->input->get('from');
		}
		if(null !== $this->input->get('isappinstalled')){
			$url .= "&isappinstalled=".$this->input->get('isappinstalled');
		}

        return $url;
    }

    protected function display($data){
        $template_dir = $this->smarty->template_dir[0];
        $tpl = $this->router->directory . $this->router->class . '/' . $this->router->method . '.tpl';
       
        if(!file_exists($template_dir . $tpl) || $this->input->get('debugo')){
            echo json_encode($data);
            exit;
        }

        if(defined('SMARTY_DEBUG') && SMARTY_DEBUG){
            $this->smarty->assign('CI', '为方便debug,把该变量清空');
            $this->smarty->debugging = true;
        }

        $this->smarty->display($tpl, $data);
    }

}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).