Discuz!常用函數解析

Discuz!常用函數解析
php, 函數, Discuz, param, Discuz二次開發
<?php
/*
        [Discuz!] (C)2001-2007 Comsenz Inc.
        This is NOT a freeware, use is subject to license terms
        $Id: global.func.php 13426 2008-04-15 03:37:02Z heyond $
*/
if(!defined('IN_DISCUZ')) {
        exit('Access Denied');
}
/**
* 加密或者解密用戶信息
* @param $string - 加密或解密的串
* @param $operation - 加密還是解密
* @param 密鑰
* @return 返回字符串
* $ckey_length 隨機密鑰長度 取值 0-32;
* 加入隨機密鑰,可以令密文無任何規律,即便是原文和密鑰完全相同,加密結果也會每次不同,增大破解難度。
* 取值越大,密文變動規律越大,密文變化 = 16 的 $ckey_length 次方
* 當此值爲 0 時,則不產生隨機密鑰
*/
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
        $ckey_length = 4;
        $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
        $cryptkey = $keya.md5($keya.$keyc);
        $key_length = strlen($cryptkey);
        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
        $string_length = strlen($string);
        $result = '';
        $box = range(0, 255);
        $rndkey = array();
        for($i = 0; $i <= 255; $i++) {
                $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }
        for($j = $i = 0; $i < 256; $i++) {
                $j = ($j + $box[$i] + $rndkey[$i]) % 256;
                $tmp = $box[$i];
                $box[$i] = $box[$j];
                $box[$j] = $tmp;
        }
        for($a = $j = $i = 0; $i < $string_length; $i++) {
                $a = ($a + 1) % 256;
                $j = ($j + $box[$a]) % 256;
                $tmp = $box[$a];
                $box[$a] = $box[$j];
                $box[$j] = $tmp;
                $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }
        if($operation == 'DECODE') {
                if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
                        return substr($result, 26);
                } else {
                        return '';
                }
        } else {
                return $keyc.str_replace('=', '', base64_encode($result));
        }
}
/**
* 清理cookie
*/
function clearcookies() {
        global $discuz_uid, $discuz_user, $discuz_pw, $discuz_secques, $adminid, $credits;
        dsetcookie('sid', '', -86400 * 365);
        dsetcookie('auth', '', -86400 * 365);
        dsetcookie('visitedfid', '', -86400 * 365);
        dsetcookie('onlinedetail', '', -86400 * 365, 0);
        dsetcookie('loginuser', '', -86400 * 365);
        dsetcookie('activationauth', '', -86400 * 365);
        $discuz_uid = $adminid = $credits = 0;
        $discuz_user = $discuz_pw = $discuz_secques = '';
}
/**
* 檢查積分下限
* @param $creditsarray - 積分數組
* @param $coef - 積分
*/
function checklowerlimit($creditsarray, $coef = 1) {
        if(is_array($creditsarray)) {
                global $extcredits, $id;
                foreach($creditsarray as $id => $addcredits) {
                        $addcredits = $addcredits * $coef;
                        if($addcredits < 0 && ($GLOBALS['extcredits'.$id] < $extcredits[$id]['lowerlimit'] || (($GLOBALS['extcredits'.$id] + $addcredits) < $extcredits[$id]['lowerlimit']))) {
                                if($coef == 1) {
                                        showmessage('credits_policy_lowerlimit');
                                } else {
                                        showmessage('credits_policy_num_lowerlimit');
                                }
                        }
                }
        }
}
/**
* 密碼檢測
*
* @param string $md5
* @param string $verified
* @param string $salt
* @return
*         0= Failed
*         1= MD5 with salt, 2= Dual MD5, 3= Normal Md5 4= MD5-16
*/
function checkmd5($md5, $verified, $salt = '') {
        if(md5($md5.$salt) == $verified) {
                $result = !empty($salt) ? 1 : 2;
        } elseif(empty($salt)) {
                $result = $md5 == $verified ? 3 : ((strlen($verified) == 16 && substr($md5, 8, 16) == $verified) ? 4 : 0);
        } else {
                $result = 0;
        }
        return $result;
}
/**
* 檢查模板源文件是否更新
* 當編譯文件不存時強制重新編譯
* 當 tplrefresh = 1 時檢查文件
* 當 tplrefresh > 1 時,則根據 tplrefresh 取餘,無餘時則檢查更新
*
*/
function checktplrefresh($maintpl, $subtpl, $timecompare, $templateid, $tpldir) {
        global $tplrefresh;
        if(empty($timecompare) || $tplrefresh == 1 || ($tplrefresh > 1 && !($GLOBALS['timestamp'] % $tplrefresh))) {
                if(empty($timecompare) || @filemtime($subtpl) > $timecompare) {
                        require_once DISCUZ_ROOT.'./include/template.func.php';
                        parse_template($maintpl, $templateid, $tpldir);
                        return TRUE;
                }
        }
        return         FALSE;
}
/**
* 根據中文裁減字符串
* @param $string - 字符串
* @param $length - 長度
* @param $doc - 縮略後綴
* @return 返回帶省略號被裁減好的字符串
*/
function cutstr($string, $length, $dot = ' ...') {
        global $charset;
        if(strlen($string) <= $length) {
                return $string;
        }
        $string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string);
        $strcut = '';
        if(strtolower($charset) == 'utf-8') {
                $n = $tn = $noc = 0;
                while($n < strlen($string)) {
                        $t = ord($string[$n]);
                        if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                                $tn = 1; $n++; $noc++;
                        } elseif(194 <= $t && $t <= 223) {
                                $tn = 2; $n += 2; $noc += 2;
                        } elseif(224 <= $t && $t < 239) {
                                $tn = 3; $n += 3; $noc += 2;
                        } elseif(240 <= $t && $t <= 247) {
                                $tn = 4; $n += 4; $noc += 2;
                        } elseif(248 <= $t && $t <= 251) {
                                $tn = 5; $n += 5; $noc += 2;
                        } elseif($t == 252 || $t == 253) {
                                $tn = 6; $n += 6; $noc += 2;
                        } else {
                                $n++;
                        }
                        if($noc >= $length) {
                                break;
                        }
                }
                if($noc > $length) {
                        $n -= $tn;
                }
                $strcut = substr($string, 0, $n);
        } else {
                for($i = 0; $i < $length; $i++) {
                        $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
                }
        }
        $strcut = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $strcut);
        return $strcut.$dot;
}
/**
* 處理轉義字符
* @param $string -字符串
* @param $force - 是否強制
* @return 返回整理好的字符串
*/
function daddslashes($string, $force = 0) {
        !defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
        if(!MAGIC_QUOTES_GPC || $force) {
                if(is_array($string)) {
                        foreach($string as $key => $val) {
                                $string[$key] = daddslashes($val, $force);
                        }
                } else {
                        $string = addslashes($string);
                }
        }
        return $string;
}
/**
* 檢測日期的有效性
*/
function datecheck($ymd, $sep='-') {
        if(!empty($ymd)) {
                list($year, $month, $day) = explode($sep, $ymd);
                return checkdate($month, $day, $year);
        } else {
                return FALSE;
        }
}
/**
* 調試信息
*/
function debuginfo() {
        if($GLOBALS['debug']) {
                global $db, $discuz_starttime, $debuginfo;
                $mtime = explode(' ', microtime());
                $debuginfo = array('time' => number_format(($mtime[1] + $mtime[0] - $discuz_starttime), 6), 'queries' => $db->querynum);
                return TRUE;
        } else {
                return FALSE;
        }
}
/**
* 退出系統
*/
function dexit($message = '') {
        echo $message;
        output();
        exit();
}
function dfopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) {
        $return = '';
        $matches = parse_url($url);
        $host = $matches['host'];
        $path = $matches['path'] ? $matches['path'].'?'.$matches['query'].'#'.$matches['fragment'] : '/';
        $port = !empty($matches['port']) ? $matches['port'] : 80;
        if($post) {
                $out = "POST $path HTTP/1.0\r\n";
                $out .= "Accept: */*\r\n";
                //$out .= "Referer: $boardurl\r\n";
                $out .= "Accept-Language: zh-cn\r\n";
                $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
                $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
                $out .= "Host: $host\r\n";
                $out .= 'Content-Length: '.strlen($post)."\r\n";
                $out .= "Connection: Close\r\n";
                $out .= "Cache-Control: no-cache\r\n";
                $out .= "Cookie: $cookie\r\n\r\n";
                $out .= $post;
        } else {
                $out = "GET $path HTTP/1.0\r\n";
                $out .= "Accept: */*\r\n";
                //$out .= "Referer: $boardurl\r\n";
                $out .= "Accept-Language: zh-cn\r\n";
                $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
                $out .= "Host: $host\r\n";
                $out .= "Connection: Close\r\n";
                $out .= "Cookie: $cookie\r\n\r\n";
        }
        $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
        if(!$fp) {
                return '';//note $errstr : $errno \r\n
        } else {
                stream_set_blocking($fp, $block);
                stream_set_timeout($fp, $timeout);
                @fwrite($fp, $out);
                $status = stream_get_meta_data($fp);
                if(!$status['timed_out']) {
                        while (!feof($fp)) {
                                if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
                                        break;
                                }
                        }
                        $stop = false;
                        while(!feof($fp) && !$stop) {
                                $data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
                                $return .= $data;
                                if($limit) {
                                        $limit -= strlen($data);
                                        $stop = $limit <= 0;
                                }
                        }
                }
                @fclose($fp);
                return $return;
        }
}
/**
* HTML轉義字符
* @param $string - 字符串
* @return 返回轉義好的字符串
*/
function dhtmlspecialchars($string) {
        if(is_array($string)) {
                foreach($string as $key => $val) {
                        $string[$key] = dhtmlspecialchars($val);
                }
        } else {
                $string = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
                str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string));
        }
        return $string;
}
function dheader($string, $replace = true, $http_response_code = 0) {
        $string = str_replace(array("\r", "\n"), array('', ''), $string);
        if(empty($http_response_code) || PHP_VERSION < '4.3' ) {
                @header($string, $replace);
        } else {
                @header($string, $replace, $http_response_code);
        }
        if(preg_match('/^\s*location:/is', $string)) {
                exit();
        }
}
/**
* 上傳文件的函數
* @param $file - 要上傳的文件
* @return 返回帶省略號被裁減好的字符串
*/
function disuploadedfile($file) {
        return function_exists('is_uploaded_file') && (is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file)));
}

