<?php

/**
 *--------------------------------------
 * 服务器信息相关
 *--------------------------------------
 * @project		: pfa
 * @author		: cblee
 * @created		: 2012-9-23
 * @copyright	: (c)2012 AsThis
 *--------------------------------------
 */

class AServer
{
	/* 获取客户端IP地址 */
	public static function get_ip()
	{
		$ip = '';
		if(!empty($_SERVER['HTTP_CLIENT_IP']))
		{
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		}
		if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
		{
			$ips = explode (',', $_SERVER['HTTP_X_FORWARDED_FOR']);
			if($ip)
			{
				array_unshift($ips, $ip);
				$ip = '';
			}
			for($i = 0; $i < count($ips); $i++)
			{
				if(!preg_match("/^(10|172\.16|192\.168)\./i", $ips[$i]))
				{
					$ip = $ips[$i];
					break;
				}
			}
		}
		$ip = $ip ? $ip : $_SERVER['REMOTE_ADDR'];
		preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $ip) or $ip = '0.0.0.0';
		return $ip;
	}

	/* 获取客户端浏览的上一个页面的url地址 */
	public static function get_preUrl()
	{
		return $_SERVER['HTTP_REFERER'];
	}

	/* 获取客户端当前访问的时间戳 */
	public static function get_time()
	{
		if(self::check_phpVersion('5.1.0'))
		{
			return self::get_env('REQUEST_TIME');
		}
		else
		{
			return time();
		}
	}

	/* 生成客户端ID */
	public static function get_clientId()
	{
		return md5(self::get_ip().self::get_env('HTTP_USER_AGENT'));
	}

	/* 获取环境信息 */
	public static function get_env($varName)
	{
		if(isset($_SERVER[$varName]))
		{
			return $_SERVER[$varName];
		}
		elseif(isset($_ENV[$varName]))
		{
			return $_ENV[$varName];
		}
		elseif(getenv($varName))
		{
			return getenv($varName);
		}
		elseif(function_exists('apache_getenv') && apache_getenv($varName, true))
		{
			return apache_getenv($varName, true);
		}
		return '';
	}

	/* 发送http状态 */
	public static function send_http_status($code)
	{
		static $_status = array(
			200 => 'OK', /** Success 2xx */
			/* Redirection 3xx */
			301 => 'Moved Permanently',
			302 => 'Moved Temporarily ',  /* 1.1 */
			/* Client Error 4xx */
			400 => 'Bad Request',
			403 => 'Forbidden',
			404 => 'Not Found',
			/* Server Error 5xx */
			500 => 'Internal Server Error',
			503 => 'Service Unavailable',
		);
		if(isset($_status[$code]))
		{
			header('HTTP/1.1 '.$code.' '.$_status[$code]);
			header('Status:'.$code.' '.$_status[$code]); /* 确保FastCGI模式下正常 */
		}
	}

	/* 服务器的php版本检查 */
	public static function check_phpVersion($version)
	{
		/* 获取当前php版本号 */
		$locVersion = phpversion();

		$result = version_compare($locVersion, $version);
		return ($result >= 0) ? true : false;
	}

	/* 构造函数私有化 */
	private function __construct(){}
}


?>