<?php
global $db,$baseUrl;
$host = $_SERVER['HTTP_HOST'];
$callback = "http://".$host.$baseUrl."user/quicklogin/type/weibo/act/callback/";
$path = str_replace("/weibo.inc.php","/",str_replace("\\","/",__FILE__));

	include_once( $path.'config.php' );
	include_once( $path.'saetv2.ex.class.php' );

$act = getgpc("act");
		if($act=="callback"){
		$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );

		if (isset($_GET['code'])) {
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = WB_CALLBACK_URL;
			try {
				$token = $o->getAccessToken( 'code', $keys ) ;
			} catch (OAuthException $e) {
			}
		}else{
			//print_r($_GET);
			Msg::show(array('msg'=>'返回码丢失','url'=>'/','time'=>1));
		}
	//echo $token;
		if ($token) {
			load_class("user");
			$um = new UserModel();
			$_SESSION['token'] = $token;
			setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );
			//print_r($token);
			
			$uid = $token['uid'];
			$access_token = $token['access_token'];

			$sql = "select userId from qk_weibo_auth where uid='$uid'";
			$userId = $db->getOne($sql);
			if($userId && is_numeric($userId) && $db->getOne("select id from qk_user where id='".$userId."'")){
				$sql = "update qk_weibo_auth set access_token='$access_token',refresh_token='$refresh_token',updatetime=UNIX_TIMESTAMP() where uid='$uid'";
				$db->query($sql);
				saveLog("新浪微博登录 ACCESS_TOKEN：$access_token refresh_token：$refresh_token uid：$uid",0,0,$userId);
				if(!$um->quickLogin($userId)){
					$db->query("delete from qk_weibo_auth where uid='$uid'");
					createWeiboUser($token);					
				}
			}else{
				createWeiboUser($token);
			}
			//echo "success";
		
		} else {
			Msg::show(array('msg'=>'获取Token失败','url'=>'/','time'=>1));
		}

}else{

	$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
	$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );
	header("Location:".$code_url);
}

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

				$c = new SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] );
				$ms  = $c->home_timeline(); // done
				$uid_get = $c->get_uid();
				$uid = $uid_get['uid'];
				$userInfo = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息
				//print_r($userInfo);
				$params = array();
				$params['loginName'] = "WEIBOLOGIN_".$uid; 
				$params['nickname'] = $userInfo['screen_name'];
				$userId = $um->add($params,true);
				if($userId){
					$sql = "insert into qk_weibo_auth set userId='$userId',uid='$uid',access_token='$access_token',refresh_token='$refresh_token'";
					$sql .= ",updatetime=UNIX_TIMESTAMP(),posttime=UNIX_TIMESTAMP()";
					if($db->query($sql)){
						$um->quickLogin($userId);
					}
				}else{
				echo $um->msg;
			}
}


/*
Array
(
    [access_token] => 2.00faXNvB0FQNcNefcf75143exop_qB
    [remind_in] => 634877
    [expires_in] => 634877
    [uid] => 1761611373
)
*/
?>