]> git.mjollnir.org Git - moodle.git/commitdiff
MDL-17754 session code refactoring; removing test cookie which will be replaced by...
authorskodak <skodak>
Fri, 2 Jan 2009 13:42:43 +0000 (13:42 +0000)
committerskodak <skodak>
Fri, 2 Jan 2009 13:42:43 +0000 (13:42 +0000)
auth/shibboleth/login.php
blocks/login/block_login.php
index.php
lib/filelib.php
lib/moodlelib.php
lib/sessionlib.php
lib/setup.php
login/confirm.php
login/index.php

index d27c117906556f0b6d4d05f95a7a8b7356f0661d..a974adf5d9be035dddf21d5f503e58847b8f3e94 100644 (file)
@@ -38,7 +38,7 @@ httpsrequired();
     $loginurl = (!empty($CFG->alternateloginurl)) ? $CFG->alternateloginurl : '';
 
 
-    if (get_moodle_cookie() == '') {   
+    if (get_moodle_cookie() == '') {
         set_moodle_cookie('nobody');   // To help search for cookies
     }
 
index 6152507c83fe08e1740dd0262a154628857c3a50..8d924e885fcfa5fa5d9db1991b6eb339bbb93d0d 100644 (file)
@@ -36,7 +36,7 @@ class block_login extends block_base {
         // TODO: now that we have multiauth it is hard to find out if there is a way to change password
         $forgot = $wwwroot . '/login/forgot_password.php';
 
-        $username = $SESSION->get_moodle_cookie() === 'nobody' ? '' : $SESSION->get_moodle_cookie();
+        $username = get_moodle_cookie() === 'nobody' ? '' : get_moodle_cookie();
 
         $this->content->footer = '';
         $this->content->text = '';
index 351c584b22f95cfb5ff84ec0cf7d8eeaf4ea6902..2e6c363fbd9463984081ae3f2baa25b3ae5e7d37 100644 (file)
--- a/index.php
+++ b/index.php
@@ -85,8 +85,8 @@
     }
 
 
-    if ($SESSION->get_moodle_cookie() == '') {
-        $SESSION->set_moodle_cookie('nobody');   // To help search for cookies on login page
+    if (get_moodle_cookie() == '') {
+        set_moodle_cookie('nobody');   // To help search for cookies on login page
     }
 
     if (!empty($USER->id)) {
index 972498d5f25a0ba364105ac92745e8a08bd87350..52bac5755a464ef1fc63b43c59458e81d7122fa7 100644 (file)
@@ -1037,7 +1037,7 @@ function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathiss
             //cookieless mode - rewrite links
             @header('Content-Type: text/html');
             $path = $pathisstring ? $path : implode('', file($path));
-            $path = $SESSION->sid_ob_rewrite($path);
+            $path = sid_ob_rewrite($path);
             $filesize = strlen($path);
             $pathisstring = true;
         } else if ($mimetype == 'text/plain') {
@@ -1063,7 +1063,7 @@ function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathiss
             $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
             if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
                 //cookieless mode - rewrite links
-                $output = $SESSION->sid_ob_rewrite($output);
+                $output = sid_ob_rewrite($output);
             }
 
             @header('Content-Length: '.strlen($output));
@@ -1079,7 +1079,7 @@ function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathiss
             $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
             if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
                 //cookieless mode - rewrite links
-                $output = $SESSION->sid_ob_rewrite($output);
+                $output = sid_ob_rewrite($output);
             }
 
             @header('Content-Length: '.strlen($output));
@@ -1224,7 +1224,7 @@ function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownl
             //cookieless mode - rewrite links
             @header('Content-Type: text/html');
             $text = $stored_file->get_content();
-            $text = $SESSION->sid_ob_rewrite($text);
+            $text = sid_ob_rewrite($text);
             $filesize = strlen($text);
             $filtered = true;
         } else if ($mimetype == 'text/plain') {
@@ -1250,7 +1250,7 @@ function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownl
             $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
             if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
                 //cookieless mode - rewrite links
-                $output = $SESSION->sid_ob_rewrite($output);
+                $output = sid_ob_rewrite($output);
             }
 
             @header('Content-Length: '.strlen($output));
@@ -1266,7 +1266,7 @@ function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownl
             $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
             if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
                 //cookieless mode - rewrite links
