<?php

/*
[Dvbbs] Dv_ClsMain.php - Version: 1.0.0
Web: http://www.dvbbs.net
Copyright: 2000-2006 Dvbbs.Net
*/
if( !defined('ISDVBBS') ){
	header('HTTP/1.0 404 Not Found');
	exit;
}
!defined('TIME_NOW') AND define('TIME_NOW', time());

function head( $isnav=0,$isboard=0,$depth=0, $arrNavMenu=array(),$mygrouplink=''){
	global $fsetting,$lang,$istoptable,$stats,$membername,$userid,$userhidden,$boardid,$boardinfo,$userinfo,$gettitle,$db,$dv,$usergroupid;
	global $ScriptName,$_DCACHE,$master,$forum_ads,$board_settings,$sendmsgnum,$sendmsgid,$sendmsguser,$ForumUrl,$usertrueip,$iswebsearch;
	//搜索引擎优化
	$title = $stats. ' - ' .$fsetting['forumname'];
	$iswebsearch = IsWebSearch();
	(true === $iswebsearch) AND ($title .= ' - powered by dvbbs.net');
	//系统菜单，搜索引擎给出另一份菜单
	//版面导航部分
	if( $boardid > 0  && $isnav == 0 ){
		$isnav = 1;
		global $_DCACHE;
		if( empty($_DCACHE['all_forums']) ){
			if( !@include_once CACHE_PATH.'board/board_all.php' ){
				return null;
			}
		}
		$currBoardInfo =& $_DCACHE['all_forums']["{$boardid}"];
		$all_forums =& $_DCACHE['all_forums'];
		if( is_array($currBoardInfo) ){
			if( $currBoardInfo['parentstr'] != '' ){
				$arrParentID = explode(',', $currBoardInfo['parentstr']);
				if( !empty($arrParentID) ){
					if (defined('THIS_SCRIPT') AND THIS_SCRIPT === 'dispbbs' AND isset($GLOBALS['page'])) {
						$otherparam = "&page={$GLOBALS['page']}";
					}
					foreach( $arrParentID AS $currParentID ){
						if ($currParentID <= 0) {
							continue;
						}
						$arrNavMenu[] = array(
						'linktitle' => $all_forums["{$currParentID}"]['boardtype']
						,'linkurl' => "index.php?boardid={$currParentID}{$otherparam}"
						,'board_depth' => intval($all_forums["{$currParentID}"]['depth'])
						,'board_id' => intval($currParentID)
						,'board_child' => intval($all_forums["{$currParentID}"]['child']));
					}
				}
			}
			$arrNavMenu[] = array('linktitle' => $boardinfo['boardtype'] ,'linkurl' => "index.php?boardid={$currBoardInfo['boardid']}{$otherparam}", 'board_depth' => intval($currBoardInfo['depth']), 'board_id' => intval($currBoardInfo['boardid']), 'board_child' => intval($currBoardInfo['child']));
			$arrNavMenu[]['linktitle'] = $gettitle;
		}
	}
	//新建论坛菜单
	$plus_arr = array();
    $plus_str=get_cookie("plusarrstr");
	if ( $plus_str !=''){
		$plus_str=str_replace(array('_',':'),array('+','/'),$plus_str);
		$plus_arr = unserialize(base64_decode($plus_str));
	}
	else{
		$query = $db->query("SELECT id,plus_type,plus_name,isuse,mainpage,plus_setting,isshowmenu,plus_copyright FROM {$dv}plus WHERE isuse='1' AND isshowmenu='1' ORDER BY id ASC");
		while($rs = $db->fetch_array($query)) {
			$plus_setting = explode('|||',$rs['plus_setting']);
			$plus_setting = $plus_setting[3];
			$plus_setting = explode(',',$plus_setting);
			$plus_setting = strpos($plus_setting[2],'@') !== false ? str_replace('@',',',$plus_setting[2]) : $plus_setting[2];
			$rs['title'] = $rs['plus_copyright'];
			$_windowtype = explode('|',$rs['plus_setting']);
			$windowtype = $_windowtype[0];
			$windowwidth = $_windowtype[1];
			$windowheight = $_windowtype[2];
			switch($windowtype) {
				case 0:
					$rs['url'] = $rs['mainpage'];
					$rs['target'] = '';
					break;
				case 1:
					$rs['url'] = $rs['mainpage'];
					$rs['target'] = ' target="_blank"';
					break;
				case 2:
					$rs['url'] = 'JavaScript:openScript(\''.$rs['mainpage'].'\','.$windowwidth.','.$windowheight.')';
					$rs['target'] = '';
					break;
				case 3:
					$rs['url'] = 'JavaScript:openScript(\''.$rs['mainpage'].'\',screen.width,screen.height)';
					$rs['target'] = '';
					break;
			}
			$rs['plus_setting']= '';
			if($rs['plus_type']) {
				$plus_arr[$rs['plus_type']]['sub'][] = $rs['id'];
			}
			$plus_arr[$rs['id']]['plus_type']= $rs['plus_type'];
			$plus_arr[$rs['id']]['sub']= $rs['sub'];
			$plus_arr[$rs['id']]['url']= $rs['url'];
			$plus_arr[$rs['id']]['target']= $rs['target'];
			$plus_arr[$rs['id']]['plus_name']= $rs['plus_name'];
		}
		set_cookie("plusarrstr", str_replace(array('=','+','/'),array('','_',':'),base64_encode(serialize($plus_arr))) , (24*3600));
	}
	
	$mailto = 'mailto:'.(!empty($fsetting['mastermail']) ? $fsetting['mastermail'] : 'dvbbs@cndw.com');
	require_once printout('header');
	//定时开放
	if( $fsetting['stoplimited'] == 1 ){
		if ( $boardid > 0 ){
			$stoptime = date('H') + 6;
			if( $board_settings[$stoptime] == 1 ){
				$lang['forum.stoptime'] = str_replace('{$manageurl}',$fsetting['manageurl'],$lang['forum.stoptime']);
				showmsg($lang['forum.stoptime']);
			}
		}else{
			$stoptimelist = explode('|',$fsetting['stoptimelist']);
			if( $stoptimelist[date('H')] == 1 ){
				$lang['forum.stoptime'] = str_replace('{$manageurl}',$fsetting['manageurl'],$lang['forum.stoptime']);
				showmsg($lang['forum.stoptime']);
			}
		}
	}
	//论坛关闭
	if( $fsetting['forumstop'] == 1 ){
		$lang['forum.stoptime'] = str_replace('{$manageurl}',$fsetting['manageurl'],$lang['forum.stoptime']);
		showmsg($fsetting['stopreadme']. '|||' .$lang['forum.stoptime']);
	}
	//防刷新，如搜索引擎来访则不运行
	if( $fsetting['refreshtime'] > 0 && $fsetting['isrefresh'] == 1 && strpos($fsetting['refreshpage'],str_replace('/','',$ScriptName)) !== false ){
		$activetime = get_cookie("activetime");
		$cboardid = get_cookie("cboardid");
		$reflashtime = dateDiff("S", $activetime, gmdate('Y-m-d H:i:s'));
		if( $reflashtime < $fsetting['refreshtime'] && $cboardid == $boardid ){
			$lang['forum.stopreflash'] = str_replace('{$reflashtime}',$fsetting['refreshtime'],$lang['forum.stopreflash']);
			$lang['forum.stopreflash'] = str_replace('{$newreflash}',$fsetting['refreshtime']-$reflashtime,$lang['forum.stopreflash']);
			$lang['forum.stopreflash'] = str_replace('{$doreflash}',($fsetting['refreshtime']-$reflashtime)*1000,$lang['forum.stopreflash']);
			showmsg($lang['forum.stopreflash']);
		}else{
			set_cookie('activetime', gmdate('Y-m-d H:i:s'), $GLOBALS['user_selected_cookiedate']);
			set_cookie('cboardid',$boardid, $GLOBALS['user_selected_cookiedate']);
		}
	}else{
		$activetime = get_cookie("activetime");
		if( $activetime == ''){
			set_cookie('activetime', gmdate('Y-m-d H:i:s'), $GLOBALS['user_selected_cookiedate']);
		}
	}
	//IP锁定
	if ( $fsetting['lockip'] != '' && $master !== true ){
		$userip = explode('.',$usertrueip);
		$lockip = explode('|',$fsetting['lockip']);
		$lockip1 = $lockip2 = $lockip3 = $lockip4 = false;
		if ( count($userip) == 4 ){
			foreach( $lockip as $val ){
				$locklist = explode('.',$val);
				if ( count($locklist) == 4 ){
					if ( $userip[0] == $locklist[0] ){$lockip1 = true;}
					if ( $userip[1] == $locklist[1] || $locklist[1] == '*' ){$lockip2 = true;}
					if ( $userip[2] == $locklist[2] || $locklist[2] == '*' ){$lockip3 = true;}
					if ( $userip[3] == $locklist[3] || $locklist[3] == '*' ){$lockip4 = true;}
					if ( $lockip1 !== false && $lockip2 !== false && $lockip3 !== false && $lockip4 !== false ){
						$lang['forum.lockip'] = str_replace('{$manageurl}',$fsetting['manageurl'],$lang['forum.lockip']);
						$lang['forum.lockip'] = str_replace('{$usertrueip}',$usertrueip,$lang['forum.lockip']);
						showmsg($lang['forum.lockip']);
						break;
					}
					$lockip1 = $lockip2 = $lockip3 = $lockip4 = false;
				}
			}
		}
	}
}


