<?
/*
生成cache函数，参数说明如下;
$file 缓存文件名
$query 查询语句
$expire 缓存时间
实例：
include_once("ftbbsdbclass.php");
$ftbbsmb=makecache($file,$query,$expire);返回数组各值$ftbbsmb[0];……$ftbbsmb[N];
makecache($file,$query,$expire);只生成缓存文件不输出返回值.
后台参数有改动时只要调用makecache($file,0);
*/
function makecache($file,$query,$expire) {
   if (file_exists($file) && filemtime($file) > (time() - $expire)) { 
       $records = unserialize(file_get_contents($file));
    }
   else { 
    $result = mysql_query($query); 
    $records = mysql_fetch_array($result);
	
    $output = serialize($records); 
    $fp = fopen("cache/".$file,"w");
    fputs($fp, $output); 
    fclose($fp); 
    }
	return $records; //返回查询结果在数组$records中
}
function adminmakecache($file,$query,$expire) {
   if (file_exists($file) && filemtime($file) > (time() - $expire)) { 
       $records = unserialize(file_get_contents($file));
    }
   else { 
    $result = mysql_query($query); 
    $records = mysql_fetch_array($result);
	
    $output = serialize($records); 
	$fp = fopen($file,"w"); 
    fputs($fp, $output); 
    fclose($fp); 
    }
	return $records; 
}
//删除缓存文件
function delcache($file) {
   if (file_exists($file)){
    unlink($file);
   }
}
//设置cookies
function set_cookie($name, $value = "", $cookiedate = 0){
	global $_COOKIE,$_SERVER,$cookiedomain,$cookiepath,$cookieprename,$timestamp;
	empty($timestamp) AND ($timestamp = time());
	$cookiedomain = (empty($cookiedomain) OR $cookiedomain == "") ? ''  : $cookiedomain;
	$cookiepath   = (empty($cookiepath) OR $cookiepath   == "") ? '/' : $cookiepath;
	$name = $cookieprename.$name;
	$_COOKIE[$name] = $value;
	$tmpport = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	if (func_num_args() < 3) {  //返回传递给函数的参数的数量
		if (($tmp = intval(get_cookie('selected_cookiedate'))) > 0) {
			$cookiedate = $tmp;
		} else {
			$cookiedate = 30*24*3600;
			setcookie('selected_cookiedate', $cookiedate, $timestamp + $cookiedate, $cookiepath, $cookiedomain, $tmpport);
		}
	}
	setcookie($name, $value, $cookiedate ? $timestamp + $cookiedate : 0, $cookiepath, $cookiedomain, $tmpport);
}
//取得cookies
function get_cookie($name){
	global $_COOKIE,$cookieprename;
	if (isset($_COOKIE[$cookieprename.$name])) {
		$value = urldecode($_COOKIE[$cookieprename.$name]);
		if (get_magic_quotes_gpc()) {
			$value = addslashes(stripslashes($value));
		} else {
			$value = addslashes($value);
		}
		if ($name=="clubuser_id" || $name=="bz" || $name=="bbsadmin" || $name=="payuser" || $name=="bokeer"){
		    $value=intval($value);
		}
		return $value;
	}
	return FALSE;
}
/**
 * Description 根据系统时差返回日期/时间格式的值
 * @return int 返回基于系统时差的日期/时间格式的值
 */
function ftgmdate($dateformat = 'Y-m-d H:i:s', $timestamp = TIME_NOW)
{
	if (empty($dateformat)) {
		$dateformat = 'Y-m-d H:i:s';
	}
	$user_timezone_offset = getUserTimeZoneOffset();
	return gmdate($dateformat, $timestamp+$user_timezone_offset);
}//end function ftgmdate

/**
 * Description 获取当前用户（包括游客）的时差的秒数
 * @return int 返回当前用户（包括游客）的时差的秒数
 */
function getUserTimeZoneOffset()
{
	static $user_timezone_offset;
	if (!isset($timezoneoffset)) {
		if (defined('USER_TIMEZONE_OFFSET')) {
			$user_timezone_offset = USER_TIMEZONE_OFFSET;
		} else {
			global $userinfo;
			if (!empty($userinfo) AND is_numeric($userinfo['user_timezone_offset'])) {
				$user_timezone_offset = intval($userinfo['user_timezone_offset']);
			} elseif (is_numeric($offsetseconds = get_cookie('user_timezone_offset'))) {
				$user_timezone_offset = $offsetseconds;
			} elseif (isset($fsetting['timeoffset']) AND is_numeric($fsetting['timeoffset'])) {
				$user_timezone_offset = $fsetting['timeoffset'] * 3600;
			} else {
				$user_timezone_offset = date('Z');
			}
			define('USER_TIMEZONE_OFFSET', $user_timezone_offset);
		}
	}
	return $user_timezone_offset;
}//end function getUserTimeZoneOffset

