<?php
require("../../class/connect.php");
require("../../class/db_sql.php");
require("../../class/q_functions.php");
require("../../member/class/user.php");
eCheckCloseMods('member');//关闭模块
eCheckCloseMods('mconnect');//关闭模块
$link=db_connect();
$empire=new mysqlquery();
$editor=1;
eCheckCloseMemberConnect();//验证开启的接口
session_start();
require('../memberconnectfun.php');

function chkuser($username,$apptype,$type=0){
    global $empire,$dbtbpre,$public_r;
    $r = $empire->fetch1("select userid from {$dbtbpre}enewsmember where username='$username' limit 1");
    if(empty($r['userid'])){
        return $username;
    }
    if($type == 0){
       return chkuser($apptype.'_'.$username,$apptype,1);
    }
    else{
        $rand = rand(100,999);
       return chkuser($username.$rand,$apptype,2);
    }
}
function chkname($username){
    if(empty($username)){
        return false;
    }
	$username = trim($username);
    preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u",$username,$chk);
    if(empty($chk)){
        $chk = get_username(6);
    }
    else{
        $chk = iconv("UTF-8", "GB2312//IGNORE", $chk[0]);
    }
    return $chk;
}
function get_username($length=4) {
    $chars = '0123456789';    
    $username = '';    
    for ( $i = 0; $i < $length; $i++ )    
    {
        $username .= $chars[ mt_rand(0, strlen($chars) - 1) ];    
    }    
    return 'qq'.$username.esub(time(),6);
}
$apptype='qq';
$appr=$empire->fetch1("select * from {$dbtbpre}enewsmember_connect_app where apptype='$apptype' and isclose=0 limit 1");
if(!$appr['id'])
{
    printerror2('请选择登录方式','../../../');
}

//应用的APPID
$app_id=$appr['appid'];

//应用的APPKEY
$app_secret=$appr['appkey'];

//成功授权后的回调地址
$ReturnUrlQz=eReturnDomainSiteUrl();
$my_url=$ReturnUrlQz."e/memberconnect/qq/loginend.php";

//----------------- 取得Token -----------------

if(!$_SESSION['state']||$_REQUEST['state']<>$_SESSION['state'])
{
    printerror2('来自的链接不存在','../../../');
}

$code=RepPostVar($_REQUEST['code']);
//拼接URL
$token_url="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"."client_id=".$app_id."&redirect_uri=".urlencode($my_url)."&client_secret=".$app_secret."&code=".$code;
$response=@file_get_contents($token_url);
if(strpos($response,"callback")!==false)
{
    $lpos=strpos($response,"(");
    $rpos=strrpos($response,")");
    $response=substr($response,$lpos+1,$rpos-$lpos-1);
    $msg=json_decode($response);
    if(isset($msg->error))
    {
        echo"<h3>error:</h3>".$msg->error;
        echo"<h3>msg  :</h3>".$msg->error_description;
        exit();
    }
}


//----------------- 取得Openid -----------------

$params=array();
parse_str($response,$params);
$access_token = RepPostVar($params['access_token']); //tbag
$params['access_token']=RepPostVar($params['access_token']);
$graph_url="https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token'];
$str=@file_get_contents($graph_url);
if(strpos($str,"callback")!==false)
{
    $lpos=strpos($str,"(");
    $rpos=strrpos($str,")");
    $str=substr($str,$lpos+1,$rpos-$lpos-1);
}
$user=json_decode($str);
if(isset($user->error))
{
    echo"<h3>error:</h3>".$user->error;
    echo"<h3>msg  :</h3>".$user->error_description;
    exit();
}

$openid=$user->openid;

if(!trim($openid)||!trim($apptype))
{
    printerror2('来自的链接不存在','../../../');
}
$openid=RepPostVar($openid);
$apptype=RepPostVar($apptype);
$_SESSION['openid']=$openid;
$_SESSION['apptype']=$apptype;
$_SESSION['openidkey']=MemberConnect_GetBindKey($apptype,$openid);
/* 自动绑定账号 */
$isbind = MemberConnect_CheckOpenid($apptype,$openid);
include('../nobind.php');
if(!$isbind['userid']){
    $UserInfoApiUrl = 'https://graph.qq.com/user/get_user_info?oauth_consumer_key='.$app_id.'&access_token='.$access_token.'&openid='.$openid;
    $UserInfo=@file_get_contents($UserInfoApiUrl);
    $UserInfo = json_decode($UserInfo);
    require("../../member/class/member_registerfun.php");
    include('../../member/class/member_modfun.php');
	//$UserInfo->nickname = iconv("UTF-8", "GB2312//IGNORE", $UserInfo->nickname);
    $UserInfo->nickname = chkname($UserInfo->nickname);    
    $UserInfo->nickname = RepPostVar($UserInfo->nickname);
    $UserInfo->nickname = str_replace('"','',$UserInfo->nickname);
    $UserInfo->nickname = str_replace("'",'',$UserInfo->nickname);
    $UserInfo->nickname = str_replace("_",' ',$UserInfo->nickname);    
    $UserInfo->nickname = chkuser($UserInfo->nickname,$apptype,0);
    $qq['username'] = RepPostStr($UserInfo->nickname);
    $qq['nickname'] = RepPostStr($UserInfo->nickname);
    $qq['email'] = 'xxxxx@qq.com';
    $qq['userpic'] = $UserInfo->figureurl_qq_2;
    $password = rand(100000,999999);   //随机密码
    $qq['password'] = (int)$password;
    $qq['repassword'] = (int)$password;
    $qq['apptype'] = $apptype;
    $qq['openid'] = $openid;
    $qq['tobind'] = 1;
    tregister($qq);
}else if(getcvar('mluserid')){
    printerrortourl('/');
}else{
    $user = $empire->fetch1("select * from {$dbtbpre}enewsmember where userid = ".$isbind['userid']);
    $set1=esetcookie("mlusername",$user['username'],time()+86400);
    $set2=esetcookie("mluserid",$user['userid'],time()+86400);
    $set3=esetcookie("mlgroupid",$user['groupid'],time()+86400);
    $set4=esetcookie("mlrnd",$user['rnd'],time()+86400);
    tMemberConnect_DoLogin($apptype,$openid);
    printerrortourl('/');
}
/* 自动绑定账号 */
db_close();
$empire=null;
?>