<?php

class xc_core {
	var $_G = array();

	var $db = array();

	var $config = array();

	var $language = array();

	var $initated = false;

	function &instance() {
		static $object;
		if(empty($object)) {
			$object = new xc_core();
		}
		return $object;
	}

	function xc_core() {
		$this->_init_env();
		$this->_init_config();
	}

	function init() {
		if($this->config['db']['config']) {
			if(!$this->initated) {
				$this->_init_db();
			}
			$this->initated = true;
		}
	}

	function _init_env() {

		error_reporting(E_ERROR);
		if(phpversion() < '5.3.0') {
			set_magic_quotes_runtime(0);
		}
		set_time_limit(0);

		define('XCONVERT_ROOT', substr(dirname(__FILE__), 0, -12));
		define('TPLDIR', './template/');
		define('MAGIC_QUOTES_GPC', function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc());
		define('ICONV_ENABLE', function_exists('iconv'));
		define('MB_ENABLE', function_exists('mb_convert_encoding'));
		define('EXT_OBGZIP', function_exists('ob_gzhandler'));

		define('TIMESTAMP', time());

		if(!@include(XCONVERT_ROOT.'./source/include/global.func.php')) {
			exit('global.func.php is missing');
		}
		@include(XCONVERT_ROOT.'./source/include/xConvert_version.php');

		if(function_exists('ini_get')) {
			$memorylimit = @ini_get('memory_limit');
			if($memorylimit && return_bytes($memorylimit) < 33554432 && function_exists('ini_set')) {
				ini_set('memory_limit', '128m');
			}
		}

		if(PHP_VERSION < '4.1.0') {
			$_GET = &$HTTP_GET_VARS;
			$_POST = &$HTTP_POST_VARS;
			$_COOKIE = &$HTTP_COOKIE_VARS;
			$_SERVER = &$HTTP_SERVER_VARS;
			$_ENV = &$HTTP_ENV_VARS;
			$_FILES = &$HTTP_POST_FILES;
		}

		isset($_REQUEST['GLOBALS']) && showmessage('common_phperror');

		foreach($_POST as $_key => $_value) {
			$_key{0} != '_' && $this->_G[$_key] = daddslashes($_value);
		}
		foreach($_GET as $_key => $_value) {
			$_key{0} != '_' && $this->_G[$_key] = daddslashes($_value);
		}

		(!MAGIC_QUOTES_GPC) && $_FILES = daddslashes($_FILES);
		
		include_once './language/zh.lang.php';
		$this->language = & $language;

		$this->_G['timestamp'] = time();
		
		$PHP_SELF = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
		$SCRIPT_FILENAME = str_replace('\\\\', '/', (isset($_SERVER['PATH_TRANSLATED']) ? $_SERVER['PATH_TRANSLATED'] : $_SERVER['SCRIPT_FILENAME']));
	}

	function _init_config() {
		$_config = array();
		if(!file_exists("./cache/lock/config_reset.lock")) {
			writeconfig2("config", '0');
		}
		require_once XCONVERT_ROOT.'./config.inc.php';
		if(empty($_config)) {
			showmessage('config_notfound');
		}
		if($_config['info']['debug'] || $action != 'convert') {
			error_reporting(E_ERROR | E_WARNING | E_PARSE);
		}
		$this->config = & $_config;
		define('CHARSET', $this->config['info']['defaultlanguage']);
	}
	
	function _init_db() {
		require_once XCONVERT_ROOT.'./source/class/db.class.php';
		switch($this->config['db']['source_dbtype']) {
			case 'mysql' :
				$this->db['source'] = new db_mysql;
				break;
			case 'mssql' :
				$this->db['source'] = new db_mssql;
				break;
			case 'access' :
				$this->db['source'] = new db_access;
				break;
			case 'oracle' :
				$this->db['source'] = new db_oracle;
				break;
		}
		$this->db['source']->connect($this->config['db']['source_dbhost'], $this->config['db']['source_dbuser'], $this->config['db']['source_dbpw'], $this->config['db']['source_dbname']);

		$this->db['discuz'] = new db_mysql;
		$this->db['discuz']->connect($this->config['db']['discuz_dbhost'], $this->config['db']['discuz_dbuser'], $this->config['db']['discuz_dbpw'], $this->config['db']['discuz_dbname']);
		
		if($this->config['db']['is_uc']){
			$this->db['uc'] = new db_mysql;
			$this->db['uc']->connect($this->config['db']['uc_dbhost'], $this->config['db']['uc_dbuser'], $this->config['db']['uc_dbpw'], $this->config['db']['uc_dbname']);
			if($this->config['db']['is_uch']) {
				$this->db['uchome'] = new db_mysql;
				$this->db['uchome']->connect($this->config['db']['uch_dbhost'], $this->config['db']['uch_dbuser'], $this->config['db']['uch_dbpw'], $this->config['db']['uch_dbname']);
			}
		}
	}
}

class DB
{

	function table($table) {
		return DB::_execute('table_name', $table);
	}

	function delete($table, $condition, $limit = 0, $unbuffered = true) {
		if(empty($condition)) {
			$where = '1';
		} elseif(is_array($condition)) {
			$where = DB::implode_field_value($condition, ' AND ');
		} else {
			$where = $condition;
		}
		$sql = "DELETE FROM ".DB::table($table)." WHERE $where ".($limit ? "LIMIT $limit" : '');
		return DB::query($sql, ($unbuffered ? 'UNBUFFERED' : ''));
	}

