PageRenderTime 6ms CodeModel.GetById 18ms app.highlight 29ms RepoModel.GetById 1ms app.codeStats 1ms

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

https://github.com/sinfey69/cms
PHP | 818 lines | 521 code | 51 blank | 246 comment | 132 complexity | f111e9d82453f6a201309af2d47977fd 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 * 返回经addslashe处理过的字符串或数组
 34 * @param $obj 需要处理的字符串或数组
 35 * @return mixed
 36 */
 37function new_html_special_chars($string) {
 38	$encoding = 'utf-8';
 39	if(strtolower(CHARSET)=='gbk') $encoding = 'gb2312';
 40	if(!is_array($string)) return htmlspecialchars($string,ENT_COMPAT,$encoding);
 41	foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
 42	return $string;
 43}
 44/**
 45 * 安全过滤函数
 46 *
 47 * @param $string
 48 * @return string
 49 */
 50function safe_replace($string) {
 51	$string = str_replace('%20','',$string);
 52	$string = str_replace('%27','',$string);
 53	$string = str_replace('%2527','',$string);
 54	$string = str_replace('*','',$string);
 55	$string = str_replace('"','&quot;',$string);
 56	$string = str_replace("'",'',$string);
 57	$string = str_replace('"','',$string);
 58	$string = str_replace(';','',$string);
 59	$string = str_replace('<','&lt;',$string);
 60	$string = str_replace('>','&gt;',$string);
 61	$string = str_replace("{",'',$string);
 62	$string = str_replace('}','',$string);
 63	$string = str_replace('\\','',$string);
 64	return $string;
 65}
 66
 67
 68
 69/**
 70 * 过滤ASCII码从0-28的控制字符
 71 * @return String
 72 */
 73function trim_unsafe_control_chars($str) {
 74	$rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
 75	return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
 76}
 77
 78/**
 79 * 格式化文本域内容
 80 *
 81 * @param $string 文本域内容
 82 * @return string
 83 */
 84function trim_textarea($string) {
 85	$string = nl2br ( str_replace ( ' ', '&nbsp;', $string ) );
 86	return $string;
 87}
 88
 89/**
 90 * 将文本格式成适合js输出的字符串
 91 * @param string $string 需要处理的字符串
 92 * @param intval $isjs 是否执行字符串格式化,默认为执行
 93 * @return string 处理后的字符串
 94 */
 95function format_js($string, $isjs = 1) {
 96	$string = addslashes(str_replace(array("\r", "\n"), array('', ''), $string));
 97	return $isjs ? 'document.write("'.$string.'");' : $string;
 98}
 99
