Added headers for javascript dump
[moodle.git] / lib / sessionlib.php
CommitLineData
57f7b7ce 1<?php //$Id$
2
542797b4 3/**
4 * Factory method returning moodle_session object.
5 * @return moodle_session
6 */
b7b64ff2 7function session_get_instance() {
5e9dd017 8 global $CFG, $DB;
0a2092a3 9
0ad6b20c 10 static $session = null;
11
12 if (is_null($session)) {
e8656bef 13 if (empty($CFG->sessiontimeout)) {
14 $CFG->sessiontimeout = 7200;
15 }
16
ad76d184 17 if (defined('SESSION_CUSTOM_CLASS')) {
e8656bef 18 // this is a hook for webservices, key based login, etc.
0a2092a3 19 if (defined('SESSION_CUSTOM_FILE')) {
20 require_once($CFG->dirroot.SESSION_CUSTOM_FILE);
21 }
ad76d184 22 $session_class = SESSION_CUSTOM_CLASS;
0a2092a3 23 $session = new $session_class();
24
35d6a2a4 25 } else if ((!isset($CFG->dbsessions) or $CFG->dbsessions) and $DB->session_lock_supported()) {
0a2092a3 26 // default recommended session type
27 $session = new database_session();
28
29 } else {
30 // legacy limited file based storage - some features and auth plugins will not work, sorry
31 $session = new legacy_file_session();
32 }
0ad6b20c 33 }
34
35 return $session;
36}
37
0a2092a3 38interface moodle_session {
56949c17 39 /**
40 * Terminate current session
41 * @return void
42 */
43 public function terminate_current();
44
45 /**
46 * No more changes in session expected.
47 * Unblocks the sesions, other scripts may start executing in parallel.
48 * @return void
49 */
50 public function write_close();
0a2092a3 51}
52
57f7b7ce 53/**
54 * Class handling all session and cookies related stuff.
55 */
0a2092a3 56abstract class session_stub implements moodle_session {
3b50631d 57 protected $justloggedout;
58
b7b64ff2 59 public function __construct() {
57f7b7ce 60 global $CFG;
57f7b7ce 61
0a2092a3 62 if (!defined('NO_MOODLE_COOKIES')) {
64d69e96 63 if (empty($CFG->version) or $CFG->version < 2009011600) {
64 // no session before sessions table gets greated
65 define('NO_MOODLE_COOKIES', true);
66 } else if (CLI_SCRIPT) {
0a2092a3 67 // CLI scripts can not have session
68 define('NO_MOODLE_COOKIES', true);
69 } else {
70 define('NO_MOODLE_COOKIES', false);
71 }
57f7b7ce 72 }
73
0ad6b20c 74 if (NO_MOODLE_COOKIES) {
0a2092a3 75 // session not used at all
45871c08 76 $CFG->usesid = 0;
0a2092a3 77
0ad6b20c 78 $_SESSION = array();
79 $_SESSION['SESSION'] = new object();
0a2092a3 80 $_SESSION['USER'] = new object();
0ad6b20c 81
82 } else {
0a2092a3 83 $this->prepare_cookies();
84 $this->init_session_storage();
85
35d6a2a4 86 $newsession = empty($_COOKIE['MoodleSession'.$CFG->sessioncookie]);
87
88 if (!empty($CFG->usesid) && $newsession) {
0a2092a3 89 sid_start_ob();
45871c08 90 } else {
91 $CFG->usesid = 0;
92 ini_set('session.use_trans_sid', '0');
0a2092a3 93 }
94
57f7b7ce 95 session_name('MoodleSession'.$CFG->sessioncookie);
e6e13284 96 session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
64d69e96 97 session_start();
57f7b7ce 98 if (!isset($_SESSION['SESSION'])) {
99 $_SESSION['SESSION'] = new object();
3b50631d 100 if (!$newsession and !$this->justloggedout) {
35d6a2a4 101 $_SESSION['SESSION']->has_timed_out = true;
102 }
57f7b7ce 103 }
104 if (!isset($_SESSION['USER'])) {
105 $_SESSION['USER'] = new object();
106 }
57f7b7ce 107 }
57f7b7ce 108
b7b64ff2 109 $this->check_user_initialised();
9bda43e6 110
111 $this->check_security();
b7b64ff2 112 }
113
56949c17 114 /**
115 * Terminates active moodle session
116 */
117 public function terminate_current() {
118 global $CFG, $SESSION, $USER;
119
120 if (NO_MOODLE_COOKIES) {
121 return;
122 }
123
64d69e96 124 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
56949c17 125 $_SESSION = array();
35d6a2a4 126 $_SESSION['SESSION'] = new object();
127 $_SESSION['USER'] = new object();
128 $_SESSION['USER']->id = 0;
56949c17 129 if (isset($CFG->mnet_localhost_id)) {
35d6a2a4 130 $_SESSION['USER']->mnethostid = $CFG->mnet_localhost_id;
56949c17 131 }
35d6a2a4 132 $SESSION = $_SESSION['SESSION']; // this may not work properly
3b50631d 133 $USER = $_SESSION['USER']; // this may not work properly
35d6a2a4 134
56949c17 135 $file = null;
136 $line = null;
137 if (headers_sent($file, $line)) {
138 error_log('Can not terminate session properly - headers were already sent in file: '.$file.' on line '.$line);
139 }
140
64d69e96 141 // now let's try to get a new session id and delete the old one
3b50631d 142 $this->justloggedout = true;
143 session_regenerate_id(true);
144 $this->justloggedout = false;
145
64d69e96 146 // write the new session
35d6a2a4 147 session_write_close();
56949c17 148 }
149
150 /**
151 * No more changes in session expected.
152 * Unblocks the sesions, other scripts may start executing in parallel.
153 * @return void
154 */
155 public function write_close() {
156 if (NO_MOODLE_COOKIES) {
157 return;
158 }
159
160 session_write_close();
161 }
162
b7b64ff2 163 /**
dd9e22f8 164 * Initialise $USER object, handles google access
165 * and sets up not logged in user properly.
b7b64ff2 166 *
167 * @return void
168 */
169 protected function check_user_initialised() {
170 if (isset($_SESSION['USER']->id)) {
171 // already set up $USER
172 return;
173 }
174
175 $user = null;
176
177 if (!empty($CFG->opentogoogle) and !NO_MOODLE_COOKIES) {
178 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
179 // allow web spiders in as guest users
180 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
181 $user = guest_user();
182 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
183 $user = guest_user();
184 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
185 $user = guest_user();
186 } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
187 $user = guest_user();
188 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) { // MSN Search
189 $user = guest_user();
190 }
191 }
1b813f5c 192 if (!empty($CFG->guestloginbutton) and !$user and !empty($_SERVER['HTTP_REFERER'])) {
b7b64ff2 193 // automaticaly log in users coming from search engine results
194 if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
195 $user = guest_user();
196 } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
197 $user = guest_user();
198 }
199 }
200 }
201
202 if (!$user) {
203 $user = new object();
204 $user->id = 0; // to enable proper function of $CFG->notloggedinroleid hack
0ad6b20c 205 if (isset($CFG->mnet_localhost_id)) {
b7b64ff2 206 $user->mnethostid = $CFG->mnet_localhost_id;
0a2092a3 207 } else {
208 $user->mnethostid = 1;
57f7b7ce 209 }
210 }
b7b64ff2 211 session_set_user($user);
57f7b7ce 212 }
213
9bda43e6 214 /**
215 * Does various session security checks
216 * @global void
217 */
93f66983 218 protected function check_security() {
219 global $CFG;
220
0a2092a3 221 if (NO_MOODLE_COOKIES) {
222 return;
223 }
224
9bda43e6 225 if (!empty($_SESSION['USER']->id) and !empty($CFG->tracksessionip)) {
226 /// Make sure current IP matches the one for this session
93f66983 227 $remoteaddr = getremoteaddr();
228
229 if (empty($_SESSION['USER']->sessionip)) {
230 $_SESSION['USER']->sessionip = $remoteaddr;
231 }
232
233 if ($_SESSION['USER']->sessionip != $remoteaddr) {
9bda43e6 234 // this is a security feature - terminate the session in case of any doubt
56949c17 235 $this->terminate_current();
9bda43e6 236 print_error('sessionipnomatch2', 'error');
93f66983 237 }
238 }
93f66983 239 }
240
57f7b7ce 241 /**
242 * Prepare cookies and varions system settings
243 */
b7b64ff2 244 protected function prepare_cookies() {
0a2092a3 245 global $CFG;
57f7b7ce 246
11e7b506 247 if (!isset($CFG->cookiesecure) or (strpos($CFG->wwwroot, 'https://') !== 0 and empty($CFG->sslproxy))) {
57f7b7ce 248 $CFG->cookiesecure = 0;
249 }
250
251 if (!isset($CFG->cookiehttponly)) {
252 $CFG->cookiehttponly = 0;
253 }
254
255 /// Set sessioncookie and sessioncookiepath variable if it isn't already
256 if (!isset($CFG->sessioncookie)) {
257 $CFG->sessioncookie = '';
258 }
e6e13284 259 if (!isset($CFG->sessioncookiedomain)) {
260 $CFG->sessioncookiedomain = '';
261 }
57f7b7ce 262 if (!isset($CFG->sessioncookiepath)) {
263 $CFG->sessioncookiepath = '/';
264 }
265
266 //discard session ID from POST, GET and globals to tighten security,
267 //this session fixation prevention can not be used in cookieless mode
268 if (empty($CFG->usesid)) {
269 unset(${'MoodleSession'.$CFG->sessioncookie});
270 unset($_GET['MoodleSession'.$CFG->sessioncookie]);
271 unset($_POST['MoodleSession'.$CFG->sessioncookie]);
b7b64ff2 272 unset($_REQUEST['MoodleSession'.$CFG->sessioncookie]);
57f7b7ce 273 }
274 //compatibility hack for Moodle Cron, cookies not deleted, but set to "deleted" - should not be needed with NO_MOODLE_COOKIES in cron.php now
275 if (!empty($_COOKIE['MoodleSession'.$CFG->sessioncookie]) && $_COOKIE['MoodleSession'.$CFG->sessioncookie] == "deleted") {
276 unset($_COOKIE['MoodleSession'.$CFG->sessioncookie]);
277 }
57f7b7ce 278 }
279
280 /**
281 * Inits session storage.
282 */
f61a032a 283 protected abstract function init_session_storage();
f61a032a 284}
285
286/**
287 * Legacy moodle sessions stored in files, not recommended any more.
288 */
0a2092a3 289class legacy_file_session extends session_stub {
b7b64ff2 290 protected function init_session_storage() {
57f7b7ce 291 global $CFG;
292
0a2092a3 293 ini_set('session.save_handler', 'files');
294
f61a032a 295 // Some distros disable GC by setting probability to 0
296 // overriding the PHP default of 1
297 // (gc_probability is divided by gc_divisor, which defaults to 1000)
298 if (ini_get('session.gc_probability') == 0) {
299 ini_set('session.gc_probability', 1);
300 }
57f7b7ce 301
3b1a9849 302 ini_set('session.gc_maxlifetime', $CFG->sessiontimeout);
57f7b7ce 303
f61a032a 304 if (!file_exists($CFG->dataroot .'/sessions')) {
305 make_upload_directory('sessions');
306 }
307 if (!is_writable($CFG->dataroot .'/sessions/')) {
308 print_error('sessionnotwritable', 'error');
57f7b7ce 309 }
f61a032a 310 ini_set('session.save_path', $CFG->dataroot .'/sessions');
311 }
312}
313
314/**
315 * Recommended moodle session storage.
316 */
0a2092a3 317class database_session extends session_stub {
318 protected $record = null;
319 protected $database = null;
320
dd9e22f8 321 public function __construct() {
322 global $DB;
323 $this->database = $DB;
324 parent::__construct();
325 }
326
f61a032a 327 protected function init_session_storage() {
328 global $CFG;
329
dd9e22f8 330 // gc only from CRON - individual user timeouts now checked during each access
331 ini_set('session.gc_probability', 0);
0a2092a3 332
ef159e5f 333 ini_set('session.gc_maxlifetime', $CFG->sessiontimeout);
0a2092a3 334
335 $result = session_set_save_handler(array($this, 'handler_open'),
336 array($this, 'handler_close'),
337 array($this, 'handler_read'),
338 array($this, 'handler_write'),
339 array($this, 'handler_destroy'),
340 array($this, 'handler_gc'));
341 if (!$result) {
eee3bd3f 342 print_error('dbsessionhandlerproblem', 'error');
0a2092a3 343 }
344 }
345
dd9e22f8 346 public function handler_open($save_path, $session_name) {
0a2092a3 347 return true;
348 }
349
350 public function handler_close() {
3b50631d 351 if (isset($this->record->id)) {
352 $this->database->release_session_lock($this->record->id);
353 }
0a2092a3 354 $this->record = null;
355 return true;
356 }
357
358 public function handler_read($sid) {
359 global $CFG;
360
0a2092a3 361 if ($this->record and $this->record->sid != $sid) {
362 error_log('Weird error reading session - mismatched sid');
363 return '';
364 }
365
366 try {
3b1a9849 367 if ($record = $this->database->get_record('sessions', array('sid'=>$sid))) {
368 $this->database->get_session_lock($record->id);
dd9e22f8 369
3b1a9849 370 } else {
0a2092a3 371 $record = new object();
372 $record->state = 0;
373 $record->sid = $sid;
374 $record->sessdata = null;
17d93489 375 $record->sessdatahash = null;
0a2092a3 376 $record->userid = 0;
377 $record->timecreated = $record->timemodified = time();
378 $record->firstip = $record->lastip = getremoteaddr();
3b50631d 379 $record->id = $this->database->insert_record_raw('sessions', $record);
0a2092a3 380
3b1a9849 381 $this->database->get_session_lock($record->id);
0a2092a3 382 }
383 } catch (dml_exception $ex) {
64d69e96 384 error_log('Can not read or insert database sessions');
0a2092a3 385 return '';
386 }
387
3b1a9849 388 // verify timeout
389 if ($record->timemodified + $CFG->sessiontimeout < time()) {
dd9e22f8 390 $ignoretimeout = false;
88fdd846 391 if (!empty($record->userid)) { // skips not logged in
392 if ($user = $this->database->get_record('user', array('id'=>$record->userid))) {
393 if ($user->username !== 'guest') {
394 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
395 foreach($authsequence as $authname) {
396 $authplugin = get_auth_plugin($authname);
e8656bef 397 if ($authplugin->ignore_timeout_hook($user, $record->sid, $record->timecreated, $record->timemodified)) {
88fdd846 398 $ignoretimeout = true;
399 break;
400 }
401 }
402 }
dd9e22f8 403 }
404 }
405 if ($ignoretimeout) {
406 //refresh session
407 $record->timemodified = time();
408 try {
409 $this->database->update_record('sessions', $record);
410 } catch (dml_exception $ex) {
411 error_log('Can not refresh database session');
412 return '';
413 }
414 } else {
415 //time out session
416 $record->state = 0;
417 $record->sessdata = null;
418 $record->sessdatahash = null;
419 $record->userid = 0;
420 $record->timecreated = $record->timemodified = time();
421 $record->firstip = $record->lastip = getremoteaddr();
422 try {
423 $this->database->update_record('sessions', $record);
424 } catch (dml_exception $ex) {
425 error_log('Can not time out database session');
426 return '';
427 }
eee3bd3f 428 }
eee3bd3f 429 }
430
200f26cf 431 if ($record->sessdata !== null) {
3b1a9849 432 if (md5($record->sessdata) !== $record->sessdatahash) {
433 // probably this is caused by misconfigured mysql - the allowed request size might be too small
434 try {
435 $this->database->delete_records('sessions', array('sid'=>$record->sid));
436 } catch (dml_exception $ignored) {
437 }
438 print_error('dbsessionbroken', 'error');
439 }
440
441 $data = base64_decode($record->sessdata);
442 } else {
443 $data = '';
444 }
445
0a2092a3 446 unset($record->sessdata); // conserve memory
447 $this->record = $record;
448
449 return $data;
450 }
451
452 public function handler_write($sid, $session_data) {
453 global $USER;
454
3b50631d 455 try {
456 if (isset($this->record->id)) {
457 $record->sid = $sid; // might be regenerating sid
458 $this->record->sessdata = base64_encode($session_data); // there might be some binary mess :-(
459 $this->record->sessdatahash = md5($this->record->sessdata);
460 $this->record->userid = empty($USER->realuser) ? $USER->id : $USER->realuser;
461 $this->record->timemodified = time();
462 $this->record->lastip = getremoteaddr();
0a2092a3 463
3b50631d 464 // TODO: verify session changed before doing update
7f79aaea 465
3b50631d 466 $this->database->update_record_raw('sessions', $this->record);
0a2092a3 467
3b50631d 468 } else {
469 // session already destroyed
470 $record = new object();
471 $record->state = 0;
472 $record->sid = $sid;
473 $record->sessdata = base64_encode($session_data); // there might be some binary mess :-(
474 $record->sessdatahash = md5($record->sessdata);
475 $record->userid = empty($USER->realuser) ? $USER->id : $USER->realuser;
476 $record->timecreated = $record->timemodified = time();
477 $record->firstip = $record->lastip = getremoteaddr();
478 $record->id = $this->database->insert_record_raw('sessions', $record);
479 $this->record = $record;
eee3bd3f 480
3b50631d 481 $this->database->get_session_lock($this->record->id);
482 }
0a2092a3 483 } catch (dml_exception $ex) {
3b50631d 484 error_log('Can not write session');
0a2092a3 485 }
17d93489 486
0a2092a3 487 return true;
488 }
489
490 public function handler_destroy($sid) {
3b50631d 491 session_kill($sid);
7f79aaea 492
3b50631d 493 if (isset($this->record->id) and $this->record->sid === $sid) {
494 $this->database->release_session_lock($this->record->id);
495 $this->record = null;
0a2092a3 496 }
497
498 return true;
499 }
500
3b1a9849 501 public function handler_gc($ignored_maxlifetime) {
64d69e96 502 session_gc();
0a2092a3 503 return true;
57f7b7ce 504 }
e8656bef 505}
506
64d69e96 507/**
508 * returns true if legacy session used.
509 * @return bool true if legacy(==file) based session used
510 */
511function session_is_legacy() {
512 global $CFG, $DB;
513 return ((isset($CFG->dbsessions) and !$CFG->dbsessions) or !$DB->session_lock_supported());
514}
515
e8656bef 516/**
517 * Terminates all sessions, auth hooks are not executed.
518 * Useful in ugrade scripts.
519 */
520function session_kill_all() {
521 global $CFG, $DB;
522
64d69e96 523 // always check db table - custom session classes use sessions table
e8656bef 524 try {
e8656bef 525 $DB->delete_records('sessions');
526 } catch (dml_exception $ignored) {
64d69e96 527 // do not show any warnings - might be during upgrade/installation
528 }
529
530 if (session_is_legacy()) {
531 $sessiondir = "$CFG->dataroot/sessions";
532 if (is_dir($sessiondir)) {
533 foreach (glob("$sessiondir/sess_*") as $filename) {
534 @unlink($filename);
535 }
536 }
537 }
538}
539
540/**
541 * Mark session as accessed, prevents timeouts.
542 * @param string $sid
543 */
544function session_touch($sid) {
545 global $CFG, $DB;
546
547 // always check db table - custom session classes use sessions table
548 try {
549 $sql = "UPDATE {sessions} SET timemodified=? WHERE sid=?";
550 $params = array(time(), $sid);
551 $DB->execute($sql, $params);
552 } catch (dml_exception $ignored) {
553 // do not show any warnings - might be during upgrade/installation
e8656bef 554 }
0a2092a3 555
64d69e96 556 if (session_is_legacy()) {
557 $sid = clean_param($sid, PARAM_FILE);
558 $sessionfile = clean_param("$CFG->dataroot/sessions/sess_$sid", PARAM_FILE);
559 if (file_exists($sessionfile)) {
560 // if the file is locked it means that it will be updated anyway
561 @touch($sessionfile);
562 }
e8656bef 563 }
564}
565
566/**
567 * Terminates one sessions, auth hooks are not executed.
568 *
569 * @param string $sid session id
570 */
571function session_kill($sid) {
572 global $CFG, $DB;
573
64d69e96 574 // always check db table - custom session classes use sessions table
e8656bef 575 try {
64d69e96 576 $DB->delete_records('sessions', array('sid'=>$sid));
e8656bef 577 } catch (dml_exception $ignored) {
64d69e96 578 // do not show any warnings - might be during upgrade/installation
e8656bef 579 }
580
64d69e96 581 if (session_is_legacy()) {
582 $sid = clean_param($sid, PARAM_FILE);
583 $sessionfile = "$CFG->dataroot/sessions/sess_$sid";
584 if (file_exists($sessionfile)) {
585 @unlink($sessionfile);
586 }
e8656bef 587 }
588}
589
590/**
591 * Terminates all sessions of one user, auth hooks are not executed.
592 * NOTE: This can not work for file based sessions!
593 *
594 * @param int $userid user id
595 */
596function session_kill_user($userid) {
597 global $CFG, $DB;
598
64d69e96 599 // always check db table - custom session classes use sessions table
e8656bef 600 try {
64d69e96 601 $DB->delete_records('sessions', array('userid'=>$userid));
e8656bef 602 } catch (dml_exception $ignored) {
64d69e96 603 // do not show any warnings - might be during upgrade/installation
604 }
605
606 if (session_is_legacy()) {
607 // log error?
e8656bef 608 }
609}
610
611/**
612 * Session garbage collection
613 * - verify timeout for all users
614 * - kill sessions of all deleted users
615 * - kill sessions of users with disabled plugins or 'nologin' plugin
616 *
617 * NOTE: this can not work when legacy file sessions used!
618 */
619function session_gc() {
620 global $CFG, $DB;
621
622 $maxlifetime = $CFG->sessiontimeout;
623
e8656bef 624 try {
625 /// kill all sessions of deleted users
626 $DB->delete_records_select('sessions', "userid IN (SELECT id FROM {user} WHERE deleted <> 0)");
627
628 /// kill sessions of users with disabled plugins
629 $auth_sequence = get_enabled_auth_plugins(true);
630 $auth_sequence = array_flip($auth_sequence);
631 unset($auth_sequence['nologin']); // no login allowed
632 $auth_sequence = array_flip($auth_sequence);
633 $notplugins = null;
634 list($notplugins, $params) = $DB->get_in_or_equal($auth_sequence, SQL_PARAMS_QM, '', false);
635 $DB->delete_records_select('sessions', "userid IN (SELECT id FROM {user} WHERE auth $notplugins)", $params);
636
637 /// now get a list of time-out candidates
638 $sql = "SELECT u.*, s.sid, s.timecreated AS s_timecreated, s.timemodified AS s_timemodified
639 FROM {user} u
640 JOIN {sessions} s ON s.userid = u.id
641 WHERE s.timemodified + ? < ? AND u.username <> 'guest'";
642 $params = array($maxlifetime, time());
643
644 $authplugins = array();
645 foreach($auth_sequence as $authname) {
646 $authplugins[$authname] = get_auth_plugin($authname);
647 }
648 $rs = $DB->get_recordset_sql($sql, $params);
649 foreach ($rs as $user) {
650 foreach ($authplugins as $authplugin) {
651 if ($authplugin->ignore_timeout_hook($user, $user->sid, $user->s_timecreated, $user->s_timemodified)) {
652 continue;
653 }
654 }
655 $DB->delete_records('sessions', array('sid'=>$user->sid));
656 }
657 $rs->close();
658 } catch (dml_exception $ex) {
659 error_log('Error gc-ing sessions');
660 }
0ad6b20c 661}
57f7b7ce 662
0ad6b20c 663/**
664 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
665 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
666 * sesskey string if $USER exists, or boolean false if not.
667 *
668 * @uses $USER
669 * @return string
670 */
671function sesskey() {
672 global $USER;
57f7b7ce 673
0ad6b20c 674 if (empty($USER->sesskey)) {
675 $USER->sesskey = random_string(10);
676 }
57f7b7ce 677
0ad6b20c 678 return $USER->sesskey;
679}
57f7b7ce 680
57f7b7ce 681
0ad6b20c 682/**
683 * For security purposes, this function will check that the currently
684 * given sesskey (passed as a parameter to the script or this function)
685 * matches that of the current user.
686 *
687 * @param string $sesskey optionally provided sesskey
688 * @return bool
689 */
690function confirm_sesskey($sesskey=NULL) {
691 global $USER;
57f7b7ce 692
eb85959b 693 if (!empty($USER->ignoresesskey)) {
0ad6b20c 694 return true;
695 }
57f7b7ce 696
0ad6b20c 697 if (empty($sesskey)) {
698 $sesskey = required_param('sesskey', PARAM_RAW); // Check script parameters
57f7b7ce 699 }
700
eb85959b 701 return (sesskey() === $sesskey);
0ad6b20c 702}
703
704/**
705 * Sets a moodle cookie with a weakly encrypted string
706 *
707 * @uses $CFG
708 * @uses DAYSECS
709 * @uses HOURSECS
710 * @param string $thing The string to encrypt and place in a cookie
711 */
712function set_moodle_cookie($thing) {
713 global $CFG;
714
0a2092a3 715 if (NO_MOODLE_COOKIES) {
716 return;
717 }
718
0ad6b20c 719 if ($thing == 'guest') { // Ignore guest account
720 return;
57f7b7ce 721 }
722
0ad6b20c 723 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
724
725 $days = 60;
726 $seconds = DAYSECS*$days;
727
728 // no need to set secure or http cookie only here - it is not secret
729 setcookie($cookiename, '', time() - HOURSECS, $CFG->sessioncookiepath, $CFG->sessioncookiedomain);
730 setcookie($cookiename, rc4encrypt($thing), time()+$seconds, $CFG->sessioncookiepath, $CFG->sessioncookiedomain);
731}
732
733/**
734 * Gets a moodle cookie with a weakly encrypted string
735 *
736 * @uses $CFG
737 * @return string
738 */
739function get_moodle_cookie() {
740 global $CFG;
741
0a2092a3 742 if (NO_MOODLE_COOKIES) {
743 return '';
744 }
745
0ad6b20c 746 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
747
748 if (empty($_COOKIE[$cookiename])) {
749 return '';
750 } else {
751 $thing = rc4decrypt($_COOKIE[$cookiename]);
752 return ($thing == 'guest') ? '': $thing; // Ignore guest account
57f7b7ce 753 }
0ad6b20c 754}
57f7b7ce 755
e8656bef 756
b7b64ff2 757/**
758 * Setup $USER object - called during login, loginas, etc.
759 * Preloads capabilities and checks enrolment plugins
760 *
761 * @param object $user full user record object
762 * @return void
763 */
764function session_set_user($user) {
765 $_SESSION['USER'] = $user;
dd9e22f8 766 unset($_SESSION['USER']->description); // conserve memory
767 if (!isset($_SESSION['USER']->access)) {
768 // check enrolments and load caps only once
769 check_enrolment_plugins($_SESSION['USER']);
770 load_all_capabilities();
771 }
eb85959b 772 sesskey(); // init session key
b7b64ff2 773}
774
542797b4 775/**
776 * Is current $USER logged-in-as somebody else?
777 * @return bool
778 */
b7b64ff2 779function session_is_loggedinas() {
85f6b737 780 return !empty($_SESSION['USER']->realuser);
542797b4 781}
782
6132768e 783/**
784 * Returns the $USER object ignoring current login-as session
785 * @return object user object
786 */
b7b64ff2 787function session_get_realuser() {
788 if (session_is_loggedinas()) {
6132768e 789 return $_SESSION['REALUSER'];
790 } else {
791 return $_SESSION['USER'];
792 }
793}
794
542797b4 795/**
796 * Login as another user - no security checks here.
797 * @param int $userid
798 * @param object $context
799 * @return void
800 */
8d1964c4 801function session_loginas($userid, $context) {
b7b64ff2 802 if (session_is_loggedinas()) {
8d1964c4 803 return;
804 }
805
85f6b737 806 // switch to fresh new $SESSION
807 $_SESSION['REALSESSION'] = $_SESSION['SESSION'];
6132768e 808 $_SESSION['SESSION'] = new object();
8d1964c4 809
85f6b737 810 /// Create the new $USER object with all details and reload needed capabilitites
811 $_SESSION['REALUSER'] = $_SESSION['USER'];
b7b64ff2 812 $user = get_complete_user_data('id', $userid);
813 $user->realuser = $_SESSION['REALUSER']->id;
814 $user->loginascontext = $context;
815 session_set_user($user);
8d1964c4 816}
817
542797b4 818/**
819 * Terminate login-as session
820 * @return void
821 */
8d1964c4 822function session_unloginas() {
b7b64ff2 823 if (!session_is_loggedinas()) {
8d1964c4 824 return;
825 }
826
6132768e 827 $_SESSION['SESSION'] = $_SESSION['REALSESSION'];
828 unset($_SESSION['REALSESSION']);
8d1964c4 829
6132768e 830 $_SESSION['USER'] = $_SESSION['REALUSER'];
831 unset($_SESSION['REALUSER']);
8d1964c4 832}
833
e8b7114d 834/**
835 * Sets up current user and course enviroment (lang, etc.) in cron.
836 * Do not use outside of cron script!
837 *
838 * @param object $user full user object, null means default cron user (admin)
839 * @param $course full course record, null means $SITE
840 * @return void
841 */
842function cron_setup_user($user=null, $course=null) {
843 global $CFG, $SITE;
844
845 static $cronuser = null;
846 static $cronsession = null;
847
848 if (empty($cronuser)) {
849 /// ignore admins timezone, language and locale - use site deafult instead!
850 $cronuser = get_admin();
851 $cronuser->timezone = $CFG->timezone;
dd9e22f8 852 $cronuser->lang = '';
853 $cronuser->theme = '';
854 unset($cronuser->description);
e8b7114d 855
856 $cronsession = array();
857 }
858
859 if (!$user) {
860 // cached default cron user (==modified admin for now)
861 session_set_user($cronuser);
862 $_SESSION['SESSION'] = $cronsession;
863
864 } else {
865 // emulate real user session - needed for caps in cron
866 if ($_SESSION['USER']->id != $user->id) {
867 session_set_user($user);
868 $_SESSION['SESSION'] = array();
869 }
870 }
871
872 if ($course) {
873 course_setup($course);
874 } else {
875 course_setup($SITE);
876 }
877
878 // TODO: it should be possible to improve perf by caching some limited number of users here ;-)
879
880}
881
0ad6b20c 882/**
883* Enable cookieless sessions by including $CFG->usesid=true;
884* in config.php.
885* Based on code from php manual by Richard at postamble.co.uk
886* Attempts to use cookies if cookies not present then uses session ids attached to all urls and forms to pass session id from page to page.
887* If site is open to google, google is given guest access as usual and there are no sessions. No session ids will be attached to urls for googlebot.
888* This doesn't require trans_sid to be turned on but this is recommended for better performance
889* you should put :
890* session.use_trans_sid = 1
891* in your php.ini file and make sure that you don't have a line like this in your php.ini
892* session.use_only_cookies = 1
893* @author Richard at postamble.co.uk and Jamie Pratt
894* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
895*/
896/**
897* You won't call this function directly. This function is used to process
898* text buffered by php in an output buffer. All output is run through this function
899* before it is ouput.
900* @param string $buffer is the output sent from php
901* @return string the output sent to the browser
902*/
903function sid_ob_rewrite($buffer){
904 $replacements = array(
905 '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*")([^"]*)(")/i',
906 '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*\')([^\']*)(\')/i');
907
908 $buffer = preg_replace_callback($replacements, 'sid_rewrite_link_tag', $buffer);
909 $buffer = preg_replace('/<form\s[^>]*>/i',
910 '\0<input type="hidden" name="' . session_name() . '" value="' . session_id() . '"/>', $buffer);
911
912 return $buffer;
913}
914/**
915* You won't call this function directly. This function is used to process
916* text buffered by php in an output buffer. All output is run through this function
917* before it is ouput.
918* This function only processes absolute urls, it is used when we decide that
919* php is processing other urls itself but needs some help with internal absolute urls still.
920* @param string $buffer is the output sent from php
921* @return string the output sent to the browser
922*/
923function sid_ob_rewrite_absolute($buffer){
924 $replacements = array(
925 '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*")((?:http|https)[^"]*)(")/i',
926 '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*\')((?:http|https)[^\']*)(\')/i');
927
928 $buffer = preg_replace_callback($replacements, 'sid_rewrite_link_tag', $buffer);
929 $buffer = preg_replace('/<form\s[^>]*>/i',
930 '\0<input type="hidden" name="' . session_name() . '" value="' . session_id() . '"/>', $buffer);
931 return $buffer;
932}
57f7b7ce 933
0ad6b20c 934/**
935* A function to process link, a and script tags found
936* by preg_replace_callback in {@link sid_ob_rewrite($buffer)}.
937*/
938function sid_rewrite_link_tag($matches){
939 $url = $matches[4];
940 $url = sid_process_url($url);
941 return $matches[1].$url.$matches[5];
942}
943
944/**
945* You can call this function directly. This function is used to process
946* urls to add a moodle session id to the url for internal links.
947* @param string $url is a url
948* @return string the processed url
949*/
950function sid_process_url($url) {
951 global $CFG;
952
953 if ((preg_match('/^(http|https):/i', $url)) // absolute url
954 && ((stripos($url, $CFG->wwwroot)!==0) && stripos($url, $CFG->httpswwwroot)!==0)) { // and not local one
955 return $url; //don't attach sessid to non local urls
956 }
957 if ($url[0]=='#' || (stripos($url, 'javascript:')===0)) {
958 return $url; //don't attach sessid to anchors
959 }
960 if (strpos($url, session_name())!==FALSE) {
961 return $url; //don't attach sessid to url that already has one sessid
962 }
963 if (strpos($url, "?")===FALSE) {
964 $append = "?".strip_tags(session_name() . '=' . session_id());
965 } else {
966 $append = "&amp;".strip_tags(session_name() . '=' . session_id());
57f7b7ce 967 }
0ad6b20c 968 //put sessid before any anchor
969 $p = strpos($url, "#");
970 if ($p!==FALSE){
971 $anch = substr($url, $p);
972 $url = substr($url, 0, $p).$append.$anch ;
973 } else {
974 $url .= $append ;
975 }
976 return $url;
977}
57f7b7ce 978
0ad6b20c 979/**
980* Call this function before there has been any output to the browser to
981* buffer output and add session ids to all internal links.
982*/
983function sid_start_ob(){
984 global $CFG;
985 //don't attach sess id for bots
986
987 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
988 if (!empty($CFG->opentogoogle)) {
989 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false) {
990 @ini_set('session.use_trans_sid', '0'); // try and turn off trans_sid
991 $CFG->usesid=false;
992 return;
57f7b7ce 993 }
0ad6b20c 994 if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false) {
57f7b7ce 995 @ini_set('session.use_trans_sid', '0'); // try and turn off trans_sid
996 $CFG->usesid=false;
997 return;
998 }
999 }
0ad6b20c 1000 if (strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) {
1001 @ini_set('session.use_trans_sid', '0'); // try and turn off trans_sid
1002 $CFG->usesid=false;
1003 return;
1004 }
1005 }
57f7b7ce 1006
0ad6b20c 1007 @ini_set('session.use_trans_sid', '1'); // try and turn on trans_sid
57f7b7ce 1008
0ad6b20c 1009 if (ini_get('session.use_trans_sid') != 0) {
1010 // use trans sid as its available
1011 ini_set('url_rewriter.tags', 'a=href,area=href,script=src,link=href,frame=src,form=fakeentry');
1012 ob_start('sid_ob_rewrite_absolute');
1013 } else {
1014 //rewrite all links ourselves
1015 ob_start('sid_ob_rewrite');
57f7b7ce 1016 }
e6e13284 1017}
0ad6b20c 1018