<?
/*将 SESSION 保存到数据库*/
class Session{
	
		private static $handler=null;
		private static $ip=null;
		private static $lifetime=null;
		private static $time=null;
		
		private static function init($handler){
				self::$handler=$handler;
				self::$ip = getip();
				self::$lifetime= 7*24*60*60;//ini_get('session.gc_maxlifetime');//身份过期时间
				self::$time=time();
		}
		
		static function start($db){
				
				//echo 'start';
				
				self::init($db);
				
				session_set_save_handler(
						array(__CLASS__,"open"),
						array(__CLASS__,"close"),
						array(__CLASS__,"read"),
						array(__CLASS__,"write"),
						array(__CLASS__,"destroy"),
						array(__CLASS__,"gc")
				
				);
				
				session_start();
				
		}
		public static function open($path,$name){
				
				//echo 'open';
				
				return true;
				
		}
		public static function close(){
				
				//echo 'close';
				self::$handler->close();
				return true;
				
		}
		public static function read($PHPSESSID){
				
				//echo 'read';
				
				$sql="select PHPSESSID,update_time,client_ip,data from hon6_session where PHPSESSID = '$PHPSESSID'";
								
				if(!$result = self::$handler->query_object($sql)){
						return '';	
				}
				
				if(self::$ip != $result->client_ip){
						self::destroy($PHPSESSID);
						return '';	
				}
				
				if(($result->update_time + self::$lifetime) < self::$time){
						self::destroy($PHPSESSID);
						return '';	
				}
				
				return $result->data;
		}
		public static function write($PHPSESSID,$data){
			
				//echo "write";
				
				$sql="select PHPSESSID,update_time,client_ip,data from hon6_session where PHPSESSID = '$PHPSESSID'";
				
				if($result = self::$handler->query_object($sql)){
						
						if($result->data != $data || self::$time > ($result->update_time+30)){
								
								$sql="update hon6_session set update_time = ".self::$time.",data = '$data' where PHPSESSID = '$PHPSESSID'";
						
								self::$handler->query($sql);
													
						}
					
				}else{
						if(!empty($data)){
								
								$sql = "insert into hon6_session(PHPSESSID,update_time,client_ip,data) values('$PHPSESSID',".self::$time.",'".self::$ip."','$data')";
								
								self::$handler->query($sql);
								
						}	
				}
				
				
				return true;
		}
		public static function destroy($PHPSESSID){
				
				//echo 'destroy';
				
				$sql="delete from hon6_session where PHPSESSID = '$PHPSESSID'";
				
				self::$handler->query($sql);
				
				return true;
		}
		private static function gc($lifetime){
			
				//echo 'gc';
			
				$ltime = self::$time-$lifetime;
			
				$sql = "delete from hon6_session where update_time < $ltime";
				
				self::$handler->query($sql);
				
				
				return true;
		}
		
}
?>