<?php
function template($file, $templateid = 0, $tpldir = '', $gettplfile = 0, $primaltpl='') {
	$cachepath ='./cache/tpl/';
	$tplfile = TPLDIR.'/'.$file.'.html';
	$cachefile = $cachepath.$file.'.tpl.php';

	if(!file_exists(XCONVERT_ROOT.$cachefile)) {
		$tplmtime = @filemtime(XCONVERT_ROOT.$cachefile);
	}
	if(empty($tplmtime) || $tplmtime < @filemtime(XCONVERT_ROOT.TPLDIR.'/'.$file.'.html')) {
		require_once XCONVERT_ROOT.'/source/class/class_template.php';
		$template = new template();
		$template->parse_template($tplfile, $templateid, $tpldir, $file, $cachefile);
	}
	
	return $cachefile;
}

function checktplrefresh($maintpl, $subtpl, $timecompare, $templateid, $cachefile, $tpldir, $file) {
	if(empty($timecompare) || @filemtime(XCONVERT_ROOT.$subtpl) > $timecompare) {
		require_once XCONVERT_ROOT.'/source/class/class_template.php';
		$template = new template();
		$template->parse_template($maintpl, $templateid, $tpldir, $file, $cachefile);
		return TRUE;
	}
	return FALSE;
}

function strexists($string, $find) {
	return !(strpos($string, $find) === FALSE);
}

function validid($id, $table, $tablepre = '', $condition = '') {//获得数据表的最大和最小 id 值
	global $start, $end, $maxid, $rpp, $source_dbtype, $xc, $source_tablepre, $source_dbowner, $language;
	$source_tablepre = preg_replace("/^$source_dbowner\.(.+)/i", '\\1', $source_tablepre);
	$tablepre = $tablepre ? $tablepre : $source_tablepre;
	$table = preg_replace("/^$tablepre(.+)/i", '\\1', $table);
	$source_dbtype = strtolower($source_dbtype);
	if ($source_dbtype == 'mssql' || $source_dbtype == 'mysql') {
		$tablepre = $source_dbowner ? $source_dbowner.'.'.$tablepre : $tablepre;
		$sql = $xc->db['source']->query("SELECT MIN($id) AS minid, MAX($id) AS maxid FROM {$tablepre}$table".($condition ? ' WHERE '.$condition : '')) or dexit($language['convert_column'].$id.'\''.$tablepre.$table.'\''.$language['convert_invalid'], 'mssql');
		$result = $xc->db['source']->fetch_array($sql);
		$start = $result['minid'] ? $result['minid'] : 1;
		$maxid = $result['maxid'];
		$end = $start + $rpp - 1;
		$source_tablepre = ($source_dbowner ? $source_dbowner.'.' : '').$source_tablepre;
	} elseif ($source_dbtype == 'access') {
		if(!$xc->db['source']->tableexist($tablepre.$table)) {
			dexit($language['convert_notable'].'\''.$tablepre.$table.'\'。 '.$language['convert_confirmright'].'<br>'.$language['convert_possiblecauses'].'：<br><font color="red">1.\''.$tablepre.'\' '.$language['convert_wrongtablepre'].'；<br>2.'.$language['convert_table'].' \''.$tablepre.$table.'\' '.$language['convert_nonentity'].'</font>');
		}
		$sql = "SELECT MIN($id) AS minid, MAX($id) AS maxid FROM {$tablepre}$table".($condition ? ' WHERE '.$condition : '');
		$rs = @$xc->db['source']->execute($sql);
		if (!$rs->EOF) {
			$start = $rs->fields[minid]->value;
			$maxid = $rs->fields[maxid]->value;
		}
		$rs->close();
		$start = $start > 1 ? $start : 1;
		$end = $start + $rpp - 1;
	}
}

function daddslashes($string, $trim = '1') {//如果$trim为1,则强制trim所有,方便查询出来的数据进行trim
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = daddslashes($val);
		}
	} else {
		$string = $trim ? trim(addslashes($string)) : addslashes($string);
	}
	return $string;
}

function diconv($string, $source, $target) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = diconv($val);
		}
	} else {
		$string = iconv($source, $target."//IGNORE", $string);
	}
	return $string;
}

function cutstr($string, $length, $dot = '') {
	global $discuz_charset;

	if(strlen($string) <= $length) {
		return $string;
	}
	$strcut = '';
	if(strtolower($discuz_charset) == 'utf8') {

		$n = $tn = $noc = 0;
		while ($n < strlen($string)) {

			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t < 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}

			if ($noc >= $length) {
				break;
			}

		}
		if ($noc > $length) {
			$n -= $tn;
		}

		$strcut = substr($string, 0, $n);

	} else {
		for($i = 0; $i < $length - strlen($dot) - 1; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}
	return $strcut.$dot;
}

function reportlog($msg = '', $nowerror='1') {
	global $xc, $step, $discuz_tablepre;
	$msg = daddslashes($msg);
	if ($nowerror == 0) {
		$reportsql = "REPLACE INTO {$discuz_tablepre}xreports (rid, step, errnum, message) VALUES ('$step', '$step', '0', '$msg')";
		$xc->db['discuz']->query($reportsql);
	} else {
		$errnum = $xc->db['discuz']->errno();
		$reportsql = "REPLACE INTO {$discuz_tablepre}xreports (rid, step, errnum, message) VALUES ('', '$step', '$errnum', '$msg')";
		if($errnum || $msg) {
			$xc->db['discuz']->query($reportsql);
		}
	}
}

function report() {
	global $xc, $convertedrows, $totalrows, $step, $discuz_tablepre;
	$timestamp = time();
	$timestart = $xc->db['discuz']->result($xc->db['discuz']->query("SELECT message FROM {$discuz_tablepre}xreports WHERE rid = '$step'"), 0);
	$msg = $convertedrows.','.$totalrows.','.$timestamp.','.$timestart;
	reportlog($msg, 0);
}

function startreport() {
	global $xc, $step, $discuz_tablepre;
	$timestamp = time();
	$xc->db['discuz']->query("DELETE FROM {$discuz_tablepre}xreports WHERE step = '$step'");
	reportlog($timestamp, 0);
}

function parseqqicq($qqicq, $minlen = 5, $maxlen = 12) {// qq 转换
	return $qqicq ? (preg_match("/^([0-9]+)$/", $qqicq) && strlen($qqicq) >= $minlen && strlen($qqicq) <= $maxlen ? $qqicq : '') : '';
}

function parsesite($site) {//个人网址转换
	if($site && strtolower($site) != 'http://') {
		$user_site = trim(preg_match("/^https?:\/\/.+/i", $site) ? $site : ($site ? 'http://'.$site : ''));
		return $user_site ? cutstr(htmlspecialchars($user_site), 75) : '';
	}
	return '';
}

function parsesign($sign) {//个人签名转换

	$searcharray = array(
		'[/color]', '[/size]', '[/font]', '[/align]', '[b]', '[/b]',
		'[i]', '[/i]', '[u]', '[/u]', '[list]', '[list=1]', '[list=a]',
		'[list=A]', '[*]', '[/list]', '[indent]', '[/indent]'
	);

	$replacearray = array(
		'</font>', '</font>', '</font>', '</p>', '<b>', '</b>', '<i>',
		'</i>', '<u>', '</u>', '<ul>', '<ol type=1>', '<ol type=a>',
		'<ol type=A>', '<li>', '</ul></ol>', '<blockquote>', '</blockquote>'
	);

	$pregfind = array(
		"/\[url\]\s*(www.|https?:\/\/|ftp:\/\/|gopher:\/\/|news:\/\/|telnet:\/\/|rtsp:\/\/|mms:\/\/|callto:\/\/|ed2k:\/\/){1}([^\[\"']+?)\s*\[\/url\]/ie",
		"/\[url=www.([^\[\"']+?)\](.+?)\[\/url\]/is",
		"/\[url=(https?|ftp|gopher|news|telnet|rtsp|mms|callto|ed2k){1}:\/\/([^\[\"']+?)\](.+?)\[\/url\]/is",
		"/\[email\]\s*([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+)\s*\[\/email\]/i",
		"/\[email=([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+)\](.+?)\[\/email\]/is",
		"/\[color=([^\[\<]+?)\]/i",
		"/\[size=([^\[\<]+?)\]/i",
		"/\[font=([^\[\<]+?)\]/i",
		"/\[align=([^\[\<]+?)\]/i",
		"/\s*\[quote\][\n\r]*(.+?)[\n\r]*\[\/quote\]\s*/is",
		"/\s*\[code\](.+?)\[\/code\]\s*/is",
		"/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies",
		"/\[img=(\d{1,3})[x|\,](\d{1,3})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies"
	);
	$pregreplace = array(
		"cuturl('\\1\\2')",
		"<a href=\"http://www.\\1\" target=\"_blank\">\\2</a>",
		"<a href=\"\\1://\\2\" target=\"_blank\">\\3</a>",
		"<a href=\"mailto:\\1@\\2\">\\1@\\2</a>",
		"<a href=\"mailto:\\1@\\2\">\\3</a>",
		"<font color=\"\\1\">",
		"<font size=\"\\1\">",
		"<font face=\"\\1\">",
		"<p align=\"\\1\">",
		"<div class=\"altbg2\" style=\"margin: 2em; margin-top: 3px; padding: 10px; border: 0px solid #86B9D6; word-break: break-all\">\\1</div>",
		"<div class=\"altbg2\" style=\"margin: 2em; margin-top: 3px; clear: both; padding: 10px; padding-top: 5px; border: 0px solid #86B9D6; word-break: break-all\">\\1</div>",
		"bbcodeurl('\\1', '<img src=\"%s\" border=\"0\" onload=\"if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.alt=\'Click here to open new window\\nCTRL+Mouse wheel to zoom in/out\';}\" onmouseover=\"if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.style.cursor=\'hand\'; this.alt=\'Click here to open new window\\nCTRL+Mouse wheel to zoom in/out\';}\" onclick=\"if(!this.resized) {return true;} else {window.open(\'%s\');}\" onmousewheel=\"return imgzoom(this);\" alt=\"\" />')",
		"bbcodeurl('\\3', '<img width=\"\\1\" height=\"\\2\" src=\"%s\" border=\"0\" alt=\"\" />')"
	);

	return daddslashes(str_replace($searcharray, $replacearray, preg_replace($pregfind, $pregreplace, $sign)));
}

