Scripts

Sessies beheer

Met deze class kan je sessies beheren. huidige versie : 1.0.4 voorbeeld: Docs: http://www.infernogm.com/data/cms/docs/ Het is handig om te gebruiken, maar kan problemen opleveren als je handmatig nog met $_SESSION gaat werken. Lees de documentatie voor meer info. Plaats vragen/bugs/requests hiero Voor set location cach moet je een root_path defineren: $root_path = './'; is de standaard

sessies-beheer
<?php
/**
 * Session control for "van der Berg CMS Framework"
 *
 * @name      van der Berg CMS Framework
 * @version   1.0.4
 * @author    iltar van der berg
 * @copyright free to use if comments remain intact
 * @since     23-12-2007
 * 
 * releases
 * 
 * 1.0.4 - 28.12.2007
 * - session_control::is_logged_in() now also checks if session_control::ip is equal to $_SERVER['REMOTE_ADDR']
 *   to prevent session hijacking and stealing
 * - added documentation for session_control::get_ip()
 * - added function session_control::get_user_id
 * - added public static $disable_sessions_start
 *   this will ignore the session_start() within the class default is false
 * - added public static $disable_set_session_in_destruct
 *   with this off, the sessions wil not be automaticly updated at __destruct
 * - added function session_control::__destruct()
 * 
 * 1.0.3 - 27.12.2007
 * - changed session_control::set_flood_date() date() to time()
 * - added function session_control::get_flood_date()
 * - added function session_control::get_ip()
 * - added function session_control::get_attempt()
 * 
 * 1.0.2 - 26.12.2007
 * - changed the handling of returns
 * - session_control::get_custom() now accepts an array for input. Note that if you search for 1,
 *   or only 1 is found, the return will NOT be an array
 * - session::unset_custom() array handling has been changed to speed up things a little
 * 
 * 1.0.1 - 25.12.2007
 * - fixed a bug returning an empty value in session_control::set_custom() when
 *   forgot to enter 'type_of_var|' in front of the string. It will now be str(string) standard
 * 
 * 1.0.0 - 23.12.2007
 * - initial release
 */
class session_control
{
	/**
	 * all available sessions (all declared private)
	 *
	 * @var $user_id
	 * @var $ip
	 * @var $logged_in
	 * @var $login_attempts
	 * @var $register_attempts
	 * @var $last_location_cache
	 * @var $last_post_date
	 * @var $last_reply_date
	 * @var $custom_sessions
	 */
	private $user_id;
	//private $session_id;          // not yet implemented
	private $ip;
	private $logged_in;
	private $login_attempts;
	private $register_attempts;
	private $last_location_cache;
	private $last_post_date;
	private $last_reply_date;
	private $custom_sessions;
	
	/**
	 * set this to false before creating the object to prevent session_start(), use this if you already have session_start() somwhere
	 *
	 * @var bool
	 */
	public static $disable_session_start = false;
	
	/**
	 * set this to true to do session_control::set_session() in session_control::__destruct()
	 *
	 * @var bool
	 */
	public static $disable_set_session_in_destruct = false;
	
	/**
	 * analyse the sessions and put them into the class
	 * 
	 * @return void
	 */
	public function __construct()
	{
		// analyse the sessions and put them in the class
		if(!self::$disable_session_start)
		{
			session_start();
		}
		
		$this->user_id             = isset($_SESSION['user_id'])             ? $_SESSION['user_id']             : (int)0;
		//$this->session_id          = isset($_SESSION['session_id'])          ? $_SESSION['session_id']          : (string)''; not yet implemented
		$this->ip                  = isset($_SESSION['ip'])                  ? $_SESSION['ip']                  : (string)'';
		$this->logged_in           = isset($_SESSION['logged_in'])           ? $_SESSION['logged_in']           : (bool)false;
		$this->login_attempts      = isset($_SESSION['login_attempts'])      ? $_SESSION['login_attempts']      : (int)0;
		$this->register_attempts   = isset($_SESSION['register_attempts'])   ? $_SESSION['register_attempts']   : (int)0;
		$this->last_location_cache = isset($_SESSION['last_location_cache']) ? $_SESSION['last_location_cache'] : (string)'index.php';
		$this->last_post_date      = isset($_SESSION['last_post_date'])      ? $_SESSION['last_post_date']      : (string)'';
		$this->last_reply_date     = isset($_SESSION['last_reply_date'])     ? $_SESSION['last_reply_date']     : (string)'';
		$this->custom_sessions     = isset($_SESSION['custom_sessions'])     ? $_SESSION['custom_sessions']     : array();
	}
	
