<?php

error_reporting(E_ERROR | E_WARNING | E_PARSE);

define('UC_VERSION', '1.0.0');				//UCenter 版本标识
define('API_DELETEUSER', 1);				//用户删除 API 接口开关
define('API_RENAMEUSER', 1);				//用户改名 API 接口开关
define('API_UPDATEPW', 1);					//用户改密码 API 接口开关
define('API_GETTAG', 1);					//获取标签 API 接口开关
define('API_SYNLOGIN', 1);					//同步登录 API 接口开关
define('API_SYNLOGOUT', 1);					//同步登出 API 接口开关
define('API_UPDATEBADWORDS', 0);			//更新关键字列表 开关
define('API_UPDATEHOSTS', 0);				//更新域名解析缓存 开关
define('API_UPDATEAPPS', 0);				//更新应用列表 开关
define('API_UPDATECLIENT', 0);				//更新客户端缓存 开关
define('API_UPDATECREDIT', 1);				//更新用户积分 开关
define('API_GETCREDITSETTINGS', 1);			//向 UCenter 提供积分设置 开关
define('API_UPDATECREDITSETTINGS', 1);		//更新应用积分设置 开关
define('API_RETURN_SUCCEED', '1');
define('API_RETURN_FAILED', '-1');
define('API_RETURN_FORBIDDEN', '-2');

define('IN_PBDIGG', TRUE);
define('PBDIGG_ROOT', str_replace('\\', '/', substr((dirname(__FILE__)), 0, -3)));

require_once(PBDIGG_ROOT.'data/cache/cache_config.php');
if (!$pb_ucenable) {return API_RETURN_FORBIDDEN;}

require_once PBDIGG_ROOT.'data/sql.inc.php';
require_once(PBDIGG_ROOT.'include/global.func.php');
require_once PBDIGG_ROOT.'config.inc.php';
require_once(PBDIGG_ROOT.'include/'.$_PBDEV['dbType'].'.class.php');

$DB = new MySQL($db_host, $db_username, $db_password, $db_name, $db_pconnect);

parse_str(authcode($_GET['code'], 'DECODE', UC_KEY), $get);
!$get && exit('Invalid Request');
!get_magic_quotes_gpc() && addS($get);
(time() - $get['time'] > 3600) && exit('Authracation has expiried');

$uc_action = $get['action'];

