<?php
/**
 * (c) ThinkSEO
 * 通用函数库
 * 包括以下函数
 * [_addslashes 转义字符串函数]
 * [_stripslashes 反转义字符串] [make_semiangle 半角到全角转换]
 * [cheak_type 检查文件类型] [getip 获得ip地址]
 * [SET_NOW 清除缓存] [upfile 上传文件]
 * 更新时间: 2009-10-09 21:36
 * 更新人员:	猪立业
 * */

/**
 * 递归方式的对变量中的特殊字符进行转义
 * @access  public
 * @param   mix     $value
 * @return  mix
 */
function _addslashes($value){
	if (empty($value)){
		return $value;
	}else{
		return is_array($value) ? array_map('_addslashes', $value) : addslashes($value);
	}
}

/**
 * 递归方式的对变量中的特殊字符去除转义
 * @access  public
 * @param   mix     $value
 * @return  mix
 */
function _stripslashes($value){
	if (empty($value)){
		return $value;
	}else{
		return is_array($value) ? array_map('_stripslashes', $value) : stripslashes($value);
	}
}

/**
 *  将一个字串中含有全角的数字字符、字母、空格或'%+-()'字符转换为相应半角字符
 * @access  public
 * @param   string       $str         待转换字串
 * @return  string       $str         处理后字串
 */
function make_semiangle($str)
{
    $arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
                 '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
                 'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
                 'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
                 'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
                 'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
                 'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
                 'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
                 'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
                 'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
                 'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
                 'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
                 'ｙ' => 'y', 'ｚ' => 'z',
                 '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
                 '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
                 '‘' => '[', '’' => ']', '｛' => '{', '｝' => '}', '《' => '<',
                 '》' => '>',
                 '％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
                 '：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',
                 '；' => ',', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',
                 '”' => '"', '’' => '`', '‘' => '`', '｜' => '|', '〃' => '"',
                 '　' => ' ');

    return strtr($str, $arr);
}

/**
 * 检查文件类型
 * @access      public
 * @param       string      filename            文件名
 * @param       string      realname            真实文件名
 * @param       string      limit_ext_types     允许的文件类型
 * @return      string
 */
function check_type($filename, $realname = '', $limit_ext_types = ''){
	if ($realname){
		$extname = strtolower(substr($realname, strrpos($realname, '.') + 1));
	}else{
		$extname = strtolower(substr($filename, strrpos($filename, '.') + 1));
	}

	if ($limit_ext_types && stristr($limit_ext_types, '|' . $extname . '|') === false){
		return '';
	}

	$str = $format = '';
	$file = @fopen($filename, 'rb');
	if ($file){
		$str = @fread($file, 0x400); // 读取前 1024 个字节
		@fclose($file);
	}else{
		if (stristr($filename, ROOT_PATH) === false){
            if ($extname == 'jpg' || $extname == 'jpeg' || $extname == 'gif' || $extname == 'png' || $extname == 'doc' ||
                $extname == 'xls' || $extname == 'txt'  || $extname == 'zip' || $extname == 'rar' || $extname == 'ppt' ||
                $extname == 'pdf' || $extname == 'rm'   || $extname == 'mid' || $extname == 'wav' || $extname == 'bmp' ||
                $extname == 'swf' || $extname == 'chm'  || $extname == 'sql' || $extname == 'cert'){
                $format = $extname;
			}
		}else{
			return '';
		}
	}

	if ($format == '' && strlen($str) >= 2 ){
		if (substr($str, 0, 4) == 'MThd' && $extname != 'txt'){
			$format = 'mid';
		}elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav'){
			$format = 'wav';
		}elseif (substr($str ,0, 3) == "\xFF\xD8\xFF"){
			$format = 'jpg';
		}elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt'){
			$format = 'gif';
		}elseif (substr($str ,0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"){
			$format = 'png';
		}elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt'){
			$format = 'bmp';
		}elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS') && $extname != 'txt'){
			$format = 'swf';
		}elseif (substr($str ,0, 4) == "\xD0\xCF\x11\xE0"){   // D0CF11E == DOCFILE == Microsoft Office Document
			if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'doc'){
				$format = 'doc';
			}elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xls'){
				$format = 'xls';
			} elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'ppt'){
				$format = 'ppt';
			}
        } elseif (substr($str ,0, 4) == "PK\x03\x04"){
            $format = 'zip';
        } elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt'){
            $format = 'rar';
        } elseif (substr($str ,0, 4) == "\x25PDF"){
            $format = 'pdf';
        } elseif (substr($str ,0, 3) == "\x30\x82\x0A"){
            $format = 'cert';
        } elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt'){
            $format = 'chm';
        } elseif (substr($str ,0, 4) == "\x2ERMF"){
            $format = 'rm';
        } elseif ($extname == 'sql'){
            $format = 'sql';
        } elseif ($extname == 'txt'){
            $format = 'txt';
        }
    }

    if ($limit_ext_types && stristr($limit_ext_types, '|' . $format . '|') === false){
        $format = '';
    }

    return $format;
}