-                $output = $SESSION->sid_ob_rewrite($output);
+                $output = sid_ob_rewrite($output);
             }
 
             @header('Content-Length: '.strlen($output));
index c2e01cec6906ec9cef2d19f5775dfddd08c2f511..f8dea4c536b3ed31f031041fbd1b67610484f515 100644 (file)
@@ -1827,55 +1827,6 @@ function dayofweek($day, $month, $year) {
 
 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
 
-/**
- * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
- * if one does not already exist, but does not overwrite existing sesskeys. Returns the
- * sesskey string if $USER exists, or boolean false if not.
- *
- * @uses $USER
- * @return string
- */
-function sesskey() {
-    global $USER;
-
-    if(!isset($USER)) {
-        return false;
-    }
-
-    if (empty($USER->sesskey)) {
-        $USER->sesskey = random_string(10);
-    }
-
-    return $USER->sesskey;
-}
-
-
-/**
- * For security purposes, this function will check that the currently
- * given sesskey (passed as a parameter to the script or this function)
- * matches that of the current user.
- *
- * @param string $sesskey optionally provided sesskey
- * @return bool
- */
-function confirm_sesskey($sesskey=NULL) {
-    global $USER;
-
-    if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
-        return true;
-    }
-
-    if (empty($sesskey)) {
-        $sesskey = required_param('sesskey', PARAM_RAW);  // Check script parameters
-    }
-
-    if (!isset($USER->sesskey)) {
-        return false;
-    }
-
-    return ($USER->sesskey === $sesskey);
-}
-
 /**
  * Setup all global $CFG course variables, set locale and also themes
  * This function can be used on pages that do not require login instead of require_login()
@@ -2202,7 +2153,7 @@ function require_logout() {
         }
     }
 
-    $SESSION->terminate();
+    get_session()->terminate();
 }
 
 /**
@@ -3205,12 +3156,12 @@ function complete_user_login($user) {
 
     update_user_login_times();
     if (empty($CFG->nolastloggedin)) {
-        $SESSION->set_moodle_cookie($USER->username);
+        set_moodle_cookie($USER->username);
     } else {
         // do not store last logged in user in cookie
         // auth plugins can temporarily override this from loginpage_hook()
         // do not save $CFG->nolastloggedin in database!
-        $SESSION->set_moodle_cookie('nobody');
+        set_moodle_cookie('nobody');
     }
     set_login_session_preferences();
 
index 8e34ef542020ba3969e4c7ea848645cdd20d6b9d..577608f3810300f3c71e640804b0c32fb126c17f 100644 (file)
 <?php  //$Id$
 
+function get_session() {
+    static $session = null;
+
+    if (is_null($session)) {
+        $session = new moodle_session();
+    }
+
+    return $session;
+}
+
 /**
  * Class handling all session and cookies related stuff.
  */
 class moodle_session {
-    private $session;
-
     function __construct() {
         global $CFG;
-
         $this->prepare_cookies();
         $this->init_session_storage();
 
         if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
-            $this->sid_start_ob();
+            sid_start_ob();
         }
 
-        if (!NO_MOODLE_COOKIES) {
+        if (NO_MOODLE_COOKIES) {
+            $_SESSION = array();
+            $_SESSION['SESSION'] = new object();
+            $_SESSION['USER'] = new object();
+
+        } else {
             session_name('MoodleSession'.$CFG->sessioncookie);
             session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
             @session_start();
             if (!isset($_SESSION['SESSION'])) {
                 $_SESSION['SESSION'] = new object();
-                $_SESSION['SESSION']->session_test = random_string(10);
-                if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
-                    $_SESSION['SESSION']->has_timed_out = true;
-                }
-                setcookie('MoodleSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
-                $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] = $_SESSION['SESSION']->session_test;
             }
             if (!isset($_SESSION['USER'])) {
                 $_SESSION['USER'] = new object();
             }
-
-            if (!isset($_SESSION['USER']->id)) {
-                $_SESSION['USER']->id = 0; // to enable proper function of $CFG->notloggedinroleid hack
-                if (isset($CFG->mnet_localhost_id)) {
-                    $_SESSION['USER']->mnethostid = $CFG->mnet_localhost_id;
-                }
-            }
-
-            $this->session = null;
-
-        } else {
-            $this->session = new object();
         }
-    }
 
