2 // This file is part of Moodle - http://moodle.org/
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.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Session manager class.
21 * @copyright 2013 Petr Skoda {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 namespace core\session;
27 defined('MOODLE_INTERNAL') || die();
30 * Session manager, this is the public Moodle API for sessions.
32 * Following PHP functions MUST NOT be used directly:
33 * - session_start() - not necessary, lib/setup.php starts session automatically,
34 * use define('NO_MOODLE_COOKIE', true) if session not necessary.
35 * - session_write_close() - use \core\session\manager::write_close() instead.
36 * - session_destroy() - use require_logout() instead.
39 * @copyright 2013 Petr Skoda {@link http://skodak.org}
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 /** @var handler $handler active session handler instance */
44 protected static $handler;
46 /** @var bool $sessionactive Is the session active? */
47 protected static $sessionactive = null;
52 * Note: This is intended to be called only from lib/setup.php!
54 public static function start() {
57 if (isset(self::$sessionactive)) {
58 debugging('Session was already started!', DEBUG_DEVELOPER);
64 // Init the session handler only if everything initialised properly in lib/setup.php file
65 // and the session is actually required.
66 if (empty($DB) or empty($CFG->version) or !defined('NO_MOODLE_COOKIES') or NO_MOODLE_COOKIES or CLI_SCRIPT) {
67 self::$sessionactive = false;
68 self::init_empty_session();
73 self::$handler->init();
74 self::prepare_cookies();
75 $isnewsession = empty($_COOKIE[session_name()]);
77 if (!self::$handler->start()) {
78 // Could not successfully start/recover session.
79 throw new \core\session\exception(get_string('servererror'));
82 self::initialise_user_session($isnewsession);
83 self::check_security();
85 // Link global $USER and $SESSION,
86 // this is tricky because PHP does not allow references to references
87 // and global keyword uses internally once reference to the $GLOBALS array.
88 // The solution is to use the $GLOBALS['USER'] and $GLOBALS['$SESSION']
89 // as the main storage of data and put references to $_SESSION.
90 $GLOBALS['USER'] = $_SESSION['USER'];
91 $_SESSION['USER'] =& $GLOBALS['USER'];
92 $GLOBALS['SESSION'] = $_SESSION['SESSION'];
93 $_SESSION['SESSION'] =& $GLOBALS['SESSION'];
95 } catch (\Exception $ex) {
96 self::init_empty_session();
97 self::$sessionactive = false;
101 self::$sessionactive = true;
105 * Returns current page performance info.
107 * @return array perf info
109 public static function get_performance_info() {
114 self::load_handler();
115 $size = display_size(strlen(session_encode()));
116 $handler = get_class(self::$handler);
119 $info['size'] = $size;
120 $info['html'] = "<span class=\"sessionsize\">Session ($handler): $size</span> ";
121 $info['txt'] = "Session ($handler): $size ";
127 * Create handler instance.
129 protected static function load_handler() {
132 if (self::$handler) {
136 // Find out which handler to use.
138 $class = '\core\session\file';
140 } else if (!empty($CFG->session_handler_class)) {
141 $class = $CFG->session_handler_class;
143 } else if (!empty($CFG->dbsessions) and $DB->session_lock_supported()) {
144 $class = '\core\session\database';
147 $class = '\core\session\file';
149 self::$handler = new $class();
153 * Empty current session, fill it with not-logged-in user info.
155 * This is intended for installation scripts, unit tests and other
156 * special areas. Do NOT use for logout and session termination
157 * in normal requests!
159 public static function init_empty_session() {
162 if (isset($GLOBALS['SESSION']->notifications)) {
163 // Backup notifications. These should be preserved across session changes until the user fetches and clears them.
164 $notifications = $GLOBALS['SESSION']->notifications;
166 $GLOBALS['SESSION'] = new \stdClass();
168 $GLOBALS['USER'] = new \stdClass();
169 $GLOBALS['USER']->id = 0;
171 if (!empty($notifications)) {
172 // Restore notifications.
173 $GLOBALS['SESSION']->notifications = $notifications;
175 if (isset($CFG->mnet_localhost_id)) {
176 $GLOBALS['USER']->mnethostid = $CFG->mnet_localhost_id;
178 // Not installed yet, the future host id will be most probably 1.
179 $GLOBALS['USER']->mnethostid = 1;
182 // Link global $USER and $SESSION.
184 $_SESSION['USER'] =& $GLOBALS['USER'];
185 $_SESSION['SESSION'] =& $GLOBALS['SESSION'];
189 * Make sure all cookie and session related stuff is configured properly before session start.
191 protected static function prepare_cookies() {
194 $cookiesecure = is_moodle_cookie_secure();
196 if (!isset($CFG->cookiehttponly)) {
197 $CFG->cookiehttponly = 0;
200 // Set sessioncookie variable if it isn't already.
201 if (!isset($CFG->sessioncookie)) {
202 $CFG->sessioncookie = '';
204 $sessionname = 'MoodleSession'.$CFG->sessioncookie;
206 // Make sure cookie domain makes sense for this wwwroot.
207 if (!isset($CFG->sessioncookiedomain)) {
208 $CFG->sessioncookiedomain = '';
209 } else if ($CFG->sessioncookiedomain !== '') {
210 $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
211 if ($CFG->sessioncookiedomain !== $host) {
212 if (substr($CFG->sessioncookiedomain, 0, 1) === '.') {
213 if (!preg_match('|^.*'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
214 // Invalid domain - it must be end part of host.
215 $CFG->sessioncookiedomain = '';
218 if (!preg_match('|^.*\.'.preg_quote($CFG->sessioncookiedomain, '|').'$|', $host)) {
219 // Invalid domain - it must be end part of host.
220 $CFG->sessioncookiedomain = '';
226 // Make sure the cookiepath is valid for this wwwroot or autodetect if not specified.
227 if (!isset($CFG->sessioncookiepath)) {
228 $CFG->sessioncookiepath = '';
230 if ($CFG->sessioncookiepath !== '/') {
231 $path = parse_url($CFG->wwwroot, PHP_URL_PATH).'/';
232 if ($CFG->sessioncookiepath === '') {
233 $CFG->sessioncookiepath = $path;
235 if (strpos($path, $CFG->sessioncookiepath) !== 0 or substr($CFG->sessioncookiepath, -1) !== '/') {
236 $CFG->sessioncookiepath = $path;
241 // Discard session ID from POST, GET and globals to tighten security,
242 // this is session fixation prevention.
243 unset($GLOBALS[$sessionname]);
244 unset($_GET[$sessionname]);
245 unset($_POST[$sessionname]);
246 unset($_REQUEST[$sessionname]);
248 // Compatibility hack for non-browser access to our web interface.
249 if (!empty($_COOKIE[$sessionname]) && $_COOKIE[$sessionname] == "deleted") {
250 unset($_COOKIE[$sessionname]);
253 // Set configuration.
254 session_name($sessionname);
255 session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $cookiesecure, $CFG->cookiehttponly);
256 ini_set('session.use_trans_sid', '0');
257 ini_set('session.use_only_cookies', '1');
258 ini_set('session.hash_function', '0'); // For now MD5 - we do not have room for sha-1 in sessions table.
259 ini_set('session.use_strict_mode', '0'); // We have custom protection in session init.
260 ini_set('session.serialize_handler', 'php'); // We can move to 'php_serialize' after we require PHP 5.5.4 form Moodle.
262 // Moodle does normal session timeouts, this is for leftovers only.
263 ini_set('session.gc_probability', 1);
264 ini_set('session.gc_divisor', 1000);
265 ini_set('session.gc_maxlifetime', 60*60*24*4);
269 * Initialise $_SESSION, handles google access
270 * and sets up not-logged-in user properly.
272 * WARNING: $USER and $SESSION are set up later, do not use them yet!
274 * @param bool $newsid is this a new session in first http request?
276 protected static function initialise_user_session($newsid) {
281 // No session, very weird.
282 error_log('Missing session ID, session not started!');
283 self::init_empty_session();
287 if (!$record = $DB->get_record('sessions', array('sid'=>$sid), 'id, sid, state, userid, lastip, timecreated, timemodified')) {
289 if (!empty($_SESSION['USER']->id)) {
290 // This should not happen, just log it, we MUST not produce any output here!
291 error_log("Cannot find session record $sid for user ".$_SESSION['USER']->id.", creating new session.");
293 // Prevent session fixation attacks.
294 session_regenerate_id(true);
300 if (isset($_SESSION['USER']->id)) {
301 if (!empty($_SESSION['USER']->realuser)) {
302 $userid = $_SESSION['USER']->realuser;
304 $userid = $_SESSION['USER']->id;
307 // Verify timeout first.
308 $maxlifetime = $CFG->sessiontimeout;
310 if (isguestuser($userid) or empty($userid)) {
311 // Ignore guest and not-logged in timeouts, there is very little risk here.
314 } else if ($record->timemodified < time() - $maxlifetime) {
316 $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
317 foreach ($authsequence as $authname) {
318 $authplugin = get_auth_plugin($authname);
319 if ($authplugin->ignore_timeout_hook($_SESSION['USER'], $record->sid, $record->timecreated, $record->timemodified)) {
327 session_regenerate_id(true);
329 $DB->delete_records('sessions', array('id'=>$record->id));
332 // Update session tracking record.
334 $update = new \stdClass();
337 if ($record->userid != $userid) {
338 $update->userid = $record->userid = $userid;
342 $ip = getremoteaddr();
343 if ($record->lastip != $ip) {
344 $update->lastip = $record->lastip = $ip;
348 $updatefreq = empty($CFG->session_update_timemodified_frequency) ? 20 : $CFG->session_update_timemodified_frequency;
350 if ($record->timemodified == $record->timecreated) {
351 // Always do first update of existing record.
352 $update->timemodified = $record->timemodified = time();
355 } else if ($record->timemodified < time() - $updatefreq) {
356 // Update the session modified flag only once every 20 seconds.
357 $update->timemodified = $record->timemodified = time();
362 $update->id = $record->id;
363 $DB->update_record('sessions', $update);
370 // This happens when people switch session handlers...
371 session_regenerate_id(true);
373 $DB->delete_records('sessions', array('id'=>$record->id));
379 if (!isset($_SESSION['SESSION'])) {
380 $_SESSION['SESSION'] = new \stdClass();
388 if (!empty($CFG->opentogoogle)) {
389 if (\core_useragent::is_web_crawler()) {
390 $user = guest_user();
392 $referer = get_local_referer(false);
393 if (!empty($CFG->guestloginbutton) and !$user and !empty($referer)) {
394 // Automatically log in users coming from search engine results.
395 if (strpos($referer, 'google') !== false ) {
396 $user = guest_user();
397 } else if (strpos($referer, 'altavista') !== false ) {
398 $user = guest_user();
403 // Setup $USER and insert the session tracking record.
405 self::set_user($user);
406 self::add_session_record($user->id);
408 self::init_empty_session();
409 self::add_session_record(0);
413 $_SESSION['SESSION']->has_timed_out = true;
418 * Insert new empty session record.
420 * @return \stdClass the new record
422 protected static function add_session_record($userid) {
424 $record = new \stdClass();
426 $record->sid = session_id();
427 $record->sessdata = null;
428 $record->userid = $userid;
429 $record->timecreated = $record->timemodified = time();
430 $record->firstip = $record->lastip = getremoteaddr();
432 $record->id = $DB->insert_record('sessions', $record);
438 * Do various session security checks.
440 * WARNING: $USER and $SESSION are set up later, do not use them yet!
441 * @throws \core\session\exception
443 protected static function check_security() {
446 if (!empty($_SESSION['USER']->id) and !empty($CFG->tracksessionip)) {
447 // Make sure current IP matches the one for this session.
448 $remoteaddr = getremoteaddr();
450 if (empty($_SESSION['USER']->sessionip)) {
451 $_SESSION['USER']->sessionip = $remoteaddr;
454 if ($_SESSION['USER']->sessionip != $remoteaddr) {
455 // This is a security feature - terminate the session in case of any doubt.
456 self::terminate_current();
457 throw new exception('sessionipnomatch2', 'error');
463 * Login user, to be called from complete_user_login() only.
464 * @param \stdClass $user
466 public static function login_user(\stdClass $user) {
469 // Regenerate session id and delete old session,
470 // this helps prevent session fixation attacks from the same domain.
473 session_regenerate_id(true);
474 $DB->delete_records('sessions', array('sid'=>$sid));
475 self::add_session_record($user->id);
477 // Let enrol plugins deal with new enrolments if necessary.
478 enrol_check_plugins($user);
480 // Setup $USER object.
481 self::set_user($user);
485 * Terminate current user session.
488 public static function terminate_current() {
491 if (!self::$sessionactive) {
492 self::init_empty_session();
493 self::$sessionactive = false;
498 $DB->delete_records('external_tokens', array('sid'=>session_id(), 'tokentype'=>EXTERNAL_TOKEN_EMBEDDED));
499 } catch (\Exception $ignored) {
500 // Probably install/upgrade - ignore this problem.
503 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line).
506 if (headers_sent($file, $line)) {
507 error_log('Cannot terminate session properly - headers were already sent in file: '.$file.' on line '.$line);
510 // Write new empty session and make sure the old one is deleted.
512 session_regenerate_id(true);
513 $DB->delete_records('sessions', array('sid'=>$sid));
514 self::init_empty_session();
515 self::add_session_record($_SESSION['USER']->id); // Do not use $USER here because it may not be set up yet.
516 session_write_close();
517 self::$sessionactive = false;
521 * No more changes in session expected.
522 * Unblocks the sessions, other scripts may start executing in parallel.
524 public static function write_close() {
525 if (version_compare(PHP_VERSION, '5.6.0', '>=')) {
526 // More control over whether session data
527 // is persisted or not.
528 if (self::$sessionactive && session_id()) {
529 // Write session and release lock only if
530 // indication session start was clean.
531 session_write_close();
533 // Otherwise, if possibile lock exists want
534 // to clear it, but do not write session.
538 // Any indication session was started, attempt
540 if (self::$sessionactive || session_id()) {
541 session_write_close();
544 self::$sessionactive = false;
548 * Does the PHP session with given id exist?
550 * The session must exist both in session table and actual
551 * session backend and the session must not be timed out.
553 * Timeout evaluation is simplified, the auth hooks are not executed.
558 public static function session_exists($sid) {
561 if (empty($CFG->version)) {
562 // Not installed yet, do not try to access database.
566 // Note: add sessions->state checking here if it gets implemented.
567 if (!$record = $DB->get_record('sessions', array('sid' => $sid), 'id, userid, timemodified')) {
571 if (empty($record->userid) or isguestuser($record->userid)) {
572 // Ignore guest and not-logged-in timeouts, there is very little risk here.
573 } else if ($record->timemodified < time() - $CFG->sessiontimeout) {
577 // There is no need the existence of handler storage in public API.
578 self::load_handler();
579 return self::$handler->session_exists($sid);
583 * Fake last access for given session, this prevents session timeout.
586 public static function touch_session($sid) {
589 // Timeouts depend on core sessions table only, no need to update anything in external stores.
591 $sql = "UPDATE {sessions} SET timemodified = :now WHERE sid = :sid";
592 $DB->execute($sql, array('now'=>time(), 'sid'=>$sid));
596 * Terminate all sessions unconditionally.
598 public static function kill_all_sessions() {
601 self::terminate_current();
603 self::load_handler();
604 self::$handler->kill_all_sessions();
607 $DB->delete_records('sessions');
608 } catch (\dml_exception $ignored) {
609 // Do not show any warnings - might be during upgrade/installation.
614 * Terminate give session unconditionally.
617 public static function kill_session($sid) {
620 self::load_handler();
622 if ($sid === session_id()) {
626 self::$handler->kill_session($sid);
628 $DB->delete_records('sessions', array('sid'=>$sid));
632 * Terminate all sessions of given user unconditionally.
634 * @param string $keepsid keep this sid if present
636 public static function kill_user_sessions($userid, $keepsid = null) {
639 $sessions = $DB->get_records('sessions', array('userid'=>$userid), 'id DESC', 'id, sid');
640 foreach ($sessions as $session) {
641 if ($keepsid and $keepsid === $session->sid) {
644 self::kill_session($session->sid);
649 * Terminate other sessions of current user depending
650 * on $CFG->limitconcurrentlogins restriction.
652 * This is expected to be called right after complete_user_login().
655 * * Do not use from SSO auth plugins, this would not work.
656 * * Do not use from web services because they do not have sessions.
659 * @param string $sid session id to be always keep, usually the current one
662 public static function apply_concurrent_login_limit($userid, $sid = null) {
665 // NOTE: the $sid parameter is here mainly to allow testing,
666 // in most cases it should be current session id.
668 if (isguestuser($userid) or empty($userid)) {
669 // This applies to real users only!
673 if (empty($CFG->limitconcurrentlogins) or $CFG->limitconcurrentlogins < 0) {
677 $count = $DB->count_records('sessions', array('userid' => $userid));
679 if ($count <= $CFG->limitconcurrentlogins) {
684 $select = "userid = :userid";
685 $params = array('userid' => $userid);
687 if ($DB->record_exists('sessions', array('sid' => $sid, 'userid' => $userid))) {
688 $select .= " AND sid <> :sid";
689 $params['sid'] = $sid;
694 $sessions = $DB->get_records_select('sessions', $select, $params, 'timecreated DESC', 'id, sid');
695 foreach ($sessions as $session) {
697 if ($i <= $CFG->limitconcurrentlogins) {
700 self::kill_session($session->sid);
707 * @param \stdClass $user record
709 public static function set_user(\stdClass $user) {
710 $GLOBALS['USER'] = $user;
711 unset($GLOBALS['USER']->description); // Conserve memory.
712 unset($GLOBALS['USER']->password); // Improve security.
713 if (isset($GLOBALS['USER']->lang)) {
714 // Make sure it is a valid lang pack name.
715 $GLOBALS['USER']->lang = clean_param($GLOBALS['USER']->lang, PARAM_LANG);
718 // Relink session with global $USER just in case it got unlinked somehow.
719 $_SESSION['USER'] =& $GLOBALS['USER'];
726 * Periodic timed-out session cleanup.
728 public static function gc() {
731 // This may take a long time...
732 \core_php_time_limit::raise();
734 $maxlifetime = $CFG->sessiontimeout;
737 // Kill all sessions of deleted and suspended users without any hesitation.
738 $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE deleted <> 0 OR suspended <> 0)", array(), 'id DESC', 'id, sid');
739 foreach ($rs as $session) {
740 self::kill_session($session->sid);
744 // Kill sessions of users with disabled plugins.
745 $auth_sequence = get_enabled_auth_plugins(true);
746 $auth_sequence = array_flip($auth_sequence);
747 unset($auth_sequence['nologin']); // No login means user cannot login.
748 $auth_sequence = array_flip($auth_sequence);
750 list($notplugins, $params) = $DB->get_in_or_equal($auth_sequence, SQL_PARAMS_QM, '', false);
751 $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE auth $notplugins)", $params, 'id DESC', 'id, sid');
752 foreach ($rs as $session) {
753 self::kill_session($session->sid);
757 // Now get a list of time-out candidates - real users only.
758 $sql = "SELECT u.*, s.sid, s.timecreated AS s_timecreated, s.timemodified AS s_timemodified
760 JOIN {sessions} s ON s.userid = u.id
761 WHERE s.timemodified < :purgebefore AND u.id <> :guestid";
762 $params = array('purgebefore' => (time() - $maxlifetime), 'guestid'=>$CFG->siteguest);
764 $authplugins = array();
765 foreach ($auth_sequence as $authname) {
766 $authplugins[$authname] = get_auth_plugin($authname);
768 $rs = $DB->get_recordset_sql($sql, $params);
769 foreach ($rs as $user) {
770 foreach ($authplugins as $authplugin) {
771 /** @var \auth_plugin_base $authplugin*/
772 if ($authplugin->ignore_timeout_hook($user, $user->sid, $user->s_timecreated, $user->s_timemodified)) {
776 self::kill_session($user->sid);
780 // Delete expired sessions for guest user account, give them larger timeout, there is no security risk here.
781 $params = array('purgebefore' => (time() - ($maxlifetime * 5)), 'guestid'=>$CFG->siteguest);
782 $rs = $DB->get_recordset_select('sessions', 'userid = :guestid AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
783 foreach ($rs as $session) {
784 self::kill_session($session->sid);
788 // Delete expired sessions for userid = 0 (not logged in), better kill them asap to release memory.
789 $params = array('purgebefore' => (time() - $maxlifetime));
790 $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid');
791 foreach ($rs as $session) {
792 self::kill_session($session->sid);
796 // Cleanup letfovers from the first browser access because it may set multiple cookies and then use only one.
797 $params = array('purgebefore' => (time() - 60*3));
798 $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified = timecreated AND timemodified < :purgebefore', $params, 'id ASC', 'id, sid');
799 foreach ($rs as $session) {
800 self::kill_session($session->sid);
804 } catch (\Exception $ex) {
805 debugging('Error gc-ing sessions: '.$ex->getMessage(), DEBUG_NORMAL, $ex->getTrace());
810 * Is current $USER logged-in-as somebody else?
813 public static function is_loggedinas() {
814 return !empty($GLOBALS['USER']->realuser);
818 * Returns the $USER object ignoring current login-as session
819 * @return \stdClass user object
821 public static function get_realuser() {
822 if (self::is_loggedinas()) {
823 return $_SESSION['REALUSER'];
825 return $GLOBALS['USER'];
830 * Login as another user - no security checks here.
832 * @param \context $context
835 public static function loginas($userid, \context $context) {
838 if (self::is_loggedinas()) {
842 // Switch to fresh new $_SESSION.
844 $_SESSION['REALSESSION'] = clone($GLOBALS['SESSION']);
845 $GLOBALS['SESSION'] = new \stdClass();
846 $_SESSION['SESSION'] =& $GLOBALS['SESSION'];
848 // Create the new $USER object with all details and reload needed capabilities.
849 $_SESSION['REALUSER'] = clone($GLOBALS['USER']);
850 $user = get_complete_user_data('id', $userid);
851 $user->realuser = $_SESSION['REALUSER']->id;
852 $user->loginascontext = $context;
854 // Let enrol plugins deal with new enrolments if necessary.
855 enrol_check_plugins($user);
857 // Create event before $USER is updated.
858 $event = \core\event\user_loggedinas::create(
860 'objectid' => $USER->id,
861 'context' => $context,
862 'relateduserid' => $userid,
864 'originalusername' => fullname($USER, true),
865 'loggedinasusername' => fullname($user, true)
869 // Set up global $USER.
870 \core\session\manager::set_user($user);
875 * Add a JS session keepalive to the page.
877 * A JS session keepalive script will be called to update the session modification time every $frequency seconds.
879 * Upon failure, the specified error message will be shown to the user.
881 * @param string $identifier The string identifier for the message to show on failure.
882 * @param string $component The string component for the message to show on failure.
883 * @param int $frequency The update frequency in seconds.
884 * @throws coding_exception IF the frequency is longer than the session lifetime.
886 public static function keepalive($identifier = 'sessionerroruser', $component = 'error', $frequency = null) {
890 if ($frequency > $CFG->sessiontimeout) {
891 // Sanity check the frequency.
892 throw new \coding_exception('Keepalive frequency is longer than the session lifespan.');
895 // A frequency of sessiontimeout / 3 allows for one missed request whilst still preserving the session.
896 $frequency = $CFG->sessiontimeout / 3;
899 // Add the session keepalive script to the list of page output requirements.
900 $sessionkeepaliveurl = new \moodle_url('/lib/sessionkeepalive_ajax.php');
901 $PAGE->requires->string_for_js($identifier, $component);
902 $PAGE->requires->yui_module('moodle-core-checknet', 'M.core.checknet.init', array(array(
903 // The JS config takes this is milliseconds rather than seconds.
904 'frequency' => $frequency * 1000,
905 'message' => array($identifier, $component),
906 'uri' => $sessionkeepaliveurl->out(),