	function insert($table, $data, $return_insert_id = false, $replace = false, $silent = false) {

		$sql = DB::implode_field_value($data);

		$cmd = $replace ? 'REPLACE INTO' : 'INSERT INTO';

		$table = DB::table($table);
		$silent = $silent ? 'SILENT' : '';

		$return = DB::query("$cmd $table SET $sql", $silent);

		return $return_insert_id ? DB::insert_id() : $return;

	}

	function update($table, $data, $condition, $unbuffered = false, $low_priority = false) {
		$sql = DB::implode_field_value($data);
		$cmd = "UPDATE ".($low_priority ? 'LOW_PRIORITY' : '');
		$table = DB::table($table);
		$where = '';
		if(empty($condition)) {
			$where = '1';
		} elseif(is_array($condition)) {
			$where = DB::implode_field_value($condition, ' AND ');
		} else {
			$where = $condition;
		}
		$res = DB::query("$cmd $table SET $sql WHERE $where", $unbuffered ? 'UNBUFFERED' : '');
		return $res;
	}

	function implode_field_value($array, $glue = ',') {
		$sql = $comma = '';
		foreach ($array as $k => $v) {
			$sql .= $comma."`$k`='$v'";
			$comma = $glue;
		}
		return $sql;
	}

	function insert_id() {
		return DB::_execute('insert_id');
	}

	function fetch($resourceid, $type = MYSQL_ASSOC) {
		return DB::_execute('fetch_array', $resourceid, $type);
	}

	function fetch_first($sql) {
		DB::checkquery($sql);
		return DB::_execute('fetch_first', $sql);
	}

	function result($resourceid, $row = 0) {
		return DB::_execute('result', $resourceid, $row);
	}

	function result_first($sql) {
		DB::checkquery($sql);
		return DB::_execute('result_first', $sql);
	}

	function query($sql, $type = '') {
		DB::checkquery($sql);
		return DB::_execute('query', $sql, $type);
	}

	function num_rows($resourceid) {
		return DB::_execute('num_rows', $resourceid);
	}

	function affected_rows() {
		return DB::_execute('affected_rows');
	}

	function free_result($query) {
		return DB::_execute('free_result', $query);
	}

	function error() {
		return DB::_execute('error');
	}

	function errno() {
		return DB::_execute('errno');
	}

	function _execute($cmd , $arg1 = '', $arg2 = '') {
		static $db;
		if(empty($db)) $db = & DB::object();
		$res = $db->$cmd($arg1, $arg2);
		return $res;
	}

	function &object() {
		static $db;
		if(empty($db)) $db = new db_mysql();
		return $db;
	}

	function checkquery($sql) {
		static $status = null, $checkcmd = array('SELECT', 'UPDATE', 'INSERT', 'REPLACE', 'DELETE');
		if($status === null) $status = getglobal('config/security/querysafe/status');
		if($status) {
			$cmd = trim(strtoupper(substr($sql, 0, strpos($sql, ' '))));
			if(in_array($cmd, $checkcmd)) {
				$test = DB::_do_query_safe($sql);
				if($test < 1) DB::_execute('halt', 'security_error', $sql);
			}
		}
		return true;
	}

	function _do_query_safe($sql) {
		static $_CONFIG = null;
		if($_CONFIG === null) {
			$_CONFIG = getglobal('config/security/querysafe');
		}

		$sql = str_replace(array('\\\\', '\\\'', '\\"', '\'\''), '', $sql);
		$mark = $clean = '';
		if(strpos($sql, '/') === false && strpos($sql, '#') === false && strpos($sql, '-- ') === false) {
			$clean = preg_replace("/'(.+?)'/s", '', $sql);
		} else {
			$len = strlen($sql);
			$mark = $clean = '';
			for ($i = 0; $i <$len; $i++) {
				$str = $sql[$i];
				switch ($str) {
					case '\'':
						if(!$mark) {
							$mark = '\'';
							$clean .= $str;
						} elseif ($mark == '\'') {
							$mark = '';
						}
						break;
					case '/':
						if(empty($mark) && $sql[$i+1] == '*') {
							$mark = '/*';
							$clean .= $mark;
							$i++;
						} elseif($mark == '/*' && $sql[$i -1] == '*') {
							$mark = '';
							$clean .= '*';
						}
						break;
					case '#':
						if(empty($mark)) {
							$mark = $str;
							$clean .= $str;
						}
						break;
					case "\n":
						if($mark == '#' || $mark == '--') {
							$mark = '';
						}
						break;
					case '-':
						if(empty($mark)&& substr($sql, $i, 3) == '-- ') {
							$mark = '-- ';
							$clean .= $mark;
						}
						break;

					default:

						break;
				}
				$clean .= $mark ? '' : $str;
			}
		}

		$clean = preg_replace("/[^a-z0-9_\-\(\)#\*\/\"]+/is", "", strtolower($clean));

		if($_CONFIG['afullnote']) {
			$clean = str_replace('/**/','',$clean);
		}

		if(is_array($_CONFIG['dfunction'])) {
			foreach($_CONFIG['dfunction'] as $fun) {
				if(strpos($clean, $fun.'(') !== false) return '-1';
			}
		}

		if(is_array($_CONFIG['daction'])) {
			foreach($_CONFIG['daction'] as $action) {
				if(strpos($clean,$action) !== false) return '-3';
			}
		}

		if($_CONFIG['dlikehex'] && strpos($clean, 'like0x')) {
			return '-2';
		}

		if(is_array($_CONFIG['dnote'])) {
			foreach($_CONFIG['dnote'] as $note) {
				if(strpos($clean,$note) !== false) return '-4';
			}
		}

		return 1;

	}

}
?>