/**
 * Description 返回已添加指定天数的日期（注：返回结果与时区无关）
 * @param mixed 可以是任意可被识别为日期和时间的日期表达式或字符串表达式
 * @param mixed 可以是任意可被识别为日期和时间的日期表达式或字符串表达式
 * @return string 返回已添加指定天数的字符串表现形式的日期。失败返回-1
 */
function addDays($date, $days, $returntimestamp = false)
{
	if (0 == $days) {
		return $date;
	}
	if (!is_numeric($days)) {
		return -1;
	}
	if ($days > 0) {
		$days = '+'.$days;
	}
	if (is_numeric($date)) {
		//return gmdate('Y-m-d H:i:s', strtotime('+'.$days.' day', $date));
		if (true === $returntimestamp) {
			return strtotime($days.' day', $date);
		} else {
			return gmdate('Y-m-d H:i:s', strtotime($days.' day', $date));
		}
	} else {
		$timestamp = @strtotime($date);
		if (-1 == $timestamp OR false === $timestamp) {
			return -1;
		}
		//return gmdate('Y-m-d H:i:s', strtotime('+'.$days.' day', $timestamp) + date('Z'));
		if (true === $returntimestamp) {
			return strtotime($days.' day', $timestamp) + date('Z');
		} else {
			return gmdate('Y-m-d H:i:s', strtotime($days.' day', $timestamp) + date('Z'));
		}
	}
	
}//end function addDays

/**
 * Description 对指定的 date 返回特定的日期格式 format（注：返回结果与时区无关）
 * @param mixed 可以是任意可被识别为日期和时间的日期表达式或字符串表达式
 * @param mixed 可以是任意可被识别为日期和时间的日期表达式或字符串表达式
 * @return string 返回日期的字符串表现形式。失败返回-1
 */
function dateFormat($date, $format)
{
	if (empty($date)) {
		return '';
	}
	if (is_numeric($date)) {
		return gmdate($format, $date);
	} else {
		if (!isDate($date)) {
			return -1;
		}
		$timestamp = @strtotime($date);
		if (-1 == $timestamp OR false === $timestamp) {
			return -1;
		}
		return gmdate($format, $timestamp + date('Z'));
	}
}//end function dateFormat

/**
 * Description 返回 Boolean 值指明某表达式是否是一个绝对日期/时间
 * @param mixed 可以是任意可被识别为日期和时间的日期表达式或字符串表达式
 * @return Boolean 返回 Boolean 值指明某表达式是否是一个绝对日期/时间
 */
function isDate($mixed)
{
	if (empty($mixed)) {
		return false;
	}
	/*if (false !== strpos($mixed, '-') OR false !== strpos($mixed, '+')) {
		return false;
	}//*/
	$timestamp = @strtotime($mixed);
	if (-1 == $timestamp OR false === $timestamp) {
		return false;
	}
	return true;
}//end function isDate

/**
 * Description 根据 date_part 返回两个日期 start_date 和 end_date 之间的时间间隔（注：返回结果与时区无关）
 * @param string 表示要添加的时间间隔
 * @param string 合法的日期文字
 * @param string 合法的日期文字
 * @return int 返回两个日期之间的时间间隔
 */
