<?php
/**
 * 彩虹聚合登录SDK
 * 1.0
**/
include dirname(__DIR__) . '/includes/common.php';
if($islogin2==1){
	@header('Content-Type: text/html; charset=UTF-8');
	exit("<script language='javascript'>alert('您已登陆！');window.location.href='./index.php';</script>");
}
// API地址
$Oauth_config['apiurl'] = $conf['quick_url'];
// APPID
$Oauth_config['appid'] = $conf['quick_appid'];
// APPKEY
$Oauth_config['appkey'] = $conf['quick_appkey'];
// 登录成功返回地址
$return_url = isset($_GET['return_url']) ? $_GET['return_url'] : ($hosturl.'/user/index.php');
$Oauth_config['callback'] = $hosturl.'/user/connect.php?return_url='.urlencode($return_url);

error_reporting(0);
session_start();
@header('Content-Type: text/html; charset=UTF-8');
include dirname(__DIR__) . '/includes/oauth/Oauth.class.php';
$type = isset($_GET['type'])?$_GET['type']:'qq';

// 生成一个唯一标识存入session和cookie，用于检测是否同一浏览器
if(!isset($_GET['code'])){
	$browser_id = md5(uniqid(rand(), TRUE));
	$_SESSION['oauth_browser_id'] = $browser_id;
	setcookie('oauth_browser_id', $browser_id, time() + 300, '/');
}

if($_GET['code']){
	// 检测是否同一浏览器
	$session_browser_id = isset($_SESSION['oauth_browser_id']) ? $_SESSION['oauth_browser_id'] : '';
	$cookie_browser_id = isset($_COOKIE['oauth_browser_id']) ? $_COOKIE['oauth_browser_id'] : '';
	
	if($_GET['state'] != $_SESSION['Oauth_state']){
		exit("The state does not match. You may be a victim of CSRF.");
	}
	$Oauth=new Oauth($Oauth_config);
	$arr = $Oauth->callback();
	if(isset($arr['code']) && $arr['code']==0){
		$_SESSION['oauth_arr'] = array('time'=>strtotime('+5minute'),'data'=>$arr);
		$openid=$arr['social_uid'];
		$openid_type = $arr['type'];

		// 保存QQ信息用于找回功能
		$_SESSION['quick_login_qq'] = $openid;
		$_SESSION['quick_login_time'] = time();

		/* 处理用户登录逻辑 */
		$row = $DB->getRow("SELECT user,pwd FROM pre_user WHERE openid_".$openid_type."='{$openid}' limit 1");
		if($row){
			$user = $row['user'];
			$pass = $row['pwd'];
			$session=md5($user.$pass.$password_hash);
			$expiretime=time()+604800;
			$token=authcode("{$user}\t{$session}\t{$expiretime}", 'ENCODE', SYS_KEY);
			setcookie("user_token", $token, time() + 604800, '/');
			@header('Content-Type: text/html; charset=UTF-8');
			exit("<script language='javascript'>window.location.href='{$return_url}';</script>");
		}else{
			//绑定openid
			@header('Content-Type: text/html; charset=UTF-8');
			exit("<script language='javascript'>alert('即将跳转绑定快捷登录');window.location.href='./oauth.php';</script>");
		}
	}elseif(isset($arr['code'])){
		exit('登录失败，返回错误原因：'.$arr['msg']);
	}else{
		exit('获取登录数据失败');
	}
}else{
	$Oauth=new Oauth($Oauth_config);
	$arr = $Oauth->login($type);
	if(isset($arr['code']) && $arr['code']==0){
		exit("<script language='javascript'>window.location.href='{$arr['url']}';</script>");
	}elseif(isset($arr['code'])){
		exit('登录接口返回：'.$arr['msg']);
	}else{
		exit('获取登录地址失败');
	}
}
