<?php

require_once("utils.php");

require_once('../../class/connect.php');
require_once('../../class/db_sql.php');
require_once('../../class/user.php');
require_once('../../data/dbcache/MemberLevel.php');
require_once "../".LoadLang("pub/fun.php");
$link=db_connect();
$empire=new mysqlquery();
$editor=1;
$ReturnUrlQz=eReturnDomainSiteUrl();
//exit('sssdssd'.$public_r[add_domain]);
//echo($public_r[add_domain]);

$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'];

$_SESSION["appid"]    = $app_id; //opensns.qq.com 申请到的appid
$_SESSION["appkey"]   = $app_secret; //opensns.qq.com 申请到的appkey

$_SESSION['newsurl']  = $ReturnUrlQz;
$_SESSION["callback"] = $_SESSION['newsurl']."e/memberconnect/qq/enews.php?enews=check_to_login"; //QQ登录成功后跳转的地址
$_SESSION["groupid"]=1;
$_SESSION["domain"]= $ReturnUrlQz; 

//exit('sssdssd'.$_SESSION["appid"]);
$enews=$_GET['enews'];if(empty($enews)){$enews=$_POST['enews'];}

function connect2qzone_bind($reurl='')
{
	global $empire,$dbtbpre;
	$user_r=connect2qzone_is_openid_exist($_SESSION["openid"]);
	
	if($user_r[userid])
	{
		ecms_memberlogin($user_r[userid]);
		
		echoJScloseWindow($reurl);
	}
	else
	{
		$qq_r=get_user_info($_SESSION["openid"],$_SESSION["appid"], $_SESSION["access_token"]);
		$_SESSION["qqinfo"]=json_decode($qq_r);
		//exit($qq_r);
		connect2qzone_register($reurl);
	}
}

function ecms_memberlogin($userid)
{
	global $empire,$user_tablename,$public_r,$user_groupid,$user_username,$user_userid,$user_email,$user_password,$user_dopass,$user_rnd,$user_registertime,$user_register,$user_group,$user_saltnum,$user_salt,$user_seting,$forumgroupid,$registerurl,$dbtbpre,$user_regcookietime,$user_userfen,$user_checked,$level_r;
	$r=$empire->fetch1("select * from ".$user_tablename." where ".$user_userid."='$userid' limit 1");
	$rnd=make_password(12);
	$sql=$empire->query("update ".$user_tablename." set ".$user_rnd."='$rnd' where ".$user_userid."='$userid' ");
	$logincookie=time()+86400*365;//cookie保存时间

	//exit('here');
	$set1=esetcookie("mlusername",$r[$user_username],$logincookie);
	$set2=esetcookie("mluserid",$r[$user_userid],$logincookie);
	$set3=esetcookie("mlgroupid",$r[$user_group],$logincookie);
	$set4=esetcookie("mlrnd",$rnd,$logincookie);	

	if( $set1 && $set2 && $set3 && $set4 )
	{
		$re=1;	
	}
	else
	{
		$re=0;
	}
	
	return $re;
}

function connect2qzone_is_openid_exist($openid)
{
	global $empire,$dbtbpre;
	$r=$empire->fetch1("select userid from {$dbtbpre}enewsmember where connect2qzone_openid='".$openid."' limit 1");
	return $r;
}



function echoJScloseWindow($reurl='')
{
	if(empty($reurl))
	{
		echo '<script>function closethewindow(){var url="'.$reurl.'";window.opener.location.reload();window.close();}setTimeout(closethewindow(),5000);</script>';
	}
	else
	{
		echo '<script>document.domain="'.$_SESSION["domain"].'";function closethewindow(){var url="'.$reurl.'";window.opener.location.reload();window.close();}closethewindow();</script>';
	}
}

function check_re_username($username)
{
	global $empire,$user_tablename,$public_r,$user_groupid,$user_username,$user_userid,$user_email,$user_password,$user_dopass,$user_rnd,$user_registertime,$user_register,$user_group,$user_saltnum,$user_salt,$user_seting,$forumgroupid,$registerurl,$dbtbpre,$user_regcookietime,$user_userfen,$user_checked,$level_r;

	$num=$empire->gettotal("select count(*) as total from ".$user_tablename." where ".$user_username."='$username' limit 1");
	if($num)
	{
		for($i=1;$i<=100;$i++)
		{
			$username.="_".$i;
			$num=$empire->gettotal("select count(*) as total from ".$user_tablename." where ".$user_username."='$username' limit 1");
			if(!$num)
			{
				break;
			}
		}
	}

	return $username;
}

