<?php

/**
 *      【TuntronJxt v4.0】 (C)2010-2012 Tuntron Inc.
 *      
 *    	http://www.tuntron.com   QQ：1121251729
 *		
 *      &全局函数文件&
 */
 
if (!defined('IS_RUN')) die('Forbidden');
require_once(TUNTRON_INC."/function/check.fun.php");
require_once(TUNTRON_INC."/function/safe.fun.php");
// Get class
function G_class($mod,$param=NULL) {
	
	$class = strpos($mod, 'tj_')?$mod:'tj_'.$mod;
	
	if(!class_exists($class)){
		
	    include_once  TUNTRON_INC.'/class/'.$mod.'.class.php';
		
	}
	if(!class_exists($class)){
		return false;
	}
	  if($param) 
		$obj = new $class($param);
	  else
	  	$obj = new $class();
		return $obj;
}

// Get Global value
function &_G() {
    global $_G;
    $max_level = 5;
    $result = '';
    $args_num = func_num_args();
    if($args_num > $max_level) return $result;
    $args = func_get_args();
    $val =& $_G;
    foreach ($args as $v) {
        if(!isset($val[$v])) return $result;
        $val =& $val[$v];
    }
    return $val;
}

function & cookie() {
        $prelen = strlen(_G('cookiepre'));
        $result = array();
        foreach($_COOKIE as $key => $value) {
            if(substr($key, 0, $prelen) == _G('cookiepre')) {
                $var = substr($key, $prelen);
                $result[$var] = $value;
            }
        }
        return $result;
    }

//取得$_COOKIE里的变量
function _cookie($var, $default = null, $prefix = 1) {
    global $_G;
    if($prefix) {
        return isset($_G['cookie'][$var]) ? $_G['cookie'][$var] : $default;
    } else {
        return isset($_COOKIE[$var]) ? $_COOKIE[$var] : $default;
    }
}

//设置cookie
function set_cookie($var, $value, $life = 0, $prefix = 1) {
     $life = $life ? _G('timestamp') + $life : 0;
    $secure = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
    $var = ($prefix ? _G('cookiepre') : '') . $var;
    return setcookie($var, $value, $life, _G('cookiepath'), _G('cookiedomain'), $secure);
}

//删除cookie
function del_cookie($var, $prefix = 1) {
    if(is_array($var)) {
        foreach($var as $val) set_cookie($val, '', -360000, $prefix);
    } else {
        set_cookie($var, '', -360000, $prefix);
    }
}




//生成表单序列
function create_formhash($p1, $p2, $p3) {
    $authkey = _G('cfg','authkey');
    return substr(md5($authkey . $p1 . $p2 . $p3), 8, 8);
}

//跳转
function location($url) {
	$url = str_replace('&amp;', '&', $url);
    header('Location:' . $url);
    exit;
}

//获取随机数 ALL(数字或字母),NUM(数字),WORD(字母)
function random($length=8, $idtype='ALL') {
    PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
    $hash = '';
    for ($i = 0; $i < $length;  $i++) {
        if ( 'NUM' == $idtype ) {
            if (0==$i) {
                $hash .= chr(rand(49, 57));
            } else {
                $hash .= chr(rand(48, 57));
            }
        } else if ( 'WORD' == $idtype ){
            $hash .= chr(rand(65, 90));
        } else {
            if ( 0==$i ) {
                $hash .= chr(rand(65, 90));
            } else {
                $hash .= (0==rand(0,1))?chr(rand(65, 90)):chr(rand(48,57));
            }
        }
    }
    return $hash;
}

//判断电子邮件
function isemail($email) {
    return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}


//get the format_date
function get_format_time($time)
{
    $limit = time() - $time;
    if($limit < 60){
        return $limit . '秒前';
    }elseif($limit >= 60 && $limit < 3600){
        return floor($limit/60) . '分钟前';
    }elseif($limit >= 3600 && $limit < 86400){
        return floor($limit/3600) . '小时前';
    }
    elseif($limit >= 86400)
    {
        return date('m-d', $time);
    }
}

