国产精品爱啪在线线免费观看_97视频精品_欧美精品一区二区在线播放_国产欧美久久一区二区三区

 找回密碼
 立即注冊

QQ登錄

只需一步,快速開始

搜索
查看: 3752|回復: 0

[內置擴展] Discuz x3.5 核心文件 function/function_forum.php 函數注釋

[復制鏈接]
1#
發表于 2024-6-23 13:20:09 | 只看該作者 |倒序瀏覽 |閱讀模式

馬上注冊,結交更多好友,享用更多功能,讓你輕松玩轉社區

您需要 登錄 才可以下載或查看,沒有賬號?立即注冊

×
[PHP] 純文本查看 復制代碼
<?php

/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: function_forum.php 36345 2017-01-12 01:55:04Z nemohou $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}
/**
 * 獲取指定用戶的Discuz!頭像
 *
 * @param int $uid 用戶ID
 * @param string $size 頭像大小,可選參數,默認為空,代表默認大小
 * @param bool $returnsrc 是否返回頭像的URL而不是直接輸出,默認為FALSE
 * @return mixed 如果 $returnsrc 為 TRUE,則返回頭像URL;否則直接輸出頭像
 */
function discuz_uc_avatar($uid, $size = '', $returnsrc = FALSE) {
    global $_G;
    return avatar($uid, $size, $returnsrc, FALSE, $_G['setting']['avatarmethod'], $_G['setting']['ucenterurl']);
}

/**
 * 刪除指定附件
 *
 * @param array $attach 包含附件信息的數組
 * @return void
 */
function dunlink($attach) {
    global $_G;
    $filename = $attach['attachment'];
    $havethumb = $attach['thumb'];
    $remote = $attach['remote'];
    if($remote) {
        ftpcmd('delete', 'forum/'.$filename);
        $havethumb && ftpcmd('delete', 'forum/'.getimgthumbname($filename));
    } else {
        @unlink($_G['setting']['attachdir'].'/forum/'.$filename);
        $havethumb && @unlink($_G['setting']['attachdir'].'/forum/'.getimgthumbname($filename));
    }
    if($attach['aid']) {
        @unlink($_G['setting']['attachdir'].'image/'.$attach['aid'].'_100_100.jpg');
    }
}

/**
 * 根據給定的權限公式判斷用戶是否有訪問權限
 *
 * @param string $formula 權限公式,可以是序列化的公式信息
 * @return bool 如果用戶有權限,則返回TRUE;否則返回FALSE
 */
function formulaperm($formula) {
    global $_G;
    // 初步檢查,如果是版主或者管理員,則直接通過
    if($_G['forum']['ismoderator']) {
        return TRUE;
    }

    $formula = dunserialize($formula);
    $medalperm = $formula['medal'];
    $permusers = $formula['users'];
    $permmessage = $formula['message'];
    // 檢查是否啟用了勛章權限控制
    if($_G['setting']['medalstatus'] && $medalperm) {
        $exists = 1;
        $_G['forum_formulamessage'] = '';
        $medalpermc = $medalperm;
        if($_G['uid']) {
            $memberfieldforum = C::t('common_member_field_forum')->fetch($_G['uid']);
            $medals = explode("\t", $memberfieldforum['medals']);
            unset($memberfieldforum);
            foreach($medalperm as $k => $medal) {
                foreach($medals as $r) {
                    list($medalid) = explode("|", $r);
                    if($medalid == $medal) {
                        $exists = 0;
                        unset($medalpermc[$k]);
                    }
                }
            }
        } else {
            $exists = 0;
        }
        if($medalpermc) {
            loadcache('medals');
            foreach($medalpermc as $medal) {
                if($_G['cache']['medals'][$medal]) {
                    $_G['forum_formulamessage'] .= '<img src="'.$_G['cache']['medals'][$medal]['image'].'" style="vertical-align:middle;" />&nbsp;'.$_G['cache']['medals'][$medal]['name'].'&nbsp; ';
                }
            }
            showmessage('forum_permforum_nomedal', NULL, array('forum_permforum_nomedal' => $_G['forum_formulamessage']), array('login' => 1));
        }
    }
    $formulatext = $formula[0];
    $formula = trim($formula[1]);
    // 檢查是否為管理員或者版主,或者用戶組有特殊權限
    if($_G['adminid'] == 1 || $_G['forum']['ismoderator'] || in_array($_G['groupid'], explode("\t", $_G['forum']['spviewperm']))) {
        return FALSE;
    }
    if($permusers) {
        $permusers = str_replace(array("\r\n", "\r"), array("\n", "\n"), $permusers);
        $permusers = explode("\n", trim($permusers));
        if(!in_array($_G['member']['username'], $permusers)) {
            showmessage('forum_permforum_disallow', NULL, array(), array('login' => 1));
        }
    }
    if(!$formula) {
        return FALSE;
    }
    // 對公式進行解析和計算,以判斷用戶是否有訪問權限
    if(strexists($formula, '$memberformula[')) {
        preg_match_all("/\\\$memberformula\['(\w+?)'\]/", $formula, $a);
        $profilefields = array();
        foreach($a[1] as $field) {
            switch($field) {
                case 'regdate':
                    $formula = preg_replace_callback("/\{(\d{4})\-(\d{1,2})\-(\d{1,2})\}/", 'formulaperm_callback_123', $formula);
                case 'regday':
                    break;
                case 'regip':
                case 'lastip':
                    $formula = preg_replace("/\{([0-9a-fA-F\.\:\/]+?)\}/", "'\\1'", $formula);
                    $formula = preg_replace('/(\$memberformula\[\'(regip|lastip)\'\])\s*=+\s*\'([0-9a-fA-F\.\:\/]+?)\'/', "ip::check_ip(\\1, '\\3')", $formula);
                case 'buyercredit':
                case 'sellercredit':
                    space_merge($_G['member'], 'status');break;
                case substr($field, 0, 5) == 'field':
                    space_merge($_G['member'], 'profile');
                    $profilefields[] = $field;break;
            }
        }
        $memberformula = array();
        if($_G['uid']) {
            $memberformula = $_G['member'];
            if(in_array('regday', $a[1])) {
                $memberformula['regday'] = intval((TIMESTAMP - $memberformula['regdate']) / 86400);
            }
            if(in_array('regdate', $a[1])) {
                $memberformula['regdate'] = date('Y-m-d', $memberformula['regdate']);
            }
            $memberformula['lastip'] = $memberformula['lastip'] ? $memberformula['lastip'] : $_G['clientip'];
        } else {
            if(isset($memberformula['regip'])) {
                $memberformula['regip'] = $_G['clientip'];
            }
            if(isset($memberformula['lastip'])) {
                $memberformula['lastip'] = $_G['clientip'];
            }
        }
    }
    @eval("\$formulaperm = ($formula) ? TRUE : FALSE;");
    if(!$formulaperm) {
        if(!$permmessage) {
            $language = lang('forum/misc');
            $search = array('regdate', 'regday', 'regip', 'lastip', 'buyercredit', 'sellercredit', 'digestposts', 'posts', 'threads', 'oltime');
            $replace = array($language['formulaperm_regdate'], $language['formulaperm_regday'], $language['formulaperm_regip'], $language['formulaperm_lastip'], $language['formulaperm_buyercredit'], $language['formulaperm_sellercredit'], $language['formulaperm_digestposts'], $language['formulaperm_posts'], $language['formulaperm_threads'], $language['formulaperm_oltime']);
            for($i = 1; $i <= 8; $i++) {
                $search[] = 'extcredits'.$i;
                $replace[] = $_G['setting']['extcredits'][$i]['title'] ? $_G['setting']['extcredits'][$i]['title'] : $language['formulaperm_extcredits'].$i;
            }
            if($profilefields) {
                loadcache(array('fields_required', 'fields_optional'));
                foreach($profilefields as $profilefield) {
                    $search[] = $profilefield;
                    $replace[] = !empty($_G['cache']['fields_optional']['field_'.$profilefield]) ? $_G['cache']['fields_optional']['field_'.$profilefield]['title'] : $_G['cache']['fields_required']['field_'.$profilefield]['title'];
                }
            }
            $i = 0;$_G['forum_usermsg'] = '';
            foreach($search as $s) {
                if(in_array($s, array('digestposts', 'posts', 'threads', 'oltime', 'extcredits1', 'extcredits2', 'extcredits3', 'extcredits4', 'extcredits5', 'extcredits6', 'extcredits7', 'extcredits8'))) {
                    $_G['forum_usermsg'] .= strexists($formulatext, $s) ? '<br />&nbsp;&nbsp;&nbsp;'.$replace[$i].': '.(@eval('return intval(getuserprofile(\''.$s.'\'));')) : '';
                } elseif(in_array($s, array('regdate', 'regip', 'regday'))) {
                    $_G['forum_usermsg'] .= strexists($formulatext, $s) ? '<br />&nbsp;&nbsp;&nbsp;'.$replace[$i].': '.(@eval('return $memberformula[\''.$s.'\'];')) : '';
                }
                $i++;
            }
            $search = array_merge($search, array('and', 'or', '>=', '<=', '=='));
            $replace = array_merge($replace, array('&nbsp;&nbsp;<b>'.$language['formulaperm_and'].'</b>&nbsp;&nbsp;', '&nbsp;&nbsp;<b>'.$language['formulaperm_or'].'</b>&nbsp;&nbsp;', '&ge;', '&le;', '='));
            $_G['forum_formulamessage'] = str_replace($search, $replace, $formulatext);
        } else {
            $_G['forum_formulamessage'] = $permmessage;
        }

        if(!$permmessage) {
            showmessage('forum_permforum_nopermission', NULL, array('formulamessage' => $_G['forum_formulamessage'], 'usermsg' => $_G['forum_usermsg']), array('login' => 1));
        } else {
            showmessage('forum_permforum_nopermission_custommsg', NULL, array('formulamessage' => $_G['forum_formulamessage']), array('login' => 1));
        }
    }
    return TRUE;
}
/**
 * 根據給定的公式和類型,計算用戶是否滿足獲得勛章的條件。
 *
 * @param string $formula 勛章獲得的計算公式,可以包含各種條件和運算符。
 * @param int $type 計算類型,1代表檢查是否滿足獲得條件,2代表檢查是否滿足保留條件。
 * @return mixed 如果用戶滿足條件,返回false;如果不滿足條件,返回提示信息的字符串。
 */