function savvyhead( $isnav=0,$isboard=0,$depth=0, $arrNavMenu=array() ){
	global $fsetting,$lang,$istoptable,$stats,$membername,$userid,$userhidden,$boardid,$boardinfo,$userinfo,$gettitle,$db,$dv,$usergroupid;
	global $ScriptName,$_DCACHE,$master,$forum_ads,$board_settings,$sendmsgnum,$sendmsgid,$sendmsguser,$ForumUrl,$usertrueip,$iswebsearch;
	//搜索引擎优化
	$title = $stats. ' - ' .$fsetting['forumname'];
	$iswebsearch = IsWebSearch();
	(true === $iswebsearch) AND ($title .= ' - powered by dvbbs.net');
	//系统菜单，搜索引擎给出另一份菜单
	//版面导航部分
	if( $boardid > 0 && $isnav == 0 ){
		$isnav = 1;
		global $_DCACHE;
		if( empty($_DCACHE['all_forums']) ){
			if( !@include_once CACHE_PATH.'board/board_all.php' ){
				return null;
			}
		}
		$currBoardInfo =& $_DCACHE['all_forums']["{$boardid}"];
		$all_forums =& $_DCACHE['all_forums'];
		if( is_array($currBoardInfo) ){
			if( $currBoardInfo['parentstr'] != '' ){
				$arrParentID = explode(',', $currBoardInfo['parentstr']);
				if( !empty($arrParentID) ){
					if (defined('THIS_SCRIPT') AND THIS_SCRIPT === 'savvy_dispbbs' AND isset($GLOBALS['page'])) {
						$otherparam = "&page={$GLOBALS['page']}";
					}
					foreach( $arrParentID AS $currParentID ){
						if ($currParentID <= 0) {
							continue;
						}
						$arrNavMenu[] = array(
						'linktitle' => $all_forums["{$currParentID}"]['boardtype']
						,'linkurl' => "forum_savvy.php?boardid={$currParentID}{$otherparam}"
						,'board_depth' => intval($all_forums["{$currParentID}"]['depth'])
						,'board_id' => intval($currParentID)
						,'board_child' => intval($all_forums["{$currParentID}"]['child']));
					}
				}
			}
			$arrNavMenu[] = array('linktitle' => $boardinfo['boardtype'] ,'linkurl' => "forum_savvy.php?boardid={$currBoardInfo['boardid']}{$otherparam}", 'board_depth' => intval($currBoardInfo['depth']), 'board_id' => intval($currBoardInfo['boardid']), 'board_child' => intval($currBoardInfo['child']));
			$arrNavMenu[]['linktitle'] = $gettitle;
		}
	}
	//新建论坛菜单
	$plus_arr = array();
    $plus_str=get_cookie("plusarrstr");
	if ( $plus_str !=''){
		$plus_str=str_replace(array('_',':'),array('+','/'),$plus_str);
		$plus_arr = unserialize(base64_decode($plus_str));
	}
	else{
		$query = $db->query("SELECT id,plus_type,plus_name,isuse,plus_setting,mainpage,isshowmenu,plus_copyright FROM {$dv}plus WHERE isuse='1' AND isshowmenu='1' ORDER BY id ASC");
		while($rs = $db->fetch_array($query)) {
			$plus_setting = explode('|||',$rs['plus_setting']);
			$plus_setting = $plus_setting[3];
			$plus_setting = explode(',',$plus_setting);
			$plus_setting = strpos($plus_setting[2],'@') !== false ? str_replace('@',',',$plus_setting[2]) : $plus_setting[2];
			$rs['title'] = $rs['plus_copyright'];
			$_windowtype = explode('|',$rs['plus_setting']);
			$windowtype = $_windowtype[0];
			$windowwidth = $_windowtype[1];
			$windowheight = $_windowtype[2];
			switch($windowtype) {
				case 0:
					$rs['url'] = $rs['mainpage'];
					$rs['target'] = '';
					break;
				case 1:
					$rs['url'] = $rs['mainpage'];
					$rs['target'] = ' target="_blank"';
					break;
				case 2:
					$rs['url'] = 'JavaScript:openScript(\''.$rs['mainpage'].'\','.$windowwidth.','.$windowheight.')';
					$rs['target'] = '';
					break;
				case 3:
					$rs['url'] = 'JavaScript:openScript(\''.$rs['mainpage'].'\',screen.width,screen.height)';
					$rs['target'] = '';
					break;
			}
			$rs['plus_setting']= '';
			if($rs['plus_type']) {
				$plus_arr[$rs['plus_type']]['sub'][] = $rs['id'];
			}
			$plus_arr[$rs['id']]['plus_type']= $rs['plus_type'];
			$plus_arr[$rs['id']]['sub']= $rs['sub'];
			$plus_arr[$rs['id']]['url']= $rs['url'];
			$plus_arr[$rs['id']]['target']= $rs['target'];
			$plus_arr[$rs['id']]['plus_name']= $rs['plus_name'];
		}
		set_cookie("plusarrstr", str_replace(array('=','+','/'),array('','_',':'),base64_encode(serialize($plus_arr))) , (24*3600));
	}

	$mailto = 'mailto:'.(!empty($fsetting['mastermail']) ? $fsetting['mastermail'] : 'dvbbs@cndw.com');
	require_once printout('header');
	//定时开放
	if( $fsetting['stoplimited'] == 1 ){
		if ( $boardid > 0 ){
			$stoptime = date('H') + 6;
			if( $board_settings[$stoptime] == 1 ){
				$lang['forum.stoptime'] = str_replace('{$manageurl}',$fsetting['manageurl'],$lang['forum.stoptime']);
				showmsg($lang['forum.stoptime']);
			}
		}else{
			$stoptimelist = explode('|',$fsetting['stoptimelist']);
			if( $stoptimelist[date('H')] == 1 ){
				$lang['forum.stoptime'] = str_replace('{$manageurl}',$fsetting['manageurl'],$lang['forum.stoptime']);
				showmsg($lang['forum.stoptime']);
			}
		}
	}
	//论坛关闭
	if( $fsetting['forumstop'] == 1 ){
		$lang['forum.stoptime'] = str_replace('{$manageurl}',$fsetting['manageurl'],$lang['forum.stoptime']);
		showmsg($fsetting['stopreadme']. '|||' .$lang['forum.stoptime']);
	}
	//防刷新，如搜索引擎来访则不运行
	if( $fsetting['refreshtime'] > 0 && $fsetting['isrefresh'] == 1 && strpos($fsetting['refreshpage'],str_replace('/','',$ScriptName)) !== false ){
		$activetime = get_cookie("activetime");
		$cboardid = get_cookie("cboardid");
		$reflashtime = dateDiff("S", $activetime, gmdate('Y-m-d H:i:s'));
		if( $reflashtime < $fsetting['refreshtime'] && $cboardid == $boardid ){
			$lang['forum.stopreflash'] = str_replace('{$reflashtime}',$fsetting['refreshtime'],$lang['forum.stopreflash']);
			$lang['forum.stopreflash'] = str_replace('{$newreflash}',$fsetting['refreshtime']-$reflashtime,$lang['forum.stopreflash']);
			$lang['forum.stopreflash'] = str_replace('{$doreflash}',($fsetting['refreshtime']-$reflashtime)*1000,$lang['forum.stopreflash']);
			showmsg($lang['forum.stopreflash']);
		}else{
			set_cookie('activetime', gmdate('Y-m-d H:i:s'), $GLOBALS['user_selected_cookiedate']);
			set_cookie('cboardid',$boardid, $GLOBALS['user_selected_cookiedate']);
		}
	}else{
		$activetime = get_cookie("activetime");
		if( $activetime == ''){
			set_cookie('activetime', gmdate('Y-m-d H:i:s'), $GLOBALS['user_selected_cookiedate']);
		}
	}
	//IP锁定
	if ( $fsetting['lockip'] != '' && $master !== true ){
		$userip = explode('.',$usertrueip);
		$lockip = explode('|',$fsetting['lockip']);
		$lockip1 = $lockip2 = $lockip3 = $lockip4 = false;
		if ( count($userip) == 4 ){
			foreach( $lockip as $val ){
				$locklist = explode('.',$val);
				if ( count($locklist) == 4 ){
					if ( $userip[0] == $locklist[0] ){$lockip1 = true;}
					if ( $userip[1] == $locklist[1] || $locklist[1] == '*' ){$lockip2 = true;}
					if ( $userip[2] == $locklist[2] || $locklist[2] == '*' ){$lockip3 = true;}
					if ( $userip[3] == $locklist[3] || $locklist[3] == '*' ){$lockip4 = true;}
					if ( $lockip1 !== false && $lockip2 !== false && $lockip3 !== false && $lockip4 !== false ){
						$lang['forum.lockip'] = str_replace('{$manageurl}',$fsetting['manageurl'],$lang['forum.lockip']);
						$lang['forum.lockip'] = str_replace('{$usertrueip}',$usertrueip,$lang['forum.lockip']);
						showmsg($lang['forum.lockip']);
						break;
					}
					$lockip1 = $lockip2 = $lockip3 = $lockip4 = false;
				}
			}
		}
	}
}

