<?php
namespace CodeIgniter\Session;
use Psr\Log\LoggerAwareTrait;
class Session implements SessionInterface
{
use LoggerAwareTrait;
protected $driver;
protected $sessionDriverName;
protected $sessionCookieName = 'ci_session';
protected $sessionExpiration = 7200;
protected $sessionSavePath = null;
protected $sessionMatchIP = false;
protected $sessionTimeToUpdate = 300;
protected $sessionRegenerateDestroy = false;
protected $cookieDomain = '';
protected $cookiePath = '/';
protected $cookieSecure = false;
protected $sidRegexp;
protected $logger;
public function __construct(\SessionHandlerInterface $driver, $config)
{
$this->driver = $driver;
$this->sessionDriverName = $config->sessionDriver;
$this->sessionCookieName = $config->sessionCookieName;
$this->sessionExpiration = $config->sessionExpiration;
$this->sessionSavePath = $config->sessionSavePath;
$this->sessionMatchIP = $config->sessionMatchIP;
$this->sessionTimeToUpdate = $config->sessionTimeToUpdate;
$this->sessionRegenerateDestroy = $config->sessionRegenerateDestroy;
$this->cookieDomain = $config->cookieDomain;
$this->cookiePath = $config->cookiePath;
$this->cookieSecure = $config->cookieSecure;
helper('array');
}
public function start()
{
if (is_cli() && ENVIRONMENT !== 'testing')
{
$this->logger->debug('Session: Initialization under CLI aborted.');
return;
}
elseif ((bool) ini_get('session.auto_start'))
{
$this->logger->error('Session: session.auto_start is enabled in php.ini. Aborting.');
return;
}
elseif (session_status() === PHP_SESSION_ACTIVE)
{
$this->logger->warning('Session: Sessions is enabled, and one exists.Please don\'t $session->start();');
return;
}
if (! $this->driver instanceof \SessionHandlerInterface)
{
$this->logger->error("Session: Handler '" . $this->driver .
"' doesn't implement SessionHandlerInterface. Aborting.");
}
$this->configure();
$this->setSaveHandler();
if (isset($_COOKIE[$this->sessionCookieName]) && (
! is_string($_COOKIE[$this->sessionCookieName]) || ! preg_match('#\A' . $this->sidRegexp . '\z#', $_COOKIE[$this->sessionCookieName])
)
)
{
unset($_COOKIE[$this->sessionCookieName]);
}
$this->startSession();
if ((empty($_SERVER['HTTP_X_REQUESTED_WITH']) ||
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') && ($regenerate_time = $this->sessionTimeToUpdate) > 0
)
{
if (! isset($_SESSION['__ci_last_regenerate']))
{
$_SESSION['__ci_last_regenerate'] = time();
}
elseif ($_SESSION['__ci_last_regenerate'] < (time() - $regenerate_time))
{
$this->regenerate((bool) $this->sessionRegenerateDestroy);
}
}
elseif (isset($_COOKIE[$this->sessionCookieName]) && $_COOKIE[$this->sessionCookieName] === session_id())
{
$this->setCookie();
}
$this->initVars();
$this->logger->info("Session: Class initialized using '" . $this->sessionDriverName . "' driver.");
return $this;
}
public function stop()
{
setcookie(
$this->sessionCookieName, session_id(), 1, $this->cookiePath, $this->cookieDomain, $this->cookieSecure, true
);
session_regenerate_id(true);
}
protected function configure()
{
if (empty($this->sessionCookieName))
{
$this->sessionCookieName = ini_get('session.name');
}
else
{
ini_set('session.name', $this->sessionCookieName);
}
session_set_cookie_params(
$this->sessionExpiration, $this->cookiePath, $this->cookieDomain, $this->cookieSecure, true );
if (! isset($this->sessionExpiration))
{
$this->sessionExpiration = (int) ini_get('session.gc_maxlifetime');
}
else
{
ini_set('session.gc_maxlifetime', (int) $this->sessionExpiration);
}
if (! empty($this->sessionSavePath))
{
ini_set('session.save_path', $this->sessionSavePath);
}
ini_set('session.use_trans_sid', 0);
ini_set('session.use_strict_mode', 1);
ini_set('session.use_cookies', 1);
ini_set('session.use_only_cookies', 1);
$this->configureSidLength();
}
protected function configureSidLength()
{
$bits_per_character = (int) (ini_get('session.sid_bits_per_character') !== false
? ini_get('session.sid_bits_per_character')
: 4);
$sid_length = (int) (ini_get('session.sid_length') !== false
? ini_get('session.sid_length')
: 40);
if (($sid_length * $bits_per_character) < 160)
{
$bits = ($sid_length * $bits_per_character);
$sid_length += (int) ceil((160 % $bits) / $bits_per_character);
ini_set('session.sid_length', $sid_length);
}
switch ($bits_per_character)
{
case 4:
$this->sidRegexp = '[0-9a-f]';
break;
case 5:
$this->sidRegexp = '[0-9a-v]';
break;
case 6:
$this->sidRegexp = '[0-9a-zA-Z,-]';
break;
}
$this->sidRegexp .= '{' . $sid_length . '}';
}
protected function initVars()
{
if (empty($_SESSION['__ci_vars']))
{
return;
}
$current_time = time();
foreach ($_SESSION['__ci_vars'] as $key => &$value)
{
if ($value === 'new')
{
$_SESSION['__ci_vars'][$key] = 'old';
}
elseif ($value < $current_time)
{
unset($_SESSION[$key], $_SESSION['__ci_vars'][$key]);
}
}
if (empty($_SESSION['__ci_vars']))
{
unset($_SESSION['__ci_vars']);
}
}
public function regenerate(bool $destroy = false)
{
$_SESSION['__ci_last_regenerate'] = time();
session_regenerate_id($destroy);
}
public function destroy()
{
session_destroy();
}
public function set($data, $value = null)
{
if (is_array($data))
{
foreach ($data as $key => &$value)
{
if (is_int($key))
{
$_SESSION[$value] = null;
}
else
{
$_SESSION[$key] = $value;
}
}
return;
}
$_SESSION[$data] = $value;
}
public function get(string $key = null)
{
if (! empty($key) && ! is_null($value = dot_array_search($key, $_SESSION)))
{
return $value;
}
elseif (empty($_SESSION))
{
return [];
}
if (! empty($key))
{
return null;
}
$userdata = [];
$_exclude = array_merge(
['__ci_vars'], $this->getFlashKeys(), $this->getTempKeys()
);
$keys = array_keys($_SESSION);
foreach ($keys as $key)
{
if (! in_array($key, $_exclude, true))
{
$userdata[$key] = $_SESSION[$key];
}
}
return $userdata;
}
public function has(string $key): bool
{
return isset($_SESSION[$key]);
}
public function push(string $key, array $data)
{
if ($this->has($key) && is_array($value = $this->get($key)))
{
$this->set($key, array_merge($value, $data));
}
}
public function remove($key)
{
if (is_array($key))
{
foreach ($key as $k)
{
unset($_SESSION[$k]);
}
return;
}
unset($_SESSION[$key]);
}
public function __set(string $key, $value)
{
$_SESSION[$key] = $value;
}
public function __get(string $key)
{
if (isset($_SESSION[$key]))
{
return $_SESSION[$key];
}
elseif ($key === 'session_id')
{
return session_id();
}
return null;
}
public function __isset(string $key): bool
{
return isset($_SESSION[$key]) || ($key === 'session_id');
}
public function setFlashdata($data, $value = null)
{
$this->set($data, $value);
$this->markAsFlashdata(is_array($data) ? array_keys($data) : $data);
}
public function getFlashdata(string $key = null)
{
if (isset($key))
{
return (isset($_SESSION['__ci_vars'], $_SESSION['__ci_vars'][$key], $_SESSION[$key]) &&
! is_int($_SESSION['__ci_vars'][$key])) ? $_SESSION[$key] : null;
}
$flashdata = [];
if (! empty($_SESSION['__ci_vars']))
{
foreach ($_SESSION['__ci_vars'] as $key => &$value)
{
is_int($value) || $flashdata[$key] = $_SESSION[$key];
}
}
return $flashdata;
}
public function keepFlashdata($key)
{
$this->markAsFlashdata($key);
}
public function markAsFlashdata($key): bool
{
if (is_array($key))
{
for ($i = 0, $c = count($key); $i < $c; $i ++)
{
if (! isset($_SESSION[$key[$i]]))
{
return false;
}
}
$new = array_fill_keys($key, 'new');
$_SESSION['__ci_vars'] = isset($_SESSION['__ci_vars']) ? array_merge($_SESSION['__ci_vars'], $new) : $new;
return true;
}
if (! isset($_SESSION[$key]))
{
return false;
}
$_SESSION['__ci_vars'][$key] = 'new';
return true;
}
public function unmarkFlashdata($key)
{
if (empty($_SESSION['__ci_vars']))
{
return;
}
is_array($key) || $key = [$key];
foreach ($key as $k)
{
if (isset($_SESSION['__ci_vars'][$k]) && ! is_int($_SESSION['__ci_vars'][$k]))
{
unset($_SESSION['__ci_vars'][$k]);
}
}
if (empty($_SESSION['__ci_vars']))
{
unset($_SESSION['__ci_vars']);
}
}
public function getFlashKeys(): array
{
if (! isset($_SESSION['__ci_vars']))
{
return [];
}
$keys = [];
foreach (array_keys($_SESSION['__ci_vars']) as $key)
{
is_int($_SESSION['__ci_vars'][$key]) || $keys[] = $key;
}
return $keys;
}
public function setTempdata($data, $value = null, int $ttl = 300)
{
$this->set($data, $value);
$this->markAsTempdata($data, $ttl);
}
public function getTempdata(string $key = null)
{
if (isset($key))
{
return (isset($_SESSION['__ci_vars'], $_SESSION['__ci_vars'][$key], $_SESSION[$key]) &&
is_int($_SESSION['__ci_vars'][$key])) ? $_SESSION[$key] : null;
}
$tempdata = [];
if (! empty($_SESSION['__ci_vars']))
{
foreach ($_SESSION['__ci_vars'] as $key => &$value)
{
is_int($value) && $tempdata[$key] = $_SESSION[$key];
}
}
return $tempdata;
}
public function removeTempdata(string $key)
{
$this->unmarkTempdata($key);
unset($_SESSION[$key]);
}
public function markAsTempdata($key, int $ttl = 300): bool
{
$ttl += time();
if (is_array($key))
{
$temp = [];
foreach ($key as $k => $v)
{
if (is_int($k))
{
$k = $v;
$v = $ttl;
}
elseif (is_string($v))
{
$v = time() + $ttl;
}
else
{
$v += time();
}
if (! array_key_exists($k, $_SESSION))
{
return false;
}
$temp[$k] = $v;
}
$_SESSION['__ci_vars'] = isset($_SESSION['__ci_vars']) ? array_merge($_SESSION['__ci_vars'], $temp) : $temp;
return true;
}
if (! isset($_SESSION[$key]))
{
return false;
}
$_SESSION['__ci_vars'][$key] = $ttl;
return true;
}
public function unmarkTempdata($key)
{
if (empty($_SESSION['__ci_vars']))
{
return;
}
is_array($key) || $key = [$key];
foreach ($key as $k)
{
if (isset($_SESSION['__ci_vars'][$k]) && is_int($_SESSION['__ci_vars'][$k]))
{
unset($_SESSION['__ci_vars'][$k]);
}
}
if (empty($_SESSION['__ci_vars']))
{
unset($_SESSION['__ci_vars']);
}
}
public function getTempKeys(): array
{
if (! isset($_SESSION['__ci_vars']))
{
return [];
}
$keys = [];
foreach (array_keys($_SESSION['__ci_vars']) as $key)
{
is_int($_SESSION['__ci_vars'][$key]) && $keys[] = $key;
}
return $keys;
}
protected function setSaveHandler()
{
session_set_save_handler($this->driver, true);
}
protected function startSession()
{
if (ENVIRONMENT === 'testing')
{
$_SESSION = [];
return;
}
session_start();
}
protected function setCookie()
{
setcookie(
$this->sessionCookieName, session_id(), (empty($this->sessionExpiration) ? 0 : time() + $this->sessionExpiration), $this->cookiePath, $this->cookieDomain, $this->cookieSecure, true
);
}
}