<?php
define('THIS_SCRIPT', 'savepost');
if(isset($_POST['base64encode'])&&$_POST['base64encode']==1){
   foreach ($_POST as $k=>$v){
	  if($k=='base64encode')continue;
	  $_POST[$k]=base64_decode(str_replace(array(',','_'),array('=','+'),$v));
   }
}

if(isset($_GET['base64encode'])&&$_GET['base64encode']==1){
   foreach ($_GET as $k=>$v){
	  if($k=='base64encode')continue;
	  $_GET[$k]=base64_decode(str_replace(array(',','_'),array('=','+'),$v));
   }
}	

require 'global.php';
require INC_PATH.'dv_code.php';
require_once INC_PATH.'FileHandler.class.php';
require_once INC_PATH.'image_misc.functions.php';
require_once CACHE_PATH.'savvy_board.php';
ini_set('display_errors','0');
ini_set('track_errors','1');
$lang = load_lang($lang, 'savepost' );
$ft_settings = explode('|', $fsetting['ft_settings']);	//	全文检索配置信息
$ajax_action = (false!==strpos($_GET['action'],'sre') and ($_GET[method]!='Topic')) ? 'sre' : '' ; 
$gb_charset = 'GB2312';//echo ajax_UTFANDGB(str_r($_POST['body']),$gb_charset);

function check_ajax(){
	global $ajax_action;
	if ($ajax_action=='sre'){		
		return true;
	}else{
		return false;
	}
}

if (check_ajax()){
	header('Content-Type: text/html;charset=UTF-8');
	if(!function_exists('mb_convert_encoding') and !function_exists('iconv') and !$_POST['base64encode'] and !$_GET['base64encode']){
		echo 'your Navigator no support,please change the ieplore'."@@@0@@@";exit;
	}

}

if( ( $master === false || $boardmaster === false ) && $boardinfo['allowpost'] == 2 ){
	$stats = $lang['Error.strings1'];
	$arrNavMenu = array( 'linktitle' => $lang['Error.strings1'] );
	if (check_ajax()){
		echo $lang['Error.strings1']."@@@0@@@";encoding_footer();
	}else{
		head(0,1,0,$arrNavMenu);
		showmsg($lang['Error.strings1']);	
	}
	exit;
}
if( $boardinfo['allowpost'] == 0 ){
	$stats = $lang['Error.strings2_1'];
	$arrNavMenu = array( 'linktitle' => $lang['Error.strings2_1'] );
	if (check_ajax()){
		echo $lang['Error.strings2_1']."@@@0@@@";encoding_footer();
	}else{
		head(0,1,0,$arrNavMenu);
		showmsg($lang['Error.strings2_1']);
	}
	exit;
}

if( $master === false && IsReadonly() ){
	$stats = $lang['Error.strings2'];
	$arrNavMenu = array( 'linktitle' => $lang['Error.strings2']);
	if (check_ajax()){
		echo $lang['Error.strings2']."@@@0@@@";encoding_footer();
	}else{
		head(0,1,0,$arrNavMenu);
		showmsg($lang['Error.strings2']);
	}
	exit;
}


$ActionName = $lang['ActionName_'.$GLOBALS['action']];
if( $ActionName == '' ){
	$ActionName = $lang['template.strings0'];
}
$gettitle = $ActionName;
$stats = $ActionName. '' .$boardinfo['boardtype'];

if (!check_ajax()){
	head(1,1,0,$arrNavMenu);
}

ArgumentationMain();	//	辩论相关处理

if( empty($totalusetable) ){
	$totalusetable = $fsetting['nowtablename'];
}

switch($GLOBALS['action']){
	case 'snew':
		if( $groupsetting[3] == 0 ){
			head();
			showmsg($lang['Error.strings70']);
			exit;
		}
		break;
	case 'sre':
		if( $groupsetting[5] == 0 ){
			echo $lang['Error.strings71']."@@@0@@@";encoding_footer();
			exit;
		}
		break;
	case 'svote':
		if( $groupsetting[8] == 0 ){
			head();
			showmsg($lang['Error.strings56']);
			exit;
		}
		break;
	case 'sedit':
		break;
	default:
		break;
}


Chk_Post();
CheckfromScript();

$topic = trim($topic);
if( Dv_StrLength($topic) > $board_settings[47] ){
	if (check_ajax()){
		echo str_replace('{$topiclimited}',$board_settings[47],$lang['template.strings23'])."@@@0@@@";encoding_footer();
	}else{
		head();
		showmsg(str_replace('{$topiclimited}',$board_settings[47],$lang['template.strings23']));
	}	
	exit;
}

if( $action == 'snew' || $action == 'svote' || $action == 'active_topic'){
 if( str_replace('','',$topic) === '' ){
  head();
  showmsg($lang['Error.strings20']);
  exit;
 }
}
$IsAudit = NeedIsAudit();

$Reuser = false;
$FoundUseMagic = false;

if( $board_settings[46] == 1 ){
	if( CodeIsTrue() !== true ){		
		if (check_ajax()){
			$retvalue=($boardsettings46>1?3:0);
			echo $lang['Error.strings5']."@@@{$retvalue}@@@".get_cercode()."@@@";encoding_footer();
		}else{
		head();
		showmsg($lang['Error.strings5']);
		}		
		exit;
	}
}

Chk_PostType();
checkmagicface();

if( $userid <= 0 ){
	$mailflag = 0;
	$signflag = 0;
} else{
	$signflag = intval(trim($signflag));
	$mailflag = intval(trim($emailflag));
}
$MyTopicMode = trim($topicximoo);
$MyTopicFont = (trim($topicfont) != '')?$topicfont:'0';

$MyLockTopic = trim($locktopic);
$MyIsTop = trim($istop);
$MyIstopAll = trim($istopall);
$topicmode = intval(trim($topicmode));

$GLOBALS['body']= str_replace('<embed></embed>','',$GLOBALS['body']);
//检查帖子内容
$Content =& CheckAlipay();
$isAlipayTopic = 2;
if( $Content == '' ){
	$Content =& $GLOBALS['body'];	
	$isAlipayTopic = 0;
}
$contentLength = strlen($Content);
if( $contentLength > $board_settings[49] ){
	if (check_ajax()){
		echo str_replace('{$bodylimited}',$board_settings[49],$lang['template.strings24'])."@@@1@@@";encoding_footer();
	}else{
	head();
	showmsg(str_replace('{$bodylimited}',$board_settings[49],$lang['template.strings24']));
	}
	exit;
}
if( $board_settings[94] != 0  && $contentLength < $board_settings[94] ){
	if (check_ajax()){
		echo str_replace('{$bodylimited}',$board_settings[94],$lang['template.strings25'])."@@@1@@@";encoding_footer();
	}else{
	head();
	showmsg(str_replace('{$bodylimited}',$board_settings[94],$lang['template.strings25']));
	}
	exit;
}
if( preg_match('/^(?:\s|(?:&nbsp;))+$/im',str_replace("\r\n","",$Content)) === 1 ){
	if (check_ajax()){
		echo $lang['Error.strings19']."@@@0@@@";encoding_footer();
	}else{
	head();
	showmsg($lang['Error.strings19']);
	}
	exit;
}
if( strpos($Content,'[/payto]') !== false && strpos($Content,'[payto]') !== false && strpos($Content,'(/seller)') !== false && strpos($Content,'(seller)') !== false ){
	$isAlipayTopic = 2;
}

$voteid = 0;
$isvote = 0;

$activeid = 0;
if( $action =='active_topic'){
 $activesubject = trim($_POST['activesubject']);
 $activiecity = trim($_POST['activiecity']);
 $activieclass = trim($_POST['activieclass']);
 $starttime = trim(strtotime($_POST['startall']));
 $endtime = trim(strtotime($_POST['end']));
 $activieplace = trim($_POST['activieplace']);
 $cost = intval(trim($_POST['cost']));
 $sex = trim($_POST['gender']);
 $strength = intval(trim($_POST['strength']));
 $expiretime = trim(strtotime($_POST['alltime']));
 $timemode = trim($_POST['timemode']);
 if($timemode == 0)
 $endtime = 0;
 if($activesubject=='' || strlen($activesubject) > 200){
  head();
  showmsg($lang['tpl_Active.str1']);
  exit;
 }
 if($activiecity=='' || strlen($activiecity) > 50){
  head();
  showmsg($lang['tpl_Active.str2']);
  exit;
 }
 if(!is_numeric($strength)||$strength==0){
  head();
  showmsg($lang['tpl_Active.str3']);
  exit;
 }
 if(!eregi('^[0-9]+$',$expiretime)){
  head();
  showmsg($lang['tpl_Active.str4']);
  exit;
 }

 if(!is_numeric($cost)){
  head();
  showmsg($lang['tpl_Active.str5']);
  exit;
 }
 if($activieplace==''){
  head();
  showmsg($lang['tpl_Active.str6']);
  exit;
 }
 if(!is_numeric($timemode)){
  head();
  showmsg($lang['tpl_Active.str7']);
  exit;
 }
}

if( $action == 'svote' ){
	$vote = trim(str_replace('|', '', $vote));
	if( $vote === '' ){
		head();
		showmsg($lang['Error.strings81']);
		exit;
	}
	if( !is_numeric($votetimeout) ){
		head();
		showmsg($lang['Error.strings82']);
		exit;
	}
	$votetype = intval($votetype);
	$vote = explode("\r\n", $vote);
	$vote_1 = '';
	$votenum = '';
	if( is_array($vote) ){
		$j = 0;
		$count = count($vote);
		$separator = '';
		foreach ($vote AS $index => $val) {
			$val = trim($val);
			if ($val !== '') {
				$vote_1 .= $separator.htmlspecialchars($val);
				$separator = '|';
				$j++;
			}
			if( $j > intval($board_settings[54]) - 1){
				break;
			}
		}//end foreach
		$separator = '';
		for( $k = 1 ; $k <= $j ; $k++ ){
			$votenum .= "{$separator}0";
			$separator = '|';
		}
	}
	$votelen = strlen($vote_1);
	$votenumlen = strlen($votenum);
	$vote = $vote_1;
	if( $votetimeout == '0' ){
		$votetimeout = dateAdd('d', 9999, TIME_NOW);
	} else{
		$votetimeout = dateAdd('d', intval($votetimeout), TIME_NOW);
	}
	$votetimeout = strtotime($votetimeout);
}
if( $action == 'snew' || $action == 'svote' || $action == 'active_topic'){
	$CanLockTopic = false;
	$CanTopTopic = false;
	$CanTopTopic_a = false;
	if( $MyLockTopic == 'yes' || $MyIstopAll == 'yes' || $MyIsTop == 'yes' ){
		if( $master === true || $superboardmaster === true || $boardmaster === true ){
			if( $groupsetting[21] == 1 ){
				$CanTopTopic = true;
			}
			if( $groupsetting[20] == 1 ){
				$CanLockTopic = true;
			}
		}
		if( $usergroupid > 3 && $groupsetting[21] == 1 ){
			$CanTopTopic = true;
		}
		if( $founduserper === true  ){
			if( $groupsetting[21] == 1 ){
				$CanTopTopic = true;
			} elseif( $groupsetting[21] == 0 ){
				$CanTopTopic = false;
			}
		}
		if( ($master === true || $superboardmaster === true || $boardmaster === true) && $groupsetting[38] == 1 ){
			$CanTopTopic_a = true;
		}
		if( $usergroupid > 3 && $groupsetting[38] == 1 ){
			$CanTopTopic_a = true;
		}
		if( $founduserper === true ){
			if( $groupsetting[38] == 1 ){
				$CanTopTopic_a = true;
			} elseif( $groupsetting[38] == 0 ){
				$CanTopTopic_a = false;
			}
		}
	}
	if( $MyLockTopic == 'yes' ){
		$MyLockTopic = 1;
	} else{
		$MyLockTopic = 0;
	}
	if( $MyIstopAll == 'yes' ){
		$MyIstopAll = 1;
	} else{
		$MyIstopAll = 0;
	}
	if( $CanTopTopic_a !== true ){
		$MyIstopAll = 0;
	}
	if( $MyIsTop == 'yes' && $MyIstopAll == 0 ){
		$MyIsTop = 1;
		if( $CanTopTopic !== true ){
			$MyIsTop = 0;
		}
	} elseif( $MyIstopAll == 1 ){
		$MyIsTop = 3;
	} else{
		$MyIsTop = 0;
	}
	if( !is_numeric($MyTopicMode) || $groupsetting[51] == '0' ){
		$MyTopicMode = 0;
	}
	if( $CanLockTopic === false ){
		$MyLockTopic = 0;
	}
	$totalusetable = $fsetting['nowtablename'];
} elseif( $action == 'sre' ){
	$AnnounceID = $followup;
	$RootID = $rootid;
	if (!is_numeric($AnnounceID) OR !is_numeric($RootID)) {
		if (check_ajax()){
			echo $lang['Error.strings30']."@@@0@@@";encoding_footer();
		}else{
		head();
		showmsg($lang['Error.strings30']);
		}
		exit;
	}
	$ParentID = $AnnounceID;
	$MyLockTopic = 0;
} elseif( $action == 'sedit' ){
	if( !is_numeric($MyTopicMode) || $groupsetting[51] == 0 ){
		$MyTopicMode = 0;
	}
	$AnnounceID = $replyid;
	if( !is_numeric($AnnounceID) ){
		head();
		showmsg($lang['Error.strings30']);
		exit;
	}
	$RootID = $id;
	if( !is_numeric($RootID) ){
		head();
		showmsg($lang['Error.strings30']);
		exit;
	}
	$MyLockTopic = 0;
	$tmpAnnounceID = intval($db->scalar("SELECT announceid FROM ".$db->escape_string(strtolower($totalusetable))." WHERE parentid=0 AND rootid={$RootID}"));
	if( $tmpAnnounceID <= 0 ){
		head();
		showmsg($lang['Error.strings30']);
		exit;
	} elseif( $tmpAnnounceID == $AnnounceID ){
		if( $topic == '' || str_replace($lang['template.strings34'],'',$topic) == '' ){
		head();
		showmsg($lang['Error.strings79']);
		exit;
		}
	}
}


