<?php

require_once P_CLASS.'/oauth.class.php';

/**
  * 用于OAuth1.0 access token 更换至 OAuth2.0 access token，帮助开发者使用新版接口和OAuth2.0时平滑迁移用户。
  * @param string $access_token OAuth 1.0的access_token
  * @param string $access_token_secret OAuth 1.0的access_token_secret
  * @return RST_Array
  * @version $Id: oauth2_exchangeToken.func.php 18383 2012-07-26 10:04:00Z yaoying $
  */
function oauth2_exchangeToken($access_token, $access_token_secret){
	static $_http = null;
	static $_consumer = null;
	static $_shal_method = null;
	static $_url = 'https://api.weibo.com/oauth2/get_oauth2_token';
	if(null === $_http){
		$_http = APP::ADP('http');
	}
	if(null === $_consumer){
		$_consumer = new OAuthConsumer(WB_AKEY, WB_SKEY);
	}
	if(null === $_shal_method){
		$_shal_method = new OAuthSignatureMethod_HMAC_SHA1();
	}
	
	$log_func_start_time = microtime(TRUE);
	$token = new OAuthConsumer($access_token, $access_token_secret);
	
	//OAuth 1.0模拟
    $request = OAuthRequest::from_consumer_and_token($_consumer, $token, 'GET', $_url);
    $request->sign_request($_shal_method, $_consumer, $token);
	$_http->base_string = $request->base_string;
	$_http->key_string = $request->key_string;
	$_http->setUrl($request->to_url());
	$_http->setHeader('API-RemoteIP', F('get_client_ip'));
	$result = $_http->request('get', true);
	
	$code = $_http->getState();
	$http_url = $_http->getUrl();
	
		$logParam = array('url'=>$http_url, 'params'=>null, 'code'=>$code, 'result'=>$result, 'error'=>$_http->getError());
		LogMgr::warningLog($log_func_start_time, 'api', "[oAuthRequest]API Request method=get", LOG_LEVEL_WARNING, $logParam);
		LOGSTR('api', "[oAuthRequest]API Request method=get", LOG_LEVEL_INFO, $logParam, $log_func_start_time);
		
		if (200 != $code) {
			//log
			$logMsg = 'url: '.$http_url." \r\ncode: ".$code." \r\nret: ".$result . "\r\nerror: " . $_http->getError()."\r\nbase_string:: ".$request->base_string."\r\nkey_string: ". strtr($request->key_string, array(WB_SKEY => '%APP_SKEY%'));
			LOGSTR('api', "[oAuthRequest]API Request methodget&".$logMsg);
			if (0 == $code) {
				return RST('', '1040002', 'Access Timeout or Access denied', 0);
			}
			return RST(false, 100000, $result);
		}
		
		$result = json_decode(preg_replace('#(?<=[,\{\[])\s*("\w+"):(\d{6,})(?=\s*[,\]\}])#si', '${1}:"${2}"', $result), true);
		return RST($result);
	
}
