<?php
if(!defined('IN_TM')) exit('Access Denied');
function new_htmlspecialchars($string){
	return is_array($string) ? array_map('new_htmlspecialchars', $string) : htmlspecialchars($string, ENT_QUOTES);
}
function new_addslashes($string){
	if(!is_array($string)) return addslashes($string);    
	foreach($string as $key => $val) $string[$key] = new_addslashes($val);    
	return $string;
}
function new_stripslashes($string){
	if(!is_array($string)) return stripslashes($string);    
	foreach($string as $key => $val) $string[$key] = new_stripslashes($val);    
	return $string;
}
function get_cookie($var){
	$var = COOKIE_PRE.$var;    
	return isset($_COOKIE[$var]) ? $_COOKIE[$var] : false;
}
function set_cookie($var, $value = '', $time = COOKIE_TTL){
	$time = $time > 0 ? $time : ($value == '' ? PHP_TIME - 3600 : 0);    
	$s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;    
	$var = COOKIE_PRE.$var;    
	$_COOKIE[$var] = $value;    
	if(is_array($value)){
		foreach($value as $k=>$v){		
			setcookie($var.'['.$k.']', $v, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);        
		}    
	}else{	
		setcookie($var, $value, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);    
	}
}
function setting_get($where){	
	global $db;        
	$r = $db->get_one("SELECT `setting` FROM `".DB_PRE."settings` WHERE `name` = '{$where}'LIMIT 1");	
	$setting = unserialize($r['setting']);	
	return $setting;
}
function str_exists($haystack, $needle){	return !(strpos($haystack, $needle) === FALSE);}
function xt_auth($txt, $operation = 'ENCODE', $key = ''){        $auth_key = md5(TM_KEY.$_SERVER['HTTP_USER_AGENT']);	$key	= $key ? $key : $auth_key;	$txt	= $operation == 'ENCODE' ? $txt : base64_decode($txt);	$len	= strlen($key);	$code	= '';	for($i=0; $i<strlen($txt); $i++){		$k		= $i % $len;		$code  .= $txt[$i] ^ $key[$k];	}	$code = $operation == 'DECODE' ? $code : base64_encode($code);	return $code;}
function formhash() {	global $_username, $_userid;	return substr(md5(substr(TIME, 0, -7).$_username.$_userid.TM_KEY.$_SERVER['HTTP_USER_AGENT']), 8, 8);}
function ip(){    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')){	$ip = getenv('HTTP_CLIENT_IP');    }elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')){	$ip = getenv('HTTP_X_FORWARDED_FOR');    }elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')){	$ip = getenv('REMOTE_ADDR');    }elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){	$ip = $_SERVER['REMOTE_ADDR'];    }    return preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : 'unknown';}
function debug(){    global $db;    if(!DEBUG) return false;    define('DEBUG_TIME', usedtime());    define('DEBUG_QUERIES', $db->querynum);    return true;}
function usedtime(){    $stime = explode(' ', MICROTIME_START);    $etime = explode(' ', microtime());    return number_format(($etime[1] + $etime[0] - $stime[1] - $stime[0]), 6);}
function tm_error($errno, $errmsg, $filename, $linenum, $vars){    $filename = str_replace(TM_ROOT, '.', $filename);    $filename = str_replace("\\", '/', $filename);    if(!defined('E_STRICT')) define('E_STRICT', 2048);    $dt = date('Y-m-d H:i:s');    $errortype = array (E_ERROR => 'Error', E_WARNING=> 'Warning',E_PARSE=> 'Parsing Error', E_NOTICE=> 'Notice',E_CORE_ERROR=> 'Core Error',E_CORE_WARNING => 'Core Warning',E_COMPILE_ERROR=> 'Compile Error',E_COMPILE_WARNING => 'Compile Warning',E_USER_ERROR=> 'User Error',E_USER_WARNING=> 'User Warning',E_USER_NOTICE=> 'User Notice',E_STRICT => 'Runtime Notice');    $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);    $err = "<errorentry>\n";    $err .= "\t<datetime>" . $dt . "</datetime>\n";    $err .= "\t<errornum>" . $errno . "</errornum>\n";    $err .= "\t<errortype>" . $errortype[$errno] . "</errortype>\n";    $err .= "\t<errormsg>" . $errmsg . "</errormsg>\n";    $err .= "\t<scriptname>" . $filename . "</scriptname>\n";    $err .= "\t<scriptlinenum>" . $linenum . "</scriptlinenum>\n";    if (in_array($errno, $user_errors)){	$err .= "\t<vartrace>" . wddx_serialize_value($vars, "Variables") . "</vartrace>\n";    }    $err .= "</errorentry>\n\n";    error_log($err, 3, TM_ROOT.'/data/php_error_log.xml');    @chmod(TM_ROOT.'/data/php_error_log.xml', 0777);}
function cache_member(){	global $db;	$status = $db->table_status(DB_PRE.'member_cache');	if($status['Rows'] == 0)	{		@set_time_limit(600);		$db->query("INSERT INTO `".DB_PRE."member_cache` SELECT * FROM `".DB_PRE."member`");		return true;	}	return false;}
function safe_replace($string){    $string = str_replace('%20','',$string);    $string = str_replace('%27','',$string);    $string = str_replace('*','',$string);    $string = str_replace('"','&quot;',$string);    $string = str_replace("'",'',$string);    $string = str_replace("\"",'',$string);    $string = str_replace('//','',$string);    $string = str_replace(';','',$string);    $string = str_replace('<','&lt;',$string);    $string = str_replace('>','&gt;',$string);    $string = str_replace('(','',$string);    $string = str_replace(')','',$string);    $string = str_replace("{",'',$string);    $string = str_replace('}','',$string);    return $string;    }
function view($tplfile) {
	$tplfile = $tplfile.'.html';    
	$cachefile =  template($tplfile);    
	return $cachefile;
}
function template($tplfile, $tplpath = '', $tplcachepath = '', $userpack = '', $userpackpath = '', $cachelimit = '') {
	require_once TM_ROOT.'include/template.class.php';      
	$tplpath = $tplpath != '' ? $tplpath : (defined("TPL_PATH") ? TPL_PATH : '');      
	$tplfile = $tplpath.$tplfile;      
	$tplcachelimit = $cachelimit === '' ? (defined("TPL_CACHE_LIMIT") ? TPL_CACHE_LIMIT : 0) : $cachelimit;      
	$cachefile = ($tplcachepath !== '' ? $tplcachepath : (defined("TPL_CACHE_PATH") ? TPL_CACHE_PATH : '')).str_replace(array('/', '.'), '_', $tplfile.($userpack ? '.'.($userpackpath ? $userpackpath : '').$userpack : '')).'.php';      
	if ($tplcachelimit || !($cachetime = @filemtime($cachefile))) {
		if (time() - $cachetime > $tplcachezlimit || @filemtime($tplfile) > $cachetime) {
			$newstengtpl = new template;		
			$newstengtpl->userpack = $userpack ? ($userpackpath ? $userpackpath : $tplpath).$userpack.'.php' : '';		
			$newstengtpl->template = file_get_contents($tplfile);		
			$newstengtpl->tplpath = $tplpath;		
			$newstengtpl->cachefile = $cachefile;		
			$newstengtpl->extraparms = ',\\\''.$tplpath.'\\\',\\\''.$tplcachepath.'\\\',\\\''.$userpack.'\\\',\\\''.$userpackpath.'\\\'';		
			return $newstengtpl->compile();	
		}     
	}      
	return $cachefile;  
}
function url($url, $isabs = 0){    
	if(strpos($url, '://') !== FALSE || $url[0] == '?') return $url;    
	if($isabs || defined('SHOWJS')){	
		$url = strpos($url, TM_PATH) === 0 ? SITE_URL.substr($url, strlen(TM_PATH)) : SITE_URL.$url;    
	}else{	
		$url = strpos($url, TM_PATH) === 0 ? $url : TM_PATH.$url;    
	}    
	return $url;
}
function showmessage($msg, $url_forward = 'goback', $ms = 1250, $direct = 0){
	if($url_forward && $url_forward != 'goback' && $url_forward != 'close') $url_forward = url($url_forward, 1);
	if($direct && $url_forward && $url_forward!='goback'){
		ob_clean();        
		header("location:$url_forward");        
		exit("<script>self.location='$url_forward';</script>");    
	}    
	if($url_forward == 'goback'){
		$url  = '<a href="javascript:history.back();">如果您的浏览器没有自动跳转，请点击这里</a>';        
		$url .= '<script language="javascript">'."setTimeout(\"history.back();\",".$ms.");";        
		$url .= '</script>';    
	}elseif($url_forward == 'close'){        
		$url  =  '<a href="#" onClick="window.close();">[点这里关闭页面]</a><br><a href="javascript:self.close()" >如果您的浏览器没有自动跳转，请点击这里</a>';        
		$url .= '<script language="javascript">'."setTimeout(\"window.close();\",".$ms.");";        
		$url .= '</script>';    
	}else{        
		$url  = '<a href="'.url($url_forward).'" >如果您的浏览器没有自动跳转，请点击这里</a>';        
		$url .= '<script language="javascript">'."setTimeout(\"redirect('".url($url_forward)."');\",".$ms.");";        
		$url .= '</script>';    
	}    
	include view('showmessage');    
	exit;
}
function load($file, $dir = '', $isinit = 1){	$path = TM_ROOT.($dir ? $dir.'/' : 'include/').$file;	if(!(@include_once $path)) return false;	if($isinit && strpos($file, '.class.php') !== false){		$classname = substr($file, 0, -10);		return new $classname();	}	return true;}
/**
 * 翻页函数
 *
 * @param int $num 总纪录数
 * @param int $perpage 每页大小
 * @param int $curpage 当前页面
 * @param string $mpurl url
 * @return string 类似于: <div class="page">***</div>
 */
