<?php
namespace CodeIgniter\Session\Handlers;
use CodeIgniter\Session\Exceptions\SessionException;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Database\BaseConnection;
use Config\Database;
class DatabaseHandler extends BaseHandler implements \SessionHandlerInterface
{
protected $DBGroup;
protected $table;
protected $db;
protected $platform;
protected $rowExists = false;
public function __construct(BaseConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
$this->table = $config->sessionSavePath;
if (empty($this->table))
{
throw SessionException::forMissingDatabaseTable();
}
$this->DBGroup = $config->sessionDBGroup ?? config(Database::class)->defaultGroup;
$this->db = Database::connect($this->DBGroup);
$driver = strtolower(get_class($this->db));
if (strpos($driver, 'mysql') !== false)
{
$this->platform = 'mysql';
}
elseif (strpos($driver, 'postgre') !== false)
{
$this->platform = 'postgre';
}
}
public function open($savePath, $name): bool
{
if (empty($this->db->connID))
{
$this->db->initialize();
}
return true;
}
public function read($sessionID): string
{
if ($this->lockSession($sessionID) === false)
{
$this->fingerprint = md5('');
return '';
}
if (is_null($this->sessionID))
{
$this->sessionID = $sessionID;
}
$builder = $this->db->table($this->table)
->select('data')
->where('id', $sessionID);
if ($this->matchIP)
{
$builder = $builder->where('ip_address', $this->ipAddress);
}
$result = $builder->get()->getRow();
if ($result === null)
{
$this->rowExists = false;
$this->fingerprint = md5('');
return '';
}
if (is_bool($result))
{
$result = '';
}
else
{
$result = ($this->platform === 'postgre') ? base64_decode(rtrim($result->data)) : $result->data;
}
$this->fingerprint = md5($result);
$this->rowExists = true;
return $result;
}
public function write($sessionID, $sessionData): bool
{
if ($this->lock === false)
{
return $this->fail();
}
elseif ($sessionID !== $this->sessionID)
{
$this->rowExists = false;
$this->sessionID = $sessionID;
}
if ($this->rowExists === false)
{
$insertData = [
'id' => $sessionID,
'ip_address' => $this->ipAddress,
'timestamp' => time(),
'data' => $this->platform === 'postgre' ? base64_encode($sessionData) : $sessionData,
];
if (! $this->db->table($this->table)->insert($insertData))
{
return $this->fail();
}
$this->fingerprint = md5($sessionData);
$this->rowExists = true;
return true;
}
$builder = $this->db->table($this->table)->where('id', $sessionID);
if ($this->matchIP)
{
$builder = $builder->where('ip_address', $this->ipAddress);
}
$updateData = [
'timestamp' => time(),
];
if ($this->fingerprint !== md5($sessionData))
{
$updateData['data'] = ($this->platform === 'postgre') ? base64_encode($sessionData) : $sessionData;
}
if (! $builder->update($updateData))
{
return $this->fail();
}
$this->fingerprint = md5($sessionData);
return true;
}
public function close(): bool
{
return ($this->lock && ! $this->releaseLock()) ? $this->fail() : true;
}
public function destroy($sessionID): bool
{
if ($this->lock)
{
$builder = $this->db->table($this->table)->where('id', $sessionID);
if ($this->matchIP)
{
$builder = $builder->where('ip_address', $this->ipAddress);
}
if (! $builder->delete())
{
return $this->fail();
}
}
if ($this->close())
{
$this->destroyCookie();
return true;
}
return $this->fail();
}
public function gc($maxlifetime): bool
{
return ($this->db->table($this->table)->delete('timestamp < ' . (time() - $maxlifetime))) ? true : $this->fail();
}
protected function lockSession(string $sessionID): bool
{
if ($this->platform === 'mysql')
{
$arg = md5($sessionID . ($this->matchIP ? '_' . $this->ipAddress : ''));
if ($this->db->query("SELECT GET_LOCK('{$arg}', 300) AS ci_session_lock")->getRow()->ci_session_lock)
{
$this->lock = $arg;
return true;
}
return $this->fail();
}
elseif ($this->platform === 'postgre')
{
$arg = "hashtext('{$sessionID}')" . ($this->matchIP ? ", hashtext('{$this->ipAddress}')" : '');
if ($this->db->simpleQuery("SELECT pg_advisory_lock({$arg})"))
{
$this->lock = $arg;
return true;
}
return $this->fail();
}
return parent::lockSession($sessionID);
}
protected function releaseLock(): bool
{
if (! $this->lock)
{
return true;
}
if ($this->platform === 'mysql')
{
if ($this->db->query("SELECT RELEASE_LOCK('{$this->lock}') AS ci_session_lock")->getRow()->ci_session_lock)
{
$this->lock = false;
return true;
}
return $this->fail();
}
elseif ($this->platform === 'postgre')
{
if ($this->db->simpleQuery("SELECT pg_advisory_unlock({$this->lock})"))
{
$this->lock = false;
return true;
}
return $this->fail();
}
return parent::releaseLock();
}
}