//保存数据
if( $master === false || $action != 'sedit' ){
	//判断发帖时间间隔
	if( $board_settings[52] == 1 ){
		$posttime = get_cookie('posttime');
		if( isDate($posttime) ){
			if( dateDiff('s', $posttime, gmdate('Y-m-d H:i:s')) < intval($board_settings[53]) ){
				if (check_ajax()){
					echo str_replace('{$PostTimes}',$board_settings[53],$lang['template.strings33'])."@@@0@@@";encoding_footer();
				}else{
				head();
				showmsg(str_replace('{$PostTimes}',$board_settings[53],$lang['template.strings33']));
				}
				exit;
			}
		}
		set_cookie('posttime', gmdate('Y-m-d H:i:s'), $user_selected_cookiedate);
	}
}

$userinfo['postdata'] = '';
if( $groupsetting[64] == 1 ){ //在审核模式下可直接发帖而不需经过审核
	$IsAudit = 0;
} else{
	if( $board_settings[57] == 1 ){
		$IsAudit = 0;
		$IsAudit = NeedIsAudit();
	}
}
if( $userid <= 0 and $groupsetting[3]==0 ){
	$IsAudit = 1;
	$IsAuditcheck = 2;
}

$locktopic = 0;
if( $MyLockTopic == 1 ){
	$locktopic = 1;
}
if( $IsAudit == 1 && $action != 'sedit' ){
	$locktopic = $boardid;
	$boardid = 777;
	set_cookie('dvbbs',$locktopic, $user_selected_cookiedate);
} else{
	set_cookie('dvbbs',$boardid, $user_selected_cookiedate);
}

$Forumupload = explode('|',$board_settings[51]);
if( is_array($Forumupload) ){
	foreach( $Forumupload as $val ){
		if( strpos($Content,'[upload='.$val.']') !== false || strpos($Content,'.'.$val) !== false || strpos($Content,'['.$val.']') !== false ){
				$uploadpic_n = $val;
				break;
		}
	}
}

if( strpos($Content,'viewfile.php?id=') !== false ){
	$uploadpic_n = 'down';
}

if( $action != 'sedit' ){
	savepost();
	
	if( $userid > 0 ){
		//更新用户积分，所需外部变量,UserPost,userid,（外加发帖回帖的积分设置数据）
		updatepostuser();
	}else{	
		$Forum_guest_info_File_url = CACHE_PATH.'Forum_guest_info_File.php';
		if (file_exists($Forum_guest_info_File_url))
		{
			include_once $Forum_guest_info_File_url;
			$arrguest_info = $Forum_guest_info['guesttoday'];			
			$userinfo['usertoday'] = $arrguest_info[0];
			
			if( $userinfo['usertoday'] == '' ){
				$arrUserToday = array(0,0,0,0,0);
			} else{
				$arrUserToday = explode('|',$userinfo['usertoday']);
			}
			if ($arrguest_info[1] == strtotime(date("Y-m-d")))
			{
				require_once INC_PATH.'BoardCache.class.php';
				Create_Forum_guest_info($arrguest_info);
			}	
		}
	}
} else{
	Update_Edit_Announce();
}

if( $groupsetting[59] == 1 ){
	if( ($action == 'snew' || $action == 'svote'|| $action == 'active_topic') && ($getposttype == 1 || $getposttype == 2) ){
	} elseif( $action == 'sre' && $getposttype == 1 && $getmoneytype == 4 ){
		GetMoney_SaveRe();
	}
}

succeed();
if(intval($fsetting['forum_put_revert'])==0){
	footer();//edit 2007-04-19
}
//魔法表情检查部分
function checkmagicface() {
	global $db, $dv, $fsetting, $userinfo, $tmagicface, $imagicface, $expression, $tmagicmoney, $tmagicticket, $FoundUseMagic;
	$tmagicface = intval($tmagicface);
	$imagicface = intval($imagicface);
	if( $expression == '' ){
		$expression = 'face1';
	} else{
		$expression = str_replace('|','',$expression);
	}
	if( $tmagicface == 1 && $imagicface > 0 && $fsetting['plus_magicface'] == 1 ){
		if( $query = $db->query("SELECT tmoney,tticket,magicsetting FROM {$dv}plus_tools_magicface WHERE magicface_s={$imagicface} ") ){
			$tmpResult = $db->fetch_row($query);
		}
		if( empty($tmpResult) ){
			$expression = "0|{$expression}";
			$tmagicmoney = 0;
			$tmagicticket = 0;
		} else{
			if( php_cCur($userinfo['userticket']) < $tmpResult[1] && php_cCur($userinfo['usermoney']) < $tmpResult[0] ){
				head();
				showmsg($lang['Error.strings9']);
				exit;
			}
			$iMagicSetting = explode('|',$tmpResult[2]);
			if( php_cCur($iMagicSetting[0]) > php_cCur($userinfo['userpost']) ){
				head();
				showmsg($lang['Error.strings10']);
				exit;
			}
			if( php_cCur($iMagicSetting[1]) > php_cCur($userinfo['userwealth']) ){
				head();
				showmsg($lang['Error.strings11']);
				exit;
			}
			if( php_cCur($iMagicSetting[2]) > php_cCur($userinfo['userep']) ){
				head();
				showmsg($lang['Error.strings13']);
				exit;
			}
			if( php_cCur($iMagicSetting[3]) > php_cCur($userinfo['usercp']) ){
				head();
				showmsg($lang['Error.strings14']);
				exit;
			}
			if( php_cCur($iMagicSetting[4]) > php_cCur($userinfo['userpower']) ){
				head();
				showmsg($lang['Error.strings15']);
				exit;
			}
			$expression = $imagicface.'|'.$expression;
			$tmagicmoney = $tmpResult[0];
			$tmagicticket = $tmpResult[1];
			$FoundUseMagic = True;
			unset($tmpResult);
		}
	} else {
		$expression = "0|{$expression}";
	}
	$expression = explode('|',$expression);
}//end function checkmagicface
//通用判断
function Chk_Post(){
	global $ajax_action,$lang,$board_settings,$groupsetting,$userid,$userinfo,$boardinfo;
	$FormID = trim($_POST['dvbbs']);
	
	if ('' === $FormID) {
		$FormID = get_cookie('dvbbs');
		set_cookie('dvbbs', '', $GLOBALS['user_selected_cookiedate']);
	}
	if( CheckFormID($FormID) === false ){
		if (check_ajax()){
			echo $lang['Error.strings4']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['Error.strings4']);
		}	
		exit;
	}
	if( $boardinfo['allowpost'] == 0 ){
		if (check_ajax()){
			echo $lang['Error.strings72']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['Error.strings72']);
		}	
		exit;
	}
	if( $boardinfo['ishidden'] == 1 && $groupsetting[37] == 0 ){
		if (check_ajax()){
			echo $lang['Error.strings72']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['Error.strings26']);
		}	
		exit;
	}

	if( $userid >= 0 ){
		$grp52 = intval($groupsetting[52]);
		if( ($grp52 > 0) && (dateDiff('s',$userinfo['joindate'],TIME_NOW) < $grp52*60) ){
			if (check_ajax()){
				echo str_replace('{$timelimited}',$grp52,$lang['template.strings21'])."@@@1@@@";encoding_footer();
			}else{
				head();
				showmsg(str_replace('{$timelimited}',$grp52,$lang['template.strings21']));
			}	
			exit;
		}
		if( $groupsetting[62] != 0 && $GLOBALS['action'] != 'sedit' ){
			if( $userid <= 0 ){
				$UserToday = 0;
			} else{
				if( $userinfo['usertoday'] == '' ){
					$arrUserToday = array(0,0,0,0,0);
				} else{
					$arrUserToday = explode('|',$userinfo['usertoday']);
				}
				$UserToday = intval($arrUserToday[0]);//Dvbbs.UserToday(0)
			}
			if( $groupsetting[62] <= $UserToday ){
				if (check_ajax()){
					echo str_replace('{$topiclimited}',$groupsetting[62],$lang['template.strings27'])."@@@0@@@";encoding_footer();
				}else{
					head();
					showmsg(str_replace('{$topiclimited}',$groupsetting[62],$lang['template.strings27']));
				}	
				exit;
			}
		}
	}
	if( $groupsetting[3] == 0 && ($GLOBALS['action'] == 'snew' || $GLOBALS['action'] == 'svote' || $GLOBALS['action'] == 'active_topic') ){
		if (check_ajax()){
			echo $lang['Error.strings28']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['Error.strings28']);
		}	
		exit;
	}
	if( $groupsetting[5] == 0 && $GLOBALS['action'] == 'sre' ){
		if (check_ajax()){
			echo $lang['template.strings29']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['template.strings29']);
		}	
		exit;
	}
}//end function Chk_Post

//检查提交来源
function CheckfromScript(){
	global $boardid,$lang,$userid,$gb_charset,$ajax_action;
	if (check_ajax()){
		getFromValue(array('body','followup','RootID','star','totalusetable','username'));
	}

	if( ChkPost() === false ){
		if (check_ajax()){
			echo $lang['Error.strings16']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['Error.strings16']);
		}	
		exit;
	}
	if( get_cookie('dvbbs') == $boardid ){
		if (check_ajax()){
			echo $lang['Error.strings30']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['Error.strings30']);
		}	
		exit;
	}
	if( $userid > 0 && preg_match('/snew|sre|svote|active_topic/i',$GLOBALS['action']) === 1 && ChkUserLogin() === false ){
		if (check_ajax()){
			echo $lang['Error.strings12']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['Error.strings12']);
		}	
		exit;
	}
}//end function CheckfromScript

//检查用户身份
function ChkUserLogin(){
	global $ajax_action,$_POST,$dv,$db,$Reuser,$_POST,$boardid,$lang,$userid,$username,$fsetting,$membername,$UserPost,$GroupID,$UserClass,$gb_charset;
	if( $userid <= 0 ){
		$username = $lang['guest'];
	} else {
		if (check_ajax()){
			$username = ajax_UTFANDGB($_POST['username'],$gb_charset);
		}else{
			$username =  $_POST['username'];
		}	

	}

	$usernamelength = Dv_StrLength($username);
	list($usernameminlength,$usernamemaxlength) = explode(',',$fsetting['usernamelength']);
	if( $username == '' || $usernamelength > $usernamemaxlength || $usernamelength < $usernameminlength ){
		
		if (check_ajax()){
			echo $lang['Error.strings17']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['Error.strings17']);
		}	
		exit;
	}
	if( IsTrueName($username) === false ){
		if (check_ajax()){
			echo $lang['Error.strings18']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['Error.strings18']);
		}	
		exit;
	}
	if( $GLOBALS['action'] === 'sedit' ){
		$UserPassWord = get_cookie('password');
		$stmt = "SELECT joindate,userid,userpost,usergroupid,userclass,lockuser,truepassword FROM {$dv}user WHERE userid={$userid}";
	} else{
		if( $username != $membername ){
			$Reuser = true;
			$UserPassWord = dv_md5($_POST['passwd']);
			$stmt = "SELECT joindate,userid,userpost,usergroupid,userclass,lockuser,userpassword FROM {$dv}user WHERE username='{$username}' ";
		} else{
			$UserPassWord = get_cookie('password');
			$stmt = "SELECT joindate,userid,userpost,usergroupid,userclass,lockuser,truepassword FROM {$dv}user WHERE userid={$userid}";
		}
	}
	$len = strlen($UserPassWord);
	if( $len != 16 && $len != 32 ){
		if (check_ajax()){
			echo $lang['Error.strings18']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['Error.strings18']);
		}	
		exit;
	}
	if( $query = $db->query($stmt) ){
		if( $result = $db->fetch_row($query) ){
			$db->free_result($query);
			if (!($UserPassWord != $result[6] OR $result[5] == 1 OR $result[3] == 5)) {
				set_cookie('upNum',0, $GLOBALS['user_selected_cookiedate']);
				//不允许使用马甲
				if( $userid != $result[1] ){
					return false;
				} else{
					$userid = $result[1];
 					$UserPost = $result[2];
 					$GroupID = $result[3];
 					$UserClass = $result[4];
					return true;
				}
			}
		}
	}
	return false;
}//end function ChkUserLogin

function IsTrueName($name){
	global $lang;
	return ( preg_match('/=|%|'.chr(32).'|\?|&|;|,|\'|'.chr(34).'|'.chr(9).'|'.preg_quote($lang['template.strings34']).'|\$/i',$name) === 0 ? true : false );
}

function CheckFormID($id){
	return true;
}//end function CheckFormID