function bbcodeurl($url, $tags) {//url 转换
	if(!preg_match("/<.+?>/s", $url)) {
		if(!in_array(strtolower(substr($url, 0, 6)), array('http:/', 'ftp://', 'rtsp:/', 'mms://'))) {
			$url = 'http://'.$url;
		}
		return str_replace(array('submit', 'logging.php'), array('', ''), sprintf($tags, $url, addslashes($url)));
	} else {
		return '&nbsp;'.$url;
	}
}

function cuturl($url) {//将超链接的链接代码缩短
	$length = 65;
	$urllink = "<a href=\"".(substr(strtolower($url), 0, 4) == 'www.' ? "http://$url" : $url).'" target="_blank">';
	if(strlen($url) > $length) {
		$url = substr($url, 0, intval($length * 0.5)).' ... '.substr($url, - intval($length * 0.3));
	}
	$urllink .= $url.'</a>';
	return $urllink;
}

function timetounix($time) {//将字符串时间转换成时间戳
	if($time > 100000000) {
		return $time;
	}
	$time = str_replace(array(' 一月 ',' 二月 ',' 三月 ',' 四月 ',' 五月 ',' 六月 ',' 七月 ',' 八月 ',' 九月 ',' 十月 ',' 十一月 ',' 十二月 ', ' 上午 '), array('-1-','-2-','-3-','-4-','-5-','-6-','-7-','-8-','-9-','-10-','-11-','-12-', ' '), $time);
	if(strrchr($time, '下午') !== false) {
		return strtotime(str_replace(' 下午 ', ' ', $time)) + 43200;
	} else {
		return strtotime($time);
	}
}

function getuid($username) {//根据 uid 获取 username
	global $xc, $discuz_tablepre, $config_type;
	$sql = '';
	$sql = "SELECT uid FROM {$discuz_tablepre}".($config_type == 'x' ? "common_member" : "members")." WHERE username='$username' LIMIT 1";
	return $username ? $xc->db['discuz']->result($xc->db['discuz']->query($sql), 0) : 0;
}

function getusername($uid) {//根据 username 获取 uid
	global $xc, $discuz_tablepre, $config_type;
	return $uid ? $xc->db['discuz']->result($xc->db['discuz']->query("SELECT username FROM {$discuz_tablepre}".($config_type == 'x' ? "common_member" : "members")." WHERE uid='$uid' LIMIT 1"), 0) : '';
}

function addmoderators($moderators, $fid) {
	global $xc, $discuz_tablepre, $language, $config_type;
	$moderator = $comma = '';
	if(is_array($moderators) && !empty($moderators)) {
		foreach($moderators AS $username) {
			$username = trim($username);
			if ($moderatorid = getuid($username)) {
				$xc->db['discuz']->query("UPDATE {$discuz_tablepre}".($config_type == 'x' ? "common_member": "members")." SET adminid=3, groupid=3 WHERE uid='$moderatorid' AND adminid=0;") or reportlog($language['report_failupdate']);
				$xc->db['discuz']->query("REPLACE INTO {$discuz_tablepre}".($config_type == 'x' ? "forum_moderator": "moderators")." (uid, fid, displayorder, inherited) VALUES ('$moderatorid', '$fid', '0', '0');") or reportlog($language['report_failsetmod']);
				$moderator .= $comma.$username;
				$comma = "\t";
			}
		}
	}
	return $moderator;
}

function convertcharset($msg) {//使用 iconv 转换字符集
	global $source_charset, $discuz_charset, $xc, $language;
	if($discuz_charset == $source_charset || ($xc->db['source']->version() > 4.1 && $xc->db['discuz']->version() > 4.1)){
		return $msg;
	} elseif (function_exists(iconv)) {
		$source_charset = str_replace('utf8', 'utf-8', $source_charset);
		$discuz_charset = str_replace('utf8', 'utf-8', $discuz_charset);
		return iconv($source_charset, $discuz_charset, $msg);
	} else {
		showmessage($language['convert_noiconv']);
	}
}

function truncatetable($table){//清空 Discuz! 数据表
	global $xc, $discuz_tablepre, $language;
	$xc->db['discuz']->query("TRUNCATE TABLE {$discuz_tablepre}$table") or dexit($language['convert_truncatetable'].$discuz_tablepre.$table.$language['convert_failed']);
}

function truncatetable_uc($table){//清空 UCenter 数据表
	global $xc, $uc_tablepre, $language;
	$xc->db['uc']->query("TRUNCATE TABLE {$uc_tablepre}$table") or dexit($language['convert_truncatetable'].$uc_tablepre.$table.$language['convert_failed']);
}

function truncatetable_uch($table){//清空 UCenter Home 数据表
	global $xc, $uch_tablepre, $language;
	$xc->db['uchome']->query("TRUNCATE TABLE {$uch_tablepre}$table") or dexit($language['convert_truncatetable'].$uch_tablepre.$table.$language['convert_failed']);
}

function copytable($sourcetable, $duplicatetable, $data = 0){//复制 Discuz! 数据表
	global $xc, $discuz_tablepre;
	$xc->db['discuz']->query("DROP TABLE IF EXISTS {$discuz_tablepre}$duplicatetable");
	$xc->db['discuz']->query("CREATE TABLE {$discuz_tablepre}$duplicatetable SELECT * FROM {$discuz_tablepre}$sourcetable".($data ? '' : " WHERE 1<>1"));
}

function altertable($table, $orderby){
	global $xc, $discuz_tablepre, $language;
	$xc->db['discuz']->query("ALTER TABLE {$discuz_tablepre}$table ORDER BY $orderby ASC") or reportlog($language['convert_altertalbe'].$discuz_tablepre.$table.$language['convert_failed']);
}

function altertable_uc($table, $orderby){
	global $xc, $uc_tablepre, $language;
	$xc->db['uc']->query("ALTER TABLE {$uc_tablepre}$table ORDER BY $orderby ASC") or reportlog($language['convert_altertalbe'].$uc_tablepre.$table.$language['convert_failed']);
}

function loadtable($table, $force = 0) {	//检查数据库表字符集函数
	global $xc;
	$discuz_tablepre = $xc->config['db']['discuz_tablepre'];
	static $tables = array();

	if(!isset($tables[$table]) || $force) {
		if($xc->db['discuz']->version() > '4.1') {
			$query = $xc->db['discuz']->query("SHOW FULL COLUMNS FROM {$discuz_tablepre}$table", 'SILENT');
		} else {
			$query = $xc->db['discuz']->query("SHOW COLUMNS FROM {$discuz_tablepre}$table", 'SILENT');
		}
		while($field = @$xc->db['discuz']->fetch_array($query)) {
			$tables[$table][$field['Field']] = $field;
		}
	}
	return $tables[$table];
}

function loadtable_uc($table, $force = 0) {	//检查数据库表字符集函数
	global $xc, $uc_tablepre, $uc_charset;
	$uc_tablepre = $xc->config['db']['uc_tablepre'];
	static $tables = array();

	if(!isset($tables[$table]) || $force) {
		if($xc->db['uc']->version() > '4.1') {
			$query = $xc->db['uc']->query("SHOW FULL COLUMNS FROM {$uc_tablepre}$table", 'SILENT');
		} else {
			$query = $xc->db['uc']->query("SHOW COLUMNS FROM {$uc_tablepre}$table", 'SILENT');
		}
		while($field = @$xc->db['uc']->fetch_array($query)) {
			$tables[$table][$field['Field']] = $field;
		}
	}
	return $tables[$table];
}

