<?php

/* ========================================================================
 * $Id: login.weixin.php 8533 2019-08-13 10:08:18Z onez $
 * 
 * Email: www@onez.cn
 * QQ: 6200103
 * HomePage: http://www.onezphp.com
 * ========================================================================
 * Copyright 2016-2017 佳蓝科技.
 * 
 * ======================================================================== */

!defined('IN_ONEZ') && exit('Access Denied');
#名称：微信公众号登录
#标识：login.weixin

class onezphp_login_weixin extends onezphp{
  function __construct(){
    
  }
  function checklogin(){
    global $G;
    ob_clean();
    $rndkey=onez()->gp('rndkey');
    $ptoken=onez()->gp('ptoken');
    $sitetoken=onez()->gp('sitetoken');
    if($sitetoken){
      $G['this']=onez($sitetoken);
      if(defined('IS_ONEZ_WWW')){
        $G['this']->data_alias=$G['this']->cname;
      }
    }
    $third=onez('login.third')->check('weixin'," and key2='$rndkey'");
    if($third){
      !$ptoken && onez()->error('无效来源');
      $G['href_extra']['_p']='';
      $G['href_extra']['_m']='';
      $A['url']=onez($ptoken)->third_login_callback('login',$third,onez()->cururl(false,array('_p','_m','rndkey','ptoken')));
      onez('login.third')->update(array('key2'=>''));
      onez()->output($A);
    }
    onez()->error('等待扫描');
  }
  protected function removeEmoji($clean_text) {

    // Match Emoticons
    $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
    $clean_text = preg_replace($regexEmoticons, '', $clean_text);

    // Match Miscellaneous Symbols and Pictographs
    $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
    $clean_text = preg_replace($regexSymbols, '', $clean_text);

    // Match Transport And Map Symbols
    $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
    $clean_text = preg_replace($regexTransport, '', $clean_text);

    // Match Miscellaneous Symbols
    $regexMisc = '/[\x{2600}-\x{26FF}]/u';
    $clean_text = preg_replace($regexMisc, '', $clean_text);

    // Match Dingbats
    $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
    $clean_text = preg_replace($regexDingbats, '', $clean_text);

    return $clean_text;
  }
  function login(){
    global $G;
    if($G['this']->token==$this->token){
      $G['this']=onez('main');
    }
    $login_weixin_appid=$G['this']->option('login_weixin_appid');
    if($login_weixin_appid){
      $login_weixin_info=array(
        'wx_AppId'=>$login_weixin_appid,
        'wx_AppSecret'=>$G['this']->option('login_weixin_appsecret'),
      );
    }else{
      $login_weixin_info=$G['this']->myoption('login_weixin_info');
    }
/*
    $scookie=onez('scookie')->call('openid');
    if(!$scookie){
*/
      $appId=$login_weixin_info['wx_AppId'];
      $code=onez()->gp('code');
      if($code){
        $AppSecret=$login_weixin_info['wx_AppSecret'];
        $data=onez()->post('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appId.'&secret='.$AppSecret.'&code='.$code.'&grant_type=authorization_code');
        
        $S=json_decode($data,1);
        if(!$S['access_token']){
          onez('m')->error($S['errmsg']);
        }
        $openid=$S['openid'];
        
        $data=onez()->post('https://api.weixin.qq.com/sns/userinfo?access_token='.$S['access_token'].'&openid='.$openid.'&lang=zh_CN');
        $data=$this->removeEmoji($data);
        $S=json_decode($data,1);
        if($S['errcode']){
          onez('m')->error($S['errmsg']);
        }
        onez('scookie')->call('openid',$S['openid']);
        $callback_url=onez()->gp('callback_url');
        $rndkey=onez()->gp('rndkey');
        if($callback_url){
          $mobile=(int)onez()->gp('mobile');
          if($mobile){
            onez()->location($callback_url.'?_p='.$this->token.'&_m=loginok&mobile=1&'.http_build_query(array(
              'rndkey'=>$rndkey,
              'ptoken'=>onez()->gp('ptoken'),
              'sitetoken'=>onez()->gp('sitetoken'),
              'extra'=>onez()->gp('extra'),
              'data'=>$data,
            )));
          }
          $r=onez()->post($callback_url.'?_p='.$this->token.'&_m=loginok',http_build_query(array(
            'rndkey'=>$rndkey,
            'ptoken'=>onez()->gp('ptoken'),
            'sitetoken'=>onez()->gp('sitetoken'),
            'extra'=>onez()->gp('extra'),
            'data'=>$data,
          )));
        }
        onez()->location('?_m=m&action='.$this->action('login'));
      }
      $url=onez()->homepage().onez()->cururl();
      
      $goto='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appId.'&redirect_uri='.urlencode($url).'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
      onez()->location($goto);
/*
    }
    #已登录
    $callback_url=onez()->gp('callback_url');
    $rndkey=onez()->gp('rndkey');
    if($callback_url){
      onez()->post($callback_url.'?_p='.$this->token.'&_m=loginok',http_build_query(array(
        'rndkey'=>$rndkey,
        'ptoken'=>onez()->gp('ptoken'),
        'data'=>$data,
      )));
    }
    onez()->location('?_m=m&action='.$this->action('login'));
*/
  }
  function loginok(){
    global $G;
    $data=$_REQUEST['data'];
    $json=json_decode($data,1);
    $rndkey=onez()->gp('rndkey');
    $ptoken=onez()->gp('ptoken');
    $sitetoken=onez()->gp('sitetoken');
    $extra=onez()->gp('extra');
    $mobile=(int)onez()->gp('mobile');
    if($sitetoken){
      $G['this']=onez($sitetoken);
      if(defined('IS_ONEZ_WWW')){
        $G['this']->data_alias=$G['this']->cname;
      }
    }
    $openid=$json['openid'];
    $r=onez('login.third')->init(array(
      'ptoken'=>$ptoken,
      'third_name'=>'weixin',
      'third_token'=>$openid,
      'nickname'=>$json['nickname'],
      'avatar'=>$json['headimgurl'],
      'sex'=>$json['sex'],
      'prov'=>$json['province'],
      'city'=>$json['city'],
      'openid'=>$json['openid'],
      'unionid'=>$json['unionid'],
    ));
    if($mobile){
      onez($ptoken)->third_login_callback('login',$G['login.third'],onez()->cururl(false,array('_p','_m','rndkey','ptoken')));
      onez()->location('?_m=m');
    }
    if($ptoken && onez()->exists($ptoken)){
      if(method_exists(onez($ptoken),'loginok')){
        onez($ptoken)->loginok($json,$extra,$G['login.third']);
        return;
      }
    }
    onez('login.third')->update(array('key2'=>$rndkey));
    exit('ok'.$rndkey);
  }
  function mlink($ptoken,$proxy=false,$extra=false){
    global $G;
    $link='?_p='.$this->token.'&_m=login&ptoken='.$ptoken.'&sitetoken='.$G['this']->token.'&callback_url='.urlencode(onez()->homepage());
    if($proxy!==false){
      $link=$proxy.$link;
    }else{
      $link=onez()->homepage().$link;
    }
    if($extra){
      $link.='&extra='.urlencode($extra);
    }
    $link.='&mobile=1';
    return $link;
  }
  function link($ptoken,$proxy=false){
    global $G;
    $rndkey=md5(uniqid());
    #$link='?_m=m&action='.$this->action('login').'&rndkey='.$rndkey;
    $link='?_p='.$this->token.'&_m=login&rndkey='.$rndkey.'&ptoken='.$ptoken.'&sitetoken='.$G['this']->token.'&callback_url='.urlencode(onez()->homepage());
    if($proxy){
      $link=$proxy.$link;
    }else{
      $link=onez()->homepage().$link;
    }
    
    #移动端
    if($G['is_mobile']){
      if($G['is_weixin']){
        return $link.'&mobile=1';
      }else{
        return 'javascript:;" data-token="page" data-action="'.$this->action('notweixin');
      }
      return;
    }
    
    $checkurl='index.php?_p='.$this->token.'&_m=checklogin&sitetoken='.$G['this']->token;
    $qrcode=onez('qrcode')->pic($link);
    $code=<<<ONEZ
var _login_weixin_time=null;
function _login_weixin(){
  if(_login_weixin_time!=null){
    clearTimeout(_login_weixin_time);
    _login_weixin_time=null;
  }
  $('#_login_weixin').remove();
  $('<div id="_login_weixin"><div style="position: fixed;left: 0;top: 0;width: 100%;height: 100%;background: rgba(0,0,0,0.7);z-index:2147483647;"></div><div style="position: absolute;left: 50%;top: 50%;margin-left: -140px;margin-top: -150px;z-index:2147483647;background:#fff;padding:5px;border-radius:5px"><p style="padding:0;margin:0">请使用微信扫描以下二维码</p><img src="$qrcode" height="280" /></div></div>').appendTo('body');
  $('#_login_weixin').bind('click',function(){
    $('#_login_weixin').remove();
    if(_login_weixin_time!=null){
      clearTimeout(_login_weixin_time);
      _login_weixin_time=null;
    }
  });
  _login_weixin_check();
}
function _login_weixin_check(){
  if($('#_login_weixin').length<1){
    return;
  }
  $.post('$checkurl',{rndkey:'$rndkey',ptoken:'$ptoken'},function(o){
    if(typeof o.url!='undefined'){
      if(o.url=='reload'){
        location.reload();
      }else{
        location.href=o.url;
      }
    }
  },'json');
  _login_weixin_time=setTimeout('_login_weixin_check()',2000);
}
ONEZ;
    $G['footer_js'].=$code;
    $G['footer-js'].=$code;
    return 'javascript:_login_weixin();';
  }
}