<?php
define('THIS_SCRIPT', 'indivgroup_savepost');
require 'global.php';
require INC_PATH.'dv_code.php';
require_once INC_PATH.'FileHandler.class.php';
require_once INC_PATH.'image_misc.functions.php';
ini_set('display_errors','0');
ini_set('track_errors','1');
$lang = load_lang($lang, 'indivgroup_savepost' );
if($fsetting['indivgroup_show'] == 0)
{
	head();
	showmsg($lang['err.str7']);
	footer();
}
global $db,$dv,$userid,$membername;
head();
//检查发贴权限start
$groupid= intval($_GET["groupid"]);
$groupboardid= intval($_GET["groupboardid"]);
$groupmaster= false;							//是否群组管理员
if($userid <= 0)
	showmsg($lang['err.str8']);
if($fsetting['indivgroup_show'] == '0')
	showmsg($lang['err.str7']);

if (($groupid==0) || ($groupboardid == 0)){
	showmsg($lang['err.str9']);
}else{
	$groupinfo= array();
	if($query=$db->query("select id,groupname,groupinfo,appuserid,appusername,usernum,stats,postnum,topicnum,todaynum,yesterdaynum,limituser,appdate,passdate,visidate,locked,viewflag from {$dv}group_name where id={$groupid}")){
		if ($arr=$db->fetch_array($query)){
			$groupinfo=$arr;
		}
	}
	$db->free_result($query);

	if(count($groupinfo)==0)
		showmsg($lang['err.str10']);
	else{
		$groupmasterStr= $arr["appusername"];
		if(($groupmasterStr == $membername) && ($membername != ""))
			$groupmaster= true;

		$userresult=$db->query("select username from {$dv}group_user where islock=2 and groupid=".$groupid);	
		while ($userarr=$db->fetch_array($userresult)){
			if((trim($userarr["username"]) != "") && (trim($userarr["username"]) != $arr["appusername"])){
				$groupmasterStr.= "|".trim($userarr["username"]);
				if(($userarr["username"] == $membername) && ($membername != ""))
					$groupmaster= true;
			}
		}
		$db->free_result($userresult);
	}

	if(!$master)
		if($groupinfo["stats"] == '0')			//检查群组状态
			showmsg($lang['err.str11']);

	if(!($master || $groupmaster)){
		if($groupinfo["stats"] == '3')
			showmsg($lang['err.str12']);
		if($groupinfo["stats"] == '2')
			showmsg($lang['err.str13']);
		if($groupinfo["viewflag"] == '1'){
			if($userid == '')
				showmsg($lang['err.str14']);
			else{
				$usernum=intval($db->scalar("select count(1) from {$dv}group_user where userid={$userid} and groupid={$groupid} and islock<>0"));
				if($usernum==0)
					showmsg($lang['err.str15']);
			}
		}
	}

	$query=$db->query("select id boardid,rootid,boardname,boardname boardtype,boardinfo,indeximg,postnum,topicnum,todaynum,lastpost,boardstats,rules from {$dv}group_board where rootid={$groupid} and id={$groupboardid}");
	$showboardlist = 1;

	$groupboardnum= mysql_num_rows($query);
	if ($groupboardnum==0)
		showmsg($lang['err.str16']);
	else{
		$arr=$db->fetch_array($query);
		$groupboardinfo=$arr;
		if($groupboardinfo["boardstats"] == '0')
			showmsg($lang['err.str17']);
	}
	$db->free_result($query);
}
$isUser= intval($db->scalar("select count(1) from {$dv}group_user where groupid={$groupid} and islock<>0 and userid={$userid}"));
if(!$master)
	if($isUser == 0)
		showmsg($lang['err.str18']);
//检查发贴权限end

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

switch($GLOBALS['action']){
	case 'sre':
		if( $groupsetting[5] == 0 ){
			head();
			showmsg($lang['Error.strings71']);
			exit;
		}
		break;
	case 'sedit':
		break;
	default:
		break;
}


CheckfromScript();

