Newer
Older
*
* The user-level session storage handlers:

Dries Buytaert
committed
* - _drupal_session_open()
* - _drupal_session_close()
* - _drupal_session_read()
* - _drupal_session_write()
* - _drupal_session_destroy()
* - _drupal_session_garbage_collection()
* are assigned by session_set_save_handler() in bootstrap.inc and are called
* automatically by PHP. These functions should not be called directly. Session
* data should instead be accessed via the $_SESSION superglobal.

Angie Byron
committed
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Session\UserSession;

catch
committed
use Drupal\Core\Utility\Error;
/**
* Session handler assigned by session_set_save_handler().
*
* This function is used to handle any initialization, such as file paths or
* database connections, that is needed before accessing session data. Drupal
* does not need to initialize anything in this function.
*
* This function should not be called directly.
*
* @return
* This function will always return TRUE.

Dries Buytaert
committed
function _drupal_session_open() {

Dries Buytaert
committed
return TRUE;
/**
* Session handler assigned by session_set_save_handler().
*
* This function is used to close the current session. Because Drupal stores
* session data in the database immediately on write, this function does
* not need to do anything.
*
* This function should not be called directly.
*
* @return
* This function will always return TRUE.

Dries Buytaert
committed
function _drupal_session_close() {

Dries Buytaert
committed
return TRUE;
/**
* Reads an entire session from the database (internal use only).
* Also initializes the $user object for the user associated with the session.
* This function is registered with session_set_save_handler() to support
* database-backed sessions. It is called on every page load when PHP sets
* up the $_SESSION superglobal.
*
* This function is an internal function and must not be called directly.
* Doing so may result in logging out the current user, corrupting session data
* or other unexpected behavior. Session data must always be accessed via the
* $_SESSION superglobal.
*

Dries Buytaert
committed
* @param $sid
* The session ID of the session to retrieve.
* @return
* The user's session, or an empty string if no session exists.

Dries Buytaert
committed
*/

Dries Buytaert
committed
function _drupal_session_read($sid) {

Alex Pott
committed
global $user;
// Write and Close handlers are called after destructing objects
// since PHP 5.0.5.

Neil Drumm
committed
// Thus destructors can use sessions but session handler can't use objects.
// So we are moving session closure before destructing objects.
drupal_register_shutdown_function('session_write_close');

Neil Drumm
committed
// Handle the case of first time visitors and clients that don't store
// cookies (eg. web crawlers).

Dries Buytaert
committed
$insecure_session_name = substr(session_name(), 1);

Angie Byron
committed
$cookies = \Drupal::request()->cookies;
if (!$cookies->has(session_name()) && !$cookies->has($insecure_session_name)) {
$user = new UserSession();

Dries Buytaert
committed
return '';

Dries Buytaert
committed
}
// Otherwise, if the session is still active, we have a record of the

Dries Buytaert
committed
// client's session in the database. If it's HTTPS then we are either have
// a HTTPS session or we are about to log in so we check the sessions table
// for an anonymous session with the non-HTTPS-only cookie. The session ID
// that is in the user's cookie is hashed before being stored in the database
// as a security measure. Thus, we have to hash it to match the database.
if (\Drupal::request()->isSecure()) {
$values = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.ssid = :ssid", array(':ssid' => Crypt::hashBase64($sid)))->fetchAssoc();
if (!$values) {

Angie Byron
committed
if ($cookies->has($insecure_session_name)) {
$values = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid AND s.uid = 0", array(
':sid' => Crypt::hashBase64($cookies->get($insecure_session_name))))
->fetchAssoc();

Dries Buytaert
committed
}
}
}
else {
$values = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid", array(':sid' => Crypt::hashBase64($sid)))->fetchAssoc();
}

