<?php
class qbase {
	static function get_object($class_name) {
		require_once(R_P . '/include/class.' . $class_name . '.php');
		$args_num = func_num_args();
		if ($args_num == 1) return new $class_name();
		static $max_param = 5;
		$args = func_get_args();
		if ($args_num - 1 < $max_param) for($i = $args_num; $i < $max_param + 1; ++$i) $args[$i] = null;
		return new $class_name($args[1], $args[2], $args[3], $args[4], $args[5]);
	} 
	static function saddslashes($string, $focus = false) {
		global $_SET, $magic_quote;
		if (is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = self :: saddslashes($val);
			} 
			return $string;
		} else {
			if ((AJAX || JSONP) && $focus == false) $string = self :: iconvs($string, $_SET['def_charset'], 'utf-8');
			return $magic_quote ? $string : addslashes($string);
		} 
	} 
	static function iconvs($str, $out_charset, $in_charset = '') {
		global $_SET;
		$in_charset = empty($in_charset) ? strtoupper($_SET['def_charset']) : strtoupper($in_charset);
		$out_charset = strtoupper($out_charset);
		if ($in_charset != $out_charset) {
			if (function_exists('iconv') && ($outstr = @iconv($in_charset, "{$out_charset}//IGNORE", $str))) {
				return $outstr;
			} elseif (function_exists('mb_convert_encoding') && ($outstr = @mb_convert_encoding($str, $out_charset, $in_charset))) {
				return $outstr;
			} else {
				include_once(R_P . "/include/class.charset.php");
				if ($in_charset == 'UTF-8' && substr($out_charset, 0, 2) == 'GB') return charset :: utf82gb($str);
				if ($out_charset == 'UTF-8' && substr($in_charset, 0, 2) == 'GB') return charset :: gb2utf8($str);
			} 
		} 
		return $str;
	} 
	static function dhtmlspecialchars($string) {
		if (is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = self :: dhtmlspecialchars($val);
			} 
		} else {
			$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
				str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
		} 
		return $string;
	} 

	static function fileext($filename) {
		return trim(substr(strrchr($filename, '.'), 1));
	} 

	static function strexists($haystack, $needle) {
		return !(strpos($haystack, $needle) === false);
	} 

	static function get_ip() {
		if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$onlineip = getenv('HTTP_CLIENT_IP');
		} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$onlineip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$onlineip = getenv('REMOTE_ADDR');
		} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$onlineip = $_SERVER['REMOTE_ADDR'];
		} 
		return sprintf("%u", ip2long($onlineip));
	} 

	static function get_domain($dom = '') {
		if ($dom == '') $dom = $_SERVER['HTTP_HOST'];
		$keys = array('com', 'org', 'net', 'gov');
		$preg = "/\A((([0-9]?[0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\.){3}(([0-9]?[0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\Z/";
		if (preg_match($preg, $dom)) return $dom;
		$temp = explode(".", $dom);
		$num = 2;
		if (in_array($temp[count($temp) - 2], $keys)) $num = 3;
		while (count($temp) > $num) {
			array_shift($temp);
		} 
		return implode(".", $temp);
	} 

	static function number2path($num) {
		$num = (string)sprintf("%010d", $num);
		return substr($num, 0, 2) . '/' . substr($num, 0, 2) ;
	} 

	static function avatar($uid, $type = '32') {
		return W_P . 'attachment/avatar/' . self :: number2path($uid) . '/' . $uid . '_' . $type . '.jpg';
	} 

	static function array2string($arr) {
		$temp = array();
		foreach($arr as $key => $val) {
			$temp[] = urlencode($key) . "=" . urlencode($val);
		} 
		return implode("&", $temp);
	} 

	static function sstripslashes($string) {
		if (is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = self :: sstripslashes($val);
			} 
		} else {
			$string = stripslashes($string);
		} 
		return $string;
	} 

	static function headerCache($exp = 3600, $purview = 'Public') {
		header("Expires: " . gmdate ("D, d M Y H:i:s", time() + $exp) . " GMT");
		header("Cache-Control: max-age={$exp}");
		header("Pragma: {$purview}");
	} 

	static function createSql($table, &$preArray , $type = 'insert') {
		if ($type == 'insert' || $type == 'replace') {
			$sql = array();
			foreach($preArray as $key => $val) {
				$sql[0][] = $key;
				$sql[1][] = $val;
			} 
			return "{$type} into {$table} (`" . implode("`,`", $sql[0]) . "`) values ('" . implode("','", $sql[1]) . "')";
		} else {
			$sql = '';
			foreach($preArray as $key => $val) {
				$sql .= "`$key`='$val',";
			} 
			$sql = substr($sql, 0, -1);
			return "update {$table} SET $sql ";
		} 
	} 

	static function authcode($string, $operation, $key = '') {
		global $_SET;
		$key = $key ? $key : $_SET['passport_key'];
		if (!$key) $key = $_SERVER['HTTP_HOST'];
		$coded = '';
		$keylength = strlen($key);
		$string = $operation == 'DECODE' ? base64_decode(urldecode($string)) : $string;
		for($i = 0; $i < strlen($string); $i += $keylength) {
			$coded .= substr($string, $i, $keylength) ^ $key;
		} 
		$coded = $operation == 'ENCODE' ? str_replace('=', '', base64_encode($coded)) : $coded;
		return $coded;
	} 
	// +--------------------------------
	// |	字符串截取函数
	// +--------------------------------
	static function substrs($content, $length = 30, $dot = '...') {
		global $_SET;
		if (strlen($content) <= $length) return $content;
		$content = self::dhtmlspecialchars($content);
		$strcut = '';
		if (strtolower($_SET['def_charset']) == 'utf-8') {
			$n = $tn = $noc = 0;
			while ($n < strlen($content)) {
				$t = ord($content[$n]);
				if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
					$tn = 1;
					$n++;
					$noc++;
				} elseif (194 <= $t && $t <= 223) {
					$tn = 2;
					$n += 2;
					$noc += 2;
				} elseif (224 <= $t && $t <= 239) {
					$tn = 3;
					$n += 3;
					$noc += 2;
				} elseif (240 <= $t && $t <= 247) {
					$tn = 4;
					$n += 4;
					$noc += 2;
				} elseif (248 <= $t && $t <= 251) {
					$tn = 5;
					$n += 5;
					$noc += 2;
				} elseif ($t == 252 || $t == 253) {
					$tn = 6;
					$n += 6;
					$noc += 2;
				} else {
					$n++;
				} 
				if ($noc >= $length) {
					break;
				} 
			} 
			if ($noc > $length) {
				$n -= $tn;
			} 
			$strcut = substr($content, 0, $n);
		} else {
			for($i = 0; $i < $length; $i++) {
				$strcut .= ord($content[$i]) > 127 ? $content[$i] . $content[++$i] : $content[$i];
			} 
		} 
		return $strcut . $dot;
	} 

	static function mkdirable($dir){
		self::createdir($dir);
		clearstatcache();
		$status = is_dir($dir);
		@rmdir($dir);
		return $status;
	}

	static function writeable($file){
		clearstatcache();
		if(is_file($file) || is_dir($file)) return is_writable($file);
		return false;
	}

	static function createdir($dir) {
		return is_dir($dir) || (self :: createdir(dirname($dir)) && @mkdir($dir));
	}

	static function wordSegment($tmpStr){
		global $_SET;
		$n = strtolower($_SET['def_charset']) == 'utf-8' ? 3 : 2;
		$press = str_repeat(" ", $n);
		$returnVal= "";
		preg_match_all("/([0-9a-zA-Z]+)/i", $tmpStr, $matches);
		if(!empty($matches)) foreach($matches[0] as $matche) $returnVal .= ' ' . $matche;
		$tmpStr= preg_replace("/([\\x00-\\x7f]+)/i", " ", $tmpStr);
		$tmpStr= preg_replace("/(\s+)/i", $press, $tmpStr);	
		$len= strlen($tmpStr);
		if($len>=$n * 2){			
			for($i= 0; $i <= $len - $n * 2;){
				if(substr($tmpStr, $i, $n) != $press && substr($tmpStr, $i+$n, $n) != $press)
					$returnVal .= " " . substr($tmpStr, $i, $n * 2);
				$i+=$n;
			}
		}
		$returnVal = trim($returnVal);
		$d = explode(" ", preg_replace("/\s(?=\s)/i", '', $returnVal));
		$r = explode('|', '在|的|与|或|就|你|我|他|她|有|了|是|其|能|对|地|年|月|日|时|分|秒|点|元|百|千|万|亿|位|辆|一|二|三|四|五|六|七|八|九|十|百|千|万|亿|数|，|,|.|。|”|\"|\'|+|-');
		foreach($d as $key=>$val){
			foreach($r as $v){
				if(strpos($val, $v) !== false || is_numeric($val)) {
					unset($d[$key]);
				}
			}
		}
		return implode(" ", $d);
	}

	static function splitWord($str) {
		global $_SET;
		$split=1;
		$array = array();
		$tps = array();
		$utf8 = strtolower($_SET['def_charset']) == 'utf-8' ? true : false;
		for ( $i=0; $i < strlen( $str ); ){
			$value = ord($str[$i]);
			if($value > 127){
				if($utf8){
					if($value >= 192 && $value <= 223)
						$split=2;
					elseif($value >= 224 && $value <= 239)
						$split=3;
					elseif($value >= 240 && $value <= 247)
						$split=4;
				}else{
					$split=2;
				}
				if(!empty($tps)){
					array_push( $array, implode('', $tps) );
					$tps = array();
				}
				$key = NULL;
				for ( $j = 0; $j < $split; $j++, $i++ ) {
					if($str[$i] !== '') $key .= $str[$i];
				}
				array_push( $array, $key );
			}else{
				$split=1;
				$tps[] = $str[$i];
				$i++;
				continue;
			}
		}
		if(!empty($tps)){
			array_push( $array, implode('', $tps) );
			$tps = array();
		}
		return $array;
	} 

	static function deletedir($file) {
		if (is_dir($file)) {
			$handle = @opendir($file);
			while (false !== ($filename = @readdir($handle))) {
				if ($filename != "." && $filename != "..") self :: deletedir($file . "/" . $filename);
			} 
			@closedir($handle);
			@rmdir($file);
			return true;
		} else {
			@unlink($file);
		} 
	} 

	static function createHashParam(){
		$param = array(
			't'=>$_SERVER['REQUEST_TIME'],
			'ip'=>qbase::get_ip()
		);
		$param_str = qbase::array2string($param);
		$param['hash'] = substr(md5($GLOBALS['_SET']['passport_key'] . $param_str), 0, 5);
		return urlencode(qbase::authcode(qbase::array2string($param), 'ENCODE'));
	}
	// +--------------------------------
	// |	删除换行
	// +--------------------------------
	static function trimn($str, $is_space = true) {
		$str = str_replace("\r", '', $str);
		$strs = explode("\n", $str);
		unset($str);
		while (list($key, $val) = each($strs)) {
			if ($is_space) $val = trim($val);
			$str .= $val . self :: br();
		} 
		if ($is_space) $str = trim($str);
		else $str = substr($str, 0, - strlen(br()));
		return $str;
	} 

	static function br() {
		if (PHP_OS == 'WINNT') $br = "\r\n";
		else $br = "\n";
		return $br;
	} 
	// +--------------------------------
	// |	取得指定长度的随机字符串
	// +--------------------------------
	static function random($length) {
		$chars = '0123456789ABCDEFGHIJ0123456789KLMNOPQRSTJ0123456789UVWXYZ0123456789abcdefghijJ0123456789klmnopqrstJ0123456789uvwxyz0123456789';
		$max = strlen($chars) - 1;
		mt_srand((double)microtime() * 1000000);
		for($i = 0; $i < $length; $i ++) {
			$hash .= $chars[mt_rand(0, $max)];
		} 
		return $hash;
	} 
	// +--------------------------------
	// |	cookie设置函数
	// +--------------------------------
	static function phpsetcookie($name, $value, $expirement = '') {
		global $_SERVER, $_SET;
		if ($expirement) $expire = $_SERVER['REQUEST_TIME'] + $expirement;
		if ($_SERVER['SERVER_PORT'] == '443') $secure = 1; // 如果用SSL加密访问
		else $secure = 0;
		setcookie($name, rawurlencode($value), $expire, $_SET['cookie_path'] ? $_SET['cookie_path'] : "/", $_SET['cookie_domain'] ? $_SET['cookie_domain'] : $_SERVER['HTTP_HOST'], $secure);
	} 
	// +--------------------------------
	// |	内容统计函数
	// +--------------------------------
	static function UpdateCount($type, $pretime) {
		$timetemp = $_SERVER['REQUEST_TIME'];
		switch ($type) {
			case 'd':
				$dtime = mktime(0, 0, 0, date("m") , date("d"), date("Y"));
				if ($pretime - $dtime > 0) return 1;
				else return 0;
				break;
			case 'w':
				$wtime = mktime(0, 0, 0, date("m"), date("d") - date('w', $timetemp), date("Y"));
				if ($pretime - $wtime > 0) return 1;
				else return 0;
				break;
			case 'm':
				$mtime = mktime(0, 0, 0, date("m"), 0, date("Y"));
				if ($pretime - $mtime > 0) return 1;
				else return 0;
				break;
		} 
	} 

	static function ChangePoint($uid, $point) {
		$point = intval($point);
		if ($point !== 0) qdb :: query("update " . TABLEPRE . "user_extend set point = point + {$point} where uid = '{$uid}' ");
	} 
	// +--------------------------------
	// |	过滤提交内容中的非法数据
	// +--------------------------------
	static function FilterString(&$string) {
		global $_SET;
		return str_replace(explode('|', $_SET['from_replace']), '**', $string);
	} 

	static function jsonencode($data, $type = false) {
		if (is_null($data)) return 'null';
		if ($data === false) return 'false';
		if ($data === true) return 'true';
		if (is_scalar($data)) {
			if (is_float($data)) return floatval(str_replace(",", ".", strval($data)));
			if (is_string($data)) {
				static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
				return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $data) . '"';
			} else return $data;
		} 
		$isList = true;
		$num = count($data);
		for ($i = 0, reset($data); $i < $num; $i++, next($data)) {
			if (key($data) !== $i) {
				$isList = false;
				break;
			} 
		} 
		$result = array();
		if ($isList) {
			foreach ($data as $v) $result[] = self :: jsonencode($v);
			return '[' . join(',', $result) . ']';
		} else {
			foreach ($data as $k => $v) $result[] = self :: jsonencode($k) . ':' . self :: jsonencode($v);
			return '{' . join(',', $result) . '}';
		} 
	} 

	static function jsondecode ($json) {
		$json = substr($json, strpos($json, '{') + 1, strlen($json));
		$json = substr($json, 0, strrpos($json, '}'));
		$json = preg_replace('/(^|,)([\\s\\t]*)([^:]*) (([\\s\\t]*)):(([\\s\\t]*))/s', '$1"$3"$4:', trim($json));
		if (function_exists('json_decode')) {
			return json_decode('{' . $json . '}', true);
		} else {
			require_once(R_P . "/include/class.Services_JSON.php");
			$obj = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
			return $obj -> decode("{" . $json . "}");
		} 
	} 
	// +--------------------------------
	// |	写入数据流（支持创建目录）
	// +--------------------------------
	static function writetofile($file_name, $data, $method = "w") {
		$dir = dirname($file_name);
		if (!is_dir($dir)) self :: createdir($dir);
		if ($fp = fopen($file_name, $method)) {
			@flock($fp, LOCK_EX);
			$file_data = fwrite($fp, $data);
			@flock($fp, LOCK_UN); 
			fclose($fp);
			return $file_data;
		} else {
			return false;
		} 
	} 
	// +--------------------------------
	// |	读取文件
	// +--------------------------------
	static function readfromfile($file_name) {
		if (!is_file($file_name)) return '';
		if (function_exists('file_get_contents')) return file_get_contents($file_name);
		$fp = @fopen($file_name, 'r');
		if ($filenum !== false) {
			@flock($fp, LOCK_SH);
			$filesize = filesize($file_name);
			$file_data = $filesize ? fread($fp, $filesize) : '';
			@flock($fp, LOCK_UN); 
			fclose($fp);
			return $file_data;
		} else {
			return '';
		} 
	} 

	static function cutHtmlUrl($channelid, $url) {
		global $channel;
		$pre = strlen($channel[$channelid]['domain'] ? $channel[$channelid]['domain'] . '/' : W_P . $channel[$channelid]['channeldir'] . '/');
		return substr($url, $pre);
	} 

	static function getMod($channelid) {
		global $channel, $_MODULE;
		return $_MODULE[$channel[$channelid]['channelselect']]['table_name'];
	} 
	// +--------------------------------
	// |	获取静态HTML文件的存储路径
	// +--------------------------------
	static function GetHtmlDirType($channelid, $id, $ciddir, $dateline, $filename = '', $ver = 0, $iif = 1, $extPage = '') {
		global $channel, $_SET, $_MODULE;
		if ($iif) {
			if (CACHE_VERSION == false) $ver = 0;
			$html_date_path = $channel[$channelid]['html_date_path'];
			if ($filename) {
				$html_type = $filename . '-' . $id . $extPage . ($ver ? '_ver' . $ver : '') . $channel[$channelid]['html_type'];
			} else {
				$html_type = $channel[$channelid]['html_pre'] . $id . $extPage . ($ver ? '_ver' . $ver : '') . $channel[$channelid]['html_type'];
			} 
			if ($channel[$channelid]['domain']) {
				$pre = $channel[$channelid]['domain'];
			} else {
				$pre = W_P . $channel[$channelid]['channeldir'];
			} 
			switch ($html_date_path) {
				case 1 :
					return $pre . "/html" . self :: formatTime('/Y/', $dateline) . $html_type;
					break;
				case 2 :
					return $pre . "/html" . self :: formatTime('/Ym/', $dateline) . $html_type;
					break;
				case 3 :
					return $pre . "/html" . self :: formatTime('/Y/m/', $dateline) . $html_type;
					break;
				case 4 :
					return $pre . "/html" . self :: formatTime('/Y/m/d/', $dateline) . $html_type;
					break;
				case 5 :
					return $pre . "/" . $ciddir . self :: formatTime('/Y/', $dateline) . $html_type;
					break;
				case 6 :
					return $pre . "/" . $ciddir . self :: formatTime('/Ym/', $dateline) . $html_type;
					break;
				case 7 :
					return $pre . "/" . $ciddir . self :: formatTime('/Y/m/', $dateline) . $html_type;
					break;
				case 8 :
					return $pre . "/" . $ciddir . self :: formatTime('/Y/m/d/', $dateline) . $html_type;
					break;
				default :
					return $pre . "/html" . self :: formatTime('/Y/', $dateline) . $html_type;
					break;
			} 
		} else {
			return REWRITE ? W_P . "index-mod-{$channelid}-ac-show-id-{$id}.html" : W_P . "index.php?mod={$channelid}&ac=show&id={$id}";
		} 
	} 

	static function GetCidHtmlDirType($channelid, $cid, $ciddir, $filename = '', $iif = 1) {
		global $channel;
		if ($iif) {
			$filename = ($filename ? $filename : 'index') . $channel[$channelid]['html_type'];
			return $channel[$channelid]['domain'] ? $channel[$channelid]['domain'] . "/" . $ciddir . "/" . $filename : W_P . $channel[$channelid]['channeldir'] . '/' . $ciddir . "/" . $filename;
		} else {
			return REWRITE ? W_P . "index-mod-{$channelid}-ac-list-cid-{$cid}.html" : W_P . "index.php?mod={$channelid}&ac=list&cid={$cid}";
		} 
	} 

	static function getSpecialHtmlUrl($channelid, $sid, $filename, $dateline) {
		global $channel;
		$name = $filename ? $filename : $sid;
		return $channel[$channelid]['channeldir'] . '/special/' . qbase :: formatTime('Y-m', $dateline) . '/' . $name . $channel[$channelid]['html_type'];
	} 

	static function orderbyToString($order, $pre) {
		if (!is_array($order)) return '';
		foreach($order as &$val) {
			$val = $pre . "." . $val;
		} 
		return " order by " . implode(',', $order);
	} 
	// +--------------------------------
	// |	获取附件的存储路径
	// +--------------------------------
	static function GetUploadPath($channelid, $dateline = 0) {
		global $channel;
		$mapping = array(
			0 => 'Y',
			1 => 'Y',
			2 => 'Ym',
			3 => 'Ymd',
			4 => 'Y/m',
			5 => 'Y/m/d',
		);
		$type = isset($mapping[$channel[$channelid]['upload_date_path']]) ? $channel[$channelid]['upload_date_path'] : 0;
		return $dateline ? qbase :: formatTime($mapping[$type], $dateline) : date($mapping[$type], $_SERVER['REQUEST_TIME']) ;
	} 
	// +--------------------------------
	// |	取得栏目风格,内容页模板
	// +--------------------------------
	static function GetCidSkin($dpath = 0) {
		global $channelselect, $_MODULE,$skin;
		switch ($dpath) {
			case 0 :
				global $showphp, $child;
				if ($showphp) {
					return $showphp;
				} else {
					$php = $child ? $_MODULE[$channelselect]['user_list_php'] : $_MODULE[$channelselect]['user_list_last_php'];
					return $skin . '/' . $_MODULE[$channelselect]['table_name'] . '/' . $php;
				} 
				break;
			case 1:
				return $_MODULE[$channelselect]['user_content_php'];
				break;
			case 2:
				$php = $_MODULE[$channelselect]['user_content_php'];
				return $skin . '/' . $_MODULE[$channelselect]['table_name'] . '/' . $php;
				break;
		} 
	} 
	// +----------------------------------------
	// |	检测URL变量中是否存在非法字符
	// +----------------------------------------
	static function checkAction($action) {
		if (is_array($action)) {
			foreach($action as $val) {
				self :: checkAction($val);
			} 
		} else {
			if (!$action) return true;
			if (!ereg("([0-9_a-zA-Z]+)", $action)) {
				self :: purviewCheckDie("error request");
			} 
		} 
	} 
	// +----------------------------------------
	// |	错误输出/自动定向
	// +----------------------------------------
	static function showmsg($show_message, $template = 'default', $url_forward = '' , $javascript = '', $shownext = '') {
		global $_SET;
		$wait = isset($GLOBALS['wait']) ? $GLOBALS['wait'] : 1;
		if (AJAX || JSONP) {
			echo self :: xmlPrint(self :: jsonencode(array('status' => 404, 'message' => $show_message)));
		} else {
			$reffer = $_SERVER['HTTP_REFERER'];
			$method = $_SERVER['REQUEST_METHOD'];
			if ($url_forward == '') {
				if ($method == 'POST' || !$reffer || basename($reffer, "php") == "index.php?action=left" || basename($reffer, "php") == "index.php?action=heads") {
					$msg .= "<html><head><meta http-equiv=\"Content-Type\" content=text/html; charset={$_SET['def_charset']}>";
					$msg .= "<script language='javascript'>window.alert('" . $show_message . "');history.go(-1);</script></head><body></body></html>";
					echo $msg;
					exit();
				} else {
					$url_forward = $reffer;
				} 
			} 
			include self :: template('showmsg');
		} 
		exit();
	} 
	// +-------------------------------------------------
	// |	unix时间戳记格式化
	// +-------------------------------------------------
	static function formatTime($format , $dateline = 0) {
		global $_SET;
		if ($dateline == 0) $dateline = $_SERVER['REQUEST_TIME'];
		return date($format, $dateline + intval($_SET['timezone']) * 3600);
	} 

	static function formatThumb($thumb, $ext = '_s'){
		$index = strrpos($thumb, '.');
		if($index === false) return $thumb;
		return substr($thumb, 0, $index) . $ext . '.'. substr($thumb, $index+1);
	}

	static function formatSubject($subject, $color = ''){
		return $color ? "<font color='{$color}'>" . $subject . "</font>" : $subject;
	}

	static function formatIp($ip){
		if(is_numeric($ip)) $ip = long2ip($ip);
		$index = strrpos($ip, '.');
		return substr($ip, 0 , $index) . '.*';
	}

	static function formatSet($key, $val, $chid = 0) {
		static $_SETMAP = array();
		if ($chid == 0) {
			global $channelid;
			$chid = $channelid;
		} 
		if (!isset($_SETMAP[$chid])) {
			$_SETMAP[$chid] = cache :: get('sys_setting_' . $chid);
			if ($_SETMAP[$chid] === false) {
				qbase :: get_object('setting', 0, 0) -> op_cache();
				$_SETMAP[$chid] = cache :: get('sys_setting_' . $chid);
			} 
			if ($_SETMAP[$chid] === false) return $val;
		} 
		if (strpos($val, ',') === false) return isset($_SETMAP[$chid]['op_' . $key][$val]) ? $_SETMAP[$chid]['op_' . $key][$val] : $val;
		else {
			$temp = explode(',', $val);
			$data = array();
			foreach($temp as $v) {
				$data[] = isset($_SETMAP[$chid]['op_' . $key][$v]) ? $_SETMAP[$chid]['op_' . $key][$v] : $v;
			} 
			return implode(',', $data);
		} 
	} 

	static function purviewCheckDie($message = '') {
		$message || $message = "forbidden";
		if ($_SERVER['HTTP_REFERER'] != "" && basename($_SERVER['HTTP_REFERER'], "php") != "index.php?action=left" && basename($_SERVER['HTTP_REFERER'], "php") != "index.php?action=heads") {
			self :: showmsg($message, "default", $_SERVER['HTTP_REFERER']);
		} else {
			self :: showmsg($message);
		} 
	} 

	static function language($languagepack) {
		if (is_file($languagepack)) {
			require_once $languagepack;
		} 
	} 

	static function template($file) {
		$index = strpos($file, ".");
		if ($index !== false) $file = substr($file, 0, $index);
		$tplfile = T_P . $file . '.php';
		$objfile = C_P . '/template_c/' . str_replace('/', '_', $file) . '.tpl.php';
		if (!is_dir(C_P . '/template_c/')) qbase :: createdir(C_P . '/template_c/');
		if (!is_file($tplfile)) die("{$tplfile} not exists");
		if (@filemtime($tplfile) > @filemtime($objfile)) self :: parse_template($file);
		return $objfile;
	} 

	static function parse_template($file) {
		global $language, $lang;
		$index = strpos($file, ".");
		if ($index !== false) $file = substr($file, 0, $index);
		$tplfile = T_P . $file . '.php';
		$objfile = C_P . '/template_c/' . str_replace('/', '_', $file) . '.tpl.php';
		if (!@$fp = fopen($tplfile, 'r')) die("template file({$tplfile}) not found or have no access!");

		$template = fread($fp, filesize($tplfile));
		fclose($fp);
		$var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*)";
		$const_regexp = "([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)";
		$template = str_replace("<?php die(); ?>", "", $template); 
		// $template = preg_replace("/([\n\r]+)\t+/s", "\\1", $template);
		$template = preg_replace("/\{lang\s+(.+?)\}/ies", "qbase::languagevar('\\1')", $template);
		$template = str_replace("{LF}", "<?=\"\\n\"?>", $template);
		$template = preg_replace("/\{(\\\$[a-zA-Z0-9_\[\]\'\"\$\.\x7f-\xff]+)\}/s", "<?=\\1?>", $template);
		$template = preg_replace("/\<\?\=\<\?\=$var_regexp\?\>\?\>/es", "self::addquote('<?=\\1?>')", $template);
		$template = preg_replace("/[\n\r\t]*\<\!\-\-\{template\s+([a-z0-9_]+)\}\-\-\>[\n\r\t]*/is", "<? include qbase::template('\\1'); ?>", $template);
		$template = preg_replace("/[\n\r\t]*\<\!\-\-\{template\s+(.+?)\}\-\-\>[\n\r\t]*/is", "<? include qbase::template(\\1); ?>", $template);
		$template = preg_replace("/[\n\r\t]*\<\!\-\-\{eval\s+(.+?)\}\-\-\>[\n\r\t]*/ies", "self::stripvtags('<? \\1; ?>','')", $template);
		$template = preg_replace("/[\n\r\t]*\<\!\-\-\{cms\s+(.+?)\}\-\-\>[\n\r\t]*/ies", "self::stripvtagsext('<? \\1; ?>','')", $template);
		$template = preg_replace("/[\n\r\t]*\<\!\-\-\{echo\s+(.+?)\}\-\-\>[\n\r\t]*/ies", "self::stripvtags('<? echo \\1; ?>','')", $template);
		$template = preg_replace("/[\n\r\t]*\<\!\-\-\{elseif\s+(.+?)\}\-\-\>[\n\r\t]*/ies", "self::stripvtags('<? } elseif(\\1) { ?>','')", $template);
		$template = preg_replace("/[\n\r\t]*\<\!\-\-\{else\}\-\-\>[\n\r\t]*/is", "<? } else { ?>", $template);
		$template = preg_replace("/[\n\r\t]*\{echo\s+(.+?)\}[\n\r\t]*/ies", "self::stripvtags('<? echo \\1; ?>','')", $template);
		$template = preg_replace("/[\n\r\t]*\{elseif\s+(.+?)\}[\n\r\t]*/ies", "self::stripvtags('<? } elseif(\\1) { ?>','')", $template);
		$template = preg_replace("/[\n\r\t]*\{else\}[\n\r\t]*/is", "<? } else { ?>", $template);
		for($i = 0; $i < 5; $i++) {
			$template = preg_replace("/[\n\r\t]*\<\!\-\-\{loop\s+(\S+)\s+(\S+)\}\-\-\>[\n\r]*(.+?)[\n\r]*\<\!\-\-\{\/loop\}\-\-\>[\n\r\t]*/ies", "self::stripvtags('<? if(is_array(\\1)) { foreach(\\1 as \\2) { ?>','\\3<? } } ?>')", $template);
			$template = preg_replace("/[\n\r\t]*\<\!\-\-\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}\-\-\>[\n\r\t]*(.+?)[\n\r\t]*\<\!\-\-\{\/loop\}\-\-\>[\n\r\t]*/ies", "self::stripvtags('<? if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>','\\4\n<? } } ?>')", $template);
			$template = preg_replace("/[\n\r\t]*\<\!\-\-\{if\s+(.+?)\}\-\-\>[\n\r]*(.+?)[\n\r]*\<\!\-\-\{\/if\}\-\-\>[\n\r\t]*/ies", "self::stripvtags('<? if(\\1) { ?>','\\2<? } ?>')", $template);
		} 
		for($i = 0; $i < 5; $i++) {
			$template = preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\}[\n\r]*(.+?)[\n\r]*\{\/loop\}[\n\r\t]*/ies", "self::stripvtags('<? if(is_array(\\1)) { foreach(\\1 as \\2) { ?>','\\3<? } } ?>')", $template);
			$template = preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}[\n\r\t]*(.+?)[\n\r\t]*\{\/loop\}[\n\r\t]*/ies", "self::stripvtags('<? if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>','\\4\n<? } } ?>')", $template);
			$template = preg_replace("/[\n\r\t]*\{if\s+(.+?)\}[\n\r]*(.+?)[\n\r]*\{\/if\}[\n\r\t]*/ies", "self::stripvtags('<? if(\\1) { ?>','\\2<? } ?>')", $template);
		} 
		$template = preg_replace("/\{$const_regexp\}/s", "<?=\\1?>", $template);
		$template = preg_replace("/ \?\>[\n\r]*\<\? /s", " ", $template);

		if (!@$fp = fopen($objfile, 'w')) die("Directory have no file {$tplfile} access!");
		@flock($fp, 2);
		fwrite($fp, $template);
		@flock($fp, LOCK_UN); 
		fclose($fp);
		clearstatcache();
	} 

	static function addquote($var) {
		return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
	} 

	static function languagevar($var) {
		if (isset($GLOBALS['lang'][$var])) {
			return $GLOBALS['lang'][$var];
		} else {
			return "!$var!";
		} 
	} 

	static function stripvtags($expr, $statement) {
		$expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr));
		$statement = str_replace("\\\"", "\"", $statement);
		return $expr . $statement;
	} 

	static function stripvtagsext($expr, $statement) {
		$expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr));
		$expr = str_replace("'", "", $expr);
		$statement = str_replace("\\\"", "\"", $statement);
		return $expr . $statement ;
	} 
	// +-------------------------------------------------
	// |	静态文件生成函数
	// +-------------------------------------------------
	static function obHtml($leval) {
		switch ($leval) {
			case 1 :
				global $channeldir, $is_html, $channelid, $html_type;
				if (!$is_html) return true;
				qbase::check_pureview_hash();
				if(intval($_GET['preview'])) return true;
				$content = ob_get_contents();
				$html = $channelid ? $channeldir . '/index' . $html_type : 'index' . $GLOBALS['_SET']['homepage_index'];
				if(is_file(R_P . '/' . $html)) @unlink(R_P . '/' . $html);
				clearstatcache();
				self :: writetofile(R_P . '/' . $html , $content);
				ob_clean();
				if (!AJAX) {
					header("location:" . W_P . $html);
				} else {
					echo self :: xmlPrint("[1]");
				} 
				return true;
				break;
			case 2 :
				global $pageno, $channeldir, $ciddir, $cfilename, $pur_browse, $category_html, $htmlPageTotal, $html_type;
				if (!$pur_browse && !$category_html) {
					qbase::check_pureview_hash();
					if(intval($_GET['preview'])) return true;
					$htmlPageTotal = intval($htmlPageTotal);
					$index = ($cfilename ? $cfilename : 'index') . ($pageno == 1 ? '' : '_' . $pageno) . $html_type;
					$file = R_P . '/' . $channeldir . '/' . $ciddir . '/' . $index;
					$url = W_P . $channeldir . '/' . $ciddir . '/' . $index;
					$content = ob_get_contents();
					if(is_file($file)) @unlink($file);
					clearstatcache();
					self :: writetofile($file , $content);
					ob_clean();
					if (!AJAX) {
						header("location:" . $url);
					} else {
						echo self :: xmlPrint("[\"" . str_replace("/", "\\/", $url) . "\", {$htmlPageTotal}]");
					} 
				}
				break;
			case 3 :
				global $_category_info, $_output, $channeldir, $page;
				$page = intval($page);
				$iif = !($_category_info['pur_browse'] || $_category_info['html'] || $_output['pay']);
				if ($iif && $_output['status'] == 0) {
					qbase::check_pureview_hash();
					if(intval($_GET['preview'])) return true;
					if ($page > 1) $extPage = '_' . $page;
					else $extPage = '';
					$url = self :: GetHtmlDirType($_output['channelid'], $_output['id'], $_category_info['ciddir'], $_output['dateline'], $_output['filename'], $_output['ver'], $iif, $extPage);
					$file = R_P . '/' . $channeldir . '/' . self :: cutHtmlUrl($_output['channelid'], $url);
					$content = ob_get_contents();
					if(is_file($file)) @unlink($file);
					clearstatcache();
					self :: writetofile($file, $content);
					ob_clean();
					if (!AJAX) {
						header("location:" . $url);
					} else {
						echo self :: xmlPrint("[\"" . str_replace("/", "\\/", $url) . "\", {$page}]");
					} 
				}
				break;

			case 4:
				global $_output, $channel;
				qbase::check_pureview_hash();
				if(intval($_GET['preview'])) return true;
				$wb = self :: getSpecialHtmlUrl($_output['channelid'], $_output['sid'], $_output['filename'], $_output['dateline']);
				$file = R_P . '/' . $wb;
				$url = W_P . $wb;
				$content = ob_get_contents();
				if(is_file($file)) @unlink($file);
				clearstatcache();
				self :: writetofile($file, $content);
				ob_clean();
				if (!AJAX) {
					header("location:" . $url);
				} else {
					echo self :: xmlPrint("[\"" . str_replace("/", "\\/", $url) . "\", 1]");
				} 
				break;
		} 
	} 

	static function is_admin(){
		if(isset($_COOKIE['admin_auth'])){
			parse_str(self::authcode(trim($_COOKIE['admin_auth']) , "DECODE"), $admin_info);
			if(isset($admin_info['u']) && isset($admin_info['s'])){
				if(intval($admin_info['u']) > 0 && strlen(urldecode($admin_info['s'])) == 32) return true;
			}
		}
		return false;
	}

	static function check_pureview_hash(){		
		$status = false;
		if(self::is_admin()) return true;
		if(isset($_GET['hash'])){
			$hash = urldecode($_GET['hash']);
			$hash_str = self::authcode($hash, 'DECODE');
			parse_str($hash_str, $arr);
			if(isset($arr['t']) && isset($arr['ip']) && isset($arr['hash'])){
				if($arr['ip'] == self::get_ip() && $_SERVER['REQUEST_TIME'] - $arr['t'] < 86400){
					$hash_verify = $arr['hash'];
					unset($arr['hash']);
					$param_str = substr(md5($GLOBALS['_SET']['passport_key'] . self::array2string($arr)), 0, 5);
					if($param_str == $hash_verify){
						$status = true;
					}
				}
			}
		}
		return true;
		/*
			在某些情况下有误封的，暂时关闭
		*/
		if($status == false){
			$ip = self::get_ip();
			qbase::get_object('banned')->add($ip, $ip, 1);
			ob_clean();
			header("HTTP/1.1 403 Forbidden");
			include_once self::template('default/403');
			exit();
		}else{
			return true;
		}
	}

	static function getChannelDir() {
		$arr = pathinfo($_SERVER['SCRIPT_NAME']);
		return array_pop(explode('/', $arr['dirname']));
	} 

	static function load($url, $limit = 0, $post = '', $cookie = '', $bysocket = false, $ip = '', $timeout = 15, $block = true, $ajax = false) {
		$return = '';
		$matches = parse_url($url);
		!isset($matches['host']) && $matches['host'] = '';
		!isset($matches['path']) && $matches['path'] = '';
		!isset($matches['query']) && $matches['query'] = '';
		!isset($matches['port']) && $matches['port'] = '';
		$host = $matches['host'];
		$path = $matches['path'] ? $matches['path'] . ($matches['query'] ? '?' . $matches['query'] : '') : '/';
		$port = !empty($matches['port']) ? $matches['port'] : 80;
		if ($ajax) $path .= (preg_match("/\?/", $path) ? "&" : "?") . "ajax=1";
		if ($post) {
			$out = "POST $path HTTP/1.0\r\n";
			$out .= "Accept: */*\r\n";
			$out .= "Referer: http://{$host}\r\n";
			$out .= "Accept-Language: zh-cn\r\n";
			$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
			$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
			$out .= "Host: $host\r\n";
			if ($ajax) $out .= "X-Requested-With:XMLHttpRequest\r\n";
			$out .= 'Content-Length: ' . strlen($post) . "\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Cache-Control: no-cache\r\n";
			$out .= "Cookie: $cookie\r\n\r\n";
			$out .= $post;
		} else {
			$out = "GET $path HTTP/1.0\r\n";
			$out .= "Accept: */*\r\n";
			$out .= "Referer: http://{$host}\r\n";
			$out .= "Accept-Language: zh-cn\r\n";
			$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
			$out .= "Host: $host\r\n";
			if ($ajax) $out .= "X-Requested-With:XMLHttpRequest\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Cookie: $cookie\r\n\r\n";
		} 
		$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
		if (!$fp) {
			return ''; //note $errstr : $errno \r\n
		} else {
			stream_set_blocking($fp, $block);
			stream_set_timeout($fp, $timeout);
			@fwrite($fp, $out);
			$status = stream_get_meta_data($fp);
			if (!$status['timed_out']) {
				while (!feof($fp)) {
					if (($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) {
						break;
					} 
				} 
				$stop = false;
				while (!feof($fp) && !$stop) {
					$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
					$return .= $data;
					if ($limit) {
						$limit -= strlen($data);
						$stop = $limit <= 0;
					} 
				} 
			} 
			@fclose($fp);
			return $return;
		} 
	} 

	static function xmlPrint($data) {
		global $_SET;
		if (AJAX) {
			return "<?xml version=\"1.0\" encoding=\"{$_SET['def_charset']}\"?><root><![CDATA[" . $data . "]]></root>";
		} else if (JSONP) {
			return "_output_back(" . self :: jsonencode($data, true) . ");";
		} else {
			return $data;
		}
	} 

	static function page ($totalsize , $pageno, $pagesize, $dynamic = 0, $dir = '', $cfilename = '', $first = 1, $last = 0, $pre_show = 0, $next = 1, $pinfo = 1, $halfPer = 4, $hash = '') {
		global $_SET, $cid, $channel, $channelid, $channelselect, $_MODULE, $htmlPageTotal, $html_type;
		$total = $htmlPageTotal = ceil($totalsize / $pagesize);
		$channeldir = $channel[$channelid]['channeldir'];
		$domain = trim($channel[$channelid]['domain']);
		if ($htmlPageTotal < 2) return '';
		$halfPer = 3;
		$re = "";
		if ($dynamic == 0) {
			$ext = $html_type;
			if ($cfilename) {
				$pre = ($domain ? $domain : W_P . $channeldir) . '/' . $dir . '/' . $cfilename . '_';
			} else {
				$pre = ($domain ? $domain : W_P . $channeldir) . '/' . $dir . '/index_';
			} 
			$first = substr($pre, 0, -1) . $ext;
		} else {
			$temp = '';
			if (REWRITE) {
				foreach($_GET as $key => $val) {
					if ($key == 'pageno') continue;
					$temp .= $key . '-' . urlencode(urlencode($val)) . '-';
				} 
				$pre = W_P . 'index-' . $temp . 'pageno-';
				$ext = '.html';
				$first = W_P . 'index-' . substr($temp, 0, -1) . '.html';
			} else {
				foreach($_GET as $key => $val) {
					if ($key == 'pageno') continue;
					$temp .= $key . '=' . urlencode($val) . '&';
				} 
				$pre = '?' . $temp . 'pageno=';
				$ext = '';
				$first = '?' . substr($temp, 0, -1);
			} 
		} 
		$prepage = ($pageno-2) ? "<a class='p-pre' href=\"{$pre}" . ($pageno-1) . "{$ext}\">" : "<a class='p-pre' href=\"{$first}\">";
		if ($first) $re .= "<a class='p-first' href=\"{$first}\">首页</a>";
		if ($pre_show && $pageno > 1) $re .= $prepage . "上一页</a>";
		for ($i = $pageno - $halfPer, $i > 0 || $i = 0 , $j = $pageno + $halfPer, $j < $total || $j = $total;$i < $j ;$i++) {
			if ($i > 0) {
				$re .= $i == $pageno-1 ? "<a href='javascript:void(0);' class='current'>" . ($i + 1) . "</a>" : "<a href=\"{$pre}" . ($i + 1) . "{$ext}\">" . ($i + 1) . "</a>";
			} else {
				$re .= $i == $pageno-1 ? "<a href='javascript:void(0);' class='current'>" . ($i + 1) . "</a>" : "<a href=\"{$first}\">" . ($i + 1) . "</a>";
			} 
		} 
		$lastpage = $pre . $total . $ext;
		if ($pageno + $halfPer < $total) $re .= '<span>...</span>';
		if ($next && $pageno < $total) $re .= "<a class='p-next' href=\"{$pre}" . ($pageno + 1) . "{$ext}\">下一页</a>";
		if ($last) $re .= "<a class='p-last' href=\"" . $lastpage . "\">尾页</a>";
		if ($pinfo) $re .= "<a href='javascript:void(0);' class='p-info'>{$pageno}/{$total}</a>";
		return $re;
	} 

	static function privatePage($id, $filename, $ver, $page, $total, $dynamic = 0, $first = 1, $last = 1, $pre_show = 0, $next = 0, $pinfo = 1, $halfPer = 4, $hash = '') {
		$page_string = '';
		global $channel, $channelid;
		if (!CACHE_VERSION) $ver = 0;
		if ($dynamic == 0) {
			$pre = $filename ? $filename . '-' . $id : $channel[$channelid]['html_pre'] . $id;
			$ext = $channel[$channelid]['html_type'];
			if ($first) $page_string .= self :: createLinkStatic(1, $page, $pre, $ext, $ver, "首页", "p-first", $hash);
			if ($pre_show && $page > 1) $page_string .= self :: createLinkStatic($page-1 , $page, $pre, $ext, $ver, "上一页", "p-pre", $hash);
			for ($i = $page - $halfPer, $i > 0 || $i = 1 , $j = $page + $halfPer, $j <= $total || $j = $total;$i <= $j ;$i++) {
				$page_string .= self :: createLinkStatic($i, $page, $pre, $ext, $ver, '', '', $hash);
			} 
			if ($next && $page < $total) $page_string .= self :: createLinkStatic($page + 1, $page, $pre, $ext, $ver, "下一页", "p-last", $hash);
			if ($last) $page_string .= self :: createLinkStatic($total, $page, $pre, $ext, $ver, "尾页", "p-last", $hash);
			if ($pinfo) $page_string .= "<a href='javascript:void(0);' class='p-info'>{$page}/{$total}</a>";
		} else {
			$temp = '';
			foreach($_GET as $key => $val) {
				if ($key == 'page') continue;
				$temp .= $key . '=' . $val . '&';
			} 
			$temp = substr($temp, 0, -1);
			if ($first) $page_string .= self :: createLink(1, $page, $temp, "首页", "p-first", $hash);
			if ($pre_show && $page > 1) $page_string .= self :: createLink($page-1, $page, $temp, "上一页", "p-pre", $hash);
			for ($i = $page - $halfPer, $i > 0 || $i = 1 , $j = $page + $halfPer, $j <= $total || $j = $total;$i <= $j ;$i++) {
				$page_string .= self :: createLink($i, $page, $temp, '', '', $hash);
			} 
			if ($next && $page < $total) $page_string .= self :: createLink($page + 1, $page, $temp, "下一页", "p-next", $hash);
			if ($last) $page_string .= self :: createLink($total, $page, $temp, "尾页", "p-last", $hash);
			if ($pinfo) $page_string .= "<a href='javascript:void(0);' class='p-info'>{$page}/{$total}</a>";
		} 
		if (REWRITE) {
			return self :: rewite($page_string, $hash, true);
		} else {
			return $hash ? self :: rewite($page_string, $hash, false) : $page_string;
		} 
	} 

	static function createLink($i, $page, $link, $word = '', $style = '') {
		if (!$word) $word = (string)$i;
		if ($style) $style = " class='{$style}'";
		if ($i == $page) {
			return "<a href='javascript:void(0);' class='current'>{$word}</a>\n";
		} else {
			return $i == 1 ? "<a{$style} href='index.php?{$link}'>{$word}</a>\n" : "<a{$style} href='index.php?{$link}&page={$i}'>{$word}</a>\n";
		} 
	} 

	static function createLinkStatic($i, $page, $pre, $ext, $ver, $word = '', $style = '', $hash = '') {
		if (!$word) $word = (string)$i;
		if ($style) $style = " class='{$style}'";
		$link = $pre . ($i > 1 ? '_' . $i : '') . ($ver ? '_ver' . $ver : '') . $ext;
		if ($i == $page) {
			return "<a href='javascript:void(0);' class='current'>{$word}</a>\n";
		} else {
			return "<a href='{$link}{$hash}'>{$word}</a>\n";
		} 
	} 

	static function rewite($param, $hash, $type) {
		if ($type == true) {
			return preg_replace("/[\'|\"]index\.php\?(.*)[\'|\"]\>/ie", "self::rewriteLink('\\1', '{$hash}')", $param);
		} else {
			return preg_replace("/[\'|\"]index\.php\?(.*)[\'|\"]\>/ie", "self::rewriteLinkHash('\\1', '{$hash}')", $param);
		} 
	} 

	static function rewriteLink($url, $hash) {
		static $replace = array('&', '&amp;', '=');
		return "'index-" . str_replace($replace, "-", $url) . ".html{$hash}'>";
	} 
	static function rewriteLinkHash($url, $hash) {
		return "'index.php?{$url}{$hash}'>";
	} 
} 

?>