/**
 * 获取访问的 IP 地址
 * 无需参数
 * 返回IP 地址
 * @return string IP 
 * **/
function getip(){
   if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
       $ip = getenv("HTTP_CLIENT_IP");
   else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
       $ip = getenv("HTTP_X_FORWARDED_FOR");
   else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
       $ip = getenv("REMOTE_ADDR");
   else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
       $ip = $_SERVER['REMOTE_ADDR'];
   else
       $ip = "unknown";
   return($ip);
}

/**
 * 清楚缓存,让页面永远保持最新
 * */
function SET_NEW(){
	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
	header("Cache-Control: no-cache, must-revalidate");
	header("Pragma: no-cache");	
}

/**
 * 上传文件函数
 * @package $file string 文件名称
 * @param $dir string 文件路径
 * @return 文件名称,多文件上传为数组
 * */
function upfile( $file , $dir ){
	$temp_name=time();
	makepath(AM_DIR.$dir);
	$re='';
	if (is_array($_FILES["{$file}"]["error"])) {
		foreach ($_FILES["{$file}"]["error"] as $_k => $error) {
			if ($error == UPLOAD_ERR_OK){
				$temp_file = $_FILES["{$file}"]["tmp_name"][$_k];
				$type = substr(strrchr($_FILES["{$file}"]["name"][$_k],'.'),1);
				$file_name = md5($temp_name . $_k).'.'.$type;
				move_uploaded_file($temp_file, AM_DIR."$dir/$file_name");
				$re[]=array('dir' => "$dir/$file_name" , 'name' => $file_name , 'size' => $_FILES["{$file}"]["size"][$_k] , 'type' => $type );
			}
		}
	}else {
		if ( isset($_FILES["{$file}"]["error"]) && $_FILES["{$file}"]["error"] == UPLOAD_ERR_OK){
			$temp_file = $_FILES["{$file}"]["tmp_name"];	//临时文件
			$type = substr(strrchr($_FILES["{$file}"]["name"],'.'),1);	//文件后缀
			$file_name = md5($temp_name).'.'.$type;
			move_uploaded_file($temp_file, AM_DIR."$dir/$file_name");
			$re=array('dir' => "$dir/$file_name" , 'name' => $file_name , 'size' => $_FILES["{$file}"]["size"] , 'type' => $type );
		}
	}
	return $re;
}

/**
* 生成目录,被定向到根目录下了
* @param string $path 文件提供路径,路径不能为带 \
* @return string 路径
**/
function makepath($path){
	$detail=explode('/',str_ireplace('\\','/',$path));
	foreach($detail AS $key=>$value){
		$newpath.="$value/";
		if((preg_match("^\/",$newpath)||preg_match(":",$newpath))&&!strstr($newpath,AM_DIR)){continue;}
		if( !is_dir($newpath) ){
			if(substr($newpath,-1)=='\\'||substr($newpath,-1)=='/'){
				$_newpath=substr($newpath,0,-1);
			}else{
				$_newpath=$newpath;
			}
			if(!mkdir($_newpath)&&!file_exists($_newpath)){
				return 'false';
			}
			@chmod($_newpath,0777);
		}
	}
	return $_newpath;
}

/**
 * 剔除出域
* */
function _getenv($var_name = 'HTTP_HOST') { 
	if (isset($_SERVER[$var_name])) {
		return $_SERVER[$var_name];
	} elseif (isset($_ENV[$var_name])) {
		return $_ENV[$var_name];
	} elseif (getenv($var_name)) {
		return getenv($var_name);
	} elseif (function_exists('apache_getenv') && apache_getenv($var_name, true)) { 
		return apache_getenv($var_name, true);
	}
	return '';
}