//判断文件是否可写
function is__writable($path) {
    if ($path{strlen($path)-1}=='/')
        return is__writable($path.uniqid(mt_rand()).'.tmp');
    else if (is_dir($path))
        return is__writable($path.'/'.uniqid(mt_rand()).'.tmp');
    $rm = file_exists($path);
    $f = @fopen($path, 'a');
    if ($f===false)
        return false;
    fclose($f);
    if (!$rm)
        unlink($path);
    return true;
}

//TuntronJxt提示
function Note($msg,$button='>>点击返回<<',$url='javascript:history.back(-1);', $debug=true){

		if($debug){
	echo 
<<<EOT
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TuntronJxt 提示</title>
<style type="text/css">
<!--
body {
font-family: Arial;
font-size: 12px;
line-height:150%;
text-align:center;
}
a{color:#555555;}
.main {
width:500px;
background-color:#FFFFFF;
font-size: 12px;
color: #666666;
margin:100px auto 0;
list-style:none;
padding:20px;
background-color: #DDF4FB;
	border-color: #C6EDF9;
	color: #404040;
	text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
	border: solid 1px #C6EDF9;
	text-shadow: 0 1px 0 white;
border-radius: 2px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
}
.main p {
line-height: 18px;
margin: 5px 20px;
font-size:14px;
}
.main .info {
}
.main .but {
color: #646464;
font: 12px Helvetica, Arial, sans-serif;
text-decoration: none;
padding: 7px 17px;
position: relative;
display: inline-block;
text-shadow: 0 1px 0 white;
background: #F3F3F3;
background: -webkit-gradient(linear,0% 40%,0% 70%,from(whiteSmoke),to(#F1F1F1));
background: -moz-linear-gradient(linear,0% 40%,0% 70%,from(whiteSmoke),to(#F1F1F1));
border: solid 1px gainsboro;
border-radius: 2px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
}
-->
</style>
</head>
<body>
<div class="main">
<p class="info">$msg</p>
<p><a href="$url" class="but">$button</a></p>
</div>
</body>
</html>
EOT;
	exit;
		}
	}


//简单加密
function authcode($string, $operation = 'DECODE') {
    $string = $operation == 'DECODE' ? base64_decode($string) : base64_encode($string);
    return $string;
}



/*写入文件，支持Memcache缓存
 @$file 缓存文件
 @$dir 缓存目录
 @$data 内容
 */
function writecache($file,$dir,$data){
	
	global $TS_CF,$TS_MC;
	
	$dfile = $dir.'/'.$file;
	
	//支持memcache
	if($TS_CF['memcache'] && extension_loaded('memcache')){
		$TS_MC->delete(md5($dfile));
		$TS_MC->set(md5($dfile),$data,0,172800);
	}

	//同时保存文件
	!is_dir($dir)?mkdir($dir,0777):'';
	if(is_file($dfile)) unlink($dfile);
	$data = "<?php\nif (!defined('IS_RUN')) die('Forbidden');\nreturn ".var_export($data,true).";";
	file_put_contents($dfile,$data);
	
	return true;
}

/*
 *读取文件 支持Memcache缓存
 *$dfile 文件
 */
function fileRead($dfile){
	global $TS_CF,$TS_MC;
	//支持memcache
	if($TS_CF['memcache'] && extension_loaded('memcache')){
	
		if($TS_MC->get(md5($dfile))){
			return $TS_MC->get(md5($dfile));
		}else{
			if(is_file($dfile)) return include $dfile;
		}
	
	}else{
	
		if(is_file($dfile)) return include $dfile;
	
	}

}

/*此处开始借用moophp的模板代码*/	

/**
* 写文件
* @param string $file - 需要写入的文件，系统的绝对路径加文件名
* @param string $content - 需要写入的内容
* @param string $mod - 写入模式，默认为w
* @param boolean $exit - 不能写入是否中断程序，默认为中断
* @return boolean 返回是否写入成功
*/
function isWriteFile($file, $content, $mod = 'w', $exit = TRUE) {
if(!@$fp = @fopen($file, $mod)) {
	if($exit) {
		exit('TuntronJxt File :<br>'.$file.'<br>Have no access to write!');
	} else {
		return false;
	}
} else {
	@flock($fp, 2);
	@fwrite($fp, $content);
	@fclose($fp);
	return true;
}
}

//创建目录
function makedir($dir) {
return is_dir($dir) or (makedir(dirname($dir)) and mkdir($dir, 0777)); 
}

/**
* 加载模板
* @param string $file - 模板文件名
* @return string 返回编译后模板的系统绝对路径
*/
function Template($file) {
	global $mod,$_G;
	
	 switch ($mod){
	 case 'system':
		$tplfile = 'template/'.$_G['template'].'/system/'.$mod.'_'.$file.'.html';
		$objfile = 'dat/cache/template/system/'.$mod.'.'.$file.'.tpl.php';
	 	
	 break;
	 case 'group':
	 	$tplfile = 'template/'.$_G['template'].'/group/'.$file.'.html';
		$objfile = 'dat/cache/template/group/'.$file.'.tpl.php';
	 break;
	 default:
       	$tplfile = 'template/'.$_G['template'].'/'.$mod.'_'.$file.'.html';
		$objfile = 'dat/cache/template/'.$mod.'.'.$file.'.tpl.php'; 
      break;
	 }

	if(@filemtime($tplfile) > @filemtime($objfile)) {
		//note 加载模板类文件
		require_once 'include/class/template.class.php';
		$T = new template();
		
		$T->complie($tplfile, $objfile);
		
	}
	
	return $objfile;
	unset($mod);
}


//加载公用html模板文件 
function pTemplate($file) {
$tplfile = 'template/common/'.$file.'.html';
$objfile = 'dat/cache/template/public.'.$file.'.tpl.php';

if(@filemtime($tplfile) > @filemtime($objfile)) {
	//note 加载模板类文件
	
	require_once 'include/class/template.class.php';
	$T = new template();
	
	$T->complie($tplfile, $objfile);
}

return $objfile;
}

//gzip压缩输出
function ob_gzip($content) { 
	if( !headers_sent() && extension_loaded("zlib") && strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip")) {
		//$content = gzencode($content." \n//此页已压缩",9); 
		$content = gzencode($content,9); 
		header("Content-Encoding: gzip"); 
		header("Vary: Accept-Encoding");
		header("Content-Length: ".strlen($content));
	}
	return $content; 
}

//输出Json
function outputJson($result,$return=FALSE)
{
	static $json = NULL;
	if($json === NULL)
	{
		require 'include/class/json.class.php';
		$json = new Json();
	}
	if($return){
		return $json->encode($result);
	}else{
		die($json->encode($result));
	}
}

//终端程序，抛出错误信息
function show_error($lang, $param=null) {
    if(preg_match('/^[a-zA-Z0-9_\-]+$/', $lang)) {
        $message = $lang;
    } else {
        $message = $lang;
    }
	//ob_end_clean();
    echo $message;
    exit;
}

//菜单LEFT_HTML
//$left_arr    菜单数组
//$str         菜单变量名
//$var         菜单变量值
//$left_url    菜单url

function left_html($left_arr,$str,$var,$left_url,$http) {
	foreach($left_arr as $key=>$item){
	$item=$item?$item:'index';
	//过滤错误输入符合
	$item = str_replace('，',',',$item);
	$item = str_replace(' ',',',$item);
	$item = str_replace('|',',',$item);
	$arrstr = explode(',',$item);
	$item = $arrstr[0];
	$isselected = in_array($var,$arrstr)?'selected':'';

	if($left_url){
		$url = $http[$key]?$http[$key]:$left_url.$str.'='.$item;
		$_blank = $http[$key]?'target="_blank"':'';
		$left_html.='<li><a href="'.$url.'" class="'.$isselected.'" '.$_blank.'>'.$key.'<span class="arrow_right"></span></a></li>';
	}
    }
	
    return $left_html;
}

//参数验证函数
//返回‘0’表示未通过验证
function fields_check($field,$authcode,$fieldname) {
	global $_G;
	if($field&&empty($authcode)){ return 0;}
	$md5code = md5($field.$_G['siteinfo']['SafeCode'].$fieldname);
	if($authcode && $authcode !== authcode($md5code,'ENCODE')) {return 0;}
}

//返回加密参数
//$field为参数值，$fieldname为参数名称
function fields_code($field,$fieldname) {
	global $_G;
	if(is_array($field)){ 
	
		foreach($field as $key=>$item){
					$idmd5code = md5($item[$fieldname].$_G['siteinfo']['SafeCode'].$fieldname);
					$idauthcode = authcode($idmd5code,'ENCODE');
					$field[$key][$fieldname.'authcode'] = $idauthcode;
				}
				return $field;
	}

	if(!is_array($field)&&isset($field)) {
			$idmd5code = md5($field.$_G['siteinfo']['SafeCode'].$fieldname);
			$idauthcode = authcode($idmd5code,'ENCODE');
			return $idauthcode;
		}
	return $field;
}

//取得字节单位
function size_bytes($val) {
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last) {
        case 'g':
             $val *= 1024;
        case 'm':
             $val *= 1024;
        case 'k':
             $val *= 1024;
    }
    return $val;
}

//格式化显示数组
function pr($var) {
    echo "<div style=\"border:1px solid #ddd;background:#F7F7F7;padding:5px 10px;\">\r\n";
    echo "<pre style=\"font-family:Arial,Vrinda;font-size:14px;\">\r\n";
    print_r($var);
    echo "\r\n</pre>\r\n";
    echo "</div>";
}

//格式化显示数组
function vp($var) {
    echo "<div style=\"border:1px solid #ddd;background:#F7F7F7;padding:5px 10px;\">\r\n";
    echo "<pre style=\"font-family:Arial,Vrinda;font-size:14px;\">\r\n";
    var_dump($var);
    echo "\r\n</pre>\r\n";
    echo "</div>";
}

//获取大小单位
function size_unit($filesize) {
	if($filesize >= 1073741824) {
		$filesize = round($filesize / 1073741824 * 100) / 100 . ' G';
	} elseif($filesize >= 1048576) {
		$filesize = round($filesize / 1048576 * 100) / 100 . ' M';
	} elseif($filesize >= 1024) {
		$filesize = round($filesize / 1024 * 100) / 100 . ' K';
	} else {
		$filesize = $filesize . ' bytes';
	}
	return $filesize;
}

//Edit by zhaobin 2012/11/16 14:19
//字符串截取函数，支持中文
function utf_substr($str, $len){
	for($i=0; $i<$len; $i++){
		$temp_str = substr($str, 0, 1);
		if(ord($temp_str) > 127){
			$i++;
			if($i<$len){
				$new_str[] = substr($str, 0, 3);
				$str = substr($str, 3);
			}
		}else{
			$new_str[] = substr($str, 0, 1);
			$str = substr($str, 1);
		}
	}
	return join($new_str) . '...';
}

//base64反序列化为UTF-8
function base64_unserialize($serial_str) {
	$serial_str= base64_decode($serial_str);    
	$serial_str= preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
	$serial_str= str_replace("\r", "", $serial_str);      
	return unserialize($serial_str);
}

//检查上传文件大小及类型 Edit by zhaobin
function checkFile($filesize,$maxsize,$filetype,$typearr){
	if($filesize>$maxsize){
		return '文件大小超过限制，支持最大上传文件大小为10M';
	}else if(!in_array($filetype, $typearr)){
		return '只支持' . implode(',', $typearr) . '类型文件上传';
	}else{
		return '';
	}
}

//文件上传 Edit by zhaobin
function file_upload($file,$path){
	if($file && $path){
		if(move_uploaded_file($file, $path)){
			return true;
		}else{
			return false;
		}
	}
}

/*
 * 读取EXCEL表格 Edit by zhaobin
 * @param	string	$file	excel表格路劲地址
 * return	array	$arr	结果集数组
 */
function readExcel($file){
	chmod($file, 0777);
	require_once(TUNTRON_INC . "/class/reader.class.php");
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP936');
	$data->read($file);
	$arr = array();
	for($i=1; $i <= $data->sheets[0]['numRows']; $i++){
		$strr="";
		for($j=1; $j <= $data->sheets[0]['numCols']; $j++){
			$strr.= $data->sheets[0]['cells'][$i][$j].",";
		}
		$arr[$i]=iconv('gb2312', 'UTF-8', $strr);
	}
	@unlink($file);
	return $arr;
}

/** 
 *  容量格式化 
 *  Recoded By Androidyue 
 * @param String   文件名（文件路径） 
 * @return  如果文件存在返回格式化的字符串 如果错误返回错误信息  Unknown File 
 */  
function sizeFormat($fileName){
	//获取文件的大小  
	@ $filesize=filesize($fileName);  
	//如果文件不存在返回错误信息  
	if(false==$filesize){
		return 'Unknown File';  
	}  
	//格式化文件容量信息
    if ($filesize >= 1073741824) $filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';  
    elseif ($filesize >= 1048576) $filesize = round($filesize / 1048576 * 100) / 100 . ' MB';  
    elseif ($filesize >= 1024) $filesize = round($filesize / 1024 * 100) / 100 . ' KB';  
    else $filesize = $filesize . ' Bytes';  
    return $filesize;  
}

function getIP(){
	global $ip;
	if (getenv("HTTP_CLIENT_IP"))
		$ip = getenv("HTTP_CLIENT_IP");
	else if(getenv("HTTP_X_FORWARDED_FOR"))
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	else if(getenv("REMOTE_ADDR"))
		$ip = getenv("REMOTE_ADDR");
	else $ip = "Unknow";
	return $ip;
}

/** 
 * 将数据导入EXCEL表
 * @param $array	待导出数据数组
 * @param $filename	导出的文件名
 * @return
 */
function export_excel($title, $array, $filename){
	header("charset=UTF-8");
	header("Content-type:application/vnd.ms-excel");   
	header("Content-Disposition:attachment;filename={$filename}");
	$tab = "\t";
	foreach($title as $key1=>$value1){
		echo iconv('UTF-8', 'gb2312', $value1) . "\t";
	}
	foreach($array as $key2=>$value2){
		print("\n");
		foreach($value2 as $key3=>$value3){
			echo iconv('UTF-8', 'gb2312', $value3) . "\t";
		}
	}
	return (true);
}
function export_excel2($title, $array, $filename){
	header("charset=gb2312");
	header("Content-type:application/vnd.ms-excel");   
	header("Content-Disposition:attachment;filename={$filename}");
	$tab = "\t";
	foreach($title as $key1=>$value1){
		echo $value1;
		print("\t");
	}
	foreach($array as $key2=>$value2){
		print("\n");
		foreach($value2 as $key3=>$value3){
			echo $value3;
			print("\t");
		}
	}
	return (true);
}

//分页函数
function grtpageno($url,$sum,$paginalnum,$pid,$ptnum=9,$fnum=2){
	//url,记录总数$sum,每页个数$paginalnum,显示页条数$ptnum,当前页码$pid,前导数=2
	$num=ceil($sum/$paginalnum);//总页数
	if($pid>$num || $num==1){return NULL;}
	$start_vfy=0; $end_vfy=0;
	if($num<=$ptnum){$num_start=1;$num_end=$num;}//总页数不大于页条数
	else{
		if($pid<=$fnum+1){$num_start=1; $num_end=$ptnum; $end_vfy=1;}//当前页不大于前倒数+1
		else{
			//本页最后一个页码不小于总页数
			if($pid+$ptnum-2>=$num){$num_start=$num-9; $num_end=$num; $start_vfy=1;}
			else{$num_start=$pid-$fnum;$num_end=$pid-$fnum+$ptnum-1; $start_vfy=1; $end_vfy=1;}
		}
	}
	$str="";
	$pidf=$pid-1;
	$pide=$pid+1;
	if($start_vfy){$str.=liaout("1..",$url."&p=1");}
	if($pid>1){$str.=liaout("上一页",$url."&p=$pidf");}
	//for($i=$num_start;$i<=$num_end;$i++){$str.=liaout($i,$url."&p=$i",$i,$pid);}
	$str .= $pid . '/' . $num;
	if($pid<$num){$str.=liaout("下一页",$url."&p=$pide");}
	//if($end_vfy){$str.=liaout("..$num",$url."&p=$num");}
	return $str;
}

//li
function liaout($str,$url,$id=null,$oid=null,$aword=null){
	if($aword){$aword=" ".$aword;}
	return "<a".nowdh($id,$oid)."{$aword} href=\"{$url}\" title=\"{$str}\">{$str}</a>&nbsp;";
}
// li a输出
function nowdh($id=null,$oid=null){
	if($id==$oid&&$id){
		return " class=\"number current\"";
	}else{
		return " class=\"number\"";
	}
}
/** 
 * 返回用户体验很好的时间格式
 * 当天时间显示如：今天 09：45
 * 昨天时间显示如：昨天 09：45
 * 其他日期显示如：2012-12-12 09：45
 * $timeType为时间格式如 09：45：34
 */
function Ue_time($timestamp,$timeType='H:i:s'){
	
	$now=time();
    $hour=($now-$timestamp)/3600;//两个时间小时差
    $nowdate=date('Y-m-d',time());
    $zero=$nowdate.' '.'00:00';
    $t_zerostamp=strtotime($zero);
    $y_zerostamp=$t_zerostamp-24*3600;
    $t_h=($now-$t_zerostamp)/3600;//当天距离零时的小时差
    $y_h=($now-$y_zerostamp)/3600;
    if($hour<$t_h){
       return '<b>'.date('今天 '.$timeType,$timestamp).'</b>';
    }
    elseif($hour>$y_h){
      return date('Y-m-d '.$timeType,$timestamp);
    }
    else{
        return date('昨天 '.$timeType,$timestamp);
    }
}

 	//检测权限
 function check_access($key,$ajax=false) {
        global $_G;
        if($_G['access'][$key]) {
			return '';
			}else{
				if($ajax){
					$json['status'] = 0;
					$json['msg'] = "您所在用户组无权进行此操作！";
					outputJson($json);
					
				}else{
				Note('您所在用户组无权进行此操作！');
				}
				};
    }

/*install function*/
function install_tpl($str)
{
	$install_tpl = 'template/'.$str.'.html';
	return $install_tpl;
}

function chk_install()
{
	if(file_exists(TUNTRON_DAT."/jxt.lock"))
	{
		$msgs = '很抱歉，您已经安装过本系统！<br /><br />如需重新安装，请删除/dat目录下的jxt.lock';
		Note($msgs);
	}
}
function openfile($url)
{
  $str="";
  $i=0;
  $f=@file($url);
  while($i<count($f)){
    $str=$str.$f[$i]."<br>";
	$i=$i+1;
  }
  return $str;
}
function get_inurl() {
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $php_domain = $_SERVER['SERVER_NAME'];
    $php_agent = $_SERVER['HTTP_USER_AGENT'];
    $php_referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
    $php_scheme = $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_reuri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
    $php_port = $_SERVER['SERVER_PORT'] == '80' ? '' : ':'.$_SERVER['SERVER_PORT'];
    $host_url = $php_scheme . $php_domain . $php_port;
    $site_url = $host_url . substr($php_self, 0, strrpos($php_self, '/'));
    $site_url = str_replace('/install', '', $site_url);

    return $site_url;
}
function write_lock()
{
    $file = @fopen(TUNTRON_DAT.'/jxt.lock', 'wb+');
    if (!$file)
    {
        die('打开文件失败');
        return false;
    }
    if (!@fwrite($file, "TUNTRON_INSTALLED"))
    {
        die('写入文件失败');
        return false;
    }
    @fclose($fp);
}
/*install function*/
?>