function loadtable_uch($table, $force = 0) {	//检查数据库表字符集函数
	global $xc, $uch_tablepre, $uch_charset;
	$uch_tablepre = $xc->config['db']['uch_tablepre'];
	static $tables = array();

	if(!isset($tables[$table]) || $force) {
		if($xc->db['uchome']->version() > '4.1') {
			$query = $xc->db['uchome']->query("SHOW FULL COLUMNS FROM {$uch_tablepre}$table", 'SILENT');
		} else {
			$query = $xc->db['uchome']->query("SHOW COLUMNS FROM {$uch_tablepre}$table", 'SILENT');
		}
		while($field = @$xc->db['uchome']->fetch_array($query)) {
			$tables[$table][$field['Field']] = $field;
		}
	}
	return $tables[$table];
}

function createform() {
	extract($GLOBALS, EXTR_SKIP);
	dheader();
	global $language;
	include_once language();
	echo $language['create_step1'];
	echo '<div style="text-align:center; font-weight:bolder;">'.$language['config_please'].'</div>';
	echo '<form method="post"><table width="95%" border="0" bgcolor="#000000" cellspacing="1" cellpadding="0" align="center"><br>';
	echo '<tr bgcolor="#3A4273">
			<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_option1'].'</td>
			<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_value'].'</td>
			<td align="center" width="60%" style="color: #FFFFFF">'.$language['config_comment'].'</td>
		</tr>';
	$create_type = array('mysql' => 'MySQL', 'mssql' => 'SQL Server', 'access' => 'Access', 'oracle' => 'Oracle');
	showsetting('ctype', 'create_type', $create_type, 'select');
	echo '<tr bgcolor="#3A4273">
			<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_discuz_option'].'</td>
			<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_value'].'</td>
			<td align="center" width="60%" style="color: #FFFFFF">'.$language['config_comment'].'</td>
		</tr>';
	showsetting('dbhost', 'discuz_dbhost', $discuz_dbhost, 'text');
	showsetting('dbuser', 'discuz_dbuser', $discuz_dbuser, 'text');
	showsetting('dbpw', 'discuz_dbpw', $discuz_dbpw, 'password');
	showsetting('dztype', 'discuz_type', $discuz_type, 'radio');
	showsetting('dbname', 'discuz_dbname', $discuz_dbname, 'text');
	showsetting('tablepre', 'discuz_tablepre', $discuz_tablepre, 'text');
	echo '<tr bgcolor="#3A4273">
			<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_uc_option'].'</td>
			<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_value'].'</td>
			<td align="center" width="60%" style="color: #FFFFFF">'.$language['config_comment'].'</td>
		</tr>';
	showsetting('dbhost', 'uc_dbhost', $uc_dbhost, 'text');
	showsetting('dbuser', 'uc_dbuser', $uc_dbuser, 'text');
	showsetting('dbpw', 'uc_dbpw', $uc_dbpw, 'password');
	showsetting('dbname', 'uc_dbname', $uc_dbname, 'text');
	showsetting('tablepre', 'uc_tablepre', $uc_tablepre, 'text');

	echo '</table><br><center><input class="button" type="submit" name="submitconfig" value="'.$language['config_save'].'" onclick="this.form.target=\'_self\';this.form.action=\'index.php?action=create&step=2\';this.form.submit()"></center></form>';
	dfooter();
}

function createstep($is_uc) {
	extract($GLOBALS, EXTR_SKIP);
	dheader();
	global $language;
	include_once language();
	echo $language['create_step2'];
	echo '<form method="post"><table width="60%" cellspacing="1" bgcolor="#000000" border="0" align="center"><tr bgcolor="#3A4273"><td align="center" colspan="2" width="20%" style="color: #FFFFFF">'.$language['convert_selectoption'].'</td></tr>';
	foreach($step_order AS $key => $value) {
		echo '<tr><td align="center" bgcolor="#E3E3EA" width="20%"><input type="checkbox" name="sstep[]" value="'.$key.'"></td><td bgcolor="#EEEEF6">&nbsp;&nbsp;&nbsp;&nbsp;[<font color="blue">'.$value.'</font>]</td></tr>';
	}
	echo '</table><br><center><input class="button" type="submit" name="submitconfig" value="'.$language['config_save'].'" onclick="this.form.target=\'_self\';this.form.action=\'index.php?action=create&step=3&uc='.$is_uc.'\';this.form.submit()"></center></form>';
	dfooter();
}

function configform() {	//配置表单
	extract($GLOBALS, EXTR_SKIP);
	dheader();
	$validdata = implode('，', $operations);
	is_array($invaliddata) && $invaliddata = implode('</li><li>', $invaliddata);
	$logging = getlogging();
	global $language;
	include_once language();
	$environment = $language[$source_dbtype.'_environment'];
	echo $language['statements1'].$source_ver.$language['statements2'].$source_ver.$language['statements3'].$discuz_ver.$language['statements4'].$discuz_ver.$language['statements5'];
	echo $language['environment_header'].$environment.$language['environment_footer'];
	echo $language['validdata_header'].$validdata.$language['validdata_footer'];
	if ($invaliddata) {
		echo $language['invaliddata_header'].$invaliddata.$language['invaliddata_footer'];
	}
	echo $language['beforeconvert1'].$discuz_ver.$language['beforeconvert2'].$beforeconvert.$language['beforeconvert3'];
	echo $language['converting'];
	echo $language['afterconvert1'].$logging.$afterconvert.$language['afterconvert2'].$discuz_ver.$language['afterconvert3'];
	echo $language['technicalsupport'];

	echo '<center><b>'.$language['config_please'].'</b></center>';
	echo '<form method="post"><table width="95%" border="0" bgcolor="#000000" cellspacing="1" cellpadding="0" align="center"><br>';
	echo '<tr bgcolor="#3A4273">
			<td align="center" width="20%" style="color: #FFFFFF">'.$source_ver.$language['config_option'].'</td>
			<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_value'].'</td>
			<td align="center" width="60%" style="color: #FFFFFF">'.$language['config_comment'].'</td>
		</tr>';
	$source_charset = $source_charset ? $source_charset : 'gbk';
	$discuz_charset = $discuz_charset ? $discuz_charset : 'gbk';
	$discuz_charset = array('gbk' => 'gbk', 'utf8' => 'utf8', 'big5' => 'big5', 'checked' => $discuz_charset);
	if ($source_dbtype == 'mysql') {
		$source_charset = array('gbk' => 'gbk', 'utf8' => 'utf8', 'big5' => 'big5', 'checked' => $source_charset);
		showsetting('dbhost', 'source_dbhost', $source_dbhost, 'text');
		showsetting('dbuser', 'source_dbuser', $source_dbuser, 'text');
		showsetting('dbpw', 'source_dbpw', $source_dbpw, 'password');
		showsetting('dbname', 'source_dbname', $source_dbname, 'text');
		showsetting('tablepre', 'source_tablepre', $source_tablepre, 'text');
		showsetting('mysql_charset', 'source_charset', $source_charset, 'select');
	} elseif ($source_dbtype == 'mssql') {
		showsetting('mssql_dbhost', 'source_dbhost', $source_dbhost, 'text');
		showsetting('dbuser', 'source_dbuser', $source_dbuser, 'text');
		showsetting('dbpw', 'source_dbpw', $source_dbpw, 'password');
		showsetting('dbname', 'source_dbname', $source_dbname, 'text');
		showsetting('tablepre', 'source_tablepre', $source_tablepre, 'text');
		showsetting('source_charset', 'source_charset', $source_charset, 'text');
		showsetting('mssql_dbowner', 'source_dbowner', $source_dbowner, 'text');
	} elseif ($source_dbtype == 'access') {
		showsetting('ac_dbhost', 'source_dbhost', $source_dbhost, 'text');
		showsetting('ac_dbuser', 'source_dbuser', $source_dbuser, 'text');
		showsetting('ac_dbpw', 'source_dbpw', $source_dbpw, 'password');
		showsetting('tablepre', 'source_tablepre', $source_tablepre, 'text');
		showsetting('source_charset', 'source_charset', $source_charset, 'text');
	} elseif ($source_dbtype == 'oracle') {
		showsetting('oci_dbuser', 'source_dbuser', $source_dbuser, 'text');
		showsetting('oci_dbpw', 'source_dbpw', $source_dbpw, 'password');
		showsetting('oci_dbname', 'source_dbname', $source_dbname, 'text');
		showsetting('tablepre', 'source_tablepre', $source_tablepre, 'text');
		showsetting('source_charset', 'source_charset', $source_charset, 'text');
	}
	showsetting('timeoffset', 'source_timeoffset', $source_timeoffset, 'text');
	if (is_array($extsettings) && count($extsettings) > 0) {
		foreach ($extsettings as $val){
			$$val[0] = isset($$val[0]) ? $$val[0] : $val[3];
			showsetting($val[1], $val[0], $$val[0], 'text', '60%', $val[2]);
		}
	}
	if ($is_uc) {
		echo '<tr bgcolor="#3A4273">
				<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_uc_option'].'</td>
				<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_value'].'</td>
				<td align="center" width="60%" style="color: #FFFFFF">'.$language['config_comment'].'</td>
			</tr>';
		showsetting('dbhost', 'uc_dbhost', $uc_dbhost, 'text');
		showsetting('dbuser', 'uc_dbuser', $uc_dbuser, 'text');
		showsetting('dbpw', 'uc_dbpw', $uc_dbpw, 'password');
		showsetting('dbname', 'uc_dbname', $uc_dbname, 'text');
		showsetting('tablepre', 'uc_tablepre', $uc_tablepre, 'text');
	}
	echo '<tr bgcolor="#3A4273">
			<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_discuz_option'].'</td>
			<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_value'].'</td>
			<td align="center" width="60%" style="color: #FFFFFF">'.$language['config_comment'].'</td>
		</tr>';
	showsetting('dbhost', 'discuz_dbhost', $discuz_dbhost, 'text');
	showsetting('dbuser', 'discuz_dbuser', $discuz_dbuser, 'text');
	showsetting('dbpw', 'discuz_dbpw', $discuz_dbpw, 'password');
	showsetting('dbname', 'discuz_dbname', $discuz_dbname, 'text');
	showsetting('tablepre', 'discuz_tablepre', $discuz_tablepre, 'text');
	if($is_uch){
		echo '<tr bgcolor="#3A4273">
				<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_uch_option'].'</td>
				<td align="center" width="20%" style="color: #FFFFFF">'.$language['config_value'].'</td>
				<td align="center" width="60%" style="color: #FFFFFF">'.$language['config_comment'].'</td>
			</tr>';
		showsetting('dbhost', 'uch_dbhost', $uch_dbhost, 'text');
		showsetting('dbuser', 'uch_dbuser', $uch_dbuser, 'text');
		showsetting('dbpw', 'uch_dbpw', $uch_dbpw, 'password');
		showsetting('dbname', 'uch_dbname', $uch_dbname, 'text');
		showsetting('tablepre', 'uch_tablepre', $uch_tablepre, 'text');
	}
	showsetting('rpp', 'rpp', $rpp, 'text');
	showsetting('pertask', 'pertask', $pertask, 'text');
	showsetting('debug', 'debug', $debug, 'text');
	showsetting('', 'child', $childselect, 'hidden');

	echo '</table><br><center><input class="button" type="submit" name="submitconfig" value="'.$language['config_save'].'" onclick="this.form.target=\'_self\';this.form.action=\'index.php?action=config&uc='.$is_uc.'&uch='.$is_uch.'&submitconfig=yes\';this.form.submit()"></center></form>';
	dfooter();
}