//判断发表类型及权限 GetPostType 0=赠送金币帖(求回复答案),1=获赠金币帖,2=金币购买帖
function Chk_PostType(){
	global $_POST,$userinfo,$ToolsBuyUser,$getmoneytype,$action,$groupsetting,$toolsid,$getposttype,$tomoney,$UseTools,$lang;
	if( $groupsetting[59] != 1 ){
		return;
	}
	$toolsid = trim($toolsid);
	$getposttype = trim($getposttype);
	$tomoney = intval(trim($tomoney));
	if( !is_numeric($toolsid) ){
		$toolsid = '';
	} else{
		$toolsid = intval($toolsid);
	}
	$UseTools = '';
	$getmoneytype = 0;
	if( $getposttype != '' && ( $action == 'snew' || $action == 'svote' || $action == 'active_topic') ){
		switch($getposttype){
			case '0':
				if( $tomoney <= 0 || $tomoney > $userinfo['usermoney'] ){	//	您设置的金币值为空或者多于您拥有的金币数量。
					head();
					showmsg($lang['Error.strings6']);
					exit;
				}
				$userinfo['usermoney'] = $userinfo['usermoney'] - $tomoney;
				$ToolsBuyUser = '0|||$SendMoney';
				$getmoneytype = 1;
				break;
			case '1':
				$ToolsBuyUser = '0|||$GetMoney';
				$getmoneytype = 2;
				break;
			case '2':
				if( $tomoney <= 0 ){
					head();
					showmsg($lang['Error.strings7']);
					exit;
				}
				$buy_orders = $_POST['buy_orders'];
				$buy_viptype = intval($_POST['buy_viptype']);
				$buy_userlist = $_POST['buy_userlist'];
				if( is_numeric($buy_orders) ){
					$buy_orders = php_cCur($buy_orders);
				} else{
					$buy_orders = -1;
				}
				if( $buy_userlist != '' ){
					$buy_userlist = str_replace('$PayMoney','',str_replace('@@@','',str_replace('|||','',$buy_userlist)));
				}
				$ToolsBuyUser = '0@@@'.$buy_orders.'@@@'.$buy_viptype.'@@@'.$buy_userlist.'|||$PayMoney|||';
				$getmoneytype = 3;
				break;
		}
	}
	if( $action == 'sre' && $getposttype == '1' ){
		if ($tomoney <= 0 OR $tomoney > $userinfo['usermoney']) {
			head();
			showmsg($lang['Error.strings8']);
			exit;
		}
	}
}//end functio Chk_PostType


function succeed(){
	global $userid,$dv,$db,$Reuser,$IsAudit,$action,$FoundUseMagic,$tmagicticket,$lang,$tmagicmoney,$board_user,$userinfo,$UserPost,$empath;
	global $stats,$IsAudit,$action,$locktopic,$boardid,$board_settings,$IsAuditcheck,$arrNavMenu,$fsetting,$boardinfo,$boardid,$userid,$RootID;
	if( $IsAudit == 1 && $action == 'sedit' ){
		$boardid = $locktopic;
	}
	function_exists('_dv_muf_callback_onposted') AND _dv_muf_callback_onposted();
	$stats .= $lang['template.strings20'];
	if(intval($fsetting['forum_put_revert'])==0){
		if (!check_ajax()){
			head();
		}
	}
	
	//更新静态缓存文件
	if( $boardid > 0 ){
		$parentstr = $boardinfo['parentstr'];
	}
	if( !empty($parentstr) ){
		$UpdateBoardID = $parentstr.','.$boardid;
	} else{
		$UpdateBoardID = $boardid;
	}

	if($action=='sre'){
		del_static_php_file($boardid,$UpdateBoardID,$RootID);
	}
	else if($action=='sedit'){
		$star= intval($_GET["star"]);
		if($star < 2){
			del_static_php_file($boardid,'',$RootID);
		}
	}
	else if( $action == 'snew' || $action == 'svote' || $action == 'active_topic' || $action == 'argue_topic'){
		del_static_php_file($boardid,$UpdateBoardID,$RootID);
	}

	require printout('savepost');
}//end function succeed()

//更新用户积分，所需外部变量,UserPost,userid,（外加发帖回帖的积分设置数据）
function updatepostuser(){
	global $userid,$dv,$db,$Reuser,$IsAudit,$action,$FoundUseMagic,$tmagicticket,$lang,$tmagicmoney,$board_user,$userinfo,$UserPost,$fsetting,$boardsettings46,$UserToday0;
	set_cookie('activetime',gmdate('Y-m-d H:i:s'), $GLOBALS['user_selected_cookiedate']);
	if( $IsAudit > 0 ){
		return;
	}
		
	$usermoney =& $userinfo['usermoney'];
	$Forum_user =& $board_user;
	$UserToday = explode('|',$userinfo['usertoday']);
	
	$UserToday0=intval($UserToday[0])+1;

	$preposttimesql="";
	
	if($boardsettings46>1&&$UserToday0&&$UserToday0%$boardsettings46==0){
		$preposttimesql=",posttimelimit=".time();
	}
	
	if( $action == 'snew' || $action == 'svote' || $action == 'active_topic'){
		if( $FoundUseMagic ){
			if ($usermoney > $tmagicmoney) {
				$usermoney -= $tmagicmoney;
				ToolsLog(-88,1,$tmagicmoney,0,1,$lang['template.strings1'],$usermoney.'|'.$userinfo['userticket']);
			} else{
				$MagicSql = ',userticket=userticket-'.$tmagicticket;
				$userticket = $userinfo['userticket']-$tmagicticket;
				ToolsLog(-88,1,0,$tmagicticket,1,$lang['template.strings'],$usermoney.'|'.$userticket);
			}
		}
		$db->query("UPDATE {$dv}user SET userlastip='{$GLOBALS['usertrueip']}',userpost=userpost+1 {$preposttimesql},usertopic=usertopic+1,userwealth=userwealth+".intval($Forum_user[1]).",userep=userep+".intval($Forum_user[6]).",usercp=usercp+".intval($Forum_user[11]).",usertoday='".(intval($UserToday[0])+1).'|'.intval($UserToday[1]).'|'.intval($UserToday[2]).'|'.intval($UserToday[3]).'|'.intval($UserToday[4])."',usermoney=".intval($usermoney)." ".$MagicSql." WHERE userid=".$userid);
		if( !$Reuser ){
			$UserPost++;
		}
	} elseif( $action == 'sre' ){
		
		if( !$Reuser ){
			$db->query("UPDATE {$dv}user SET userlastip='{$GLOBALS['usertrueip']}',userpost=userpost+1 {$preposttimesql},userwealth=userwealth+".intval($Forum_user[2]).",userep=userep+".intval($Forum_user[7]).",usercp=usercp+".intval($Forum_user[12]).",usertoday='".(intval($UserToday[0])+1).'|'.intval($UserToday[1]).'|'.intval($UserToday[2]).'|'.intval($UserToday[3]).'|'.intval($UserToday[4])."',usermoney=".intval($usermoney)." WHERE userid={$userid}");
			$UserPost++;
		} else{
			$db->query("UPDATE {$dv}user SET userlastip='{$GLOBALS['usertrueip']}',userpost=userpost+1 {$preposttimesql},userwealth=userwealth+".intval($Forum_user[2]).",userep=userep+".intval($Forum_user[7]).",usercp=usercp+".intval($Forum_user[12]).",usermoney=".intval($usermoney)." WHERE userid={$userid}");
		}
	}
	if($fsetting["userupgrage_online"]){
		Updategrade();
	}
}//end function updatepostuser

//更新用户等级，所需外部变量,UserPost,GroupID,userid
function Updategrade(){
	global $db,$dv,$UserClass,$GroupID,$lang,$userid,$UserPost,$UserClass,$GroupID,$fsetting;
	if( $query = $db->query("SELECT minarticle,issetting,parentgid,usertitle,grouppic FROM {$dv}usergroups WHERE usergroupid={$GroupID}") ){
		$tmpResult = $db->fetch_row($query);
	}
	if( !empty($tmpResult) ){
		if( $tmpResult[2] != 3 ){//用户等级不按照文章升级，用户为系统或特殊或多属性组
			$UserClass = $tmpResult[0];
			$TitlePic = $tmpResult[1];
			$FoundGrade = true;
		}
		unset($tmpResult);
	}
	if( !$FoundGrade ){
		if( $query = $db->query("Select usertitle,grouppic,usergroupid From {$dv}usergroups Where parentgid=3 And minarticle={$UserPost} Order By minarticle Desc,usergroupid Limit 1") ){
			$tmpResult = $db->fetch_row($query);
		}
		if( !empty($tmpResult) ){
			$UserClass = $tmpResult[0];
			$TitlePic = $tmpResult[1];
			$GroupID = $tmpResult[2];
			$FoundGrade = true;
			unset($tmpResult);
			
			if($db->query("UPDATE {$dv}user SET userclass='{$UserClass}',titlepic='{$TitlePic}',usergroupid={$GroupID} WHERE userid={$userid}"))
			{
				if($fsetting["userupgrage_show"])
					include_once 'userupgrage.php';
			}
		}
	}
}//end function Updategrade