function footer($displaytpl=true){
	global $_GET,$_POST,$_COOKIE,$_SESSION,$db,$fsetting,$lang,$time_start,$db_footertime,$timestamp,$db_obstart,$forum_ads,$zliboutputenable,$boardid;
	if($db){
		$qn=$db->querynum;
	}
	if ($fsetting['isruntime'] == 1){
		$t_array	= explode(' ',microtime());
		$totaltime	= number_format(($t_array[0]+$t_array[1]-$time_start),6);
		$is_gzip=((1 === $db_obstart OR $zliboutputenable) ? "Gzip enabled" : "Gzip disabled").$db_union[3];
		$forum_speed	= "{$lang['global.footer4']} $totaltime {$lang['global.footer5']}, $qn {$lang['global.footer6']}  , $is_gzip";
	}
	useractiveonline();
	if (isset($GLOBALS['_COOKIE_USERID'])) {
		set_cookie('userid', $GLOBALS['_COOKIE_USERID'], $GLOBALS['user_selected_cookiedate']);
		set_cookie('username', $GLOBALS['_COOKIE_USERNAME'], $GLOBALS['user_selected_cookiedate']);
		set_cookie('password', $GLOBALS['_COOKIE_USERPASSWD'], $GLOBALS['user_selected_cookiedate']);
		set_cookie('cometime', $GLOBALS['_COOKIE_COME_TIME'], $GLOBALS['user_selected_cookiedate']);
		set_cookie('cboardid', $GLOBALS['_COOKIE_CBOARDID'], $GLOBALS['user_selected_cookiedate']);
		set_cookie('sysusername',  get_cookie("sysusername"), 3600);
		set_cookie('syspassword', get_cookie("syspassword"), 3600);
	}
	if ($displaytpl === true) {
		require_once printout('footer');
	}
    
	$obcontents = str_replace(array('<!--<!---->', '<!---->', '<!---->-->', '<!-- -->', '<!--  -->'), '', ob_get_contents());
	if($fsetting['wss_enabled']){
		$obcontents.="<div style='display:none'><script src='http://pw.cnzz.com/c.php?id={$fsetting['wss_site_id']}&l=2' language='JavaScript' charset='gb2312'></script></div>";
	}
	ob_end_clean();

	if (!isset($db_obstart)) {
		$db_obstart = function_exists('ob_gzhandler') ? 1 : 0;
	}

	$db_obstart == 1 ? ob_start('ob_gzhandler') : ob_start();
	if(1 == $fsetting['bogushtml_settings'] AND defined('THIS_SCRIPT') AND ('index' === THIS_SCRIPT OR 'dispbbs' === THIS_SCRIPT OR 'query' === THIS_SCRIPT OR 'savepost' === THIS_SCRIPT OR 'post' === THIS_SCRIPT)){
		$obcontents = preg_replace(array('/(=["\']?)\?/i', '/(<a\s*[^>]+\s*href=["\']?)([^"\'\s>]*(?:index|dispbbs)\.php\?[^"\'\s>]+)(.*?>)/ies'), array('$1'.THIS_SCRIPT.'.php?', '"$1"._urlrewrite("$2")."$3"'), $obcontents);
	}
	print $obcontents;
	@$db->close();
	ob_end_flush();
	exit;
}
function _urlrewrite($url)
{
	global $fsetting;
	if(1 != $fsetting['bogushtml_settings'])return $url;
	static $cache_url;
	if (isset($cache_url[$url])) {
		return $cache_url[$url];
	}

	if (!($parseurl = @parse_url($url))) {
		return $url;
	}

	if (empty($parseurl['query'])) {
		return $url;
	}

	if (true === preg_match('/(?<!boardid|page|id|replyid|star|skin|topicmode|TopicDate|TopicOrder|TopicDA|location|action)=/i', $parseurl['query'])) {
		return $url;
	}
	$parsedquery = array('boardid'=>0, 'page'=>0, 'id'=>0, 'replyid'=>0, 'star'=>0, 'skin'=>0, 'topicmode'=>0,'TopicDate'=>0,'TopicOrder'=>0,'TopicDA'=>0,'location'=>'',''=>'action');
	
	!empty($parseurl['query']) AND ($parseurl['query'] = str_replace(array('&amp;', '&amp'), '&', $parseurl['query'])) AND (parse_str($parseurl['query'], $parsedquery));
	if($parsedquery['action']!=''||$parsedquery['TopicDate']||$parsedquery['TopicOrder'])return $url;
	$boardname=$parsedquery['boardid'];
	switch ($parseurl['path'] = str_replace('.php', '', $parseurl['path'])) {
		case 'index':
		case '/index':
			$boardname=$fsetting['bogushtml_settings_board'][$parsedquery['boardid']];
			$pageredirect="f";
			break;
		case 'dispargue':
		case '/dispargue':
			$pageredirect="d";
			break;
		case 'dispbbs':
		case '/dispbbs':
			$pageredirect="b";
			break;
		case 'savvy_dispbbs':
		case '/savvy_dispbbs':
			$pageredirect="s";
			break;
		default:
			return $url;
			break;
	}//end switch

	if((($parseurl['path'] =='index'||$parseurl['path'] =='/index')&&$fsetting['bogushtml_settings_forum']=='')||(($parseurl['path'] !='index'&&$parseurl['path'] !='/index')&&$fsetting['bogushtml_settings_bbs']=='')){
		!empty($parsedquery) AND ($url = $parseurl['path'].'-'.intval($parsedquery['boardid']).'-'.intval($parsedquery['topicmode']).'-'.intval($parsedquery['page']).'-'.intval($parsedquery['id']).'-'.intval($parsedquery['replyid']).'-'.intval($parsedquery['star']).'-'.intval($parsedquery['skin']).($parseurl['fragment'] ? '#'.$parseurl['fragment'] : ''));
		$url=preg_replace("/index/i","forum",$url);
		$cache_url[$url] = $url;
	}else{
		$exturl='';
		if($parsedquery['topicmode'])$exturl.="t".intval($parsedquery['topicmode']);
		if($parsedquery['page'])$exturl.="p".intval($parsedquery['page']);
		if($parsedquery['id'])$exturl.="i".intval($parsedquery['id']);
		if($parsedquery['replyid'])$exturl.="ri".intval($parsedquery['replyid']);
		if($parsedquery['star'])$exturl.="s".intval($parsedquery['star']);
		if($parsedquery['skin'])$exturl.="k".intval($parsedquery['skin']);
		if($parsedquery['fragment'])$exturl.="#".($parsedquery['fragment']);
		if($pageredirect=="f"&&$fsetting['bogushtml_settings_forum']=='domain'){
			($exturl)&&($exturl="rwf$exturl");
			$url="http://".$boardname.".".$fsetting['bogushtml_settings_domain']."/$exturl";
		}else{
			$urlback=$pageredirect=="f"?$fsetting['bogushtml_settings_forum']:$fsetting['bogushtml_settings_bbs'];
			if($urlback=='ndir'||$urlback==''){
				$urlback='';
			}else {
				$urlback='.'.$urlback;
			}
			
			if(!is_numeric($boardname)){
				if($exturl)$boardname.="_";
				$boardname="_".$boardname;
			}
			$url="rw{$pageredirect}{$boardname}{$exturl}".$urlback;
		}
	}
	return $url;
}//end function
function printout($template,$ext="tpl.php"){
	global $fsetting, $lang, $_DCACHE,$settplurl;
	if (empty($fsetting)) {
		require_once CACHE_PATH.'forum_setting.php';
		$fsetting =& $_DCACHE['settings'];
	}
	$tplurl = (!empty($settplurl)) ? $settplurl : "templates/{$fsetting['styletpl']}/";
	$filepath = ROOT_PATH.$tplurl."{$fsetting['styletpl_prev']}{$template}.{$ext}";
	if (!@is_file($filepath)) {
		global $db;
		if (is_object($db)) {
			@$db->close();
		}
		print 'Cannot find template file "'.$filepath.'"!';
		exit(0);
	}
	return $filepath;
}
function showmsg($message,$issuc=0,$gotourl="",$dispfooter=true,$dispheader=false){
	global $fsetting,$lang,$boardid,$db,$stats,$gettitle;
	$showmsg = $message;
	if ( $dispheader == true ){
		$stats = $lang['showmsg_title'];
		if ( $boardid == 0 ){
			$arrNavMenu = array(
			0=>array('linktitle'=>$stats)
			);
			head(1,0,0,$arrNavMenu);
		}else{
			$gettitle = $stats;
			head();
		}
	}
	$lang = load_lang($lang,'showerr');
	require printout('showerr');
	if( $dispfooter == true ){
		footer();
	} elseif( $db ){
		@$db->close();
	}
	exit;
}
function load_lang($current_lang, $area){
	global $fsetting, $lang, $_DCACHE;
	if (empty($fsetting)) {
		require_once CACHE_PATH.'forum_setting.php';
		$fsetting =& $_DCACHE['settings'];
	}
	$langpath = ROOT_PATH.'templates/lang/'.basename($fsetting['lang'])."/$area.lang.php";
	if (!@is_file($langpath)) {
		print 'Cannot find language file "'.$langpath.'"!';
		exit(0);
	}
	require $langpath;
	if( !empty($language) ){
		if( is_array($language) ){
			foreach ($language as $k => $v) {
				if( is_array($v) && !empty($v) ){
					$current_lang[$k] = $v;
				} else{
					$current_lang[$k] = $v;
				}
			}
			unset($language);
			return $current_lang;
		} else {
			showmsg('Error on load lang.');
		}
	} else{
		showmsg('Error on load lang.');
	}
}
function forumusertrueip(){
	global $_SERVER;
	static $UserTrueIP = '';
	if ( $UserTrueIP !== '' ) {
		return $UserTrueIP;
	}
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$UserTrueIP = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$UserTrueIP = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$UserTrueIP = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$UserTrueIP = $_SERVER['REMOTE_ADDR'];
	}
	return addslashes(str_filter_xss($UserTrueIP = preg_replace("/^([\d\.]+).*/", "\\1", $UserTrueIP)));
}
function get_datetime($string_format='Y-m-d H:i:s'){
	global $timestamp,$fsetting;
	return gmdate($string_format,$timestamp+$fsetting['timeoffset']*3600);
}
function ToolsLog($Log_ToolsID,$CountNum,$Log_Money,$Log_Ticket,$Log_Type,$Conect,$HMoney){
	global $db,$dv,$membername,$userid,$usertrueip,$boardid;
	$Log_ToolsID = is_numeric($Log_ToolsID) ? intval($Log_ToolsID) : 0 ;
	$CountNum = is_numeric($CountNum) ? intval($CountNum) : 0 ;
	$Log_Money = is_numeric($Log_Money) ? intval($Log_Money) : 0 ;
	$Log_Ticket = is_numeric($Log_Ticket) ? intval($Log_Ticket) : 0 ;
	if( get_magic_quotes_gpc() != 1 ){
		$membername = $db->escape_string($membername);
		$userid = $db->escape_string($userid);
		$Log_Type = $db->escape_string($Log_Type);
		$boardid = $db->escape_string($boardid);
		$Conect = $db->escape_string($Conect);
		$HMoney = $db->escape_string($HMoney);
	}
	$stmt = "INSERT INTO {$dv}moneylog (toolsid,countnum,log_money,log_ticket,addusername,adduserid,log_ip,log_type,boardid,conect,hmoney,log_time) VALUES('{$Log_ToolsID}','{$CountNum}','{$Log_Money}','{$Log_Ticket}','{$membername}','{$userid}','{$usertrueip}','{$Log_Type}','{$boardid}','{$Conect}','{$HMoney}','".TIME_NOW."')";
	$db->query($stmt);
}//end function ToolLog
function iHtmlencode(&$str){
	if( is_null($str) ) return '';
	$strTmp = str_replace('>','&gt;',$str);
	$strTmp = str_replace('<','&lt;',$strTmp);
	$strTmp = str_replace(chr(32),' ',$strTmp);
	$strTmp = str_replace(chr(9),' ',$strTmp);
	$strTmp = str_replace(chr(34),'&quot;',$strTmp);
	$strTmp = str_replace(chr(13),'',$strTmp);
	$strTmp = str_replace(chr(10).chr(10),'</p><p>',$strTmp);
	$strTmp = str_replace(chr(1),'<br />',$strTmp);
	return $strTmp;
}//end function iHtmlencode
//---------------------2007-8-27 IvanSky-----------------------------------
function iHtmltocode(&$str){
	if( is_null($str) ) return '';
	$strTmp = htmlspecialchars($str);
	$strTmp = str_replace(array(" ","　　","'",chr(34))
	,array("&nbsp;","&nbsp;&nbsp;&nbsp;&nbsp;","&acute;","&quot;"),$strTmp);
	$strTmp = nl2br($strTmp);
	$strTmp = stripslashes($strTmp);//\'去掉\ addslashes ' 加上/'
	return $strTmp;
}//end function iHtmltocode
function IsReadonly(){
	global $boardid,$fsetting,$board_settings;
	if( $fsetting['stoplimited'] == 2 ){
		$timeSetting = explode('|',$fsetting['stoptimelist']);
		if( intval($timeSetting[intval(date('H'))]) == 1 ){
			return true;
		}
	}//edit 2007-04-12
	if( $boardid > 0 ){
		if( $board_settings[5] == 2 ){
			$stoptime = date('H') + 6;
			if( $board_settings[$stoptime] == 1 ){
				return true;
			}
		}
	}
	return false;
}//end function IsReadonly
//显示验证码
function GetCode(){
}//end function
function NewPassword(){
}//end function NewPassword
//判断用户的版面权限
function chkboardlogin(){
	global $board_settings,$groupsetting,$userid,$boardid,$userinfo,$boardinfo,$lang,$ScriptName,$membername;
	if( $boardinfo['ishidden'] == 1 && $groupsetting[37] == '0' ){
		showmsg($lang['check.str1'],0,'',true,true);
	}
	if($groupsetting[0]=='0'){
		showmsg($lang['check.str2'],0,'',true,true);
	}
	if(intval($board_settings[30])!==0 && is_numeric($board_settings[30])){
		eval("\$lang['check.str3']=\"{$lang['check.str3']}\";");
		if($userid==0){showmsg($lang['check.str3'],0,'',true,true);}
		if($userinfo['userpost'] < intval($board_settings[30])){showmsg($lang['check.str3'],0,'',true,true);}
	}
	if(intval($board_settings[31])!==0 && is_numeric($board_settings[31])){
		eval("\$lang['check.str4']=\"{$lang['check.str4']}\";");
		if($userid==0){showmsg($lang['check.str4'],0,'',true,true);}
		if($userinfo['userep'] < intval($board_settings[31])){showmsg($lang['check.str4'],0,'',true,true);}
	}
	if(intval($board_settings[32])!==0 && is_numeric($board_settings[32])){
		eval("\$lang['check.str5']=\"{$lang['check.str5']}\";");
		if($userid==0){showmsg($lang['check.str5'],0,'',true,true);}
		if($userinfo['userwealth'] < intval($board_settings[32])){showmsg($lang['check.str5'],0,'',true,true);}
	}
	if(intval($board_settings[33])!==0 && is_numeric($board_settings[33])){
		eval("\$lang['check.str6']=\"{$lang['check.str6']}\";");
		if($userid==0){showmsg($lang['check.str6'],0,'',true,true);}
		if($userinfo['usercp'] < intval($board_settings[33])){showmsg($lang['check.str6'],0,'',true,true);}
	}
	if(intval($board_settings[34])!==0 && is_numeric($board_settings[34])){
		eval("\$lang['check.str7']=\"{$lang['check.str7']}\";");
		if($userid==0){showmsg($lang['check.str7'],0,'',true,true);}
		if($userinfo['userpower'] < intval($board_settings[34])){showmsg($lang['check.str7'],0,'',true,true);}
	}
	if(intval($board_settings[35])!==0 && is_numeric($board_settings[35])){
		eval("\$lang['check.str8']=\"{$lang['check.str8']}\";");
		if($userid==0){showmsg($lang['check.str8'],0,'',true,true);}
		if($userinfo['userisbest'] < intval($board_settings[35])){showmsg($lang['check.str8'],0,'',true,true);}
	}
	if(intval($board_settings[36])!==0 && is_numeric($board_settings[36])){
		eval("\$lang['check.str9']=\"{$lang['check.str9']}\";");
		if($userid==0){showmsg($lang['check.str9'],0,'',true,true);}
		if($userinfo['userdel'] < intval($board_settings[36])){showmsg($lang['check.str9'],0,'',true,true);}
	}
	if(intval($board_settings[37])!==0 && is_numeric($board_settings[37])){
		eval("\$lang['check.str10']=\"{$lang['check.str10']}\";");
		if($userid==0){showmsg($lang['check.str10'],0,'',true,true);}
		if(dateDiff('s',$userinfo['joindate'], TIME_NOW) < intval($board_settings[37])*60){showmsg($lang['check.str10'],0,'',true,true);}
	}
	//认证版面
	$get_boarduser_money = $canlogin = false;
	if(intval($boardinfo['ischeckout'])==1){
		if(intval($board_settings[39]) > 0 || intval($board_settings[40]) > 0){$get_boarduser_money = true;}
		if($userid==0){
			showmsg($lang['check.str11'],0,'',true,true);
		}else{
			if($boardinfo['boarduser']!=''){
				$boarduser = explode(',',$boardinfo['boarduser']);
				foreach($boarduser as $val){
					if ( $get_boarduser_money !== false ){
						$boarduser_money = explode('=',$val);
						if ( strtolower($boarduser_money[0]) == strtolower($membername) ){
							//判断支付金币或点券进入版面的有效期
							if ( dateDiff('d',$boarduser_money[1],TIME_NOW) < intval($board_settings[42])*30 ){
								$canlogin = true;
								break;
							}
						}
					}else{
						if ( strtolower($val) == strtolower($membername) ){
							$canlogin = true;
							break;
						}
					}
				}
			}
		}
		if($get_boarduser_money === true && $ScriptName != 'pay_boardlimited.php' && $canlogin === false){
			header("Location:pay_boardlimited.php?boardid={$boardid}");
		}
		if($ScriptName != 'pay_boardlimited.php' && $canlogin !== true){showmsg($lang['check.str11'],0,'',true,true);}
	}
}
function useractiveonline($isupdate=0){
	global $db,$userid,$dv,$statuserid,$userinfo,$stats,$boardid,$usertrueip,$userhidden,$onlineexists,$fsetting,$seccode,$usergroupid,$iswebsearch,$lang;
	if (!isset($_SERVER['HTTP_ACCEPT']) OR !isset($_SERVER['HTTP_CONNECTION']) OR $_SERVER['SERVER_ADDR'] == '::1' OR true === IsWebSearch()) {
		return false;
	}
	$stats = i_addslashes($stats);
	if (!$usertrueip) {
		$usertrueip = forumusertrueip();
	}
	if($userid<=0){
		if($userinfo){
			$reflashtime = datediff("S",$userinfo['lastimebk'],TIME_NOW);
			if(($reflashtime > 120 && $boardid == $userinfo['boardid']) || $boardid != $userinfo['boardid'] || $isupdate == 1){
				$db->query("Update {$dv}online Set lastimebk = '".TIME_NOW."',boardid = '$boardid',stats = '$stats',actforip = '$seccode' Where id = '$statuserid'");
			}
		}else{
			if($fsetting['onlinefrom'] == 1){
				$actcome = ipfrom($usertrueip);
				$actcome = i_addslashes($actcome);
			}
			$ibrowser = sysinfo($_SERVER["HTTP_USER_AGENT"]).'|'.browser($_SERVER["HTTP_USER_AGENT"]);
			$db->query("Insert Into {$dv}online (id,username,userclass,ip,actforip,startime,lastimebk,boardid,browser,stats,usergroupid,actcome,userhidden,userid) Values ('$statuserid','{$lang['clsmain.str1']}','{$lang['clsmain.str1']}','$usertrueip','$seccode','".TIME_NOW."','".TIME_NOW."','$boardid','$ibrowser','$stats','7','$actcome','$userhidden','0')");
			$deltime = TIME_NOW - ($fsetting['onlinetimeout'] * 60);
			$db->query("Delete From {$dv}online Where lastimebk<'$deltime'");
		}
	}else{
		if($onlineexists == 1){
			if($fsetting['onlinefrom'] == 1){
				$actcome = ipfrom($usertrueip);
				$actcome = i_addslashes($actcome);
			}
			$ibrowser = sysinfo($_SERVER["HTTP_USER_AGENT"]).'|'.browser($_SERVER["HTTP_USER_AGENT"]);
			$db->query("Insert Into {$dv}online (id,username,userclass,ip,actforip,startime,lastimebk,boardid,browser,stats,usergroupid,actcome,userhidden,userid) Values ('$userid','$userinfo[username]','$userinfo[userclass]','$usertrueip','$seccode','".TIME_NOW."','".TIME_NOW."','$boardid','$ibrowser','$stats','$usergroupid','$actcome','$userhidden','$userid')");
			$deltime = TIME_NOW - ($fsetting['onlinetimeout'] * 60);
			$db->query("Delete From {$dv}online Where lastimebk<'$deltime'");
		}else{
			$reflashtime = TIME_NOW - $userinfo['lastimebk'];
			if(($reflashtime > 120 && $boardid == $userinfo['boardid']) || $boardid != $userinfo['boardid'] || $isupdate == 1){
				$db->query("Update {$dv}online Set lastimebk = '".TIME_NOW."',boardid = '$boardid',stats = '$stats',actforip = '$seccode',usergroupid = '$usergroupid' Where userid = '$userid'");
			}
		}
	}
}
function ChkBadWords(&$str){
	global $fsetting;
	if( is_null($str) ) return;
	if( $fsetting['badwords'] == '' ) return $str;
	$BadWords = explode('|',$fsetting['badwords']);
	$rBadWords = explode('|',$fsetting['rbadwords']);
	$count1 = count($BadWords);
	$count2 = count($rBadWords);
	for( $i = 0 ; $i < $count1 ; $i++ ){
		if(!isset($BadWords[$i]) or !empty($BadWords[$i])){
			if(strpos($str,$BadWords[$i]) !== false ){
				if(preg_match("/^[a-zA-Z]+$/",$BadWords[$i])){
					$BadWords[$i]= '\b'.$BadWords[$i].'\b';
					if( $i >= $count2 )
					$str=preg_replace('#([^a-z\']|\b)'.$BadWords[$i].'([^a-z\']|\b)#i','$1$2',$str);
					else
					$str=preg_replace('#([^a-z\']|\b)'.$BadWords[$i].'([^a-z\']|\b)#i','$1'.$rBadWords[$i].'$2',$str);
				}
				else{
					if( $i >= $count2 ){
						if(function_exists('mb_ereg_replace'))
						$str= mb_ereg_replace($BadWords[$i],'*',$str);
						else
						$str = str_replace($BadWords[$i],'*',$str);
					} else{
						if(function_exists('mb_ereg_replace'))
						$str= mb_ereg_replace($BadWords[$i],$rBadWords[$i],$str);
						else
						$str = str_replace($BadWords[$i],$rBadWords[$i],$str);
					}
				}
			}
		}
	}
	return $str;
}//end function ChkBadWords


