MDL-30811 output: Add support for session notifications
[moodle.git] / lib / classes / session / manager.php
CommitLineData
d79d5ac2
PS
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.
13//
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/>.
16
17/**
18 * Session manager class.
19 *
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
23 */
24
25namespace core\session;
26
27defined('MOODLE_INTERNAL') || die();
28
29/**
30 * Session manager, this is the public Moodle API for sessions.
31 *
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.
37 *
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
41 */
42class manager {
43 /** @var handler $handler active session handler instance */
44 protected static $handler;
45
46 /** @var bool $sessionactive Is the session active? */
47 protected static $sessionactive = null;
48
49 /**
50 * Start user session.
51 *
52 * Note: This is intended to be called only from lib/setup.php!
53 */
54 public static function start() {
55 global $CFG, $DB;
56
57 if (isset(self::$sessionactive)) {
58 debugging('Session was already started!', DEBUG_DEVELOPER);
59 return;
60 }
61
62 self::load_handler();
63
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;
70 }
71
72 try {
73 self::$handler->init();
74 self::prepare_cookies();
75 $newsid = empty($_COOKIE[session_name()]);
76
6ec361c6 77 self::$handler->start();
d79d5ac2
PS
78
79 self::initialise_user_session($newsid);
80 self::check_security();
81
2e00d01d
PS
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'];
91
d79d5ac2
PS
92 } catch (\Exception $ex) {
93 @session_write_close();
94 self::init_empty_session();
95 self::$sessionactive = false;
96 throw $ex;
97 }
98
99 self::$sessionactive = true;
100 }
101
102 /**
103 * Returns current page performance info.
104 *
105 * @return array perf info
106 */
107 public static function get_performance_info() {
108 if (!session_id()) {
109 return array();
110 }
111
112 self::load_handler();
113 $size = display_size(strlen(session_encode()));
114 $handler = get_class(self::$handler);
115
116 $info = array();
117 $info['size'] = $size;
118 $info['html'] = "<span class=\"sessionsize\">Session ($handler): $size</span> ";
119 $info['txt'] = "Session ($handler): $size ";
120
121 return $info;
122 }
123
124 /**
125 * Create handler instance.
126 */
127 protected static function load_handler() {
128 global $CFG, $DB;
129
130 if (self::$handler) {
131 return;
132 }
133
134 // Find out which handler to use.
135 if (PHPUNIT_TEST) {
136 $class = '\core\session\file';
137
138 } else if (!empty($CFG->session_handler_class)) {
139 $class = $CFG->session_handler_class;
140
141 } else if (!empty($CFG->dbsessions) and $DB->session_lock_supported()) {
142 $class = '\core\session\database';
143
144 } else {
145 $class = '\core\session\file';
146 }
147 self::$handler = new $class();
148 }
149
150 /**
151 * Empty current session, fill it with not-logged-in user info.
2e00d01d
PS
152 *
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!
d79d5ac2 156 */
2e00d01d 157 public static function init_empty_session() {
d79d5ac2
PS
158 global $CFG;
159
0346323c
AN
160 // Backup notifications. These should be preserved across session changes until the user fetches and clears them.
161 $notifications = [];
162 if (isset($GLOBALS['SESSION']->notifications)) {
163 $notifications = $GLOBALS['SESSION']->notifications;
164 }
2e00d01d
PS
165 $GLOBALS['SESSION'] = new \stdClass();
166
167 $GLOBALS['USER'] = new \stdClass();
168 $GLOBALS['USER']->id = 0;
0346323c
AN
169
170 // Restore notifications.
171 $GLOBALS['SESSION']->notifications = $notifications;
d79d5ac2 172 if (isset($CFG->mnet_localhost_id)) {
2e00d01d 173 $GLOBALS['USER']->mnethostid = $CFG->mnet_localhost_id;
d79d5ac2
PS
174 } else {
175 // Not installed yet, the future host id will be most probably 1.
2e00d01d 176 $GLOBALS['USER']->mnethostid = 1;
d79d5ac2
PS
177 }
178
2e00d01d
PS
179 // Link global $USER and $SESSION.
180 $_SESSION = array();
181 $_SESSION['USER'] =& $GLOBALS['USER'];
182 $_SESSION['SESSION'] =& $GLOBALS['SESSION'];
d79d5ac2
PS
183 }
184
185 /**
186 * Make sure all cookie and session related stuff is configured properly before session start.
187 */
188 protected static function prepare_cookies() {
189 global $CFG;
190
1e31f118 191 if (!isset($CFG->cookiesecure) or (!is_https() and empty($CFG->sslproxy))) {
d79d5ac2
PS
192 $CFG->cookiesecure = 0;
193 }
194
195 if (!isset($CFG->cookiehttponly)) {
196 $CFG->cookiehttponly = 0;
197 }
198
199 // Set sessioncookie variable if it isn't already.
200 if (!isset($CFG->sessioncookie)) {
201 $CFG->sessioncookie = '';
202 }
203 $sessionname = 'MoodleSession'.$CFG->sessioncookie;
204
205 // Make sure cookie domain makes sense for this wwwroot.
206 if (!isset($CFG->sessioncookiedomain)) {
207 $CFG->sessioncookiedomain = '';
208 } else if ($CFG->sessioncookiedomain !== '') {
209 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
210 if ($CFG->sessioncookiedomain !== $host) {
211 if (substr($CFG->sessioncookiedomain, 0, 1) === '.') {
212 if (!preg_match('|^.*'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
213 // Invalid domain - it must be end part of host.
214 $CFG->sessioncookiedomain = '';
215 }
216 } else {
217 if (!preg_match('|^.*\.'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
218 // Invalid domain - it must be end part of host.
219 $CFG->sessioncookiedomain = '';
220 }
221 }
222 }
223 }
224
225 // Make sure the cookiepath is valid for this wwwroot or autodetect if not specified.
226 if (!isset($CFG->sessioncookiepath)) {
227 $CFG->sessioncookiepath = '';
228 }
229 if ($CFG->sessioncookiepath !== '/') {
230 $path = parse_url($CFG->wwwroot, PHP_URL_PATH).'/';
231 if ($CFG->sessioncookiepath === '') {
232 $CFG->sessioncookiepath = $path;
233 } else {
234 if (strpos($path, $CFG->sessioncookiepath) !== 0 or substr($CFG->sessioncookiepath, -1) !== '/') {
235 $CFG->sessioncookiepath = $path;
236 }
237 }
238 }
239
240 // Discard session ID from POST, GET and globals to tighten security,
241 // this is session fixation prevention.
242 unset($GLOBALS[$sessionname]);
243 unset($_GET[$sessionname]);
244 unset($_POST[$sessionname]);
245 unset($_REQUEST[$sessionname]);
246
247 // Compatibility hack for non-browser access to our web interface.
248 if (!empty($_COOKIE[$sessionname]) && $_COOKIE[$sessionname] == "deleted") {
249 unset($_COOKIE[$sessionname]);
250 }
251
252 // Set configuration.
253 session_name($sessionname);
254 session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
255 ini_set('session.use_trans_sid', '0');
256 ini_set('session.use_only_cookies', '1');
257 ini_set('session.hash_function', '0'); // For now MD5 - we do not have room for sha-1 in sessions table.
258 ini_set('session.use_strict_mode', '0'); // We have custom protection in session init.
259 ini_set('session.serialize_handler', 'php'); // We can move to 'php_serialize' after we require PHP 5.5.4 form Moodle.
260
261 // Moodle does normal session timeouts, this is for leftovers only.
262 ini_set('session.gc_probability', 1);
263 ini_set('session.gc_divisor', 1000);
264 ini_set('session.gc_maxlifetime', 60*60*24*4);
265 }
266
267 /**
2e00d01d 268 * Initialise $_SESSION, handles google access
d79d5ac2
PS
269 * and sets up not-logged-in user properly.
270 *
2e00d01d
PS
271 * WARNING: $USER and $SESSION are set up later, do not use them yet!
272 *
d79d5ac2
PS
273 * @param bool $newsid is this a new session in first http request?
274 */
275 protected static function initialise_user_session($newsid) {
276 global $CFG, $DB;
277
278 $sid = session_id();
279 if (!$sid) {
280 // No session, very weird.
281 error_log('Missing session ID, session not started!');
282 self::init_empty_session();
283 return;
284 }
285
286 if (!$record = $DB->get_record('sessions', array('sid'=>$sid), 'id, sid, state, userid, lastip, timecreated, timemodified')) {
287 if (!$newsid) {
288 if (!empty($_SESSION['USER']->id)) {
289 // This should not happen, just log it, we MUST not produce any output here!
290 error_log("Cannot find session record $sid for user ".$_SESSION['USER']->id.", creating new session.");
291 }
226991e9
PS
292 // Prevent session fixation attacks.
293 session_regenerate_id(true);
d79d5ac2 294 }
d79d5ac2
PS
295 $_SESSION = array();
296 }
297 unset($sid);
298
299 if (isset($_SESSION['USER']->id)) {
300 if (!empty($_SESSION['USER']->realuser)) {
301 $userid = $_SESSION['USER']->realuser;
302 } else {
303 $userid = $_SESSION['USER']->id;
304 }
305
306 // Verify timeout first.
307 $maxlifetime = $CFG->sessiontimeout;
308 $timeout = false;
309 if (isguestuser($userid) or empty($userid)) {
310 // Ignore guest and not-logged in timeouts, there is very little risk here.
311 $timeout = false;
312
313 } else if ($record->timemodified < time() - $maxlifetime) {
314 $timeout = true;
315 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
316 foreach ($authsequence as $authname) {
317 $authplugin = get_auth_plugin($authname);
318 if ($authplugin->ignore_timeout_hook($_SESSION['USER'], $record->sid, $record->timecreated, $record->timemodified)) {
319 $timeout = false;
320 break;
321 }
322 }
323 }
324
325 if ($timeout) {
326 session_regenerate_id(true);
327 $_SESSION = array();
328 $DB->delete_records('sessions', array('id'=>$record->id));
329
330 } else {
331 // Update session tracking record.
332
333 $update = new \stdClass();
334 $updated = false;
335
336 if ($record->userid != $userid) {
337 $update->userid = $record->userid = $userid;
338 $updated = true;
339 }
340
341 $ip = getremoteaddr();
342 if ($record->lastip != $ip) {
343 $update->lastip = $record->lastip = $ip;
344 $updated = true;
345 }
346
347 $updatefreq = empty($CFG->session_update_timemodified_frequency) ? 20 : $CFG->session_update_timemodified_frequency;
348
349 if ($record->timemodified == $record->timecreated) {
350 // Always do first update of existing record.
351 $update->timemodified = $record->timemodified = time();
352 $updated = true;
353
354 } else if ($record->timemodified < time() - $updatefreq) {
355 // Update the session modified flag only once every 20 seconds.
356 $update->timemodified = $record->timemodified = time();
357 $updated = true;
358 }
359
360 if ($updated) {
361 $update->id = $record->id;
362 $DB->update_record('sessions', $update);
363 }
364
365 return;
366 }
367 } else {
368 if ($record) {
369 // This happens when people switch session handlers...
370 session_regenerate_id(true);
371 $_SESSION = array();
372 $DB->delete_records('sessions', array('id'=>$record->id));
373 }
374 }
375 unset($record);
376
377 $timedout = false;
378 if (!isset($_SESSION['SESSION'])) {
379 $_SESSION['SESSION'] = new \stdClass();
380 if (!$newsid) {
381 $timedout = true;
382 }
383 }
384
385 $user = null;
386
387 if (!empty($CFG->opentogoogle)) {
34c6ec18 388 if (\core_useragent::is_web_crawler()) {
d79d5ac2
PS
389 $user = guest_user();
390 }
dcee0b94
SL
391 $referer = get_local_referer(false);
392 if (!empty($CFG->guestloginbutton) and !$user and !empty($referer)) {
d79d5ac2 393 // Automatically log in users coming from search engine results.
dcee0b94 394 if (strpos($referer, 'google') !== false ) {
d79d5ac2 395 $user = guest_user();
dcee0b94 396 } else if (strpos($referer, 'altavista') !== false ) {
d79d5ac2
PS
397 $user = guest_user();
398 }
399 }
400 }
401
402 // Setup $USER and insert the session tracking record.
403 if ($user) {
404 self::set_user($user);
405 self::add_session_record($user->id);
406 } else {
407 self::init_empty_session();
408 self::add_session_record(0);
409 }
410
411 if ($timedout) {
412 $_SESSION['SESSION']->has_timed_out = true;
413 }
414 }
415
416 /**
417 * Insert new empty session record.
418 * @param int $userid
419 * @return \stdClass the new record
420 */
421 protected static function add_session_record($userid) {
422 global $DB;
423 $record = new \stdClass();
424 $record->state = 0;
425 $record->sid = session_id();
426 $record->sessdata = null;
427 $record->userid = $userid;
428 $record->timecreated = $record->timemodified = time();
429 $record->firstip = $record->lastip = getremoteaddr();
430
431 $record->id = $DB->insert_record('sessions', $record);
432
433 return $record;
434 }
435
436 /**
437 * Do various session security checks.
2e00d01d
PS
438 *
439 * WARNING: $USER and $SESSION are set up later, do not use them yet!
d79d5ac2
PS
440 */
441 protected static function check_security() {
442 global $CFG;
443
444 if (!empty($_SESSION['USER']->id) and !empty($CFG->tracksessionip)) {
445 // Make sure current IP matches the one for this session.
446 $remoteaddr = getremoteaddr();
447
448 if (empty($_SESSION['USER']->sessionip)) {
449 $_SESSION['USER']->sessionip = $remoteaddr;
450 }
451
452 if ($_SESSION['USER']->sessionip != $remoteaddr) {
453 // This is a security feature - terminate the session in case of any doubt.
454 self::terminate_current();
455 throw new exception('sessionipnomatch2', 'error');
456 }
457 }
458 }
459
460 /**
461 * Login user, to be called from complete_user_login() only.
462 * @param \stdClass $user
463 */
464 public static function login_user(\stdClass $user) {
465 global $DB;
466
467 // Regenerate session id and delete old session,
468 // this helps prevent session fixation attacks from the same domain.
469
470 $sid = session_id();
471 session_regenerate_id(true);
472 $DB->delete_records('sessions', array('sid'=>$sid));
473 self::add_session_record($user->id);
474
475 // Let enrol plugins deal with new enrolments if necessary.
476 enrol_check_plugins($user);
477
478 // Setup $USER object.
479 self::set_user($user);
480 }
481
482 /**
483 * Terminate current user session.
484 * @return void
485 */
486 public static function terminate_current() {
487 global $DB;
488
489 if (!self::$sessionactive) {
490 self::init_empty_session();
491 self::$sessionactive = false;
492 return;
493 }
494
495 try {
496 $DB->delete_records('external_tokens', array('sid'=>session_id(), 'tokentype'=>EXTERNAL_TOKEN_EMBEDDED));
497 } catch (\Exception $ignored) {
498 // Probably install/upgrade - ignore this problem.
499 }
500
501 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line).
502 $file = null;
503 $line = null;
504 if (headers_sent($file, $line)) {
505 error_log('Cannot terminate session properly - headers were already sent in file: '.$file.' on line '.$line);
506 }
507
508 // Write new empty session and make sure the old one is deleted.
509 $sid = session_id();
510 session_regenerate_id(true);
511 $DB->delete_records('sessions', array('sid'=>$sid));
512 self::init_empty_session();
2e00d01d 513 self::add_session_record($_SESSION['USER']->id); // Do not use $USER here because it may not be set up yet.
d79d5ac2
PS
514 session_write_close();
515 self::$sessionactive = false;
516 }
517
518 /**
519 * No more changes in session expected.
520 * Unblocks the sessions, other scripts may start executing in parallel.
521 */
522 public static function write_close() {
523 if (self::$sessionactive) {
524 session_write_close();
525 } else {
526 if (session_id()) {
527 @session_write_close();
528 }
529 }
530 self::$sessionactive = false;
531 }
532
533 /**
534 * Does the PHP session with given id exist?
535 *
c6b5f18d
PS
536 * The session must exist both in session table and actual
537 * session backend and the session must not be timed out.
538 *
539 * Timeout evaluation is simplified, the auth hooks are not executed.
d79d5ac2
PS
540 *
541 * @param string $sid
542 * @return bool
543 */
544 public static function session_exists($sid) {
c6b5f18d
PS
545 global $DB, $CFG;
546
547 if (empty($CFG->version)) {
548 // Not installed yet, do not try to access database.
549 return false;
550 }
551
552 // Note: add sessions->state checking here if it gets implemented.
553 if (!$record = $DB->get_record('sessions', array('sid' => $sid), 'id, userid, timemodified')) {
554 return false;
555 }
556
557 if (empty($record->userid) or isguestuser($record->userid)) {
558 // Ignore guest and not-logged-in timeouts, there is very little risk here.
559 } else if ($record->timemodified < time() - $CFG->sessiontimeout) {
560 return false;
561 }
562
563 // There is no need the existence of handler storage in public API.
d79d5ac2
PS
564 self::load_handler();
565 return self::$handler->session_exists($sid);
566 }
567
568 /**
569 * Fake last access for given session, this prevents session timeout.
570 * @param string $sid
571 */
572 public static function touch_session($sid) {
573 global $DB;
574
575 // Timeouts depend on core sessions table only, no need to update anything in external stores.
576
577 $sql = "UPDATE {sessions} SET timemodified = :now WHERE sid = :sid";
578 $DB->execute($sql, array('now'=>time(), 'sid'=>$sid));
579 }
580
581 /**
582 * Terminate all sessions unconditionally.
583 */
584 public static function kill_all_sessions() {
585 global $DB;
586
587 self::terminate_current();
588
589 self::load_handler();
590 self::$handler->kill_all_sessions();
591
592 try {
593 $DB->delete_records('sessions');
594 } catch (\dml_exception $ignored) {
595 // Do not show any warnings - might be during upgrade/installation.
596 }
597 }
598
599 /**
600 * Terminate give session unconditionally.
601 * @param string $sid
602 */
603 public static function kill_session($sid) {
604 global $DB;
605
606 self::load_handler();
607
608 if ($sid === session_id()) {
609 self::write_close();
610 }
611
612 self::$handler->kill_session($sid);
613
614 $DB->delete_records('sessions', array('sid'=>$sid));
615 }
616
617 /**
618 * Terminate all sessions of given user unconditionally.
619 * @param int $userid
866f03de 620 * @param string $keepsid keep this sid if present
d79d5ac2 621 */
866f03de 622 public static function kill_user_sessions($userid, $keepsid = null) {
d79d5ac2
PS
623 global $DB;
624
625 $sessions = $DB->get_records('sessions', array('userid'=>$userid), 'id DESC', 'id, sid');
626 foreach ($sessions as $session) {
866f03de
PS
627 if ($keepsid and $keepsid === $session->sid) {
628 continue;
629 }
d79d5ac2
PS
630 self::kill_session($session->sid);
631 }
632 }
633
89e9321f
PS
634 /**
635 * Terminate other sessions of current user depending
636 * on $CFG->limitconcurrentlogins restriction.
637 *
638 * This is expected to be called right after complete_user_login().
639 *
640 * NOTE:
641 * * Do not use from SSO auth plugins, this would not work.
642 * * Do not use from web services because they do not have sessions.
643 *
644 * @param int $userid
645 * @param string $sid session id to be always keep, usually the current one
646 * @return void
647 */
648 public static function apply_concurrent_login_limit($userid, $sid = null) {
649 global $CFG, $DB;
650
651 // NOTE: the $sid parameter is here mainly to allow testing,
652 // in most cases it should be current session id.
653
654 if (isguestuser($userid) or empty($userid)) {
655 // This applies to real users only!
656 return;
657 }
658
659 if (empty($CFG->limitconcurrentlogins) or $CFG->limitconcurrentlogins < 0) {
660 return;
661 }
662
663 $count = $DB->count_records('sessions', array('userid' => $userid));
664
665 if ($count <= $CFG->limitconcurrentlogins) {
666 return;
667 }
668
669 $i = 0;
670 $select = "userid = :userid";
671 $params = array('userid' => $userid);
672 if ($sid) {
673 if ($DB->record_exists('sessions', array('sid' => $sid, 'userid' => $userid))) {
674 $select .= " AND sid <> :sid";
675 $params['sid'] = $sid;
676 $i = 1;
677 }
678 }
679
680 $sessions = $DB->get_records_select('sessions', $select, $params, 'timecreated DESC', 'id, sid');
681 foreach ($sessions as $session) {
682 $i++;
683 if ($i <= $CFG->limitconcurrentlogins) {
684 continue;
685 }
686 self::kill_session($session->sid);
687 }
688 }
689
d79d5ac2
PS
690 /**
691 * Set current user.
692 *
693 * @param \stdClass $user record
694 */
695 public static function set_user(\stdClass $user) {
2e00d01d
PS
696 $GLOBALS['USER'] = $user;
697 unset($GLOBALS['USER']->description); // Conserve memory.
698 unset($GLOBALS['USER']->password); // Improve security.
699 if (isset($GLOBALS['USER']->lang)) {
d79d5ac2 700 // Make sure it is a valid lang pack name.
2e00d01d 701 $GLOBALS['USER']->lang = clean_param($GLOBALS['USER']->lang, PARAM_LANG);
d79d5ac2 702 }
d79d5ac2 703
2e00d01d
PS
704 // Relink session with global $USER just in case it got unlinked somehow.
705 $_SESSION['USER'] =& $GLOBALS['USER'];
706
707 // Init session key.
708 sesskey();
d79d5ac2
PS
709 }
710
711 /**
712 * Periodic timed-out session cleanup.
713 */
714 public static function gc() {
715 global $CFG, $DB;
716
717 // This may take a long time...
3ef7279f 718 \core_php_time_limit::raise();
d79d5ac2
PS
719
720 $maxlifetime = $CFG->sessiontimeout;
721
722 try {
723 // Kill all sessions of deleted and suspended users without any hesitation.
724 $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE deleted <> 0 OR suspended <> 0)", array(), 'id DESC', 'id, sid');
725 foreach ($rs as $session) {
726 self::kill_session($session->sid);
727 }
728 $rs->close();
729
730 // Kill sessions of users with disabled plugins.
731 $auth_sequence = get_enabled_auth_plugins(true);
732 $auth_sequence = array_flip($auth_sequence);
733 unset($auth_sequence['nologin']); // No login means user cannot login.
734 $auth_sequence = array_flip($auth_sequence);
735
736 list($notplugins, $params) = $DB->get_in_or_equal($auth_sequence, SQL_PARAMS_QM, '', false);
737 $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE auth $notplugins)", $params, 'id DESC', 'id, sid');
738 foreach ($rs as $session) {
739 self::kill_session($session->sid);
740 }
741 $rs->close();
742
743 // Now get a list of time-out candidates - real users only.
744 $sql = "SELECT u.*, s.sid, s.timecreated AS s_timecreated, s.timemodified AS s_timemodified
745 FROM {user} u
746 JOIN {sessions} s ON s.userid = u.id
747 WHERE s.timemodified < :purgebefore AND u.id <> :guestid";
748 $params = array('purgebefore' => (time() - $maxlifetime), 'guestid'=>$CFG->siteguest);
749
750 $authplugins = array();
751 foreach ($auth_sequence as $authname) {
752 $authplugins[$authname] = get_auth_plugin($authname);
753 }
754 $rs = $DB->get_recordset_sql($sql, $params);
755 foreach ($rs as $user) {
756 foreach ($authplugins as $authplugin) {
757 /** @var \auth_plugin_base $authplugin*/
758 if ($authplugin->ignore_timeout_hook($user, $user->sid, $user->s_timecreated, $user->s_timemodified)) {
759 continue;
760 }
761 }
762 self::kill_session($user->sid);
763 }
764 $rs->close();
765
766 // Delete expired sessions for guest user account, give them larger timeout, there is no security risk here.
767 $params = array('purgebefore' => (time() - ($maxlifetime * 5)), 'guestid'=>$CFG->siteguest);
768 $rs = $DB->get_recordset_select('sessions', 'userid = :guestid AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
769 foreach ($rs as $session) {
770 self::kill_session($session->sid);
771 }
772 $rs->close();
773
774 // Delete expired sessions for userid = 0 (not logged in), better kill them asap to release memory.
775 $params = array('purgebefore' => (time() - $maxlifetime));
776 $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
777 foreach ($rs as $session) {
778 self::kill_session($session->sid);
779 }
780 $rs->close();
781
782 // Cleanup letfovers from the first browser access because it may set multiple cookies and then use only one.
783 $params = array('purgebefore' => (time() - 60*3));
784 $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified = timecreated AND timemodified < :purgebefore', $params, 'id ASC', 'id, sid');
785 foreach ($rs as $session) {
786 self::kill_session($session->sid);
787 }
788 $rs->close();
789
790 } catch (\Exception $ex) {
791 debugging('Error gc-ing sessions: '.$ex->getMessage(), DEBUG_NORMAL, $ex->getTrace());
792 }
793 }
794
795 /**
796 * Is current $USER logged-in-as somebody else?
797 * @return bool
798 */
799 public static function is_loggedinas() {
2e00d01d 800 return !empty($GLOBALS['USER']->realuser);
d79d5ac2
PS
801 }
802
803 /**
804 * Returns the $USER object ignoring current login-as session
805 * @return \stdClass user object
806 */
807 public static function get_realuser() {
808 if (self::is_loggedinas()) {
809 return $_SESSION['REALUSER'];
810 } else {
2e00d01d 811 return $GLOBALS['USER'];
d79d5ac2
PS
812 }
813 }
814
815 /**
816 * Login as another user - no security checks here.
817 * @param int $userid
818 * @param \context $context
819 * @return void
820 */
821 public static function loginas($userid, \context $context) {
822 global $USER;
823
824 if (self::is_loggedinas()) {
825 return;
826 }
827
2e00d01d
PS
828 // Switch to fresh new $_SESSION.
829 $_SESSION = array();
830 $_SESSION['REALSESSION'] = clone($GLOBALS['SESSION']);
831 $GLOBALS['SESSION'] = new \stdClass();
832 $_SESSION['SESSION'] =& $GLOBALS['SESSION'];
d79d5ac2
PS
833
834 // Create the new $USER object with all details and reload needed capabilities.
2e00d01d 835 $_SESSION['REALUSER'] = clone($GLOBALS['USER']);
d79d5ac2
PS
836 $user = get_complete_user_data('id', $userid);
837 $user->realuser = $_SESSION['REALUSER']->id;
838 $user->loginascontext = $context;
839
840 // Let enrol plugins deal with new enrolments if necessary.
841 enrol_check_plugins($user);
842
843 // Create event before $USER is updated.
844 $event = \core\event\user_loggedinas::create(
845 array(
846 'objectid' => $USER->id,
847 'context' => $context,
848 'relateduserid' => $userid,
849 'other' => array(
850 'originalusername' => fullname($USER, true),
851 'loggedinasusername' => fullname($user, true)
852 )
853 )
854 );
855 // Set up global $USER.
856 \core\session\manager::set_user($user);
857 $event->trigger();
858 }
57996fe9
AN
859
860 /**
861 * Add a JS session keepalive to the page.
862 *
863 * A JS session keepalive script will be called to update the session modification time every $frequency seconds.
864 *
865 * Upon failure, the specified error message will be shown to the user.
866 *
867 * @param string $identifier The string identifier for the message to show on failure.
868 * @param string $component The string component for the message to show on failure.
869 * @param int $frequency The update frequency in seconds.
870 * @throws coding_exception IF the frequency is longer than the session lifetime.
871 */
872 public static function keepalive($identifier = 'sessionerroruser', $component = 'error', $frequency = null) {
873 global $CFG, $PAGE;
874
875 if ($frequency) {
876 if ($frequency > $CFG->sessiontimeout) {
877 // Sanity check the frequency.
878 throw new \coding_exception('Keepalive frequency is longer than the session lifespan.');
879 }
880 } else {
881 // A frequency of sessiontimeout / 3 allows for one missed request whilst still preserving the session.
882 $frequency = $CFG->sessiontimeout / 3;
883 }
884
885 // Add the session keepalive script to the list of page output requirements.
886 $sessionkeepaliveurl = new \moodle_url('/lib/sessionkeepalive_ajax.php');
887 $PAGE->requires->string_for_js($identifier, $component);
888 $PAGE->requires->yui_module('moodle-core-checknet', 'M.core.checknet.init', array(array(
889 // The JS config takes this is milliseconds rather than seconds.
890 'frequency' => $frequency * 1000,
891 'message' => array($identifier, $component),
892 'uri' => $sessionkeepaliveurl->out(),
893 )));
894 }
895
d79d5ac2 896}