function medalformulaperm($formula, $type) {
    global $_G;

    // 解序列化公式字符串,獲取公式配置
    $formula = dunserialize($formula);
    $permmessage = $formula['message'];
    $formula = $formula['medal'];

    // 檢查用戶組是否被允許獲得該勛章
    if(!empty($formula['usergroupallow']) && is_array($formula['usergroups']) && !in_array($_G['groupid'], $formula['usergroups'])) {
        loadcache('usergroups');
        // 如果用戶組不允許,返回相應的用戶組權限提示信息
        $message = array();
        foreach($formula['usergroups'] as $groupid) {
            $message[] = $_G['cache']['usergroups'][$groupid]['grouptitle'].' ';
        }
        $_G['forum_formulamessage'] = implode(', ', $message);
        $_G['forum_usermsg'] = $_G['cache']['usergroups'][$_G['groupid']]['grouptitle'];
        return FALSE;
    }

    $formulatext = $formula[0];
    $formula = $formula[1];
    if(!$formula) {
        return FALSE;
    }

    // 處理公式中的$memberformula變量
    if(strexists($formula, '$memberformula[')) {
        preg_match_all("/\\\$memberformula\['(\w+?)'\]/", $formula, $a);
        $profilefields = array();
        foreach($a[1] as $field) {
            switch($field) {
                case 'regdate':
                    $formula = preg_replace_callback("/\{(\d{4})\-(\d{1,2})\-(\d{1,2})\}/", 'medalformulaperm_callback_123', $formula);
                case 'regday':
                    break;
                case 'regip':
                case 'lastip':
                    $formula = preg_replace("/\{([0-9a-fA-F\.\:\/]+?)\}/", "'\\1'", $formula);
                    $formula = preg_replace('/(\$memberformula\[\'(regip|lastip)\'\])\s*=+\s*\'([0-9a-fA-F\.\:\/]+?)\'/', "ip::check_ip(\\1, '\\3')", $formula);
                case 'buyercredit':
                case 'sellercredit':
                    space_merge($_G['member'], 'status');break;
                case substr($field, 0, 5) == 'field':
                    space_merge($_G['member'], 'profile');
                    $profilefields[] = $field;break;
            }
        }
        $memberformula = array();
        if($_G['uid']) {
            $memberformula = $_G['member'];
            if(in_array('regday', $a[1])) {
                $memberformula['regday'] = intval((TIMESTAMP - $memberformula['regdate']) / 86400);
            }
            if(in_array('regdate', $a[1])) {
                $memberformula['regdate'] = date('Y-m-d', $memberformula['regdate']);
            }
            $memberformula['lastip'] = $memberformula['lastip'] ? $memberformula['lastip'] : $_G['clientip'];
        } else {
            if(isset($memberformula['regip'])) {
                $memberformula['regip'] = $_G['clientip'];
            }
            if(isset($memberformula['lastip'])) {
                $memberformula['lastip'] = $_G['clientip'];
            }
        }
    }

    // 評估公式,并根據結果和類型返回相應的值
    @eval("\$formulaperm = ($formula) ? TRUE : FALSE;");
    if(!$formulaperm || $type == 1) {
        if(!$permmessage) {
            $language = lang('forum/misc');
            $search = array('regdate', 'regday', 'regip', 'lastip', 'buyercredit', 'sellercredit', 'digestposts', 'posts', 'threads', 'oltime');
            $replace = array($language['formulaperm_regdate'], $language['formulaperm_regday'], $language['formulaperm_regip'], $language['formulaperm_lastip'], $language['formulaperm_buyercredit'], $language['formulaperm_sellercredit'], $language['formulaperm_digestposts'], $language['formulaperm_posts'], $language['formulaperm_threads'], $language['formulaperm_oltime']);
            for($i = 1; $i <= 8; $i++) {
                $search[] = 'extcredits'.$i;
                $replace[] = $_G['setting']['extcredits'][$i]['title'] ? $_G['setting']['extcredits'][$i]['title'] : $language['formulaperm_extcredits'].$i;
            }
            if($profilefields) {
                loadcache(array('fields_required', 'fields_optional'));
                foreach($profilefields as $profilefield) {
                    $search[] = $profilefield;
                    $replace[] = !empty($_G['cache']['fields_optional']['field_'.$profilefield]) ? $_G['cache']['fields_optional']['field_'.$profilefield]['title'] : $_G['cache']['fields_required']['field_'.$profilefield]['title'];
                }
            }
            $i = 0;$_G['forum_usermsg'] = '';
            foreach($search as $s) {
                if(in_array($s, array('digestposts', 'posts', 'threads', 'oltime', 'extcredits1', 'extcredits2', 'extcredits3', 'extcredits4', 'extcredits5', 'extcredits6', 'extcredits7', 'extcredits8'))) {
                    $_G['forum_usermsg'] .= strexists($formulatext, $s) ? '<br />&nbsp;&nbsp;&nbsp;'.$replace[$i].': '.(@eval('return intval(getuserprofile(\''.$s.'\'));')) : '';
                } elseif(in_array($s, array('regdate', 'regip'))) {
                    $_G['forum_usermsg'] .= strexists($formulatext, $s) ? '<br />&nbsp;&nbsp;&nbsp;'.$replace[$i].': '.(@eval('return $memberformula[\''.$s.'\'];')) : '';
                }
                $i++;
            }
            $search = array_merge($search, array('and', 'or', '>=', '<=', '=='));
            $replace = array_merge($replace, array('&nbsp;&nbsp;<b>'.$language['formulaperm_and'].'</b>&nbsp;&nbsp;', '&nbsp;&nbsp;<b>'.$language['formulaperm_or'].'</b>&nbsp;&nbsp;', '&ge;', '&le;', '='));
            $permmessage = str_replace($search, $replace, $formulatext);
        }
        if(!$formulaperm) {
            $_G['forum_formulamessage'] = $permmessage;
        }

        return $permmessage;
    } elseif($formulaperm && $type == 2) {
        return FALSE;
    }
    return TRUE;
}

