<?php
/**
 * -----------------------------------------------------------------------------
 *
 * SyL - Web Application Framework for PHP
 *
 * PHP version 4 (>= 4.3.x) or 5
 *
 * Copyright (C) 2006 k.watanabe
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * -----------------------------------------------------------------------------
 * @package   SyL
 * @author    k.watanabe <k.watanabe@syl.jp>
 * @copyright 2006 k.watanabe
 * @license   http://www.opensource.org/licenses/lgpl-license.php
 * @version   CVS: $Id: SyL_SessionDB.php,v 1.2 2006/12/25 17:30:18 seasonstream Exp $
 * @link      http://www.syl.jp/
 * -----------------------------------------------------------------------------
 */

/**
 * DBクラス
 */
require_once SYL_INCLUDE_DIR . '/lib/SyL_DB.php';

/**
 * DBセッション保持クラス
 *
 * 例）
 * CREATE TABLE SYL_SESSIONS ( 
 *   session_id varchar(32) NOT NULL, 
 *   session_expires int NOT NULL, 
 *   session_data text,
 *   PRIMARY KEY  (session_id)  
 * ); 
 * のようなテーブルを想定
 *
 * @package   SyL
 * @author    k.watanabe <k.watanabe@syl.jp>
 * @copyright 2006 k.watanabe
 * @license   http://www.opensource.org/licenses/lgpl-license.php
 * @version   CVS: $Id: SyL_SessionDB.php,v 1.2 2006/12/25 17:30:18 seasonstream Exp $
 * @link      http://www.syl.jp/
 */
class SyL_SessionDB
{ 
    /**
     * セッション保持時間
     *
     * @access private
     * @var int
     */
    var $life_time;
    /**
     * セッションテーブル名
     *
     * @access private
     * @var string
     */
    var $table;
    /**
     * セッションIDカラム名
     *
     * @access private
     * @var string
     */
    var $id;
    /**
     * セッションデータカラム名
     *
     * @access private
     * @var string
     */
    var $data;
    /**
     * セッションタイムスタンプカラム名
     *
     * @access private
     * @var string
     */
    var $timestamp;

    /**
     * DBコネクション
     *
     * @access private
     * @var object
     */
    var $conn = null; 

    /**
     * コンストラクタ
     *
     * @access public
     */
    function SyL_SessionDB()
    {
        session_set_save_handler(
          array(&$this, 'open'),
          array(&$this, 'close'),
          array(&$this, 'read'),
          array(&$this, 'write'),
          array(&$this, 'destroy'),
          array(&$this, 'gc')
        );

        if (!defined('SYL_SESSION_DB_TABLE') || !defined('SYL_DB_DSN')) {
            trigger_error("[SyL error] SyL_RequestSessionDB require constant SYL_SESSION_DB_TABLE and SYL_DB_DSN", E_USER_ERROR);
        }

        // テーブルプロパティ取得
        list($this->table, $this->id, $this->data, $this->timestamp) = explode(':', SYL_SESSION_DB_TABLE);

        if (!isset($_SESSION)) {
            session_start();
        }

   //register_shutdown_function('session_write_close');
    }

    /**
     * セッションオープンイベント
     *
     * @access public
     * @param string セッション保存パス
     * @param string セッション名
     * @return bool true: OK, false: NG
     */
    function open($save_path, $session_name)
    {
        $this->life_time = get_cfg_var("session.gc_maxlifetime"); 
        $this->conn =& SyL_DB::getConnection(SYL_DB_DSN);
        return is_object($this->conn);
    }

    /**
     * セッション読み込みイベント
     *
     * @access public
     * @param string セッションID
     * @return string セッションデータ
     */
    function read($session_id)
    {
        $sql  = "";
        $sql .= "SELECT ";
        $sql .=   "{$this->data} ";
        $sql .= "FROM ";
        $sql .=   "{$this->table} ";
        $sql .= "WHERE ";
        $sql .=   "{$this->id} = '$session_id' and ";
        $sql .=   "{$this->timestamp} >= " . time() . " ";

        $this->conn->executeGet($sql, $result, 'one');

        if (!$result) { 
            $sql  = "";
            $sql .= "INSERT INTO {$this->table} (";
            $sql .=   "{$this->id}, ";
            $sql .=   "{$this->timestamp}, ";
            $sql .=   "{$this->data} ";
            $sql .= ") VALUES ( ";
            $sql .=   "'{$session_id}', ";
            $sql .=   " " . (time() + $this->life_time) . ", ";
            $sql .=   "NULL ";
            $sql .= ") ";
            $this->conn->execute($sql, $result);
            $result = null;
        }
        return $result;
    }

    /**
     * セッション書き込みイベント
     *
     * @access public
     * @param string セッションID
     * @param string セッションデータ
     * @return bool true: OK, false: NG
     */
    function write($session_id, $session_data)
    {
        $sql  = "";
        $sql .= "UPDATE ";
        $sql .=   "{$this->table} ";
        $sql .= "SET ";
        $sql .=   "{$this->timestamp} = " . (time() + $this->life_time) . ", ";
        $sql .=   "{$this->data} = '{$session_data}' ";
        $sql .= "WHERE ";
        $sql .=   "{$this->id} = '{$session_id}' ";
        return $this->conn->execute($sql, $result);
    }

    /**
     * セッションクローズイベント
     *
     * @access public
     * @return bool true
     */
    function close()
    {
        return true;
    }

    /**
     * セッション削除イベント
     *
     * @access public
     * @param string セッションID
     * @return bool true: OK, false: NG
     */
    function destroy($session_id)
    {
        $sql  = "";
        $sql .= "DELETE FROM  ";
        $sql .=   "{$this->table} ";
        $sql .= "WHERE ";
        $sql .=   "{$this->id} = '$session_id'";
        return $this->conn->execute($sql, $result);
    }

    /**
     * 古いセッション情報の削除イベント
     *
     * @access public
     * @param int セッション保持時間
     * @return bool true: OK, false: NG
     */
    function gc($life_time)
    {
        $sql  = "";
        $sql .= "DELETE FROM  ";
        $sql .=   "{$this->table} ";
        $sql .= "WHERE ";
        $sql .=   "{$this->timestamp} < " . time() . " ";
        return $this->conn->execute($sql, $result);
    }
}

?>
