steffen: server/kolab-horde-framework/kolab-horde-framework/SessionHandler/SessionHandler dbm.php, NONE, 1.1 mysql.php, NONE, 1.1 oci8.php, NONE, 1.1 pgsql.php, NONE, 1.1 sapdb.php, NONE, 1.1 sql.php, NONE, 1.1

cvs at intevation.de cvs at intevation.de
Fri Oct 14 16:33:13 CEST 2005


Author: steffen

Update of /kolabrepository/server/kolab-horde-framework/kolab-horde-framework/SessionHandler/SessionHandler
In directory doto:/tmp/cvs-serv28903/kolab-horde-framework/kolab-horde-framework/SessionHandler/SessionHandler

Added Files:
	dbm.php mysql.php oci8.php pgsql.php sapdb.php sql.php 
Log Message:
Separated Horde Framework from kolab-resource-handlers

--- NEW FILE: dbm.php ---
<?php
/**
 * SessionHandler:: implementation for DBM files.
 * NOTE: The PHP DBM functions are deprecated.
 *
 * No additional configuration parameters needed.
 *
 * $Horde: framework/SessionHandler/SessionHandler/dbm.php,v 1.9 2004/01/01 15:14:27 jan Exp $
 *
 * Copyright 2002-2004 Chuck Hagenbuch <chuck at horde.org>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Chuck Hagenbuch <chuck at horde.org>
 * @version $Revision: 1.1 $
 * @since   Horde 3.0
 * @package Horde_SessionHandler
 */
class SessionHandler_dbm extends SessionHandler {

    /**
     * Our pointer to the DBM file, if open.
     *
     * @var resource $_dbm
     */
    var $_dbm;

    /**
     * Constructs a new DBM SessionHandler object.
     *
     * @access public
     *
     * @param optional array $params  [Unused].
     */
    function SessionHandler_dbm($params = array())
    {
    }

    /**
     * TODO
     */
    function open($save_path, $session_name)
    {
        $this->_dbm = @dbmopen("$save_path/$session_name", 'c');
        return $this->_dbm;
    }

    /**
     * TODO
     */
    function close()
    {
        return @dbmclose($this->_dbm);
    }

    /**
     * TODO
     */
    function read($id)
    {
        if ($data = dbmfetch($this->_dbm, $id)) {
            return base64_decode(substr($data, strpos($data, '|') + 1));
        } else {
            return '';
        }
    }

    /**
     * TODO
     */
    function write($id, $session_data)
    {
        return @dbmreplace($this->_dbm, $id, time() . '|' . base64_encode($session_data));
    }

