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

require_once 'global.php';
$leftbarsign = get_cookie('leftbarsign');
if($fsetting['leftbar'] && !$leftbarsign && $boardid == 0 && !$targeturl) {
	set_cookie('leftbarsign', 1, 31536000);
	$targeturl = $ScriptName.'?'.$_SERVER['QUERY_STRING'];
	$targeturl = urlencode($targeturl);
	echo "<script language=\"JavaScript\">top.location.href=\"".$fsetting['homepage']."?targeturl=".$targeturl."\"</script>";
	exit;
}

$page= intval($_GET['page']);

if( $fsetting['leftbar'] == 1 && $targeturl == 'left' ){
	$query=$db->query("Select boardid,boardtype,parentid,ishidden From {$dv}board Where depth<2 Order By rootid,orders");
	require_once printout('left');
	footer(false);
	exit;
}elseif ( $fsetting['leftbar'] == 1 && $targeturl != '' ){
	$istoptable = 0;
	head();
	$targeturl = strtolower(urldecode($targeturl));
	require_once printout('main');
	footer(false);
	exit;
}
if($boardid == 0){
	//Start 在线用户总数计算
	$tmpnowtime = gmdate('Y-m-d H:i:s');
	$totalonline = intval(get_cookie('totalonline'));
	$memberonline = intval(get_cookie('memberonline'));
	$onlinecachetime = get_cookie('onlinecachetime');
	if ($totalonline <= 0 OR !$onlinecachetime OR dateDiff('s', $onlinecachetime, $tmpnowtime) > 15) {//每隔15秒更新一次在线总数
		if ($tmpquery = $db->query("SELECT /*!40001 SQL_CACHE */ COUNT(1) AS total_online, COUNT(CASE WHEN userid>0 THEN 1 ELSE NULL END) AS member_online FROM {$dv}online")) {
			if ($tmponline = $db->fetch_row($tmpquery)) {
				$totalonline = $tmponline[0];
				$memberonline = $tmponline[1];
				if ($totalonline > intval($fsetting['maxonline'])){
					$db->query("Update {$dv}setup Set forum_maxonline={$totalonline},forum_maxonlinedate='".TIME_NOW."'");
					include_once INC_PATH.'BoardCache.class.php';
					$mycache =& new BoardCache($db);
					$mycache->createForumSetting();
				}
			}
		}
		$onlinecachetime = $tmpnowtime;
	}
	if ($totalonline <= 0 ) {
		$totalonline = 1;
		$memberonline = ($userid > 0 ? 1 : 0);
	}
	$guestonline = $totalonline - ($memberonline < 0 ? 0 : $memberonline);
	set_cookie('onlinecachetime', $onlinecachetime, $GLOBALS['user_selected_cookiedate']);
	set_cookie('totalonline', $totalonline, $GLOBALS['user_selected_cookiedate']);
	set_cookie('memberonline', $memberonline, $GLOBALS['user_selected_cookiedate']);
	//End 在线用户总数计算
}