/**
* 刷新重定向
*/
function dreferer($default = '') {
        global $referer, $indexname;
        $default = empty($default) ? $indexname : '';
        if(empty($referer) && isset($GLOBALS['_SERVER']['HTTP_REFERER'])) {
                $referer = preg_replace("/([\?&])((sid\=[a-z0-9]{6})(&|$))/i", '\\1', $GLOBALS['_SERVER']['HTTP_REFERER']);
                $referer = substr($referer, -1) == '?' ? substr($referer, 0, -1) : $referer;
        } else {
                $referer = dhtmlspecialchars($referer);
        }
        if(!preg_match("/(\.php|[a-z]+(\-\d+)+\.html)/", $referer) || strpos($referer, 'logging.php')) {
                $referer = $default;
        }
        return $referer;
}
/**
* 設置cookie
* @param $var - 變量名
* @param $value - 變量值
* @param $life - 生命期
* @param $prefix - 前綴
*/
function dsetcookie($var, $value, $life = 0, $prefix = 1) {
        global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
        setcookie(($prefix ? $cookiepre : '').$var, $value,
                $life ? $timestamp + $life : 0, $cookiepath,
                $cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}
function dunlink($filename, $havethumb = 0, $remote = 0) {
        global $authkey, $ftp, $attachdir;
        if($remote) {
                require_once DISCUZ_ROOT.'./include/ftp.func.php';
                if(!$ftp['connid']) {
                        if(!($ftp['connid'] = dftp_connect($ftp['host'], $ftp['username'], authcode($ftp['password'], 'DECODE', md5($authkey)), $ftp['attachdir'], $ftp['port'], $ftp['ssl']))) {
                                return;
                        }
                }
                dftp_delete($ftp['connid'], $filename);
                $havethumb && dftp_delete($ftp['connid'], $filename.'.thumb.jpg');
        } else {
                @unlink($attachdir.'/'.$filename);
                $havethumb && @unlink($attachdir.'/'.$filename.'.thumb.jpg');
        }
}
/**
* 格式化email
* @param $email - 郵箱地址
* @param $tolink - 是否增加鏈接
* @return 返回代碼
*/
function emailconv($email, $tolink = 1) {
        $email = str_replace(array('@', '.'), array('@', '.'), $email);
        return $tolink ? '<a href="mailto: '.$email.'">'.$email.'</a>': $email;
}
/**
* 系統錯誤日誌
* @param $type - 信息類型
* @param $message - 信息
* @param $halt - 是否退出
*/
function errorlog($type, $message, $halt = 1) {
        global $timestamp, $discuz_userss, $onlineip, $_SERVER;
        $user = empty($discuz_userss) ? '' : $discuz_userss.'<br />';
        $user .= $onlineip.'|'.$_SERVER['REMOTE_ADDR'];
        writelog('errorlog', dhtmlspecialchars("$timestamp\t$type\t$user\t".str_replace(array("\r", "\n"), array(' ', ' '), trim($message))));
        if($halt) {
                exit();
        }
}
/**
* 去掉文件擴展名
* @param $finename - 文件名稱
* @return 文件名
*/
function fileext($filename) {
        return trim(substr(strrchr($filename, '.'), 1, 10));
}
/**
* 產生form防僞碼
*/
function formhash($specialadd = '') {
        global $discuz_user, $discuz_uid, $discuz_pw, $timestamp, $discuz_auth_key;
        $hashadd = defined('IN_ADMINCP') ? 'Only For Discuz! Admin Control Panel' : '';
        return substr(md5(substr($timestamp, 0, -7).$discuz_user.$discuz_uid.$discuz_pw.$discuz_auth_key.$hashadd.$specialadd), 8, 8);
}
/**
* 論壇權限
* @param $permstr - 權限信息
* @return 0 無權限 > 0 有權限
*/
function forumperm($permstr) {
        global $groupid, $extgroupids;
        $groupidarray = array($groupid);
        foreach(explode("\t", $extgroupids) as $extgroupid) {
                if($extgroupid = intval(trim($extgroupid))) {
                        $groupidarray[] = $extgroupid;
                }
        }
        return preg_match("/(^|\t)(".implode('|', $groupidarray).")(\t|$)/", $permstr);
}
/**
權限表達式
* @param $formula - 權限表達式
* @param $type - 0 論壇權限驗證 1 勳章權限驗證 2 返回勳章權限字串
*/
function formulaperm($formula, $type = 0) {
        global $_DSESSION, $extcredits, $formulamessage, $usermsg, $forum, $language;
        if((!$formula || $_DSESSION['adminid'] == 1 || $forum['ismoderator']) && !$type) {
                return;
        }
        $formula = unserialize($formula);$formula = $formula[1];
        if(!$formula) {
                return;
        }
        @eval("\$formulaperm = ($formula) ? TRUE : FALSE;");
        if(!$formulaperm || $type == 2) {
                include_once language('misc');
                $search = array('$_DSESSION[\'digestposts\']', '$_DSESSION[\'posts\']', '$_DSESSION[\'oltime\']', '$_DSESSION[\'pageviews\']');
                $replace = array($language['formulaperm_digestposts'], $language['formulaperm_posts'], $language['formulaperm_oltime'], $language['formulaperm_pageviews']);
                for($i = 1; $i <= 8; $i++) {
                        $search[] = '$_DSESSION[\'extcredits'.$i.'\']';
                        $replace[] = $extcredits[$i]['title'] ? $extcredits[$i]['title'] : $language['formulaperm_extcredits'].$i;
                }
                $i = 0;$usermsg = '';
                foreach($search as $s) {
                        $usermsg .= strexists($formula, $s) ? $replace[$i].' = '.(@eval('return intval('.$s.');')).'   ' : '';
                        $i++;
                }
                $search = array_merge($search, array('and', 'or', '>=', '<='));
                $replace = array_merge($replace, array('  '.$language['formulaperm_and'].'  ', '  '.$language['formulaperm_or'].'  ', '≥', '≤'));
                $formulamessage = str_replace($search, $replace, $formula);
                if($type == 1) {
                        showmessage('medal_permforum_nopermission', NULL, 'NOPERM');
                } elseif($type == 2) {
                        return $formulamessage;
                } else {
                        showmessage('forum_permforum_nopermission', NULL, 'NOPERM');
                }
        }
        return TRUE;
}
/**
* 獲取用戶所在組
* @param $uid - 用戶組
* @param $group - 用戶組
* @param $member - 用戶組
*/
function getgroupid($uid, $group, &$member) {
        global $creditsformula, $db, $tablepre;
        if(!empty($creditsformula)) {
                $updatearray = array();
                eval("\$credits = round($creditsformula);");
                if($credits != $member['credits']) {
                        $updatearray[] = "credits='$credits'";
                        $member['credits'] = $credits;
                }
                if($group['type'] == 'member' && !($member['credits'] >= $group['creditshigher'] && $member['credits'] < $group['creditslower'])) {
                        $query = $db->query("SELECT groupid FROM {$tablepre}usergroups WHERE type='member' AND $member[credits]>=creditshigher AND $member[credits]<creditslower LIMIT 1");
                        if($db->num_rows($query)) {
                                $member['groupid'] = $db->result($query, 0);
                                $updatearray[] = "groupid='$member[groupid]'";
                        }
                }
                if($updatearray) {
                        $db->query("UPDATE {$tablepre}members SET ".implode(', ', $updatearray)." WHERE uid='$uid'");
                }
        }
        return $member['groupid'];
}
function getrobot() {
        if(!defined('IS_ROBOT')) {
                $kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
                $kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
                if(preg_match("/($kw_browsers)/", $_SERVER['HTTP_USER_AGENT'])) {
                        define('IS_ROBOT', FALSE);
                } elseif(preg_match("/($kw_spiders)/", $_SERVER['HTTP_USER_AGENT'])) {
                        define('IS_ROBOT', TRUE);
                } else {
                        define('IS_ROBOT', FALSE);
                }
        }
        return IS_ROBOT;
}
/**
* 根據用戶的 uid 得到 avatar/home 目錄
*
* @param int $uid
* @return string
*/
function get_home($uid) {
        $uid = sprintf("%05d", $uid);
        $dir1 = substr($uid, 0, -4);
        $dir2 = substr($uid, -4, 2);
        $dir3 = substr($uid, -2, 2);
        return $dir1.'/'.$dir2.'/'.$dir3;
}
/**
* vip用戶購買組權限是否到期
* @param $terms 期限 來源於 memberfields 表的 groupterms 字段
* @return 返回過期信息
*/
function groupexpiry($terms) {
        $terms = is_array($terms) ? $terms : unserialize($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;
}
/**
* ip允許訪問
* @param $ip 要檢查的ip地址
* @param - $accesslist 允許訪問的ip地址
* @param 返回結果
*/
function ipaccess($ip, $accesslist) {
        return preg_match("/^(".str_replace(array("\r\n", ' '), array('|', ''), preg_quote($accesslist, '/')).")/", $ip);
}
/**
* 將數組元素格式化成類似 '1','2','3' 的字符串
* @return STRING 字串 否則爲 NULL
*/
function implodeids($array) {
        if(!empty($array)) {
                return "'".implode("','", is_array($array) ? $array : array($array))."'";
        } else {
                return '';
        }
}
/**
* ip限制訪問
* @param $ip 要檢查的ip地址
* @param - $accesslist 允許訪問的ip地址
* @param 返回結果
*/
function ipbanned($onlineip) {
        global $ipaccess, $timestamp, $cachelost;
        if($ipaccess && !ipaccess($onlineip, $ipaccess)) {
                return TRUE;
        }
        $cachelost .= (@include DISCUZ_ROOT.'./forumdata/cache/cache_ipbanned.php') ? '' : ' ipbanned';
        if(empty($_DCACHE['ipbanned'])) {
                return FALSE;
        } else {
                if($_DCACHE['ipbanned']['expiration'] < $timestamp) {
                        @unlink(DISCUZ_ROOT.'./forumdata/cache/cache_ipbanned.php');
                }
                return preg_match("/^(".$_DCACHE['ipbanned']['regexp'].")$/", $onlineip);
        }
}
/**
* 檢查郵箱是否有效
* @param $email 要檢查的郵箱
* @param 返回結果
*/
function isemail($email) {
        return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}
/**
* 加載語言
* @param $file - 語言文件
* @param $templateid - 模板號碼
* @param $tpldir - 模板路徑
* @return 加載的語言
*/
function language($file, $templateid = 0, $tpldir = '') {
        $tpldir = $tpldir ? $tpldir : TPLDIR;
        $templateid = $templateid ? $templateid : TEMPLATEID;
        $languagepack = DISCUZ_ROOT.'./'.$tpldir.'/'.$file.'.lang.php';
        if(file_exists($languagepack)) {
                return $languagepack;
        } elseif($templateid != 1 && $tpldir != './templates/default') {
                return language($file, 1, './templates/default');
        } else {
                return FALSE;
        }
}
/**
* 分頁
* @param $num - 總數
* @param $perpage - 每頁數
* @param $curpage - 當前頁
* @param $mpurl - 跳轉的路徑
* @param $maxpages - 允許顯示的最大頁數
* @param $page - 最多顯示多少頁碼
* @param $autogoto - 最後一頁,自動跳轉
* @param $simple - 是否簡潔模式(簡潔模式不顯示上一頁、下一頁和頁碼跳轉)
* @return 返回分頁代碼
*/
function multi($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 10, $autogoto = TRUE, $simple = FALSE) {
        global $maxpage;
        //debug 加入 ajaxtarget 屬性
        $ajaxtarget = !empty($_GET['ajaxtarget']) ? " ajaxtarget=\"".dhtmlspecialchars($_GET['ajaxtarget'])."\" " : '';
        $multipage = '';
        $mpurl .= strpos($mpurl, '?') ? '&' : '?';
        $realpages = 1;
        if($num > $perpage) {
                $offset = 2;
                $realpages = @ceil($num / $perpage);
                $pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;
                if($page > $pages) {
                        $from = 1;
                        $to = $pages;
                } else {
                        $from = $curpage - $offset;
                        $to = $from + $page - 1;
                        if($from < 1) {
                                $to = $curpage + 1 - $from;
                                $from = 1;
                                if($to - $from < $page) {
                                        $to = $page;
                                }
                        } elseif($to > $pages) {
                                $from = $pages - $page + 1;
                                $to = $pages;
                        }
                }
                $multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'page=1" class="first"'.$ajaxtarget.'>1 ...</a>' : '').
                        ($curpage > 1 && !$simple ? '<a href="'.$mpurl.'page='.($curpage - 1).'" class="prev"'.$ajaxtarget.'>‹‹</a>' : '');
                for($i = $from; $i <= $to; $i++) {
                        $multipage .= $i == $curpage ? '<strong>'.$i.'</strong>' :
                                '<a href="'.$mpurl.'page='.$i.($ajaxtarget && $i == $pages && $autogoto ? '#' : '').'"'.$ajaxtarget.'>'.$i.'</a>';
                }
                $multipage .= ($curpage < $pages && !$simple ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="next"'.$ajaxtarget.'>››</a>' : '').
                        ($to < $pages ? '<a href="'.$mpurl.'page='.$pages.'" class="last"'.$ajaxtarget.'>... '.$realpages.'</a>' : '').
                        (!$simple && $pages > $page && !$ajaxtarget ? '<kbd><input type="text" name="custompage" size="3" /></kbd>' : '');
                $multipage = $multipage ? '<div class="pages">'.(!$simple ? '<em> '.$num.' </em>' : '').$multipage.'</div>' : '';
        }
        $maxpage = $realpages;
        return $multipage;
}
/**
* 系統輸出
* @return 返回內容
*/
function output() {
        if(defined('DISCUZ_OUTPUTED')) {
                return;
        }
        define('DISCUZ_OUTPUTED', 1);
        global $sid, $transsidstatus, $rewritestatus, $ftp, $advlist, $insenz, $queryfloat, $thread, $inajax;
        if(($advlist || !empty($insenz['hardadstatus']) || $queryfloat) && !defined('IN_ADMINCP') && !(CURSCRIPT == 'viewthread' && $thread['digest'] == '-1') && !$inajax) {
                include template('adv');
        }
        if(($transsidstatus = empty($GLOBALS['_DCOOKIE']['sid']) && $transsidstatus) || $rewritestatus) {
                if($transsidstatus) {
                        $searcharray = array
                                (
                                "/\<a(\s*[^\>]+\s*)href\=([\"|\']?)([^\"\'\s]+)/ies",
                                "/(\<form.+?\>)/is"
                                );
                        $replacearray = array
                                (
                                "transsid('\\3','<a\\1href=\\2')",
                                "\\1\n<input type=\"hidden\" name=\"sid\" value=\"$sid\" />"
                                );
                } else {
                        $searcharray = $replacearray = array();
                        if($rewritestatus & 1) {
                                $searcharray[] = "/\<a href\=\"forumdisplay\.php\?fid\=(\d+)(&page\=(\d+))?\"([^\>]*)\>/e";
                                $replacearray[] = "rewrite_forum('\\1', '\\3', '\\4')";
                        }
                        if($rewritestatus & 2) {
                                $searcharray[] = "/\<a href\=\"viewthread\.php\?tid\=(\d+)(&extra\=page\%3D(\d+))?(&page\=(\d+))?\"([^\>]*)\>/e";
                                $replacearray[] = "rewrite_thread('\\1', '\\5', '\\3', '\\6')";
                        }
                        if($rewritestatus & 4) {
                                $searcharray[] = "/\<a href\=\"space\.php\?(uid\=(\d+)|username\=([^&]+?))\"([^\>]*)\>/e";
                                $replacearray[] = "rewrite_space('\\2', '\\3', '\\4')";
                        }
                        if($rewritestatus & 8) {
                                $searcharray[] = "/\<a href\=\"tag\.php\?name\=([^&]+?)\"([^\>]*)\>/e";
                                $replacearray[] = "rewrite_tag('\\1', '\\2')";
                        }
                }
                $content = preg_replace($searcharray, $replacearray, ob_get_contents());
                ob_end_clean();
                $GLOBALS['gzipcompress'] ? ob_start('ob_gzhandler') : ob_start();
                echo $content;
        }
        if($ftp['connid']) {
                @ftp_close($ftp['connid']);
        }
        $ftp = array();
        //debug Module:HTML_CACHE 如果定義了緩存常量,則此處將緩衝區的內容寫入文件。如果爲 index 緩存,則直接寫入 forumdata/index.cache ,如果爲 viewthread 緩存,則根據md5(tid,等參數)取前三位爲目錄加上$tid_$page,做文件名。
        //debug $threadcacheinfo, $indexcachefile 爲全局變量
        if(defined('CACHE_FILE') && CACHE_FILE && !defined('CACHE_FORBIDDEN')) {
                global $cachethreaddir;
                if(diskfreespace(DISCUZ_ROOT.'./'.$cachethreaddir) > 1000000) {
                        if($fp = @fopen(CACHE_FILE, 'w')) {
                                flock($fp, LOCK_EX);
                                fwrite($fp, empty($content) ? ob_get_contents() : $content);
                        }
                        @fclose($fp);
                        chmod(CACHE_FILE, 0777);
                }
        }
}
/**
* 時間段設置檢測
* @param $periods - 那種時間段 $settings[$periods]  $settings['postbanperiods'] $settings['postmodperiods']
* @param $showmessage - 是否提示信息
* @return 返回檢查結果
*/
function periodscheck($periods, $showmessage = 1) {
        global $timestamp, $disableperiodctrl, $_DCACHE, $banperiods;
        if(!$disableperiodctrl && $_DCACHE['settings'][$periods]) {
                $now = gmdate('G.i', $timestamp + $_DCACHE['settings']['timeoffset'] * 3600);
                foreach(explode("\r\n", str_replace(':', '.', $_DCACHE['settings'][$periods])) as $period) {
                        list($periodbegin, $periodend) = explode('-', $period);
                        if(($periodbegin > $periodend && ($now >= $periodbegin || $now < $periodend)) || ($periodbegin < $periodend && $now >= $periodbegin && $now < $periodend)) {
                                $banperiods = str_replace("\r\n", ', ', $_DCACHE['settings'][$periods]);
                                if($showmessage) {
                                        showmessage('period_nopermission', NULL, 'NOPERM');
                                } else {
                                        return TRUE;
                                }
                        }
                }
        }
        return FALSE;
}
function postfeed($feed) {
        global $discuz_uid, $discuz_user;
        require_once DISCUZ_ROOT.'./templates/default/feed.lang.php';
        require_once DISCUZ_ROOT.'./uc_client/client.php';
        $feed['title_template'] = $feed['title_template'] ? $language[$feed['title_template']] : '';
        $feed['body_template'] = $feed['title_template'] ? $language[$feed['body_template']] : '';
        uc_feed_add($feed['icon'], $discuz_uid, $discuz_user, $feed['title_template'], $feed['title_data'], $feed['body_template'], $feed['body_data'], '', '', $feed['images']);
}
/**
* 問題答案加密
* @param $questionid - 問題
* @param $answer - 答案
* @return 返回加密的字串
*/
function quescrypt($questionid, $answer) {
        return $questionid > 0 && $answer != '' ? substr(md5($answer.md5($questionid)), 16, 8) : '';
}
/**
* 產生僞靜態地址
* @param $tid 主題id
* @param $page 頁標
* @param $prevpage 上一頁
* @param extra 擴展
* @return 返回鏈接
*/
function rewrite_thread($tid, $page = 0, $prevpage = 0, $extra = '') {
        return '<a href="thread-'.$tid.'-'.($page ? $page : 1).'-'.($prevpage && !IS_ROBOT ? $prevpage : 1).'.html"'.stripslashes($extra).'>';
}
/**
* 產生僞靜態地址
* @param $fid 論壇id
* @param $page 頁標
* @param extra 擴展
* @return 返回鏈接
*/
function rewrite_forum($fid, $page = 0, $extra = '') {
        return '<a href="forum-'.$fid.'-'.($page ? $page : 1).'.html"'.stripslashes($extra).'>';
}
function rewrite_space($uid, $username, $extra = '') {
        $GLOBALS['rewritecompatible'] && $username = rawurlencode($username);
        return '<a href="space-'.($uid ? 'uid-'.$uid : 'username-'.$username).'.html"'.stripslashes($extra).'>';
}
function rewrite_tag($name, $extra = '') {
        $GLOBALS['rewritecompatible'] && $name = rawurlencode($name);
        return '<a href="tag-'.$name.'.html"'.stripslashes($extra).'>';
}

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章