//发贴的一些限制start
$title_limit= 100;
$content_limit= 65353;
$time_limit= 10;
//发贴的一些限制end

$topic = trim($topic);
if( Dv_StrLength($topic) > $title_limit){
	head();
	showmsg(str_replace('{$topiclimited}',$title_limit,$lang['template.strings23']));
	exit;
}
if( $action == 'snew' || $action == 'svote' ){
	if( str_replace($lang['template.strings34'],'',$topic) === '' ){
		head();
		showmsg($lang['Error.strings20']);
		exit;
	}
}

$IsAudit = true;//NeedIsAudit();
$Reuser = false;
$FoundUseMagic = false;

if( $userid <= 0 ){
	$mailflag = 0;
	$signflag = 0;
} else{
	$signflag = intval(trim($signflag));
}
$MyTopicMode = trim($topicximoo);
$MyTopicFont = (trim($topicfont) != '')?$topicfont:'0';
$MyLockTopic = trim($locktopic);
$MyIsTop = trim($istop);
$MyIstopAll = trim($istopall);
$topicmode = intval(trim($topicmode));

if( $board_settings[46] == 1 ){
	if( CodeIsTrue() !== true ){		
		head();
		showmsg($lang['Error.strings5']);	
		exit;
	}
}

//检查帖子内容
$Content =& CheckAlipay();
$isAlipayTopic = 2;
if( $Content == '' ){
	$Content =& $GLOBALS['body'];
	$isAlipayTopic = 0;
}
$contentLength = strlen($Content);
if( $contentLength > $content_limit){
	head();
	showmsg(str_replace('{$bodylimited}',$content_limit,$lang['template.strings24']));
	exit;
}
if( strpos($Content,'[/payto]') !== false && strpos($Content,'[payto]') !== false && strpos($Content,'(/seller)') !== false && strpos($Content,'(seller)') !== false ){
	$isAlipayTopic = 2;
}

$voteid = 0;
$isvote = 0;

if( $action == 'snew' || $action == 'svote' ){
	$CanLockTopic = false;
	$CanTopTopic = false;
	$CanTopTopic_a = false;
	if( $MyLockTopic == 'yes' || $MyIstopAll == 'yes' || $MyIsTop == 'yes' ){
		if( $master === true || $groupmaster === true){
			$CanLockTopic = true;
			$CanTopTopic = true;
			$CanTopTopic_a = true;
		}
	}
	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 = "{$dv}group_bbs1";//$fsetting['nowtablename'];
} elseif( $action == 'sre' ){
	$AnnounceID = $followup;
	$RootID = $rootid;
	if (!is_numeric($AnnounceID) OR !is_numeric($RootID)) {
		head();
		showmsg($lang['Error.strings30']);
		exit;
	}
	$ParentID = $AnnounceID;
	$MyLockTopic = 0;
} elseif( $action == 'sedit' ){
	if( !is_numeric($MyTopicMode)){
		$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' ){
	//判断发帖时间间隔
	$posttime = get_cookie('posttime');
	if( isDate($posttime) ){
		if( dateDiff('s', $posttime, gmdate('Y-m-d H:i:s')) < intval($time_limit) ){
			head();
			showmsg(str_replace('{$PostTimes}',$time_limit,$lang['template.strings33']));
			exit;
		}
	}
	set_cookie('posttime', gmdate('Y-m-d H:i:s'), $user_selected_cookiedate);
}
$userinfo['postdata'] = '';

if( $userid <= 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);
}

if( $action != 'sedit' ){
	savepost();
	if( $userid > 0 ){
		//更新用户积分，所需外部变量,UserPost,userid,（外加发帖回帖的积分设置数据）
		//updatepostuser();
	}
} else{
	Update_Edit_Announce();
}
succeed();