/**
 * 用于公式中處理日期格式的回調函數。
 *
 * @param array $matches 正則匹配到的內容數組。
 * @return string 返回格式化后的日期字符串。
 */
function formulaperm_callback_123($matches) {
    return '\''.$matches[1].'-'.sprintf('%02d', $matches[2]).'-'.sprintf('%02d', $matches[3]).'\'';
}

/**
 * 計算用戶組過期時間。
 *
 * @param array $terms 包含用戶組過期條件的數組。
 * @return int 返回用戶組的最短過期時間。
 */
function groupexpiry($terms) {
    $terms = is_array($terms) ? $terms : dunserialize($terms);
    $groupexpiry = isset($terms['main']['time']) ? intval($terms['main']['time']) : 0;
    if(is_array($terms['ext'])) {
        foreach($terms['ext'] as $expiry) {
            if((!$groupexpiry && $expiry) || $expiry < $groupexpiry) {
                $groupexpiry = $expiry;
            }
        }
    }
    return $groupexpiry;
}

/**
 * 生成論壇主題類型的下拉選擇菜單。
 *
 * @param int $curtypeid 當前選擇的類型ID。
 * @return string 返回包含選擇菜單的HTML代碼。
 */
function typeselect($curtypeid = 0) {
    global $_G;
    if($threadtypes = $_G['forum']['threadtypes']) {
        $html = '<select name="typeid" id="typeid"><option value="0">&nbsp;</option>';
        foreach($threadtypes['types'] as $typeid => $name) {
            $html .= '<option value="'.$typeid.'" '.($curtypeid == $typeid ? 'selected' : '').'>'.strip_tags($name).'</option>';
        }
        $html .= '</select>';
        return $html;
    } else {
        return '';
    }
}

/**
 * 更新版主操作記錄。
 *
 * @param string $modaction 版主操作的類型。
 * @param int $posts 操作涉及的帖子數量,默認為1。
 */
function updatemodworks($modaction, $posts = 1) {
    global $_G;
    $today = dgmdate(TIMESTAMP, 'Y-m-d');
    if($_G['setting']['modworkstatus'] && $modaction && $posts) {
        $affect_rows = C::t('forum_modwork')->increase_count_posts_by_uid_modaction_dateline(1, $posts, $_G['uid'], $modaction, $today);
        if(!$affect_rows) {
            C::t('forum_modwork')->insert(array(
                'uid' => $_G['uid'],
                'modaction' => $modaction,
                'dateline' => $today,
                'count' => 1,
                'posts' => $posts,
            ));
        }
    }
}
/**
 * 構建SQL語句的特定部分,用于更新指定字段的位狀態。
 *
 * @param string $fieldname 要操作的數據庫字段名。
 * @param int $position 指定位子字段的位置。
 * @param bool $value 指定要設置的狀態值,true為啟用,false為禁用。
 * @return string 返回構建的SQL更新語句部分。
 */
function buildbitsql($fieldname, $position, $value) {
    // 初始化SQL片段,準備設置字段值
    $t = " `$fieldname`=`$fieldname`";
    // 根據$value的真偽,選擇性地添加設置狀態的語句
    if($value) {
        $t .= ' | '.setstatus($position, 1); // 啟用狀態
    } else {
        $t .= ' & '.setstatus($position, 0); // 禁用狀態
    }
    // 返回完整的SQL語句部分
    return $t.' ';
}

/**
 * 顯示用戶沒有權限的消息
 *
 * @param string $type 操作類型,對應不同的權限
 * @param int $fid 論壇版塊ID
 * @param string $formula 權限公式,可選,用于自定義權限消息
 * @global array $_G 全局變量數組
 * @return void 無返回值,直接輸出消息并終止執行
 */
function showmessagenoperm($type, $fid, $formula = '') {
    global $_G;
    loadcache('usergroups'); // 加載用戶組緩存

    // 如果存在權限公式,則解析并獲取自定義權限消息
    if($formula) {
        $formula = dunserialize($formula);
        $permmessage = stripslashes($formula['message']);
    }

    // 初始化用戶組、無權限用戶組和論壇權限數組
    $usergroups = $nopermgroup = $forumnoperms = array();
    // 默認無權限設置
    $nopermdefault = array(
        'viewperm' => array(),
        'getattachperm' => array(),
        'postperm' => array(7),
        'replyperm' => array(7),
        'postattachperm' => array(7),
    );
    // 權限類型數組
    $perms = array('viewperm', 'postperm', 'replyperm', 'getattachperm', 'postattachperm');

    // 根據用戶組類型分配權限
    foreach($_G['cache']['usergroups'] as $gid => $usergroup) {
        $usergroups[$gid] = $usergroup['type'];
        $grouptype = $usergroup['type'] == 'member' ? 0 : 1;
        $nopermgroup[$grouptype][] = $gid;
    }

    // 獲取當前論壇版塊信息
    if($fid == $_G['forum']['fid']) {
        $forum = $_G['forum'];
    } else {
        $forum = C::t('forum_forumfield')->fetch($fid);
    }

    // 遍歷權限類型,獲取每個類型的具體權限設置
    foreach($perms as $perm) {
        $permgroups = explode("\t", $forum[$perm]);
        $membertype = $forum[$perm] ? array_intersect($nopermgroup[0], $permgroups) : TRUE;
        $forumnoperm = $forum[$perm] ? array_diff(array_keys($usergroups), $permgroups) : $nopermdefault[$perm];
        foreach($forumnoperm as $groupid) {
            $nopermtype = $membertype && $groupid == 7 ? 'login' : ($usergroups[$groupid] == 'system' || $usergroups[$groupid] == 'special' ? 'none' : ($membertype ? 'upgrade' : 'none'));
            $forumnoperms[$fid][$perm][$groupid] = array($nopermtype, $permgroups);
        }
    }

    // 獲取當前用戶組的權限信息,用于顯示
    $v = $forumnoperms[$fid][$type][$_G['groupid']][0];
    $gids = $forumnoperms[$fid][$type][$_G['groupid']][1];
    $comma = $permgroups = '';
    // 拼接具有權限的用戶組名稱或驗證類型名稱
    if(is_array($gids)) {
        foreach($gids as $gid) {
            if($gid && $_G['cache']['usergroups'][$gid]) {
                $permgroups .= $comma.$_G['cache']['usergroups'][$gid]['grouptitle'];
                $comma = ', ';
            } elseif($_G['setting']['verify']['enabled'] && substr($gid, 0, 1) == 'v') {
                $vid = substr($gid, 1);
                $permgroups .= $comma.$_G['setting']['verify'][$vid]['title'];
                $comma = ', ';
            }
        }
    }

    // 判斷是否使用自定義消息
    $custom = 0;
    if($permmessage) {
        $message = $permmessage;
        $custom = 1;
    } else {
        // 根據權限設置獲取系統消息
        if($v) {
            $message = $type.'_'.$v.'_nopermission';
        } else {
            $message = 'group_nopermission';
        }
    }

    // 顯示權限消息
    showmessage($message, NULL, array('fid' => $fid, 'permgroups' => $permgroups, 'grouptitle' => $_G['group']['grouptitle']), array('login' => 1), $custom);
}
/**
 * 加載論壇板塊或主題
 *
 * 本函數用于根據提供的板塊ID(fid)或主題ID(tid)加載相應的論壇數據。
 * 如果沒有提供fid或tid,將嘗試從全局變量或GET請求中獲取。
 *
 * @param int $fid 板塊ID,如果未提供,則嘗試從GET請求中獲取
 * @param int $tid 主題ID,如果未提供,則嘗試從GET請求中獲取
 * @global array $_G 全局變量數組
 * @return void
 */
