weekly release 2.8dev
[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
82 } catch (\Exception $ex) {
83 @session_write_close();
84 self::init_empty_session();
85 self::$sessionactive = false;
86 throw $ex;
87 }
88
89 self::$sessionactive = true;
90 }
91
92 /**
93 * Returns current page performance info.
94 *
95 * @return array perf info
96 */
97 public static function get_performance_info() {
98 if (!session_id()) {
99 return array();
100 }
101
102 self::load_handler();
103 $size = display_size(strlen(session_encode()));
104 $handler = get_class(self::$handler);
105
106 $info = array();
107 $info['size'] = $size;
108 $info['html'] = "<span class=\"sessionsize\">Session ($handler): $size</span> ";
109 $info['txt'] = "Session ($handler): $size ";
110
111 return $info;
112 }
113
114 /**
115 * Create handler instance.
116 */
117 protected static function load_handler() {
118 global $CFG, $DB;
119
120 if (self::$handler) {
121 return;
122 }
123
124 // Find out which handler to use.
125 if (PHPUNIT_TEST) {
126 $class = '\core\session\file';
127
128 } else if (!empty($CFG->session_handler_class)) {
129 $class = $CFG->session_handler_class;
130
131 } else if (!empty($CFG->dbsessions) and $DB->session_lock_supported()) {
132 $class = '\core\session\database';
133
134 } else {
135 $class = '\core\session\file';
136 }
137 self::$handler = new $class();
138 }
139
140 /**
141 * Empty current session, fill it with not-logged-in user info.
142 */
143 protected static function init_empty_session() {
144 global $CFG;
145
146 // Session not used at all.
147 $_SESSION = array();
148 $_SESSION['SESSION'] = new \stdClass();
149 $_SESSION['USER'] = new \stdClass();
150 $_SESSION['USER']->id = 0;
151 if (isset($CFG->mnet_localhost_id)) {
152 $_SESSION['USER']->mnethostid = $CFG->mnet_localhost_id;
153 } else {
154 // Not installed yet, the future host id will be most probably 1.
155 $_SESSION['USER']->mnethostid = 1;
156 }
157
de230fd3
PS
158 if (PHPUNIT_TEST or defined('BEHAT_TEST')) {
159 // Phpunit tests and behat init use reversed reference,
160 // the reason is we can not point global to $_SESSION outside of global scope.
d79d5ac2
PS
161 global $USER, $SESSION;
162 $USER = $_SESSION['USER'];
163 $SESSION = $_SESSION['SESSION'];
164 $_SESSION['USER'] =& $USER;
165 $_SESSION['SESSION'] =& $SESSION;
166 }
167 }
168
169 /**
170 * Make sure all cookie and session related stuff is configured properly before session start.
171 */
172 protected static function prepare_cookies() {
173 global $CFG;
174
175 if (!isset($CFG->cookiesecure) or (strpos($CFG->wwwroot, 'https://') !== 0 and empty($CFG->sslproxy))) {
176 $CFG->cookiesecure = 0;
177 }
178
179 if (!isset($CFG->cookiehttponly)) {
180 $CFG->cookiehttponly = 0;
181 }
182
183 // Set sessioncookie variable if it isn't already.
184 if (!isset($CFG->sessioncookie)) {
185 $CFG->sessioncookie = '';
186 }
187 $sessionname = 'MoodleSession'.$CFG->sessioncookie;
188
189 // Make sure cookie domain makes sense for this wwwroot.
190 if (!isset($CFG->sessioncookiedomain)) {
191 $CFG->sessioncookiedomain = '';
192 } else if ($CFG->sessioncookiedomain !== '') {
193 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
194 if ($CFG->sessioncookiedomain !== $host) {
195 if (substr($CFG->sessioncookiedomain, 0, 1) === '.') {
196 if (!preg_match('|^.*'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
197 // Invalid domain - it must be end part of host.
198 $CFG->sessioncookiedomain = '';
199 }
200 } else {
201 if (!preg_match('|^.*\.'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
202 // Invalid domain - it must be end part of host.
203 $CFG->sessioncookiedomain = '';
204 }
205 }
206 }
207 }
208
209 // Make sure the cookiepath is valid for this wwwroot or autodetect if not specified.
210 if (!isset($CFG->sessioncookiepath)) {
211 $CFG->sessioncookiepath = '';
212 }
213 if ($CFG->sessioncookiepath !== '/') {
214 $path = parse_url($CFG->wwwroot, PHP_URL_PATH).'/';
215 if ($CFG->sessioncookiepath === '') {
216 $CFG->sessioncookiepath = $path;
217 } else {
218 if (strpos($path, $CFG->sessioncookiepath) !== 0 or substr($CFG->sessioncookiepath, -1) !== '/') {
219 $CFG->sessioncookiepath = $path;
220 }
221 }
222 }
223
224 // Discard session ID from POST, GET and globals to tighten security,
225 // this is session fixation prevention.
226 unset($GLOBALS[$sessionname]);
227 unset($_GET[$sessionname]);
228 unset($_POST[$sessionname]);
229 unset($_REQUEST[$sessionname]);
230
231 // Compatibility hack for non-browser access to our web interface.
232 if (!empty($_COOKIE[$sessionname]) && $_COOKIE[$sessionname] == "deleted") {
233 unset($_COOKIE[$sessionname]);
234 }
235
236 // Set configuration.
237 session_name($sessionname);
238 session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
239 ini_set('session.use_trans_sid', '0');
240 ini_set('session.use_only_cookies', '1');
241 ini_set('session.hash_function', '0'); // For now MD5 - we do not have room for sha-1 in sessions table.
242 ini_set('session.use_strict_mode', '0'); // We have custom protection in session init.
243 ini_set('session.serialize_handler', 'php'); // We can move to 'php_serialize' after we require PHP 5.5.4 form Moodle.
244
245 // Moodle does normal session timeouts, this is for leftovers only.
246 ini_set('session.gc_probability', 1);
247 ini_set('session.gc_divisor', 1000);
248 ini_set('session.gc_maxlifetime', 60*60*24*4);
249 }
250
251 /**
252 * Initialise $USER and $SESSION objects, handles google access
253 * and sets up not-logged-in user properly.
254 *
255 * @param bool $newsid is this a new session in first http request?
256 */
257 protected static function initialise_user_session($newsid) {
258 global $CFG, $DB;
259
260 $sid = session_id();
261 if (!$sid) {
262 // No session, very weird.
263 error_log('Missing session ID, session not started!');
264 self::init_empty_session();
265 return;
266 }
267
268 if (!$record = $DB->get_record('sessions', array('sid'=>$sid), 'id, sid, state, userid, lastip, timecreated, timemodified')) {
269 if (!$newsid) {
270 if (!empty($_SESSION['USER']->id)) {
271 // This should not happen, just log it, we MUST not produce any output here!
272 error_log("Cannot find session record $sid for user ".$_SESSION['USER']->id.", creating new session.");
273 }
226991e9
PS
274 // Prevent session fixation attacks.
275 session_regenerate_id(true);
d79d5ac2 276 }
d79d5ac2
PS
277 $_SESSION = array();
278 }
279 unset($sid);
280
281 if (isset($_SESSION['USER']->id)) {
282 if (!empty($_SESSION['USER']->realuser)) {
283 $userid = $_SESSION['USER']->realuser;
284 } else {
285 $userid = $_SESSION['USER']->id;
286 }
287
288 // Verify timeout first.
289 $maxlifetime = $CFG->sessiontimeout;
290 $timeout = false;
291 if (isguestuser($userid) or empty($userid)) {
292 // Ignore guest and not-logged in timeouts, there is very little risk here.
293 $timeout = false;
294
295 } else if ($record->timemodified < time() - $maxlifetime) {
296 $timeout = true;
297 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
298 foreach ($authsequence as $authname) {
299 $authplugin = get_auth_plugin($authname);
300 if ($authplugin->ignore_timeout_hook($_SESSION['USER'], $record->sid, $record->timecreated, $record->timemodified)) {
301 $timeout = false;
302 break;
303 }
304 }
305 }
306
307 if ($timeout) {
308 session_regenerate_id(true);
309 $_SESSION = array();
310 $DB->delete_records('sessions', array('id'=>$record->id));
311
312 } else {
313 // Update session tracking record.
314
315 $update = new \stdClass();
316 $updated = false;
317
318 if ($record->userid != $userid) {
319 $update->userid = $record->userid = $userid;
320 $updated = true;
321 }
322
323 $ip = getremoteaddr();
324 if ($record->lastip != $ip) {
325 $update->lastip = $record->lastip = $ip;
326 $updated = true;
327 }
328
329 $updatefreq = empty($CFG->session_update_timemodified_frequency) ? 20 : $CFG->session_update_timemodified_frequency;
330
331 if ($record->timemodified == $record->timecreated) {
332 // Always do first update of existing record.
333 $update->timemodified = $record->timemodified = time();
334 $updated = true;
335
336 } else if ($record->timemodified < time() - $updatefreq) {
337 // Update the session modified flag only once every 20 seconds.
338 $update->timemodified = $record->timemodified = time();
339 $updated = true;
340 }
341
342 if ($updated) {
343 $update->id = $record->id;
344 $DB->update_record('sessions', $update);
345 }
346
347 return;
348 }
349 } else {
350 if ($record) {
351 // This happens when people switch session handlers...
352 session_regenerate_id(true);
353 $_SESSION = array();
354 $DB->delete_records('sessions', array('id'=>$record->id));
355 }
356 }
357 unset($record);
358
359 $timedout = false;
360 if (!isset($_SESSION['SESSION'])) {
361 $_SESSION['SESSION'] = new \stdClass();
362 if (!$newsid) {
363 $timedout = true;
364 }
365 }
366
367 $user = null;
368
369 if (!empty($CFG->opentogoogle)) {
370 if (is_web_crawler()) {
371 $user = guest_user();
372 }
373 if (!empty($CFG->guestloginbutton) and !$user and !empty($_SERVER['HTTP_REFERER'])) {
374 // Automatically log in users coming from search engine results.
375 if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
376 $user = guest_user();
377 } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
378 $user = guest_user();
379 }
380 }
381 }
382
383 // Setup $USER and insert the session tracking record.
384 if ($user) {
385 self::set_user($user);
386 self::add_session_record($user->id);
387 } else {
388 self::init_empty_session();
389 self::add_session_record(0);
390 }
391
392 if ($timedout) {
393 $_SESSION['SESSION']->has_timed_out = true;
394 }
395 }
396
397 /**
398 * Insert new empty session record.
399 * @param int $userid
400 * @return \stdClass the new record
401 */
402 protected static function add_session_record($userid) {
403 global $DB;
404 $record = new \stdClass();
405 $record->state = 0;
406 $record->sid = session_id();
407 $record->sessdata = null;
408 $record->userid = $userid;
409 $record->timecreated = $record->timemodified = time();
410 $record->firstip = $record->lastip = getremoteaddr();
411
412 $record->id = $DB->insert_record('sessions', $record);
413
414 return $record;
415 }
416
417 /**
418 * Do various session security checks.
419 */
420 protected static function check_security() {
421 global $CFG;
422
423 if (!empty($_SESSION['USER']->id) and !empty($CFG->tracksessionip)) {
424 // Make sure current IP matches the one for this session.
425 $remoteaddr = getremoteaddr();
426
427 if (empty($_SESSION['USER']->sessionip)) {
428 $_SESSION['USER']->sessionip = $remoteaddr;
429 }
430
431 if ($_SESSION['USER']->sessionip != $remoteaddr) {
432 // This is a security feature - terminate the session in case of any doubt.
433 self::terminate_current();
434 throw new exception('sessionipnomatch2', 'error');
435 }
436 }
437 }
438
439 /**
440 * Login user, to be called from complete_user_login() only.
441 * @param \stdClass $user
442 */
443 public static function login_user(\stdClass $user) {
444 global $DB;
445
446 // Regenerate session id and delete old session,
447 // this helps prevent session fixation attacks from the same domain.
448
449 $sid = session_id();
450 session_regenerate_id(true);
451 $DB->delete_records('sessions', array('sid'=>$sid));
452 self::add_session_record($user->id);
453
454 // Let enrol plugins deal with new enrolments if necessary.
455 enrol_check_plugins($user);
456
457 // Setup $USER object.
458 self::set_user($user);
459 }
460
461 /**
462 * Terminate current user session.
463 * @return void
464 */
465 public static function terminate_current() {
466 global $DB;
467
468 if (!self::$sessionactive) {
469 self::init_empty_session();
470 self::$sessionactive = false;
471 return;
472 }
473
474 try {
475 $DB->delete_records('external_tokens', array('sid'=>session_id(), 'tokentype'=>EXTERNAL_TOKEN_EMBEDDED));
476 } catch (\Exception $ignored) {
477 // Probably install/upgrade - ignore this problem.
478 }
479
480 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line).
481 $file = null;
482 $line = null;
483 if (headers_sent($file, $line)) {
484 error_log('Cannot terminate session properly - headers were already sent in file: '.$file.' on line '.$line);
485 }
486
487 // Write new empty session and make sure the old one is deleted.
488 $sid = session_id();
489 session_regenerate_id(true);
490 $DB->delete_records('sessions', array('sid'=>$sid));
491 self::init_empty_session();
492 self::add_session_record($_SESSION['USER']->id);
493 session_write_close();
494 self::$sessionactive = false;
495 }
496
497 /**
498 * No more changes in session expected.
499 * Unblocks the sessions, other scripts may start executing in parallel.
500 */
501 public static function write_close() {
502 if (self::$sessionactive) {
503 session_write_close();
504 } else {
505 if (session_id()) {
506 @session_write_close();
507 }
508 }
509 self::$sessionactive = false;
510 }
511
512 /**
513 * Does the PHP session with given id exist?
514 *
515 * Note: this does not actually verify the presence of sessions record.
516 *
517 * @param string $sid
518 * @return bool
519 */
520 public static function session_exists($sid) {
521 self::load_handler();
522 return self::$handler->session_exists($sid);
523 }
524
525 /**
526 * Fake last access for given session, this prevents session timeout.
527 * @param string $sid
528 */
529 public static function touch_session($sid) {
530 global $DB;
531
532 // Timeouts depend on core sessions table only, no need to update anything in external stores.
533
534 $sql = "UPDATE {sessions} SET timemodified = :now WHERE sid = :sid";
535 $DB->execute($sql, array('now'=>time(), 'sid'=>$sid));
536 }
537
538 /**
539 * Terminate all sessions unconditionally.
540 */
541 public static function kill_all_sessions() {
542 global $DB;
543
544 self::terminate_current();
545
546 self::load_handler();
547 self::$handler->kill_all_sessions();
548
549 try {
550 $DB->delete_records('sessions');
551 } catch (\dml_exception $ignored) {
552 // Do not show any warnings - might be during upgrade/installation.
553 }
554 }
555
556 /**
557 * Terminate give session unconditionally.
558 * @param string $sid
559 */
560 public static function kill_session($sid) {
561 global $DB;
562
563 self::load_handler();
564
565 if ($sid === session_id()) {
566 self::write_close();
567 }
568
569 self::$handler->kill_session($sid);
570
571 $DB->delete_records('sessions', array('sid'=>$sid));
572 }
573
574 /**
575 * Terminate all sessions of given user unconditionally.
576 * @param int $userid
577 */
578 public static function kill_user_sessions($userid) {
579 global $DB;
580
581 $sessions = $DB->get_records('sessions', array('userid'=>$userid), 'id DESC', 'id, sid');
582 foreach ($sessions as $session) {
583 self::kill_session($session->sid);
584 }
585 }
586
587 /**
588 * Set current user.
589 *
590 * @param \stdClass $user record
591 */
592 public static function set_user(\stdClass $user) {
593 $_SESSION['USER'] = $user;
594 unset($_SESSION['USER']->description); // Conserve memory.
595 unset($_SESSION['USER']->password); // Improve security.
596 if (isset($_SESSION['USER']->lang)) {
597 // Make sure it is a valid lang pack name.
598 $_SESSION['USER']->lang = clean_param($_SESSION['USER']->lang, PARAM_LANG);
599 }
600 sesskey(); // Init session key.
601
de230fd3
PS
602 if (PHPUNIT_TEST or defined('BEHAT_TEST')) {
603 // Phpunit tests and behat init use reversed reference,
604 // the reason is we can not point global to $_SESSION outside of global scope.
d79d5ac2
PS
605 global $USER;
606 $USER = $_SESSION['USER'];
607 $_SESSION['USER'] =& $USER;
608 }
609 }
610
611 /**
612 * Periodic timed-out session cleanup.
613 */
614 public static function gc() {
615 global $CFG, $DB;
616
617 // This may take a long time...
3ef7279f 618 \core_php_time_limit::raise();
d79d5ac2
PS
619
620 $maxlifetime = $CFG->sessiontimeout;
621
622 try {
623 // Kill all sessions of deleted and suspended users without any hesitation.
624 $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE deleted <> 0 OR suspended <> 0)", array(), 'id DESC', 'id, sid');
625 foreach ($rs as $session) {
626 self::kill_session($session->sid);
627 }
628 $rs->close();
629
630 // Kill sessions of users with disabled plugins.
631 $auth_sequence = get_enabled_auth_plugins(true);
632 $auth_sequence = array_flip($auth_sequence);
633 unset($auth_sequence['nologin']); // No login means user cannot login.
634 $auth_sequence = array_flip($auth_sequence);
635
636 list($notplugins, $params) = $DB->get_in_or_equal($auth_sequence, SQL_PARAMS_QM, '', false);
637 $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE auth $notplugins)", $params, 'id DESC', 'id, sid');
638 foreach ($rs as $session) {
639 self::kill_session($session->sid);
640 }
641 $rs->close();
642
643 // Now get a list of time-out candidates - real users only.
644 $sql = "SELECT u.*, s.sid, s.timecreated AS s_timecreated, s.timemodified AS s_timemodified
645 FROM {user} u
646 JOIN {sessions} s ON s.userid = u.id
647 WHERE s.timemodified < :purgebefore AND u.id <> :guestid";
648 $params = array('purgebefore' => (time() - $maxlifetime), 'guestid'=>$CFG->siteguest);
649
650 $authplugins = array();
651 foreach ($auth_sequence as $authname) {
652 $authplugins[$authname] = get_auth_plugin($authname);
653 }
654 $rs = $DB->get_recordset_sql($sql, $params);
655 foreach ($rs as $user) {
656 foreach ($authplugins as $authplugin) {
657 /** @var \auth_plugin_base $authplugin*/
658 if ($authplugin->ignore_timeout_hook($user, $user->sid, $user->s_timecreated, $user->s_timemodified)) {
659 continue;
660 }
661 }
662 self::kill_session($user->sid);
663 }
664 $rs->close();
665
666 // Delete expired sessions for guest user account, give them larger timeout, there is no security risk here.
667 $params = array('purgebefore' => (time() - ($maxlifetime * 5)), 'guestid'=>$CFG->siteguest);
668 $rs = $DB->get_recordset_select('sessions', 'userid = :guestid AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
669 foreach ($rs as $session) {
670 self::kill_session($session->sid);
671 }
672 $rs->close();
673
674 // Delete expired sessions for userid = 0 (not logged in), better kill them asap to release memory.
675 $params = array('purgebefore' => (time() - $maxlifetime));
676 $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
677 foreach ($rs as $session) {
678 self::kill_session($session->sid);
679 }
680 $rs->close();
681
682 // Cleanup letfovers from the first browser access because it may set multiple cookies and then use only one.
683 $params = array('purgebefore' => (time() - 60*3));
684 $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified = timecreated AND timemodified < :purgebefore', $params, 'id ASC', 'id, sid');
685 foreach ($rs as $session) {
686 self::kill_session($session->sid);
687 }
688 $rs->close();
689
690 } catch (\Exception $ex) {
691 debugging('Error gc-ing sessions: '.$ex->getMessage(), DEBUG_NORMAL, $ex->getTrace());
692 }
693 }
694
695 /**
696 * Is current $USER logged-in-as somebody else?
697 * @return bool
698 */
699 public static function is_loggedinas() {
700 return !empty($_SESSION['USER']->realuser);
701 }
702
703 /**
704 * Returns the $USER object ignoring current login-as session
705 * @return \stdClass user object
706 */
707 public static function get_realuser() {
708 if (self::is_loggedinas()) {
709 return $_SESSION['REALUSER'];
710 } else {
711 return $_SESSION['USER'];
712 }
713 }
714
715 /**
716 * Login as another user - no security checks here.
717 * @param int $userid
718 * @param \context $context
719 * @return void
720 */
721 public static function loginas($userid, \context $context) {
722 global $USER;
723
724 if (self::is_loggedinas()) {
725 return;
726 }
727
728 // Switch to fresh new $SESSION.
729 $_SESSION['REALSESSION'] = $_SESSION['SESSION'];
730 $_SESSION['SESSION'] = new \stdClass();
731
732 // Create the new $USER object with all details and reload needed capabilities.
733 $_SESSION['REALUSER'] = $_SESSION['USER'];
734 $user = get_complete_user_data('id', $userid);
735 $user->realuser = $_SESSION['REALUSER']->id;
736 $user->loginascontext = $context;
737
738 // Let enrol plugins deal with new enrolments if necessary.
739 enrol_check_plugins($user);
740
741 // Create event before $USER is updated.
742 $event = \core\event\user_loggedinas::create(
743 array(
744 'objectid' => $USER->id,
745 'context' => $context,
746 'relateduserid' => $userid,
747 'other' => array(
748 'originalusername' => fullname($USER, true),
749 'loggedinasusername' => fullname($user, true)
750 )
751 )
752 );
753 // Set up global $USER.
754 \core\session\manager::set_user($user);
755 $event->trigger();
756 }
757}