<?php
//自定义函数库
function convertbbcode($message) {//转帖子ubb代码
	global $source_bbsurl, $discuz_url, $source_name, $tid, $first;
	$pregfind = array(
		"/\[post\]/i",
		"/\[\/post\]/i",
		"/\[hide=(\d+),rvrc\]/i",
		"/\[attachment=(\d+)\]/is",
		"/\[p_w_upload=(\d+)\]/is",
		"/&nbsp;/i",
		"/\[rm=\d+,\d+,\d+\]/i",
		"/\[\/rm\]/i",
		"/\[wmv=(\d+)\]/i",
		"/\[wmv=(\d+),(\d+),(\d+)\]/i",
		"/\[\/wmv\]/i",
		"/\[flash=(\d+),(\d+),\d+\]/i",
		"/^\[sell=(\d+)(,money)*\]/i",
		"/\[\/sell\]$/i",
		"/\[sell=(\d+)(,money)*\]/i",
		"/\[\/sell\]/i",
		"/\[backcolor=([#|\w]+)\]/i",
		"/\[\/backcolor\]/i",
	);
	$pregreplace = array(
		"[hide]",
		"[/hide]",
		"[hide=\\1]",
		"[attach]\\1[/attach]",
		"[attach]\\1[/attach]",
		' ',
		"[audio]",
		"[/audio]",
		"[media=wmv,400,300,\\1]",
		"[media=wmv,\\1,\\2,\\3]",
		"[/media]",
		"[flash=\\1,\\2]",
		'',
		'',
		"[/free]",
		"[free]",
		"[table=100%,\\1]",
		"[/table]",
	);

	if ($first && $tid) {
		$sellfind = array("/\[sell=(\d+)\](.+)\[\/sell\]/ies");
		$sellreplace = array("parsesell('\\1', '\\2', $tid)");
		$pregfind = array_merge($pregfind, $sellfind);
		$pregreplace = array_merge($pregreplace, $sellreplace);
	}

	$bbsurl = str_replace(' ', '', $source_bbsurl);//去掉空格
	if($bbsurl){
		$bbsurl = substr($bbsurl, 0, 1) == '|' ? substr($bbsurl, 1) : $bbsurl;//去掉开头的|
		$bbsurl = substr($bbsurl, -1) == '|' ? substr($bbsurl, 0, -1) : $bbsurl;//去掉尾部的|
		$bbsurltemp = str_replace(array('/', '.'), array('\/', '\.'), $bbsurl);//转义
		$sourcename = $source_name ? $source_name.'/' : $source_name;//处理附件目录
		$urlfind = array(
			"/($bbsurltemp)\/index\.php\?cateid=(\d+)/is",
			"/($bbsurltemp)\/index-htm-cateid-(\d+)\.html/is",
			"/($bbsurltemp)\/thread\.php\?fid=(\d+)/is",
			"/($bbsurltemp)\/thread-htm-fid-(\d+)\.html/is",
			"/($bbsurltemp)\/read\.php\?tid=(\d+)&page=(\d+)&fpage=\d/is",
			"/($bbsurltemp)\/read\.php\?tid=(\d+)&fpage=\d+&toread=&page=(\d+)/is",
			"/($bbsurltemp)\/read-htm-tid-(\d+)-page-(\d+)-fpage-\d+\.html/is",
			"/($bbsurltemp)\/read\.php\?tid=(\d+)&page=e&#a/is",
			"/($bbsurltemp)\/read\.php\?tid=(\d+)/is",
			"/($bbsurltemp)\/read-htm-tid-(\d+)\.html/is",
			"/($bbsurltemp)\/p_w_upload\//is",
			"/($bbsurltemp)\/attachment\//is"
		);
		$urlreplace = array(
			$discuz_url."/index.php?gid=\\2",
			$discuz_url."/index.php?gid=\\2",
			$discuz_url."/forumdisplay.php?fid=\\2",
			$discuz_url."/forum-\\2-1.html",
			$discuz_url."/viewthread.php?tid=\\2&extra=page%3D1&page=\\3",
			$discuz_url."/viewthread.php?tid=\\2&extra=page%3D1&page=\\3",
			$discuz_url."/thread-\\2-\\3-1.html",
			$discuz_url."/viewthread.php?tid=\\2",
			$discuz_url."/viewthread.php?tid=\\2",
			$discuz_url."/thread-\\2-1-1.html",
			$discuz_url."/data/attachment/forum/pw/$sourcename",
			$discuz_url."/data/attachment/forum/pw/$sourcename"
		);
		$pregfind = array_merge($pregfind, $urlfind);
		$pregreplace = array_merge($pregreplace, $urlreplace);
	}

	return addslashes(preg_replace($pregfind, $pregreplace, stripslashes($message)));
}