function xconvert_encrypt($txt, $key) {
	srand((double)microtime() * 1000000);
	$encrypt_key = md5(rand(0, 32000));
	$ctr = 0;
	$tmp = '';
	for($i = 0;$i < strlen($txt); $i++) {
		$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
		$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
	}
	return base64_encode(xconvert_key($tmp, $key));
}

function xconvert_decrypt($txt, $key) {
	$txt = xconvert_key(base64_decode($txt), $key);
	$tmp = '';
	for($i = 0;$i < strlen($txt); $i++) {
		$md5 = $txt[$i];
		$tmp .= $txt[++$i] ^ $md5;
	}
	return $tmp;
}

function xconvert_key($txt, $encrypt_key) {
	$encrypt_key = md5($encrypt_key);
	$ctr = 0;
	$tmp = '';
	for($i = 0; $i < strlen($txt); $i++) {
		$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
		$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
	}
	return $tmp;
}

function showmessage($message, $url_forward = '', $values = array(), $extraparam = array(), $custom = 0) {
	global $inajax, $handlekey, $returnmessage;
	$param = array(
		'header'	=> false,
		'timeout'	=> null,
		'refreshtime'	=> null,
		'closetime'	=> null,
		'locationtime'	=> 3,
		'alert'		=> null,
		'return'	=> false,
		'redirectmsg'	=> 0,
		'msgtype'	=> 1,
		'showmsg'	=> true,
		'showdialog'	=> false,
		'login'		=> false,
		'handle'	=> false,
		'extrajs'	=> '',
	);

	if($custom) {
		echo $message;
	} else {
		define('CACHE_FORBIDDEN', TRUE);
		$leftmsg = '';

		if($url_forward) {
			$param['timeout'] = true;
		}

		foreach($extraparam as $k => $v) {
			$param[$k] = $v;
		}
		if(array_key_exists('set', $extraparam)) {
			$setdata = array('1' => array('msgtype' => 3));
			if($setdata[$extraparam['set']]) {
				foreach($setdata[$extraparam['set']] as $k => $v) {
					$param[$k] = $v;
				}
			}
		}

		$timedefault = intval($param['refreshtime']);
		if($param['timeout'] !== null) {
			$refreshsecond = 3;
			$refreshtime = $refreshsecond * 1000;
		} else {
			$refreshtime = $refreshsecond = 0;
		}

		$show_message = lang($message);
		$show_jsmessage = str_replace("'", "\\'", $show_message);

		if(!$param['showmsg']) {
			$show_message = '';
		}

		if($param['msgtype'] == 3) {
			$show_message = str_replace(lang('message', 'return_search'), lang('message', 'return_replace'), $show_message);
		}

		$allowreturn = !$param['timeout'] && stristr($show_message, lang('message', 'return')) || $param['return'] ? true : false;
		if($param['alert'] === null) {
			$alerttype = $url_forward ? (preg_match('/\_(succeed|success)$/', $message) ? 'alert_right' : 'alert_info') : ($allowreturn ? 'alert_error' : 'alert_info');
		} else {
			$alerttype = 'alert_'.$param['alert'];
		}
		
		$extra = '';
		
		if($inajax) {
			$extra .= 'if(typeof errorhandle_'.$handlekey.'==\'function\') {errorhandle_'.$handlekey.'(\''.$show_jsmessage.'\', \''.$returnmessage.'\');}';
		}		
		if($url_forward) {
			$st = $param['locationtime'] !== null ?'setTimeout("window.location.href =\''.$url_forward.'\';", '.($param['locationtime'] * 1000).');' : '';
		}
		$show_message .= $extra ? '<script type="text/javascript" reload="1">'.$extra.$st.'</script>' : '';
		$show_message .= $param['extrajs'] ? $param['extrajs'] : '';

		include template('showmessage');
		exit();
	}
}
function reportshowmessage($message, $url_forward = '', $msgtype = 'message', $extra = '', $delaymsec = 1000, $cancelurl = '') {

	global $xc, $lable;
	include_once language();

	if(strpos($message, $xc->language['return'])) {
		$message .= "<br><br><br><a href=\"javascript:history.go(-1);\" class=\"mediumtxt\">$xc->language[message_return]</a>";
	}
	$message = "<br>$message$extra<br><br>";

	$head = reportdheader();
	$foot = reportdfooter();
	$content = $head.$message.$foot;

	$content = str_replace("index.php","transfer.php",$content);
	$file = $lable.".html";
	$p = fopen($file,"w");
	fwrite($p, $content);
	fclose($p);

}

/**
 * 语言包调用函数 language
 *
 * @param string $filename ; 语言包的名称(不包括后缀的名称 .lang.php), 放在 ./language/ 目录下
*/

function lang($file, $langvar = null, $vars = array(), $default = null) {
	$key = $file;
	include XCONVERT_ROOT.'./source/language/lang_template.php';
	$returnvalue = &$lang;
	$return = $langvar !== null ? (isset($returnvalue[$key][$langvar]) ? $returnvalue[$key][$langvar] : null) : $returnvalue[$key];
	$return = $return === null ? ($default !== null ? $default : $langvar) : $return;
	if($vars && is_array($vars)) {
		$searchs = $replaces = array();
		foreach($vars as $k => $v) {
			$searchs[] = '{'.$k.'}';
			$replaces[] = $v;
		}
		$return = str_replace($searchs, $replaces, $return);
	}
	return $return;
}

function language($filename = '') {
	global $defaultlanguage;
	if (empty($filename)) {
		$filename = 'zh';
	}
	$languagepack = './language/' . $filename . '.lang.php';
	if(!@file_exists($languagepack)) {
		showmessage($filename.'.lang.php not exists. Please Checked.');
	}
	return $languagepack;
}


/**
 * 表单设置函数 showsetting
 *
 * @param string
*/