function dateDiff($date_part, $start_date, $end_date)
{
	if (empty($start_date) OR empty($end_date)) {
		return false;
	}
	if (is_numeric($start_date) AND is_numeric($end_date)) {
		$starttimestamp = $start_date;
		$endtimestamp = $end_date;
	} else {
		if (!isDate($start_date) OR !isDate($end_date)) {
			return -1;
		}
		$starttimestamp = @strtotime($start_date);
		if (-1 == $starttimestamp OR false === $starttimestamp) {
			return false;
		}
		$endtimestamp = @strtotime($end_date);
		if (-1 == $endtimestamp OR false === $endtimestamp) {
			return false;
		}
		$starttimestamp = $starttimestamp + date('Z');
		$endtimestamp = $endtimestamp + date('Z');
	}

	switch(strtoupper(trim($date_part)))
	{
		case "S":
		case "SECOND"://按秒计算，精确到秒
			return intval($endtimestamp - $starttimestamp);
			break;
		case "M":
		case "MINUTE"://按分计算，精确到分
			/*
			$starttimestamp = strtotime(gmdate('Y-m-d H:i:00', $starttimestamp));
			$endtimestamp = strtotime(gmdate('Y-m-d H:i:00', $endtimestamp));
			return intval(($endtimestamp - $starttimestamp) / 60);//*/
			$starttimestamp = $starttimestamp - ($starttimestamp % 60);
			$endtimestamp = $endtimestamp - ($endtimestamp % 60);
			return intval(($endtimestamp - $starttimestamp) / 60);
			break;
		case "H":
		case "HOUR"://按小时计算，精确到小时
			/*
			$starttimestamp = strtotime(gmdate('Y-m-d H:00:00', $starttimestamp));
			$endtimestamp = strtotime(gmdate('Y-m-d H:00:00', $endtimestamp));
			return intval(($endtimestamp - $starttimestamp) / 3600);//*/
			$starttimestamp = $starttimestamp - ($starttimestamp % 3600);
			$endtimestamp = $endtimestamp - ($endtimestamp % 3600);
			return intval(($endtimestamp - $starttimestamp) / 3600);
			break;
		case "D":
		case "DAY"://按天计算，精确到天
			/*
			$starttimestamp = strtotime(gmdate('Y-m-d 00:00:00', $starttimestamp));
			$endtimestamp = strtotime(gmdate('Y-m-d 00:00:00', $endtimestamp));
			return intval(($endtimestamp - $starttimestamp) / 86400);//*/
			$starttimestamp = $starttimestamp - ($starttimestamp % 86400);
			$endtimestamp = $endtimestamp - ($endtimestamp % 86400);
			return intval(($endtimestamp - $starttimestamp) / 86400);
			break;
		case "N":
		case "MONTH"://按月计算，精确到月
			$year_offset = intval(gmdate("Y",$endtimestamp)-gmdate("Y",$starttimestamp));
			$month_offset = intval(gmdate("m",$endtimestamp)-gmdate("m",$starttimestamp));
			return $year_offset*12+$month_offset;
			break;
		case "Y":
		case "YEAR"://按年计算，精确到年
			return intval(gmdate("Y",$endtimestamp)-gmdate("Y",$starttimestamp));
			break;
		case "WW":
		case "WEEK"://按星期计算，精确到星期
			/*
			$starttimestamp = strtotime(gmdate('Y-m-d 00:00:00', $starttimestamp));
			$endtimestamp = strtotime(gmdate('Y-m-d 00:00:00', $endtimestamp));
			return intval(($endtimestamp - $starttimestamp) / 604800);//*/
			$starttimestamp = $starttimestamp - ($starttimestamp % 86400);
			$endtimestamp = $endtimestamp - ($endtimestamp % 86400);
			return intval(($endtimestamp - $starttimestamp) / 604800);
			break;
		case "Q":
		case "QUARTER"://按季度计算，精确到季度
			$year_offset = intval(gmdate("Y",$endtimestamp)-gmdate("Y",$starttimestamp));
			$month_offset = intval(gmdate("m",$endtimestamp)-gmdate("m",$starttimestamp));
			return intval(($year_offset*12+$month_offset+1)/3);
			break;
		default:
			return FALSE;
	}
}//end function dateDiff

/**
 * Description 根据 date_part 在 date 上执行加 number 的操作（注：返回结果与时区无关）
 * @param string 表示要添加的时间间隔
 * @param int 表示要添加的时间间隔的个数
 * @param mixed unix时间戳或要添加 date_part 的表示日期的文字(它应该是一个合法的日期文字)
 * @param string 指定返回值的日期格式，如果指定的值为空字符串、flase、null，则表明返回值是时间戳
 * @return mixed 返回已添加指定时间间隔的字符串表示的日期或时间戳。
 */
