<?php
define('THIS_SCRIPT', 'savvy_dispbbs');
require_once 'global.php';
require_once INC_PATH.'DV_Encoding.class.php';
$lang = load_lang($lang, 'savvy_dispbbs' );
$stats = $lang['HeaderTitle'];
if( $groupsetting[2] == 0 ){
	$gettitle = str_replace('{$repl}', $boardinfo['boardtype'], $lang['Error.strings1']);
	savvyhead(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 ){
	$gettitle = str_replace('{$repl}',$boardinfo['boardtype'],$lang['Error.strings1']);
	savvyhead(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($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 */ ';
if( $query = $db->query("SELECT {$SQL_CACHE} CASE WHEN topicmode<>1 THEN REPLACE(title,'<','&lt;') ELSE title END AS title,istop,isbest,postusername,postuserid,hits,isvote,child,pollid,locktopic,posttable,boardid,topicmode,topicfont,getmoney,usetools,getmoneytype,dateandtime,expression,topicid,solve,anonymity,againmoney,topicid AS replyid,topicid AS star,topicid AS page,topicid AS skin,@PostUserIDList:=NULL FROM {$dv}savvy_topic WHERE topicid={$AnnounceID} AND boardid={$boardid}",array('pageSize'=>1)) ){
	$TopicInfo =& $db->fetch_array($query);
}
if( empty($TopicInfo) ){
	$gettitle = strip_tags(str_replace('{$repl}',$boardinfo['boardtype'],$lang['Error.strings1']));
	savvyhead(0);
	showmsg($lang['Error.strings32']);
} 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}savvy_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;
}
//********************************


if( !empty($TopicInfo) ){
	$stats = $TopicInfo['title']. ' - ' .preg_replace( '/<([^<>]*?)>/i' ,'' ,$boardinfo['boardtype']);
}
$gettitle ='<a href="forum_savvy.php?boardid='.$boardid.'">'.$lang['dv_fsettings.global.str4'].'</a> → '.$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>...';
	}
}
savvyhead();


//***************************************
$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( $page > 0 ) $star = $page;
if( $star > $PageCount ) $star = $PageCount;
if( $star < 1 ) $star = 1;
require_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,savvy_comment,forumtype,ask_solve,@PostUserIDList:=COALESCE(CONCAT(@PostUserIDList,',',postuserid),postuserid) AS postuseridlist FROM ".strtolower($TopicInfo['posttable'])." WHERE boardid={$boardid} AND rootid={$AnnounceID} AND forumtype=1";
	} 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,savvy_comment,forumtype,ask_solve,@PostUserIDList:=COALESCE(CONCAT(@PostUserIDList,',',postuserid),postuserid) AS postuseridlist FROM ".strtolower($TopicInfo['posttable'])." WHERE announceid={$replyid} AND boardid={$boardid}";
	}
} 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,savvy_comment,forumtype,ask_solve,@PostUserIDList:=COALESCE(CONCAT(@PostUserIDList,',',postuserid),postuserid) AS postuseridlist FROM ".strtolower($TopicInfo['posttable'])." WHERE boardid={$boardid} AND rootid={$AnnounceID} AND forumtype=1 ORDER BY ask_solve DESC, dateandtime ASC";//dateandtime  announceid
}
$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]}"];
				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);
					}
					//利用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;
				}
			}
		}
	}
}
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 */ ';
	$tmpTopicTitle = preg_replace('#^\[.*?]#i','',$TopicInfo['title']);
	$arrTopicTitle =& DV_ChineseWordSegment($tmpTopicTitle);
	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']}' AND issavvytopic=1 LIMIT {$limitNumber})\r\n";
				}
			}
			else{
				$arrRand = array();
				for( $i = 0 ; $i < $keyWordCount ; $i++  ){
					$indexRand = array_rand($arrTopicTitle);
					if( isset($arrRand[$arrTopicTitle[$indexRand].'']) ){
						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']}' AND issavvytopic=1 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 issavvytopic=1 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.mode,dt.getmoney,dt.usetools,dt.getmoneytype,dt.hidename,dt.solve,dt.anonymity FROM {$dv}savvy_topic AS dt WHERE dt.topicid IN({$topicIDList}) ORDER BY dt.topicid DESC";
			$arrRelatedTopic =& $db->getResultSet($stmt,array('pageSize'=>$limitNumber));
		}
	}
}
//End 相关主题处理
require printout('savvy_dispbbs');
//***************************************

footer();
?>