function parsesell($price, $msg, $tid) {
	global $xc, $discuz_tablepre, $config_type;

	$xc->db['discuz']->query("UPDATE {$discuz_tablepre}".($config_type == "x" ? "forum_thread" : "threads")." SET price = '$price' WHERE tid = '$tid'");
	return $msg;
}

function ctspecialgroup($sourcetable, $discuz_tablepre){//转特殊用户组
	global $xc, $discuz_tablepre, $config_type;
	if($config_type == 'x'){
		$xc->db['discuz']->query("DELETE FROM {$discuz_tablepre}common_usergroup WHERE groupid > 9");
		$xc->db['discuz']->query("DELETE FROM {$discuz_tablepre}common_usergroup_field WHERE groupid > 9");
		$xc->db['discuz']->query("DELETE FROM {$discuz_tablepre}common_admingroup WHERE admingid > 9");
		$gquery = $xc->db['source']->query("SELECT gid, grouptitle, gptype, grouppost FROM $sourcetable WHERE gid > 7 AND (gptype = 'special' OR gptype = 'member') ORDER BY gid ASC") or dexit();
		while($g = $xc->db['source']->fetch_array($gquery)) {
			$g		=	daddslashes($g);
			$groupid	=	$g['gid'] + 9;
			$grouptitle	=	$g['grouptitle'];
			$type		=	$g['gptype'];
			$creditshigher	=	$g['grouppost'];
			$credittmp		=	$xc->db['source']->result($xc->db['source']->query("SELECT grouppost FROM $sourcetable WHERE grouppost>$creditshigher ORDER BY grouppost ASC LIMIT 1"));
			$creditslower	=	$type == 'special' ? 0 : ($credittmp ? $credittmp : '99999999');

			$xc->db['discuz']->query("REPLACE INTO {$discuz_tablepre}common_usergroup (groupid, radminid, type, system, grouptitle, creditshigher, creditslower, stars, color, icon, allowvisit, allowsendpm, allowinvite, allowmailinvite, maxinvitenum, inviteprice, maxinviteday) VALUES ('$groupid', '0', '$type', 'private', '$grouptitle', '$creditshigher', '$creditslower', '0', '', '', '1', '1', '0', '0', '0', '0', '10');");
			$xc->db['discuz']->query("REPLACE INTO {$discuz_tablepre}common_usergroup_field (groupid, readaccess, allowpost, allowreply, allowpostpoll, allowpostreward, allowposttrade, allowpostactivity, allowdirectpost, allowgetattach, allowpostattach, allowpostimage, allowvote, allowsearch, allowcstatus, allowinvisible, allowtransfer, allowsetreadperm, allowsetattachperm, allowhidecode, allowhtml, allowanonymous, allowsigbbcode, allowsigimgcode, allowmagics, disableperiodctrl, reasonpm, maxprice, maxsigsize, maxattachsize, maxsizeperday, maxpostsperhour, attachextensions, raterange, mintradeprice, maxtradeprice, minrewardprice, maxrewardprice, magicsdiscount, maxmagicsweight, allowpostdebate, tradestick, exempt, maxattachnum, allowposturl, allowrecommend, allowpostrushreply, maxfriendnum, maxspacesize, allowcomment, searchinterval, searchignore, allowblog, allowdoing, allowupload, allowshare, allowcss, allowpoke, allowfriend, allowclick, allowmagic, allowstat, videophotoignore, allowviewvideophoto, allowmyop, magicdiscount, domainlength, seccode, disablepostctrl, allowbuildgroup, edittimelimit, allowpostarticle, allowspacediyhtml, allowspacediybbcode, allowspacediyimgcode, allowcommentpost, allowcommentitem) VALUES ('$groupid', '1', '1', '1', '1', '1', '1', '1', '3', '1', '1', '1', '1', '30', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '1', '2', '0', '0', '0', '0', '0', '', '', '1', '0', '1', '0', '0', '0', '1', '0', '0', '0', '3', '1', '1', '0', '0', '1', '0', '0', '1', '1', '1', '1', '0', '1', '1', '1', '0', '0', '0', '0', '1', '0', '0', '0', '1', '10', '0', '0', '1', '1', '1', '2', '1');");
		}
	} else {
		$xc->db['discuz']->query("DELETE FROM {$discuz_tablepre}usergroups WHERE groupid > 15");
		$gquery = $xc->db['source']->query("SELECT gid, grouptitle FROM $sourcetable WHERE gptype ='special' or (gptype = 'system' and gid > 7) ORDER BY gid ASC") or dexit();
		while($g = $xc->db['source']->fetch_array($gquery)) {
			$g		=	daddslashes($g);
			$groupid	=	$g['gid'] + 15;
			$grouptitle	=	$g['grouptitle'];
			$gsql		=	"REPLACE INTO {$discuz_tablepre}usergroups (groupid, radminid, type, system, grouptitle, creditshigher, creditslower, stars, color, groupavatar, readaccess, allowvisit, allowpost, allowreply, allowpostpoll, allowpostreward, allowposttrade, allowpostactivity, allowdirectpost, allowgetattach, allowpostattach, allowvote, allowsearch, allowcstatus, allowuseblog, allowinvisible, allowtransfer, allowsetreadperm, allowsetattachperm, allowhidecode, allowhtml, allowanonymous, allownickname, allowsigbbcode, allowsigimgcode, allowviewpro, allowviewstats, disableperiodctrl, reasonpm, maxprice, maxsigsize, maxattachsize, maxsizeperday, maxpostsperhour, attachextensions, raterange, mintradeprice, maxtradeprice, minrewardprice, maxrewardprice, magicsdiscount, allowmagics, maxmagicsweight, allowbiobbcode, allowbioimgcode, maxbiosize, maxattachnum, allowposturl, allowrecommend, edittimelimit, allowpostrushreply) VALUES ('$groupid', 0, 'special', 'private', '$grouptitle', 50, 200, 2, '', '', 20, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 100, 0, 0, 0, 'chm, pdf, zip, rar, tar, gz, bzip2, gif, jpg, jpeg, png', '', 1, 0, 1, 0, 0, 1, 60, 0, 0, 0, 0, 3, 1, 0, 0)";
			$xc->db['discuz']->query($gsql);
		}
	}
}

