<?php

/**
 * 微分享数据接口
 */
require_once libfile('function/discuzcode');
include 'includes/functions/discuzcode.php';
if($_G['pa_count'] < 1) {
    odz_error('parameters_error', -112);
}
$_G['tpp'] = 20; // 每页展示的帖子数量
$_GET['stickymode'] = isset($_GET['stickymode']) ? 1 : 0; // 是否启用置顶帖模式
$_G['gp_filter'] = empty($_GET['filter']) ? '' : $_GET['filter'];
$_G['gp_orderby']=empty($_GET['orderby']) ? '' : $_GET['orderby'];
$order='';
if(empty($_GET['typeid'])) {
	unset($_GET['typeid']);
}else{
	$order=" and typeid='{$_GET['typeid']}'";
}
require_once libfile('function/forumlist');
$_GET['fid']=$_G['forum']['fid']=$_G['action']['fid'] = $_G['fid']=$_G['mocuz_config']['share_fid'];
odz_loadforum();
//odz_stats(array('typeid'=>3, 'action'=>'click'));

if(empty($_G['forum']['fid'])) {
	showmessage('forum_nonexistence', NULL);
}
//$_G['gp_specialtype'] = isset($_G['gp_specialtype']) ? $_G['gp_specialtype'] : '';
//$_G['gp_dateline'] = isset($_G['gp_dateline']) ? intval($_G['gp_dateline']) : 0;
//// $_G['gp_digest'] = isset($_G['gp_digest']) ? 1 : '';
//$_G['gp_archiveid'] = isset($_G['gp_archiveid']) ? intval($_G['gp_archiveid']) : 0;

$_G['gp_digest'] = isset($_GET['digest']) ? 1 : ''; // 精华帖
$_G['forum']['name'] = strip_tags($_G['forum']['name']) ? strip_tags($_G['forum']['name']) : $_G['forum']['name'];
$_G['forum']['extra'] = unserialize($_G['forum']['extra']);
if(!is_array($_G['forum']['extra'])) {
	$_G['forum']['extra'] = array();
}
$threadtable_info = !empty($_G['cache']['threadtable_info']) ? $_G['cache']['threadtable_info'] : array();
$forumarchive = array();
$threadclass  = array();
// 仅在第一页返回主题分类列表
if(empty($_GET['page']) || $_GET['page'] == 1) {
	//过滤未启用分类 zl
	require_once libfile('function/forumlist');

	odz_loadforum();
	$tmp = array_keys($_G['forum']['threadsorts']['types']);
	$sortid = isset($tmp[0])?$tmp[0]:'';
	$thread = array('readperm' => '', 'pricedisplay' => '', 'hiddenreplies' => '');
	$threadclass = array();
	if($_G['forum']['ismoderator'] || empty($_G['forum']['threadtypes']['moderators'][$thread['typeid']])) {
		$arr = $_G['forum']['threadtypes'];
		foreach($arr['types'] as $key => $value) {
			$threadclass[] = array('fid'=>$_G['forum']['fid'],'typeid'=>$key, 'name'=>strip_tags($value));
		}
	}
}


$forum_up = $_G['cache']['forums'][$_G[forum][fup]];

if($_G['forum']['viewperm'] && !forumperm($_G['forum']['viewperm']) && !$_G['forum']['allowview']) {
	showmessagenoperm('viewperm', $_G['fid'], $_G['forum']['formulaperm']);
} elseif($_G['forum']['formulaperm']) {
	formulaperm($_G['forum']['formulaperm']);
}

if($_G['forum']['password']) {
	// 移动端取消版块密码认证
	if(!isset($_G['cookie']['fidpw'.$_G['fid']])) {
		dsetcookie('fidpw'.$_G['fid'], $_G['forum']['password']);
	}
}

if(!isset($_G['cookie']['collapse']) || strpos($_G['cookie']['collapse'], 'forum_rules_'.$_G['fid']) === FALSE) {
	$collapse['forum_rules'] = '';
	$collapse['forum_rulesimg'] = 'no';
} else {
	$collapse['forum_rules'] = 'display: none';
	$collapse['forum_rulesimg'] = 'yes';
}

$forumlastvisit = 0;

$threadtableids = !empty($_G['cache']['threadtableids']) ? $_G['cache']['threadtableids'] : array();
$threadtable = $_G['gp_archiveid'] && in_array($_G['gp_archiveid'], $threadtableids) ? "forum_thread_{$_G['gp_archiveid']}" : 'forum_thread';

if($_G['setting']['allowmoderatingthread'] && $_G['uid']) {
	$threadmodcount = DB::result_first("SELECT COUNT(*) FROM ".DB::table($threadtable)." WHERE fid='{$_G['fid']}' AND displayorder='-2' AND authorid='{$_G['uid']}'");
}

if($_G['forum']['modworks'] || $_G['forum']['modnewposts']) {
	$_G['forum']['modnewposts'] && $_G['forum']['modworks'] = 1;
	$modusernum = $_G['group']['allowmoduser'] ? DB::result_first("SELECT COUNT(*) FROM ".DB::table('common_member_validate')." WHERE status='0'") : 0;
}

$optionadd = $filterurladd = $searchsorton = '';