function dateAdd($date_part, $number, $date, $return_format="Y-m-d H:i:s")
{
	if (!is_numeric($number)) {
		return NULL;
	}
	$type = gettype($date);
	if ('integer' === $type OR 'float' === $type OR 'double' === $type) {
		$timestamp = intval($date);
	} elseif ('string' === $type) {
		if (!isDate($date)) {
			return NULL;
		}
		//$timestamp = strtotime($date) + date('Z');
		$timestamp = @strtotime($date);
		if (-1 == $timestamp OR false === $timestamp) {
			return false;
		}
		$timestamp += date('Z');
	} else {
		return NULL;
	}
	$number = intval($number);
	$strtmp = '';
	$date_part = strtoupper(trim($date_part));
	switch ($date_part) {
		case 'Y':		//	按年进行计算
		case 'YEAR':	//	按年进行计算
			$strtmp = ' year ';
			break;
		case 'N':		//	按月进行计算
		case 'MONTH':	//	按月进行计算
			$strtmp = ' month ';
			break;
		case 'D':		//	按日进行计算
		case 'DAY':		//	按日进行计算
			$strtmp = ' day ';
			break;
		case 'H':		//	按小时进行计算
		case 'HOUR':	//	按小时进行计算
			$strtmp = ' hour ';
			break;
		case 'm':		//	按分钟进行计算
		case 'MINUTE':	//	按分钟进行计算
			$strtmp = ' minute ';
			break;
		case 's':		//	按秒钟进行计算
		case 'SECOND':	//	按秒钟进行计算
			$strtmp = ' second ';
			break;
		case 'ww':		//	按星期进行计算
		case 'WEEK':	//	按星期进行计算
			$strtmp = ' week ';
			break;
		case 'Q':		//	按季度进行计算
		case 'QUARTER':	//	按季度进行计算
			$number = $number * 3;
			$strtmp = ' month ';
			break;
		default:	//	如果没有指定日期格式，则返回时间戳
			$strtmp = '';
			return NULL;
			break;
	}//end switch
	if ($number >= 0) {
		$number = '+'.$number;
	}
	if ('' === trim($return_format)) {
		return strtotime($number.$strtmp, $timestamp);
	} else {
		return gmdate($return_format, strtotime($number.$strtmp, $timestamp));
	}
}//end function dateAdd
//过滤特殊字符
function FilterJS($v){
	if( !is_null($v) ){
		$arrPatterns = array( '/ /i' ,'/(&#)/i' ,'/(script)/i' ,'/(js:)/i' ,'/(value)/i' ,'/(about:)/i' ,'/(file:)/i' ,'/(Document.cookie)/i' ,'/(vbs:)/i' ,'/(on(mouse|Exit|error|click|key|load))/i' );
		$arrReplacements = array( '' ,'<I>&#</I>' ,'<I>script</I>' ,'<I>js:</I>' ,'<I>value</I>' ,'<I>about:</I>' ,'<I>file:</I>' ,'<I>Documents.cookie</I>' ,'<I>vbs:</I>' ,'<I>on$2</I>' );
		return htmlspecialchars(preg_replace($arrPatterns,$arrReplacements,$v));
	} else{
		return false;
	}
}
function GetUserIP() //获取用户IP地址
    {
        if($_SERVER['HTTP_X_FORWARDED_FOR'])
        {
             return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else if($_SERVER['HTTP_CLIENT_IP'])
        {
             return $_SERVER['HTTP_CLIENT_IP'];
        }else
        {
            return $_SERVER['REMOTE_ADDR'];
        }
    }
//IE
function browser($agent = '') 
{
	$expser = $expserver = '';
	if (empty($agent)) {
		$agent = $_SERVER["HTTP_USER_AGENT"];
	}
	$loweragent = strtolower($agent);
	if (false !== strpos($loweragent, 'mozilla')) {
		if (false !== strpos($loweragent, 'msie')) {
			$temp = explode('(', $agent);
			$temp = explode(';', $temp[1]);
			$temp = explode(' ', $temp[1]);
			$expserver = ' '.preg_replace('/([\d\.]+)/', '\\1', $temp[2]);
			$expser = "Internet Explorer";
		} else {
			$temp = explode('(', $agent);
			$temp = explode('/', $temp[0]);
			$expserver = $temp[1];
			$temp = explode(' ', $expserver);
			$expserver = ' '.preg_replace('/([\d\.]+)/', '\\1', $temp[0]);
			if (false !== strpos($loweragent, 'opera')) {
				$expser = 'Opera';
			} elseif (false !== strpos($loweragent, 'netscape')) {
				$expser = 'Netscape';
			} elseif (false !== strpos($loweragent, 'firefox')) {
				$expserver = '';
				$expser = str_replace('/', ' ', substr($agent, strpos($loweragent, 'firefox')));
			} elseif (false !== strpos($loweragent, 'rv:')) {
				$expser = 'rv:';
			} else {
			$expser = 'Netscape Navigator';
			}
		}
	}
	if ($expser != '') {
		$expseinfo = "{$expser}{$expserver}";
	} else {
		$expseinfo = 'Unknown';
	}
	return addslashes($expseinfo);
}
//用户系统信息
function sysinfo($agent = '')
{
	$sys = 'Unknown';
	if (empty($agent)) {
		$agent = $_SERVER["HTTP_USER_AGENT"];
	}
	$loweragent = strtolower($agent);
	if (false !== strpos($loweragent, 'win')) {
		$sys = 'Windows ';
		if (false !== strpos($loweragent, 'nt')) {
			if (false !== strpos($loweragent, '5.2')) {
				$sys .= '2003';
			} elseif (false !== strpos($loweragent, '5.1')) {
				$sys .= 'XP';
			} elseif (false !== strpos($loweragent, '5.0')) {
				$sys .= '2000';
			} elseif (false !== strpos($loweragent, '4.0')) {
				$sys .= 'NT';
			}
		} elseif (false !== strpos($loweragent, '98')) {
			$sys .= '98';
		} elseif (false !== strpos($loweragent, '9x') AND false !== strpos($loweragent, '4.90')) {
			$sys .= 'ME';
		} elseif (false !== strpos($loweragent, '95')) {
			$sys .= '95';
		} elseif (false !== strpos($loweragent, '32')) {
			$sys .= '32';
		}
	} else {
		if (false !== strpos($loweragent, 'linux')) {
			$sys = 'Linux';
		} elseif (false !== strpos($loweragent, 'unix')) {
			$sys = 'Unix';
		} elseif (false !== strpos($loweragent, 'ibm') AND false !== strpos($loweragent, 'os')) {
			$sys = 'IBM OS/2';
		} elseif (false !== strpos($loweragent, 'netbsd')) {
			$sys = 'NetBSD';
		} elseif (false !== strpos($loweragent, 'bsd')) {
			$sys = 'BSD';
		} elseif (false !== strpos($loweragent, 'freebsd')) {
			$sys = 'FreeBSD';
		}
	}
	return addslashes($sys);
}
//用户名检查
function CheckName($name){
	//if (1 == preg_match('/\s+/i', $name)) {	//	用户名中不允许存在空白字符
		//return false;
	//}
	//if (1 == preg_match('/=|%|'.chr(32).'|\?|&|;|\||,|\'|'.chr(34).'|'.chr(9).'||\$/i',$name)) {
	//if (1 == preg_match('/\x2f|\x5c|\x27|\x22|=|%|'.chr(32).'|\?|&|;|\||,|\'|'.chr(34).'|'.chr(9).'||\$/i',$name)) {
	//if (1 == preg_match("/\!|\@|\#|\$|\%|\,|\;|\{|\)/",$name)){ //判断注册用户名中不能包含!@#$%,;'{)等特殊字符
	    //return false;
	//}
	if (1 == preg_match('/[^a-z0-9\-_.]/i', $name)) { //判断用户名只能为 中文，英文，数字和下划线
	    return false;
	}
	//if (1 !== preg_match('/^(?:[-\w]|[\x80-\xff])+$/im', $name)) {
		//return false;
	//}
	//简体编码的全角空白符\xa1\xa1	繁体编码的全角空白符\xa1\x40	utf-8编码的全角空白符\xe3\x80\x80
	//if (1 == preg_match('/\xa1\xa1|\xa1\x40|\xe3\x80\x80/i', $name)) {
		//return false;
	//}
	//$charscope = '\x'.strtoupper(dechex(10)).'-\x'.dechex(ord('A')-1).'\x'.dechex(ord('Z')+1).'-\x'.dechex(ord('a')-1).'-\x'.dechex(ord('z')+1).'\x'.dechex(ord('_')).'';
	//if (1 == preg_match('#^['.$charscope.']+$#i', $name)) {
		//return false;
	//}
	return true;
}

Function sh($t1,$t2){
   $ymd=date("Y-m-d");
   $xiao=$ymd." ".$t1;
   $now=date("Y-m-d H:i");
   $da=$ymd." ".$t2;
   $a=dateDiff("S", $xiao, $now); //小--->$now
   $b=dateDiff("S", $now, $da); //$now-->大
   if ($a>0 && $b>0){
   $shva=0;
   }
   else{
   $shva=1;
   }
   return $shva;
}
//错误信息返回函数
Function login_msg($msg,$reurl){
   header("Location:".$reurl."?msg=".$msg);
}
Function ftbbs_msg($msg,$reurl){
   echo "<script language='javascript'>";
   echo "alert('".$msg."');";
   echo "window.location.href='".$reurl."';";
   echo "</script>";
}
?>