initial commit

This commit is contained in:
Chris Sewell
2012-11-28 03:55:08 -05:00
parent 7adb399b2e
commit cf140a2e97
3247 changed files with 492437 additions and 0 deletions

View File

@ -0,0 +1,212 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfCreoleDatabase provides connectivity for the Creole database abstraction
* layer.
*
* <b>Optional parameters:</b>
*
* # <b>classpath</b> - [none] - An absolute filesystem path to the main
* Creole class file.
* # <b>database</b> - [none] - The database name.
* # <b>dsn</b> - [none] - The DSN formatted connection string.
* # <b>host</b> - [none] - The database host specifications.
* # <b>port</b> - [none] - The database port.
* # <b>encoding</b> - [none] - The database encoding.
* # <b>method</b> - [normal] - How to read connection parameters.
* Possible values are dsn, normal,
* server, and env. The dsn method reads
* them from the dsn parameter. The
* normal method reads them from the
* specified values. server reads them
* from $_SERVER where the keys to
* retrieve the values are what you
* specify the value as in the settings.
* env reads them from $_ENV and works
* like $_SERVER.
* # <b>no_assoc_lower</b> - [Off] - Turn off portabilty of resultset
* field names.
* # <b>password</b> - [none] - The database password.
* # <b>persistent</b> - [No] - Indicates that the connection should
* persistent.
* # <b>phptype</b> - [none] - The type of database (mysql, pgsql,
* etc).
* # <b>username</b> - [none] - The database username.
*
* @package symfony
* @subpackage database
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @version SVN: $Id: sfCreoleDatabase.class.php 3329 2007-01-23 08:29:34Z fabien $
*/
class sfCreoleDatabase extends sfDatabase
{
/**
* Connect to the database.
*
* @throws <b>sfDatabaseException</b> If a connection could not be created.
*/
public function connect()
{
try
{
// determine how to get our settings
$method = $this->getParameter('method', 'normal');
switch ($method)
{
case 'normal':
// get parameters normally, and all are required
$database = $this->getParameter('database', null);
$hostspec = $this->getParameter('hostspec') ? $this->getParameter('hostspec') : ($this->getParameter('host') ? $this->getParameter('hostspec') : null);
$password = $this->getParameter('password', null);
$phptype = $this->getParameter('phptype', null);
$username = $this->getParameter('username', null);
$port = $this->getParameter('port', null);
$encoding = $this->getParameter('encoding', null);
$dsn = array('database' => $database,
'hostspec' => $hostspec,
'password' => $password,
'phptype' => $phptype,
'username' => $username,
'port' => $port,
'encoding' => $encoding);
break;
case 'dsn':
$dsn = $this->getParameter('dsn');
if ($dsn == null)
{
// missing required dsn parameter
$error = 'Database configuration specifies method "dsn", but is missing dsn parameter';
throw new sfDatabaseException($error);
}
break;
case 'server':
// construct a DSN connection string from existing $_SERVER values
$dsn =& $this->loadDSN($_SERVER);
break;
case 'env':
// construct a DSN connection string from existing $_ENV values
$dsn =& $this->loadDSN($_ENV);
break;
default:
// who knows what the user wants...
$error = 'Invalid CreoleDatabase parameter retrieval method "%s"';
$error = sprintf($error, $method);
throw new sfDatabaseException($error);
}
// get creole class path
$classPath = $this->getParameter('classpath');
// include the creole file
if ($classPath == null)
{
require_once('creole/Creole.php');
}
else
{
require_once($classPath);
}
// set our flags
$noAssocLower = $this->getParameter('no_assoc_lower', false);
$persistent = $this->getParameter('persistent', false);
$compatAssocLower = $this->getParameter('compat_assoc_lower', false);
$compatRtrimString = $this->getParameter('compat_rtrim_string', false);
$flags = 0;
$flags |= ($noAssocLower) ? Creole::NO_ASSOC_LOWER : 0;
$flags |= ($persistent) ? Creole::PERSISTENT : 0;
$flags |= ($compatAssocLower) ? Creole::COMPAT_ASSOC_LOWER : 0;
$flags |= ($compatRtrimString) ? Creole::COMPAT_RTRIM_STRING : 0;
// do the duuuurtay work, right thurr
if ($flags > 0)
{
$this->connection = Creole::getConnection($dsn, $flags);
}
else
{
$this->connection = Creole::getConnection($dsn);
}
// get our resource
$this->resource = $this->connection->getResource();
}
catch (SQLException $e)
{
// the connection's foobar'd
throw new sfDatabaseException($e->toString());
}
}
/**
* Load a DSN connection string from an existing array.
*
* @return array An associative array of connection parameters.
*/
protected function & loadDSN(&$array)
{
// determine if a dsn is set, otherwise use separate parameters
$dsn = $this->getParameter('dsn');
if ($dsn == null)
{
// list of available parameters
$available = array('database', 'hostspec', 'password', 'phptype', 'username', 'port');
$dsn = array();
// yes, i know variable variables are ugly, but let's avoid using
// an array for array's sake in this single spot in the source
foreach ($available as $parameter)
{
$$parameter = $this->getParameter($parameter);
$dsn[$parameter] = ($$parameter != null) ? $array[$$parameter] : null;
}
}
else
{
$dsn = $array[$dsn];
}
return $dsn;
}
/**
* Execute the shutdown procedure.
*
* @return void
*
* @throws <b>sfDatabaseException</b> If an error occurs while shutting down this database.
*/
public function shutdown()
{
if ($this->connection !== null)
{
@$this->connection->close();
}
}
}