$quicksearchlist = array();
if(!empty($_G['forum']['threadsorts']['types'])) {
	require_once libfile('function/threadsort');
	$showpic = intval($_G['gp_showpic']);
	$templatearray = $sortoptionarray = array();
	foreach($_G['forum']['threadsorts']['types'] as $stid => $sortname) {
		loadcache(array('threadsort_option_'.$stid, 'threadsort_template_'.$stid));
		sortthreadsortselectoption($stid);
		$templatearray[$stid] = $_G['cache']['threadsort_template_'.$stid]['subject'];
		$sortoptionarray[$stid] = $_G['cache']['threadsort_option_'.$stid];
	}

	if(!empty($_G['forum']['threadsorts']['defaultshow']) && empty($_G['gp_sortid']) && empty($_G['gp_sortall'])) {
		$_G['gp_sortid'] = $_G['forum']['threadsorts']['defaultshow'];
		$_G['gp_filter'] = 'sortid';
		$_SERVER['QUERY_STRING'] = $_SERVER['QUERY_STRING'] ? $_SERVER['QUERY_STRING'].'&sortid='.$_G['gp_sortid'] : 'sortid='.$_G['gp_sortid'];
		$filterurladd = '&amp;filter=sort';
	}

	$_G['gp_sortid'] = $_G['gp_sortid'] ? $_G['gp_sortid'] : $_G['gp_searchsortid'];
	if(isset($_G['gp_sortid']) && $_G['forum']['threadsorts']['types'][$_G['gp_sortid']]) {
		$searchsortoption = $sortoptionarray[$_G['gp_sortid']];
		$quicksearchlist = quicksearch($searchsortoption);
		$_G['forum_optionlist'] = $_G['cache']['threadsort_option_'.$_G['gp_sortid']];
		$forum_optionlist = getsortedoptionlist();
	}
}
$moderatedby = $_G['forum']['status'] != 3 ? moddisplay($_G['forum']['moderators'], 'forumdisplay') : '';
$_G['gp_highlight'] = empty($_G['gp_highlight']) ? '' : htmlspecialchars($_G['gp_highlight']);
if($_G['forum']['autoclose']) {
	$closedby = $_G['forum']['autoclose'] > 0 ? 'dateline' : 'lastpost';
	$_G['forum']['autoclose'] = abs($_G['forum']['autoclose']) * 86400;
}

$page = $_G['page'];
$subforumonly = $_G['forum']['simple'] & 1;
$simplestyle = !$_G['forum']['allowside'] || $page > 1 ? true : false;

if($subforumonly) {
	$_G['setting']['fastpost'] = false;
	$_G['gp_orderby'] = '';
	if(!defined('IN_ARCHIVER')) {
		include template('diy:forum/forumdisplay:'.$_G['fid']);
	} else {
		include loadarchiver('forum/forumdisplay');
	}
	exit();
}

$page = $_G['setting']['threadmaxpages'] && $page > $_G['setting']['threadmaxpages'] ? 1 : $page;
$start_limit = ($page - 1) * $_G['tpp'];

if($_G['forum']['modrecommend'] && $_G['forum']['modrecommend']['open']) {
	$_G['forum']['recommendlist'] = recommendupdate($_G['fid'], $_G['forum']['modrecommend'], '', 1);
}
$recommendgroups = array();
if($_G['forum']['status'] != 3 && $_G['setting']['groupstatus']) {
	loadcache('forumrecommend');
	$recommendgroups = $_G['cache']['forumrecommend'][$_G['fid']];
}

if(!$simplestyle || !$_G['forum']['allowside'] && $page == 1) {
	if($_G['cache']['announcements_forum'] && (!$_G['cache']['announcements_forum']['endtime'] || $_G['cache']['announcements_forum']['endtime'] > TIMESTAMP)) {
		$announcement = $_G['cache']['announcements_forum'];
		$announcement['starttime'] = dgmdate($announcement['starttime'], 'd');
	} else {
		$announcement = NULL;
	}
}

$filteradd = $sortoptionurl = $sp = '';
$sorturladdarray = $selectadd = array();
$forumdisplayadd = array('orderby' => '');
$specialtype = array('poll' => 1, 'trade' => 2, 'reward' => 3, 'activity' => 4, 'debate' => 5);
$filterfield = array('digest', 'recommend', 'sortall', 'typeid', 'sortid', 'dateline', 'page', 'orderby', 'specialtype', 'author', 'view', 'reply', 'lastpost');

foreach($filterfield as $v) {
	$forumdisplayadd[$v] = '';
}

$filter = isset($_G['gp_filter']) && in_array($_G['gp_filter'], $filterfield) ? $_G['gp_filter'] : '';
$multiadd = array();
if($filter) {
    $geturl = daddslashes($_GET, 1);
	if($geturl && is_array($geturl)) {
		$issort = isset($_G['gp_sortid']) && isset($_G['forum']['threadsorts']['types'][$_G['gp_sortid']]) && $quicksearchlist ? TRUE : FALSE;
		$selectadd = $issort ? $geturl : array();
		foreach($filterfield as $option) {
			foreach($geturl as $field => $value) {
				if(in_array($field, $filterfield) && $option != $field && $field != 'page' && ($field != 'orderby' || !in_array($option, array('author', 'reply', 'view', 'lastpost', 'heat')))) {
					if(!(in_array($option, array('digest', 'recommend')) && in_array($field, array('digest', 'recommend')))) {
						$forumdisplayadd[$option] .= '&'.$field.'='.rawurlencode($value);
					}
				}
			}
			if($issort) {
				$sfilterfield = array_merge(array('filter', 'sortid', 'orderby', 'fid'), $filterfield);
				foreach($geturl as $soption => $value) {
					$forumdisplayadd[$soption] .= !in_array($soption, $sfilterfield) ? "&$soption=".rawurlencode($value) : '';
				}
			}
		}
		if($issort && is_array($quicksearchlist)) {
			foreach($quicksearchlist as $option) {
				$identifier = $option['identifier'];
				foreach($geturl as $option => $value) {
					$sorturladdarray[$identifier] .= !in_array($option, array('filter', 'sortid', 'orderby', 'fid', 'searchsort', $identifier)) ? "&amp;$option=$value" : '';
				}
			}
		}
		foreach($geturl as $field => $value) {
                    if($field != 'page' && $field != 'fid') {
                        $multiadd[] = $field.'='.rawurlencode($value);
                        if(in_array($field, $filterfield)) {
                            $filteradd .= $sp;
                            if($field == 'digest') {
                                    $filteradd .= "AND digest>'0'";
                            } elseif($field == 'recommend') {
                                    $filteradd .= "AND recommends>'".intval($_G['setting']['recommendthread']['iconlevels'][0])."'";
                            } elseif($field == 'specialtype') {
                                    $filteradd .= "AND special='$specialtype[$value]'";
                            } elseif($field == 'dateline') {
                                    $filteradd .= $value ? "AND lastpost>='".(TIMESTAMP - $value)."'" : '';
                            } elseif($field == 'typeid' || $field == 'sortid') {
                                    $filteradd .= "AND $field='$value'";
                            }
                            $sp = ' ';
                        }
                    }
		}
	}

	$simplestyle = true;
}

