PageRenderTime 78ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 1ms

/source/function/function_core.php

https://github.com/kuaileshike/upload
PHP | 2018 lines | 1784 code | 228 blank | 6 comment | 579 complexity | c5a6f2be1bdebf27af923fee23df76bd MD5 | raw file
  1. <?php
  2. /**
  3. * [Discuz!] (C)2001-2099 Comsenz Inc.
  4. * This is NOT a freeware, use is subject to license terms
  5. *
  6. * $Id: function_core.php 31961 2012-10-26 06:32:42Z monkey $
  7. */
  8. if(!defined('IN_DISCUZ')) {
  9. exit('Access Denied');
  10. }
  11. define('DISCUZ_CORE_FUNCTION', true);
  12. function system_error($message, $show = true, $save = true, $halt = true) {
  13. discuz_error::system_error($message, $show, $save, $halt);
  14. }
  15. function updatesession() {
  16. return C::app()->session->updatesession();
  17. }
  18. function setglobal($key , $value, $group = null) {
  19. global $_G;
  20. $key = explode('/', $group === null ? $key : $group.'/'.$key);
  21. $p = &$_G;
  22. foreach ($key as $k) {
  23. if(!isset($p[$k]) || !is_array($p[$k])) {
  24. $p[$k] = array();
  25. }
  26. $p = &$p[$k];
  27. }
  28. $p = $value;
  29. return true;
  30. }
  31. function getglobal($key, $group = null) {
  32. global $_G;
  33. $key = explode('/', $group === null ? $key : $group.'/'.$key);
  34. $v = &$_G;
  35. foreach ($key as $k) {
  36. if (!isset($v[$k])) {
  37. return null;
  38. }
  39. $v = &$v[$k];
  40. }
  41. return $v;
  42. }
  43. function getgpc($k, $type='GP') {
  44. $type = strtoupper($type);
  45. switch($type) {
  46. case 'G': $var = &$_GET; break;
  47. case 'P': $var = &$_POST; break;
  48. case 'C': $var = &$_COOKIE; break;
  49. default:
  50. if(isset($_GET[$k])) {
  51. $var = &$_GET;
  52. } else {
  53. $var = &$_POST;
  54. }
  55. break;
  56. }
  57. return isset($var[$k]) ? $var[$k] : NULL;
  58. }
  59. function getuserbyuid($uid, $fetch_archive = 0) {
  60. static $users = array();
  61. if(empty($users[$uid])) {
  62. $users[$uid] = C::t('common_member'.($fetch_archive === 2 ? '_archive' : ''))->fetch($uid);
  63. if($fetch_archive === 1 && empty($users[$uid])) {
  64. $users[$uid] = C::t('common_member_archive')->fetch($uid);
  65. }
  66. }
  67. if(!isset($users[$uid]['self']) && $uid == getglobal('uid') && getglobal('uid')) {
  68. $users[$uid]['self'] = 1;
  69. }
  70. return $users[$uid];
  71. }
  72. function getuserprofile($field) {
  73. global $_G;
  74. if(isset($_G['member'][$field])) {
  75. return $_G['member'][$field];
  76. }
  77. static $tablefields = array(
  78. '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'),
  79. 'status' => array('regip','lastip','lastvisit','lastactivity','lastpost','lastsendmail','invisible','buyercredit','sellercredit','favtimes','sharetimes','profileprogress'),
  80. 'field_forum' => array('publishfeed','customshow','customstatus','medals','sightml','groupterms','authstr','groups','attentiongroup'),
  81. 'field_home' => array('videophoto','spacename','spacedescription','domain','addsize','addfriend','menunum','theme','spacecss','blockposition','recentnote','spacenote','privacy','feedfriend','acceptemail','magicgift','stickblogs'),
  82. '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'),
  83. 'verify' => array('verify1', 'verify2', 'verify3', 'verify4', 'verify5', 'verify6', 'verify7'),
  84. );
  85. $profiletable = '';
  86. foreach($tablefields as $table => $fields) {
  87. if(in_array($field, $fields)) {
  88. $profiletable = $table;
  89. break;
  90. }
  91. }
  92. if($profiletable) {
  93. if(is_array($_G['member']) && $_G['member']['uid']) {
  94. space_merge($_G['member'], $profiletable);
  95. } else {
  96. foreach($tablefields[$profiletable] as $k) {
  97. $_G['member'][$k] = '';
  98. }
  99. }
  100. return $_G['member'][$field];
  101. }
  102. return null;
  103. }
  104. function daddslashes($string, $force = 1) {
  105. if(is_array($string)) {
  106. $keys = array_keys($string);
  107. foreach($keys as $key) {
  108. $val = $string[$key];
  109. unset($string[$key]);
  110. $string[addslashes($key)] = daddslashes($val, $force);
  111. }
  112. } else {
  113. $string = addslashes($string);
  114. }
  115. return $string;
  116. }
  117. function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
  118. $ckey_length = 4;
  119. $key = md5($key != '' ? $key : getglobal('authkey'));
  120. $keya = md5(substr($key, 0, 16));
  121. $keyb = md5(substr($key, 16, 16));
  122. $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
  123. $cryptkey = $keya.md5($keya.$keyc);
  124. $key_length = strlen($cryptkey);
  125. $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
  126. $string_length = strlen($string);
  127. $result = '';
  128. $box = range(0, 255);
  129. $rndkey = array();
  130. for($i = 0; $i <= 255; $i++) {
  131. $rndkey[$i] = ord($cryptkey[$i % $key_length]);
  132. }
  133. for($j = $i = 0; $i < 256; $i++) {
  134. $j = ($j + $box[$i] + $rndkey[$i]) % 256;
  135. $tmp = $box[$i];
  136. $box[$i] = $box[$j];
  137. $box[$j] = $tmp;
  138. }
  139. for($a = $j = $i = 0; $i < $string_length; $i++) {
  140. $a = ($a + 1) % 256;
  141. $j = ($j + $box[$a]) % 256;
  142. $tmp = $box[$a];
  143. $box[$a] = $box[$j];
  144. $box[$j] = $tmp;
  145. $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
  146. }
  147. if($operation == 'DECODE') {
  148. if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
  149. return substr($result, 26);
  150. } else {
  151. return '';
  152. }
  153. } else {
  154. return $keyc.str_replace('=', '', base64_encode($result));
  155. }
  156. }
  157. function fsocketopen($hostname, $port = 80, &$errno, &$errstr, $timeout = 15) {
  158. $fp = '';
  159. if(function_exists('fsockopen')) {
  160. $fp = @fsockopen($hostname, $port, $errno, $errstr, $timeout);
  161. } elseif(function_exists('pfsockopen')) {
  162. $fp = @pfsockopen($hostname, $port, $errno, $errstr, $timeout);
  163. } elseif(function_exists('stream_socket_client')) {
  164. $fp = @stream_socket_client($hostname.':'.$port, $errno, $errstr, $timeout);
  165. }
  166. return $fp;
  167. }
  168. function dfsockopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE, $encodetype = 'URLENCODE', $allowcurl = TRUE, $position = 0) {
  169. require_once libfile('function/filesock');
  170. return _dfsockopen($url, $limit, $post, $cookie, $bysocket, $ip, $timeout, $block, $encodetype, $allowcurl, $position);
  171. }
  172. function dhtmlspecialchars($string, $flags = null) {
  173. if(is_array($string)) {
  174. foreach($string as $key => $val) {
  175. $string[$key] = dhtmlspecialchars($val, $flags);
  176. }
  177. } else {
  178. if($flags === null) {
  179. $string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
  180. if(strpos($string, '&amp;#') !== false) {
  181. $string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
  182. }
  183. } else {
  184. if(PHP_VERSION < '5.4.0') {
  185. $string = htmlspecialchars($string, $flags);
  186. } else {
  187. if(strtolower(CHARSET) == 'utf-8') {
  188. $charset = 'UTF-8';
  189. } else {
  190. $charset = 'ISO-8859-1';
  191. }
  192. $string = htmlspecialchars($string, $flags, $charset);
  193. }
  194. }
  195. }
  196. return $string;
  197. }
  198. function dexit($message = '') {
  199. echo $message;
  200. output();
  201. exit();
  202. }
  203. function dheader($string, $replace = true, $http_response_code = 0) {
  204. $islocation = substr(strtolower(trim($string)), 0, 8) == 'location';
  205. if(defined('IN_MOBILE') && strpos($string, 'mobile') === false && $islocation) {
  206. if (strpos($string, '?') === false) {
  207. $string = $string.'?mobile=yes';
  208. } else {
  209. if(strpos($string, '#') === false) {
  210. $string = $string.'&mobile=yes';
  211. } else {
  212. $str_arr = explode('#', $string);
  213. $str_arr[0] = $str_arr[0].'&mobile=yes';
  214. $string = implode('#', $str_arr);
  215. }
  216. }
  217. }
  218. $string = str_replace(array("\r", "\n"), array('', ''), $string);
  219. if(empty($http_response_code) || PHP_VERSION < '4.3' ) {
  220. @header($string, $replace);
  221. } else {
  222. @header($string, $replace, $http_response_code);
  223. }
  224. if($islocation) {
  225. exit();
  226. }
  227. }
  228. function dsetcookie($var, $value = '', $life = 0, $prefix = 1, $httponly = false) {
  229. global $_G;
  230. $config = $_G['config']['cookie'];
  231. $_G['cookie'][$var] = $value;
  232. $var = ($prefix ? $config['cookiepre'] : '').$var;
  233. $_COOKIE[$var] = $value;
  234. if($value == '' || $life < 0) {
  235. $value = '';
  236. $life = -1;
  237. }
  238. if(defined('IN_MOBILE')) {
  239. $httponly = false;
  240. }
  241. $life = $life > 0 ? getglobal('timestamp') + $life : ($life < 0 ? getglobal('timestamp') - 31536000 : 0);
  242. $path = $httponly && PHP_VERSION < '5.2.0' ? $config['cookiepath'].'; HttpOnly' : $config['cookiepath'];
  243. $secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
  244. if(PHP_VERSION < '5.2.0') {
  245. setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure);
  246. } else {
  247. setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure, $httponly);
  248. }
  249. }
  250. function getcookie($key) {
  251. global $_G;
  252. return isset($_G['cookie'][$key]) ? $_G['cookie'][$key] : '';
  253. }
  254. function fileext($filename) {
  255. return addslashes(strtolower(substr(strrchr($filename, '.'), 1, 10)));
  256. }
  257. function formhash($specialadd = '') {
  258. global $_G;
  259. $hashadd = defined('IN_ADMINCP') ? 'Only For Discuz! Admin Control Panel' : '';
  260. return substr(md5(substr($_G['timestamp'], 0, -7).$_G['username'].$_G['uid'].$_G['authkey'].$hashadd.$specialadd), 8, 8);
  261. }
  262. function checkrobot($useragent = '') {
  263. static $kw_spiders = array('bot', 'crawl', 'spider' ,'slurp', 'sohu-search', 'lycos', 'robozilla');
  264. static $kw_browsers = array('msie', 'netscape', 'opera', 'konqueror', 'mozilla');
  265. $useragent = strtolower(empty($useragent) ? $_SERVER['HTTP_USER_AGENT'] : $useragent);
  266. if(strpos($useragent, 'http://') === false && dstrpos($useragent, $kw_browsers)) return false;
  267. if(dstrpos($useragent, $kw_spiders)) return true;
  268. return false;
  269. }
  270. function checkmobile() {
  271. global $_G;
  272. $mobile = array();
  273. static $mobilebrowser_list =array('iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini',
  274. 'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung',
  275. 'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser',
  276. 'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource',
  277. 'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone',
  278. 'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop',
  279. 'benq', 'haier', '^lct', '320x320', '240x320', '176x220');
  280. $pad_list = array('pad', 'gt-p1000');
  281. $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
  282. if(dstrpos($useragent, $pad_list)) {
  283. return false;
  284. }
  285. if(($v = dstrpos($useragent, $mobilebrowser_list, true))) {
  286. $_G['mobile'] = $v;
  287. return true;
  288. }
  289. $brower = array('mozilla', 'chrome', 'safari', 'opera', 'm3gate', 'winwap', 'openwave', 'myop');
  290. if(dstrpos($useragent, $brower)) return false;
  291. $_G['mobile'] = 'unknown';
  292. if($_GET['mobile'] === 'yes') {
  293. return true;
  294. } else {
  295. return false;
  296. }
  297. }
  298. function dstrpos($string, &$arr, $returnvalue = false) {
  299. if(empty($string)) return false;
  300. foreach((array)$arr as $v) {
  301. if(strpos($string, $v) !== false) {
  302. $return = $returnvalue ? $v : true;
  303. return $return;
  304. }
  305. }
  306. return false;
  307. }
  308. function isemail($email) {
  309. return strlen($email) > 6 && strlen($email) <= 32 && preg_match("/^([A-Za-z0-9\-_.+]+)@([A-Za-z0-9\-]+[.][A-Za-z0-9\-.]+)$/", $email);
  310. }
  311. function quescrypt($questionid, $answer) {
  312. return $questionid > 0 && $answer != '' ? substr(md5($answer.md5($questionid)), 16, 8) : '';
  313. }
  314. function random($length, $numeric = 0) {
  315. $seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  316. $seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
  317. if($numeric) {
  318. $hash = '';
  319. } else {
  320. $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
  321. $length--;
  322. }
  323. $max = strlen($seed) - 1;
  324. for($i = 0; $i < $length; $i++) {
  325. $hash .= $seed{mt_rand(0, $max)};
  326. }
  327. return $hash;
  328. }
  329. function strexists($string, $find) {
  330. return !(strpos($string, $find) === FALSE);
  331. }
  332. function avatar($uid, $size = 'middle', $returnsrc = FALSE, $real = FALSE, $static = FALSE, $ucenterurl = '') {
  333. global $_G;
  334. if($_G['setting']['plugins']['func'][HOOKTYPE]['avatar']) {
  335. $_G['hookavatar'] = '';
  336. $param = func_get_args();
  337. hookscript('avatar', 'global', 'funcs', array('param' => $param), 'avatar');
  338. if($_G['hookavatar']) {
  339. return $_G['hookavatar'];
  340. }
  341. }
  342. static $staticavatar;
  343. if($staticavatar === null) {
  344. $staticavatar = $_G['setting']['avatarmethod'];
  345. }
  346. $ucenterurl = empty($ucenterurl) ? $_G['setting']['ucenterurl'] : $ucenterurl;
  347. $size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
  348. $uid = abs(intval($uid));
  349. if(!$staticavatar && !$static) {
  350. return $returnsrc ? $ucenterurl.'/avatar.php?uid='.$uid.'&size='.$size : '<img src="'.$ucenterurl.'/avatar.php?uid='.$uid.'&size='.$size.($real ? '&type=real' : '').'" />';
  351. } else {
  352. $uid = sprintf("%09d", $uid);
  353. $dir1 = substr($uid, 0, 3);
  354. $dir2 = substr($uid, 3, 2);
  355. $dir3 = substr($uid, 5, 2);
  356. $file = $ucenterurl.'/data/avatar/'.$dir1.'/'.$dir2.'/'.$dir3.'/'.substr($uid, -2).($real ? '_real' : '').'_avatar_'.$size.'.jpg';
  357. return $returnsrc ? $file : '<img src="'.$file.'" onerror="this.onerror=null;this.src=\''.$ucenterurl.'/images/noavatar_'.$size.'.gif\'" />';
  358. }
  359. }
  360. function lang($file, $langvar = null, $vars = array(), $default = null) {
  361. global $_G;
  362. list($path, $file) = explode('/', $file);
  363. if(!$file) {
  364. $file = $path;
  365. $path = '';
  366. }
  367. if($path != 'plugin') {
  368. $key = $path == '' ? $file : $path.'_'.$file;
  369. if(!isset($_G['lang'][$key])) {
  370. include DISCUZ_ROOT.'./source/language/'.($path == '' ? '' : $path.'/').'lang_'.$file.'.php';
  371. $_G['lang'][$key] = $lang;
  372. }
  373. if(defined('IN_MOBILE') && !defined('TPL_DEFAULT')) {
  374. include DISCUZ_ROOT.'./source/language/mobile/lang_template.php';
  375. $_G['lang'][$key] = array_merge($_G['lang'][$key], $lang);
  376. }
  377. $returnvalue = &$_G['lang'];
  378. } else {
  379. if(empty($_G['config']['plugindeveloper'])) {
  380. loadcache('pluginlanguage_script');
  381. } elseif(!isset($_G['cache']['pluginlanguage_script'][$file]) && preg_match("/^[a-z]+[a-z0-9_]*$/i", $file)) {
  382. if(@include(DISCUZ_ROOT.'./data/plugindata/'.$file.'.lang.php')) {
  383. $_G['cache']['pluginlanguage_script'][$file] = $scriptlang[$file];
  384. } else {
  385. loadcache('pluginlanguage_script');
  386. }
  387. }
  388. $returnvalue = & $_G['cache']['pluginlanguage_script'];
  389. $key = &$file;
  390. }
  391. $return = $langvar !== null ? (isset($returnvalue[$key][$langvar]) ? $returnvalue[$key][$langvar] : null) : $returnvalue[$key];
  392. $return = $return === null ? ($default !== null ? $default : $langvar) : $return;
  393. $searchs = $replaces = array();
  394. if($vars && is_array($vars)) {
  395. foreach($vars as $k => $v) {
  396. $searchs[] = '{'.$k.'}';
  397. $replaces[] = $v;
  398. }
  399. }
  400. if(is_string($return) && strpos($return, '{_G/') !== false) {
  401. preg_match_all('/\{_G\/(.+?)\}/', $return, $gvar);
  402. foreach($gvar[0] as $k => $v) {
  403. $searchs[] = $v;
  404. $replaces[] = getglobal($gvar[1][$k]);
  405. }
  406. }
  407. $return = str_replace($searchs, $replaces, $return);
  408. return $return;
  409. }
  410. function checktplrefresh($maintpl, $subtpl, $timecompare, $templateid, $cachefile, $tpldir, $file) {
  411. static $tplrefresh, $timestamp, $targettplname;
  412. if($tplrefresh === null) {
  413. $tplrefresh = getglobal('config/output/tplrefresh');
  414. $timestamp = getglobal('timestamp');
  415. }
  416. if(empty($timecompare) || $tplrefresh == 1 || ($tplrefresh > 1 && !($timestamp % $tplrefresh))) {
  417. if(empty($timecompare) || @filemtime(DISCUZ_ROOT.$subtpl) > $timecompare) {
  418. require_once DISCUZ_ROOT.'/source/class/class_template.php';
  419. $template = new template();
  420. $template->parse_template($maintpl, $templateid, $tpldir, $file, $cachefile);
  421. if($targettplname === null) {
  422. $targettplname = getglobal('style/tplfile');
  423. if(!empty($targettplname)) {
  424. include_once libfile('function/block');
  425. $targettplname = strtr($targettplname, ':', '_');
  426. update_template_block($targettplname, getglobal('style/tpldirectory'), $template->blocks);
  427. }
  428. $targettplname = true;
  429. }
  430. return TRUE;
  431. }
  432. }
  433. return FALSE;
  434. }
  435. function template($file, $templateid = 0, $tpldir = '', $gettplfile = 0, $primaltpl='') {
  436. global $_G;
  437. static $_init_style = false;
  438. if($_init_style === false) {
  439. C::app()->_init_style();
  440. $_init_style = true;
  441. }
  442. $oldfile = $file;
  443. if(strpos($file, ':') !== false) {
  444. $clonefile = '';
  445. list($templateid, $file, $clonefile) = explode(':', $file);
  446. $oldfile = $file;
  447. $file = empty($clonefile) ? $file : $file.'_'.$clonefile;
  448. if($templateid == 'diy') {
  449. $indiy = false;
  450. $_G['style']['tpldirectory'] = $tpldir ? $tpldir : (defined('TPLDIR') ? TPLDIR : '');
  451. $_G['style']['prefile'] = '';
  452. $diypath = DISCUZ_ROOT.'./data/diy/'.$_G['style']['tpldirectory'].'/'; //DIY模板文件目录
  453. $preend = '_diy_preview';
  454. $_GET['preview'] = !empty($_GET['preview']) ? $_GET['preview'] : '';
  455. $curtplname = $oldfile;
  456. $basescript = $_G['mod'] == 'viewthread' && !empty($_G['thread']) ? 'forum' : $_G['basescript'];
  457. if(isset($_G['cache']['diytemplatename'.$basescript])) {
  458. $diytemplatename = &$_G['cache']['diytemplatename'.$basescript];
  459. } else {
  460. if(!isset($_G['cache']['diytemplatename'])) {
  461. loadcache('diytemplatename');
  462. }
  463. $diytemplatename = &$_G['cache']['diytemplatename'];
  464. }
  465. $tplsavemod = 0;
  466. 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')) {
  467. $tpldir = 'data/diy/'.$_G['style']['tpldirectory'].'/';
  468. !$gettplfile && $_G['style']['tplsavemod'] = $tplsavemod;
  469. $curtplname = $file;
  470. if(isset($_GET['diy']) && $_GET['diy'] == 'yes' || isset($_GET['diy']) && $_GET['preview'] == 'yes') { //DIY模式或预览模式下做以下判断
  471. $flag = file_exists($diypath.$file.$preend.'.htm');
  472. if($_GET['preview'] == 'yes') {
  473. $file .= $flag ? $preend : '';
  474. } else {
  475. $_G['style']['prefile'] = $flag ? 1 : '';
  476. }
  477. }
  478. $indiy = true;
  479. } else {
  480. $file = $primaltpl ? $primaltpl : $oldfile;
  481. }
  482. $tplrefresh = $_G['config']['output']['tplrefresh'];
  483. if($indiy && ($tplrefresh ==1 || ($tplrefresh > 1 && !($_G['timestamp'] % $tplrefresh))) && filemtime($diypath.$file.'.htm') < filemtime(DISCUZ_ROOT.$_G['style']['tpldirectory'].'/'.($primaltpl ? $primaltpl : $oldfile).'.htm')) {
  484. if (!updatediytemplate($file, $_G['style']['tpldirectory'])) {
  485. unlink($diypath.$file.'.htm');
  486. $tpldir = '';
  487. }
  488. }
  489. if (!$gettplfile && empty($_G['style']['tplfile'])) {
  490. $_G['style']['tplfile'] = empty($clonefile) ? $curtplname : $oldfile.':'.$clonefile;
  491. }
  492. $_G['style']['prefile'] = !empty($_GET['preview']) && $_GET['preview'] == 'yes' ? '' : $_G['style']['prefile'];
  493. } else {
  494. $tpldir = './source/plugin/'.$templateid.'/template';
  495. }
  496. }
  497. $file .= !empty($_G['inajax']) && ($file == 'common/header' || $file == 'common/footer') ? '_ajax' : '';
  498. $tpldir = $tpldir ? $tpldir : (defined('TPLDIR') ? TPLDIR : '');
  499. $templateid = $templateid ? $templateid : (defined('TEMPLATEID') ? TEMPLATEID : '');
  500. $filebak = $file;
  501. if(defined('IN_MOBILE') && !defined('TPL_DEFAULT') && strpos($file, 'mobile/') === false || (isset($_G['forcemobilemessage']) && $_G['forcemobilemessage'])) {
  502. $file = 'mobile/'.$oldfile;
  503. }
  504. if(!$tpldir) {
  505. $tpldir = './template/default';
  506. }
  507. $tplfile = $tpldir.'/'.$file.'.htm';
  508. $file == 'common/header' && defined('CURMODULE') && CURMODULE && $file = 'common/header_'.$_G['basescript'].'_'.CURMODULE;
  509. if(defined('IN_MOBILE') && !defined('TPL_DEFAULT')) {
  510. if(strpos($tpldir, 'plugin')) {
  511. if(!file_exists(DISCUZ_ROOT.$tpldir.'/'.$file.'.htm') && !file_exists(DISCUZ_ROOT.$tpldir.'/'.$file.'.php')) {
  512. discuz_error::template_error('template_notfound', $tpldir.'/'.$file.'.htm');
  513. } else {
  514. $mobiletplfile = $tpldir.'/'.$file.'.htm';
  515. }
  516. }
  517. !$mobiletplfile && $mobiletplfile = $file.'.htm';
  518. if(strpos($tpldir, 'plugin') && (file_exists(DISCUZ_ROOT.$mobiletplfile) || file_exists(substr(DISCUZ_ROOT.$mobiletplfile, 0, -4).'.php'))) {
  519. $tplfile = $mobiletplfile;
  520. } elseif(!file_exists(DISCUZ_ROOT.TPLDIR.'/'.$mobiletplfile) && !file_exists(substr(DISCUZ_ROOT.TPLDIR.'/'.$mobiletplfile, 0, -4).'.php')) {
  521. $mobiletplfile = './template/default/'.$mobiletplfile;
  522. if(!file_exists(DISCUZ_ROOT.$mobiletplfile) && !$_G['forcemobilemessage']) {
  523. $tplfile = str_replace('mobile/', '', $tplfile);
  524. $file = str_replace('mobile/', '', $file);
  525. define('TPL_DEFAULT', true);
  526. } else {
  527. $tplfile = $mobiletplfile;
  528. }
  529. } else {
  530. $tplfile = TPLDIR.'/'.$mobiletplfile;
  531. }
  532. }
  533. $cachefile = './data/template/'.(defined('STYLEID') ? STYLEID.'_' : '_').$templateid.'_'.str_replace('/', '_', $file).'.tpl.php';
  534. if($templateid != 1 && !file_exists(DISCUZ_ROOT.$tplfile) && !file_exists(substr(DISCUZ_ROOT.$tplfile, 0, -4).'.php')
  535. && !file_exists(DISCUZ_ROOT.($tplfile = $tpldir.$filebak.'.htm'))) {
  536. $tplfile = './template/default/'.$filebak.'.htm';
  537. }
  538. if($gettplfile) {
  539. return $tplfile;
  540. }
  541. checktplrefresh($tplfile, $tplfile, @filemtime(DISCUZ_ROOT.$cachefile), $templateid, $cachefile, $tpldir, $file);
  542. return DISCUZ_ROOT.$cachefile;
  543. }
  544. function dsign($str, $length = 16){
  545. return substr(md5(getglobal('uid').$str.getglobal('authkey')), 0, ($length ? max(8, $length) : 16));
  546. }
  547. function modauthkey($id) {
  548. global $_G;
  549. return md5($_G['username'].$_G['uid'].$_G['authkey'].substr(TIMESTAMP, 0, -7).$id);
  550. }
  551. function getcurrentnav() {
  552. global $_G;
  553. if(!empty($_G['mnid'])) {
  554. return $_G['mnid'];
  555. }
  556. $mnid = '';
  557. $_G['basefilename'] = $_G['basefilename'] == $_G['basescript'] ? $_G['basefilename'] : $_G['basescript'].'.php';
  558. if(isset($_G['setting']['navmns'][$_G['basefilename']])) {
  559. if($_G['basefilename'] == 'home.php' && $_GET['mod'] == 'space' && (empty($_GET['do']) || in_array($_GET['do'], array('follow', 'view')))) {
  560. $_GET['mod'] = 'follow';
  561. }
  562. foreach($_G['setting']['navmns'][$_G['basefilename']] as $navmn) {
  563. 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'))) {
  564. $mnid = $navmn[1];
  565. }
  566. }
  567. }
  568. if(!$mnid && isset($_G['setting']['navdms'])) {
  569. foreach($_G['setting']['navdms'] as $navdm => $navid) {
  570. if(strpos(strtolower($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']), $navdm) !== false) {
  571. $mnid = $navid;
  572. break;
  573. }
  574. }
  575. }
  576. if(!$mnid && isset($_G['setting']['navmn'][$_G['basefilename']])) {
  577. $mnid = $_G['setting']['navmn'][$_G['basefilename']];
  578. }
  579. return $mnid;
  580. }
  581. function loaducenter() {
  582. require_once DISCUZ_ROOT.'./config/config_ucenter.php';
  583. require_once DISCUZ_ROOT.'./uc_client/client.php';
  584. }
  585. function loadcache($cachenames, $force = false) {
  586. global $_G;
  587. static $loadedcache = array();
  588. $cachenames = is_array($cachenames) ? $cachenames : array($cachenames);
  589. $caches = array();
  590. foreach ($cachenames as $k) {
  591. if(!isset($loadedcache[$k]) || $force) {
  592. $caches[] = $k;
  593. $loadedcache[$k] = true;
  594. }
  595. }
  596. if(!empty($caches)) {
  597. $cachedata = C::t('common_syscache')->fetch_all($caches);
  598. foreach($cachedata as $cname => $data) {
  599. if($cname == 'setting') {
  600. $_G['setting'] = $data;
  601. } elseif($cname == 'usergroup_'.$_G['groupid']) {
  602. $_G['cache'][$cname] = $_G['group'] = $data;
  603. } elseif($cname == 'style_default') {
  604. $_G['cache'][$cname] = $_G['style'] = $data;
  605. } elseif($cname == 'grouplevels') {
  606. $_G['grouplevels'] = $data;
  607. } else {
  608. $_G['cache'][$cname] = $data;
  609. }
  610. }
  611. }
  612. return true;
  613. }
  614. function dgmdate($timestamp, $format = 'dt', $timeoffset = '9999', $uformat = '') {
  615. global $_G;
  616. $format == 'u' && !$_G['setting']['dateconvert'] && $format = 'dt';
  617. static $dformat, $tformat, $dtformat, $offset, $lang;
  618. if($dformat === null) {
  619. $dformat = getglobal('setting/dateformat');
  620. $tformat = getglobal('setting/timeformat');
  621. $dtformat = $dformat.' '.$tformat;
  622. $offset = getglobal('member/timeoffset');
  623. $lang = lang('core', 'date');
  624. }
  625. $timeoffset = $timeoffset == 9999 ? $offset : $timeoffset;
  626. $timestamp += $timeoffset * 3600;
  627. $format = empty($format) || $format == 'dt' ? $dtformat : ($format == 'd' ? $dformat : ($format == 't' ? $tformat : $format));
  628. if($format == 'u') {
  629. $todaytimestamp = TIMESTAMP - (TIMESTAMP + $timeoffset * 3600) % 86400 + $timeoffset * 3600;
  630. $s = gmdate(!$uformat ? $dtformat : $uformat, $timestamp);
  631. $time = TIMESTAMP + $timeoffset * 3600 - $timestamp;
  632. if($timestamp >= $todaytimestamp) {
  633. if($time > 3600) {
  634. return '<span title="'.$s.'">'.intval($time / 3600).'&nbsp;'.$lang['hour'].$lang['before'].'</span>';
  635. } elseif($time > 1800) {
  636. return '<span title="'.$s.'">'.$lang['half'].$lang['hour'].$lang['before'].'</span>';
  637. } elseif($time > 60) {
  638. return '<span title="'.$s.'">'.intval($time / 60).'&nbsp;'.$lang['min'].$lang['before'].'</span>';
  639. } elseif($time > 0) {
  640. return '<span title="'.$s.'">'.$time.'&nbsp;'.$lang['sec'].$lang['before'].'</span>';
  641. } elseif($time == 0) {
  642. return '<span title="'.$s.'">'.$lang['now'].'</span>';
  643. } else {
  644. return $s;
  645. }
  646. } elseif(($days = intval(($todaytimestamp - $timestamp) / 86400)) >= 0 && $days < 7) {
  647. if($days == 0) {
  648. return '<span title="'.$s.'">'.$lang['yday'].'&nbsp;'.gmdate($tformat, $timestamp).'</span>';
  649. } elseif($days == 1) {
  650. return '<span title="'.$s.'">'.$lang['byday'].'&nbsp;'.gmdate($tformat, $timestamp).'</span>';
  651. } else {
  652. return '<span title="'.$s.'">'.($days + 1).'&nbsp;'.$lang['day'].$lang['before'].'</span>';
  653. }
  654. } else {
  655. return $s;
  656. }
  657. } else {
  658. return gmdate($format, $timestamp);
  659. }
  660. }
  661. function dmktime($date) {
  662. if(strpos($date, '-')) {
  663. $time = explode('-', $date);
  664. return mktime(0, 0, 0, $time[1], $time[2], $time[0]);
  665. }
  666. return 0;
  667. }
  668. function dnumber($number) {
  669. return abs($number) > 10000 ? '<span title="'.$number.'">'.intval($number / 10000).lang('core', '10k').'</span>' : $number;
  670. }
  671. function savecache($cachename, $data) {
  672. C::t('common_syscache')->insert($cachename, $data);
  673. }
  674. function save_syscache($cachename, $data) {
  675. savecache($cachename, $data);
  676. }
  677. function block_get($parameter) {
  678. include_once libfile('function/block');
  679. block_get_batch($parameter);
  680. }
  681. function block_display($bid) {
  682. include_once libfile('function/block');
  683. block_display_batch($bid);
  684. }
  685. function dimplode($array) {
  686. if(!empty($array)) {
  687. $array = array_map('addslashes', $array);
  688. return "'".implode("','", is_array($array) ? $array : array($array))."'";
  689. } else {
  690. return 0;
  691. }
  692. }
  693. function libfile($libname, $folder = '') {
  694. $libpath = '/source/'.$folder;
  695. if(strstr($libname, '/')) {
  696. list($pre, $name) = explode('/', $libname);
  697. $path = "{$libpath}/{$pre}/{$pre}_{$name}";
  698. } else {
  699. $path = "{$libpath}/{$libname}";
  700. }
  701. return preg_match('/^[\w\d\/_]+$/i', $path) ? realpath(DISCUZ_ROOT.$path.'.php') : false;
  702. }
  703. function dstrlen($str) {
  704. if(strtolower(CHARSET) != 'utf-8') {
  705. return strlen($str);
  706. }
  707. $count = 0;
  708. for($i = 0; $i < strlen($str); $i++){
  709. $value = ord($str[$i]);
  710. if($value > 127) {
  711. $count++;
  712. if($value >= 192 && $value <= 223) $i++;
  713. elseif($value >= 224 && $value <= 239) $i = $i + 2;
  714. elseif($value >= 240 && $value <= 247) $i = $i + 3;
  715. }
  716. $count++;
  717. }
  718. return $count;
  719. }
  720. function cutstr($string, $length, $dot = ' ...') {
  721. if(strlen($string) <= $length) {
  722. return $string;
  723. }
  724. $pre = chr(1);
  725. $end = chr(1);
  726. $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), $string);
  727. $strcut = '';
  728. if(strtolower(CHARSET) == 'utf-8') {
  729. $n = $tn = $noc = 0;
  730. while($n < strlen($string)) {
  731. $t = ord($string[$n]);
  732. if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  733. $tn = 1; $n++; $noc++;
  734. } elseif(194 <= $t && $t <= 223) {
  735. $tn = 2; $n += 2; $noc += 2;
  736. } elseif(224 <= $t && $t <= 239) {
  737. $tn = 3; $n += 3; $noc += 2;
  738. } elseif(240 <= $t && $t <= 247) {
  739. $tn = 4; $n += 4; $noc += 2;
  740. } elseif(248 <= $t && $t <= 251) {
  741. $tn = 5; $n += 5; $noc += 2;
  742. } elseif($t == 252 || $t == 253) {
  743. $tn = 6; $n += 6; $noc += 2;
  744. } else {
  745. $n++;
  746. }
  747. if($noc >= $length) {
  748. break;
  749. }
  750. }
  751. if($noc > $length) {
  752. $n -= $tn;
  753. }
  754. $strcut = substr($string, 0, $n);
  755. } else {
  756. for($i = 0; $i < $length; $i++) {
  757. $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
  758. }
  759. }
  760. $strcut = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
  761. $pos = strrpos($strcut, chr(1));
  762. if($pos !== false) {
  763. $strcut = substr($strcut,0,$pos);
  764. }
  765. return $strcut.$dot;
  766. }
  767. function dstripslashes($string) {
  768. if(empty($string)) return $string;
  769. if(is_array($string)) {
  770. foreach($string as $key => $val) {
  771. $string[$key] = dstripslashes($val);
  772. }
  773. } else {
  774. $string = stripslashes($string);
  775. }
  776. return $string;
  777. }
  778. function aidencode($aid, $type = 0, $tid = 0) {
  779. global $_G;
  780. $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;
  781. return rawurlencode(base64_encode($s));
  782. }
  783. function getforumimg($aid, $nocache = 0, $w = 140, $h = 140, $type = '') {
  784. global $_G;
  785. $key = dsign($aid.'|'.$w.'|'.$h);
  786. return 'forum.php?mod=image&aid='.$aid.'&size='.$w.'x'.$h.'&key='.rawurlencode($key).($nocache ? '&nocache=yes' : '').($type ? '&type='.$type : '');
  787. }
  788. function rewriteoutput($type, $returntype, $host) {
  789. global $_G;
  790. $fextra = '';
  791. if($type == 'forum_forumdisplay') {
  792. list(,,, $fid, $page, $extra) = func_get_args();
  793. $r = array(
  794. '{fid}' => empty($_G['setting']['forumkeys'][$fid]) ? $fid : $_G['setting']['forumkeys'][$fid],
  795. '{page}' => $page ? $page : 1,
  796. );
  797. } elseif($type == 'forum_viewthread') {
  798. list(,,, $tid, $page, $prevpage, $extra) = func_get_args();
  799. $r = array(
  800. '{tid}' => $tid,
  801. '{page}' => $page ? $page : 1,
  802. '{prevpage}' => $prevpage && !IS_ROBOT ? $prevpage : 1,
  803. );
  804. } elseif($type == 'home_space') {
  805. list(,,, $uid, $username, $extra) = func_get_args();
  806. $_G['setting']['rewritecompatible'] && $username = rawurlencode($username);
  807. $r = array(
  808. '{user}' => $uid ? 'uid' : 'username',
  809. '{value}' => $uid ? $uid : $username,
  810. );
  811. } elseif($type == 'home_blog') {
  812. list(,,, $uid, $blogid, $extra) = func_get_args();
  813. $r = array(
  814. '{uid}' => $uid,
  815. '{blogid}' => $blogid,
  816. );
  817. } elseif($type == 'group_group') {
  818. list(,,, $fid, $page, $extra) = func_get_args();
  819. $r = array(
  820. '{fid}' => $fid,
  821. '{page}' => $page ? $page : 1,
  822. );
  823. } elseif($type == 'portal_topic') {
  824. list(,,, $name, $extra) = func_get_args();
  825. $r = array(
  826. '{name}' => $name,
  827. );
  828. } elseif($type == 'portal_article') {
  829. list(,,, $id, $page, $extra) = func_get_args();
  830. $r = array(
  831. '{id}' => $id,
  832. '{page}' => $page ? $page : 1,
  833. );
  834. } elseif($type == 'forum_archiver') {
  835. list(,, $action, $value, $page, $extra) = func_get_args();
  836. $host = '';
  837. $r = array(
  838. '{action}' => $action,
  839. '{value}' => $value,
  840. );
  841. if($page) {
  842. $fextra = '?page='.$page;
  843. }
  844. } elseif($type == 'plugin') {
  845. list(,, $pluginid, $module,, $param, $extra) = func_get_args();
  846. $host = '';
  847. $r = array(
  848. '{pluginid}' => $pluginid,
  849. '{module}' => $module,
  850. );
  851. if($param) {
  852. $fextra = '?'.$param;
  853. }
  854. }
  855. $href = str_replace(array_keys($r), $r, $_G['setting']['rewriterule'][$type]).$fextra;
  856. if(!$returntype) {
  857. return '<a href="'.$host.$href.'"'.(!empty($extra) ? stripslashes($extra) : '').'>';
  858. } else {
  859. return $host.$href;
  860. }
  861. }
  862. function mobilereplace($file, $replace) {
  863. return helper_mobile::mobilereplace($file, $replace);
  864. }
  865. function mobileoutput() {
  866. helper_mobile::mobileoutput();
  867. }
  868. function output() {
  869. global $_G;
  870. if(defined('DISCUZ_OUTPUTED')) {
  871. return;
  872. } else {
  873. define('DISCUZ_OUTPUTED', 1);
  874. }
  875. if(!empty($_G['blockupdate'])) {
  876. block_updatecache($_G['blockupdate']['bid']);
  877. }
  878. if(defined('IN_MOBILE')) {
  879. mobileoutput();
  880. }
  881. if(!defined('IN_MOBILE') && !defined('IN_ARCHIVER')) {
  882. $tipsService = Cloud::loadClass('Service_DiscuzTips');
  883. $tipsService->show();
  884. }
  885. $havedomain = implode('', $_G['setting']['domain']['app']);
  886. if($_G['setting']['rewritestatus'] || !empty($havedomain)) {
  887. $content = ob_get_contents();
  888. $content = output_replace($content);
  889. ob_end_clean();
  890. $_G['gzipcompress'] ? ob_start('ob_gzhandler') : ob_start();
  891. echo $content;
  892. }
  893. if($_G['setting']['ftp']['connid']) {
  894. @ftp_close($_G['setting']['ftp']['connid']);
  895. }
  896. $_G['setting']['ftp'] = array();
  897. if(defined('CACHE_FILE') && CACHE_FILE && !defined('CACHE_FORBIDDEN') && !defined('IN_MOBILE') && !checkmobile()) {
  898. if(diskfreespace(DISCUZ_ROOT.'./'.$_G['setting']['cachethreaddir']) > 1000000) {
  899. if($fp = @fopen(CACHE_FILE, 'w')) {
  900. flock($fp, LOCK_EX);
  901. fwrite($fp, empty($content) ? ob_get_contents() : $content);
  902. }
  903. @fclose($fp);
  904. chmod(CACHE_FILE, 0777);
  905. }
  906. }
  907. if(defined('DISCUZ_DEBUG') && DISCUZ_DEBUG && @include(libfile('function/debug'))) {
  908. function_exists('debugmessage') && debugmessage();
  909. }
  910. }
  911. function output_replace($content) {
  912. global $_G;
  913. if(defined('IN_MODCP') || defined('IN_ADMINCP')) return $content;
  914. if(!empty($_G['setting']['output']['str']['search'])) {
  915. if(empty($_G['setting']['domain']['app']['default'])) {
  916. $_G['setting']['output']['str']['replace'] = str_replace('{CURHOST}', $_G['siteurl'], $_G['setting']['output']['str']['replace']);
  917. }
  918. $content = str_replace($_G['setting']['output']['str']['search'], $_G['setting']['output']['str']['replace'], $content);
  919. }
  920. if(!empty($_G['setting']['output']['preg']['search'])) {
  921. if(empty($_G['setting']['domain']['app']['default'])) {
  922. $_G['setting']['output']['preg']['search'] = str_replace('\{CURHOST\}', preg_quote($_G['siteurl'], '/'), $_G['setting']['output']['preg']['search']);
  923. $_G['setting']['output']['preg']['replace'] = str_replace('{CURHOST}', $_G['siteurl'], $_G['setting']['output']['preg']['replace']);
  924. }
  925. $content = preg_replace($_G['setting']['output']['preg']['search'], $_G['setting']['output']['preg']['replace'], $content);
  926. }
  927. return $content;
  928. }
  929. function output_ajax() {
  930. global $_G;
  931. $s = ob_get_contents();
  932. ob_end_clean();
  933. $s = preg_replace("/([\\x01-\\x08\\x0b-\\x0c\\x0e-\\x1f])+/", ' ', $s);
  934. $s = str_replace(array(chr(0), ']]>'), array(' ', ']]&gt;'), $s);
  935. if(defined('DISCUZ_DEBUG') && DISCUZ_DEBUG && @include(libfile('function/debug'))) {
  936. function_exists('debugmessage') && $s .= debugmessage(1);
  937. }
  938. $havedomain = implode('', $_G['setting']['domain']['app']);
  939. if($_G['setting']['rewritestatus'] || !empty($havedomain)) {
  940. $s = output_replace($s);
  941. }
  942. return $s;
  943. }
  944. function runhooks($scriptextra = '') {
  945. if(!defined('HOOKTYPE')) {
  946. define('HOOKTYPE', !defined('IN_MOBILE') ? 'hookscript' : 'hookscriptmobile');
  947. }
  948. if(defined('CURMODULE')) {
  949. global $_G;
  950. if($_G['setting']['plugins']['func'][HOOKTYPE]['common']) {
  951. hookscript('common', 'global', 'funcs', array(), 'common');
  952. }
  953. hookscript(CURMODULE, $_G['basescript'], 'funcs', array(), '', $scriptextra);
  954. }
  955. }
  956. function hookscript($script, $hscript, $type = 'funcs', $param = array(), $func = '', $scriptextra = '') {
  957. global $_G;
  958. static $pluginclasses;
  959. if($hscript == 'home') {
  960. if($script == 'space') {
  961. $scriptextra = !$scriptextra ? $_GET['do'] : $scriptextra;
  962. $script = 'space'.(!empty($scriptextra) ? '_'.$scriptextra : '');
  963. } elseif($script == 'spacecp') {
  964. $scriptextra = !$scriptextra ? $_GET['ac'] : $scriptextra;
  965. $script .= !empty($scriptextra) ? '_'.$scriptextra : '';
  966. }
  967. }
  968. if(!isset($_G['setting'][HOOKTYPE][$hscript][$script][$type])) {
  969. return;
  970. }
  971. if(!isset($_G['cache']['plugin'])) {
  972. loadcache('plugin');
  973. }
  974. foreach((array)$_G['setting'][HOOKTYPE][$hscript][$script]['module'] as $identifier => $include) {
  975. $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']);
  976. if($hooksadminid[$identifier]) {
  977. @include_once DISCUZ_ROOT.'./source/plugin/'.$include.'.class.php';
  978. }
  979. }
  980. if(@is_array($_G['setting'][HOOKTYPE][$hscript][$script][$type])) {
  981. $_G['inhookscript'] = true;
  982. $funcs = !$func ? $_G['setting'][HOOKTYPE][$hscript][$script][$type] : array($func => $_G['setting'][HOOKTYPE][$hscript][$script][$type][$func]);
  983. foreach($funcs as $hookkey => $hookfuncs) {
  984. foreach($hookfuncs as $hookfunc) {
  985. if($hooksadminid[$hookfunc[0]]) {
  986. $classkey = (HOOKTYPE != 'hookscriptmobile' ? '' : 'mobile').'plugin_'.($hookfunc[0].($hscript != 'global' ? '_'.$hscript : ''));
  987. if(!class_exists($classkey, false)) {
  988. continue;
  989. }
  990. if(!isset($pluginclasses[$classkey])) {
  991. $pluginclasses[$classkey] = new $classkey;
  992. }
  993. if(!method_exists($pluginclasses[$classkey], $hookfunc[1])) {
  994. continue;
  995. }
  996. $return = $pluginclasses[$classkey]->$hookfunc[1]($param);
  997. if(is_array($return)) {
  998. if(!isset($_G['setting']['pluginhooks'][$hookkey]) || is_array($_G['setting']['pluginhooks'][$hookkey])) {
  999. foreach($return as $k => $v) {
  1000. $_G['setting']['pluginhooks'][$hookkey][$k] .= $v;
  1001. }
  1002. }
  1003. } else {
  1004. if(!is_array($_G['setting']['pluginhooks'][$hookkey])) {
  1005. $_G['setting']['pluginhooks'][$hookkey] .= $return;
  1006. } else {
  1007. foreach($_G['setting']['pluginhooks'][$hookkey] as $k => $v) {
  1008. $_G['setting']['pluginhooks'][$hookkey][$k] .= $return;
  1009. }
  1010. }
  1011. }
  1012. }
  1013. }
  1014. }
  1015. }
  1016. $_G['inhookscript'] = false;
  1017. }
  1018. function hookscriptoutput($tplfile) {
  1019. global $_G;
  1020. if(!empty($_G['hookscriptoutput'])) {
  1021. return;
  1022. }
  1023. hookscript('global', 'global');
  1024. if(defined('CURMODULE')) {
  1025. $param = array('template' => $tplfile, 'message' => $_G['hookscriptmessage'], 'values' => $_G['hookscriptvalues']);
  1026. hookscript(CURMODULE, $_G['basescript'], 'outputfuncs', $param);
  1027. }
  1028. $_G['hookscriptoutput'] = true;
  1029. }
  1030. function pluginmodule($pluginid, $type) {
  1031. global $_G;
  1032. if(!isset($_G['cache']['plugin'])) {
  1033. loadcache('plugin');
  1034. }
  1035. list($identifier, $module) = explode(':', $pluginid);
  1036. if(!is_array($_G['setting']['plugins'][$type]) || !array_key_exists($pluginid, $_G['setting']['plugins'][$type])) {
  1037. showmessage('plugin_nonexistence');
  1038. }
  1039. if(!empty($_G['setting']['plugins'][$type][$pluginid]['url'])) {
  1040. dheader('location: '.$_G['setting']['plugins'][$type][$pluginid]['url']);
  1041. }
  1042. $directory = $_G['setting']['plugins'][$type][$pluginid]['directory'];
  1043. if(empty($identifier) || !preg_match("/^[a-z]+[a-z0-9_]*\/$/i", $directory) || !preg_match("/^[a-z0-9_\-]+$/i", $module)) {
  1044. showmessage('undefined_action');
  1045. }
  1046. if(@!file_exists(DISCUZ_ROOT.($modfile = './source/plugin/'.$directory.$module.'.inc.php'))) {
  1047. showmessage('plugin_module_nonexistence', '', array('mod' => $modfile));
  1048. }
  1049. return DISCUZ_ROOT.$modfile;
  1050. }
  1051. function updatecreditbyaction($action, $uid = 0, $extrasql = array(), $needle = '', $coef = 1, $update = 1, $fid = 0) {
  1052. $credit = credit::instance();
  1053. if($extrasql) {
  1054. $credit->extrasql = $extrasql;
  1055. }
  1056. return $credit->execrule($action, $uid, $needle, $coef, $update, $fid);
  1057. }
  1058. function checklowerlimit($action, $uid = 0, $coef = 1, $fid = 0, $returnonly = 0) {
  1059. require_once libfile('function/credit');
  1060. return _checklowerlimit($action, $uid, $coef, $fid, $returnonly);
  1061. }
  1062. function batchupdatecredit($action, $uids = 0, $extrasql = array(), $coef = 1, $fid = 0) {
  1063. $credit = & credit::instance();
  1064. if($extrasql) {
  1065. $credit->extrasql = $extrasql;
  1066. }
  1067. return $credit->updatecreditbyrule($action, $uids, $coef, $fid);
  1068. }
  1069. function updatemembercount($uids, $dataarr = array(), $checkgroup = true, $operation = '', $relatedid = 0, $ruletxt = '') {
  1070. if(!empty($uids) && (is_array($dataarr) && $dataarr)) {
  1071. require_once libfile('function/credit');
  1072. return _updatemembercount($uids, $dataarr, $checkgroup, $operation, $relatedid, $ruletxt);
  1073. }
  1074. return true;
  1075. }
  1076. function checkusergroup($uid = 0) {
  1077. $credit = & credit::instance();
  1078. $credit->checkusergroup($uid);
  1079. }
  1080. function checkformulasyntax($formula, $operators, $tokens) {
  1081. $var = implode('|', $tokens);
  1082. $operator = implode('', $operators);
  1083. $operator = str_replace(
  1084. array('+', '-', '*', '/', '(', ')', '{', '}', '\''),
  1085. array('\+', '\-', '\*', '\/', '\(', '\)', '\{', '\}', '\\\''),
  1086. $operator
  1087. );
  1088. if(!empty($formula)) {
  1089. if(!preg_match("/^([$operator\.\d\(\)]|(($var)([$operator\(\)]|$)+))+$/", $formula) || !is_null(eval(preg_replace("/($var)/", "\$\\1", $formula).';'))){
  1090. return false;
  1091. }
  1092. }
  1093. return true;
  1094. }
  1095. function checkformulacredits($formula) {
  1096. return checkformulasyntax(
  1097. $formula,
  1098. array('+', '-', '*', '/', ' '),
  1099. array('extcredits[1-8]', 'digestposts', 'posts', 'threads', 'oltime', 'friends', 'doings', 'polls', 'blogs', 'albums', 'sharings')
  1100. );
  1101. }
  1102. function debug($var = null, $vardump = false) {
  1103. echo '<pre>';
  1104. $vardump = empty($var) ? true : $vardump;
  1105. if($vardump) {
  1106. var_dump($var);
  1107. } else {
  1108. print_r($var);
  1109. }
  1110. exit();
  1111. }
  1112. function debuginfo() {
  1113. global $_G;
  1114. if(getglobal('setting/debug')) {
  1115. $db = & DB::object();
  1116. $_G['debuginfo'] = array(
  1117. 'time' => number_format((microtime(true) - $_G['starttime']), 6),
  1118. 'queries' => $db->querynum,
  1119. 'memory' => ucwords(C::memory()->type)
  1120. );
  1121. if($db->slaveid) {
  1122. $_G['debuginfo']['queries'] = 'Total '.$db->querynum.', Slave '.$db->slavequery;
  1123. }
  1124. return TRUE;
  1125. } else {
  1126. return FALSE;
  1127. }
  1128. }
  1129. function getfocus_rand($module) {
  1130. global $_G;
  1131. if(empty($_G['setting']['focus']) || !array_key_exists($module, $_G['setting']['focus']) || !empty($_G['cookie']['nofocus_'.$module]) || !$_G['setting']['focus'][$module]) {
  1132. return null;
  1133. }
  1134. loadcache('focus');
  1135. if(empty($_G['cache']['focus']['data']) || !is_array($_G['cache']['focus']['data'])) {
  1136. return null;
  1137. }
  1138. $focusid = $_G['setting']['focus'][$module][array_rand($_G['setting']['focus'][$module])];
  1139. return $focusid;
  1140. }
  1141. function check_seccode($value, $idhash) {
  1142. return helper_form::check_seccode($value, $idhash);
  1143. }
  1144. function check_secqaa($value, $idhash) {
  1145. return helper_form::check_secqaa($value, $idhash);
  1146. }
  1147. function adshow($parameter) {
  1148. global $_G;
  1149. if($_G['inajax']) {
  1150. return;
  1151. }
  1152. if(isset($_G['config']['plugindeveloper']) && $_G['config']['plugindeveloper'] == 2) {
  1153. return '<hook>[ad '.$parameter.']</hook>';
  1154. }
  1155. $params = explode('/', $parameter);
  1156. $customid = 0;
  1157. $customc = explode('_', $params[0]);
  1158. if($customc[0] == 'custom') {
  1159. $params[0] = $customc[0];
  1160. $customid = $customc[1];
  1161. }
  1162. $adcontent = null;
  1163. if(empty($_G['setting']['advtype']) || !in_array($params[0], $_G['setting']['advtype'])) {
  1164. $adcontent = '';
  1165. }
  1166. if($adcontent === null) {
  1167. loadcache('advs');
  1168. $adids = array();
  1169. $evalcode = &$_G['cache']['advs']['evalcode'][$params[0]];
  1170. $parameters = &$_G['cache']['advs']['parameters'][$params[0]];
  1171. $codes = &$_G['cache']['advs']['code'][$_G['basescript']][$params[0]];
  1172. if(!empty($codes)) {
  1173. foreach($codes as $adid => $code) {
  1174. $parameter = &$parameters[$adid];
  1175. $checked = true;
  1176. @eval($evalcode['check']);
  1177. if($checked) {
  1178. $adids[] = $adid;
  1179. }
  1180. }
  1181. if(!empty($adids)) {
  1182. $adcode = $extra = '';
  1183. @eval($evalcode['create']);
  1184. if(empty($notag)) {
  1185. $adcontent = '<div'.($params[1] != '' ? ' class="'.$params[1].'"' : '').$extra.'>'.$adcode.'</div>';
  1186. } else {
  1187. $adcontent = $adcode;
  1188. }
  1189. }
  1190. }
  1191. }
  1192. $adfunc = 'ad_'.$params[0];
  1193. $_G['setting']['pluginhooks'][$adfunc] = null;
  1194. hookscript('ad', 'global', 'funcs', array('params' => $params, 'content' => $adcontent), $adfunc);
  1195. if(!$_G['setting']['hookscript']['global']['ad']['funcs'][$adfunc]) {
  1196. hookscript('ad', $_G['basescript'], 'funcs', array('params' => $params, 'content' => $adcontent), $adfunc);
  1197. }
  1198. return $_G['setting']['pluginhooks'][$adfunc] === null ? $adcontent : $_G['setting']['pluginhooks'][$adfunc];
  1199. }
  1200. function showmessage($message, $url_forward = '', $values = array(), $extraparam = array(), $custom = 0) {
  1201. require_once libfile('function/message');
  1202. return dshowmessage($message, $url_forward, $values, $extraparam, $custom);
  1203. }
  1204. function submitcheck($var, $allowget = 0, $seccodecheck = 0, $secqaacheck = 0) {
  1205. if(!getgpc($var)) {
  1206. return FALSE;
  1207. } else {
  1208. return helper_form::submitcheck($var, $allowget, $seccodecheck, $secqaacheck);
  1209. }
  1210. }
  1211. function multi($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 10, $autogoto = FALSE, $simple = FALSE, $jsfunc = FALSE) {
  1212. return $num > $perpage ? helper_page::multi($num, $perpage, $curpage, $mpurl, $maxpages, $page, $autogoto, $simple, $jsfunc) : '';
  1213. }
  1214. function simplepage($num, $perpage, $curpage, $mpurl) {
  1215. return helper_page::simplepage($num, $perpage, $curpage, $mpurl);
  1216. }
  1217. function censor($message, $modword = NULL, $return = FALSE) {
  1218. return helper_form::censor($message, $modword, $return);
  1219. }
  1220. function censormod($message) {
  1221. return getglobal('group/ignorecensor') || !$message ? false :helper_form::censormod($message);
  1222. }
  1223. function space_merge(&$values, $tablename, $isarchive = false) {
  1224. global $_G;
  1225. $uid = empty($values['uid'])?$_G['uid']:$values['uid'];
  1226. $var = "member_{$uid}_{$tablename}";
  1227. if($uid) {
  1228. if(!isset($_G[$var])) {
  1229. $ext = $isarchive ? '_archive' : '';
  1230. if(($_G[$var] = C::t('common_member_'.$tablename.$ext)->fetch($uid)) !== false) {
  1231. if($tablename == 'field_home') {
  1232. $_G['setting']['privacy'] = empty($_G['setting']['privacy']) ? array() : (is_array($_G['setting']['privacy']) ? $_G['setting']['privacy'] : dunserialize($_G['setting']['privacy']));
  1233. $_G[$var]['privacy'] = empty($_G[$var]['privacy'])? array() : is_array($_G[$var]['privacy']) ? $_G[$var]['privacy'] : dunserialize($_G[$var]['privacy']);
  1234. foreach (array('feed','view','profile') as $pkey) {
  1235. if(empty($_G[$var]['privacy'][$pkey]) && !isset($_G[$var]['privacy'][$pkey])) {
  1236. $_G[$var]['privacy'][$pkey] = isset($_G['setting']['privacy'][$pkey]) ? $_G['setting']['privacy'][$pkey] : array();
  1237. }
  1238. }
  1239. $_G[$var]['acceptemail'] = empty($_G[$var]['acceptemail'])? array() : dunserialize($_G[$var]['acceptemail']);
  1240. if(empty($_G[$var]['acceptemail'])) {
  1241. $_G[$var]['acceptemail'] = empty($_G['setting']['acceptemail'])?array():dunserialize($_G['setting']['acceptemail']);
  1242. }
  1243. }
  1244. } else {
  1245. C::t('common_member_'.$tablename.$ext)->insert(array('uid'=>$uid));
  1246. $_G[$var] = array();
  1247. }
  1248. }
  1249. $values = array_merge($values, $_G[$var]);
  1250. }
  1251. }
  1252. function runlog($file, $message, $halt=0) {
  1253. helper_log::runlog($file, $message, $halt);
  1254. }
  1255. function stripsearchkey($string) {
  1256. $string = trim($string);
  1257. $string = str_replace('*', '%', addcslashes($string, '%_'));
  1258. return $string;
  1259. }
  1260. function dmkdir($dir, $mode = 0777, $makeindex = TRUE){
  1261. if(!is_dir($dir)) {
  1262. dmkdir(dirname($dir), $mode, $makeindex);
  1263. @mkdir($dir, $mode);
  1264. if(!empty($makeindex)) {
  1265. @touch($dir.'/index.html'); @chmod($dir.'/index.html', 0777);
  1266. }
  1267. }
  1268. return true;
  1269. }
  1270. function dreferer($default = '') {
  1271. global $_G;
  1272. $default = empty($default) ? $GLOBALS['_t_curapp'] : '';
  1273. $_G['referer'] = !empty($_GET['referer']) ? $_GET['referer'] : $_SERVER['HTTP_REFERER'];
  1274. $_G['referer'] = substr($_G['referer'], -1) == '?' ? substr($_G['referer'], 0, -1) : $_G['referer'];
  1275. if(strpos($_G['referer'], 'member.php?mod=logging')) {
  1276. $_G['referer'] = $default;
  1277. }
  1278. $_G['referer'] = dhtmlspecialchars($_G['referer'], ENT_QUOTES);
  1279. $_G['referer'] = str_replace('&amp;', '&', $_G['referer']);
  1280. $reurl = parse_url($_G['referer']);
  1281. 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']))) {
  1282. if(!in_array($reurl['host'], $_G['setting']['domain']['app']) && !isset($_G['setting']['domain']['list'][$reurl['host']])) {
  1283. $domainroot = substr($reurl['host'], strpos($reurl['host'], '.')+1);
  1284. if(empty($_G['setting']['domain']['root']) || (is_array($_G['setting']['domain']['root']) && !in_array($domainroot, $_G['setting']['domain']['root']))) {
  1285. $_G['referer'] = $_G['setting']['domain']['defaultindex'] ? $_G['setting']['domain']['defaultindex'] : 'index.php';
  1286. }
  1287. }
  1288. } elseif(empty($reurl['host'])) {
  1289. $_G['referer'] = $_G['siteurl'].'./'.$_G['referer'];
  1290. }
  1291. return strip_tags($_G['referer']);
  1292. }
  1293. function ftpcmd($cmd, $arg1 = '') {
  1294. static $ftp;
  1295. $ftpon = getglobal('setting/ftp/on');
  1296. if(!$ftpon) {
  1297. return $cmd == 'error' ? -101 : 0;
  1298. } elseif($ftp == null) {
  1299. $ftp = & discuz_ftp::instance();
  1300. }
  1301. if(!$ftp->enabled) {
  1302. return $ftp->error();
  1303. } elseif($ftp->enabled && !$ftp->connectid) {
  1304. $ftp->connect();
  1305. }
  1306. switch ($cmd) {
  1307. case 'upload' : return $ftp->upload(getglobal('setting/attachdir').'/'.$arg1, $arg1); break;
  1308. case 'delete' : return $ftp->ftp_delete($arg1); break;
  1309. case 'close' : return $ftp->ftp_close(); break;
  1310. case 'error' : return $ftp->error(); break;
  1311. case 'object' : return $ftp; break;
  1312. default : return false;
  1313. }
  1314. }
  1315. function diconv($str, $in_charset, $out_charset = CHARSET, $ForceTable = FALSE) {
  1316. global $_G;
  1317. $in_charset = strtoupper($in_charset);
  1318. $out_charset = strtoupper($out_charset);
  1319. if(empty($str) || $in_charset == $out_charset) {
  1320. return $str;
  1321. }
  1322. $out = '';
  1323. if(!$ForceTable) {
  1324. if(function_exists('iconv')) {
  1325. $out = iconv($in_charset, $out_charset.'//IGNORE', $str);
  1326. } elseif(function_exists('mb_convert_encoding')) {
  1327. $out = mb_convert_encoding($str, $out_charset, $in_charset);
  1328. }
  1329. }
  1330. if($out == '') {
  1331. $chinese = new Chinese($in_charset, $out_charset, true);
  1332. $out = $chinese->Convert($str);
  1333. }
  1334. return $out;
  1335. }
  1336. function widthauto() {
  1337. global $_G;
  1338. if($_G['disabledwidthauto']) {
  1339. return 0;
  1340. }
  1341. if(!empty($_G['widthauto'])) {
  1342. return $_G['widthauto'] > 0 ? 1 : 0;
  1343. }
  1344. if($_G['setting']['switchwidthauto'] && !empty($_G['cookie']['widthauto'])) {
  1345. return $_G['cookie']['widthauto'] > 0 ? 1 : 0;
  1346. } else {
  1347. return $_G['setting']['allowwidthauto'] ? 0 : 1;
  1348. }
  1349. }
  1350. function renum($array) {
  1351. $newnums = $nums = array();
  1352. foreach ($array as $id => $num) {
  1353. $newnums[$num][] = $id;
  1354. $nums[$num] = $num;
  1355. }
  1356. return array($nums, $newnums);
  1357. }
  1358. function sizecount($size) {
  1359. if($size >= 1073741824) {
  1360. $size = round($size / 1073741824 * 100) / 100 . ' GB';
  1361. } elseif($size >= 1048576) {
  1362. $size = round($size / 1048576 * 100) / 100 . ' MB';
  1363. } elseif($size >= 1024) {
  1364. $size = round($size / 1024 * 100) / 100 . ' KB';
  1365. } else {
  1366. $size = $size . ' Bytes';
  1367. }
  1368. return $size;
  1369. }
  1370. function swapclass($class1, $class2 = '') {
  1371. static $swapc = null;
  1372. $swapc = isset($swapc) && $swapc != $class1 ? $class1 : $class2;
  1373. return $swapc;
  1374. }
  1375. function writelog($file, $log) {
  1376. helper_log::writelog($file, $log);
  1377. }
  1378. function getstatus($status, $position) {
  1379. $t = $status & pow(2, $position - 1) ? 1 : 0;
  1380. return $t;
  1381. }
  1382. function setstatus($position, $value, $baseon = null) {
  1383. $t = pow(2, $position - 1);
  1384. if($value) {
  1385. $t = $baseon | $t;
  1386. } elseif ($baseon !== null) {
  1387. $t = $baseon & ~$t;
  1388. } else {
  1389. $t = ~$t;
  1390. }
  1391. return $t & 0xFFFF;
  1392. }
  1393. function notification_add($touid, $type, $note, $notevars = array(), $system = 0) {
  1394. return helper_notification::notification_add($touid, $type, $note, $notevars, $system);
  1395. }
  1396. function manage_addnotify($type, $from_num = 0, $langvar = array()) {
  1397. helper_notification::manage_addnotify($type, $from_num, $langvar);
  1398. }
  1399. function sendpm($toid, $subject, $message, $fromid = '', $replypmid = 0, $isusername = 0, $type = 0) {
  1400. return helper_pm::sendpm($toid, $subject, $message, $fromid, $replypmid, $isusername, $type);
  1401. }
  1402. function g_icon($groupid, $return = 0) {
  1403. global $_G;
  1404. if(empty($_G['cache']['usergroups'][$groupid]['icon'])) {
  1405. $s = '';
  1406. } else {
  1407. if(substr($_G['cache']['usergroups'][$groupid]['icon'], 0, 5) == 'http:') {
  1408. $s = '<img src="'.$_G['cache']['usergroups'][$groupid]['icon'].'" alt="" class="vm" />';
  1409. } else {
  1410. $s = '<img src="'.$_G['setting']['attachurl'].'common/'.$_G['cache']['usergroups'][$groupid]['icon'].'" alt="" class="vm" />';
  1411. }
  1412. }
  1413. if($return) {
  1414. return $s;
  1415. } else {
  1416. echo $s;
  1417. }
  1418. }
  1419. function updatediytemplate($targettplname = '', $tpldirectory = '') {
  1420. $r = false;
  1421. $alldata = !empty($targettplname) ? array( C::t('common_diy_data')->fetch($targettplname, $tpldirectory)) : C::t('common_diy_data')->range();
  1422. require_once libfile('function/portalcp');
  1423. foreach($alldata as $value) {
  1424. $r = save_diy_data($value['tpldirectory'], $value['primaltplname'], $value['targettplname'], dunserialize($value['diycontent']));
  1425. }
  1426. return $r;
  1427. }
  1428. function space_key($uid, $appid=0) {
  1429. global $_G;
  1430. return substr(md5($_G['setting']['siteuniqueid'].'|'.$uid.(empty($appid)?'':'|'.$appid)), 8, 16);
  1431. }
  1432. function getposttablebytid($tids, $primary = 0) {
  1433. return table_forum_post::getposttablebytid($tids, $primary);
  1434. }
  1435. function getposttable($tableid = 0, $prefix = false) {
  1436. return table_forum_post::getposttable($tableid, $prefix);
  1437. }
  1438. function memory($cmd, $key='', $value='', $ttl = 0, $prefix = '') {
  1439. if($cmd == 'check') {
  1440. return C::memory()->enable ? C::memory()->type : '';
  1441. } elseif(C::memory()->enable && in_array($cmd, array('set', 'get', 'rm', 'inc', 'dec'))) {
  1442. if(defined('DISCUZ_DEBUG') && DISCUZ_DEBUG) {
  1443. if(is_array($key)) {
  1444. foreach($key as $k) {
  1445. C::memory()->debug[$cmd][] = ($cmd == 'get' || $cmd == 'rm' ? $value : '').$prefix.$k;
  1446. }
  1447. } else {
  1448. C::memory()->debug[$cmd][] = ($cmd == 'get' || $cmd == 'rm' ? $value : '').$prefix.$key;
  1449. }
  1450. }
  1451. switch ($cmd) {
  1452. case 'set': return C::memory()->set($key, $value, $ttl, $prefix); break;
  1453. case 'get': return C::memory()->get($key, $value); break;
  1454. case 'rm': return C::memory()->rm($key, $value); break;
  1455. case 'inc': return C::memory()->inc($key, $value ? $value : 1); break;
  1456. case 'dec': return C::memory()->dec($key, $value ? $value : -1); break;
  1457. }
  1458. }
  1459. return null;
  1460. }
  1461. function ipaccess($ip, $accesslist) {
  1462. return preg_match("/^(".str_replace(array("\r\n", ' '), array('|', ''), preg_quote($accesslist, '/')).")/", $ip);
  1463. }
  1464. function ipbanned($onlineip) {
  1465. global $_G;
  1466. if($_G['setting']['ipaccess'] && !ipaccess($onlineip, $_G['setting']['ipaccess'])) {
  1467. return TRUE;
  1468. }
  1469. loadcache('ipbanned');
  1470. if(empty($_G['cache']['ipbanned'])) {
  1471. return FALSE;
  1472. } else {
  1473. if($_G['cache']['ipbanned']['expiration'] < TIMESTAMP) {
  1474. require_once libfile('function/cache');
  1475. updatecache('ipbanned');
  1476. }
  1477. return preg_match("/^(".$_G['cache']['ipbanned']['regexp'].")$/", $onlineip);
  1478. }
  1479. }
  1480. function getcount($tablename, $condition) {
  1481. if(empty($condition)) {
  1482. $where = '1';
  1483. } elseif(is_array($condition)) {
  1484. $where = DB::implode_field_value($condition, ' AND ');
  1485. } else {
  1486. $where = $condition;
  1487. }
  1488. $ret = intval(DB::result_first("SELECT COUNT(*) AS num FROM ".DB::table($tablename)." WHERE $where"));
  1489. return $ret;
  1490. }
  1491. function sysmessage($message) {
  1492. helper_sysmessage::show($message);
  1493. }
  1494. function forumperm($permstr, $groupid = 0) {
  1495. global $_G;
  1496. $groupidarray = array($_G['groupid']);
  1497. if($groupid) {
  1498. return preg_match("/(^|\t)(".$groupid.")(\t|$)/", $permstr);
  1499. }
  1500. foreach(explode("\t", $_G['member']['extgroupids']) as $extgroupid) {
  1501. if($extgroupid = intval(trim($extgroupid))) {
  1502. $groupidarray[] = $extgroupid;
  1503. }
  1504. }
  1505. if($_G['setting']['verify']['enabled']) {
  1506. getuserprofile('verify1');
  1507. foreach($_G['setting']['verify'] as $vid => $verify) {
  1508. if($verify['available'] && $_G['member']['verify'.$vid] == 1) {
  1509. $groupidarray[] = 'v'.$vid;
  1510. }
  1511. }
  1512. }
  1513. return preg_match("/(^|\t)(".implode('|', $groupidarray).")(\t|$)/", $permstr);
  1514. }
  1515. function checkperm($perm) {
  1516. global $_G;
  1517. return defined('IN_ADMINCP') ? true : (empty($_G['group'][$perm])?'':$_G['group'][$perm]);
  1518. }
  1519. function periodscheck($periods, $showmessage = 1) {
  1520. global $_G;
  1521. if(($periods == 'postmodperiods' || $periods == 'postbanperiods') && ($_G['setting']['postignorearea'] || $_G['setting']['postignoreip'])) {
  1522. if($_G['setting']['postignoreip']) {
  1523. foreach(explode("\n", $_G['setting']['postignoreip']) as $ctrlip) {
  1524. if(preg_match("/^(".preg_quote(($ctrlip = trim($ctrlip)), '/').")/", $_G['clientip'])) {
  1525. return false;
  1526. break;
  1527. }
  1528. }
  1529. }
  1530. if($_G['setting']['postignorearea']) {
  1531. $location = $whitearea = '';
  1532. require_once libfile('function/misc');
  1533. $location = trim(convertip($_G['clientip'], "./"));
  1534. if($location) {
  1535. $whitearea = preg_quote(trim($_G['setting']['postignorearea']), '/');
  1536. $whitearea = str_replace(array("\\*"), array('.*'), $whitearea);
  1537. $whitearea = '.*'.$whitearea.'.*';
  1538. $whitearea = '/^('.str_replace(array("\r\n", ' '), array('.*|.*', ''), $whitearea).')$/i';
  1539. if(@preg_match($whitearea, $location)) {
  1540. return false;
  1541. }
  1542. }
  1543. }
  1544. }
  1545. if(!$_G['group']['disableperiodctrl'] && $_G['setting'][$periods]) {
  1546. $now = dgmdate(TIMESTAMP, 'G.i', $_G['setting']['timeoffset']);
  1547. foreach(explode("\r\n", str_replace(':', '.', $_G['setting'][$periods])) as $period) {
  1548. list($periodbegin, $periodend) = explode('-', $period);
  1549. if(($periodbegin > $periodend && ($now >= $periodbegin || $now < $periodend)) || ($periodbegin < $periodend && $now >= $periodbegin && $now < $periodend)) {
  1550. $banperiods = str_replace("\r\n", ', ', $_G['setting'][$periods]);
  1551. if($showmessage) {
  1552. showmessage('period_nopermission', NULL, array('banperiods' => $banperiods), array('login' => 1));
  1553. } else {
  1554. return TRUE;
  1555. }
  1556. }
  1557. }
  1558. }
  1559. return FALSE;
  1560. }
  1561. function cknewuser($return=0) {
  1562. global $_G;
  1563. $result = true;
  1564. if(!$_G['uid']) return true;
  1565. if(checkperm('disablepostctrl')) {
  1566. return $result;
  1567. }
  1568. $ckuser = $_G['member'];
  1569. if($_G['setting']['newbiespan'] && $_G['timestamp']-$ckuser['regdate']<$_G['setting']['newbiespan']*60) {
  1570. if(empty($return)) showmessage('no_privilege_newbiespan', '', array('newbiespan' => $_G['setting']['newbiespan']), array());
  1571. $result = false;
  1572. }
  1573. if($_G['setting']['need_avatar'] && empty($ckuser['avatarstatus'])) {
  1574. if(empty($return)) showmessage('no_privilege_avatar', '', array(), array());
  1575. $result = false;
  1576. }
  1577. if($_G['setting']['need_email'] && empty($ckuser['emailstatus'])) {
  1578. if(empty($return)) showmessage('no_privilege_email', '', array(), array());
  1579. $result = false;
  1580. }
  1581. if($_G['setting']['need_friendnum']) {
  1582. space_merge($ckuser, 'count');
  1583. if($ckuser['friends'] < $_G['setting']['need_friendnum']) {
  1584. if(empty($return)) showmessage('no_privilege_friendnum', '', array('friendnum' => $_G['setting']['need_friendnum']), array());
  1585. $result = false;
  1586. }
  1587. }
  1588. return $result;
  1589. }
  1590. function manyoulog($logtype, $uids, $action, $fid = '') {
  1591. helper_manyou::manyoulog($logtype, $uids, $action, $fid);
  1592. }
  1593. function useractionlog($uid, $action) {
  1594. return helper_log::useractionlog($uid, $action);
  1595. }
  1596. function getuseraction($var) {
  1597. return helper_log::getuseraction($var);
  1598. }
  1599. function getuserapp($panel = 0) {
  1600. return helper_manyou::getuserapp($panel);
  1601. }
  1602. function getmyappiconpath($appid, $iconstatus=0) {
  1603. return helper_manyou::getmyappiconpath($appid, $iconstatus);
  1604. }
  1605. function getexpiration() {
  1606. global $_G;
  1607. $date = getdate($_G['timestamp']);
  1608. return mktime(0, 0, 0, $date['mon'], $date['mday'], $date['year']) + 86400;
  1609. }
  1610. function return_bytes($val) {
  1611. $val = trim($val);
  1612. $last = strtolower($val{strlen($val)-1});
  1613. switch($last) {
  1614. case 'g': $val *= 1024;
  1615. case 'm': $val *= 1024;
  1616. case 'k': $val *= 1024;
  1617. }
  1618. return $val;
  1619. }
  1620. function iswhitelist($host) {
  1621. global $_G;
  1622. static $iswhitelist = array();
  1623. if(isset($iswhitelist[$host])) {
  1624. return $iswhitelist[$host];
  1625. }
  1626. $hostlen = strlen($host);
  1627. $iswhitelist[$host] = false;
  1628. if(!$_G['cache']['domainwhitelist']) {
  1629. loadcache('domainwhitelist');
  1630. }
  1631. if(is_array($_G['cache']['domainwhitelist'])) foreach($_G['cache']['domainwhitelist'] as $val) {
  1632. $domainlen = strlen($val);
  1633. if($domainlen > $hostlen) {
  1634. continue;
  1635. }
  1636. if(substr($host, -$domainlen) == $val) {
  1637. $iswhitelist[$host] = true;
  1638. break;
  1639. }
  1640. }
  1641. if($iswhitelist[$host] == false) {
  1642. $iswhitelist[$host] = $host == $_SERVER['HTTP_HOST'];
  1643. }
  1644. return $iswhitelist[$host];
  1645. }
  1646. function getattachtablebyaid($aid) {
  1647. $attach = C::t('forum_attachment')->fetch($aid);
  1648. $tableid = $attach['tableid'];
  1649. return 'forum_attachment_'.($tableid >= 0 && $tableid < 10 ? intval($tableid) : 'unused');
  1650. }
  1651. function getattachtableid($tid) {
  1652. $tid = (string)$tid;
  1653. return intval($tid{strlen($tid)-1});
  1654. }
  1655. function getattachtablebytid($tid) {
  1656. return 'forum_attachment_'.getattachtableid($tid);
  1657. }
  1658. function getattachtablebypid($pid) {
  1659. $tableid = DB::result_first("SELECT tableid FROM ".DB::table('forum_attachment')." WHERE pid='$pid' LIMIT 1");
  1660. return 'forum_attachment_'.($tableid >= 0 && $tableid < 10 ? intval($tableid) : 'unused');
  1661. }
  1662. function getattachnewaid($uid = 0) {
  1663. global $_G;
  1664. $uid = !$uid ? $_G['uid'] : $uid;
  1665. return C::t('forum_attachment')->insert(array('tid' => 0, 'pid' => 0, 'uid' => $uid, 'tableid' => 127), true);
  1666. }
  1667. function get_seosetting($page, $data = array(), $defset = array()) {
  1668. return helper_seo::get_seosetting($page, $data, $defset);
  1669. }
  1670. function getimgthumbname($fileStr, $extend='.thumb.jpg', $holdOldExt=true) {
  1671. if(empty($fileStr)) {
  1672. return '';
  1673. }
  1674. if(!$holdOldExt) {
  1675. $fileStr = substr($fileStr, 0, strrpos($fileStr, '.'));
  1676. }
  1677. $extend = strstr($extend, '.') ? $extend : '.'.$extend;
  1678. return $fileStr.$extend;
  1679. }
  1680. function updatemoderate($idtype, $ids, $status = 0) {
  1681. helper_form::updatemoderate($idtype, $ids, $status);
  1682. }
  1683. function userappprompt() {
  1684. global $_G;
  1685. if($_G['setting']['my_app_status'] && $_G['setting']['my_openappprompt'] && empty($_G['cookie']['userappprompt'])) {
  1686. $sid = $_G['setting']['my_siteid'];
  1687. $ts = $_G['timestamp'];
  1688. $key = md5($sid.$ts.$_G['setting']['my_sitekey']);
  1689. $uchId = $_G['uid'] ? $_G['uid'] : 0;
  1690. 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>';
  1691. }
  1692. }
  1693. function dintval($int, $allowarray = false) {
  1694. $ret = intval($int);
  1695. if($int == $ret || !$allowarray && is_array($int)) return $ret;
  1696. if($allowarray && is_array($int)) {
  1697. foreach($int as &$v) {
  1698. $v = dintval($v, true);
  1699. }
  1700. return $int;
  1701. } elseif($int <= 0xffffffff) {
  1702. $l = strlen($int);
  1703. $m = substr($int, 0, 1) == '-' ? 1 : 0;
  1704. if(($l - $m) === strspn($int,'0987654321', $m)) {
  1705. return $int;
  1706. }
  1707. }
  1708. return $ret;
  1709. }
  1710. function makeSearchSignUrl() {
  1711. return getglobal('setting/my_search_data/status') ? helper_manyou::makeSearchSignUrl() : array();
  1712. }
  1713. function get_related_link($extent) {
  1714. return helper_seo::get_related_link($extent);
  1715. }
  1716. function parse_related_link($content, $extent) {
  1717. return helper_seo::parse_related_link($content, $extent);
  1718. }
  1719. function check_diy_perm($topic = array(), $flag = '') {
  1720. static $ret;
  1721. if(!isset($ret)) {
  1722. global $_G;
  1723. $common = !empty($_G['style']['tplfile']) || $_GET['inajax'];
  1724. $blockallow = getstatus($_G['member']['allowadmincp'], 4) || getstatus($_G['member']['allowadmincp'], 5) || getstatus($_G['member']['allowadmincp'], 6);
  1725. $ret['data'] = $common && $blockallow;
  1726. $ret['layout'] = $common && ($_G['group']['allowdiy'] || (
  1727. CURMODULE === 'topic' && ($_G['group']['allowmanagetopic'] || $_G['group']['allowaddtopic'] && $topic && $topic['uid'] == $_G['uid'])
  1728. ));
  1729. }
  1730. return empty($flag) ? $ret['data'] || $ret['layout'] : $ret[$flag];
  1731. }
  1732. function strhash($string, $operation = 'DECODE', $key = '') {
  1733. $key = md5($key != '' ? $key : getglobal('authkey'));
  1734. if($operation == 'DECODE') {
  1735. $hashcode = gzuncompress(base64_decode(($string)));
  1736. $string = substr($hashcode, 0, -16);
  1737. $hash = substr($hashcode, -16);
  1738. unset($hashcode);
  1739. }
  1740. $vkey = substr(md5($string.substr($key, 0, 16)), 4, 8).substr(md5($string.substr($key, 16, 16)), 18, 8);
  1741. if($operation == 'DECODE') {
  1742. return $hash == $vkey ? $string : '';
  1743. }
  1744. return base64_encode(gzcompress($string.$vkey));
  1745. }
  1746. function dunserialize($data) {
  1747. if(($ret = unserialize($data)) === false) {
  1748. $ret = unserialize(stripslashes($data));
  1749. }
  1750. return $ret;
  1751. }
  1752. function browserversion($type) {
  1753. static $return = array();
  1754. static $types = array('ie' => 'msie', 'firefox' => '', 'chrome' => '', 'opera' => '', 'safari' => '', 'mozilla' => '', 'webkit' => '', 'maxthon' => '', 'qq' => 'qqbrowser');
  1755. if(!$return) {
  1756. $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
  1757. $other = 1;
  1758. foreach($types as $i => $v) {
  1759. $v = $v ? $v : $i;
  1760. if(strpos($useragent, $v) !== false) {
  1761. preg_match('/'.$v.'(\/|\s)([\d\.]+)/i', $useragent, $matches);
  1762. $ver = $matches[2];
  1763. $other = $ver !== 0 && $v != 'mozilla' ? 0 : $other;
  1764. } else {
  1765. $ver = 0;
  1766. }
  1767. $return[$i] = $ver;
  1768. }
  1769. $return['other'] = $other;
  1770. }
  1771. return $return[$type];
  1772. }
  1773. function currentlang() {
  1774. $charset = strtoupper(CHARSET);
  1775. if($charset == 'GBK') {
  1776. return 'SC_GBK';
  1777. } elseif($charset == 'BIG5') {
  1778. return 'TC_BIG5';
  1779. } elseif($charset == 'UTF-8') {
  1780. global $_G;
  1781. if($_G['config']['output']['language'] == 'zh_cn') {
  1782. return 'SC_UTF8';
  1783. } elseif ($_G['config']['output']['language'] == 'zh_tw') {
  1784. return 'TC_UTF8';
  1785. }
  1786. } else {
  1787. return '';
  1788. }
  1789. }
  1790. ?>