<?php
/**
 * PHP SDK for weibo.com (using OAuth2)
 * Xweibo改造版
 * 此类仅进行获取token信息操作。
 * 
 * @author Elmer Zhang <freeboy6716@gmail.com>
 * @author yaoying <yaoying@staff.sina.com.cn>
 * @version $Id: xwbOAuthV2.class.php 18382 2012-07-26 08:56:46Z yaoying $
 */
/**
 * 新浪微博 OAuth 认证类(OAuth2)
 * 原类名：SaeTOAuthV2。为防止在SAE平台冲突，故进行改名
 *
 * 授权机制说明请大家参考微博开放平台文档：{@link http://open.weibo.com/wiki/Oauth2}
 *
 * @package sae
 * @author Elmer Zhang
 * @version 1.0
 */
class xwbOAuthV2 {
	
	/**
	 * 解析 signed_request
	 *
	 * @param string $signed_request 应用框架在加载iframe时会通过向Canvas URL post的参数signed_request
	 * @param string $client_secret client secret。参与签名对比
	 *
	 * @return array
	 */
	function parseSignedRequest($signed_request, $client_secret) {
		list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
		$sig = self::base64decode($encoded_sig) ;
		$data = json_decode(self::base64decode($payload), true);
		if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') return '-1';
		$expected_sig = hash_hmac('sha256', $payload, $client_secret, true);
		return ($sig !== $expected_sig)? '-2':$data;
	}

	/**
	 * @ignore
	 */
	function base64decode($str) {
		return base64_decode(strtr($str.str_repeat('=', (4 - strlen($str) % 4)), '-_', '+/'));
	}

	/**
	 * 读取jssdk授权信息，用于和jssdk的同步登录
	 * @param string $client_id 要读取的client id cookie
	 * @return array 成功返回array('access_token'=>'value', 'refresh_token'=>'value'); 失败返回false
	 */
	function getTokenFromJSSDK($client_id) {
		$key = "weibojs_" . $client_id;
		if ( isset($_COOKIE[$key]) && $cookie = $_COOKIE[$key] ) {
			parse_str($cookie, $token);
			if ( isset($token['access_token'])) {
				$token['refresh_token'] = isset($token['refresh_token']) ? $token['refresh_token'] : null;
				return $token;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	/**
	 * 从数组中读取access_token和refresh_token
	 * 常用于从Session或Cookie中读取token，或通过Session/Cookie中是否存有token判断登录状态。
	 *
	 * @param array $arr 存有access_token和secret_token的数组
	 * @return array 成功返回array('access_token'=>'value', 'refresh_token'=>'value'); 失败返回false
	 */
	function getTokenFromArray( $arr ) {
		if (isset($arr['access_token']) && $arr['access_token']) {
			$token = array();
			$token['access_token'] = $arr['access_token'];
			if (isset($arr['refresh_token']) && $arr['refresh_token']) {
				$token['access_token'] = $arr['refresh_token'];
			}
			return $token;
		} else {
			return false;
		}
	}
	
}