/**
 * Description 根据参数，返回 HTML 形式的分页区块
 * @author xiaodu@dvbbs
 * @param int 要分页的数据的总数
 * @param int 当前页实际应该显示几条数据，默认值为 1
 * @param int 当前页码
 * @param int 每一页最多显示几条数据，即分页的基数，默认值为 10
 * @param int 最多显示几个页码，默认值为 10
 * @param array 扩展选项
 * @return string 返回 HTML 形式的分页区块
 */
function pagenation_UI($recordcount, $realnum, $absolutepage=1, $pagesize=10, $pagenocount=10, $opts = array(), $skin=0)
{
	global $lang;
	if ($recordcount <= 0) {
		return '';
	}
	if ($realnum <= 0) {
		return '';
	}
	if ($absolutepage <= 0) {
		$absolutepage = 1;
	}
	if ($pagesize <= 0) {
		$pagesize = 10;
	}
	if ($pagenocount <= 0 ) {
		$pagenocount = 10;
	}
	empty($opts['url']) AND ($opts['url'] = 'dispbbs.php?');
	empty($opts['pagevar']) AND ($opts['pagevar'] = 'star');
	$opts['target'] = (empty($opts['target']) ? ' target="_self" ' : ' target="'.$opts['target'].'"');
	$pagecount = ceil((double)$recordcount / (double)$pagesize);
	($pagecount < 1) AND ($pagecount = 1);
	$basenum = intval((($absolutepage - 1) / $pagenocount));
	$i_start = $basenum * $pagenocount + 1;
	$i_end = $i_start - 1 + $pagenocount;
	($i_end > $pagecount) AND ($i_end = $pagecount);
	$pagelist = '';
	$get_gotopage = <<<EOT
	<script type="text/JavaScript">
	<!--
	function _dv_GotoPage()
	{
		var absolutepage = '{$absolutepage}';
		var pagecount = '{$pagecount}';
		var id = document.getElementById('GoToPage');
		var newpage = parseInt(id.value);
		if (isNaN(newpage) || newpage <= 0 || newpage > pagecount) {
			alert('{$lang['clsmain.str5_2']}');
			id.focus();
			id.select();
			return false;
		}
		var url = '{$opts['url']}&amp;{$opts['pagevar']}='+newpage;
		window.location.href = url;
		return false;
	}//end function _dv_GotoPage
	//-->
	</script>
EOT;
	switch($skin){
		case 0:
			for ($i = $i_start; $i <= $i_end AND $i <= $pagecount ; $i++) {
				if ($i != $absolutepage) {
					$pagelist .= '<td  class="tablebody1" nowrap="nowrap">&nbsp;<a href="'._urlrewrite($opts['url'].'&'.$opts['pagevar'].'='.$i).'" '.$opts['target'].' '.$opts['link_other_prop'].'>'.$i.'<a/>&nbsp;</td>';
				} else {

					$pagelist .= '<td class="tablebody2" nowrap="nowrap">&nbsp;<font class="normalTextSmall"><u><b>'.$i.'</b></u></font>&nbsp;</td>';
				}
			}//end for
			if ($i_start <= $pagenocount) {
				$strfirst = $strpreviours = '';
			} else {
				$strfirst = '<td class="tablebody1" nowrap="nowrap">&nbsp;<a href="'._urlrewrite($opts['url'].'&'.$opts['pagevar'].'=1').'"><img src="images/pagelist/first.gif" border="0" alt="'.$lang['clsmain.str3_0'].'"></a>&nbsp;</td>';
				$strpreviours = '<td class="tablebody1" nowrap="nowrap">&nbsp;<a href="'.$opts['url'].'&amp;'.$opts['pagevar'].'='.($i_start - 1).'"><img src="images/pagelist/previous.gif" border="0" alt="'.$lang['clsmain.str2_0'].'"></a>&nbsp;</td>';
			}
			if ($i_end >= $pagecount) {
				$strlast = $strnext = '';
			} else {
				$strnext = '<td class="tablebody1" nowrap="nowrap">&nbsp;<a href="'._urlrewrite($opts['url'].'&'.$opts['pagevar'].'='.($i_end + 1)).'"><img src="images/pagelist/next.gif" border="0" alt="'.$lang['clsmain.str2'].'"></a>&nbsp;</td>';
				$strlast = '<td class="tablebody1" nowrap="nowrap">&nbsp;<a href="'._urlrewrite($opts['url'].'&'.$opts['pagevar'].'='.$pagecount).'"><img src="images/pagelist/last.gif" border="0" alt="'.$lang['clsmain.str3'].'"></a>&nbsp;</td>';
			}
			if ($i_start > $pagenocount OR $pagecount >= $i_end) {
				$gotopage = <<<EOT
				{$get_gotopage}
				<td class="tablebody1" nowrap="nowrap"><input id="GoToPage" type="text" name="GoToPage" size="1" value="{$absolutepage}" /><input type="button" value="GO" name="button" class="button" onclick="return _dv_GotoPage()" /></td>
EOT;
			} else {
				$gotopage = '';
			}
		$PageTemplate = <<<EOT
		<div id="DV_PagenationUI">
			<table class="tableborder3" cellpadding="0" cellspacing="1">
				<tr align="center">
					<td class="tabletitle1" nowrap="nowrap" title="{$lang['clsmain.str4']}" height=23>&nbsp;{$recordcount}&nbsp;</td>
					<td class="tabletitle1" nowrap="nowrap" title="{$lang['clsmain.str5']}">&nbsp;{$realnum}&nbsp;</td>
					<td class="tabletitle1" nowrap="nowrap" title="{$lang['clsmain.str5_1']}">&nbsp;{$pagesize}&nbsp;</td>
					<td class="tabletitle1" nowrap="nowrap">&nbsp;{$absolutepage}/{$pagecount}&nbsp;</td>
					{$strfirst}{$strpreviours}{$pagelist}{$strnext}{$strlast}{$gotopage}
				</tr>
			</table>
		</div>
EOT;
		break;
		case 1:
			for ($i = $i_start; $i <= $i_end AND $i <= $pagecount ; $i++) {
				if ($i != $absolutepage) {
					$pagelist .= '<a class="page" href="'._urlrewrite($opts['url'].'&'.$opts['pagevar'].'='.$i).'" '.$opts['target'].' '.$opts['link_other_prop'].'>'.$i.'<a/>';
				} else {
					$pagelist .= '<font class="page" id="on"><u><b>'.$i.'</b></u></font>';
				}
			}//end for
			if ($i_start <= $pagenocount) {
				$strfirst = $strpreviours = '';
			} else {
				$strfirst = '<a class="page" href="'._urlrewrite($opts['url'].'&'.$opts['pagevar'].'=1').'"><img src="images/pagelist/first.gif" border="0" alt="'.$lang['clsmain.str3_0'].'"></a>';
				$strpreviours = '<a class="page" href="'.$opts['url'].'&amp;'.$opts['pagevar'].'='.($i_start - 1).'"><img src="images/pagelist/previous.gif" border="0" alt="'.$lang['clsmain.str2_0'].'"></a>';
			}
			if ($i_end >= $pagecount) {
				$strlast = $strnext = '';
			} else {
				$strnext = '<a class="page" href="'._urlrewrite($opts['url'].'&'.$opts['pagevar'].'='.($i_end + 1)).'"><img src="images/pagelist/next.gif" border="0" alt="'.$lang['clsmain.str2'].'"></a>';
				$strlast = '<a class="page" href="'._urlrewrite($opts['url'].'&'.$opts['pagevar'].'='.$pagecount).'"><img src="images/pagelist/last.gif" border="0" alt="'.$lang['clsmain.str3'].'"></a>';
			}
			if ($i_start > $pagenocount OR $pagecount >= $i_end) {
				$gotopage = <<<EOT
				{$get_gotopage}
				<b class="page"><input id="GoToPage" type="text" name="GoToPage" size="1" value="{$absolutepage}" /></b><a href="#" class="page"  onclick="return _dv_GotoPage()" >GO</a>
EOT;
			} else {
				$gotopage = '';
			}
			$recordcount=($recordcount>1)? $recordcount-1:0;
		$PageTemplate = <<<EOT
			<b class="page"><font color="red">{$recordcount}</font> / {$lang['dispbbs_info_rebacknum']}</b>
			<b class="page">{$absolutepage}/{$pagecount}</b>
			{$strfirst}{$strpreviours}{$pagelist}{$strnext}{$strlast}{$gotopage}
EOT;

		break;
	}

return $PageTemplate;
}//end function pagenation_UI

