<?php

/***************         Kevin      ******************************/
/***************      全局函数文档    ******************************/
error_reporting(E_ERROR | E_PARSE);
set_magic_quotes_runtime(0);
function_exists('date_default_timezone_set') && date_default_timezone_set('Etc/GMT+0');



//绝对路径;
define('R_P',__FILE__  ?  GetDirName(__FILE__).'/'  :  './');

//  网站全局变量定义文件
require("data/variables_global.php");


//  网站全局变量数据库定义文件
require(R_P."data/sql_config.php");


//  数据库配置文件require(R_P."data/cache/".config_path);


//  房产全局定义文件
require(R_P."data/config.php");

header("Content-Type: text/html; charset=$charset");

//$db_obstart == 1 && function_exists('ob_gzhandler') ? ob_start('ob_gzhandler') : ob_start():



function sql_return($sql,$type=1,$sql_c){
	global $db;
	switch ($type){
		case 1:
			$q_sql = $db->Execute($sql);
			break;
		case 2:
			$q_sql = $db->GetRow($sql);
			break;
		case 3:
			$q_sql = $db->GetOne($sql);
			break;
		case 'Insert_ID':
			$q_sql = $db->Insert_ID();
			break;
		case 'count':
			$q_sql = $sql->RecordCount();
			break;
		case 'FetchRow':
			$q_sql = $sql->FetchRow();
			break;
		case 'EOF':
			$q_sql = $sql->EOF;
			break;
		case 'Err':
			$q_sql = $db->ErrorMsg();
			break;
		case 'fields':
			$q_sql = $sql->fields($sql_c);
			break;
		case 'MoveNext':
			$q_sql = $sql->MoveNext();
			break;
		default:
			$q_sql = $db->Execute($sql);
			break;
	}
	return $q_sql;
}

function jumpPage($msg_info,$jumpurl){
	extract($GLOBALS, EXTR_SKIP);
	require (R_P."require/jump_msg.php");
	$arr_msg[$msg_info] && $msg_info=$arr_msg[$msg_info];
	require PrintEot('jump_page');
	exit;
}

function empty_chk($str){
	!is_array($str) && $str = array($str);
	foreach ($str as $k){
		empty($k) && Showmsg('empty');
	}
}


function  Arr_topToFoot($arr){
	$top = $arr[0];
	array_shift($arr);array_push($arr,$top);
	return $arr;
}

function GetDirName($path){
	if(strpos($path,'\\')!==false){
		return substr($path,0,strrpos($path,'\\'));
	} elseif(strpos($path,'/')!==false){
		return substr($path,0,strrpos($path,'/'));
	} else{
		return '/';
	}
}


function str_filter($msgs,$t=0){
	global $str_filter,$str_format_rep,$str_dangerous_filter;
	$msgs = trim($msgs);
	!is_array($msgs) && $msg = array($msgs);
	foreach ($msg as $k){
		!$t  &&  $k = str_ireplace($str_filter,'',$k);//字符过滤;
		$t == 1 &&  $k = str_ireplace($str_dangerous_filter,'',$k);//危险字符过滤
		$t == 2 &&  $k = str_ireplace($str_filter,'',$k = str_replace($str_dangerous_filter,'',$k)) ;//双过滤
		$t == 3 &&  $k = str_ireplace($str_filter,$str_format_rep,$k);//字符替换
		$t == 'chk' && in_array($k,$str_dangerous_filter) && Showmsg('str_chk') ;//危险字符过滤检查
		$k_arr[] = trim($k);
	}
	if (!is_array($msgs)) {
		return $k;
	}else return $k_arr;

}


function CacheFile($arr_data, $path=false,$arr = false){
	$arr && $re_data .= '$'.$arr.'_arr = array(
	';
	foreach ($arr_data as $Key => $Value){
		if ($arr) {
			//如果有第二层的array
			if (is_array($Value)) {
				$re_data .= '\''.$Key.'\'  => array(
				';
				foreach ($Value as $Key1 => $Value1){
					$Value1 =  str_filter($Value1);//字符过滤;
					$re_data .= '\''.$Value1.'\',
					';
				}
				$re_data .= '),
				';
				//完成格式化第二层的array

			}else $re_data .= '\''.$Value.'\',
			';
		}else $re_data .= '$'.$Key.' = \''.$Value.'\';
		';
	}
	$arr && $re_data .= ')';
	$re_data = '<?php '.$re_data. ' ?>';
	if ($path)  writeover($path, $re_data);
	else return $re_data;
}



function Cookie($ck_Var,$ck_Value,$ck_Time = 'F',$p = true,$ck_Httponly = false){
	global $cookie_path,$cookie_domain,$timestamp;
	!$cookie_path && $cookie_path = '/';
	$p && $ck_Var = CookiePre().'_'.$ck_Var;
	if ($ck_Time=='F') {
		$ck_Time = $timestamp+31536000;
	} else {
	($ck_Value=='' && $ck_Time==0) && $ck_Time = $timestamp-31536000;
	}
	$https = $_SERVER['REQUEST_URI'] ? parse_url($_SERVER['REQUEST_URI']) : array();
	if (empty($https['scheme'])) {
		if ($_SERVER['HTTP_SCHEME']) {
			$https['scheme'] = $_SERVER['HTTP_SCHEME'];
		} else {
			$https['scheme'] = ($_SERVER['HTTPS'] && strtolower($_SERVER['HTTPS']) != 'off') ? 'https' : 'http';
		}
	}
	$ck_Secure = $https['scheme'] == 'https' ? true : false;
	if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
		return setcookie($ck_Var, $ck_Value, $ck_Time, $cookie_path, $cookie_domain, $ck_Secure, $httponly);
	} else {
		return setcookie($ck_Var, $ck_Value, $ck_Time, $cookie_path.($ck_Httponly ? '; HttpOnly' : ''), $cookie_domain, $ck_Secure);
	}
}