100/**
101 * 转义 javascript 代码标记
102 *
103 * @param $str
104 * @return mixed
105 */
106function trim_script($str) {
107	$str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str );
108	$str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str );
109	$str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str );
110	$str = preg_replace ( '/]]\>/si', ']] >', $str );
111	return $str;
112}
113/**
114 * 获取当前页面完整URL地址
115 */
116function get_url() {
117	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
118	$php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
119	$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
120	$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
121	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
122}
123/**
124 * 字符截取 支持UTF8/GBK
125 * @param $string
126 * @param $length
127 * @param $dot
128 */
129function str_cut($string, $length, $dot = '...') {
130	$strlen = strlen($string);
131	if($strlen <= $length) return $string;
132	$string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
133	$strcut = '';
134	if(strtolower(CHARSET) == 'utf-8') {
135		$n = $tn = $noc = 0;
136		while($n < $strlen) {
137			$t = ord($string[$n]);
138			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
139				$tn = 1; $n++; $noc++;
140			} elseif(194 <= $t && $t <= 223) {
141				$tn = 2; $n += 2; $noc += 2;
142			} elseif(224 <= $t && $t < 239) {
143				$tn = 3; $n += 3; $noc += 2;
144			} elseif(240 <= $t && $t <= 247) {
145				$tn = 4; $n += 4; $noc += 2;
146			} elseif(248 <= $t && $t <= 251) {
147				$tn = 5; $n += 5; $noc += 2;
148			} elseif($t == 252 || $t == 253) {
149				$tn = 6; $n += 6; $noc += 2;
150			} else {
151				$n++;
152			}
153			if($noc >= $length) break;
154		}
155		if($noc > $length) $n -= $tn;
156		$strcut = substr($string, 0, $n);
157	} else {
158		$dotlen = strlen($dot);
159		$maxi = $length - $dotlen - 1;
160		for($i = 0; $i < $maxi; $i++)
161		{
162			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
163		}
164	}
165	$strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
166	return $strcut.$dot;
167}
168
169
170
171/**
172 * 获取请求ip
173 *
174 * @return ip地址
175 */
176function ip() {
177	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
178		$ip = getenv('HTTP_CLIENT_IP');
179	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
180		$ip = getenv('HTTP_X_FORWARDED_FOR');
181	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
182		$ip = getenv('REMOTE_ADDR');
183	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
184		$ip = $_SERVER['REMOTE_ADDR'];
185	}
186	return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
187}
188
189function get_cost_time() {
190	$microtime = microtime(TRUE);
191	return $microtime - SYS_START_TIME;
192}
193
194/**
195 * 程序执行时间
196 *
197 * @return	int	单位ms
198 */
199function execute_time() {
200	$stime = explode ( ' ', SYS_START_TIME );
201	$etime = explode ( ' ', microtime () );
202	return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 );
203}
204
205/**
206* 产生随机字符串
207*
208* @param    int        $length  输出长度 
209* @param    string     $chars   可选的 ,默认为 0123456789
210* @return   string     字符串
211*/
212function random($length, $chars = '0123456789') {
213	$hash = '';
214	$max = strlen($chars) - 1;
215	for($i = 0; $i < $length; $i++) {
216		$hash .= $chars[mt_rand(0, $max)];
217	}
218	return $hash;
219}
220
221/**
222* 将字符串转换为数组
223*
224* @param	string	$data	字符串
225* @return	array	返回数组格式,如果,data为空,则返回空数组
226*/
227function string2array($data) {
228	if($data == '') return array();
229	eval("\$array = $data;");
230	return $array;
231}
232
233/**
234* 将数组转换为字符串
235*
236* @param	array	$data		数组
237* @param	bool	$isformdata	如果为0,则不使用new_stripslashes处理,可选参数,默认为1
238* @return	string	返回字符串,如果,data为空,则返回空
239*/
240function array2string($data, $isformdata = 1) {
241	if($data == '') return '';
242	if($isformdata) $data = new_stripslashes($data);
243	return addslashes(var_export($data, TRUE));
244}
245
246/**
247* 转换字节数为其他单位
248*
249*
250* @param	string	$filesize	字节大小
251* @return	string	返回大小
252*/
253function sizecount($filesize) {
254	if ($filesize >= 1073741824) {
255		$filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
256	} elseif ($filesize >= 1048576) {
257		$filesize = round($filesize / 1048576 * 100) / 100 .' MB';
258	} elseif($filesize >= 1024) {
259		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
260	} else {
261		$filesize = $filesize.' Bytes';
262	}
263	return $filesize;
264}
265
266/**
267* 字符串加密、解密函数
268*
269*
270* @param	string	$txt		字符串
271* @param	string	$operation	ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE,
272* @param	string	$key		密钥:数字、字母、下划线
273* @param	string	$expiry		过期时间
274* @return	string
275*/
276function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
277	$key_length = 4;
278	$key = md5($key != '' ? $key : pc_base::load_config('system', 'auth_key'));
279	$fixedkey = hash('md5', $key);
280	$egiskeys = md5(substr($fixedkey, 16, 16));
281	$runtokey = $key_length ? ($operation == 'ENCODE' ? substr(hash('md5', microtime(true)), -$key_length) : substr($string, 0, $key_length)) : ''; 
282	$keys = hash('md5', substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
283	$string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));
284	
285	$i = 0; $result = '';
286	$string_length = strlen($string);
287	for ($i = 0; $i < $string_length; $i++){
288		$result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
289	}
290	if($operation == 'ENCODE') {
291		return $runtokey . str_replace('=', '', base64_encode($result));
292	} else {
293		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
294			return substr($result, 26);
295		} else {
296			return '';
297		}
298	}
299}
300
301/**
302* 语言文件处理
303*
304* @param	string		$language	标示符
305* @param	array		$pars	转义的数组,二维数组 ,'key1'=>'value1','key2'=>'value2',
306* @param	string		$modules 多个模块之间用半角逗号隔开,如:member,guestbook
307* @return	string		语言字符
308*/
309function L($language = 'no_language',$pars = array(), $modules = '') {
310	static $LANG = array();
311	if(!$LANG) {
312		$lang = pc_base::load_config('system','lang');
313		require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system.lang.php';
314		if(defined('IN_ADMIN')) require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system_menu.lang.php';
315		if(file_exists(PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php')) require PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php';
316		if(!empty($modules)) {
317			$modules = explode(',',$modules);
318			foreach($modules AS $m) {
319				require PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.$m.'.lang.php';
320			}
321		}
322	}
323	if(!array_key_exists($language,$LANG)) {
324		return $LANG['no_language'].'['.$language.']';
325	} else {
326		$language = $LANG[$language];
327		if($pars) {
328			foreach($pars AS $_k=>$_v) {
329				$language = str_replace('{'.$_k.'}',$_v,$language);
330			}
331		}
332		return $language;
333	}
334}
335
336/**
337 * 模板调用
338 * 
339 * @param $module
340 * @param $template
341 * @param $istag
342 * @return unknown_type
343 */
344function template($module = 'content', $template = 'index', $style = 'default') {
345	$template_cache = pc_base::load_sys_class('template_cache');
346	
347	$compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
348	
349	if(file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
350		if(!file_exists($compiledtplfile) || (@filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > @filemtime($compiledtplfile))) {	
351			$template_cache->template_compile($module, $template, $style);
352		}
353	} else {
354		$compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.default.php';
355		if(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)) {
356			$template_cache->template_compile($module, $template, 'default');
357		} else {
358			showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html');
359		}
360	}
361	return $compiledtplfile;
362}
363
364/**
365 * 输出自定义错误
366 * 
367 * @param $errno 错误号
368 * @param $errstr 错误描述
369 * @param $errfile 报错文件地址
370 * @param $errline 错误行号
371 * @return string 错误提示
372 */
373
374function my_error_handler($errno, $errstr, $errfile, $errline) {
375	if($errno==8) return '';
376	$errfile = str_replace(PHPCMS_PATH,'',$errfile);
377	if(pc_base::load_config('system','errorlog')) {
378		error_log(date('m-d H:i:s',SYS_TIME).' | '.$errno.' | '.str_pad($errstr,30).' | '.$errfile.' | '.$errline."\r\n", 3, CACHE_PATH.'error_log.php');
379	} else {
380		$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>';
381		echo $str;
382	}
383}
384
385/**
386 * 提示信息页面跳转,跳转地址如果传入数组,页面会提示多个地址供用户选择,默认跳转地址为数组的第一个值,时间为5秒。
387 * showmessage('登录成功', array('默认跳转地址'=>'http://www.phpcms.cn'));
388 * @param string $msg 提示信息
389 * @param mixed(string/array) $url_forward 跳转地址
390 * @param int $ms 跳转等待时间
391 */
392function showmessage($msg, $url_forward = 'goback', $ms = 1250, $dialog = '') {
393	if(defined('IN_ADMIN')) {
394		include(admin::admin_tpl('showmessage', 'admin'));
395	} else {
396		include(template('content', 'message'));
397	}
398	exit;
399}
400
401/**
402 * 查询字符是否存在于某字符串
403 * 
404 * @param $haystack 字符串
405 * @param $needle 要查找的字符
406 * @return bool
407 */
408function str_exists($haystack, $needle)
409{
410	return !(strpos($haystack, $needle) === FALSE);
411}
412
413/**
414 * 取得文件扩展
415 * 
416 * @param $filename 文件名
417 * @return 扩展名
418 */
419function fileext($filename) {
420	return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
421}
422
423/**
424 * 加载模板标签缓存
425 * @param string $name 缓存名
426 * @param integer $times 缓存时间
427 */
428function tpl_cache($name,$times = 0) {
429	$filepath = 'tpl_data';
430	$info = getcacheinfo($name, $filepath);
431	if (SYS_TIME - $info['filemtime'] >= $times) {
432		return false;
433	} else {
434		return getcache($name,$filepath);
435	}
436}
437
438/**
439 * 写入缓存,默认为文件缓存,不加载缓存配置。
440 * @param $name 缓存名称
441 * @param $data 缓存数据
442 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
443 * @param $type 缓存类型[file,memcache,apc]
444 * @param $config 配置名称
445 * @param $timeout 过期时间
446 */
447function setcache($name, $data, $filepath='', $type='file', $config='', $timeout='') {
448	pc_base::load_sys_class('cache_factory','',0);
449	if($config) {
450		$cacheconfig = pc_base::load_config('cache');
451		$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
452	} else {
453		$cache = cache_factory::get_instance()->get_cache($type);
454	}
455
456	return $cache->set($name, $data, $timeout, '', $filepath);
457}
458
459/**
460 * 读取缓存,默认为文件缓存,不加载缓存配置。
461 * @param string $name 缓存名称
462 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
463 * @param string $config 配置名称
464 */
465function getcache($name, $filepath='', $type='file', $config='') {
466	pc_base::load_sys_class('cache_factory','',0);
467	if($config) {
468		$cacheconfig = pc_base::load_config('cache');
469		$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
470	} else {
471		$cache = cache_factory::get_instance()->get_cache($type);
472	}
473	return $cache->get($name, '', '', $filepath);
474}
475
476/**
477 * 删除缓存,默认为文件缓存,不加载缓存配置。
478 * @param $name 缓存名称
479 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
480 * @param $type 缓存类型[file,memcache,apc]
481 * @param $config 配置名称
482 */
483function delcache($name, $filepath='', $type='file', $config='') {
484	pc_base::load_sys_class('cache_factory','',0);
485	if($config) {
486		$cacheconfig = pc_base::load_config('cache');
487		$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
488	} else {
489		$cache = cache_factory::get_instance()->get_cache($type);
490	}
491	return $cache->delete($name, '', '', $filepath);
492}
493
494/**
495 * 读取缓存,默认为文件缓存,不加载缓存配置。
496 * @param string $name 缓存名称
497 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
498 * @param string $config 配置名称
499 */
500function getcacheinfo($name, $filepath='', $type='file', $config='') {
501	pc_base::load_sys_class('cache_factory');
502	if($config) {
503		$cacheconfig = pc_base::load_config('cache');
504		$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
505	} else {
506		$cache = cache_factory::get_instance()->get_cache($type);
507	}
508	return $cache->cacheinfo($name, '', '', $filepath);
509}
510
511function url($url, $isabs = 0) {
512	if(strpos($url, '://') !== FALSE || $url[0] == '?') return $url;
513	$siteurl = get_url();
514	if($isabs || defined('SHOWJS')) {
515		$url = strpos($url, WEB_PATH) === 0 ? $siteurl.substr($url, strlen(WEB_PATH)) : $siteurl.$url;
516	} else {
517		$url = strpos($url, WEB_PATH) === 0 ? $url : WEB_PATH.$url;
518	}
519	return $url;
520}
521
522/**
523 * 生成sql语句,如果传入$in_cloumn 生成格式为 IN('a', 'b', 'c')
524 * @param $data 条件数组或者字符串
525 * @param $front 连接符
526 * @param $in_column 字段名称
527 * @return string
528 */
529function to_sqls($data, $front = ' AND ', $in_column = false) {
530	if($in_column && is_array($data)) {
531		$ids = '\''.implode('\',\'', $data).'\'';
532		$sql = "$in_column IN ($ids)";
533		return $sql;
534	} else {
535		if ($front == '') {
536			$front = ' AND ';
537		}
538		if(is_array($data) && count($data) > 0) {
539			$sql = '';
540			foreach ($data as $key => $val) {
541				$sql .= $sql ? " $front `$key` = '$val' " : " `$key` = '$val' ";	
542			}
543			return $sql;
544		} else {
545			return $data;
546		}
547	}
548}
549
550/**
551 * 分页函数
552 * 
553 * @param $num 信息总数
554 * @param $curr_page 当前分页
555 * @param $perpage 每页显示数
556 * @param $urlrule URL规则
557 * @param $array 需要传递的数组,用于增加额外的方法
558 * @return 分页
559 */
560function pages($num, $curr_page, $perpage = 20, $urlrule = '', $array = array()) {
561	if($urlrule == '') $urlrule = url_par('page={$page}');
562	$multipage = '';
563	if($num > $perpage) {
564		$page = 11;
565		$offset = 4;
566		$pages = ceil($num / $perpage);
567		$from = $curr_page - $offset;
568		$to = $curr_page + $offset;
569		$more = 0;
570		if($page >= $pages) {
571			$from = 2;
572			$to = $pages-1;
573		} else {
574			if($from <= 1) {
575				$to = $page-1;
576				$from = 2;
577			}  elseif($to >= $pages) { 
578				$from = $pages-($page-2);  
579				$to = $pages-1;  
580			}
581			$more = 1;
582		} 
583		$multipage .= L('total').'<b>'.$num.'</b>&nbsp;&nbsp;';
584		if($curr_page>0) {
585			$multipage .= ' <a href="'.pageurl($urlrule, $curr_page-1, $array).'" class="a1">'.L('previous').'</a>';
586			if($curr_page==1) {
587				$multipage .= ' <span>1</span>';
588			} elseif($curr_page>6 && $more) {
589				$multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>..';
590			} else {
591				$multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>';
592			}
593		}
594		for($i = $from; $i <= $to; $i++) { 
595			if($i != $curr_page) { 
596				$multipage .= ' <a href="'.pageurl($urlrule, $i, $array).'">'.$i.'</a>'; 
597			} else { 
598				$multipage .= ' <span>'.$i.'</span>'; 
599			} 
600		} 
601		if($curr_page<$pages) {
602			if($curr_page<$pages-5 && $more) {
603				$multipage .= ' ..<a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
604			} else {
605				$multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
606			}
607		} elseif($curr_page==$pages) {
608			$multipage .= ' <span>'.$pages.'</span> <a href="'.pageurl($urlrule, $curr_page, $array).'" class="a1">'.L('next').'</a>';
609		} else {
610			$multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';		}
611
612	}
613	return $multipage;
614}
615
616/**
617 * 返回分页路径
618 * 
619 * @param $urlrule 分页规则
620 * @param $page 当前页
621 * @param $array 需要传递的数组,用于增加额外的方法
622 * @return 完整的URL路径
623 */
624function pageurl($urlrule, $page, $array = array()) {
625	if(strpos($urlrule, '#')) {
626		$urlrules = explode('#', $urlrule);
627		$urlrule = $page < 2 ? $urlrules[0] : $urlrules[1];
628	}
629	$findme = array('{$page}');
630	$replaceme = array($page);
631	if (is_array($array)) foreach ($array as $k=>$v) {
632		$findme[] = '{$'.$k.'}';
633		$replaceme[] = $v;
634	}
635	$url = str_replace($findme, $replaceme, $urlrule);
636	return $url;
637}
638
639/**
640 * URL路径解析,pages 函数的辅助函数
641 *
642 * @param $par 传入需要解析的变量 默认为,page={$page}
643 * @param $url URL地址
644 * @return URL
645 */
646function url_par($par, $url = '') {
647	if($url == '') $url = get_url();
648	$pos = strpos($url, '?');
649	if($pos === false) {
650		$url .= '?'.$par;
651	} else {
652		$querystring = substr(strstr($url, '?'), 1);
653		parse_str($querystring, $pars);
654		$query_array = array();
655		foreach($pars as $k=>$v) {
656			$query_array[$k] = $v;
657		}
658		$querystring = http_build_query($query_array).'&'.$par;
659		$url = substr($url, 0, $pos).'?'.$querystring;
660	}
661	return $url;
662}
663
664/**
665 * 判断email格式是否正确
666 * @param $email
667 */
668function is_email($email) {
669	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
670}
671
672/**
673 * iconv 编辑转换
674 */
675if (!function_exists('iconv')) {
676	function iconv($in_charset, $out_charset, $str) {
677		$in_charset = strtoupper($in_charset);
678		$out_charset = strtoupper($out_charset);
679		if (function_exists('mb_convert_encoding')) {
680			return mb_convert_encoding($str, $out_charset, $in_charset);
681		} else {
682
683			pc_base::load_sys_func('iconv');
684			$in_charset = strtoupper($in_charset);
685			$out_charset = strtoupper($out_charset);
686			if($in_charset == 'UTF-8' && ($out_charset == 'GBK' || $out_charset == 'GB2312')) {
687				return utf8_to_gbk($str);
688			}
689			if(($in_charset == 'GBK' || $in_charset == 'GB2312') && $out_charset == 'UTF-8') {
690				return gbk_to_utf8($str);
691			}
692			return $str;
693		}
694	}
695}
696
697/**
698 * 代码广告展示函数
699 * @param intval $siteid 所属站点
700 * @param intval $id 广告ID
701 * @return 返回广告代码
702 */
703function show_ad($siteid, $id) {
704	$siteid = intval($siteid);
705	$id = intval($id);
706	if(!$id || !$siteid) return false;
707	$p = pc_base::load_model('poster_model');
708	$r = $p->get_one(array('spaceid'=>$id, 'siteid'=>$siteid), 'setting', '`id` ASC');
709	if ($r['setting']) {
710		$c = string2array($r['setting']);
711	} else {
712		$r['code'] = '';
713	}
714	return $c['code'];
715}
716
717/**
718 * 获取当前的站点ID
719 */
720function get_siteid() {
721	static $siteid;
722	if (!empty($siteid)) return $siteid;
723	if (defined('IN_ADMIN')) {
724		if ($d = param::get_cookie('siteid')) {
725			$siteid = $d;
726		} else {
727			return '';
728		}
729	} else {
730		$data = getcache('sitelist', 'commons');
731		$site_url = SITE_PROTOCOL.SITE_URL;
732		foreach ($data as $v) {
733			if ($v['url'].'/' == $site_url) $siteid = $v['siteid'];
734		}
735	}
736	return $siteid;
737}
738
739/**
740 * 调用关联菜单
741 * @param $linkageid
742 * @param $id
743 * @param $defaultvalue
744 */
745function menu_linkage($linkageid = 0, $id = 'linkid', $defaultvalue = 0) {
746	$linkageid = intval($linkageid);
747	$datas = array();
748	$datas = getcache($linkageid,'linkage');
749	$infos = $datas['data'];
750	$title = $defaultvalue ? $infos[$defaultvalue]['name'] : $datas['title'];	
751	$colObj = random(3).date('is');
752	$string = '';
753	if(!defined('LINKAGE_INIT')) {
754		define('LINKAGE_INIT', 1);
755		$string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/mln.colselect.js"></script>';
756		if(defined('IN_ADMIN')) {
757			$string .= '<link href="'.JS_PATH.'linkage/style/admin.css" rel="stylesheet" type="text/css">';
758		} else {
759			$string .= '<link href="'.JS_PATH.'linkage/style/css.css" rel="stylesheet" type="text/css">';
760		}
761	}
762	$string .= '<input type="hidden" name="info['.$id.']" value="1"><div id="'.$id.'"></div>';
763	$string .= '<script type="text/javascript">';
764	$string .= 'var colObj'.$colObj.' = {"Items":[';
765	
766	foreach($infos AS $k=>$v) {
767		$s .= '{"name":"'.$v['name'].'","topid":"'.$v['parentid'].'","colid":"'.$k.'","value":"'.$k.'","fun":function(){}},';
768	}
769
770	$string .= substr($s, 0, -1);
771	$string .= ']};';
772	$string .= '$("#'.$id.'").mlnColsel(colObj'.$colObj.',{';
773	$string .= 'title:"'.$title.'",';
774	$string .= 'value:"'.$defaultvalue.'",';
775	$string .= 'width:100';
776	$string .= '});';
777	$string .= '</script>';
778	return $string;
779}
780
781/**
782 * 判断字符串是否为utf8编码,英文和半角字符返回ture
783 * @param $string
784 * @return bool
785 */
786function is_utf8($string) {
787	return preg_match('%^(?:
788					[\x09\x0A\x0D\x20-\x7E] # ASCII
789					| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
790					| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
791					| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
792					| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
793					| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
794					| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
795					| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
796					)*$%xs', $string);
797}
798
799/**
800 * 获取UCenter数据库配置
801 */
802function get_uc_database() {
803	$config = pc_base::load_config('system');
804	$config['uc_dbtablepre'] = str_replace('`'.$config['uc_dbname'].'`.','',$config['uc_dbtablepre']);
805	return  array (
806		'hostname' => $config['uc_dbhost'],
807		'database' => $config['uc_dbname'],
808		'username' => $config['uc_dbuser'],
809		'password' => $config['uc_dbpw'],
810		'tablepre' =>  $config['uc_dbtablepre'],
811		'charset' => $config['uc_dbcharset'],
812		'type' => 'mysql',
813		'debug' => true,
814		'pconnect' => 0,
815		'autoconnect' => 0
816		);
817}
818?>