MDL-50891 useragent: Move web crawler checks to useragent class
[moodle.git] / lib / classes / session / manager.php
blobd565a22cfa40c5494e4c9e50de6ed47a733b8481
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Session manager class.
20 * @package core
21 * @copyright 2013 Petr Skoda {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 namespace core\session;
27 defined('MOODLE_INTERNAL') || die();
29 /**
30 * Session manager, this is the public Moodle API for sessions.
32 * Following PHP functions MUST NOT be used directly:
33 * - session_start() - not necessary, lib/setup.php starts session automatically,
34 * use define('NO_MOODLE_COOKIE', true) if session not necessary.
35 * - session_write_close() - use \core\session\manager::write_close() instead.
36 * - session_destroy() - use require_logout() instead.
38 * @package core
39 * @copyright 2013 Petr Skoda {@link http://skodak.org}
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 class manager {
43 /** @var handler $handler active session handler instance */
44 protected static $handler;
46 /** @var bool $sessionactive Is the session active? */
47 protected static $sessionactive = null;
49 /**
50 * Start user session.
52 * Note: This is intended to be called only from lib/setup.php!
54 public static function start() {
55 global $CFG, $DB;
57 if (isset(self::$sessionactive)) {
58 debugging('Session was already started!', DEBUG_DEVELOPER);
59 return;
62 self::load_handler();
64 // Init the session handler only if everything initialised properly in lib/setup.php file
65 // and the session is actually required.
66 if (empty($DB) or empty($CFG->version) or !defined('NO_MOODLE_COOKIES') or NO_MOODLE_COOKIES or CLI_SCRIPT) {
67 self::$sessionactive = false;
68 self::init_empty_session();
69 return;
72 try {
73 self::$handler->init();
74 self::prepare_cookies();
75 $newsid = empty($_COOKIE[session_name()]);
77 self::$handler->start();
79 self::initialise_user_session($newsid);
80 self::check_security();
82 // Link global $USER and $SESSION,
83 // this is tricky because PHP does not allow references to references
84 // and global keyword uses internally once reference to the $GLOBALS array.
85 // The solution is to use the $GLOBALS['USER'] and $GLOBALS['$SESSION']
86 // as the main storage of data and put references to $_SESSION.
87 $GLOBALS['USER'] = $_SESSION['USER'];
88 $_SESSION['USER'] =& $GLOBALS['USER'];
89 $GLOBALS['SESSION'] = $_SESSION['SESSION'];
90 $_SESSION['SESSION'] =& $GLOBALS['SESSION'];
92 } catch (\Exception $ex) {
93 @session_write_close();
94 self::init_empty_session();
95 self::$sessionactive = false;
96 throw $ex;
99 self::$sessionactive = true;
103 * Returns current page performance info.
105 * @return array perf info
107 public static function get_performance_info() {
108 if (!session_id()) {
109 return array();
112 self::load_handler();
113 $size = display_size(strlen(session_encode()));
114 $handler = get_class(self::$handler);
116 $info = array();
117 $info['size'] = $size;
118 $info['html'] = "<span class=\"sessionsize\">Session ($handler): $size</span> ";
119 $info['txt'] = "Session ($handler): $size ";
121 return $info;
125 * Create handler instance.
127 protected static function load_handler() {
128 global $CFG, $DB;
130 if (self::$handler) {
131 return;
134 // Find out which handler to use.
135 if (PHPUNIT_TEST) {
136 $class = '\core\session\file';
138 } else if (!empty($CFG->session_handler_class)) {
139 $class = $CFG->session_handler_class;
141 } else if (!empty($CFG->dbsessions) and $DB->session_lock_supported()) {
142 $class = '\core\session\database';
144 } else {
145 $class = '\core\session\file';
147 self::$handler = new $class();
151 * Empty current session, fill it with not-logged-in user info.
153 * This is intended for installation scripts, unit tests and other
154 * special areas. Do NOT use for logout and session termination
155 * in normal requests!
157 public static function init_empty_session() {
158 global $CFG;
160 $GLOBALS['SESSION'] = new \stdClass();
162 $GLOBALS['USER'] = new \stdClass();
163 $GLOBALS['USER']->id = 0;
164 if (isset($CFG->mnet_localhost_id)) {
165 $GLOBALS['USER']->mnethostid = $CFG->mnet_localhost_id;
166 } else {
167 // Not installed yet, the future host id will be most probably 1.
168 $GLOBALS['USER']->mnethostid = 1;
171 // Link global $USER and $SESSION.
172 $_SESSION = array();
173 $_SESSION['USER'] =& $GLOBALS['USER'];
174 $_SESSION['SESSION'] =& $GLOBALS['SESSION'];
178 * Make sure all cookie and session related stuff is configured properly before session start.
180 protected static function prepare_cookies() {
181 global $CFG;
183 if (!isset($CFG->cookiesecure) or (!is_https() and empty($CFG->sslproxy))) {
184 $CFG->cookiesecure = 0;
187 if (!isset($CFG->cookiehttponly)) {
188 $CFG->cookiehttponly = 0;
191 // Set sessioncookie variable if it isn't already.
192 if (!isset($CFG->sessioncookie)) {
193 $CFG->sessioncookie = '';
195 $sessionname = 'MoodleSession'.$CFG->sessioncookie;
197 // Make sure cookie domain makes sense for this wwwroot.
198 if (!isset($CFG->sessioncookiedomain)) {
199 $CFG->sessioncookiedomain = '';
200 } else if ($CFG->sessioncookiedomain !== '') {
201 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
202 if ($CFG->sessioncookiedomain !== $host) {
203 if (substr($CFG->sessioncookiedomain, 0, 1) === '.') {
204 if (!preg_match('|^.*'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
205 // Invalid domain - it must be end part of host.
206 $CFG->sessioncookiedomain = '';
208 } else {
209 if (!preg_match('|^.*\.'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
210 // Invalid domain - it must be end part of host.
211 $CFG->sessioncookiedomain = '';
217 // Make sure the cookiepath is valid for this wwwroot or autodetect if not specified.
218 if (!isset($CFG->sessioncookiepath)) {
219 $CFG->sessioncookiepath = '';
221 if ($CFG->sessioncookiepath !== '/') {
222 $path = parse_url($CFG->wwwroot, PHP_URL_PATH).'/';
223 if ($CFG->sessioncookiepath === '') {
224 $CFG->sessioncookiepath = $path;
225 } else {
226 if (strpos($path, $CFG->sessioncookiepath) !== 0 or substr($CFG->sessioncookiepath, -1) !== '/') {
227 $CFG->sessioncookiepath = $path;
232 // Discard session ID from POST, GET and globals to tighten security,
233 // this is session fixation prevention.
234 unset($GLOBALS[$sessionname]);
235 unset($_GET[$sessionname]);
236 unset($_POST[$sessionname]);
237 unset($_REQUEST[$sessionname]);
239 // Compatibility hack for non-browser access to our web interface.
240 if (!empty($_COOKIE[$sessionname]) && $_COOKIE[$sessionname] == "deleted") {
241 unset($_COOKIE[$sessionname]);
244 // Set configuration.
245 session_name($sessionname);
246 session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
247 ini_set('session.use_trans_sid', '0');
248 ini_set('session.use_only_cookies', '1');
249 ini_set('session.hash_function', '0'); // For now MD5 - we do not have room for sha-1 in sessions table.
250 ini_set('session.use_strict_mode', '0'); // We have custom protection in session init.
251 ini_set('session.serialize_handler', 'php'); // We can move to 'php_serialize' after we require PHP 5.5.4 form Moodle.
253 // Moodle does normal session timeouts, this is for leftovers only.
254 ini_set('session.gc_probability', 1);
255 ini_set('session.gc_divisor', 1000);
256 ini_set('session.gc_maxlifetime', 60*60*24*4);
260 * Initialise $_SESSION, handles google access
261 * and sets up not-logged-in user properly.
263 * WARNING: $USER and $SESSION are set up later, do not use them yet!
265 * @param bool $newsid is this a new session in first http request?
267 protected static function initialise_user_session($newsid) {
268 global $CFG, $DB;
270 $sid = session_id();
271 if (!$sid) {
272 // No session, very weird.
273 error_log('Missing session ID, session not started!');
274 self::init_empty_session();
275 return;
278 if (!$record = $DB->get_record('sessions', array('sid'=>$sid), 'id, sid, state, userid, lastip, timecreated, timemodified')) {
279 if (!$newsid) {
280 if (!empty($_SESSION['USER']->id)) {
281 // This should not happen, just log it, we MUST not produce any output here!
282 error_log("Cannot find session record $sid for user ".$_SESSION['USER']->id.", creating new session.");
284 // Prevent session fixation attacks.
285 session_regenerate_id(true);
287 $_SESSION = array();
289 unset($sid);
291 if (isset($_SESSION['USER']->id)) {
292 if (!empty($_SESSION['USER']->realuser)) {
293 $userid = $_SESSION['USER']->realuser;
294 } else {
295 $userid = $_SESSION['USER']->id;
298 // Verify timeout first.
299 $maxlifetime = $CFG->sessiontimeout;
300 $timeout = false;
301 if (isguestuser($userid) or empty($userid)) {
302 // Ignore guest and not-logged in timeouts, there is very little risk here.
303 $timeout = false;
305 } else if ($record->timemodified < time() - $maxlifetime) {
306 $timeout = true;
307 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
308 foreach ($authsequence as $authname) {
309 $authplugin = get_auth_plugin($authname);
310 if ($authplugin->ignore_timeout_hook($_SESSION['USER'], $record->sid, $record->timecreated, $record->timemodified)) {
311 $timeout = false;
312 break;
317 if ($timeout) {
318 session_regenerate_id(true);
319 $_SESSION = array();
320 $DB->delete_records('sessions', array('id'=>$record->id));
322 } else {
323 // Update session tracking record.
325 $update = new \stdClass();
326 $updated = false;
328 if ($record->userid != $userid) {
329 $update->userid = $record->userid = $userid;
330 $updated = true;
333 $ip = getremoteaddr();
334 if ($record->lastip != $ip) {
335 $update->lastip = $record->lastip = $ip;
336 $updated = true;
339 $updatefreq = empty($CFG->session_update_timemodified_frequency) ? 20 : $CFG->session_update_timemodified_frequency;
341 if ($record->timemodified == $record->timecreated) {
342 // Always do first update of existing record.
343 $update->timemodified = $record->timemodified = time();
344 $updated = true;
346 } else if ($record->timemodified < time() - $updatefreq) {
347 // Update the session modified flag only once every 20 seconds.
348 $update->timemodified = $record->timemodified = time();
349 $updated = true;
352 if ($updated) {
353 $update->id = $record->id;
354 $DB->update_record('sessions', $update);
357 return;
359 } else {
360 if ($record) {
361 // This happens when people switch session handlers...
362 session_regenerate_id(true);
363 $_SESSION = array();
364 $DB->delete_records('sessions', array('id'=>$record->id));
367 unset($record);
369 $timedout = false;
370 if (!isset($_SESSION['SESSION'])) {
371 $_SESSION['SESSION'] = new \stdClass();
372 if (!$newsid) {
373 $timedout = true;
377 $user = null;
379 if (!empty($CFG->opentogoogle)) {
380 if (\core_useragent::is_web_crawler()) {
381 $user = guest_user();
383 $referer = get_local_referer(false);
384 if (!empty($CFG->guestloginbutton) and !$user and !empty($referer)) {
385 // Automatically log in users coming from search engine results.
386 if (strpos($referer, 'google') !== false ) {
387 $user = guest_user();
388 } else if (strpos($referer, 'altavista') !== false ) {
389 $user = guest_user();
394 // Setup $USER and insert the session tracking record.
395 if ($user) {
396 self::set_user($user);
397 self::add_session_record($user->id);
398 } else {
399 self::init_empty_session();
400 self::add_session_record(0);
403 if ($timedout) {
404 $_SESSION['SESSION']->has_timed_out = true;
409 * Insert new empty session record.
410 * @param int $userid
411 * @return \stdClass the new record
413 protected static function add_session_record($userid) {
414 global $DB;
415 $record = new \stdClass();
416 $record->state = 0;
417 $record->sid = session_id();
418 $record->sessdata = null;
419 $record->userid = $userid;
420 $record->timecreated = $record->timemodified = time();
421 $record->firstip = $record->lastip = getremoteaddr();
423 $record->id = $DB->insert_record('sessions', $record);
425 return $record;
429 * Do various session security checks.
431 * WARNING: $USER and $SESSION are set up later, do not use them yet!
433 protected static function check_security() {
434 global $CFG;
436 if (!empty($_SESSION['USER']->id) and !empty($CFG->tracksessionip)) {
437 // Make sure current IP matches the one for this session.
438 $remoteaddr = getremoteaddr();
440 if (empty($_SESSION['USER']->sessionip)) {
441 $_SESSION['USER']->sessionip = $remoteaddr;
444 if ($_SESSION['USER']->sessionip != $remoteaddr) {
445 // This is a security feature - terminate the session in case of any doubt.
446 self::terminate_current();
447 throw new exception('sessionipnomatch2', 'error');
453 * Login user, to be called from complete_user_login() only.
454 * @param \stdClass $user
456 public static function login_user(\stdClass $user) {
457 global $DB;
459 // Regenerate session id and delete old session,
460 // this helps prevent session fixation attacks from the same domain.
462 $sid = session_id();
463 session_regenerate_id(true);
464 $DB->delete_records('sessions', array('sid'=>$sid));
465 self::add_session_record($user->id);
467 // Let enrol plugins deal with new enrolments if necessary.
468 enrol_check_plugins($user);
470 // Setup $USER object.
471 self::set_user($user);
475 * Terminate current user session.
476 * @return void
478 public static function terminate_current() {
479 global $DB;
481 if (!self::$sessionactive) {
482 self::init_empty_session();
483 self::$sessionactive = false;
484 return;
487 try {
488 $DB->delete_records('external_tokens', array('sid'=>session_id(), 'tokentype'=>EXTERNAL_TOKEN_EMBEDDED));
489 } catch (\Exception $ignored) {
490 // Probably install/upgrade - ignore this problem.
493 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line).
494 $file = null;
495 $line = null;
496 if (headers_sent($file, $line)) {
497 error_log('Cannot terminate session properly - headers were already sent in file: '.$file.' on line '.$line);
500 // Write new empty session and make sure the old one is deleted.
501 $sid = session_id();
502 session_regenerate_id(true);
503 $DB->delete_records('sessions', array('sid'=>$sid));
504 self::init_empty_session();
505 self::add_session_record($_SESSION['USER']->id); // Do not use $USER here because it may not be set up yet.
506 session_write_close();
507 self::$sessionactive = false;
511 * No more changes in session expected.
512 * Unblocks the sessions, other scripts may start executing in parallel.
514 public static function write_close() {
515 if (self::$sessionactive) {
516 session_write_close();
517 } else {
518 if (session_id()) {
519 @session_write_close();
522 self::$sessionactive = false;
526 * Does the PHP session with given id exist?
528 * The session must exist both in session table and actual
529 * session backend and the session must not be timed out.
531 * Timeout evaluation is simplified, the auth hooks are not executed.
533 * @param string $sid
534 * @return bool
536 public static function session_exists($sid) {
537 global $DB, $CFG;
539 if (empty($CFG->version)) {
540 // Not installed yet, do not try to access database.
541 return false;
544 // Note: add sessions->state checking here if it gets implemented.
545 if (!$record = $DB->get_record('sessions', array('sid' => $sid), 'id, userid, timemodified')) {
546 return false;
549 if (empty($record->userid) or isguestuser($record->userid)) {
550 // Ignore guest and not-logged-in timeouts, there is very little risk here.
551 } else if ($record->timemodified < time() - $CFG->sessiontimeout) {
552 return false;
555 // There is no need the existence of handler storage in public API.
556 self::load_handler();
557 return self::$handler->session_exists($sid);
561 * Fake last access for given session, this prevents session timeout.
562 * @param string $sid
564 public static function touch_session($sid) {
565 global $DB;
567 // Timeouts depend on core sessions table only, no need to update anything in external stores.
569 $sql = "UPDATE {sessions} SET timemodified = :now WHERE sid = :sid";
570 $DB->execute($sql, array('now'=>time(), 'sid'=>$sid));
574 * Terminate all sessions unconditionally.
576 public static function kill_all_sessions() {
577 global $DB;
579 self::terminate_current();
581 self::load_handler();
582 self::$handler->kill_all_sessions();
584 try {
585 $DB->delete_records('sessions');
586 } catch (\dml_exception $ignored) {
587 // Do not show any warnings - might be during upgrade/installation.
592 * Terminate give session unconditionally.
593 * @param string $sid
595 public static function kill_session($sid) {
596 global $DB;
598 self::load_handler();
600 if ($sid === session_id()) {
601 self::write_close();
604 self::$handler->kill_session($sid);
606 $DB->delete_records('sessions', array('sid'=>$sid));
610 * Terminate all sessions of given user unconditionally.
611 * @param int $userid
612 * @param string $keepsid keep this sid if present
614 public static function kill_user_sessions($userid, $keepsid = null) {
615 global $DB;
617 $sessions = $DB->get_records('sessions', array('userid'=>$userid), 'id DESC', 'id, sid');
618 foreach ($sessions as $session) {
619 if ($keepsid and $keepsid === $session->sid) {
620 continue;
622 self::kill_session($session->sid);
627 * Terminate other sessions of current user depending
628 * on $CFG->limitconcurrentlogins restriction.
630 * This is expected to be called right after complete_user_login().
632 * NOTE:
633 * * Do not use from SSO auth plugins, this would not work.
634 * * Do not use from web services because they do not have sessions.
636 * @param int $userid
637 * @param string $sid session id to be always keep, usually the current one
638 * @return void
640 public static function apply_concurrent_login_limit($userid, $sid = null) {
641 global $CFG, $DB;
643 // NOTE: the $sid parameter is here mainly to allow testing,
644 // in most cases it should be current session id.
646 if (isguestuser($userid) or empty($userid)) {
647 // This applies to real users only!
648 return;
651 if (empty($CFG->limitconcurrentlogins) or $CFG->limitconcurrentlogins < 0) {
652 return;
655 $count = $DB->count_records('sessions', array('userid' => $userid));
657 if ($count <= $CFG->limitconcurrentlogins) {
658 return;
661 $i = 0;
662 $select = "userid = :userid";
663 $params = array('userid' => $userid);
664 if ($sid) {
665 if ($DB->record_exists('sessions', array('sid' => $sid, 'userid' => $userid))) {
666 $select .= " AND sid <> :sid";
667 $params['sid'] = $sid;
668 $i = 1;
672 $sessions = $DB->get_records_select('sessions', $select, $params, 'timecreated DESC', 'id, sid');
673 foreach ($sessions as $session) {
674 $i++;
675 if ($i <= $CFG->limitconcurrentlogins) {
676 continue;
678 self::kill_session($session->sid);
683 * Set current user.
685 * @param \stdClass $user record
687 public static function set_user(\stdClass $user) {
688 $GLOBALS['USER'] = $user;
689 unset($GLOBALS['USER']->description); // Conserve memory.
690 unset($GLOBALS['USER']->password); // Improve security.
691 if (isset($GLOBALS['USER']->lang)) {
692 // Make sure it is a valid lang pack name.
693 $GLOBALS['USER']->lang = clean_param($GLOBALS['USER']->lang, PARAM_LANG);
696 // Relink session with global $USER just in case it got unlinked somehow.
697 $_SESSION['USER'] =& $GLOBALS['USER'];
699 // Init session key.
700 sesskey();
704 * Periodic timed-out session cleanup.
706 public static function gc() {
707 global $CFG, $DB;
709 // This may take a long time...
710 \core_php_time_limit::raise();
712 $maxlifetime = $CFG->sessiontimeout;
714 try {
715 // Kill all sessions of deleted and suspended users without any hesitation.
716 $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE deleted <> 0 OR suspended <> 0)", array(), 'id DESC', 'id, sid');
717 foreach ($rs as $session) {
718 self::kill_session($session->sid);
720 $rs->close();
722 // Kill sessions of users with disabled plugins.
723 $auth_sequence = get_enabled_auth_plugins(true);
724 $auth_sequence = array_flip($auth_sequence);
725 unset($auth_sequence['nologin']); // No login means user cannot login.
726 $auth_sequence = array_flip($auth_sequence);
728 list($notplugins, $params) = $DB->get_in_or_equal($auth_sequence, SQL_PARAMS_QM, '', false);
729 $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE auth $notplugins)", $params, 'id DESC', 'id, sid');
730 foreach ($rs as $session) {
731 self::kill_session($session->sid);
733 $rs->close();
735 // Now get a list of time-out candidates - real users only.
736 $sql = "SELECT u.*, s.sid, s.timecreated AS s_timecreated, s.timemodified AS s_timemodified
737 FROM {user} u
738 JOIN {sessions} s ON s.userid = u.id
739 WHERE s.timemodified < :purgebefore AND u.id <> :guestid";
740 $params = array('purgebefore' => (time() - $maxlifetime), 'guestid'=>$CFG->siteguest);
742 $authplugins = array();
743 foreach ($auth_sequence as $authname) {
744 $authplugins[$authname] = get_auth_plugin($authname);
746 $rs = $DB->get_recordset_sql($sql, $params);
747 foreach ($rs as $user) {
748 foreach ($authplugins as $authplugin) {
749 /** @var \auth_plugin_base $authplugin*/
750 if ($authplugin->ignore_timeout_hook($user, $user->sid, $user->s_timecreated, $user->s_timemodified)) {
751 continue;
754 self::kill_session($user->sid);
756 $rs->close();
758 // Delete expired sessions for guest user account, give them larger timeout, there is no security risk here.
759 $params = array('purgebefore' => (time() - ($maxlifetime * 5)), 'guestid'=>$CFG->siteguest);
760 $rs = $DB->get_recordset_select('sessions', 'userid = :guestid AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
761 foreach ($rs as $session) {
762 self::kill_session($session->sid);
764 $rs->close();
766 // Delete expired sessions for userid = 0 (not logged in), better kill them asap to release memory.
767 $params = array('purgebefore' => (time() - $maxlifetime));
768 $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
769 foreach ($rs as $session) {
770 self::kill_session($session->sid);
772 $rs->close();
774 // Cleanup letfovers from the first browser access because it may set multiple cookies and then use only one.
775 $params = array('purgebefore' => (time() - 60*3));
776 $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified = timecreated AND timemodified < :purgebefore', $params, 'id ASC', 'id, sid');
777 foreach ($rs as $session) {
778 self::kill_session($session->sid);
780 $rs->close();
782 } catch (\Exception $ex) {
783 debugging('Error gc-ing sessions: '.$ex->getMessage(), DEBUG_NORMAL, $ex->getTrace());
788 * Is current $USER logged-in-as somebody else?
789 * @return bool
791 public static function is_loggedinas() {
792 return !empty($GLOBALS['USER']->realuser);
796 * Returns the $USER object ignoring current login-as session
797 * @return \stdClass user object
799 public static function get_realuser() {
800 if (self::is_loggedinas()) {
801 return $_SESSION['REALUSER'];
802 } else {
803 return $GLOBALS['USER'];
808 * Login as another user - no security checks here.
809 * @param int $userid
810 * @param \context $context
811 * @return void
813 public static function loginas($userid, \context $context) {
814 global $USER;
816 if (self::is_loggedinas()) {
817 return;
820 // Switch to fresh new $_SESSION.
821 $_SESSION = array();
822 $_SESSION['REALSESSION'] = clone($GLOBALS['SESSION']);
823 $GLOBALS['SESSION'] = new \stdClass();
824 $_SESSION['SESSION'] =& $GLOBALS['SESSION'];
826 // Create the new $USER object with all details and reload needed capabilities.
827 $_SESSION['REALUSER'] = clone($GLOBALS['USER']);
828 $user = get_complete_user_data('id', $userid);
829 $user->realuser = $_SESSION['REALUSER']->id;
830 $user->loginascontext = $context;
832 // Let enrol plugins deal with new enrolments if necessary.
833 enrol_check_plugins($user);
835 // Create event before $USER is updated.
836 $event = \core\event\user_loggedinas::create(
837 array(
838 'objectid' => $USER->id,
839 'context' => $context,
840 'relateduserid' => $userid,
841 'other' => array(
842 'originalusername' => fullname($USER, true),
843 'loggedinasusername' => fullname($user, true)
847 // Set up global $USER.
848 \core\session\manager::set_user($user);
849 $event->trigger();
853 * Add a JS session keepalive to the page.
855 * A JS session keepalive script will be called to update the session modification time every $frequency seconds.
857 * Upon failure, the specified error message will be shown to the user.
859 * @param string $identifier The string identifier for the message to show on failure.
860 * @param string $component The string component for the message to show on failure.
861 * @param int $frequency The update frequency in seconds.
862 * @throws coding_exception IF the frequency is longer than the session lifetime.
864 public static function keepalive($identifier = 'sessionerroruser', $component = 'error', $frequency = null) {
865 global $CFG, $PAGE;
867 if ($frequency) {
868 if ($frequency > $CFG->sessiontimeout) {
869 // Sanity check the frequency.
870 throw new \coding_exception('Keepalive frequency is longer than the session lifespan.');
872 } else {
873 // A frequency of sessiontimeout / 3 allows for one missed request whilst still preserving the session.
874 $frequency = $CFG->sessiontimeout / 3;
877 // Add the session keepalive script to the list of page output requirements.
878 $sessionkeepaliveurl = new \moodle_url('/lib/sessionkeepalive_ajax.php');
879 $PAGE->requires->string_for_js($identifier, $component);
880 $PAGE->requires->yui_module('moodle-core-checknet', 'M.core.checknet.init', array(array(
881 // The JS config takes this is milliseconds rather than seconds.
882 'frequency' => $frequency * 1000,
883 'message' => array($identifier, $component),
884 'uri' => $sessionkeepaliveurl->out(),
885 )));