function loadforum($fid = null, $tid = null) {
	global $_G;

	// 嘗試從參數或GET請求中獲取主題ID,并轉換為整數
	$tid = intval(isset($tid) ? $tid : getgpc('tid'));

	// 如果提供了板塊ID,則轉換為整數,否則從GET請求中獲取
	if(isset($fid)) {
		$fid = intval($fid);
	} else {
		$fid = getgpc('fid');
		// 如果未獲取到板塊ID,且GET請求中存在群組ID(gid),則嘗試使用群組ID
		if(!$fid && getgpc('gid')) {
			$fid = intval(getgpc('gid'));
		}
	}


	if(isset($_G['forum']['fid']) && $_G['forum']['fid'] == $fid || isset($_G['thread']['tid']) && $_G['thread']['tid'] == $tid){
		return null;
	}
	if(!empty($_GET['archiver'])) {//X1.5的Archiver兼容
		if($fid) {
			dheader('location: archiver/?fid-'.$fid.'.html');
		} elseif($tid) {
			dheader('location: archiver/?tid-'.$tid.'.html');
		} else {
			dheader('location: archiver/');
		}
	}
	if(defined('IN_ARCHIVER') && $_G['setting']['archiverredirect'] && !IS_ROBOT) {
		dheader('location: ../forum.php'.($_G['mod'] ? '?mod='.$_G['mod'].(!empty($_GET['fid']) ? '&fid='.$_GET['fid'] : (!empty($_GET['tid']) ? '&tid='.$_GET['tid'] : '')) : ''));
	}
	if(isset($_G['setting']['forumpicstyle'])) {
		$_G['setting']['forumpicstyle'] = dunserialize($_G['setting']['forumpicstyle']);
		empty($_G['setting']['forumpicstyle']['thumbwidth']) && $_G['setting']['forumpicstyle']['thumbwidth'] = 203;
		empty($_G['setting']['forumpicstyle']['thumbheight']) && $_G['setting']['forumpicstyle']['thumbheight'] = 0;
	} else {
		$_G['setting']['forumpicstyle'] = array('thumbwidth' => 203, 'thumbheight' => 0);
	}
	if($fid) {
		$fid = is_numeric($fid) ? intval($fid) : (!empty($_G['setting']['forumfids'][$fid]) ? $_G['setting']['forumfids'][$fid] : 0);
	}

	$modthreadkey = isset($_GET['modthreadkey']) && $_GET['modthreadkey'] == modauthkey($tid) ? $_GET['modthreadkey'] : '';
	$_G['forum_auditstatuson'] = $modthreadkey ? true : false;

	$metadescription = $hookscriptmessage = '';
	$adminid = $_G['adminid'];

	if(!empty($tid) || !empty($fid)) {

		if(!empty ($tid)) {
			$archiveid = !empty($_GET['archiveid']) ? intval($_GET['archiveid']) : null;
			$_G['thread'] = get_thread_by_tid($tid, $archiveid);
			$_G['thread']['allreplies'] = $_G['thread']['replies'] + $_G['thread']['comments'];
			if(!$_G['forum_auditstatuson'] && !empty($_G['thread'])
					&& !($_G['thread']['displayorder'] >= 0 || (in_array($_G['thread']['displayorder'], array(-4,-3,-2)) && $_G['uid'] && $_G['thread']['authorid'] == $_G['uid']))) {
				$_G['thread'] = null;
			}

			$_G['forum_thread'] = & $_G['thread'];

			if(empty($_G['thread'])) {
				$fid = $tid = 0;
			} else {
				$fid = $_G['thread']['fid'];
				$tid = $_G['thread']['tid'];
			}
		}

		if($fid) {
			$forum = C::t('forum_forum')->fetch_info_by_fid($fid);
		}

		if($forum) {
			if($_G['uid']) {
				if($_G['member']['accessmasks']) {
					$query = C::t('forum_access')->fetch_all_by_fid_uid($fid, $_G['uid']);
					$forum['allowview'] = $query[0]['allowview'];
					$forum['allowpost'] = $query[0]['allowpost'];
					$forum['allowreply'] = $query[0]['allowreply'];
					$forum['allowgetattach'] = $query[0]['allowgetattach'];
					$forum['allowgetimage'] = $query[0]['allowgetimage'];
					$forum['allowpostattach'] = $query[0]['allowpostattach'];
					$forum['allowpostimage'] = $query[0]['allowpostimage'];
				}
				if($adminid == 3) {
					$forum['ismoderator'] = C::t('forum_moderator')->fetch_uid_by_fid_uid($fid, $_G['uid']);
				}
			}
			$forum['ismoderator'] = !empty($forum['ismoderator']) || $adminid == 1 || $adminid == 2 ? 1 : 0;
			$fid = $forum['fid'];
			$gorup_admingroupids = $_G['setting']['group_admingroupids'] ? dunserialize($_G['setting']['group_admingroupids']) : array('1' => '1');

			if($forum['status'] == 3) {
				if(!empty($forum['moderators'])) {
					$forum['moderators'] = dunserialize($forum['moderators']);
				} else {
					require_once libfile('function/group');
					$forum['moderators'] = update_groupmoderators($fid);
				}
				if($_G['uid'] && $_G['adminid'] != 1) {
					$forum['ismoderator'] = !empty($forum['moderators'][$_G['uid']]) ? 1 : 0;
					$_G['adminid'] = 0;
					if($forum['ismoderator'] || $gorup_admingroupids[$_G['groupid']]) {
						$_G['adminid'] = $_G['adminid'] ? $_G['adminid'] : 3;
						if(!empty($gorup_admingroupids[$_G['groupid']])) {
							$forum['ismoderator'] = 1;
							$_G['adminid'] = 2;
						}

						$group_userperm = dunserialize($_G['setting']['group_userperm']);
						if(is_array($group_userperm)) {
							$_G['group'] = array_merge($_G['group'], $group_userperm);
							$_G['group']['allowmovethread'] = $_G['group']['allowcopythread'] = $_G['group']['allowedittypethread']= 0;
						}
					}
				}
			}
			foreach(array('threadtypes', 'threadsorts', 'creditspolicy', 'modrecommend') as $key) {
				$forum[$key] = !empty($forum[$key]) ? dunserialize($forum[$key]) : array();
				if(!is_array($forum[$key])) {
					$forum[$key] = array();
				}
			}

			if(!empty($forum['threadtypes']['types'])) {
				safefilter($forum['threadtypes']['types']);
			}
			if(!empty($forum['threadtypes']['options']['name'])) {
				safefilter($forum['threadtypes']['options']['name']);
			}
			if(!empty($forum['threadsorts']['types'])) {
				safefilter($forum['threadsorts']['types']);
			}

			if($forum['status'] == 3) {
				$_G['isgroupuser'] = 0;
				$_G['basescript'] = 'group';
				if($forum['level'] == 0) {
					$levelinfo = C::t('forum_grouplevel')->fetch_by_credits($forum['commoncredits']);
					$levelid = $levelinfo['levelid'];
					$forum['level'] = $levelid;
					C::t('forum_forum')->update_group_level($levelid, $fid);
				}
				if($forum['level'] != -1) {
					loadcache('grouplevels');
					$grouplevel = $_G['grouplevels'][$forum['level']];
					if(!empty($grouplevel['icon'])) {
						$valueparse = parse_url($grouplevel['icon']);
						if(!isset($valueparse['host'])) {
							$grouplevel['icon'] = $_G['setting']['attachurl'].'common/'.$grouplevel['icon'];
						}
					}
				}

				$group_postpolicy = $grouplevel['postpolicy'];
				if(is_array($group_postpolicy)) {
					$forum = array_merge($forum, $group_postpolicy);
				}
				$forum['allowfeed'] = $_G['setting']['group_allowfeed'];
				if($_G['uid']) {
					if(!empty($forum['moderators'][$_G['uid']])) {
						$_G['isgroupuser'] = 1;
					} else {
						$groupuserinfo = C::t('forum_groupuser')->fetch_userinfo($_G['uid'], $fid);
						$_G['isgroupuser'] = $groupuserinfo['level'];
						if($_G['isgroupuser'] <= 0 && empty($forum['ismoderator'])) {
							$_G['group']['allowrecommend'] = $_G['cache']['usergroup_'.$_G['groupid']]['allowrecommend'] = 0;
							$_G['group']['allowcommentpost'] = $_G['cache']['usergroup_'.$_G['groupid']]['allowcommentpost'] = 0;
							$_G['group']['allowcommentitem'] = $_G['cache']['usergroup_'.$_G['groupid']]['allowcommentitem'] = 0;
							$_G['group']['raterange'] = $_G['cache']['usergroup_'.$_G['groupid']]['raterange'] = array();
							$_G['group']['allowvote'] = $_G['cache']['usergroup_'.$_G['groupid']]['allowvote'] = 0;
						} else {
							$_G['isgroupuser'] = 1;
						}
					}
				}
			}
		} else {
			$fid = 0;
		}
	}

	$_G['fid'] = $fid;
	$_G['tid'] = $tid;
	$_G['forum'] = &$forum;
	$_G['current_grouplevel'] = &$grouplevel;

	if(empty($_G['uid'])) {
		$_G['group']['allowpostactivity'] = $_G['group']['allowpostpoll'] = $_G['group']['allowvote'] = $_G['group']['allowpostreward'] = $_G['group']['allowposttrade'] = $_G['group']['allowpostdebate'] = $_G['group']['allowpostrushreply'] = 0;
	}
	if(!empty($_G['forum']['widthauto'])) {
		$_G['widthauto'] = $_G['forum']['widthauto'];
	}
}
/**
 * 根據主題ID獲取主題信息
 *
 * @param int $tid 主題ID
 * @param null $forcetableid 強制使用的表ID,如果為null,則自動判斷
 * @return array 返回主題信息數組,如果找不到則返回空數組
 */
