<?php
define('THIS_SCRIPT', 'dispbbs');

require_once 'global.php';
$stats= '';

if( $groupsetting[2] == 0 ){
	$lang = load_lang($lang, 'dispbbs' );
	$gettitle = str_replace('{$repl}', $boardinfo['boardtype'], $lang['Error.strings1']);
	head(0);
	showmsg($lang['Error.strings31']);
	exit;
}
if( !is_numeric($id) ){
	$id = 0;
}
if (!is_numeric($replyid)) {
	$replyid = 0;
}
if (!is_numeric($announceid)) {
	$announceid = 0;
}
if (!is_numeric($rootid)) {
	$rootid = 0;
}
$AnnounceID = $id;
if( $AnnounceID <= 0 ){
	$lang = load_lang($lang, 'dispbbs' );
	$gettitle = str_replace('{$repl}',$boardinfo['boardtype'],$lang['Error.strings1']);
	head(0);
	showmsg($lang['Error.strings30']);
	exit;
}
if( !is_numeric($replyid) ) $replyid = 0;
if( $replyid <= 0 ) $replyid = $AnnounceID;
if( !is_numeric($star) ){
	$star = 1;
}
if( !is_numeric($star) ){
	$star = 1;
}

if( !is_numeric($skin) ){
	$skin = intval($board_settings[83]);
}

$CanRead = false;
$TrueMaster = false;
if( $boardmaster === false ){
	if( $userid > 0 ){
		for( $i = 18 ; $i <= 31 ;$i++ ){
			if( $groupsetting[$i] == 1 ){
				$boardmaster = true;
				$CanRead = true;
				break;
			}
		}
	}
} else{
	$TrueMaster = true;
}
$userinfo['truemaster'] = $TrueMaster;
global $plus_index_value;
if(intval($plus_index_value['beplusvalue']['isuse'])==1){////edit 2007-04-25
	honortitle();
}
$SQL_CACHE = ' /*!40001 SQL_CACHE */ ';


//$SQL_CACHE = ' /*!40001 SQL_NO_CACHE */ ';
//-------------------------2007-8-27 active start-------------------------------------------
if( $query = $db->query("SELECT {$SQL_CACHE} CASE WHEN topicmode<>1 THEN REPLACE(title,'<','&lt;') ELSE title END AS title,boardid,istop,isbest,postusername,postuserid,hits,isvote,child,pollid,locktopic,posttable,boardid,topicmode,topicfont,getmoney,usetools,getmoneytype,dateandtime,expression,topicid,activeid,topicid AS replyid,topicid AS star,topicid AS page,@PostUserIDList:=NULL FROM {$dv}topic WHERE topicid={$AnnounceID}",array('pageSize'=>1)) ){
 $TopicInfo =& $db->fetch_array($query);
 if($boardid==0)$boardid=intval($TopicInfo['boardid']);
}

//-------------------------2007-8-27 active end-------------------------------------------

if( empty($TopicInfo) ){
	$lang = load_lang($lang, 'dispbbs' );
	$gettitle = strip_tags(str_replace('{$repl}',$boardinfo['boardtype'],$lang['Error.strings1']));
	//head(0);
	LoadStyleJs();
	showmsg($lang['Error.strings33']);
} else{
	$db->free_result($query);
	if (-1 == $TopicInfo['isvote']) {
		header('Location: dispargue.php?boardid='.$boardid.'&id='.$TopicInfo['topicid'].'&star='.$star.'&page='.$page.'&skin='.$skin);
		exit;
	}
	$TotalUseTable = $TopicInfo['posttable'];
	$T_GetMoneyType = $TopicInfo['getmoneytype'];
	//锁定N天前的帖子判断
	if( $board_settings[55] != 0 && $TopicInfo['locktopic'] == 0 && dateDiff('d',$TopicInfo['dateandtime'],TIME_NOW) > $board_settings[55] ){
		$TopicInfo['locktopic'] = 1;
		$setStmt = ',locktopic=1';
	}
	$db->query("UPDATE {$dv}topic SET hits=(CASE WHEN hits IS NULL THEN 1 ELSE hits+1 END) {$setStmt} WHERE topicid={$AnnounceID}");
	$TopicInfo['title'] = ChkBadWords($TopicInfo['title']);
}