function template($tplfile, $fullpath=0) {
	global $_TG;
	
	if(empty($fullpath)) {
		$filename = 'skin/'.$_TG['skin'].'/'.$tplfile.'_'.$_TG['language'].'.html.php';
		$objfile = AM_DIR.'./cache/tpl/tpl_'.$_TG['skin'].'_'.$tplfile.'_'.$_TG['language'].'.php';
		$tplfile = AM_DIR.'./'.$filename;
//	是不是存在该语言的模板 没有使用默认模板
		if (!file_exists($tplfile)) {
			if (!file_exists($tplfile = str_replace("_{$_TG['language']}.html.php",'.html.php',$tplfile))) {
				if (!file_exists($tplfile = (str_replace('.html.php','_'.$_TG['language'].'.html.php',(str_replace(AM_DIR.'./skin/'.$_TG['skin'].'/',AM_DIR.'./skin/default/',$tplfile)))))) {
					$tplfile = str_replace("_{$_TG['language']}.html.php",'.html.php',$tplfile);
				}
			}
		}
	} else {
		$filename = $tplfile;
		if (file_exists(AM_DIR.'./'.(str_replace(strrchr($filename,'.'),"_{$_TG['language']}".strrchr($filename,'.'),$filename)))) {
			$filename = str_replace(strrchr($filename,'.'),"_{$_TG['language']}".strrchr($filename,'.'),$filename);
		}
		$objfile = str_replace('/', '_', $filename);
		$objfile = AM_DIR.'./cache/tpl/tpl_'.$objfile.'.php';
		$tplfile = AM_DIR.'./'.$filename;
	}
	
	$tplrefresh = 1;
	if(file_exists($objfile)) {
		if(empty($_TG['tplrefresh'])) {
			$tplrefresh = 0;
		} else {
			if(@filemtime($tplfile) <= @filemtime($objfile)) {
				$tplrefresh = 0;
			}
		}
	}

	if($tplrefresh) {
		include_once(AM_DIR.'./include/lib_template.php');
		parse_template($tplfile, $objfile);
	}

	return $objfile;
}

//	转换路径
function srealpath($path) {
	$path = str_replace('./', '', $path);
	if(DIRECTORY_SEPARATOR == '\\') {
		$path = str_replace('/', '\\', $path);
	} elseif(DIRECTORY_SEPARATOR == '/') {
		$path = str_replace('\\', '/', $path);
	}
	return $path;
}

//写文件
function writefile($filename, $writetext, $filemod='text', $openmod='w', $eixt=1) {
	if(!@$fp = fopen($filename, $openmod)) {
		if($eixt) {
			exit('File :<br>'.srealpath($filename).'<br>Have no access to write!');
		} else {
			return false;
		}
	} else {
		$text = '';
		if($filemod == 'php') {
			$text = "<?php\r\n\r\nif(!defined('IN_TK')) exit('Access Denied');\r\n\r\n";
		}
		$text .= $writetext;
		if($filemod == 'php') {
			$text .= "\r\n\r\n?>";
		}
		flock($fp, 2);
		fwrite($fp, $text);
		fclose($fp);
		return true;
	}
}

//	格式化表名
function tname($name){
	global $_TG;
	return " `{$_TG['sqlpre']}{$name}` ";
}


/**
 * 将数组合成字符串,缓存为php字符串格式
 * 返回转化后的字符串
 * @param  array $array
 * @return string
 * */
function _serialize($array = array()){
	$str = "Array (";
	$comma = '';
	foreach ($array as $_k=>$_v){
		$_k = is_string($_k) ? '\''.addcslashes($_k, '\'\\').'\'' : $_k;
		$_v = !is_array($_v) && (!preg_match("/^\-?\d+$/", $_v) || strlen($_v) > 12) ? '\''.addcslashes($_v, '\'\\').'\'' : $_v;
		if (is_array($_v)) {
			$str .= "$comma $_k => "._serialize($_v); 
		}else {
			$str .= "$comma $_k => $_v";
		}
		$comma = ',';
	}
	
	$str .= ')';
	return $str;
}


/**
 * 过滤所有空字符串
 * 返回没有带空格的字符串
 * @param $string 传入字符串
 * @return String
 * */
function Tblank($string){
	$string=str_replace("&nbsp;","",$string);
	$string=str_replace(" ","",$string);
	$string=str_replace("　","",$string);
	$string=str_replace("\r","",$string);
	$string=str_replace("\n","",$string);
	$string=str_replace("\t","",$string);
	return $string;
}