function connect2qzone_register($reurl=''){
	global $empire,$user_tablename,$public_r,$user_groupid,$user_username,$user_userid,$user_email,$user_password,$user_dopass,$user_rnd,$user_registertime,$user_register,$user_group,$user_saltnum,$user_salt,$user_seting,$forumgroupid,$registerurl,$dbtbpre,$user_regcookietime,$user_userfen,$user_checked,$level_r;
	if($public_r['register_ok'])//关闭
	{
		printerror("CloseRegister",$gotourl,1);
	}

	//已经登陆不能注册
	if(getcvar('mluserid'))
	{
		echo 1;
		printerror("LoginToRegister",$gotourl,1);
	}
	CheckCanPostUrl();//验证来源

	
	$username=$_SESSION['qqinfo']->nickname;
	//$password=make_password(8);
	$username=RepPostVar($username);
	$password=$_SESSION["openid"];
	$truepassword=$_SESSION["openid"];
	$email=$_SESSION['openid'].'@qq.com';
	$user_groupid=(int)$_SESSION["groupid"];
	$groupid=(int)$_SESSION["groupid"];
	$groupid=empty($groupid)?$user_groupid:$groupid;
	CheckMemberGroupCanReg($groupid);
	
	
	//IP
	$regip=egetip();
	
	//同一IP注册
	eCheckIpRegTime($regip,$pr['regretime']);
	
	//保留用户
	toCheckCloseWord($username,$pr['regclosewords'],'RegHaveCloseword');
	$username=RepPostStr($username);
	$username=check_re_username($username);
	

	//注册时间
	if($user_register)
	{
		$registertime=time();
	}
	else
	{
		$registertime=date("Y-m-d H:i:s");
	}
	
	$birthday=$y.$m.$d;
	$rnd=make_password(12);//产生随机密码
	
	//密码
	if(empty($user_dopass))//单重md5
	{
		$password=md5($password);
	}
	elseif($user_dopass==2)//双重md5
	{
		$salt=make_password($user_saltnum);
		$password=md5(md5($password).$salt);
	}
	elseif($user_dopass==3)//16位md5
	{
		$password=substr(md5($password),8,16);
	}
	//审核
	$checked=ReturnGroupChecked($groupid);
	if($checked&&$public_r['regacttype']==1)
	{
		$checked=0;
	}
	//验证附加表必填项

/*
//--------------------------- Ucenter ---------------------------
	$uid=uc_user_register($username,$truepassword,$email);
	//exit($uid);
	if($uid <= 0)
	{
		if($uid == -1)
		{
			printerror('用户名不合法','',1,0,1);
		} 
		elseif($uid == -2)
		{
			printerror('包含要允许注册的词语','',1,0,1);
		} 
		elseif($uid == -3)
		{
			printerror($uid.'用户名已经存在','',1,0,1);
		}
		elseif($uid == -4)
		{
			printerror('Email 格式有误','',1,0,1);
		}
		elseif($uid == -5)
		{
			printerror('Email 不允许注册','',1,0,1);
		}
		elseif($uid == -6)
		{
			printerror('该 Email 已经被注册','',1,0,1);
		} 
		else
		{
			printerror('未定义','',1,0,1);
		}
	}
	
	@mysql_select_db($GLOBALS['phome_db_dbname']);
//--------------------------- Ucenter ---------------------------
*/

	$sql=$empire->query("insert into ".$user_tablename."(".$user_username.",".$user_password.",".$user_email.",".$user_registertime.",".$user_group.",".$user_rnd.",".$user_userfen.",".$user_checked.",connect2qzone_openid) values('$username','$password','$email','$registertime','$groupid','$rnd','$public_r[reggetfen]','$checked','".$_SESSION['openid']."');");
	//取得userid
	$userid=$empire->lastid();
	//附加表
	$addr=$empire->fetch1("select * from {$dbtbpre}enewsmemberadd where userid='$userid'");
	if(!$addr[userid])
	{
		$spacestyleid=ReturnGroupSpaceStyleid($groupid);
		$sql1=$empire->query("insert into {$dbtbpre}enewsmemberadd(userid,spacestyleid,regip,userpic) values('$userid','$spacestyleid','$regip','".$_SESSION['qqinfo']->figureurl_2."');");
	}
	ecmsEmptyShowKey($keyvname);//清空验证码
	if($sql)
	{
		
		//邮箱激活
		if($checked==0&&$public_r['regacttype']==1)
		{
			include('../class/qmemberfun.php');
			SendActUserEmail($userid,$username,$email);
		}
		//审核
		if($checked==0)
		{
			$location=DoingReturnUrl("../../",$_POST['ecmsfrom']);
			printerror("RegisterSuccessCheck",$gotourl,1);
		}
		$logincookie=time()+86400*365;//cookie保存时间
		if($user_regcookietime)
		{
			$logincookie=time()+$user_regcookietime;
		}
		$set1=esetcookie("mlusername",$username,$logincookie);
		$set2=esetcookie("mluserid",$userid,$logincookie);
		$set3=esetcookie("mlgroupid",$groupid,$logincookie);
		$set4=esetcookie("mlrnd",$rnd,$logincookie);
		//echo uc_user_synlogin($uid);
		echoJScloseWindow($reurl);
		exit;
	}
	else
	{printerror("DbError",$gotourl,1);}
}

if($enews=='qzonelogin')
{
	$_SESSION["callback"]=$_SESSION['newsurl'].'e/memberconnect/qq/enews.php?enews=qzonelogin_action&reurl='.$_GET['reurl'];
	redirect_to_login($_SESSION["appid"], $_SESSION["appkey"], $_SESSION["callback"]);
}
elseif($enews=='qzonelogin_action')
{
	//connect2qzone_sessioncheck();
	//connect2qzone_bind($_GET['reurl']);

	//---------------------------------------------------oauth2.0  2013-1-24
	$code=RepPostVar($_REQUEST['code']);
	//拼接URL
	$token_url="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"."client_id=".$_SESSION["appid"] ."&redirect_uri=".urlencode($_SESSION["callback"])."&client_secret=".$_SESSION["appkey"]."&code=".$code;
	
	//echo($token_url);
	$response=http_request($token_url);
	//exit($response);
	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);

	$params['access_token']=RepPostVar($params['access_token']);
	$_SESSION['access_token']=$params['access_token'];
	$graph_url="https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token'];
	$str=http_request($graph_url);
	//exit($str);
	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))
	{
		exit('openid不对'.$openid);
		//printerror2('来自的链接不存在','../../../');
	}
	$openid=RepPostVar($openid);
	//$apptype=RepPostVar($apptype);
	$_SESSION['openid']=$openid;
	
	
	//$_SESSION['apptype']=$apptype;
	//$_SESSION['openidkey']=MemberConnect_GetBindKey($apptype,$openid);
	//处理登录
	connect2qzone_bind($_GET['reurl']);
		
}

db_close();
$empire=null;
?>
