quiz: MDL-17578 Review quiz_get_view_actions and quiz_get_post_actions.
[moodle.git] / lib / sessionlib.php
CommitLineData
57f7b7ce 1<?php //$Id$
2
3/**
4 * Class handling all session and cookies related stuff.
5 */
6class moodle_session {
7 private $session;
8
9 function __construct() {
10 global $CFG;
11
12 $this->prepare_cookies();
13 $this->init_session_storage();
14
15 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
16 $this->sid_start_ob();
17 }
18
19 if (!NO_MOODLE_COOKIES) {
20 session_name('MoodleSession'.$CFG->sessioncookie);
21 session_set_cookie_params(0, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
22 @session_start();
23 if (!isset($_SESSION['SESSION'])) {
24 $_SESSION['SESSION'] = new object();
25 $_SESSION['SESSION']->session_test = random_string(10);
26 if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
27 $_SESSION['SESSION']->has_timed_out = true;
28 }
29 setcookie('MoodleSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
30 $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] = $_SESSION['SESSION']->session_test;
31 }
32 if (!isset($_SESSION['USER'])) {
33 $_SESSION['USER'] = new object();
34 }
35
36 if (!isset($_SESSION['USER']->id)) {
37 $_SESSION['USER']->id = 0; // to enable proper function of $CFG->notloggedinroleid hack
38 if (isset($CFG->mnet_localhost_id)) {
39 $_SESSION['USER']->mnethostid = $CFG->mnet_localhost_id;
40 }
41 }
42
43 $this->session = null;
44
45 } else {
46 $this->session = new object();
47 }
48 }
49
50 /**
51 * Verify session, this detects problems with "switched" sessions
52 * or multiple different wwwroot used at the same time.
53 */
54 public function session_verify() {
55 global $CFG;
56
57 /// disable checks when working in cookieless mode
58 if (empty($CFG->usesid) || !empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
59 if ($this->session != NULL) {
60 if (empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
61 $this->report_session_error();
62 } else if (isset($this->session->session_test) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] != $this->session->session_test) {
63 $this->report_session_error();
64 }
65 }
66 }
67 }
68
69 /**
70 * Report serious problem detected in suer session
71 */
72 function report_session_error() {
73 global $CFG, $FULLME;
74
75 if (empty($CFG->lang)) {
76 $CFG->lang = "en";
77 }
78 // Set up default theme and locale
79 theme_setup();
80 moodle_setlocale();
81
82 //clear session cookies
83 setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
84 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
85
86 //increment database error counters
87 if (isset($CFG->session_error_counter)) {
88 set_config('session_error_counter', 1 + $CFG->session_error_counter);
89 } else {
90 set_config('session_error_counter', 1);
91 }
92 redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
93 }
94
95 /**
96 * Terminates active moodle session
97 */
98 public function terminate() {
99 global $CFG, $SESSION, $USER;
100
101 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
102 $file = null;
103 $line = null;
104 if (headers_sent($file, $line)) {
105 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__);
106 error_log('Headers were already sent in file: '.$file.' on line '.$line);
107 } else {
108 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
109 }
110
111 $this->session = new object();
112 $_SESSION = array();
113
114 $USER = new object();
115 $USER->id = 0;
116 if (isset($CFG->mnet_localhost_id)) {
117 $USER->mnethostid = $CFG->mnet_localhost_id;
118 }
119
120 @session_write_close();
121 }
122
123
124 public function __set($name, $value) {
125 if (!is_null($this->session)) {
126 $this->session->{$name} = $value;
127 } else {
128 $_SESSION['SESSION']->{$name} = $value;
129 }
130 }
131
132 public function &__get($name) { // this is a weird hack for this stupid bug http://bugs.php.net/bug.php?id=39449
133 if (!is_null($this->session)) {
134 return $this->session->{$name};
135 } else {
136 return $_SESSION['SESSION']->{$name};
137 }
138 }
139
140 public function __isset($name) {
141 if (!is_null($this->session)) {
142 return isset($this->session->{$name});
143 } else {
144 return isset($_SESSION['SESSION']->{$name});
145 }
146 }
147
148 public function __unset($name) {
149 if (!is_null($this->session)) {
150 unset($this->session->{$name});
151 } else {
152 unset($_SESSION['SESSION']->{$name});
153 }
154 }
155
156 /**
157 * Prepare cookies and varions system settings
158 */
159 private function prepare_cookies() {
160 global $CFG, $nomoodlecookie;
161
162 if (!defined('NO_MOODLE_COOKIES')) {
163 if (isset($nomoodlecookie)) {
164 // backwards compatibility only
165 define('NO_MOODLE_COOKIES', $nomoodlecookie);
166 unset($nomoodlecookie);
167 } else {
168 define('NO_MOODLE_COOKIES', false);
169 }
170 }
171
172 if (!isset($CFG->cookiesecure) or strpos($CFG->wwwroot, 'https://') !== 0) {
173 $CFG->cookiesecure = 0;
174 }
175
176 if (!isset($CFG->cookiehttponly)) {
177 $CFG->cookiehttponly = 0;
178 }
179
180 /// Set sessioncookie and sessioncookiepath variable if it isn't already
181 if (!isset($CFG->sessioncookie)) {
182 $CFG->sessioncookie = '';
183 }
184 if (!isset($CFG->sessioncookiepath)) {
185 $CFG->sessioncookiepath = '/';
186 }
187
188 //discard session ID from POST, GET and globals to tighten security,
189 //this session fixation prevention can not be used in cookieless mode
190 if (empty($CFG->usesid)) {
191 unset(${'MoodleSession'.$CFG->sessioncookie});
192 unset($_GET['MoodleSession'.$CFG->sessioncookie]);
193 unset($_POST['MoodleSession'.$CFG->sessioncookie]);
194 }
195 //compatibility hack for Moodle Cron, cookies not deleted, but set to "deleted" - should not be needed with NO_MOODLE_COOKIES in cron.php now
196 if (!empty($_COOKIE['MoodleSession'.$CFG->sessioncookie]) && $_COOKIE['MoodleSession'.$CFG->sessioncookie] == "deleted") {
197 unset($_COOKIE['MoodleSession'.$CFG->sessioncookie]);
198 }
199 if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] == "deleted") {
200 unset($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]);
201 }
202 }
203
204 /**
205 * Inits session storage.
206 */
207 private function init_session_storage() {
208 global $CFG;
209
210 /// Set up session handling
211 if(empty($CFG->respectsessionsettings)) {
212 if (true) { /// File-based sessions
213 // Some distros disable GC by setting probability to 0
214 // overriding the PHP default of 1
215 // (gc_probability is divided by gc_divisor, which defaults to 1000)
216 if (ini_get('session.gc_probability') == 0) {
217 ini_set('session.gc_probability', 1);
218 }
219
220 if (!empty($CFG->sessiontimeout)) {
221 ini_set('session.gc_maxlifetime', $CFG->sessiontimeout);
222 }
223
224 if (!file_exists($CFG->dataroot .'/sessions')) {
225 make_upload_directory('sessions');
226 }
227 ini_set('session.save_path', $CFG->dataroot .'/sessions');
228
229 } else { /// Database sessions
230 // TODO: implement proper database session storage
231 }
232 }
233 }
234
235 /**
236 * Sets a moodle cookie with a weakly encrypted string
237 *
238 * @uses $CFG
239 * @uses DAYSECS
240 * @uses HOURSECS
241 * @param string $thing The string to encrypt and place in a cookie
242 */
243 public static function set_moodle_cookie($thing) {
244 global $CFG;
245
246 if ($thing == 'guest') { // Ignore guest account
247 return;
248 }
249
250 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
251
252 $days = 60;
253 $seconds = DAYSECS*$days;
254
255 // no need to set secure or http cookie only here - it is not secret
256 setCookie($cookiename, '', time() - HOURSECS, $CFG->sessioncookiepath);
257 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, $CFG->sessioncookiepath);
258 }
259
260 /**
261 * Gets a moodle cookie with a weakly encrypted string
262 *
263 * @uses $CFG
264 * @return string
265 */
266 public static function get_moodle_cookie() {
267 global $CFG;
268
269 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
270
271 if (empty($_COOKIE[$cookiename])) {
272 return '';
273 } else {
274 $thing = rc4decrypt($_COOKIE[$cookiename]);
275 return ($thing == 'guest') ? '': $thing; // Ignore guest account
276 }
277 }
278
279 /**
280 * Enable cookieless sessions by including $CFG->usesid=true;
281 * in config.php.
282 * Based on code from php manual by Richard at postamble.co.uk
283 * 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.
284 * 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.
285 * This doesn't require trans_sid to be turned on but this is recommended for better performance
286 * you should put :
287 * session.use_trans_sid = 1
288 * in your php.ini file and make sure that you don't have a line like this in your php.ini
289 * session.use_only_cookies = 1
290 * @author Richard at postamble.co.uk and Jamie Pratt
291 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
292 */
293 /**
294 * You won't call this function directly. This function is used to process
295 * text buffered by php in an output buffer. All output is run through this function
296 * before it is ouput.
297 * @param string $buffer is the output sent from php
298 * @return string the output sent to the browser
299 */
300 public static function sid_ob_rewrite($buffer){
301 $replacements = array(
302 '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*")([^"]*)(")/i',
303 '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*\')([^\']*)(\')/i');
304
305 $buffer = preg_replace_callback($replacements, array('moodle_session', 'sid_rewrite_link_tag'), $buffer);
306 $buffer = preg_replace('/<form\s[^>]*>/i',
307 '\0<input type="hidden" name="' . session_name() . '" value="' . session_id() . '"/>', $buffer);
308
309 return $buffer;
310 }
311 /**
312 * You won't call this function directly. This function is used to process
313 * text buffered by php in an output buffer. All output is run through this function
314 * before it is ouput.
315 * This function only processes absolute urls, it is used when we decide that
316 * php is processing other urls itself but needs some help with internal absolute urls still.
317 * @param string $buffer is the output sent from php
318 * @return string the output sent to the browser
319 */
320 public static function sid_ob_rewrite_absolute($buffer){
321 $replacements = array(
322 '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*")((?:http|https)[^"]*)(")/i',
323 '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*\')((?:http|https)[^\']*)(\')/i');
324
325 $buffer = preg_replace_callback($replacements, array('moodle_session', 'sid_rewrite_link_tag'), $buffer);
326 $buffer = preg_replace('/<form\s[^>]*>/i',
327 '\0<input type="hidden" name="' . session_name() . '" value="' . session_id() . '"/>', $buffer);
328 return $buffer;
329 }
330
331 /**
332 * A function to process link, a and script tags found
333 * by preg_replace_callback in {@link sid_ob_rewrite($buffer)}.
334 */
335 public static function sid_rewrite_link_tag($matches){
336 $url = $matches[4];
337 $url = moodle_session::sid_process_url($url);
338 return $matches[1].$url.$matches[5];
339 }
340
341 /**
342 * You can call this function directly. This function is used to process
343 * urls to add a moodle session id to the url for internal links.
344 * @param string $url is a url
345 * @return string the processed url
346 */
347 public static function sid_process_url($url) {
348 global $CFG;
349
350 if ((preg_match('/^(http|https):/i', $url)) // absolute url
351 && ((stripos($url, $CFG->wwwroot)!==0) && stripos($url, $CFG->httpswwwroot)!==0)) { // and not local one
352 return $url; //don't attach sessid to non local urls
353 }
354 if ($url[0]=='#' || (stripos($url, 'javascript:')===0)) {
355 return $url; //don't attach sessid to anchors
356 }
357 if (strpos($url, session_name())!==FALSE) {
358 return $url; //don't attach sessid to url that already has one sessid
359 }
360 if (strpos($url, "?")===FALSE) {
361 $append = "?".strip_tags(session_name() . '=' . session_id());
362 } else {
363 $append = "&amp;".strip_tags(session_name() . '=' . session_id());
364 }
365 //put sessid before any anchor
366 $p = strpos($url, "#");
367 if ($p!==FALSE){
368 $anch = substr($url, $p);
369 $url = substr($url, 0, $p).$append.$anch ;
370 } else {
371 $url .= $append ;
372 }
373 return $url;
374 }
375
376 /**
377 * Call this function before there has been any output to the browser to
378 * buffer output and add session ids to all internal links.
379 */
380 public static function sid_start_ob(){
381 global $CFG;
382 //don't attach sess id for bots
383
384 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
385 if (!empty($CFG->opentogoogle)) {
386 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false) {
387 @ini_set('session.use_trans_sid', '0'); // try and turn off trans_sid
388 $CFG->usesid=false;
389 return;
390 }
391 if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false) {
392 @ini_set('session.use_trans_sid', '0'); // try and turn off trans_sid
393 $CFG->usesid=false;
394 return;
395 }
396 }
397 if (strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) {
398 @ini_set('session.use_trans_sid', '0'); // try and turn off trans_sid
399 $CFG->usesid=false;
400 return;
401 }
402 }
403
404 @ini_set('session.use_trans_sid', '1'); // try and turn on trans_sid
405
406 if (ini_get('session.use_trans_sid') != 0) {
407 // use trans sid as its available
408 ini_set('url_rewriter.tags', 'a=href,area=href,script=src,link=href,frame=src,form=fakeentry');
409 ob_start(array('moodle_session', 'sid_ob_rewrite_absolute'));
410 } else {
411 //rewrite all links ourselves
412 ob_start(array('moodle_session', 'sid_ob_rewrite'));
413 }
414 }
415}