//信息数/每页数/当前页/URL/当前页信息数/最大页/扩展的URL参数，格式为key1=val1&key2=val2...等等，以此类推
function pagelist($num, $perpage, $curpage, $mpurl, $topicnum, $maxpages = 0, $otherparam = '', $skin=0) {
	global $lang;
	$multipage = '';
	$mpurl .= strpos($mpurl, '?') !== false ? '&' : '?';
	if($num > $perpage) {
		$page = 10;
		$offset = 2;

		$realpages = @ceil($num / $perpage);
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;

		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $curpage + $page - $offset - 1;
			if($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if(($to - $from) < $page && ($to - $from) < $pages) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $curpage - $pages + $to;
				$to = $pages;
				if(($to - $from) < $page && ($to - $from) < $pages) {
					$from = $pages - $page + 1;
				}
			}
		}

		if (!is_string($otherparam)) {
			$otherparam = '';
		} elseif ($otherparam{0} !== '&' OR $otherparam{0} !== '&amp;') {
			$otherparam = '&amp;'.$otherparam;
		}
		if (defined('THIS_SCRIPT') AND ('dispbbs' === THIS_SCRIPT OR 'dispargue' === THIS_SCRIPT)) {
			$pageparamname = 'star';
		} else {
			$pageparamname = 'page';
		}
	$get_gotopage = <<<EOT
	<script type="text/JavaScript">
	<!--
	function _dv_GotoPage()
	{
		var curpage = '{$curpage}';
		var realpages = '{$realpages}';
		var id = document.getElementById('GoToPage');
		var newpage = parseInt(id.value);
		if (isNaN(newpage) || newpage <= 0 || newpage > realpages) {
			alert('{$lang['clsmain.str5_2']}');
			id.focus();
			id.select();
			return false;
		}
		var url = '{$mpurl}&amp;page='+newpage;
		window.location.href = url;
		return false;
	}//end function _dv_GotoPage
	//-->
	</script>
EOT;
		switch($skin){
			case 0://默认风格
				$multipage = ($curpage - $offset > 1 && $pages > $page ? '<td class="tablebody1">&nbsp;<a href="'._urlrewrite($mpurl.$pageparamname.'=1'.$otherparam).'"><img src="images/pagelist/first.gif" border="0"></a>&nbsp;</td>' : '').
				($curpage > 1 ? '<td class="tablebody1">&nbsp;<a href="'._urlrewrite($mpurl.$pageparamname.'='.($curpage - 1).$otherparam).'"><img src="images/pagelist/previous.gif" border="0" alt="'.$lang['clsmain.str2_0'].'"></a>&nbsp;</td>' : '');
				for($i = $from; $i <= $to; $i++) {
					$url=_urlrewrite($mpurl.$pageparamname.'='.$i.$otherparam);
					$multipage .= $i == $curpage ? '<td class="tablebody2">&nbsp;<font class="normalTextSmall"><u><b>'.$i.'</b></u></font>&nbsp;</td>' :
					'<td class="tablebody1">&nbsp;<a href="'.$url.'">'.$i.'</a>&nbsp;</td>';
				}

				$multipage .= ($curpage < $pages ? '<td class="tablebody1">&nbsp;<a href="'._urlrewrite($mpurl.$pageparamname.'='.($curpage + 1).$otherparam).'"><img src="images/pagelist/next.gif" border="0" alt="'.$lang['clsmain.str2'].'"></a>&nbsp;</td>' : '').
				($to < $pages ? '<td class="tablebody1">&nbsp;<a href="'._urlrewrite($mpurl.$pageparamname.'='.$pages.$otherparam).'"><img src="images/pagelist/last.gif" border="0" alt="'.$lang['clsmain.str3'].'"></a>&nbsp;</td>' : '').
				($curpage == $maxpages ? '<td class="tablebody1">&nbsp;<img src="images/pagelist/last.gif" border="0" alt=""><!--<a href="index.php?action=maxpages&pages='.$maxpages.$otherparam.'">&gt;<b>?</b>--></a>&nbsp;</td>' : '').
				($pages > $page ? '<td class="tablebody1"><input type="text" name="'.$pageparamname.'" size="1" value="1"><input type="submit" value="GO" name="submit" class="button"></td>' : '');
				$multipage = $multipage ? '<table class="tableborder3" cellpadding="0" cellspacing="1">'.
				'<tr align="center"><td class="tabletitle1" title="'.$lang['clsmain.str4'].'" height=23>&nbsp;'.$num.'&nbsp;</td><td class="tabletitle1" title="'.$lang['clsmain.str5'].'">&nbsp;'.$topicnum.'&nbsp;</td><td class="tabletitle1">&nbsp;'.$curpage.'/'.$realpages.'&nbsp;</td>'.$multipage.'</tr></table>' : '';
			break;
			case 1: //清蓝色
				$previous= ($from>8)?($from-8):1;
				$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a class="page" href="'._urlrewrite($mpurl.$pageparamname.'=1'.$otherparam).'"><img src="images/pagelist/first.gif" align="absmiddle" style="margin-top:8px" border="0"></a>' : '').
				($curpage > 1 ? '<a class="page" href="'._urlrewrite($mpurl.$pageparamname.'='.($previous).$otherparam).'"><img src="images/pagelist/previous.gif" align="absmiddle" style="margin-top:8px" border="0" alt="'.$lang['clsmain.str2_0'].'"></a>' : '');
				for($i = $from; $i <= $to; $i++) {
					$url=_urlrewrite($mpurl.$pageparamname.'='.$i.$otherparam);
					$multipage .= $i == $curpage ? '<font class="page" id="on"><u><b>'.$i.'</b></u></font>' :
					'<a class="page" href="'.$url.'">'.$i.'</a>';
				}
				if(strpos($_SERVER['PHP_SELF'],'savvy_dispbbs')!==false){
					$rebackinfo=$lang['dispbbs_info_rebacknum'];
				}
				else{
					$rebackinfo=$lang['clsmain.str4'];
				}
				$num=($num>1)? $num-1:0;
				$next= (($i+2)>$realpages)?$realpages:($i+2);
				$multipage .= ($curpage < $pages ? '<a class="page" href="'._urlrewrite($mpurl.$pageparamname.'='.($next).$otherparam).'"><img src="images/pagelist/next.gif"  align="absmiddle" style="margin-top:8px" border="0" alt="'.$lang['clsmain.str2'].'"></a>' : '').
				($to < $pages ? '<a class="page" href="'._urlrewrite($mpurl.$pageparamname.'='.$pages.$otherparam).'"><img src="images/pagelist/last.gif" align="absmiddle" style="margin-top:8px"  border="0" alt="'.$lang['clsmain.str3'].'"></a>' : '').
				($curpage == $maxpages ? '<img src="images/pagelist/last.gif" align="absmiddle" style="margin-top:8px"  border="0" alt=""><!--<a class="page" href="index.php?action=maxpages&pages='.$maxpages.$otherparam.'">&gt;<b>?</b>--></a>' : '').
				($pages > $page ? $get_gotopage.'<b class="page"><input id="GoToPage" type="text" name="GoToPage" size="1" value="'.$curpage.'" /></b><a href="#" class="page"  onclick="return _dv_GotoPage()" >GO</a>' : '');
				$multipage = $multipage ? '<b class="page"><font color="red">'.$num.'</font> / '.$rebackinfo.'</b><b class="page" title="'.$lang['clsmain.str5'].'">'.$curpage.'/'.$realpages.'</b>'.$multipage.'' : '';
			break;
		}

	}
	return $multipage;
}


