<?php
/**************************************************
*  Created:  2010-06-08
*
*  文件说明
*
*  @Xweibo (C)1996-2099 SINA Inc.
*  @Author xionghui <xionghui1@staff.sina.com.cn>
*
***************************************************/

class clientUser 
{
	var $uidField;
	function clientUser($uidField='uid'){
		$this->uidField = $uidField;
	}
	
	function initUser(){
		if (!defined('IS_SESSION_START') || !IS_SESSION_START ){
			session_start();
		}
	}
	
	function setOAuthKey($keys,$is_confirm = false){
		$k = $is_confirm ? WB_OAUTH_KEYS2 : WB_OAUTH_KEYS1 ;
		$_SESSION[$k] = $keys;
	}
	
	function getOAuthKey($is_confirm = false){
		$k = $is_confirm ? WB_OAUTH_KEYS2 : WB_OAUTH_KEYS1 ;
		return $_SESSION[$k];
	}
	
	function setInfo($k,$v=false){
		if (!isset($_SESSION[WB_CLIENT_SESSION])){
			$_SESSION[WB_CLIENT_SESSION] = array();
		}
		if( is_array($k) ){
			$_SESSION[WB_CLIENT_SESSION] = array_merge($_SESSION[WB_ADMIN_SESSION],$k);
		}else{
			$_SESSION[WB_CLIENT_SESSION][$k] = $v;
		}
	}
	
	function getInfo($key=false){
		return (is_array($_SESSION[WB_CLIENT_SESSION]) && $key ) ?  $_SESSION[WB_CLIENT_SESSION][$key] : $_SESSION[WB_CLIENT_SESSION];
	}
	
	function delInfo($k){
		if (!isset($_SESSION[WB_CLIENT_SESSION])){
			return true;
		}
		if(!is_array($k)) {$k = array($k);}
		foreach($k as $kv ){
			if (isset($_SESSION[WB_CLIENT_SESSION][$kv])) unset($_SESSION[WB_CLIENT_SESSION][$kv]);
		}
		return true;
	}
	
	function isLogin(){
		$r = $this->getInfo($this->uidField);
		return !empty($r);
	}
	
	function keywCheck(){
		// 已经检查通过
		if ($this->setInfo('pass_keywCheck')==1){return true;}
		
		$nick = $this->getInfo('screen_name');
		$description = $this->getInfo('description');
		
		//print_r(array($nick, $description));
		$kType	= '';
		$kw		= '';
		$kwChk = APP::F('filter', $nick, 'nick');
		if (  $kwChk !== true ) {
			$kType .= '昵称';
			$kw .= $kwChk;
		}
		
		if (!empty($description)){
			$kwChk = APP::F('filter', $description, 'nick');
			if (  $kwChk !== true ) {
				$kType .= '简介';
				$kw .= $kwChk;
			}			
		}

		
		$timeout = 3;
		if ( !empty($kType) && !empty($kw) ){
			//echo 'reach...';exit;
			APP::tips(array('tpl' => 'error', 
							'msg' => '你的'.$kType.'中含有非法关键词['.$kw.'],请在个人设置更改，'.$timeout.'秒后将自动跳转到个人设置页面。', 
							'location' => URL('setting'), 
							'timeout' => 3),true);
		}
		$this->setInfo('pass_keywCheck', 1);
	}
	
