Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

MDL-31501 rework user session architecture

List of changes:
 * New OOP API using PHP namespace \core\session\.
 * All handlers now update the sessions table consistently.
 * Experimental DB session support in Oracle.
 * Full support for session file handler (filesystem locking required).
 * New option for alternative session directory.
 * Official memcached session handler support.
 * Workaround for memcached version with non-functional gc.
 * Improved security - forced session id regeneration.
 * Improved compatibility with recent PHP releases.
 * Fixed borked CSS during install in debug mode.
 * Switched to file based sessions in new installs.
 * DB session setting disappears if DB does not support sessions.
 * DB session setting disappears if session handler specified in config.php.
 * Fast purging of sessions used in request only.
 * No legacy distinction -  file, database and memcached support the same functionality.
 * Session handler name included in performance info.
 * Fixed user_loggedin and user_loggedout event triggering.
 * Other minor bugfixing and improvements.
 * Fixed database session segfault if MUC disposed before $DB.

Limitations:
 * Session access time is now updated right after session start.
 * Support for $CFG->sessionlockloggedinonly was removed.
 * First request does not update userid in sessions table.
 * The timeouts may break badly if server hosting forces PHP.ini session settings.
 * The session GC is a lot slower, we do not rely on external session timeouts.
 * There cannot be any hooks triggered at the session write time.
 * File and memcached handlers do not support session lock acquire timeouts.
 * Some low level PHP session functions can not be used directly in Moodle code.
  • Loading branch information...
commit d79d5ac2760b7c5508aca8a7b319543ce08e1b17 1 parent 81881cb
@skodak skodak authored
Showing with 2,266 additions and 1,349 deletions.
  1. +2 −2 admin/auth.php
  2. +1 −1  admin/cli/upgrade.php
  3. +1 −1  admin/cron.php
  4. +1 −1  admin/index.php
  5. +3 −1 admin/settings/server.php
  6. +1 −1  admin/tool/assignmentupgrade/batchupgrade.php
  7. +2 −2 admin/tool/dbtransfer/locallib.php
  8. +1 −1  admin/tool/generator/cli/maketestcourse.php
  9. +1 −1  admin/tool/generator/cli/maketestsite.php
  10. +1 −1  admin/tool/uploaduser/index.php
  11. +3 −3 admin/user.php
  12. +1 −1  admin/user/user_bulk_delete.php
  13. +1 −1  auth/ldap/auth.php
  14. +5 −5 auth/mnet/auth.php
  15. +1 −1  auth/shibboleth/index.php
  16. +1 −1  badges/ajax.php
  17. +1 −1  blocks/html/lib.php
  18. +1 −1  blocks/mnet_hosts/block_mnet_hosts.php
  19. +1 −1  calendar/tests/calendartype_test.php
  20. +16 −4 config-dist.php
  21. +2 −2 course/loginas.php
  22. +1 −1  draftfile.php
  23. +1 −1  enrol/index.php
  24. +1 −1  file.php
  25. +1 −0  lang/en/error.php
  26. +1 −3 lib/authlib.php
  27. +1 −1  lib/classes/event/user_loggedin.php
  28. +1 −0  lib/classes/event/user_loggedout.php
  29. +315 −0 lib/classes/session/database.php
  30. +34 −0 lib/classes/session/exception.php
  31. +120 −0 lib/classes/session/file.php
  32. +63 −0 lib/classes/session/handler.php
  33. +754 −0 lib/classes/session/manager.php
  34. +187 −0 lib/classes/session/memcached.php
  35. +4 −3 lib/cronlib.php
  36. +2 −2 lib/datalib.php
  37. +134 −0 lib/deprecatedlib.php
  38. +31 −4 lib/dml/moodle_database.php
  39. +3 −4 lib/dml/mssql_native_moodle_database.php
  40. +3 −4 lib/dml/mysqli_native_moodle_database.php
  41. +7 −4 lib/dml/oci_native_moodle_database.php
  42. +3 −4 lib/dml/pgsql_native_moodle_database.php
  43. +3 −4 lib/dml/sqlite3_pdo_moodle_database.php
  44. +3 −4 lib/dml/sqlsrv_native_moodle_database.php
  45. +26 −26 lib/filelib.php
  46. +1 −1  lib/installlib.php
  47. +58 −36 lib/moodlelib.php
  48. +4 −4 lib/navigationlib.php
  49. +3 −3 lib/outputrenderers.php
  50. +1 −1  lib/phpunit/classes/advanced_testcase.php
  51. +1 −1  lib/phpunit/classes/util.php
  52. +1 −1  lib/phpunit/tests/advanced_test.php
  53. +2 −1,054 lib/sessionlib.php
  54. +9 −6 lib/setup.php
  55. +1 −1  lib/setuplib.php
  56. +0 −20 lib/tests/authlib_test.php
  57. +1 −1  lib/tests/behat/behat_hooks.php
  58. +24 −1 lib/tests/moodlelib_test.php
  59. +374 −0 lib/tests/session_manager_test.php
  60. +0 −88 lib/tests/sessionlib_test.php
  61. +12 −0 lib/upgrade.txt
  62. +4 −5 lib/weblib.php
  63. +1 −1  login/change_password.php
  64. +2 −3 login/token.php
  65. +1 −1  mod/assignment/type/online/assignment.class.php
  66. +1 −1  mod/chat/chat_ajax.php
  67. +1 −1  mod/chat/gui_header_js/insert.php
  68. +1 −1  mod/quiz/report/overview/report.php
  69. +1 −1  report/log/index.php
  70. +1 −1  report/loglive/index.php
  71. +1 −1  repository/lib.php
  72. +1 −1  repository/tests/repositorylib_test.php
  73. +1 −1  rss/file.php
  74. +5 −5 theme/mymobile/renderers.php
  75. +2 −2 user/editadvanced.php
  76. +1 −1  user/index.php
  77. +4 −6 webservice/lib.php