function get_thread_by_tid($tid, $forcetableid = null) {
    global $_G;

    $ret = array();
    // 檢查tid是否為數字
    if(!is_numeric($tid)) {
        return $ret;
    }
    // 加載主題表ID的緩存
    loadcache('threadtableids');
    $threadtableids = array(0);
    // 處理表ID的選擇
    if(!empty($_G['cache']['threadtableids'])) {
        if($forcetableid === null || ($forcetableid > 0 && !in_array($forcetableid, $_G['cache']['threadtableids']))) {
            $threadtableids = array_merge($threadtableids, $_G['cache']['threadtableids']);
        } else {
            $threadtableids = array(intval($forcetableid));
        }
    }
    // 去重并遍歷每個表ID查詢主題信息
    $threadtableids = array_unique($threadtableids);
    foreach($threadtableids as $tableid) {
        $tableid = $tableid > 0 ? $tableid : 0;
        $ret = C::t('forum_thread')->fetch_thread($tid, $tableid);
        // 如果找到主題信息,處理并返回
        if($ret) {
            $ret['threadtable'] = C::t('forum_thread')->get_table_name($tableid);
            $ret['threadtableid'] = $tableid;
            $ret['posttable'] = 'forum_post'.($ret['posttableid'] ? '_'.$ret['posttableid'] : '');
            break;
        }
    }

    // 如果未找到主題信息,返回空數組,或者根據設置優化視圖
    if(!is_array($ret)) {
        $ret = array();
    } elseif(getglobal('setting/optimizeviews')) {
        if(($row = C::t('forum_threadaddviews')->fetch($tid))) {
            $ret['addviews'] = intval($row['addviews']);
            $ret['views'] += $ret['addviews'];
        }
    }

    return $ret;
}

/**
 * 根據帖子ID獲取帖子信息
 *
 * @param int $pid 帖子ID
 * @param string $fields 需要查詢的字段,默認為'*'
 * @param string $addcondiction 添加的查詢條件,默認為空
 * @param null $forcetable 強制使用的表名或表ID,如果為null,則自動判斷
 * @return array 返回帖子信息數組,如果找不到則返回空數組
 */
function get_post_by_pid($pid, $fields = '*', $addcondiction = '', $forcetable = null) {
    global $_G;

    $ret = array();
    // 檢查pid是否為數字
    if(!is_numeric($pid)) {
        return $ret;
    }

    // 加載帖子表信息緩存
    loadcache('posttable_info');

    $posttableids = array(0);
    // 處理表ID的選擇
    if($_G['cache']['posttable_info']) {
        if(isset($forcetable)) {
            if(is_numeric($forcetable) && array_key_exists($forcetable, $_G['cache']['posttable_info'])) {
                $posttableids[] = $forcetable;
            } elseif(substr($forcetable, 0, 10) == 'forum_post') {
                $posttableids[] = $forcetable;
            }
        } else {
            $posttableids = array_keys($_G['cache']['posttable_info']);
        }
    }

    // 遍歷每個表ID查詢帖子信息
    foreach ($posttableids as $id) {
        $table = empty($id) ? 'forum_post' : (is_numeric($id) ? 'forum_post_'.$id : $id);
        $ret = C::t('forum_post')->fetch_by_pid_condition($id, $pid, $addcondiction, $fields);
        // 如果找到帖子信息,處理并返回
        if($ret) {
            $ret['posttable'] = $table;
            break;
        }
    }

    // 如果未找到帖子信息,返回空數組
    if(!is_array($ret)) {
        $ret = array();
    }

    return $ret;
}

/**
 * 根據主題ID和帖子ID獲取帖子信息
 *
 * @param int $tid 主題ID
 * @param int $pid 帖子ID
 * @return array 返回帖子信息數組
 */
function get_post_by_tid_pid($tid, $pid) {
    static $postlist = array();
    if(empty($postlist[$pid])) {
        // 從數據庫獲取帖子信息
        $postlist[$pid] = C::t('forum_post')->fetch_post('tid:'.$tid, $pid, false);
        if($postlist[$pid] && $postlist[$pid]['tid'] == $tid) {
            // 獲取帖子作者信息并更新到帖子信息中
            $user = getuserbyuid($postlist[$pid]['authorid']);
            $postlist[$pid]['adminid'] = $user['adminid'];
        } else {
            $postlist[$pid] = array();
        }
    }
    return $postlist[$pid];
}

/**
 * 設置RSS認證信息
 */
function set_rssauth() {
    global $_G;
    // 檢查是否開啟RSS功能并且用戶已登錄
    if($_G['setting']['rssstatus'] && $_G['uid']) {
        $auth = authcode($_G['uid']."\t".($_G['fid'] ? $_G['fid'] : '').
        "\t".substr(md5($_G['member']['password']), 0, 8), 'ENCODE', md5($_G['config']['security']['authkey']));
    } else {
        $auth = '0';
    }
    $_G['rssauth'] = rawurlencode($auth);
}

/**
 * 檢查論壇板塊是否允許RSS訪問
 *
 * @param array $forum 包含板塊信息的數組
 * @return bool 返回板塊是否允許RSS訪問
 */
function rssforumperm($forum) {
    $is_allowed = $forum['type'] != 'group' && (!$forum['viewperm'] || ($forum['viewperm'] && forumperm($forum['viewperm'], 7)));
    return $is_allowed;
}
/**
 * 上傳圖標或橫幅
 *
 * @param array &$data 上傳數據,包含狀態、擴展ID等
 * @param array $file 上傳的文件信息
 * @param string $type 文件類型(例如:icon或banner)
 * @return string|boolean 上傳成功返回文件路徑,失敗返回空字符串或false
 */
function upload_icon_banner(&$data, $file, $type) {
    global $_G;
    // 設置默認的擴展ID為論壇ID
    $data['extid'] = empty($data['extid']) ? $data['fid'] : $data['extid'];
    if(empty($data['extid'])) return '';

    // 檢查群組圖片大小限制
    if($data['status'] == 3 && $_G['setting']['group_imgsizelimit']) {
        $file['size'] > ($_G['setting']['group_imgsizelimit'] * 1024) && showmessage('file_size_overflow', '', array('size' => $_G['setting']['group_imgsizelimit'] * 1024));
    }
    $upload = new discuz_upload();
    $uploadtype = $data['status'] == 3 ? 'group' : 'common'; // 根據狀態確定上傳類型

    if(!$upload->init($file, $uploadtype, $data['extid'], $type)) {
        return false;
    }

    if(!$upload->save()) {
        if(!defined('IN_ADMINCP')) {
            showmessage($upload->errormessage());
        } else {
            cpmsg($upload->errormessage(), '', 'error');
        }
    }
    // 如果是群組圖標,生成縮略圖
    if($data['status'] == 3 && $type == 'icon') {
        require_once libfile('class/image');
        $img = new image;
        $img->Thumb($upload->attach['target'], './'.$uploadtype.'/'.$upload->attach['attachment'], 200, 200, 'fixwr');
    }
    return $upload->attach['attachment'];
}

/**
 * 生成多頁鏈接
 *
 * @param int $total 總數量
 * @param int $perpage 每頁數量
 * @param int $page 當前頁碼
 * @param string $link 鏈接基礎部分
 * @return string 生成的分頁鏈接
 */