	/// 全局预处理模块，从COOKIE 自动登录 并引导注册
	function autoLogin(){
		//return true;
		/// 调试用
		//print_r($_SESSION);exit;
		//-----------------------------------
		if ( $this->isLogin() ) {return true;}
		//-----------------------------------
		// 需要绑定
		if ($this->_getNeedToBind()){
			$site_uid = $this->_getSiteUid();
			// 未能正确检查到 原站点UID ，即在 原站点 未登录
			if (empty($site_uid)){ $this->_goToSiteLogin();}
			//-----------------------------------
			$keys = $this->_getOAuthFromDB($site_uid);
			// 未绑定用户
			if (empty($keys) || !is_array($keys) ) {
				//进行OAUTH 认证
				$goUrl = $this->_getOAuthUrl();
				APP::redirect($goUrl, 3);
			}else{
				$this->setOAuthKey($keys, true);
				$this->setInfo($this->uidField, $site_uid);
				$this->setInfo('sina_uid', $keys['sina_uid']);
				$this->setInfo('uid', $keys['sina_uid']);
				
				$wbApi = APP::N('weibo');
				$uInfo = $wbApi->getUserShow($keys['sina_uid']);
				$this->setInfo('screen_name', $uInfo['screen_name']);
				$this->setInfo('description', $uInfo['description']);
			}
		}else{
			// 不需要绑定 进行OAUTH 认证
			$goUrl = $this->_getOAuthUrl();
			APP::redirect($goUrl, 3);
		}
	}
	
	/// 是否需要与原站点绑定
	function _getNeedToBind(){
		return false;
		$st = V('-:sysConfig/bind_enable');
		return empty($st) ? false : true;
	}
	/// 获取 OAUTH 认证URL
	function _getOAuthUrl(){
		static $aurl;
		if (!empty($aurl)) {return $aurl; }
		
		$this->setOAuthKey(array(),false);
		$this->setOAuthKey(array(),true);
		$wb = APP::N('weibo');
		$keys = $wb->getRequestToken();
		$aurl = $wb->getAuthorizeURL($keys['oauth_token'] ,false , W_BASE_HTTP.URL('account.oauthBind'));
		//print_r(array(URL('account.oauthBind'),V('s')));exit;
		$this->setOAuthKey($keys);
		return rtrim($aurl, '&').'&from=xweibo&xtype='.V('-:sysConfig/bind_enable');
	}
	/// 跳转到 附属 站点 进行
	function _goToSiteLogin(){
		if ($this->_getNeedToBind()){
			$goUrl = XWB_OWNER_SITE_X_URL.XWB_OWNER_SITE_TYPE.'.php';
		}else{
			$goUrl = $this->_getOAuthUrl();
		}
		APP::redirect($goUrl, 3);
		exit;
	}
	
	/// 获取 原站点 UID , 获取失败则返回 0  取过一次后保存在SESSION
	function _getSiteUid(){
		
		$sess_site_uid = $this->getInfo('site_uid');
		if ($sess_site_uid) {return $sess_site_uid;}
		
		$cData	= V('c:'.XWB_AUTH_CK_NAME);
		if (empty($cData) ||  strlen($cData)<32 ) {
			return 0;
		}
		
		$info	= substr($cData,0,-32);
		$chk	= substr($cData,-32);
		
		$DES	= APP::N('des');
		$DES->setMode('ECB', 'PKCS5');
		$uData	= $DES->decrypt($info, XWB_XPLUGINS_AUTH_KEY);
		if ( preg_match("#^(\d+),(\d+)\$#",$uData,$m) ){
			//print_r($m);exit;
			if ( xwb_sign_req($m[2]) != $chk ) {
				echo 'COOKIE 签名 较检出错'; exit;
			}else{
				$site_uid = $m[1] ;
			}
		}else{
				echo " 无法解开密文 " ; exit;
		}
		
		//$site_uid = 0;
		$this->setInfo('site_uid', $site_uid);
		return $site_uid;
	}
	
	/// 从数据库中获取 OAUTH KEYS 
	function _getOAuthFromDB($uid){
		$db = APP::ADP('db');
		$r	= $db->getRow('SELECT * FROM `' . $db->getTable(T_USER_TOKEN) . '` WHERE `uid`='.mysql_escape_string($uid));
		if ($r === false){
			trigger_error("DB error :  ".$db->getError(), E_USER_ERROR);
			return false;
		}
		
		if (empty($r)) {return false;}
		return array('oauth_token'=>$r['oauth_token'],
					 'screen_name'=>$r['screen_name'],
					 'oauth_token_secret'=>$r['oauth_token_secret'],
					 'sina_uid'=>$r['sina_uid']);
	}
}
?>