View File

@ -0,0 +1,294 @@
<?php
/**
* Debug implementation of Connection.
*
* This is a Connection that implements the decorator pattern, wrapping around
* the true Connection object (stored in $childConnection). This Connection
* tracks information about queries executed and makes that information available
* for debugging purposes. The information tracked is the last query executed
* on the connection (getLastExecutedQuery()) and the total number of
* queries executed on the connection thus far (getNumQueriesExecuted()).
*
* To use this debug connection, you need to register it as a new Creole
* driver that handles all connection types. To do this, call the following
* before calling Creole::getConnection():
*
* <code>
* Creole::registerDriver('*', 'creole.drivers.debug.DebugConnection');
* </code>
*
* The next call to Creole::getConnection() will return an instance of
* DebugConnection.
*
* @author Michael Sims
* @package creole.drivers.debug
*/
class sfDebugConnection implements Connection
{
/** @var Connection */
private $childConnection = null;
/** @var int */
private $numQueriesExecuted = 0;
/** @var string */
private $lastExecutedQuery = '';
/**
* Optional PEAR Log class; if set queries will be logged at PEAR_LOG_INFO level.
* @var Log
*/
private static $logger;
/**
* Sets a Logger class (e.g. PEAR Log) to use for logging.
* The logger class must have a log() method. All messages are logged at default log level.
* @param object $logger
*/
public static function setLogger($logger)
{
self::$logger = $logger;
}
/**
* Returns the number of queries executed on this connection so far
*
* @return int
*/
public function getNumQueriesExecuted()
{
return $this->numQueriesExecuted;
}
/**
* Returns the last query executed on this connection
*
* @return string
*/
public function getLastExecutedQuery()
{
return $this->lastExecutedQuery;
}
/**
* connect()
*/
public function connect($dsninfo, $flags = 0)
{
if (!($driver = Creole::getDriver($dsninfo['phptype'])))
{
throw new SQLException("No driver has been registered to handle connection type: $type");
}
$connectionClass = Creole::import($driver);
$this->childConnection = new $connectionClass();
$this->log("{sfCreole} connect(): DSN: ". var_export($dsninfo, true) . ", FLAGS: " . var_export($flags, true));
return $this->childConnection->connect($dsninfo, $flags);
}
/**
* @see Connection::getDatabaseInfo()
*/
public function getDatabaseInfo()
{
return $this->childConnection->getDatabaseInfo();
}
/**
* @see Connection::getIdGenerator()
*/
public function getIdGenerator()
{
return $this->childConnection->getIdGenerator();
}
/**
* @see Connection::isConnected()
*/
public function isConnected()
{
return $this->childConnection->isConnected();
}
/**
* @see Connection::prepareStatement()
*/
public function prepareStatement($sql)
{
$this->log("{sfCreole} prepareStatement(): $sql");
$obj = $this->childConnection->prepareStatement($sql);
$objClass = get_class($obj);
return new $objClass($this, $sql);
}
/**
* @see Connection::createStatement()
*/
public function createStatement()
{
$obj = $this->childConnection->createStatement();
$objClass = get_class($obj);
return new $objClass($this);
}
/**
* @see Connection::applyLimit()
*/
public function applyLimit(&$sql, $offset, $limit)
{
$this->log("{sfCreole} applyLimit(): $sql, offset: $offset, limit: $limit");
return $this->childConnection->applyLimit($sql, $offset, $limit);
}
/**
* @see Connection::close()
*/
public function close()
{
$this->log("{sfCreole} close(): Closing connection.");
return $this->childConnection->close();
}
/**
* @see Connection::executeQuery()
*/
public function executeQuery($sql, $fetchmode = null)
{
$this->lastExecutedQuery = $sql;
$this->numQueriesExecuted++;
$elapsedTime = 0;
if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
{
$sqlTimer = sfTimerManager::getTimer('Database');
$timer = new sfTimer();
}
$retval = $this->childConnection->executeQuery($sql, $fetchmode);
if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
{
$sqlTimer->addTime();
$elapsedTime = $timer->getElapsedTime();
}
$this->log(sprintf("{sfCreole} executeQuery(): [%.2f ms] %s", $elapsedTime * 1000, $sql));
return $retval;
}
/**
* @see Connection::executeUpdate()
**/
public function executeUpdate($sql)
{
$this->log("{sfCreole} executeUpdate(): $sql");
$this->lastExecutedQuery = $sql;
$this->numQueriesExecuted++;
return $this->childConnection->executeUpdate($sql);
}
/**
* @see Connection::getUpdateCount()
*/
public function getUpdateCount()
{
return $this->childConnection->getUpdateCount();
}
/**
* @see Connection::prepareCall()
**/
public function prepareCall($sql)
{
$this->log("{sfCreole} prepareCall(): $sql");
return $this->childConnection->prepareCall($sql);
}
/**
* @see Connection::getResource()
*/
public function getResource()
{
return $this->childConnection->getResource();
}
/**
* @see Connection::connect()
*/
public function getDSN()
{
return $this->childConnection->getDSN();
}
/**
* @see Connection::getFlags()
*/
public function getFlags()
{
return $this->childConnection->getFlags();
}
/**
* @see Connection::begin()
*/
public function begin()
{
$this->log("{sfCreole} beginning transaction.");
return $this->childConnection->begin();
}
/**
* @see Connection::commit()
*/
public function commit()
{
$this->log("{sfCreole} committing transaction.");
return $this->childConnection->commit();
}
/**
* @see Connection::rollback()
*/
public function rollback()
{
$this->log("{sfCreole} rolling back transaction.");
return $this->childConnection->rollback();
}
/**
* @see Connection::setAutoCommit()
*/
public function setAutoCommit($bit)
{
$this->log("{sfCreole} setting autocommit to: ".var_export($bit, true));
return $this->childConnection->setAutoCommit($bit);
}
/**
* @see Connection::getAutoCommit()
*/
public function getAutoCommit()
{
return $this->childConnection->getAutoCommit();
}
/**
* Private function that logs message using specified logger (if provided).
* @param string $msg Message to log.
*/
private function log($msg)
{
if (self::$logger)
{
// message on one line
$msg = preg_replace("/\r?\n/", ' ', $msg);
self::$logger->log($msg);
}
}
public function __call($method, $arguments)
{
return $this->childConnection->$method($arguments);
}
}