function arch_multi($total, $perpage, $page, $link) {
    $pages = @ceil($total / $perpage) + 1;
    $pagelink = '';
    if($pages > 1) {
        $pagelink .= lang('forum/archiver', 'page') . ": \n";
        $pagestart = $page - 10 < 1 ? 1 : $page - 10;
        $pageend = $page + 10 >= $pages ? $pages : $page + 10;
        for($i = $pagestart; $i < $pageend; $i++) {
            $pagelink .= ($i == $page ? "<strong>[$i]</strong>" : "<a href=\"$link&page=$i\">$i</a>")." \n";
        }
    }
    return $pagelink;
}

/**
 * 加載存檔文件
 *
 * @param string $path 文件路徑
 * @return string 完整的文件路徑
 */
function loadarchiver($path) {
    global $_G;
    if(!$_G['setting']['archiver']) {
        require_once DISCUZ_ROOT . "./source/archiver/common/header.php";
        echo '<div id="content">'.lang('message', 'forum_archiver_disabled').'</div>';
        require_once DISCUZ_ROOT . "./source/archiver/common/footer.php";
        exit;
    }
    $filename = $path . '.php';
    return DISCUZ_ROOT . "./source/archiver/$filename";
}

/**
 * 更新帖子參與度
 *
 * @param int $tid 帖子ID
 * @param boolean $getsetarr 是否返回更新設置數組
 * @return array|void 返回更新設置數組或者無返回
 */
function update_threadpartake($tid, $getsetarr = false) {
    global $_G;
    $setarr = array();
    if($_G['uid'] && $tid) {
        if($_G['setting']['heatthread']['period']) {
            $partaked = C::t('forum_threadpartake')->fetch_threadpartake($tid, $_G['uid']);
            $partaked = $partaked['uid'];
            if(!$partaked) {
                C::t('forum_threadpartake')->insert(array('tid' => $tid, 'uid' => $_G['uid'], 'dateline' => TIMESTAMP));
                $setarr = C::t('forum_thread')->increase($tid, array('heats' => 1), false, 0, $getsetarr);
            }
        } else {
            $setarr = C::t('forum_thread')->increase($tid, array('heats' => 1), false, 0, $getsetarr);
        }
    }
    if($getsetarr) {
        return $setarr;
    }
}

/**
 * 獲取帖子封面路徑
 *
 * @param int $tid 帖子ID
 * @param int $cover 指定封面版本
 * @param int $getfilename 是否只返回文件名
 * @return string 封面路徑或文件名
 */