//更新主题、帖子内容
function Update_Edit_Announce(){
	global $dv,$db,$Content,$username,$membername,$fsetting,$groupsetting,$boardid,$userid,$lang,$signflag,$RootID,$userinfo;
	global $totalusetable,$AnnounceID,$CanEditPost;
	global $expression,$signflag,$topic,$MyTopicMode,$MyTopicFont,$isAlipayTopic;
	global $IsAudit,$usertrueip,$mailflag,$ihaveupfile,$upfileinfo,$FoundUseMagic;
	global $tmagicmoney,$lang,$tmagicticket,$char_changed,$dvstatu,$dvid;
	(!isset($dvstatu))&&($dvstatu='');
	$dvid=intval($dvid);
	$Content = preg_replace(
				array(
					'/\[align=right\]\[color=#000066\](.*)\[\/color\]\[\/align\]/'
					,'/<div align=right><font color=#000066>(.*)<\/font><\/div>/i'
				)
				,array(
					''
					,''
				)
				,$Content
			   );
	if(!empty($dvid)){
		$Content=preg_replace('/\[mergepic,[\d]?][_0-9a-z]*\[\/mergepic]/ei','',$Content);
		$Content="[mergepic,{$dvstatu}]{$dvid}[/mergepic]".$Content;
	}  		   
	$EditDateTime = TIME_NOW;
	if( $query = $db->query("SELECT username FROM ".$db->escape_string(strtolower($totalusetable))." WHERE announceid={$AnnounceID}") ){
		$tmpResult = $db->fetch_array($query);

		if( $membername != $tmpResult["username"] ){
			if( $fsetting['ismastereditinfo'] == 1 ){
				$char_changed = '[align=right][color=#000066]['.str_replace(array('{$membername}', '{$EditDateTime}'), array($membername, '[lastedittime]'.$EditDateTime.'[/lastedittime]'), $lang['template.strings4']).'][/color][/align]';
			}
		} else{
			if( $fsetting['iseditinfo'] == 1 ){
				$char_changed = '[align=right][color=#000066]['.str_replace('{$EditDateTime}','[lastedittime]'.$EditDateTime.'[/lastedittime]',$lang['template.strings5']).'][/color][/align]';
			}
		}

	}
	Get_Edit_PermissionInfo();
	uploadedFilesProc(); // 处理上传文件
	$lastpost = trim($db->scalar("SELECT lastpost FROM {$dv}board WHERE boardid='{$boardid}'"));
	if ($lastpost !== '') {
		$LastBoard = explode('$',$lastpost);
		$count = count($LastBoard);
		if( $count == 8 ){
			if( $LastBoard[1] == $AnnounceID ){
				if( $signflag == 2 ){
					$LastBoard[0] = $lang['template.strings3'];
					$LastBoard[5] = '';
				} else {
					$LastBoard[0] = $membername;
					$LastBoard[5] = $userid;
				}
				$lastpost = $LastBoard[0].'$'.$LastBoard[1].'$'.time().'$'.strip_tags($LastBoard[3]).'$'.$LastBoard[4].'$'.$LastBoard[5].'$'.$LastBoard[6].'$'.$boardid;
				$db->query("UPDATE {$dv}board SET lastpost='".$db->escape_string(htmlspecialchars($lastpost))."' WHERE boardid='{$boardid}'");
				UpDate_BoardInfoAndCache();
			}
		}
	}

	//取得当前主题最后回复id,如果本帖为最后回复则更新相应数据0
	$lastpost = '';
	if( $query = $db->query("SELECT lastpost,istop,expression FROM {$dv}topic WHERE topicid={$RootID}") ){
		$tmpResult = $db->fetch_row($query);
	}
	if( !empty($tmpResult) ){
		$istop = $tmpResult[1];
		$MyMagicFace = explode('|',$tmpResult[2]);
		$count = count($MyMagicFace);
		if( $count == 2 ){
			$iFoundUseMagic = $MyMagicFace[0];
		}
		$lastpost = $tmpResult[0] = trim($tmpResult[0]);
		if($tmpResult[0] !== ''){
			$LastTopic = explode('$', $tmpResult[0]);
			if( $LastTopic[1] == $AnnounceID ){
				if( $signflag == 2 ){
					$LastTopic[0] = $lang['template.strings3'];
					$LastTopic[5] = '';
					$lastpost = $LastTopic[0].'$'.$LastTopic[1].'$'.time().'$'.strip_tags(str_replace('$','&#36;',cutStr(reUBBCode($Content),20))).'$'.$LastTopic[4].'$'.$LastTopic[5].'$'.$LastTopic[6].'$'.$boardid;
				} else {
					$LastTopic[0] = $membername;
					$LastTopic[5] = $userid;
					$lastpost = $LastTopic[0].'$'.$LastTopic[1].'$'.time().'$'.strip_tags(str_replace('$','&#36;',cutStr(reUBBCode($Content),20))).'$'.$LastTopic[4].'$'.$LastTopic[5].'$'.$LastTopic[6].'$'.$boardid;
				}
			}
		}
	}

	unset($tmpResult);
	$usernamecompare = '';
	if( $CanEditPost === false ){ // 您没有足够的权限编辑本帖子，请和管理员联系。
		head();
		showmsg($lang['Error.strings77']);
		exit;
	} elseif ($master === true) {
		$usernamecompare = " AND username='{$username}' ";
	}
	if( $query = $db->query("SELECT announceid,parentid,boardid,username,postuserid,topic,body,dateandtime,length,rootid,layer,orders,isbest,ip,expression,locktopic,signflag,emailflag,isagree,isaudit,isupload,postbuyuser,ubblist,getmoney,usetools,getmoneytype FROM ".$db->escape_string(strtolower($totalusetable))." WHERE announceid={$AnnounceID} {$usernamecompare}") ){
		$tmpResult = $db->fetch_array($query);
	}
	if( empty($tmpResult) ) {
		head();
		showmsg($lang['Error.strings77']);
		exit;
	} elseif ( $master === false && $tmpResult['locktopic'] == 1 ) {
		head();
		showmsg($lang['Error.strings48']);
		exit;
	} else {
		$db->free_result($query);
		//Start 特殊标题处理
			(0 == $groupsetting[51]) AND ($MyTopicMode = 0);
			if ($MyTopicMode == 1) {
				$tmptopic = stripslashes($topic);
				$topic = cross_site_html_proc($tmptopic, $errcode, $errstr);
				if ($errno OR $errstr) {
					$topic = strip_tags($tmptopic);
				}
			} else {
				$topic = preg_replace('/&amp;#(\d+)(;?)/ie', '(("$1">127)?"&#$1$2":"$1")', htmlspecialchars(stripslashes($topic)));
			}
		//End 特殊标题处理

		if( $tmpResult['parentid'] == 0 ){
			$iExpression = ",expression='".$expression[0].'|'.$expression[1]."'";
			if( $signflag == 2 ){
				$db->query("UPDATE {$dv}topic SET title='".$db->escape_string($topic)."',topicmode={$MyTopicMode},topicfont='".$MyTopicFont."',issmstopic={$isAlipayTopic} {$iExpression},hidename='1',lastpost=".(!empty($lastpost) ? "'".$db->escape_string(strip_tags($lastpost))."'" : "lastpost")." WHERE topicid='{$RootID}'");
			} else{
				$db->query("UPDATE {$dv}topic SET title='".$db->escape_string($topic)."',topicmode={$MyTopicMode},topicfont='".$MyTopicFont."',issmstopic={$isAlipayTopic} {$iExpression},hidename='0',lastpost=".(!empty($lastpost) ? "'".$db->escape_string(strip_tags($lastpost))."'" : "lastpost")." WHERE topicid='{$RootID}'");
			}
			global $ft_settings;
			if (1 == $ft_settings[0]) {	//更新主题的全文索引分表
				$arrTopicIndex =& DV_ChineseWordSegment($topic);
				if( !empty($arrTopicIndex) && is_array($arrTopicIndex) ){
					$topicindex = $db->escape_string(implode(' ',$arrTopicIndex));
					if( $topicindex !== '' ){
						$db->query("UPDATE {$dv}topic_ft SET topicindex='{$topicindex}' WHERE topicid='{$RootID}'");
					} else{
						$db->query("DELETE FROM {$dv}topic_ft WHERE topicid='{$RootID}'");
					}
				}
			}
		} elseif (!empty($lastpost)) {
			if( $signflag == 2 ){
				$db->query("UPDATE {$dv}topic SET lastpost='".$db->escape_string(strip_tags($lastpost))."' WHERE topicid='{$RootID}'");
			} else {
				$db->query("UPDATE {$dv}topic SET lastpost='".$db->escape_string(strip_tags($lastpost))."' WHERE topicid='{$RootID}'");
			}
		}
		if( $IsAudit == 1 ){
			$tmpResult['locktopic'] = 3;
		} elseif( $tmpResult['locktopic'] == 3 && $IsAudit == 0 ){
			$tmpResult['locktopic'] = 0;
		}

		$tmpResult['topic'] = $topic;
		$tmpResult['body'] =& cross_site_html_proc(stripslashes($Content), $errcode, $errstr);
		$tmpResult['length'] = Dv_StrLength(stripslashes($Content));
		$tmpResult['ip'] = $usertrueip;
		$tmpResult['expression'] = $expression[1];
		global $board_settings;
		if (2 == $signflag AND 0 == $board_settings[58]) {
			$signflag = 1;
		}
		$tmpResult['signflag'] = $signflag;
		$tmpResult['emailflag'] = $mailflag;
		if( intval($tmpResult['isupload']) == 0 && $ihaveupfile == 1 ){
			$tmpResult['isupload'] = 1;
		}
		$tmpResult['ubblist'] =& Ubblist($Content);
		$stmt = "UPDATE ".$db->escape_string(strtolower($totalusetable))." SET ";
		$tmpAnnounceID = intval($tmpResult['announceid']);
		unset($tmpResult['announceid']);
		$i = 0;
		foreach( $tmpResult as $key => $val ){
			if( $i > 0 ) $stmt .= ',';
			$stmt .= "{$key}='".$db->escape_string($val)."'";
			$i++;
		}
		$stmt .= " WHERE announceid={$tmpAnnounceID} ";
		$db->query($stmt);

		global $ft_settings;
		if (1 == $ft_settings[0]) {	//更新帖子的全文索引分表
			$topicindex = '';
			$arrTopicIndex =& DV_ChineseWordSegment($tmpResult['topic']);
			if( !empty($arrTopicIndex) && is_array($arrTopicIndex) ){
				$topicindex = implode(' ',$arrTopicIndex);
			}
			$bodyindexStmt = '';
			$bodyindex = '';
			$arrBodyIndex = DV_ChineseWordSegment($tmpResult['body']);
			if( !empty($arrBodyIndex) && is_array($arrBodyIndex) ){
				$bodyindex = implode(' ',$arrBodyIndex);
				if( $bodyindex !== '' ){
					$bodyindexStmt = "bodyindex='{$bodyindex}'";
				}
			}
			if( $topicindex === '' && $bodyindex === '' ){
				$db->query("DELETE FROM {$dv}bbs_ft WHERE announceid='{$tmpAnnounceID}'");
			} elseif( $bodyindexStmt !== '' ){
				if( $topicindex !== '' ){
					$topicindexStmt = "topicindex='{$topicindex}'";
				} else{
					$topicindexStmt = 'topicindex=topicindex';
				}
				$db->query("UPDATE {$dv}bbs_ft SET {$topicindexStmt},{$bodyindexStmt} WHERE announceid='{$tmpAnnounceID}'");
			}
		}

		if ($ihaveupfile == 1 AND $upfileinfo) {
			$db->query("UPDATE {$dv}upfile SET f_announceid='".$RootID."|".$AnnounceID."',f_readme='".str_replace("'","''",$tmpResult['topic'])."',f_flag=0 WHERE f_id IN({$upfileinfo})");
		}
		if( $FoundUseMagic ){
			if( $imagicface != intval($iFoundUseMagic) ){
				$tmpusermoney =& $userinfo['usermoney'];
				if ($tmpusermoney > $tmagicmoney) {
					$db->query("UPDATE {$dv}user SET usermoney=usermoney-{$tmagicmoney} WHERE userid={$userid}");
					$tmpusermoney -= $tmagicmoney;
					ToolsLog(-88,1,$tmagicmoney,0,1,$lang['template.strings1'],$tmpusermoney.'|'.$userinfo['userticket']);
				} else{
					$db->query("UPDATE {$dv}user SET userticket=userticket-{$tmagicticket} WHERE userid={$userid}");
					$tmpuserticket = $userinfo['userticket'] - $tmagicticket;
					ToolsLog(-88,1,0,$tmagicticket,1,$lang['template.strings2'],intval($userinfo['usermoney']).'|'.$tmpuserticket);
				}
			}
		}
	}
}//end function Update_Edit_Announce

//回复获赠金币帖时更新
function GetMoney_SaveRe(){
	global $dv,$db,$lang,$totalusetable,$tomoney,$username,$RootID;
	$tmpResult = false;
	if( $query = $db->query("SELECT postuserid,getmoney,postbuyuser,username FROM ".$db->escape_string(strtolower($totalusetable))." WHERE rootid={$RootID} AND parentid=0 AND getmoneytype=2") ){
		$tmpResult = $db->fetch_row($query);
	}
	if( !empty($tmpResult) ){
		$ToUserID = intval($tmpResult[0]);
		$UpGetMoney = $tmpResult[1] + $tomoney;
		$UpPostBuyUser = $tmpResult[2];
		$ToUserName = $tmpResult[3];
		$arrTmp = explode('|||', $UpPostBuyUser, 2);
		$arrTmp[0] = $UpGetMoney;
		$arrTmp[1] .= '|||'.$username.','.$tomoney;
		$UpPostBuyUser = trim($arrTmp[0].'|||'.$arrTmp[1]);
		$tmpResult[1] = $UpGetMoney;
		$tmpResult[2] = $UpPostBuyUser;
		$db->query("UPDATE ".$db->escape_string($totalusetable)." SET getmoney={$tmpResult[1]},postbuyuser='".$db->escape_string($tmpResult[2])."' WHERE rootid={$RootID} AND parentid=0 AND getmoneytype=2");
	}
	//更新主题MONEY值
	$db->query("UPDATE {$dv}topic SET getmoney={$UpGetMoney} WHERE topicid={$RootID}");
	//主题作者获取金币
	$db->query("UPDATE {$dv}user SET usermoney=usermoney+{$tomoney} WHERE userid={$ToUserID}");
}//end function GetMoney_SaveRe

//判断用户是否有编辑权限且提取相关信息
function Get_Edit_PermissionInfo(){
	global $action,$dv,$db,$lang,$totalusetable,$tomoney,$username,$RootID,$AnnounceID,$replyid,$membername,$char_changed;
	if( $action == '4' ){
		$stmt = "SELECT b.username,b.topic,b.body,b.dateandtime,u.usergroupid,b.signflag,b.emailflag FROM ".$db->escape_string(strtolower($totalusetable))." b LEFT OUTER JOIN {$dv}user u ON b.postuserid=u.userid WHERE b.rootid={$AnnounceID} AND b.announceid={$replyid}";
	} else{
		$stmt = "SELECT b.username,b.topic,b.body,b.dateandtime,u.usergroupid,b.signflag,b.emailflag FROM ".$db->escape_string(strtolower($totalusetable))." b LEFT OUTER JOIN {$dv}user u ON b.postuserid=u.userid WHERE b.rootid={$RootID} AND b.announceid={$AnnounceID}";
	}
	if( $query = $db->query($stmt) ){
		$tmpResult = $db->fetch_array($query);
	}
	if( empty($tmpResult) ){
		head();
		showmsg($lang['Error.strings48']);
		exit;
	} else{
		$db->free_result($query);
		global $signflag,$mailflag,$topic,$Content,$fsetting;
		if( $action == '4' ){
			$signflag = $tmpResult['signflag'];
			$mailflag = $tmpResult['emailflag'];
			$topic = $tmpResult['topic'];
			if( $topic != '' ){
				$topic = preg_replace('/&amp;#(\d+)(;?)/ie', '(("$1">127)?"&#$1$2":"$1")', htmlspecialchars($topic));
			}
			$Content = $tmpResult['body'];
			$old_user = $tmpResult['username'];
		} else{
			if( $fsetting['editinfo_time'] > 0 ){
				if( dateDiff('s',$tmpResult['dateandtime'],time()) > $fsetting['editinfo_time']*60 ){
					$Content .= "\r\n".$char_changed."\r";
				}
			} else{
				$Content .= "\r\n".$char_changed."\r";
			}
		}
		global $master,$boardmaster,$superboardmaster;
		if( $fsetting['editinfo_timeout'] > 0 && ( $master === false && $boardmaster === false && $superboardmaster === false ) ){
			$tmp = dateDiff('s',$tmpResult['dateandtime'],time());
			if( $tmp > $fsetting['editinfo_timeout']*60 ){
				head();
				showmsg(str_replace('{$etlimited}',$fsetting['editinfo_timeout'],str_replace('{$posttime}',$tmp/60,$lang['template.strings22'])));
				exit;
			}
		}
		global $signflag,$membername,$groupsetting,$CanEditPost;
		if( $tmpResult['username'] == $membername ){
			if( $groupsetting[10] == 0 ){
				$CanEditPost = false;
				head();
				showmsg($lang['Error.strings74']);
				exit;
			} else{
				$CanEditPost = true;
			}
		} else{
			$signflag = $tmpResult['signflag'];
			$mailflag = $tmpResult['emailflag'];
			if( ($master === true || $superboardmaster || $boardmaster ) && $groupsetting[23] == 1 ){
				$CanEditPost = true;
			} else{
				$CanEditPost = false;
			}
			global $usergroupid,$founduserper;
			if( $usergroupid > 3 && $groupsetting[23] == 1 ){
				$CanEditPost = true;
			}
			if( $groupsetting[23] == 1 && $founduserper === true ){
				$CanEditPost = true;
			} elseif( $groupsetting[23] == 0 && $founduserper === true ){
				$CanEditPost = false;
			}
			if( $usergroupid < 4 && $usergroupid == $tmpResult['usergroupid'] ){
				head();
				showmsg($lang['Error.strings75']);
				exit;
			} elseif( $usergroupid < 4 && $usergroupid > $tmpResult['usergroupid'] ){
				head();
				showmsg($lang['Error.strings76']);
				exit;
			}
			if( $CanEditPost === false ){
				head();
				showmsg($lang['Error.strings77']);
				exit;
			}
		}
	}
	if( $action == '4' ){
		$membername = $old_user;
	}
}//end function Get_Edit_PermissionInfo

//更新版面数据（取消更新缓存）
function UpDate_BoardInfoAndCache(){
	global $LastPost_1,$action,$boardinfo,$dv,$db,$lang,$fsetting,$groupsetting,$board_settings,$boardid,$userid;
	if( $boardid > 0 ){
		$parentstr = $boardinfo['parentstr'];
	}
	if( !empty($parentstr) ){
		$UpdateBoardID = $parentstr.','.$boardid;
	} else{
		$UpdateBoardID = $boardid;
	}
	$LastPost_1 = str_replace('<','&lt;',$LastPost_1);
	if( $action == 'sre' ){
		$db->query("UPDATE {$dv}board SET postnum=postnum+1,todaynum=todaynum+1,lastpost='{$LastPost_1}' WHERE boardid IN ({$UpdateBoardID})");
	} elseif( $action == 'snew' || $action == 'svote' || $action == 'active_topic'){
		$db->query("UPDATE {$dv}board SET postnum=postnum+1,topicnum=topicnum+1,todaynum=todaynum+1,lastpost='{$LastPost_1}' WHERE boardid IN({$UpdateBoardID})");
	}
}//end function UpDate_BoardInfoAndCache