global $totalonline,$boardmemberonline,$boardguestonline,$boardmaster_online;
if ($boardid > 0 && $boardinfo['allowpost'] == 1){
	//Start 版面在线用户总数计算
	$tmpnowtime = gmdate('Y-m-d H:i:s');
	$totalonline = intval(get_cookie('totalonline'));
	$boardtotalonline = intval(get_cookie('boardtotalonline'));
	$boardmemberonline = intval(get_cookie('boardmemberonline'));
	$boardonlinecachetime = get_cookie('boardonlinecachetime');
	//每隔15秒更新一次版面在线总数
	if (($totalonline <= 0 OR $boardtotalonline <= 0) OR !$boardonlinecachetime OR dateDiff('s', $boardonlinecachetime, $tmpnowtime) > 15) {
		if ($tmpquery = $db->query("SELECT /*!40001 SQL_CACHE */ COUNT(1) AS total_online, COUNT(CASE WHEN {$boardid}>0 AND boardid='{$boardid}' THEN 1 ELSE NULL END) AS board_total_online, COUNT(CASE WHEN {$boardid}>0 AND boardid='{$boardid}' AND userid>0 THEN 1 ELSE NULL END) AS board_member_online FROM {$dv}online")) {
			if ($tmpboardonline = $db->fetch_row($tmpquery)) {
				$totalonline = $tmpboardonline[0];
				$boardtotalonline = $tmpboardonline[1];
				$boardmemberonline = $tmpboardonline[2];
				if ($totalonline > intval($fsetting['maxonline'])){
					$db->query("Update {$dv}setup Set forum_maxonline={$totalonline},forum_maxonlinedate='".TIME_NOW."'");
					include_once INC_PATH.'BoardCache.class.php';
					$mycache =& new BoardCache($db);
					$mycache->createForumSetting();
				}
			}
		}
		$boardonlinecachetime = $tmpnowtime;
	}
	if ($boardtotalonline <= 0 ) {
		$boardtotalonline = 1;
		$boardmemberonline = ($userid > 0 ? 1 : 0);
	}
	$boardguestonline = $boardtotalonline - ($boardmemberonline < 0 ? 0 : $boardmemberonline);
	set_cookie('totalonline', $totalonline, $GLOBALS['user_selected_cookiedate']);
	set_cookie('boardonlinecachetime', $boardonlinecachetime, $GLOBALS['user_selected_cookiedate']);
	set_cookie('boardtotalonline', $boardtotalonline, $GLOBALS['user_selected_cookiedate']);
	set_cookie('boardmemberonline', $boardmemberonline, $GLOBALS['user_selected_cookiedate']);
	//End 版面在线用户总数计算
}

if($userid == 0){
	$indexstatic= CACHE_PATH."static/index_0_".$boardid.".php";
}
else{
	$indexstatic= CACHE_PATH."static/index_".$boardid.".php";
}
$topicmode = intval($_GET['topicmode']);

global $useindexstatic,$useindexstatic_file;
if(!empty($TopicDate))
	$useindexstatic_css= false;
else if(intval($TopicOrder))
	$useindexstatic_css= false;
else if(!empty($TopicDA))
	$useindexstatic_css= false;
if($_GET['action'] == 'batch')
	$useindexstatic_css= false;

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