View File

@ -0,0 +1,445 @@
<?php
/**
* sfMessageSource_Creole class file.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the BSD License.
*
* Copyright(c) 2004 by Qiang Xue. All rights reserved.
*
* To contact the author write to {@link mailto:qiang.xue@gmail.com Qiang Xue}
* The latest version of PRADO can be obtained from:
* {@link http://prado.sourceforge.net/}
*
* @author Wei Zhuo <weizhuo[at]gmail[dot]com>
* @version $Id: sfMessageSource_Creole.class.php 3245 2007-01-12 15:01:53Z fabien $
* @package symfony
* @subpackage i18n
*/
/*
CREATE TABLE `catalogue` (
`cat_id` int(11) NOT NULL auto_increment,
`name` varchar(100) NOT NULL default '',
`source_lang` varchar(100) NOT NULL default '',
`target_lang` varchar(100) NOT NULL default '',
`date_created` int(11) NOT NULL default '0',
`date_modified` int(11) NOT NULL default '0',
`author` varchar(255) NOT NULL default '',
PRIMARY KEY (`cat_id`)
);
CREATE TABLE `trans_unit` (
`msg_id` int(11) NOT NULL auto_increment,
`cat_id` int(11) NOT NULL default '1',
`source` text NOT NULL,
`target` text NOT NULL,
`comments` text NOT NULL,
`date_added` int(11) NOT NULL default '0',
`date_modified` int(11) NOT NULL default '0',
`author` varchar(255) NOT NULL default '',
`translated` tinyint(1) NOT NULL default '0',
PRIMARY KEY (`msg_id`)
);
*/
/**
* sfMessageSource_Creole class.
*
* Retrieve the message translation from a Creole supported database.
*
* See the MessageSource::factory() method to instantiate this class.
*
* @author RoVeRT <symfony[at]rovert[dot]net>
*/
class sfMessageSource_Creole extends sfMessageSource
{
/**
* A resource link to the database
* @var db
*/
protected $db;
/**
* Constructor.
* Create a new message source using Creole.
* @param string Creole datasource.
* @see MessageSource::factory();
*/
public function __construct($source)
{
$this->db = sfContext::getInstance()->getDatabaseConnection($source);
if ($this->db == null || !$this->db instanceof Connection)
{
$error = 'Creole dabatase connection doesn\'t exist. Unable to open session.';
throw new sfDatabaseException($error);
}
}
/**
* Destructor, close the database connection.
*/
public function __destruct()
{
}
/**
* Get the database connection.
* @return db database connection.
*/
public function connection()
{
return $this->db;
}
/**
* Get an array of messages for a particular catalogue and cultural
* variant.
* @param string the catalogue name + variant
* @return array translation messages.
*/
protected function &loadData($variant)
{
$sql = 'SELECT t.source, t.target, t.comments '.
'FROM trans_unit t, catalogue c '.
'WHERE c.cat_id = t.cat_id AND c.name = ? '.
'ORDER BY msg_id ASC';
$stmt = $this->db->prepareStatement($sql);
$rs = $stmt->executeQuery(array($variant), ResultSet::FETCHMODE_NUM);
$result = array();
$count = 0;
while ($rs->next())
{
$source = $rs->getString(1);
$result[$source][] = $rs->getString(2); //target
$result[$source][] = $count++; //id
$result[$source][] = $rs->getString(3); //comments
}
return $result;
}
/**
* Get the last modified unix-time for this particular catalogue+variant.
* We need to query the database to get the date_modified.
*
* @param string catalogue+variant
* @return int last modified in unix-time format.
*/
protected function getLastModified($source)
{
$sql = 'SELECT date_modified FROM catalogue WHERE name = ?';
$stmt = $this->db->prepareStatement($sql);
$rs = $stmt->executeQuery(array($source), ResultSet::FETCHMODE_NUM);
$result = $rs->next() ? $rs->getInt(1) : 0;
return $result;
}
/**
* Check if a particular catalogue+variant exists in the database.
*
* @param string catalogue+variant
* @return boolean true if the catalogue+variant is in the database, false otherwise.
*/
protected function isValidSource($variant)
{
$sql = 'SELECT COUNT(*) FROM catalogue WHERE name = ?';
$stmt = $this->db->prepareStatement($sql);
$rs = $stmt->executeQuery(array($variant), ResultSet::FETCHMODE_NUM);
$result = $rs->next() ? $rs->getInt(1) == 1 : false;
return $result;
}
/**
* Get all the variants of a particular catalogue.
*
* @param string catalogue name
* @return array list of all variants for this catalogue.
*/
protected function getCatalogueList($catalogue)
{
$variants = explode('_', $this->culture);
$catalogues = array($catalogue);
$variant = null;
for ($i = 0, $max = count($variants); $i < $max; $i++)
{
if (strlen($variants[$i]) > 0)
{
$variant .= ($variant) ? '_'.$variants[$i] : $variants[$i];
$catalogues[] = $catalogue.'.'.$variant;
}
}
return array_reverse($catalogues);
}
/**
* Retrieve catalogue details, array($cat_id, $variant, $count).
*
* @param string catalogue
* @return array catalogue details, array($cat_id, $variant, $count).
*/
protected function getCatalogueDetails($catalogue = 'messages')
{
if (empty($catalogue))
{
$catalogue = 'messages';
}
$variant = $catalogue.'.'.$this->culture;
$name = $this->getSource($variant);
$sql = 'SELECT cat_id FROM catalogue WHERE name = ?';
$stmt = $this->db->prepareStatement($sql);
$rs = $stmt->executeQuery(array($name), ResultSet::FETCHMODE_NUM);
if ($rs->getRecordCount() != 1)
{
return false;
}
$rs->next();
$cat_id = $rs->getInt(1);
//first get the catalogue ID
$sql = 'SELECT count(msg_id) FROM trans_unit WHERE cat_id = ?';
$stmt = $this->db->prepareStatement($sql);
$rs = $stmt->executeQuery(array($cat_id), ResultSet::FETCHMODE_NUM);
$rs->next();
$count = $rs->getInt(1);
return array($cat_id, $variant, $count);
}
/**
* Update the catalogue last modified time.
*
* @return boolean true if updated, false otherwise.
*/
protected function updateCatalogueTime($cat_id, $variant)
{
$time = time();
$sql = 'UPDATE catalogue SET date_modified = ? WHERE cat_id = ?';
$stmt = $this->db->prepareStatement($sql);
$result = $stmt->executeUpdate(array($time, $cat_id));
if (!empty($this->cache))
{
$this->cache->clean($variant, $this->culture);
}
return true;
}
/**
* Save the list of untranslated blocks to the translation source.
* If the translation was not found, you should add those
* strings to the translation source via the <b>append()</b> method.
*
* @param string the catalogue to add to
* @return boolean true if saved successfuly, false otherwise.
*/
function save($catalogue='messages')
{
$messages = $this->untranslated;
if (count($messages) <= 0)
{
return false;
}
$details = $this->getCatalogueDetails($catalogue);
if ($details)
{
list($cat_id, $variant, $count) = $details;
}
else
{
return false;
}
if ($cat_id <= 0)
{
return false;
}
$inserted = 0;
$time = time();
try
{
$sql = 'SELECT msg_id FROM trans_unit WHERE source = ?';
$stmt = $this->db->prepareStatement($sql);
foreach($messages as $key => $message)
{
$rs = $stmt->executeQuery(array($message), ResultSet::FETCHMODE_NUM);
if ($rs->next())
{
unset($messages[$key]);
}
}
}
catch (Exception $e)
{
}
try
{
$this->db->begin();
$sql = 'INSERT INTO trans_unit (cat_id, source, target, comments, date_added, date_modified) VALUES (?, ?, ?, ?, ?, ?)';
$stmt = $this->db->prepareStatement($sql);
foreach ($messages as $message)
{
$stmt->executeUpdate(array($cat_id, $message, '', '', $time, $time));
++$inserted;
}
$this->db->commit();
}
catch (Exception $e)
{
$this->db->rollback();
}
if ($inserted > 0)
{
$this->updateCatalogueTime($cat_id, $variant);
}
return $inserted > 0;
}
/**
* Delete a particular message from the specified catalogue.
*
* @param string the source message to delete.
* @param string the catalogue to delete from.
* @return boolean true if deleted, false otherwise.
*/
function delete($message, $catalogue='messages')
{
$details = $this->getCatalogueDetails($catalogue);
if ($details)
{
list($cat_id, $variant, $count) = $details;
}
else
{
return false;
}
$deleted = false;
$sql = 'DELETE FROM trans_unit WHERE cat_id = ? AND source = ?';
$stmt = $this->db->prepareStatement($sql);
$rows = $stmt->executeUpdate(array($cat_id, $message));
if ($rows == 1)
{
$deleted = $this->updateCatalogueTime($cat_id, $variant);
}
return $deleted;
}
/**
* Update the translation.
*
* @param string the source string.
* @param string the new translation string.
* @param string comments
* @param string the catalogue of the translation.
* @return boolean true if translation was updated, false otherwise.
*/
function update($text, $target, $comments, $catalogue='messages')
{
$details = $this->getCatalogueDetails($catalogue);
if ($details)
{
list($cat_id, $variant, $count) = $details;
}
else
{
return false;
}
$time = time();
$sql = 'UPDATE trans_unit SET target = ?, comments = ?, date_modified = ? WHERE cat_id = ? AND source = ?';
$updated = false;
$stmt = $this->db->prepareStatement($sql);
$rows = $stmt->executeUpdate(array($target, $comments, $time, $cat_id, $text));
if ($rows == 1)
{
$updated = $this->updateCatalogueTime($cat_id, $variant);
}
return $updated;
}
/**
* Returns a list of catalogue as key and all it variants as value.
*
* @return array list of catalogues
*/
function catalogues()
{
$sql = 'SELECT name FROM catalogue ORDER BY name';
$rs = $this->db->executeQuery($sql, ResultSet::FETCHMODE_NUM);
$result = array();
while ($rs->next())
{
$details = explode('.', $rs->getString(1));
if (!isset($details[1]))
{
$details[1] = null;
}
$result[] = $details;
}
return $result;
}
}