function UpDate_ForumInfoAndCache(){
}//end function UpDate_ForumInfoAndCache

function reUBBCode(&$strContent){
	if ('' == $strContent) {
		return '';
	}
	$strContent = str_replace('&nbsp;', '', $strContent);
	static $st_arr_pattern, $st_arr_repl;
	if (!isset($st_arr_pattern)) {
		$st_arr_pattern = array(0=>'/\[QUOTE\].*\[\/QUOTE\]/is', 1=>'/\[point\s*=\s*[0-9]*\].*\[\/point\]/is', 2=>'/\[post\s*=\s*[0-9]*\].*\[\/post\]/is', 3=>'/\[power\s*=\s*[0-9]*\].*\[\/power\]/is', 4=>'/\[usercp\s*=\s*[0-9]*\].*\[\/usercp\]/is', 5=>'/\[money\s*=\s*[0-9]*\].*\[\/money\]/is', 6=>'/\[replyview\].*\[\/replyview\]/is', 7=>'/\[usemoney\s*=\s*[0-9]*\].*\[\/usemoney\]/is', 8=>'/<I><\/I>/i');
		$st_arr_repl = array(0=>'', 1=>'&nbsp;', 2=>'&nbsp;', 3=>'&nbsp;', 4=>'&nbsp;', 5=>'&nbsp;', 6=>'&nbsp;', 7=>'&nbsp;', 8=>'');
	}
	return str_replace(array("\r", "\n", chr(32), chr(9), '<'), array('', '', ' ', '&lt;'), strip_tags(preg_replace($st_arr_pattern, $st_arr_repl, $strContent)));
}//end function reUBBCode

//截取指定字符
function &cutStr(&$str, $strlen){
	if ($strlen <= 0) {
		return '';
	}
	$returnval = trim($str);
	if ($returnval === '') {
		return '';
	}
	//去掉所有HTML标记
	$returnval = preg_replace( '/<([^<>]*?)>/i' ,'' ,$returnval);
	static $objenc = null;
	if (empty($objenc)) {
		require_once INC_PATH.'DV_Encoding.class.php';
		$objenc = DV_Encoding::GetEncoding($GLOBALS['charset']);
	}
	$returnval = str_replace(array("\r", "\n"), '', $objenc->SubString($returnval, 0, $strlen));
	return $returnval;
}//end function cutStr

//保存发帖，投票和回帖
function savepost(){
	global $dv,$db,$ilayer,$action,$MyIsTop,$MyIstopAll;
	global $RootID,$boardid,$boardinfo;
	global $topic,$Content,$ihaveupfile,$RootID,$AnnounceID,$toptopic,$upfileinfo;
	global $action,$IsAudit,$Tools_UseTools,$action,$Tools_LastPostTime,$lastpost,$RootID,$Child,$board_settings,$star;
	global $toptopic,$topic,$LastPost_1,$uploadpic_n,$userid,$RootID,$boardid,$username,$IsAudit;
	global $savvy_yes,$savvy_topicid,$Postid;
	
	uploadedFilesProc(); // 处理上传文件
	if( $action == 'snew' || $action == 'svote' || $action == 'active_topic'){
		if( $action == 'svote' ){
			Insert_To_Vote();
		}
		if( $action == 'active_topic'){
			Insert_To_Active();
		}
		Insert_To_Topic();
		//更新总固顶和固顶的数据以及缓存数据
		if( $MyIsTop == 3 ){//将总固顶ID插入总设置表
			$Forum_AllTopNum = trim($db->scalar("SELECT forum_alltopnum FROM {$dv}setup"));
			if( $Forum_AllTopNum.'' === '' ){
				$iForum_AllTopNum = $RootID;
			} else{
				$iForum_AllTopNum = $Forum_AllTopNum.','.$RootID;
			}
			$db->query("UPDATE {$dv}setup SET forum_alltopnum='".$db->escape_string($iForum_AllTopNum)."'");
			include_once INC_PATH.'BoardCache.class.php';
			$boardcache =& new BoardCache($db);
			$boardcache->createForumSetting();
		} elseif( $MyIsTop == 1 ){
			if( $query = $db->query("SELECT boardid,boardtopstr FROM {$dv}board WHERE boardid=".intval($boardid)) ){
				$tmpResult = $db->fetch_row($query);
			}
			if( !empty($tmpResult) ){
				if( $tmpResult[1] == '' || is_null($tmpResult[1]) ){
					$BoardTopStr = $RootID;
				} else{
					if( strpos(",{$tmpResult[1]},",",{$RootID},") !== false ){
						$BoardTopStr = $tmpResult[1];
					} else{
						$BoardTopStr = $tmpResult[1].','.$RootID;
					}
				}
				$db->query("UPDATE {$dv}board SET boardtopstr='".$db->escape_string($BoardTopStr)."' WHERE boardid='{$tmpResult[0]}'");
			}
		}
	} elseif( $action == 'sre' ){
		Get_SaveRe_TopicInfo();
		Get_ForumTreeCode();
	}
	Insert_To_Announce();
	if( $action == 'sre' ){
		$topic = str_replace("'",'',str_replace(chr(10),'',cutStr(reUBBCode($topic),14)));
		if( $topic == '' ){
			$topic = str_replace(chr(10),'',cutStr(reUBBCode($Content),14));
		} else{
			$topic = str_replace(chr(10),'',cutStr(reUBBCode($topic),14));
		}
		if( $ihaveupfile == 1 ){
			$db->query("UPDATE {$dv}upfile SET f_announceid='".$RootID."|".$AnnounceID."',f_readme='".str_replace("'",'',$topic)."',f_flag=0 WHERE f_id IN (".$upfileinfo.")");
		}
	} else{
		if( $ihaveupfile == 1 ){
			$db->query("UPDATE {$dv}upfile SET f_announceid='".$RootID."|".$AnnounceID."',f_readme='".$db->escape_string($topic)."',f_flag=0 WHERE f_id IN (".$upfileinfo.")");
		}
	}
	global $signflag,$lastpost,$lang,$uploadpic_n,$boardid,$username,$userid;
	if( $signflag == 2 ){
		$lastpost = $lang['template.strings3'].'$'.$AnnounceID.'$'.time().'$'.strip_tags(str_replace('$','&#36;',$topic)).'$'.$uploadpic_n.'$'.' '.'$'.$RootID.'$'.$boardid;
	} else{
		$lastpost = str_replace('$','&#36;',$username).'$'.$AnnounceID.'$'.time().'$'.strip_tags(str_replace('$','&#36;',$topic)).'$'.$uploadpic_n.'$'.$userid.'$'.$RootID.'$'.$boardid;
	}
	$lastpost = ChkBadWords(str_replace("'",'',$lastpost));
	if( $IsAudit != 1 ){
		$IsUpDateLastPostTime = false;
		if( strpos(",{$Tools_UseTools},",',13,') !== false || strpos(",{$Tools_UseTools},",',14,') !== false ){
			$IsUpDateLastPostTime = true;
		}
		if( $action == 'sre' ){
			if( $IsUpDateLastPostTime === true ){
				if( dateDiff('h',time(),$Tools_LastPostTime) <= 0 ){
					$stmt = "UPDATE {$dv}topic SET child=child+1,lastposttime='".time()."',lastpost='".$db->escape_string($lastpost)."' WHERE topicid={$RootID}";
				} else{
					$stmt = "UPDATE {$dv}topic SET child=child+1,lastpost='".$db->escape_string($lastpost)."' WHERE topicid={$RootID}";
				}
			} else{
				$stmt = "UPDATE {$dv}topic SET child=child+1,lastposttime='".time()."',lastpost='".$db->escape_string($lastpost)."' WHERE topicid={$RootID}";
			}
			$db->query($stmt);
			$Child = $Child+2;
			if ($board_settings[61] < 1) {
				$board_settings[61] = 20;
			}
			if( $Child % $board_settings[61] == 0 ){
				$star = intval($Child / $board_settings[61]);
			} else{
				$star = ceil( (float)$Child / (float)$board_settings[61]);
			}
		} else{
			if($savvy_yes==1){
				$db->query("UPDATE {$dv}savvy_topic SET lastpost='".$db->escape_string($lastpost)."' WHERE topicid={$savvy_topicid}");
			}
			$db->query("UPDATE {$dv}topic SET lastpost='".$db->escape_string($lastpost)."' WHERE topicid={$RootID}");
		}
	} else{
		//待审核取消回复更新最后发帖。
		if( $action == 'snew' || $action == 'svote' || $action == 'active_topic'){
			if($savvy_yes==1){
				$db->query("UPDATE {$dv}savvy_topic SET lastpost='".$db->escape_string($lastpost)."' WHERE topicid={$savvy_topicid}");
			}
			$db->query("UPDATE {$dv}topic SET lastpost='".$db->escape_string($lastpost)."' WHERE topicid={$RootID}");
		}
	}
	if( $action == 'snew' || $action == 'svote'  || $action == 'active_topic'){
		$toptopic = str_replace('$','&#36;',cutStr($topic,20));
	} else{
		$toptopic = str_replace('$','&#36;',cutStr($toptopic,20));
	}
	//toptopic =主标题,Content=内容
	//判断是否是加密的论坛，如果是，则不显示最后发帖内容。
	if( intval($boardinfo['ischeckout']) == 1 ){
		$LastPost_1 = $lang['template.strings8'].$AnnounceID.'$'.time().$lang['template.strings9'].$uploadpic_n.'$'.$userid.'$'.$RootID.'$'.$boardid;
	} elseif( $signflag == 2 ){
		$LastPost_1 = $lang['template.strings3'].'$'.$AnnounceID.'$'.time().'$'.$toptopic.'$'.$uploadpic_n.'$'.' $'.$RootID.'$'.$boardid;
	} else{
		$LastPost_1 = str_replace('$','',$username).'$'.$AnnounceID.'$'.time().'$'.$toptopic.'$'.$uploadpic_n.'$'.$userid.'$'.$RootID.'$'.$boardid;
	}
	$LastPost_1 = ChkBadWords(reUBBCode(str_replace("'",'',$LastPost_1)));
	if( $IsAudit == 0 ){
		UpDate_BoardInfoAndCache();
		UpDate_ForumInfoAndCache();
	}
	set_cookie('dvbbs',$boardid, $GLOBALS['user_selected_cookiedate']);
}//end function savepost



function Insert_savvy_table($bid,$word){//插入论坛知道表
	global $fsetting,$savvy_board;
	$postwordset=explode(',',$savvy_board['boardkey']['board_key']);
	$boardidset=explode(',',$savvy_board['boardidset']['boardid_set']);
	if($fsetting['issavvy_show']==1){
		if(intval($savvy_board['setup']['isInsertSavvy'])==1){
			if(in_array($bid,$boardidset)){
				foreach ($postwordset as $postword){
					if(strpos($word,$postword)!==false){
						$insertssvvy=true;						
					}
				}
			}
		}
		else{
			$insertssvvy=false;
		}
	}
	return $insertssvvy;
}

