<?php
/* * *********************************************************
 * [cml] (C)2012 - 3000 cml http://linhecheng.com
 * @desc 数据库保存session
 * @Author  linhecheng<linhechengbush@live.com>
 * @Date: 13-8-9 下午2:22
 * *********************************************************** */
/*
CREATE TABLE `cml_session` (
    `id` char(32) NOT NULL,
	`value` varchar(5000) NOT NULL,
	`time` int(11) unsigned NOT NULL,
	PRIMARY KEY(`id`)
)ENGINE=MEMORY DEFAULT CHARSET=utf8;
*/

class CmlSession
{
	private $lifeTime; //session超时时间
	private $handler;

	public static function init()
	{
		$cmlSession = new CmlSession();
		$cmlSession->lifeTime = ini_get('session.gc_maxlifetime');
		if(C('SESSION_USER_LOC') == 'db') {
			$cmlSession->handler = M()->db();
		} else {
			$cmlSession->handler = M()->cache() ;
		}
		ini_set('session.save_handler', 'user');
		session_module_name('user');
		session_set_save_handler(
			array($cmlSession, 'open'), 
			array($cmlSession, 'close'), 
			array($cmlSession, 'read'),
			array($cmlSession, 'write'),
			array($cmlSession, 'destroy'), 
			array($cmlSession, 'gc')
		);
		ini_get('session.auto_start') || session_start(); //自动开启session
	}

	public function open($savePath, $sessionName)
	{
		return true;
	}

	public function close()
	{
		if(C('SESSION_USER_LOC') == 'db') {
			if(C('DEFAULT_DB.DRIVER') == 'MySql') {
				mysql_close($this->handler ->wlink);
			} else {
				$this->handler ->wlink = null;
			}
		}
		//$this->gc($this->lifeTime);
		return true;
	}

	public  function read($sessionId)
	{
		$result = $this->handler ->get('session-id-'.$sessionId);
		if(C('SESSION_USER_LOC') == 'db') {
			return $result ? $result[0]['value'] : null;
		} else {
			return $result ? $result : null;
		}
	}

	public function write($sessionId, $value)
	{
		if(C('SESSION_USER_LOC') == 'db') {
			$this->handler ->set('session', array(
				'id' => $sessionId,
				'value' => $value,
				'time' => time()
			));
		} else {
			$this->handler->set('session-id-'.$sessionId, $value, $this->lifeTime);
		}
		return true;
	}

	public function destroy($sessionId)
	{
		$this->handler->delete('session-id-'.$sessionId);
		return true;
	}

	public function gc($lifeTime = 0)
	{
		if(C('SESSION_USER_LOC') == 'db') {
			$lifeTime || $lifeTime = $this->lifeTime;
			$this->handler->exec('DELETE FROM `cml_session` where `time` < '.time()-$lifeTime);
		} else {
			//cache 本身会回收
		}
		return true;
	}

}