-    /**
-     * Verify session, this detects problems with "switched" sessions
-     * or multiple different wwwroot used at the same time.
-     */
-    public function session_verify() {
-        global $CFG;
-
-    /// disable checks when working in cookieless mode
-        if (empty($CFG->usesid) || !empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
-            if ($this->session != NULL) {
-                if (empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
-                    $this->report_session_error();
-                } else if (isset($this->session->session_test) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] != $this->session->session_test) {
-                    $this->report_session_error();
-                }
+        if (!isset($_SESSION['USER']->id)) {
+            $_SESSION['USER']->id = 0; // to enable proper function of $CFG->notloggedinroleid hack
+            if (isset($CFG->mnet_localhost_id)) {
+                $_SESSION['USER']->mnethostid = $CFG->mnet_localhost_id;
             }
         }
     }
 
-    /**
-     * Report serious problem detected in suer session
-     */
-    function report_session_error() {
-        global $CFG, $FULLME;
-
-        if (empty($CFG->lang)) {
-            $CFG->lang = "en";
-        }
-        // Set up default theme and locale
-        theme_setup();
-        moodle_setlocale();
-
-        //clear session cookies
-        setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
-        setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
-
-        //increment database error counters
-        if (isset($CFG->session_error_counter)) {
-            set_config('session_error_counter', 1 + $CFG->session_error_counter);
-        } else {
-            set_config('session_error_counter', 1);
-        }
-        redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
-    }
-
     /**
      * Terminates active moodle session
      */
     public function terminate() {
         global $CFG, $SESSION, $USER;
 
-        // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
-        $file = null;
-        $line = null;
-        if (headers_sent($file, $line)) {
-            error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__);
-            error_log('Headers were already sent in file: '.$file.' on line '.$line);
-        } else {
-            setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
-        }
-
-        $this->session = new object();
-        $_SESSION      = array();
+        $_SESSION = array();
 
+        $SESSION  = new object();
         $USER     = new object();
         $USER->id = 0;
         if (isset($CFG->mnet_localhost_id)) {
             $USER->mnethostid = $CFG->mnet_localhost_id;
         }
 
-        @session_write_close();
-    }
-
-
-    public function __set($name, $value) {
-        if (!is_null($this->session)) {
-            $this->session->{$name} = $value;
-        } else {
-            $_SESSION['SESSION']->{$name} = $value;
-        }
-    }
-
-    public function &__get($name) { // this is a weird hack for this stupid bug http://bugs.php.net/bug.php?id=39449
-        if (!is_null($this->session)) {
-            return $this->session->{$name};
-        } else {
-            return $_SESSION['SESSION']->{$name};
-        }
-    }
-
-    public function __isset($name) {
-        if (!is_null($this->session)) {
-            return isset($this->session->{$name});
+        // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
+        $file = null;
+        $line = null;
+        if (headers_sent($file, $line)) {
+            error_log('Can not terminate session properly - headers were already sent in file: '.$file.' on line '.$line);
         } else {
-            return isset($_SESSION['SESSION']->{$name});
+            // TODO: regenerate session ID here
+            
         }
-    }
 
-    public function __unset($name) {
-        if (!is_null($this->session)) {
-            unset($this->session->{$name});
-        } else {
-            unset($_SESSION['SESSION']->{$name});
-        }
+        @session_write_close();
     }
 
     /**
@@ -199,9 +122,6 @@ class moodle_session {
         if (!empty($_COOKIE['MoodleSession'.$CFG->sessioncookie]) && $_COOKIE['MoodleSession'.$CFG->sessioncookie] == "deleted") {
             unset($_COOKIE['MoodleSession'.$CFG->sessioncookie]);
         }
-        if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] == "deleted") {
-            unset($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]);
-        }
     }
 
     /**
@@ -234,185 +154,235 @@ class moodle_session {
             }
         }
     }
+}
 
-    /**
-     * Sets a moodle cookie with a weakly encrypted string
-     *
-     * @uses $CFG
-     * @uses DAYSECS
-     * @uses HOURSECS
-     * @param string $thing The string to encrypt and place in a cookie
    */
-    public static function set_moodle_cookie($thing) {
-        global $CFG;
+/**
+ * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
+ * if one does not already exist, but does not overwrite existing sesskeys. Returns the
+ * sesskey string if $USER exists, or boolean false if not.
+ *
+ * @uses $USER
+ * @return string
+ */
+function sesskey() {
+    global $USER;
 
-        if ($thing == 'guest') {  // Ignore guest account
-            return;
-        }
+    if(!isset($USER)) {
+        return false;
+    }
 
-        $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
+    if (empty($USER->sesskey)) {
+        $USER->sesskey = random_string(10);
+    }
 
-        $days = 60;
-        $seconds = DAYSECS*$days;
+    return $USER->sesskey;
+}
 
-        // no need to set secure or http cookie only here - it is not secret
-        setcookie($cookiename, '', time() - HOURSECS, $CFG->sessioncookiepath, $CFG->sessioncookiedomain);
-        setcookie($cookiename, rc4encrypt($thing), time()+$seconds, $CFG->sessioncookiepath, $CFG->sessioncookiedomain);
-    }
 
-    /**
-     * Gets a moodle cookie with a weakly encrypted string
-     *
-     * @uses $CFG
-     * @return string
-     */
-    public static function get_moodle_cookie() {
-        global $CFG;
+/**
+ * For security purposes, this function will check that the currently
+ * given sesskey (passed as a parameter to the script or this function)
+ * matches that of the current user.
+ *
+ * @param string $sesskey optionally provided sesskey
+ * @return bool
+ */
+function confirm_sesskey($sesskey=NULL) {
+    global $USER;
 
-        $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
+    if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
+        return true;
+    }
 
-        if (empty($_COOKIE[$cookiename])) {
-            return '';
-        } else {
-            $thing = rc4decrypt($_COOKIE[$cookiename]);
-            return ($thing == 'guest') ? '': $thing;  // Ignore guest account
-        }
+    if (empty($sesskey)) {
+        $sesskey = required_param('sesskey', PARAM_RAW);  // Check script parameters
     }
 
-    /**
-    * Enable cookieless sessions by including $CFG->usesid=true;
-    * in config.php.
-    * Based on code from php manual by Richard at postamble.co.uk
-    * 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.
-    * 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.
-    * This doesn't require trans_sid to be turned on but this is recommended for better performance
-    * you should put :
-    * session.use_trans_sid = 1
-    * in your php.ini file and make sure that you don't have a line like this in your php.ini
-    * session.use_only_cookies = 1
-    * @author Richard at postamble.co.uk and Jamie Pratt
-    * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
-    */
-    /**
-    * You won't call this function directly. This function is used to process
-    * text buffered by php in an output buffer. All output is run through this function
-    * before it is ouput.
-    * @param string $buffer is the output sent from php
-    * @return string the output sent to the browser
-    */
-    public static function sid_ob_rewrite($buffer){
-        $replacements = array(
-            '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*")([^"]*)(")/i',
-            '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*\')([^\']*)(\')/i');
-
-        $buffer = preg_replace_callback($replacements, array('moodle_session', 'sid_rewrite_link_tag'), $buffer);
-        $buffer = preg_replace('/<form\s[^>]*>/i',
-            '\0<input type="hidden" name="' . session_name() . '" value="' . session_id() . '"/>', $buffer);
-
-          return $buffer;
+    if (!isset($USER->sesskey)) {
+        return false;
     }
-    /**
-    * You won't call this function directly. This function is used to process
-    * text buffered by php in an output buffer. All output is run through this function
-    * before it is ouput.
-    * This function only processes absolute urls, it is used when we decide that
-    * php is processing other urls itself but needs some help with internal absolute urls still.
-    * @param string $buffer is the output sent from php
-    * @return string the output sent to the browser
-    */
-    public static function sid_ob_rewrite_absolute($buffer){
-        $replacements = array(
-            '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*")((?:http|https)[^"]*)(")/i',
-            '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*\')((?:http|https)[^\']*)(\')/i');
-
-        $buffer = preg_replace_callback($replacements, array('moodle_session', 'sid_rewrite_link_tag'), $buffer);
-        $buffer = preg_replace('/<form\s[^>]*>/i',
-            '\0<input type="hidden" name="' . session_name() . '" value="' . session_id() . '"/>', $buffer);
-        return $buffer;
+
+    return ($USER->sesskey === $sesskey);
+}
+
+/**
+ * Sets a moodle cookie with a weakly encrypted string
+ *
+ * @uses $CFG
+ * @uses DAYSECS
+ * @uses HOURSECS
+ * @param string $thing The string to encrypt and place in a cookie
+ */
+function set_moodle_cookie($thing) {
+    global $CFG;
+
+    if ($thing == 'guest') {  // Ignore guest account
+        return;
     }
 
-    /**
-    * A function to process link, a and script tags found
-    * by preg_replace_callback in {@link sid_ob_rewrite($buffer)}.
-    */
-    public static function sid_rewrite_link_tag($matches){
-        $url = $matches[4];
-        $url = moodle_session::sid_process_url($url);
-        return $matches[1].$url.$matches[5];
+    $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
+
+    $days = 60;
+    $seconds = DAYSECS*$days;
+
+    // no need to set secure or http cookie only here - it is not secret
+    setcookie($cookiename, '', time() - HOURSECS, $CFG->sessioncookiepath, $CFG->sessioncookiedomain);
+    setcookie($cookiename, rc4encrypt($thing), time()+$seconds, $CFG->sessioncookiepath, $CFG->sessioncookiedomain);
+}
+
+/**
+ * Gets a moodle cookie with a weakly encrypted string
+ *
+ * @uses $CFG
+ * @return string
+ */
+function get_moodle_cookie() {
+    global $CFG;
+
+    $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
+
+    if (empty($_COOKIE[$cookiename])) {
+        return '';
+    } else {
+        $thing = rc4decrypt($_COOKIE[$cookiename]);
+        return ($thing == 'guest') ? '': $thing;  // Ignore guest account
     }
+}
 
-    /**
-    * You can call this function directly. This function is used to process
-    * urls to add a moodle session id to the url for internal links.
-    * @param string $url is a url
-    * @return string the processed url
-    */
-    public static function sid_process_url($url) {
-        global $CFG;
+/**
+* Enable cookieless sessions by including $CFG->usesid=true;
+* in config.php.
+* Based on code from php manual by Richard at postamble.co.uk
+* 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.
+* 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.
+* This doesn't require trans_sid to be turned on but this is recommended for better performance
+* you should put :
+* session.use_trans_sid = 1
+* in your php.ini file and make sure that you don't have a line like this in your php.ini
+* session.use_only_cookies = 1
+* @author Richard at postamble.co.uk and Jamie Pratt
+* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
+*/
+/**
+* You won't call this function directly. This function is used to process
+* text buffered by php in an output buffer. All output is run through this function
+* before it is ouput.
+* @param string $buffer is the output sent from php
+* @return string the output sent to the browser
+*/
+function sid_ob_rewrite($buffer){
+    $replacements = array(
+        '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*")([^"]*)(")/i',
+        '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*\')([^\']*)(\')/i');
+
+    $buffer = preg_replace_callback($replacements, 'sid_rewrite_link_tag', $buffer);
+    $buffer = preg_replace('/<form\s[^>]*>/i',
+        '\0<input type="hidden" name="' . session_name() . '" value="' . session_id() . '"/>', $buffer);
+
+      return $buffer;
+}
+/**
+* You won't call this function directly. This function is used to process
+* text buffered by php in an output buffer. All output is run through this function
+* before it is ouput.
+* This function only processes absolute urls, it is used when we decide that
+* php is processing other urls itself but needs some help with internal absolute urls still.
+* @param string $buffer is the output sent from php
+* @return string the output sent to the browser
+*/
+function sid_ob_rewrite_absolute($buffer){
+    $replacements = array(
+        '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*")((?:http|https)[^"]*)(")/i',
+        '/(<\s*(a|link|script|frame|area)\s[^>]*(href|src)\s*=\s*\')((?:http|https)[^\']*)(\')/i');
+
+    $buffer = preg_replace_callback($replacements, 'sid_rewrite_link_tag', $buffer);
+    $buffer = preg_replace('/<form\s[^>]*>/i',
+        '\0<input type="hidden" name="' . session_name() . '" value="' . session_id() . '"/>', $buffer);
+    return $buffer;
+}
 
-        if ((preg_match('/^(http|https):/i', $url)) // absolute url
-            &&  ((stripos($url, $CFG->wwwroot)!==0) && stripos($url, $CFG->httpswwwroot)!==0)) { // and not local one
-            return $url; //don't attach sessid to non local urls
-        }
-        if ($url[0]=='#' || (stripos($url, 'javascript:')===0)) {
-            return $url; //don't attach sessid to anchors
-        }
-        if (strpos($url, session_name())!==FALSE) {
-            return $url; //don't attach sessid to url that already has one sessid
-        }
-        if (strpos($url, "?")===FALSE) {
-            $append = "?".strip_tags(session_name() . '=' . session_id());
-        }    else {
-            $append = "&amp;".strip_tags(session_name() . '=' . session_id());
-        }
-        //put sessid before any anchor
-        $p = strpos($url, "#");
-        if ($p!==FALSE){
-            $anch = substr($url, $p);
-            $url = substr($url, 0, $p).$append.$anch ;
-        } else  {
-            $url .= $append ;
-        }
-        return $url;
+/**
+* A function to process link, a and script tags found
+* by preg_replace_callback in {@link sid_ob_rewrite($buffer)}.
+*/
+function sid_rewrite_link_tag($matches){
+    $url = $matches[4];
+    $url = sid_process_url($url);
+    return $matches[1].$url.$matches[5];
+}
+
+/**
+* You can call this function directly. This function is used to process
+* urls to add a moodle session id to the url for internal links.
+* @param string $url is a url
+* @return string the processed url
+*/
+function sid_process_url($url) {
+    global $CFG;
+
+    if ((preg_match('/^(http|https):/i', $url)) // absolute url
+        &&  ((stripos($url, $CFG->wwwroot)!==0) && stripos($url, $CFG->httpswwwroot)!==0)) { // and not local one
+        return $url; //don't attach sessid to non local urls
+    }
+    if ($url[0]=='#' || (stripos($url, 'javascript:')===0)) {
+        return $url; //don't attach sessid to anchors
+    }
+    if (strpos($url, session_name())!==FALSE) {
+        return $url; //don't attach sessid to url that already has one sessid
+    }
+    if (strpos($url, "?")===FALSE) {
+        $append = "?".strip_tags(session_name() . '=' . session_id());
+    }    else {
+        $append = "&amp;".strip_tags(session_name() . '=' . session_id());
     }
+    //put sessid before any anchor
+    $p = strpos($url, "#");
+    if ($p!==FALSE){
+        $anch = substr($url, $p);
+        $url = substr($url, 0, $p).$append.$anch ;
+    } else  {
+        $url .= $append ;
+    }
+    return $url;
+}
 
-    /**
-    * Call this function before there has been any output to the browser to
-    * buffer output and add session ids to all internal links.
-    */
-    public static function sid_start_ob(){
-        global $CFG;
-        //don't attach sess id for bots
-
-        if (!empty($_SERVER['HTTP_USER_AGENT'])) {
-            if (!empty($CFG->opentogoogle)) {
-                if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false) {
-                    @ini_set('session.use_trans_sid', '0'); // try and turn off trans_sid
-                    $CFG->usesid=false;
-                    return;
-                }
-                if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false) {
-                    @ini_set('session.use_trans_sid', '0'); // try and turn off trans_sid
-                    $CFG->usesid=false;
-                    return;
-                }
+/**
+* Call this function before there has been any output to the browser to
+* buffer output and add session ids to all internal links.
+*/
+function sid_start_ob(){
+    global $CFG;
+    //don't attach sess id for bots
+
+    if (!empty($_SERVER['HTTP_USER_AGENT'])) {
+        if (!empty($CFG->opentogoogle)) {
+            if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false) {
+                @ini_set('session.use_trans_sid', '0'); // try and turn off trans_sid
+                $CFG->usesid=false;
+                return;
             }
-            if (strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) {
+            if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false) {
                 @ini_set('session.use_trans_sid', '0'); // try and turn off trans_sid
                 $CFG->usesid=false;
                 return;
             }
         }
+        if (strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) {
+            @ini_set('session.use_trans_sid', '0'); // try and turn off trans_sid
+            $CFG->usesid=false;
+            return;
+        }
+    }
 
-        @ini_set('session.use_trans_sid', '1'); // try and turn on trans_sid
+    @ini_set('session.use_trans_sid', '1'); // try and turn on trans_sid
 
-        if (ini_get('session.use_trans_sid') != 0) {
-            // use trans sid as its available
-            ini_set('url_rewriter.tags', 'a=href,area=href,script=src,link=href,frame=src,form=fakeentry');
-            ob_start(array('moodle_session', 'sid_ob_rewrite_absolute'));
-        } else {
-            //rewrite all links ourselves
-            ob_start(array('moodle_session', 'sid_ob_rewrite'));
-        }
+    if (ini_get('session.use_trans_sid') != 0) {
+        // use trans sid as its available
+        ini_set('url_rewriter.tags', 'a=href,area=href,script=src,link=href,frame=src,form=fakeentry');
+        ob_start('sid_ob_rewrite_absolute');
+    } else {
+        //rewrite all links ourselves
+        ob_start('sid_ob_rewrite');
     }
 }
+
index 9dc398e1ec311787676125bc78a51fbbf7ee7ba7..db3ca6dd5ad3e417e8b15e9dc2a09b7f9874f727 100644 (file)
@@ -386,19 +386,10 @@ global $HTTPSPAGEREQUIRED;
         }
     }
 
-/// start session and prepare global $SESSION
-    $SESSION = new moodle_session();
-
-/// set up global $USER
-    if (!NO_MOODLE_COOKIES) {
-        $USER = &$_SESSION['USER'];
-    } else {
-        $USER     = new object();
-        $USER->id = 0; // user not logged in when session disabled
-        if (isset($CFG->mnet_localhost_id)) {
-            $USER->mnethostid = $CFG->mnet_localhost_id;
-        }
-    }
+/// start session and prepare global $SESSION, $USER
+    get_session();
+    $SESSION = &$_SESSION['SESSION'];
+    $USER    = &$_SESSION['USER'];
 
     if (defined('FULLME')) {     // Usually in command-line scripts like admin/cron.php
         $FULLME = FULLME;
@@ -430,9 +421,6 @@ global $HTTPSPAGEREQUIRED;
         $CFG->theme = 'standardwhite';
     }
 
-/// now do a session test to prevent random user switching - observed on some PHP/Apache combinations,
-    $SESSION->session_verify();
-
 /// Set language/locale of printed times.  If user has chosen a language that
 /// that is different from the site language, then use the locale specified
 /// in the language file.  Otherwise, if the admin hasn't specified a locale
index 4f7a6712c3be0900442bf5bdf0b326fd602df1dd..5e4a15e9a3e1495397fe94a544475ff1b9ddbc29 100644 (file)
@@ -48,7 +48,7 @@
                 print_error('cannotfinduser', '', '', $username);
             }
 
-            $SESSION->set_moodle_cookie($USER->username);
+            set_moodle_cookie($USER->username);
 
             if ( ! empty($SESSION->wantsurl) ) {   // Send them where they were going
                 $goto = $SESSION->wantsurl;
index 03b7c1a6065759124db676237e9375da63e7a99d..f8a61df48c561699f394544abb02feaee8bb1e3f 100644 (file)
@@ -99,7 +99,7 @@ httpsrequired();
 
 /// Check if the user has actually submitted login data to us
 
-    if (empty($CFG->usesid) and $testcookies and ($SESSION->get_moodle_cookie() == '')) {    // Login without cookie when test requested
+    if (empty($CFG->usesid) and $testcookies and (get_moodle_cookie() == '')) {    // Login without cookie when test requested
 
         $errormsg = get_string("cookiesnotenabled");
         $errorcode = 1;
@@ -268,12 +268,12 @@ httpsrequired();
 
 /// Generate the login page with forms
 
-    if ($SESSION->get_moodle_cookie() == '') {
-        $SESSION->set_moodle_cookie('nobody');   // To help search for cookies
+    if (get_moodle_cookie() == '') {
+        set_moodle_cookie('nobody');   // To help search for cookies
     }
 
     if (empty($frm->username) && $authsequence[0] != 'shibboleth') {  // See bug 5184
-        $frm->username = $SESSION->get_moodle_cookie() === 'nobody' ? '' : $SESSION->get_moodle_cookie();
+        $frm->username = get_moodle_cookie() === 'nobody' ? '' : get_moodle_cookie();
         $frm->password = "";
     }