function Insert_To_Topic(){//插入主题表	
	global $groupsetting, $expression,$signflag,$RootID,$dv,$db,$userid, $MyIsTop, $MyTopicMode,$MyTopicFont, $ft_settings,$savvy_board,$fsetting,$boardid;
	global $savvy_yes,$savvy_topicid,$Postid;
	if( $signflag == 2 ){
		$hidename = 1;
	} else{
		$hidename = 0;
	}
	if ($groupsetting[51] == 0) {
		$MyTopicMode = 0;
	}
	if ($MyTopicMode == 1) {
		$tmptopic = stripslashes($GLOBALS['topic']);
		$topic = cross_site_html_proc($tmptopic, $errcode, $errstr);
		if ($errno OR $errstr) {
			$topic = $db->escape_string(strip_tags($tmptopic));
		} else {
			$topic = $db->escape_string($topic);
		}
	} else {
		$topic = $db->escape_string(preg_replace('/&amp;#(\d+)(;?)/ie', '(("$1">127)?"&#$1$2":"$1")', htmlspecialchars(stripslashes($GLOBALS['topic']))));
	}
	$strDateTime = $MyLastPostTime = time();
	$GLOBALS['anonymity']='0';
	if(Insert_savvy_table($boardid,$topic)===true){	//如果论坛的贴子符合知道功能的条件，那写入知道表
		$beuserexist=$db->scalar("select count(1) from {$dv}savvy_integral where userid={$userid}");
		if($beuserexist <= 0){//写入用户的积分信息表
			$db->query("insert into {$dv}savvy_integral (userid,username,answercount,answeradopt,askcount,askdonecount,askdoningcount,asknodonecount,wealthcount,answerwealth,savvy_hortation,offer_pay,anonymity_ask,punishother) values ({$userid},'".$db->escape_string($GLOBALS['username'])."',0,0,1,0,0,0,0,0,0,0,0,0)");
		}
		else{
			$db->query("UPDATE {$dv}savvy_integral set askcount=askcount+1 where userid={$userid}");
		}	
		$stmt_savvy = "INSERT INTO {$dv}savvy_topic (title,boardid,postusername,postuserid,dateandtime,expression,lastpost,lastposttime,posttable,locktopic,istop,topicmode,topicfont,isvote,pollid,mode,getmoney,usetools,getmoneytype,issmstopic,hidename,anonymity) VALUES('{$topic}',".$GLOBALS['boardid'].",'".$db->escape_string($GLOBALS['username'])."',".$GLOBALS['userid'].",'".$strDateTime."','".$db->escape_string($expression[0])."|".$db->escape_string($expression[1])."','$$".$strDateTime."$$$$','".$MyLastPostTime."','".$db->escape_string($GLOBALS['totalusetable'])."',".intval($GLOBALS['locktopic']).",".intval($GLOBALS['MyIsTop']).",".intval($GLOBALS['MyTopicMode']).",'".$GLOBALS['MyTopicFont']."',".$GLOBALS['isvote'].",".$GLOBALS['voteid'].",".$GLOBALS['topicmode'].",5,'".$db->escape_string($GLOBALS['UseTools'])."',".($GLOBALS['getmoneytype']?$GLOBALS['getmoneytype']:'NULL').",".$GLOBALS['isAlipayTopic'].",0,".$GLOBALS['anonymity'].")";
		$savvy_yes=1;
		$db->query($stmt_savvy); 
		$savvy_topicid = $db->insert_id();
	}
	$stmt = "INSERT INTO {$dv}topic (title,boardid,postusername,postuserid,dateandtime,expression,lastpost,lastposttime,posttable,locktopic,istop,topicmode,topicfont,isvote,pollid,mode,getmoney,usetools,getmoneytype,issmstopic,hidename,activeid) VALUES('{$topic}',".$GLOBALS['boardid'].",'".$db->escape_string($GLOBALS['username'])."',".$GLOBALS['userid'].",'".$strDateTime."','".$db->escape_string($expression[0])."|".$db->escape_string($expression[1])."','$$".$strDateTime."$$$$','".$MyLastPostTime."','".$db->escape_string($GLOBALS['totalusetable'])."',".intval($GLOBALS['locktopic']).",".intval($GLOBALS['MyIsTop']).",".intval($GLOBALS['MyTopicMode']).",'".$GLOBALS['MyTopicFont']."',".$GLOBALS['isvote'].",".$GLOBALS['voteid'].",".$GLOBALS['topicmode'].",'".$GLOBALS['tomoney']."','".$db->escape_string($GLOBALS['UseTools'])."',".($GLOBALS['getmoneytype']?$GLOBALS['getmoneytype']:'NULL').",".$GLOBALS['isAlipayTopic'].",".$hidename.",'".$GLOBALS['activeid']."')";

	$db->query($stmt);
	set_cookie("lastuserposttime", $nowtimes);

	$RootID = $db->insert_id();
	if (1 == $ft_settings[0]) {	//插入全文索引分表
		$arrTopicIndex =& DV_ChineseWordSegment($GLOBALS['topic']);
		if( is_array($arrTopicIndex) && !empty($arrTopicIndex) ){
			$topicindex = $db->escape_string(implode(' ',$arrTopicIndex));
			if( $topicindex !== '' ){
				$db->query("INSERT INTO {$dv}topic_ft(topicid,boardid,posttable,topicindex) VALUES('{$RootID}','{$GLOBALS['boardid']}','".$db->escape_string($GLOBALS['totalusetable'])."','{$topicindex}')");
			}
		}
	}
}//end function Insert_To_Topic


//插入投票记录
function Insert_To_Vote(){
	global $isvote,$votenum,$dv,$db,$groupsetting,$uarticle,$uwealth,$uep,$ucp,$upower,$vote,$votetype,$voteid,$Postid;
	$uarticle = intval($uarticle);
	$uwealth = intval($uwealth);
	$uep = intval($uep);
	$ucp = intval($ucp);
	$upower = intval($upower);
	//groupSetting[68]投票项目中是否可以使用HTML
	if( $groupsetting[68] != 1 ){
		$vote = preg_replace('/&amp;#(\d+)(;?)/ie', '(("$1">127)?"&#$1$2":"$1")', htmlspecialchars($vote));
	}
	$vote = stripslashes($vote);
	$db->query("INSERT INTO {$dv}vote(vote,votenum,votetype,timeout,uarticle,uwealth,uep,ucp,upower) VALUES ('".$db->escape_string($vote)."','".$db->escape_string($votenum)."',".$votetype.",'".$db->escape_string($GLOBALS['votetimeout'])."',".$uarticle.",".$uwealth.",".$uep.",".$ucp.",".$upower.")");
	$voteid = intval($db->scalar("SELECT MAX(voteid) FROM {$dv}vote"));
	$isvote = 1;
}//end function Insert_To_Vote
//-------------------------2007-8-27  active start-------------------------------
function Insert_To_Active(){
 global $userid,$isvote,$dv,$db,$groupsetting,$uarticle,$activesubject,$activiecity,$activieclass,$starttime,$endtime,$activieplace,$cost,$sex,$strength,$expiretime,$timemode,$endtime,$activeid;
 $db->query("INSERT INTO {$dv}active(postuserid,activename,activecity,activeclass,timemode,starttime,endtime,location,cost,sex,strength,expiretime) VALUES(".$userid.",'".$activesubject."','".$activiecity."','".$activieclass."',".$timemode.",'".$starttime."','".$endtime."','".$activieplace."','".$cost."','".$sex."','".$strength."','".$expiretime."');");
 $activeid= intval($db->scalar("SELECT MAX(activeid) FROM {$dv}active"));
 $isvote = -2;
}//end function Insert_To_Active
function Get_SaveRe_TopicInfo(){
	global $dv,$db,$boardid,$RootID,$lang,$userinfo,$getmoneytype,$ajax_action;
	if( $query = $db->query("SELECT locktopic,lastpost,title,smsuserlist,issmstopic,istop,child,usetools,lastposttime,getmoneytype,postuserid, dateandtime FROM {$dv}topic WHERE boardid={$boardid} AND topicid=".$RootID) ){
		$tmpResult = $db->fetch_array($query);
	}
	if( empty($tmpResult) ){
		return;
	}
	global $board_settings,$toptopic,$istop,$Child,$Tools_UseTools,$Tools_LastPostTime,$smsuserlist,$master,$boardmaster,$superboardmaster;
	if( ( $master !== true || $boardmaster !== true || $superboardmaster !== true ) && $tmpResult['locktopic'] == 1 ){
		if (check_ajax()){
			echo $lang['Error.strings78']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['Error.strings78']);
		}	
		exit;
	}
	if( $tmpResult['getmoneytype'] == 5 ){
		if (check_ajax()){
			echo $lang['template.strings32']."@@@0@@@";encoding_footer();
		}else{
			head();
			showmsg($lang['template.strings32']);
		}	
		exit;
	}
	//锁定多少天前的帖子判断
	if( $master === true || $boardmaster === true || $superboardmaster === true ){
		if( $board_settings[55] != 0 && dateDiff('d',$tmpResult['dateandtime'],time()) > $board_settings[55] ){
			if (check_ajax()){
				echo $lang['Error.strings78']."@@@0@@@";encoding_footer();
			}else{
				head();
				showmsg($lang['Error.strings78']);
			}	
			exit;
		}
	}
	$db->free_result($query);
	$toptopic = $tmpResult['title'];
	$istop = $tmpResult['istop'];
	$Child = $tmpResultRs['child'];
	$Tools_UseTools = ",{$tmpResult['usetools']},";
	$Tools_LastPostTime = $tmpResult['lastposttime'];
	if( $tmpResult['issmstopic'] == 1 ){
		$smsuserlist = $tmpResult['smsuserlist'];
	}
	global $lastpost,$UpLoadPic_n,$userid,$tomoney,$userinfo;
	if( $tmpResult['lastpost'] !='' && !is_null($tmpResult['lastpost']) ){
		$lastpost = explode('$',$tmpResult['lastpost']);
		if( count($lastpost) == 8 ){
			$UpLoadPic_n = $lastpost[4];
		} else{
			$UpLoadPic_n = '';
		}
	}
	if ($tmpResult['postuserid'] != $userid AND $tmpResult['getmoneytype'] == 2 AND $GLOBALS['getposttype'] == 1) {
		$getmoneytype = 4;
		$userinfo['usermoney'] -= $tomoney;
	} else{
		$getmoneytype = 0;
		$tomoney = 0;
	}
}//end function Get_SaveRe_TopicInfo

function Get_ForumTreeCode(){
	global $db,$dv,$totalusetable,$ParentID;
	if( $query = $db->query("SELECT b.layer,b.orders,b.emailflag,b.username,u.useremail FROM ".$db->escape_string($totalusetable)." b INNER JOIN {$dv}user u ON b.postuserid=u.userid WHERE b.announceid=".intval($ParentID)) ){
		$tmpResult = $db->fetch_array($query);
	}
	global $iLayer,$iOrders,$membername,$groupsetting,$fsetting,$lang,$boardid,$star,$RootID;
	if( !empty($tmpResult) ){
		if( $tmpResult['username'] == $membername ){
			if( $groupsetting[4] == 0 ){
				if (check_ajax()){
					echo $lang['Error.strings73']."@@@0@@@";encoding_footer();
				}else{
					head();
					showmsg($lang['Error.strings73']);
				}	
				exit;
			}
		} else{
			if( $tmpResult['emailflag'] > 0 ){
				$arrTmp[] = $lang['template.html0'];
				$arrTmp[] = $lang['template.html1'];
				$sUrl = getScriptUrl();
				if( $tmpResult['emailflag'] == 1 || $tmpResult['emailflag'] == 3 ){
					$etopic = str_replace('{$forumname}',$fsetting['forumname'],$lang['template.strings10']);
					$email = $tmpResult['useremail'];
					$mailbody = $lang['template.html0'];
					$mailbody = str_replace('{$boardid}',$boardid,$mailbody);
					$mailbody = str_replace('{$forumname}',$fsetting['forumname'],$mailbody);
					$mailbody = str_replace('{$topicid}',$RootID,$mailbody);
					$mailbody = str_replace('{$star}',$star,$mailbody);
					$mailbody = str_replace('{$surl}',$sUrl,$mailbody);
					$mailbody = str_replace('{$parentid}',$ParentID,$mailbody);
					mail($email,$etopic,$mailbody);
				}
				if( $tmpResult['emailflag'] == 2 || $tmpResult['emailflag'] == 3 ){
					$mailbody = $lang['template.html1'];
					$mailbody = str_replace('{$boardid}',$boardid,$mailbody);
					$mailbody = str_replace('{$topicid}',$RootID,$mailbody);
					$mailbody = str_replace('{$star}',$star,$mailbody);
					$mailbody = str_replace('{$surl}',$sUrl,$mailbody);
					$mailbody = str_replace('{$parentid}',$ParentID,$mailbody);
					$db->query("INSERT INTO {$dv}message(incept,sender,title,content,sendtime,flag,issend) VALUES('".$db->escape_string($tmpResult['username'])."','".$db->escape_string($fsetting['forumname'])."','".$db->escape_string($lang['template.strings26'])."','".$db->escape_string($mailbody)."','".time()."',0,1)");
					update_user_msg($tmpResult['username']);
				}
			}
		}
		if( is_null($tmpResult['layer']) || $tmpResult['layer'] == '' ){
			$iLayer = 0;
		} else{
			$iLayer = $tmpResult['layer'];
		}
		if( is_null($tmpResult['orders']) || $tmpResult['orders'] == '' ){
			$iOrders = 0;
		} else{
			$iOrders = $tmpResult['orders'];
		}
	} else{
		$iLayer = 1;
		$iOrders = 0;
	}
	global $RootID,$totalusetable;
	if( $RootID > 0 ){
		$iLayer++;
		$db->query("UPDATE ".$db->escape_string($totalusetable)." SET orders=orders+1 WHERE rootid=".intval($RootID)." AND orders>".intval($iOrders));
		$iOrders++;
	}
}//end function get_forumtreecode

