<?php
error_reporting(E_ALL ^ E_NOTICE);
global $db;global $baseUrl;
$path = str_replace("/baidu.inc.php","/",str_replace("\\","/",__FILE__));
require $path.'lib/Baidu.php';


$config = getConfig("baiduLogin");
if(!$config || !$config['apiKey'] || !$config['secretKey']){
	Msg::show("未配置百度账号登录或已关闭该应用");
}

$apiKey = $config['apiKey'];
$secretKey = $config['secretKey'];

$baidu = new Baidu($apiKey, $secretKey, new BaiduCookieStore($apiKey));
$host = $_SERVER['HTTP_HOST'];
$act = getgpc("act");
if($act=="callback"){
	$access_token = $baidu->getAccessToken();
	$user = $baidu->getLoggedInUser();
	if($access_token && $user){
				$params = array();
				$uid = $user['uid'];
				$uname = $user['uname'];
				$params['loginName'] = "BAIDULOGIN_".$uid; 
				$params['nickname'] = $uname;
				$params['access_token'] = $access_token;
				$params['uid'] = $uid;
				//$params['email'] = $email;

		load_class("user");	//Array ( [uid] => 2501329766 [uname] => qkweb ) 
		$um = new UserModel();
		$sql = "select userId from qk_baidu_auth where uid='$uid'";//echo$sql;exit;
		$userId = $db->getOne($sql);
		if($userId && is_numeric($userId) && $db->getOne("select id from qk_user where id='".$userId."'")){
				$sql = "update qk_baidu_auth set access_token='$access_token',updatetime=UNIX_TIMESTAMP() where uid='$uid'";
				saveLog("百度账号登录 ACCESS_TOKEN：$access_token OPENID：$openid",0,0,$userId);
				if(!$um->quickLogin($userId)){
						$db->query("delete from qk_baidu_auth where uid='$uid'");
						createBaiduUser($params);
				}
		}else{
				createBaiduUser($params);
		}
	}else{
			Msg::show(array('msg'=>'百度账号登录失败','url'=>'/','time'=>1));
	}
}else{
	  $loginUrl = $baidu->getLoginUrl(array('response_type' => 'code', 'redirect_uri' => 'http://'.$host.$baseUrl.'user/quicklogin/type/baidu/act/callback/'));
	if($loginUrl){
		header("Location:$loginUrl\r\n");
	}
}

function createBaiduUser($param){
	global $db;
		load_class("user");
		$um = new UserModel();
		$loginName = $param['loginName'];
		$nickname = $param['nickname'];
		$uid = $param['uid'];
		$access_token=$param['access_token'];
			$params = array();
			$params['loginName'] = "BAIDU_".$uid;
			$params['nickname'] = $nickname;
			$userId = $um->add($params,true);
			//echo $userId;
			//print_r($params);
			if($userId){
					$sql = "insert into qk_baidu_auth set userId='$userId',uid='$uid',access_token='$access_token',uname='$nickname'";
					$sql .= ",updatetime=UNIX_TIMESTAMP(),posttime=UNIX_TIMESTAMP()";
				if($db->query($sql)){
					$um->quickLogin($userId);
				}
			}else{
				Msg::show($um->msg);
			}
}

?>