	/**
	 * if the user is logged in, return the ip address
	 *
	 * @return mixed
	 */
	public function get_ip()
	{
		// check if user is logged in, if so, return the ip logged in from
		if($this->logged_in)
		{
			$return = $this->ip;
		}
		else
		{
			$return = null;
		}
		
		return $return;
	}
	
	/**
	 * if the user is logged in, return the user_id
	 *
	 * @return mixed
	 */
	public function get_user_id()
	{
		// check if user is logged in, if so, return the user_id
		if($this->logged_in)
		{
			$return = $this->user_id;
		}
		else
		{
			$return = null;
		}
		
		return $return;
	}
	
	/**
	 * Check if the user is logged in
	 *
	 * @return bool
	 */
	public function is_logged_in()
	{
		if
		(
			// check user_id
			!is_numeric($this->user_id) || $this->user_id == 0 || trim($this->user_id) == '' ||
			// check session_id
			//!is_string($this->session_id) || empty(trim($this->session_id)) || // not yet implemented
			// check ip
			!is_string($this->ip) || trim($this->ip) == '' || $this->ip != $_SERVER['REMOTE_ADDR'] ||
			// check logged_in
			!is_bool($this->logged_in) || trim($this->logged_in) == '' || $this->logged_in === false
		)
		{
			$this->unset_login();
			$return_this = null;
		}
		else
		{
			$return_this = true;
		}
		
		return $return_this;
	}
	
	/**
	 * create login session
	 *
	 * @param int $user_id
	 * @param string[optional] $ip
	 * @return bool
	 */
	public function set_login($user_id, $ip = null)
	{
		// set the login with the selected user id
		$this->logged_in = (bool)true;
		$this->user_id   = (int)$user_id;
		if(is_null($ip))
		{
			$this->ip = (string)$_SERVER['REMOTE_ADDR'];
		}
		else
		{
			$this->ip = (string)$ip;
		}
		
		return true;
	}
	
	/**
	 * empty the login
	 * 
	 * @return bool
	 */
	public function unset_login()
	{
		$this->logged_in = (bool)false;
		$this->user_id   = (int)0;
		$this->ip        = (string)'';
		
		return true;
	}
	
	/**
	 * input the location into the cach session
	 *
	 * @param string[optional] $location
	 * @param mixed[optional] $query_string
	 * @return bool
	 */
	public function set_location_cache($location = null, $query_string = null)
	{
		global $root_path;
		
		$qs_array = array();
		
		// check if the page has valid signs and exists, else redirect to index.php
		if(trim($location) == '' || !preg_match('#(\./([a-z]*[\-_][a-z]*/)*){0,1}([a-z]*[\.\-_][a-z]*)*\.php#i', $location) || !file_exists($root_path . $location))
		{
			$location = 'index.php';
		}
		// the file is valid and exists, now it's possible that the file uses a query string
		// check if the query string is valid
		elseif(is_array($query_string))
		{
			foreach($query_string as $key => $value)
			{
				if(!is_array($value) && preg_match('#[a-z][a-z0-9_]*#i', $value) && preg_match('#[a-z][a-z0-9_]*#i', $key) && $key != 'redir')
				{
					$qs_array[] = $key . '=' . $value;
				}
			}
			
			// create a location with the query_string in it xhtml valid
			$location .= '?' . implode('&amp;', $qs_array);
		}
		
		$this->last_location_cache = $location;
		return true;
	}
	