function Insert_To_Announce(){//插入回复表
	global $board_settings,$dv,$db,$totalusetable,$Content,$AnnounceID,$userid, $__ViewFileID, $signflag, $MyTopicMode,$MyTopicFont,$dvstatu,$dvid;
	global $savvy_yes,$savvy_topicid,$Postid;
	$UbblistBody = Ubblist($Content);
	$signflag = intval($signflag);
	(!isset($dvstatu))&&($dvstatu='');
	(!isset($dvid))&&($dvid=0);
	if (2 == $signflag AND 0 == $board_settings[58]) {
		$signflag = 1;
	}
 
	if ($MyTopicMode == 1) {
		$tmptopic = stripslashes($GLOBALS['topic']);
		$topic = cross_site_html_proc($tmptopic, $errcode, $errstr);
		if ($errno OR $errstr) {
			$topic = $db->escape_string(strip_tags($tmptopic));
		} else {
			$topic = $db->escape_string($topic);
		}
	} else {
		$topic = $db->escape_string(preg_replace('/&amp;#(\d+)(;?)/ie', '(("$1">127)?"&#$1$2":"$1")', htmlspecialchars(stripslashes($GLOBALS['topic']))));
	}
	if(!empty($dvid)){
		$Content=preg_replace('/\[mergepic,[\d]?][_0-9a-z]*\[\/mergepic]/ei','',$Content);
		$Content="[mergepic,{$dvstatu}]{$dvid}[/mergepic]".$Content;
	}
	$emailflag = intval($GLOBALS['emailflag'] ? $GLOBALS['emailflag'] : $GLOBALS['mailflag']);
	if($savvy_yes==1){		
		$db->query("INSERT INTO ".$db->escape_string(strtolower($totalusetable))."(boardid,parentid,username,topic,body,dateandtime,length,rootid,layer,orders,ip,expression,locktopic,signflag,emailflag,isbest,postuserid,isupload,isaudit,ubblist,getmoney,usetools,postbuyuser,getmoneytype,forumtype) VALUES(".intval($GLOBALS['boardid']).",".intval($GLOBALS['ParentID']).",'".$db->escape_string($GLOBALS['username'])."','{$topic}','".$db->escape_string(cross_site_html_proc(stripslashes($Content), $errcode, $errstr))."','".time()."','".Dv_StrLength($Content)."',".intval($GLOBALS['savvy_topicid']).",".intval($GLOBALS['ilayer']).",".intval($GLOBALS['iorders']).",'".$db->escape_string($GLOBALS['usertrueip'])."','".$db->escape_string($GLOBALS['expression'][1])."',".intval($GLOBALS['locktopic']).",'".intval($GLOBALS['signflag'])."','{$emailflag}',0,".intval($GLOBALS['userid']).",'".intval($GLOBALS['ihaveupfile'])."',".intval($GLOBALS['IsAudit']).",'".$db->escape_string($UbblistBody)."',".intval($GLOBALS['tomoney']).",'".$db->escape_string($GLOBALS['UseTools'])."','".$db->escape_string($GLOBALS['ToolsBuyUser'])."',".intval($GLOBALS['getmoneytype']).",1)");	
	}

	$db->query("INSERT INTO ".$db->escape_string(strtolower($totalusetable))."(boardid,parentid,username,topic,body,dateandtime,length,rootid,layer,orders,ip,expression,locktopic,signflag,emailflag,isbest,postuserid,isupload,isaudit,ubblist,getmoney,usetools,postbuyuser,getmoneytype) VALUES(".intval($GLOBALS['boardid']).",".intval($GLOBALS['ParentID']).",'".$db->escape_string($GLOBALS['username'])."','{$topic}','".$db->escape_string(cross_site_html_proc(stripslashes($Content), $errcode, $errstr))."','".time()."','".Dv_StrLength($Content)."',".intval($GLOBALS['RootID']).",".intval($GLOBALS['ilayer']).",".intval($GLOBALS['iorders']).",'".$db->escape_string($GLOBALS['usertrueip'])."','".$db->escape_string($GLOBALS['expression'][1])."',".intval($GLOBALS['locktopic']).",'".intval($GLOBALS['signflag'])."','{$emailflag}',0,".intval($GLOBALS['userid']).",'".intval($GLOBALS['ihaveupfile'])."',".intval($GLOBALS['IsAudit']).",'".$db->escape_string($UbblistBody)."',".intval($GLOBALS['tomoney']).",'".$db->escape_string($GLOBALS['UseTools'])."','".$db->escape_string($GLOBALS['ToolsBuyUser'])."',".intval($GLOBALS['getmoneytype']).")");	
	if (($AnnounceID = $db->insert_id()) <= 0) {
		$AnnounceID = $db->scalar("SELECT MAX(announceid) FROM ".$db->escape_string($totalusetable)." WHERE postuserid=".intval($userid));
	}
	require_once INC_PATH.'BoardCache.class.php';
	Create_index_forumnum();//20070523
	global $ft_settings;
	if (1 == $ft_settings[0]) {	//插入记录到全文索引表
		$topicindex = '';
		$bodyindex = '';
		$arrTopicIndex = DV_ChineseWordSegment($GLOBALS['topic']);
		if( !empty($arrTopicIndex) && is_array($arrTopicIndex) ){
			$topicindex = $db->escape_string(implode(' ',$arrTopicIndex));
		}
		$arrBodyIndex = DV_ChineseWordSegment($Content);
		if( !empty($arrBodyIndex) && is_array($arrBodyIndex) ){
			$bodyindex = $db->escape_string(implode(' ',$arrBodyIndex));
		}
		if( $bodyindex !== '' ){
			$db->query("INSERT INTO {$dv}bbs_ft(announceid,boardid,posttable,topicindex,bodyindex) VALUES('{$AnnounceID}','{$GLOBALS['boardid']}','".$db->escape_string($totalusetable)."','{$topicindex}','{$bodyindex}')");
		}
	}
}//end function Insert_To_Announce

//发帖时用，为了减少入库量
//更新用户短信通知信息（新短信条数||新短讯ID||发信人名）
function UPDATE_User_Msg($username){
	global $dv,$db,$membername;
	$newmsg = newincept($username);
	if( $newmsg > 0 ){
		$msginfo = $newmsg.'||'.inceptid(1,$username).'||'.inceptid(2,$username);
	} else{
		$msginfo = '0||0||null';
	}
	$db->query("UPDATE {$dv}user SET usermsg='".$db->escape_string($msginfo)."' WHERE username='".$db->escape_string($username)."'");
}//end function UPDATE_User_Msg

//统计留言
function newincept($iusername){
	if( $iusername == '' ) return 0;
	global $dv,$db;
	return intval($db->scalar("SELECT COUNT(id) FROM {$dv}message WHERE flag=0 AND issend=1 AND DelR=0 AND incept='".$db->escape_string($iusername)."'"));
}//end function newincept

function inceptid($stype,$iusername){
	global $dv,$db;
	if( $query = $db->query("SELECT id,sender FROM {$dv}message WHERE flag=0 AND issend=1 AND DelR=0 AND incept='".$db->escape_string($iusername)."'",array('pageSize'=>1)) ){
		$tmpResult = $db->fetch_row($query);
	}
	if( empty($tmpResult) ){
		if( $stype == 1 ){
			return 0;
		} else{
			return 'null';
		}
	} else{
		if( $stype == 1 ){
			return $tmpResult[0];
		} else{
			return $tmpResult[1];
		}
	}
}//end function

//支付宝检查
function &CheckAlipay(){
	global $_POST;
	if( $_POST['alipay_seller'] == '@' || $_POST['alipay_seller'] == '' || $_POST['alipay_subject'] == '' || !is_numeric($_POST['alipay_price']) || $_POST['body'] == '' ){
		return '';
	}
	$strReturnVal = "[payto](seller){$_POST[alipay_seller]}(/seller)(subject){$_POST[alipay_subject]}(/subject)(body){$_POST[body]}(/body)(price){$_POST[alipay_price]}(/price)(transport){$_POST[ialipay_transport]}(/transport)";
	if( is_numeric($_POST['alipay_mail']) ){
		$strReturnVal .= "(ordinary_fee){$_POST[alipay_mail]}(/ordinary_fee)";
	}
	if( is_numeric($_POST['alipay_express']) ){
		$strReturnVal .= "(express_fee){$_POST[alipay_express]}(/express_fee)";
	}
	if( $_POST['alipay_demo'] != '' && strtolower($_POST['alipay_demo']) != 'http://' ){
		$strReturnVal .= "(demo){$_POST[alipay_demo]}(/demo)";
	}
	if( $_POST['alipay_ww'] != '' ){
		$strReturnVal .= "(ww){$_POST[alipay_ww]}(/ww)";
	}
	if( $_POST['alipay_qq'] != '' ){
		$strReturnVal .= "(qq){$_POST[alipay_qq]}(/qq)";
	}
	return $strReturnVal.'[/payto]';
}//end function CheckAlipay
function _reg_upfileurl($s1 ,$s2 ,$s3){
	//$s1=base64_encode(trim($s1));
	$s1=str_replace("\\","",$s1);
	$s2=str_replace("\\","",$s2);
	return (false !== strpos($s1, $s2))?$s3:$s1;
}
function _reg_upfilename($s){
	$s = str_replace(" ","%20",$s);
	//$s = str_replace("&","&amp;",$s);
	$s = str_replace("^","%5E",$s);
	$s = str_replace("\\'","\\\'",$s);
	$s = str_replace("{","%7B",$s);
	$s = str_replace("}","%7D",$s);
	$s = str_replace("[","\\[",$s);
	$s = str_replace("]","\\]",$s);
	$s = str_replace("(","\\(",$s);
	$s = str_replace(")","\\)",$s);
	$s = htmlspecialchars($s);

return $s;
}

function uploadedFilesProc() // 对已成功上传的文件进行处理，包括预览图片的生成
{
	global $fsetting, $Content, $upfileinfo, $ihaveupfile, $uploadedfilesinfo, $fsetting, $boardid, $userid, $membername, $db, $dv, $__upfileinfo;
	if (empty($Content)) {
		$Content =& $GLOBALS['body'];
	}

	$ihaveupfile = 0;
	$upfileinfo = '';
	//Start 检查上传临时目录中是否有此次上传的相关文件
		if (false !== strpos($__upfileinfo, '||')) {
			if ($tmparr = explode('||', $__upfileinfo)) {
				foreach ($tmparr AS $val) {
					$tmp1 = unserialize(base64_decode($val));
					foreach ($tmp1 AS $tmp2) {
						$uploadedfilesinfo[] = $tmp2;
					}
				}
				unset($tmparr, $tmp);
			}
		} else {
			$uploadedfilesinfo = unserialize(base64_decode($__upfileinfo));
		}
		if (empty($uploadedfilesinfo) OR !is_array($uploadedfilesinfo)) {
			return false;
		}

		//End 检查上传临时目录中是否有此次上传的相关文件
		//Start 初始化相关目录
		require_once INC_PATH.'upload.functions.php';
		$updirs = initUploadDirectories(array('init_preview_dir'=>true, 'init_space_preview_dir'=>true, 'init_space_updestdir'=>false, 'destdir'=>$uploadedfilesinfo[0]['subuploaddir']));
		FileHandler::find_writable_dir($updirs['uptmpdir']); // 设置可写目录
		$tmpimgdir = $updirs['uptmpdir'];
		$destdir = $updirs['updestdir'];
		$uploadsettings = explode('|', $fsetting['uploadsetting']);
		$canmakethumbnail = (($uploadsettings[17] != 0) AND canmakethumbnail());
		$previewimgdir = $updirs['previewdestdir'];
		//End 初始化相关目录


	$documentroot = $updirs['documentroot'];
	$comma = '';
	$insert_stmt = $renamelist_src = $renamelist_dest = array();
	$nowdate = time();
	$arrtmpname = array();

	foreach ($uploadedfilesinfo AS $key=>$val) {
		$val['ext'] = strtolower($val['ext']);
		//关于文件后缀/文件扩展名的一劳永逸的防范说明：除了图片以外的所有文件，都将在其文件名的末尾，追加一个下划线"_"，用于提高安全性
		//音乐文件也不加后缀(swf|wma|mp3)
		if ($val['ftype'] != 1 && false === strpos('|gif|jpg|jpeg|png|bmp|tif|iff|swf|wma|mp3|rm|avi|wav|', '|'.strtolower(trim($val['ext'])).'|')) {
			$val['ext'] .= '_';
		}
		$val['name'] = strtolower($val['name']);
		$thumbnailfile = $tmpimgdir.'/__dv_tmp_preview_file__'.$val['name'];
		$destfile = $destdir.'/'.$val['name'].'.'.$val['ext'];			// 即将移动到的正式存储位置
		$tmpfile = realpath($tmpimgdir.'/'.$val['uploaded_tmpfile']);	// 成功上传的在临时存储目录内的文件
		
		if (false === $tmpfile) {
			continue;
		}
		$previewfile = '';
		if ($val['ftype'] == 1 AND true === $canmakethumbnail) {
			
			if (image_thumbnail($tmpfile, $uploadsettings[14], $uploadsettings[15], $thumbnailfile)) {
				$previewfile = $previewimgdir.'/'.$val['name'].'.jpg';
				$renamelist_src[] = $thumbnailfile.'.jpg';
				$renamelist_dest[] = $previewfile;
			}
		}
		$renamelist_src[] = $tmpfile;
		$renamelist_dest[] = $destfile;
		$destfile = $db->escape_string(str_replace($updirs['uptopdir'].'/', '', $destfile));
		$previewfile = $db->escape_string(str_replace($updirs['uptopdir'].'/', '', $previewfile));
		$arrtmpname[] = $val['name'];
		$insert_stmt[] = "INSERT INTO {$dv}upfile(f_boardid,f_userid,f_username,f_filename,f_viewname,f_filetype,f_type,f_fileSize,f_flag,f_addtime) VALUES ('{$boardid}','{$userid}','{$membername}','".$db->escape_string($destfile)."','".$db->escape_string($previewfile)."','".$db->escape_string($val['ext'])."','".$db->escape_string($val['ftype'])."','".$db->escape_string($val['size'])."',4,'{$nowdate}')";
		if ((false !== strpos($Content, '<img src=\\"file:///')) and (!empty($val['LocalName']))) {
			$valLocalName= $val['LocalName'];
			$valUpUrl= $val['UpUrl'];
			$valLocalName=_reg_upfilename($valLocalName);

			$arrreg1[] = '/<img\s*src=\\\"file:\/\/\/(.*?\/'.$valLocalName.')\\\"\s*(.*?)\/>/iesm';
			$arrreg2[] = '_reg_upfileurl("$1","'.$valLocalName.'","'.$valUpUrl.'");';

		}
	}
		if (is_array ($arrreg1) ){
		$Content = preg_replace( $arrreg1 ,$arrreg2 ,$Content );
		}

	require INC_PATH.'BoardCache.class.php';
	Create_forum_show();//EDIT 2007-04-20
	if (!empty($renamelist_src) AND !empty($renamelist_dest)) {
		if (count($renamelist_src) == count($renamelist_dest)) {
			if (FileHandler::rename($renamelist_src, $renamelist_dest)) {
				foreach ($insert_stmt AS $index => $stmt) {
					if ($db->query($stmt)) {
						$insertedid = $db->insert_id();
						if ($insertedid <= 0) {
							$insertedid = $db->scalar("SELECT MAX(f_id) FROM {$dv}upfile");
						}
						if ($insertedid > 0) {
							$ihaveupfile = 1;
							$upfileinfo .= $comma.$insertedid;
							$comma =',';
							$Content = str_replace(']viewfile.php?id=ViewFileID_'.$arrtmpname[$index].'[/upload]', ']viewfile.php?id='.$insertedid.'[/upload]', $Content);
						}
					}
				}//end foreach
				@FileHandler::chmod($renamelist_dest, 0755);
			} else {
				head();
				global $php_errormsg, $lang;
				showmsg($lang['err.str6']);
				exit;
			}
		}
	}
}//end function uploadedFilesProc