if(!empty($_G['gp_orderby']) && in_array($_G['gp_orderby'], array('lastpost', 'dateline', 'replies', 'views', 'recommends', 'heats'))) {
	$forumdisplayadd['orderby'] .= '&orderby='.$_G['gp_orderby'];
} else {
	$_G['gp_orderby'] = isset($_G['cache']['forums'][$_G['fid']]['orderby']) ? $_G['cache']['forums'][$_G['fid']]['orderby'] : 'dateline';
}

$_G['gp_ascdesc'] = isset($_G['cache']['forums'][$_G['fid']]['ascdesc']) ? $_G['cache']['forums'][$_G['fid']]['ascdesc'] : 'DESC';

$check = array();
$check[$filter] = $check[$_G['gp_orderby']] = $check[$_G['gp_ascdesc']] = 'selected="selected"';

if($_G['forum']['threadsorts']['types'] && $sortoptionarray && ($_G['gp_searchoption'] || $_GET['searchsort'])) {
	$sortid = intval($_G['gp_sortid']);
	if($_G['gp_searchoption']){
		$forumdisplayadd['page'] = '&sortid='.$sortid;
		foreach($_G['gp_searchoption'] as $optionid => $option) {
			$identifier = $sortoptionarray[$sortid][$optionid]['identifier'];
			$forumdisplayadd['page'] .= $option['value'] ? "&searchoption[$optionid][value]=$option[value]&searchoption[$optionid][type]=$option[type]" : '';
		}
	}
	if($searchsorttids = sortsearch($_G['gp_sortid'], $sortoptionarray, $_G['gp_searchoption'], $selectadd, $_G['fid'])) {
		$filteradd .= "AND t.tid IN (".dimplode($searchsorttids).")";
	}
}

$fidsql = '';
if($_G['forum']['relatedgroup']) {
	$relatedgroup = explode(',', $_G['forum']['relatedgroup']);
	$relatedgroup[] = $_G['fid'];
	$fidsql = " t.fid IN(".dimplode($relatedgroup).")";
} else {
	$fidsql = " t.fid='{$_G['fid']}'";
}
if(!$_GET['stickymode'] && empty($filter) && empty($_G['gp_sortid']) && empty($_G['gp_archiveid']) && empty($_G['forum']['archive']) && empty($_G['forum']['relatedgroup'])) {
	$_G['forum_threadcount'] = $_G['forum']['threads'];
} else {
	$indexadd = '';
	if(strexists($filteradd, "t.digest>'0'")) {
		$indexadd = " FORCE INDEX (digest) ";
	}
	// $_G['forum_threadcount'] = DB::result_first("SELECT COUNT(*) FROM ".DB::table($threadtable)." t $indexadd WHERE $fidsql $filteradd AND t.displayorder>='0'");
	$_G['forum_threadcount'] = DB::result_first("SELECT COUNT(*) FROM ".DB::table($threadtable)." t $indexadd WHERE $fidsql $filteradd AND t.displayorder" . (!$_GET['stickymode'] ? '=0' : '>0'));
}

$thisgid = $_G['forum']['type'] == 'forum' ? $_G['forum']['fup'] : (!empty($_G['cache']['forums'][$_G['forum']['fup']]['fup']) ? $_G['cache']['forums'][$_G['forum']['fup']]['fup'] : 0);
$forumstickycount = $stickycount = 0;
$stickytids = '';
if($_G['setting']['globalstick'] && $_G['forum']['allowglobalstick']) {
	$stickytids = $_G['cache']['globalstick']['global']['tids'];
	if(!empty($_G['cache']['globalstick']['categories'][$thisgid]['count'])) {
		$stickytids .= ($stickytids ? ',' : '').$_G['cache']['globalstick']['categories'][$thisgid]['tids'];
	}

	if($_G['forum']['status'] != 3) {
		$stickycount = $_G['cache']['globalstick']['global']['count'];
		if(!empty($_G['cache']['globalstick']['categories'][$thisgid])) {
			$stickycount += $_G['cache']['globalstick']['categories'][$thisgid]['count'];
		}
	}
}

$forumstickytids = array();
$forumstickycount = 0;
$forumstickfid = $_G['forum']['status'] != 3 ? $_G['fid'] : $_G['forum']['fup'];
if(isset($_G['cache']['forumstick'][$forumstickfid])) {
	$forumstickycount = count($_G['cache']['forumstick'][$forumstickfid]);
	$forumstickytids = $_G['cache']['forumstick'][$forumstickfid];
}
if(!empty($forumstickytids)) {
	$stickytids .= ($stickytids ? ', ' : '').dimplode($forumstickytids);
}
$stickycount += $forumstickycount;