Dries Buytaert
committed
// We found the client's session record and they are an authenticated,
// active user.
if ($values && $values['uid'] > 0 && $values['status'] == 1) {

Dries Buytaert
committed
// Add roles element to $user.
$rids = db_query("SELECT ur.rid FROM {users_roles} ur WHERE ur.uid = :uid", array(':uid' => $values['uid']))->fetchCol();
$values['roles'] = array_merge(array(DRUPAL_AUTHENTICATED_RID), $rids);
$user = new UserSession($values);

Dries Buytaert
committed
}
elseif ($values) {
// The user is anonymous or blocked. Only preserve two fields from the
// {sessions} table.
$user = new UserSession(array(
'session' => $values['session'],
'access' => $values['access'],
));
else {
// The session has expired.
$user = new UserSession();

Dries Buytaert
committed
}
// Store the session that was read for comparison in _drupal_session_write().
$last_read = &drupal_static('drupal_session_last_read');
$last_read = array(
'sid' => $sid,
'value' => $user->session,
);

Dries Buytaert
committed
return $user->session;
/**
* Writes an entire session to the database (internal use only).
* This function is registered with session_set_save_handler() to support
* database-backed sessions.
*
* This function is an internal function and must not be called directly.
* Doing so may result in corrupted session data or other unexpected behavior.
* Session data must always be accessed via the $_SESSION superglobal.
*

Dries Buytaert
committed
* @param $sid
* The session ID of the session to write to.
* @param $value
* Session data to write as a serialized string.
* @return
* Always returns TRUE.

Dries Buytaert
committed
*/

Dries Buytaert
committed
function _drupal_session_write($sid, $value) {

Alex Pott
committed
global $user;
// The exception handler is not active at this point, so we need to do it
// manually.

Dries Buytaert
committed
try {
if (!drupal_save_session()) {
// We don't have anything to do if we are not allowed to save the session.
return;
}

Dries Buytaert
committed
// Check whether $_SESSION has been changed in this request.
$last_read = &drupal_static('drupal_session_last_read');
$is_changed = !isset($last_read) || $last_read['sid'] != $sid || $last_read['value'] !== $value;
// For performance reasons, do not update the sessions table, unless
// $_SESSION has changed or more than 180 has passed since the last update.
if ($is_changed || !$user->getLastAccessedTime() || REQUEST_TIME - $user->getLastAccessedTime() > settings()->get('session_write_interval', 180)) {
// Either ssid or sid or both will be added from $key below.
$fields = array(

Dries Buytaert
committed
'uid' => $user->id(),
'hostname' => \Drupal::request()->getClientIP(),
'session' => $value,
'timestamp' => REQUEST_TIME,
);

Dries Buytaert
committed
// Use the session ID as 'sid' and an empty string as 'ssid' by default.
// _drupal_session_read() does not allow empty strings so that's a safe
// default.
$key = array('sid' => Crypt::hashBase64($sid), 'ssid' => '');

Dries Buytaert
committed
// On HTTPS connections, use the session ID as both 'sid' and 'ssid'.
if (\Drupal::request()->isSecure()) {
$key['ssid'] = Crypt::hashBase64($sid);

Angie Byron
committed
$cookies = \Drupal::request()->cookies;

Dries Buytaert
committed
// The "secure pages" setting allows a site to simultaneously use both
// secure and insecure session cookies. If enabled and both cookies are
// presented then use both keys. The session ID from the cookie is
// hashed before being stored in the database as a security measure.
if (settings()->get('mixed_mode_sessions', FALSE)) {

Dries Buytaert
committed
$insecure_session_name = substr(session_name(), 1);

Angie Byron
committed
if ($cookies->has($insecure_session_name)) {
$key['sid'] = Crypt::hashBase64($cookies->get($insecure_session_name));

Dries Buytaert
committed
}
}
}
elseif (settings()->get('mixed_mode_sessions', FALSE)) {
unset($key['ssid']);
}

Dries Buytaert
committed
db_merge('sessions')
->key($key)
->fields($fields)
->execute();
}

Dries Buytaert
committed
// Likewise, do not update access time more than once per 180 seconds.
if ($user->isAuthenticated() && REQUEST_TIME - $user->getLastAccessedTime() > settings()->get('session_write_interval', 180)) {

Dries Buytaert
committed
db_update('users')
->fields(array(
'access' => REQUEST_TIME
))

Dries Buytaert
committed
->condition('uid', $user->id())

Dries Buytaert
committed
->execute();
}
return TRUE;
}
catch (Exception $exception) {
require_once __DIR__ . '/errors.inc';
// If we are displaying errors, then do so with no possibility of a further
// uncaught exception being thrown.

Dries Buytaert
committed
if (error_displayable()) {
print '<h1>Uncaught exception thrown in session handler.</h1>';

catch
committed
print '<p>' . Error::renderExceptionSafe($exception) . '</p><hr />';

Dries Buytaert
committed
}
return FALSE;
}

Dries Buytaert
committed
/**
* Initializes the session handler, starting a session if needed.

Dries Buytaert
committed
*/

Dries Buytaert
committed
function drupal_session_initialize() {

Alex Pott
committed
global $user;

Dries Buytaert
committed

Dries Buytaert
committed
session_set_save_handler('_drupal_session_open', '_drupal_session_close', '_drupal_session_read', '_drupal_session_write', '_drupal_session_destroy', '_drupal_session_garbage_collection');

Dries Buytaert
committed
$is_https = \Drupal::request()->isSecure();

Angie Byron
committed
$cookies = \Drupal::request()->cookies;
if (($cookies->has(session_name()) && ($session_name = $cookies->get(session_name()))) || ($is_https && settings()->get('mixed_mode_sessions', FALSE) && ($cookies->has(substr(session_name(), 1))) && ($session_name = $cookies->get(substr(session_name(), 1))))) {

Dries Buytaert
committed
// If a session cookie exists, initialize the session. Otherwise the
// session is only started on demand in drupal_session_commit(), making
// anonymous users not use a session cookie unless something is stored in
// $_SESSION. This allows HTTP proxies to cache anonymous pageviews.
drupal_session_start();

Dries Buytaert
committed
if ($user->isAuthenticated() || !empty($_SESSION)) {

Dries Buytaert
committed
drupal_page_is_cacheable(FALSE);
}
}
else {
// Set a session identifier for this request. This is necessary because
// we lazily start sessions at the end of this request, and some

Dries Buytaert
committed
// processes (like drupal_get_token()) needs to know the future
// session ID in advance.
$GLOBALS['lazy_session'] = TRUE;

Dries Buytaert
committed
$user = drupal_anonymous_user();

Dries Buytaert
committed
// Less random sessions (which are much faster to generate) are used for
// anonymous users than are generated in drupal_session_regenerate() when
// a user becomes authenticated.

Angie Byron
committed
session_id(Crypt::hashBase64(uniqid(mt_rand(), TRUE)));
if ($is_https && settings()->get('mixed_mode_sessions', FALSE)) {
$insecure_session_name = substr(session_name(), 1);

Angie Byron
committed
$session_id = Crypt::hashBase64(uniqid(mt_rand(), TRUE));

Angie Byron
committed
$cookies->set($insecure_session_name, $session_id);

Dries Buytaert
committed
}
date_default_timezone_set(drupal_get_user_timezone());

Dries Buytaert
committed
}
/**

Jennifer Hodgdon
committed
* Starts a session forcefully, preserving already set session data.

Dries Buytaert
committed
*
* @ingroup php_wrappers

Dries Buytaert
committed
*/

Dries Buytaert
committed
function drupal_session_start() {
// Command line clients do not support cookies nor sessions.
if (!drupal_session_started() && !drupal_is_cli()) {

Dries Buytaert
committed
// Save current session data before starting it, as PHP will destroy it.
$session_data = isset($_SESSION) ? $_SESSION : NULL;
session_start();
drupal_session_started(TRUE);
// Restore session data.
if (!empty($session_data)) {
$_SESSION += $session_data;
}
}

Dries Buytaert
committed
}
/**
* Commits the current session, if necessary.

Dries Buytaert
committed
*

Dries Buytaert
committed
* If an anonymous user already have an empty session, destroy it.

Dries Buytaert
committed
*/

Dries Buytaert
committed
function drupal_session_commit() {

Alex Pott
committed
global $user;

Dries Buytaert
committed

Dries Buytaert
committed
if (!drupal_save_session()) {
// We don't have anything to do if we are not allowed to save the session.
return;
}

Dries Buytaert
committed
if ($user->isAnonymous() && empty($_SESSION)) {

Dries Buytaert
committed
// There is no session data to store, destroy the session if it was
// previously started.

Dries Buytaert
committed
if (drupal_session_started()) {
session_destroy();
}

Dries Buytaert
committed
}
else {

Dries Buytaert
committed
// There is session data to store. Start the session if it is not already
// started.

Dries Buytaert
committed
if (!drupal_session_started()) {
drupal_session_start();
if (\Drupal::request()->isSecure() && settings()->get('mixed_mode_sessions', FALSE)) {
$insecure_session_name = substr(session_name(), 1);
$params = session_get_cookie_params();
$expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;

Angie Byron
committed
$cookie_params = \Drupal::request()->cookies;
setcookie($insecure_session_name, $cookie_params->get($insecure_session_name), $expire, $params['path'], $params['domain'], FALSE, $params['httponly']);

Dries Buytaert
committed
}
// Write the session data.
session_write_close();

Dries Buytaert
committed
}
}
/**
* Returns whether a session has been started.

Dries Buytaert
committed
*/

Dries Buytaert
committed
function drupal_session_started($set = NULL) {
static $session_started = FALSE;
if (isset($set)) {
$session_started = $set;
}
return $session_started && session_id();

Dries Buytaert
committed
}
/**
* Called when an anonymous user becomes authenticated or vice-versa.

Dries Buytaert
committed
*
* @ingroup php_wrappers

Dries Buytaert
committed
function drupal_session_regenerate() {

Alex Pott
committed
global $user;
// Nothing to do if we are not allowed to change the session.
if (!drupal_save_session()) {
return;
}
$is_https = \Drupal::request()->isSecure();

Angie Byron
committed
$cookies = \Drupal::request()->cookies;

Alex Pott
committed
if ($is_https && settings()->get('mixed_mode_sessions', FALSE)) {

Dries Buytaert
committed
$insecure_session_name = substr(session_name(), 1);

Angie Byron
committed
if (!isset($GLOBALS['lazy_session']) && $cookies->has($insecure_session_name)) {
$old_insecure_session_id = $cookies->get($insecure_session_name);

Dries Buytaert
committed
}

Dries Buytaert
committed
$params = session_get_cookie_params();

Angie Byron
committed
$session_id = Crypt::hashBase64(uniqid(mt_rand(), TRUE) . Crypt::randomBytes(55));
// If a session cookie lifetime is set, the session will expire
// $params['lifetime'] seconds from the current request. If it is not set,
// it will expire when the browser is closed.

Dries Buytaert
committed
$expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
setcookie($insecure_session_name, $session_id, $expire, $params['path'], $params['domain'], FALSE, $params['httponly']);

Angie Byron
committed
$cookies->set($insecure_session_name, $session_id);

Dries Buytaert
committed
}

Dries Buytaert
committed
if (drupal_session_started()) {
$old_session_id = session_id();
}

Angie Byron
committed
session_id(Crypt::hashBase64(uniqid(mt_rand(), TRUE) . Crypt::randomBytes(55)));

Dries Buytaert
committed
if (isset($old_session_id)) {

Dries Buytaert
committed
$params = session_get_cookie_params();

Dries Buytaert
committed
$expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
setcookie(session_name(), session_id(), $expire, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
$fields = array('sid' => Crypt::hashBase64(session_id()));

Dries Buytaert
committed
if ($is_https) {
$fields['ssid'] = Crypt::hashBase64(session_id());

Dries Buytaert
committed
// If the "secure pages" setting is enabled, use the newly-created
// insecure session identifier as the regenerated sid.
if (settings()->get('mixed_mode_sessions', FALSE)) {
$fields['sid'] = Crypt::hashBase64($session_id);

Dries Buytaert
committed
}
}
db_update('sessions')
->fields($fields)
->condition($is_https ? 'ssid' : 'sid', Crypt::hashBase64($old_session_id))

Dries Buytaert
committed
->execute();
}
elseif (isset($old_insecure_session_id)) {
// If logging in to the secure site, and there was no active session on the
// secure site but a session was active on the insecure site, update the
// insecure session with the new session identifiers.

Dries Buytaert
committed
db_update('sessions')
->fields(array('sid' => Crypt::hashBase64($session_id), 'ssid' => Crypt::hashBase64(session_id())))
->condition('sid', Crypt::hashBase64($old_insecure_session_id))

Dries Buytaert
committed
->execute();
}

Dries Buytaert
committed
else {
// Start the session when it doesn't exist yet.
// Preserve the logged in user, as it will be reset to anonymous
// by _drupal_session_read.
$account = $user;
drupal_session_start();
$user = $account;
}
date_default_timezone_set(drupal_get_user_timezone());
}
/**

Dries Buytaert
committed
* Session handler assigned by session_set_save_handler().
* Cleans up a specific session.

Dries Buytaert
committed
*

Dries Buytaert
committed
* @param $sid

Dries Buytaert
committed
* Session ID.

Dries Buytaert
committed
*/

Dries Buytaert
committed
function _drupal_session_destroy($sid) {

Alex Pott
committed
global $user;

Dries Buytaert
committed
// Nothing to do if we are not allowed to change the session.
if (!drupal_save_session()) {
return;
}
$is_https = \Drupal::request()->isSecure();

Dries Buytaert
committed
// Delete session data.

Dries Buytaert
committed
db_delete('sessions')
->condition($is_https ? 'ssid' : 'sid', Crypt::hashBase64($sid))

Dries Buytaert
committed
->execute();

Dries Buytaert
committed
// Reset $_SESSION and $user to prevent a new session from being started
// in drupal_session_commit().
$_SESSION = array();
$user = drupal_anonymous_user();

Dries Buytaert
committed
// Unset the session cookies.
_drupal_session_delete_cookie(session_name());
if ($is_https) {
_drupal_session_delete_cookie(substr(session_name(), 1), FALSE);
}
elseif (settings()->get('mixed_mode_sessions', FALSE)) {
_drupal_session_delete_cookie('S' . session_name(), TRUE);

Dries Buytaert
committed
}
}
/**
* Deletes the session cookie.
*
* @param $name
* Name of session cookie to delete.
* @param boolean $secure
* Force the secure value of the cookie.

Dries Buytaert
committed
*/
function _drupal_session_delete_cookie($name, $secure = NULL) {

Angie Byron
committed
$cookies = \Drupal::request()->cookies;
if ($cookies->has($name) || (!\Drupal::request()->isSecure() && $secure === TRUE)) {

Dries Buytaert
committed
$params = session_get_cookie_params();
if ($secure !== NULL) {
$params['secure'] = $secure;
}
setcookie($name, '', REQUEST_TIME - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']);

Angie Byron
committed
$cookies->remove($name);

Dries Buytaert
committed
}

Dries Buytaert
committed
}
/**
* Ends a specific user's session(s).

Dries Buytaert
committed
* @param $uid

Dries Buytaert
committed
* User ID.

Dries Buytaert
committed
function drupal_session_destroy_uid($uid) {
// Nothing to do if we are not allowed to change the session.
if (!drupal_save_session()) {
return;
}

Dries Buytaert
committed
db_delete('sessions')
->condition('uid', $uid)
->execute();

Dries Buytaert
committed
/**
* Session handler assigned by session_set_save_handler().
* Cleans up stalled sessions.

Dries Buytaert
committed
*

Dries Buytaert
committed
* @param $lifetime

Dries Buytaert
committed
* The value of session.gc_maxlifetime, passed by PHP.
* Sessions not updated for more than $lifetime seconds will be removed.

Dries Buytaert
committed
*/

Dries Buytaert
committed
function _drupal_session_garbage_collection($lifetime) {

Dries Buytaert
committed
// Be sure to adjust 'php_value session.gc_maxlifetime' to a large enough
// value. For example, if you want user sessions to stay in your database

Dries Buytaert
committed
// for three weeks before deleting them, you need to set gc_maxlifetime
// to '1814400'. At that value, only after a user doesn't log in after

Dries Buytaert
committed
// three weeks (1814400 seconds) will his/her session be removed.

Dries Buytaert
committed
db_delete('sessions')
->condition('timestamp', REQUEST_TIME - $lifetime, '<')
->execute();

Dries Buytaert
committed
return TRUE;

Gábor Hojtsy
committed
/**
* Determines whether to save session data of the current request.

Gábor Hojtsy
committed
*
* This function allows the caller to temporarily disable writing of
* session data, should the request end while performing potentially
* dangerous operations, such as manipulating the global $user object.

Dries Buytaert
committed
* See http://drupal.org/node/218104 for usage.

Gábor Hojtsy
committed
*
* @param $status
* Disables writing of session data when FALSE, (re-)enables
* writing when TRUE.

Gábor Hojtsy
committed
* @return
* FALSE if writing session data has been disabled. Otherwise, TRUE.
*/

Dries Buytaert
committed
function drupal_save_session($status = NULL) {
// PHP session ID, session, and cookie handling happens in the global scope.
// This value has to persist across calls to drupal_static_reset(), since a
// potentially wrong or disallowed session would be written otherwise.
static $save_session = TRUE;

Gábor Hojtsy
committed
if (isset($status)) {
$save_session = $status;
}

Dries Buytaert
committed
return $save_session;