//通用判断
function Chk_Post(){
	global $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 ){
		head();
		showmsg($lang['Error.strings4']);
		exit;
	}
	if( $boardinfo['allowpost'] == 0 ){
		head();
		showmsg($lang['Error.strings72']);
		exit;
	}
	if( $boardinfo['ishidden'] == 1 && $groupsetting[37] == 0 ){
		head();
		showmsg($lang['Error.strings26']);
		exit;
	}
	if( $userid > 0 ){
		$grp52 = intval($groupsetting[52]);
		if( ($grp52 > 0) && (dateDiff('s',$userinfo['joindate'],TIME_NOW) < $grp52*60) ){
			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[0] ){
				head();
				showmsg(str_replace('{$topiclimited}',$groupsetting[62],$lang['template.strings27']));
				exit;
			}
		}
	}
	if( $groupsetting[3] == 0 && ($GLOBALS['action'] == 'snew' || $GLOBALS['action'] == 'svote' ) ){
		head();
		showmsg($lang['template.strings28']);
		exit;
	}
	if( $groupsetting[5] == 0 && $GLOBALS['action'] == 'sre' ){
		head();
		showmsg($lang['template.strings29']);
		exit;
	}
}//end function Chk_Post

//检查提交来源
function CheckfromScript(){
	global $boardid,$lang,$userid;

	if( $userid > 0 && preg_match('/snew|sre|svote/i',$GLOBALS['action']) === 1 && ChkUserLogin() === false ){
		head();
		showmsg($lang['Error.strings12']);
		exit;
	}
}//end function CheckfromScript

//检查用户身份
function ChkUserLogin(){
	global $dv,$db,$Reuser,$_POST,$boardid,$lang,$userid,$username,$fsetting,$membername,$UserPost,$GroupID,$UserClass;
	if( $userid <= 0 ){
		$username = $lang['guest'];
	} else {
		$username = $_POST['username'];
	}
	$usernamelength = Dv_StrLength($username);
	list($usernameminlength,$usernamemaxlength) = explode(',',$fsetting['usernamelength']);
	if( $username == '' || $usernamelength > $usernamemaxlength || $usernamelength < $usernameminlength ){
		head();
		showmsg($lang['Error.strings17']);
		exit;
	}
	if( IsTrueName($username) === false ){
		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 ){
		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);
	}
	//$tomoney = php_cCur($tomoney);
	$UseTools = '';
	$getmoneytype = 0;
	if( $getposttype != '' && ( $action == 'snew' || $action == 'svote' ) ){
		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;
	global $stats,$IsAudit,$action,$locktopic,$boardid,$board_settings,$IsAuditcheck,$arrNavMenu,$fsetting;
	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){
		head();//2007-04-19
	}
	require printout('indivgroup_savepost');
}//end function succeed()