if($_G['forum']['picstyle']) {
	$forumdefstyle = isset($_G['gp_forumdefstyle']) ? $_G['gp_forumdefstyle'] : '';
	if($forumdefstyle) {
		switch($forumdefstyle) {
			case 'no': dsetcookie('forumdefstyle', ''); break;
			case 'yes': dsetcookie('forumdefstyle', 1, 31536000); break;
		}
	}
	if(empty($_G['cookie']['forumdefstyle'])) {
		$stickycount = 0;
	}
}

$filterbool = !empty($filter) && in_array($filter, $filterfield);
$_G['forum_threadcount'] += $filterbool ? 0 : $stickycount;
$forumdisplayadd['page'] = !empty($forumdisplayadd['page']) ? $forumdisplayadd['page'] : '';
// $multipage_archive = $_G['gp_archiveid'] && in_array($_G['gp_archiveid'], $threadtableids) ? "&archiveid={$_G['gp_archiveid']}" : '';
// $multipage = multi($_G['forum_threadcount'], $_G['tpp'], $page, "forum.php?mod=forumdisplay&fid=$_G[fid]".($multiadd ? '&'.implode('&', $multiadd) : '')."$multipage_archive", $_G['setting']['threadmaxpages']);

$extra = rawurlencode(!IS_ROBOT ? 'page='.$page.($forumdisplayadd['page'] ? '&filter='.$filter.$forumdisplayadd['page'] : '').($forumdisplayadd['orderby'] ? $forumdisplayadd['orderby'] : '') : 'page=1');

$separatepos = 0;
$_G['forum_threadlist'] = $threadids = array();
//$_G['forum_colorarray'] = array('', '#EE1B2E', '#EE5023', '#996600', '#3C9D40', '#2897C5', '#2B65B7', '#8F2A90', '#EC1282');

// $displayorderadd = !$filterbool && $stickycount ? 't.displayorder IN (0, 1)' : 't.displayorder IN (0, 1, 2, 3, 4)';

$displayorderadd = 't.displayorder IN (0, 1, 2, 3, 4)';
//热帖显示规则 zl
if($_GET['filter'] == 'heat' && $_GET['orderby'] == 'heats'){
  $hot_thread_sql = '';
  $biu_show_rule = get_mocuz_setting('biu_show_rule');
  $biu_show_rule = $biu_show_rule['biu_show_rule'];
  if($biu_show_rule == 7){
    $hot_thread_sql = "dateline BETWEEN ".(time() - 7*86400)." AND ".time();
  }elseif($biu_show_rule == 14){
    $hot_thread_sql = "dateline BETWEEN ".(time() - 14*86400)." AND ".time();
  }elseif($biu_show_rule == 30){
    $hot_thread_sql = "dateline BETWEEN ".(time() - 30*86400)." AND ".time();
  }else{
    $hot_thread_sql = " 1=1 ";
  }
}else{
  $hot_thread_sql = " 1=1 ";
}

//我的微分享
$limit = 10;
$offset = ($_GET['page']-1)*$limit;
$uidsql = '';
$csql = " AND t.closed = 0";
if($_GET['ac']=='me'&&$_GET['uid']){
	$uidsql = " AND t.authorid ='{$_GET['uid']}'";
} else {
	$checksql = " INNER JOIN ".DB::table('common_member')." c ON t.authorid = c.uid";
}