View
4 admin/auth.php
@@ -51,7 +51,7 @@
if ($auth == $CFG->registerauth) {
set_config('registerauth', '');
}
- session_gc(); // remove stale sessions
+ \core\session\manager::gc(); // Remove stale sessions.
break;
case 'enable':
@@ -61,7 +61,7 @@
$authsenabled = array_unique($authsenabled);
set_config('auth', implode(',', $authsenabled));
}
- session_gc(); // remove stale sessions
+ \core\session\manager::gc(); // Remove stale sessions.
break;
case 'down':
View
2  admin/cli/upgrade.php
@@ -172,7 +172,7 @@
upgrade_noncore(true);
// log in as admin - we need doanything permission when applying defaults
-session_set_user(get_admin());
+\core\session\manager::set_user(get_admin());
// apply all default settings, just in case do it twice to fill all defaults
admin_apply_default_settings(NULL, false);
View
2  admin/cron.php
@@ -53,7 +53,7 @@
require_once($CFG->libdir.'/cronlib.php');
// extra safety
-session_get_instance()->write_close();
+\core\session\manager::write_close();
// check if execution allowed
if (!empty($CFG->cronclionly)) {
View
2  admin/index.php
@@ -163,7 +163,7 @@
$strinstallation = get_string('installation', 'install');
// remove current session content completely
- session_get_instance()->terminate_current();
+ \core\session\manager::terminate_current();
if (empty($agreelicense)) {
$strlicense = get_string('license');
View
4 admin/settings/server.php
@@ -35,7 +35,9 @@
// "sessionhandling" settingpage
$temp = new admin_settingpage('sessionhandling', new lang_string('sessionhandling', 'admin'));
-$temp->add(new admin_setting_configcheckbox('dbsessions', new lang_string('dbsessions', 'admin'), new lang_string('configdbsessions', 'admin'), 1));
+if (empty($CFG->session_handler_class) and $DB->session_lock_supported()) {
+ $temp->add(new admin_setting_configcheckbox('dbsessions', new lang_string('dbsessions', 'admin'), new lang_string('configdbsessions', 'admin'), 0));
+}
$temp->add(new admin_setting_configselect('sessiontimeout', new lang_string('sessiontimeout', 'admin'), new lang_string('configsessiontimeout', 'admin'), 7200, array(14400 => new lang_string('numhours', '', 4),
10800 => new lang_string('numhours', '', 3),
7200 => new lang_string('numhours', '', 2),
View
2  admin/tool/assignmentupgrade/batchupgrade.php
@@ -47,7 +47,7 @@
}
raise_memory_limit(MEMORY_EXTRA);
// Release session.
-session_get_instance()->write_close();
+\core\session\manager::write_close();
echo $renderer->header();
echo $renderer->heading(get_string('batchupgrade', 'tool_assignmentupgrade'));
View
4 admin/tool/dbtransfer/locallib.php
@@ -52,7 +52,7 @@
function tool_dbtransfer_export_xml_database($description, $mdb) {
@set_time_limit(0);
- session_get_instance()->write_close(); // Release session.
+ \core\session\manager::write_close(); // Release session.
header('Content-Type: application/xhtml+xml; charset=utf-8');
header('Content-Disposition: attachment; filename=database.xml');
@@ -79,7 +79,7 @@ function tool_dbtransfer_export_xml_database($description, $mdb) {
function tool_dbtransfer_transfer_database(moodle_database $sourcedb, moodle_database $targetdb, progress_trace $feedback = null) {
@set_time_limit(0);
- session_get_instance()->write_close(); // Release session.
+ \core\session\manager::write_close(); // Release session.
$var = new database_mover($sourcedb, $targetdb, true, $feedback);
$var->export_database(null);
View
2  admin/tool/generator/cli/maketestcourse.php
@@ -90,7 +90,7 @@
}
// Switch to admin user account.
-session_set_user(get_admin());
+\core\session\manager::set_user(get_admin());
// Do backend code to generate course.
$backend = new tool_generator_course_backend($shortname, $size, $fixeddataset, empty($options['quiet']));
View
2  admin/tool/generator/cli/maketestsite.php
@@ -88,7 +88,7 @@
}
// Switch to admin user account.
-session_set_user(get_admin());
+\core\session\manager::set_user(get_admin());
// Do backend code to generate site.
$backend = new tool_generator_site_backend($size, $options['bypasscheck'], $fixeddataset, empty($options['quiet']));
View
2  admin/tool/uploaduser/index.php
@@ -687,7 +687,7 @@
}
if ($dologout) {
- session_kill_user($existinguser->id);
+ \core\session\manager::kill_user_sessions($existinguser->id);
}
} else {
View
6 admin/user.php
@@ -82,10 +82,10 @@
die;
} else if (data_submitted() and !$user->deleted) {
if (delete_user($user)) {
- session_gc(); // remove stale sessions
+ \core\session\manager::gc(); // Remove stale sessions.
redirect($returnurl);
} else {
- session_gc(); // remove stale sessions
+ \core\session\manager::gc(); // Remove stale sessions.
echo $OUTPUT->header();
echo $OUTPUT->notification($returnurl, get_string('deletednot', '', fullname($user, true)));
}
@@ -125,7 +125,7 @@
if (!is_siteadmin($user) and $USER->id != $user->id and $user->suspended != 1) {
$user->suspended = 1;
// Force logout.
- session_kill_user($user->id);
+ \core\session\manager::kill_user_sessions($user->id);
user_update_user($user, false);
}
}
View
2  admin/user/user_bulk_delete.php
@@ -34,7 +34,7 @@
}
}
$rs->close();
- session_gc(); // remove stale sessions
+ \core\session\manager::gc(); // Remove stale sessions.
echo $OUTPUT->box_start('generalbox', 'notice');
if (!empty($notifications)) {
echo $notifications;
View
2  auth/ldap/auth.php
@@ -808,7 +808,7 @@ function sync_users($do_updates=true) {
$updateuser->suspended = 1;
user_update_user($updateuser, false);
echo "\t"; print_string('auth_dbsuspenduser', 'auth_db', array('name'=>$user->username, 'id'=>$user->id)); echo "\n";
- session_kill_user($user->id);
+ \core\session\manager::kill_user_sessions($user->id);
}
} else {
print_string('nouserentriestoremove', 'auth_ldap');
View
10 auth/mnet/auth.php
@@ -141,7 +141,7 @@ function start_jump_session($mnethostid, $wantsurl, $wantsurlbackhere=false) {
global $CFG, $USER, $DB;
require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
- if (session_is_loggedinas()) {
+ if (\core\session\manager::is_loggedinas()) {
print_error('notpermittedtojumpas', 'mnet');
}
@@ -919,7 +919,7 @@ function keepalive_server($array) {
$returnString .= "We failed to refresh the session for the following usernames: \n".implode("\n", $subArray)."\n\n";
} else {
foreach($results as $emigrant) {
- session_touch($emigrant->session_id);
+ \core\session\manager::touch_session($emigrant->session_id);
}
}
}
@@ -1076,7 +1076,7 @@ function kill_children($username, $useragent) {
array('useragent'=>$useragent, 'userid'=>$userid));
if (isset($remoteclient) && isset($remoteclient->id)) {
- session_kill_user($userid);
+ \core\session\manager::kill_user_sessions($userid);
}
return $returnstring;
}
@@ -1096,7 +1096,7 @@ function kill_child($username, $useragent) {
$session = $DB->get_record('mnet_session', array('username'=>$username, 'mnethostid'=>$remoteclient->id, 'useragent'=>$useragent));
$DB->delete_records('mnet_session', array('username'=>$username, 'mnethostid'=>$remoteclient->id, 'useragent'=>$useragent));
if (false != $session) {
- session_kill($session->session_id);
+ \core\session\manager::kill_session($session->session_id);
return true;
}
return false;
@@ -1113,7 +1113,7 @@ function end_local_sessions(&$sessionArray) {
global $CFG;
if (is_array($sessionArray)) {
while($session = array_pop($sessionArray)) {
- session_kill($session->session_id);
+ \core\session\manager::kill_session($session->session_id);
}
return true;
}
View
2  auth/shibboleth/index.php
@@ -48,7 +48,7 @@
&& $user = authenticate_user_login($frm->username, $frm->password)) {
enrol_check_plugins($user);
- session_set_user($user);
+ \core\session\manager::set_user($user);
$USER->loggedin = true;
$USER->site = $CFG->wwwroot; // for added security, store the site in the
View
2  badges/ajax.php
@@ -34,7 +34,7 @@
$PAGE->set_context(context_system::instance());
// Unlock session during potentially long curl request.
-session_get_instance()->write_close();
+\core\session\manager::write_close();
$result = badges_check_backpack_accessibility();
View
2  blocks/html/lib.php
@@ -81,7 +81,7 @@ function block_html_pluginfile($course, $birecord_or_cm, $context, $filearea, $a
$forcedownload = true;
}
- session_get_instance()->write_close();
+ \core\session\manager::write_close();
send_stored_file($file, 60*60, 0, $forcedownload, $options);
}
View
2  blocks/mnet_hosts/block_mnet_hosts.php
@@ -25,7 +25,7 @@ function get_content() {
return false;
}
- if (session_is_loggedinas()) {
+ if (\core\session\manager::is_loggedinas()) {
$this->content = new stdClass();
$this->content->footer = html_writer::tag('span',
get_string('notpermittedtojumpas', 'mnet'));
View
2  calendar/tests/calendartype_test.php
@@ -277,6 +277,6 @@ private function datetime_field_submission_test($type, $date) {
*/
private function set_calendar_type($type) {
$this->user->calendartype = $type;
- session_set_user($this->user);
+ \core\session\manager::set_user($this->user);
}
}
View
20 config-dist.php
@@ -224,10 +224,22 @@
// RewriteRule (^.*/theme/yui_combo\.php)(/.*) $1?file=$2
//
//
-// By default all user sessions should be using locking, uncomment
-// the following setting to prevent locking for guests and not-logged-in
-// accounts. This may improve performance significantly.
-// $CFG->sessionlockloggedinonly = 1;
+// Following settings may be used to select session driver, uncomment only one of the handlers.
+// Database session handler (not compatible with MyISAM):
+// $CFG->session_handler_class = '\core\session\database';
+// $CFG->session_database_acquire_lock_timeout = 120;
+//
+// File session handler (file system locking required):
+// $CFG->session_handler_class = '\core\session\file';
+// $CFG->session_file_save_path = $CFG->dataroot.'/sessions';
+//
+// Memcached session handler (requires memcached server and extension):
+// $CFG->session_handler_class = '\core\session\memcached';
+// $CFG->session_memcached_save_path = '127.0.0.1:11211';
+// $CFG->session_memcached_prefix = 'memc.sess.key.';
+//
+// Following setting allows you to alter how frequently is timemodified updated in sessions table.
+// $CFG->session_update_timemodified_frequency = 20; // In seconds.
//
// If this setting is set to true, then Moodle will track the IP of the
// current user to make sure it hasn't changed during a session. This
View
4 course/loginas.php
@@ -11,7 +11,7 @@
$PAGE->set_url($url);
// Reset user back to their real self if needed, for security reasons you need to log out and log in again.
-if (session_is_loggedinas()) {
+if (\core\session\manager::is_loggedinas()) {
require_sesskey();
require_logout();
@@ -61,7 +61,7 @@
}
// Login as this user and return to course home page.
-session_loginas($userid, $context);
+\core\session\manager::loginas($userid, $context);
$newfullname = fullname($USER, true);
$strloginas = get_string('loginas');
View
2  draftfile.php
@@ -84,5 +84,5 @@
// ========================================
// finally send the file
// ========================================
-session_get_instance()->write_close(); // unlock session during fileserving
+\core\session\manager::write_close(); // Unlock session during file serving.
send_stored_file($file, 0, false, true, array('preview' => $preview)); // force download - security first!
View
2  enrol/index.php
@@ -46,7 +46,7 @@
$PAGE->set_url('/enrol/index.php', array('id'=>$course->id));
// do not allow enrols when in login-as session
-if (session_is_loggedinas() and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
+if (\core\session\manager::is_loggedinas() and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
print_error('loginasnoenrol', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
}
View
2  file.php
@@ -111,7 +111,7 @@
// ========================================
// finally send the file
// ========================================
-session_get_instance()->write_close(); // unlock session during fileserving
+\core\session\manager::write_close(); // Unlock session during file serving.
send_stored_file($file, $lifetime, $CFG->filteruploadedfiles, $forcedownload);
View
1  lang/en/error.php
@@ -466,6 +466,7 @@
$string['sessionwaiterr'] = 'Timed out while waiting for session lock.<br />Wait for your current requests to finish and try again later.';
$string['sessioncookiesdisable'] = 'Incorrect use of require_key_login() - session cookies must be disabled!';
$string['sessiondiskfull'] = 'The session partition is full. It is not possible to login at this time.<br /><br />Please notify server administrator.';
+$string['sessionhandlerproblem'] = 'Session handler is misconfigured';
$string['sessionerroruser'] = 'Your session has timed out. Please login again.';
$string['sessionerroruser2'] = 'A server error that affects your login session was detected. Please login again or restart your browser.';
$string['sessionipnomatch'] = 'Sorry, but your IP number seems to have changed from when you first logged in. This security feature prevents crackers stealing your identity while logged in to this site. Normal users should not be seeing this message - please ask the site administrator for help.';
View
4 lib/authlib.php
@@ -618,9 +618,7 @@ function login_is_lockedout($user) {
function login_attempt_valid($user) {
global $CFG;
- $event = \core\event\user_loggedin::create(array('objectid' => $user->id, 'other' => array('username' => $user->username)));
- $event->add_record_snapshot('user', $user);
- $event->trigger();
+ // Note: user_loggedin event is triggered in complete_user_login().
if ($user->mnethostid != $CFG->mnet_localhost_id) {
return;
View
2  lib/classes/event/user_loggedin.php
@@ -96,7 +96,7 @@ protected function init() {
/**
* Custom validation.
*
- * @throws coding_exception when validation does not pass.
+ * @throws \coding_exception when validation does not pass.
* @return void
*/
protected function validate_data() {
View
1  lib/classes/event/user_loggedout.php
@@ -38,6 +38,7 @@ class user_loggedout extends base {
* Initialise required event data properties.
*/
protected function init() {
+ $this->context = \context_system::instance();
$this->data['objecttable'] = 'user';
$this->data['crud'] = 'r';
$this->data['level'] = self::LEVEL_OTHER;
View
315 lib/classes/session/database.php
@@ -0,0 +1,315 @@
+<?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;
+
+defined('MOODLE_INTERNAL') || die();
+
+/**
+ * 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 {
+ /** @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(array($this, 'handler_open'),
+ array($this, 'handler_close'),
+ array($this, 'handler_read'),
+ array($this, 'handler_write'),
+ array($this, 'handler_destroy'),
+ array($this, 'handler_gc'));
+ if (!$result) {
+ throw new exception('dbsessionhandlerproblem', 'error');
+ }
+
+ register_shutdown_function(array($this, 'handler_shutdown'));
+ }
+
+ /**
+ * Check for existing session with id $sid.
+ *
+ * Note: this verifies the storage backend only, not the actual session records.
+ *
+ * @param string $sid
+ * @return bool true if session found.
+ */
+ public function session_exists($sid) {
+ try {
+ return $this->database->record_exists('sessions', array('sid'=>$sid, 'state'=>0));
+ } catch (\dml_exception $ex) {
+ return false;
+ }
+ }
+
+ /**
+ * 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 $save_path
+ * @param string $session_name
+ * @return bool success
+ */
+ public function handler_open($save_path, $session_name) {
+ // 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 handler_close() {
+ 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
+ */
+ public function handler_read($sid) {
+ 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.
+ $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 $sid
+ * @param string $session_data
+ * @return bool success
+ */
+ public function handler_write($sid, $session_data) {
+ if ($this->failed) {
+ // Do not write anything back - we failed to start the session properly.
+ return false;
+ }
+
+ $sessdata = base64_encode($session_data); // There might be some binary mess :-(
+ $hash = sha1($sessdata);
+
+ if ($hash === $this->lasthash) {
+ return true;
+ }
+
+ try {
+ if ($this->recordid) {
+ $this->database->set_field('sessions', 'sessdata', $sessdata, array('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, array('sid'=>$sid));
+ }
+ } catch (\Exception $ex) {
+ // Do not rethrow exceptions here, this should not happen.
+ error_log('Unknown exception when writing database session data : '.$sid.' - '.$ex->getMessage());
+ }
+
+ return true;
+ }
+
+ /**
+ * Destroy session handler.
+ *
+ * {@see http://php.net/manual/en/function.session-set-save-handler.php}
+ *
+ * @param string $sid
+ * @return bool success
+ */
+ public function handler_destroy($sid) {
+ if (!$session = $this->database->get_record('sessions', array('sid'=>$sid), 'id, sid')) {
+ if ($sid == session_id()) {
+ $this->recordid = null;
+ $this->lasthash = null;
+ }
+ return true;
+ }
+
+ if ($this->recordid and $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', array('id'=>$session->id));
+
+ return true;
+ }
+
+ /**
+ * GC session handler.
+ *
+ * {@see http://php.net/manual/en/function.session-set-save-handler.php}
+ *
+ * @param int $ignored_maxlifetime moodle uses special timeout rules
+ * @return bool success
+ */
+ public function handler_gc($ignored_maxlifetime) {
+ // This should do something only if cron is not running properly...
+ if (!$stalelifetime = ini_get('session.gc_maxlifetime')) {
+ return true;
+ }
+ $params = array('purgebefore' => (time() - $stalelifetime));
+ $this->database->delete_records_select('sessions', 'userid = 0 AND timemodified < :purgebefore', $params);
+ return true;
+ }
+
+ /**
+ * This makes sure the session is written to disk at the end of request.
+ */
+ public function handler_shutdown() {
+ $this->database->dispose();
+ }
+}
View
34 lib/classes/session/exception.php
@@ -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 {
+}
View
120 lib/classes/session/file.php
@@ -0,0 +1,120 @@
+<?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);
+ if (!($freespace > 2048) and $freespace !== false) {
+ 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 for existing session with id $sid.
+ *
+ * Note: this verifies the storage backend only, not the actual session records.
+ *
+ * @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);
+ }
+ }
+}
View
63 lib/classes/session/handler.php
@@ -0,0 +1,63 @@
+<?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 {
+ /**
+ * Init session handler.
+ */
+ public abstract function init();
+
+ /**
+ * Check for existing session with id $sid.
+ *
+ * Note: this verifies the storage backend only, not the actual session records.
+ *
+ * @param string $sid
+ * @return bool true if session found.
+ */
+ public abstract function session_exists($sid);
+
+ /**
+ * Kill all active sessions, the core sessions table is
+ * purged afterwards.
+ */
+ public abstract function kill_all_sessions();
+
+ /**
+ * Kill one session, the session record is removed afterwards.
+ * @param string $sid
+ */
+ public abstract function kill_session($sid);
+}
View
754 lib/classes/session/manager.php
@@ -0,0 +1,754 @@
+<?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 manager class.
+ *
+ * @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 manager, this is the public Moodle API for sessions.
+ *
+ * Following PHP functions MUST NOT be used directly:
+ * - session_start() - not necessary, lib/setup.php starts session automatically,
+ * use define('NO_MOODLE_COOKIE', true) if session not necessary.
+ * - session_write_close() - use \core\session\manager::write_close() instead.
+ * - session_destroy() - use require_logout() instead.
+ *
+ * @package core
+ * @copyright 2013 Petr Skoda {@link http://skodak.org}
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class manager {
+ /** @var handler $handler active session handler instance */
+ protected static $handler;
+
+ /** @var bool $sessionactive Is the session active? */
+ protected static $sessionactive = null;
+
+ /**
+ * Start user session.
+ *
+ * Note: This is intended to be called only from lib/setup.php!
+ */
+ public static function start() {
+ global $CFG, $DB;
+
+ if (isset(self::$sessionactive)) {
+ debugging('Session was already started!', DEBUG_DEVELOPER);
+ return;
+ }
+
+ self::load_handler();
+
+ // Init the session handler only if everything initialised properly in lib/setup.php file
+ // and the session is actually required.
+ if (empty($DB) or empty($CFG->version) or !defined('NO_MOODLE_COOKIES') or NO_MOODLE_COOKIES or CLI_SCRIPT) {
+ self::$sessionactive = false;
+ self::init_empty_session();
+ return;
+ }
+
+ try {
+ self::$handler->init();
+ self::prepare_cookies();
+ $newsid = empty($_COOKIE[session_name()]);
+
+ session_start();
+
+ self::initialise_user_session($newsid);
+ self::check_security();
+
+ } catch (\Exception $ex) {
+ @session_write_close();
+ self::init_empty_session();
+ self::$sessionactive = false;
+ throw $ex;
+ }
+
+ self::$sessionactive = true;
+ }
+
+ /**
+ * Returns current page performance info.
+ *
+ * @return array perf info
+ */
+ public static function get_performance_info() {
+ if (!session_id()) {
+ return array();
+ }
+
+ self::load_handler();
+ $size = display_size(strlen(session_encode()));
+ $handler = get_class(self::$handler);
+
+ $info = array();
+ $info['size'] = $size;
+ $info['html'] = "<span class=\"sessionsize\">Session ($handler): $size</span> ";
+ $info['txt'] = "Session ($handler): $size ";
+
+ return $info;
+ }
+
+ /**
+ * Create handler instance.
+ */
+ protected static function load_handler() {
+ global $CFG, $DB;
+
+ if (self::$handler) {
+ return;
+ }
+
+ // Find out which handler to use.
+ if (PHPUNIT_TEST) {
+ $class = '\core\session\file';
+
+ } else if (!empty($CFG->session_handler_class)) {
+ $class = $CFG->session_handler_class;
+
+ } else if (!empty($CFG->dbsessions) and $DB->session_lock_supported()) {
+ $class = '\core\session\database';
+
+ } else {
+ $class = '\core\session\file';
+ }
+ self::$handler = new $class();
+ }
+
+ /**
+ * Empty current session, fill it with not-logged-in user info.
+ */
+ protected static function init_empty_session() {
+ global $CFG;
+
+ // Session not used at all.
+ $_SESSION = array();
+ $_SESSION['SESSION'] = new \stdClass();
+ $_SESSION['USER'] = new \stdClass();
+ $_SESSION['USER']->id = 0;
+ if (isset($CFG->mnet_localhost_id)) {
+ $_SESSION['USER']->mnethostid = $CFG->mnet_localhost_id;
+ } else {
+ // Not installed yet, the future host id will be most probably 1.
+ $_SESSION['USER']->mnethostid = 1;
+ }
+
+ if (PHPUNIT_TEST) {
+ // Phpunit tests use reversed reference.
+ global $USER, $SESSION;
+ $USER = $_SESSION['USER'];
+ $SESSION = $_SESSION['SESSION'];
+ $_SESSION['USER'] =& $USER;
+ $_SESSION['SESSION'] =& $SESSION;
+ }
+ }
+
+ /**
+ * Make sure all cookie and session related stuff is configured properly before session start.
+ */
+ protected static function prepare_cookies() {
+ global $CFG;
+
+ if (!isset($CFG->cookiesecure) or (strpos($CFG->wwwroot, 'https://') !== 0 and empty($CFG->sslproxy))) {
+ $CFG->cookiesecure = 0;
+ }
+
+ if (!isset($CFG->cookiehttponly)) {
+ $CFG->cookiehttponly = 0;
+ }
+
+ // Set sessioncookie variable if it isn't already.
+ if (!isset($CFG->sessioncookie)) {
+ $CFG->sessioncookie = '';
+ }
+ $sessionname = 'MoodleSession'.$CFG->sessioncookie;
+
+ // Make sure cookie domain makes sense for this wwwroot.
+ if (!isset($CFG->sessioncookiedomain)) {
+ $CFG->sessioncookiedomain = '';
+ } else if ($CFG->sessioncookiedomain !== '') {
+ $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
+ if ($CFG->sessioncookiedomain !== $host) {
+ if (substr($CFG->sessioncookiedomain, 0, 1) === '.') {
+ if (!preg_match('|^.*'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
+ // Invalid domain - it must be end part of host.
+ $CFG->sessioncookiedomain = '';
+ }
+ } else {
+ if (!preg_match('|^.*\.'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
+ // Invalid domain - it must be end part of host.
+ $CFG->sessioncookiedomain = '';
+ }
+ }
+ }
+ }
+
+ // Make sure the cookiepath is valid for this wwwroot or autodetect if not specified.
+ if (!isset($CFG->sessioncookiepath)) {
+ $CFG->sessioncookiepath = '';
+ }
+ if ($CFG->sessioncookiepath !== '/') {
+ $path = parse_url($CFG->wwwroot, PHP_URL_PATH).'/';
+ if ($CFG->sessioncookiepath === '') {
+ $CFG->sessioncookiepath = $path;
+ } else {
+ if (strpos($path, $CFG->sessioncookiepath) !== 0 or substr($CFG->sessioncookiepath, -1) !== '/') {
+ $CFG->sessioncookiepath = $path;
+ }
+ }
+ }
+
+ // Discard session ID from POST, GET and globals to tighten security,
+ // this is session fixation prevention.
+ unset($GLOBALS[$sessionname]);
+ unset($_GET[$sessionname]);
+ unset($_POST[$sessionname]);
+ unset($_REQUEST[$sessionname]);
+
+ // Compatibility hack for non-browser access to our web interface.
+ if (!empty($_COOKIE[$sessionname]) && $_COOKIE[$sessionname] == "deleted") {
+ unset($_COOKIE[$sessionname]);
+ }
+
+ // Set configuration.
+ session_name($sessionname);
+ session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
+ ini_set('session.use_trans_sid', '0');
+ ini_set('session.use_only_cookies', '1');
+ ini_set('session.hash_function', '0'); // For now MD5 - we do not have room for sha-1 in sessions table.
+ ini_set('session.use_strict_mode', '0'); // We have custom protection in session init.
+ ini_set('session.serialize_handler', 'php'); // We can move to 'php_serialize' after we require PHP 5.5.4 form Moodle.
+
+ // Moodle does normal session timeouts, this is for leftovers only.
+ ini_set('session.gc_probability', 1);
+ ini_set('session.gc_divisor', 1000);
+ ini_set('session.gc_maxlifetime', 60*60*24*4);
+ }
+
+ /**
+ * Initialise $USER and $SESSION objects, handles google access
+ * and sets up not-logged-in user properly.
+ *
+ * @param bool $newsid is this a new session in first http request?
+ */
+ protected static function initialise_user_session($newsid) {
+ global $CFG, $DB;
+
+ $sid = session_id();
+ if (!$sid) {
+ // No session, very weird.
+ error_log('Missing session ID, session not started!');
+ self::init_empty_session();
+ return;
+ }
+
+ if (!$record = $DB->get_record('sessions', array('sid'=>$sid), 'id, sid, state, userid, lastip, timecreated, timemodified')) {
+ if (!$newsid) {
+ if (!empty($_SESSION['USER']->id)) {
+ // This should not happen, just log it, we MUST not produce any output here!
+ error_log("Cannot find session record $sid for user ".$_SESSION['USER']->id.", creating new session.");
+ }
+ }
+ session_regenerate_id(true);
+ $_SESSION = array();
+ }
+ unset($sid);
+
+ if (isset($_SESSION['USER']->id)) {
+ if (!empty($_SESSION['USER']->realuser)) {
+ $userid = $_SESSION['USER']->realuser;
+ } else {
+ $userid = $_SESSION['USER']->id;
+ }
+
+ // Verify timeout first.
+ $maxlifetime = $CFG->sessiontimeout;
+ $timeout = false;
+ if (isguestuser($userid) or empty($userid)) {
+ // Ignore guest and not-logged in timeouts, there is very little risk here.
+ $timeout = false;
+
+ } else if ($record->timemodified < time() - $maxlifetime) {
+ $timeout = true;
+ $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
+ foreach ($authsequence as $authname) {
+ $authplugin = get_auth_plugin($authname);
+ if ($authplugin->ignore_timeout_hook($_SESSION['USER'], $record->sid, $record->timecreated, $record->timemodified)) {
+ $timeout = false;
+ break;
+ }
+ }
+ }
+
+ if ($timeout) {
+ session_regenerate_id(true);
+ $_SESSION = array();
+ $DB->delete_records('sessions', array('id'=>$record->id));
+
+ } else {
+ // Update session tracking record.
+
+ $update = new \stdClass();
+ $updated = false;
+
+ if ($record->userid != $userid) {
+ $update->userid = $record->userid = $userid;
+ $updated = true;
+ }
+
+ $ip = getremoteaddr();
+ if ($record->lastip != $ip) {
+ $update->lastip = $record->lastip = $ip;
+ $updated = true;
+ }
+
+ $updatefreq = empty($CFG->session_update_timemodified_frequency) ? 20 : $CFG->session_update_timemodified_frequency;
+
+ if ($record->timemodified == $record->timecreated) {
+ // Always do first update of existing record.
+ $update->timemodified = $record->timemodified = time();
+ $updated = true;
+
+ } else if ($record->timemodified < time() - $updatefreq) {
+ // Update the session modified flag only once every 20 seconds.
+ $update->timemodified = $record->timemodified = time();
+ $updated = true;
+ }
+
+ if ($updated) {
+ $update->id = $record->id;
+ $DB->update_record('sessions', $update);
+ }
+
+ return;
+ }
+ } else {
+ if ($record) {
+ // This happens when people switch session handlers...
+ session_regenerate_id(true);
+ $_SESSION = array();
+ $DB->delete_records('sessions', array('id'=>$record->id));
+ }
+ }
+ unset($record);
+
+ $timedout = false;
+ if (!isset($_SESSION['SESSION'])) {
+ $_SESSION['SESSION'] = new \stdClass();
+ if (!$newsid) {
+ $timedout = true;
+ }
+ }
+
+ $user = null;
+
+ if (!empty($CFG->opentogoogle)) {
+ if (is_web_crawler()) {
+ $user = guest_user();
+ }
+ if (!empty($CFG->guestloginbutton) and !$user and !empty($_SERVER['HTTP_REFERER'])) {
+ // Automatically log in users coming from search engine results.
+ if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
+ $user = guest_user();
+ } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
+ $user = guest_user();
+ }
+ }
+ }
+
+ // Setup $USER and insert the session tracking record.
+ if ($user) {
+ self::set_user($user);
+ self::add_session_record($user->id);
+ } else {
+ self::init_empty_session();
+ self::add_session_record(0);
+ }
+
+ if ($timedout) {
+ $_SESSION['SESSION']->has_timed_out = true;
+ }
+ }
+
+ /**
+ * Insert new empty session record.
+ * @param int $userid
+ * @return \stdClass the new record
+ */
+ protected static function add_session_record($userid) {
+ global $DB;
+ $record = new \stdClass();
+ $record->state = 0;
+ $record->sid = session_id();
+ $record->sessdata = null;
+ $record->userid = $userid;
+ $record->timecreated = $record->timemodified = time();
+ $record->firstip = $record->lastip = getremoteaddr();
+
+ $record->id = $DB->insert_record('sessions', $record);
+
+ return $record;
+ }
+
+ /**
+ * Do various session security checks.
+ */
+ protected static function check_security() {
+ global $CFG;
+
+ if (!empty($_SESSION['USER']->id) and !empty($CFG->tracksessionip)) {
+ // Make sure current IP matches the one for this session.
+ $remoteaddr = getremoteaddr();
+
+ if (empty($_SESSION['USER']->sessionip)) {
+ $_SESSION['USER']->sessionip = $remoteaddr;
+ }
+
+ if ($_SESSION['USER']->sessionip != $remoteaddr) {
+ // This is a security feature - terminate the session in case of any doubt.
+ self::terminate_current();
+ throw new exception('sessionipnomatch2', 'error');
+ }
+ }
+ }
+
+ /**
+ * Login user, to be called from complete_user_login() only.
+ * @param \stdClass $user
+ */
+ public static function login_user(\stdClass $user) {
+ global $DB;
+
+ // Regenerate session id and delete old session,
+ // this helps prevent session fixation attacks from the same domain.
+
+ $sid = session_id();
+ session_regenerate_id(true);
+ $DB->delete_records('sessions', array('sid'=>$sid));
+ self::add_session_record($user->id);
+
+ // Let enrol plugins deal with new enrolments if necessary.
+ enrol_check_plugins($user);
+
+ // Setup $USER object.
+ self::set_user($user);
+ }
+
+ /**
+ * Terminate current user session.
+ * @return void
+ */
+ public static function terminate_current() {
+ global $DB;
+
+ if (!self::$sessionactive) {
+ self::init_empty_session();
+ self::$sessionactive = false;
+ return;
+ }
+
+ try {
+ $DB->delete_records('external_tokens', array('sid'=>session_id(), 'tokentype'=>EXTERNAL_TOKEN_EMBEDDED));
+ } catch (\Exception $ignored) {
+ // Probably install/upgrade - ignore this problem.
+ }
+
+ // Initialize variable to pass-by-reference to headers_sent(&$file, &$line).
+ $file = null;
+ $line = null;
+ if (headers_sent($file, $line)) {
+ error_log('Cannot terminate session properly - headers were already sent in file: '.$file.' on line '.$line);
+ }
+
+ // Write new empty session and make sure the old one is deleted.
+ $sid = session_id();
+ session_regenerate_id(true);
+ $DB->delete_records('sessions', array('sid'=>$sid));
+ self::init_empty_session();
+ self::add_session_record($_SESSION['USER']->id);
+ session_write_close();
+ self::$sessionactive = false;
+ }
+
+ /**
+ * No more changes in session expected.
+ * Unblocks the sessions, other scripts may start executing in parallel.
+ */
+ public static function write_close() {
+ if (self::$sessionactive) {
+ session_write_close();
+ } else {
+ if (session_id()) {
+ @session_write_close();
+ }
+ }
+ self::$sessionactive = false;
+ }
+
+ /**
+ * Does the PHP session with given id exist?
+ *
+ * Note: this does not actually verify the presence of sessions record.
+ *
+ * @param string $sid
+ * @return bool
+ */
+ public static function session_exists($sid) {
+ self::load_handler();
+ return self::$handler->session_exists($sid);
+ }
+
+ /**
+ * Fake last access for given session, this prevents session timeout.
+ * @param string $sid
+ */
+ public static function touch_session($sid) {
+ global $DB;
+
+ // Timeouts depend on core sessions table only, no need to update anything in external stores.
+
+ $sql = "UPDATE {sessions} SET timemodified = :now WHERE sid = :sid";
+ $DB->execute($sql, array('now'=>time(), 'sid'=>$sid));
+ }
+
+ /**
+ * Terminate all sessions unconditionally.
+ */
+ public static function kill_all_sessions() {
+ global $DB;
+
+ self::terminate_current();
+
+ self::load_handler();
+ self::$handler->kill_all_sessions();
+
+ try {
+ $DB->delete_records('sessions');
+ } catch (\dml_exception $ignored) {
+ // Do not show any warnings - might be during upgrade/installation.
+ }
+ }
+
+ /**
+ * Terminate give session unconditionally.
+ * @param string $sid
+ */
+ public static function kill_session($sid) {
+ global $DB;
+
+ self::load_handler();
+
+ if ($sid === session_id()) {
+ self::write_close();
+ }
+
+ self::$handler->kill_session($sid);
+
+ $DB->delete_records('sessions', array('sid'=>$sid));
+ }
+
+ /**
+ * Terminate all sessions of given user unconditionally.
+ * @param int $userid
+ */
+ public static function kill_user_sessions($userid) {
+ global $DB;
+
+ $sessions = $DB->get_records('sessions', array('userid'=>$userid), 'id DESC', 'id, sid');
+ foreach ($sessions as $session) {
+ self::kill_session($session->sid);
+ }
+ }
+
+ /**
+ * Set current user.
+ *
+ * @param \stdClass $user record
+ */
+ public static function set_user(\stdClass $user) {
+ $_SESSION['USER'] = $user;
+ unset($_SESSION['USER']->description); // Conserve memory.
+ unset($_SESSION['USER']->password); // Improve security.
+ if (isset($_SESSION['USER']->lang)) {
+ // Make sure it is a valid lang pack name.
+ $_SESSION['USER']->lang = clean_param($_SESSION['USER']->lang, PARAM_LANG);
+ }
+ sesskey(); // Init session key.
+
+ if (PHPUNIT_TEST) {
+ // Phpunit tests use reversed reference.
+ global $USER;
+ $USER = $_SESSION['USER'];
+ $_SESSION['USER'] =& $USER;
+ }
+ }
+
+ /**
+ * Periodic timed-out session cleanup.
+ */
+ public static function gc() {
+ global $CFG, $DB;
+
+ // This may take a long time...
+ set_time_limit(0);
+
+ $maxlifetime = $CFG->sessiontimeout;
+
+ try {
+ // Kill all sessions of deleted and suspended users without any hesitation.
+ $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE deleted <> 0 OR suspended <> 0)", array(), 'id DESC', 'id, sid');
+ foreach ($rs as $session) {
+ self::kill_session($session->sid);
+ }
+ $rs->close();
+
+ // Kill sessions of users with disabled plugins.
+ $auth_sequence = get_enabled_auth_plugins(true);
+ $auth_sequence = array_flip($auth_sequence);
+ unset($auth_sequence['nologin']); // No login means user cannot login.
+ $auth_sequence = array_flip($auth_sequence);
+
+ list($notplugins, $params) = $DB->get_in_or_equal($auth_sequence, SQL_PARAMS_QM, '', false);
+ $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE auth $notplugins)", $params, 'id DESC', 'id, sid');
+ foreach ($rs as $session) {
+ self::kill_session($session->sid);
+ }
+ $rs->close();
+
+ // Now get a list of time-out candidates - real users only.
+ $sql = "SELECT u.*, s.sid, s.timecreated AS s_timecreated, s.timemodified AS s_timemodified
+ FROM {user} u
+ JOIN {sessions} s ON s.userid = u.id
+ WHERE s.timemodified < :purgebefore AND u.id <> :guestid";
+ $params = array('purgebefore' => (time() - $maxlifetime), 'guestid'=>$CFG->siteguest);
+
+ $authplugins = array();
+ foreach ($auth_sequence as $authname) {
+ $authplugins[$authname] = get_auth_plugin($authname);
+ }
+ $rs = $DB->get_recordset_sql($sql, $params);
+ foreach ($rs as $user) {
+ foreach ($authplugins as $authplugin) {
+ /** @var \auth_plugin_base $authplugin*/
+ if ($authplugin->ignore_timeout_hook($user, $user->sid, $user->s_timecreated, $user->s_timemodified)) {
+ continue;
+ }
+ }
+ self::kill_session($user->sid);
+ }
+ $rs->close();
+
+ // Delete expired sessions for guest user account, give them larger timeout, there is no security risk here.
+ $params = array('purgebefore' => (time() - ($maxlifetime * 5)), 'guestid'=>$CFG->siteguest);
+ $rs = $DB->get_recordset_select('sessions', 'userid = :guestid AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
+ foreach ($rs as $session) {
+ self::kill_session($session->sid);
+ }
+ $rs->close();
+
+ // Delete expired sessions for userid = 0 (not logged in), better kill them asap to release memory.
+ $params = array('purgebefore' => (time() - $maxlifetime));
+ $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
+ foreach ($rs as $session) {
+ self::kill_session($session->sid);
+ }
+ $rs->close();
+
+ // Cleanup letfovers from the first browser access because it may set multiple cookies and then use only one.
+ $params = array('purgebefore' => (time() - 60*3));
+ $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified = timecreated AND timemodified < :purgebefore', $params, 'id ASC', 'id, sid');
+ foreach ($rs as $session) {
+ self::kill_session($session->sid);
+ }
+ $rs->close();
+
+ } catch (\Exception $ex) {
+ debugging('Error gc-ing sessions: '.$ex->getMessage(), DEBUG_NORMAL, $ex->getTrace());
+ }
+ }
+
+ /**
+ * Is current $USER logged-in-as somebody else?
+ * @return bool
+ */
+ public static function is_loggedinas() {
+ return !empty($_SESSION['USER']->realuser);
+ }
+
+ /**
+ * Returns the $USER object ignoring current login-as session
+ * @return \stdClass user object
+ */
+ public static function get_realuser() {
+ if (self::is_loggedinas()) {
+ return $_SESSION['REALUSER'];
+ } else {
+ return $_SESSION['USER'];
+ }
+ }
+
+ /**
+ * Login as another user - no security checks here.
+ * @param int $userid
+ * @param \context $context
+ * @return void
+ */
+ public static function loginas($userid, \context $context) {
+ global $USER;
+
+ if (self::is_loggedinas()) {
+ return;
+ }
+
+ // Switch to fresh new $SESSION.
+ $_SESSION['REALSESSION'] = $_SESSION['SESSION'];
+ $_SESSION['SESSION'] = new \stdClass();
+
+ // Create the new $USER object with all details and reload needed capabilities.
+ $_SESSION['REALUSER'] = $_SESSION['USER'];
+ $user = get_complete_user_data('id', $userid);
+ $user->realuser = $_SESSION['REALUSER']->id;
+ $user->loginascontext = $context;
+
+ // Let enrol plugins deal with new enrolments if necessary.
+ enrol_check_plugins($user);
+
+ // Create event before $USER is updated.
+ $event = \core\event\user_loggedinas::create(
+ array(
+ 'objectid' => $USER->id,
+ 'context' => $context,
+ 'relateduserid' => $userid,
+ 'other' => array(
+ 'originalusername' => fullname($USER, true),
+ 'loggedinasusername' => fullname($user, true)
+ )
+ )
+ );
+ // Set up global $USER.
+ \core\session\manager::set_user($user);
+ $event->trigger();
+ }
+}
View
187 lib/classes/session/memcached.php
@@ -0,0 +1,187 @@
+<?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;
+
+ /**
+ * 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_servers($this->savepath);
+ }
+
+ if (empty($CFG->session_memcached_prefix)) {
+ $this->prefix = ini_get('memcached.sess_prefix');
+ } else {
+ $this->prefix = $CFG->session_memcached_prefix;
+ }
+ }
+
+ /**
+ * 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');
+ }
+
+ // NOTE: we cannot set any lock acquiring timeout here - bad luck.
+ ini_set('session.save_handler', 'memcached');
+ ini_set('session.save_path', $this->savepath);
+ ini_set('memcached.sess_prefix', $this->prefix);
+ ini_set('memcached.sess_locking', '1'); // Locking is required!
+ }
+
+ /**
+ * Check for existing session with id $sid.
+ *
+ * Note: this verifies the storage backend only, not the actual session records.
+ *
+ * @param string $sid
+ * @return bool true if session found.
+ */
+ public function session_exists($sid) {
+ if (!$this->servers) {
+ return false;
+ }
+
+ $memcached = new \Memcached();
+ $memcached->addServers($this->servers);
+ $value = $memcached->get($this->prefix.$sid);
+ $memcached->quit();
+
+ return ($value !== false);
+ }
+
+ /**
+ * Kill all active sessions, the core sessions table is
+ * purged afterwards.
+ */
+ public function kill_all_sessions() {
+ global $DB;
+ if (!$this->servers) {
+ return;
+ }
+
+ $memcached = new \Memcached();
+ $memcached->addServers($this->servers);
+
+ // 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) {
+ $memcached->delete($this->prefix.$record->sid);
+ }
+ $rs->close();
+
+ $memcached->quit();
+ }
+
+ /**
+ * Kill one session, the session record is removed afterwards.
+ * @param string $sid
+ */
+ public function kill_session($sid) {
+ if (!$this->servers) {
+ return;
+ }
+
+ $memcached = new \Memcached();
+ $memcached->addServers($this->servers);
+ $memcached->delete($this->prefix.$sid);
+
+ $memcached->quit();
+ }
+
+ /**
+ * Convert a connection string to an array of servers
+ *
+ * EG: Converts: "abc:123, xyz:789" to
+ *
+ * array(
+ * array('abc', '123'),
+ * array('xyz', '789'),
+ * )
+ *
+ * @copyright 2013 Moodlerooms Inc. (http://www.moodlerooms.com)
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @author Mark Nielsen
+ *
+ * @param string $str save_path value containing memcached connection string
+ * @return array
+ */
+ protected static function connection_string_to_servers($str) {
+ $servers = array();
+ $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[] = array($host, $port);
+ }
+ return $servers;
+ }
+}
View
7 lib/cronlib.php
@@ -190,9 +190,10 @@ function cron_run() {
mtrace(' Created missing context instances');
- // Session gc
- session_gc();
- mtrace("Cleaned up stale user sessions");
+ // Session gc.
+ mtrace("Running session gc tasks...");
+ \core\session\manager::gc();
+ mtrace("...finished stale session cleanup");
// Run the auth cron, if any before enrolments
View
4 lib/datalib.php
@@ -1645,7 +1645,7 @@ function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user
if ($user) {
$userid = $user;
} else {
- if (session_is_loggedinas()) { // Don't log