<?php
/*
+--------------------------------------------------------------------------
|   TanyaCMS - Question and Answer Sofware
|   -----------------------------------------------------------------------
|   by fbschool dev team
|   (c) 2011 - 2012 FBSCHOOL
|   http://www.fbschool.com/tanyacms
|   -----------------------------------------------------------------------
|   This is NOT a freeware, use is subject to license terms
|   Support: 13455n@gmail.com
+--------------------------------------------------------------------------
*/

class USER
{
	public static function &instance()
	{
		static $u;
		
		if (empty($u))
		{
			$u = new session_user(); //Used to verify SESSION, client record user information
		}
		
		return $u;
	}
	
	/// Get a session variable
	public static function get($key = false)
	{
		$u = &USER::instance();
		
		return $u->get_info($key);
	}
	
	///uid of the current visitor
	public static function get_client_uid()
	{
		return (int)USER::get('__CLIENT_UID');
	}
	
	/// Current visitor is logged, uid is empty unregistered
	public static function isuser_login()
	{
		$uid = USER::get('__CLIENT_UID');
		
		if ($uid > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}

/**
* A user class SESSION
*
* @author ibox
*
*/
class session_user
{
	// Save the client user information
	public static $server_user_info = array();

	public function __construct()
	{
		// cookie Clear the session also clears
		if ($_SESSION['client_info'] && ! $_COOKIE[GET_COOKIE_PREFIX . "_user_login"])
		{
			unset($_SESSION['client_info']);
		}
		
		// From off COOKIE, then validate
		if (! $_SESSION['client_info'] && $_COOKIE[GET_COOKIE_PREFIX . "_user_login"])
		{
			// Decode cookie
			$sso_user_login = H::decode_hash($_COOKIE[GET_COOKIE_PREFIX . "_user_login"]);
			
			$account_class = new account_class();
			
			if ($sso_user_login['user_name'] && $sso_user_login['password'] && $sso_user_login['uid'] && $_SERVER['HTTP_USER_AGENT'] == $sso_user_login['UA'])
			{			
				if ($account_class->check_hash_login($sso_user_login['user_name'], $sso_user_login['password']))
				{
					$_SESSION['client_info']['__CLIENT_UID'] = $sso_user_login['uid'];
					$_SESSION['client_info']['__CLIENT_USER_NAME'] = $sso_user_login['user_name'];
					$_SESSION['client_info']['__CLIENT_PASSWORD'] = $sso_user_login['password'];
										
					return true;
				}
			}
			
			return false;
		}
	}

	/**
	 * Returns information
	 *
	 *  @param $key Field name
	 */
	public function get_info($key)
	{
		return $_SESSION['client_info'][$key];
	}
}
