<?php

/*
	[Gatewei] (C)2008-2009 wangten studio.
*/

if(!defined('IN_GATEWEI')) {
	exit('Access Denied');
}

function cutstr($string, $length, $dot = ' ...') {
	global $charset;

	if(strlen($string) <= $length) {
		return $string;
	}

	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);

	$strcut = '';
	if(strtolower($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;
}


function gaddslashes($string,$force = 0) {
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = gaddslashes($val,$force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}



function gexit($message = '') {
	echo $message;
	//output();
	exit();
}

function ghtmlspecialchars($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = 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;
}

function gheader($string, $replace = true, $http_response_code = 0) {
	$string = str_replace(array("\r", "\n"), array('', ''), $string);
	if(empty($http_response_code) || PHP_VERSION < '4.3' ) {
		@header($string, $replace);
	} else {
		@header($string, $replace, $http_response_code);
	}
	if(preg_match('/^\s*location:/is', $string)) {
		exit();
	}
}


//要注意\\的问题, windows和linux的目录间隔不同
//is_uploaded_file在php中的作用是判断上传的文件是否成功
function gisuploadedfile($file) {
	return function_exists('is_uploaded_file') && (is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file)));
}

function getrobot() {
	if(!defined('IS_ROBOT')) {
		$kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
		$kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
		if(preg_match("/($kw_browsers)/", $_SERVER['HTTP_USER_AGENT'])) {
			define('IS_ROBOT', FALSE);
		} elseif(preg_match("/($kw_spiders)/", $_SERVER['HTTP_USER_AGENT'])) {
			define('IS_ROBOT', TRUE);
		} else {
			define('IS_ROBOT', FALSE);
		}
	}
	return IS_ROBOT;
}

function isallowclient() {
		$allowclientconn = 'MSIE|Netscape|Opera|Konqueror|Mozilla|Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
		if(preg_match("/($allowclientconn)/", $_SERVER['HTTP_USER_AGENT'])) {
			$allowclient=true;
		} else {
			$allowclient=false;
		}
	return $allowclient;
}




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


function cururldir(){
	 return site(1).substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'],"/")+1);
}

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


function debuginfo() {
		global $db, $g_run_starttime, $debuginfo;
		$mtime = explode(' ', microtime());
		$debuginfo = array('time' => number_format(($mtime[1] + $mtime[0] - $g_run_starttime), 6), 'queries' => $db->querynum);
		return TRUE;
}