function showsetting($setname, $varname, $value = '', $type = 'text', $width = '60%', $comment = '') {

	if($type == 'hidden') {
		echo "<input type=\"hidden\" id=\"$varname\" name=\"$varname\" value=\"$value\">";
		return ;
	}

	global $language;
	include_once language();

	$check = array();
	$comment = isset($language[$setname.'_comment']) ? $language[$setname.'_comment'] : (isset($comment) ? $comment : '');

	$aligntop = $type == "textarea" || $width != "60%" ? "valign=\"top\"" : NULL;
	echo "<tr><td width=\"$width\" class=\"altbg1\" $aligntop>&nbsp;".(isset($language[$setname]) ? $language[$setname] : $setname).'</td>'.'<td class="altbg2">';

	if($type == 'radio') {
		$value ? $check['true'] = "checked" : $check['false'] = "checked";
		$value ? $check['false'] = '' : $check['true'] = '';
		echo "&nbsp;<input class=\"radio\" class=\"radio\" type=\"radio\" name=\"$varname\" value=\"1\" $check[true]> {$language['yes']} &nbsp; &nbsp; \n".
			"<input class=\"radio\" class=\"radio\" type=\"radio\" name=\"$varname\" value=\"0\" $check[false]> {$language['no']}\n";
	} elseif($type == 'text' || $type == 'password') {
		echo "&nbsp;<input type=\"$type\" size=\"30\" name=\"$varname\" value=\"".htmlspecialchars($value)."\">\n";
	}elseif($type == 'select') {
		echo '&nbsp;<select id="'.$varname.'" name="'.$varname.'">';
		foreach($value as $key => $title) {
			if ($key != 'checked'){
				echo "<option value=\"$key\"".($value['checked'] && $key == $value['checked'] ? ' selected' : '').">$title</option>";
			}
		}
	} else {
		echo $type;
	}
	echo '</td><td class="altbg3">&nbsp;'.$comment.'</td></tr>';
}