View File

@ -0,0 +1,307 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004, 2005 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004, 2005 Sean Kerr.
*
* The original version the file is based on is licensed under the LGPL, but a special license was granted.
* Please see the licenses/LICENSE.Agavi file
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Provides support for session storage using a CreoleDb database abstraction layer.
*
* <b>Required parameters:</b>
*
* # <b>db_table</b> - [none] - The database table in which session data will be
* stored.
*
* <b>Optional parameters:</b>
*
* # <b>database</b> - [default] - The database connection to use
* (see databases.ini).
* # <b>db_id_col</b> - [sess_id] - The database column in which the
* session id will be stored.
* # <b>db_data_col</b> - [sess_data] - The database column in which the
* session data will be stored.
* # <b>db_time_col</b> - [sess_time] - The database column in which the
* session timestamp will be stored.
* # <b>session_name</b> - [Agavi] - The name of the session.
*
* @package symfony
* @subpackage storage
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Sean Kerr <skerr@mojavi.org>
* @author Veikko Mäkinen <mail@veikkomakinen.com>
* @version SVN: $Id: sfCreoleSessionStorage.class.php 2995 2006-12-09 18:01:32Z fabien $
*/
class sfCreoleSessionStorage extends sfSessionStorage
{
/**
* Creole Database Connection
* @var Connection
*/
protected $db;
/**
* Initialize this Storage.
*
* @param Context A Context instance.
* @param array An associative array of initialization parameters.
*
* @return bool true, if initialization completes successfully, otherwise
* false.
*
* @throws <b>InitializationException</b> If an error occurs while
* initializing this Storage.
*/
public function initialize($context, $parameters = null)
{
// disable auto_start
$parameters['auto_start'] = false;
// initialize the parent
parent::initialize($context, $parameters);
if (!$this->getParameterHolder()->has('db_table'))
{
// missing required 'db_table' parameter
$error = 'Factory configuration file is missing required "db_table" parameter for the Storage category';
throw new sfInitializationException($error);
}
// use this object as the session handler
session_set_save_handler(array($this, 'sessionOpen'),
array($this, 'sessionClose'),
array($this, 'sessionRead'),
array($this, 'sessionWrite'),
array($this, 'sessionDestroy'),
array($this, 'sessionGC'));
// start our session
session_start();
}
/**
* Close a session.
*
* @return bool true, if the session was closed, otherwise false.
*/
public function sessionClose()
{
// do nothing
return true;
}
/**
* Destroy a session.
*
* @param string A session ID.
*
* @return bool true, if the session was destroyed, otherwise an exception
* is thrown.
*
* @throws <b>DatabaseException</b> If the session cannot be destroyed.
*/
public function sessionDestroy($id)
{
// get table/column
$db_table = $this->getParameterHolder()->get('db_table');
$db_id_col = $this->getParameterHolder()->get('db_id_col', 'sess_id');
// delete the record associated with this id
$sql = 'DELETE FROM ' . $db_table . ' WHERE ' . $db_id_col . '=?';
try
{
$stmt = $this->db->prepareStatement($sql);
$stmt->setString(1, $id);
$stmt->executeUpdate();
}
catch (SQLException $e) {
$error = 'Creole SQLException was thrown when trying to manipulate session data. ';
$error .= 'Message: ' . $e->getMessage();
throw new sfDatabaseException($error);
}
}
/**
* Cleanup old sessions.
*
* @param int The lifetime of a session.
*
* @return bool true, if old sessions have been cleaned, otherwise an
* exception is thrown.
*
* @throws <b>DatabaseException</b> If any old sessions cannot be cleaned.
*/
public function sessionGC($lifetime)
{
// determine deletable session time
$time = time() - $lifetime;
// get table/column
$db_table = $this->getParameterHolder()->get('db_table');
$db_time_col = $this->getParameterHolder()->get('db_time_col', 'sess_time');
// delete the record associated with this id
$sql = 'DELETE FROM ' . $db_table . ' ' .
'WHERE ' . $db_time_col . ' < ' . $time;
try
{
$this->db->executeQuery($sql);
return true;
}
catch (SQLException $e)
{
$error = 'Creole SQLException was thrown when trying to manipulate session data. ';
$error .= 'Message: ' . $e->getMessage();
throw new sfDatabaseException($error);
}
}
/**
* Open a session.
*
* @param string
* @param string
*
* @return bool true, if the session was opened, otherwise an exception is
* thrown.
*
* @throws <b>DatabaseException</b> If a connection with the database does
* not exist or cannot be created.
*/
public function sessionOpen($path, $name)
{
// what database are we using?
$database = $this->getParameterHolder()->get('database', 'default');
// autoload propel propely if we're reusing the propel connection for session storage
if ($this->getContext()->getDatabaseManager()->getDatabase($database) instanceof sfPropelDatabase && !Propel::isInit())
{
$error = 'Creole dabatase connection is the same as the propel database connection, but could not be initialized.';
throw new sfDatabaseException($error);
}
$this->db = $this->getContext()->getDatabaseConnection($database);
if ($this->db == null || !$this->db instanceof Connection)
{
$error = 'Creole dabatase connection doesn\'t exist. Unable to open session.';
throw new sfDatabaseException($error);
}
return true;
}
/**
* Read a session.
*
* @param string A session ID.
*
* @return bool true, if the session was read, otherwise an exception is
* thrown.
*
* @throws <b>DatabaseException</b> If the session cannot be read.
*/
public function sessionRead($id)
{
// get table/columns
$db_table = $this->getParameterHolder()->get('db_table');
$db_data_col = $this->getParameterHolder()->get('db_data_col', 'sess_data');
$db_id_col = $this->getParameterHolder()->get('db_id_col', 'sess_id');
$db_time_col = $this->getParameterHolder()->get('db_time_col', 'sess_time');
try
{
$sql = 'SELECT ' . $db_data_col . ' FROM ' . $db_table . ' WHERE ' . $db_id_col . '=?';
$stmt = $this->db->prepareStatement($sql);
$stmt->setString(1, $id);
$dbRes = $stmt->executeQuery(ResultSet::FETCHMODE_NUM);
if ($dbRes->next())
{
$data = $dbRes->getString(1);
return $data;
}
else
{
// session does not exist, create it
$sql = 'INSERT INTO ' . $db_table . '('.$db_id_col.','.$db_data_col.','.$db_time_col;
$sql .= ') VALUES (?,?,?)';
$stmt = $this->db->prepareStatement($sql);
$stmt->setString(1, $id);
$stmt->setString(2, '');
$stmt->setInt(3, time());
$stmt->executeUpdate();
return '';
}
}
catch (SQLException $e)
{
$error = 'Creole SQLException was thrown when trying to manipulate session data. ';
$error .= 'Message: ' . $e->getMessage();
throw new sfDatabaseException($error);
}
}
/**
* Write session data.
*
* @param string A session ID.
* @param string A serialized chunk of session data.
*
* @return bool true, if the session was written, otherwise an exception is
* thrown.
*
* @throws <b>DatabaseException</b> If the session data cannot be written.
*/
public function sessionWrite($id, $data)
{
// get table/column
$db_table = $this->getParameterHolder()->get('db_table');
$db_data_col = $this->getParameterHolder()->get('db_data_col', 'sess_data');
$db_id_col = $this->getParameterHolder()->get('db_id_col', 'sess_id');
$db_time_col = $this->getParameterHolder()->get('db_time_col', 'sess_time');
$sql = 'UPDATE ' . $db_table . ' SET ' . $db_data_col . '=?, ' . $db_time_col . ' = ' . time() .
' WHERE ' . $db_id_col . '=?';
try
{
$stmt = $this->db->prepareStatement($sql);
$stmt->setString(1, $data);
$stmt->setString(2, $id);
$stmt->executeUpdate();
return true;
}
catch (SQLException $e)
{
$error = 'Creole SQLException was thrown when trying to manipulate session data. ';
$error .= 'Message: ' . $e->getMessage();
throw new sfDatabaseException($error);
}
return false;
}
/**
* Execute the shutdown procedure.
*
* @return void
*/
public function shutdown()
{
}
}