function multi($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 5, $autogoto = TRUE, $simple = FALSE) {
	global $maxpage;
	$ajaxtarget = !empty($_GET['ajaxtarget']) ? " ajaxtarget=\"".dhtmlspecialchars($_GET['ajaxtarget'])."\" " : '';

	$multipage = '';
	$mpurl .= strpos($mpurl, '?') ? '&amp;' : '?';
	$realpages = 1;
	if($num > $perpage) {
		$offset = 2;

		$realpages = @ceil($num / $perpage);
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;

		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">1 ...</a>' : '').
			($curpage > 1 && !$simple ? '<a href="'.$mpurl.'page='.($curpage - 1).'" class="prev">上一页</a>' : '');
		for($i = $from; $i <= $to; $i++) {
			$multipage .= $i == $curpage ? '<strong>'.$i.'</strong>' :
				'<a href="'.$mpurl.'page='.$i.'">'.$i.'</a>';
		}

		$multipage .= ($curpage < $pages && !$simple ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="next">下一页</a>' : '').
			($to < $pages ? '<a href="'.$mpurl.'page='.$pages.'" class="last">... '.$realpages.'</a>' : '');

		$multipage = $multipage ? '<div class="pages">'.(!$simple ? '<em>&nbsp;'.$num.'&nbsp;</em>' : '').$multipage.'</div>' : '';
	}
	$maxpage = $realpages;
	return $multipage;
}

function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
	if($numeric) {
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}


function site($protocol=0) {
	if($protocol){
		return 'http://'.$_SERVER['HTTP_HOST'];
	}else{
		return $_SERVER['HTTP_HOST'];
	}
}

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

function updatesession() {
	global $db,$sid;
	if($sid){
	$db->query("UPDATE g_sessions SET uptime=$timestamp WHERE sid='$sid'");
	}
}

function writelog($message) {
	global $timestamp,$currentip;
	$yearmonth = gmdate('Ym', $timestamp + 8 * 3600);
	$logdir = GATEWEI_ROOT.'./clientdata/logs/';
	$logfile = $logdir.$yearmonth.'_log.php';
	if(file_exists($logfile)){
		if(@filesize($logfile) > 1024000) {
			return false;
		}
	}
	$message=gmdate('r',$timestamp+8*3600)."\t".$currentip."\t".$message;
		if($fp = @fopen($logfile, 'a')) {
			@flock($fp, 2);
				fwrite($fp, "<?PHP exit;?>".str_replace(array('<?', '?>'), '', $message)."\n");
			fclose($fp);
		}
}



function filterurl($string)
{
$string = trim($string);
if(empty($string)){
	return "";
	}
$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
if(substr($string,0,7)!="http://"){
		$string='http://'.$string;
     }

return $string;
}


function height_light($string,$b,$type){
	global $hlightways;
	if(!$b){
		return $string;
	}else{
	return '<font style="'.$hlightways[$type][1].'">'.$string.'</font>';
	}
}

function replaceimg($img){
	$ext=fileext($img);
	if($ext=="gif"){
		$img=str_replace(".gif", ".thumb.gif", $img);
	}elseif($ext=="jpg"){
		$img=str_replace(".jpg", ".thumb.jpg", $img);
	}elseif($ext=="png"){
		$img=str_replace(".png", ".thumb.png", $img);
	}
	return $img;
}

function showmsg($msg , $url_forward = '') {
	global $charset,$templatedir,$sid,$_GSESSION,$sitename,$g_project_name,$g_project_version,$debuginfo,$timestamp,$companyname,$siteicp,$nav,$registerfilename,$registerlinkword,$sitename,$siteheadtitle;
	$showmessage="";
	@extract($_GSESSION);
	if($url_forward) {
			$showmessage .= "<br /><center>$msg<br /><a href=\"$url_forward\" >如果没有系统没有自动转回请点击这里</a></center>";
			$showmessage .= "<script>setTimeout(\"redirect('$url_forward');\", 10000);</script>";
	} else {
			$showmessage .= "<br /><center>$msg<br /><a href=\"javascript:history.go(-1);\">点击这里返回</a></center>";
	}
	include($templatedir."message.tpl.php");
	exit();
	}




function gsendmail($to, $subject = 'No subject', $body) {    

global $smtpserver,$emailaddress,$emailid,$emailpwd;

	$smtp_access = $emailid; //Smtp认证的用户名，    
	$smtp_pwd=$emailpwd; //Smtp认证的密码，一般等同pop3密码    
	$smtp_server=$smtpserver; //SMTP服务器地址，类似 smtp.tom.com    
	$from=$emailaddress; //发信人Email地址，你的发信信箱地址    
	$headers = "Content-Type: text/plain; charset=\"gb2312\"\r\nContent-Transfer-Encoding: base64";    
	$br="\r\n"; 
  
	$hdr = explode($br,$headers);
	if($body) {$message = preg_replace("/^\./","..",explode($br,$body));}//解析后的Body    
  
$smtp = array(
	array("EHLO ".$smtp_server.$br,"220,250","HELO error: "), 
	array("AUTH LOGIN".$br,"334","AUTH error:"),     
	array(base64_encode($smtp_access).$br,"334","AUTHENTIFICATION error : "), 
	array(base64_encode($smtp_pwd).$br,"235","AUTHENTIFICATION error : ")
	); 
$smtp[] = array("MAIL FROM: <".$from.">".$br,"250","MAIL FROM error: ");    
$smtp[] = array("RCPT TO: <".$to.">".$br,"250","RCPT TO error: ");    
$smtp[] = array("DATA".$br,"354","DATA error: ");     
$smtp[] = array("From: ".$from.$br,"","");        
$smtp[] = array("To: ".$to.$br,"","");    
$smtp[] = array("Subject: ".$subject.$br,"","");    
foreach($hdr as $h) {
	$smtp[] = array($h.$br,"","");
}     
$smtp[] = array($br,"","");     
if($message){
	foreach($message as $msg) {
		$smtp[] = array(base64_encode($msg.$br).$br,"","");
		}
	}    
$smtp[] = array(".".$br,"250","DATA(end)error: ");    

$smtp[] = array("QUIT".$br,"221","QUIT error: ");    
    
$fp = @fsockopen($smtp_server, 25);
if (!$fp) echo "<b>Error:</b> Cannot conect to ".$smtp_server."<br>";    
while($result = @fgets($fp, 1024)){
	if(substr($result,3,1) == " ") {
		break; 
	}
}    

$result_str="";    

foreach($smtp as $req){
	@fputs($fp, $req[0]);    
	if($req[1]){
		while($result = @fgets($fp, 1024)){
		if(substr($result,3,1) == " ") {
			break;
		}
	}
	if (!strstr($req[1],substr($result,0,3))){
		$result_str.=$req[2].$result."<br>";
		}
	}
}
	@fclose($fp);
	return $result_str;
}    


function ismemberexist($member){
	if(is_array($member)&&!$member['uid']){
		$member['userid']='访客';
		$member['accessip']=$member['ip1'].'.'.$member['ip2'].'.*.*';
		$member['gid']=4;
		$member['userface']='01.png';
		}
	return $member;
}

 function form_select_var(){
	global $maincategory,$subcategory;
	$s="";
	foreach($maincategory as $key => $category){ 
	$s.="<option value=\"".$category['pid'].",".$key."\"  style=\"background-color:#b1c3d9\">".$category['categorytitle']."</option >";
			if(isset($subcategory[$key])){
				foreach($subcategory[$key] as $subkey =>$subone){
				$s.= "<option value=\"".$subone['pid'].",".$subkey."\">>>".$subone['categorytitle']."</option>";
			}
		}
	}
	return $s;
}





function accessforum(){
	global $access,$postaccesspwd,$accesspwd,$templatedir,$gid,$accessgroup,$forumurl,$forid,$charset,$templatedir,$sid,$_GSESSION,$sitename,$g_project_name,$g_project_version,$debuginfo,$timestamp,$companyname,$siteicp,$nav,$registerfilename,$registerlinkword,$sitename,$siteheadtitle,$db,$allowedforum;
	$access=intval($access);
	if($access==1){
		if($allowedforum){
			if(in_array($forid,explode(",",$allowedforum))){
				return;
			}
		}
		if($postaccesspwd){
			$postaccesspwd=md5($postaccesspwd);
			if(strcmp($accesspwd,$postaccesspwd)){
				showmsg("对不起,你输入的密码不正确");
			}else{
				if($allowedforum){
					if(!in_array($forid,explode(",",$allowedforum))){
					    $allowedforum.=','.$forid;
					}
				}else{
					$allowedforum=$forid;
				}
				$db->query("update g_sessions set allowedforum = '$allowedforum' where sid='$sid' limit 1");
			}
		}else{
			include($templatedir."accessforum.tpl.php");
			exit();
		}
	}elseif($access==2){
		if($gid!=1&&$gid!=$accessgroup){
			showmsg("对不起,您没有访问论坛的权限");
		}
	}
	if($forumurl){
		header("location:".$forumurl);
	}
}
  
?>