function getthreadcover($tid, $cover = 0, $getfilename = 0) {
    global $_G;
    if(empty($tid)) {
        return '';
    }
    $coverpath = '';
    $covername = 'threadcover/'.substr(md5($tid), 0, 2).'/'.substr(md5($tid), 2, 2).'/'.$tid.'.jpg';
    if($getfilename) {
        return $covername;
    }
    if($cover) {
        $coverpath = ($cover < 0 ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']).'forum/'.$covername;
    }
    return $coverpath;
}

/**
 * 轉換未使用的附件關聯信息
 *
 * @param int $aid 附件ID
 * @param int $tid 主題ID
 * @param int $pid 帖子ID
 * @return void
 */
function convertunusedattach($aid, $tid, $pid) {
    if(!$aid) {
        return;
    }
    global $_G;
    $attach = C::t('forum_attachment_n')->fetch_by_aid_uid(127, $aid, $_G['uid']);
    if(!$attach) {
        return;
    }
    $attach = daddslashes($attach);
    $attach['tid'] = $tid;
    $attach['pid'] = $pid;
    C::t('forum_attachment_n')->insert_attachment('tid:'.$tid, $attach);
    C::t('forum_attachment')->update($attach['aid'], array('tid' => $tid, 'pid' => $pid, 'tableid' => getattachtableid($tid)));
    C::t('forum_attachment_unused')->delete($attach['aid']);
}

/**
 * 更新附件關聯的帖子ID
 *
 * @param string $idtype 關聯類型
 * @param array $ids 關聯ID列表
 * @param int $oldtid 舊帖子ID
 * @param int $newtid 新帖子ID
 * @return void
 */
function updateattachtid($idtype, $ids, $oldtid, $newtid) {
    foreach(C::t('forum_attachment_n')->fetch_all_by_id('tid:'.$oldtid, $idtype, $ids) as $attach) {
        $attach['tid'] = $newtid;
        C::t('forum_attachment_n')->insert_attachment('tid:'.$newtid, $attach);
    }
    C::t('forum_attachment_n')->delete_by_id('tid:'.$oldtid, $idtype, $ids);
    C::t('forum_attachment')->update_by_id($idtype, $ids, $newtid);
}
/**
 * 更新帖子信息
 *
 * @param array $data 包含帖子數據的數組
 * @param string $condition 更新條件
 * @param bool $unbuffered 是否使用緩沖查詢,默認為false
 * @param bool $posttableid 帖子表ID,默認為false
 * @return bool 操作結果,通常為false
 */
function updatepost($data, $condition, $unbuffered = false, $posttableid = false) {
    return false;
}

/**
 * 插入帖子
 *
 * @param array $data 包含帖子數據的數組
 * @return int 插入的帖子ID,失敗則返回false
 */
function insertpost($data) {
    // 如果$data中包含tid,嘗試獲取帖子信息并確定帖子所屬的表ID
    if(isset($data['tid'])) {
        $thread = C::t('forum_thread')->fetch_thread($data['tid']);
        $tableid = $thread['posttableid'];
        // 如果帖子回復數為0且存在沙發,則刪除沙發帖
        if($thread['replies'] <= 0 && C::t('forum_sofa')->fetch($thread['tid'])) {
            C::t('forum_sofa')->delete($thread['tid']);
        }
    } else {
        // 如果沒有提供tid,則默認tid和tableid為0
        $tableid = $data['tid'] = 0;
    }
    // 插入帖子到forum_post_tableid表并獲取插入的PID
    $pid = C::t('forum_post_tableid')->insert(array('pid' => null), true);

    // 合并數據并插入到forum_post表
    $data = array_merge($data, array('pid' => $pid));
    C::t('forum_post')->insert_post($tableid, $data);
    // 如果PID是1024的倍數,刪除forum_post_tableid中PID小于等于該值的記錄
    if($pid % 1024 == 0) {
        C::t('forum_post_tableid')->delete_by_lesspid($pid);
    }
    // 保存最大帖子ID緩存
    savecache('max_post_id', $pid);
    return $pid;
}

/**
 * 根據字符串內容判斷帖子是否需要審核
 *
 * @param string $string 帖子的主題和內容
 * @return array 包含帖子是否需要審核的信息
 */
function threadmodstatus($string) {
    global $_G;
    // 檢查是否在指定時間范圍內需要審核
    $postmodperiods = periodscheck('postmodperiods', 0);
    if($postmodperiods) {
        $modnewthreads = $modnewreplies = 1;
    } else {
        // 根據用戶組和論壇設置判斷帖子是否需要審核
        $censormod = censormod($string);
        $modnewthreads = (!$_G['group']['allowdirectpost'] || $_G['group']['allowdirectpost'] == 1) && $_G['forum']['modnewposts'] || $censormod ? 1 : 0;
        $modnewreplies = (!$_G['group']['allowdirectpost'] || $_G['group']['allowdirectpost'] == 2) && $_G['forum']['modnewposts'] == 2 || $censormod ? 1 : 0;

        // 考慮論壇狀態對審核需求的影響
        if($_G['forum']['status'] == 3) {
            $modnewthreads = !$_G['group']['allowgroupdirectpost'] || $_G['group']['allowgroupdirectpost'] == 1 || $censormod ? 1 : 0;
            $modnewreplies = !$_G['group']['allowgroupdirectpost'] || $_G['group']['allowgroupdirectpost'] == 2 || $censormod ? 1 : 0;
        }
    }

    // 處理允許發布URL的權限
    $_G['group']['allowposturl'] = $_G['forum']['status'] != 3 ? $_G['group']['allowposturl'] : $_G['group']['allowgroupposturl'];
    if($_G['group']['allowposturl'] == 1) {
        if(!$postmodperiods) {
            $censormod = censormod($string);
        }
        if($censormod) {
            $modnewthreads = $modnewreplies = 1;
        }
    }
    return array($modnewthreads, $modnewreplies);
}

/**
 * 保存主題發布信息
 *
 * @param int $tid 主題ID
 * @param bool $passapproval 是否通過審核,默認為false
 * @return int 操作結果,1為成功,0為主題不存在,-1為需審核,-2為回復需審核
 */
function threadpubsave($tid, $passapproval = false) {
    global $_G;
    // 執行插件鉤子
    if($_G['setting']['plugins']['func'][HOOKTYPE]['threadpubsave']) {
        $hookparam = func_get_args();
        hookscript('threadpubsave', 'global', 'funcs', array('param' => $hookparam, 'step' => 'check'), 'threadpubsave');
    }
    // 獲取主題信息
    $thread = C::t('forum_thread')->fetch_by_tid_displayorder($tid, -4, '=', !$passapproval ? $_G['uid'] : null);
    if(!$thread) {
        return 0;
    }
    // 獲取主題帖子信息
    $threadpost = C::t('forum_post')->fetch_threadpost_by_tid_invisible($tid);
    $thread['message'] = $threadpost['message'];

    // 初始化變量
    $modworksql = 0;
    $displayorder = 0;
    $dateline = $_G['timestamp'];
    $moderatepids = $saveposts = array();
    $return = 1;

    // 判斷帖子是否需要審核
    list($modnewthreads) = threadmodstatus($thread['subject']."\t".$thread['message']);
    if($modnewthreads && $passapproval === false) {
        // 如果需要審核,則更新審核信息并通知管理員
        updatemoderate('tid', $tid);
        manage_addnotify('verifythread');
        $displayorder = -2;
        $modworksql = 1;
        $return = -1;
        C::t('forum_post')->update_by_tid('tid:'.$tid, $tid, array('dateline' => $dateline), false, false, 1);
    } else {
        // 如果不需要審核,則更新帖子時間
        C::t('forum_post')->update_by_tid('tid:'.$tid, $tid, array('dateline' => $dateline, 'invisible' => '0'), false, false, 1);
    }

    // 更新主題信息
    C::t('forum_thread')->update($tid, array('displayorder'=>$displayorder, 'dateline'=>$_G['timestamp'], 'lastpost'=>$_G['timestamp']));
    $posts = $thread['replies'] + 1;
    // 如果有回復,則處理每個回復
    if($thread['replies']) {
        $saveposts = C::t('forum_post')->fetch_all_by_tid('tid:'.$tid, $tid, true, '', 0, 0, 0);
        foreach($saveposts as $post) {
            $dateline++;
            $invisible = 0;
            list(, $modnewreplies) = threadmodstatus($post['subject']."\t".$post['message']);
            if($modnewreplies) {
                $moderatepids[] = $post['pid'];
                $verifypost = true;
                $invisible = -2;
                $modworksql = 1;
                $return = -2;
            }
            // 更新回復信息
            C::t('forum_post')->update_post('tid:'.$tid, $post['pid'], array('dateline' => $dateline, 'invisible' => $invisible));
            // 更新用戶積分
            updatepostcredits('+', $thread['authorid'], 'reply', $thread['fid']);
        }
    }
    // 如果有需要審核的帖子,更新審核信息并通知管理員
    if($moderatepids) {
        updatemoderate('pid', $moderatepids);
        manage_addnotify('verifypost');
    }
    // 更新用戶積分
    updatepostcredits('+', $thread['authorid'], 'post', $thread['fid']);
    // 更新附件積分
    $attachcount = C::t('forum_attachment_n')->count_by_id('tid:'.$thread['tid'], 'tid', $thread['tid']);
    updatecreditbyaction('postattach', $thread['authorid'], array(), '', $attachcount, 1, $thread['fid']);
    // 如果論壇為分類討論區,則更新用戶在該分類下的帖子數
    if($_G['forum']['status'] == 3) {
        C::t('forum_groupuser')->update_counter_for_user($thread['authorid'], $thread['fid'], 1);
    }

    // 更新論壇和分類討論區的最新帖子信息
    $subject = str_replace("\t", ' ', $thread['subject']);
    $lastpost = $thread['tid']."\t".$subject."\t".$thread['lastpost']."\t".$thread['lastposter'];
    C::t('forum_forum')->update($_G['fid'], array('lastpost' => $lastpost));
    C::t('forum_forum')->update_forum_counter($thread['fid'], 1, $posts, $posts, $modworksql);
    // 更新父版塊的最新帖子信息
    if($_G['forum']['type'] == 'sub') {
        C::t('forum_forum')->update($_G['forum']['fup'], array('lastpost' => $lastpost));
    }
    // 執行插件鉤子
    if($_G['setting']['plugins']['func'][HOOKTYPE]['threadpubsave']) {
        hookscript('threadpubsave', 'global', 'funcs', array('param' => $hookparam, 'step' => 'save', 'posts' => $saveposts), 'threadpubsave');
    }
    return $return;
}
/**
 * 獲取相關收藏集
 *
 * @param int $tid 主題ID
 * @param bool $all 是否獲取全部相關收藏集,默認為false,即獲取設置數量內的收藏集
 * @param int &$num 返回相關收藏集的數量
 * @param int &$more 如果收藏集數量超過設置的最大顯示數量,$more設為1,否則設為0
 * @return array 返回收藏集信息數組,如果無相關收藏集則返回null
 */
function getrelatecollection($tid, $all = false, &$num = null, &$more = null) {
    global $_G;

    $maxdisplay = $_G['setting']['collectionnum']; // 獲取設置的收藏集顯示數量
    if(!$maxdisplay) return; // 如果設置為不顯示,則直接返回

    $tidrelate = C::t('forum_collectionrelated')->fetch($tid); // 獲取指定主題的收藏集信息
    $ctids = explode("\t", $tidrelate['collection'], -1); // 解析收藏集ID字符串為數組
    $num = count($ctids); // 計算收藏集數量

    if(!$ctids || !$num) {
        $more = $num = 0;
        return null;
    }
    if($all !== true && $num > $maxdisplay) {
        $more = 1; // 如果未設置獲取全部且收藏集數量超過最大顯示數量,則設置$more為1
    } else {
        $maxdisplay = 0; // 否則設置$maxdisplay為0,表示獲取全部
    }
    return C::t('forum_collection')->fetch_all($ctids, 'follownum', 'DESC', 0, $maxdisplay, '', $tid); // 獲取收藏集信息
}

/**
 * 設置@列表的Cookie
 *
 * @param array $uids 要設置的UID列表
 */
function set_atlist_cookie($uids) {
    global $_G;
    $atlist = $tmp = array();
    $num = 0;
    $maxlist = 10; // 設置@列表的最大數量
    if(empty($uids)) {
        return;
    }
    $newnum = count($uids); // 新的@列表數量
    if($newnum >= $maxlist) {
        $uids = array_slice($uids, 0, $maxlist); // 如果超過最大數量,則截取前$maxlist個UID
        dsetcookie('atlist', implode(',', $uids), 86400 * 360); // 設置Cookie
        return;
    }
    if($_G['cookie']['atlist']) {
        $atlist = explode(',', $_G['cookie']['atlist']);
        foreach($atlist as $key => $val) {
            if(!in_array($val, $uids)) {
                $num++;
                if($num == ($maxlist - $newnum)) {
                    break;
                }
                $tmp[$key] = $val;
            }
        }
    }
    dsetcookie('atlist', implode(',', $uids).($tmp ? ','.implode(',', $tmp) : ''), 86400 * 360); // 更新或設置Cookie
}

/**
 * 檢查HTTP_REFERER是否來自指定搜索引擎
 *
 * @return bool 返回true表示HTTP_REFERER來自指定搜索引擎,否則返回false
 */
function viewthread_is_search_referer() {
    $regex = "((http|https)\:\/\/)?";
    $regex .= "([a-z]*.)?(toutiao.com|m.sm.cn|[url]www.so.com[/url]|sogou.com|bing.com|baidu.com|google.com|google.cn|google.com.hk)(.[a-z]{2,3})?\/";
    if(preg_match("/^$regex/", $_SERVER['HTTP_REFERER'])) {
        return true;
    }
    return false;
}

/**
 * 生成字符串話題的圖片表示
 *
 * @param string $value 要生成圖片的字符串
 * @param string $key 生成圖片的標識關鍵字,默認與$value相同
 * @param bool $force 是否強制重新生成圖片,默認為false
 * @param int $rlength 如果指定,將對字符串進行截斷,使其長度不超過此參數
 * @return string 返回圖片的URL地址
 */
function stringtopic($value, $key = '', $force = false, $rlength = 0) {
    if($key === '') {
        $key = $value; // 如果未指定$key,則使用$value作為$key
    }
    // 計算圖片存儲路徑和URL
    $basedir = !getglobal('setting/attachdir') ? './data/attachment' : getglobal('setting/attachdir');
    $url = !getglobal('setting/attachurl') ? './data/attachment/' : getglobal('setting/attachurl');
    $subdir1 = substr(md5($key), 0, 2);
    $subdir2 = substr(md5($key), 2, 2);
    $target = 'temp/'.$subdir1.'/'.$subdir2.'/';
    $targetname = substr(md5($key), 8, 16).'.png';
    discuz_upload::check_dir_exists('temp', $subdir1, $subdir2); // 檢查目錄是否存在,不存在則創建
    // 檢查是否需要重新生成圖片
    if(!$force && file_exists($basedir.'/'.$target.$targetname)) {
        return $url.$target.$targetname; // 如果存在則直接返回圖片URL
    }
    $value = str_replace("\n", '', $value); // 去除字符串中的換行符
    // 默認字體設置
    $fontfile = $fontname = '';
    $ttfenabled = false;
    $size = 10;
    $w = 130;
    $rowh = 25;
    // 處理字符串,按換行符分割
    $value = explode("\r", $value);
    // 如果指定了最大長度,則對字符串進行截斷
    if($rlength) {
        $temp = array();
        foreach($value as $str) {
            $strlen = dstrlen($str);
            if($strlen > $rlength) {
                for($i = 0; $i < $strlen; $i++) {
                    $sub = cutstr($str, $rlength, '');
                    $temp[] = $sub;
                    $str = substr($str, strlen($sub));
                    $strlen = $strlen - $rlength;
                }
            } else {
                $temp[] = $str;
            }
        }
        $value = $temp;
        unset($temp);
    }
    // 使用TrueType字體繪制文本
    if(function_exists('imagettftext')) {
        $fontroot = DISCUZ_ROOT.'./static/image/seccode/font/ch/';
        $dirs = opendir($fontroot);
        while($entry = readdir($dirs)) {
            if($entry != '.' && $entry != '..' && in_array(strtolower(fileext($entry)), array('ttf', 'ttc'))) {
                $fontname = $entry;
                break;
            }
        }
        if(!empty($fontname)) {
            $fontfile = DISCUZ_ROOT.'./static/image/seccode/font/ch/'.$fontname;
        }
        if($fontfile) {
            if(strtoupper(CHARSET) != 'UTF-8') {
                include DISCUZ_ROOT.'./source/class/class_chinese.php';
                $cvt = new Chinese(CHARSET, 'utf8');
                $value = $cvt->Convert(implode("\r", $value));
                $value = explode("\r", $value);
            }
            $ttfenabled = true;
        }
    }

    // 計算文本的寬度和高度
    foreach($value as $str) {
        if($ttfenabled) {
            $box = imagettfbbox($size, 0, $fontfile, $str);
            $height = max($box[1], $box[3]) - min($box[5], $box[7]);
            $len = (max($box[2], $box[4]) - min($box[0], $box[6]));
            $rowh = max(array($height, $rowh));
        } else {
            $len = strlen($str) * 12;
        }
        $w = max(array($len, $w));
    }
    $h = $rowh * count($value) + count($value) * 2;
    // 創建圖片并繪制文本
    $im = @imagecreate($w, $h);
    $background_color = imagecolorallocate($im, 255, 255, 255); // 設置背景顏色
    $text_color = imagecolorallocate($im, 60, 60, 60); // 設置文本顏色
    $h = $ttfenabled ? $rowh : 4;
    foreach($value as $str) {
        if($ttfenabled) {
            imagettftext($im, $size, 0, 0, $h, $text_color, $fontfile, $str);
            $h += 2;
        } else {
            imagestring($im, $size, 0, $h, $str, $text_color);
        }
        $h += $rowh;
    }
    imagepng($im, $basedir.'/'.$target.$targetname); // 保存圖片
    imagedestroy($im);
    return $url.$target.$targetname; // 返回圖片URL
}
/**
 * 獲取回復背景樣式
 *
 * 根據用戶設置或全局設置, 獲取并返回回復內容的背景圖片樣式。
 *
 * @param string $replybg 用戶自定義的回復背景圖片名稱。
 * @return string 返回背景圖片的樣式字符串,如果沒有設置,則返回空字符串。
 */
function getreplybg($replybg = '') {
	global $_G;
	$style = '';
	// 檢查是否允許自定義回復背景
	if(getglobal('setting/allowreplybg')) {
		// 處理用戶自定義回復背景
		if($replybg) {
			$bgurl = $replybg;
			// 檢查文件是否存在,確保附件URL正確
			if(file_exists($_G['setting']['attachurl'].'common/'.$replybg)) {
				$bgurl = $_G['setting']['attachurl'].'common/'.$replybg;
			}
		// 處理全局默認回復背景
		} elseif($_G['setting']['globalreplybg']) {
			$bgurl = $_G['setting']['globalreplybg'];
			// 檢查文件是否存在,確保附件URL正確
			if(file_exists($_G['setting']['attachurl'].'common/'.$_G['setting']['globalreplybg'])) {
				$bgurl = $_G['setting']['attachurl'].'common/'.$_G['setting']['globalreplybg'];
			}
		}
		// 如果設置了背景圖片,則生成樣式字符串
		if($bgurl) {
			$style = ' style="background-image: url('.$bgurl.');"';
		}
	}
	return $style;
}

/**
 * 安全過濾數據
 *
 * 對數組或字符串進行安全過濾,替換BBCODE為HTML標簽,并移除潛在的XSS攻擊向量。
 *
 * @param &$data 需要進行安全過濾的數據,可以是數組或字符串。
 */
function safefilter(&$data) {
	if(is_array($data)) {
		// 遞歸處理數組中的每個元素
		foreach($data as $k => $v) {
			safefilter($data[$k]);
		}
	} else {
		// 替換和清理特定的BBCODE以及HTML標簽,避免XSS攻擊
		$data = str_replace(array(
			'[/color]', '[b]', '[/b]', '[s]', '[/s]', '[i]', '[/i]', '[u]', '[/u]',
			), array(
			'</font>', '<b>', '</b>', '<strike>', '</strike>', '<i>', '</i>', '<u>', '</u>'
			), preg_replace(array(
			"/\[color=([#\w]+?)\]/i",
			"/\[color=((rgb|rgba)\([\d\s\.,]+?\))\]/i",
			), array(
			"<font color=\"\\1\">",
			"<font style=\"color:\\1\">",
			), strip_tags($data)));
	}
}

?>
帖子永久地址: 

新秀網絡驗證系統 - 論壇版權1、本主題所有言論和圖片純屬會員個人意見,與本論壇立場無關
2、本站所有主題由該帖子作者發表,該帖子作者與新秀網絡驗證系統享有帖子相關版權
3、其他單位或個人使用、轉載或引用本文時必須同時征得該帖子作者和新秀網絡驗證系統的同意
4、帖子作者須承擔一切因本文發表而直接或間接導致的民事或刑事法律責任
5、本帖部分內容轉載自其它媒體,但并不代表本站贊同其觀點和對其真實性負責
6、如本帖侵犯到任何版權問題,請立即告知本站,本站將及時予與刪除并致以最深的歉意
7、新秀網絡驗證系統管理員和版主有權不事先通知發貼者而刪除本文

您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規則

QQ|Archiver|手機版|新秀網絡驗證系統API[軟著登字第13061951號] ( 豫ICP備2021033257號-1 )

GMT+8, 2025-7-1 13:21 , Processed in 0.218757 second(s), 40 queries , Redis On.

Powered by Discuz! X3.5 Licensed

© 2001-2025 Discuz! Team.

快速回復 返回頂部 返回列表