Scripts

Session class

Bij deze een sessie class waarmee je je eigen sessies kunt beheren. Sessie class heeft ongeveer alle functies die $_SESSION ook heeft, echter worden hiermee alle sessies opgeslagen in je database. Je kunt, met deze class, dus ook weer nieuwe functies erbij schrijven of wat je maar wilt. Hier onder even de functies uitgelegt die deze class bevatten.

Session.php
<?php
Class Session {
	
	private static $oInstance;
	private static $_iSessionId;
	private static $_iExpireTime = 3600;
	
		/**
		 * __constructs
		 *		Writes a new cookie with session id and saves it.
		 *
		 * @acces					private
		 *
		 * @returns 				void
		 **/

		private function __construct() {
			
			$iSessionId = self::generateSessionId();
			
			if(!isset($_COOKIE[ 'SynapsSessionId' ])) {
				setcookie('SynapsSessionId', $iSessionId, time() + self::$_iExpireTime);
				self::$_iSessionId = $iSessionId;
			} else {
				self::$_iSessionId = $_COOKIE[ 'SynapsSessionId' ];
				setcookie('SynapsSessionId', self::$_iSessionId, time() + self::$_iExpireTime);
			}
		}
		
		
		/**
		 * initialise
		 *		Singleton pattern, makes sure class can be loaded once.
		 *
		 * @acces					public static
		 * 
		 * @returns 				object
		 **/
		
		public static function initialise() {
			if (is_null(self::$oInstance)) {
				$c = __CLASS__;
				self::$oInstance = new $c;
			}
			return self::$oInstance;
		}
		
		
		/**
		 * get
		 *		Returns session if exists
		 *
		 * @acces					public static 
		 * 
		 * @returns 				value 
		 **/
		 
		public static function get($sKey) {
		
			$aKeys = explode('.', $sKey);
	
				try {
				
					$oGetSession = Database::pdo()->prepare(' SELECT sValue, sType, sKey
																FROM s_binSessions
																	WHERE sKey LIKE :sKey
																	AND sClientSessionId = :sClientSessionId
																	AND sClientIpAddress = :sClientIpAddress ');
																	
							$sLikeKey = $sKey.'%';
						$oGetSession->bindParam(':sKey', $sLikeKey, PDO::PARAM_STR);
						$oGetSession->bindParam(':sClientSessionId', self::$_iSessionId, PDO::PARAM_STR);
							$sClientIpAddress = new IpAddress();
						$oGetSession->bindParam(':sClientIpAddress', $sClientIpAddress->getIpAddress(), PDO::PARAM_STR);
						$oGetSession->execute();
						
						$rGetSession = $oGetSession->fetchAll(PDO::FETCH_ASSOC);
						
					} catch(PDOException $e) {
						throw new SessionException($e, SessionException::E_CORE_ERROR);
					}	
						
						if(count($rGetSession) > 1)  {
						    $aSessionData = array();
						 
						    foreach($rGetSession as $key => $value) {
						        $aKeys = explode('.', $value['sKey']);
						        $aNewArray = array();
						        $aPointer =& $aNewArray;
						 
						        foreach($aKeys as $sKey) {
						            if(!isset($aPointer[$sKey]) || !is_array($aPointer[$sKey])) $aPointer[$sKey] = Array();
						            $aPointer =& $aPointer[$sKey];
						        }
						
						        switch($value['sType']) {
						            case 'Object':
						                $mValue = unserialize($value['sValue']);
						            break;
						            case 'Integer':
						                $mValue = (int) $value['sValue'];
						            break;
						            case 'Array':
						                $mValue = unserialize($value['sValue']);
						            break;
						            case 'Float':
						                $mValue = (float) $value['sValue'];
						            break;
						            case 'String':
						                $mValue = (string) $value['sValue'];
						            break;
						            case 'Boolean':
						                $mValue = (bool) $value['sValue'];
						            break;
						            default:
						                $mValue = (string) $value['sValue'];
						        }
						 
						        $aPointer = $mValue;

						        $oCombineArray = new tbCombineArray;
						        $aSessionData = $oCombineArray->combineArray($aSessionData, $aNewArray);
						    }
						    
						    return $aSessionData;
								
							} else {
								switch($rGetSession[0]['sType']) {
									case 'Object':
										return unserialize($rGetSession[0]['sValue']);
										break;
									
									case 'Integer':
										return (int) $rGetSession[0]['sValue'];
										break;
										
									case 'Array':
										return unserialize($rGetSession[0]['sValue']);
										break;
										
									case 'Float':
										return (float) $rGetSession[0]['sValue'];
										break;
										
									case 'String':
										return (string) $rGetSession[0]['sValue'];
										break;
										
									case 'Boolean':
										return (bool) $rGetSession[0]['sValue'];
										break;
										
									default:
										return (string) $rGetSession[0]['sValue'];
								}
							}
		}
		
		
		/**
		 * set
		 *		sets a new value to a given session or creats a new one when nonexisting
		 *
		 * @acces					static public
		 *
		 * @returns 				boolean
		 **/
		
		public static function set($sKey, $sValue ) {
			try {
				$oCheckSession = Database::pdo()->prepare('SELECT sId
															FROM s_binSessions
																WHERE sKey = :sKey
																AND sClientSessionId = :sClientSessionId
																AND sClientIpAddress = :sClientIpAddress');
					
					$oCheckSession->bindParam(':sKey', $sKey, PDO::PARAM_STR);
					$oCheckSession->bindParam(':sClientSessionId', self::$_iSessionId, PDO::PARAM_STR);
						$sClientIpAddress = new IpAddress();
					$oCheckSession->bindParam(':sClientIpAddress', $sClientIpAddress->getIpAddress(), PDO::PARAM_STR);
					$oCheckSession->execute();
					$rCheckSession = $oCheckSession->fetchAll(PDO::FETCH_ASSOC);
					
					$sPreparedValue = ( is_array($sValue) || is_object($sValue) ) ? serialize($sValue) : $sValue;
			} catch(PDOException $e) {
				throw new SessionException($e, SessionException::E_CORE_ERROR);
			}
			
			if(count($rCheckSession) > 0 && is_array($rCheckSession)) {
			
				try {
					$oUpdateSession = Database::pdo()->prepare('UPDATE s_binSessions
																	SET sValue = :sValue,
																		sType = :sType,
																		sClientDate = NOW()
																		WHERE sKey = :sKey
																		AND sClientSessionId = :sClientSessionId
																		AND sClientIpAddress = :sClientIpAddress');
																		
						$oUpdateSession->bindParam(':sValue', $sPreparedValue, PDO::PARAM_STR); 
						$oUpdateSession->bindParam(':sKey', $sKey, PDO::PARAM_STR); 
						$oUpdateSession->bindParam(':sClientSessionId', self::$_iSessionId, PDO::PARAM_STR); 
							$sClientIpAddress = new IpAddress;
						$oUpdateSession->bindParam(':sClientIpAddress', $sClientIpAddress->getIpAddress(), PDO::PARAM_STR);
						$oUpdateSession->bindParam(':sType', self::Type($sValue), PDO::PARAM_STR);	
						$oUpdateSession->execute();
				} catch(PDOException $e) {
					throw new SessionException($e, SessionException::E_CORE_ERROR);
				}
					
			} else {
				try {
					$oNewSession = Database::pdo()->prepare('INSERT INTO s_binSessions
																		( 	sClientSessionId,
																			sClientIpAddress,
																			sClientDate,
																			sKey,
																			sValue,
																			sType	)
																	VALUES
																		( 	:sClientSessionId, 
																			:sClientIpAddress,
																			NOW(),
																			:sKey,
																			:sValue,
																			:sType					) ');
					
						$oNewSession->bindParam(':sClientSessionId', self::$_iSessionId, PDO::PARAM_STR);
							$sClientIpAddress = new IpAddress();
						$oNewSession->bindParam(':sClientIpAddress', $sClientIpAddress->getIpAddress(), PDO::PARAM_STR);
						$oNewSession->bindParam(':sKey', $sKey, PDO::PARAM_STR);
						$oNewSession->bindParam(':sValue', $sPreparedValue, PDO::PARAM_STR);
						$oNewSession->bindParam(':sType', self::Type($sValue), PDO::PARAM_STR);
						$oNewSession->execute();
					} catch(PDOException $e) {
						throw new SessionException($e, SessionException::E_CORE_ERROR);
					}
			}
		}
		
		
		/**
		 * delete
		 *		deletes given session
		 *
		 * @acces					static public
		 *
		 * @returns 				boolean
		 **/
		
		public static function delete($sKey) {
			$oCheckSessionType = Database::pdo()->prepare('DELETE
															FROM s_binSessions
																WHERE sKey LIKE :sKey
																AND sClientSessionId = :sClientSessionId
																AND sClientIpAddress = :sClientIpAddress');
																
				$sLikeKey = $sKey.'%';
				$oCheckSessionType->bindParam(':sKey', $sLikeKey, PDO::PARAM_STR);
				$oCheckSessionType->bindParam(':sClientSessionId', self::$_iSessionId, PDO::PARAM_STR);
					$sClientIpAddress = new IpAddress();
				$oCheckSessionType->bindParam(':sClientIpAddress', $sClientIpAddress->getIpAddress(), PDO::PARAM_STR);
					if($oCheckSessionType->execute()) {
						if( $oCheckSessionType->rowCount() > 0 ) {
							return true;
						} else {
							throw new SessionException('Can\'t return Type of a nonexisting session', SessionException::E_CORE_ERROR);
							return false;
						}
					} else {
						throw new SessionException('Can\'t return Type of a nonexisting session', SessionException::E_CORE_ERROR);
						return false;
					}
		}
		
		
		/**
		 * destroy
		 *		Ends the session.
		 *
		 * @acces					static public
		 *
		 * @returns 				boolean
		 **/
		
		public static function destroy() {
			setcookie ("SynapsSessionId", "", time() - 3600); 
			unset($_COOKIE['SynapsSessionId']); 
				
				if(isset($_COOKIE['SynapsSessionId']) && !empty($_COOKIE['SynapsSessionId'])) {
					throw new SessionException('Can\'t destroy session', SessionException::E_CORE_ERROR);
					return false;
				} else {
					self::$_iSessionId = null;
					return true;
				}
		}
		
		
		/**
		 * getType
		 *		Returns type of given session
		 *
		 * @acces					static public
		 *
		 * @returns 				string
		 **/
		
		public static function getType($sKey) {
			$oCheckSessionType = Database::pdo()->prepare('SELECT sType
															FROM s_binSessions
																WHERE sKey = :sKey
																AND sClientSessionId = :sClientSessionId
																AND sClientIpAddress = :sClientIpAddress
																	LIMIT 1');
				
				$oCheckSessionType->bindParam(':sKey', $sKey, PDO::PARAM_STR);
				$oCheckSessionType->bindParam(':sClientSessionId', self::$_iSessionId, PDO::PARAM_STR);
					$sClientIpAddress = new IpAddress();
				$oCheckSessionType->bindParam(':sClientIpAddress', $sClientIpAddress->getIpAddress(), PDO::PARAM_STR);
				
			if($oCheckSessionType->execute()) {
				$rCheckSession = $oCheckSessionType->fetch(PDO::FETCH_ASSOC);
					return $rCheckSession['sType'];
			} else {
				throw new SessionException('Can\'t return Type of a nonexisting session', SessionException::E_CORE_ERROR);
				return false;
			}
		}
		
		public static function exists($sKey) {
			try {
				$oCheckSession = Database::pdo()->prepare('SELECT sId
																FROM s_binSessions
																	WHERE sKey LIKE :sKey
																	AND sClientSessionId = :sClientSessionId
																	AND sClientIpAddress = :sClientIpAddress ');
					
					$sLikeKey = $sKey.'%';
					$oCheckSession->bindParam(':sKey', $sLikeKey, PDO::PARAM_STR);
					$oCheckSession->bindParam(':sClientSessionId', self::$_iSessionId, PDO::PARAM_STR);
						$sClientIpAddress = new IpAddress();
					$oCheckSession->bindParam(':sClientIpAddress', $sClientIpAddress->getIpAddress(), PDO::PARAM_STR);
					
				$oCheckSession->execute();
				
					$rCheckSession = $oCheckSession->fetchAll(PDO::FETCH_ASSOC);
						if(count($rCheckSession) > 0) {
							return true;
						} else {
							return false;
						}
				} catch(PDOException $e) {
					throw new SessionException($e, SessionException::E_CORE_ERROR);
					return false;
				}
		}
		
		public static function newId() {
			$sNewSessionId = self::generateSessionId();
			
			Database::pdo()->beginTransaction();
			
				$oCheckSessionType = Database::pdo()->prepare('UPDATE s_binSessions
																SET sClientSessionId = :sClientSessionIdNew
																		WHERE sClientSessionId = :sClientSessionId
																		AND sClientIpAddress = :sClientIpAddress ');
					
					$oCheckSessionType->bindParam(':sClientSessionIdNew', $sNewSessionId, PDO::PARAM_STR);
					$oCheckSessionType->bindParam(':sClientSessionId', self::$_iSessionId, PDO::PARAM_STR);
						$sClientIpAddress = new IpAddress();
					$oCheckSessionType->bindParam(':sClientIpAddress', $sClientIpAddress->getIpAddress(), PDO::PARAM_STR);
					
				if(setcookie('SynapsSessionId', $sNewSessionId, time() + self::$_iExpireTime)) {
					Database::pdo()->commit();
						return true;
				} else {
					Database::pdo()->rollBack();
						return false;
				}
		}
		
		public static function setExpireTime ($iExpireMinute) {
			if(is_int($iExpireMinute)) {
				self::$_iExpireTime = ($iExpireMinute * 60);
				setcookie ("SynapsSessionId", self::$_iSessionId, time() + self::$_iExpireTime);
			} else {
				throw new SessionException(__FUNCTION__.'needs a integer as parameter', SessionException::E_CORE_ERROR);
			}
		}
		
		
		/**
		 * getId
		 *		Returns current session id
		 *
		 * @acces					static public
		 *
		 * @returns 				string
		 **/
		
		public static function getId() {
			return self::$_iSessionId;
		}
		
		
		/**
		 * clone
		 *
		 * @acces					public
		 * 
		 * @returns 				void
		 **/
		
		public function __clone() {

		}
		
		
		/**
		 * destruct
		 *
		 * @acces					public
		 * 
		 * @returns 				void
		 **/
		
		public function __destruct() {

		}
		
		
		/**
		 * generateSessionId
		 *		Generates a unique id using characters and numbers
		 *
		 * @acces					private
		 *
		 * @returns 				string
		 **/
		
		private static function generateSessionId( ) {
			$sIdentity = '';
			$iIntegers = range(0,100);
			$sLowerCase = range('a','z');
			$sUpperCase = range('A','Z');
			
			$aChars = array_merge($iIntegers, $sLowerCase , $sUpperCase);
			
				for($i = 0; $i <= 50; $i++) {
						$sIdentity .= $aChars[rand(0,count($aChars)-1)];
				}
			
			return sha1(microtime().$sIdentity);
		}
		
		/**
		 * Type
		 *		returns the type of value
		 *
		 * @acces					static private
		 *
		 * @returns 				string
		 **/
		
		private static function Type( $sValue ) {
			if(is_string($sValue)) {
				return 'String';
			} elseif(is_bool($sValue)) {
				return 'Boolean';
			} elseif(is_float($sValue)) {
				return 'Float';
			} elseif(is_int($sValue)) {
				return 'Integer';
			} elseif(is_object($sValue)) {
				return 'Object';
			} elseif(is_array($sValue)) {
				return 'Array';
			} else {
				return 'String';
			}
		}
}
?>
SessionException.php
<?php
class SessionException extends Exception {

		#Constants with exception levels
		const E_ERROR			= 	1;
		const E_WARNING			= 	2;
		const E_PARSE			= 	4;
		const E_NOTICE			= 	8;
		const E_CORE_ERROR		= 	16;
		const E_CORE_WARNING	= 	32;
		const E_USER_ERROR		= 	256;
		const E_USER_WARNING	= 	512;
		const E_USER_NOTICE		= 	1024;
		const E_STRICT 			= 	2048;
		
		/**
		 * Constructor of class ServerException
		 *		Specifies custom error message with class name
		 *
		 * @acces					public
		 * 
		 * @param sMessage 			Custom error message
		 * @param sLevel			Exception level
		 *
		 * @returns 				void
		 **/
		
		public function __construct($sMessage = NULL, $sLevel = 1) {
			parent::__construct(__CLASS__.' threw: '.$sMessage, $sLevel);
		}
}
?>
tbCombineArray.php
<?php
Class tbCombineArray {
	
		public function __construct () {
		}
		
		/**
		 * combineArray
		 * 		combines 2 arrays
		 *
		 * @param aArray1 first array for combining
		 * @param aArray2 second array for combining
		 *
		 * @acces				public
		 *
		 * @return				array
		 **/
		 
		function combineArray($aArray1, $aArray2) {
			if(!is_array($aArray1) || !is_array($aArray2)) {
				return NULL;
			}
				$aNewArray = Array();
				
			foreach($aArray1 as $siIndex => $mValue){
				if(isset($aArray2[$siIndex]) && is_array($mValue) && is_array($aArray2[$siIndex])) {
					$aNewArray[$siIndex] = $this->combineArray($mValue, $aArray2[$siIndex]);
				} else {
					$aNewArray[$siIndex] = $aArray1[$siIndex];
				}
			}
			
			foreach($aArray2 as $siIndex => $mValue){
				if(!isset($aArray1[$siIndex])) {
					$aNewArray[$siIndex] = $aArray2[$siIndex];
				}
			}
		  return $aNewArray;
		} 
}
?>
IpAddress.php
<?php
class IpAddress {
    
	private $_sIpAddress;

		public function __construct() {
			$this->_sIpAddress = $_SERVER['REMOTE_ADDR'];
		}

		public function getIpAddress() {
			if(filter_var($this->_sIpAddress, FILTER_VALIDATE_IP)) {
				return (string) $this->_sIpAddress;
			} else {
				throw new SessionException('Global ip-address is not valid.', SessionException::E_CORE_ERROR);
					return false;
			}
		}
}
?>

Reacties

0
Nog geen reacties.