function gethighlightid($string) {//取得高亮id
	$highlightlist	= array(''=>'0','red'=>'1','orange'=>'2','yellow'=>'3','green'=>'4','cyan'=>'5','blue'=>'6','purple'=>'7','gray'=>'8');
	$threadstitlefont = explode('~',$string);
	$stylebin = '';
	$highlight_color = 0;
	for($i = 1; $i <= 3; $i++) {
		$stylebin .= empty($threadstitlefont[$i]) ? '0' : '1';
	}
	$highlight_style = bindec($stylebin);
	if (!empty($threadstitlefont[0])) {
		$titlefont = strtolower($threadstitlefont[0]);
		$highlight_color = isset($highlightlist[$titlefont]) ? $highlightlist[$titlefont] : 0;
	}

	return "$highlight_style$highlight_color";
}

function addmedals() {
	global $xc, $source_tablepre, $discuz_tablepre, $config_type;
	$medalquery = $xc->db['source']->query("SELECT * FROM {$source_tablepre}medalinfo") or dexit();
	while($medal = $xc->db['source']->fetch_array($medalquery)) {
		$medal		=	daddslashes($medal);
		$medalid	=	$medal['id'] + 10;
		$name		=	$medal['name'];
		$available	=	1;
		$image		=	substr($medal['picurl'], strrpos('/'.$medal['picurl'], '/'));
		$medalsql	=	"REPLACE INTO {$discuz_tablepre}".($config_type == 'x' ? 'forum_medal': 'medals')." (medalid, name, available, image) VALUES ('$medalid', '$name', '$available', '$image')";
		$xc->db['discuz']->query($medalsql);
	}
}
/**
 * 修正字符串中的特殊字符 去掉字符串末尾的‘\’
 *
 * 功能添加中
 *
*/
function formatstr($str) {
	while(ereg('\\\$',$str)){
		$str = substr($str,0,-1);
	}
	return 	$str;
}