    /**
     * TODO
     */
    function destroy($id)
    {
        if (!(@dbmdelete($this->_dbm, $id))) {
            Horde::logMessage('Failed to delete session (id = ' . $id . ')', __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        return true;
    }

    /**
     * TODO
     */
    function gc($maxlifetime = 300) 
    {
        $expired = time() - $maxlifetime;
        $id = dbmfirstkey($this->_dbm);

        while ($id) {
            if ($data = dbmfetch($this->_dbm, $id)) {
                $age = substr($tmp, 0, strpos($data, '|'));
                if ($expired > $age) {
                    $this->destroy($id);
                }
            }

            $id = dbmnextkey($this->_dbm, $id);
        }

        return true;
    }

}

--- NEW FILE: mysql.php ---
<?php
/**
 * SessionHandler:: implementation for MySQL (native).
 *
 * Required values for $params:<pre>
 *     'hostspec'  --  The hostname of the database server.
 *     'protocol'  --  The communication protocol ('tcp', 'unix', etc.).
 *     'username'  --  The username with which to connect to the database.
 *     'password'  --  The password associated with 'username'.
 *     'database'  --  The name of the database.
 *     'table'     --  The name of the sessiondata table in 'database'.</pre>
 *
 * Required for some configurations:
 *     'port'  --  The port on which to connect to the database.
 *
 * Optional parameters:
 *     'persistent'  --  Use persistent DB connections? (boolean)
 *
 * The table structure can be created by the scripts/db/sessionhandler.sql
 * script.
 *
 * $Horde: framework/SessionHandler/SessionHandler/mysql.php,v 1.16 2004/01/01 15:14:28 jan Exp $
 *
 * Copyright 2002-2004 Mike Cochrane <mike at graftonhall.co.nz>
 * Copyright 2002-2004 Chuck Hagenbuch <chuck at horde.org>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Mike Cochrame <mike at graftonhall.co.nz>
 * @version $Revision: 1.1 $
 * @since   Horde 3.0
 * @package Horde_SessionHandler
 */
class SessionHandler_mysql extends SessionHandler {

    /**
     * Hash containing connection parameters.
     *
     * @var array $_params
     */
    var $_params = array();

    /**
     * Handle for the current database connection.
     *
     * @var resource $_db
     */
    var $_db;

    /**
     * Are we connected to the SQL server.
     *
     * @var boolean $_connected
     */
    var $_connected = false;

    /**
     * Constructs a new MySQL SessionHandler object.
     *
     * @access public
     *
     * @param optional array $params  A hash containing connection parameters.
     *                                See details above.
     */
    function SessionHandler_mysql($params = array())
    {
        $this->_params = $params;
    }

    /**
     * TODO
     */
    function open($save_path, $session_name)
    {
        /* Connect to database. */
        $this->_connect();
    }

    /**
     * TODO
     */
    function close()
    {
        /* Disconnect from database. */
        $this->_disconnect();
    }

    /**
     * TODO
     */
    function read($id)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Session timeout, don't rely on garbage collection */
        $timeout = time() - ini_get('session.gc_maxlifetime');

        $query = sprintf('SELECT session_data FROM %s WHERE session_id = %s' .
                         ' AND session_lastmodified > %s',
                         $this->_params['table'],
                         $this->_quote($id),
                         $timeout);

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_mysql::read(): query = "%s"', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        $result = @mysql_query($query, $this->_db);
        if (!$result){
            Horde::logMessage('Error retrieving session data (id = ' . $id . ')',
                              __FILE__, __LINE__, PEAR_LOG_ERR);
            return '';
        }
            list($value) = mysql_fetch_row($result);
            return $value;
    }

    /**
     * TODO
     */
    function write($id, $session_data)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        $query = sprintf('REPLACE INTO %s (session_id, session_data, session_lastmodified)' .
                         ' VALUES (%s, %s, %s)',
                         $this->_params['table'],
                         $this->_quote($id),
                         $this->_quote($session_data),
                         time());

        $result = mysql_query($query, $this->_db);
        if (!$result){
            Horde::logMessage('Error writing session data', __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        return true;
    }

    /**
     * TODO
     */
    function destroy($id)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        $query = sprintf('DELETE FROM %s WHERE session_id = %s',
                         $this->_params['table'], $this->_quote($id));

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_mysql::destroy(): query = "%s"', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query. */
        $result = @mysql_query($query, $this->_db);
        if (!$result) {
            Horde::logMessage('Failed to delete session (id = ' . $id . ')', __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        return true;
    }

    /**
     * TODO
     */
    function gc($maxlifetime = 300)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        $query = sprintf('DELETE FROM %s WHERE session_lastmodified < %s',
                         $this->_params['table'], (int)(time() - $maxlifetime));

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_mysql::gc(): query = "%s"', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query. */
        $result = @mysql_query($query, $this->_db);
        if (!$result) {
            Horde::logMessage('Error garbage collecting old sessions', __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        return @mysql_affected_rows($this->_db);
    }

    /**
     * Escape a mysql string.
     *
     * @access private
     *
     * @param string $value  The string to quote.
     *
     * @return string  The quoted string.
     */
    function _quote($value)
    {
        switch (strtolower(gettype($value))) {
        case 'null':
            return 'NULL';

        case 'integer':
            return $value;

        case 'string':
        default:
            return "'" . mysql_real_escape_string($value) . "'";
        }
    }

    /**
     * Attempts to open a connection to the SQL server.
     *
     * @access private
     */
    function _connect()
    {
        if ($this->_connected) {
            return;
        }

        Horde::assertDriverConfig($this->_params, 'sessionhandler',
            array('hostspec', 'username', 'database', 'password'),
            'session handler MySQL');

        if (empty($this->_params['table'])) {
            $this->_params['table'] = 'horde_sessionhandler';
        }

        if (empty($this->_params['persistent'])) {
            $connect = 'mysql_connect';
        } else {
            $connect = 'mysql_pconnect';
        }

        if (!$this->_db = @$connect($this->_params['hostspec'],
                                    $this->_params['username'],
                                    $this->_params['password'])) {
            Horde::fatal(PEAR::raiseError('Could not connect to database for SQL SessionHandler.'), __FILE__, __LINE__);
        }

        if (!@mysql_select_db($this->_params['database'], $this->_db)) {
            Horde::fatal(PEAR::raiseError(sprintf('Could not connect to table %s for SQL SessionHandler.', $this->_params['database']), __FILE__, __LINE__));
        }

        $this->_connected = true;
    }

    /**
     * Disconnect from the SQL server and clean up the connection.
     *
     * @access private
     */
    function _disconnect()
    {
        if ($this->_connected) {
            return @mysql_close($this->_db);
        }
        $this->_connected = false;
    }

}

--- NEW FILE: oci8.php ---
<?php
/**
 * SessionHandler:: implementation for Oracle 8i (native).
 *
 * Required values for $params:<pre>
 *     'hostspec'  --  The hostname of the database server.
 *     'protocol'  --  The communication protocol ('tcp', 'unix', etc.).
 *     'username'  --  The username with which to connect to the database.
 *     'password'  --  The password associated with 'username'.
 *     'database'  --  The name of the database.
 *     'table'     --  The name of the sessiondata table in 'database'.</pre>
 *
 * Required for some configurations:
 *     'port'  --  The port on which to connect to the database.
 *
 * Optional parameters:
 *     'persistent'  --  Use persistent DB connections? (boolean)
 *
 * The table structure can be created by the scripts/db/sessionhandler.sql
 * script.
 *
 * $Horde: framework/SessionHandler/SessionHandler/oci8.php,v 1.7 2004/01/01 15:14:28 jan Exp $
 *
 * Copyright 2003-2004 Liam Hoekenga <liamr at umich.edu>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Liam Hoekenga <liamr at umich.edu>
 * @version $Revision: 1.1 $
 * @since   Horde 2.2
 * @package Horde_SessionHandler
 */
class SessionHandler_oci8 extends SessionHandler {

    /**
     * Hash containing connection parameters.
     *
     * @var array $_params
     */
    var $_params = array();

    /**
     * Handle for the current database connection.
     *
     * @var resource $_db
     */
    var $_db;

    /**
     * Are we connected to the SQL server.
     *
     * @var boolean $_connected
     */
    var $_connected = false;

    /**
     * The quote function to use.
     *
     * @var string $_quote
     */
    var $_quote = null;

    /**
     * Constructs a new Oracle8 SessionHandler object.
     *
     * @access public
     *
     * @param optional array $params  A hash containing connection parameters.
     *                                See details above.
     */
    function SessionHandler_oci8($params = array())
    {
        $this->_params = $params;
    }

    function open($save_path, $session_name)
    {
        /* Connect to database. */
        $this->_connect();
    }

    function close()
    {
        /* Disconnect from database. */
        $this->_disconnect();
    }

    function read($id)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        $select_query = sprintf('SELECT session_data FROM %s WHERE session_id = %s',
                $this->_params['table'], $this->_quote($id));

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_oci8::read(): query = "%s"', $select_query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute query */
        $select_statement = OCIParse($this->_db, $select_query);
        OCIExecute($select_statement);
        if (!OCIFetchInto($select_statement, $result)) {
            $insert_query = sprintf('INSERT INTO %s (session_id, session_lastmodified, session_data) VALUES (%s, %s, EMPTY_BLOB()) RETURNING session_data INTO :blob',
                    $this->_params['table'],
                    $this->_quote($id),
                    $this->_quote(time()));
            $insert_statement = OCIParse($this->_db, $insert_query);
            $lob = OCINewDescriptor($this->_db);
            OCIBindByName($insert_statement, ':blob', $lob, -1, SQLT_BLOB);
            OCIExecute($insert_statement, OCI_DEFAULT);
            if ($session_data) {
                $lob->save($session_data);
            }
            $result = OCICommit($this->_db);
            OCIFreeStatement($insert_statement);
            OCIExecute($select_statement);
            OCIFetchInto($select_statement, $result);
        }
        $value = $result[0]->load();
        OCIFreeStatement($select_statement);
        return($value);
    }

    function write($id, $session_data)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        /* there has to be a better way to to do this... */
        $query = sprintf('UPDATE %s SET session_lastmodified = %s, session_data = EMPTY_BLOB() WHERE session_id = %s RETURNING session_data INTO :blob',
                $this->_params['table'],
                $this->_quote(time()),
                $this->_quote($id));

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_oci8::write(): query = "%s"', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute query */
        $statement = OCIParse($this->_db, $query);
        $lob = OCINewDescriptor($this->_db);
        OCIBindByName($statement, ':blob', $lob, -1, SQLT_BLOB);
        OCIExecute($statement, OCI_DEFAULT);
        if ($session_data) {
            $lob->save($session_data);
        }
        $result = OCICommit($this->_db);
        if (!$result){
            Horde::logMessage('Error writing session data', __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        return true;
    }

    function destroy($id)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        $query = sprintf( 'DELETE FROM %s WHERE session_id = %s',
                $this->_params['table'], $this->_quote($id));

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_oci8::destroy(): query = "%s"', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query. */
        $statement = OCIParse($this->_db, $query);
        $result = OCIExecute($statement);
        if (!$result) {
            OCIFreeStatement($statement);
            Horde::logMessage('Failed to delete session (id = ' . $id . ')', __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        OCIFreeStatement($statement);
        return true;
    }

    function gc($maxlifetime = 1)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        $query = sprintf('DELETE FROM %s WHERE session_lastmodified < %s',
                         $this->_params['table'], $this->_quote(time() - $maxlifetime));

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_oci8::gc(): query = "%s"', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query. */
        $statement = OCIParse($this->_db, $query);
        $result = OCIExecute($statement);
        if (!$result) {
            OCIFreeStatement($statement);
            Horde::logMessage('Error garbage collecting old sessions', __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        OCIFreeStatement($statement);
        return true;
    }

    /**
     * Escape a string for insertion.   stolen from PEAR::DB
     * @access private
     *
     * @param string $value  The string to quote.
     *
     * @return string  The quoted string.
     */
    function _quote($value)
    {
        return ($value === null) ? 'NULL' : "'" . str_replace("'", "''", $value) . "'";
    }

    /**
     * Attempts to open a connection to the SQL server.
     *
     * @access private
     */
    function _connect()
    {
        if ($this->_connected) {
            return;
        }

        Horde::assertDriverConfig($this->_params, 'sessionhandler',
            array('hostspec', 'username', 'database', 'password'),
            'session handler Oracle');

        if (!array_key_exists('table', $this->_params)) {
            $this->_params['table'] = 'horde_sessionhandler';
        }

        if (empty($this->_params['persistent'])) {
            $connect = 'OCILogon';
        } else {
            $connect = 'OCIPLogon';
        }

        if (!$this->_db = @$connect($this->_params['username'],
                                    $this->_params['password'],
                                    $this->_params['hostspec'])) {
            Horde::fatal(PEAR::raiseError('Could not connect to database for SQL SessionHandler.'), __FILE__, __LINE__);
        }

        $this->_connected = true;
    }

    /**
     * Disconnect from the SQL server and clean up the connection.
     *
     * @access private
     */
    function _disconnect()
    {
        if ($this->_connected) {
            return OCILogOff($this->_db);
        }
        $this->_connected = false;
    }

}

--- NEW FILE: pgsql.php ---
<?php
/**
 * PostgreSQL Session Handler for PHP (native).
 *
 * Copyright 2000-2004 Jon Parise <jon at csh.rit.edu>.  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 *  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 *  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 *  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 *  SUCH DAMAGE.
 *
 * <pre>
 * Required values for $params:
 *     'database'  --  The name of the database.
 *     'password'  --  The password associated with 'username'.
 *     'protocol'  --  The communication protocol ('tcp', 'unix').
 *     'username'  --  The username with which to connect to the database.
 *
 * Required for some configurations (i.e. 'protocol' = 'tcp'):
 *     'hostspec'  --  The hostname of the database server.
 *     'port'      --  The port on which to connect to the database.
 *
 * Optional parameters:
 *     'persistent'  --  Use persistent DB connections? (boolean)
 *                       Default: NO
 *     'table'       --  The name of the sessiondata table in 'database'.
 *                       Default: 'horde_sessionhandler'
 * </pre>
 *  
 * The table structure can be created by the
 * scripts/db/pgsql_sessionhandler.sql script.
 *
 * Contributors:
 *  Jason Carlson           Return an empty string on failed reads
 *  pat at pcprogrammer.com    Perform update in a single transaction
 *  Jonathan Crompton       Lock row for life of session
 *
 * $Horde: framework/SessionHandler/SessionHandler/pgsql.php,v 1.11 2004/01/01 15:14:28 jan Exp $
 *
 * @author  Jon Parise <jon at csh.rit.edu>
 * @version 1.10, 9/11/02
 * @since   Horde 3.0
 * @package Horde_SessionHandler
 */
class SessionHandler_pgsql extends SessionHandler {

    /** Hash containing connection parameters. */
    var $_params = array();

    /** Handle for the current database connection.
        @var resource $_db */
    var $_db;

    /**
     * Boolean indicating whether or not we're connected to the SQL
     * server. */
    var $_connected = false;

    /**
     * Constructs a new PostgreSQL SessionHandler object.
     *
     * @param array  $params    A hash containing connection parameters.
     */
    function SessionHandler_pgsql($params = array())
    {
        $this->_params = $params;
    }

    function open($save_path, $session_name)
    {
        /* Connect to database. */
        $this->_connect();
    }

    function close()
    {
        /* Disconnect from database. */
        $this->_disconnect();
    }

    function read($id)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        $expired = time() - ini_get('session.gc_maxlifetime');
        $squery = sprintf('BEGIN; SELECT session_data FROM %s WHERE session_id = %s AND session_lastmodified >= %s FOR UPDATE;',
                         $this->_params['table'], $this->quote($id), $expired);

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_pgsql::read(): query = "%s"', $squery),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        $result = @pg_exec($this->_db, $squery);
        if (pg_numrows($result) < 1) {
            pg_freeresult($result);

            $iquery = sprintf('INSERT INTO %s VALUES (%s, %s, \'\')',
                             $this->_params['table'], $this->quote($id), time());
            $result = @pg_exec($this->_db, $iquery);

            $result = @pg_exec($this->_db, $squery);
        }

        $data = pg_result($result, 0, 'session_data');
        pg_freeresult($result);

        return $data;
    }

    function write($id, $session_data)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        $query = sprintf('UPDATE %s SET session_lastmodified = %s, session_data = %s WHERE session_id = %s; commit;',
                         $this->_params['table'],
                         time(),
                         $this->quote($session_data),
                         $this->quote($id));

        $result = @pg_exec($this->_db, $query);
        $success = (pg_cmdtuples($result) == 0);
        pg_freeresult($result);

        if (!$success){
            Horde::logMessage('Error writing session data', __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        return true;
    }

    function destroy($id)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        $query = sprintf('DELETE FROM %s WHERE session_id = %s; commit;',
                         $this->_params['table'], $this->quote($id));

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_pgsql::destroy(): query = "%s"', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query. */
        $result = @pg_exec($this->_db, $query);
        if (!$result) {
            pg_freeresult($result);
            Horde::logMessage('Failed to delete session (id = ' . $id . ')', __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        pg_freeresult($result);
        return true;
    }

    function gc($maxlifetime = 300)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        $query = sprintf('DELETE FROM %s WHERE session_lastmodified < %s',
                         $this->_params['table'], $this->quote(time() - $maxlifetime));

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_pgsql::gc(): query = "%s"', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query. */
        $result = @pg_exec($this->_db, $query);
        if (!$result) {
            pg_freeresult($result);
            Horde::logMessage('Error garbage collecting old sessions', __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        pg_freeresult($result);
        return $result;
    }

    function quote($value)
    {
        return "'" . addslashes($value) . "'";
    }

    /**
     * Attempts to open a connection to the SQL server.
     *
     * @return boolean  True on success; exits (Horde::fatal()) on error.
     */
    function _connect()
    {
        if (!$this->_connected) {
            Horde::assertDriverConfig($this->_params, 'sessionhandler',
                array('hostspec', 'username', 'database', 'password'),
                'session handler pgsql');

            if (!array_key_exists('table', $this->_params)) {
                $this->_params['table'] = 'horde_sessionhandler';
            }

            $connect = (empty($this->_params['persistent'])) ? 'pg_connect' :'pg_pconnect';

            $paramstr = '';
            if ($tcp_protocol) {
                $paramstr .= ' host=' . $this->_params['hostspec'];
                $paramstr .= ' port=' . $this->_params['port'];
            }
            $paramstr .= ' dbname=' . $this->_params['database'];
            $paramstr .= ' user=' . $this->_params['username'];
            $paramstr .= ' password=' . $this->_params['password'];

            if (!$this->_db = @$connect($paramstr)) {
                return false;
            }

            $this->_connected = true;
        }

        return true;
    }

    /**
     * Disconnect from the SQL server and clean up the connection.
     *
     * @return boolean     true on success, false on failure.
     */
    function _disconnect()
    {
        if ($this->_connected) {
            $this->_connected = false;
            return @pg_close($this->_db);
        }

        return true;
    }

}

--- NEW FILE: sapdb.php ---
<?php

require_once(HORDE_BASE . '/lib/SessionHandler/sql.php');

/**
 * SessionHandler implementation for PHP's PEAR database abstraction layer.
 *
 * If you access your database through ODBC, you will almost certainly need
 * to change PHP's default value for odbc.defaultlrl (this is a php.ini
 * setting). The default is 4096, which is too small (your session data will
 * data will be chopped off), and setting it to 0 DOES NOT work - that
 * doesn't mean no limit, for some reason. odbc.defaultlrl = 32768
 * seems to work pretty well (using MSSQL-2000).
 *
 * Required values for $params:<pre>
 *     'hostspec'  --  The hostname of the database server.
 *     'protocol'  --  The communication protocol ('tcp', 'unix', etc.).
 *     'username'  --  The username with which to connect to the database.
 *     'password'  --  The password associated with 'username'.
 *     'database'  --  The name of the database.
 *     'table'     --  The name of the sessiondata table in 'database'.</pre>
 *
 * The table structure can be created by the scripts/db/sessionhandler.sql
 * script.
 *
 * $Horde: framework/SessionHandler/SessionHandler/sapdb.php,v 1.13 2004/01/01 15:14:28 jan Exp $
 *
 * Copyright 2002-2004 Mike Cochrane <mike at graftonhall.co.nz>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Mike Cochrane <mike at graftonhall.co.nz>
 * @version $Revision: 1.1 $
 * @since   Horde 3.0
 * @package Horde_SessionHandler
 */
class SessionHandler_sapdb extends SessionHandler_sql {

    /** Hash containing connection parameters. */
    var $_params = array();

    /** Handle for the current database connection.
        @var object DB $db */
    var $_db;

    /**
     * Boolean indicating whether or not we're connected to the SQL
     * server. */
    var $_connected = false;

    /**
     * Constructs a new SQL SessionHandler object.
     *
     * @param array  $params    A hash containing connection parameters.
     */
    function SessionHandler_sapdb($params = array())
    {
        $this->_params = $params;
        $this->_params['phptype'] = 'odbc';
    }

    function read($id)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        $query = sprintf('SELECT session_data FROM %s WHERE session_id = %s',
                         $this->_params['table'],
                         $this->_db->quote($id));

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_sql::read(): query = "%s"', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query */
        $result = odbc_exec($this->_db->connection, $query);
        odbc_longreadlen($result, 1024*1024);

        /* Fetch the value */
        odbc_fetch_row($result, 0);
        $data = odbc_result($result, 'session_data');

        /* Clean up */
        odbc_free_result($result);

        return $data;
    }

}

--- NEW FILE: sql.php ---
<?php
/**
 * SessionHandler implementation for PHP's PEAR database abstraction layer.
 *
 * Required values for $params:<pre>
 *     'phptype'   --  The database type (e.g. 'pgsql', 'mysql', etc.).
 *     'hostspec'  --  The hostname of the database server.
 *     'protocol'  --  The communication protocol ('tcp', 'unix', etc.).
 *     'username'  --  The username with which to connect to the database.
 *     'password'  --  The password associated with 'username'.
 *     'database'  --  The name of the database.
 *     'table'     --  The name of the sessiondata table in 'database'.</pre>
 *
 * Required by some database implementations:
 *     'options'  --   Additional options to pass to the database.
 *     'tty'      --   The TTY on which to connect to the database.
 *     'port'     --   The port on which to connect to the database.
 *
 * Optional parameters:
 *     'persistent'  --  Use persistent DB connections? (boolean)
 *
 * Ths table structure can be created by the scripts/db/sessionhandler.sql
 * script.
 *
 * $Horde: framework/SessionHandler/SessionHandler/sql.php,v 1.21 2004/04/07 14:43:13 chuck Exp $
 *
 * Copyright 2002-2004 Mike Cochrane <mike at graftonhall.co.nz>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Mike Cochrane <mike at graftonhall.co.nz>
 * @version $Revision: 1.1 $
 * @since   Horde 3.0
 * @package Horde_SessionHandler
 */
class SessionHandler_sql extends SessionHandler {

    /** Hash containing connection parameters. */
    var $_params = array();

    /** Handle for the current database connection.
        @var object DB $_db */
    var $_db;

    /**
     * Boolean indicating whether or not we're connected to the SQL
     * server. */
    var $_connected = false;

    /**
     * Constructs a new SQL SessionHandler object.
     *
     * @param array  $params    A hash containing connection parameters.
     */
    function SessionHandler_sql($params = array())
    {
        $this->_params = $params;
    }

    function open($save_path, $session_name)
    {
        /* Connect to database */
        $this->_connect();
    }

    function close()
    {
        /* Disconnect from Database */
        $this->_disconnect();
    }

    function read($id)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        require_once 'Horde/SQL.php';

        /* Execute the query. */
        $result = Horde_SQL::readBlob($this->_db, $this->_params['table'], 'session_data',
                                      array('session_id' => $id));

        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
            return '';
        }

        return $result;
    }

    function write($id, $session_data)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        $query = sprintf('SELECT session_id FROM %s WHERE session_id = %s',
                         $this->_params['table'], $this->_db->quote($id));

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_sql::write(): query = "%s"', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query. */
        $result = $this->_db->getOne($query);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        require_once 'Horde/SQL.php';
        if ($result) {
            $result = Horde_SQL::updateBlob($this->_db, $this->_params['table'], 'session_data',
                                            $session_data, array('session_id' => $id),
                                            array('session_lastmodified' => time()));
        } else {
            $result = Horde_SQL::insertBlob($this->_db, $this->_params['table'], 'session_data',
                                            $session_data, array('session_id' => $id,
                                                                 'session_lastmodified' => time()));
        }

        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        return true;
    }

    function destroy($id)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        $query = sprintf('DELETE FROM %s WHERE session_id = %s',
                         $this->_params['table'], $this->_db->quote($id));

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_sql::destroy(): query = "%s"', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query. */
        $result = $this->_db->query($query);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        return true;
    }

    function gc($maxlifetime = 300)
    {
        /* Make sure we have a valid database connection. */
        $this->_connect();

        /* Build the SQL query. */
        $query = sprintf('DELETE FROM %s WHERE session_lastmodified < %s',
                         $this->_params['table'], $this->_db->quote(time() - $maxlifetime));

        /* Log the query at a DEBUG log level. */
        Horde::logMessage(sprintf('SQL Query by SessionHandler_sql::gc(): query = "%s"', $query),
                          __FILE__, __LINE__, PEAR_LOG_DEBUG);

        /* Execute the query. */
        $result = $this->_db->query($query);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
            return false;
        }

        return true;
    }

    /**
     * Attempts to open a connection to the SQL server.
     *
     * @return boolean  True on success; exits (Horde::fatal()) on error.
     */
    function _connect()
    {
        if (!$this->_connected) {
            Horde::assertDriverConfig($this->_params, 'sessionhandler',
                array('phptype', 'hostspec', 'username', 'database', 'password'),
                'session handler SQL');

            if (empty($this->_params['table'])) {
                $this->_params['table'] = 'horde_sessionhandler';
            }

            /* Connect to the SQL server using the supplied
             * parameters. */
            include_once 'DB.php';
            $this->_db = &DB::connect($this->_params,
                                      array('persistent' => !empty($this->_params['persistent'])));
            if (is_a($this->_db, 'PEAR_Error')) {
                Horde::fatal($this->_db, __FILE__, __LINE__);
            }

            /* Enable the "portability" option. */
            $this->_db->setOption('optimize', 'portability');

            $this->_connected = true;
        }

        return true;
    }

    /**
     * Disconnect from the SQL server and clean up the connection.
     *
     * @return boolean     true on success, false on failure.
     */
    function _disconnect()
    {
        if ($this->_connected) {
            $this->_connected = false;
            return $this->_db->disconnect();
        }

        return true;
    }

}





More information about the commits mailing list