PageRenderTime 112ms CodeModel.GetById 3ms app.highlight 94ms RepoModel.GetById 1ms app.codeStats 1ms

/phpcms/libs/functions/global.func.php

https://github.com/sinfey69/cms
PHP | 1701 lines | 1157 code | 98 blank | 446 comment | 321 complexity | 46f64dc2a266228146f836d7c77781a9 MD5 | raw file
   1<?php
   2/**
   3 *  global.func.php 公共函数库
   4 *
   5 * @copyright			(C) 2005-2010 PHPCMS
   6 * @license				http://www.phpcms.cn/license/
   7 * @lastmodify			2010-6-1
   8 */
   9
  10/**
  11 * 返回经addslashes处理过的字符串或数组
  12 * @param $string 需要处理的字符串或数组
  13 * @return mixed
  14 */
  15function new_addslashes($string){
  16	if(!is_array($string)) return addslashes($string);
  17	foreach($string as $key => $val) $string[$key] = new_addslashes($val);
  18	return $string;
  19}
  20
  21/**
  22 * 返回经stripslashes处理过的字符串或数组
  23 * @param $string 需要处理的字符串或数组
  24 * @return mixed
  25 */
  26function new_stripslashes($string) {
  27	if(!is_array($string)) return stripslashes($string);
  28	foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
  29	return $string;
  30}
  31
  32/**
  33 * 返回经htmlspecialchars处理过的字符串或数组
  34 * @param $obj 需要处理的字符串或数组
  35 * @return mixed
  36 */
  37function new_html_special_chars($string) {
  38	$encoding = 'utf-8';
  39	if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
  40	if(!is_array($string)) return htmlspecialchars($string,ENT_QUOTES,$encoding);
  41	foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
  42	return $string;
  43}
  44
  45function new_html_entity_decode($string) {
  46	$encoding = 'utf-8';
  47	if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
  48	return html_entity_decode($string,ENT_QUOTES,$encoding);
  49}
  50
  51function new_htmlentities($string) {
  52	$encoding = 'utf-8';
  53	if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
  54	return htmlentities($string,ENT_QUOTES,$encoding);
  55}
  56
  57/**
  58 * 安全过滤函数
  59 *
  60 * @param $string
  61 * @return string
  62 */
  63function safe_replace($string) {
  64	$string = str_replace('%20','',$string);
  65	$string = str_replace('%27','',$string);
  66	$string = str_replace('%2527','',$string);
  67	$string = str_replace('*','',$string);
  68	$string = str_replace('"','&quot;',$string);
  69	$string = str_replace("'",'',$string);
  70	$string = str_replace('"','',$string);
  71	$string = str_replace(';','',$string);
  72	$string = str_replace('<','&lt;',$string);
  73	$string = str_replace('>','&gt;',$string);
  74	$string = str_replace("{",'',$string);
  75	$string = str_replace('}','',$string);
  76	$string = str_replace('\\','',$string);
  77	return $string;
  78}
  79
  80/**
  81 * xss过滤函数
  82 *
  83 * @param $string
  84 * @return string
  85 */
  86function remove_xss($string) { 
  87    $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);
  88
  89    $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  90
  91    $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
  92
  93    $parm = array_merge($parm1, $parm2); 
  94
  95	for ($i = 0; $i < sizeof($parm); $i++) { 
  96		$pattern = '/'; 
  97		for ($j = 0; $j < strlen($parm[$i]); $j++) { 
  98			if ($j > 0) { 
  99				$pattern .= '('; 
 100				$pattern .= '(&#[x|X]0([9][a][b]);?)?'; 
 101				$pattern .= '|(&#0([9][10][13]);?)?'; 
 102				$pattern .= ')?'; 
 103			}
 104			$pattern .= $parm[$i][$j]; 
 105		}
 106		$pattern .= '/i';
 107		$string = preg_replace($pattern, ' ', $string); 
 108	}
 109	return $string;
 110}
 111
 112/**
 113 * 过滤ASCII码从0-28的控制字符
 114 * @return String
 115 */
 116function trim_unsafe_control_chars($str) {
 117	$rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
 118	return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
 119}
 120
 121/**
 122 * 格式化文本域内容
 123 *
 124 * @param $string 文本域内容
 125 * @return string
 126 */
 127function trim_textarea($string) {
 128	$string = nl2br ( str_replace ( ' ', '&nbsp;', $string ) );
 129	return $string;
 130}
 131
 132/**
 133 * 将文本格式成适合js输出的字符串
 134 * @param string $string 需要处理的字符串
 135 * @param intval $isjs 是否执行字符串格式化,默认为执行
 136 * @return string 处理后的字符串
 137 */
 138function format_js($string, $isjs = 1) {
 139	$string = addslashes(str_replace(array("\r", "\n", "\t"), array('', '', ''), $string));
 140	return $isjs ? 'document.write("'.$string.'");' : $string;
 141}
 142
 143/**
 144 * 转义 javascript 代码标记
 145 *
 146 * @param $str
 147 * @return mixed
 148 */
 149 function trim_script($str) {
 150	if(is_array($str)){
 151		foreach ($str as $key => $val){
 152			$str[$key] = trim_script($val);
 153		}
 154 	}else{
 155 		$str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str );
 156		$str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str );
 157		$str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str );
 158		$str = str_replace ( 'javascript:', 'javascript:', $str );
 159 	}
 160	return $str;
 161}
 162/**
 163 * 获取当前页面完整URL地址
 164 */
 165function get_url() {
 166	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
 167	$php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
 168	$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
 169	$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
 170	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
 171}
 172/**
 173 * 字符截取 支持UTF8/GBK
 174 * @param $string
 175 * @param $length
 176 * @param $dot
 177 */
 178function str_cut($string, $length, $dot = '...') {
 179	$strlen = strlen($string);
 180	if($strlen <= $length) return $string;
 181	$string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
 182	$strcut = '';
 183	if(strtolower(CHARSET) == 'utf-8') {
 184		$length = intval($length-strlen($dot)-$length/3);
 185		$n = $tn = $noc = 0;
 186		while($n < strlen($string)) {
 187			$t = ord($string[$n]);
 188			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
 189				$tn = 1; $n++; $noc++;
 190			} elseif(194 <= $t && $t <= 223) {
 191				$tn = 2; $n += 2; $noc += 2;
 192			} elseif(224 <= $t && $t <= 239) {
 193				$tn = 3; $n += 3; $noc += 2;
 194			} elseif(240 <= $t && $t <= 247) {
 195				$tn = 4; $n += 4; $noc += 2;
 196			} elseif(248 <= $t && $t <= 251) {
 197				$tn = 5; $n += 5; $noc += 2;
 198			} elseif($t == 252 || $t == 253) {
 199				$tn = 6; $n += 6; $noc += 2;
 200			} else {
 201				$n++;
 202			}
 203			if($noc >= $length) {
 204				break;
 205			}
 206		}
 207		if($noc > $length) {
 208			$n -= $tn;
 209		}
 210		$strcut = substr($string, 0, $n);
 211		$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
 212	} else {
 213		$dotlen = strlen($dot);
 214		$maxi = $length - $dotlen - 1;
 215		$current_str = '';
 216		$search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
 217		$replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
 218		$search_flip = array_flip($search_arr);
 219		for ($i = 0; $i < $maxi; $i++) {
 220			$current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
 221			if (in_array($current_str, $search_arr)) {
 222				$key = $search_flip[$current_str];
 223				$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
 224			}
 225			$strcut .= $current_str;
 226		}
 227	}
 228	return $strcut.$dot;
 229}
 230
 231
 232
 233/**
 234 * 获取请求ip
 235 *
 236 * @return ip地址
 237 */
 238function ip() {
 239	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
 240		$ip = getenv('HTTP_CLIENT_IP');
 241	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
 242		$ip = getenv('HTTP_X_FORWARDED_FOR');
 243	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
 244		$ip = getenv('REMOTE_ADDR');
 245	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
 246		$ip = $_SERVER['REMOTE_ADDR'];
 247	}
 248	return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
 249}
 250
 251function get_cost_time() {
 252	$microtime = microtime ( TRUE );
 253	return $microtime - SYS_START_TIME;
 254}
 255/**
 256 * 程序执行时间
 257 *
 258 * @return	int	单位ms
 259 */
 260function execute_time() {
 261	$stime = explode ( ' ', SYS_START_TIME );
 262	$etime = explode ( ' ', microtime () );
 263	return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 );
 264}
 265
 266/**
 267* 产生随机字符串
 268*
 269* @param    int        $length  输出长度
 270* @param    string     $chars   可选的 ,默认为 0123456789
 271* @return   string     字符串
 272*/
 273function random($length, $chars = '0123456789') {
 274	$hash = '';
 275	$max = strlen($chars) - 1;
 276	for($i = 0; $i < $length; $i++) {
 277		$hash .= $chars[mt_rand(0, $max)];
 278	}
 279	return $hash;
 280}
 281
 282/**
 283* 将字符串转换为数组
 284*
 285* @param	string	$data	字符串
 286* @return	array	返回数组格式,如果,data为空,则返回空数组
 287*/
 288function string2array($data) {
 289	if($data == '') return array();
 290	@eval("\$array = $data;");
 291	return $array;
 292}
 293/**
 294* 将数组转换为字符串
 295*
 296* @param	array	$data		数组
 297* @param	bool	$isformdata	如果为0,则不使用new_stripslashes处理,可选参数,默认为1
 298* @return	string	返回字符串,如果,data为空,则返回空
 299*/
 300function array2string($data, $isformdata = 1) {
 301	if($data == '') return '';
 302	if($isformdata) $data = new_stripslashes($data);
 303	return addslashes(var_export($data, TRUE));
 304}
 305
 306/**
 307* 转换字节数为其他单位
 308*
 309*
 310* @param	string	$filesize	字节大小
 311* @return	string	返回大小
 312*/
 313function sizecount($filesize) {
 314	if ($filesize >= 1073741824) {
 315		$filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
 316	} elseif ($filesize >= 1048576) {
 317		$filesize = round($filesize / 1048576 * 100) / 100 .' MB';
 318	} elseif($filesize >= 1024) {
 319		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
 320	} else {
 321		$filesize = $filesize.' Bytes';
 322	}
 323	return $filesize;
 324}
 325/**
 326* 字符串加密、解密函数
 327*
 328*
 329* @param	string	$txt		字符串
 330* @param	string	$operation	ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE,
 331* @param	string	$key		密钥:数字、字母、下划线
 332* @param	string	$expiry		过期时间
 333* @return	string
 334*/
 335function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
 336	$key_length = 4;
 337	$key = md5($key != '' ? $key : pc_base::load_config('system', 'auth_key'));
 338	$fixedkey = md5($key);
 339	$egiskeys = md5(substr($fixedkey, 16, 16));
 340	$runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
 341	$keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
 342	$string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));
 343
 344	$i = 0; $result = '';
 345	$string_length = strlen($string);
 346	for ($i = 0; $i < $string_length; $i++){
 347		$result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
 348	}
 349	if($operation == 'ENCODE') {
 350		return $runtokey . str_replace('=', '', base64_encode($result));
 351	} else {
 352		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
 353			return substr($result, 26);
 354		} else {
 355			return '';
 356		}
 357	}
 358}
 359/**
 360* 语言文件处理
 361*
 362* @param	string		$language	标示符
 363* @param	array		$pars	转义的数组,二维数组 ,'key1'=>'value1','key2'=>'value2',
 364* @param	string		$modules 多个模块之间用半角逗号隔开,如:member,guestbook
 365* @return	string		语言字符
 366*/
 367function L($language = 'no_language',$pars = array(), $modules = '') {
 368	static $LANG = array();
 369	static $LANG_MODULES = array();
 370	static $lang = '';
 371	if(defined('IN_ADMIN')) {
 372		$lang = SYS_STYLE ? SYS_STYLE : 'zh-cn';
 373	} else {
 374		$lang = pc_base::load_config('system','lang');
 375	}
 376	if(!$LANG) {
 377		require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system.lang.php';
 378		if(defined('IN_ADMIN')) require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system_menu.lang.php';
 379		if(file_exists(PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php')) require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php';
 380	}
 381	if(!empty($modules)) {
 382		$modules = explode(',',$modules);
 383		foreach($modules AS $m) {
 384			if(!isset($LANG_MODULES[$m])) require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.$m.'.lang.php';
 385		}
 386	}
 387	if(!array_key_exists($language,$LANG)) {
 388		return $language;
 389	} else {
 390		$language = $LANG[$language];
 391		if($pars) {
 392			foreach($pars AS $_k=>$_v) {
 393				$language = str_replace('{'.$_k.'}',$_v,$language);
 394			}
 395		}
 396		return $language;
 397	}
 398}
 399
 400/**
 401 * 模板调用
 402 *
 403 * @param $module
 404 * @param $template
 405 * @param $istag
 406 * @return unknown_type
 407 */
 408function template($module = 'content', $template = 'index', $style = '') {
 409
 410	if(strpos($module, 'plugin/')!== false) {
 411		$plugin = str_replace('plugin/', '', $module);
 412		return p_template($plugin, $template,$style);
 413	}
 414	$module = str_replace('/', DIRECTORY_SEPARATOR, $module);
 415	if(!empty($style) && preg_match('/([a-z0-9\-_]+)/is',$style)) {
 416	} elseif (empty($style) && !defined('STYLE')) {
 417		if(defined('SITEID')) {
 418			$siteid = SITEID;
 419		} else {
 420			$siteid = param::get_cookie('siteid');
 421		}
 422		if (!$siteid) $siteid = 1;
 423		$sitelist = getcache('sitelist','commons');
 424		if(!empty($siteid)) {
 425			$style = $sitelist[$siteid]['default_style'];
 426		}
 427	} elseif (empty($style) && defined('STYLE')) {
 428		$style = STYLE;
 429	} else {
 430		$style = 'default';
 431	}
 432	if(!$style) $style = 'default';
 433	$template_cache = pc_base::load_sys_class('template_cache');
 434	$compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
 435	if(file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
 436		if(!file_exists($compiledtplfile) || (@filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > @filemtime($compiledtplfile))) {
 437			$template_cache->template_compile($module, $template, $style);
 438		}
 439	} else {
 440		$compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
 441		if(!file_exists($compiledtplfile) || (file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile))) {
 442			$template_cache->template_compile($module, $template, 'default');
 443		} elseif (!file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
 444			showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html');
 445		}
 446	}
 447	return $compiledtplfile;
 448}
 449
 450/**
 451 * 输出自定义错误
 452 *
 453 * @param $errno 错误号
 454 * @param $errstr 错误描述
 455 * @param $errfile 报错文件地址
 456 * @param $errline 错误行号
 457 * @return string 错误提示
 458 */
 459
 460function my_error_handler($errno, $errstr, $errfile, $errline) {
 461	if($errno==8) return '';
 462	$errfile = str_replace(PHPCMS_PATH,'',$errfile);
 463	if(pc_base::load_config('system','errorlog')) {
 464		error_log('<?php exit;?>'.date('m-d H:i:s',SYS_TIME).' | '.$errno.' | '.str_pad($errstr,30).' | '.$errfile.' | '.$errline."\r\n", 3, CACHE_PATH.'error_log.php');
 465	} else {
 466		$str = '<div style="font-size:12px;text-align:left; border-bottom:1px solid #9cc9e0; border-right:1px solid #9cc9e0;padding:1px 4px;color:#000000;font-family:Arial, Helvetica,sans-serif;"><span>errorno:' . $errno . ',str:' . $errstr . ',file:<font color="blue">' . $errfile . '</font>,line' . $errline .'<br /><a href="http://faq.phpcms.cn/?type=file&errno='.$errno.'&errstr='.urlencode($errstr).'&errfile='.urlencode($errfile).'&errline='.$errline.'" target="_blank" style="color:red">Need Help?</a></span></div>';
 467		echo $str;
 468	}
 469}
 470
 471/**
 472 * 提示信息页面跳转,跳转地址如果传入数组,页面会提示多个地址供用户选择,默认跳转地址为数组的第一个值,时间为5秒。
 473 * showmessage('登录成功', array('默认跳转地址'=>'http://www.phpcms.cn'));
 474 * @param string $msg 提示信息
 475 * @param mixed(string/array) $url_forward 跳转地址
 476 * @param int $ms 跳转等待时间
 477 */
 478function showmessage($msg, $url_forward = 'goback', $ms = 1250, $dialog = '', $returnjs = '') {
 479	if(defined('IN_ADMIN')) {
 480		include(admin::admin_tpl('showmessage', 'admin'));
 481	} else {
 482		include(template('content', 'message'));
 483	}
 484	exit;
 485}
 486/**
 487 * 查询字符是否存在于某字符串
 488 *
 489 * @param $haystack 字符串
 490 * @param $needle 要查找的字符
 491 * @return bool
 492 */
 493function str_exists($haystack, $needle)
 494{
 495	return !(strpos($haystack, $needle) === FALSE);
 496}
 497
 498/**
 499 * 取得文件扩展
 500 *
 501 * @param $filename 文件名
 502 * @return 扩展名
 503 */
 504function fileext($filename) {
 505	return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
 506}
 507
 508/**
 509 * 加载模板标签缓存
 510 * @param string $name 缓存名
 511 * @param integer $times 缓存时间
 512 */
 513function tpl_cache($name,$times = 0) {
 514	$filepath = 'tpl_data';
 515	$info = getcacheinfo($name, $filepath);
 516	if (SYS_TIME - $info['filemtime'] >= $times) {
 517		return false;
 518	} else {
 519		return getcache($name,$filepath);
 520	}
 521}
 522
 523/**
 524 * 写入缓存,默认为文件缓存,不加载缓存配置。
 525 * @param $name 缓存名称
 526 * @param $data 缓存数据
 527 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
 528 * @param $type 缓存类型[file,memcache,apc]
 529 * @param $config 配置名称
 530 * @param $timeout 过期时间
 531 */
 532function setcache($name, $data, $filepath='', $type='file', $config='', $timeout=0) {
 533	pc_base::load_sys_class('cache_factory','',0);
 534	if($config) {
 535		$cacheconfig = pc_base::load_config('cache');
 536		$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
 537	} else {
 538		$cache = cache_factory::get_instance()->get_cache($type);
 539	}
 540
 541	return $cache->set($name, $data, $timeout, '', $filepath);
 542}
 543
 544/**
 545 * 读取缓存,默认为文件缓存,不加载缓存配置。
 546 * @param string $name 缓存名称
 547 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
 548 * @param string $config 配置名称
 549 */
 550function getcache($name, $filepath='', $type='file', $config='') {
 551	pc_base::load_sys_class('cache_factory','',0);
 552	if($config) {
 553		$cacheconfig = pc_base::load_config('cache');
 554		$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
 555	} else {
 556		$cache = cache_factory::get_instance()->get_cache($type);
 557	}
 558	return $cache->get($name, '', '', $filepath);
 559}
 560
 561/**
 562 * 删除缓存,默认为文件缓存,不加载缓存配置。
 563 * @param $name 缓存名称
 564 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
 565 * @param $type 缓存类型[file,memcache,apc]
 566 * @param $config 配置名称
 567 */
 568function delcache($name, $filepath='', $type='file', $config='') {
 569	pc_base::load_sys_class('cache_factory','',0);
 570	if($config) {
 571		$cacheconfig = pc_base::load_config('cache');
 572		$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
 573	} else {
 574		$cache = cache_factory::get_instance()->get_cache($type);
 575	}
 576	return $cache->delete($name, '', '', $filepath);
 577}
 578
 579/**
 580 * 读取缓存,默认为文件缓存,不加载缓存配置。
 581 * @param string $name 缓存名称
 582 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
 583 * @param string $config 配置名称
 584 */
 585function getcacheinfo($name, $filepath='', $type='file', $config='') {
 586	pc_base::load_sys_class('cache_factory');
 587	if($config) {
 588		$cacheconfig = pc_base::load_config('cache');
 589		$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
 590	} else {
 591		$cache = cache_factory::get_instance()->get_cache($type);
 592	}
 593	return $cache->cacheinfo($name, '', '', $filepath);
 594}
 595
 596/**
 597 * 生成sql语句,如果传入$in_cloumn 生成格式为 IN('a', 'b', 'c')
 598 * @param $data 条件数组或者字符串
 599 * @param $front 连接符
 600 * @param $in_column 字段名称
 601 * @return string
 602 */
 603function to_sqls($data, $front = ' AND ', $in_column = false) {
 604	if($in_column && is_array($data)) {
 605		$ids = '\''.implode('\',\'', $data).'\'';
 606		$sql = "$in_column IN ($ids)";
 607		return $sql;
 608	} else {
 609		if ($front == '') {
 610			$front = ' AND ';
 611		}
 612		if(is_array($data) && count($data) > 0) {
 613			$sql = '';
 614			foreach ($data as $key => $val) {
 615				$sql .= $sql ? " $front `$key` = '$val' " : " `$key` = '$val' ";
 616			}
 617			return $sql;
 618		} else {
 619			return $data;
 620		}
 621	}
 622}
 623
 624/**
 625 * 分页函数
 626 *
 627 * @param $num 信息总数
 628 * @param $curr_page 当前分页
 629 * @param $perpage 每页显示数
 630 * @param $urlrule URL规则
 631 * @param $array 需要传递的数组,用于增加额外的方法
 632 * @return 分页
 633 */
 634function pages($num, $curr_page, $perpage = 20, $urlrule = '', $array = array(),$setpages = 10) {
 635	if(defined('URLRULE') && $urlrule == '') {
 636		$urlrule = URLRULE;
 637		$array = $GLOBALS['URL_ARRAY'];
 638	} elseif($urlrule == '') {
 639		$urlrule = url_par('page={$page}');
 640	}
 641	$multipage = '';
 642	if($num > $perpage) {
 643		$page = $setpages+1;
 644		$offset = ceil($setpages/2-1);
 645		$pages = ceil($num / $perpage);
 646		if (defined('IN_ADMIN') && !defined('PAGES')) define('PAGES', $pages);
 647		$from = $curr_page - $offset;
 648		$to = $curr_page + $offset;
 649		$more = 0;
 650		if($page >= $pages) {
 651			$from = 2;
 652			$to = $pages-1;
 653		} else {
 654			if($from <= 1) {
 655				$to = $page-1;
 656				$from = 2;
 657			}  elseif($to >= $pages) {
 658				$from = $pages-($page-2);
 659				$to = $pages-1;
 660			}
 661			$more = 1;
 662		}
 663		$multipage .= '<a class="a1">'.$num.L('page_item').'</a>';
 664		if($curr_page>0) {
 665			$multipage .= ' <a href="'.pageurl($urlrule, $curr_page-1, $array).'" class="a1">'.L('previous').'</a>';
 666			if($curr_page==1) {
 667				$multipage .= ' <span>1</span>';
 668			} elseif($curr_page>6 && $more) {
 669				$multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>..';
 670			} else {
 671				$multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>';
 672			}
 673		}
 674		for($i = $from; $i <= $to; $i++) {
 675			if($i != $curr_page) {
 676				$multipage .= ' <a href="'.pageurl($urlrule, $i, $array).'">'.$i.'</a>';
 677			} else {
 678				$multipage .= ' <span>'.$i.'</span>';
 679			}
 680		}
 681		if($curr_page<$pages) {
 682			if($curr_page<$pages-5 && $more) {
 683				$multipage .= ' ..<a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
 684			} else {
 685				$multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
 686			}
 687		} elseif($curr_page==$pages) {
 688			$multipage .= ' <span>'.$pages.'</span> <a href="'.pageurl($urlrule, $curr_page, $array).'" class="a1">'.L('next').'</a>';
 689		} else {
 690			$multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
 691		}
 692	}
 693	return $multipage;
 694}
 695/**
 696 * 返回分页路径
 697 *
 698 * @param $urlrule 分页规则
 699 * @param $page 当前页
 700 * @param $array 需要传递的数组,用于增加额外的方法
 701 * @return 完整的URL路径
 702 */
 703function pageurl($urlrule, $page, $array = array()) {
 704	if(strpos($urlrule, '~')) {
 705		$urlrules = explode('~', $urlrule);
 706		$urlrule = $page < 2 ? $urlrules[0] : $urlrules[1];
 707	}
 708	$findme = array('{$page}');
 709	$replaceme = array($page);
 710	if (is_array($array)) foreach ($array as $k=>$v) {
 711		$findme[] = '{$'.$k.'}';
 712		$replaceme[] = $v;
 713	}
 714	$url = str_replace($findme, $replaceme, $urlrule);
 715	$url = str_replace(array('http://','//','~'), array('~','/','http://'), $url);
 716	return $url;
 717}
 718
 719/**
 720 * URL路径解析,pages 函数的辅助函数
 721 *
 722 * @param $par 传入需要解析的变量 默认为,page={$page}
 723 * @param $url URL地址
 724 * @return URL
 725 */
 726function url_par($par, $url = '') {
 727	if($url == '') $url = get_url();
 728	$pos = strpos($url, '?');
 729	if($pos === false) {
 730		$url .= '?'.$par;
 731	} else {
 732		$querystring = substr(strstr($url, '?'), 1);
 733		parse_str($querystring, $pars);
 734		$query_array = array();
 735		foreach($pars as $k=>$v) {
 736			if($k != 'page') $query_array[$k] = $v;
 737		}
 738		$querystring = http_build_query($query_array).'&'.$par;
 739		$url = substr($url, 0, $pos).'?'.$querystring;
 740	}
 741	return $url;
 742}
 743
 744/**
 745 * 判断email格式是否正确
 746 * @param $email
 747 */
 748function is_email($email) {
 749	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
 750}
 751
 752/**
 753 * iconv 编辑转换
 754 */
 755if (!function_exists('iconv')) {
 756	function iconv($in_charset, $out_charset, $str) {
 757		$in_charset = strtoupper($in_charset);
 758		$out_charset = strtoupper($out_charset);
 759		if (function_exists('mb_convert_encoding')) {
 760			return mb_convert_encoding($str, $out_charset, $in_charset);
 761		} else {
 762			pc_base::load_sys_func('iconv');
 763			$in_charset = strtoupper($in_charset);
 764			$out_charset = strtoupper($out_charset);
 765			if ($in_charset == 'UTF-8' && ($out_charset == 'GBK' || $out_charset == 'GB2312')) {
 766				return utf8_to_gbk($str);
 767			}
 768			if (($in_charset == 'GBK' || $in_charset == 'GB2312') && $out_charset == 'UTF-8') {
 769				return gbk_to_utf8($str);
 770			}
 771			return $str;
 772		}
 773	}
 774}
 775
 776/**
 777 * 代码广告展示函数
 778 * @param intval $siteid 所属站点
 779 * @param intval $id 广告ID
 780 * @return 返回广告代码
 781 */
 782function show_ad($siteid, $id) {
 783	$siteid = intval($siteid);
 784	$id = intval($id);
 785	if(!$id || !$siteid) return false;
 786	$p = pc_base::load_model('poster_model');
 787	$r = $p->get_one(array('spaceid'=>$id, 'siteid'=>$siteid), 'disabled, setting', '`id` ASC');
 788	if ($r['disabled']) return '';
 789	if ($r['setting']) {
 790		$c = string2array($r['setting']);
 791	} else {
 792		$r['code'] = '';
 793	}
 794	return $c['code'];
 795}
 796
 797/**
 798 * 获取当前的站点ID
 799 */
 800function get_siteid() {
 801	static $siteid;
 802	if (!empty($siteid)) return $siteid;
 803	if (defined('IN_ADMIN')) {
 804		if ($d = param::get_cookie('siteid')) {
 805			$siteid = $d;
 806		} else {
 807			return '';
 808		}
 809	} else {
 810		$data = getcache('sitelist', 'commons');
 811		if(!is_array($data)) return '1';
 812		$site_url = SITE_PROTOCOL.SITE_URL;
 813		foreach ($data as $v) {
 814			if ($v['url'] == $site_url.'/') $siteid = $v['siteid'];
 815		}
 816	}
 817	if (empty($siteid)) $siteid = 1;
 818	return $siteid;
 819}
 820
 821/**
 822 * 获取用户昵称
 823 * 不传入userid取当前用户nickname,如果nickname为空取username
 824 * 传入field,取用户$field字段信息
 825 */
 826function get_nickname($userid='', $field='') {
 827	$return = '';
 828	if(is_numeric($userid)) {
 829		$member_db = pc_base::load_model('member_model');
 830		$memberinfo = $member_db->get_one(array('userid'=>$userid));
 831		if(!empty($field) && $field != 'nickname' && isset($memberinfo[$field]) &&!empty($memberinfo[$field])) {
 832			$return = $memberinfo[$field];
 833		} else {
 834			$return = isset($memberinfo['nickname']) && !empty($memberinfo['nickname']) ? $memberinfo['nickname'].'('.$memberinfo['username'].')' : $memberinfo['username'];
 835		}
 836	} else {
 837		if (param::get_cookie('_nickname')) {
 838			$return .= '('.param::get_cookie('_nickname').')';
 839		} else {
 840			$return .= '('.param::get_cookie('_username').')';
 841		}
 842	}
 843	return $return;
 844}
 845
 846/**
 847 * 获取用户信息
 848 * 不传入$field返回用户所有信息,
 849 * 传入field,取用户$field字段信息
 850 */
 851function get_memberinfo($userid, $field='') {
 852	if(!is_numeric($userid)) {
 853		return false;
 854	} else {
 855		static $memberinfo;
 856		if (!isset($memberinfo[$userid])) {
 857			$member_db = pc_base::load_model('member_model');
 858			$memberinfo[$userid] = $member_db->get_one(array('userid'=>$userid));
 859		}
 860		if(!empty($field) && !empty($memberinfo[$userid][$field])) {
 861			return $memberinfo[$userid][$field];
 862		} else {
 863			return $memberinfo[$userid];
 864		}
 865	}
 866}
 867
 868/**
 869 * 通过 username 值,获取用户所有信息
 870 * 获取用户信息
 871 * 不传入$field返回用户所有信息,
 872 * 传入field,取用户$field字段信息
 873 */
 874function get_memberinfo_buyusername($username, $field='') {
 875	if(empty($username)){return false;}
 876	static $memberinfo;
 877	if (!isset($memberinfo[$username])) {
 878		$member_db = pc_base::load_model('member_model');
 879		$memberinfo[$username] = $member_db->get_one(array('username'=>$username));
 880	}
 881	if(!empty($field) && !empty($memberinfo[$username][$field])) {
 882		return $memberinfo[$username][$field];
 883	} else {
 884		return $memberinfo[$username];
 885	}
 886}
 887
 888/**
 889 * 获取用户头像,建议传入phpssouid
 890 * @param $uid 默认为phpssouid
 891 * @param $is_userid $uid是否为v9 userid,如果为真,执行sql查询此用户的phpssouid
 892 * @param $size 头像大小 有四种[30x30 45x45 90x90 180x180] 默认30
 893 */
 894function get_memberavatar($uid, $is_userid='', $size='30') {
 895	if($is_userid) {
 896		$db = pc_base::load_model('member_model');
 897		$memberinfo = $db->get_one(array('userid'=>$uid));
 898		if(isset($memberinfo['phpssouid'])) {
 899			$uid = $memberinfo['phpssouid'];
 900		} else {
 901			return false;
 902		}
 903	}
 904
 905	pc_base::load_app_class('client', 'member', 0);
 906	define('APPID', pc_base::load_config('system', 'phpsso_appid'));
 907	$phpsso_api_url = pc_base::load_config('system', 'phpsso_api_url');
 908	$phpsso_auth_key = pc_base::load_config('system', 'phpsso_auth_key');
 909	$client = new client($phpsso_api_url, $phpsso_auth_key);
 910	$avatar = $client->ps_getavatar($uid);
 911	if(isset($avatar[$size])) {
 912		return $avatar[$size];
 913	} else {
 914		return false;
 915	}
 916}
 917
 918/**
 919 * 调用关联菜单
 920 * @param $linkageid 联动菜单id
 921 * @param $id 生成联动菜单的样式id
 922 * @param $defaultvalue 默认值
 923 */
 924function menu_linkage($linkageid = 0, $id = 'linkid', $defaultvalue = 0) {
 925	$linkageid = intval($linkageid);
 926	$datas = array();
 927	$datas = getcache($linkageid,'linkage');
 928	$infos = $datas['data'];
 929
 930	if($datas['style']=='1') {
 931		$title = $datas['title'];
 932		$container = 'content'.random(3).date('is');
 933		if(!defined('DIALOG_INIT_1')) {
 934			define('DIALOG_INIT_1', 1);
 935			$string .= '<script type="text/javascript" src="'.JS_PATH.'dialog.js"></script>';
 936			//TODO $string .= '<link href="'.CSS_PATH.'dialog.css" rel="stylesheet" type="text/css">';
 937		}
 938		if(!defined('LINKAGE_INIT_1')) {
 939			define('LINKAGE_INIT_1', 1);
 940			$string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/pop.js"></script>';
 941		}
 942		$var_div = $defaultvalue && (ROUTE_A=='edit' || ROUTE_A=='account_manage_info'  || ROUTE_A=='info_publish' || ROUTE_A=='orderinfo') ? menu_linkage_level($defaultvalue,$linkageid,$infos) : $datas['title'];
 943		$var_input = $defaultvalue && (ROUTE_A=='edit' || ROUTE_A=='account_manage_info'  || ROUTE_A=='info_publish') ? '<input type="hidden" name="info['.$id.']" value="'.$defaultvalue.'">' : '<input type="hidden" name="info['.$id.']" value="">';
 944		$string .= '<div name="'.$id.'" value="" id="'.$id.'" class="ib">'.$var_div.'</div>'.$var_input.' <input type="button" name="btn_'.$id.'" class="button" value="'.L('linkage_select').'" onclick="open_linkage(\''.$id.'\',\''.$title.'\','.$container.',\''.$linkageid.'\')">';
 945		$string .= '<script type="text/javascript">';
 946		$string .= 'var returnid_'.$id.'= \''.$id.'\';';
 947		$string .= 'var returnkeyid_'.$id.' = \''.$linkageid.'\';';
 948		$string .=  'var '.$container.' = new Array(';
 949		foreach($infos AS $k=>$v) {
 950			if($v['parentid'] == 0) {
 951				$s[]='new Array(\''.$v['linkageid'].'\',\''.$v['name'].'\',\''.$v['parentid'].'\')';
 952			} else {
 953				continue;
 954			}
 955		}
 956		$s = implode(',',$s);
 957		$string .=$s;
 958		$string .= ')';
 959		$string .= '</script>';
 960		
 961	} elseif($datas['style']=='2') {
 962		if(!defined('LINKAGE_INIT_1')) {
 963			define('LINKAGE_INIT_1', 1);
 964			$string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/jquery.ld.js"></script>';
 965		}
 966		$default_txt = '';
 967		if($defaultvalue) {
 968				$default_txt = menu_linkage_level($defaultvalue,$linkageid,$infos);
 969				$default_txt = '["'.str_replace(' > ','","',$default_txt).'"]';
 970		}
 971		$string .= $defaultvalue && (ROUTE_A=='edit' || ROUTE_A=='account_manage_info'  || ROUTE_A=='info_publish') ? '<input type="hidden" name="info['.$id.']"  id="'.$id.'" value="'.$defaultvalue.'">' : '<input type="hidden" name="info['.$id.']"  id="'.$id.'" value="">';
 972
 973		for($i=1;$i<=$datas['setting']['level'];$i++) {
 974			$string .='<select class="pc-select-'.$id.'" name="'.$id.'-'.$i.'" id="'.$id.'-'.$i.'" width="100"><option value="">请选择菜单</option></select> ';
 975		}
 976
 977		$string .= '<script type="text/javascript">
 978					$(function(){
 979						var $ld5 = $(".pc-select-'.$id.'");					  
 980						$ld5.ld({ajaxOptions : {"url" : "'.APP_PATH.'api.php?op=get_linkage&act=ajax_select&keyid='.$linkageid.'"},defaultParentId : 0,style : {"width" : 120}})	 
 981						var ld5_api = $ld5.ld("api");
 982						ld5_api.selected('.$default_txt.');
 983						$ld5.bind("change",onchange);
 984						function onchange(e){
 985							var $target = $(e.target);
 986							var index = $ld5.index($target);
 987							$("#'.$id.'-'.$i.'").remove();
 988							$("#'.$id.'").val($ld5.eq(index).show().val());
 989							index ++;
 990							$ld5.eq(index).show();								}
 991					})
 992		</script>';
 993			
 994	} else {
 995		$title = $defaultvalue ? $infos[$defaultvalue]['name'] : $datas['title'];
 996		$colObj = random(3).date('is');
 997		$string = '';
 998		if(!defined('LINKAGE_INIT')) {
 999			define('LINKAGE_INIT', 1);
1000			$string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/mln.colselect.js"></script>';
1001			if(defined('IN_ADMIN')) {
1002				$string .= '<link href="'.JS_PATH.'linkage/style/admin.css" rel="stylesheet" type="text/css">';
1003			} else {
1004				$string .= '<link href="'.JS_PATH.'linkage/style/css.css" rel="stylesheet" type="text/css">';
1005			}
1006		}
1007		$string .= '<input type="hidden" name="info['.$id.']" value="1"><div id="'.$id.'"></div>';
1008		$string .= '<script type="text/javascript">';
1009		$string .= 'var colObj'.$colObj.' = {"Items":[';
1010
1011		foreach($infos AS $k=>$v) {
1012			$s .= '{"name":"'.$v['name'].'","topid":"'.$v['parentid'].'","colid":"'.$k.'","value":"'.$k.'","fun":function(){}},';
1013		}
1014
1015		$string .= substr($s, 0, -1);
1016		$string .= ']};';
1017		$string .= '$("#'.$id.'").mlnColsel(colObj'.$colObj.',{';
1018		$string .= 'title:"'.$title.'",';
1019		$string .= 'value:"'.$defaultvalue.'",';
1020		$string .= 'width:100';
1021		$string .= '});';
1022		$string .= '</script>';
1023	}
1024	return $string;
1025}
1026
1027/**
1028 * 联动菜单层级
1029 */
1030
1031function menu_linkage_level($linkageid,$keyid,$infos,$result=array()) {
1032	if(array_key_exists($linkageid,$infos)) {
1033		$result[]=$infos[$linkageid]['name'];
1034		return menu_linkage_level($infos[$linkageid]['parentid'],$keyid,$infos,$result);
1035	}
1036	krsort($result);
1037	return implode(' > ',$result);
1038}
1039/**
1040 * 通过catid获取显示菜单完整结构
1041 * @param  $menuid 菜单ID
1042 * @param  $cache_file 菜单缓存文件名称
1043 * @param  $cache_path 缓存文件目录
1044 * @param  $key 取得缓存值的键值名称
1045 * @param  $parentkey 父级的ID
1046 * @param  $linkstring 链接字符
1047 */
1048function menu_level($menuid, $cache_file, $cache_path = 'commons', $key = 'catname', $parentkey = 'parentid', $linkstring = ' > ', $result=array()) {
1049	$menu_arr = getcache($cache_file, $cache_path);
1050	if (array_key_exists($menuid, $menu_arr)) {
1051		$result[] = $menu_arr[$menuid][$key];
1052		return menu_level($menu_arr[$menuid][$parentkey], $cache_file, $cache_path, $key, $parentkey, $linkstring, $result);
1053	}
1054	krsort($result);
1055	return implode($linkstring, $result);
1056}
1057/**
1058 * 通过id获取显示联动菜单
1059 * @param  $linkageid 联动菜单ID
1060 * @param  $keyid 菜单keyid
1061 * @param  $space 菜单间隔符
1062 * @param  $tyoe 1 返回间隔符链接,完整路径名称 3 返回完整路径数组,2返回当前联动菜单名称,4 直接返回ID
1063 * @param  $result 递归使用字段1
1064 * @param  $infos 递归使用字段2
1065 */
1066function get_linkage($linkageid, $keyid, $space = '>', $type = 1, $result = array(), $infos = array()) {
1067	if($space=='' || !isset($space))$space = '>';
1068	if(!$infos) {
1069		$datas = getcache($keyid,'linkage');
1070		$infos = $datas['data'];
1071	}
1072	if($type == 1 || $type == 3 || $type == 4) {
1073		if(array_key_exists($linkageid,$infos)) {
1074			$result[]= ($type == 1) ? $infos[$linkageid]['name'] : (($type == 4) ? $linkageid :$infos[$linkageid]);
1075			return get_linkage($infos[$linkageid]['parentid'], $keyid, $space, $type, $result, $infos);
1076		} else {
1077			if(count($result)>0) {
1078				krsort($result);
1079				if($type == 1 || $type == 4) $result = implode($space,$result);
1080				return $result;
1081			} else {
1082				return $result;
1083			}
1084		}
1085	} else {
1086		return $infos[$linkageid]['name'];
1087	}
1088}
1089/**
1090 * IE浏览器判断
1091 */
1092
1093function is_ie() {
1094	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
1095	if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
1096	if(strpos($useragent, 'msie ') !== false) return true;
1097	return false;
1098}
1099
1100
1101/**
1102 * 文件下载
1103 * @param $filepath 文件路径
1104 * @param $filename 文件名称
1105 */
1106
1107function file_down($filepath, $filename = '') {
1108	if(!$filename) $filename = basename($filepath);
1109	if(is_ie()) $filename = rawurlencode($filename);
1110	$filetype = fileext($filename);
1111	$filesize = sprintf("%u", filesize($filepath));
1112	if(ob_get_length() !== false) @ob_end_clean();
1113	header('Pragma: public');
1114	header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
1115	header('Cache-Control: no-store, no-cache, must-revalidate');
1116	header('Cache-Control: pre-check=0, post-check=0, max-age=0');
1117	header('Content-Transfer-Encoding: binary');
1118	header('Content-Encoding: none');
1119	header('Content-type: '.$filetype);
1120	header('Content-Disposition: attachment; filename="'.$filename.'"');
1121	header('Content-length: '.$filesize);
1122	readfile($filepath);
1123	exit;
1124}
1125
1126/**
1127 * 判断字符串是否为utf8编码,英文和半角字符返回ture
1128 * @param $string
1129 * @return bool
1130 */
1131function is_utf8($string) {
1132	return preg_match('%^(?:
1133					[\x09\x0A\x0D\x20-\x7E] # ASCII
1134					| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
1135					| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
1136					| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
1137					| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
1138					| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
1139					| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
1140					| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
1141					)*$%xs', $string);
1142}
1143
1144/**
1145 * 组装生成ID号
1146 * @param $modules 模块名
1147 * @param $contentid 内容ID
1148 * @param $siteid 站点ID
1149 */
1150function id_encode($modules,$contentid, $siteid) {
1151	return urlencode($modules.'-'.$contentid.'-'.$siteid);
1152}
1153
1154/**
1155 * 解析ID
1156 * @param $id 评论ID
1157 */
1158function id_decode($id) {
1159	return explode('-', $id);
1160}
1161
1162/**
1163 * 对用户的密码进行加密
1164 * @param $password
1165 * @param $encrypt //传入加密串,在修改密码时做认证
1166 * @return array/password
1167 */
1168function password($password, $encrypt='') {
1169	$pwd = array();
1170	$pwd['encrypt'] =  $encrypt ? $encrypt : create_randomstr();
1171	$pwd['password'] = md5(md5(trim($password)).$pwd['encrypt']);
1172	return $encrypt ? $pwd['password'] : $pwd;
1173}
1174/**
1175 * 生成随机字符串
1176 * @param string $lenth 长度
1177 * @return string 字符串
1178 */
1179function create_randomstr($lenth = 6) {
1180	return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
1181}
1182
1183/**
1184 * 检查密码长度是否符合规定
1185 *
1186 * @param STRING $password
1187 * @return 	TRUE or FALSE
1188 */
1189function is_password($password) {
1190	$strlen = strlen($password);
1191	if($strlen >= 6 && $strlen <= 20) return true;
1192	return false;
1193}
1194
1195 /**
1196 * 检测输入中是否含有错误字符
1197 *
1198 * @param char $string 要检查的字符串名称
1199 * @return TRUE or FALSE
1200 */
1201function is_badword($string) {
1202	$badwords = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n","#");
1203	foreach($badwords as $value){
1204		if(strpos($string, $value) !== FALSE) {
1205			return TRUE;
1206		}
1207	}
1208	return FALSE;
1209}
1210
1211/**
1212 * 检查用户名是否符合规定
1213 *
1214 * @param STRING $username 要检查的用户名
1215 * @return 	TRUE or FALSE
1216 */
1217function is_username($username) {
1218	$strlen = strlen($username);
1219	if(is_badword($username) || !preg_match("/^[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/", $username)){
1220		return false;
1221	} elseif ( 20 < $strlen || $strlen < 2 ) {
1222		return false;
1223	}
1224	return true;
1225}
1226
1227/**
1228 * 检查id是否存在于数组中
1229 *
1230 * @param $id
1231 * @param $ids
1232 * @param $s
1233 */
1234function check_in($id, $ids = '', $s = ',') {
1235	if(!$ids) return false;
1236	$ids = explode($s, $ids);
1237	return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);
1238}
1239
1240/**
1241 * 对数据进行编码转换
1242 * @param array/string $data       数组
1243 * @param string $input     需要转换的编码
1244 * @param string $output    转换后的编码
1245 */
1246function array_iconv($data, $input = 'gbk', $output = 'utf-8') {
1247	if (!is_array($data)) {
1248		return iconv($input, $output, $data);
1249	} else {
1250		foreach ($data as $key=>$val) {
1251			if(is_array($val)) {
1252				$data[$key] = array_iconv($val, $input, $output);
1253			} else {
1254				$data[$key] = iconv($input, $output, $val);
1255			}
1256		}
1257		return $data;
1258	}
1259}
1260
1261/**
1262 * 生成缩略图函数
1263 * @param  $imgurl 图片路径
1264 * @param  $width  缩略图宽度
1265 * @param  $height 缩略图高度
1266 * @param  $autocut 是否自动裁剪 默认裁剪,当高度或宽度有一个数值为0是,自动关闭
1267 * @param  $smallpic 无图片是默认图片路径
1268 */
1269function thumb($imgurl, $width = 100, $height = 100 ,$autocut = 1, $smallpic = 'nopic.gif') {
1270	global $image;
1271	$upload_url = pc_base::load_config('system','upload_url');
1272	$upload_path = pc_base::load_config('system','upload_path');
1273	if(empty($imgurl)) return IMG_PATH.$smallpic;
1274	$imgurl_replace= str_replace($upload_url, '', $imgurl);
1275	if(!extension_loaded('gd') || strpos($imgurl_replace, '://')) return $imgurl;
1276	if(!file_exists($upload_path.$imgurl_replace)) return IMG_PATH.$smallpic;
1277
1278	list($width_t, $height_t, $type, $attr) = getimagesize($upload_path.$imgurl_replace);
1279	if($width>=$width_t || $height>=$height_t) return $imgurl;
1280
1281	$newimgurl = dirname($imgurl_replace).'/thumb_'.$width.'_'.$height.'_'.basename($imgurl_replace);
1282
1283	if(file_exists($upload_path.$newimgurl)) return $upload_url.$newimgurl;
1284
1285	if(!is_object($image)) {
1286		pc_base::load_sys_class('image','','0');
1287		$image = new image(1,0);
1288	}
1289	return $image->thumb($upload_path.$imgurl_replace, $upload_path.$newimgurl, $width, $height, '', $autocut) ? $upload_url.$newimgurl : $imgurl;
1290}
1291
1292/**
1293 * 水印添加
1294 * @param $source 原图片路径
1295 * @param $target 生成水印图片途径,默认为空,覆盖原图
1296 * @param $siteid 站点id,系统需根据站点id获取水印信息
1297 */
1298function watermark($source, $target = '',$siteid) {
1299	global $image_w;
1300	if(empty($source)) return $source;
1301	if(!extension_loaded('gd') || strpos($source, '://')) return $source;
1302	if(!$target) $target = $source;
1303	if(!is_object($image_w)){
1304		pc_base::load_sys_class('image','','0');
1305		$image_w = new image(0,$siteid);
1306	}
1307		$image_w->watermark($source, $target);
1308	return $target;
1309}
1310
1311/**
1312 * 当前路径
1313 * 返回指定栏目路径层级
1314 * @param $catid 栏目id
1315 * @param $symbol 栏目间隔符
1316 */
1317function catpos($catid, $symbol=' > '){
1318	$category_arr = array();
1319	$siteids = getcache('category_content','commons');
1320	$siteid = $siteids[$catid];
1321	$category_arr = getcache('category_content_'.$siteid,'commons');
1322	if(!isset($category_arr[$catid])) return '';
1323	$pos = '';
1324	$siteurl = siteurl($category_arr[$catid]['siteid']);
1325	$arrparentid = array_filter(explode(',', $category_arr[$catid]['arrparentid'].','.$catid));
1326	foreach($arrparentid as $catid) {
1327		$url = $category_arr[$catid]['url'];
1328		if(strpos($url, '://') === false) $url = $siteurl.$url;
1329		$pos .= '<a href="'.$url.'">'.$category_arr[$catid]['catname'].'</a>'.$symbol;
1330	}
1331	return $pos;
1332}
1333
1334/**
1335 * 根据catid获取子栏目数据的sql语句
1336 * @param string $module 缓存文件名
1337 * @param intval $catid 栏目ID
1338 */
1339
1340function get_sql_catid($file = 'category_content_1', $catid = 0, $module = 'commons') {
1341	$category = getcache($file,$module);
1342	$catid = intval($catid);
1343	if(!isset($category[$catid])) return false;
1344	return $category[$catid]['child'] ? " `catid` IN(".$category[$catid]['arrchildid'].") " : " `catid`=$catid ";
1345}
1346
1347/**
1348 * 获取子栏目
1349 * @param $parentid 父级id
1350 * @param $type 栏目类型
1351 * @param $self 是否包含本身 0为不包含
1352 * @param $siteid 站点id
1353 */
1354function subcat($parentid = NULL, $type = NULL,$self = '0', $siteid = '') {
1355	if (empty($siteid)) $siteid = get_siteid();
1356	$category = getcache('category_content_'.$siteid,'commons');
1357	foreach($category as $id=>$cat) {
1358		if($cat['siteid'] == $siteid && ($parentid === NULL || $cat['parentid'] == $parentid) && ($type === NULL || $cat['type'] == $type)) $subcat[$id] = $cat;
1359		if($self == 1 && $cat['catid'] == $parentid && !$cat['child'])  $subcat[$id] = $cat;
1360	}
1361	return $subcat;
1362}
1363
1364/**
1365 * 获取内容地址
1366 * @param $catid   栏目ID
1367 * @param $id      文章ID
1368 * @param $allurl  是否以绝对路径返回
1369 */
1370function go($catid,$id, $allurl = 0) {
1371	static $category;
1372	if(empty($category)) {
1373		$siteids = getcache('category_content','commons');
1374		$siteid = $siteids[$catid];
1375		$category = getcache('category_content_'.$siteid,'commons');
1376	}
1377	$id = intval($id);
1378	if(!$id || !isset($category[$catid])) return '';
1379	$modelid = $category[$catid]['modelid'];
1380	if(!$modelid) return '';
1381	$db = pc_base::load_model('content_model');
1382	$db->set_model($modelid);
1383	$r = $db->get_one(array('id'=>$id), '`url`');
1384	if (!empty($allurl)) {
1385		if (strpos($r['url'], '://')===false) {
1386			if (strpos($category[$catid]['url'], '://') === FALSE) {
1387				$site = siteinfo($category[$catid]['siteid']);
1388				$r['url'] = substr($site['domain'], 0, -1).$r['url'];
1389			} else {
1390				$r['url'] = $category[$catid]['url'].$r['url'];
1391			}
1392		}
1393	}
1394
1395	return $r['url'];
1396}
1397
1398/**
1399 * 将附件地址转换为绝对地址
1400 * @param $path 附件地址
1401 */
1402function atturl($path) {
1403	if(strpos($path, ':/')) {
1404		return $path;
1405	} else {
1406		$sitelist = getcache('sitelist','commons');
1407		$siteid =  get_siteid();
1408		$siteurl = $sitelist[$siteid]['domain'];
1409		$domainlen = strlen($sitelist[$siteid]['domain'])-1;
1410		$path = $siteurl.$path;
1411		$path = substr_replace($path, '/', strpos($path, '//',$domainlen),2);
1412		return 	$path;
1413	}
1414}
1415
1416/**
1417 * 判断模块是否安装
1418 * @param $m	模块名称
1419 */
1420function module_exists($m = '') {
1421	if ($m=='admin') return true;
1422	$modules = getcache('modules', 'commons');
1423	$modules = array_keys($modules);
1424	return in_array($m, $modules);
1425}
1426
1427/**
1428 * 生成SEO
1429 * @param $siteid       站点ID
1430 * @param $catid        栏目ID
1431 * @param $title        标题
1432 * @param $description  描述
1433 * @param $keyword      关键词
1434 */
1435function seo($siteid, $catid = '', $title = '', $description = '', $keyword = '') {
1436	if (!empty($title))$title = strip_tags($title);
1437	if (!empty($description)) $description = strip_tags($description);
1438	if (!empty($keyword)) $keyword = str_replace(' ', ',', strip_tags($keyword));
1439	$sites = getcache('sitelist', 'commons');
1440	$site = $sites[$siteid];
1441	$cat = array();
1442	if (!empty($catid)) {
1443		$siteids = getcache('category_content','commons');
1444		$siteid = $siteids[$catid];
1445		$categorys = getcache('category_content_'.$siteid,'commons');
1446		$cat = $categorys[$catid];
1447		$cat['setting'] = string2array($cat['setting']);
1448	}
1449	$seo['site_title'] =isset($site['site_title']) && !empty($site['site_title']) ? $site['site_title'] : $site['name'];
1450	$seo['keyword'] = !empty($keyword) ? $keyword : $site['keywords'];
1451	$seo['description'] = isset($description) && !empty($description) ? $description : (isset($cat['setting']['meta_description']) && !empty($cat['setting']['meta_description']) ? $cat['setting']['meta_description'] : (isset($site['description']) && !empty($site['description']) ? $site['description'] : ''));
1452	$seo['title'] =  (isset($title) && !empty($title) ? $title.' - ' : '').(isset($cat['setting']['meta_title']) && !empty($cat['setting']['meta_title']) ? $cat['setting']['meta_title'].' - ' : (isset($cat['catname']) && !empty($cat['catname']) ? $cat['catname'].' - ' : ''));
1453	foreach ($seo as $k=>$v) {
1454		$seo[$k] = str_replace(array("\n","\r"),	'', $v);
1455	}
1456	return $seo;
1457}
1458
1459/**
1460 * 获取站点的信息
1461 * @param $siteid   站点ID
1462 */
1463function siteinfo($siteid) {
1464	static $sitelist;
1465	if (empty($sitelist)) $sitelist  = getcache('sitelist','commons');
1466	return isset($sitelist[$siteid]) ? $sitelist[$siteid] : '';
1467}
1468
1469/**
1470 * 生成CNZZ统计代码
1471 */
1472
1473function tjcode() {
1474	if(!module_exists('cnzz')) return false;
1475	$config = getcache('cnzz', 'commons');
1476	if (empty($config)) {
1477		return false;
1478	} else {
1479		return '<script src=\'http://pw.cnzz.com/c.php?id='.$config['siteid'].'&l=2\' language=\'JavaScript\' charset=\'gb2312\'></script>';
1480	}
1481}
1482
1483/**
1484 * 生成标题样式
1485 * @param $style   样式
1486 * @param $html    是否显示完整的STYLE
1487 */
1488function title_style($style, $html = 1) {
1489	$str = '';
1490	if ($html) $str = ' style="';
1491	$style_arr = explode(';',$style);
1492	if (!empty($style_arr[0])) $str .= 'color:'.$style_arr[0].';';
1493	if (!empty($style_arr[1])) $str .= 'font-weight:'.$style_arr[1].';';
1494	if ($html) $str .= '" ';
1495	return $str;
1496}
1497
1498/**
1499 * 获取站点域名
1500 * @param $siteid   站点id
1501 */
1502function siteurl($siteid) {
1503	static $sitelist;
1504	if(!$siteid) return WEB_PATH;
1505	if(empty($sitelist)) $sitelist = getcache('sitelist','commons');
1506	return substr($sitelist[$siteid]['domain'],0,-1);
1507}
1508/**
1509 * 生成上传附件验证
1510 * @param $args   参数
1511 * @param $operation   操作类型(加密解密)
1512 */
1513
1514function upload_key($args) {
1515	$pc_auth_key = md5(pc_base::load_config('system','auth_key').$_SERVER['HTTP_USER_AGENT']);
1516	$authkey = md5($args.$pc_auth_key);
1517	return $authkey;
1518}
1519
1520/**
1521 * 文本转换为图片
1522 * @param string $txt 图形化文本内容
1523 * @param int $fonttype 无外部字体时生成文字大小,取值范围1-5
1524 * @param int $fontsize 引入外部字体时,字体大小
1525 * @param string $font 字体名称 字体请放于phpcms\libs\data\font下
1526 * @param string $fontcolor 字体颜色 十六进制形式 如FFFFFF,FF0000
1527 */
1528function string2img($txt, $fonttype = 5, $fontsize = 16, $font = '', $fontcolor = 'FF0000',$transparent = '1') {
1529	if(empty($txt)) return false;
1530	if(function_exists("imagepng")) {
1531		$txt = urlencode(sys_auth($txt));
1532		$txt = '<img src="'.APP_PATH.'api.php?op=creatimg&txt='.$txt.'&fonttype='.$fonttype.'&fontsize='.$fontsize.'&font='.$font.'&fontcolor='.$fontcolor.'&transparent='.$transparent.'" align="absmiddle">';
1533	}
1534	return $txt;
1535}
1536
1537/**
1538 * 获取phpcms版本号
1539 */
1540function get_pc_version($type='') {
1541	$version = pc_base::load_config('version');
1542	if($type==1) {
1543		return $version['pc_version'];
1544	} elseif($type==2) {
1545		return $version['pc_release'];
1546	} else {
1547		return $version['pc_version'].' '.$version['pc_release'];
1548	}
1549}
1550/**
1551 * 运行钩子(插件使用)
1552 */
1553function runhook($method) {
1554	$time_start = getmicrotime();
1555	$data  = '';
1556	$getpclass = FALSE;
1557	$hook_appid = getcache('hook','plugins');
1558	if(!empty($hook_appid)) {
1559		foreach($hook_appid as $appid => $p) {
1560			$pluginfilepath = PC_PATH.'plugin'.DIRECTORY_SEPARATOR.$p.DIRECTORY_SEPARATOR.'hook.class.php';
1561			$getpclass = TRUE;
1562			include_once $pluginfilepath;
1563		}
1564		$hook_appid = array_flip($hook_appid);
1565		if($getpclass) {
1566			$pclass = new ReflectionClass('hook');
1567			foreach($pclass->getMethods() as $r) {
1568				$legalmethods[] = $r->getName();
1569			}
1570		}
1571		if(in_array($method,$legalmethods)) {
1572			foreach (get_declared_classes() as $class){
1573			   $refclass = new ReflectionClass($class);
1574			   if($refclass->isSubclassOf('hook')){
1575				  if ($_method = $refclass->getMethod($method)) {
1576						  $classname = $refclass->getName();
1577						if ($_method->isPublic() && $_method->isFinal()) {
1578							plugin_stat($hook_appid[$classname]);
1579							$data .= $_method->invoke(null);
1580						}
1581					}
1582			   }
1583			}
1584		}
1585		return $data;
1586	}
1587}
1588
1589function getmicrotime() {
1590	list($usec, $sec) = explode(" ",microtime());
1591	return ((float)$usec + (float)$sec);
1592}
1593
1594/**
1595 * 插件前台模板加载
1596 * Enter description here ...
1597 * @param unknown_type $module
1598 * @param unknown_type $template
1599 * @param unknown_type $style
1600 */
1601function p_template($plugin = 'content', $template = 'index',$style='default') {
1602	if(!$style) $style = 'default';
1603	$template_cache = pc_base::load_sys_class('template_cache');
1604	$compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.$template.'.php';
1605
1606	if(!file_exists($compiledtplfile) || (file_exists(PC_PATH.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(PC_PATH.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile))) {
1607		$template_cache->template_compile('plugin/'.$plugin, $template, 'default');
1608	} elseif (!file_exists(PC_PATH.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$template.'.html')) {
1609		showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.$template.'.html');
1610	}
1611
1612	return $compiledtplfile;
1613}
1614/**
1615 * 读取缓存动态页面
1616 */
1617function cache_page_start() {
1618	$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
1619	define('CACHE_PAGE_ID', md5($relate_url));
1620	$contents = getcache(CACHE_PAGE_ID, 'page_tmp/'.substr(CACHE_PAGE_ID, 0, 2));
1621	if($contents && intval(substr($contents, 15, 10)) > SYS_TIME) {
1622		echo substr($contents, 29);
1623		exit;
1624	}
1625	if (!defined('HTML')) define('HTML',true);
1626	return true;
1627}
1628/**
1629 * 写入缓存动态页面
1630 */
1631function cache_page($ttl = 360, $isjs = 0) {
1632	if($ttl == 0 || !defined('CACHE_PAGE_ID')) return false;
1633	$contents = ob_get_contents();
1634
1635	if($isjs) $contents = format_js($contents);
1636	$contents = "<!--expiretime:".(SYS_TIME + $ttl)."-->\n".$contents;
1637	setcache(CACHE_PAGE_ID, $contents, 'page_tmp/'.substr(CACHE_PAGE_ID, 0, 2));
1638}
1639
1640/**
1641 *
1642 * 获取远程内容
1643 * @param $url 接口url地址
1644 * @param $timeout 超时时间
1645 */
1646function pc_file_get_contents($url, $timeout=30) {
1647	$stream = stream_context_create(array('http' => array('timeout' => $timeout)));
1648	return @file_get_contents($url, 0, $stream);
1649}
1650
1651/**
1652 * Function get_vid
1653 * 获取视频信息
1654 * @param int $contentid 内容ID 必须
1655 * @param int $catid 栏目id 取内容里面视频信息时必须
1656 * @param int $isspecial 是否取专题的视频信息
1657 */
1658function get_vid($contentid = 0, $catid = 0, $isspecial = 0) {
1659	static $categorys;
1660	if (!$contentid) return false;
1661	if (!$isspecial) {
1662		if (!$catid) return false;
1663		$contentid = intval($contentid);
1664		$catid = intval($catid);
1665		$siteid = get_siteid();
1666		if (!$categorys) {
1667			$categorys = getcache('category_content_'.$siteid, 'commons');
1668		}
1669		$modelid = $categorys[$catid]['modelid'];
1670		$video_content = pc_base::load_model('video_content_model');
1671		$r = $video_content->get_one(array('contentid'=>$contentid, 'modelid'=>$modelid), 'videoid', '`listorder` ASC');
1672		$video_store =pc_base::load_model('video_store_model');
1673		return $video_store->get_one(array('videoid'=>$r['videoid']));
1674	} else {
1675		$special_content = pc_base::load_model('special_content_model');
1676		$contentid = intval($contentid);
1677		$video_store =pc_base::load_model('video_store_model');
1678		$r = $special_content->get_one(array('id'=>$contentid), 'videoid');
1679		return $video_store->get_one(array('videoid'=>$r['videoid']));
1680	}
1681}
1682
1683/**
1684 * Function dataformat
1685 * 时间转换
1686  * @param $n INT时间
1687 */
1688 function dataformat($n) {
1689	$hours = floor($n/3600);
1690	$minite	= floor($n%3600/60);
1691	$secend = floor($n%3600%60);
1692	$minite = $minite < 10 ? "0".$minite : $minite;
1693	$secend = $secend < 10 ? "0".$secend : $secend;
1694	if($n >= 3600){
1695		return $hours.":".$minite.":".$secend;
1696	}else{
1697		return $minite.":".$secend;
1698	}
1699
1700 } 
1701?>