if((!$useindexstatic) || (!$useindexstatic_css) || $page>1 || $topicmode>0){
	if($useindexstatic_css &&$page < 2 && $topicmode==0){
		$useindexstatic= true;
		ob_start();
	}
	else
		$useindexstatic= false;
	include_once INC_PATH.'DV_Encoding.class.php';
	$objenc =& DV_Encoding::GetEncoding($charset);
	$lang = load_lang($lang, 'index' );
	if ($boardid > 0){
		if ($boardinfo['allowpost'] > 0 && $boardinfo['child'] > 0){
			$gettitle = $lang['tpl.str1'];
		}elseif($boardinfo['child']){
			$gettitle = $lang['tpl.str2'];
		}else{
			$gettitle = $lang['tpl.str3'];
		}
		$stats = preg_replace( '/<([^<>]*?)>/i' ,'' ,$boardinfo['boardtype']). ' - ' .$gettitle;
	}else{
		$stats = $lang['hometitle'];
	}

	if (admin_boardset_check())
	LoadStyleJs();
	else
	head();

	//allowpost=0作为父分类不许发帖/=1开放/=2锁定(有权限用户可发帖)
	//ischeckout是否认证版面
	//ishidden是否隐含版面
	//listmod版面列表模式，0为列表模式，大于0为每行版面个数
	$showboardlist=0;
	$activetime = get_cookie("activetime");
	if ($boardid==0){
		$query=$db->query("select boardid,boardtype,showtype,parentid,readme,indeximg,boardmaster,child,postnum,topicnum,todaynum,lastpost,allowpost,ishidden,ischeckout,depth from {$dv}board where depth<3 order by rootid,orders");

		$showboardlist = 1;
		global $index_forumnum,$indivgroup_forumnum;
		is_file(CACHE_PATH.'Forum_Postcache_File.php') AND require_once CACHE_PATH.'Forum_Postcache_File.php';
		is_file(CACHE_PATH.'Forum_Postcache_File_Group.php') AND require_once CACHE_PATH.'Forum_Postcache_File_Group.php';
		require_once CACHE_PATH.'forum_index.php';

		//主页群组信息
		if (file_exists(CACHE_PATH.'Forum_Group_top.php')){
			require_once CACHE_PATH.'Forum_Group_top.php';
		}

		//主页右侧帖子列表
		if (file_exists(CACHE_PATH.'Forum_Topic_list.php')){
			require_once CACHE_PATH.'Forum_Topic_list.php';
		}

		//主页右侧广告
		if (file_exists(CACHE_PATH.'index_right_ads_file.php')){
			require_once CACHE_PATH.'index_right_ads_file.php';
			$arrIndex_Ads = $index_right_ads['setting'];
			$arrdb=$arrIndex_Ads['setting'];
		}
		$Index_Right_Ads_1= '';
		$Index_Right_Ads_2= '';
		$Index_Right_Ads_3= '';
		if(!empty($arrIndex_Ads))
		{
			if(is_array($arrIndex_Ads))
			{
				foreach($arrIndex_Ads as $k => $arrdb)
				{
					if($arrdb[DB_width] > 220)
						$arrdb[DB_width]= 220;

					if($arrdb[DB_close] == '1'){
						$temp= 'Index_Right_Ads_'.$arrdb[DB_boardid];
						if($arrdb[DB_File] == '')
						{
							
							$$temp.= '<A HREF="'.$arrdb[DB_linkurl].'" target="_blank">'.$arrdb[DB_name].'</A><div class="partition"></div>';
						}
						else{
							if (strtolower($arrdb[DB_File_type]) == 'swf')
							{
								$$temp.= '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="'.$arrdb[DB_width].'" height="'.$arrdb[DB_height].'"><param name=movie value="'.$arrdb[DB_File].'"><PARAM NAME=wmode VALUE=opaque><param name=quality value=autolow><embed src="'.$arrdb[DB_File].'" quality=autolow pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="'.$arrdb[DB_width].'" height="'.$arrdb[DB_height].'" wmode="opaque"></embed></object><div class="partition"></div>';
							}
							elseif (strtolower($arrdb[DB_File_type]) == 'gif' || strtolower($arrdb[DB_File_type]) == 'jpg')
							{
								$$temp.= '<A HREF="'.$arrdb[DB_linkurl].'" target="_blank"><img  src="'.$arrdb[DB_File].'" height="'.$arrdb[DB_height].'" width="'.$arrdb[DB_width].'" border="0" alt="'.$arrdb[DB_name].'" ></A><div class="partition"></div><div class="partition"></div>';
							}
						}
					}
				}
			}
		}
	}else{
		if($boardinfo['child'] > 0){
			$query=$db->query("select boardid,boardtype,parentid,readme,indeximg,boardmaster,child,postnum,topicnum,todaynum,lastpost,allowpost,ishidden,ischeckout,showtype from {$dv}board where boardid=$boardid or parentid=$boardid order by rootid,orders");
			$showboardlist = 1;
		}
	}
	$forum_today = $forum_topic = $forum_posts = 0;
	if($showboardlist == 1){
		while($forum =& $db->fetch_array($query)) {
			if ($forum['allowpost'] == 1 and $forum['parentid']!=0){
				$forum_topic += $forum['topicnum'];//主题数;
				$forum_posts += $forum['postnum'];//贴子数;
				$forum_today += $forum['todaynum'];
			}
			if ( $forum['depth'] >= 2 )
			{
				$_forumchild[$forum['parentid']][$forum['boardid']] = $forum[boardtype];
			}else{
				$_forum[] =& $forum;
			}

		}
        /*$tmppath=printout('index');
        if($fp=fopen("log.txt",'wb')){
        	fwrite($fp,$tmppath);
        	fclose($p);
        }*/
		require_once printout('index');
	}

	if ($boardid > 0 && $boardinfo['allowpost'] == 1){
		$lang = load_lang($lang, 'index.list' );
		$_sql = $topicmode && is_numeric($topicmode) ? ' AND mode='.$topicmode : '';
		if( $fsetting['forum_alltopnum'] != '' ){
			if( trim($boardinfo['boardtopstr']) !== '' ){
				$boardtopstr = $boardinfo['boardtopstr']. ',' .$fsetting['forum_alltopnum'];
			}else{
				$boardtopstr = $fsetting['forum_alltopnum'];
			}
		}else{
			if( $boardinfo['boardtopstr'] != '' ){
				$boardtopstr = $boardinfo['boardtopstr'];
			}
		}
		if ($page == '' || !is_numeric($page) || $page <= 0){
			$page = 1;
		}
		$result1_hasmore = true;
		/*查询排序begin*/
		$whereStmt='';
		if(!empty($TopicDate)){
			$whereStmt .= " And dateandtime >= '".dateAdd('d',-$TopicDate,time(), '')."' ";
		}
		switch (intval($TopicOrder)){
			case 1:
				$orderstr="lastposttime";
				break;
			case 2:
				$orderstr="dateandtime";
				break;
			case 3:
				$orderstr="child";
				break;
			case 4:
				$orderstr="hits";
				break;
			default:
				$orderstr="lastposttime";
				break;
		}
		$TopicDA=(empty($TopicDA))? 'Desc':$TopicDA;
		$whereQuery=$whereStmt.'Order By istop Desc,'.$orderstr." ".$TopicDA;
		$whereStmt .= " Order By ".$orderstr." ".$TopicDA;
		/*查询排序end*/
		if ( $boardtopstr != '' && $page == 1 ){
			$boardtop_str=explode(",",$boardtopstr);
			$boardtop_num=count($boardtop_str);
			for($btopid=0;$btopid<$boardtop_num;$btopid++){
				if($boardtop_str[$btopid]!=''){
					$board_topstr.=$boardtop_str[$btopid].",";
				}
			}
			$boardtopstr=substr($board_topstr,0,-1);
			$query1=$db->query("Select /*!40001 SQL_CACHE */ topicid,boardid,title,postusername,postuserid,dateandtime,child,hits,votetotal,lastpost,lastposttime,istop,isvote,isbest,locktopic,expression,topicmode,topicfont,mode,getmoney,getmoneytype,usetools,issmstopic,hidename From {$dv}topic Where topicid in ({$boardtopstr}) AND istop>0 AND boardid NOT IN (444,777){$_sql} {$whereQuery}");
			$boardtopstr = explode(',',$boardtopstr);
			$boardtopcount = count($boardtopstr);
		}
		else{
			$boardtopcount = 0;
			$result1_hasmore = false;
		}
		if ($board_settings[60] <= 0) {
			$board_settings[60] = 30;
		}
		if ($page == 1){
			$query2=$db->query("Select /*!40001 SQL_CACHE */ topicid,boardid,title,postusername,postuserid,dateandtime,child,hits,votetotal,lastpost,lastposttime,istop,isvote,isbest,locktopic,expression,topicmode,topicfont,mode,getmoney,getmoneytype,usetools,issmstopic,hidename From {$dv}topic /*!32312 USE INDEX(board_topic_list) */ Where istop=0 And boardid={$boardid}{$_sql} {$whereStmt} Limit ".$board_settings[60]);
		}else{
			$query2=$db->query("Select /*!40001 SQL_CACHE */ topicid,boardid,title,postusername,postuserid,dateandtime,child,hits,votetotal,lastpost,lastposttime,istop,isvote,isbest,locktopic,expression,topicmode,topicfont,mode,getmoney,getmoneytype,usetools,issmstopic,hidename From {$dv}topic /*!32312 USE INDEX(board_topic_list) */ Where istop=0 And boardid={$boardid}{$_sql} {$whereStmt}",array('absolutePage'=>$page,'pageSize'=>$board_settings[60]));
		}
		$result = false;
		while( true ){
			if( $result1_hasmore === true && $page == 1 ){
				$result = $db->fetch_array($query1);
			}
			if( $result === false ){
				$result1_hasmore = false;
			}
			if( $result1_hasmore === false ){
				$result = $db->fetch_array($query2);
			}
			if( $result === false ){
				break;
			}
			if ($result['istop'] > 0){
				switch($result['istop']){
				case 1:
					$result['istop'] = 0;
					break;
				case 2:
					$result['istop'] = 1;
					break;
				case 3:
					$result['istop'] = 2;
					break;
				}
			}else{
					//-------------------------2007-8-27  active start-------------------------------
				   if (intval($result['isbest']) == 1){
					$result['istop'] = 3;
				   }elseif($result['locktopic'] == 1){
					$result['istop'] = 4;
				   }elseif($result['isvote'] == 1){
					$result['istop'] = 5;
				   }elseif($result['child'] > $fsetting['hottopicreply']){
					$result['istop'] = 6;
				   }elseif($result['isvote'] == -2){
					$result['istop'] = 7;
				   }else{
					$result['istop'] = 8;
				   }
					//-------------------------2007-8-27  active end-------------------------------

			}

			$result['title'] = ChkBadWords($result['title']);
			$result['locktopic'] = htmlspecialchars($result['title']);
			
			if( $result['topicmode'] != 1 ){ #1 是HTML代码
				$_topictitlelength = $objenc->StrLength($result['title']);
				if ( $_topictitlelength > intval($board_settings[59])){
					$result['title'] = $objenc->SubString(strip_tags($result['title']), 0, intval($board_settings[59])).'...';
				}
			}
			$result['topicmode']= ShowCodeTitle($result['topicmode'],$result['topicfont'],1);

			if($board_settings[65] && $timestamp - $result['dateandtime'] < $board_settings['64'] * 60) {
				$result['newsign'] = '<img src="'.$board_settings[65].'" />';
			} else {
				$result['newsign'] = '';
			}
			$_topics[] = $result;
		}

		$stmt = "SELECT id,username,usergroupid,userhidden,userid,userclass{$fldlist} FROM {$dv}online WHERE boardid='{$boardid}' ORDER BY userid DESC,lastimebk DESC";
		if ($query = $db->query($stmt, array('absolutePage'=>1, 'pageSize'=>10))) {
			while ($dbinfo =& $db->fetch_array($query)) {
				$OnlineInfo[] =$dbinfo;
			}
		}
		require_once printout('index.list');
	}

	if($useindexstatic_css && $page < 2 && $topicmode==0){
		$this_my_f= ob_get_contents(); //生成缓存文件
		ob_end_clean();
		to_static_php_file($indexstatic,$this_my_f);
	}
}

if($useindexstatic)
	if($page < 2 && $topicmode==0){
		include_once($indexstatic);
		if($useindexstatic_file){
			unlink($indexstatic);
			if($_GET['reload'] != 1)
				echo "<script>document.location.href='index.php?reload=1&boardid={$boardid}&ftime=".microtime()."';</script>";
			return;
		}
	}

set_cookie('leftbarsign', '', -31536000);

if (!admin_boardset_check())
footer();

function get_special_type($modestr,$board_settingstr){
	global $boardinfo,$lang;
	$board_setlist = explode('$$',$board_settingstr);
	foreach ($board_setlist as $board_key => $board_setvalue){
		if($board_key==$modestr){
			$special_type='<b>'.$board_setvalue.'</b>&nbsp;';
		}
	}
	return $special_type;
}

?>