//更新主题、帖子内容
function Update_Edit_Announce(){
	global $dv,$db,$Content,$username,$membername,$fsetting,$groupsetting,$groupid,$groupboardid,$userid,$lang,$signflag,$RootID,$userinfo;
	global $totalusetable,$AnnounceID,$CanEditPost,$master,$groupmaster;
	global $expression,$signflag,$topic,$MyTopicMode,$MyTopicFont,$isAlipayTopic;
	global $IsAudit,$usertrueip,$mailflag,$ihaveupfile,$upfileinfo,$FoundUseMagic;
	global $tmagicmoney,$lang,$tmagicticket,$char_changed;
	$totalusetable= "{$dv}group_bbs1";
	$Content = preg_replace(
				array(
					// '/<br>/i'
					'/\[align=right\]\[color=#000066\](.*)\[\/color\]\[\/align\]/'
					,'/<div align=right><font color=#000066>(.*)<\/font><\/div>/i'
					//,'/\[br\]/i'
				)
				,array(
					// '[br]'
					''
					,''
					//,'<br>'
				)
				,$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]';
			}
		}

	}
	$usernamecompare = '';
	if( $tmpResult['username'] == $membername ){
	}else{
		if($master === true || $groupmaster === true){
			$CanEditPost = true;
			//$usernamecompare = " AND username='{$username}' ";
		} 
		else{
			showmsg($lang['Error.strings77']);
			exit;
		}
	}
	//uploadedFilesProc(); // 处理上传文件
	$lastpost = trim($db->scalar("SELECT lastpost FROM {$dv}group_board WHERE id='{$groupboardid}'"));
	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}group_board SET lastpost='".$db->escape_string(htmlspecialchars($lastpost))."' WHERE id='{$groupboardid}'");
				//UpDate_BoardInfoAndCache();
			}
		}
	}

	//取得当前主题最后回复id,如果本帖为最后回复则更新相应数据0
	$lastpost = '';
	if( $query = $db->query("SELECT lastpost,istop,expression FROM {$dv}group_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);

	if( $query = $db->query("SELECT announceid,parentid,boardid,username,postuserid,topic,body,dateandtime,length,rootid,layer,orders,isbest,ip,expression,locktopic,signflag,isagree,ubblist FROM ".$db->escape_string(strtolower($totalusetable))." WHERE announceid={$AnnounceID}") ){
		$tmpResult = $db->fetch_array($query);
	}$usernamecompare = " AND username='{$username}' ";
	if( empty($tmpResult)) {
		head();
		showmsg($lang['Error.strings77']);
		exit;
	}
	elseif ( $master === false ) {
		if($tmpResult['username'] != $username ){
			head();
			showmsg($lang['Error.strings77']);
			exit;
		}
		else if($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."'";
			$db->query("UPDATE {$dv}group_topic SET title='".$db->escape_string($topic)."',topicmode={$MyTopicMode} {$iExpression},topicfont='".$MyTopicFont."',lastpost=".(!empty($lastpost) ? "'".$db->escape_string(strip_tags($lastpost))."'" : "lastpost")." WHERE topicid='{$RootID}'");
		} elseif (!empty($lastpost)) {
			$db->query("UPDATE {$dv}group_topic SET lastpost='".$db->escape_string(strip_tags($lastpost))."' WHERE topicid='{$RootID}'");
		}
		if( $tmpResult['locktopic'] == 3){
			$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;
		global $board_settings;
		if (2 == $signflag AND 0 == $board_settings[58]) {
			$signflag = 1;
		}
		$tmpResult['signflag'] = $signflag;
		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);
	}
}//end function Update_Edit_Announce

//判断用户是否有编辑权限且提取相关信息
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 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 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'];
			$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'];
			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,$groupid,$groupboardid,$userid;
	$LastPost_1 = str_replace('<','&lt;',$LastPost_1);
	if( $action == 'sre' ){
		$db->query("UPDATE {$dv}group_board SET postnum=postnum+1,todaynum=todaynum+1,lastpost='{$LastPost_1}' WHERE id ={$groupboardid}");
		$db->query("UPDATE {$dv}group_name SET postnum=postnum+1,todaynum=todaynum+1 WHERE id ={$groupid}");
	} elseif( $action == 'snew'){
		$db->query("UPDATE {$dv}group_board SET postnum=postnum+1,topicnum=topicnum+1,todaynum=todaynum+1,lastpost='{$LastPost_1}' WHERE id={$groupboardid}");
		$db->query("UPDATE {$dv}group_name SET postnum=postnum+1,topicnum=topicnum+1,todaynum=todaynum+1 WHERE id={$groupid}");
	}
}//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,$groupid,$groupboardid,$username,$IsAudit;
	if( $action == 'snew'){
		Insert_To_Topic();
	} 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));
		}
	}
	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( $action == 'sre' ){
		if( dateDiff('h',time(),$Tools_LastPostTime) <= 0 ){
			$stmt = "UPDATE {$dv}group_topic SET child=child+1,lastposttime='".time()."',lastpost='".$db->escape_string($lastpost)."' WHERE topicid={$RootID}";
		} else{
			$stmt = "UPDATE {$dv}group_topic SET child=child+1,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{
		$db->query("UPDATE {$dv}group_topic SET lastpost='".$db->escape_string($lastpost)."' WHERE topicid={$RootID}");
	}
	if( $action == 'snew' || $action == 'svote' ){
		$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)));

	UpDate_BoardInfoAndCache();
	//UpDate_ForumInfoAndCache();
	require_once INC_PATH.'BoardCache.class.php';
	Create_index_forumnum_group();
	set_cookie('dvbbs',$boardid, $GLOBALS['user_selected_cookiedate']);
}//end function savepost

