Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
 
25
namespace core\session;
26
 
27
defined('MOODLE_INTERNAL') || die();
28
 
29
use html_writer;
30
 
31
/**
32
 * Session manager, this is the public Moodle API for sessions.
33
 *
34
 * Following PHP functions MUST NOT be used directly:
35
 * - session_start() - not necessary, lib/setup.php starts session automatically,
36
 *   use define('NO_MOODLE_COOKIE', true) if session not necessary.
37
 * - session_write_close() - use \core\session\manager::write_close() instead.
38
 * - session_destroy() - use require_logout() instead.
39
 *
40
 * @package    core
41
 * @copyright  2013 Petr Skoda {@link http://skodak.org}
42
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43
 */
44
class manager {
45
    /** @var int A hard cutoff of maximum stored history */
46
    const MAXIMUM_STORED_SESSION_HISTORY = 50;
47
 
48
    /** @var int The recent session locks array is reset if there is a time gap more than this value in seconds */
49
    const SESSION_RESET_GAP_THRESHOLD = 1;
50
 
51
    /** @var handler $handler active session handler instance */
52
    protected static $handler;
53
 
54
    /** @var bool $sessionactive Is the session active? */
55
    protected static $sessionactive = null;
56
 
57
    /** @var string $logintokenkey Key used to get and store request protection for login form. */
58
    protected static $logintokenkey = 'core_auth_login';
59
 
60
    /** @var array Stores the the SESSION before a request is performed, used to check incorrect read-only modes */
61
    private static $priorsession = [];
62
 
63
    /** @var array Stores the the SESSION after write_close is called, used to check if it was mutated after the session is closed */
64
    private static $sessionatclose = [];
65
 
66
    /**
67
     * @var bool Used to trigger the SESSION mutation warning without actually preventing SESSION mutation.
68
     * This variable is used to "copy" what the $requireslock parameter  does in start_session().
69
     * Once requireslock is set in start_session it's later accessible via $handler->requires_write_lock,
70
     * When using $CFG->enable_read_only_sessions_debug mode, this variable serves the same purpose without
71
     * actually setting the handler as requiring a write lock.
72
     */
73
    private static $requireslockdebug;
74
 
75
    /**
76
     * If the current session is not writeable, abort it, and re-open it
77
     * requesting (and blocking) until a write lock is acquired.
78
     * If current session was already opened with an intentional write lock,
79
     * this call will not do anything.
80
     * NOTE: Even when using a session handler that does not support non-locking sessions,
81
     * if the original session was not opened with the explicit intention of being locked,
82
     * this will still restart your session so that code behaviour matches as closely
83
     * as practical across environments.
84
     *
85
     * @param bool $readonlysession Used by debugging logic to determine if whatever
86
     *                              triggered the restart (e.g., a webservice) declared
87
     *                              itself as read only.
88
     */
89
    public static function restart_with_write_lock(bool $readonlysession) {
90
        global $CFG;
91
 
92
        if (!empty($CFG->enable_read_only_sessions_debug)) {
93
            self::$requireslockdebug = !$readonlysession;
94
        }
95
 
96
        if (self::$sessionactive && !self::$handler->requires_write_lock()) {
97
            @self::$handler->abort();
98
            self::$sessionactive = false;
99
            self::start_session(true);
100
        }
101
    }
102
 
103
    /**
104
     * Start user session.
105
     *
106
     * Note: This is intended to be called only from lib/setup.php!
107
     */
108
    public static function start() {
109
        global $CFG, $DB, $PERF;
110
 
111
        if (isset(self::$sessionactive)) {
112
            debugging('Session was already started!', DEBUG_DEVELOPER);
113
            return;
114
        }
115
 
116
        // Grab the time before session lock starts.
117
        $PERF->sessionlock['start'] = microtime(true);
118
        self::load_handler();
119
 
120
        // Init the session handler only if everything initialised properly in lib/setup.php file
121
        // and the session is actually required.
122
        if (empty($DB) or empty($CFG->version) or !defined('NO_MOODLE_COOKIES') or NO_MOODLE_COOKIES or CLI_SCRIPT) {
123
            self::$sessionactive = false;
124
            self::init_empty_session();
125
            return;
126
        }
127
 
128
        if (defined('READ_ONLY_SESSION') && !empty($CFG->enable_read_only_sessions)) {
129
            $requireslock = !READ_ONLY_SESSION;
130
        } else {
131
            $requireslock = true; // For backwards compatibility, we default to assuming that a lock is needed.
132
        }
133
 
134
        // By default make the two variables the same. This means that when they are
135
        // checked below in start_session and write_close there is no possibility for
136
        // the debug version to "accidentally" execute the debug mode.
137
        self::$requireslockdebug = $requireslock;
138
        if (defined('READ_ONLY_SESSION') && !empty($CFG->enable_read_only_sessions_debug)) {
139
            // Only change the debug variable if READ_ONLY_SESSION is declared,
140
            // as would happen with the real requireslock variable.
141
            self::$requireslockdebug = !READ_ONLY_SESSION;
142
        }
143
 
144
        self::start_session($requireslock);
145
    }
146
 
147
    /**
148
     * Handles starting a session.
149
     *
150
     * @param bool $requireslock If this is false then no write lock will be acquired,
151
     *                           and the session will be read-only.
152
     */
153
    private static function start_session(bool $requireslock) {
154
        global $PERF, $CFG;
155
 
156
        try {
157
            self::$handler->init();
158
            self::$handler->set_requires_write_lock($requireslock);
159
            self::prepare_cookies();
160
            $isnewsession = empty($_COOKIE[session_name()]);
161
 
162
            if (!self::$handler->start()) {
163
                // Could not successfully start/recover session.
164
                throw new \core\session\exception(get_string('servererror'));
165
            }
166
 
167
            if ($requireslock) {
168
                // Grab the time when session lock starts.
169
                $PERF->sessionlock['gained'] = microtime(true);
170
                $PERF->sessionlock['wait'] = $PERF->sessionlock['gained'] - $PERF->sessionlock['start'];
171
            }
172
            self::initialise_user_session($isnewsession);
173
            self::$sessionactive = true; // Set here, so the session can be cleared if the security check fails.
174
            self::check_security();
175
 
176
            if (!$requireslock || !self::$requireslockdebug) {
177
                self::$priorsession = (array) $_SESSION['SESSION'];
178
            }
179
 
180
            if (!empty($CFG->enable_read_only_sessions) && isset($_SESSION['SESSION']->cachestore_session)) {
181
                $caches = join(', ', array_keys($_SESSION['SESSION']->cachestore_session));
182
                $caches = str_replace('default_session-', '', $caches);
183
                throw new \moodle_exception("The session caches can not be in the session store when "
184
                    . "enable_read_only_sessions is enabled. Please map all session mode caches to be outside of the "
185
                    . "default session store before enabling this features. Found these definitions in the session: $caches");
186
            }
187
 
188
            // Link global $USER and $SESSION,
189
            // this is tricky because PHP does not allow references to references
190
            // and global keyword uses internally once reference to the $GLOBALS array.
191
            // The solution is to use the $GLOBALS['USER'] and $GLOBALS['$SESSION']
192
            // as the main storage of data and put references to $_SESSION.
193
            $GLOBALS['USER'] = $_SESSION['USER'];
194
            $_SESSION['USER'] =& $GLOBALS['USER'];
195
            $GLOBALS['SESSION'] = $_SESSION['SESSION'];
196
            $_SESSION['SESSION'] =& $GLOBALS['SESSION'];
197
 
198
        } catch (\Exception $ex) {
199
            self::init_empty_session();
200
            self::$sessionactive = false;
201
            throw $ex;
202
        }
203
    }
204
 
205
    /**
206
     * Returns current page performance info.
207
     *
208
     * @return array perf info
209
     */
210
    public static function get_performance_info() {
211
        global $CFG, $PERF;
212
 
213
        if (!session_id()) {
214
            return array();
215
        }
216
 
217
        self::load_handler();
218
        $size = display_size(strlen(session_encode()));
219
        $handler = get_class(self::$handler);
220
 
221
        $info = array();
222
        $info['size'] = $size;
223
        $info['html'] = html_writer::div("Session ($handler): $size", "sessionsize");
224
        $info['txt'] = "Session ($handler): $size ";
225
 
226
        if (!empty($CFG->debugsessionlock)) {
227
            $sessionlock = self::get_session_lock_info();
228
            if (!empty($sessionlock['held'])) {
229
                // The page displays the footer and the session has been closed.
230
                $sessionlocktext = "Session lock held: ".number_format($sessionlock['held'], 3)." secs";
231
            } else {
232
                // The session hasn't yet been closed and so we assume now with microtime.
233
                $sessionlockheld = microtime(true) - $PERF->sessionlock['gained'];
234
                $sessionlocktext = "Session lock open: ".number_format($sessionlockheld, 3)." secs";
235
            }
236
            $info['txt'] .= $sessionlocktext;
237
            $info['html'] .= html_writer::div($sessionlocktext, "sessionlockstart");
238
            $sessionlockwaittext = "Session lock wait: ".number_format($sessionlock['wait'], 3)." secs";
239
            $info['txt'] .= $sessionlockwaittext;
240
            $info['html'] .= html_writer::div($sessionlockwaittext, "sessionlockwait");
241
        }
242
 
243
        return $info;
244
    }
245
 
246
    /**
247
     * Get fully qualified name of session handler class.
248
     *
249
     * @return string The name of the handler class
250
     */
251
    public static function get_handler_class() {
252
        global $CFG, $DB;
253
 
254
        if (PHPUNIT_TEST) {
255
            return '\core\session\file';
256
        } else if (!empty($CFG->session_handler_class)) {
257
            return $CFG->session_handler_class;
258
        } else if (!empty($CFG->dbsessions) and $DB->session_lock_supported()) {
259
            return '\core\session\database';
260
        }
261
 
262
        return '\core\session\file';
263
    }
264
 
265
    /**
266
     * Create handler instance.
267
     */
268
    protected static function load_handler() {
269
        if (self::$handler) {
270
            return;
271
        }
272
 
273
        // Find out which handler to use.
274
        $class = self::get_handler_class();
275
        self::$handler = new $class();
276
    }
277
 
278
    /**
279
     * Empty current session, fill it with not-logged-in user info.
280
     *
281
     * This is intended for installation scripts, unit tests and other
282
     * special areas. Do NOT use for logout and session termination
283
     * in normal requests!
284
     *
285
     * @param mixed $newsid only used after initialising a user session, is this a new user session?
286
     */
287
    public static function init_empty_session(?bool $newsid = null) {
288
        global $CFG;
289
 
290
        if (isset($GLOBALS['SESSION']->notifications)) {
291
            // Backup notifications. These should be preserved across session changes until the user fetches and clears them.
292
            $notifications = $GLOBALS['SESSION']->notifications;
293
        }
294
        $GLOBALS['SESSION'] = new \stdClass();
295
        if (isset($newsid)) {
296
            $GLOBALS['SESSION']->isnewsessioncookie = $newsid;
297
        }
298
 
299
        $GLOBALS['USER'] = new \stdClass();
300
        $GLOBALS['USER']->id = 0;
301
 
302
        if (!empty($notifications)) {
303
            // Restore notifications.
304
            $GLOBALS['SESSION']->notifications = $notifications;
305
        }
306
        if (isset($CFG->mnet_localhost_id)) {
307
            $GLOBALS['USER']->mnethostid = $CFG->mnet_localhost_id;
308
        } else {
309
            // Not installed yet, the future host id will be most probably 1.
310
            $GLOBALS['USER']->mnethostid = 1;
311
        }
312
 
313
        // Link global $USER and $SESSION.
314
        $_SESSION = array();
315
        $_SESSION['USER'] =& $GLOBALS['USER'];
316
        $_SESSION['SESSION'] =& $GLOBALS['SESSION'];
317
    }
318
 
319
    /**
320
     * Make sure all cookie and session related stuff is configured properly before session start.
321
     */
322
    protected static function prepare_cookies() {
323
        global $CFG;
324
 
325
        $cookiesecure = is_moodle_cookie_secure();
326
 
327
        if (!isset($CFG->cookiehttponly)) {
328
            $CFG->cookiehttponly = 1;
329
        }
330
 
331
        // Set sessioncookie variable if it isn't already.
332
        if (!isset($CFG->sessioncookie)) {
333
            $CFG->sessioncookie = '';
334
        }
335
        $sessionname = 'MoodleSession'.$CFG->sessioncookie;
336
 
337
        // Make sure cookie domain makes sense for this wwwroot.
338
        if (!isset($CFG->sessioncookiedomain)) {
339
            $CFG->sessioncookiedomain = '';
340
        } else if ($CFG->sessioncookiedomain !== '') {
341
            $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
342
            if ($CFG->sessioncookiedomain !== $host) {
343
                if (substr($CFG->sessioncookiedomain, 0, 1) === '.') {
344
                    if (!preg_match('|^.*'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
345
                        // Invalid domain - it must be end part of host.
346
                        $CFG->sessioncookiedomain = '';
347
                    }
348
                } else {
349
                    if (!preg_match('|^.*\.'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
350
                        // Invalid domain - it must be end part of host.
351
                        $CFG->sessioncookiedomain = '';
352
                    }
353
                }
354
            }
355
        }
356
 
357
        // Make sure the cookiepath is valid for this wwwroot or autodetect if not specified.
358
        if (!isset($CFG->sessioncookiepath)) {
359
            $CFG->sessioncookiepath = '';
360
        }
361
        if ($CFG->sessioncookiepath !== '/') {
362
            $path = parse_url($CFG->wwwroot, PHP_URL_PATH).'/';
363
            if ($CFG->sessioncookiepath === '') {
364
                $CFG->sessioncookiepath = $path;
365
            } else {
366
                if (strpos($path, $CFG->sessioncookiepath) !== 0 or substr($CFG->sessioncookiepath, -1) !== '/') {
367
                    $CFG->sessioncookiepath = $path;
368
                }
369
            }
370
        }
371
 
372
        // Discard session ID from POST, GET and globals to tighten security,
373
        // this is session fixation prevention.
374
        unset($GLOBALS[$sessionname]);
375
        unset($_GET[$sessionname]);
376
        unset($_POST[$sessionname]);
377
        unset($_REQUEST[$sessionname]);
378
 
379
        // Compatibility hack for non-browser access to our web interface.
380
        if (!empty($_COOKIE[$sessionname]) && $_COOKIE[$sessionname] == "deleted") {
381
            unset($_COOKIE[$sessionname]);
382
        }
383
 
384
        // Set configuration.
385
        session_name($sessionname);
386
 
387
        $sessionoptions = [
388
            'lifetime' => 0,
389
            'path' => $CFG->sessioncookiepath,
390
            'domain' => $CFG->sessioncookiedomain,
391
            'secure' => $cookiesecure,
392
            'httponly' => $CFG->cookiehttponly,
393
        ];
394
 
395
        if (self::should_use_samesite_none()) {
396
            // If $samesite is empty, we don't want there to be any SameSite attribute.
397
            $sessionoptions['samesite'] = 'None';
398
        }
399
 
400
        session_set_cookie_params($sessionoptions);
401
 
402
        ini_set('session.use_trans_sid', '0');
403
        ini_set('session.use_only_cookies', '1');
404
        ini_set('session.use_strict_mode', '0');      // We have custom protection in session init.
405
        ini_set('session.serialize_handler', 'php');  // We can move to 'php_serialize' after we require PHP 5.5.4 form Moodle.
406
 
407
        // Moodle does normal session timeouts, this is for leftovers only.
408
        ini_set('session.gc_probability', 1);
409
        ini_set('session.gc_divisor', 1000);
410
        ini_set('session.gc_maxlifetime', 60*60*24*4);
411
    }
412
 
413
    /**
414
     * Initialise $_SESSION, handles google access
415
     * and sets up not-logged-in user properly.
416
     *
417
     * WARNING: $USER and $SESSION are set up later, do not use them yet!
418
     *
419
     * @param bool $newsid is this a new session in first http request?
420
     */
421
    protected static function initialise_user_session($newsid) {
422
        global $CFG, $DB;
423
 
424
        $sid = session_id();
425
        if (!$sid) {
426
            // No session, very weird.
427
            error_log('Missing session ID, session not started!');
428
            self::init_empty_session($newsid);
429
            return;
430
        }
431
 
432
        if (!$record = $DB->get_record('sessions', array('sid'=>$sid), 'id, sid, state, userid, lastip, timecreated, timemodified')) {
433
            if (!$newsid) {
434
                if (!empty($_SESSION['USER']->id)) {
435
                    // This should not happen, just log it, we MUST not produce any output here!
436
                    error_log("Cannot find session record $sid for user ".$_SESSION['USER']->id.", creating new session.");
437
                }
438
                // Prevent session fixation attacks.
439
                session_regenerate_id(true);
440
            }
441
            $_SESSION = array();
442
        }
443
        unset($sid);
444
 
445
        if (isset($_SESSION['USER']->id)) {
446
            if (!empty($_SESSION['USER']->realuser)) {
447
                $userid = $_SESSION['USER']->realuser;
448
            } else {
449
                $userid = $_SESSION['USER']->id;
450
            }
451
 
452
            // Verify timeout first.
453
            $maxlifetime = $CFG->sessiontimeout;
454
            $timeout = false;
455
            if (isguestuser($userid) or empty($userid)) {
456
                // Ignore guest and not-logged in timeouts, there is very little risk here.
457
                $timeout = false;
458
 
459
            } else if ($record->timemodified < time() - $maxlifetime) {
460
                $timeout = true;
461
                $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
462
                foreach ($authsequence as $authname) {
463
                    $authplugin = get_auth_plugin($authname);
464
                    if ($authplugin->ignore_timeout_hook($_SESSION['USER'], $record->sid, $record->timecreated, $record->timemodified)) {
465
                        $timeout = false;
466
                        break;
467
                    }
468
                }
469
            }
470
 
471
            if ($timeout) {
472
                if (defined('NO_SESSION_UPDATE') && NO_SESSION_UPDATE) {
473
                    return;
474
                }
475
                session_regenerate_id(true);
476
                $_SESSION = array();
477
                $DB->delete_records('sessions', array('id'=>$record->id));
478
 
479
            } else {
480
                // Update session tracking record.
481
 
482
                $update = new \stdClass();
483
                $updated = false;
484
 
485
                if ($record->userid != $userid) {
486
                    $update->userid = $record->userid = $userid;
487
                    $updated = true;
488
                }
489
 
490
                $ip = getremoteaddr();
491
                if ($record->lastip != $ip) {
492
                    $update->lastip = $record->lastip = $ip;
493
                    $updated = true;
494
                }
495
 
496
                $updatefreq = empty($CFG->session_update_timemodified_frequency) ? 20 : $CFG->session_update_timemodified_frequency;
497
 
498
                if ($record->timemodified == $record->timecreated) {
499
                    // Always do first update of existing record.
500
                    $update->timemodified = $record->timemodified = time();
501
                    $updated = true;
502
 
503
                } else if ($record->timemodified < time() - $updatefreq) {
504
                    // Update the session modified flag only once every 20 seconds.
505
                    $update->timemodified = $record->timemodified = time();
506
                    $updated = true;
507
                }
508
 
509
                if ($updated && (!defined('NO_SESSION_UPDATE') || !NO_SESSION_UPDATE)) {
510
                    $update->id = $record->id;
511
                    $DB->update_record('sessions', $update);
512
                }
513
 
514
                return;
515
            }
516
        } else {
517
            if ($record) {
518
                // This happens when people switch session handlers...
519
                session_regenerate_id(true);
520
                $_SESSION = array();
521
                $DB->delete_records('sessions', array('id'=>$record->id));
522
            }
523
        }
524
        unset($record);
525
 
526
        $timedout = false;
527
        if (!isset($_SESSION['SESSION'])) {
528
            $_SESSION['SESSION'] = new \stdClass();
529
            if (!$newsid) {
530
                $timedout = true;
531
            }
532
        }
533
 
534
        $user = null;
535
 
536
        if (!empty($CFG->opentowebcrawlers)) {
537
            if (\core_useragent::is_web_crawler()) {
538
                $user = guest_user();
539
            }
540
            $referer = get_local_referer(false);
541
            if (!empty($CFG->guestloginbutton) and !$user and !empty($referer)) {
542
                // Automatically log in users coming from search engine results.
543
                if (strpos($referer, 'google') !== false ) {
544
                    $user = guest_user();
545
                } else if (strpos($referer, 'altavista') !== false ) {
546
                    $user = guest_user();
547
                }
548
            }
549
        }
550
 
551
        // Setup $USER and insert the session tracking record.
552
        if ($user) {
553
            self::set_user($user);
554
            self::add_session_record($user->id);
555
        } else {
556
            self::init_empty_session($newsid);
557
            self::add_session_record(0);
558
        }
559
 
560
        if ($timedout) {
561
            $_SESSION['SESSION']->has_timed_out = true;
562
        }
563
    }
564
 
565
    /**
566
     * Insert new empty session record.
567
     * @param int $userid
568
     * @return \stdClass the new record
569
     */
570
    protected static function add_session_record($userid) {
571
        global $DB;
572
        $record = new \stdClass();
573
        $record->state       = 0;
574
        $record->sid         = session_id();
575
        $record->sessdata    = null;
576
        $record->userid      = $userid;
577
        $record->timecreated = $record->timemodified = time();
578
        $record->firstip     = $record->lastip = getremoteaddr();
579
 
580
        $record->id = $DB->insert_record('sessions', $record);
581
 
582
        return $record;
583
    }
584
 
585
    /**
586
     * Do various session security checks.
587
     *
588
     * WARNING: $USER and $SESSION are set up later, do not use them yet!
589
     * @throws \core\session\exception
590
     */
591
    protected static function check_security() {
592
        global $CFG;
593
 
594
        if (!empty($_SESSION['USER']->id) and !empty($CFG->tracksessionip)) {
595
            // Make sure current IP matches the one for this session.
596
            $remoteaddr = getremoteaddr();
597
 
598
            if (empty($_SESSION['USER']->sessionip)) {
599
                $_SESSION['USER']->sessionip = $remoteaddr;
600
            }
601
 
602
            if ($_SESSION['USER']->sessionip != $remoteaddr) {
603
                // This is a security feature - terminate the session in case of any doubt.
604
                self::terminate_current();
605
                throw new exception('sessionipnomatch2', 'error');
606
            }
607
        }
608
    }
609
 
610
    /**
611
     * Login user, to be called from complete_user_login() only.
612
     * @param \stdClass $user
613
     */
614
    public static function login_user(\stdClass $user) {
615
        global $DB;
616
 
617
        // Regenerate session id and delete old session,
618
        // this helps prevent session fixation attacks from the same domain.
619
 
620
        $sid = session_id();
621
        session_regenerate_id(true);
622
        $DB->delete_records('sessions', array('sid'=>$sid));
623
        self::add_session_record($user->id);
624
 
625
        // Let enrol plugins deal with new enrolments if necessary.
626
        enrol_check_plugins($user);
627
 
628
        // Setup $USER object.
629
        self::set_user($user);
630
    }
631
 
632
    /**
633
     * Returns a valid setting for the SameSite cookie attribute.
634
     *
635
     * @return string The desired setting for the SameSite attribute on the cookie. Empty string indicates the SameSite attribute
636
     * should not be set at all.
637
     */
638
    private static function should_use_samesite_none(): bool {
639
        // We only want None or no attribute at this point. When we have cookie handling compatible with Lax,
640
        // we can look at checking a setting.
641
 
642
        // Browser support for none is not consistent yet. There are known issues with Safari, and IE11.
643
        // Things are stablising, however as they're not stable yet we will deal specifically with the version of chrome
644
        // that introduces a default of lax, setting it to none for the current version of chrome (2 releases before the change).
645
        // We also check you are using secure cookies and HTTPS because if you are not running over HTTPS
646
        // then setting SameSite=None will cause your session cookie to be rejected.
647
        if (\core_useragent::is_chrome() && \core_useragent::check_chrome_version('78') && is_moodle_cookie_secure()) {
648
            return true;
649
        }
650
        return false;
651
    }
652
 
653
    /**
654
     * Terminate current user session.
655
     * @return void
656
     */
657
    public static function terminate_current() {
658
        global $DB;
659
 
660
        if (!self::$sessionactive) {
661
            self::init_empty_session();
662
            self::$sessionactive = false;
663
            return;
664
        }
665
 
666
        try {
667
            $DB->delete_records('external_tokens', array('sid'=>session_id(), 'tokentype'=>EXTERNAL_TOKEN_EMBEDDED));
668
        } catch (\Exception $ignored) {
669
            // Probably install/upgrade - ignore this problem.
670
        }
671
 
672
        // Initialize variable to pass-by-reference to headers_sent(&$file, &$line).
673
        $file = null;
674
        $line = null;
675
        if (headers_sent($file, $line)) {
676
            error_log('Cannot terminate session properly - headers were already sent in file: '.$file.' on line '.$line);
677
        }
678
 
679
        // Write new empty session and make sure the old one is deleted.
680
        $sid = session_id();
681
        session_regenerate_id(true);
682
        $DB->delete_records('sessions', array('sid'=>$sid));
683
        self::init_empty_session();
684
        self::add_session_record($_SESSION['USER']->id); // Do not use $USER here because it may not be set up yet.
685
        self::write_close();
686
    }
687
 
688
    /**
689
     * No more changes in session expected.
690
     * Unblocks the sessions, other scripts may start executing in parallel.
691
     */
692
    public static function write_close() {
693
        global $PERF, $ME, $CFG;
694
 
695
        if (self::$sessionactive) {
696
            $requireslock = self::$handler->requires_write_lock();
697
            if ($requireslock) {
698
                // Grab the time when session lock is released.
699
                $PERF->sessionlock['released'] = microtime(true);
700
                if (!empty($PERF->sessionlock['gained'])) {
701
                    $PERF->sessionlock['held'] = $PERF->sessionlock['released'] - $PERF->sessionlock['gained'];
702
                }
703
                $PERF->sessionlock['url'] = me();
704
                self::update_recent_session_locks($PERF->sessionlock);
705
                self::sessionlock_debugging();
706
            }
707
 
708
            // If debugging, take a snapshot of session at close and compare on shutdown to detect any accidental mutations.
709
            if (debugging()) {
710
                self::$sessionatclose = (array) $_SESSION['SESSION'];
711
                \core_shutdown_manager::register_function('\core\session\manager::check_mutated_closed_session');
712
            }
713
 
714
            if (!$requireslock || !self::$requireslockdebug) {
715
                // Compare the array of the earlier session data with the array now, if
716
                // there is a difference then a lock is required.
717
                $arraydiff = self::array_session_diff(
718
                    self::$priorsession,
719
                    (array) $_SESSION['SESSION']
720
                );
721
 
722
                if ($arraydiff) {
723
                    $error = "Script $ME defined READ_ONLY_SESSION but the following SESSION attributes were changed:";
724
                    foreach ($arraydiff as $key => $value) {
725
                        $error .= ' $SESSION->' . $key;
726
                    }
727
                    // This will emit an error if debugging is on, even if $CFG->enable_read_only_sessions
728
                    // is not true as we need to surface this class of errors.
729
                    error_log($error); // phpcs:ignore
730
                }
731
            }
732
        }
733
 
734
        // More control over whether session data
735
        // is persisted or not.
736
        if (self::$sessionactive && session_id()) {
737
            // Write session and release lock only if
738
            // indication session start was clean.
739
            self::$handler->write_close();
740
        } else {
741
            // Otherwise, if possible lock exists want
742
            // to clear it, but do not write session.
743
            // If the $handler has not been set then
744
            // there is no session to abort.
745
            if (isset(self::$handler)) {
746
                @self::$handler->abort();
747
            }
748
        }
749
 
750
        self::$sessionactive = false;
751
    }
752
 
753
    /**
754
     * Checks if the session has been mutated since it was closed.
755
     * In write_close the session is saved to the variable $sessionatclose
756
     * If there is a difference between $sessionatclose and the current session,
757
     * it means a script has erroneously closed the session too early.
758
     * Script is usually called in shutdown_manager
759
     */
760
    public static function check_mutated_closed_session() {
761
        global $ME;
762
 
763
        // Session is still open, mutations are allowed.
764
        if (self::$sessionactive) {
765
            return;
766
        }
767
 
768
        // Detect if session was cleared.
769
        if (!isset($_SESSION['SESSION']) && isset(self::$sessionatclose)) {
770
            debugging("Script $ME cleared the session after it was closed.");
771
            return;
772
        } else if (!isset($_SESSION['SESSION'])) {
773
            // Else session is empty, nothing to check.
774
            return;
775
        }
776
 
777
        // Session is closed - compare the current session to the session when write_close was called.
778
        $arraydiff = self::array_session_diff(
779
            self::$sessionatclose,
780
            (array) $_SESSION['SESSION']
781
        );
782
 
783
        if ($arraydiff) {
784
            $error = "Script $ME mutated the session after it was closed:";
785
            foreach ($arraydiff as $key => $value) {
786
                $error .= ' $SESSION->' . $key;
787
 
788
                // Extra debugging for cachestore session changes.
789
                if (strpos($key, 'cachestore_') === 0 && is_array($value)) {
790
                    $error .= ': ' . implode(',', array_keys($value));
791
                }
792
            }
793
            debugging($error);
794
        }
795
    }
796
 
797
    /**
798
     * Does the PHP session with given id exist?
799
     *
800
     * The session must exist both in session table and actual
801
     * session backend and the session must not be timed out.
802
     *
803
     * Timeout evaluation is simplified, the auth hooks are not executed.
804
     *
805
     * @param string $sid
806
     * @return bool
807
     */
808
    public static function session_exists($sid) {
809
        global $DB, $CFG;
810
 
811
        if (empty($CFG->version)) {
812
            // Not installed yet, do not try to access database.
813
            return false;
814
        }
815
 
816
        // Note: add sessions->state checking here if it gets implemented.
817
        if (!$record = $DB->get_record('sessions', array('sid' => $sid), 'id, userid, timemodified')) {
818
            return false;
819
        }
820
 
821
        if (empty($record->userid) or isguestuser($record->userid)) {
822
            // Ignore guest and not-logged-in timeouts, there is very little risk here.
823
        } else if ($record->timemodified < time() - $CFG->sessiontimeout) {
824
            return false;
825
        }
826
 
827
        // There is no need the existence of handler storage in public API.
828
        self::load_handler();
829
        return self::$handler->session_exists($sid);
830
    }
831
 
832
    /**
833
     * Return the number of seconds remaining in the current session.
834
     * @param string $sid
835
     */
836
    public static function time_remaining($sid) {
837
        global $DB, $CFG;
838
 
839
        if (empty($CFG->version)) {
840
            // Not installed yet, do not try to access database.
841
            return ['userid' => 0, 'timeremaining' => $CFG->sessiontimeout];
842
        }
843
 
844
        // Note: add sessions->state checking here if it gets implemented.
845
        if (!$record = $DB->get_record('sessions', array('sid' => $sid), 'id, userid, timemodified')) {
846
            return ['userid' => 0, 'timeremaining' => $CFG->sessiontimeout];
847
        }
848
 
849
        if (empty($record->userid) or isguestuser($record->userid)) {
850
            // Ignore guest and not-logged-in timeouts, there is very little risk here.
851
            return ['userid' => 0, 'timeremaining' => $CFG->sessiontimeout];
852
        } else {
853
            return ['userid' => $record->userid, 'timeremaining' => $CFG->sessiontimeout - (time() - $record->timemodified)];
854
        }
855
    }
856
 
857
    /**
858
     * Fake last access for given session, this prevents session timeout.
859
     * @param string $sid
860
     */
861
    public static function touch_session($sid) {
862
        global $DB;
863
 
864
        // Timeouts depend on core sessions table only, no need to update anything in external stores.
865
 
866
        $sql = "UPDATE {sessions} SET timemodified = :now WHERE sid = :sid";
867
        $DB->execute($sql, array('now'=>time(), 'sid'=>$sid));
868
    }
869
 
870
    /**
871
     * Terminate all sessions unconditionally.
872
     */
873
    public static function kill_all_sessions() {
874
        global $DB;
875
 
876
        self::terminate_current();
877
 
878
        self::load_handler();
879
        self::$handler->kill_all_sessions();
880
 
881
        try {
882
            $DB->delete_records('sessions');
883
        } catch (\dml_exception $ignored) {
884
            // Do not show any warnings - might be during upgrade/installation.
885
        }
886
    }
887
 
888
    /**
889
     * Terminate give session unconditionally.
890
     * @param string $sid
891
     */
892
    public static function kill_session($sid) {
893
        global $DB;
894
 
895
        self::load_handler();
896
 
897
        if ($sid === session_id()) {
898
            self::write_close();
899
        }
900
 
901
        self::$handler->kill_session($sid);
902
 
903
        $DB->delete_records('sessions', array('sid'=>$sid));
904
    }
905
 
906
    /**
907
     * Terminate all sessions of given user unconditionally.
908
     * @param int $userid
909
     * @param string $keepsid keep this sid if present
910
     */
911
    public static function kill_user_sessions($userid, $keepsid = null) {
912
        global $DB;
913
 
914
        $sessions = $DB->get_records('sessions', array('userid'=>$userid), 'id DESC', 'id, sid');
915
        foreach ($sessions as $session) {
916
            if ($keepsid and $keepsid === $session->sid) {
917
                continue;
918
            }
919
            self::kill_session($session->sid);
920
        }
921
    }
922
 
923
    /**
924
     * Terminate other sessions of current user depending
925
     * on $CFG->limitconcurrentlogins restriction.
926
     *
927
     * This is expected to be called right after complete_user_login().
928
     *
929
     * NOTE:
930
     *  * Do not use from SSO auth plugins, this would not work.
931
     *  * Do not use from web services because they do not have sessions.
932
     *
933
     * @param int $userid
934
     * @param string $sid session id to be always keep, usually the current one
935
     * @return void
936
     */
937
    public static function apply_concurrent_login_limit($userid, $sid = null) {
938
        global $CFG, $DB;
939
 
940
        // NOTE: the $sid parameter is here mainly to allow testing,
941
        //       in most cases it should be current session id.
942
 
943
        if (isguestuser($userid) or empty($userid)) {
944
            // This applies to real users only!
945
            return;
946
        }
947
 
948
        if (empty($CFG->limitconcurrentlogins) or $CFG->limitconcurrentlogins < 0) {
949
            return;
950
        }
951
 
952
        $count = $DB->count_records('sessions', array('userid' => $userid));
953
 
954
        if ($count <= $CFG->limitconcurrentlogins) {
955
            return;
956
        }
957
 
958
        $i = 0;
959
        $select = "userid = :userid";
960
        $params = array('userid' => $userid);
961
        if ($sid) {
962
            if ($DB->record_exists('sessions', array('sid' => $sid, 'userid' => $userid))) {
963
                $select .= " AND sid <> :sid";
964
                $params['sid'] = $sid;
965
                $i = 1;
966
            }
967
        }
968
 
969
        $sessions = $DB->get_records_select('sessions', $select, $params, 'timecreated DESC', 'id, sid');
970
        foreach ($sessions as $session) {
971
            $i++;
972
            if ($i <= $CFG->limitconcurrentlogins) {
973
                continue;
974
            }
975
            self::kill_session($session->sid);
976
        }
977
    }
978
 
979
    /**
980
     * Set current user.
981
     *
982
     * @param \stdClass $user record
983
     */
984
    public static function set_user(\stdClass $user) {
985
        global $ADMIN;
986
        $GLOBALS['USER'] = $user;
987
        unset($GLOBALS['USER']->description); // Conserve memory.
988
        unset($GLOBALS['USER']->password);    // Improve security.
989
        if (isset($GLOBALS['USER']->lang)) {
990
            // Make sure it is a valid lang pack name.
991
            $GLOBALS['USER']->lang = clean_param($GLOBALS['USER']->lang, PARAM_LANG);
992
        }
993
 
994
        // Relink session with global $USER just in case it got unlinked somehow.
995
        $_SESSION['USER'] =& $GLOBALS['USER'];
996
 
997
        // Nullify the $ADMIN tree global. If we're changing users, then this is now stale and must be generated again if needed.
998
        $ADMIN = null;
999
 
1000
        // Init session key.
1001
        sesskey();
1002
 
1003
        // Make sure the user is correct in web server access logs.
1004
        set_access_log_user();
1005
    }
1006
 
1007
    /**
1008
     * Periodic timed-out session cleanup.
1009
     */
1010
    public static function gc() {
1011
        global $CFG, $DB;
1012
 
1013
        // This may take a long time...
1014
        \core_php_time_limit::raise();
1015
 
1016
        $maxlifetime = $CFG->sessiontimeout;
1017
 
1018
        try {
1019
            // Kill all sessions of deleted and suspended users without any hesitation.
1020
            $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE deleted <> 0 OR suspended <> 0)", array(), 'id DESC', 'id, sid');
1021
            foreach ($rs as $session) {
1022
                self::kill_session($session->sid);
1023
            }
1024
            $rs->close();
1025
 
1026
            // Kill sessions of users with disabled plugins.
1027
            $authsequence = get_enabled_auth_plugins();
1028
            $authsequence = array_flip($authsequence);
1029
            unset($authsequence['nologin']); // No login means user cannot login.
1030
            $authsequence = array_flip($authsequence);
1031
 
1032
            list($notplugins, $params) = $DB->get_in_or_equal($authsequence, SQL_PARAMS_QM, '', false);
1033
            $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE auth $notplugins)", $params, 'id DESC', 'id, sid');
1034
            foreach ($rs as $session) {
1035
                self::kill_session($session->sid);
1036
            }
1037
            $rs->close();
1038
 
1039
            // Now get a list of time-out candidates - real users only.
1040
            $sql = "SELECT u.*, s.sid, s.timecreated AS s_timecreated, s.timemodified AS s_timemodified
1041
                      FROM {user} u
1042
                      JOIN {sessions} s ON s.userid = u.id
1043
                     WHERE s.timemodified < :purgebefore AND u.id <> :guestid";
1044
            $params = array('purgebefore' => (time() - $maxlifetime), 'guestid'=>$CFG->siteguest);
1045
 
1046
            $authplugins = array();
1047
            foreach ($authsequence as $authname) {
1048
                $authplugins[$authname] = get_auth_plugin($authname);
1049
            }
1050
            $rs = $DB->get_recordset_sql($sql, $params);
1051
            foreach ($rs as $user) {
1052
                foreach ($authplugins as $authplugin) {
1053
                    /** @var \auth_plugin_base $authplugin*/
1054
                    if ($authplugin->ignore_timeout_hook($user, $user->sid, $user->s_timecreated, $user->s_timemodified)) {
1055
                        continue 2;
1056
                    }
1057
                }
1058
                self::kill_session($user->sid);
1059
            }
1060
            $rs->close();
1061
 
1062
            // Delete expired sessions for guest user account, give them larger timeout, there is no security risk here.
1063
            $params = array('purgebefore' => (time() - ($maxlifetime * 5)), 'guestid'=>$CFG->siteguest);
1064
            $rs = $DB->get_recordset_select('sessions', 'userid = :guestid AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
1065
            foreach ($rs as $session) {
1066
                self::kill_session($session->sid);
1067
            }
1068
            $rs->close();
1069
 
1070
            // Delete expired sessions for userid = 0 (not logged in), better kill them asap to release memory.
1071
            $params = array('purgebefore' => (time() - $maxlifetime));
1072
            $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
1073
            foreach ($rs as $session) {
1074
                self::kill_session($session->sid);
1075
            }
1076
            $rs->close();
1077
 
1078
            // Cleanup letfovers from the first browser access because it may set multiple cookies and then use only one.
1079
            $params = array('purgebefore' => (time() - 60*3));
1080
            $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified = timecreated AND timemodified < :purgebefore', $params, 'id ASC', 'id, sid');
1081
            foreach ($rs as $session) {
1082
                self::kill_session($session->sid);
1083
            }
1084
            $rs->close();
1085
 
1086
        } catch (\Exception $ex) {
1087
            debugging('Error gc-ing sessions: '.$ex->getMessage(), DEBUG_NORMAL, $ex->getTrace());
1088
        }
1089
    }
1090
 
1091
    /**
1092
     * Is current $USER logged-in-as somebody else?
1093
     * @return bool
1094
     */
1095
    public static function is_loggedinas() {
1096
        return !empty($GLOBALS['USER']->realuser);
1097
    }
1098
 
1099
    /**
1100
     * Returns the $USER object ignoring current login-as session
1101
     * @return \stdClass user object
1102
     */
1103
    public static function get_realuser() {
1104
        if (self::is_loggedinas()) {
1105
            return $_SESSION['REALUSER'];
1106
        } else {
1107
            return $GLOBALS['USER'];
1108
        }
1109
    }
1110
 
1111
    /**
1112
     * Login as another user - no security checks here.
1113
     * @param int $userid
1114
     * @param \context $context
1115
     * @param bool $generateevent Set to false to prevent the loginas event to be generated
1116
     * @return void
1117
     */
1118
    public static function loginas($userid, \context $context, $generateevent = true) {
1119
        global $USER;
1120
 
1121
        if (self::is_loggedinas()) {
1122
            return;
1123
        }
1124
 
1125
        // Switch to fresh new $_SESSION.
1126
        $_SESSION = array();
1127
        $_SESSION['REALSESSION'] = clone($GLOBALS['SESSION']);
1128
        $GLOBALS['SESSION'] = new \stdClass();
1129
        $_SESSION['SESSION'] =& $GLOBALS['SESSION'];
1130
 
1131
        // Create the new $USER object with all details and reload needed capabilities.
1132
        $_SESSION['REALUSER'] = clone($GLOBALS['USER']);
1133
        $user = get_complete_user_data('id', $userid);
1134
        $user->realuser       = $_SESSION['REALUSER']->id;
1135
        $user->loginascontext = $context;
1136
 
1137
        // Let enrol plugins deal with new enrolments if necessary.
1138
        enrol_check_plugins($user);
1139
 
1140
        if ($generateevent) {
1141
            // Create event before $USER is updated.
1142
            $event = \core\event\user_loggedinas::create(
1143
                array(
1144
                    'objectid' => $USER->id,
1145
                    'context' => $context,
1146
                    'relateduserid' => $userid,
1147
                    'other' => array(
1148
                        'originalusername' => fullname($USER, true),
1149
                        'loggedinasusername' => fullname($user, true)
1150
                    )
1151
                )
1152
            );
1153
        }
1154
 
1155
        // Set up global $USER.
1156
        \core\session\manager::set_user($user);
1157
 
1158
        if ($generateevent) {
1159
            $event->trigger();
1160
        }
1161
 
1162
        // Queue migrating the messaging data, if we need to.
1163
        if (!get_user_preferences('core_message_migrate_data', false, $userid)) {
1164
            // Check if there are any legacy messages to migrate.
1165
            if (\core_message\helper::legacy_messages_exist($userid)) {
1166
                \core_message\task\migrate_message_data::queue_task($userid);
1167
            } else {
1168
                set_user_preference('core_message_migrate_data', true, $userid);
1169
            }
1170
        }
1171
    }
1172
 
1173
    /**
1174
     * Add a JS session keepalive to the page.
1175
     *
1176
     * A JS session keepalive script will be called to update the session modification time every $frequency seconds.
1177
     *
1178
     * Upon failure, the specified error message will be shown to the user.
1179
     *
1180
     * @param string $identifier The string identifier for the message to show on failure.
1181
     * @param string $component The string component for the message to show on failure.
1182
     * @param int $frequency The update frequency in seconds.
1183
     * @param int $timeout The timeout of each request in seconds.
1184
     * @throws \coding_exception IF the frequency is longer than the session lifetime.
1185
     */
1186
    public static function keepalive($identifier = 'sessionerroruser', $component = 'error', $frequency = null, $timeout = 0) {
1187
        global $CFG, $PAGE;
1188
 
1189
        if ($frequency) {
1190
            if ($frequency > $CFG->sessiontimeout) {
1191
                // Sanity check the frequency.
1192
                throw new \coding_exception('Keepalive frequency is longer than the session lifespan.');
1193
            }
1194
        } else {
1195
            // A frequency of sessiontimeout / 10 matches the timeouts in core/network amd module.
1196
            $frequency = $CFG->sessiontimeout / 10;
1197
        }
1198
 
1199
        $PAGE->requires->js_call_amd('core/network', 'keepalive', array(
1200
                $frequency,
1201
                $timeout,
1202
                $identifier,
1203
                $component
1204
            ));
1205
    }
1206
 
1207
    /**
1208
     * Generate a new login token and store it in the session.
1209
     *
1210
     * @return array The current login state.
1211
     */
1212
    private static function create_login_token() {
1213
        global $SESSION;
1214
 
1215
        $state = [
1216
            'token' => random_string(32),
1217
            'created' => time() // Server time - not user time.
1218
        ];
1219
 
1220
        if (!isset($SESSION->logintoken)) {
1221
            $SESSION->logintoken = [];
1222
        }
1223
 
1224
        // Overwrite any previous values.
1225
        $SESSION->logintoken[self::$logintokenkey] = $state;
1226
 
1227
        return $state;
1228
    }
1229
 
1230
    /**
1231
     * Get the current login token or generate a new one.
1232
     *
1233
     * All login forms generated from Moodle must include a login token
1234
     * named "logintoken" with the value being the result of this function.
1235
     * Logins will be rejected if they do not include this token as well as
1236
     * the username and password fields.
1237
     *
1238
     * @return string The current login token.
1239
     */
1240
    public static function get_login_token() {
1241
        global $CFG, $SESSION;
1242
 
1243
        $state = false;
1244
 
1245
        if (!isset($SESSION->logintoken)) {
1246
            $SESSION->logintoken = [];
1247
        }
1248
 
1249
        if (array_key_exists(self::$logintokenkey, $SESSION->logintoken)) {
1250
            $state = $SESSION->logintoken[self::$logintokenkey];
1251
        }
1252
        if (empty($state)) {
1253
            $state = self::create_login_token();
1254
        }
1255
 
1256
        // Check token lifespan.
1257
        if ($state['created'] < (time() - $CFG->sessiontimeout)) {
1258
            $state = self::create_login_token();
1259
        }
1260
 
1261
        // Return the current session login token.
1262
        if (array_key_exists('token', $state)) {
1263
            return $state['token'];
1264
        } else {
1265
            return false;
1266
        }
1267
    }
1268
 
1269
    /**
1270
     * Check the submitted value against the stored login token.
1271
     *
1272
     * @param mixed $token The value submitted in the login form that we are validating.
1273
     *                     If false is passed for the token, this function will always return true.
1274
     * @return boolean If the submitted token is valid.
1275
     */
1276
    public static function validate_login_token($token = false) {
1277
        global $CFG, $SESSION;
1278
 
1279
        if (!empty($CFG->alternateloginurl) || !empty($CFG->disablelogintoken)) {
1280
            // An external login page cannot generate the login token we need to protect CSRF on
1281
            // login requests.
1282
            // Other custom login workflows may skip this check by setting disablelogintoken in config.
1283
            return true;
1284
        }
1285
        if ($token === false) {
1286
            // authenticate_user_login is a core function was extended to validate tokens.
1287
            // For existing uses other than the login form it does not
1288
            // validate that a token was generated.
1289
            // Some uses that do not validate the token are login/token.php,
1290
            // or an auth plugin like auth/ldap/auth.php.
1291
            return true;
1292
        }
1293
 
1294
        $currenttoken = self::get_login_token();
1295
 
1296
        // We need to clean the login token so the old one is not valid again.
1297
        unset($SESSION->logintoken);
1298
 
1299
        if ($currenttoken !== $token) {
1300
            // Fail the login.
1301
            return false;
1302
        }
1303
        return true;
1304
    }
1305
 
1306
    /**
1307
     * Get the recent session locks array.
1308
     *
1309
     * @return array Recent session locks array.
1310
     */
1311
    public static function get_recent_session_locks() {
1312
        global $SESSION;
1313
 
1314
        if (!isset($SESSION->recentsessionlocks)) {
1315
            // This will hold the pages that blocks other page.
1316
            $SESSION->recentsessionlocks = array();
1317
        }
1318
 
1319
        return $SESSION->recentsessionlocks;
1320
    }
1321
 
1322
    /**
1323
     * Updates the recent session locks.
1324
     *
1325
     * This function will store session lock info of all the pages visited.
1326
     *
1327
     * @param array $sessionlock Session lock array.
1328
     */
1329
    public static function update_recent_session_locks($sessionlock) {
1330
        global $CFG, $SESSION;
1331
 
1332
        if (empty($CFG->debugsessionlock)) {
1333
            return;
1334
        }
1335
 
1336
        $readonlysession = defined('READ_ONLY_SESSION') && READ_ONLY_SESSION;
1337
        $readonlydebugging = !empty($CFG->enable_read_only_sessions) || !empty($CFG->enable_read_only_sessions_debug);
1338
        if ($readonlysession && $readonlydebugging) {
1339
            return;
1340
        }
1341
 
1342
        $SESSION->recentsessionlocks = self::get_recent_session_locks();
1343
        array_push($SESSION->recentsessionlocks, $sessionlock);
1344
 
1345
        self::cleanup_recent_session_locks();
1346
    }
1347
 
1348
    /**
1349
     * Reset recent session locks array if there is a time gap more than SESSION_RESET_GAP_THRESHOLD.
1350
     */
1351
    public static function cleanup_recent_session_locks() {
1352
        global $SESSION;
1353
 
1354
        $locks = self::get_recent_session_locks();
1355
 
1356
        if (count($locks) > self::MAXIMUM_STORED_SESSION_HISTORY) {
1357
            // Keep the last MAXIMUM_STORED_SESSION_HISTORY locks and ignore the rest.
1358
            $locks = array_slice($locks, -1 * self::MAXIMUM_STORED_SESSION_HISTORY);
1359
        }
1360
 
1361
        if (count($locks) > 2) {
1362
            for ($i = count($locks) - 1; $i > 0; $i--) {
1363
                // Calculate the gap between session locks.
1364
                $gap = $locks[$i]['released'] - $locks[$i - 1]['start'];
1365
                if ($gap >= self::SESSION_RESET_GAP_THRESHOLD) {
1366
                    // Remove previous locks if the gap is 1 second or more.
1367
                    $SESSION->recentsessionlocks = array_slice($locks, $i);
1368
                    break;
1369
                }
1370
            }
1371
        }
1372
    }
1373
 
1374
    /**
1375
     * Get the page that blocks other pages at a specific timestamp.
1376
     *
1377
     * Look for a page whose lock was gained before that timestamp, and released after that timestamp.
1378
     *
1379
     * @param  float $time Time before session lock starts.
1380
     * @return array|null
1381
     */
1382
    public static function get_locked_page_at($time) {
1383
        $recentsessionlocks = self::get_recent_session_locks();
1384
        foreach ($recentsessionlocks as $recentsessionlock) {
1385
            if ($time >= $recentsessionlock['gained'] &&
1386
                $time <= $recentsessionlock['released']) {
1387
                return $recentsessionlock;
1388
            }
1389
        }
1390
    }
1391
 
1392
    /**
1393
     * Display the page which blocks other pages.
1394
     *
1395
     * @return string
1396
     */
1397
    public static function display_blocking_page() {
1398
        global $PERF;
1399
 
1400
        $page = self::get_locked_page_at($PERF->sessionlock['start']);
1401
        $output = "Script ".me()." was blocked for ";
1402
        $output .= number_format($PERF->sessionlock['wait'], 3);
1403
        if ($page != null) {
1404
            $output .= " second(s) by script: ";
1405
            $output .= $page['url'];
1406
        } else {
1407
            $output .= " second(s) by an unknown script.";
1408
        }
1409
 
1410
        return $output;
1411
    }
1412
 
1413
    /**
1414
     * Get session lock info of the current page.
1415
     *
1416
     * @return array
1417
     */
1418
    public static function get_session_lock_info() {
1419
        global $PERF;
1420
 
1421
        if (!isset($PERF->sessionlock)) {
1422
            return null;
1423
        }
1424
        return $PERF->sessionlock;
1425
    }
1426
 
1427
    /**
1428
     * Display debugging info about slow and blocked script.
1429
     */
1430
    public static function sessionlock_debugging() {
1431
        global $CFG, $PERF;
1432
 
1433
        if (!empty($CFG->debugsessionlock)) {
1434
            if (isset($PERF->sessionlock['held']) && $PERF->sessionlock['held'] > $CFG->debugsessionlock) {
1435
                debugging("Script ".me()." locked the session for ".number_format($PERF->sessionlock['held'], 3)
1436
                ." seconds, it should close the session using \core\session\manager::write_close().", DEBUG_NORMAL);
1437
            }
1438
 
1439
            if (isset($PERF->sessionlock['wait']) && $PERF->sessionlock['wait'] > $CFG->debugsessionlock) {
1440
                $output = self::display_blocking_page();
1441
                debugging($output, DEBUG_DEVELOPER);
1442
            }
1443
        }
1444
    }
1445
 
1446
    /**
1447
     * Compares two arrays and outputs the difference.
1448
     *
1449
     * Note - checking between objects and array type is only done at the top level.
1450
     * Any changes in types below the top level will not be detected.
1451
     * However, if their values are the same, they will be treated as equal.
1452
     *
1453
     * Any changes, such as removals, edits or additions will be detected.
1454
     *
1455
     * @param array $previous
1456
     * @param array $current
1457
     * @return array
1458
     */
1459
    private static function array_session_diff(array $previous, array $current): array {
1460
        // To use array_udiff_uassoc, the first array must have the most keys; this ensures every key is checked.
1461
        // To do this, we first need to sort them by the length of their keys.
1462
        $arrays = [$current, $previous];
1463
 
1464
        // Sort them by the length of their keys.
1465
        usort($arrays, function ($a, $b) {
1466
            return count(array_keys($b)) - count(array_keys($a));
1467
        });
1468
 
1469
        // The largest is the first value in the $arrays, after sorting.
1470
        // The smallest is then the last one.
1471
        // If they are the same size, it does not matter which is which.
1472
        $largest = $arrays[0];
1473
        $smallest = $arrays[1];
1474
 
1475
        // Defines a function that casts the values to arrays.
1476
        // This is so the properties are compared, instead any object's identities.
1477
        $casttoarray = function ($value) {
1478
            return json_decode(json_encode($value), true);
1479
        };
1480
 
1481
        // Defines a function that compares all keys by their string value.
1482
        $keycompare = function ($a, $b) {
1483
            return strcmp($a, $b);
1484
        };
1485
 
1486
        // Defines a function that compares all values by first their type, and then their values.
1487
        // If the value contains any objects, they are cast to arrays before comparison.
1488
        $valcompare = function ($a, $b) use ($casttoarray) {
1489
            // First compare type.
1490
            // If they are not the same type, they are definitely not the same.
1491
            // Note we do not check types recursively.
1492
            if (gettype($a) !== gettype($b)) {
1493
                return 1;
1494
            }
1495
 
1496
            // Next compare value. Cast any objects to arrays to compare their properties,
1497
            // instead of the identitiy of the object itself.
1498
            $v1 = $casttoarray($a);
1499
            $v2 = $casttoarray($b);
1500
 
1501
            if ($v1 !== $v2) {
1502
                return 1;
1503
            }
1504
 
1505
            return 0;
1506
        };
1507
 
1508
        // Apply the comparison functions to the two given session arrays,
1509
        // making sure to use the largest array first, so that all keys are considered.
1510
        return array_udiff_uassoc($largest, $smallest, $valcompare, $keycompare);
1511
    }
1512
}