<?php
/**
 *
 * 此文件为 api/uc.php 文件的开发样例，用户处理 UCenter 通知给应用程序的任务
 */

define('UC_VERSION', '1.0.0');		//UCenter 版本标识

define('API_DELETEUSER', 1);		//用户删除 API 接口开关
define('API_GETTAG', 1);		//获取标签 API 接口开关
define('API_SYNLOGIN', 1);		//同步登录 API 接口开关
define('API_SYNLOGOUT', 1);		//同步登出 API 接口开关
define('API_UPDATEPW', 1);		//更改用户密码 开关
define('API_UPDATEBADWORDS', 1);	//更新关键字列表 开关
define('API_UPDATEHOSTS', 1);		//更新域名解析缓存 开关
define('API_UPDATEAPPS', 1);		//更新应用列表 开关
define('API_UPDATECLIENT', 1);		//更新客户端缓存 开关
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');

error_reporting(7);
set_magic_quotes_runtime(0);

define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());

define('IN_MUDDER', TRUE);
define('MUDDER_ROOT', substr(dirname(__FILE__), 0, -3));
define('UC_CLIENT_ROOT', MUDDER_ROOT.'./uc_client/');

require_once MUDDER_ROOT.'./config.inc.php';

//mo_debug('GET_BEFOR', $_GET);

$code = $_GET['code'];
parse_str(authcode($code, 'DECODE', UC_KEY), $get);
if(MAGIC_QUOTES_GPC) {
	$get = dstripslashes($get);
}

if(time() - $get['time'] > 3600) {
	exit('Authracation has expiried');
}
if(empty($get)) {
	exit('Invalid Request');
}
$action = $get['action'];
$timestamp = time();

mo_debug('GET', $get);