	/**
	 * set flood date moment it was posted, no params for reply and post. else set 'post' or 'reply'
	 *
	 * @param string[optional] $type_of_post
	 * @return bool
	 */
	public function set_flood_date($type_of_post = null)
	{
		// set the time in the selected session
		$date = time();
		
		switch($type_of_post)
		{
			case 'post':
				$this->last_post_date = $date;
				break;
			case 'reply':
				$this->last_reply_date = $date;
				break;
			default:
				$this->last_post_date = $this->last_reply_date = $date;
				break;
		}
		
		return true;
	}
	
	/**
	 * get the flood date
	 * type of post is either post or reply
	 * time period is the compare time in seconds
	 * return type is either boolean, seconds or session_time
	 * boolean will return if the time period has been passed
	 * seconds will return the remaining seconds
	 * session_time will return the time when it was set with time()
	 *
	 * @param string $type_of_post
	 * @param int[optional] $time_period
	 * @param int[optional] $return_type
	 * @return mixed
	 */
	public function get_flood_date($type_of_post, $time_period = 300, $return_type = 'bool')
	{
		// determine the session that is used
		switch($type_of_post)
		{
			case 'post':
				$type = $this->last_post_date;
				break;
			case 'reply':
				$type = $this->last_reply_date;
				break;
			default:
				$type = time();
				break;
		}
		
		// check what the user wants to return
		// bool is true if the difference is more than $time_period
		// seconds/int returns the difference in seconds between now, and when the session was set
		// session_time returns the time of the session
		switch($return_type)
		{
			case 'boolean':
			case 'bool':
				if((int)(time() - $type) >= (int)$time_period)
				{
					$return = true;
				}
				else
				{
					$return = null;
				}
				break;
			case 'sec':
			case 'second':
			case 'seconds':
			case 'int':
				if((int)(time() - $type) >= 0)
				{
					$return = (time() - $type);
				}
				else
				{
					$return = null;
				}
				break;
			case 'session':
			case 'time':
			case 'session_time':
			default:
				$return = $type;
				break;
		}
		
		return $return;
	}
	
	/**
	 * either increment, $this->login_attempts, $this->register_attempts or reset them to 0
	 *
	 * @param string $type_of_increment
	 * @return bool
	 */
	public function increment_attempt($type_of_increment = 'reset')
	{
		switch($type_of_increment)
		{
			case 'login':
				$this->login_attempts++;
				break;
			case 'register':
				$this->register_attempts++;	
				break;
			case 'reset':
			default:
				$this->login_attempts = (int)0;
				$this->register_attempts = (int)0;
				break;
		}
		
		return true;
	}
	
	/**
	 * get the login or register attempts
	 *
	 * @param string $type_of_attempt
	 * @return int
	 */
	public function get_attempt($type_of_attempt)
	{
		switch($type_of_attempt)
		{
			case 'login':
				$return = (int)$this->login_attempts;
				break;
			case 'register':
				$return = (int)$this->register_attempts;	
				break;
			default:
				$return = (int)0;
				break;
		}
		
		return $return;
	}
	