$CanReply = false;
if( $userid <= 0 && $groupsetting[3] == 0 ){
	$CanReply = false;
} elseif(($master === true||$boardmaster===true||$superboardmaster===true)||($boardinfo['allowpost']==1&&$TopicInfo['locktopic']==0)){
	$CanReply = true;
}
//********************************

//***************************************
global $PageCount;
$TopicCount = $TopicInfo['child'] + 1;
$pagesize = $board_settings[61];
if ($pagesize < 1) {
	$pagesize = 30;
}
$PageCount = ceil( (float)$TopicCount / (float)$pagesize );
$star = (is_numeric($star)?$star:1);
$page = (is_numeric($page)?$page:1);
if( $star > $PageCount ) $star = $PageCount;
if( $star < 1 ) $star = 1;


if($userid == 0){
	$indexstatic= CACHE_PATH."static/dispbbs_0_".$boardid."_".$id.".php";
}
else{
	$indexstatic= CACHE_PATH."static/dispbbs_".$boardid."_".$id.".php";
}
global $useindexstatic,$useindexstatic_file;
$useindexstatic=false;

if($fsetting['useindexstatic'] == 0){
	$useindexstatic_css= false;//为FALSE时是关闭缓存
}
else{	
	$useindexstatic=false;
	$useindexstatic_file= true;
	if($useindexstatic_css)
		if(file_exists($indexstatic))
			$useindexstatic= true;
}

