Proyectos de Subversion Moodle

Rev

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