<?php

/**
 *--------------------------------------
 * session
 *--------------------------------------
 * @project		: pfa
 * @author		: cblee
 * @created		: 2012-9-23
 * @copyright	: (c)2012 AsThis
 *--------------------------------------
 */
defined('PFA_PATH') or exit('Access Denied');

if(!isset($_SESSION)) {
	session_start();
}
$session_id = ARequest::get(session_name());
if(!empty($session_id)) {
	session_id($session_id);
}
if(!isset($_SESSION['_pfa_session_initiated'])) {
	ASession::regenerate_id();
	$_SESSION['_pfa_session_initiated'] = true;
}

class ASession {
	public static function set($name, $value = '', $prefix = null) {
		$prefix = is_null($prefix) ? C('SESSION.PREFIX') : $prefix;

		if(C('SESSION.CLIENT_CHECK')) {
			$_SESSION[$prefix.'client_id'] = AServer::get_clientId();
		}

		$_SESSION[$prefix.$name] = $value;
	}

	public static function get($name = null, $prefix = null) {
		$prefix = is_null($prefix) ? C('SESSION.PREFIX') : $prefix;

		$is_checked = 1;
		if(C('SESSION.CLIENT_CHECK')) {
			$is_checked = self::_check_clientId();
		}

		if(1 == $is_checked) {
			if(is_null($name)) {
				$_s = array();
				foreach($_SESSION as $k => $v) {
					$_t_name = substr($k, strlen($prefix));
					if((substr($k, 0, strlen($prefix)) == $prefix) and 'client_id' != $_t_name) {
						$_s[$_t_name] = $v;
					}
				}
				return $_s;
			}
			return isset($_SESSION[$prefix.$name]) ? $_SESSION[$prefix.$name] : '';
		}
		elseif(0 == $is_checked) {
			self::del($prefix.'client_id');
		}
		return '';
	}

	public static function del($name, $prefix = null) {
		$prefix = is_null($prefix) ? C('SESSION.PREFIX') : $prefix;
		unset($_SESSION[$prefix.$name]);
	}

	/* clear session */
	public static function clear($destroy = false, $prefix = null) {
		if($destroy) {
			return session_destroy();
		}

		$prefix = is_null($prefix) ? C('SESSION.PREFIX') : $prefix;
		foreach($_SESSION as $key => $val) {
			if(strpos($key, $prefix) === 0) {
				unset($_SESSION[$key]);
			}
		}
	}

	public static function regenerate_id() {
		@session_start();
		session_regenerate_id(); // PHPSESSID's Cookie have not been writen yet.
		// for IE, when more than one PFA in a master domain.
		if(C('SESSION.MASTER_DOMAIN') and
			(strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE')
			or strpos($_SERVER["HTTP_USER_AGENT"], 'rv:11.0')
			or strpos($_SERVER["HTTP_USER_AGENT"], 'Edge')
			or strpos($_SERVER["HTTP_USER_AGENT"], 'IEMobile'))
		) {
			setcookie(session_name(), session_id(), null, '/', C('SESSION.MASTER_DOMAIN'));
		}
	}

	/* session client verify */
	private static function _check_clientId($prefix = null) {
		$prefix = is_null($prefix) ? C('SESSION.PREFIX') : $prefix;
		if(isset($_SESSION[$prefix.'client_id'])) {
			if(AServer::get_clientId() == $_SESSION[$prefix.'client_id']) {
				return 1;
			}
			return 0;
		}
		return - 1;
	}

	public function __construct() {
	}
}

?>