if(($start_limit && $start_limit > $stickycount) || !$stickycount || $filterbool) {
	$indexadd = '';
	if(strexists($filteradd, "t.digest>'0'")) {
		$indexadd = " FORCE INDEX (digest) ";
	}
	$querysticky = '';
	$query = DB::query("SELECT t.* FROM ".DB::table($threadtable)." t $checksql $indexadd
		WHERE $fidsql $filteradd $order AND ($displayorderadd) $uidsql $csql
		AND $hot_thread_sql ORDER BY t.$_G[gp_orderby] $_G[gp_ascdesc]
		LIMIT ".($filterbool ? $start_limit : $start_limit - $stickycount).", $_G[tpp]");

} else {
	if($_GET['stickymode']) {
		$querysticky = DB::query("SELECT t.* FROM ".DB::table($threadtable)." t $checksql
			WHERE t.tid IN ($stickytids) $order AND (t.displayorder IN (2, 3, 4)) $uidsql $csql
			ORDER BY displayorder DESC, $_G[gp_orderby] $_G[gp_ascdesc]
			LIMIT $start_limit, ".($stickycount - $start_limit < $_G['tpp'] ? $stickycount - $start_limit : $_G['tpp']));
	}
	if($_G['tpp'] - $stickycount + $start_limit > 0) {
		$query = DB::query("SELECT t.* FROM ".DB::table($threadtable)." t
			WHERE $fidsql $filteradd AND ($displayorderadd) $uidsql
			AND $hot_thread_sql ORDER BY $_G[gp_orderby] $_G[gp_ascdesc]
			LIMIT ".($_G['tpp'] - $stickycount + $start_limit));
	} else {
		$query = '';
	}
}
if($_GET['page']==1){
    $query_total = DB::query("SELECT t.* FROM ".DB::table($threadtable)." t $checksql $indexadd
            WHERE $fidsql $filteradd $order AND ($displayorderadd) $uidsql $csql
            ORDER BY t.$_G[gp_orderby] $_G[gp_ascdesc] limit 0, 200");
}
$totalsql = "SELECT count(*) AS num FROM ".DB::table($threadtable).' WHERE fid='.$_G['fid'].' AND '.$hot_thread_sql.' AND displayorder = 0';
$query1 = DB::query($totalsql);
$total = DB::fetch($query1);
$totals = $total['num'];
$_G['ppp'] = $_G['forum']['threadcaches'] && !$_G['uid'] ? $_G['setting']['postperpage'] : $_G['ppp'];
$page = $_G['page'];
$todaytime = strtotime(dgmdate(TIMESTAMP, 'Ymd'));

$verify = $verifyuids = $grouptids = array();
while(($query_total && $thread_total = DB::fetch($query_total))) {
        foreach(C::t('mocuz_forum_post')->fetch_all_by_tid_user_check(0, $thread_total['tid'], 0, 6, 0) as $post) {
            if(!$post['message']) {
                    continue;
            }
            if(!$post['first']){
            }else{ $thread_total['pid'] = $post['pid'];}
	}
        if(!empty($_G['uid'])) {//点赞
           $query_praid = C::t('home_praise')->fetch_by_id_idtype($thread_total['tid'], 'tid', $_G['uid']);
        }
        $praidlist = C::t('home_praise')->fetch_all_by_id_idtype($thread_total['tid'], 'tid');
        if(!empty($praidlist)){
            foreach($praidlist as $vals){
		$username= DB::fetch_all('SELECT username  FROM '.DB::table('common_member')." WHERE uid = ".$vals['uid']);
               if($username[0]['username']) {
               		$userlist =  $username[0]['username'];
               		$thread_total["praiselist"][]=$userlist;
               }

               $thread_total['pratimes']=count($thread_total["praiselist"]);
            }
        }
    $thread_list[] = $thread_total;
}

while(($querysticky && $thread = DB::fetch($querysticky)) || ($query && $thread = DB::fetch($query))) {
	if(!C::t('common_member')->fetch_uid_by_username($thread['author'])){
		continue;
	}
	if($_G['forum']['picstyle'] && empty($_G['cookie']['forumdefstyle'])) {
		if($thread['fid'] != $_G['fid'] && empty($thread['cover'])) {
			continue;
		}
		$thread['coverpath'] = getthreadcover($thread['tid'], $thread['cover']);
		$thread['cover'] = abs($thread['cover']);
	}
	$thread['forumstick'] = in_array($thread['tid'], $forumstickytids);
	$thread['related_group'] = 0;
	if($_G['forum']['relatedgroup'] && $thread['fid'] != $_G['fid']) {
		if($thread['closed'] > 1) continue;
		$thread['related_group'] = 1;
		$grouptids[] = $thread['tid'];
	}
        $maxposition = C::t('forum_post')->fetch_maxposition_by_tid(0, $thread['tid']);
        $maxposition=$maxposition-1;
	foreach(C::t('mocuz_forum_post')->fetch_all_by_tid_user_check(0, $thread['tid'], 0, 6, 0) as $post) {
            if(!$post['first']){
              //替换附件图片为图片文字 zl
                $post['message'] = preg_replace('/\[attach\](.*)\[\/attach\]/s', odz_lang('image'), $post['message']);
                $post['message'] = preg_replace('/\[img\].*?\[\/img\]/', odz_lang('image'), $post['message']);
                $post['message'] = str_replace("\r\n", '', $post['message']);
                $post_message = preg_replace('/\[quote\](.*?)\[\/quote\]/s', ' ', $post['message']);
                if(preg_match('/\[quote\](.*?)\[\/quote\]/s', $post['message'], $match)) {
                    $quotemsg = preg_replace('/\[img\].*?\[\/img\]/', '', $match[1]);
                    $quotemsg = preg_replace('/\[.*?\]/', '', $quotemsg);
                    $quotemsg = odz_lang('post_quote') . ':' . $quotemsg;
                    $post['message'] = str_replace($match[0], $quotemsg, $post['message']);
                    $post['message'] = str_replace(odz_lang('post_requte').':', ' ', $post['message']);
                    preg_match('/([\S\s]+) '.odz_lang('post_requte_match').' \d+\-\d+-\d+/', $post['message'], $matchs);
                    $post['requtename']=$matchs[1];
                    $post_message = str_replace("\n", '', $post_message);
                    $post['message']=$post_message;
					$post['message'] = $post['message'];
                }
                if($post['invisible']==0 ){//正常回复评论才可以显示
                    $rely_list['pid']=$post['pid'];
                    $rely_list['tid']=$post['tid'];
                    $rely_list['fid']=$post['fid'];
                    $rely_list['author']=$post['author'];
                    $rely_list['authorid']=$post['authorid'];
                    $rely_list['message']=replace_smile($post['message']);
                    if($post['requtename']){
                        $rely_list['requtename']=$post['requtename'];
                    }else{
                        unset($rely_list['requtename']);
                    }
                    $thread["replylist"][] = $rely_list;
                }
            }else{
		$post['message'] = preg_replace('/\[attach\](.*)\[\/attach\]/s', '', $post['message']);
                $post['message'] = preg_replace('/\[.*?\]/', '', $post['message']);
                $thread["message"]=$post['message'];
                //by zlc
                $thread['pid'] = $post['pid'];
            }
	}

        if(!empty($_G['uid'])) {//点赞
                $query_praid = C::t('home_praise')->fetch_by_id_idtype($thread['tid'], 'tid', $_G['uid']);
        }
        $praidlist = C::t('home_praise')->fetch_all_by_id_idtype($thread['tid'], 'tid');
        if(!empty($praidlist)){
            foreach($praidlist as $vals){
                $username= DB::fetch_all('SELECT username  FROM '.DB::table('common_member')." WHERE uid = ".$vals['uid']);
               if($username[0]['username']) {
               		$userlist =  $username[0]['username'];
               		$thread["praiselist"][]=$userlist;
               }
               $thread['pratimes']=count($thread["praiselist"]);
            }
        }
        $thread['praid'] = isset($query_praid['praid'])?$query_praid['praid']:'';
	$thread['lastposterenc'] = rawurlencode($thread['lastposter']);
        if($thread['typeid'] && isset($_G['forum']['threadtypes']['types'][$thread['typeid']])) {
		$thread['typehtml'] = $_G['forum']['threadtypes']['types'][$thread['typeid']];
	} else {
		$thread['typeid'] = $thread['typehtml'] = '';
	}
//	$thread['sorthtml'] = $thread['sortid'] && !empty($_G['forum']['threadsorts']['prefix']) && isset($_G['forum']['threadsorts']['types'][$thread['sortid']]) ?
//		'<em>[<a href="forum.php?mod=forumdisplay&fid='.$_G['fid'].'&amp;filter=sortid&amp;sortid='.$thread['sortid'].'">'.$_G['forum']['threadsorts']['types'][$thread['sortid']].'</a>]</em>' : '';
//	$thread['multipage'] = '';
//	$topicposts = $thread['special'] ? $thread['replies'] : $thread['replies'] + 1;
//	$multipate_archive = $_G['gp_archiveid'] && in_array($_G['gp_archiveid'], $threadtableids) ? "archiveid={$_G['gp_archiveid']}" : '';
//	if($topicposts > $_G['ppp']) {
//		$pagelinks = '';
//		$thread['pages'] = ceil($topicposts / $_G['ppp']);
//		$realtid = $_G['forum']['status'] != 3 && $thread['isgroup'] == 1 ? $thread['closed'] : $thread['tid'];
//		for($i = 2; $i <= 6 && $i <= $thread['pages']; $i++) {
//			$pagelinks .= "<a href=\"forum.php?mod=viewthread&tid=$realtid&amp;".(!empty($multipate_archive) ? "$multipate_archive&amp;" : '')."extra=$extra&amp;page=$i\">$i</a>";
//		}
//		if($thread['pages'] > 6) {
//			$pagelinks .= "..<a href=\"forum.php?mod=viewthread&tid=$realtid&amp;".(!empty($multipate_archive) ? "$multipate_archive&amp;" : '')."extra=$extra&amp;page=$thread[pages]\">$thread[pages]</a>";
//		}
//		$thread['multipage'] = '&nbsp;...'.$pagelinks;
//	}
        //optimizeviews开启时，正确获取浏览数
	// if($_G['setting']['optimizeviews']) {
	// 	if(($row = C::t('forum_threadaddviews')->fetch($thread['tid']))) {
	// 		$ret['addviews'] = intval($row['addviews']);
	// 		$thread['views'] += $ret['addviews'];
	// 	}
	// }
//	$thread['recommendicon'] = '';
//	if(!empty($_G['setting']['recommendthread']['status']) && $thread['recommends']) {
//		foreach($_G['setting']['recommendthread']['iconlevels'] as $k => $i) {
//			if($thread['recommends'] > $i) {
//				$thread['recommendicon'] = $k+1;
//				break;
//			}
//		}
//	}

//	$thread['moved'] = $thread['heatlevel'] = $thread['new'] = 0;
//	$thread['icontid'] = $thread['forumstick'] || !$thread['moved'] && $thread['isgroup'] != 1 ? $thread['tid'] : $thread['closed'];
//	if($_G['forum']['status'] != 3 && ($thread['closed'] || ($_G['forum']['autoclose'] && TIMESTAMP - $thread[$closedby] > $_G['forum']['autoclose']))) {
//		if($thread['isgroup'] == 1) {
//			$thread['folder'] = 'common';
//			$grouptids[] = $thread['closed'];
//		} else {
//			if($thread['closed'] > 1) {
//				$thread['moved'] = $thread['tid'];
//				$thread['replies'] = '-';
//				$thread['views'] = '-';
//			}
//			$thread['folder'] = 'lock';
//		}
//	} elseif($_G['forum']['status'] == 3 && $thread['closed'] == 1) {
//		$thread['folder'] = 'lock';
//	} else {
//		$thread['folder'] = 'common';
//		$thread['weeknew'] = TIMESTAMP - 604800 <= $thread['dbdateline'];
//		if($thread['replies'] > $thread['views']) {
//			$thread['views'] = $thread['replies'];
//		}
//		if($_G['setting']['heatthread']['iconlevels']) {
//			foreach($_G['setting']['heatthread']['iconlevels'] as $k => $i) {
//				if($thread['heats'] > $i) {
//					$thread['heatlevel'] = $k + 1;
//					break;
//				}
//			}
//		}
//	}
	$thread['istoday'] = $thread['dateline'] > $todaytime ? 1 : 0;
	$thread['dbdateline'] = $thread['dateline'];
	$thread['dateline'] = dgmdate($thread['dateline'], 'd');
	$thread['dblastpost'] = $thread['lastpost'];
	$thread['lastpost'] = dgmdate($thread['lastpost'], 'u');

	if(in_array($thread['displayorder'], array(1, 2, 3, 4))) {
		$thread['id'] = 'stickthread_'.$thread['tid'];
		$separatepos++;
	} else {
		$thread['id'] = 'normalthread_'.$thread['tid'];
		if($thread['folder'] == 'common' && $thread['dblastpost'] >= $forumlastvisit || !$forumlastvisit) {
			$thread['new'] = 1;
			$thread['folder'] = 'new';
			$thread['weeknew'] = TIMESTAMP - 604800 <= $thread['dbdateline'];
		}
	}
	if(isset($_G['setting']['verify']['enabled']) && $_G['setting']['verify']['enabled']) {
		$verifyuids[$thread['authorid']] = $thread['authorid'];
	}
	$threadids[] = $thread['tid'];
	$_G['forum_threadlist'][] = $thread;
}
  //end我的朋友圈功能
//    if($_G['setting']['verify']['enabled'] && $verifyuids) {
//            $verifyquery = DB::query("SELECT * FROM ".DB::table('common_member_verify')." WHERE uid IN(".dimplode($verifyuids).")");
//            while($value = DB::fetch($verifyquery)) {
//                    foreach($_G['setting']['verify'] as $vid => $vsetting) {
//                            if($vsetting['available'] && $vsetting['showicon'] && !empty($vsetting['icon']) && $value['verify'.$vid] == 1) {
//                                    $verify[$value['uid']] .= "<a href=\"home.php?mod=spacecp&ac=profile&op=verify&vid=$vid\" target=\"_blank\">".(!empty($vsetting['icon']) ? '<img src="'.$vsetting['icon'].'" class="vm" alt="'.$vsetting['title'].'" title="'.$vsetting['title'].'" />' : $vsetting['title']).'</a>';
//                            }
//                    }
//            }
//    }

    $_G['forum_threadnum'] = count($_G['forum_threadlist']) - $separatepos;

    if(!empty($grouptids)) {
            $query = DB::query("SELECT t.tid, t.views, f.name, f.fid FROM ".DB::table('forum_thread')." t LEFT JOIN ".DB::table('forum_forum')." f ON f.fid=t.fid WHERE t.tid IN(".dimplode($grouptids).")");
            while($row = DB::fetch($query)) {
                    $groupnames[$row['tid']]['name'] = $row['name'];
                    $groupnames[$row['tid']]['fid'] = $row['fid'];
                    $groupnames[$row['tid']]['views'] = $row['views'];
            }
    }
    if(!empty($_GET['sortlist']) && $_G['forum']['threadsorts']['types'] && $sortoptionarray && $templatearray) {
            require_once 'includes/functions/threadsort.php';
            $sortid = intval($_G['gp_sortid']);
            $sortlistarray = odz_showsorttemplate($_G['gp_sortid'], $_G['fid'], $sortoptionarray, $templatearray, $_G['forum_threadlist'], $threadids);
    }

    $separatepos = $separatepos ? $separatepos + 1 : 0;

//$_G['setting']['visitedforums'] = $_G['setting']['visitedforums'] ? visitedforums() : '';

    $_G['group']['allowpost'] = (!$_G['forum']['postperm'] && $_G['group']['allowpost']) || ($_G['forum']['postperm'] && forumperm($_G['forum']['postperm'])) || (isset($_G['forum']['allowpost']) && $_G['forum']['allowpost'] == 1 && $_G['group']['allowpost']);
    $fastpost = $_G['setting']['fastpost'] && $_G['group']['allowpost'] && !$_G['forum']['allowspecialonly'] && !$_G['forum']['threadsorts']['required'];
    $fastpost = $fastpost && !$_G['forum']['allowspecialonly'];
    $_G['group']['allowpost'] = isset($_G['forum']['allowpost']) && $_G['forum']['allowpost'] == -1 ?  false : $_G['group']['allowpost'];

    $_G['forum']['allowpostattach'] = isset($_G['forum']['allowpostattach']) ? $_G['forum']['allowpostattach'] : '';
    $allowpostattach = $fastpost && ($_G['forum']['allowpostattach'] != -1 && ($_G['forum']['allowpostattach'] == 1 || (!$_G['forum']['postattachperm'] && $_G['group']['allowpostattach']) || ($_G['forum']['postattachperm'] && forumperm($_G['forum']['postattachperm']))));
    require_once libfile('function/post');
    // 组织返回数据
    $threadlist = array();
    foreach($_G['forum_threadlist'] as $key=>$forum_thread) {
	// 主题列表推荐图标
	$showcommendicon = 0;
	if (in_array($forum_thread['icon'], array(14))) {
		$showcommendicon = 1;
	}
        $thread_biu = array(
            'tid' => $forum_thread['tid'],
            'typeid' => $forum_thread['typeid'],
            'fid' => $forum_thread['fid'],
            'pid' => $forum_thread['pid'],
            'idtype' =>'tid' ,
            'author' => $forum_thread['author'],
            'sharetext' => odz_lang('biu_subject', array('author'=>$forum_thread['author'])),
            'authorid' => $forum_thread['authorid'],
            'avatar' => avatar($forum_thread['authorid'], 'small', true),
            'subject' => odz_format_subject($forum_thread['subject']),
            'message' => $forum_thread['message'],
            'dateline' => $forum_thread['dbdateline'],
            'showtime' => dgmdate($forum_thread['dbdateline'], 'mu'),
            'views' => strval($forum_thread['views']),
            'replies' => strval($forum_thread['replies']),
            'displayorder' => $forum_thread['displayorder'], // see http://blog.ailab.cn/post/110
            'lastpost' => strip_tags($forum_thread['lastpost']),
            'lastposter' => $forum_thread['lastposter'],
//            'status' => $forum_thread['status'],
            'praid' => $forum_thread['praid'],
            'praiselist' => $forum_thread['praiselist'],
            'pratimes' => $forum_thread['pratimes'],//点赞次数
            'icon' => $forum_thread['icon'],
            'replylist' => $forum_thread['replylist'],
            'typehtml' => strip_tags($forum_thread['typehtml']),
    //       'highlight' => $forum_thread['highlight'],
            'weiurl' => $_G['baseurl'].$_G['mocuz_config']['mocuz_type'].'/index.php?mod=viewthread&tid='.$forum_thread['tid'].'&viewthread_share=1&version='.$_G['mocuz_config']['version'],
//            'detailurl' => $_G['baseurl'].$_G['mocuz_config']['mocuz_type'].'/index.php?mod=viewthread&tid='.$forum_thread['tid'].'&ishtml=1&version='.$_G['mocuz_config']['version'],
            'showcommendicon' => $showcommendicon,
            'hasimageattachment' => ($forum_thread['attachment'] == 2 ? 1 : 0), // 是否包含图片附件
            'haslock' => $forum_thread['closed'] // 主题是否关闭
        );
        if(empty($forum_thread['tid']) || empty($forum_thread['pid']) || empty($forum_thread['message'])) {
                continue;
        }
        $threadlist[$key] = $thread_biu;
    }
//    if(!empty($threadids)) {
//            $indexlist = array_flip($threadids);
//            foreach(C::t('forum_threadaddviews')->fetch_all($threadids) as $tidkey => $value) {
//                    $index = $indexlist[$tidkey];
//                    if(!isset($threadlist[$index])){
//                            continue;
//                    }
//                    $threadlist[$index]['views'] += $value['addviews'];
//            }
//    }
    $threadlist = array_values($threadlist);
    unset($_G['forum_threadlist']);
    require_once libfile('function/attachment');
    require_once 'includes/functions/attachment.php';

    foreach($thread_list as $ke => $forum_threads) {
        $forum_thread_lists=$forum_threads;
        $_G['tid']=$forum_threads['tid'];
        //分类图片处理
        foreach($threadclass as $keys => $val) {
            if($val['typeid']==$forum_threads['typeid']){
                $threadclass[$keys]['total_pratimes'] += $forum_threads['pratimes'];
//                $threadclass[$keys]['total_num'] += 1;
                $threadclass[$keys]['total_replies'] += $forum_threads['replies'];
                //$mdid=$forum_threads['tid'].'_0';
                if(count($threadclass[$keys]['imagelist'])<4){
                    odz_parseattach($forum_threads['pid'], '', $forum_thread_lists, '');
                    $first=current($forum_thread_lists[$forum_threads['pid']]['attachments']);
                    if ($first['isimage'] != 0&&$first) {
                        $url=$first['url_host_ex'];
                        $ImageFile = mocuz_thumb($first['aid'], 150, 150);
                        $threadclass[$keys]['imagelist'][] = $ImageFile;
                    }
                }
            }
        }
    }
//  echo '<pre>';  print_R($threadclass);exit;
    foreach($threadlist as $key => $forum_thread) {
        $sortlist = array();
        $_G['tid']=$forum_thread['tid'];
        $forum_thread_list=$forum_thread;
        odz_parseattach($forum_thread['pid'], '', $forum_thread_list, '');
        $i=0;

        /**
         * 微分享缩略图尺寸
         *
         * 最新列表多图 300x300
         * 最新列表单图 450x450
         * 热门列表单图 300x0
         */

        $attachs = $forum_thread_list[$forum_thread['pid']]['attachments'];
        $tmp = array();
        foreach($attachs as $attach) {
            if($attach['isimage'] != 0 && count($tmp) < 9) {
                $tmp[] = $attach;
            }
        }
        unset($attachs);

        $thumbwidth = $thumbheight = 450;
        if(count($tmp) > 1) {
            $thumbwidth = $thumbheight = 300;
        }
        if(isset($_GET['orderby']) && $_GET['orderby'] == 'heats') {
            $thumbwidth = 300;
            $thumbheight = 0;
        }

        foreach($tmp as $attach) {
            $thumburl = mocuz_thumb($attach['aid'], $thumbwidth, $thumbheight);
            $thumbimageurl = $_G['baseurl'] . $attach['url'] . $attach['attachment'];
            $sortlist[] = array(
                'thumb' => $thumburl,
                'thumb_image' => $thumbimageurl,
                'weight' => isset($attach['width']) ? $attach['width'] : 100,
                'height' => isset($attach['height']) ? $attach['height'] : 100,
            );
        }

        // foreach($forum_thread_list[$forum_thread['pid']]['attachments'] as  $attach) {
        //         $attachurl = $attach['url'].$attach['attachment'].($attach['thumb'] ? '.thumb.jpg' : '');
        //         if ($attach['isimage'] != 0&&$i<9) {
        //                 $sortlist[$i]['thumb']= mocuz_thumb($attach['aid'], intval($attach['width']), intval($attach['height']));
        //                 $sortlist[$i]['thumb_image']=$attach['url_ex'];
        //                 $sortlist[$i]['weight']=$attach['width'];//获取图片的宽
        //                 $sortlist[$i]['height']= $attach['height'] ? $attach['height'] : 100;//获取图片的宽
        //         }
        //         $i++;
        // }

        if ($forum_thread['replies'] > $_G['tpp']) {
                $forum_thread['replies_pagecount'] = @ceil($forum_thread['replies'] / $_G['tpp']);
//                for($i=1;$i<=$replies_pagecount;$i++){
//                    $forum_thread['page_list'][]=$_G['baseurl'].$_G['mocuz_config']['mocuz_type']."/index.php?mod=viewthread&tid={$_G['tid']}&item_view=1&page=".$i;
//                }
        }
        $forum_thread['sortlist'] = $sortlist;
        $threadlist[$key] = $forum_thread;
    }

$pagecount = 1;
if ($_G['forum_threadcount'] > $_G['tpp']) {
	$pagecount = @ceil($totals / $_G['tpp']);
}

$resultdata = array(
	'total' => $totals,
        'threadclass' => $threadclass,
	'page' => $page,
	'pagecount' => $pagecount,
	'forumname' => $_G['forum']['name']
);
$resultdata['threadlist'] = $threadlist;
odz_result($resultdata);
/**
 * 十六进制转RGB
 * @param string
 * @return array
 */
//function hex2rgb($hexColor = '') {
//	$color = str_replace('#', '', $hexColor);
//	if (strlen($color) > 3) {
//		$rgb = array(
//			hexdec(substr($color, 0, 2)),
//			hexdec(substr($color, 2, 2)),
//			hexdec(substr($color, 4, 2))
//		);
//	} else {
//		$color = $hexColor;
//		$r = substr($color, 0, 1) . substr($color, 0, 1);
//		$g = substr($color, 1, 1) . substr($color, 1, 1);
//		$b = substr($color, 2, 1) . substr($color, 2, 1);
//		$rgb = array(
//			hexdec($r),
//			hexdec($g),
//			hexdec($b)
//		);
//	}
//	return $rgb;
//}

?>
