<?phpjavascript
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: function_core.php 34523 2014-05-15 04:22:29Z nemohou $
*/php
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}css
define('DISCUZ_CORE_FUNCTION', true);html
/**
* like url encode, but can encode full url, not only the parms
* this function to encode URLs according to RFC 3986(exclude char ',(,) )
* @param type $url
* @return type
*/
function durlencode($url) {
static $fix = array('%21', '%2A','%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
static $replacements = array('!', '*', ';', ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
return str_replace($fix, $replacements, urlencode($url));
}java
/**
* 系統錯誤處理
* @param <type> $message 錯誤信息a
* @param <type> $show 是否顯示信息
* @param <type> $save 是否存入日誌
* @param <type> $halt 是否中斷訪問
*/
function system_error($message, $show = true, $save = true, $halt = true) {
discuz_error::system_error($message, $show, $save, $halt);
}android
/**
* 更新 session
* @global <type> $_G
* @staticvar boolean $updated
* @return boolean
*/
function updatesession() {
return C::app()->session->updatesession();
}c++
/**
* 設置全局 $_G 中的變量
* @global <array> $_G
* @param <string> $key 鍵
* @param <string> $value 值
* @return true
*
* @example
* setglobal('test', 1); // $_G['test'] = 1;
* setglobal('config/test/abc') = 2; //$_G['config']['test']['abc'] = 2;
*
*/
function setglobal($key , $value, $group = null) {
global $_G;
$key = explode('/', $group === null ? $key : $group.'/'.$key);
$p = &$_G;
foreach ($key as $k) {
if(!isset($p[$k]) || !is_array($p[$k])) {
$p[$k] = array();
}
$p = &$p[$k];
}
$p = $value;
return true;
}web
/**
* 獲取全局變量 $_G 當中的某個數值
* @example
* $v = getglobal('test'); // $v = $_G['test']
* $v = getglobal('test/hello/ok'); // $v = $_G['test']['hello']['ok']
*
* @global $_G
* @param string $key
*
* @return type
*/
function getglobal($key, $group = null) {
global $_G;
$key = explode('/', $group === null ? $key : $group.'/'.$key);
$v = &$_G;
foreach ($key as $k) {
if (!isset($v[$k])) {
return null;
}
$v = &$v[$k];
}
return $v;
}ajax
/**
* 取出 get, post, cookie 當中的某個變量
*
* @param string $k key 值
* @param string $type 類型
* @return mix
*/
function getgpc($k, $type='GP') {
$type = strtoupper($type);
switch($type) {
case 'G': $var = &$_GET; break;
case 'P': $var = &$_POST; break;
case 'C': $var = &$_COOKIE; break;
default:
if(isset($_GET[$k])) {
$var = &$_GET;
} else {
$var = &$_POST;
}
break;
}sql
return isset($var[$k]) ? $var[$k] : NULL;
}
/**
* 根據uid 獲取用戶基本數據
* @staticvar array $users 存放已經獲取的用戶的信息,避免重複查庫
* @param <int> $uid
* @param int $fetch_archive 0:只查詢主表,1:查詢主表和存檔表,2只查詢存檔表
* @return <array>
*/
function getuserbyuid($uid, $fetch_archive = 0) {
static $users = array();
if(empty($users[$uid])) {
$users[$uid] = C::t('common_member'.($fetch_archive === 2 ? '_archive' : ''))->fetch($uid);
if($fetch_archive === 1 && empty($users[$uid])) {
$users[$uid] = C::t('common_member_archive')->fetch($uid);
}
}
if(!isset($users[$uid]['self']) && $uid == getglobal('uid') && getglobal('uid')) {
$users[$uid]['self'] = 1;
}
return $users[$uid];
}
/**
* 獲取當前用戶的擴展資料
* @param $field 字段
*/
function getuserprofile($field) {
global $_G;
if(isset($_G['member'][$field])) {
return $_G['member'][$field];
}
static $tablefields = array(
'count' => array('extcredits1','extcredits2','extcredits3','extcredits4','extcredits5','extcredits6','extcredits7','extcredits8','friends','posts','threads','digestposts','doings','blogs','albums','sharings','attachsize','views','oltime','todayattachs','todayattachsize', 'follower', 'following', 'newfollower', 'blacklist'),
'status' => array('regip','lastip','lastvisit','lastactivity','lastpost','lastsendmail','invisible','buyercredit','sellercredit','favtimes','sharetimes','profileprogress'),
'field_forum' => array('publishfeed','customshow','customstatus','medals','sightml','groupterms','authstr','groups','attentiongroup'),
'field_home' => array('videophoto','spacename','spacedescription','domain','addsize','addfriend','menunum','theme','spacecss','blockposition','recentnote','spacenote','privacy','feedfriend','acceptemail','magicgift','stickblogs'),
'profile' => array('realname','gender','birthyear','birthmonth','birthday','constellation','zodiac','telephone','mobile','idcardtype','idcard','address','zipcode','nationality','birthprovince','birthcity','resideprovince','residecity','residedist','residecommunity','residesuite','graduateschool','company','education','occupation','position','revenue','affectivestatus','lookingfor','bloodtype','height','weight','alipay','icq','qq','yahoo','msn','taobao','site','bio','interest','field1','field2','field3','field4','field5','field6','field7','field8'),
'verify' => array('verify1', 'verify2', 'verify3', 'verify4', 'verify5', 'verify6', 'verify7'),
);
$profiletable = '';
foreach($tablefields as $table => $fields) {
if(in_array($field, $fields)) {
$profiletable = $table;
break;
}
}
if($profiletable) {
/*$data = array();
if($_G['uid']) {
//$data = DB::fetch_first("SELECT ".implode(', ', $tablefields[$profiletable])." FROM ".DB::table('common_member_'.$profiletable)." WHERE uid='$_G[uid]'");
$data = C::t('common_member_'.$profiletable)->fetch($_G['uid']);
}
if(!$data) {
foreach($tablefields[$profiletable] as $k) {
$data[$k] = '';
}
}
$_G['member'] = array_merge(is_array($_G['member']) ? $_G['member'] : array(), $data);*/
if(is_array($_G['member']) && $_G['member']['uid']) {
space_merge($_G['member'], $profiletable);
} else {
foreach($tablefields[$profiletable] as $k) {
$_G['member'][$k] = '';
}
}
return $_G['member'][$field];
}
return null;
}
/**
* 對字符串或者輸入進行 addslashes 操做
* @param <mix> $string
* @param <int> $force
* @return <mix>
*/
function daddslashes($string, $force = 1) {
if(is_array($string)) {
$keys = array_keys($string);
foreach($keys as $key) {
$val = $string[$key];
unset($string[$key]);
$string[addslashes($key)] = daddslashes($val, $force);
}
} else {
$string = addslashes($string);
}
return $string;
}
/**
* 對字符串進行加密和解密
* @param <string> $string
* @param <string> $operation DECODE 解密 | ENCODE 加密
* @param <string> $key 當爲空的時候,取全局密鑰
* @param <int> $expiry 有效期,單位秒
* @return <string>
*/
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
$ckey_length = 4;
$key = md5($key != '' ? $key : getglobal('authkey'));
$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));
}
}
function fsocketopen($hostname, $port = 80, &$errno, &$errstr, $timeout = 15) {
$fp = '';
if(function_exists('fsockopen')) {
$fp = @fsockopen($hostname, $port, $errno, $errstr, $timeout);
} elseif(function_exists('pfsockopen')) {
$fp = @pfsockopen($hostname, $port, $errno, $errstr, $timeout);
} elseif(function_exists('stream_socket_client')) {
//note php5支持
$fp = @stream_socket_client($hostname.':'.$port, $errno, $errstr, $timeout);
}
return $fp;
}
/**
* 遠程文件文件請求兼容函數
*/
function dfsockopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE, $encodetype = 'URLENCODE', $allowcurl = TRUE, $position = 0, $files = array()) {
require_once libfile('function/filesock');
return _dfsockopen($url, $limit, $post, $cookie, $bysocket, $ip, $timeout, $block, $encodetype, $allowcurl, $position, $files);
}
/**
* HTML轉義字符
* @param $string - 字符串
* @param $flags 參見手冊 htmlspecialchars
* @return 返回轉義好的字符串
*/
function dhtmlspecialchars($string, $flags = null) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = dhtmlspecialchars($val, $flags);
}
} else {
if($flags === null) {
$string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string);
if(strpos($string, '&#') !== false) {
$string = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
}
} else {
if(PHP_VERSION < '5.4.0') {
$string = htmlspecialchars($string, $flags);
} else {
if(strtolower(CHARSET) == 'utf-8') {
$charset = 'UTF-8';
} else {
$charset = 'ISO-8859-1';
}
$string = htmlspecialchars($string, $flags, $charset);
}
}
}
return $string;
}
/**
* 退出程序 同 exit 的區別, 對輸出數據會進行 從新加工和處理
* 一般狀況下,咱們建議使用本函數終止程序, 除非有特別需求
* @param <type> $message
*/
function dexit($message = '') {
echo $message;
output();
exit();
}
/**
* 同 php header函數, 針對 location 跳轉作了特殊處理
* @param <type> $string
* @param <type> $replace
* @param <type> $http_response_code
*/
function dheader($string, $replace = true, $http_response_code = 0) {
//noteX 手機header跳轉的統一修改(IN_MOBILE)
$islocation = substr(strtolower(trim($string)), 0, 8) == 'location';
if(defined('IN_MOBILE') && strpos($string, 'mobile') === false && $islocation) {
if (strpos($string, '?') === false) {
$string = $string.'?mobile='.IN_MOBILE;
} else {
if(strpos($string, '#') === false) {
$string = $string.'&mobile='.IN_MOBILE;
} else {
$str_arr = explode('#', $string);
$str_arr[0] = $str_arr[0].'&mobile='.IN_MOBILE;
$string = implode('#', $str_arr);
}
}
}
$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($islocation) {
exit();
}
}
/**
* 設置cookie
* @param $var - 變量名
* @param $value - 變量值
* @param $life - 生命期
* @param $prefix - 前綴
*/
function dsetcookie($var, $value = '', $life = 0, $prefix = 1, $httponly = false) {
global $_G;
$config = $_G['config']['cookie'];
$_G['cookie'][$var] = $value;
$var = ($prefix ? $config['cookiepre'] : '').$var;
$_COOKIE[$var] = $value;
if($value == '' || $life < 0) {
$value = '';
$life = -1;
}
/*手機瀏覽器設置cookie,強制取消HttpOnly(IN_MOBILE)*/
if(defined('IN_MOBILE')) {
$httponly = false;
}
$life = $life > 0 ? getglobal('timestamp') + $life : ($life < 0 ? getglobal('timestamp') - 31536000 : 0);
$path = $httponly && PHP_VERSION < '5.2.0' ? $config['cookiepath'].'; HttpOnly' : $config['cookiepath'];
$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
if(PHP_VERSION < '5.2.0') {
setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure);
} else {
setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure, $httponly);
}
}
/**
* 獲取cookie
*/
function getcookie($key) {
global $_G;
return isset($_G['cookie'][$key]) ? $_G['cookie'][$key] : '';
}
/**
* 獲取文件擴展名
*/
function fileext($filename) {
return addslashes(strtolower(substr(strrchr($filename, '.'), 1, 10)));
}
//note 規則待調整
function formhash($specialadd = '') {
global $_G;
$hashadd = defined('IN_ADMINCP') ? 'Only For Discuz! Admin Control Panel' : '';
return substr(md5(substr($_G['timestamp'], 0, -7).$_G['username'].$_G['uid'].$_G['authkey'].$hashadd.$specialadd), 8, 8);
}
function checkrobot($useragent = '') {
static $kw_spiders = array('bot', 'crawl', 'spider' ,'slurp', 'sohu-search', 'lycos', 'robozilla');
static $kw_browsers = array('msie', 'netscape', 'opera', 'konqueror', 'mozilla');
$useragent = strtolower(empty($useragent) ? $_SERVER['HTTP_USER_AGENT'] : $useragent);
if(strpos($useragent, 'http://') === false && dstrpos($useragent, $kw_browsers)) return false;
if(dstrpos($useragent, $kw_spiders)) return true;
return false;
}
/**
* 檢查是不是以手機瀏覽器進入(IN_MOBILE)
*/
function checkmobile() {
global $_G;
$mobile = array();
static $touchbrowser_list =array('iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini',
'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung',
'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser',
'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource',
'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone',
'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop',
'benq', 'haier', '^lct', '320x320', '240x320', '176x220', 'windows phone');
static $wmlbrowser_list = array('cect', 'compal', 'ctl', 'lg', 'nec', 'tcl', 'alcatel', 'ericsson', 'bird', 'daxian', 'dbtel', 'eastcom',
'pantech', 'dopod', 'philips', 'haier', 'konka', 'kejian', 'lenovo', 'benq', 'mot', 'soutec', 'nokia', 'sagem', 'sgh',
'sed', 'capitel', 'panasonic', 'sonyericsson', 'sharp', 'amoi', 'panda', 'zte');
static $pad_list = array('ipad');//note 包含ipad,WebOS HP Touchpad,Samsung Galaxy Pad
$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
//note 判斷是否爲pad瀏覽器
if(dstrpos($useragent, $pad_list)) {
return false;
}
if(($v = dstrpos($useragent, $touchbrowser_list, true))){
$_G['mobile'] = $v;
return '2'; //默認觸屏版
}
//note wml版手機瀏覽器 //isset($_SERVER[HTTP_X_WAP_PROFILE]) or isset($_SERVER[HTTP_PROFILE]) 這兩個屬性暫不使用
if(($v = dstrpos($useragent, $wmlbrowser_list))) {
$_G['mobile'] = $v;
return '3'; //wml版
}
$brower = array('mozilla', 'chrome', 'safari', 'opera', 'm3gate', 'winwap', 'openwave', 'myop');
if(dstrpos($useragent, $brower)) return false;
$_G['mobile'] = 'unknown';
if(isset($_G['mobiletpl'][$_GET['mobile']])) {
return true;
} else {
return false;
}
}
/**
* 字符串方式實現 preg_match("/(s1|s2|s3)/", $string, $match)
* @param string $string 源字符串
* @param array $arr 要查找的字符串 如array('s1', 's2', 's3')
* @param bool $returnvalue 是否返回找到的值
* @return bool
*/
function dstrpos($string, $arr, $returnvalue = false) {
if(empty($string)) return false;
foreach((array)$arr as $v) {
if(strpos($string, $v) !== false) {
$return = $returnvalue ? $v : true;
return $return;
}
}
return false;
}
/**
* 檢查郵箱是否有效
* @param $email 要檢查的郵箱
* @param 返回結果
*/
function isemail($email) {
return strlen($email) > 6 && strlen($email) <= 32 && preg_match("/^([A-Za-z0-9\-_.+]+)@([A-Za-z0-9\-]+[.][A-Za-z0-9\-.]+)$/", $email);
}
/**
* 問題答案加密
* @param $questionid - 問題
* @param $answer - 答案
* @return 返回加密的字串
*/
function quescrypt($questionid, $answer) {
return $questionid > 0 && $answer != '' ? substr(md5($answer.md5($questionid)), 16, 8) : '';
}
/**
* 產生隨機碼
* @param $length - 要多長
* @param $numberic - 數字仍是字符串
* @return 返回字符串
*/
function random($length, $numeric = 0) {
$seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
if($numeric) {
$hash = '';
} else {
$hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
$length--;
}
$max = strlen($seed) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $seed{mt_rand(0, $max)};
}
return $hash;
}
/**
* 判斷一個字符串是否在另外一個字符串中存在
*
* @param string 原始字串 $string
* @param string 查找 $find
* @return boolean
*/
function strexists($string, $find) {
return !(strpos($string, $find) === FALSE);
}
/**
* 獲取頭像
*
* @param int $uid 須要獲取的用戶UID值
* @param string $size 獲取尺寸 'small', 'middle', 'big'
* @param boolean $returnsrc 是否直接返回圖片src
* @param boolean $real 是否返回真實圖片
* @param boolean $static 是否返回真實路徑
* @param string $ucenterurl 強制uc路徑
*/
function avatar($uid, $size = 'middle', $returnsrc = FALSE, $real = FALSE, $static = FALSE, $ucenterurl = '') {
global $_G;
if($_G['setting']['plugins']['func'][HOOKTYPE]['avatar']) {
$_G['hookavatar'] = '';
$param = func_get_args();
hookscript('avatar', 'global', 'funcs', array('param' => $param), 'avatar');
if($_G['hookavatar']) {
return $_G['hookavatar'];
}
}
static $staticavatar;
if($staticavatar === null) {
$staticavatar = $_G['setting']['avatarmethod'];
}
$ucenterurl = empty($ucenterurl) ? $_G['setting']['ucenterurl'] : $ucenterurl;
$size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
$uid = abs(intval($uid));
if(!$staticavatar && !$static) {
return $returnsrc ? $ucenterurl.'/avatar.php?uid='.$uid.'&size='.$size.($real ? '&type=real' : '') : '<img src="'.$ucenterurl.'/avatar.php?uid='.$uid.'&size='.$size.($real ? '&type=real' : '').'" />';
} else {
$uid = sprintf("%09d", $uid);
$dir1 = substr($uid, 0, 3);
$dir2 = substr($uid, 3, 2);
$dir3 = substr($uid, 5, 2);
$file = $ucenterurl.'/data/avatar/'.$dir1.'/'.$dir2.'/'.$dir3.'/'.substr($uid, -2).($real ? '_real' : '').'_avatar_'.$size.'.jpg';
return $returnsrc ? $file : '<img src="'.$file.'" onerror="this.onerror=null;this.src=\''.$ucenterurl.'/images/noavatar_'.$size.'.gif\'" />';
}
}
/**
* 加載語言
* 語言文件統一爲 $lang = array();
* @param $file - 語言文件,可包含路徑如 forum/xxx home/xxx
* @param $langvar - 語言文字索引
* @param $vars - 變量替換數組
* @return 語言文字
*/
function lang($file, $langvar = null, $vars = array(), $default = null) {
global $_G;
$fileinput = $file;
list($path, $file) = explode('/', $file);
if(!$file) {
$file = $path;
$path = '';
}
if(strpos($file, ':') !== false) {
$path = 'plugin';
list($file) = explode(':', $file);
}
if($path != 'plugin') {
$key = $path == '' ? $file : $path.'_'.$file;
if(!isset($_G['lang'][$key])) {
//#start
$_akey = '#file#source/language/'.($path == '' ? '' : $path.'/').'lang_'.$file.'.php';
C::analysisStart($_akey);
//#end
include DISCUZ_ROOT.'./source/language/'.($path == '' ? '' : $path.'/').'lang_'.$file.'.php';
//#start
C::analysisStop($_akey);
//#end
$_G['lang'][$key] = $lang;
}
//noteX 合併手機語言包(IN_MOBILE)
if(defined('IN_MOBILE') && !defined('TPL_DEFAULT')) {
//#start
$_akey = '#file#source/language/mobile/lang_template.php';
C::analysisStart($_akey);
//#end
include DISCUZ_ROOT.'./source/language/mobile/lang_template.php';
//#start
C::analysisStop($_akey);
//#end
$_G['lang'][$key] = array_merge($_G['lang'][$key], $lang);
}
if($file != 'error' && !isset($_G['cache']['pluginlanguage_system'])) {
loadcache('pluginlanguage_system');
}
if(!isset($_G['hooklang'][$fileinput])) {
if(isset($_G['cache']['pluginlanguage_system'][$fileinput]) && is_array($_G['cache']['pluginlanguage_system'][$fileinput])) {
$_G['lang'][$key] = array_merge($_G['lang'][$key], $_G['cache']['pluginlanguage_system'][$fileinput]);
}
$_G['hooklang'][$fileinput] = true;
}
$returnvalue = &$_G['lang'];
} else {
if(empty($_G['config']['plugindeveloper'])) {
loadcache('pluginlanguage_script');
} elseif(!isset($_G['cache']['pluginlanguage_script'][$file]) && preg_match("/^[a-z]+[a-z0-9_]*$/i", $file)) {
if(@include(DISCUZ_ROOT.'./data/plugindata/'.$file.'.lang.php')) {
$_G['cache']['pluginlanguage_script'][$file] = $scriptlang[$file];
} else {
loadcache('pluginlanguage_script');
}
}
$returnvalue = & $_G['cache']['pluginlanguage_script'];
$key = &$file;
}
$return = $langvar !== null ? (isset($returnvalue[$key][$langvar]) ? $returnvalue[$key][$langvar] : null) : $returnvalue[$key];
$return = $return === null ? ($default !== null ? $default : $langvar) : $return;
$searchs = $replaces = array();
if($vars && is_array($vars)) {
foreach($vars as $k => $v) {
$searchs[] = '{'.$k.'}';
$replaces[] = $v;
}
}
if(is_string($return) && strpos($return, '{_G/') !== false) {
preg_match_all('/\{_G\/(.+?)\}/', $return, $gvar);
foreach($gvar[0] as $k => $v) {
$searchs[] = $v;
$replaces[] = getglobal($gvar[1][$k]);
}
}
$return = str_replace($searchs, $replaces, $return);
return $return;
}
/**
* 檢查模板源文件是否更新
* 當編譯文件不存時強制從新編譯
* 當 tplrefresh = 1 時檢查文件
* 當 tplrefresh > 1 時,則根據 tplrefresh 取餘,無餘時則檢查更新
*
*/
function checktplrefresh($maintpl, $subtpl, $timecompare, $templateid, $cachefile, $tpldir, $file) {
static $tplrefresh, $timestamp, $targettplname;
if($tplrefresh === null) {
$tplrefresh = getglobal('config/output/tplrefresh');
$timestamp = getglobal('timestamp');
}
if(empty($timecompare) || $tplrefresh == 1 || ($tplrefresh > 1 && !($timestamp % $tplrefresh))) {
if(empty($timecompare) || @filemtime(DISCUZ_ROOT.$subtpl) > $timecompare) {
require_once DISCUZ_ROOT.'/source/class/class_template.php';
$template = new template();
$template->parse_template($maintpl, $templateid, $tpldir, $file, $cachefile);
//更新頁面和模塊的關聯
if($targettplname === null) {
$targettplname = getglobal('style/tplfile');
if(!empty($targettplname)) {
include_once libfile('function/block');
$targettplname = strtr($targettplname, ':', '_');
update_template_block($targettplname, getglobal('style/tpldirectory'), $template->blocks);
}
$targettplname = true;
}
return TRUE;
}
}
return FALSE;
}
/**
* 解析模板
* @return 返回域名
*/
function template($file, $templateid = 0, $tpldir = '', $gettplfile = 0, $primaltpl='') {
global $_G;
static $_init_style = false;
if($_init_style === false) {
C::app()->_init_style();
$_init_style = true;
}
$oldfile = $file; //原模板
if(strpos($file, ':') !== false) {
$clonefile = '';
list($templateid, $file, $clonefile) = explode(':', $file);
$oldfile = $file;
$file = empty($clonefile) ? $file : $file.'_'.$clonefile;
if($templateid == 'diy') {
$indiy = false; //是否存在DIY
$_G['style']['tpldirectory'] = $tpldir ? $tpldir : (defined('TPLDIR') ? TPLDIR : ''); //模板文件所在的目錄,DIY保存時使用
$_G['style']['prefile'] = ''; //非預覽環境標記預覽文件是否存在
$diypath = DISCUZ_ROOT.'./data/diy/'.$_G['style']['tpldirectory'].'/'; //DIY模板文件目錄
$preend = '_diy_preview'; //預覽文件後綴
$_GET['preview'] = !empty($_GET['preview']) ? $_GET['preview'] : ''; //是否預覽
$curtplname = $oldfile;//當前模板名
$basescript = $_G['mod'] == 'viewthread' && !empty($_G['thread']) ? 'forum' : $_G['basescript']; //帖子查看頁歸到froum中
if(isset($_G['cache']['diytemplatename'.$basescript])) {
$diytemplatename = &$_G['cache']['diytemplatename'.$basescript];//當前應用的DIY文件緩存
} else {
if(!isset($_G['cache']['diytemplatename'])) {
loadcache('diytemplatename');
}
$diytemplatename = &$_G['cache']['diytemplatename'];//全部DIY文件緩存
}
$tplsavemod = 0; //公共DIY頁面標記
//獨立DIY頁面 || 分區或版塊沒有指定模板 && 公共DIY頁面
if(isset($diytemplatename[$file]) && file_exists($diypath.$file.'.htm') && ($tplsavemod = 1) || empty($_G['forum']['styleid']) && ($file = $primaltpl ? $primaltpl : $oldfile) && isset($diytemplatename[$file]) && file_exists($diypath.$file.'.htm')) {
$tpldir = 'data/diy/'.$_G['style']['tpldirectory'].'/'; //文件目錄
!$gettplfile && $_G['style']['tplsavemod'] = $tplsavemod; //獨立DIY頁面標記:1,公共DIY頁面標記:0
$curtplname = $file; //當前模板名
if(isset($_GET['diy']) && $_GET['diy'] == 'yes' || isset($_GET['diy']) && $_GET['preview'] == 'yes') { //DIY模式或預覽模式下作如下判斷
$flag = file_exists($diypath.$file.$preend.'.htm'); //預覽文件是否存在
if($_GET['preview'] == 'yes') { //預覽環境
$file .= $flag ? $preend : ''; //使用預覽模板文件
} else {
$_G['style']['prefile'] = $flag ? 1 : ''; //非預覽環境標記預覽文件是否存在
}
}
$indiy = true;
} else {
$file = $primaltpl ? $primaltpl : $oldfile; //無DIY頁面則使用原模板
}
//根據模板自動刷新開關$tplrefresh 更新DIY模板
$tplrefresh = $_G['config']['output']['tplrefresh'];
//在有DIY生成模板文件時 && 自動刷新開啓 && DIY生成模板文件修改時間 < 原模板修改修改
if($indiy && ($tplrefresh ==1 || ($tplrefresh > 1 && !($_G['timestamp'] % $tplrefresh))) && filemtime($diypath.$file.'.htm') < filemtime(DISCUZ_ROOT.$_G['style']['tpldirectory'].'/'.($primaltpl ? $primaltpl : $oldfile).'.htm')) {
//原模板更改則更新DIY模板,若是更新失敗則刪除DIY模板
if (!updatediytemplate($file, $_G['style']['tpldirectory'])) {
unlink($diypath.$file.'.htm');
$tpldir = '';
}
}
//保存當前模板名
if (!$gettplfile && empty($_G['style']['tplfile'])) {
$_G['style']['tplfile'] = empty($clonefile) ? $curtplname : $oldfile.':'.$clonefile;
}
//是否顯示繼續DIY
$_G['style']['prefile'] = !empty($_GET['preview']) && $_GET['preview'] == 'yes' ? '' : $_G['style']['prefile'];
} else {
$tpldir = './source/plugin/'.$templateid.'/template';
}
}
$file .= !empty($_G['inajax']) && ($file == 'common/header' || $file == 'common/footer') ? '_ajax' : '';
$tpldir = $tpldir ? $tpldir : (defined('TPLDIR') ? TPLDIR : '');
$templateid = $templateid ? $templateid : (defined('TEMPLATEID') ? TEMPLATEID : '');
$filebak = $file;
//noteX 將頁面模板加一層Mobile目錄,用以定位手機模板頁面(IN_MOBILE)
if(defined('IN_MOBILE') && !defined('TPL_DEFAULT') && strpos($file, $_G['mobiletpl'][IN_MOBILE].'/') === false || (isset($_G['forcemobilemessage']) && $_G['forcemobilemessage'])) {
if(IN_MOBILE == 2) {
$oldfile .= !empty($_G['inajax']) && ($oldfile == 'common/header' || $oldfile == 'common/footer') ? '_ajax' : '';
}
$file = $_G['mobiletpl'][IN_MOBILE].'/'.$oldfile;
}
//確保$tpldir有值
if(!$tpldir) {
$tpldir = './template/default';
}
$tplfile = $tpldir.'/'.$file.'.htm';
$file == 'common/header' && defined('CURMODULE') && CURMODULE && $file = 'common/header_'.$_G['basescript'].'_'.CURMODULE;
//noteX 手機模板的判斷(IN_MOBILE)
if(defined('IN_MOBILE') && !defined('TPL_DEFAULT')) {
//首先判斷是不是DIY模板,若是是就刪除可能存在的forumdisplay_1中的數字
if(strpos($tpldir, 'plugin')) {
if(!file_exists(DISCUZ_ROOT.$tpldir.'/'.$file.'.htm') && !file_exists(DISCUZ_ROOT.$tpldir.'/'.$file.'.php')) {
$url = $_SERVER['REQUEST_URI'].(strexists($_SERVER['REQUEST_URI'], '?') ? '&' : '?').'mobile=no';
showmessage('mobile_template_no_found', '', array('url' => $url));
} else {
$mobiletplfile = $tpldir.'/'.$file.'.htm';
}
}
!$mobiletplfile && $mobiletplfile = $file.'.htm';
if(strpos($tpldir, 'plugin') && (file_exists(DISCUZ_ROOT.$mobiletplfile) || file_exists(substr(DISCUZ_ROOT.$mobiletplfile, 0, -4).'.php'))) {
$tplfile = $mobiletplfile;
} elseif(!file_exists(DISCUZ_ROOT.TPLDIR.'/'.$mobiletplfile) && !file_exists(substr(DISCUZ_ROOT.TPLDIR.'/'.$mobiletplfile, 0, -4).'.php')) {
$mobiletplfile = './template/default/'.$mobiletplfile;
if(!file_exists(DISCUZ_ROOT.$mobiletplfile) && !$_G['forcemobilemessage']) {
$tplfile = str_replace($_G['mobiletpl'][IN_MOBILE].'/', '', $tplfile);
$file = str_replace($_G['mobiletpl'][IN_MOBILE].'/', '', $file);
define('TPL_DEFAULT', true);
} else {
$tplfile = $mobiletplfile;
}
} else {
$tplfile = TPLDIR.'/'.$mobiletplfile;
}
}
$cachefile = './data/template/'.(defined('STYLEID') ? STYLEID.'_' : '_').$templateid.'_'.str_replace('/', '_', $file).'.tpl.php';
//非系統模板目錄 && $tplfile模板文件不存在 && .php後綴的模板文件不存在 && //當前模板目錄+原模板文件不存在
if($templateid != 1 && !file_exists(DISCUZ_ROOT.$tplfile) && !file_exists(substr(DISCUZ_ROOT.$tplfile, 0, -4).'.php')
&& !file_exists(DISCUZ_ROOT.($tplfile = $tpldir.$filebak.'.htm'))) {
$tplfile = './template/default/'.$filebak.'.htm';
}
if($gettplfile) {
return $tplfile;
}
checktplrefresh($tplfile, $tplfile, @filemtime(DISCUZ_ROOT.$cachefile), $templateid, $cachefile, $tpldir, $file);
return DISCUZ_ROOT.$cachefile;
}
/**
* 數據簽名
* @param string $str 源數據
* @param int $length 返回值的長度,8-32位之間
* @return string
*/
function dsign($str, $length = 16){
return substr(md5($str.getglobal('config/security/authkey')), 0, ($length ? max(8, $length) : 16));
}
/**
* 對某id進行個性化md5
*/
function modauthkey($id) {
return md5(getglobal('username').getglobal('uid').getglobal('authkey').substr(TIMESTAMP, 0, -7).$id);
}
/**
* 得到當前應用頁面選中的導航id
*/
function getcurrentnav() {
global $_G;
if(!empty($_G['mnid'])) {
return $_G['mnid'];
}
$mnid = '';
$_G['basefilename'] = $_G['basefilename'] == $_G['basescript'] ? $_G['basefilename'] : $_G['basescript'].'.php';
if(isset($_G['setting']['navmns'][$_G['basefilename']])) {
if($_G['basefilename'] == 'home.php' && $_GET['mod'] == 'space' && (empty($_GET['do']) || in_array($_GET['do'], array('follow', 'view')))) {
$_GET['mod'] = 'follow';
}
foreach($_G['setting']['navmns'][$_G['basefilename']] as $navmn) {
if($navmn[0] == array_intersect_assoc($navmn[0], $_GET) || ($navmn[0]['mod'] == 'space' && $_GET['mod'] == 'spacecp' && ($navmn[0]['do'] == $_GET['ac'] || $navmn[0]['do'] == 'album' && $_GET['ac'] == 'upload'))) {
$mnid = $navmn[1];
}
}
}
if(!$mnid && isset($_G['setting']['navdms'])) {
foreach($_G['setting']['navdms'] as $navdm => $navid) {
if(strpos(strtolower($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']), $navdm) !== false && strpos(strtolower($_SERVER['HTTP_HOST']), $navdm) === false) {
$mnid = $navid;
break;
}
}
}
if(!$mnid && isset($_G['setting']['navmn'][$_G['basefilename']])) {
$mnid = $_G['setting']['navmn'][$_G['basefilename']];
}
return $mnid;
}
//讀取UC庫
function loaducenter() {
require_once DISCUZ_ROOT.'./config/config_ucenter.php';
require_once DISCUZ_ROOT.'./uc_client/client.php';
}
/**
* 讀取緩存
* @param $cachenames - 緩存名稱數組或字串
*/
function loadcache($cachenames, $force = false) {
global $_G;
static $loadedcache = array();
$cachenames = is_array($cachenames) ? $cachenames : array($cachenames);
$caches = array();
foreach ($cachenames as $k) {
if(!isset($loadedcache[$k]) || $force) {
$caches[] = $k;
$loadedcache[$k] = true;
}
}
if(!empty($caches)) {
$cachedata = C::t('common_syscache')->fetch_all($caches);
foreach($cachedata as $cname => $data) {
if($cname == 'setting') {
$_G['setting'] = $data;
} elseif($cname == 'usergroup_'.$_G['groupid']) {
$_G['cache'][$cname] = $_G['group'] = $data;
} elseif($cname == 'style_default') {
$_G['cache'][$cname] = $_G['style'] = $data;
} elseif($cname == 'grouplevels') {
$_G['grouplevels'] = $data;
} else {
$_G['cache'][$cname] = $data;
}
}
}
return true;
}
/**
* 格式化時間
* @param $timestamp - 時間戳
* @param $format - dt=日期時間 d=日期 t=時間 u=個性化 其餘=自定義
* @param $timeoffset - 時區
* @return string
*/
function dgmdate($timestamp, $format = 'dt', $timeoffset = '9999', $uformat = '') {
global $_G;
$format == 'u' && !$_G['setting']['dateconvert'] && $format = 'dt';
static $dformat, $tformat, $dtformat, $offset, $lang;
if($dformat === null) {
$dformat = getglobal('setting/dateformat');
$tformat = getglobal('setting/timeformat');
$dtformat = $dformat.' '.$tformat;
$offset = getglobal('member/timeoffset');
$sysoffset = getglobal('setting/timeoffset');
$offset = $offset == 9999 ? ($sysoffset ? $sysoffset : 0) : $offset;
$lang = lang('core', 'date');
}
$timeoffset = $timeoffset == 9999 ? $offset : $timeoffset;
$timestamp += $timeoffset * 3600;
$format = empty($format) || $format == 'dt' ? $dtformat : ($format == 'd' ? $dformat : ($format == 't' ? $tformat : $format));
if($format == 'u') {
$todaytimestamp = TIMESTAMP - (TIMESTAMP + $timeoffset * 3600) % 86400 + $timeoffset * 3600;
$s = gmdate(!$uformat ? $dtformat : $uformat, $timestamp);
$time = TIMESTAMP + $timeoffset * 3600 - $timestamp;
if($timestamp >= $todaytimestamp) {
if($time > 3600) {
$return = intval($time / 3600).' '.$lang['hour'].$lang['before'];
} elseif($time > 1800) {
$return = $lang['half'].$lang['hour'].$lang['before'];
} elseif($time > 60) {
$return = intval($time / 60).' '.$lang['min'].$lang['before'];
} elseif($time > 0) {
$return = $time.' '.$lang['sec'].$lang['before'];
} elseif($time == 0) {
$return = $lang['now'];
} else {
$return = $s;
}
if($time >=0 && !defined('IN_MOBILE')) {
$return = '<span title="'.$s.'">'.$return.'</span>';
}
} elseif(($days = intval(($todaytimestamp - $timestamp) / 86400)) >= 0 && $days < 7) {
if($days == 0) {
$return = $lang['yday'].' '.gmdate($tformat, $timestamp);
} elseif($days == 1) {
$return = $lang['byday'].' '.gmdate($tformat, $timestamp);
} else {
$return = ($days + 1).' '.$lang['day'].$lang['before'];
}
if(!defined('IN_MOBILE')) {
$return = '<span title="'.$s.'">'.$return.'</span>';
}
} else {
$return = $s;
}
return $return;
} else {
return gmdate($format, $timestamp);
}
}
/**
獲得時間戳
*/
function dmktime($date) {
if(strpos($date, '-')) {
$time = explode('-', $date);
return mktime(0, 0, 0, $time[1], $time[2], $time[0]);
}
return 0;
}
/**
* 個性化數字
*/
function dnumber($number) {
return abs($number) > 10000 ? '<span title="'.$number.'">'.intval($number / 10000).lang('core', '10k').'</span>' : $number;
}
/**
* 更新緩存
* @param $cachename - 緩存名稱
* @param $data - 緩存數據
*/
function savecache($cachename, $data) {
C::t('common_syscache')->insert($cachename, $data);
}
/**
* 更新緩存 savecache的別名
* @param $cachename - 緩存名稱
* @param $data - 緩存數據
*/
function save_syscache($cachename, $data) {
savecache($cachename, $data);
}
/**
* Portal模塊
* @param $parameter - 參數集合
*/
function block_get($parameter) {
include_once libfile('function/block');
block_get_batch($parameter);
}
/**
* Portal 模塊顯示
*
* @param $parameter - 參數集合
*/
function block_display($bid) {
include_once libfile('function/block');
block_display_batch($bid);
}
//鏈接字符
function dimplode($array) {
if(!empty($array)) {
$array = array_map('addslashes', $array);
return "'".implode("','", is_array($array) ? $array : array($array))."'";
} else {
return 0;
}
}
/**
* 返回庫文件的全路徑
*
* @param string $libname 庫文件分類及名稱
* @param string $folder 模塊目錄'module','include','class'
* @return string
*
* @example require DISCUZ_ROOT.'./source/function/function_cache.php'
* @example 咱們能夠利用此函數簡寫爲:require libfile('function/cache');
*
*/
function libfile($libname, $folder = '') {
$libpath = '/source/'.$folder;
if(strstr($libname, '/')) {
list($pre, $name) = explode('/', $libname);
$path = "{$libpath}/{$pre}/{$pre}_{$name}";
//return realpath("{$libpath}/{$pre}/{$pre}_{$name}.php");
} else {
$path = "{$libpath}/{$libname}";
//return realpath("{$libpath}/{$libname}.php");
}
return preg_match('/^[\w\d\/_]+$/i', $path) ? realpath(DISCUZ_ROOT.$path.'.php') : false;
}
/**
* 針對uft-8進行特殊處理的strlen
* @param string $str
* @return int
*/
function dstrlen($str) {
if(strtolower(CHARSET) != 'utf-8') {
return strlen($str);
}
$count = 0;
for($i = 0; $i < strlen($str); $i++){
$value = ord($str[$i]);
if($value > 127) {
$count++;
if($value >= 192 && $value <= 223) $i++;
elseif($value >= 224 && $value <= 239) $i = $i + 2;
elseif($value >= 240 && $value <= 247) $i = $i + 3;
}
$count++;
}
return $count;
}
/**
* 根據中文裁減字符串
* @param $string - 字符串
* @param $length - 長度
* @param $doc - 縮略後綴
* @return 返回帶省略號被裁減好的字符串
*/
function cutstr($string, $length, $dot = ' ...') {
if(strlen($string) <= $length) {
return $string;
}
$pre = chr(1);
$end = chr(1);
//保護特殊字符串
$string = str_replace(array('&', '"', '<', '>'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), $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 {
$_length = $length - 1;
for($i = 0; $i < $length; $i++) {
//ASCII 碼值小於等於127時直接累加字符,大於127時一次取兩位累加
//但當只剩一位時且遇到大於127字符時則捨去此字符,避免大於裁減長度
if(ord($string[$i]) <= 127) {
$strcut .= $string[$i];
} else if($i < $_length) {
$strcut .= $string[$i].$string[++$i];
}
}
}
//還原特殊字符串
$strcut = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), array('&', '"', '<', '>'), $strcut);
//修復出現特殊字符串截段的問題
$pos = strrpos($strcut, chr(1));
if($pos !== false) {
$strcut = substr($strcut,0,$pos);
}
return $strcut.$dot;
}
//去掉slassh
function dstripslashes($string) {
if(empty($string)) return $string;
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = dstripslashes($val);
}
} else {
$string = stripslashes($string);
}
return $string;
}
/**
* 論壇 aid url 生成
*/
function aidencode($aid, $type = 0, $tid = 0) {
global $_G;
$s = !$type ? $aid.'|'.substr(md5($aid.md5($_G['config']['security']['authkey']).TIMESTAMP.$_G['uid']), 0, 8).'|'.TIMESTAMP.'|'.$_G['uid'].'|'.$tid : $aid.'|'.md5($aid.md5($_G['config']['security']['authkey']).TIMESTAMP).'|'.TIMESTAMP;
return rawurlencode(base64_encode($s));
}
/**
* 返回論壇縮放附件圖片的地址 url
*/
function getforumimg($aid, $nocache = 0, $w = 140, $h = 140, $type = '') {
global $_G;
$key = dsign($aid.'|'.$w.'|'.$h);
return 'forum.php?mod=image&aid='.$aid.'&size='.$w.'x'.$h.'&key='.rawurlencode($key).($nocache ? '&nocache=yes' : '').($type ? '&type='.$type : '');
}
/**
* 獲取rewrite字符串
* @param string $type 須要獲取的rewite
* @param boolean $returntype true:直接返回href, false:返回a標籤
* @param string $host 可選網站域名
* @return string
*/
function rewriteoutput($type, $returntype, $host) {
global $_G;
$fextra = '';
if($type == 'forum_forumdisplay') {
list(,,, $fid, $page, $extra) = func_get_args();
$r = array(
'{fid}' => empty($_G['setting']['forumkeys'][$fid]) ? $fid : $_G['setting']['forumkeys'][$fid],
'{page}' => $page ? $page : 1,
);
} elseif($type == 'forum_viewthread') {
list(,,, $tid, $page, $prevpage, $extra) = func_get_args();
$r = array(
'{tid}' => $tid,
'{page}' => $page ? $page : 1,
'{prevpage}' => $prevpage && !IS_ROBOT ? $prevpage : 1,
);
} elseif($type == 'home_space') {
list(,,, $uid, $username, $extra) = func_get_args();
$_G['setting']['rewritecompatible'] && $username = rawurlencode($username);
$r = array(
'{user}' => $uid ? 'uid' : 'username',
'{value}' => $uid ? $uid : $username,
);
} elseif($type == 'home_blog') {
list(,,, $uid, $blogid, $extra) = func_get_args();
$r = array(
'{uid}' => $uid,
'{blogid}' => $blogid,
);
} elseif($type == 'group_group') {
list(,,, $fid, $page, $extra) = func_get_args();
$r = array(
'{fid}' => $fid,
'{page}' => $page ? $page : 1,
);
} elseif($type == 'portal_topic') {
list(,,, $name, $extra) = func_get_args();
$r = array(
'{name}' => $name,
);
} elseif($type == 'portal_article') {
list(,,, $id, $page, $extra) = func_get_args();
$r = array(
'{id}' => $id,
'{page}' => $page ? $page : 1,
);
} elseif($type == 'forum_archiver') {
list(,, $action, $value, $page, $extra) = func_get_args();
$host = '';
$r = array(
'{action}' => $action,
'{value}' => $value,
);
if($page) {
$fextra = '?page='.$page;
}
} elseif($type == 'plugin') {
list(,, $pluginid, $module,, $param, $extra) = func_get_args();
$host = '';
$r = array(
'{pluginid}' => $pluginid,
'{module}' => $module,
);
if($param) {
$fextra = '?'.$param;
}
}
$href = str_replace(array_keys($r), $r, $_G['setting']['rewriterule'][$type]).$fextra;
if(!$returntype) {
return '<a href="'.$host.$href.'"'.(!empty($extra) ? stripslashes($extra) : '').'>';
} else {
return $host.$href;
}
}
/**
* 手機模式下替換全部連接爲mobile=yes形式
* @param $file - 正則匹配到的文件字符串
* @param $file - 要被替換的字符串
* @$replace 替換後字符串
*/
function mobilereplace($file, $replace) {
return helper_mobile::mobilereplace($file, $replace);
}
/**
* 手機的output函數
*/
function mobileoutput() {
helper_mobile::mobileoutput();
}
/**
* 系統輸出
* @return 返回內容
*/
function output() {
global $_G;
//===================================
//判斷寫入頁面緩存
//===================================
//writepagecache();
if(defined('DISCUZ_OUTPUTED')) {
return;
} else {
define('DISCUZ_OUTPUTED', 1);
}
// 更新模塊
if(!empty($_G['blockupdate'])) {
block_updatecache($_G['blockupdate']['bid']);
}
//noteX 手機模式下從新制做頁面輸出(IN_MOBILE)
if(defined('IN_MOBILE')) {
mobileoutput();
}
if(!defined('IN_MOBILE') && !defined('IN_ARCHIVER')) {
$tipsService = Cloud::loadClass('Service_DiscuzTips');
$tipsService->show();
}
$havedomain = implode('', $_G['setting']['domain']['app']);
if($_G['setting']['rewritestatus'] || !empty($havedomain)) {
$content = ob_get_contents();
$content = output_replace($content);
ob_end_clean();
$_G['gzipcompress'] ? ob_start('ob_gzhandler') : ob_start();//note X:待調整
echo $content;
}
//生成靜態文件
if(isset($_G['makehtml'])) {
helper_makehtml::make_html();
}
if($_G['setting']['ftp']['connid']) {
@ftp_close($_G['setting']['ftp']['connid']);
}
$_G['setting']['ftp'] = array();
//debug Module:HTML_CACHE 若是定義了緩存常量,則此處將緩衝區的內容寫入文件。若是爲 index 緩存,則直接寫入 data/index.cache ,若是爲 viewthread 緩存,則根據md5(tid,等參數)取前三位爲目錄加上$tid_$page,作文件名。
//debug $threadcacheinfo, $indexcachefile 爲全局變量
if(defined('CACHE_FILE') && CACHE_FILE && !defined('CACHE_FORBIDDEN') && !defined('IN_MOBILE') && !checkmobile()) {
if(diskfreespace(DISCUZ_ROOT.'./'.$_G['setting']['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);
}
}
if(defined('DISCUZ_DEBUG') && DISCUZ_DEBUG && @include(libfile('function/debug'))) {
function_exists('debugmessage') && debugmessage();
}
}
function output_replace($content) {
global $_G;
if(defined('IN_MODCP') || defined('IN_ADMINCP')) return $content;
if(!empty($_G['setting']['output']['str']['search'])) {
if(empty($_G['setting']['domain']['app']['default'])) {
$_G['setting']['output']['str']['replace'] = str_replace('{CURHOST}', $_G['siteurl'], $_G['setting']['output']['str']['replace']);
}
$content = str_replace($_G['setting']['output']['str']['search'], $_G['setting']['output']['str']['replace'], $content);
}
if(!empty($_G['setting']['output']['preg']['search']) && (empty($_G['setting']['rewriteguest']) || empty($_G['uid']))) {
if(empty($_G['setting']['domain']['app']['default'])) {
$_G['setting']['output']['preg']['search'] = str_replace('\{CURHOST\}', preg_quote($_G['siteurl'], '/'), $_G['setting']['output']['preg']['search']);
$_G['setting']['output']['preg']['replace'] = str_replace('{CURHOST}', $_G['siteurl'], $_G['setting']['output']['preg']['replace']);
}
$content = preg_replace($_G['setting']['output']['preg']['search'], $_G['setting']['output']['preg']['replace'], $content);
}
return $content;
}
/**
* ajax footer使用輸出頁面內容
*/
function output_ajax() {
global $_G;
$s = ob_get_contents();
ob_end_clean();
$s = preg_replace("/([\\x01-\\x08\\x0b-\\x0c\\x0e-\\x1f])+/", ' ', $s);
$s = str_replace(array(chr(0), ']]>'), array(' ', ']]>'), $s);
if(defined('DISCUZ_DEBUG') && DISCUZ_DEBUG && @include(libfile('function/debug'))) {
function_exists('debugmessage') && $s .= debugmessage(1);
}
$havedomain = implode('', $_G['setting']['domain']['app']);
if($_G['setting']['rewritestatus'] || !empty($havedomain)) {
$s = output_replace($s);
}
return $s;
}
/**
* 運行鉤子
*/
function runhooks($scriptextra = '') {
if(!defined('HOOKTYPE')) {
define('HOOKTYPE', !defined('IN_MOBILE') ? 'hookscript' : 'hookscriptmobile');
}
if(defined('CURMODULE')) {
global $_G;
if($_G['setting']['plugins']['func'][HOOKTYPE]['common']) {
hookscript('common', 'global', 'funcs', array(), 'common');
}
hookscript(CURMODULE, $_G['basescript'], 'funcs', array(), '', $scriptextra);
}
}
/**
* 執行插件腳本
*/
function hookscript($script, $hscript, $type = 'funcs', $param = array(), $func = '', $scriptextra = '') {
global $_G;
static $pluginclasses;
if($hscript == 'home') {
if($script == 'space') {
$scriptextra = !$scriptextra ? $_GET['do'] : $scriptextra;
$script = 'space'.(!empty($scriptextra) ? '_'.$scriptextra : '');
} elseif($script == 'spacecp') {
$scriptextra = !$scriptextra ? $_GET['ac'] : $scriptextra;
$script .= !empty($scriptextra) ? '_'.$scriptextra : '';
}
}
if(!isset($_G['setting'][HOOKTYPE][$hscript][$script][$type])) {
return;
}
if(!isset($_G['cache']['plugin'])) {
loadcache('plugin');
}
foreach((array)$_G['setting'][HOOKTYPE][$hscript][$script]['module'] as $identifier => $include) {
if($_G['pluginrunlist'] && !in_array($identifier, $_G['pluginrunlist'])) {
continue;
}
$hooksadminid[$identifier] = !$_G['setting'][HOOKTYPE][$hscript][$script]['adminid'][$identifier] || ($_G['setting'][HOOKTYPE][$hscript][$script]['adminid'][$identifier] && $_G['adminid'] > 0 && $_G['setting']['hookscript'][$hscript][$script]['adminid'][$identifier] >= $_G['adminid']);
if($hooksadminid[$identifier]) {
//#start
$_akey = '#file#source/plugin/'.$include.'.class.php';
C::analysisStart($_akey);
//#end;
@include_once DISCUZ_ROOT.'./source/plugin/'.$include.'.class.php';
//#start
C::analysisStop($_akey);
//#end
}
}
if(@is_array($_G['setting'][HOOKTYPE][$hscript][$script][$type])) {
$_G['inhookscript'] = true;
$funcs = !$func ? $_G['setting'][HOOKTYPE][$hscript][$script][$type] : array($func => $_G['setting'][HOOKTYPE][$hscript][$script][$type][$func]);
foreach($funcs as $hookkey => $hookfuncs) {
foreach($hookfuncs as $hookfunc) {
if($hooksadminid[$hookfunc[0]]) {
$classkey = (HOOKTYPE != 'hookscriptmobile' ? '' : 'mobile').'plugin_'.($hookfunc[0].($hscript != 'global' ? '_'.$hscript : ''));
if(!class_exists($classkey, false)) {
continue;
}
if(!isset($pluginclasses[$classkey])) {
$pluginclasses[$classkey] = new $classkey;
}
if(!method_exists($pluginclasses[$classkey], $hookfunc[1])) {
continue;
}
//#start
$_akey = '#function#'.$classkey.'::'.$hookfunc[1];
C::analysisStart($_akey);
//#end
$return = $pluginclasses[$classkey]->$hookfunc[1]($param);
//#start
C::analysisStop($_akey);
//#end
if(substr($hookkey, -7) == '_extend' && !empty($_G['setting']['pluginhooks'][$hookkey])) {
continue;
}
if(is_array($return)) {
if(!isset($_G['setting']['pluginhooks'][$hookkey]) || is_array($_G['setting']['pluginhooks'][$hookkey])) {
foreach($return as $k => $v) {
$_G['setting']['pluginhooks'][$hookkey][$k] .= $v;
}
} else {
foreach($return as $k => $v) {
$_G['setting']['pluginhooks'][$hookkey][$k] = $v;
}
}
} else {
if(!is_array($_G['setting']['pluginhooks'][$hookkey])) {
$_G['setting']['pluginhooks'][$hookkey] .= $return;
} else {
foreach($_G['setting']['pluginhooks'][$hookkey] as $k => $v) {
$_G['setting']['pluginhooks'][$hookkey][$k] .= $return;
}
}
}
}
}
}
}
$_G['inhookscript'] = false;
}
function hookscriptoutput($tplfile) {
global $_G;
if(!empty($_G['hookscriptoutput'])) {
return;
}
// //note mobiledata
// if(!empty($_GET['mobiledata'])) {
// require_once libfile('class/mobiledata');
// $mobiledata = new mobiledata();
// if($mobiledata->validator()) {
// $mobiledata->outputvariables();
// }
// }
hookscript('global', 'global');
if(defined('CURMODULE')) {
$param = array('template' => $tplfile, 'message' => $_G['hookscriptmessage'], 'values' => $_G['hookscriptvalues']);
hookscript(CURMODULE, $_G['basescript'], 'outputfuncs', $param);
}
$_G['hookscriptoutput'] = true;
}
/**
* 獲取插件模塊
*/
function pluginmodule($pluginid, $type) {
global $_G;
//note 過濾插件ID
$pluginid = $pluginid ? preg_replace("/[^A-Za-z0-9_:]/", '', $pluginid) : '';
if(!isset($_G['cache']['plugin'])) {
loadcache('plugin');
}
list($identifier, $module) = explode(':', $pluginid);
if(!is_array($_G['setting']['plugins'][$type]) || !array_key_exists($pluginid, $_G['setting']['plugins'][$type])) {
showmessage('plugin_nonexistence');
}
if(!empty($_G['setting']['plugins'][$type][$pluginid]['url'])) {
dheader('location: '.$_G['setting']['plugins'][$type][$pluginid]['url']);
}
$directory = $_G['setting']['plugins'][$type][$pluginid]['directory'];
if(empty($identifier) || !preg_match("/^[a-z]+[a-z0-9_]*\/$/i", $directory) || !preg_match("/^[a-z0-9_\-]+$/i", $module)) {
showmessage('undefined_action');
}
if(@!file_exists(DISCUZ_ROOT.($modfile = './source/plugin/'.$directory.$module.'.inc.php'))) {
showmessage('plugin_module_nonexistence', '', array('mod' => $modfile));
}
return DISCUZ_ROOT.$modfile;
}
/**
* 執行積分規則
* @param String $action: 規則action名稱
* @param Integer $uid: 操做用戶
* @param array $extrasql: common_member_count的額外操做字段數組格式爲 array('extcredits1' => '1')
* @param String $needle: 防重字符串
* @param Integer $coef: 積分放大倍數
* @param Integer $update: 是否執行更新操做
* @param Integer $fid: 版塊ID
* @return 返回積分策略
*/
function updatecreditbyaction($action, $uid = 0, $extrasql = array(), $needle = '', $coef = 1, $update = 1, $fid = 0) {
//include_once libfile('class/credit');
$credit = credit::instance();
if($extrasql) {
$credit->extrasql = $extrasql;
}
return $credit->execrule($action, $uid, $needle, $coef, $update, $fid);
}
/**
* 檢查積分下限
* @param string $action: 策略動做Action或者須要檢測的操做積分值使如extcredits1積分進行減1操做檢測array('extcredits1' => -1)
* @param Integer $uid: 用戶UID
* @param Integer $coef: 積分放大倍數/負數爲減分操做
* @param Integer $returnonly: 只要返回結果,不用中斷程序運行
*/
function checklowerlimit($action, $uid = 0, $coef = 1, $fid = 0, $returnonly = 0) {
require_once libfile('function/credit');
return _checklowerlimit($action, $uid, $coef, $fid, $returnonly);
}
/**
* 批量執行某一條策略規則
* @param String $action: 規則action名稱
* @param Integer $uids: 操做用戶能夠爲單個uid或uid數組
* @param array $extrasql: common_member_count的額外操做字段數組格式爲 array('extcredits1' => '1')
* @param Integer $coef: 積分放大倍數,當爲負數時爲反轉操做
* @param Integer $fid: 版塊ID
*/
function batchupdatecredit($action, $uids = 0, $extrasql = array(), $coef = 1, $fid = 0) {
$credit = & credit::instance();
if($extrasql) {
$credit->extrasql = $extrasql;
}
return $credit->updatecreditbyrule($action, $uids, $coef, $fid);
}
/**
* 添加積分
* @param Integer $uids: 用戶uid或者uid數組
* @param String $dataarr: member count相關操做數組,例: array('threads' => 1, 'doings' => -1)
* @param Boolean $checkgroup: 是否檢查用戶組 true or false
* @param String $operation: 操做類型
* @param Integer $relatedid:
* @param String $ruletxt: 積分規則文本
* @param String $customtitle: 自定義積分記錄標題
* @param String $custommemo: 自定義積分記錄說明
*/
function updatemembercount($uids, $dataarr = array(), $checkgroup = true, $operation = '', $relatedid = 0, $ruletxt = '', $customtitle = '', $custommemo = '') {
if(!empty($uids) && (is_array($dataarr) && $dataarr)) {
require_once libfile('function/credit');
return _updatemembercount($uids, $dataarr, $checkgroup, $operation, $relatedid, $ruletxt, $customtitle, $custommemo);
}
return true;
}
/**
* 校驗用戶組
* @param $uid
*/
function checkusergroup($uid = 0) {
$credit = & credit::instance();
$credit->checkusergroup($uid);
}
function checkformulasyntax($formula, $operators, $tokens) {
$var = implode('|', $tokens);
$operator = implode('', $operators);
$operator = str_replace(
array('+', '-', '*', '/', '(', ')', '{', '}', '\''),
array('\+', '\-', '\*', '\/', '\(', '\)', '\{', '\}', '\\\''),
$operator
);
if(!empty($formula)) {
if(!preg_match("/^([$operator\.\d\(\)]|(($var)([$operator\(\)]|$)+))+$/", $formula) || !is_null(eval(preg_replace("/($var)/", "\$\\1", $formula).';'))){
return false;
}
}
return true;
}
//檢驗積分公式語法
function checkformulacredits($formula) {
return checkformulasyntax(
$formula,
array('+', '-', '*', '/', ' '),
array('extcredits[1-8]', 'digestposts', 'posts', 'threads', 'oltime', 'friends', 'doings', 'polls', 'blogs', 'albums', 'sharings')
);
}
//臨時調試通用
function debug($var = null, $vardump = false) {
echo '<pre>';
$vardump = empty($var) ? true : $vardump;
if($vardump) {
var_dump($var);
} else {
print_r($var);
}
exit();
}
/**
* 調試信息
*/
function debuginfo() {
global $_G;
if(getglobal('setting/debug')) {
$db = & DB::object();
$_G['debuginfo'] = array(
'time' => number_format((microtime(true) - $_G['starttime']), 6),
'queries' => $db->querynum,
'memory' => ucwords(C::memory()->type)
);
if($db->slaveid) {
$_G['debuginfo']['queries'] = 'Total '.$db->querynum.', Slave '.$db->slavequery;
}
return TRUE;
} else {
return FALSE;
}
}
/**
* 隨機取出一個站長推薦的條目
* @param $module 當前模塊
* @return array
*/
function getfocus_rand($module) {
global $_G;
if(empty($_G['setting']['focus']) || !array_key_exists($module, $_G['setting']['focus']) || !empty($_G['cookie']['nofocus_'.$module]) || !$_G['setting']['focus'][$module]) {
return null;
}
loadcache('focus');
if(empty($_G['cache']['focus']['data']) || !is_array($_G['cache']['focus']['data'])) {
return null;
}
$focusid = $_G['setting']['focus'][$module][array_rand($_G['setting']['focus'][$module])];
return $focusid;
}
/**
* 檢查驗證碼正確性
* @param $value 驗證碼變量值
*/
function check_seccode($value, $idhash, $fromjs = 0, $modid = '') {
return helper_seccheck::check_seccode($value, $idhash, $fromjs, $modid);
}
/**
* 檢查驗證問答正確性
* @param $value 驗證問答變量值
*/
function check_secqaa($value, $idhash) {
return helper_seccheck::check_secqaa($value, $idhash);
}
/**
* 檢查是否須要啓用驗證碼、驗證問答
*/
function seccheck($rule, $param = array()) {
return helper_seccheck::seccheck($rule, $param);
}
function make_seccode($seccode = '') {
return helper_seccheck::make_seccode($seccode);
}
function make_secqaa() {
return helper_seccheck::make_secqaa();
}
/**
* 獲取廣告
*/
function adshow($parameter) {
global $_G;
if($_G['inajax'] || $_G['group']['closead']) {
return;
}
if(isset($_G['config']['plugindeveloper']) && $_G['config']['plugindeveloper'] == 2) {
return '<hook>[ad '.$parameter.']</hook>';
}
$params = explode('/', $parameter);
$customid = 0;
$customc = explode('_', $params[0]);
if($customc[0] == 'custom') {
$params[0] = $customc[0];
$customid = $customc[1];
}
$adcontent = null;
if(empty($_G['setting']['advtype']) || !in_array($params[0], $_G['setting']['advtype'])) {
$adcontent = '';
}
if($adcontent === null) {
loadcache('advs');
$adids = array();
$evalcode = &$_G['cache']['advs']['evalcode'][$params[0]];
$parameters = &$_G['cache']['advs']['parameters'][$params[0]];
$codes = &$_G['cache']['advs']['code'][$_G['basescript']][$params[0]];
if(!empty($codes)) {
foreach($codes as $adid => $code) {
$parameter = &$parameters[$adid];
$checked = true;
@eval($evalcode['check']);
if($checked) {
$adids[] = $adid;
}
}
if(!empty($adids)) {
$adcode = $extra = '';
@eval($evalcode['create']);
if(empty($notag)) {
$adcontent = '<div'.($params[1] != '' ? ' class="'.$params[1].'"' : '').$extra.'>'.$adcode.'</div>';
} else {
$adcontent = $adcode;
}
}
}
}
$adfunc = 'ad_'.$params[0];
$_G['setting']['pluginhooks'][$adfunc] = null;
hookscript('ad', 'global', 'funcs', array('params' => $params, 'content' => $adcontent), $adfunc);
if(!$_G['setting']['hookscript']['global']['ad']['funcs'][$adfunc]) {
hookscript('ad', $_G['basescript'], 'funcs', array('params' => $params, 'content' => $adcontent), $adfunc);
}
return $_G['setting']['pluginhooks'][$adfunc] === null ? $adcontent : $_G['setting']['pluginhooks'][$adfunc];
}
/**
* 顯示提示信息
* @param $message - 提示信息,可中文也能夠是 lang_message.php 中的數組 key 值
* @param $url_forward - 提示後跳轉的 url
* @param $values - 提示信息中可替換的變量值 array(key => value ...) 形式
* @param $extraparam - 擴展參數 array(key => value ...) 形式
* 跳轉控制
header header跳轉
location location JS 跳轉,限於 msgtype = 二、3
timeout 定時跳轉
refreshtime 自定義跳轉時間
closetime 自定義關閉時間,限於 msgtype = 2,值爲 true 時爲默認
locationtime 自定義跳轉時間,限於 msgtype = 2,值爲 true 時爲默認
內容控制
alert alert 圖標樣式 right/info/error
return 顯示請返回
redirectmsg 下載時用的提示信息,當跳轉時顯示的信息樣式
0:若是您的瀏覽器沒有自動跳轉,請點擊此連接
1:若是 n 秒後下載仍未開始,請點擊此連接
msgtype 信息樣式
1:非 Ajax
2:Ajax 彈出框
3:Ajax 只顯示信息文本
showmsg 顯示信息文本
showdialog 關閉原彈出框顯示 showDialog 信息,限於 msgtype = 2
login 未登陸時顯示登陸連接
extrajs 擴展 js
striptags 過濾 HTML 標記
Ajax 控制
handle 執行 js 回調函數
showid 控制顯示的對象 ID
*/
function showmessage($message, $url_forward = '', $values = array(), $extraparam = array(), $custom = 0) {
require_once libfile('function/message');
return dshowmessage($message, $url_forward, $values, $extraparam, $custom);
}
/**
* 檢查是否正確提交了表單
* @param $var 須要檢查的變量
* @param $allowget 是否容許GET方式
* @param $seccodecheck 驗證碼檢測是否開啓
* @return 返回是否正確提交了表單
*/
function submitcheck($var, $allowget = 0, $seccodecheck = 0, $secqaacheck = 0) {
if(!getgpc($var)) {
return FALSE;
} else {
return helper_form::submitcheck($var, $allowget, $seccodecheck, $secqaacheck);
}
}
/**
* 分頁
* @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 = FALSE, $simple = FALSE, $jsfunc = FALSE) {
return $num > $perpage ? helper_page::multi($num, $perpage, $curpage, $mpurl, $maxpages, $page, $autogoto, $simple, $jsfunc) : '';
}
/**
* 只有上一頁下一頁的分頁(無需知道數據總數)
* @param $num - 本次所取數據條數
* @param $perpage - 每頁數
* @param $curpage - 當前頁
* @param $mpurl - 跳轉的路徑
* @return 返回分頁代碼
*/
function simplepage($num, $perpage, $curpage, $mpurl) {
return helper_page::simplepage($num, $perpage, $curpage, $mpurl);
}
/**
* 詞語過濾
* @param $message - 詞語過濾文本
* @return 成功返回原始文本,不然提示錯誤或被替換
*/
function censor($message, $modword = NULL, $return = FALSE) {
return helper_form::censor($message, $modword, $return);
}
/**
詞語過濾,檢測是否含有須要審覈的詞
*/
function censormod($message) {
return getglobal('group/ignorecensor') || !$message ? false :helper_form::censormod($message);
}
//獲取用戶附屬表信息,累加到第一個變量$values
function space_merge(&$values, $tablename, $isarchive = false) {
global $_G;
$uid = empty($values['uid'])?$_G['uid']:$values['uid'];//默認當前用戶
$var = "member_{$uid}_{$tablename}";
if($uid) {
if(!isset($_G[$var])) {
//$query = DB::query("SELECT * FROM ".DB::table('common_member_'.$tablename)." WHERE uid='$uid'");
//if($_G[$var] = DB::fetch($query)) {
$ext = $isarchive ? '_archive' : '';
if(($_G[$var] = C::t('common_member_'.$tablename.$ext)->fetch($uid)) !== false) {
if($tablename == 'field_home') {
//隱私設置
$_G['setting']['privacy'] = empty($_G['setting']['privacy']) ? array() : (is_array($_G['setting']['privacy']) ? $_G['setting']['privacy'] : dunserialize($_G['setting']['privacy']));
$_G[$var]['privacy'] = empty($_G[$var]['privacy'])? array() : is_array($_G[$var]['privacy']) ? $_G[$var]['privacy'] : dunserialize($_G[$var]['privacy']);
foreach (array('feed','view','profile') as $pkey) {
if(empty($_G[$var]['privacy'][$pkey]) && !isset($_G[$var]['privacy'][$pkey])) {
$_G[$var]['privacy'][$pkey] = isset($_G['setting']['privacy'][$pkey]) ? $_G['setting']['privacy'][$pkey] : array();//取站點默認設置
}
}
//郵件提醒
$_G[$var]['acceptemail'] = empty($_G[$var]['acceptemail'])? array() : dunserialize($_G[$var]['acceptemail']);
if(empty($_G[$var]['acceptemail'])) {
$_G[$var]['acceptemail'] = empty($_G['setting']['acceptemail'])?array():dunserialize($_G['setting']['acceptemail']);
}
}
} else {
//插入默認數據
//DB::insert('common_member_'.$tablename, array('uid'=>$uid));
C::t('common_member_'.$tablename.$ext)->insert(array('uid'=>$uid));
$_G[$var] = array();
}
}
$values = array_merge($values, $_G[$var]);
}
}
/*
* 運行log記錄
*/
function runlog($file, $message, $halt=0) {
helper_log::runlog($file, $message, $halt);
}
/*
* 處理搜索關鍵字
*/
function stripsearchkey($string) {
$string = trim($string);
$string = str_replace('*', '%', addcslashes($string, '%_'));
//$string = str_replace('_', '\_', $string);
return $string;
}
/*
* 遞歸建立目錄
*/
function dmkdir($dir, $mode = 0777, $makeindex = TRUE){
if(!is_dir($dir)) {
dmkdir(dirname($dir), $mode, $makeindex);
@mkdir($dir, $mode);
if(!empty($makeindex)) {
@touch($dir.'/index.html'); @chmod($dir.'/index.html', 0777);
}
}
return true;
}
/**
* 刷新重定向
*/
function dreferer($default = '') {
global $_G;
$default = empty($default) && $_ENV['curapp'] ? $_ENV['curapp'].'.php' : '';
$_G['referer'] = !empty($_GET['referer']) ? $_GET['referer'] : $_SERVER['HTTP_REFERER'];
$_G['referer'] = substr($_G['referer'], -1) == '?' ? substr($_G['referer'], 0, -1) : $_G['referer'];
if(strpos($_G['referer'], 'member.php?mod=logging')) {
$_G['referer'] = $default;
}
$reurl = parse_url($_G['referer']);
/**
* 判斷host是否相同,不一樣時作進一步的校驗
* 當解析到的host與HTTP_HOST,相同的,不論是不是加www均給予放行
*/
if(!empty($reurl['host']) && !in_array($reurl['host'], array($_SERVER['HTTP_HOST'], 'www.'.$_SERVER['HTTP_HOST'])) && !in_array($_SERVER['HTTP_HOST'], array($reurl['host'], 'www.'.$reurl['host']))) {
//校驗是否在應用域名或版塊域名配置中
if(!in_array($reurl['host'], $_G['setting']['domain']['app']) && !isset($_G['setting']['domain']['list'][$reurl['host']])) {
$domainroot = substr($reurl['host'], strpos($reurl['host'], '.')+1);
//是否爲子域名,若是不爲子域名則跳到index.php
if(empty($_G['setting']['domain']['root']) || (is_array($_G['setting']['domain']['root']) && !in_array($domainroot, $_G['setting']['domain']['root']))) {
$_G['referer'] = $_G['setting']['domain']['defaultindex'] ? $_G['setting']['domain']['defaultindex'] : 'index.php';
}
}
} elseif(empty($reurl['host'])) {
$_G['referer'] = $_G['siteurl'].'./'.$_G['referer'];
}
$_G['referer'] = durlencode($_G['referer']);
return$_G['referer'];
}
/**
* 遠程FTP使用
*/
function ftpcmd($cmd, $arg1 = '') {
static $ftp;
$ftpon = getglobal('setting/ftp/on');
if(!$ftpon) {
return $cmd == 'error' ? -101 : 0;
} elseif($ftp == null) {
$ftp = & discuz_ftp::instance();
}
if(!$ftp->enabled) {
return $ftp->error();
} elseif($ftp->enabled && !$ftp->connectid) {
$ftp->connect();
}
switch ($cmd) {
case 'upload' : return $ftp->upload(getglobal('setting/attachdir').'/'.$arg1, $arg1); break;
case 'delete' : return $ftp->ftp_delete($arg1); break;
case 'close' : return $ftp->ftp_close(); break;
case 'error' : return $ftp->error(); break;
case 'object' : return $ftp; break;
default : return false;
}
}
/**
* 編碼轉換
* @param <string> $str 要轉碼的字符
* @param <string> $in_charset 輸入字符集
* @param <string> $out_charset 輸出字符集(默認當前)
* @param <boolean> $ForceTable 強制使用碼錶(默認不強制)
*
*/
function diconv($str, $in_charset, $out_charset = CHARSET, $ForceTable = FALSE) {
global $_G;
$in_charset = strtoupper($in_charset);
$out_charset = strtoupper($out_charset);
if(empty($str) || $in_charset == $out_charset) {
return $str;
}
$out = '';
if(!$ForceTable) {
if(function_exists('iconv')) {
$out = iconv($in_charset, $out_charset.'//IGNORE', $str);
} elseif(function_exists('mb_convert_encoding')) {
$out = mb_convert_encoding($str, $out_charset, $in_charset);
}
}
if($out == '') {
$chinese = new Chinese($in_charset, $out_charset, true);
$out = $chinese->Convert($str);
}
return $out;
}
function widthauto() {
global $_G;
if($_G['disabledwidthauto']) {
return 0;
}
if(!empty($_G['widthauto'])) {
return $_G['widthauto'] > 0 ? 1 : 0;
}
if($_G['setting']['switchwidthauto'] && !empty($_G['cookie']['widthauto'])) {
return $_G['cookie']['widthauto'] > 0 ? 1 : 0;
} else {
return $_G['setting']['allowwidthauto'] ? 0 : 1;
}
}
/**
* 重建數組
* @param <string> $array 須要反轉的數組
* @return array 原數組與的反轉後的數組
*/
function renum($array) {
$newnums = $nums = array();
foreach ($array as $id => $num) {
$newnums[$num][] = $id;
$nums[$num] = $num;
}
return array($nums, $newnums);
}
/**
* 字節格式化單位
* @param $filesize - 大小(字節)
* @return 返回格式化後的文本
*/
function sizecount($size) {
if($size >= 1073741824) {
$size = round($size / 1073741824 * 100) / 100 . ' GB';
} elseif($size >= 1048576) {
$size = round($size / 1048576 * 100) / 100 . ' MB';
} elseif($size >= 1024) {
$size = round($size / 1024 * 100) / 100 . ' KB';
} else {
$size = intval($size) . ' Bytes';
}
return $size;
}
function swapclass($class1, $class2 = '') {
static $swapc = null;
$swapc = isset($swapc) && $swapc != $class1 ? $class1 : $class2;
return $swapc;
}
/**
* 寫入運行日誌
*/
function writelog($file, $log) {
helper_log::writelog($file, $log);
}
/**
* 取得某標誌位的數值 (0|1)
*
* @param 數值 $status
* @param 位置 $position
* @return 0 | 1
*/
function getstatus($status, $position) {
$t = $status & pow(2, $position - 1) ? 1 : 0;
return $t;
}
/**
* 設置某一bit位的數值 0 or 1
*
* @param int $position 1-16
* @param int $value 0|1
* @param 原始數值 $baseon 0x0000-0xffff
* @return int
*/
function setstatus($position, $value, $baseon = null) {
$t = pow(2, $position - 1);
if($value) {
$t = $baseon | $t;
} elseif ($baseon !== null) {
$t = $baseon & ~$t;
} else {
$t = ~$t;
}
return $t & 0xFFFF;
}
/**
* 通知
* @param Integer $touid: 通知給誰
* @param String $type: 通知類型
* @param String $note: 語言key
* @param Array $notevars: 語言變量對應的值
* @param Integer $system: 是否爲系統通知 0:非系統通知; 1:系統通知
*/
function notification_add($touid, $type, $note, $notevars = array(), $system = 0) {
return helper_notification::notification_add($touid, $type, $note, $notevars, $system);
}
/**
* 發送管理通知
* @param $type - 通知類型
*/
function manage_addnotify($type, $from_num = 0, $langvar = array()) {
helper_notification::manage_addnotify($type, $from_num, $langvar);
}
/**
* 發送短消息(兼容提醒)
* @param $toid - 接收方id
* @param $subject - 標題
* @param $message - 內容
* @param $fromid - 發送方id
*/
function sendpm($toid, $subject, $message, $fromid = '', $replypmid = 0, $isusername = 0, $type = 0) {
return helper_pm::sendpm($toid, $subject, $message, $fromid, $replypmid, $isusername, $type);
}
//得到用戶組圖標
function g_icon($groupid, $return = 0) {
global $_G;
if(empty($_G['cache']['usergroups'][$groupid]['icon'])) {
$s = '';
} else {
if(substr($_G['cache']['usergroups'][$groupid]['icon'], 0, 5) == 'http:') {
$s = '<img src="'.$_G['cache']['usergroups'][$groupid]['icon'].'" alt="" class="vm" />';
} else {
$s = '<img src="'.$_G['setting']['attachurl'].'common/'.$_G['cache']['usergroups'][$groupid]['icon'].'" alt="" class="vm" />';
}
}
if($return) {
return $s;
} else {
echo $s;
}
}
//從數據庫中更新DIY模板文件
function updatediytemplate($targettplname = '', $tpldirectory = '') {
$r = false;
//$where = empty($targettplname) ? '' : " WHERE targettplname='$targettplname'";
//$query = DB::query("SELECT * FROM ".DB::table('common_diy_data')."$where");
$alldata = !empty($targettplname) ? array( C::t('common_diy_data')->fetch($targettplname, $tpldirectory)) : C::t('common_diy_data')->range();
require_once libfile('function/portalcp');
//while($value = DB::fetch($query)) {
foreach($alldata as $value) {
$r = save_diy_data($value['tpldirectory'], $value['primaltplname'], $value['targettplname'], dunserialize($value['diycontent']));
}
return $r;
}
//得到用戶惟一串
function space_key($uid, $appid=0) {
global $_G;
//$siteuniqueid = DB::result_first("SELECT svalue FROM ".DB::table('common_setting')." WHERE skey='siteuniqueid'");
return substr(md5($_G['setting']['siteuniqueid'].'|'.$uid.(empty($appid)?'':'|'.$appid)), 8, 16);
}
//note post分表相關函數
/**
*
* 經過tid獲得相應的單一post表名或post表集合
* @param <mix> $tids: 容許傳進單個tid,也能夠是tid集合
* @param $primary: 是否只查主題表 0:遍歷全部表;1:只查主表
* @return 當傳進來的是單一的tid將直接返回表名,不然返回表集合的二維數組例:array('forum_post' => array(tids),'forum_post_1' => array(tids))
* @TODO tid傳進來的是字符串的,返回單個表名,傳進來的是數組的,不論是不是一個數組,返回的仍是數組,保證進出值對應
*/
function getposttablebytid($tids, $primary = 0) {
return table_forum_post::getposttablebytid($tids, $primary);
}
/**
* 獲取論壇帖子表名
* @param <int> $tableid: 分表ID,默認爲:fourm_post表
* @param <boolean> $prefix: 是否默認帶有表前綴
* @return forum_post or forum_post_*
*/
function getposttable($tableid = 0, $prefix = false) {
return table_forum_post::getposttable($tableid, $prefix);
}
/**
* 內存讀寫接口函數
* <code>
* memory('get', 'keyname') === false;//緩存中沒有這個keyname時結果爲true
* </code>
* * @param 命令 $cmd (set|get|rm|check|inc|dec)
* @param 鍵值 $key
* @param 數據 $value 當$cmd=get|rm時,$value即爲$prefix;當$cmd=inc|dec時,$value爲$step,默認爲1
* @param 有效期 $ttl
* @param 鍵值的前綴 $prefix
* @return mix
*
* @example set : 寫入內存 $ret = memory('set', 'test', 'ok')
* @example get : 讀取內存 $data = memory('get', 'test')
* @example rm : 刪除內存 $ret = memory('rm', 'test')
* @example check : 檢查內存功能是否可用 $allow = memory('check')
*/
function memory($cmd, $key='', $value='', $ttl = 0, $prefix = '') {
if($cmd == 'check') {
return C::memory()->enable ? C::memory()->type : '';
} elseif(C::memory()->enable && in_array($cmd, array('set', 'get', 'rm', 'inc', 'dec'))) {
if(defined('DISCUZ_DEBUG') && DISCUZ_DEBUG) {
if(is_array($key)) {
foreach($key as $k) {
C::memory()->debug[$cmd][] = ($cmd == 'get' || $cmd == 'rm' ? $value : '').$prefix.$k;
}
} else {
C::memory()->debug[$cmd][] = ($cmd == 'get' || $cmd == 'rm' ? $value : '').$prefix.$key;
}
}
switch ($cmd) {
case 'set': return C::memory()->set($key, $value, $ttl, $prefix); break;
case 'get': return C::memory()->get($key, $value); break;
case 'rm': return C::memory()->rm($key, $value); break;
case 'inc': return C::memory()->inc($key, $value ? $value : 1); break;
case 'dec': return C::memory()->dec($key, $value ? $value : -1); break;
}
}
return null;
}
/**
* 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);
}
/**
* ip限制訪問
* @param $ip 要檢查的ip地址
* @param - $accesslist 容許訪問的ip地址
* @param 返回結果
*/
function ipbanned($onlineip) {
global $_G;
if($_G['setting']['ipaccess'] && !ipaccess($onlineip, $_G['setting']['ipaccess'])) {
return TRUE;
}
loadcache('ipbanned');
if(empty($_G['cache']['ipbanned'])) {
return FALSE;
} else {
if($_G['cache']['ipbanned']['expiration'] < TIMESTAMP) {
require_once libfile('function/cache');
updatecache('ipbanned');
}
return preg_match("/^(".$_G['cache']['ipbanned']['regexp'].")$/", $onlineip);
}
}
//得到統計數
function getcount($tablename, $condition) {
if(empty($condition)) {
$where = '1';
} elseif(is_array($condition)) {
$where = DB::implode_field_value($condition, ' AND ');
} else {
$where = $condition;
}
$ret = intval(DB::result_first("SELECT COUNT(*) AS num FROM ".DB::table($tablename)." WHERE $where"));
return $ret;
}
/**
* 系統級消息
*/
function sysmessage($message) {
//require libfile('function/sysmessage');
//show_system_message($message);
helper_sysmessage::show($message);
}
/**
* 論壇權限
* @param $permstr - 權限信息
* @param $groupid - 只判斷用戶組
* @return 0 無權限 > 0 有權限
*/
function forumperm($permstr, $groupid = 0) {
global $_G;
$groupidarray = array($_G['groupid']);
if($groupid) {
return preg_match("/(^|\t)(".$groupid.")(\t|$)/", $permstr);
}
foreach(explode("\t", $_G['member']['extgroupids']) as $extgroupid) {
if($extgroupid = intval(trim($extgroupid))) {
$groupidarray[] = $extgroupid;
}
}
if($_G['setting']['verify']['enabled']) {
getuserprofile('verify1');
foreach($_G['setting']['verify'] as $vid => $verify) {
if($verify['available'] && $_G['member']['verify'.$vid] == 1) {
$groupidarray[] = 'v'.$vid;
}
}
}
return preg_match("/(^|\t)(".implode('|', $groupidarray).")(\t|$)/", $permstr);
}
//檢查權限
function checkperm($perm) {
global $_G;
return defined('IN_ADMINCP') ? true : (empty($_G['group'][$perm])?'':$_G['group'][$perm]);
}
/**
* 時間段設置檢測
* @param $periods - 那種時間段 $settings[$periods] $settings['postbanperiods'] $settings['postmodperiods']
* @param $showmessage - 是否提示信息
* @return 返回檢查結果
*/
function periodscheck($periods, $showmessage = 1) {
global $_G;
if(($periods == 'postmodperiods' || $periods == 'postbanperiods') && ($_G['setting']['postignorearea'] || $_G['setting']['postignoreip'])) {
if($_G['setting']['postignoreip']) {
foreach(explode("\n", $_G['setting']['postignoreip']) as $ctrlip) {
if(preg_match("/^(".preg_quote(($ctrlip = trim($ctrlip)), '/').")/", $_G['clientip'])) {
return false;
break;
}
}
}
if($_G['setting']['postignorearea']) {
$location = $whitearea = '';
require_once libfile('function/misc');
$location = trim(convertip($_G['clientip'], "./"));
if($location) {
$whitearea = preg_quote(trim($_G['setting']['postignorearea']), '/');
$whitearea = str_replace(array("\\*"), array('.*'), $whitearea);
$whitearea = '.*'.$whitearea.'.*';
$whitearea = '/^('.str_replace(array("\r\n", ' '), array('.*|.*', ''), $whitearea).')$/i';
if(@preg_match($whitearea, $location)) {
return false;
}
}
}
}
if(!$_G['group']['disableperiodctrl'] && $_G['setting'][$periods]) {
$now = dgmdate(TIMESTAMP, 'G.i', $_G['setting']['timeoffset']);
foreach(explode("\r\n", str_replace(':', '.', $_G['setting'][$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", ', ', $_G['setting'][$periods]);
if($showmessage) {
showmessage('period_nopermission', NULL, array('banperiods' => $banperiods), array('login' => 1));
} else {
return TRUE;
}
}
}
}
return FALSE;
}
//新用戶發言
function cknewuser($return=0) {
global $_G;
$result = true;
if(!$_G['uid']) return true;
//不受防灌水限制
if(checkperm('disablepostctrl')) {
return $result;
}
$ckuser = $_G['member'];
//見習時間
if($_G['setting']['newbiespan'] && $_G['timestamp']-$ckuser['regdate']<$_G['setting']['newbiespan']*60) {
if(empty($return)) showmessage('no_privilege_newbiespan', '', array('newbiespan' => $_G['setting']['newbiespan']), array());
$result = false;
}
//須要上傳頭像
if($_G['setting']['need_avatar'] && empty($ckuser['avatarstatus'])) {
if(empty($return)) showmessage('no_privilege_avatar', '', array(), array());
$result = false;
}
//強制新用戶激活郵箱
if($_G['setting']['need_email'] && empty($ckuser['emailstatus'])) {
if(empty($return)) showmessage('no_privilege_email', '', array(), array());
$result = false;
}
//強制新用戶好友個數
if($_G['setting']['need_friendnum']) {
space_merge($ckuser, 'count');
if($ckuser['friends'] < $_G['setting']['need_friendnum']) {
if(empty($return)) showmessage('no_privilege_friendnum', '', array('friendnum' => $_G['setting']['need_friendnum']), array());
$result = false;
}
}
return $result;
}
function manyoulog($logtype, $uids, $action, $fid = '') {
helper_manyou::manyoulog($logtype, $uids, $action, $fid);
}
/**
* 用戶操做日誌
* @param int $uid 用戶ID
* @param string $action 操做類型 tid=thread pid=post blogid=blog picid=picture doid=doing sid=share aid=article uid_cid/blogid_cid/sid_cid/picid_cid/aid_cid/topicid_cid=comment
* @return bool
*/
function useractionlog($uid, $action) {
return helper_log::useractionlog($uid, $action);
}
/**
* 獲得用戶操做的代碼或表明字符,參數爲數字返回字符串,參數爲字符串返回數字
* @param string/int $var
* @return int/string 注意:若是失敗返回false,請使用===判斷,由於代碼0表明tid
*/
function getuseraction($var) {
return helper_log::getuseraction($var);
}
/**
* 獲取個人中心中展現的應用
*/
function getuserapp($panel = 0) {
return helper_manyou::getuserapp($panel);
}
/**
* 獲取manyou應用本地圖標路徑
* @param <type> $appid
*/
function getmyappiconpath($appid, $iconstatus=0) {
return helper_manyou::getmyappiconpath($appid, $iconstatus);
}
//獲取超時時間
function getexpiration() {
global $_G;
$date = getdate($_G['timestamp']);
return mktime(0, 0, 0, $date['mon'], $date['mday'], $date['year']) + 86400;
}
function return_bytes($val) {
$val = trim($val);
$last = strtolower($val{strlen($val)-1});
switch($last) {
case 'g': $val *= 1024;
case 'm': $val *= 1024;
case 'k': $val *= 1024;
}
return $val;
}
function iswhitelist($host) {
global $_G;
static $iswhitelist = array();
if(isset($iswhitelist[$host])) {
return $iswhitelist[$host];
}
$hostlen = strlen($host);
$iswhitelist[$host] = false;
if(!$_G['cache']['domainwhitelist']) {
loadcache('domainwhitelist');
}
if(is_array($_G['cache']['domainwhitelist'])) foreach($_G['cache']['domainwhitelist'] as $val) {
$domainlen = strlen($val);
if($domainlen > $hostlen) {
continue;
}
if(substr($host, -$domainlen) == $val) {
$iswhitelist[$host] = true;
break;
}
}
if($iswhitelist[$host] == false) {
$iswhitelist[$host] = $host == $_SERVER['HTTP_HOST'];
}
return $iswhitelist[$host];
}
/**
* 經過 AID 獲取附件表名
* @param <int> $aid
*/
function getattachtablebyaid($aid) {
// $tableid = DB::result_first("SELECT tableid FROM ".DB::table('forum_attachment')." WHERE aid='$aid'");
$attach = C::t('forum_attachment')->fetch($aid);
$tableid = $attach['tableid'];
return 'forum_attachment_'.($tableid >= 0 && $tableid < 10 ? intval($tableid) : 'unused');
}
/**
* 返回指定 TID 所對應的附件表編號
* @param <int> $tid
*/
function getattachtableid($tid) {
$tid = (string)$tid;
return intval($tid{strlen($tid)-1});
}
/**
* 經過 TID 獲取附件表名
* @param <int> $tid
*/
function getattachtablebytid($tid) {
return 'forum_attachment_'.getattachtableid($tid);
}
/**
* 經過 PID 獲取附件表名
* @param <int> $pid
*/
function getattachtablebypid($pid) {
$tableid = DB::result_first("SELECT tableid FROM ".DB::table('forum_attachment')." WHERE pid='$pid' LIMIT 1");
return 'forum_attachment_'.($tableid >= 0 && $tableid < 10 ? intval($tableid) : 'unused');
}
/**
* 添加一個新的附件索引記錄,並返回新附件 ID
* @param <int> $uid
*/
function getattachnewaid($uid = 0) {
global $_G;
$uid = !$uid ? $_G['uid'] : $uid;
// return DB::insert('forum_attachment', array('tid' => 0, 'pid' => 0, 'uid' => $uid, 'tableid' => 127), true);
return C::t('forum_attachment')->insert(array('tid' => 0, 'pid' => 0, 'uid' => $uid, 'tableid' => 127), true);
}
/**
* 獲取 SEO設置
* @param string $page 調用哪一個頁面的
* @param array $data 可替換數據
* @return array('seotitle', 'seodescription', 'seokeywords')
*/
function get_seosetting($page, $data = array(), $defset = array()) {
return helper_seo::get_seosetting($page, $data, $defset);
}
/**
*
* 生成縮略圖文件名
* @param String $fileStr: 原文件名,容許附帶路徑
* @param String $extend: 新文件名後綴
* @param Boolean $holdOldExt: 是否保留原擴展名
* @return 返加新的後綴文件名
*/
function getimgthumbname($fileStr, $extend='.thumb.jpg', $holdOldExt=true) {
if(empty($fileStr)) {
return '';
}
//去掉原擴展名
if(!$holdOldExt) {
$fileStr = substr($fileStr, 0, strrpos($fileStr, '.'));
}
$extend = strstr($extend, '.') ? $extend : '.'.$extend;
return $fileStr.$extend;
}
/**
* 更新數據的審覈狀態
* @param <string> $idtype 數據類型 tid=thread pid=post blogid=blog picid=picture doid=doing sid=share aid=article uid_cid/blogid_cid/sid_cid/picid_cid/aid_cid/topicid_cid=comment
* @param <array/int> $ids ID 數組、ID 值
* @param <int> $status 狀態 0=加入審覈(默認) 1=忽略審覈 2=審覈經過
*/
function updatemoderate($idtype, $ids, $status = 0) {
helper_form::updatemoderate($idtype, $ids, $status);
}
/**
* 顯示漫遊應用公告
*/
function userappprompt() {
global $_G;
if($_G['setting']['my_app_status'] && $_G['setting']['my_openappprompt'] && empty($_G['cookie']['userappprompt'])) {
$sid = $_G['setting']['my_siteid'];
$ts = $_G['timestamp'];
$key = md5($sid.$ts.$_G['setting']['my_sitekey']);
$uchId = $_G['uid'] ? $_G['uid'] : 0;
echo '<script type="text/javascript" src="http://notice.uchome.manyou.com/notice/userNotice?sId='.$sid.'&ts='.$ts.'&key='.$key.'&uchId='.$uchId.'" charset="UTF-8"></script>';
}
}
/**
* 安全的 intval, 能夠支持 int(10) unsigned
* 支持最大整數 0xFFFFFFFF 4294967295
* @param mixed $int string|int|array
* @return mixed
*/
function dintval($int, $allowarray = false) {
$ret = intval($int);
if($int == $ret || !$allowarray && is_array($int)) return $ret;
if($allowarray && is_array($int)) {
foreach($int as &$v) {
$v = dintval($v, true);
}
return $int;
} elseif($int <= 0xffffffff) {
$l = strlen($int);
$m = substr($int, 0, 1) == '-' ? 1 : 0;
if(($l - $m) === strspn($int,'0987654321', $m)) {
return $int;
}
}
return $ret;
}
function makeSearchSignUrl() {
return getglobal('setting/my_search_data/status') ? helper_manyou::makeSearchSignUrl() : array();
}
/**
* 獲取批定類型的關聯鏈接
*
* @param string $extent 內容所需關聯連接範圍 article, forum, group, blog
* @return string 有效的關聯連接
*/
function get_related_link($extent) {
return helper_seo::get_related_link($extent);
}
/**
* 在給定內容中加入關聯鏈接
*
* @param string $content 須要加入關聯連接的內容
* @param string $extent 內容所需關聯連接範圍 article, forum, group, blog
* @return string 變動後的內容
*/
function parse_related_link($content, $extent) {
return helper_seo::parse_related_link($content, $extent);
}
function check_diy_perm($topic = array(), $flag = '') {
static $ret;
if(!isset($ret)) {
global $_G;
$common = !empty($_G['style']['tplfile']) || $_GET['inajax'];
$blockallow = getstatus($_G['member']['allowadmincp'], 4) || getstatus($_G['member']['allowadmincp'], 5) || getstatus($_G['member']['allowadmincp'], 6);
$ret['data'] = $common && $blockallow;
$ret['layout'] = $common && ($_G['group']['allowdiy'] || (
CURMODULE === 'topic' && ($_G['group']['allowmanagetopic'] || $_G['group']['allowaddtopic'] && $topic && $topic['uid'] == $_G['uid'])
));
}
return empty($flag) ? $ret['data'] || $ret['layout'] : $ret[$flag];
}
function strhash($string, $operation = 'DECODE', $key = '') {
$key = md5($key != '' ? $key : getglobal('authkey'));
if($operation == 'DECODE') {
$hashcode = gzuncompress(base64_decode(($string)));
$string = substr($hashcode, 0, -16);
$hash = substr($hashcode, -16);
unset($hashcode);
}
$vkey = substr(md5($string.substr($key, 0, 16)), 4, 8).substr(md5($string.substr($key, 16, 16)), 18, 8);
if($operation == 'DECODE') {
return $hash == $vkey ? $string : '';
}
return base64_encode(gzcompress($string.$vkey));
}
function dunserialize($data) {
if(($ret = unserialize($data)) === false) {
$ret = unserialize(stripslashes($data));
}
return $ret;
}
function browserversion($type) {
static $return = array();
static $types = array('ie' => 'msie', 'firefox' => '', 'chrome' => '', 'opera' => '', 'safari' => '', 'mozilla' => '', 'webkit' => '', 'maxthon' => '', 'qq' => 'qqbrowser');
if(!$return) {
$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
$other = 1;
foreach($types as $i => $v) {
$v = $v ? $v : $i;
if(strpos($useragent, $v) !== false) {
preg_match('/'.$v.'(\/|\s)([\d\.]+)/i', $useragent, $matches);
$ver = $matches[2];
$other = $ver !== 0 && $v != 'mozilla' ? 0 : $other;
} else {
$ver = 0;
}
$return[$i] = $ver;
}
$return['other'] = $other;
}
return $return[$type];
}
function currentlang() {
$charset = strtoupper(CHARSET);
if($charset == 'GBK') {
return 'SC_GBK';
} elseif($charset == 'BIG5') {
return 'TC_BIG5';
} elseif($charset == 'UTF-8') {
global $_G;
if($_G['config']['output']['language'] == 'zh_cn') {
return 'SC_UTF8';
} elseif ($_G['config']['output']['language'] == 'zh_tw') {
return 'TC_UTF8';
}
} else {
return '';
}
}
/*
* 儘可能不要在此文件中添加全局函數
* 請在source/class/helper/目錄下建立相應的靜態函數集類文件
* 類的靜態方法能夠在產品中全部地方使用,使用方法相似:helper_form::submitcheck()
*
*/
?>