if($action == 'test') {

	exit(API_RETURN_SUCCEED);

} elseif($action == 'deleteuser') {
	!API_DELETEUSER && exit(API_RETURN_FORBIDDEN);

	//用户删除 API 接口
	require_once MUDDER_ROOT.'./include/mysql.class.php';
	$db = new Db_class($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
	unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);

	$uids = $get['id'];
	$query = $db->query("DELETE FROM {$dbpre}members WHERE uid IN ($uids)");
	$query = $db->query("DELETE FROM {$dbpre}spaces WHERE uid IN ($uids)");
    $query = $db->query("DELETE FROM {$dbpre}favorites WHERE uid IN ($uids)");

	exit(API_RETURN_SUCCEED);

} elseif($action == 'gettag') {

	!API_GETTAG && exit(API_RETURN_FORBIDDEN);

	//获取标签 API 接口
	exit(API_RETURN_SUCCEED);

} elseif($action == 'synlogin') {

	!API_SYNLOGIN && exit(API_RETURN_FORBIDDEN);

	//同步登录 API 接口
	require_once MUDDER_ROOT.'./include/mysql.class.php';
    $db = new Db_class($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
    unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
    header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
    $cookietime = 31536000;
	$uid = intval($get['uid']);
	$query = $db->query("SELECT uid, username FROM {$dbpre}members WHERE uid='$uid'");
	if($member = $db->fetch_array($query)) {
		set_cookie('myauth', authcode($member['uid']."\t".$member['username'], 'ENCODE'), $cookietime);
	} else {
        set_cookie('loginuser', $get['username'], $cookietime);
        set_cookie('activationauth', rawurlencode(authcode($get['username']."\t".$timestamp, 'ENCODE')), 2592000);
    }

} elseif($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"');
	set_cookie('myauth', '', -86400 * 365);
    set_cookie('loginuser', '', -86400 * 365);
    set_cookie('activationauth', '', -86400 * 365);


} elseif($access == 'updatepw') {

	!API_UPDATEPW && exit(API_RETURN_FORBIDDEN);

	require_once MUDDER_ROOT.'./include/mysql.class.php';
    $db = new Db_class($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
    unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
	$username = $get['username'];
	$password = md5($get['password']);
	$db->update("UPDATE {$dbpre}members SET password='$password' WHERE username='$username'");

	//更改用户密码
	exit(API_RETURN_SUCCEED);

} elseif($action == 'updateclient') {

	!API_UPDATECLIENT && exit(API_RETURN_FORBIDDEN);

	//更新客户端缓存
	exit(API_RETURN_SUCCEED);

} elseif($action == 'updatebadwords') {

	!API_UPDATEBADWORDS && exit(API_RETURN_FORBIDDEN);

	//更新关键字列表
	exit(API_RETURN_SUCCEED);

} elseif($action == 'updatehosts') {

	!API_UPDATEHOSTS && exit(API_RETURN_FORBIDDEN);

	//更新HOST文件
	exit(API_RETURN_SUCCEED);

} elseif($action == 'updateapps') {

	!API_UPDATEAPPS && exit(API_RETURN_FORBIDDEN);

	//更新应用列表
	exit(API_RETURN_SUCCEED);

} elseif($action == 'updateclient') {

	!API_UPDATECLIENT && exit(API_RETURN_FORBIDDEN);

	//更新客户端缓存
	exit(API_RETURN_SUCCEED);

} elseif($action == 'updatecredit') {

	!UPDATECREDIT && exit(API_RETURN_FORBIDDEN);

	require_once MUDDER_ROOT.'./include/mysql.class.php';
    $db = new Db_class($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
    unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);

	$credit = intval($get['credit']);
	$amount = intval($get['amount']);
	$uid = intval($get['uid']);

	$db->query("UPDATE {$dbpre}members SET coin=coin+'$amount' WHERE uid='$uid'");

	//更新用户积分
	exit(API_RETURN_SUCCEED);

} elseif($action == 'getcreditsettings') {

	!GETCREDITSETTINGS && exit(API_RETURN_FORBIDDEN);

    $credits = array();
    $credits[] = array('金币', '');

	//向 UCenter 提供积分设置
	echo uc_serialize($credits);

} elseif($action == 'updatecreditsettings') {

	!API_UPDATECREDITSETTINGS && exit(API_RETURN_FORBIDDEN);

	$outextcredits = array();
	foreach($get['credit'] as $appid => $credititems) {
		if($appid == UC_APPID) {
			foreach($credititems as $value) {
				$outextcredits[$value['appiddesc'].'|'.$value['creditdesc']] = array(
					'creditsrc' => $value['creditsrc'],
					'title' => $value['title'],
					'unit' => $value['unit'],
					'ratio' => $value['ratio']
				);
			}
		}
	}

	require_once(MUDDER_ROOT.'./include/mysql.class.php');
    $db = new Db_class($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
    unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);

	$db->query("REPLACE INTO {$dbpre}config (variable, value) VALUES ('outextcredits', '".addslashes(serialize($outextcredits))."');");

    require_once(MUDDER_ROOT.'./data/cachefiles/cache_config.php');

    $_config['outextcredits'] = $outextcredits;
    $cachedata = "\$_config = ".mo_arrayeval($_config).";\r\n";

    if($fp = @fopen(MUDDER_ROOT.'./data/cachefiles/cache_config.php', 'wb')) {
        @fwrite($fp, "<?php\r\n//Modoer cache file\r\n//Created on ".date('Y-m-d H:i:s', $timestamp)."\r\n!defined('IN_MUDDER') && exit('Access Denied');\r\n\r\n".$cachedata."\r\n?>");
        @fclose($fp);
        @chmod($cachefile, 0777);
    }

	//更新应用积分设置
	exit(API_RETURN_SUCCEED);

} else {

	exit(API_RETURN_FAILED);

}

function set_cookie($var, $value, $life = 0) {
	global $timestamp, $cookiepre, $cookiepath, $cookiedomain, $_SERVER;
	$life = $life ? ($timestamp + $life) : 0;
	$secure = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
	$var = $cookiepre.$var;
	return setcookie($var, $value, $life, $cookiepath, $cookiedomain, $secure);
}

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 dsetcookie($var, $value, $life = 0, $prefix = 1) {
	global $cookiedomain, $cookiepath, $timestamp, $_SERVER;
	setcookie($var, $value,
		$life ? $timestamp + $life : 0, $cookiepath,
		$cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}

function dstripslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dstripslashes($val);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}

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

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

function mo_addcslashes($string) {
    return $string ? addcslashes($string, '\'\\') : '';
}

function mo_arrayeval($array, $level = 0) {

	if(!is_array($array)) {
		return "'".$array."'";
	}

	if(is_array($array) && function_exists('var_export')) {
		return var_export($array, true);
	}

	$space = '';
	for($i = 0; $i <= $level; $i++) {
		$space .= "\t";
	}
	$evaluate = "array (\n\r";
	$comma = $space;
	if(is_array($array)) {
		foreach($array as $key => $val) {
			$key = is_string($key) ? '\''.mo_addcslashes($key).'\'' : $key;
			$val = !is_array($val) && (!preg_match("/^\-?[0-9]\d*$/", $val) || strlen($val) > 12) ? '\''.mo_addcslashes($val, '\'\\').'\'' : $val;
			if(is_array($val)) {
				$evaluate .= "$comma$key => ".mo_addcslashes($val, $level + 1);
			} else {
				$evaluate .= "$comma$key => $val";
			}
			$comma = ",\n\r$space";
		}
	}
	$evaluate .= "\n\r$space)";
	return $evaluate;
}

function mo_debug($name, $array) {
    global $timestamp;
    $logfile = MUDDER_ROOT.'./api/api_'.$name.'.log';
    if(@$fp = fopen($logfile, 'a')) {
        @fwrite($fp, date('Y-m-d H:i:s', $timestamp)."\r\n");
        @fwrite($fp, mo_arrayeval($array,TRUE)."\r\n");
        @fwrite($fp, '--------------------------------------------'."\r\n");
        @fclose($fp);
    }
}

?>