<?php
class oauth_qq {
	private static $_instance;
	private $config = array();
	
	private function __construct($config) {
		$this->oauth_qq($config);
	}
	
	public static function get_instance($config) {
		if (!isset(self::$_instance)) {
			$class = __CLASS__;
			self::$_instance = new $class($config);
		}
		return self::$_instance;
	}
	
	private function oauth_qq($config) {
		$this->config = $config;
		$_SESSION["appid"] = $this->config['appid'];
		$_SESSION["appkey"] = $this->config['appkey'];
		$_SESSION["callback"] = $this->config['callback'];
		$_SESSION["scope"] = "get_user_info";
	}

	public function login() {
		$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
		$login_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=".$_SESSION["appid"]."&redirect_uri=".urlencode($_SESSION["callback"])."&scope=".$_SESSION["scope"]."&state=".$_SESSION['state'];
		header("Location: $login_url");
	}

public function callback() {
		if ($_REQUEST['state'] == $_SESSION['state']) {
        $params=array(
            'grant_type'=>'authorization_code',
            'client_id'=>$_SESSION["appid"],
            'client_secret'=>$_SESSION["appkey"],
            'code'=>$_REQUEST["code"],
            'redirect_uri'=>$_SESSION["callback"]
        );
       $token_url= $url='https://graph.qq.com/oauth2.0/token?'.http_build_query($params);
        //$result_str=$this->http($url);
       $result_str=$this->http($url);
        $json_r=array();
								if(get_magic_quotes_gpc())
         {
         $result_str = is_array($result_str) ? array_map('stripslashes_deep', $result_str) : (isset($result_str) ? stripslashes($result_str) : null);
         //return $value;
         }
        if($result_str!='')parse_str($result_str, $json_r);
								//print_r($json_r);exit;
			     $_SESSION["access_token"]=$json_r['access_token'];
			     $_SESSION["refresh_token"]=$json_r['refresh_token'];
								
		}
}
function http($url, $postfields='', $method='GET', $headers=array()){
        $ci=curl_init();
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); 
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        if($method=='POST'){
            curl_setopt($ci, CURLOPT_POST, TRUE);
            if($postfields!='')curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
        }
        $headers[]="User-Agent: qqPHP(piscdong.com)";
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLOPT_URL, $url);
        $response=curl_exec($ci);
        curl_close($ci);
        return $response;
    }
  //根据 access_token 获取openid
public function get_openid(){
        $params=array(
            'access_token'=>$_SESSION["access_token"]
        );
        $url='https://graph.qq.com/oauth2.0/me?'.http_build_query($params);
        $result_str=$this->http($url);
        $json_r=array();
        if($result_str!=''){
            preg_match('/callback\(\s+(.*?)\s+\)/i', $result_str, $result_a);
            $json_r=json_decode($result_a[1], true);
        }
								$_SESSION["openid"] = $json_r['openid'];
						
    }



	public function get_user_info() {
		$get_user_info = "https://graph.qq.com/user/get_user_info?access_token=".$_SESSION['access_token']."&oauth_consumer_key=".$_SESSION["appid"]."&openid=".$_SESSION["openid"]. "&format=json";
		$info = get_url_contents($get_user_info);
		$arr = json_decode($info, true);
		
		return $arr;
	}

	public function __clone() {
		trigger_error('Clone is not allow', E_USER_ERROR);
	}
}

function get_url_contents($url) {
    if (ini_get("allow_url_fopen") == "1")
				{
        return file_get_contents($url);
				}
			
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}
?>