$tempmaster= $master;
if((!$useindexstatic) || (!$useindexstatic_css) || $page>1 || $star>1 || $skin==1){
	if($useindexstatic_css && $page<2 && $star<2 && $skin!=1){
		$useindexstatic= true;
	}
	else
		$useindexstatic= false;

	$lang = load_lang($lang, 'dispbbs' );
	include_once INC_PATH.'DV_Encoding.class.php';

	if( !empty($TopicInfo) ){
		$stats = $TopicInfo['title']. ' - ' .preg_replace( '/<([^<>]*?)>/i' ,'' ,$boardinfo['boardtype']);
	}
	$gettitle = strip_tags($TopicInfo['title']);
	$gettitle = $TopicInfo['title'];
	if ($gettitle != '') {
		$objenc =& DV_Encoding::GetEncoding($charset);
		$_topictitlelength = $objenc->StrLength($gettitle);
		if ($_topictitlelength > 100) {
			$gettitle = '<span title="'.strip_tags($gettitle).'">'.$objenc->SubString(strip_tags($gettitle), 0, 35).'</span>...';
		}
	}

	include_once CACHE_PATH.'forum_pic.php';
	$empath = $_DCACHE['forum_emot'][0];
	//Start 过滤标题HTML
	if( $TopicInfo['topicmode'] != 1 ){
		$topicStmt = "topic";
	} else{
		$topicStmt = "topic";
	}
	//End 过滤标题HTML
	if( $skin == 1 ){
		if( $replyid == $AnnounceID ){
			$stmt = "SELECT {$SQL_CACHE} announceid,username,{$topicStmt},dateandtime,body,expression,ip,rootid,signflag,emailflag,isbest,postuserid,layer,isagree,getmoneytype,isupload,ubblist,locktopic,getmoney,usetools,postbuyuser,parentid,@PostUserIDList:=COALESCE(CONCAT(@PostUserIDList,',',postuserid),postuserid) AS postuseridlist FROM ".strtolower($TopicInfo['posttable'])." WHERE boardid={$boardid} AND rootid={$AnnounceID} AND forumtype=0 ORDER BY dateandtime ASC";
		}
		else{
			$pagesize = 1;
			$istar = $star;
			$star = 1;
			$stmt = "SELECT {$SQL_CACHE} announceid,username,{$topicStmt},dateandtime,body,expression,ip,rootid,signflag,emailflag,isbest,postuserid,layer,isagree,getmoneytype,isupload,ubblist,locktopic,getmoney,usetools,postbuyuser,parentid,@PostUserIDList:=COALESCE(CONCAT(@PostUserIDList,',',postuserid),postuserid) AS postuseridlist FROM ".strtolower($TopicInfo['posttable'])." WHERE announceid={$replyid} AND boardid={$boardid} ORDER BY dateandtime ASC";
		}
	}
	else{
		$stmt = "SELECT {$SQL_CACHE} announceid,username,{$topicStmt},dateandtime,body,expression,ip,rootid,signflag,emailflag,isbest,postuserid,layer,isagree,getmoneytype,isupload,ubblist,locktopic,getmoney,usetools,postbuyuser,parentid,@PostUserIDList:=COALESCE(CONCAT(@PostUserIDList,',',postuserid),postuserid) AS postuseridlist FROM ".strtolower($TopicInfo['posttable'])." WHERE boardid={$boardid} AND rootid={$AnnounceID} AND forumtype=0 ORDER BY dateandtime ASC, announceid ASC";
	}
	$NumRows = 0;
	if( $query = $db->query($stmt,array('absolutePage'=>$star,'pageSize'=>$pagesize)) ){
		$postResultCount = 0;
		$refPostResult = array();
		$NumRows = $db->num_rows($query);
		while( $result =& $db->fetch_array($query) ){
			//过滤脏字
			$result['username'] = ChkBadWords($result['username']);
			$result['topic'] = ChkBadWords($result['topic']);
			$result['body'] = ChkBadWords($result['body']);
			$_PostResults[$postResultCount] =& $result;

			$refPostResult["{$result[postuserid]}"][] =& $result;
			$postResultCount++;
		}
		$db->free_result($query);
	}
	if( !empty($_PostResults) ){
		$nameglow = array( $_DCACHE['stylecss'][43] ,$_DCACHE['stylecss'][41] ,$_DCACHE['stylecss'][41] ,$_DCACHE['stylecss'][39] ,null ,null  ,$_DCACHE['stylecss'][40] );
		$TopicInfo['replyid'] = $_PostResults[0]['announceid'];
		$TopicInfo['star'] = $star;
		$TopicInfo['page'] = $page;
		$TopicInfo['skin'] = $skin;
		//如果顶楼是主题帖，并且是购买帖的时候，提取购买信息
			//主题金币帖子类型0=无，1=赠送金币帖，2=获赠金币帖，3=金币购买帖，4=回复赠送金币（回复表），5=已结帖（主题表）
		if( $_PostResults[0]['parentid'] == 0 && $TopicInfo['getmoneytype'] == 3 ){
			$_PostResults[0]['postbuyuser'] = trim($_PostResults[0]['postbuyuser']);
			$postbuyinfo = array( 'money' => 0 ,'maxbuy' => 0 ,'notvipbuy' => '' ,'buyuser' => '' );
			if ($_PostResults[0]['postbuyuser'] !== '') {
				$postbuyusers = explode('|||', $_PostResults[0]['postbuyuser']);
				//postbuyinfo[0] 收入 postbuyinfo[1] 购买限制 postbuyinfo[2] vip是否需要购买 postbuyinfo[3] 允许购买用户列表
				$postbuyinfo = explode('@@@',$postbuyusers[0]);
				if( count($postbuyinfo) > 3 ){
					$postbuyinfo = array( 'money' => $postbuyinfo[0] ,'maxbuy' => $postbuyinfo[1] ,'notvipbuy' => $postbuyinfo[2] ,'buyuser' => ",{$postbuyinfo[3]}," );
				}
			}
		}
		//发帖用户ID列表
		if( $postResultCount > 0 ) $postuseridlist = $_PostResults[$postResultCount-1]['postuseridlist'];
		if(intval($plus_index_value['beplusvalue']['isuse'])==1){//edit 2007-04-25
			$query_sql="SELECT {$SQL_CACHE} u.userid,u.username,u.useremail,u.userim,u.usermobile,u.usersign,u.userclass,u.usertitle,u.userwidth,u.userheight,u.userpost,u.userface,u.joindate,u.userwealth,u.userep,u.usercp,u.userbirthday,u.usersex,u.usergroup,u.lockuser,u.userpower,u.titlepic,CASE WHEN u.usergroupid IS NULL OR u.usergroupid<=0 THEN 7 ELSE u.usergroupid END AS usergroupid,u.lastlogin,u.userhidden,u.ischallenge,u.usermoney,u.userticket,u.useravasetting,u.userisava,u.userhonor FROM {$dv}user u WHERE u.userid IN ({$postuseridlist})";
		}
		else{
			$query_sql="SELECT {$SQL_CACHE} u.userid,u.username,u.useremail,u.userim,u.usermobile,u.usersign,u.userclass,u.usertitle,u.userwidth,u.userheight,u.userpost,u.userface,u.joindate,u.userwealth,u.userep,u.usercp,u.userbirthday,u.usersex,u.usergroup,u.lockuser,u.userpower,u.titlepic,CASE WHEN u.usergroupid IS NULL OR u.usergroupid<=0 THEN 7 ELSE u.usergroupid END AS usergroupid,u.lastlogin,u.userhidden,u.ischallenge,u.usermoney,u.userticket,u.useravasetting,u.userisava FROM {$dv}user u WHERE u.userid IN ({$postuseridlist})";
		}
		if( !empty($postuseridlist) ){
			if( $query = $db->query($query_sql) ){
				$forumad_topic = intval($fsetting['forumad_topic']);
				include_once INC_PATH.'dv_code.php';
				$nowtimes = TIME_NOW;
				while( $result =& $db->fetch_array($query) ){
					if (2 == $result['userhidden']) {
						if (is_numeric($result['lastlogin']) AND $result['lastlogin'] > 0) {
							if (dateDiff('s', $result['lastlogin'], $nowtimes) > $fsetting['onlinetimeout'] * 60) {
								$result['userhidden'] = 1;
							}
						} else {
							$result['userhidden'] = 1;
						}
					} else {
						$result['userhidden'] = 1;
					}
					$tmpRef =& $refPostResult["{$result[userid]}"];
					$ubblists= array(',9,',',10,',',11,',',12,',',13,',',14,',',15,',',41,');
					foreach( $tmpRef AS $key=>$val ){
						$result['current_replyid'] = $result['current_announceid'] = $tmpRef[$key]['announceid'];
						$result['current_rootid'] = $tmpRef[$key]['rootid'];
						$result['posttable'] = $TopicInfo['posttable'];
						$result['postbuyuser'] = $tmpRef[$key]['postbuyuser'];
						//Ubb转换
						if( strpos($tmpRef[$key]['ubblist'],',39,') !== false ){
							$tmpRef[$key]['body'] = Dv_CodeProcess($tmpRef[$key]['body'],$result,$tmpRef[$key]['ubblist'],1,0);
						} else{
							$tmpRef[$key]['body'] = Dv_CodeProcess($tmpRef[$key]['body'],$result,$tmpRef[$key]['ubblist'],1,1);
						}
						//如果帖子内容为特殊内容,不使用缓存
						if($useindexstatic){
							if($tmpRef[$key]['locktopic'] != 0){
								$useindexstatic= false;
							}
							else{
								for($i=0;$i<8;$i++){
									if(strpos($tmpRef[$key]['ubblist'],$ubblists[$i]) !== false ){
										$useindexstatic= false;
										break;
									}
								}
							}
						}
						//利用ubblist节点传送广告数据
						if( $forumad_topic === 1 ){
							$tmpRef[$key]['ubblist'] = Topic_Ads();
						} else{
							$tmpRef[$key]['ubblist'] = '';
						}
					}
					$postUserResult["{$result['userid']}"] =& $result;
				}
			}
		}
	}
	//投票数据结构
	if( $TopicInfo['isvote'] == 1 ){
		if( $query = $db->query("SELECT {$SQL_CACHE} voteid,vote,votenum,votetype,lockvote,voters,timeout,uarticle,uwealth,uep,ucp,upower FROM {$dv}vote WHERE voteid='".$TopicInfo['pollid']."'") ){
			$NumSum = 0;
			$voteinfo =& $db->fetch_array($query);
			if( !empty($voteinfo) ) {
				$db->free_result($query);
				$voteinfo['voteitem'] = explode('|', $voteinfo['vote']);
				$voteinfo['num'] = explode('|', $voteinfo['votenum']);
				unset($voteinfo['vote'],$voteinfo['votenum']);
				$voteinfo['SumNum'] = 0;
				if( is_array($voteinfo['num']) ){
					foreach( $voteinfo['num'] AS $num ){
						$voteinfo['NumSum'] += intval($num);
					}
				}
				//投票过期限制判断
				if( dateDiff('S',$voteinfo['timeout'],TIME_NOW) > 0 ){
					$voteinfo['istimeout'] = 1;
				} else{//检查此人是否已经投过票了
					if( $userid > 0 && $TopicInfo['locktopic'] === 0 && $voteinfo['userid'] === $userid ){
						$voteinfo['alreadyvote'] = 1;
					}
				}
			}
		}
	}
	//-------------------------2007-8-27 active start-------------------------------------------
	if( $TopicInfo['isvote'] == -2 ){
	  if( $query = $db->query("SELECT {$SQL_CACHE} activeid,activename,activecity,activeclass,timemode,starttime,endtime,location,cost,sex,strength,expiretime,postuserid FROM {$dv}active WHERE activeid='".$TopicInfo['activeid']."'")){
	  $activeinfo =& $db->fetch_array($query);
	   if( !empty($activeinfo) ) {
	   $db->free_result($query);
	   }
	  }
	  $joinquery = $db->query("SELECT u1.id,u1.joindate,u1.userid,u1.costmode,u1.costnum,u1.systemmode,u1.message,u1.isexamine,u2.username FROM {$dv}activeuser as u1,{$dv}user as u2 WHERE activeid='".$TopicInfo['activeid']."' and u1.userid = u2.userid;");
	  if( $nonum = $db->query("SELECT {$SQL_CACHE} count(*) as nonum from {$dv}activeuser where isexamine = 0 and activeid='".$TopicInfo['activeid']."'")){
	  $activenonum =& $db->fetch_array($nonum);
	   if( !empty($activenonum) ) {
	   $db->free_result($nonum);
	   }
	  }
	  if( $isnum = $db->query("SELECT {$SQL_CACHE} count(*) as isnum from {$dv}activeuser where isexamine = 1 and activeid='".$TopicInfo['activeid']."'")){
	  $activeisnum =& $db->fetch_array($isnum);
	   if( !empty($activeisnum) ) {
	   $db->free_result($nonum);
	   }
	  }
	}
	//-------------------------2007-8-27 active end-------------------------------------------

	if( $GLOBALS['CanReply'] ){
		$userinfo['canreply'] = true;
	}
	if( $board_settings[58] == 1 ){
		$userinfo['cananony'] = 1;
	}

	//Start 相关主题处理
	$ft_settings = explode('|', $fsetting['ft_settings']);
	if (1 == $ft_settings[0] AND 1 == $ft_settings[1] AND !empty($_PostResults)) {
		$SQL_CACHE = ' /*!40001 SQL_CACHE */ ';
		//$SQL_CACHE = ' /*!40001 SQL_NO_CACHE */ ';
		$tmpTopicTitle = preg_replace('#^\[.*?]#i','',$TopicInfo['title']);
		$arrTopicTitle =& DV_ChineseWordSegment($tmpTopicTitle);
		//echo implode(' ',$arrTopicTitle);
		if (is_array($arrTopicTitle) AND !empty($arrTopicTitle)) {
			$topicIDList = '';
			$limitNumber = 5;
			$keyWordCount = 3;
			$stmt = '';
			$count = count($arrTopicTitle);
			if( $count > 1 ){
				$stmt = '';
				if( $count <= $keyWordCount ){
					for( $i = 0 ; $i < $count ; $i++  ){
						if( $stmt !== '' ){
							$stmt .= "\r\n UNION \r\n";
						}
						$stmt .= "\r\n(SELECT {$SQL_CACHE} SQL_SMALL_RESULT ft.topicid FROM {$dv}topic_ft AS ft WHERE MATCH(ft.topicindex) AGAINST('{$arrTopicTitle[$i]}') AND (ft.boardid<>444 AND ft.locktopic=0) AND ft.posttable='{$TotalUseTable}' AND ft.topicid<>'{$TopicInfo['topicid']}' LIMIT {$limitNumber})\r\n";
					}
				} else{
					$arrRand = array();
					for( $i = 0 ; $i < $keyWordCount ; $i++  ){
						$indexRand = array_rand($arrTopicTitle);
						if( isset($arrRand[$arrTopicTitle[$indexRand].'']) ){
							//$i--;
							continue;
						}
						$arrRand[$arrTopicTitle[$indexRand].''] = true;
						if( $stmt !== '' ){
							$stmt .= ' UNION ';
						}
						$stmt .= "\r\n(SELECT {$SQL_CACHE} SQL_SMALL_RESULT ft.topicid FROM {$dv}topic_ft AS ft WHERE MATCH(ft.topicindex) AGAINST('{$arrTopicTitle[$indexRand]}') AND (ft.boardid<>444 AND ft.locktopic=0) AND ft.posttable='{$TotalUseTable}' AND ft.topicid<>'{$TopicInfo['topicid']}' LIMIT {$limitNumber})\r\n";
					}
				}
				$stmt .= "ORDER BY RAND()";
			} elseif( $count === 1 ){
				$stmt = "SELECT {$SQL_CACHE} SQL_SMALL_RESULT ft.topicid FROM {$dv}topic_ft AS ft WHERE MATCH(ft.topicindex) AGAINST('{$arrTopicTitle[0]}') AND (ft.boardid<>444 AND ft.locktopic=0) AND ft.topicid<>'{$TopicInfo['topicid']}'";
			}
			if( $query = $db->query($stmt,array('pageSize'=>$limitNumber)) ){
				$comma = '';
				while( $tmpResult =& $db->fetch_row($query) ){
					$topicIDList .= "{$comma}{$tmpResult[0]}";
					$comma = ',';
				}
			}
			if (!empty($topicIDList)) {
				$stmt = "SELECT {$SQL_CACHE} SQL_SMALL_RESULT  dt.topicid,dt.title,dt.boardid,dt.pollid,dt.locktopic,dt.child,dt.postusername,dt.postuserid,dt.dateandtime,dt.hits,dt.expression,dt.votetotal,dt.lastpost,dt.lastposttime,dt.istop,dt.isvote,dt.isbest,dt.posttable,dt.smsuserlist,dt.issmstopic,dt.lastsmstime,dt.topicmode,dt.topicfont,dt.mode,dt.getmoney,dt.usetools,dt.getmoneytype,dt.hidename FROM {$dv}topic AS dt WHERE dt.topicid IN({$topicIDList}) ORDER BY dt.topicid DESC";
				$arrRelatedTopic =& $db->getResultSet($stmt,array('pageSize'=>$limitNumber));
			}
		}
	}
	if($page<2){
		foreach ($postUserResult as $postUserResultlockuserarr){
			if($postUserResultlockuserarr['lockuser']==1){
				$useindexstatic=false;
			}
		}
	}
	//End 相关主题处理

	//End 相关主题处理
	if($useindexstatic){
		$master= true;
		$boardmaster= true;
		ob_start();
	}

	head();
	include printout('dispbbs');
	//***************************************
	if($useindexstatic){
		 $this_my_f= ob_get_contents(); //生成缓存文件
		 ob_end_clean();
		 to_static_php_file($indexstatic,$this_my_f);
	}
}
$master= $tempmaster;
if($useindexstatic)
	if($page < 2 && $topicmode==0){
		include_once($indexstatic);
		if($useindexstatic_file){
			unlink($indexstatic);
			if($_GET['reload'] != 1)
				echo "<script>document.location.href='dispbbs.php?reload=1&boardid={$boardid}&id={$id}&ftime=".microtime()."';</script>";
			return;
		}
	}

footer();

?>