//论坛知道分页涵数

//信息数/每页数/当前页/URL/当前页信息数/最大页/扩展的URL参数，格式为key1=val1&key2=val2...等等，以此类推
function savvypagelist($num, $perpage, $curpage, $mpurl, $topicnum, $maxpages = 0, $otherparam = '') {
	global $lang;
	$multipage = '';
	$mpurl .= strpos($mpurl, '?') !== false ? '&' : '?';
	if($num > $perpage) {
		$page = 10;
		$offset = 2;

		$realpages = @ceil($num / $perpage);
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;

		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $curpage + $page - $offset - 1;
			if($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if(($to - $from) < $page && ($to - $from) < $pages) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $curpage - $pages + $to;
				$to = $pages;
				if(($to - $from) < $page && ($to - $from) < $pages) {
					$from = $pages - $page + 1;
				}
			}
		}

		if (!is_string($otherparam)) {
			$otherparam = '';
		} elseif ($otherparam{0} !== '&' OR $otherparam{0} !== '&amp;') {
			$otherparam = '&amp;'.$otherparam;
		}
		if (defined('THIS_SCRIPT') AND ('savvy_dispbbs' === THIS_SCRIPT)) {
			$pageparamname = 'star';
		} else {
			$pageparamname = 'page';
		}

		$multipage = ($curpage - $offset > 1 && $pages > $page ? '<td class="tablebody1">&nbsp;<a href="'._urlrewrite($mpurl.$pageparamname.'=1'.$otherparam).'"><img src="images/pagelist/first.gif" border="0"></a>&nbsp;</td>' : '').
		($curpage > 1 ? '<td class="tablebody1">&nbsp;<a href="'._urlrewrite($mpurl.$pageparamname.'='.($curpage - 1).$otherparam).'"><img src="images/pagelist/previous.gif" border="0" alt="'.$lang['clsmain.str2_0'].'"></a>&nbsp;</td>' : '');
		for($i = $from; $i <= $to; $i++) {
			$multipage .= $i == $curpage ? '<td class="tablebody2">&nbsp;<font class="normalTextSmall"><u><b>'.$i.'</b></u></font>&nbsp;</td>' :
			'<td class="tablebody1">&nbsp;<a href="'._urlrewrite($mpurl.$pageparamname.'='.$i.$otherparam).'">'.$i.'</a>&nbsp;</td>';
		}

		$multipage .= ($curpage < $pages ? '<td class="tablebody1">&nbsp;<a href="'._urlrewrite($mpurl.$pageparamname.'='.($curpage + 1).$otherparam).'"><img src="images/pagelist/next.gif" border="0" alt="'.$lang['clsmain.str2'].'"></a>&nbsp;</td>' : '').
		($to < $pages ? '<td class="tablebody1">&nbsp;<a href="'._urlrewrite($mpurl.$pageparamname.'='.$pages.$otherparam).'"><img src="images/pagelist/last.gif" border="0" alt="'.$lang['clsmain.str3'].'"></a>&nbsp;</td>' : '').
		($curpage == $maxpages ? '<td class="tablebody1">&nbsp;<img src="images/pagelist/last.gif" border="0" alt=""><!--<a href="forum_savvy.php?action=maxpages&pages='.$maxpages.$otherparam.'">&gt;<b>?</b>--></a>&nbsp;</td>' : '').
		($pages > $page ? '<td class="tablebody1"><input type="text" name="'.$pageparamname.'" size="1" value="1"><input type="submit" value="GO" name="submit" class="button"></td>' : '');
		$multipage = $multipage ? '<table class="tableborder3" cellpadding="0" cellspacing="1">'.
		'<tr align="center"><td class="tabletitle1" title="'.$lang['clsmain.str4'].'" height=23>&nbsp;'.$num.'&nbsp;</td><td class="tabletitle1" title="'.$lang['clsmain.str5'].'">&nbsp;'.$topicnum.'&nbsp;</td><td class="tabletitle1">&nbsp;'.$curpage.'/'.$realpages.'&nbsp;</td>'.$multipage.'</tr></table>' : '';
	}
	return $multipage;
}