/**
 * 弹出返回
 * @param $str
 * @param $url
 * */
function alert($str = '',$url = ''){
	global $isback;
	if($isback == 1) $url=''; //强制后退，通过$_GET['back'] ||　$_POST['back'] 控制。
	if (empty($url)) {
echo <<<END
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<script>alert("$str");history.go(-1);</script>
END;
	}else {
echo <<<END
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<script>alert("$str");this.location.href="{$url}";</script>
END;
	}
	exit;
}

function block($str){
	global $_TD,$_TG,$_TB;
	$strarr = explode('/',$str);
	for ($i=0; $i<count($strarr); $i+=2){
		if(!empty($strarr[$i]))$sqlarr[$strarr[$i]] = $strarr[$i+1];
	}
	$wheresql = 'WHERE 1=1 ';
	if (!empty($sqlarr['sort'])) {
		$wheresql .= preg_match("/^[0-9]+$/",$sqlarr['sort']) ? "AND `sid` = ".intval($sqlarr['sort']) : "AND `sid` in ({$sqlarr['sort']})";
	}
	
	if (!empty($sqlarr['order'])) {
		$wheresql .= " ORDER BY ".$sqlarr['order'];
	}
	
	if (!empty($sqlarr['limit'])) {
		$wheresql .= " LIMIT ".$sqlarr['limit'];
	}
	
	if (!empty($sqlarr['sql'])) {
		$qy = $_TD->QY($sqlarr['sql']);
	}else{
		$qy = $_TD->QY("SELECT * FROM ".tname('content')." $wheresql");
	}
	
	if ($sqlarr['bname']) {
		$bname = trim($sqlarr['bname']);
	}else{
		$bname = 0;
	}
	
	while ($arr = $_TD->FA($qy)) {
		if (intval($sqlarr['subjectlen']) > 0) {
			$arr['titleall'] = $arr['title'];
			$arr['title'] = cutstr(preg_replace("/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is", ' ', $arr['title']),intval($sqlarr['subjectlen']),'...');
		}
		if (intval($sqlarr['contentlen']) > 0) {
			$arr['contentall'] = $arr['content'];
			$arr['content'] = cutstr(preg_replace("/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is", ' ', $arr['content']),intval($sqlarr['contentlen']),'...');
		}
		$_TB[$bname][] = $arr;
	}
}

function cutstr($string, $length, $dot = '...') {
	global $_TC;
	if(strlen($string) <= $length) {
		return $string;
	}
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
	$strcut = '';
	
	if(strtolower($_TC['charset']) == 'utf-8') {
		$n = $tn = $noc = 0;
		while($n < strlen($string)) {
			$t = ord($string[$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($string, 0, $n);
	} else {
		for($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}
	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}



//解决JSON中文null
function tb_json_encode($value, $options = 0) 
{ 
return json_encode(tb_json_convert_encoding($value, 'GBK', 'UTF-8')); 
} 
function tb_json_decode($str, $assoc = false, $depth = 512) 
	{ 
	return tb_json_convert_encoding(json_decode($str, $assoc), 'UTF-8', 'GBK'); 
} 
function tb_json_convert_encoding($m, $from, $to) 
{ 
	switch(gettype($m)) { 
	case 'integer': 
	case 'boolean': 
	case 'float': 
	case 'double': 
	case 'NULL': 
	return $m; 

	case 'string': 
	return mb_convert_encoding($m, $to, $from); 
	case 'object': 
	$vars = array_keys(get_object_vars($m)); 
	foreach($vars as $key) { 
	$m->$key = tb_json_convert_encoding($m->$key, $from ,$to); 
	} 
	return $m; 
	case 'array':
	foreach($m as $k => $v) { 
	$m[tb_json_convert_encoding($k, $from, $to)] = tb_json_convert_encoding($v, $from, $to); 
	} 
	return $m; 
	default: 
	} 
	return $m; 
} 

//判断是否为utf8
function is_utf8_bak($word) { 
    if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$word) == true) 
    { 
        return true; 
    } else { 
        return false; 
    } 
}

function myjsoncode($value)
{
	global $_TC;
	$code = $_TC['dbcharset'];
	
	//strpos($a, $b) !== false 如果$a 中存在 $b，则为 true 
	if(stripos($code,'gbk')===false)
	{
		return json_encode($value);
	}else {
		return json_encode(tb_json_convert_encoding($value, 'GBK', 'UTF-8'));
	}
}


?>