function Insert_To_Topic(){//插入主题表
	global $groupsetting, $expression,$signflag,$RootID,$dv,$db,$userid, $MyIsTop, $MyTopicMode, $MyTopicFont, $ft_settings,$savvy_board,$fsetting,$groupid,$groupboardid;
	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']))));
	}//showmsg($expression[0]."###".$expression[1]."###".$expression);
	$strDateTime = $MyLastPostTime = time();
	//插入论坛贴子表
	$stmt = "INSERT INTO {$dv}group_topic (title,groupid,boardid,postusername,postuserid,dateandtime,expression,lastpost,lastposttime,locktopic,istop,pollid,mode,topicmode,topicfont) VALUES('{$topic}',{$groupid},{$groupboardid},'".$db->escape_string($GLOBALS['username'])."',".$GLOBALS['userid'].",'".$strDateTime."','".$db->escape_string($expression)."','$$".$strDateTime."$$$$','".$MyLastPostTime."',".intval($GLOBALS['locktopic']).",".intval($GLOBALS['MyIsTop']).",".$GLOBALS['voteid'].",".$GLOBALS['topicmode'].",".intval($GLOBALS['MyTopicMode']).",'".$GLOBALS['MyTopicFont']."')";
	$db->query($stmt);
	$RootID = $db->insert_id();
}//end function Insert_To_Topic

function Get_SaveRe_TopicInfo(){
	global $dv,$db,$boardid,$RootID,$lang,$userinfo,$groupid,$groupboardid,$getmoneytype;
	if( $query = $db->query("SELECT locktopic,lastpost,title,istop,child,lastposttime,postuserid, dateandtime FROM {$dv}group_topic WHERE boardid={$groupboardid} 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 || $groupmaster !== true) && $tmpResult['locktopic'] == 1 ){
		head();
		showmsg($lang['Error.strings78']);
		exit;
	}
	//锁定多少天前的帖子判断
	if( $master === true || $groupmaster === true){
		if( $board_settings[55] != 0 && dateDiff('d',$tmpResult['dateandtime'],time()) > $board_settings[55] ){
			head();
			showmsg($lang['Error.strings78']);
			exit;
		}
	}
	$db->free_result($query);
	$toptopic = $tmpResult['title'];
	$istop = $tmpResult['istop'];
	$Child = $tmpResultRs['child'];
	$Tools_LastPostTime = $tmpResult['lastposttime'];
	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;
	$totalusetable= "{$dv}group_bbs1";
	if( $query = $db->query("SELECT b.layer,b.orders,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 ){
				head();
				showmsg($lang['Error.strings73']);
				exit;
			}
		}
		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,$groupid,$groupboardid;
	$UbblistBody = Ubblist($Content);
	$signflag = intval($signflag);
	if (2 == $signflag) {
		$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']))));
	}

	$db->query("INSERT INTO ".$db->escape_string(strtolower($totalusetable))."(groupid,boardid,parentid,username,topic,body,dateandtime,length,rootid,layer,orders,ip,expression,locktopic,signflag,isbest,postuserid,isupload,ubblist) VALUES(".intval($GLOBALS['groupid']).",".intval($GLOBALS['groupboardid']).",".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'])."',".intval($GLOBALS['locktopic']).",'".intval($GLOBALS['signflag'])."',0,".intval($GLOBALS['userid']).",'".intval($GLOBALS['ihaveupfile'])."','".$db->escape_string($UbblistBody)."')");

	if (($AnnounceID = $db->insert_id()) <= 0) {
		$AnnounceID = $db->scalar("SELECT MAX(announceid) FROM ".$db->escape_string($totalusetable)." WHERE postuserid=".intval($userid));
	}
}//end function Insert_To_Announce

//支付宝检查
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
?>