function page($num, $perpage, $curpage, $mpurl) {
	$multipage = '';
	$mpurl .= strpos($mpurl, '?') ? '&' : '?';
	if($num > $perpage) {
		$page = 10;
		$offset = 2;
		$pages = @ceil($num / $perpage);
		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $from + $page - 1;
			if($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if($to - $from < $page) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $pages - $page + 1;
				$to = $pages;
			}
		}

		$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'page=1" class="first"'.$ajaxtarget.'>1 ...</a>' : '').
		($curpage > 1 && !$simple ? '<a href="'.$mpurl.'page='.($curpage - 1).'" class="prev"'.$ajaxtarget.'>上一页</a>' : '');
		for($i = $from; $i <= $to; $i++) {
			$multipage .= $i == $curpage ? '<strong>'.$i.'</strong>' :
			'&nbsp;<a href="'.$mpurl.'page='.$i.($ajaxtarget && $i == $pages && $autogoto ? '#' : '').'"'.$ajaxtarget.'>'.$i.'</a>&nbsp;';
		}

		$multipage .= ($curpage < $pages && !$simple ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="next"'.$ajaxtarget.'>下一页</a>' : '').
		($to < $pages ? '&nbsp;&nbsp;<a href="'.$mpurl.'page='.$pages.'" class="last"'.$ajaxtarget.'>... '.$realpages.'</a>&nbsp;' : '').
		(!$simple && $pages > $page && !$ajaxtarget ? '<kbd><input type="text" name="custompage" size="3" onkeydown="if(event.keyCode==13) {window.location=\''.$mpurl.'page=\'+this.value; return false;}" /></kbd>' : '');

		$multipage = $multipage ? '<p align=center>共'.(!$simple ? $num.'' : '').'条记录&nbsp;&nbsp;'.$multipage.'' : '';
	}
	return $multipage;
}
/**
 * 对翻页的起始位置进行判断和调整
 *
 * @param int $page 页码
 * @param int $ppp 每页大小
 * @param int $totalnum 总纪录数
 * @return unknown
 */
