first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
+307
View File
@@ -0,0 +1,307 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Database based session handler.
*
* @package core
* @copyright 2013 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\session;
use SessionHandlerInterface;
/**
* Database based session handler.
*
* @package core
* @copyright 2013 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class database extends handler implements SessionHandlerInterface {
/** @var \stdClass $record session record */
protected $recordid = null;
/** @var \moodle_database $database session database */
protected $database = null;
/** @var bool $failed session read/init failed, do not write back to DB */
protected $failed = false;
/** @var string $lasthash hash of the session data content */
protected $lasthash = null;
/** @var int $acquiretimeout how long to wait for session lock */
protected $acquiretimeout = 120;
/**
* Create new instance of handler.
*/
public function __construct() {
global $DB, $CFG;
// Note: we store the reference here because we need to modify database in shutdown handler.
$this->database = $DB;
if (!empty($CFG->session_database_acquire_lock_timeout)) {
$this->acquiretimeout = (int)$CFG->session_database_acquire_lock_timeout;
}
}
/**
* Init session handler.
*/
public function init() {
if (!$this->database->session_lock_supported()) {
throw new exception('sessionhandlerproblem', 'error', '', null, 'Database does not support session locking');
}
$result = session_set_save_handler($this);
if (!$result) {
throw new exception('dbsessionhandlerproblem', 'error');
}
}
/**
* Check the backend contains data for this session id.
*
* Note: this is intended to be called from manager::session_exists() only.
*
* @param string $sid
* @return bool true if session found.
*/
public function session_exists($sid) {
// It was already checked in the calling code that the record in sessions table exists.
return true;
}
/**
* Kill all active sessions, the core sessions table is
* purged afterwards.
*/
public function kill_all_sessions() {
// Nothing to do, the sessions table is cleared from core.
return;
}
/**
* Kill one session, the session record is removed afterwards.
* @param string $sid
*/
public function kill_session($sid) {
// Nothing to do, the sessions table is purged afterwards.
return;
}
/**
* Open session handler.
*
* {@see http://php.net/manual/en/function.session-set-save-handler.php}
*
* @param string $path
* @param string $name
* @return bool success
*/
public function open(string $path, string $name): bool {
// Note: we use the already open database.
return true;
}
/**
* Close session handler.
*
* {@see http://php.net/manual/en/function.session-set-save-handler.php}
*
* @return bool success
*/
public function close(): bool {
if ($this->recordid) {
try {
$this->database->release_session_lock($this->recordid);
} catch (\Exception $ex) {
// Ignore any problems.
}
}
$this->recordid = null;
$this->lasthash = null;
return true;
}
/**
* Read session handler.
*
* {@see http://php.net/manual/en/function.session-set-save-handler.php}
*
* @param string $sid
* @return string|false
*/
public function read(string $sid): string|false {
try {
if (!$record = $this->database->get_record('sessions', array('sid'=>$sid), 'id')) {
// Let's cheat and skip locking if this is the first access,
// do not create the record here, let the manager do it after session init.
$this->failed = false;
$this->recordid = null;
$this->lasthash = sha1('');
return '';
}
if ($this->recordid and $this->recordid != $record->id) {
error_log('Second session read with different record id detected, cannot read session');
$this->failed = true;
$this->recordid = null;
return '';
}
if (!$this->recordid) {
// Lock session if exists and not already locked.
if ($this->requires_write_lock()) {
$this->database->get_session_lock($record->id, $this->acquiretimeout);
}
$this->recordid = $record->id;
}
} catch (\dml_sessionwait_exception $ex) {
// This is a fatal error, better inform users.
// It should not happen very often - all pages that need long time to execute
// should close session immediately after access control checks.
error_log('Cannot obtain session lock for sid: '.$sid);
$this->failed = true;
throw $ex;
} catch (\Exception $ex) {
// Do not rethrow exceptions here, this should not happen.
error_log('Unknown exception when starting database session : '.$sid.' - '.$ex->getMessage());
$this->failed = true;
$this->recordid = null;
return '';
}
// Finally read the full session data because we know we have the lock now.
if (!$record = $this->database->get_record('sessions', array('id'=>$record->id), 'id, sessdata')) {
// Ignore - something else just deleted the session record.
$this->failed = true;
$this->recordid = null;
return '';
}
$this->failed = false;
if (is_null($record->sessdata)) {
$data = '';
$this->lasthash = sha1('');
} else {
$data = base64_decode($record->sessdata);
$this->lasthash = sha1($record->sessdata);
}
return $data;
}
/**
* Write session handler.
*
* {@see http://php.net/manual/en/function.session-set-save-handler.php}
*
* NOTE: Do not write to output or throw any exceptions!
* Hopefully the next page is going to display nice error or it recovers...
*
* @param string $id
* @param string $data
* @return bool success
*/
public function write(string $id, string $data): bool {
if ($this->failed) {
// Do not write anything back - we failed to start the session properly.
return false;
}
// There might be some binary mess.
$sessdata = base64_encode($data);
$hash = sha1($sessdata);
if ($hash === $this->lasthash) {
return true;
}
try {
if ($this->recordid) {
$this->database->set_field('sessions', 'sessdata', $sessdata, ['id' => $this->recordid]);
} else {
// This happens in the first request when session record was just created in manager.
$this->database->set_field('sessions', 'sessdata', $sessdata, ['sid' => $id]);
}
} catch (\Exception $ex) {
// Do not rethrow exceptions here, this should not happen.
// phpcs:ignore moodle.PHP.ForbiddenFunctions.FoundWithAlternative
error_log(
"Unknown exception when writing database session data : {$id} - " . $ex->getMessage(),
);
}
return true;
}
/**
* Destroy session handler.
*
* {@see http://php.net/manual/en/function.session-set-save-handler.php}
*
* @param string $id
* @return bool success
*/
public function destroy(string $id): bool {
if (!$session = $this->database->get_record('sessions', ['sid' => $id], 'id, sid')) {
if ($id == session_id()) {
$this->recordid = null;
$this->lasthash = null;
}
return true;
}
if ($this->recordid && ($session->id == $this->recordid)) {
try {
$this->database->release_session_lock($this->recordid);
} catch (\Exception $ex) {
// Ignore problems.
}
$this->recordid = null;
$this->lasthash = null;
}
$this->database->delete_records('sessions', ['id' => $session->id]);
return true;
}
/**
* GC session handler.
*
* {@see http://php.net/manual/en/function.session-set-save-handler.php}
*
* @param int $max_lifetime moodle uses special timeout rules
* @return bool success
*/
// phpcs:ignore moodle.NamingConventions.ValidVariableName.VariableNameUnderscore
public function gc(int $max_lifetime): int|false {
// This should do something only if cron is not running properly...
if (!$stalelifetime = ini_get('session.gc_maxlifetime')) {
return false;
}
$params = ['purgebefore' => (time() - $stalelifetime)];
$count = $this->database->count_records_select('sessions', 'userid = 0 AND timemodified < :purgebefore', $params);
$this->database->delete_records_select('sessions', 'userid = 0 AND timemodified < :purgebefore', $params);
return $count;
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Session exception.
*
* @package core
* @copyright 2013 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\session;
defined('MOODLE_INTERNAL') || die();
/**
* Session related exception class.
* @package core
*/
class exception extends \moodle_exception {
}
+99
View File
@@ -0,0 +1,99 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This class contains a list of webservice functions related to session.
*
* @package core
* @copyright 2019 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\session;
use core_external\external_api;
use core_external\external_description;
use core_external\external_function_parameters;
use core_external\external_single_structure;
use core_external\external_value;
/**
* This class contains a list of webservice functions related to session.
*
* @copyright 2019 Damyon Wiese
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since 2.9
*/
class external extends external_api {
/**
* Returns description of touch_session() parameters.
*
* @return external_function_parameters
*/
public static function touch_session_parameters() {
return new external_function_parameters([]);
}
/**
* Extend the current session.
*
* @return array the mapping
*/
public static function touch_session() {
\core\session\manager::touch_session(session_id());
return true;
}
/**
* Returns description of touch_session() result value.
*
* @return external_description
*/
public static function touch_session_returns() {
return new external_value(PARAM_BOOL, 'result');
}
/**
* Returns description of time_remaining() parameters.
*
* @return external_function_parameters
*/
public static function time_remaining_parameters() {
return new external_function_parameters([]);
}
/**
* Extend the current session.
*
* @return array the mapping
*/
public static function time_remaining() {
return \core\session\manager::time_remaining(session_id());
}
/**
* Returns description of touch_session() result value.
*
* @return external_description
*/
public static function time_remaining_returns() {
return new external_single_structure([
'userid' => new external_value(PARAM_INT, 'The current user id.'),
'timeremaining' => new external_value(PARAM_INT, 'The number of seconds remaining in this session.'),
]);
}
}
+121
View File
@@ -0,0 +1,121 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* File based session handler.
*
* @package core
* @copyright 2013 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\session;
defined('MOODLE_INTERNAL') || die();
/**
* File based session handler.
*
* @package core
* @copyright 2013 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class file extends handler {
/** @var string session dir */
protected $sessiondir;
/**
* Create new instance of handler.
*/
public function __construct() {
global $CFG;
if (!empty($CFG->session_file_save_path)) {
$this->sessiondir = $CFG->session_file_save_path;
} else {
$this->sessiondir = "$CFG->dataroot/sessions";
}
}
/**
* Init session handler.
*/
public function init() {
if (preg_match('/^[0-9]+;/', $this->sessiondir)) {
throw new exception('sessionhandlerproblem', 'error', '', null, 'Multilevel session directories are not supported');
}
// Make sure session directory exists and is writable.
make_writable_directory($this->sessiondir, false);
if (!is_writable($this->sessiondir)) {
throw new exception('sessionhandlerproblem', 'error', '', null, 'Session directory is not writable');
}
// Need to disable debugging since disk_free_space()
// will fail on very large partitions (see MDL-19222).
$freespace = @disk_free_space($this->sessiondir);
// MDL-43039: disk_free_space() returns null if disabled.
if (!($freespace > 2048) and ($freespace !== false) and ($freespace !== null)) {
throw new exception('sessiondiskfull', 'error');
}
// NOTE: we cannot set any lock acquiring timeout here - bad luck.
ini_set('session.save_handler', 'files');
ini_set('session.save_path', $this->sessiondir);
}
/**
* Check the backend contains data for this session id.
*
* Note: this is intended to be called from manager::session_exists() only.
*
* @param string $sid
* @return bool true if session found.
*/
public function session_exists($sid) {
$sid = clean_param($sid, PARAM_FILE);
if (!$sid) {
return false;
}
$sessionfile = "$this->sessiondir/sess_$sid";
return file_exists($sessionfile);
}
/**
* Kill all active sessions, the core sessions table is
* purged afterwards.
*/
public function kill_all_sessions() {
if (is_dir($this->sessiondir)) {
foreach (glob("$this->sessiondir/sess_*") as $filename) {
@unlink($filename);
}
}
}
/**
* Kill one session, the session record is removed afterwards.
* @param string $sid
*/
public function kill_session($sid) {
$sid = clean_param($sid, PARAM_FILE);
if (!$sid) {
return;
}
$sessionfile = "$this->sessiondir/sess_$sid";
if (file_exists($sessionfile)) {
@unlink($sessionfile);
}
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Session handler base.
*
* @package core
* @copyright 2013 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\session;
defined('MOODLE_INTERNAL') || die();
/**
* Session handler base.
*
* @package core
* @copyright 2013 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class handler {
/** @var boolean $requireswritelock does the session need and/or have a lock? */
protected $requireswritelock = false;
/**
* Start the session.
* @return bool success
*/
public function start() {
return session_start();
}
/**
* Write the session and release lock. If the session was not intentionally opened
* with a write lock, then we will abort the session instead if able.
*/
public function write_close() {
if ($this->requires_write_lock()) {
session_write_close();
$this->requireswritelock = false;
} else {
$this->abort();
}
}
/**
* Release lock on the session without writing it.
* May not be possible in older versions of PHP. If so, session may be written anyway
* so that any locks are released.
*/
public function abort() {
session_abort();
$this->requireswritelock = false;
}
/**
* This is called after init() and before start() to indicate whether the session
* opened should be writable or not. This is intentionally captured even if your
* handler doesn't support non-locking sessions, so that behavior (upon session close)
* matches closely between handlers.
* @param bool $requireswritelock true if needs to be open for writing
*/
public function set_requires_write_lock($requireswritelock) {
$this->requireswritelock = $requireswritelock;
}
/**
* Has this session been opened with a writelock? Your handler should call this during
* start() if you support read-only sessions.
* @return bool true if session is intended to have a write lock.
*/
public function requires_write_lock() {
return $this->requireswritelock;
}
/**
* Init session handler.
*/
abstract public function init();
/**
* Check the backend contains data for this session id.
*
* Note: this is intended to be called from manager::session_exists() only.
*
* @param string $sid
* @return bool true if session found.
*/
abstract public function session_exists($sid);
/**
* Kill all active sessions, the core sessions table is
* purged afterwards.
*/
abstract public function kill_all_sessions();
/**
* Kill one session, the session record is removed afterwards.
* @param string $sid
*/
abstract public function kill_session($sid);
}
File diff suppressed because it is too large Load Diff
+301
View File
@@ -0,0 +1,301 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Memcached based session handler.
*
* @package core
* @copyright 2013 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\session;
defined('MOODLE_INTERNAL') || die();
/**
* Memcached based session handler.
*
* @package core
* @copyright 2013 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class memcached extends handler {
/** @var string $savepath save_path string */
protected $savepath;
/** @var array $servers list of servers parsed from save_path */
protected $servers;
/** @var string $prefix session key prefix */
protected $prefix;
/** @var int $acquiretimeout how long to wait for session lock */
protected $acquiretimeout = 120;
/**
* @var int $lockexpire how long to wait before expiring the lock so that other requests
* may continue execution, ignored if PECL memcached is below version 2.2.0.
*/
protected $lockexpire = 7200;
/**
* @var integer $lockretrysleep Used for memcached 3.x (PHP7), the amount of time to
* sleep between attempts to acquire the session lock. Mimics the deprecated config
* memcached.sess_lock_wait.
*/
protected $lockretrysleep = 150;
/**
* Create new instance of handler.
*/
public function __construct() {
global $CFG;
if (empty($CFG->session_memcached_save_path)) {
$this->savepath = '';
} else {
$this->savepath = $CFG->session_memcached_save_path;
}
if (empty($this->savepath)) {
$this->servers = array();
} else {
$this->servers = self::connection_string_to_memcache_servers($this->savepath);
}
if (empty($CFG->session_memcached_prefix)) {
$this->prefix = ini_get('memcached.sess_prefix');
} else {
$this->prefix = $CFG->session_memcached_prefix;
}
if (!empty($CFG->session_memcached_acquire_lock_timeout)) {
$this->acquiretimeout = (int)$CFG->session_memcached_acquire_lock_timeout;
}
if (!empty($CFG->session_memcached_lock_expire)) {
$this->lockexpire = (int)$CFG->session_memcached_lock_expire;
}
if (!empty($CFG->session_memcached_lock_retry_sleep)) {
$this->lockretrysleep = (int)$CFG->session_memcached_lock_retry_sleep;
}
}
/**
* Start the session.
* @return bool success
*/
public function start() {
ini_set('memcached.sess_locking', $this->requires_write_lock() ? '1' : '0');
// NOTE: memcached before 2.2.0 expires session locks automatically after max_execution_time,
// this leads to major difference compared to other session drivers that timeout
// and stop the second request execution instead.
$default = ini_get('max_execution_time');
set_time_limit($this->acquiretimeout);
$isnewsession = empty($_COOKIE[session_name()]);
$starttimer = microtime(true);
$result = parent::start();
// If session_start returned TRUE, but it took as long
// as the timeout value, and the $_SESSION returned is
// empty when should not have been (isnewsession false)
// then assume it did timeout and is invalid.
// Add 1 second to elapsed time to account for inexact
// timings in php_memcached_session.c.
// @TODO Remove this check when php-memcached is fixed
// to return false after key lock acquisition timeout.
if (!$isnewsession && $result && count($_SESSION) == 0
&& (microtime(true) - $starttimer + 1) >= floatval($this->acquiretimeout)) {
$result = false;
}
set_time_limit($default);
return $result;
}
/**
* Init session handler.
*/
public function init() {
if (!extension_loaded('memcached')) {
throw new exception('sessionhandlerproblem', 'error', '', null, 'memcached extension is not loaded');
}
$version = phpversion('memcached');
if (!$version or version_compare($version, '2.0') < 0) {
throw new exception('sessionhandlerproblem', 'error', '', null, 'memcached extension version must be at least 2.0');
}
if (empty($this->savepath)) {
throw new exception('sessionhandlerproblem', 'error', '', null, '$CFG->session_memcached_save_path must be specified in config.php');
}
ini_set('session.save_handler', 'memcached');
ini_set('session.save_path', $this->savepath);
ini_set('memcached.sess_prefix', $this->prefix);
ini_set('memcached.sess_lock_expire', $this->lockexpire);
if (version_compare($version, '3.0.0-dev') >= 0) {
// With memcached 3.x (PHP 7) we configure the max retries to make and the time to sleep between each retry.
// There are two sleep config values, an initial and a max value.
// After each attempt the memcached module adjusts the sleep value to be the lesser of the configured max
// value, or 2X the previous value.
// With default memcached.ini configs (5, 1s, 2s) the result is only 5 attempts to lock over 9 sec.
// To mimic the behavior of the 2.2.x module so we get more attempts and much more frequently, config both
// sleep values to the old default value of 150 msec (making it constant) and calculate number of retries
// using the existing Moodle config $CFG->session_memcached_acquire_lock_timeout.
// Doing this so admins configure session lock attempt timeout in familiar terms, and more straight-forward
// to detect if lock attempt timeout has occurred in start().
// If _min and _max values are not equal, the actual lock acquire timeout will not be the expected
// configured value in $CFG->session_memcached_acquire_lock_timeout; this will cause session data loss when
// failure to acquire the lock is not detected.
ini_set('memcached.sess_lock_wait_min', $this->lockretrysleep);
ini_set('memcached.sess_lock_wait_max', $this->lockretrysleep);
ini_set('memcached.sess_lock_retries', (int)(($this->acquiretimeout * 1000) / $this->lockretrysleep) + 1);
} else {
// With memcached 2.2.x we configure max time to attempt lock, and accept default value (in memcached.ini)
// for sleep time between each attempt (usually 150 msec), then memcached calculates the max number of
// retries to make.
ini_set('memcached.sess_lock_max_wait', $this->acquiretimeout);
}
}
/**
* Check the backend contains data for this session id.
*
* Note: this is intended to be called from manager::session_exists() only.
*
* @param string $sid
* @return bool true if session found.
*/
public function session_exists($sid) {
if (!$this->servers) {
return false;
}
// Go through the list of all servers because
// we do not know where the session handler put the
// data.
foreach ($this->servers as $server) {
list($host, $port) = $server;
$memcached = new \Memcached();
$memcached->addServer($host, $port);
$value = $memcached->get($this->prefix . $sid);
$memcached->quit();
if ($value !== false) {
return true;
}
}
return false;
}
/**
* Kill all active sessions, the core sessions table is
* purged afterwards.
*/
public function kill_all_sessions() {
global $DB;
if (!$this->servers) {
return;
}
// Go through the list of all servers because
// we do not know where the session handler put the
// data.
$memcacheds = array();
foreach ($this->servers as $server) {
list($host, $port) = $server;
$memcached = new \Memcached();
$memcached->addServer($host, $port);
$memcacheds[] = $memcached;
}
// Note: this can be significantly improved by fetching keys from memcached,
// but we need to make sure we are not deleting somebody else's sessions.
$rs = $DB->get_recordset('sessions', array(), 'id DESC', 'id, sid');
foreach ($rs as $record) {
foreach ($memcacheds as $memcached) {
$memcached->delete($this->prefix . $record->sid);
}
}
$rs->close();
foreach ($memcacheds as $memcached) {
$memcached->quit();
}
}
/**
* Kill one session, the session record is removed afterwards.
* @param string $sid
*/
public function kill_session($sid) {
if (!$this->servers) {
return;
}
// Go through the list of all servers because
// we do not know where the session handler put the
// data.
foreach ($this->servers as $server) {
list($host, $port) = $server;
$memcached = new \Memcached();
$memcached->addServer($host, $port);
$memcached->delete($this->prefix . $sid);
$memcached->quit();
}
}
/**
* Convert a connection string to an array of servers.
*
* "abc:123, xyz:789" to
* [
* ['abc', '123'],
* ['xyz', '789'],
* ]
*
* @param string $str save_path value containing memcached connection string
* @return array[]
*/
protected static function connection_string_to_memcache_servers(string $str): array {
$servers = [];
$parts = explode(',', $str);
foreach ($parts as $part) {
$part = trim($part);
$pos = strrpos($part, ':');
if ($pos !== false) {
$host = substr($part, 0, $pos);
$port = substr($part, ($pos + 1));
} else {
$host = $part;
$port = 11211;
}
$servers[] = [$host, $port];
}
return $servers;
}
}
+703
View File
@@ -0,0 +1,703 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Redis based session handler.
*
* @package core
* @copyright 2015 Russell Smith <mr-russ@smith2001.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\session;
use RedisException;
use RedisClusterException;
use SessionHandlerInterface;
/**
* Redis based session handler.
*
* The default Redis session handler does not handle locking in 2.2.7, so we have written a php session handler
* that uses locking. The places where locking is used was modeled from the memcached code that is used in Moodle
* https://github.com/php-memcached-dev/php-memcached/blob/master/php_memcached_session.c
*
* @package core
* @copyright 2016 Russell Smith
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class redis extends handler implements SessionHandlerInterface {
/**
* Compressor: none.
*/
const COMPRESSION_NONE = 'none';
/**
* Compressor: PHP GZip.
*/
const COMPRESSION_GZIP = 'gzip';
/**
* Compressor: PHP Zstandard.
*/
const COMPRESSION_ZSTD = 'zstd';
/**
* Minimum version of the Redis extension required.
*/
public const REDIS_EXTENSION_MIN_VERSION = '2.2.4';
/**
* Minimum version of the Redis extension required.
*/
private const REDIS_SERVER_MIN_VERSION = '2.6.12';
/** @var array $host save_path string */
protected array $host = [];
/** @var int $port The port to connect to */
protected $port = 6379;
/** @var array $sslopts SSL options, if applicable */
protected $sslopts = [];
/** @var string $auth redis password */
protected $auth = '';
/** @var int $database the Redis database to store sesions in */
protected $database = 0;
/** @var array $servers list of servers parsed from save_path */
protected $prefix = '';
/** @var int $acquiretimeout how long to wait for session lock in seconds */
protected $acquiretimeout = 120;
/** @var int $acquirewarn how long before warning when waiting for a lock in seconds */
protected $acquirewarn = null;
/** @var int $lockretry how long to wait between session lock attempts in ms */
protected $lockretry = 100;
/** @var int $serializer The serializer to use */
protected $serializer = \Redis::SERIALIZER_PHP;
/** @var int $compressor The compressor to use */
protected $compressor = self::COMPRESSION_NONE;
/** @var string $lasthash hash of the session data content */
protected $lasthash = null;
/**
* @var int $lockexpire how long to wait in seconds before expiring the lock automatically
* so that other requests may continue execution, ignored if PECL redis is below version 2.2.0.
*/
protected $lockexpire;
/** @var Redis|RedisCluster Connection */
protected $connection = null;
/** @var array $locks List of currently held locks by this page. */
protected $locks = array();
/** @var int $timeout How long sessions live before expiring. */
protected $timeout;
/** @var bool $clustermode Redis in cluster mode. */
protected bool $clustermode = false;
/** @var int Maximum number of retries for cache store operations. */
const MAX_RETRIES = 5;
/** @var int The number of seconds to wait for a connection or response from the Redis server. */
const CONNECTION_TIMEOUT = 10;
/**
* Create new instance of handler.
*/
public function __construct() {
global $CFG;
if (isset($CFG->session_redis_host)) {
// If there is only one host, use the single Redis connection.
// If there are multiple hosts (separated by a comma), use the Redis cluster connection.
$this->host = array_filter(array_map('trim', explode(',', $CFG->session_redis_host)));
$this->clustermode = count($this->host) > 1;
}
if (isset($CFG->session_redis_port)) {
$this->port = (int)$CFG->session_redis_port;
}
if (isset($CFG->session_redis_encrypt) && $CFG->session_redis_encrypt) {
$this->sslopts = $CFG->session_redis_encrypt;
}
if (isset($CFG->session_redis_auth)) {
$this->auth = $CFG->session_redis_auth;
}
if (isset($CFG->session_redis_database)) {
$this->database = (int)$CFG->session_redis_database;
}
if (isset($CFG->session_redis_prefix)) {
$this->prefix = $CFG->session_redis_prefix;
}
if (isset($CFG->session_redis_acquire_lock_timeout)) {
$this->acquiretimeout = (int)$CFG->session_redis_acquire_lock_timeout;
}
if (isset($CFG->session_redis_acquire_lock_warn)) {
$this->acquirewarn = (int)$CFG->session_redis_acquire_lock_warn;
}
if (isset($CFG->session_redis_acquire_lock_retry)) {
$this->lockretry = (int)$CFG->session_redis_acquire_lock_retry;
}
if (!empty($CFG->session_redis_serializer_use_igbinary) && defined('\Redis::SERIALIZER_IGBINARY')) {
$this->serializer = \Redis::SERIALIZER_IGBINARY; // Set igbinary serializer if phpredis supports it.
}
// The following configures the session lifetime in redis to allow some
// wriggle room in the user noticing they've been booted off and
// letting them log back in before they lose their session entirely.
$updatefreq = empty($CFG->session_update_timemodified_frequency) ? 20 : $CFG->session_update_timemodified_frequency;
$this->timeout = $CFG->sessiontimeout + $updatefreq + MINSECS;
// This sets the Redis session lock expiry time to whatever is lower, either
// the PHP execution time `max_execution_time`, if the value is positive, or the
// globally configured `sessiontimeout`.
//
// Setting it to the lower of the two will not make things worse it if the execution timeout
// is longer than the session timeout.
//
// For the PHP execution time, once the PHP execution time is over, we can be sure
// that the lock is no longer actively held so that the lock can expire safely.
//
// Although at `lib/classes/php_time_limit.php::raise(int)`, Moodle can
// progressively increase the maximum PHP execution time, this is limited to the
// `max_execution_time` value defined in the `php.ini`.
// For the session timeout, we assume it is safe to consider the lock to expire
// once the session itself expires.
// If we unnecessarily hold the lock any longer, it blocks other session requests.
$this->lockexpire = ini_get('max_execution_time');
if ($this->lockexpire < 0) {
// If the max_execution_time is set to a value lower than 0, which is invalid, use the default value.
// https://www.php.net/manual/en/info.configuration.php#ini.max-execution-time defines the default as 30.
// Note: This value is not available programatically.
$this->lockexpire = 30;
}
if (empty($this->lockexpire) || ($this->lockexpire > (int)$CFG->sessiontimeout)) {
// The value of the max_execution_time is either unlimited (0), or higher than the session timeout.
// Cap it at the session timeout.
$this->lockexpire = (int)$CFG->sessiontimeout;
}
if (isset($CFG->session_redis_lock_expire)) {
$this->lockexpire = (int)$CFG->session_redis_lock_expire;
}
if (isset($CFG->session_redis_compressor)) {
$this->compressor = $CFG->session_redis_compressor;
}
}
/**
* Start the session.
*
* @return bool success
*/
public function start() {
$result = parent::start();
return $result;
}
/**
* Init session handler.
*/
public function init() {
if (!extension_loaded('redis')) {
throw new exception('sessionhandlerproblem', 'error', '', null, 'redis extension is not loaded');
}
if (empty($this->host)) {
throw new exception('sessionhandlerproblem', 'error', '', null,
'$CFG->session_redis_host must be specified in config.php');
}
// The session handler requires a version of PHP Redis extension with support for SET command options (at least 2.2.4).
$version = phpversion('Redis');
if (!$version || version_compare($version, self::REDIS_EXTENSION_MIN_VERSION) <= 0) {
throw new exception('sessionhandlerproblem', 'error', '', null,
'redis extension version must be at least ' . self::REDIS_EXTENSION_MIN_VERSION);
}
$result = session_set_save_handler($this);
if (!$result) {
throw new exception('redissessionhandlerproblem', 'error');
}
$encrypt = (bool) ($this->sslopts ?? false);
// Set Redis server(s).
$trimmedservers = [];
foreach ($this->host as $host) {
$server = strtolower(trim($host));
if (!empty($server)) {
if ($server[0] === '/' || str_starts_with($server, 'unix://')) {
$port = 0;
$trimmedservers[] = $server;
} else {
$port = $this->port ?? 6379; // No Unix socket so set default port.
if (strpos($server, ':')) { // Check for custom port.
list($server, $port) = explode(':', $server);
}
$trimmedservers[] = $server.':'.$port;
}
// We only need the first record for the single redis.
if (!$this->clustermode) {
// Handle the case when the server is not a Unix domain socket.
if ($port !== 0) {
list($server, ) = explode(':', $trimmedservers[0]);
} else {
$server = $trimmedservers[0];
}
break;
}
}
}
// TLS/SSL Configuration.
$opts = [];
if ($encrypt) {
if ($this->clustermode) {
$opts = $this->sslopts;
} else {
// For a single (non-cluster) Redis, the TLS/SSL config must be added to the 'stream' key.
$opts['stream'] = $this->sslopts;
}
}
// MDL-59866: Add retries for connections (up to 5 times) to make sure it goes through.
$counter = 1;
$exceptionclass = $this->clustermode ? 'RedisClusterException' : 'RedisException';
while ($counter <= self::MAX_RETRIES) {
$this->connection = null;
// Make a connection to Redis server(s).
try {
// Create a $redis object of a RedisCluster or Redis class.
if ($this->clustermode) {
$this->connection = new \RedisCluster(
null,
$trimmedservers,
self::CONNECTION_TIMEOUT, // Timeout.
self::CONNECTION_TIMEOUT, // Read timeout.
true,
$this->auth,
!empty($opts) ? $opts : null,
);
} else {
$delay = rand(100, 500);
$this->connection = new \Redis();
$this->connection->connect(
$server,
$port,
self::CONNECTION_TIMEOUT, // Timeout.
null,
$delay, // Retry interval.
self::CONNECTION_TIMEOUT, // Read timeout.
$opts,
);
if ($this->auth !== '' && !$this->connection->auth($this->auth)) {
throw new $exceptionclass('Unable to authenticate.');
}
}
if (!$this->connection->setOption(\Redis::OPT_SERIALIZER, $this->serializer)) {
throw new $exceptionclass('Unable to set the Redis PHP Serializer option.');
}
if ($this->prefix !== '') {
// Use custom prefix on sessions.
if (!$this->connection->setOption(\Redis::OPT_PREFIX, $this->prefix)) {
throw new $exceptionclass('Unable to set the Redis Prefix option.');
}
}
if ($this->sslopts && !$this->connection->ping('Ping')) {
// In case of a TLS connection,
// if phpredis client does not communicate immediately with the server the connection hangs.
// See https://github.com/phpredis/phpredis/issues/2332.
throw new $exceptionclass("Ping failed");
}
if ($this->database !== 0) {
if (!$this->connection->select($this->database)) {
throw new $exceptionclass('Unable to select the Redis database ' . $this->database . '.');
}
}
// The session handler requires a version of Redis server with support for SET command options (at least 2.6.12).
$serverversion = $this->connection->info('server')['redis_version'];
if (version_compare($serverversion, self::REDIS_SERVER_MIN_VERSION) <= 0) {
throw new exception('sessionhandlerproblem', 'error', '', null,
'redis server version must be at least ' . self::REDIS_SERVER_MIN_VERSION);
}
return true;
} catch (RedisException | RedisClusterException $e) {
$redishost = $this->clustermode ? implode(',', $this->host) : $server. ':'. $port;
$logstring = "Failed to connect (try {$counter} out of " . self::MAX_RETRIES . ") to Redis ";
$logstring .= "at ". $redishost .", the error returned was: {$e->getMessage()}";
debugging($logstring);
}
$counter++;
// Introduce a random sleep between 100ms and 500ms.
usleep(rand(100000, 500000));
}
if (isset($logstring)) {
// We have exhausted our retries; it's time to give up.
throw new $exceptionclass($logstring);
}
$result = session_set_save_handler($this);
if (!$result) {
throw new exception('redissessionhandlerproblem', 'error');
}
}
/**
* Update our session search path to include session name when opened.
*
* @param string $path unused session save path. (ignored)
* @param string $name Session name for this session. (ignored)
* @return bool true always as we will succeed.
*/
public function open(string $path, string $name): bool {
return true;
}
/**
* Close the session completely. We also remove all locks we may have obtained that aren't expired.
*
* @return bool true on success. false on unable to unlock sessions.
*/
public function close(): bool {
$this->lasthash = null;
try {
foreach ($this->locks as $id => $expirytime) {
if ($expirytime > $this->time()) {
$this->unlock_session($id);
}
unset($this->locks[$id]);
}
} catch (RedisException | RedisClusterException $e) {
error_log('Failed talking to redis: '.$e->getMessage());
return false;
}
return true;
}
/**
* Read the session data from storage
*
* @param string $id The session id to read from storage.
* @return string The session data for PHP to process.
*
* @throws RedisException when we are unable to talk to the Redis server.
*/
public function read(string $id): string|false {
try {
if ($this->requires_write_lock()) {
$this->lock_session($id);
}
$sessiondata = $this->uncompress($this->connection->get($id));
if ($sessiondata === false) {
if ($this->requires_write_lock()) {
$this->unlock_session($id);
}
$this->lasthash = sha1('');
return '';
}
$this->connection->expire($id, $this->timeout);
} catch (RedisException | RedisClusterException $e) {
error_log('Failed talking to redis: '.$e->getMessage());
throw $e;
}
$this->lasthash = sha1(base64_encode($sessiondata));
return $sessiondata;
}
/**
* Compresses session data.
*
* @param mixed $value
* @return string
*/
private function compress($value) {
switch ($this->compressor) {
case self::COMPRESSION_NONE:
return $value;
case self::COMPRESSION_GZIP:
return gzencode($value);
case self::COMPRESSION_ZSTD:
return zstd_compress($value);
default:
debugging("Invalid compressor: {$this->compressor}");
return $value;
}
}
/**
* Uncompresses session data.
*
* @param string $value
* @return mixed
*/
private function uncompress($value) {
if ($value === false) {
return false;
}
switch ($this->compressor) {
case self::COMPRESSION_NONE:
break;
case self::COMPRESSION_GZIP:
$value = gzdecode($value);
break;
case self::COMPRESSION_ZSTD:
$value = zstd_uncompress($value);
break;
default:
debugging("Invalid compressor: {$this->compressor}");
}
return $value;
}
/**
* Write the serialized session data to our session store.
*
* @param string $id session id to write.
* @param string $data session data
* @return bool true on write success, false on failure
*/
public function write(string $id, string $data): bool {
$hash = sha1(base64_encode($data));
// If the content has not changed don't bother writing.
if ($hash === $this->lasthash) {
return true;
}
if (is_null($this->connection)) {
// The session has already been closed, don't attempt another write.
error_log('Tried to write session: '.$id.' before open or after close.');
return false;
}
// We do not do locking here because memcached doesn't. Also
// PHP does open, read, destroy, write, close. When a session doesn't exist.
// There can be race conditions on new sessions racing each other but we can
// address that in the future.
try {
$data = $this->compress($data);
$this->connection->setex($id, $this->timeout, $data);
} catch (RedisException | RedisClusterException $e) {
error_log('Failed talking to redis: '.$e->getMessage());
return false;
}
return true;
}
/**
* Handle destroying a session.
*
* @param string $id the session id to destroy.
* @return bool true if the session was deleted, false otherwise.
*/
public function destroy(string $id): bool {
$this->lasthash = null;
try {
$this->connection->del($id);
$this->unlock_session($id);
} catch (RedisException | RedisClusterException $e) {
error_log('Failed talking to redis: '.$e->getMessage());
return false;
}
return true;
}
/**
* Garbage collect sessions. We don't we any as Redis does it for us.
*
* @param integer $max_lifetime All sessions older than this should be removed.
* @return bool true, as Redis handles expiry for us.
*/
// phpcs:ignore moodle.NamingConventions.ValidVariableName.VariableNameUnderscore
public function gc(int $max_lifetime): int|false {
return false;
}
/**
* Unlock a session.
*
* @param string $id Session id to be unlocked.
*/
protected function unlock_session($id) {
if (isset($this->locks[$id])) {
$this->connection->del($id.".lock");
unset($this->locks[$id]);
}
}
/**
* Obtain a session lock so we are the only one using it at the moment.
*
* @param string $id The session id to lock.
* @return bool true when session was locked, exception otherwise.
* @throws exception When we are unable to obtain a session lock.
*/
protected function lock_session($id) {
$lockkey = $id.".lock";
$haslock = isset($this->locks[$id]) && $this->time() < $this->locks[$id];
$startlocktime = $this->time();
/* To be able to ensure sessions don't write out of order we must obtain an exclusive lock
* on the session for the entire time it is open. If another AJAX call, or page is using
* the session then we just wait until it finishes before we can open the session.
*/
// Store the current host, process id and the request URI so it's easy to track who has the lock.
$hostname = gethostname();
if ($hostname === false) {
$hostname = 'UNKNOWN HOST';
}
$pid = getmypid();
if ($pid === false) {
$pid = 'UNKNOWN';
}
$uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'unknown uri';
$whoami = "[pid {$pid}] {$hostname}:$uri";
$haswarned = false; // Have we logged a lock warning?
while (!$haslock) {
$haslock = $this->connection->set($lockkey, $whoami, ['nx', 'ex' => $this->lockexpire]);
if ($haslock) {
$this->locks[$id] = $this->time() + $this->lockexpire;
return true;
}
if (!empty($this->acquirewarn) && !$haswarned && $this->time() > $startlocktime + $this->acquirewarn) {
// This is a warning to better inform users.
$whohaslock = $this->connection->get($lockkey);
// phpcs:ignore
error_log("Warning: Cannot obtain session lock for sid: $id within $this->acquirewarn seconds but will keep trying. " .
"It is likely another page ($whohaslock) has a long session lock, or the session lock was never released.");
$haswarned = true;
}
if ($this->time() > $startlocktime + $this->acquiretimeout) {
// This is a fatal error, better inform users.
// It should not happen very often - all pages that need long time to execute
// should close session immediately after access control checks.
$whohaslock = $this->connection->get($lockkey);
// phpcs:ignore
error_log("Error: Cannot obtain session lock for sid: $id within $this->acquiretimeout seconds. " .
"It is likely another page ($whohaslock) has a long session lock, or the session lock was never released.");
$acquiretimeout = format_time($this->acquiretimeout);
$lockexpire = format_time($this->lockexpire);
$a = (object)[
'id' => substr($id, 0, 10),
'acquiretimeout' => $acquiretimeout,
'whohaslock' => $whohaslock,
'lockexpire' => $lockexpire];
throw new exception("sessioncannotobtainlock", 'error', '', $a);
}
if ($this->time() < $startlocktime + 5) {
// We want a random delay to stagger the polling load. Ideally
// this delay should be a fraction of the average response
// time. If it is too small we will poll too much and if it is
// too large we will waste time waiting for no reason. 100ms is
// the default starting point.
$delay = rand($this->lockretry, (int)($this->lockretry * 1.1));
} else {
// If we don't get a lock within 5 seconds then there must be a
// very long lived process holding the lock so throttle back to
// just polling roughly once a second.
$delay = rand(1000, 1100);
}
usleep($delay * 1000);
}
}
/**
* Return the current time.
*
* @return int the current time as a unixtimestamp.
*/
protected function time() {
return time();
}
/**
* Check the backend contains data for this session id.
*
* Note: this is intended to be called from manager::session_exists() only.
*
* @param string $sid
* @return bool true if session found.
*/
public function session_exists($sid) {
if (!$this->connection) {
return false;
}
try {
return !empty($this->connection->exists($sid));
} catch (RedisException | RedisClusterException $e) {
return false;
}
}
/**
* Kill all active sessions, the core sessions table is purged afterwards.
*/
public function kill_all_sessions() {
global $DB;
if (!$this->connection) {
return;
}
$rs = $DB->get_recordset('sessions', array(), 'id DESC', 'id, sid');
foreach ($rs as $record) {
$this->destroy($record->sid);
}
$rs->close();
}
/**
* Kill one session, the session record is removed afterwards.
*
* @param string $sid
*/
public function kill_session($sid) {
if (!$this->connection) {
return;
}
$this->destroy($sid);
}
}
@@ -0,0 +1,166 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core\session\utility;
/**
* Helper class providing utils dealing with cookies, particularly 3rd party cookies.
*
* This class primarily provides a means to augment outbound cookie headers, in order to satisfy browser-specific
* requirements for setting 3rd party cookies.
*
* @package core
* @copyright 2024 Jake Dallimore <jrhdallimore@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class cookie_helper {
/**
* Make sure the given attributes are set on the Set-Cookie response header identified by name=$cookiename.
*
* This function only affects Set-Cookie headers and modifies the headers directly with the required changes, if any.
*
* @param string $cookiename the cookie name.
* @param array $attributes the attributes to set/ensure are set.
* @return void
*/
public static function add_attributes_to_cookie_response_header(string $cookiename, array $attributes): void {
$setcookieheaders = array_filter(headers_list(), function($val) {
return preg_match("/Set-Cookie:/i", $val);
});
if (empty($setcookieheaders)) {
return;
}
$updatedheaders = self::cookie_response_headers_add_attributes($setcookieheaders, [$cookiename], $attributes);
// Note: The header_remove() method is quite crude and removes all headers of that header name.
header_remove('Set-Cookie');
foreach ($updatedheaders as $header) {
header($header, false);
}
}
/**
* Given a list of HTTP header strings, return a list of HTTP header strings where the matched 'Set-Cookie' headers
* have been updated with the attributes defined in $attribute - an array of strings.
*
* This method does not verify whether a given attribute is valid or not. It blindly sets it and returns the header
* strings. It's up to calling code to determine whether an attribute makes sense or not.
*
* @param array $headerstrings the array of header strings.
* @param array $cookiestomatch the array of cookie names to match.
* @param array $attributes the attributes to set on each matched 'Set-Cookie' header.
* @param bool $casesensitive whether to match the attribute in a case-sensitive way.
* @return array the updated array of header strings.
*/
public static function cookie_response_headers_add_attributes(array $headerstrings, array $cookiestomatch, array $attributes,
bool $casesensitive = false): array {
return array_map(function($headerstring) use ($attributes, $casesensitive, $cookiestomatch) {
if (!self::cookie_response_header_matches_names($headerstring, $cookiestomatch)) {
return $headerstring;
}
foreach ($attributes as $attribute) {
if (!self::cookie_response_header_contains_attribute($headerstring, $attribute, $casesensitive)) {
$headerstring = self::cookie_response_header_append_attribute($headerstring, $attribute);
}
}
return $headerstring;
}, $headerstrings);
}
/**
* Forces the expiry of the MoodleSession cookie.
*
* This is useful to force a new Set-Cookie header on the next redirect.
*
* @return void
*/
public static function expire_moodlesession(): void {
global $CFG;
$setcookieheader = array_filter(headers_list(), function($val) use ($CFG) {
return self::cookie_response_header_matches_name($val, 'MoodleSession'.$CFG->sessioncookie);
});
if (!empty($setcookieheader)) {
$expirestr = 'Expires='.gmdate(DATE_RFC7231, time() - 60);
self::add_attributes_to_cookie_response_header('MoodleSession'.$CFG->sessioncookie, [$expirestr]);
} else {
setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 60);
}
}
/**
* Check whether the header string is a 'Set-Cookie' header for the cookie identified by $cookiename.
*
* @param string $headerstring the header string to check.
* @param string $cookiename the name of the cookie to match.
* @return bool true if the header string is a Set-Cookie header for the named cookie, false otherwise.
*/
private static function cookie_response_header_matches_name(string $headerstring, string $cookiename): bool {
// Generally match the format, but in a case-insensitive way so that 'set-cookie' and "SET-COOKIE" are both valid.
return preg_match("/Set-Cookie: *$cookiename=/i", $headerstring)
// Case-sensitive match on cookiename, which is case-sensitive.
&& preg_match("/: *$cookiename=/", $headerstring);
}
/**
* Check whether the header string is a 'Set-Cookie' header for the cookies identified in the $cookienames array.
*
* @param string $headerstring the header string to check.
* @param array $cookienames the array of cookie names to match.
* @return bool true if the header string is a Set-Cookie header for one of the named cookies, false otherwise.
*/
private static function cookie_response_header_matches_names(string $headerstring, array $cookienames): bool {
foreach ($cookienames as $cookiename) {
if (self::cookie_response_header_matches_name($headerstring, $cookiename)) {
return true;
}
}
return false;
}
/**
* Check whether the header string contains the given attribute.
*
* @param string $headerstring the header string to check.
* @param string $attribute the attribute to check for.
* @param bool $casesensitive whether to perform a case-sensitive check.
* @return bool true if the header contains the attribute, false otherwise.
*/
private static function cookie_response_header_contains_attribute(string $headerstring, string $attribute,
bool $casesensitive): bool {
if ($casesensitive) {
return str_contains($headerstring, $attribute);
}
return str_contains(strtolower($headerstring), strtolower($attribute));
}
/**
* Append the given attribute to the header string.
*
* @param string $headerstring the header string to append to.
* @param string $attribute the attribute to append.
* @return string the updated header string.
*/
private static function cookie_response_header_append_attribute(string $headerstring, string $attribute): string {
$headerstring = rtrim($headerstring, ';'); // Sometimes included.
return "$headerstring; $attribute;";
}
}