<?php
global $db;
$path = str_replace("/qq.inc.php","/",str_replace("\\","/",__FILE__));
$act = getgpc("act");
require_once($path."comm/config.php");
require_once($path."comm/function.php");
if($act!="callback"){
	qq_login($_SESSION["appid"], $_SESSION["scope"], $_SESSION["callback"]);
}else{
	qq_callback();
	get_openid();
	if($_SESSION['access_token'] && $_SESSION['openid']){
		load_class("user");
		$um = new UserModel();
		$openid = $_SESSION['openid'];
		$sql = "select userId from qk_qq_auth where openid='$openid'";
		$userId = $db->getOne($sql);
		$access_token = $_SESSION['access_token'];
		if($userId && is_numeric($userId) && $db->getOne("select id from qk_user where id='".$userId."'")){
			$sql = "update qk_qq_auth set access_token='$access_token',updatetime=UNIX_TIMESTAMP() where openid='$openid'";
			$db->query($sql);
			saveLog("QQ登录 ACCESS_TOKEN：$access_token OPENID：$openid",0,0,$userId);
			if(!$um->quickLogin($userId)){
				$db->query("delete from qk_qq_auth where openid='$openid'");
				createWeiboUser();
			}
		}else{
			createWeiboUser();
		}
	}else{
			Msg::show(array('msg'=>'QQ账号登录失败','url'=>'/','time'=>1));
	}
}

function createWeiboUser(){
	global $db;
		load_class("user");
		$um = new UserModel();
		$openid = $_SESSION['openid'];
		$access_token = $_SESSION['access_token'];

			$userInfo = get_user_info();
			$params = array();
			$params['loginName'] = "QQLOGIN_".$openid; 
			$params['nickname'] = $userInfo['nickname'];
			$userId = $um->add($params,true);
			//echo $userId;
			//print_r($params);
			if($userId){
				$sql = "insert into qk_qq_auth set userId='$userId',openid='$openid',access_token='$access_token'";
				$sql .= ",updatetime=UNIX_TIMESTAMP(),posttime=UNIX_TIMESTAMP()";
				if($db->query($sql)){
					$um->quickLogin($userId);
				}
			}else{
				Msg::show($um->msg);
			}
}
/*
Array
(
    [appid] => 100239844
    [appkey] => f1d9b6e74e3df2683e6b6559c85be00f
    [callback] => http://qp.qkweb.net/user/quicklogin/type/qq/act/callback
    [state] => c4d41e77a166ea8e3d054f722de6a60a
    [access_token] => 53B7F745CE998420E76AE1D1F10ECC32
    [openid] => E94CE851D0884ACACF4EA8AFACAAC9E1
)
*/
?>