<?php

/**
 *--------------------------------------
 * COOKIE类
 *--------------------------------------
 * @project		: pfa
 * @author		: cblee
 * @created		: 2012-9-23
 * @copyright	: (c)2012 AsThis
 *--------------------------------------
 */

class ACookie
{
	/* 设置 */
	public static function set($name, $value = '', $key = null, $prefix = null, $expire = null, $path = null, $domain = null)
	{
		if(is_null($key))
		{
			$key = C('COOKIE.KEY');
		}

		if(is_null($prefix))
		{
			$prefix = C('COOKIE.PREFIX');
		}

		if(is_null($expire))
		{
			$expire = time() + C('COOKIE.EXPIRE');
		}
		else
		{
			$expire = time() + $expire;
		}

		if(is_null($path))
		{
			$path = C('COOKIE.PATH');
		}

		if(is_null($domain))
		{
			$domain = C('COOKIE.DOMAIN');
		}

		if(C('COOKIE.CILENT_CHECK'))
		{
			setcookie($prefix.'client_id', ACrypt::encrypt(AServer::get_clientId(), $key), $expire, $path, $domain);
		}

		$value = ACrypt::encrypt(serialize($value), $key);
		setCookie($prefix.$name, $value, $expire, $path, $domain);
	}

	/* 获取 */
	public static function get($name, $key = null, $prefix = null)
	{
		if(is_null($key))
		{
			$key = C('COOKIE.KEY');
		}

		if(is_null($prefix))
		{
			$prefix = C('COOKIE.PREFIX');
		}

		$is_checked = 1;
		if(C('COOKIE.CILENT_CHECK'))
		{
			$is_checked = self::check_clientId();
		}

		if(1 == $is_checked)
		{
			if(isset($_COOKIE[$prefix.$name]))
			{
				$cookie = unserialize(ACrypt::decrypt($_COOKIE[$prefix.$name], $key));
				return $cookie;
			}
			return '';
		}
		elseif(0 == $is_checked)
		{
			self::del($prefix.'client_id');
		}
		return '';
	}

	/* 删除 */
	public static function del($name, $key = null, $prefix = null)
	{
		self::set($name, '', $key, $prefix, -1000);
	}

	/* 清除所有的cookie数据 */
	public static function clear($prefix = null)
	{
		if(is_null($prefix))
		{
			$prefix = C('COOKIE.PREFIX');
		}
		$preLen = strlen($prefix);
		foreach($_COOKIE as $name => $val)
		{
			if(strpos($name, $prefix) === 0)
			{
				self::del(substr($name, $preLen), '', $prefix);
			}
		}
	}

	/* 检查客户端ID */
	private static function check_clientId()
	{
		$prefix = C('COOKIE.PREFIX');
		$key = C('COOKIE.KEY');
		if(isset($_COOKIE[$prefix.'client_id']))
		{
			if(AServer::get_clientId() == ACrypt::decrypt($_COOKIE[$prefix.'client_id'], $key))
			{
				return 1;
			}
			return 0;
		}
		return -1;
	}

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

?>