PageRenderTime 730ms CodeModel.GetById 101ms app.highlight 409ms RepoModel.GetById 144ms 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

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file