if ($uc_action == 'test')
{
	exit(API_RETURN_SUCCEED);
}
elseif ($uc_action == 'deleteuser')
{
	!API_DELETEUSER && exit(API_RETURN_FORBIDDEN);
	//PBDIGG 用户不做删除处理
	exit(API_RETURN_SUCCEED);
}
elseif ($uc_action == 'renameuser')
{
	!API_RENAMEUSER && exit(API_RETURN_FORBIDDEN);
	//用户改名 API 接口
	$uid = $DB->db_fetch_one_array("SELECT uid FROM {$db_prefix}memberdata WHERE ucuid = '".$get['uid']."'");
	if ($uid)
	{
		$DB->db_query("UPDATE {$db_prefix}members SET username = '".$get['newusername']."' WHERE uid = '".$uid['uid']."'");
		$DB->db_query("UPDATE {$db_prefix}threads SET author = '".$get['newusername']."' WHERE uid = ".$uid['uid']);
		$DB->db_query("UPDATE {$db_prefix}comments SET author = '".$get['newusername']."' WHERE uid = ".$uid['uid']);
	}
	exit(API_RETURN_SUCCEED);
}
elseif ($uc_action == 'updatepw')
{
	!API_UPDATEPW && exit(API_RETURN_FORBIDDEN);
	//更改用户密码
	$DB->db_query("UPDATE {$db_prefix}members SET password = '".md5($get['password'])."' WHERE username = '".$get['username']."'");
	exit(API_RETURN_SUCCEED);
}
elseif ($uc_action == 'gettag')
{
	!API_GETTAG && exit(API_RETURN_FORBIDDEN);
	$tagname = trim($get['id']);
	if(empty($tagname) || !preg_match('/^([\x7f-\xff_-]|\w|\s)+$/', $tagname) || strlen($tagname) > 20)
	{
		exit(API_RETURN_FAILED);
	}
	//获取标签 API 接口
	$threads = array();
	$DB->db_query("SELECT t.tid, t.subject, t.postdate, t.author FROM {$db_prefix}threads t LEFT JOIN {$db_prefix}tagcache tc USING ( tid ) LEFT JOIN {$db_prefix}tags tg ON tc.tagid = tg.tagid WHERE tg.tagname = '".$tagname."'");
	while ($r = $DB->db_fetch_array())
	{
		if ($r['tid'])
		{
			$threads[] = array(
				'subject' => $r['subject'],
				'postdate' => $r['postdate'],
				'author' => $r['author'],
				'url' => $_PBENV['PB_URL'].'show.php?tid='.$r['tid']
			);
		}
	}
	echo uc_serialize(array($tagname, $threads), 1);
}
elseif ($uc_action == 'synlogin' && $_GET['time'] == $get['time'])
{
	!API_SYNLOGIN && exit(API_RETURN_FORBIDDEN);
	//同步登录 API 接口
	$uid = intval($get['uid']);
	$member = $DB->db_fetch_one_array("SELECT m.uid, m.password FROM {$db_prefix}members m LEFT JOIN {$db_prefix}memberdata md USING (uid) WHERE md.ucuid = '$uid'");
	if($member)
	{
		header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
		sCookie('pb_auth', PEncode(($member['uid']."\t".$member['password']), $pb_sitehash), 0);
		$DB->db_query("UPDATE {$db_prefix}memberdata SET visitcount = visitcount + 1 WHERE uid = ".$member['uid']." LIMIT 1");
	}
}
elseif ($uc_action == 'synlogout')
{
	!API_SYNLOGOUT && exit(API_RETURN_FORBIDDEN);
	//同步登出 API 接口
	header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
	sCookie('pb_auth', '', -1);
	sCookie('pb_sid', '', -1);
}
elseif ($uc_action == 'updatebadwords')
{
	!API_UPDATEBADWORDS && exit(API_RETURN_FORBIDDEN);
	//更新关键字列表
	exit(API_RETURN_SUCCEED);
}
elseif ($uc_action == 'updatehosts')
{
	!API_UPDATEHOSTS && exit(API_RETURN_FORBIDDEN);
	//更新HOST文件
	exit(API_RETURN_SUCCEED);
}
elseif ($uc_action == 'updateapps')
{
	!API_UPDATEAPPS && exit(API_RETURN_FORBIDDEN);
	//更新应用列表
	exit(API_RETURN_SUCCEED);
}
elseif ($uc_action == 'updateclient')
{
	!API_UPDATECLIENT && exit(API_RETURN_FORBIDDEN);
	//更新客户端缓存
	exit(API_RETURN_SUCCEED);
}
elseif ($uc_action == 'updatecredit')
{
	//更新用户积分
	!UPDATECREDIT && exit(API_RETURN_FORBIDDEN);
	$amount = intval($get['amount']);
	$uid = intval($get['uid']);
	$DB->db_query("UPDATE {$db_prefix}memberdata SET currency = currency + '$amount' WHERE ucuid = '$uid'");
	exit(API_RETURN_SUCCEED);
}
elseif ($uc_action == 'getcreditsettings')
{
	//向 UCenter 提供积分设置
	!GETCREDITSETTINGS && exit(API_RETURN_FORBIDDEN);
	echo uc_serialize(array('1' => array($pb_customcredit, '')));
}
elseif ($uc_action == 'updatecreditsettings')
{
	//更新应用积分设置
	!API_UPDATECREDITSETTINGS && exit(API_RETURN_FORBIDDEN);
	exit(API_RETURN_SUCCEED);
}
else
{
	exit(API_RETURN_FAILED);
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

	$ckey_length = 4;

	$key = md5($key ? $key : UC_KEY);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}

}

function uc_serialize($arr, $htmlon = 0) {
	include_once PBDIGG_ROOT.'client/lib/xml.class.php';
	return xml_serialize($arr, $htmlon);
}

function uc_unserialize($s) {
	include_once PBDIGG_ROOT.'client/lib/xml.class.php';
	return xml_unserialize($s);
}