function getrecordsnum($table = '', $condition = '', $flag = 1) {	//flag=1,表示从原库中查询；flag=2,表示从新库中查询
	global $xc, $source_tablepre, $discuz_tablepre;

	$result = 0;
	if($table == '' || $conditon == ''){
		return 0;
	}else{
		if($flag == 1){
			$result = $xc->db['source']->result($xc->db['source']->query("SELECT count(*) FROM {$source_tablepre}{$table} WHERE ".$condition), 0);
		}else{
			$result = $xc->db['discuz']->result($xc->db['discuz']->query("SELECT count(*) FROM {$discuz_tablepre}{$table} WHERE ".$condition), 0);
		}
	}
	return $result;
}

function gexplode($str, $num, $flag='-'){
	$temp	=	explode($flag, $str);
	return $temp[$num];
}

function getdiscuztid($otid, $dateline) {
	global $xc, $discuz_tablepre;
	//通过源数据获取源现在的帖子ID
	$query = $xc->db['discuz']->query("SELECT pid,fid,tid FROM {$discuz_tablepre}forum_post WHERE first='1' AND dateline='$dateline' limit 1");
	$post = $xc->db['discuz']->fetch_array($query);

	return array('tid' => $post['tid'], 'pid' => $post['pid'], 'fid'=>$post['fid']);
}

function random($length, $numeric = 0) {
	$seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed{mt_rand(0, $max)};
	}
	return $hash;
}

function relationship($fromuid, $touid) {
	if($fromuid < $touid) {
		return $fromuid.'_'.$touid;
	} elseif($fromuid > $touid) {
		return $touid.'_'.$fromuid;
	} else {
		return '';
	}
}

function _parseLink($content) {
	if (strpos($content,'[/URL]') !== false || strpos($content,'[/url]') !== false) {
		$content = preg_replace("/\[url=([^\[]+?)\](.*?)\[\/url\]/is","<a href=\"\\1\" target=\"_blank\">\\2</a>", $content);
	}
	return preg_replace("/(?<!\shref=['\"])((https?|ftp|gopher|news|telnet|mms|rtsp):\/\/[a-z0-9\/\-_+=.~!%@?#%&;:$\\│\|]+)/ie", "_parseLinkContent('\\1')", $content);
}
function _parseLinkContent($url) {
	return _parseWebUrl($url);
}
function _parseWebUrl($url) {
	return '[url]' . $url . '[/url]';
}

function getattachtableid($tid) {
	$tid = (string)$tid;
	return intval($tid{strlen($tid)-1});
}

function getattachtablebytid($tid) {
	return 'forum_attachment_'.getattachtableid($tid);
}
?>