	/**
	 * create or update custom sessions eg 'session_key' => 'string|this is a string.' 
	 * please note that an array will overwrite the old one, use get_custom first to 
	 * merge te arrays, for arrays, resource and objects, please use $obj->set_custom($session_setup, '', false);
	 * 
	 * possible entries in front of the explode character
	 * int/integer
	 * bool/boolean
	 * empty/null
	 * obj/object
	 * array
	 * resource
	 * str/string
	 * resource - default
	 *
	 * @param array $session_setup
	 * @param string[optional] $explode_this_character
	 * @param bool[optional] $check_for_explode_in_value
	 * @return bool
	 */
	public function set_custom($session_setup, $explode_this_character = '|', $check_for_explode_in_value = true)
	{
		// check if it is an array
		if(is_array($session_setup))
		{
			// create a loop for each input session
			foreach($session_setup as $key => $value)
			{
				// check if explode is needed
				if($check_for_explode_in_value)
				{
					// check whether the explode character is found or not, if not, add str|
					if(!strpos($value, $explode_this_character))
					{
						$value = 'str|' . $value;
					}
					
					// explode the value
					$exploded = explode($explode_this_character, $value, 2);
					
					$exploded[0] = trim($exploded[0]);
					
					switch($exploded[0])
					{
						// it's an int
						case 'integer':
						case 'int':
							$session_setup[$key] = (int)$exploded[1];
							break;
							
						// it's a bool
						case 'boolean':
						case 'bool':
							$session_setup[$key] = (bool)$exploded[1];
							break;
							
						// it's empty
						case 'empty':
						case 'null':
							$session_setup[$key] = null;
							break;
							
						// it's an object
						case 'object':
						case 'obj':
							$session_setup[$key] = (object)$exploded[1];
							break;
							
						// it's an array
						case 'array':
							$session_setup[$key] = array();
							$session_setup[$key] = $exploded[1];
							break;
							
						// it's a resource
						case 'resource':
							$session_setup[$key] = $exploded[1];
							break;
						// it's a string
						case 'string':
						case 'str':
							$session_setup[$key] = (string)$exploded[1];
							break;
						default:
							$session_setup[$key] = $exploded[1];
						break;
					}
				}
			}
			
			// return the array, first the old one, than overwrite same values by the new one
			$this->custom_sessions = array_merge($this->custom_sessions, $session_setup);
			
			$return_this = true;
		}
		else
		{
			$return_this = null;
		}
		
		return $return_this;
	}
	
	/**
	 * remove the custom session eg "array('foo', 'bar')" will remove "foo" and "bar", "foo" will remove "foo"
	 *
	 * @param mixed $remove_this
	 * @return bool
	 */
	public function unset_custom($remove_this)
	{
		// check if input is array or not, if not, convert it inot one
		if(!is_array($remove_this))
		{
			$remove_this = array($remove_this);
		}
		
		// create a loop $value is the key of the custom_sessions
		foreach($remove_this as $key => $value)
		{
			if(array_key_exists($value, $this->custom_sessions))
			{
				$this->custom_sessions[$value] = null;
				unset($this->custom_sessions[$value]);
			}
		}
		
		return true;
	}
	
	/**
	 * get one array item back from the custom sessions
	 *
	 * @param mixed $search_for
	 * @return mixed
	 */
	public function get_custom($search_for)
	{	
		// if it is not a string, integer or array, return null
		if(!is_string($search_for) && !is_int(!$search_for) && !is_array($search_for))
		{
			return null;
		}
		
		// make it an array if it is not already
		if(!is_array($search_for))
		{
			$search_for = array($search_for);
		}
		
		// walk the array and check if the sessions exist
		foreach($search_for as $key => $value)
		{
			// if it exist add it to an array
			if(isset($this->custom_sessions[$value]))
			{
				$custom_sessions[] = $this->custom_sessions[$value];
			}
		}
		
		// check what to return, case 0: returns null, case 1: return (string)first array item, default: return the compleet result array
		switch(count($custom_sessions))
		{
			case 1:
				$return_this = (string)$custom_sessions[0];
				break;
			case 0:
				$return_this = null;
				break;
			default:
				$return_this = $custom_sessions;	
		}
		
		return $return_this;
	}
	
	/**
	 * return the values to the sessions
	 * 
	 * @return bool
	 */
	public function set_sessions()
	{
		$_SESSION['user_id']             = $this->user_id;
		//$_SESSION['session_id']          = $this->session_id; not yet implemented
		$_SESSION['ip']                  = $this->ip;
		$_SESSION['logged_in']           = $this->logged_in;
		$_SESSION['login_attempts']      = $this->login_attempts;
		$_SESSION['register_attempts']   = $this->register_attempts;
		$_SESSION['last_location_cache'] = $this->last_location_cache;
		$_SESSION['last_post_date']      = $this->last_post_date;
		$_SESSION['last_reply_date']     = $this->last_reply_date;
		$_SESSION['custom_sessions']     = $this->custom_sessions;
		
		return true;
	}
	
	/**
	 * automaticly set the sessions if $disable_set_session_in_destruct is false
	 * 
	 * @return void
	 */
	public function __destruct()
	{
		if(!self::$disable_set_session_in_destruct)
		{
			$this->set_sessions();
		}
	}
}

?>

Reacties

0
Nog geen reacties.