//Start 辩论相关处理函数
	function ArgumentationMain()
	{
		global $action, $dv, $boardid, $board_settings, $userid, $membername, $id, $lang, $stats, $gettitle;
		if (false === strpos($action, 'argue')) {
			return true;
		}
		require_once INC_PATH.'argue_mod.functions.php';
		!defined('TABLE_PREFIX') AND define('TABLE_PREFIX', $dv);
		!defined('USER_ID') AND define('USER_ID', $userid);
		!defined('MEMBER_NAME') AND define('MEMBER_NAME', $membername);
		!defined('ROOT_ID') AND define('ROOT_ID', $id);
		!defined('BOARD_ID') AND define('BOARD_ID', $boardid);
		if ($board_settings[61] <= 0) {
			$board_settings[61] = 10;
		}
		!defined('PAGE_SIZE') AND define('PAGE_SIZE', $board_settings[61]);
		switch ($action) {
			case 'argue_topic':
				argue_topic();
				break;
			case 'argue_topic_edit':
				argue_topic_edit();
				break;
			case 'argue_reply':
				argue_reply();
				break;
			case 'argue_append':
				argue_append();
				break;
			default:
				return true;
				break;
		}//end switch
	}//end function ArgumentationMain
	function argue_topic()	//	发起一个辩论主题
	{
		global $db, $lang, $stats, $gettitle, $RootID, $expression;
		$gettitle = $stats = $lang['tpl.str4'];
		head(0, 1, 0);
		$argue_start_time = trim($_POST['argue_start_time']);
		if ($argue_start_time !== '') {
			$argue_start_time = dv_gmtimestamp($argue_start_time) - getUserTimeZoneOffset();
			if (-1 === $argue_start_time) {	//	开始时间格式不合法！
				showmsg($lang['err.str0']);
				exit;
			}
		} elseif (empty($argue_start_time)) {
			$argue_start_time = 0;
		}
		$argue_end_time = trim($_POST['argue_end_time']);
		if ($argue_end_time !== '') {
			$argue_end_time = dv_gmtimestamp($argue_end_time) - getUserTimeZoneOffset();
			if (-1 === $argue_end_time) {	//	结束时间格式不合法！
				showmsg($lang['err.str1']);
				exit;
			}
		} elseif (empty($argue_end_time)) {
			$argue_end_time = 0;
		}
		$argue_start_time = $argue_start_time + date('Z') - getUserTimeZoneOffset();
		$argue_end_time = $argue_end_time + date('Z') - getUserTimeZoneOffset();

		$argue_topic = trim($_POST['argue_topic']);
		if ('' === $argue_topic) {	//	请填写辩论主标题！
			showmsg($lang['err.str2']);
			exit;
		}
		$argue_title_obverse = trim($_POST['argue_title_obverse']);
		if ('' === $argue_title_obverse) {	//	请填写正方观点！
			showmsg($lang['err.str3']);
			exit;
		}
		$argue_title_reversed = trim($_POST['argue_title_reversed']);
		if ('' === $argue_title_reversed) {	//	请填写反方观点！
			showmsg($lang['err.str4']);
			exit;
		}
		$argue_context_info = trim($_POST['argue_context_info']);
		if ('' === $argue_context_info) {	//	请填写背景资料！
			showmsg($lang['err.str5']);
			exit;
		}
		$tmpexpression = '';
		$execresult = post_argumentation_topic(array('boardid'=>BOARD_ID, 'topic_title'=>$argue_topic, 'postuserid'=>USER_ID, 'postusername'=>MEMBER_NAME, 'title_obverse'=>$argue_title_obverse, 'title_reversed'=>$argue_title_reversed, 'start_time'=>$argue_start_time, 'end_time'=>$argue_end_time, 'context_info'=>$argue_context_info, 'expression'=>$tmpexpression));
		if (false === $execresult['execflag']) {	//	有错误发生
			showmsg($execresult['execmsg']);
			exit;
		} else {
			$RootID = $execresult['inserted_topicid'];
			succeed();
			footer();
		}
	}//end function argue_topic

	function argue_topic_edit()	//	编辑辩论主题
	{
	}//end function argue_topic_edit

	function argue_reply()	//	发表一个观点/回复/评论
	{
		global $db, $lang, $stats, $gettitle, $RootID, $_POST, $_GET, $expression, $ihaveupfile, $upfileinfo;

		$gettitle = $stats = $lang['tpl.str4'];
		head(0, 1, 0);
		if (!is_numeric($GLOBALS['parentid']) OR $GLOBALS['parentid'] <= 0) {
			$parentid = 0;
		} else {
			$parentid = $GLOBALS['parentid'] + 0;
		}
		checkmagicface();
		if (is_array($expression)) {
			if (0 == $parentid) {
				$tmpexpression = implode('|', $expression);
			} else {
				$tmpexpression = $expression[1];
			}
		} else {
			$tmpexpression = '';
		}
		uploadedFilesProc();
		$execresult = post_argumentation(array('boardid'=>BOARD_ID, 'rootid'=>ROOT_ID, 'arguetype'=>$GLOBALS['arguetype'], 'parentid'=>$parentid, 'argue_title'=>$_POST['topic'], 'argue_content'=>$_POST['body'], 'postuserid'=>USER_ID, 'postusername'=>MEMBER_NAME, 'expression'=>$tmpexpression, 'upfileidlist'=>$upfileinfo));
		if (false === $execresult['execflag']) {	//	有错误发生
			head();
			showmsg($execresult['execmsg']);
			exit;
		} else {
			$RootID = ROOT_ID;
			succeed();
			footer();
		}
	}//end function argue_reply

	function argue_append()	//	对某个观点/回复/评论进行补充
	{
		global $db, $lang, $stats, $gettitle, $RootID, $_POST, $_GET, $expression, $ihaveupfile, $upfileinfo;
		$gettitle = $stats = $lang['tpl.str4'];
		head(0, 1, 0);
		if (!is_numeric($GLOBALS['argueid']) OR $GLOBALS['argueid'] <= 0) {
			$argueid = 0;
		}
		$argueid = $GLOBALS['argueid'] + 0;
		checkmagicface();
		if (is_array($expression)) {
			if (0 == $parentid) {
				$tmpexpression = implode('|', $expression);
			} else {
				$tmpexpression = $expression[1];
			}
		} else {
			$tmpexpression = '';
		}
		uploadedFilesProc();
		$execresult = append_argumentation(array('argueid'=>$argueid, 'boardid'=>BOARD_ID, 'argue_title'=>$_POST['topic'], 'argue_content'=>$_POST['body'], 'postuserid'=>USER_ID, 'postusername'=>MEMBER_NAME, 'expression'=>$tmpexpression, 'upfileidlist'=>$upfileinfo));
		if (false === $execresult['execflag']) {	//	有错误发生
			showmsg($execresult['execmsg']);
			exit;
		} else {
			$RootID = ROOT_ID;
			succeed();
			footer();
		}
	}//end function argue_append
//End 辩论相关处理函数

function &__getAuditSettingsDbInfo($settingsid)
{
	if ($settingsid <= 0) {
		$returnval = false;
		return $returnval;
	}
	static $cache_auditsettings;
	if (!isset($cache_auditsettings[$settingsid])) {
		$cache_auditsettings[$settingsid] = false;
		global $_DCACHE;
		if (!isset($_DCACHE['forum_settings']) OR empty($_DCACHE['forum_settings'])) {
			$cachefile = CACHE_PATH.'board/board_all.php';
			if (!@is_file($cachefile) OR !@include($cachefile)) {
				require INC_PATH.'BoardCache.class.php';
				$objcache =& new BoardCache($db);
				$objcache->createAll();
				require($cachefile);
				unset($objcache);
			}
		}
		$cache_auditsettings[$settingsid] = $_DCACHE['forum_settings'][$settingsid];
		!empty($cache_auditsettings[$settingsid]) AND (3 != $cache_auditsettings[$settingsid]['class']) AND ($cache_auditsettings[$settingsid] = false);
	}
	return $cache_auditsettings[$settingsid];
}//end function __getAuditSettingsDbInfo
function NeedIsAudit()
{
	static $cache_isaudit;
	if (!isset($cache_isaudit)) {
		$GLOBALS['IsAuditcheck'] = 2;
		$cache_isaudit = 0;
		global $boardinfo, $userinfo;
		if ($boardinfo['audit_settings_id'] > 0) {
			$dbinfo =& __getAuditSettingsDbInfo($boardinfo['audit_settings_id']);
			if (!empty($dbinfo) AND !empty($dbinfo['setting'])) {
				$auditsettings = @unserialize($dbinfo['setting'][0]);
				if (!empty($auditsettings) AND (true === $auditsettings['isenable'])) {
						//检查豁免用户
						if (!empty($auditsettings['exempt_user_list'])) {
							require_once INC_PATH.'dv_fsettings.global.php';
							if (isset($auditsettings['exempt_user_list'][settingsHashCode($userinfo['username'])])) {
								$cache_isaudit = 0;
								return $cache_isaudit;
							}
						}
						//审核范围
						if (!empty($auditsettings['scope'])) {
							global $action;
							if ('snew' === $action) {	//	对新主题进行审核
								if (true !== $auditsettings['scope']['newtopic']) {
									$cache_isaudit = 0;
									return $cache_isaudit;
								}
							}
							if ('sre' === $action) {	//	对新回帖进行审核
								if (true !== $auditsettings['scope']['newreply']) {
									$cache_isaudit = 0;
									return $cache_isaudit;
								}
							}
							if ('sedit' === $action) {	//	对编辑帖进行审核
								if (true !== $auditsettings['scope']['reedit']) {
									$cache_isaudit = 0;
									return $cache_isaudit;
								}
							}
						}
						//审核等级——对不同的用户组进行“限制设置”的审核
						foreach ($auditsettings['grade'] AS $gradesettings) {
							if ((true !== $gradesettings['isenable']) || (true === $gradesettings['isenable'] AND $userinfo['usergroupid'] == $gradesettings['groupid'])) {
								
								if (true === $gradesettings['check_content']) {//“对内容进行检查”
									$cache_isaudit = 1;
									return $cache_isaudit;
								}
								if (true === $gradesettings['shield'] AND 2 == $userinfo['lockuser']) {//“被屏蔽用户审核”
									$cache_isaudit = 1;
									return $cache_isaudit;
								}
								// 验证主题数
								if (($gradesettings['topic_lessthan'] > 0) AND ($userinfo['usertopic'] < $gradesettings['topic_lessthan'])) {
									$cache_isaudit = 1;
									return $cache_isaudit;
								}
								// 验证发帖数
								if (($gradesettings['post_lessthan'] > 0) AND ($userinfo['userpost'] < $gradesettings['post_lessthan'])) {
									$cache_isaudit = 1;
									return $cache_isaudit;
								}
								// 验证注册时间少于多少天
								if (($gradesettings['register_lessthan'] > 0) AND (dateDiff('d', $userinfo['joindate'], TIME_NOW) < $gradesettings['register_lessthan'])) {
									$cache_isaudit = 1;
									return $cache_isaudit;
								}
								// 验证被删率
								if (($gradesettings['delete_morethan'] > 0) AND ($userinfo['userdel'] < $gradesettings['delete_morethan'])) {
									$cache_isaudit = 1;
									return $cache_isaudit;
								}
							}
						}//end foreach
						//敏感字设置
						if (!empty($auditsettings['sensitive_character_list'])) {
							foreach ($auditsettings['sensitive_character_list'] AS $key => $val) {
								if (1 == @preg_match('/'.$val.'/i', $GLOBALS['body'])) {
									$cache_isaudit = 1;
									$GLOBALS['IsAuditcheck'] = 1;
									return $cache_isaudit;
								}
							}//end foreach
						}
						//内容检查设置的审核
						if (!empty($auditsettings['check_content_misc'])) {
							if (true === $auditsettings['check_content_misc']['pic_audit']) {	//	含图片审核
								if (1 == preg_match('/(?:<img\s+)|(?:\[upload\s*=\s*(?:gif|jpg|jpeg|bmp|png)][^\[\n]*?\[\/upload])/i', $GLOBALS['body'])) {
									$cache_isaudit = 1;
									return $cache_isaudit;
								}
							}
							if (true === $auditsettings['check_content_misc']['link_audit']) {	//	含链接审核
								if (1 == preg_match('/(?:<a\s+href)|(?:\[url.*?].*?\[\/url])/i', $GLOBALS['body'])) {
									$cache_isaudit = 1;
									return $cache_isaudit;
								}
							}
							if (true === $auditsettings['check_content_misc']['flash_audit']) {	//	含flash审核
								if (1 == preg_match('/(?:<object.+?flash\/swflash.cab#version)|(?:<embed.*?ShockwaveFlash)|(?:\[flash=([0-9]+),([0-9]+)][^\s\[]*?\[\/flash])/i', $GLOBALS['body'])) {
									$cache_isaudit = 1;
									return $cache_isaudit;
								}
							}
							if (true === $auditsettings['check_content_misc']['realplayer_audit']) {	//	含RealPlayer审核
								if (1 == preg_match('/(?:<object.+?clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA)|(?:\[rm=([0-9]+),([0-9]+),(.*?)]([^\s\[]*)\[\/rm])/i', $GLOBALS['body'])) {
									$cache_isaudit = 1;
									return $cache_isaudit;
								}
							}
							if (true === $auditsettings['check_content_misc']['media_audit']) {	//	含媒体审核
								if (1 == preg_match('/(?:<object.+?)|(?:<embed.+?/i', $GLOBALS['body'])) {
									$cache_isaudit = 1;
									return $cache_isaudit;
								}
							}
						}
				}
			}
		}
	}
	return $cache_isaudit;
}//end function NeedIsAudit
?>