function page_get_start($page, $ppp, $totalnum) {
	$totalpage = ceil($totalnum / $ppp);
	$page =  max(1, min($totalpage, intval($page)));
	return ($page - 1) * $ppp;
}

function get($tabname = '',$where = '', $order = '', $page = 1, $pagesize = 10){
	global $db;     
	$limit = $result = '';
	if($where) $where = "$where";
	if($order) $order = " ORDER BY $order";
	$page = max(intval($page), 1);
    $offset = $pagesize*($page-1);
    $limit = " LIMIT $offset, $pagesize";
    $array = array();
	$result = $db->query("SELECT * FROM `".DB_PRE.$tabname."` $where $order $limit");
	while($r = $db->fetch_array($result)){			
		$array[] = $r;
	}
    $db->free_result($result);
	return $array;
}
function str_cut($string, $length, $dot = '...'){
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	if(strtolower(CHARSET) == 'utf-8'){
		$n = $tn = $noc = 0;
		while($n < $strlen){
			$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{
		$dotlen = strlen($dot);
		$maxi = $length - $dotlen - 1;
		for($i = 0; $i < $maxi; $i++){
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}
	$strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}
/*
Utf-8、gb2312都支持的汉字截取函数
cut_str(字符串, 截取长度, 开始长度, 编码);
编码默认为 utf-8
开始长度默认为 0
*/

function cut_str($string, $sublen, $code = 'UTF-8', $start = 0)
{
    if($code == 'UTF-8')
    {
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);

        if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
        return join('', array_slice($t_string[0], $start, $sublen));
    }
    else
    {
        $start = $start*2;
        $sublen = $sublen*2;
        $strlen = strlen($string);
        $tmpstr = '';

        for($i=0; $i< $strlen; $i++)
        {
            if($i>=$start && $i< ($start+$sublen))
            {
                if(ord(substr($string, $i, 1))>129){
                    $tmpstr.= substr($string, $i, 2);
                }else{
                    $tmpstr.= substr($string, $i, 1);
                }
            }
            if(ord(substr($string, $i, 1))>129) $i++;
        }
        if(strlen($tmpstr)< $strlen ) $tmpstr.= "...";
        return $tmpstr;
    }
} 
function authorization() {
    $encode = $_SERVER['SERVER_SOFTWARE'] . $_SERVER['SERVER_NAME'] . $_SERVER['DOCUMENT_ROOT'] . $_SERVER['SERVER_ADMIN'] . $_SERVER['SERVER_ADDR'] . PHP_VERSION . PHP_OS . __FILE__;
    return md5 ($encode);
}
?>