function dheader() {
	global $defaultlanguage, $action, $step, $steps, $operation, $source_ver, $discuz_ver, $scriptname, $convertversion, $lastmodified, $operation, $language;
	$converttitle = $source_ver && $discuz_ver ? "$source_ver => $discuz_ver".$language['header_convertprogram'] : 'XConvert';
	switch ($action) {
		case '': $nowtitle = $language['header_license']; break;
		case 'config': $nowtitle = $language['header_config']; break;
		case 'check': $nowtitle = $language['header_check']; break;
		case 'convert': $nowtitle = $language['header_stepfrom'].$step.'/'.$steps.$language['header_step']; break;
		case 'finish': $nowtitle = $language['header_finish']; break;
		case 'stats': $nowtitle = $language['header_stats']; break;
		case 'report': $nowtitle = $language['header_report']; break;
		case 'create': $nowtitle = $language['header_create']; break;
	}
	$nowtitle = $action == 'convert' && !$step ? $language['header_selectoption'] : $nowtitle;
	$nowtitle .= $operation ? '('.$operation.')' : '';
	$nowtitle .= ' - '.$converttitle;
	@header('Content-Type: text/html; charset='.$defaultlanguage);
	print <<< EOT

	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=$defaultlanguage">
	<title>$nowtitle</title>
	<style type="text/css">
		A:visited	{COLOR: #3A4273; TEXT-DECORATION: none}
		A:link		{COLOR: #3A4273; TEXT-DECORATION: none}
		A:hover		{COLOR: #3A4273; TEXT-DECORATION: underline}
		body,table,td	{COLOR: #3A4273; FONT-FAMILY: Tahoma, Verdana, Arial; FONT-SIZE: 12px; LINE-HEIGHT: 20px; scrollbar-base-color: #E3E3EA; scrollbar-arrow-color: #5C5C8D}
		input		{COLOR: #085878; FONT-FAMILY: Tahoma, Verdana, Arial; FONT-SIZE: 12px; background-color: #3A4273; color: #FFFFFF; scrollbar-base-color: #E3E3EA; scrollbar-arrow-color: #5C5C8D}
		.install	{FONT-FAMILY: Arial, Verdana; FONT-SIZE: 20px; FONT-WEIGHT: bold; COLOR: #000000}
		.red td		{border: 1px solid red;}
		.altbg1		{BACKGROUND: #E3E3EA; WIDTH: 20%}
		.altbg2		{BACKGROUND: #EEEEF6; WIDTH: 20%}
		.altbg3		{BACKGROUND: #E3E3EA; WIDTH: 60%}
.p_bar {
	margin: 1px 0px;
	clear: both;
}
.p_input {
	border: 0px;
	padding: 0px;
	width: 40px;
	height: 17px !important;
	height: 15px;
	margin: 0px;
	background: #EEEEF6;
	color: #000000;
}
.p_total {
	background-color: #E3E3EA;
	border: 1px solid #000000;
	border-right: 0px solid #000000;
	font-weight: bold;
}
.p_pages {
	background-color: #E3E3EA;
	border: 1px solid #000000;
	margin-right:1px;
	vertical-align: middle;
	font-weight: bold;
}
.p_num {
	background-color: #FFFFFF;
	border: 1px solid #DEDEB8;
	margin-right:2px;
	vertical-align: middle;
}

.p_redirect {
	background-color: #EEEEF6;
	border: 1px solid #DEDEB8;
	margin-right:1px;
	font-size: 12px;
}
.p_curpage {
	margin-right:1px;
	border: 1px solid #DEDEB8;
	vertical-align: middle;
	background-color: #EEEEF6;
	color: #92A05A;
	font-weight: bold;
}
	</style>

	<script language="JavaScript">
		function redirect(url) {
			window.location.replace(url);
		}
	</script>

	</head>
	<body bgcolor="#3A4273" text="#000000">
	<table width="95%" border="0" cellspacing="0" cellpadding="0" bgcolor="#FFFFFF" align="center">
	  <tr>
	    <td>
	      <table width="98%" border="0" cellspacing="0" cellpadding="0" align="center">
		<tr>
		  <td class="install" height="30" valign="bottom"><font color="#FF0000">&gt;&gt;</font>
		    <b><span style='font-size:14px'>$converttitle</span></b></td>
		</tr>
		<tr>
		  <td>
		    <hr noshade align="center" width="100%" size="1">
		  </td>
		</tr>
		<tr>
		  <td align="center">
		    <b><span style='color:#FF58C0'>$language[header_welcome]</span></b>
		  </td>
		</tr>
		<tr>
		  <td>
		    <hr noshade align="center" width="100%" size="1">
		  </td>
		</tr>
		<tr>
		  <td>
EOT;
}

function reportdheader() {
	global $defaultlanguage, $action, $step, $steps, $operation, $source_ver, $discuz_ver, $scriptname, $convertversion, $lastmodified, $operation, $language;
	$converttitle = $source_ver && $discuz_ver ? "$source_ver => $discuz_ver".$language['header_convertprogram'] : 'XConvert';
	switch ($action) {
		case '': $nowtitle = $language['header_license']; break;
		case 'config': $nowtitle = $language['header_config']; break;
		case 'check': $nowtitle = $language['header_check']; break;
		case 'convert': $nowtitle = $language['header_stepfrom'].$step.'/'.$steps.$language['header_step']; break;
		case 'finish': $nowtitle = $language['header_finish']; break;
		case 'stats': $nowtitle = $language['header_stats']; break;
		case 'report': $nowtitle = $language['header_report']; break;
		case 'create': $nowtitle = $language['header_create']; break;
	}
	$nowtitle = $action == 'convert' && !$step ? $language['header_selectoption'] : $nowtitle;
	$nowtitle .= $operation ? '('.$operation.')' : '';
	$nowtitle .= ' - '.$converttitle;
	@header('Content-Type: text/html; charset='.$defaultlanguage);
	$head = <<< EOT

	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=$defaultlanguage">
	<title>$nowtitle</title>
	<style type="text/css">
		A:visited	{COLOR: #3A4273; TEXT-DECORATION: none}
		A:link		{COLOR: #3A4273; TEXT-DECORATION: none}
		A:hover		{COLOR: #3A4273; TEXT-DECORATION: underline}
		body,table,td	{COLOR: #3A4273; FONT-FAMILY: Tahoma, Verdana, Arial; FONT-SIZE: 12px; LINE-HEIGHT: 20px; scrollbar-base-color: #E3E3EA; scrollbar-arrow-color: #5C5C8D}
		input		{COLOR: #085878; FONT-FAMILY: Tahoma, Verdana, Arial; FONT-SIZE: 12px; background-color: #3A4273; color: #FFFFFF; scrollbar-base-color: #E3E3EA; scrollbar-arrow-color: #5C5C8D}
		.install	{FONT-FAMILY: Arial, Verdana; FONT-SIZE: 20px; FONT-WEIGHT: bold; COLOR: #000000}
		.red td		{border: 1px solid red;}
		.altbg1		{BACKGROUND: #E3E3EA; WIDTH: 20%}
		.altbg2		{BACKGROUND: #EEEEF6; WIDTH: 20%}
		.altbg3		{BACKGROUND: #E3E3EA; WIDTH: 60%}
.p_bar {
	margin: 1px 0px;
	clear: both;
}
.p_input {
	border: 0px;
	padding: 0px;
	width: 40px;
	height: 17px !important;
	height: 15px;
	margin: 0px;
	background: #EEEEF6;
	color: #000000;
}
.p_total {
	background-color: #E3E3EA;
	border: 1px solid #000000;
	border-right: 0px solid #000000;
	font-weight: bold;
}
.p_pages {
	background-color: #E3E3EA;
	border: 1px solid #000000;
	margin-right:1px;
	vertical-align: middle;
	font-weight: bold;
}
.p_num {
	background-color: #FFFFFF;
	border: 1px solid #DEDEB8;
	margin-right:2px;
	vertical-align: middle;
}

.p_redirect {
	background-color: #EEEEF6;
	border: 1px solid #DEDEB8;
	margin-right:1px;
	font-size: 12px;
}
.p_curpage {
	margin-right:1px;
	border: 1px solid #DEDEB8;
	vertical-align: middle;
	background-color: #EEEEF6;
	color: #92A05A;
	font-weight: bold;
}
	</style>

	<script language="JavaScript">
		function redirect(url) {
			window.location.replace(url);
		}
	</script>

	</head>
	<body bgcolor="#3A4273" text="#000000">
	<table width="95%" border="0" cellspacing="0" cellpadding="0" bgcolor="#FFFFFF" align="center">
	  <tr>
	    <td>
	      <table width="98%" border="0" cellspacing="0" cellpadding="0" align="center">
		<tr>
		  <td class="install" height="30" valign="bottom"><font color="#FF0000">&gt;&gt;</font>
		    <b><span style='font-size:14px'>$converttitle</span></b></td>
		</tr>
		<tr>
		  <td>
		    <hr noshade align="center" width="100%" size="1">
		  </td>
		</tr>
		<tr>
		  <td align="center">
		    <b><span style='color:#FF58C0'>$language[header_welcome]</span></b>
		  </td>
		</tr>
		<tr>
		  <td>
		    <hr noshade align="center" width="100%" size="1">
		  </td>
		</tr>
		<tr>
		  <td>
EOT;
	return $head;
}

function dfooter() {
	$version = XCONVERT_VERSION;

	print <<< EOT
	</td></tr>
	<tr> <td> <hr noshade align="center" width="100%" size="1"></td></tr>
	<tr><td align="center"><b style="font-size: 11px">Powered by <a href="http://www.discuz.net" target="_blank">XConvert $version</a> , &nbsp; Copyright &copy; <a href="http://www.comsenz.com" target="_blank">Comsenz Inc.</a>, 2001-2010</b> </td></tr>
	</table>
	</td> </tr></table><br>
	</body>
	</html>
EOT;
	exit();
}

function reportdfooter() {
	$version = XCONVERT_VERSION;

	$foot = <<< EOT
	</td></tr>
	<tr> <td> <hr noshade align="center" width="100%" size="1"></td></tr>
	<tr><td align="center"><b style="font-size: 11px">Powered by <a href="http://www.discuz.net" target="_blank">XConvert $version</a> , &nbsp; Copyright &copy; <a href="http://www.comsenz.com" target="_blank">Comsenz Inc.</a>, 2001-2009</b> </td></tr>
	</table>
	</td> </tr></table><br>
	</body>
	</html>
EOT;
	return $foot;
}

function getfiletype($filename = '') {
	$extnum	=	strrpos($filename, '.') + 1;
	$exts	=	strtolower(substr($filename, $extnum));
	switch ($exts) {
		case 'jpg':
			return 'image/pjpeg';
		break;
		case 'jpe':
			return 'image/pjpeg';
		break;
		case 'jpeg':
			return 'image/pjpeg';
		break;
		case 'pdf':
			return 'application/pdf';
		break;
		case 'gif':
			return 'image/gif';
		break;
		case 'bmp':
			return 'image/bmp';
		break;
		case 'png':
			return 'image/png';
		break;
		case 'rar':
			return 'x-rar-compressed';
		break;
		case 'txt':
			return 'text/plain';
		break;
		case 'swf':
			return 'application/x-shockwave-flash';
		break;
		case 'zip':
			return 'application/zip';
		break;
		case 'doc':
			return 'application/msword';
		break;
		default:
			return 'application/octet-stream';
		break;
	}
}

function creatreporttable() {
	global $xc, $discuz_tablepre;
	$xc->db['discuz']->query("DROP TABLE IF EXISTS {$discuz_tablepre}xreports;");
	$xc->db['discuz']->query("CREATE TABLE {$discuz_tablepre}xreports (
		rid int(10) unsigned NOT NULL AUTO_INCREMENT,
		step tinyint(2) unsigned NOT NULL DEFAULT '0',
		errnum mediumint(8) unsigned NOT NULL DEFAULT '0',
		message mediumtext NOT NULL DEFAULT '',
		PRIMARY KEY (rid),
		KEY step (step)
		)ENGINE=MyISAM AUTO_INCREMENT=100;");
}

function multi($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 10, $simple = 0, $onclick = '') {
	$multipage = '';
	$mpurl .= strpos($mpurl, '?') ? '&amp;' : '?';
	$onclick = $onclick ? ' onclick="'.$onclick.'(event)"' : '';
	if($num > $perpage) {
		$offset = 2;

		$realpages = @ceil($num / $perpage);
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;
		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $from + $page - 1;
			if($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if($to - $from < $page) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $pages - $page + 1;
				$to = $pages;
			}
		}

		$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'page=1" class="p_redirect"'.$onclick.'>|&lsaquo;</a>' : '').
			($curpage > 1 && !$simple ? '<a href="'.$mpurl.'page='.($curpage - 1).'" class="p_redirect">&lsaquo;&lsaquo;</a>' : '');
		for($i = $from; $i <= $to; $i++) {
			$multipage .= $i == $curpage ? '<a class="p_curpage">'.$i.'</a>' :
				'<a href="'.$mpurl.'page='.$i.'" class="p_num"'.$onclick.'>'.$i.'</a>';
		}

		$multipage .= ($curpage < $pages && !$simple ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="p_redirect"'.$onclick.'>&rsaquo;&rsaquo;</a>' : '').
			($to < $pages ? '<a href="'.$mpurl.'page='.$pages.'" class="p_redirect"'.$onclick.'>&rsaquo;|</a>' : '').
			($curpage == $maxpages ? '<a class="p_redirect" href="misc.php?action=maxpages&amp;pages='.$maxpages.'">&rsaquo;?</a>' : '').
			(!$simple && $pages > $page ? '<a class="p_pages" style="padding: 0px"><input class="p_input" type="text" name="custompage" onKeyDown="if(event.keyCode==13) {window.location=\''.$mpurl.'page=\'+this.value; return false;}"></a>' : '');

		$multipage = $multipage ? '<div class="p_bar">'.(!$simple ? '<a class="p_total">&nbsp;'.$num.'&nbsp;</a><a class="p_pages">&nbsp;'.$curpage.'/'.$realpages.'&nbsp;</a>' : '').$multipage.'</div>' : '';
	}
	return $multipage;
}

function writeconfig($type = 'p') {
	$fp = fopen('./config.inc.php', 'r');
	$configfile = fread($fp, filesize('./config.inc.php'));
	fclose($fp);

	$parameterdata = $type == 'p' ? $_POST : ($type == 'g' ? $_GET : array());
	foreach($parameterdata as $key => $value){
		if (preg_match("/[$]_config\[\'db\'\]\[\'".$key."\'\]\s*\=\s*[\"'].*?[\"'];/is", $configfile)) {
			$configfile = preg_replace("/[$]_config\[\'db\'\]\[\'".$key."\'\]\s*\=\s*[\"'].*?[\"'];/is", '$_config[\'db\'][\''.$key."'] = '".$value."';", $configfile);
		} elseif (substr($key, 0, 5) == "info_") {
			$realkey = "";
			$realkey = substr($key, 5);
			if (preg_match("/[$]_config\[\'info\'\]\[\'".$realkey."\'\]\s*\=\s*[\"'].*?[\"'];/is", $configfile)) {
				$configfile = preg_replace("/[$]_config\[\'info\'\]\[\'".$realkey."\'\]\s*\=\s*[\"'].*?[\"'];/is", '$_config[\'info\'][\''.$realkey."'] = '".$value."';", $configfile);
			}
		} elseif (!in_array($key, array('submitconfig', 'submit')) && !in_array($key, array('mod', 'operation'))) {
			$configfileadd .= '$'.$key." = '".$value."';\r\n";
		}
	}
	
	$configfile = str_replace('?>', '', $configfile).$configfileadd.'?>';
	$fp = fopen('./config.inc.php', 'w');
	fwrite($fp, trim($configfile));
	fclose($fp);
}

function writeconfig2($key, $value) {
	$fp = fopen('./config.inc.php', 'r');
	$configfile = fread($fp, filesize('./config.inc.php'));
	fclose($fp);
	if (preg_match("/[$]_config\[\'info\'\]\[\'".$key."\'\]\s*\=\s*[\"'].*?[\"'];/is", $configfile)) {
		$configfile = preg_replace("/[$]_config\[\'info\'\]\[\'".$key."\'\]\s*\=\s*[\"'].*?[\"'];/is", '$_config[\'info\'][\''.$key."'] = '".$value."';", $configfile);
	} elseif (preg_match("/[$]_config\[\'db\'\]\[\'".$key."\'\]\s*\=\s*[\"'].*?[\"'];/is", $configfile)) {
		$configfile = preg_replace("/[$]_config\[\'db\'\]\[\'".$key."\'\]\s*\=\s*[\"'].*?[\"'];/is", '$_config[\'db\'][\''.$key."'] = '".$value."';", $configfile);
	} elseif ($key != 'submitconfig') {
		$configfileadd .= '$'.$key." = '".$value."';\r\n";
	}
	$configfile = str_replace('?>', '', $configfile).$configfileadd.'?>';
	$fp = fopen('./config.inc.php', 'w');
	fwrite($fp, trim($configfile));
	fclose($fp);
}

function checkcharset() {
	global $source_dbtype;
	foreach ($_POST as $key => $val) {
		$var = 'c'.$key;
		$$var = $val;
	}
	require_once XCONVERT_ROOT.'./data/'.$cchild.'/config.php';
	if (!$checkchar) {
		showmessage('checkchar_noexist');
	}
	$csource_charset == 'utf8' && $csource_charset = 'utf-8';
	$carray = explode(',', str_replace(' ', '', $checkchar));
	$ctable = $carray[0];
	$cname = $carray[1];
	$dbclass = 'db_'.$source_dbtype;
	$csource_tablepre = ($csource_dbowner ? $csource_dbowner.'.' : '').$csource_tablepre;
	$xc->db['source'] = new $dbclass;
	if (substr(strtolower(trim($source_dbtype)), 0, 1) == 'a' && substr($_POST['source_dbhost'], 0, 1) == '.') {
		$csource_dbhost = str_replace('\\', '/', XCONVERT_ROOT.substr($csource_dbhost, 2));
	}
	$xc->db['source']->connect($csource_dbhost, $csource_dbuser, $csource_dbpw, $csource_dbname);
	$csource_dbhost = $csource_dbuser = $csource_dbpw = $csource_dbname = NULL;
	$cheader = $source_dbtype == 'mysql' ? '' : ' TOP 20';
	$cfooter = $source_dbtype == 'mysql' ? ' LIMIT 20' : '';
	$csql = 'SELECT'.$cheader.' '.$cname.' FROM '.$csource_tablepre.$ctable.$cfooter;
	if (substr(strtolower(trim($source_dbtype)), 0, 1) == 'a') {
		$rs = $xc->db['source']->execute($csql);
		while (!$rs->EOF) {
			$name .= $rs->fields[$cname]->value.'<br>';
			$rs->movenext();
		}
		$rs->close();
	} else {
		$fetchfunction = $source_dbtype.'_fetch_assoc';
		$cquery = $xc->db['source']->query($csql);
		while ($c = $fetchfunction($cquery)) {
			$name .= $c[$cname].'<br>';
		}
	}

	$csourcemessage = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset='.$csource_charset.'">
	<title>'.$csource_charset.'</title>
	<style type="text/css">
		A:visited	{COLOR: #3A4273; TEXT-DECORATION: none}
		A:link		{COLOR: #3A4273; TEXT-DECORATION: none}
		body,table,td	{COLOR: #3A4273; FONT-FAMILY: Tahoma, Verdana, Arial; FONT-SIZE: 12px; LINE-HEIGHT: 20px; scrollbar-base-color: #E3E3EA; scrollbar-arrow-color: #5C5C8D}
	</style>
	</head>
	<body bgcolor="#3A4273" text="#000000">
	<table width="95%" border="0" cellspacing="0" cellpadding="0" bgcolor="#FFFFFF" align="center">
	  <tr>
	    <td>
	      <table width="98%" border="0" cellspacing="0" cellpadding="0" align="center">
		<tr>
		  <td class="install" height="30" valign="bottom"><font color="#FF0000">&gt;&gt;</font>
		    <b><span style="font-size:14px">'.$csource_charset.'</span></b>
		  </td>
		</tr>
		<tr>
		  <td>
		    <hr noshade align="center" width="100%" size="1">
		  </td>
		</tr>
		<tr>
		  <td>
		     <b><span style="color:red">&#25552;&#31034;&#65306;&#22914;&#26524;&#19979;&#38754;&#26174;&#31034;&#30340;&#26159;&#20081;&#30721;&#35828;&#26126;&#23383;&#31526;&#38598;&#35774;&#32622;&#38169;&#35823;</span></b>
		  </td>
		</tr>
		<tr>
		  <td>
		    <hr noshade align="center" width="100%" size="1">
		  </td>
		</tr>
		<tr>
		  <td>
		  '.$name.'
		  </td>
		<tr>
		<tr>
		  <td><p align="center"><input type="button" name="close" value="&#20851;&#38381;&#26412;&#31383;&#21475;"  onClick="window.close()"></p>';
	echo $csourcemessage;
	dfooter();
}

function showsteps($operations){
	global $language;
	dheader();
	echo '<form method="post" action="index.php"><table width="60%" cellspacing="1" bgcolor="#000000" border="0" align="center"><tr bgcolor="#3A4273"><td align="center" colspan="2" width="20%" style="color: #FFFFFF">'.$language['convert_selectoption'].'</td></tr><tr><td align="center" bgcolor="#E3E3EA" width="20%"><input type="radio" name="sstep" value="0" checked></td><td bgcolor="#EEEEF6">&nbsp;&nbsp;'.$language['convert_selectall'].'</td></tr>';
	foreach($operations AS $key => $value) {
		echo '<tr><td align="center" bgcolor="#E3E3EA" width="20%"><input type="radio" name="sstep" value="'.$key.'"></td><td bgcolor="#EEEEF6">&nbsp;&nbsp;'.$language['convert_alone'].'[<font color="blue">'.$value.'</font>]</td></tr>';
	}
	echo '</td></tr></table><input type="hidden" name="action" value="convert"><center><input type="submit" name="submit" value="'.$language['convert_start'].'" style="height: 25"><input type="button" name="gohome" value="'.$language['convert_returnindex'].'" onclick="javascript: location.replace(\'index.php\')" style="height: 25"></center></form>';
	dfooter();
}

function dexit($msg = '', $sql = 'mysql') {
	global $language;
	$str = '</td></tr><tr><td>'.$msg.'</td></tr><tr><td><br><br><font color="blue">'.$language['dexit_msg'].'</font>';
	showmessage($str, '', array(), array(), 1);
}

function getlogging() {
	global $xc, $discuz_ver, $loggingfilename, $language;
	$childpath = $xc->config['info']['childtype'].'/'.$xc->config['info']['child'];
	require_once XCONVERT_ROOT.'./data/'.$childpath.'/config.php';
	$loggingfilename = $loggingfilename ? $loggingfilename : 'logging.php';
	$file = './data/'.$childpath.'/'.$loggingfilename;
	if (file_exists($file)) {
		return '<li><font color="red">'.$xc->language['logging_please'].$loggingfilename.$xc->language['logging_cover'].$discuz_ver .$xc->language['logging_inpro'].$loggingfilename.$xc->language['logging_then'].'；</font><a href="?mod=getlogging&file='.$file.'">'.$xc->language['logging_click'].'</a></li>';
	} else {
		return '';
	}
}

/**
 * 取得插入语句sql的函数 getinsertsql
 *
 * @param string $table table name
 * @param array $fields INSERT field array
 * @param string $mode 1: INSERT INTO  else  REPLACE INTO
*/
function getinsertsql($table, $fields, $mode = 1) {
	$mode = $mode == 1 ? 'INSERT INTO ' : 'REPLACE INTO ';
	$fields = is_array($fields) ? $fields : array($fields);
	$fieldvaulesql = $comma = '';
	$fieldsql = implode(', ', $fields);
	foreach($fields as $field) {
		$fieldvaulesql .= "$comma '$GLOBALS[$field]'";
		$comma = ',';
	}
	return $mode.$table.' ('.$fieldsql.') VALUES ('.$fieldvaulesql.');';
}

/**
 * 转换为 UC 的密码格式
 *
 * @param string $password MD5 后的密码
 * @return array 包括 UC 格式密码和 SALT
*/
function convertucpw($password) {
	$salt = substr(uniqid(rand()), -6);
	$pass = md5(strtolower($password).$salt);
	return array('password'=>$pass, 'salt'=>$salt);
}

//输出函数
function pr($array, $exit=1, $type='print_r') {
	if(is_array($array)) {
		echo '<pre>';
		$type == 'print_r' ? print_r($array) : var_dump($array);
		echo '</pre>';
	} else {
		echo '<br>';
		echo htmlspecialchars($array);
		echo '<br>';
	}
	if($exit) exit();
}

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last) {
        case 'g': $val *= 1024;
        case 'm': $val *= 1024;
        case 'k': $val *= 1024;
    }
    return $val;
}

function writesql($table, $filenum, $content) {
	checksqldir($table);
	$sqldir = XCONVERT_ROOT.'./cache/sql/'.$table.'/'.$filenum.'.sql';
	file_put_contents($sqldir, $content, FILE_APPEND);

	$sqldir = XCONVERT_ROOT.'./cache/sql/'.$table.'/';
	if(!is_dir($sqldir)){
		mkdir($sqldir, 0777);
	}
}

function checksqldir($table) {
	$sqldir = XCONVERT_ROOT.'./cache/sql/'.$table.'/';
	if(!is_dir($sqldir)){
		mkdir($sqldir, 0777);
	}
}

function output_ajax() {
	$s = ob_get_contents();
	ob_end_clean();
	$s = preg_replace("/([\\x01-\\x08\\x0b-\\x0c\\x0e-\\x1f])+/", ' ', $s);
	$s = str_replace(array(chr(0), ']]>'), array(' ', ']]&gt;'), $s);

	return $s;
}

function sendmail($toemail, $subject, $message, $from = '') {
	global $xc;
file_put_contents("mailtest.txt", "toemail=".$toemail.", subject=".$subject."\r\n", FILE_APPEND);
$message = <<<EOT
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>$subject</title>
</head>
<body>
$subject<br />
$message
</body>
</html>
EOT;

	$maildelimiter = $xc->config['info']['mail']['maildelimiter'] == 1 ? "\r\n" : ($xc->config['info']['mail']['maildelimiter'] == 2 ? "\r" : "\n");
	$mailusername = isset($xc->config['info']['mail']['mailusername']) ? $xc->config['info']['mail']['mailusername'] : 1;

	if($xc->config['info']['mail']['mailsend'] == 3) {
		$email_from = empty($from) ? $xc->config['info']['adminemail'] : $from;
	} else {
		$email_from = $from == '' ? '=?'.$xc->config['info']['defaultlanguage'].'?B?'."?= <".$xc->config['info']['adminemail'].">" : (preg_match('/^(.+?) \<(.+?)\>$/',$from, $mats) ? '=?'.$xc->config['info']['defaultlanguage'].'?B?'.base64_encode($mats[1])."?= <$mats[2]>" : $from);
	}

	$email_to = preg_match('/^(.+?) \<(.+?)\>$/',$toemail, $mats) ? ($mailusername ? '=?'.$xc->config['info']['defaultlanguage'].'?B?'.base64_encode($mats[1])."?= <$mats[2]>" : $mats[2]) : $toemail;

	$email_subject = '=?'.$xc->config['info']['defaultlanguage'].'?B?'.base64_encode(preg_replace("/[\r|\n]/", '', $subject)).'?=';
	$email_message = chunk_split(base64_encode(str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $message))))));
	$host = $_SERVER['HTTP_HOST'];
	$headers = "From: $email_from{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: $host {$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: text/html; charset=".$xc->config['info']['defaultlanguage']."{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}";
	if($xc->config['info']['mail']['mailsend'] == 1) {
		if(function_exists('mail') && @mail($email_to, $email_subject, $email_message, $headers)) {
			return true;
		}
		return false;

	} elseif($xc->config['info']['mail']['mailsend'] == 2) {

		if(!$fp = fsockopen($xc->config['info']['mail']['server'], $xc->config['info']['mail']['port'], $errno, $errstr, 30)) {
			runlog('SMTP', "({$xc->config[info][mail][server]}:{$xc->config[info][mail][port]}) CONNECT - Unable to connect to the SMTP server", 0);
			return false;
		}
		stream_set_blocking($fp, true);

		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != '220') {
			runlog('SMTP', "$xc->config[info][mail][server]:$xc->config[info][mail][port] CONNECT - $lastmessage", 0);
			return false;
		}

		fputs($fp, ($xc->config['info']['mail']['auth'] ? 'EHLO' : 'HELO')." uchome\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {
			runlog('SMTP', "({$xc->config[info][mail][server]}:{$xc->config[info][mail][port]}) HELO/EHLO - $lastmessage", 0);
			return false;
		}

		while(1) {
			if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {
				break;
			}
			$lastmessage = fgets($fp, 512);
		}

		if($xc->config['info']['mail']['auth']) {
			fputs($fp, "AUTH LOGIN\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 334) {
				runlog('SMTP', "({$xc->config[info][mail][server]}:{$xc->config[info][mail][port]}) AUTH LOGIN - $lastmessage", 0);
				return false;
			}

			fputs($fp, base64_encode($xc->config['info']['mail']['auth_username'])."\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 334) {
				runlog('SMTP', "({$xc->config[info][mail][server]}:{$xc->config[info][mail][port]}) USERNAME - $lastmessage", 0);
				return false;
			}

			fputs($fp, base64_encode($xc->config['info']['mail']['auth_password'])."\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 235) {
				runlog('SMTP', "({$xc->config[info][mail][server]}:{$xc->config[info][mail][port]}) PASSWORD - $lastmessage", 0);
				return false;
			}

			$email_from = $xc->config['info']['mail']['from'];
		}

		fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 250) {
				runlog('SMTP', "({$xc->config[info][mail][server]}:{$xc->config[info][mail][port]}) MAIL FROM - $lastmessage", 0);
				return false;
			}
		}

		fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $toemail).">\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $toemail).">\r\n");
			$lastmessage = fgets($fp, 512);
			runlog('SMTP', "({$xc->config[info][mail][server]}:{$xc->config[info][mail][port]}) RCPT TO - $lastmessage", 0);
			return false;
		}

		fputs($fp, "DATA\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 354) {
			runlog('SMTP', "({$xc->config[info][mail][server]}:{$xc->config[info][mail][port]}) DATA - $lastmessage", 0);
			return false;
		}

		$headers .= 'Message-ID: <'.gmdate('YmdHs').'.'.substr(md5($email_message.microtime()), 0, 6).rand(100000, 999999).'@'.$_SERVER['HTTP_HOST'].">{$maildelimiter}";

		fputs($fp, "Date: ".gmdate('r')."\r\n");
		fputs($fp, "To: ".$email_to."\r\n");
		fputs($fp, "Subject: ".$email_subject."\r\n");
		fputs($fp, $headers."\r\n");
		fputs($fp, "\r\n\r\n");
		fputs($fp, "$email_message\r\n.\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250) {
			runlog('SMTP', "({$xc->config[info][mail][server]}:{$xc->config[info][mail][port]}) END - $lastmessage", 0);
		}
		fputs($fp, "QUIT\r\n");

		return true;

	} elseif($xc->config['info']['mail']['mailsend'] == 3) {

		ini_set('SMTP', $xc->config['info']['mail']['server']);
		ini_set('smtp_port', $xc->config['info']['mail']['port']);
		ini_set('sendmail_from', $email_from);

		if(function_exists('mail') && @mail($email_to, $email_subject, $email_message, $headers)) {
			return true;
		}
		return false;
	}
}

function runlog($file, $message, $halt=0) {
	$timestamp = time();
	$nowurl = $_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:($_SERVER['PHP_SELF']?$_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME']);
	$log = dgmdate($timestamp, 'Y-m-d H:i:s')."\t{$nowurl}\t".str_replace(array("\r", "\n"), array(' ', ' '), trim($message))."\n";
	$yearmonth = dgmdate($timestamp, 'Ym');
	$logdir = XCONVERT_ROOT.'./cache/lock/';
	if(!is_dir($logdir)) mkdir($logdir, 0777);
	$logfile = $logdir.$yearmonth.'_'.$file.'.php';
	if(@filesize($logfile) > 2048000) {
		$dir = opendir($logdir);
		$length = strlen($file);
		$maxid = $id = 0;
		while($entry = readdir($dir)) {
			if(strexists($entry, $yearmonth.'_'.$file)) {
				$id = intval(substr($entry, $length + 8, -4));
				$id > $maxid && $maxid = $id;
			}
		}
		closedir($dir);
		$logfilebak = $logdir.$yearmonth.'_'.$file.'_'.($maxid + 1).'.php';
		@rename($logfile, $logfilebak);
	}
	if($fp = @fopen($logfile, 'a')) {
		@flock($fp, 2);
		fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>', "\r", "\n"), '', $log)."\n");
		fclose($fp);
	}
	if($halt) exit();
}

function dgmdate($timestamp, $format = 'dt', $timeoffset = '9999', $uformat = '') {
	$format == 'u' && $format = 'dt';
	static $dformat, $tformat, $dtformat, $offset;
	if($dformat === null) {
		$dformat = 'Y-m-d';
		$tformat = 'H:i:s';
		$dtformat = $dformat.' '.$tformat;
		$offset = '8';
	}
	$timeoffset = $timeoffset == 9999 ? $offset : $timeoffset;
	$timestamp += $timeoffset * 3600;
	$format = empty($format) || $format == 'dt' ? $dtformat : ($format == 'd' ? $dformat : ($format == 't' ? $tformat : $format));
	
	return gmdate($format, $timestamp);
}
?>