function boardjumplist($inboardid = 0,$defaultTitle=''){
	global $_DCACHE, $lang;
	('' === $defaultTitle) AND ($defaultTitle = $lang['clsmain.str6']);
	$jumplist = '<option value="0">'.$defaultTitle.'</option>';
	if( empty($_DCACHE['all_forums']) ){
		include_once CACHE_PATH.'board/board_all.php';
	}
	if( !empty($_DCACHE['all_forums']) && is_array($_DCACHE['all_forums']) ){
		foreach( $_DCACHE['all_forums'] as $currBoardid => $currForum ){
			$currBoardType = "<option ";
			if( $currBoardid == $inboardid ){
				$currBoardType .= ' selected ';
			}
			$currBoardType .= " value='{$currForum[boardid]}'>";
			if( $currForum['depth'] == 0 ){
				$currBoardType .= $lang['clsmain.str7'];
			} elseif($currForum['depth'] == 1){
				$currBoardType .= "&nbsp;&nbsp;".$lang['clsmain.str8'];
			}
			if( $currForum['depth'] > 1 ){
				for ($i = 2; $i <= $currForum['depth'] ; $i++){
					$currBoardType .= "&nbsp;&nbsp;".$lang['clsmain.str9'];
				}
				$currBoardType .= "&nbsp;&nbsp;".$lang['clsmain.str8'];
			}
			$currBoardType .= "{$currForum[boardtype]}</option>";
			$jumplist .= $currBoardType;
		}
	}
	return $jumplist;
}
function &LoadBoardData($boardid,$useCache=true){
	global $dv,$db;
	if( !is_numeric($boardid) ) $boardid = 0;
	if( $boardid <= 0 ) return null;
	if( $useCache == true ){
		static $arrBoardData = array();
	} else{
		$arrBoardData = array();
	}
	if( !isset($arrBoardData["{$boardid}"]) ){
		if( $query = $db->query("SELECT boardid,boarduser,board_user,isgroupsetting,rootid,board_setting,cid,rules FROM {$dv}board WHERE boardid={$boardid}") ){
			if( $tmpResult = $db->fetch_array($query) ) $arrBoardData["{$boardid}"] =& $tmpResult;
		}
	}
	return $arrBoardData["{$boardid}"];
}//end function LoadBoardData
function Dv_FilterJS($v){
	if( !is_null($v) ){
		$arrPatterns = array( '/ /i' ,'/(&#)/i' ,'/(script)/i' ,'/(js:)/i' ,'/(value)/i' ,'/(about:)/i' ,'/(file:)/i' ,'/(Document.cookie)/i' ,'/(vbs:)/i' ,'/(on(mouse|Exit|error|click|key|load))/i' );
		$arrReplacements = array( '' ,'<I>&#</I>' ,'<I>script</I>' ,'<I>js:</I>' ,'<I>value</I>' ,'<I>about:</I>' ,'<I>file:</I>' ,'<I>Documents.cookie</I>' ,'<I>vbs:</I>' ,'<I>on$2</I>' );
		return htmlspecialchars(preg_replace($arrPatterns,$arrReplacements,$v));
	} else{
		return false;
	}
}//end function Dv_FilterJS
function ChkPost(){
	global $_SERVER;
	if (empty($_SERVER['HTTP_REFERER'])) {
		return false;
	}
	if (7 === strpos($_SERVER['HTTP_REFERER'],$_SERVER['SERVER_NAME']) OR 7 === strpos($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST'])) {
		return true;
	}
	return false;
}
//检查验证码是否正确
function CodeIsTrue(){
	global $_SESSION,$userinfo;
	$getcode = strtolower(trim($GLOBALS['getcode']));
	$_blnReturnVal = false;
	if ('' === $getcode) {
		return $_blnReturnVal;
	}
	@session_start();
	$_blnReturnVal = (strtolower($_SESSION['getcode']) === $getcode OR strtolower($userinfo['getcode']) === $getcode);
	unset($_SESSION['getcode']);
	return $_blnReturnVal;
}//end function CodeIsTrue()
function ipfrom($ip){
	global $ipa0;
	$arrip = explode('.', $ip);
	$ipdatafile = ROOT_PATH.'cache/ipdata/'.$arrip[0].'.txt';
	$ipdatafile0 = ROOT_PATH.'cache/ipdata/0.txt';
	if (!file_exists($ipdatafile)) {
		$ipdatafile = $ipdatafile0;
	}
	if (!file_exists($ipdatafile)) {
		return 'Unknow';
	}
	$filesize = filesize($ipdatafile);
	if ($filesize <= 0) {
		return 'Unknow';
	}
	$ip = implode('.', ipprocess3($arrip));
	$filedata = '';
	$fp = fopen($ipdatafile, 'rb');
	if (!$fp OR !is_resource($fp)) {
		return 'Unknow';
	}
	@flock($fp, LOCK_SH);
	$filedata = fread($fp, $filesize);
	$tmpip1 = "\n{$arrip[0]}.{$arrip[1]}.{$arrip[2]}";
	if ($strpos1 = strpos($filedata, $tmpip1)) {
		if (!($tmpip2 = ipprocess1($fp, $strpos1, $ip))) {
			list($tmpstr1, $tmpip3) = ipprocess2($fp);
		}
	} else {
		$tmpip1 = "\n{$arrip[0]}.{$arrip[1]}";
		if($strpos1 = strpos($filedata, $tmpip1)){
			if (!($tmpip2 = ipprocess1($fp, $strpos1, $ip))) {
				list($tmpstr1, $tmpip3) = ipprocess2($fp);
			}
		} elseif (($strpos1 = strpos($d,"\n{$arrip[0]}")) AND $ipdatafile == $ipdatafile0){
			$tmpip1 = "\n{$arrip[0]}";
			if (!($tmpip2 = ipprocess1($fp, $strpos1, $ip))) {
				list($tmpstr1,$tmpip3) = ipprocess2($fp);
			}
		}else{
			$tmpip2 = 'Unknown';
		}
	}
	if(empty($tmpip2) AND $strpos1 !== false){
		while(ereg("^{$tmpip1}","\n".$tmpstr1)!==false){
			if (1 == $ipa0 OR ($tmpip2 = ipprocess1($fp, $strpos1, $ip, $tmpstr1)) ) {
				break;
			}
			list($tmpstr1, $tmpip4) = ipprocess2($fp);
			if ($tmpip4) {
				$tmpip3 = $tmpip4;
			}
		}
	}
	fclose($fp);
	return ($tmpip2 ? $tmpip2 : $tmpip3);
}

function ipprocess1(&$fp, $arg_s, $ip, $arg_ld = ''){
	global $ipa0;
	if(!$arg_ld){
		fseek($fp, $arg_s+1, SEEK_SET);
		$arg_ld = fgets($fp, 100);
	}
	$ip_a = explode("\t", $arg_ld);
	$ip_a[0] = implode('.', ipprocess3(explode('.', $ip_a[0])));
	$ip_a[1] = implode('.', ipprocess3(explode('.', $ip_a[1])));
	if ($ip < $ip_a[0]) {
		$ipa0 = 1;
	}
	if ($ip >= $ip_a[0] AND $ip <= $ip_a[1]) {
		return $ip_a[2].$ip_a[3];
	}
}
function ipprocess2($fp){
	$fc = fgets($fp, 100);
	$ip_a = explode("\t", $fc);
	return array($fc, $ip_a[2].$ip_a[3]);
}
function ipprocess3($arrip){
	for($i=0; $i <= 3; $i++){
		$arrip[$i] = sprintf("%03d", $arrip[$i]);
	}
	return $arrip;
}
function browser($agent = '')
{
	$expser = $expserver = '';
	if (empty($agent)) {
		$agent = $_SERVER["HTTP_USER_AGENT"];
	}
	$loweragent = strtolower($agent);
	if (false !== strpos($loweragent, 'mozilla')) {
		if (false !== strpos($loweragent, 'msie')) {
			$temp = explode('(', $agent);
			$temp = explode(';', $temp[1]);
			$temp = explode(' ', $temp[1]);
			$expserver = ' '.preg_replace('/([\d\.]+)/', '\\1', $temp[2]);
			$expser = "Internet Explorer";
		} else {
			$temp = explode('(', $agent);
			$temp = explode('/', $temp[0]);
			$expserver = $temp[1];
			$temp = explode(' ', $expserver);
			$expserver = ' '.preg_replace('/([\d\.]+)/', '\\1', $temp[0]);
			if (false !== strpos($loweragent, 'opera')) {
				$expser = 'Opera';
			} elseif (false !== strpos($loweragent, 'netscape')) {
				$expser = 'Netscape';
			} elseif (false !== strpos($loweragent, 'firefox')) {
				$expserver = '';
				$expser = str_replace('/', ' ', substr($agent, strpos($loweragent, 'firefox')));
			} elseif (false !== strpos($loweragent, 'rv:')) {
				$expser = 'rv:';
			} else {
				$expser = 'Netscape Navigator';
			}
		}
	}
	if ($expser != '') {
		$expseinfo = "{$expser}{$expserver}";
	} else {
		$expseinfo = 'Unknown';
	}
	return addslashes(str_filter_xss($expseinfo));
}
//会员操作系统
function sysinfo($agent = '')
{
	$sys = 'Unknown';
	if (empty($agent)) {
		$agent = $_SERVER["HTTP_USER_AGENT"];
	}
	$loweragent = strtolower($agent);
	if (false !== strpos($loweragent, 'win')) {
		$sys = 'Windows ';
		if (false !== strpos($loweragent, 'nt')) {
			if (false !== strpos($loweragent, '5.2')) {
				$sys .= '2003';
			} elseif (false !== strpos($loweragent, '5.1')) {
				$sys .= 'XP';
			} elseif (false !== strpos($loweragent, '5.0')) {
				$sys .= '2000';
			} elseif (false !== strpos($loweragent, '4.0')) {
				$sys .= 'NT';
			}
		} elseif (false !== strpos($loweragent, '98')) {
			$sys .= '98';
		} elseif (false !== strpos($loweragent, '9x') AND false !== strpos($loweragent, '4.90')) {
			$sys .= 'ME';
		} elseif (false !== strpos($loweragent, '95')) {
			$sys .= '95';
		} elseif (false !== strpos($loweragent, '32')) {
			$sys .= '32';
		}
	} else {
		if (false !== strpos($loweragent, 'linux')) {
			$sys = 'Linux';
		} elseif (false !== strpos($loweragent, 'unix')) {
			$sys = 'Unix';
		} elseif (false !== strpos($loweragent, 'ibm') AND false !== strpos($loweragent, 'os')) {
			$sys = 'IBM OS/2';
		} elseif (false !== strpos($loweragent, 'netbsd')) {
			$sys = 'NetBSD';
		} elseif (false !== strpos($loweragent, 'bsd')) {
			$sys = 'BSD';
		} elseif (false !== strpos($loweragent, 'freebsd')) {
			$sys = 'FreeBSD';
		}
	}
	return addslashes($sys);
}
function IsWebSearch(){
	static $iswebsearch;
	if (!isset($iswebsearch)) {
		$useragent = strtolower($_SERVER["HTTP_USER_AGENT"]);
		$searchs = array('google','isaac','surveybot','baiduspider','yahoo','yisou','3721','qihoo','daqi','ia_archiver','p.arthur','fast-webcrawler','java','microsoft-atl-native','turnitinbot','webgather','sleipnir','msn');
		foreach( $searchs as $val ){
			if( strpos($useragent,$val) !== false ){
				$iswebsearch = true;
				return $iswebsearch;
			}
		}
		$iswebsearch = false;
	}
	return $iswebsearch;
}
function UpdateUserInfoById($userID,$arrFld=array(),$useEscape=true){//$arrFld=array('filedName'=>'fieldValue')
	if( !is_numeric($userID) ){
		return false;
	}
	if( empty($arrFld) || !is_array($arrFld) ){
		return false;
	}
	global $db,$dv;
	$comma = '';
	$SetList = '';
	foreach( $arrFld as $fldName => $fldVal ){
		$SetList .= "{$comma}{$fldName}='".($useEscape===true?$db->escape_string($fldVal):$fldVal)."'";
		$comma = ',';
	}
	if(	$SetList !== '' ){
		if( $db->query("UPDATE {$dv}user SET {$SetList} WHERE userid='{$userID}'") ){
			return true;
		}
	}
	return false;
}
function UpdateUserInfoByName($userName,$arrFld=array(),$useEscape=true){//$arrFld=array('filedName'=>'fieldValue')
	if( empty($userName) ){
		return false;
	}
	if( empty($arrFld) || !is_array($arrFld) ){
		return false;
	}
	global $db,$dv;
	$comma = '';
	$SetList = '';
	foreach( $arrFld as $fldName => $fldVal ){
		$SetList .= "{$comma}{$fldName}='".($useEscape===true?$db->escape_string($fldVal):$fldVal)."'";
		$comma = ',';
	}
	if(	$SetList !== '' ){
		if( $db->query("UPDATE {$dv}user SET {$SetList} WHERE username='{$userName}'") ){
			return true;
		}
	}
	return false;
}
function masterpoint() {
	global $action,$dv,$db,$userid,$username,$usergroupid,$boardid,$userclass;
	$action_str=$_GET['action'];
	$boardid=$_GET['boardid'];
	$dateid=intval(str_replace('-','',date('Y-m-d')));
	$nowtime=time();
	$url=$_SERVER['QUERY_STRING'];
	if($userid>0 && $boardid>0){
		if($usergroupid==1 or $usergroupid==2 or $usergroupid==3 or $usergroupid==35){
			$usertopicwealth=0;
			$userpostwealth=0;
			if($action_str=='snew' or $action_str=='svote' or strpos($url,'savepost.php?action=argue_topic')!==false){
				$usertopicwealth=$db->scalar("select topicwealth from {$dv}masterpointboard where boardid={$boardid}");
				$manage_actions=1;
				$userposttodaydate=$db->scalar("select dateid from {$dv}masterpoint where userid={$userid} and dateid={$dateid}");
				if($userposttodaydate==$dateid){
					$db->query("update {$dv}masterpoint set pageview=pageview+1,usertopic=usertopic+{$usertopicwealth},userpost=userpost+{$userpostwealth},manageactions=manageactions+{$manage_actions} where dateid={$userposttodaydate} and userid={$userid}");
				}
				else{
					$sql=$db->query("select username,userclass from {$dv}user where userid={$userid}");
					$arr=$db->fetch_array($sql);
					$userclass=$arr['userclass'];
					$username=$arr['username'];
					$db->query("insert into {$dv}masterpoint (userid,username,usergroupid,userclass,pageview,usertopic,userpost,manageactions,otherpoint,dateid,addtime) values ({$userid},'{$username}',{$usergroupid},'{$userclass}',1,{$usertopicwealth},{$userpostwealth},{$manage_actions},0,{$dateid},{$nowtime})");
				}
			}
			elseif($action_str=='sre' or strpos($url,'savepost.php?action=argue_reply')!==false){
				$userpostwealth=intval($db->scalar("select postwealth from {$dv}masterpointboard where boardid={$boardid}"));
				$manage_actions=1;
				$userposttodaydate=$db->scalar("select dateid from {$dv}masterpoint where userid={$userid} and dateid={$dateid}");
				if($userposttodaydate==$dateid){
					$db->query("update {$dv}masterpoint set pageview=pageview+1,usertopic=usertopic+{$usertopicwealth},userpost=userpost+{$userpostwealth},manageactions=manageactions+{$manage_actions} where dateid={$userposttodaydate} and userid={$userid}");
				}
				else{
					$sql=$db->query("select username,userclass from {$dv}user where userid={$userid}");
					$arr=$db->fetch_array($sql);
					$userclass=$arr['userclass'];
					$username=$arr['username'];
					$db->query("insert into {$dv}masterpoint (userid,username,usergroupid,userclass,pageview,usertopic,userpost,manageactions,otherpoint,dateid,addtime) values ({$userid},'{$username}',{$usergroupid},'{$userclass}',1,{$usertopicwealth},{$userpostwealth},{$manage_actions},0,{$dateid},{$nowtime})");
				}
			}
			else{
				$userposttodaydate=$db->scalar("select dateid from {$dv}masterpoint where userid={$userid} and dateid={$dateid}");
				if($userposttodaydate==$dateid){
					$db->query("update {$dv}masterpoint set pageview=pageview+1 where dateid={$userposttodaydate} and userid={$userid}");
				}
				else{
					$sql=$db->query("select username,userclass from {$dv}user where userid={$userid}");
					$arr=$db->fetch_array($sql);
					$userclass=$arr['userclass'];
					$username=$arr['username'];
					$db->query("insert into {$dv}masterpoint (userid,username,usergroupid,userclass,pageview,usertopic,userpost,manageactions,otherpoint,dateid,addtime) values ({$userid},'{$username}',{$usergroupid},'{$userclass}',1,0,0,0,0,{$dateid},{$nowtime})");
				}
			}
		}
	}
}

function func_script($content) {
	$content= htmlspecialchars($content);
	$content= html_entity_decode($content);
	$content= preg_replace("'<script[^>]*?>.*?</script>'si", "", $content);
	return $content;
}

function SetWordColor($color,$word,$str)
{
	if($color=='' || $color=='0')
	return $str;
	else
	{
		$repWord= "<font color='".$color."'>".$word."</font>";
		$str= str_replace($word,$repWord,$str);
		return $str;
	}
}

function LoadStyleJs(){
	global $imgurl,$styleurl,$pagecharset,$title,$forum_keyword,$fsetting;
	if(THIS_SCRIPT=='post') {
		header('Content-Type:text/html;charset=UTF-8');
		ob_start();
		$pagecharset='UTF-8';
	}else{
		echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	<html xml:lang="zh-CN" lang="zh-CN" xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset='.$pagecharset.'" />
	<title>'.$title.$forum_keyword.'</title>
	<meta name="generator" content="dvbbs" />
	<meta name="keywords" content="'.$fsetting[keyword].'" />
	<meta name="description" content="'.$fsetting[description].'" />
	<meta name="MSSmartTagsPreventParsing" content="TRUE" />
	<meta http-equiv="MSThemeCompatible" content="Yes" />
	<link rel="stylesheet" type="text/css" href="'.$styleurl.'" />
	<script LANGUAGE="JavaScript">var imgpath = "'.$imgurl.'"</script>
	<script src="templates/lang/'.$fsetting["lang"].'/js/main_new.js" type="text/javascript"></script>
	<script src="templates/lang/'.$fsetting["lang"].'/js/main.js" type="text/javascript"></script>
	<script src="templates/lang/'.$fsetting["lang"].'/js/tab.js" type="text/javascript"></script>
	

	</head>
	<body >';}
}



function LoadFooter(){
	echo '</body>
</html>';
}

function ajax_encoding(){
	global $getcon,$db_obstart;
	$getcon = (empty($getcon)) ? ob_get_contents() : $getcon;
	$getcon = str_replace(array('<!--<!---->','<!---->'),array('',''),$getcon);
	
	if (!isset($db_obstart)) {
		$db_obstart = function_exists('ob_gzhandler') ? 1 : 0;
	}
	$db_obstart == 1 ? ob_start('ob_gzhandler') : ob_start();
	ajax_UTFANDGB($getcon,"GB2312");
	ob_end_clean();
	echo $outcon;exit;
}
function ajax_UTFANDGB($s,$to_GB,$from_U='UTF-8'){
	
	if (function_exists('mb_convert_encoding')) {
		$outcon=mb_convert_encoding($s,"{$to_GB}","{$from_U}");//gbk to utf
	}elseif (function_exists('iconv')){
		$outcon=iconv("{$from_U}","{$to_GB}",$s);
	}else{
		return $s;
	}
	return $outcon;
}

function ajax_UtfToGbk($s,$to_GB,$from_U='UTF-8'){
   
	if (function_exists('mb_convert_encoding')) {
		$outcon=mb_convert_encoding($s,"{$from_U}","{$to_GB}"); //utf to gbk
	}elseif (function_exists('iconv')){
		$outcon=iconv("{$to_GB}","{$from_U}",$s);
	}else{
		return $s;
	}
	return $outcon;
}
function encoding_footer(){
	global $charset,$db_obstart,$_POST;
	$output = ob_get_contents();
	$output = str_replace(array('<!--<!---->','<!---->'),array('',''),ob_get_contents());

	if($_POST['base64encode']||$_GET['base64encode']){
		$output=base64_encode($output);
		//exit;
	}elseif($charset!='utf-8'){
		$output = ajax_UTFANDGB($output,'utf-8',$charset);
	}
	ob_end_clean();
	$db_obstart == 1 && function_exists('ob_gzhandler') ? ob_start('ob_gzhandler') : ob_start();
	echo $output."";exit;

}

function str_r($s){
	$s = str_replace('&amp;','&',$s);
	$s = str_replace('&nbsp;',' ',$s);
	$s = str_replace('"','&quot;',$s);
	$s = str_replace("'",'&#39;',$s);
	$s = str_replace("<","&lt;",$s);
	$s = str_replace(">","&gt;",$s);
	$s = str_replace("\t","&nbsp; &nbsp; ",$s);
	$s = str_replace("\r","",$s);
	$s = str_replace("  ","&nbsp; ",$s);
	return $s;
}

function getFromValue($n , $m='P'){
	global $gb_charset, $_POST,$_GET;
	!is_array($n) && $n = array($n);
	$errchar_space=array("\xC2\xA0","\x3F\x20");


	foreach($n as $v)
	{
		$GLOBALS[$v] = NULL;
		if ( $m =='P' && isset($_POST[$v]) )
		{
			$GLOBALS[$v] = $_POST[$v];
		} 
		elseif($m =='G' && isset($_GET[$v]) )
		{
			$GLOBALS[$v] = $_GET[$v];
		}
        $GLOBALS[$v]=str_replace($errchar_space,array(' ',' '),$GLOBALS[$v]);

		if(!$_POST['base64encode'] AND !$_GET['base64encode']){
			$GLOBALS[$v]= ajax_UTFANDGB($GLOBALS[$v],$gb_charset);
		}
		
	}
}//1快速回复 2快速回复  3快速回复 4快速回复


function Return_Userdono(){
	global $db,$dv,$lang,$userid,$savvy_board;
	require_once CACHE_PATH.'savvy_board.php';
	$nodone=$db->scalar("select count(1) from {$dv}savvy_topic where postuserid={$userid} and solve=0");
	$askcountvalue=(empty($savvy_board['boardkey']['askcount']))? 3:$savvy_board['boardkey']['askcount'];
	if($nodone>=$askcountvalue){
		return true;//true
	}
	else{
		return false;//false
	}
}
//=============================start dispbbs function==========================================================

function honortitle($h_pic) {
	global $dv,$db;
	$htitle=$db->scalar("select honorname from {$dv}honor_list where honorpic='{$h_pic}'");
	return $htitle;
}
function Topic_Ads(){
	global $fsetting;
	return $fsetting['forumad_topic_text'][(count($fsetting['forumad_topic_text'])-1)*rand()];
}//end function Topic_Ads

function php_cCur($var){
	return number_format($var,4,'.','');
}//end function php_cCur

function &getCurrUserGrpSettings($userGroupId)
{
	static $st_cache = array();
	if (!is_numeric($userGroupId) OR $userGroupId <= 0) {
		return $st_cache;
	}
	if (!isset($st_cache[$userGroupId])) {
		$st_cache[$userGroupId] = array();
		$cache_file = CACHE_PATH.'group/group_'.$userGroupId.'.php';
		if (@is_file($cache_file) AND include($cache_file)) {
			$st_cache[$userGroupId] =& $groupsetting;
		}
	}
	return $st_cache[$userGroupId];
}//end function getCurrUserGrpSettings

function canusersign($GroupID){
	global $groupsetting, $fsetting;
	if( !is_numeric($GroupID) ) return false;
	static $cache = array();
	if( empty($cache["{$GroupID}"]) ){
		$cache["{$GroupID}"] = false;
		if (1 == $fsetting['usersign']) {
			$cache["{$GroupID}"] = true;
		} else {
			require_once CACHE_PATH.'group/group_'.$GroupID.'.php';
			if (1 == $groupsetting[55]) {
				$cache["{$GroupID}"] = true;
			}
		}
	}
	return $cache["{$GroupID}"];
}//end function canusersign

//=============================end dispbbs function==========================================================


#标题颜色 
function ShowCodeTitle ($TopicMode,$TopicFont,$list=0){

	$colorstr = array('','','red','blue','green');
	$fontstr = array('7'=>'font-weight:bold;','8'=>'font-style:italic;','9'=>'text-decoration:underline;');
	$TopicMode = intval($TopicMode);
	$TopicFont = trim($TopicFont);

	if( intval($TopicMode) > 1) {
		$TopicMode_Code = ' color:' .$colorstr[$TopicMode]. ';';
	}else{
		$TopicMode_Code = '';
	}
	$arrfontstr = explode('|',$TopicFont);
	$TopicFont_Code='';
	if (!empty($arrfontstr[0])) foreach ( $arrfontstr as $v) $TopicFont_Code .= $fontstr[$v];

	$styletitle = (!empty($TopicMode_Code) or !empty($TopicFont_Code)) ? 'style="' .$TopicMode_Code.$TopicFont_Code.'"':'';
	return $styletitle;
} #ShowCodeTitle end
?>