function GetCookie($Var){
	return $_COOKIE[CookiePre().'_'.$Var];
}


function CookiePre(){
	return substr(md5($GLOBALS['db_name']),0,5);
}


function writeover($filename,$data,$method="rb+",$iflock=1,$check=1,$chmod=1){
	$check && strpos($filename,'..')!==false && exit('Forbidden');
	touch($filename);
	$handle=fopen($filename,$method);
	if($iflock){
		flock($handle,LOCK_EX);
	}
	fwrite($handle,$data);
	if($method=="rb+") ftruncate($handle,strlen($data));
	fclose($handle);
	$chmod && chmod($filename,0777);
}



function Showmsg($msg_info,$msg_v=0){
	extract($GLOBALS, EXTR_SKIP);
	require (R_P."require/msg.php");
	$arr_msg[$msg_info] && $msg_info=$arr_msg[$msg_info];
	require PrintEot('showmsg');
	//footer();
	exit;
}




function PrintEot($template,$type='N',$EXT="html"){
	global $tpl_path;
	if(!$template) $template=N;
	$path=R_P."template/$tpl_path/$template.$EXT";
	!file_exists($path) && $path=R_P."template/default/$template.$EXT";
	$type == 'A' &&  $path=R_P."template/admin/$template.$EXT";
	$type == 'U' &&  $path=R_P."template/default/user/$template.$EXT";
	return $path;

}


function footer($type = 'N' ){
	global $timestamp,$P_S_T,$onlineip,$Version;
	$ft_time = '  Now Time :'.date(' Y-m-d H:i:s',$timestamp)."  ;";

	$t_array	= explode(' ',microtime());
	$totaltime	= number_format(($t_array[0]+$t_array[1]-$P_S_T),6);
	$spend	= " Total $totaltime(s)   ; ";;
	$ip = ' Ip :'.$onlineip."  ; ";;
	$footer = $spend.$ft_time.$ip.$Version;

	if ($type == 'N') return $footer ;
	else require PrintEot('footer');

}

function InitGP($keys,$method='GP',$chk=1){
	!is_array($keys) && $keys = array($keys);
	foreach($keys as $val){
		$GLOBALS[$val] = NULL;
		if($method!='P' && isset($_GET[$val])){
			$GLOBALS[$val] = $_GET[$val];
		} elseif($method!='G' && isset($_POST[$val])){
			$GLOBALS[$val] = $_POST[$val];
			submitCheck();
		}
		$chk && $GLOBALS[$val] = str_filter($GLOBALS[$val],$chk);
	}
}

function GetGP($key,$method='GP'){
	if($method=='G' || $method!='P' && isset($_GET[$key])){
		return $_GET[$key];
	}
	return $_POST[$key];
}

function gbutf_str($str,$t=1){
	if ($t == 1) $strout = iconv("gb2312","utf-8",$str);
	elseif ($t == 2)  $strout = iconv("utf-8","gb2312",$str);
	else $strout = 'ERR_SRT';
	return $strout;
}


function substrs($content,$length,$add='Y'){
	global $db_charset;
	if($length && strlen($content)>$length){
		if($db_charset !== 'utf8'){
			$retstr='';
			for($i = 0; $i < $length - 2; $i++){
				$retstr .= ord($content[$i]) > 127 ? $content[$i].$content[++$i] : $content[$i];
			}
			$add=='Y' && $retstr .= ' ..';
			return $retstr;
		} else{
			return utf8_trim(substr($content,0,$length)).($add=='Y' ? ' ..' : '');
		}
	}
	return $content;
}


function utf8_trim($str) {
	$len = strlen($str);
	for($i=strlen($str)-1;$i>=0;$i-=1){
		$hex .= ' '.ord($str[$i]);
		$ch   = ord($str[$i]);
		if(($ch & 128)==0)	return substr($str,0,$i);
		if(($ch & 192)==192)return substr($str,0,$i);
	}
	return($str.$hex);
}


function submitCheck() {
	if(preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])) return true;
	else  Showmsg('submit_invalid');
}
/******************************************/

function num_rand($lenth){
	mt_srand((double)microtime() * 1000000);
	for($i=0;$i<$lenth;$i++){
		$randval.= mt_rand(0,9);
	}
	return $randval;
}



function StrCode($string,$action='ENCODE'){
	$key	= substr(md5($_SERVER["HTTP_USER_AGENT"].$GLOBALS['db_hash']),8,18);
	$string	= $action == 'ENCODE' ? $string : base64_decode($string);
	$len	= strlen($key);
	$code	= '';
	for($i=0; $i<strlen($string); $i++){
		$k		= $i % $len;
		$code  .= $string[$i] ^ $key[$k];
	}
	$code = $action == 'DECODE' ? $code : base64_encode($code);
	return $code;
}
/******************************************/
?>
