Index: theme/preview.php
===================================================================
RCS file: /cvsroot/moodle/moodle/theme/preview.php,v
retrieving revision 1.10
diff -u -r1.10 preview.php
--- theme/preview.php	29 Jun 2009 03:10:06 -0000	1.10
+++ theme/preview.php	30 Jun 2009 12:57:53 -0000
@@ -1,41 +1,49 @@
-<?php // $Id: preview.php,v 1.10 2009/06/29 03:10:06 tjhunt Exp $
+<?php
 
-    require_once("../config.php");
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * This page alows you to preview an arbitrary theme before selecting it.
+ */
+
+require_once("../config.php");
+
+$preview = optional_param('preview','standard',PARAM_FILE); // which theme to show
+
+if (!file_exists($CFG->themedir .'/'. $preview)) {
+    $preview = 'standard';
+}
+
+require_login();
+
+require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM));
+
+$PAGE->force_theme($preview);
+
+$strthemes = get_string('themes');
+$strpreview = get_string('preview');
+
+$navlinks = array();
+$navlinks[] = array('name' => $strthemes, 'link' => null, 'type' => 'misc');
+$navlinks[] = array('name' => $strpreview, 'link' => null, 'type' => 'misc');
+$navigation = build_navigation($navlinks);
+print_header("$SITE->shortname: $strpreview", $SITE->fullname, $navigation);
+
+print_box_start();
+print_heading($preview);
+print_box_end();
 
-    $preview = optional_param('preview','standard',PARAM_FILE); // which theme to show
-
-    if (!file_exists($CFG->themedir .'/'. $preview)) {
-        $preview = 'standard';
-    }
-
-    if (!$site = get_site()) {
-        print_error('siteisnotdefined', 'debug');
-    }
-
-    require_login();
-
-    require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM));
-
-    $CFG->theme = $preview;
-
-    theme_setup($CFG->theme, array('forceconfig='.$CFG->theme));
-
-    $stradministration = get_string("administration");
-    $strconfiguration = get_string("configuration");
-    $strthemes = get_string("themes");
-    $strpreview = get_string("preview");
-    $strsavechanges = get_string("savechanges");
-    $strtheme = get_string("theme");
-    $strthemesaved = get_string("themesaved");
-
-    $navlinks = array();
-    $navlinks[] = array('name' => $strthemes, 'link' => null, 'type' => 'misc');
-    $navlinks[] = array('name' => $strpreview, 'link' => null, 'type' => 'misc');
-    $navigation = build_navigation($navlinks);
-    print_header("$site->shortname: $strpreview", $site->fullname, $navigation);
-
-    print_box_start();
-    print_heading($preview);
-    print_box_end();
-
-    print_footer();
+print_footer();
\ No newline at end of file
Index: theme/index.php
===================================================================
RCS file: /cvsroot/moodle/moodle/theme/index.php,v
retrieving revision 1.45
diff -u -r1.45 index.php
--- theme/index.php	26 Jun 2009 10:29:56 -0000	1.45
+++ theme/index.php	30 Jun 2009 12:57:53 -0000
@@ -1,144 +1,162 @@
-<?php // $Id: index.php,v 1.45 2009/06/26 10:29:56 tjhunt Exp $
+<?php
 
-    require_once("../config.php");
-    require_once($CFG->libdir.'/adminlib.php');
-
-    $choose = optional_param("choose",'',PARAM_FILE);   // set this theme as default
-
-    admin_externalpage_setup('themeselector');
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * This page prvides the Administration -> ... -> Theme selector UI.
+ */
+
+require_once("../config.php");
+require_once($CFG->libdir.'/adminlib.php');
+
+$choose = optional_param("choose",'',PARAM_FILE);   // set this theme as default
+
+admin_externalpage_setup('themeselector');
+
+unset($SESSION->theme);
+
+$stradministration = get_string("administration");
+$strconfiguration = get_string("configuration");
+$strthemes = get_string("themes");
+$strpreview = get_string("preview");
+$strchoose = get_string("choose");
+$strinfo = get_string("info");
+$strtheme = get_string("theme");
+$strthemesaved = get_string("themesaved");
+$strscreenshot = get_string("screenshot");
+$stroldtheme = get_string("oldtheme");
+
+
+if ($choose and confirm_sesskey()) {
+    if (!is_dir($CFG->themedir .'/'. $choose)) {
+        print_error('themenotinstall');
+    }
+    if (set_config("theme", $choose)) {
+        admin_externalpage_print_header();
+        print_heading(get_string("themesaved"));
+
+        if (file_exists("$choose/README.html")) {
+            print_box_start();
+            readfile("$choose/README.html");
+            print_box_end();
+
+        } else if (file_exists("$choose/README.txt")) {
+            print_box_start("center");
+            $file = file("$choose/README.txt");
+            echo format_text(implode('', $file), FORMAT_MOODLE);
+            print_box_end();
+        }
+
+        print_continue("$CFG->wwwroot/");
+
+        admin_externalpage_print_footer();
+        exit;
+    } else {
+        print_error('cannotsettheme');
+    }
+}
 
-    unset($SESSION->theme);
+admin_externalpage_print_header('themeselector');
 
-    $stradministration = get_string("administration");
-    $strconfiguration = get_string("configuration");
-    $strthemes = get_string("themes");
-    $strpreview = get_string("preview");
-    $strchoose = get_string("choose");
-    $strinfo = get_string("info");
-    $strtheme = get_string("theme");
-    $strthemesaved = get_string("themesaved");
-    $strscreenshot = get_string("screenshot");
-    $stroldtheme = get_string("oldtheme");
 
+print_heading($strthemes);
 
-    if ($choose and confirm_sesskey()) {
-        if (!is_dir($CFG->themedir .'/'. $choose)) {
-            print_error('themenotinstall');
-        }
-        if (set_config("theme", $choose)) {
-            theme_setup($choose);
-            admin_externalpage_print_header();
-            print_heading(get_string("themesaved"));
-
-            if (file_exists("$choose/README.html")) {
-                print_box_start();
-                readfile("$choose/README.html");
-                print_box_end();
-
-            } else if (file_exists("$choose/README.txt")) {
-                print_box_start("center");
-                $file = file("$choose/README.txt");
-                echo format_text(implode('', $file), FORMAT_MOODLE);
-                print_box_end();
-            }
-            
-            print_continue("$CFG->wwwroot/");
-            
-            admin_externalpage_print_footer();
-            exit;
-        } else {
-            print_error('cannotsettheme');
-        }
-    }
+$themes = get_plugin_list("theme");
+$sesskey = sesskey();
 
-    admin_externalpage_print_header('themeselector');
+echo "<table style=\"margin-left:auto;margin-right:auto;\" cellpadding=\"7\" cellspacing=\"5\">\n";
 
+if (!$USER->screenreader) {
+    echo "\t<tr class=\"generaltableheader\">\n\t\t<th scope=\"col\">$strtheme</th>\n";
+    echo "\t\t<th scope=\"col\">$strinfo</th>\n\t</tr>\n";
+}
 
-    print_heading($strthemes);
+$original_theme = fullclone($THEME);
 
-    $themes = get_plugin_list("theme");
-    $sesskey = sesskey();
+foreach ($themes as $theme => $themedir) {
 
-    echo "<table style=\"margin-left:auto;margin-right:auto;\" cellpadding=\"7\" cellspacing=\"5\">\n";
+    unset($THEME);
 
-    if (!$USER->screenreader) {
-        echo "\t<tr class=\"generaltableheader\">\n\t\t<th scope=\"col\">$strtheme</th>\n";
-        echo "\t\t<th scope=\"col\">$strinfo</th>\n\t</tr>\n";
+    if (!file_exists($themedir.'/config.php')) {   // bad folder
+        continue;
     }
 
-    $original_theme = fullclone($THEME);
+    include($themedir.'/config.php');
 
-    foreach ($themes as $theme => $themedir) {
+    $readme = '';
+    $screenshot = '';
+    $screenshotpath = '';
+
+    if (file_exists("$theme/README.html")) {
+        $readme =  "\t\t\t\t<li>".
+        link_to_popup_window($CFG->themewww .'/'. $theme .'/README.html', $theme, $strinfo, 400, 500, '', 'none', true)."</li>\n";
+    } else if (file_exists("$theme/README.txt")) {
+        $readme =  "\t\t\t\t<li>".
+        link_to_popup_window($CFG->themewww .'/'. $theme .'/README.txt', $theme, $strinfo, 400, 500, '', 'none', true)."</li>\n";
+    }
+    if (file_exists("$theme/screenshot.png")) {
+        $screenshotpath = "$theme/screenshot.png";
+    } else if (file_exists("$theme/screenshot.jpg")) {
+        $screenshotpath = "$theme/screenshot.jpg";
+    }
 
-        unset($THEME);
+    echo "\t<tr>\n";
 
-        if (!file_exists($themedir.'/config.php')) {   // bad folder
-            continue;
+    // no point showing this if user is using screen reader
+    if (!$USER->screenreader) {
+        echo "\t\t<td align=\"center\">\n";
+        if ($screenshotpath) {
+            $screenshot = "\t\t\t\t<li><a href=\"$theme/screenshot.jpg\">$strscreenshot</a></li>\n";
+            echo "\t\t\t<object type=\"text/html\" data=\"$screenshotpath\" height=\"200\" width=\"400\">$theme</object>\n\t\t</td>\n";
+        } else {
+            echo "\t\t\t<object type=\"text/html\" data=\"preview.php?preview=$theme\" height=\"200\" width=\"400\">$theme</object>\n\t\t</td>\n";
         }
+    }
 
-        include($themedir.'/config.php');
-
-        $readme = '';
-        $screenshot = '';
-        $screenshotpath = '';
-
-        if (file_exists("$theme/README.html")) {
-            $readme =  "\t\t\t\t<li>".
-            link_to_popup_window($CFG->themewww .'/'. $theme .'/README.html', $theme, $strinfo, 400, 500, '', 'none', true)."</li>\n";
-        } else if (file_exists("$theme/README.txt")) {
-            $readme =  "\t\t\t\t<li>".
-            link_to_popup_window($CFG->themewww .'/'. $theme .'/README.txt', $theme, $strinfo, 400, 500, '', 'none', true)."</li>\n";
-        }
-        if (file_exists("$theme/screenshot.png")) {
-            $screenshotpath = "$theme/screenshot.png";
-        } else if (file_exists("$theme/screenshot.jpg")) {
-            $screenshotpath = "$theme/screenshot.jpg";
-        }
+    if ($CFG->theme == $theme) {
+        echo "\t\t" . '<td valign="top" style="border-style:solid; border-width:1px; border-color:#555555">'."\n";
+    } else {
+        echo "\t\t" . '<td valign="top">'."\n";
+    }
 
-        echo "\t<tr>\n";
+    if (isset($THEME->sheets)) {
+        echo "\t\t\t" . '<p style="font-size:1.5em;font-weight:bold;">'.$theme.'</p>'."\n";
+    } else {
+        echo "\t\t\t" . '<p style="font-size:1.5em;font-weight:bold;color:red;">'.$theme.' (Moodle 1.4)</p>'."\n";
+    }
 
-        // no point showing this if user is using screen reader
+    if ($screenshot or $readme) {
+        echo "\t\t\t<ul>\n";
         if (!$USER->screenreader) {
-            echo "\t\t<td align=\"center\">\n";
-            if ($screenshotpath) {
-                $screenshot = "\t\t\t\t<li><a href=\"$theme/screenshot.jpg\">$strscreenshot</a></li>\n";
-                echo "\t\t\t<object type=\"text/html\" data=\"$screenshotpath\" height=\"200\" width=\"400\">$theme</object>\n\t\t</td>\n";
-            } else {
-                echo "\t\t\t<object type=\"text/html\" data=\"preview.php?preview=$theme\" height=\"200\" width=\"400\">$theme</object>\n\t\t</td>\n";
-            }
-        }
-
-        if ($CFG->theme == $theme) {
-            echo "\t\t" . '<td valign="top" style="border-style:solid; border-width:1px; border-color:#555555">'."\n";
-        } else {
-            echo "\t\t" . '<td valign="top">'."\n";
+            echo "\t\t\t\t<li><a href=\"preview.php?preview=$theme\">$strpreview</a></li>\n";
         }
-
-        if (isset($THEME->sheets)) {
-            echo "\t\t\t" . '<p style="font-size:1.5em;font-weight:bold;">'.$theme.'</p>'."\n";
-        } else {
-            echo "\t\t\t" . '<p style="font-size:1.5em;font-weight:bold;color:red;">'.$theme.' (Moodle 1.4)</p>'."\n";
-        }
-
-        if ($screenshot or $readme) {
-            echo "\t\t\t<ul>\n";
-            if (!$USER->screenreader) {
-                echo "\t\t\t\t<li><a href=\"preview.php?preview=$theme\">$strpreview</a></li>\n";
-            }
-            echo $screenshot.$readme;
-            echo "\t\t\t</ul>\n";
-        }
-
-        $options = null;
-        $options['choose'] = $theme;
-        $options['sesskey'] = $sesskey;
-        echo "\t\t\t" . print_single_button('index.php', $options, $strchoose, 'get', null, true) . "\n";
-        echo "\t\t</td>\n";
-        echo "\t</tr>\n";
+        echo $screenshot.$readme;
+        echo "\t\t\t</ul>\n";
     }
-    echo "</table>\n";
 
-    $THEME = $original_theme;
+    $options = null;
+    $options['choose'] = $theme;
+    $options['sesskey'] = $sesskey;
+    echo "\t\t\t" . print_single_button('index.php', $options, $strchoose, 'get', null, true) . "\n";
+    echo "\t\t</td>\n";
+    echo "\t</tr>\n";
+}
+echo "</table>\n";
+
+$THEME = $original_theme;
 
-    admin_externalpage_print_footer();
+admin_externalpage_print_footer();
 ?>
Index: lib/weblib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/weblib.php,v
retrieving revision 1.1281
diff -u -r1.1281 weblib.php
--- lib/weblib.php	29 Jun 2009 08:17:31 -0000	1.1281
+++ lib/weblib.php	30 Jun 2009 12:57:53 -0000
@@ -2358,256 +2358,6 @@
 }
 
 /**
- * Print a standard header
- *
- * @param string  $title Appears at the top of the window
- * @param string  $heading Appears at the top of the page
- * @param string  $navigation Array of $navlinks arrays (keys: name, link, type) for use as breadcrumbs links
- * @param string  $focus Indicates form element to get cursor focus on load eg  inputform.password
- * @param string  $meta Meta tags to be added to the header
- * @param boolean $cache Should this page be cacheable?
- * @param string  $button HTML code for a button (usually for module editing)
- * @param string  $menu HTML code for a popup menu
- * @param boolean $usexml use XML for this page
- * @param string  $bodytags This text will be included verbatim in the <body> tag (useful for onload() etc)
- * @param bool    $return If true, return the visible elements of the header instead of echoing them.
- * @return string|void If return=true then string else void
- */
-function print_header_old($title='', $heading='', $navigation='', $focus='',
-                       $meta='', $cache=true, $button='&nbsp;', $menu='',
-                       $usexml=false, $bodytags='', $return=false) {
-
-    global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE, $PAGE;
-
-    if (gettype($navigation) == 'string' && strlen($navigation) != 0 && $navigation != 'home') {
-        debugging("print_header() was sent a string as 3rd ($navigation) parameter. "
-                . "This is deprecated in favour of an array built by build_navigation(). Please upgrade your code.", DEBUG_DEVELOPER);
-    }
-
-    $PAGE->set_state(moodle_page::STATE_PRINTING_HEADER);
-
-    $heading = format_string($heading); // Fix for MDL-8582
-
-    if (CLI_SCRIPT) {
-        $output = $heading."\n";
-        if ($return) {
-            return $output;
-        } else {
-            echo $output;
-            return;
-        }
-    }
-
-/// Add the required stylesheets
-    $stylesheetshtml = '';
-    foreach ($CFG->stylesheets as $stylesheet) {
-        $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
-    }
-    $meta = $stylesheetshtml.$meta;
-
-
-/// Add the meta page from the themes if any were requested
-
-    $metapage = '';
-
-    if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
-        ob_start();
-        include_once($CFG->dirroot.'/theme/standard/meta.php');
-        $metapage .= ob_get_contents();
-        ob_end_clean();
-    }
-
-    if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
-        if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
-            ob_start();
-            include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
-            $metapage .= ob_get_contents();
-            ob_end_clean();
-        }
-    }
-
-    if (!isset($THEME->metainclude) || $THEME->metainclude) {
-        if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
-            ob_start();
-            include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
-            $metapage .= ob_get_contents();
-            ob_end_clean();
-        }
-    }
-
-    $meta = $meta."\n".$metapage;
-    $meta .= $PAGE->requires->get_head_code();
-
-/// Set up some navigation variables
-
-    if (is_newnav($navigation)){
-        $home = false;
-    } else {
-        if ($navigation == 'home') {
-            $home = true;
-            $navigation = '';
-        } else {
-            $home = false;
-        }
-    }
-
-/// This is another ugly hack to make navigation elements available to print_footer later
-    $THEME->title      = $title;
-    $THEME->heading    = $heading;
-    $THEME->navigation = $navigation;
-    $THEME->button     = $button;
-    $THEME->menu       = $menu;
-    $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
-
-    if ($button == '') {
-        $button = '&nbsp;';
-    }
-
-    if (!empty($CFG->maintenance_enabled)) {
-        $button = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/settings.php?section=maintenancemode">'.get_string('maintenancemode', 'admin').'</a> '.$button;
-        if(!empty($title)) {
-            $title .= ' - ';
-        }
-        $title .= get_string('maintenancemode', 'admin');
-    }
-
-    if (!$menu and $navigation) {
-        if (empty($CFG->loginhttps)) {
-            $wwwroot = $CFG->wwwroot;
-        } else {
-            $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
-        }
-        $menu = user_login_string($COURSE);
-    }
-
-    if (isset($SESSION->justloggedin)) {
-        unset($SESSION->justloggedin);
-        if (!empty($CFG->displayloginfailures)) {
-            if (!empty($USER->username) and $USER->username != 'guest') {
-                if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
-                    $menu .= '&nbsp;<font size="1">';
-                    if (empty($count->accounts)) {
-                        $menu .= get_string('failedloginattempts', '', $count);
-                    } else {
-                        $menu .= get_string('failedloginattemptsall', '', $count);
-                    }
-                    if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
-                        $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
-                                             '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
-                    }
-                    $menu .= '</font>';
-                }
-            }
-        }
-    }
-
-
-    $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
-            "\n" . $meta . "\n";
-    if (!$usexml) {
-        @header('Content-Type: text/html; charset=utf-8');
-    }
-    @header('Content-Script-Type: text/javascript');
-    @header('Content-Style-Type: text/css');
-
-    //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
-    $direction = get_html_lang($dir=true);
-
-    if ($cache) {  // Allow caching on "back" (but not on normal clicks)
-        @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
-        @header('Pragma: no-cache');
-        @header('Expires: ');
-    } else {       // Do everything we can to always prevent clients and proxies caching
-        @header('Cache-Control: no-store, no-cache, must-revalidate');
-        @header('Cache-Control: post-check=0, pre-check=0', false);
-        @header('Pragma: no-cache');
-        @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
-        @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
-
-        $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
-        $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
-    }
-    @header('Accept-Ranges: none');
-
-    $currentlanguage = current_language();
-
-    if (empty($usexml)) {
-        $direction =  ' xmlns="http://www.w3.org/1999/xhtml"'. $direction;  // See debug_header
-    } else {
-        $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
-        if(!$mathplayer) {
-            header('Content-Type: application/xhtml+xml');
-        }
-        echo '<?xml version="1.0" ?>'."\n";
-        if (!empty($CFG->xml_stylesheets)) {
-            $stylesheets = explode(';', $CFG->xml_stylesheets);
-            foreach ($stylesheets as $stylesheet) {
-                echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
-            }
-        }
-        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
-        if (!empty($CFG->xml_doctype_extra)) {
-            echo ' plus '. $CFG->xml_doctype_extra;
-        }
-        echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
-        $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
-                       xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
-                       xmlns:xlink=\"http://www.w3.org/1999/xlink\"
-                       $direction";
-        if($mathplayer) {
-            $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
-            $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
-            $meta .= '</object>'."\n";
-            $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
-        }
-    }
-
-    // Clean up the title
-
-    $title = format_string($title);    // fix for MDL-8582
-    $title = str_replace('"', '&quot;', $title);
-
-    // Create class and id for this page
-    $pageid = $PAGE->pagetype;
-    $pageclass = $PAGE->bodyclasses;
-    $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
-
-    ob_start();
-    include($CFG->header);
-    $output = ob_get_contents();
-    ob_end_clean();
-
-    // container debugging info
-    $THEME->open_header_containers = open_containers();
-
-    // Skip to main content, see skip_main_destination().
-    if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
-        $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
-        if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
-            preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
-        }
-        $output = $matches[1]."\n". $skiplink .$matches[2];
-    }
-
-    $output = force_strict_header($output);
-
-    if (!empty($CFG->messaging)) {
-        $output .= message_popup_window();
-    }
-
-    // Add in any extra JavaScript libraries that occurred during the header
-    $output .= $PAGE->requires->get_top_of_body_code();
-
-    $PAGE->set_state(moodle_page::STATE_IN_BODY);
-
-    if ($return) {
-        return $output;
-    } else {
-        echo $output;
-    }
-}
-
-/**
  * This version of print_header is simpler because the course name does not have to be
  * provided explicitly in the strings. It can be used on the site page as in courses
  * Eventually all print_header could be replaced by print_header_simple
@@ -2656,569 +2406,6 @@
     }
 }
 
-
-/**
- * Can provide a course object to make the footer contain a link to
- * to the course home page, otherwise the link will go to the site home
- *
- * @global object
- * @global object
- * @global object
- * @global object Apparently not used in this function
- * @global string
- * @global object
- * @param mixed $course course object, used for course link button or
- *                      'none' means no user link, only docs link
- *                      'empty' means nothing printed in footer
- *                      'home' special frontpage footer
- * @param object $usercourse course used in user link
- * @param boolean $return output as string
- * @return mixed string or void
- */
-function print_footer_old($course=NULL, $usercourse=NULL, $return=false) {
-    global $USER, $CFG, $THEME, $COURSE, $SITE, $PAGE;
-
-    if (defined('ADMIN_EXT_HEADER_PRINTED') and !defined('ADMIN_EXT_FOOTER_PRINTED')) {
-        admin_externalpage_print_footer();
-        return;
-    }
-
-    $PAGE->set_state(moodle_page::STATE_PRINTING_FOOTER);
-
-/// Course links or special footer
-    if ($course) {
-        if ($course === 'empty') {
-            // special hack - sometimes we do not want even the docs link in footer
-            $output = '';
-            if (!empty($THEME->open_header_containers)) {
-                for ($i=0; $i<$THEME->open_header_containers; $i++) {
-                    $output .= print_container_end_all(); // containers opened from header
-                }
-            } else {
-                //1.8 theme compatibility
-                $output .= "\n</div>"; // content div
-            }
-            $output .= "\n</div>\n" . $PAGE->requires->get_end_code() . "</body>\n</html>"; // close page div started in header
-            if ($return) {
-                return $output;
-            } else {
-                echo $output;
-                return;
-            }
-
-        } else if ($course === 'none') {          // Don't print any links etc
-            $homelink = '';
-            $loggedinas = '';
-            $home  = false;
-
-        } else if ($course === 'home') {   // special case for site home page - please do not remove
-            $course = $SITE;
-            $homelink  = '<div class="sitelink">'.
-               '<a title="Moodle '. $CFG->release .'" href="http://moodle.org/">'.
-               '<img style="width:100px;height:30px" src="'.$CFG->wwwroot.'/pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
-            $home  = true;
-
-        } else if ($course === 'upgrade') {
-            $home = false;
-            $loggedinas = '';
-            $homelink  = '<div class="sitelink">'.
-               '<a title="Moodle '. $CFG->target_release .'" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">'.
-               '<img style="width:100px;height:30px" src="'.$CFG->wwwroot.'/pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
-
-        } else {
-            $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
-                        '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
-            $home  = false;
-        }
-
-    } else {
-        $course = $SITE;  // Set course as site course by default
-        $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
-        $home  = false;
-    }
-
-/// Set up some other navigation links (passed from print_header by ugly hack)
-    $menu        = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
-    $title       = isset($THEME->title) ? $THEME->title : '';
-    $button      = isset($THEME->button) ? $THEME->button : '';
-    $heading     = isset($THEME->heading) ? $THEME->heading : '';
-    $navigation  = isset($THEME->navigation) ? $THEME->navigation : '';
-    $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';
-
-
-/// Set the user link if necessary
-    if (!$usercourse and is_object($course)) {
-        $usercourse = $course;
-    }
-
-    if (!isset($loggedinas)) {
-        $loggedinas = user_login_string($usercourse, $USER);
-    }
-
-    if ($loggedinas == $menu) {
-        $menu = '';
-    }
-
-/// there should be exactly the same number of open containers as after the header
-    if ($THEME->open_header_containers != open_containers()) {
-        debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
-    }
-
-/// Provide some performance info if required
-    $performanceinfo = '';
-    if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
-        $perf = get_performance_info();
-        if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
-            error_log("PERF: " . $perf['txt']);
-        }
-        if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
-            $performanceinfo = $perf['html'];
-        }
-    }
-
-/// Include the actual footer file
-
-    ob_start();
-    include($CFG->footer);
-    $output = ob_get_contents();
-    ob_end_clean();
-
-    // Put the end of page <script> tags just inside </body> to maintain validity.
-    $output = str_replace('</body>', $PAGE->requires->get_end_code() . '</body>', $output); 
-
-    $PAGE->set_state(moodle_page::STATE_DONE);
-
-    if ($return) {
-        return $output;
-    } else {
-        echo $output;
-    }
-}
-
-/**
- * Returns the name of the current theme
- *
- * @global object
- * @global object
- * @global object
- * @global object
- * @global string
- * @return string
- */
-function current_theme() {
-    global $CFG, $USER, $SESSION, $COURSE, $SCRIPT;
-
-    if (empty($CFG->themeorder)) {
-        $themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
-    } else {
-        $themeorder = $CFG->themeorder;
-    }
-
-    if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) {
-        require_once($CFG->dirroot.'/mnet/peer.php');
-        $mnet_peer = new mnet_peer();
-        $mnet_peer->set_id($USER->mnethostid);
-    }
-
-    $theme = '';
-    foreach ($themeorder as $themetype) {
-
-        if (!empty($theme)) continue;
-
-        switch ($themetype) {
-            case 'page': // Page theme is for special page-only themes set by code
-                if (!empty($CFG->pagetheme)) {
-                    $theme = $CFG->pagetheme;
-                }
-                break;
-            case 'course':
-                if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) {
-                    $theme = $COURSE->theme;
-                }
-                break;
-            case 'category':
-                if (!empty($CFG->allowcategorythemes)) {
-                /// Nasty hack to check if we're in a category page
-                    if ($SCRIPT == '/course/category.php') {
-                        global $id;
-                        if (!empty($id)) {
-                            $theme = current_category_theme($id);
-                        }
-                /// Otherwise check if we're in a course that has a category theme set
-                    } else if (!empty($COURSE->category)) {
-                        $theme = current_category_theme($COURSE->category);
-                    }
-                }
-                break;
-            case 'session':
-                if (!empty($SESSION->theme)) {
-                    $theme = $SESSION->theme;
-                }
-                break;
-            case 'user':
-                if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
-                    if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
-                        $theme = $mnet_peer->theme;
-                    } else {
-                        $theme = $USER->theme;
-                    }
-                }
-                break;
-            case 'site':
-                if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') {
-                    $theme = $mnet_peer->theme;
-                } else {
-                    $theme = $CFG->theme;
-                }
-                break;
-            default:
-                /// do nothing
-        }
-    }
-
-/// A final check in case 'site' was not included in $CFG->themeorder
-    if (empty($theme)) {
-        $theme = $CFG->theme;
-    }
-
-    return $theme;
-}
-
-/**
- * Retrieves the category theme if one exists, otherwise checks the parent categories.
- * Recursive function.
- *
- * @global object
- * @global object
- * @param   integer   $categoryid   id of the category to check
- * @return  string    theme name
- */
-function current_category_theme($categoryid=0) {
-    global $COURSE, $DB;
-
-/// Use the COURSE global if the categoryid not set
-    if (empty($categoryid)) {
-        if (!empty($COURSE->category)) {
-            $categoryid = $COURSE->category;
-        } else {
-            return false;
-        }
-    }
-
-/// Retrieve the current category
-    if ($category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
-
-    /// Return the category theme if it exists
-        if (!empty($category->theme)) {
-            return $category->theme;
-
-    /// Otherwise try the parent category if one exists
-        } else if (!empty($category->parent)) {
-            return current_category_theme($category->parent);
-        }
-
-/// Return false if we can't find the category record
-    } else {
-        return false;
-    }
-}
-
-/**
- * This function is called by stylesheets to set up the header
- * approriately as well as the current path
- *
- * @global object
- * @global object
- * @uses PARAM_SAFEDIR
- * @param int $lastmodified Always gets set to now
- * @param int $lifetime The max-age header setting (seconds) defaults to 300
- * @param string $themename The name of the theme to use (optional) defaults to current theme
- * @param string $forceconfig Force a particular theme config (optional)
- * @param string $lang Load styles for the specified language (optional)
- */
-function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
-
-    global $CFG, $THEME;
-
-    // Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
-    $lastmodified = time();
-
-    header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
-    header('Expires: ' . gmdate("D, d M Y H:i:s", time() + $lifetime) . ' GMT');
-    header('Cache-Control: max-age='. $lifetime);
-    header('Pragma: ');
-    header('Content-type: text/css'); // Correct MIME type
-
-    $DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
-
-    if (empty($themename)) {
-        $themename = current_theme(); // So we have something.  Normally not needed.
-    } else {
-        $themename = clean_param($themename, PARAM_SAFEDIR);
-    }
-
-    theme_setup($themename);
-
-    if (!empty($forceconfig)) { // Page wants to use the config from this theme instead
-        unset($THEME);
-        include($CFG->themedir.'/'.$forceconfig.'/'.'config.php');
-    }
-
-/// If this is the standard theme calling us, then find out what sheets we need
-    if ($themename == 'standard') {
-        if (!isset($THEME->standardsheets) or $THEME->standardsheets === true) { // Use all the sheets we have
-            $THEME->sheets = $DEFAULT_SHEET_LIST;
-        } else if (empty($THEME->standardsheets)) { // We can stop right now!
-            echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
-            exit;
-        } else { // Use the provided subset only
-            $THEME->sheets = $THEME->standardsheets;
-        }
-
-/// If we are a parent theme, then check for parent definitions
-    } else if (!empty($THEME->parent) && $themename == $THEME->parent) {
-        if (!isset($THEME->parentsheets) or $THEME->parentsheets === true) {     // Use all the sheets we have
-            $THEME->sheets = $DEFAULT_SHEET_LIST;
-        } else if (empty($THEME->parentsheets)) {                                // We can stop right now!
-            echo "/***** Nothing required from this stylesheet by main theme *****/\n\n";
-            exit;
-        } else {                                                                 // Use the provided subset only
-            $THEME->sheets = $THEME->parentsheets;
-        }
-    }
-
-/// Work out the last modified date for this theme
-    foreach ($THEME->sheets as $sheet) {
-        if (file_exists($CFG->themedir.'/'.$themename.'/'.$sheet.'.css')) {
-            $sheetmodified = filemtime($CFG->themedir.'/'.$themename.'/'.$sheet.'.css');
-            if ($sheetmodified > $lastmodified) {
-                $lastmodified = $sheetmodified;
-            }
-        }
-    }
-
-/// Get a list of all the files we want to include
-    $files = array();
-
-    foreach ($THEME->sheets as $sheet) {
-        $files[] = array($CFG->themedir, $themename.'/'.$sheet.'.css');
-    }
-
-    if ($themename == 'standard') {          // Add any standard styles included in any modules
-        if (!empty($THEME->modsheets)) {     // Search for styles.php within activity modules
-            $mods = get_plugin_list('mod');
-            foreach ($mods as $mod => $moddir) {
-                if (file_exists($moddir.'/styles.php')) {
-                    $files[] = array($moddir, 'styles.php');
-                }
-            }
-        }
-
-        if (!empty($THEME->blocksheets)) {     // Search for styles.php within block modules
-            $mods = get_plugin_list('blocks');
-            foreach ($mods as $mod => $moddir) {
-                if (file_exists($moddir.'/styles.php')) {
-                    $files[] = array($moddir, 'styles.php');
-                }
-            }
-        }
-
-        if (!isset($THEME->courseformatsheets) || $THEME->courseformatsheets) { // Search for styles.php in course formats
-            $mods = get_plugin_list('format');
-            foreach ($mods as $mod => $moddir) {
-                if (file_exists($moddir.'/styles.php')) {
-                    $files[] = array($moddir, 'styles.php');
-                }
-            }
-        }
-
-        if (!isset($THEME->gradereportsheets) || $THEME->gradereportsheets) { // Search for styles.php in grade reports
-            $reports = get_plugin_list('gradereport');
-            foreach ($reports as $report => $reportdir) {
-                if (file_exists($reportdir.'/styles.php')) {
-                    $files[] = array($reportdir, 'styles.php');
-                }
-            }
-        }
-
-        if (!empty($THEME->langsheets)) {     // Search for styles.php within the current language
-            if (file_exists($CFG->dirroot.'/lang/'.$lang.'/styles.php')) {
-                $files[] = array($CFG->dirroot, 'lang/'.$lang.'/styles.php');
-            }
-        }
-    }
-
-    if ($files) {
-    /// Produce a list of all the files first
-        echo '/**************************************'."\n";
-        echo ' * THEME NAME: '.$themename."\n *\n";
-        echo ' * Files included in this sheet:'."\n *\n";
-        foreach ($files as $file) {
-            echo ' *   '.$file[1]."\n";
-        }
-        echo ' **************************************/'."\n\n";
-
-
-        /// check if csscobstants is set
-        if (!empty($THEME->cssconstants)) {
-            require_once("$CFG->libdir/cssconstants.php");
-            /// Actually collect all the files in order.
-            $css = '';
-            foreach ($files as $file) {
-                $css .= '/***** '.$file[1].' start *****/'."\n\n";
-                $css .= file_get_contents($file[0].'/'.$file[1]);
-                $ccs .= '/***** '.$file[1].' end *****/'."\n\n";
-            }
-            /// replace css_constants with their values
-            echo replace_cssconstants($css);
-        } else {
-        /// Actually output all the files in order.
-            if (empty($CFG->CSSEdit) && empty($THEME->CSSEdit)) {
-                foreach ($files as $file) {
-                    echo '/***** '.$file[1].' start *****/'."\n\n";
-                    @include_once($file[0].'/'.$file[1]);
-                    echo '/***** '.$file[1].' end *****/'."\n\n";
-                }
-            } else {
-                foreach ($files as $file) {
-                    echo '/* @group '.$file[1].' */'."\n\n";
-                    if (strstr($file[1], '.css') !== FALSE) {
-                        echo '@import url("'.$CFG->themewww.'/'.$file[1].'");'."\n\n";
-                    } else {
-                        @include_once($file[0].'/'.$file[1]);
-                    }
-                    echo '/* @end */'."\n\n";
-                }
-            }
-        }
-    }
-
-    return $CFG->themewww.'/'.$themename;   // Only to help old themes (1.4 and earlier)
-}
-
-/**
- * Sets up the global variables related to theme
- *
- * @global object
- * @global object
- * @global object Apparently not used here
- * @global object Apparently not used here
- * @global object
- * @global object
- * @param string $theme The theme to use defaults to current theme
- * @param array $params An array of parameters to use
- */
-function theme_setup($theme = '', $params=NULL) {
-/// Sets up global variables related to themes
-
-    global $CFG, $THEME, $SESSION, $USER, $HTTPSPAGEREQUIRED, $PAGE;
-
-/// Do not mess with THEME if header already printed - this would break all the extra stuff in global $THEME from print_header()!!
-    if ($PAGE->headerprinted) {
-        return;
-    }
-
-    if (empty($theme)) {
-        $theme = current_theme();
-    }
-
-/// If the theme doesn't exist for some reason then revert to standardwhite
-    if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
-        $CFG->theme = $theme = 'standardwhite';
-    }
-
-/// Load up the theme config
-    $THEME = NULL;   // Just to be sure
-    include($CFG->themedir .'/'. $theme .'/config.php');  // Main config for current theme
-    $THEME->name = $theme;
-    $THEME->dir = $CFG->themedir .'/'. $theme;
-
-/// Put together the parameters
-    if (!$params) {
-        $params = array();
-    }
-
-    if ($theme != $CFG->theme) {
-        $params[] = 'forceconfig='.$theme;
-    }
-
-/// Force language too if required
-    if (!empty($THEME->langsheets)) {
-        $params[] = 'lang='.current_language();
-    }
-
-/// Convert params to string
-    if ($params) {
-        $paramstring = '?'.implode('&', $params);
-    } else {
-        $paramstring = '';
-    }
-
-/// Set up image paths
-    if(isset($CFG->smartpix) && $CFG->smartpix==1) {
-        if($CFG->slasharguments) {        // Use this method if possible for better caching
-            $extra='';
-        } else {
-            $extra='?file=';
-        }
-
-        $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
-        $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
-    } else if (empty($THEME->custompix)) {    // Could be set in the above file
-        $CFG->pixpath = $CFG->wwwroot .'/pix';
-        $CFG->modpixpath = $CFG->wwwroot .'/mod';
-    } else {
-        $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
-        $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
-    }
-
-/// Define stylesheet loading order
-    $CFG->stylesheets = array();
-    if ($theme != 'standard') {    /// The standard sheet is always loaded first
-        $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
-    }
-    if (!empty($THEME->parent)) {  /// Parent stylesheets are loaded next
-        $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
-    }
-    $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;
-
-/// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
-    if (!empty($HTTPSPAGEREQUIRED)) {
-        $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
-        $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
-        $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
-        foreach ($CFG->stylesheets as $key => $stylesheet) {
-            $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
-        }
-    }
-
-// RTL support - only for RTL languages, add RTL CSS
-    if (get_string('thisdirection') == 'rtl') {
-        $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
-        $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
-    }
-
-    // Support legacy themes, by setting sensible defaults for some of the new
-    // properties that were introduced in Moodle 2.0.
-    if (empty($THEME->rendererfactory)) {
-        if (!empty($THEME->customcorners)) {
-            // $THEME->customcorners is deprecated but we provide support for it via the
-            // custom_corners_renderer_factory class in lib/deprecatedlib.php
-            debugging('$THEME->customcorners is deprecated. Please use the new $THEME->rendererfactory to control HTML generation.', DEBUG_DEVELOPER);
-            $THEME->rendererfactory = 'custom_corners_renderer_factory';
-        } else {
-            $THEME->rendererfactory = 'standard_renderer_factory';
-        }
-    }
-    if (empty($THEME->blockregions)) {
-        $THEME->blockregions = array('side-pre', 'side-post');
-    }
-    if (empty($THEME->defaultblockregion)) {
-        $THEME->defaultblockregion = 'side-post';
-    }
-}
-
-
 /**
  * Returns text to be displayed to the user which reflects their login status
  *
@@ -6348,18 +5535,15 @@
 }
 
 /**
- * Returns boolean true if the current language is right-to-left (Hebrew, Arabic etc)
- *
- * @staticvar bool $result
- * @return bool
+ * @return boolean true if the current language is right-to-left (Hebrew, Arabic etc)
  */
 function right_to_left() {
     static $result;
 
-    if (isset($result)) {
-        return $result;
+    if (!isset($result)) {
+        $result = get_string('thisdirection') == 'rtl';
     }
-    return $result = (get_string('thisdirection') == 'rtl');
+    return $result;
 }
 
 
Index: lib/pagelib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/pagelib.php,v
retrieving revision 1.125
diff -u -r1.125 pagelib.php
--- lib/pagelib.php	29 Jun 2009 05:00:45 -0000	1.125
+++ lib/pagelib.php	30 Jun 2009 12:57:50 -0000
@@ -124,6 +124,14 @@
 
     protected $_button = '';
 
+    protected $_theme = null;
+
+    /**
+     * Then the theme is initialsed, we save the stack trace, for use in error messages.
+     * @var array stack trace.
+     */
+    protected $_wherethemewasinitialised = null;
+
     /**
      * This is simply to improve backwards compatability. If old code relies on
      * a page class that implements print_header, or complex logic in
@@ -337,15 +345,12 @@
     public function get_blocks() {
         global $CFG, $THEME;
         if (is_null($this->_blocks)) {
-            initialise_theme_and_output();
             if (!empty($CFG->blockmanagerclass)) {
                 $classname = $CFG->blockmanagerclass;
             } else {
                 $classname = 'block_manager';
             }
             $this->_blocks = new $classname($this);
-            $this->_blocks->add_regions($THEME->blockregions);
-            $this->_blocks->set_default_region($THEME->defaultblockregion);
         }
         return $this->_blocks;
     }
@@ -387,6 +392,17 @@
     }
 
     /**
+     * Please do not call this method directly, use the ->theme syntax. {@link __get()}.
+     * @return string the initialised theme for this page.
+     */
+    public function get_theme() {
+        if (is_null($this->_theme)) {
+            $this->initialise_theme_and_output();
+        }
+        return $this->_theme;
+    }
+
+    /**
      * PHP overloading magic to make the $PAGE->course syntax work by redirecting
      * it to the corresponding $PAGE->get_course() method if there is one, and
      * throwing an exception if not.
@@ -462,28 +478,28 @@
      * @param object the course to set as the global course.
      */
     public function set_course($course) {
-        global $COURSE;
+        global $COURSE, $PAGE;
 
         if (empty($course->id)) {
             throw new coding_exception('$course passed to moodle_page::set_course does not look like a proper course object.');
         }
 
-        if ($this->_state > self::STATE_BEFORE_HEADER) {
-            throw new coding_exception('Cannot call moodle_page::set_course after output has been started.');
-        }
+        $this->ensure_theme_not_set();
 
         if (!empty($this->_course->id) && $this->_course->id != $course->id) {
             $this->_categories = null;
         }
 
         $this->_course = clone($course);
-        $COURSE = $this->_course;
+
+        if ($this === $PAGE) {
+            $COURSE = $this->_course;
+            moodle_setlocale();
+        }
 
         if (!$this->_context) {
             $this->set_context(get_context_instance(CONTEXT_COURSE, $this->_course->id));
         }
-
-        moodle_setlocale();
     }
 
     /**
@@ -626,6 +642,7 @@
         if (is_array($this->_categories)) {
             throw new coding_exception('Course category has already been set. You are not allowed to change it.');
         }
+        $this->ensure_theme_not_set();
         $this->set_course($SITE);
         $this->load_category($categoryid);
         $this->set_context(get_context_instance(CONTEXT_COURSECAT, $categoryid));
@@ -731,6 +748,18 @@
         $this->_cacheable = $cacheable;
     }
 
+    /**
+     * 
+     * @param $themename
+     */
+    public function force_theme($themename) {
+        global $PAGE, $THEME;
+        $this->load_theme_config($themename);
+        if ($this === $PAGE) {
+            $THEME = $this->_theme;
+        }
+    }
+
 /// Initialisation methods =====================================================
 /// These set various things up in a default way.
 
@@ -754,6 +783,165 @@
 
         $this->initialise_standard_body_classes();
         $this->blocks->load_blocks();
+
+        // Add any stylesheets required using the horrible legacy mechanism.
+        if (!empty($CFG->stylesheets)) {
+            debugging('Some code on this page is using the horrible legacy mechanism $CFG->stylesheets to include links to ' .
+                    'extra stylesheets. This is deprecated. Please use $PAGE->requires->css(...) instead.', DEBUG_DEVELOPER);
+            foreach ($CFG->stylesheets as $stylesheet) {
+                $this->page->requires->css($stylesheet, true);
+            }
+        }
+
+        // Require theme stylesheets.
+        $stylesheets = $this->theme->get_stylesheet_urls();
+        foreach ($stylesheets as $stylesheet) {
+            $this->requires->css($stylesheet, true);
+        }
+    }
+
+    /**
+     * 
+     */
+    public function initialise_theme_and_output() {
+        global $OUTPUT, $PAGE, $THEME;
+
+        if (is_null($this->_theme)) {
+            $theme = $this->resolve_theme();
+            $this->load_theme_config($theme);
+        }
+
+        $this->blocks->add_regions($this->_theme->blockregions);
+        $this->blocks->set_default_region($this->_theme->defaultblockregion);
+
+        if ($this === $PAGE) {
+            $THEME = $this->_theme;
+            if (CLI_SCRIPT) {
+                $classname = 'cli_renderer_factory';
+            } else {
+                $classname = $this->_theme->rendererfactory;
+            }
+            $rendererfactory = new $classname($this->_theme, $this);
+            $OUTPUT = $rendererfactory->get_renderer('core');
+        }
+    }
+
+    /**
+     * Based on the 
+     * @return string the name of the theme that should be used on this page.
+     */
+    protected function resolve_theme() {
+        global $CFG, $USER, $SESSION;
+
+        if (empty($CFG->themeorder)) {
+            $themeorder = array('course', 'category', 'session', 'user', 'site');
+        } else {
+            $themeorder = $CFG->themeorder;
+            // Just in case, make sure we always use the site theme if nothing else matched.
+            $themeorder[] = 'site';
+        }
+
+        $mnetpeertheme = '';
+        if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) {
+            require_once($CFG->dirroot.'/mnet/peer.php');
+            $mnetpeer = new mnet_peer();
+            $mnetpeer->set_id($USER->mnethostid);
+            if ($mnetpeer->force_theme == 1 && $mnetpeer->theme != '') {
+                $mnetpeertheme = $mnetpeer->theme;
+            }
+        }
+
+        $theme = '';
+        foreach ($themeorder as $themetype) {
+            switch ($themetype) {
+                case 'course':
+                    if (!empty($CFG->allowcoursethemes) and !empty($this->course->theme)) {
+                        return $this->course->theme;
+                    }
+
+                case 'category':
+                    if (!empty($CFG->allowcategorythemes)) {
+                        $categories = $this->categories;
+                        foreach ($categories as $category) {
+                            if (!empty($category->theme)) {
+                                return $category->theme;
+                            }
+                        }
+                    }
+
+                case 'session':
+                    if (!empty($SESSION->theme)) {
+                        return $SESSION->theme;
+                    }
+
+                case 'user':
+                    if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) {
+                        if ($mnetpeertheme) {
+                            return $mnetpeertheme;
+                        } else {
+                            return $USER->theme;
+                        }
+                    }
+
+                case 'site':
+                    if ($mnetpeertheme) {
+                        return $mnetpeertheme;
+                    } else {
+                        return $CFG->theme;
+                    }
+            }
+        }
+    }
+
+    protected function load_theme_config($themename) {
+        global $CFG, $PAGE;
+        $this->ensure_theme_not_set();
+
+        // Set some other standard properties of the theme.
+        $THEME = new theme_config;
+        $THEME->name = $themename;
+        $THEME->dir = $CFG->themedir . '/' . $themename;
+
+        // Load up the theme config
+        $configfile = $THEME->dir . '/config.php';
+        if (!is_readable($configfile)) {
+            throw new coding_exception('Cannot use theme ' . $themename .
+                    '. The file ' . $configfile . ' does not exist or is not readable.');
+        }
+        include($configfile);
+
+        // Set up image paths
+        if (!empty($CFG->smartpix)) {
+            if ($CFG->slasharguments) {
+                // Use this method if possible for better caching
+                $extra = '';
+            } else {
+                $extra = '?file=';
+            }
+            $CFG->pixpath = $CFG->httpswwwroot . '/pix/smartpix.php' . $extra . '/' . $themename;
+            $CFG->modpixpath = $CFG->httpswwwroot . '/pix/smartpix.php' . $extra . '/' . $themename . '/mod';
+
+        } else if (empty($THEME->custompix)) {
+            $CFG->pixpath = $CFG->httpswwwroot . '/pix';
+            $CFG->modpixpath = $CFG->httpswwwroot . '/mod';
+
+        } else {
+            $CFG->pixpath = $CFG->httpsthemewww . '/' . $themename . '/pix';
+            $CFG->modpixpath = $CFG->httpsthemewww . '/' . $themename . '/pix/mod';
+        }
+
+        // Support legacy themes using customcorners.
+        if (!empty($THEME->customcorners)) {
+            // $THEME->customcorners is deprecated but we provide support for it via the
+            // custom_corners_renderer_factory class in lib/deprecatedlib.php
+            debugging('$THEME->customcorners is deprecated. Please use the new $THEME->rendererfactory to control HTML generation.', DEBUG_DEVELOPER);
+            $THEME->rendererfactory = 'custom_corners_renderer_factory';
+        }
+
+        // Store the newly initialised theme, and also where the initialisation
+        // happened, so we can include that if error messages.
+        $this->_theme = $THEME;
+        $this->_wherethemewasinitialised = debug_backtrace();
     }
 
     /**
@@ -795,7 +983,7 @@
     }
 
     protected function initialise_standard_body_classes() {
-        global $CFG;
+        global $CFG, $USER;
 
         $pagetype = $this->pagetype;
         if ($pagetype == 'site-index') {
@@ -908,6 +1096,15 @@
         }
     }
 
+    protected function ensure_theme_not_set() {
+        if (!is_null($this->_theme)) {
+            throw new coding_exception('The theme has already been set up for this page ready for output. ' .
+                    'Therefore, you can no longer change the theme, or anything that might affect what ' .
+                    'the current theme is, for example, the course.',
+                    'Stack trace when the theme was set up: ' . format_backtrace($this->_wherethemewasinitialised));
+        }
+    }
+
     protected function url_to_class_name($url) {
         $bits = parse_url($url);
         $class = str_replace('.', '-', $bits['host']);
Index: lib/cssconstants.php
===================================================================
RCS file: lib/cssconstants.php
diff -N lib/cssconstants.php
--- lib/cssconstants.php	22 May 2009 08:41:00 -0000	1.3
+++ /dev/null	1 Jan 1970 00:00:00 -0000
@@ -1,102 +0,0 @@
-<?php
-// This file is part of Moodle - http://moodle.org/ 
-// 
-// Moodle is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-//
-// Moodle is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-// 
-// You should have received a copy of the GNU General Public License
-// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
-
-/**
- * Plug in constants/variables    - See MDL-6798 for details
- * 
- * Information from Urs Hunkler:
- * 
- * 
- * More flexible themes with CSS constants: An option for Moodle retro themes and easy colour palette variants.
- * 
- * I adopted Shaun Inman's "CSS Server-side Constants" to Moodle: http://www.shauninman.com/post/heap/2005/08/09/css_constants
- *  
- * With setting "cssconstants" to true in "config.php" you activate the CSS constants. If "cssconstants" is missing or set to "false" the
- * replacement function is not used.
- *  
- * $THEME->cssconstants = true;
- * By setting this to true, you will be able to use CSS constants
- *   
- * The constant definitions are written into a separate CSS file named like "constants.css" and loaded first in config.php. You can use constants for any CSS properties. The constant definition looks like:
- * <code>
- * \@server constants {
- *   fontColor: #3a2830;
- *   aLink: #116699;
- *   aVisited: #AA2200;
- *   aHover: #779911;
- *   pageBackground: #FFFFFF;
- *   backgroundColor: #EEEEEE;
- *   backgroundSideblockHeader: #a8a4e9;
- *   fontcolorSideblockHeader: #222222;
- *   color1: #98818b;
- *   color2: #bd807b;
- *   color3: #f9d1d7;
- *   color4: #e8d4d8;
- * }
- * </code>
- * 
- * The lines in the CSS files using CSS constants look like:
- * <code>
- * body {
- *   font-size: 100%;
- *   background-color: pageBackground;
- *   color: fontColor;
- *   font-family: 'Bitstream Vera Serif', georgia, times, serif;
- *   margin: 0;
- *   padding: 0;
- * }
- * div#page {
- *   margin: 0 10px;
- *   padding-top: 5px;
- *   border-top-width: 10px;
- *   border-top-style: solid;
- *   border-top-color: color3;
- * }
- * div.clearer {
- *   clear: both;
- * }
- * a:link {
- *   color: aLink;
- * } 
- * </code>
- *
- * @package   moodlecore
- * @copyright 1999 onwards Martin Dougiamas  http://dougiamas.com
- * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
- /** 
-  * Replaces CSS Constants within CSS string
-  *
-  * @param string $css
-  * @return string
-  */
-function replace_cssconstants($css) {
-    if (preg_match_all("/@server\s+(?:variables|constants)\s*\{\s*([^\}]+)\s*\}\s*/i",$css,$matches)) {
-        $variables  = array();
-        foreach ($matches[0] as $key=>$server) {
-            $css = str_replace($server,'',$css);
-            preg_match_all("/([^:\}\s]+)\s*:\s*([^;\}]+);/",$matches[1][$key],$vars);
-            foreach ($vars[1] as $var=>$value) {
-                $variables[$value] = $vars[2][$var];
-                }
-            }
-        $css = str_replace(array_keys($variables),array_values($variables),$css);
-        }
-    return ($css);
-}
-
-?>
Index: lib/setuplib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/setuplib.php,v
retrieving revision 1.64
diff -u -r1.64 setuplib.php
--- lib/setuplib.php	30 Jun 2009 05:34:50 -0000	1.64
+++ lib/setuplib.php	30 Jun 2009 12:57:51 -0000
@@ -191,7 +191,7 @@
         }
     }
 
-    echo $OUTPUT->fatal_error($message, $moreinfourl, $link, debug_backtrace());
+    echo $OUTPUT->fatal_error($message, $moreinfourl, $link, debug_backtrace(), $debuginfo);
     exit(1); // General error code
 }
 
@@ -751,16 +751,21 @@
      */
     protected $initialising = false;
 
+    /**
+     * Have we started output yet?
+     * @return boolean true if the header has been printed.
+     */
+    public function has_started() {
+        return false;
+    }
+
     public function __call($method, $arguments) {
-        global $OUTPUT;
+        global $OUTPUT, $PAGE;
 
         // If lib/outputlib.php has been loaded, call it.
-        if (!$this->initialising && function_exists('initialise_theme_and_output')) {
-            $this->initialising = true;
-            initialise_theme_and_output(debug_backtrace());
-            if (!($OUTPUT instanceof bootstrap_renderer)) {
-                return call_user_func_array(array($OUTPUT, $method), $arguments);
-            }
+        if (!empty($PAGE)) {
+            $PAGE->initialise_theme_and_output();
+            return call_user_func_array(array($OUTPUT, $method), $arguments);
         }
 
         $this->initialising = true;
Index: lib/deprecatedlib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/deprecatedlib.php,v
retrieving revision 1.118
diff -u -r1.118 deprecatedlib.php
--- lib/deprecatedlib.php	29 Jun 2009 17:11:34 -0000	1.118
+++ lib/deprecatedlib.php	30 Jun 2009 12:57:45 -0000
@@ -1766,6 +1766,55 @@
 
 
 /**
+ * Used to be used for setting up the theme. No longer used by core code, and
+ * should not have been used elsewhere.
+ *
+ * The theme is now automatically initialised before it is first used. If you really need
+ * to force this to happen, just reference $PAGE->theme.
+ *
+ * To force a particular theme on a particular page, you can use $PAGE->force_theme(...).
+ * However, I can't think of any valid reason to do that outside the theme selector UI.
+ *
+ * @deprecated
+ * @param string $theme The theme to use defaults to current theme
+ * @param array $params An array of parameters to use
+ */
+function theme_setup($theme = '', $params=NULL) {
+    throw new coding_exception('The function theme_setup is no longer required, and should no longer be used. ' .
+            'The current theme gets initialised automatically before it is first used.');
+}
+
+/**
+ * @deprecated use $PAGE->theme->name instead.
+ * @return string the name of the current theme.
+ */
+function current_theme() {
+    global $PAGE;
+    // TODO, uncomment this once we have eliminated all references to current_theme in core code.
+    // debugging('current_theme is deprecated, use $PAGE->theme->name instead', DEBUG_DEVELOPER);
+    return $PAGE->theme->name;
+}
+
+/**
+ * This used to be the thing that theme styles.php files used to do all the work.
+ * This is now handled differently. You should copy theme/standard/styes.php
+ * into your theme.
+ *
+ * @deprecated
+ * @param int $lastmodified Always gets set to now
+ * @param int $lifetime The max-age header setting (seconds) defaults to 300
+ * @param string $themename The name of the theme to use (optional) defaults to current theme
+ * @param string $forceconfig Force a particular theme config (optional)
+ * @param string $lang Load styles for the specified language (optional)
+ */
+function style_sheet_setup($lastmodified=0, $lifetime=300, $themename='', $forceconfig='', $lang='') {
+    global $CFG, $PAGE, $THEME, $showdeprecatedstylesheetsetupwarning;
+    $showdeprecatedstylesheetsetupwarning = true;
+    include($CFG->dirroot . '/theme/styles.php');
+    exit;
+}
+
+/**
  * Prints some red text using echo
  *
  * @deprecated
Index: lib/outputlib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/outputlib.php,v
retrieving revision 1.9
diff -u -r1.9 outputlib.php
--- lib/outputlib.php	30 Jun 2009 06:00:12 -0000	1.9
+++ lib/outputlib.php	30 Jun 2009 12:57:50 -0000
@@ -24,30 +24,10 @@
  *
  * @package   moodlecore
  * @copyright 2009 Tim Hunt
- * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later (5)
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  */
 
 
-function initialise_theme_and_output() {
-    global $CFG, $OUTPUT, $PAGE, $THEME;
-    if (!($OUTPUT instanceof bootstrap_renderer)) {
-        return; // Already done.
-    }
-    if (!isset($CFG->theme) || empty($PAGE)) {
-        // Too soon to do anything.
-        return;
-    }
-    theme_setup();
-    if (CLI_SCRIPT) {
-        $rendererfactory = new cli_renderer_factory($THEME, $PAGE);
-    } else {
-        $classname = $THEME->rendererfactory;
-        $rendererfactory = new $classname($THEME, $PAGE);
-    }
-    $OUTPUT = $rendererfactory->get_renderer('core');
-}
-
-
 /**
  * A renderer factory is just responsible for creating an appropriate renderer
  * for any given part of Moodle.
@@ -377,6 +357,14 @@
         $this->page = $page;
     }
 
+    /**
+     * Have we started output yet?
+     * @return boolean true if the header has been printed.
+     */
+    public function has_started() {
+        return $this->page->state >= moodle_page::STATE_IN_BODY;
+    }
+
     protected function output_tag($tagname, $attributes, $contents) {
         return $this->output_start_tag($tagname, $attributes) . $contents .
                 $this->output_end_tag($tagname);
@@ -787,19 +775,23 @@
         }
         // This is only set by the {@link redirect()} method
         $output .= $this->metarefreshtag;
+
+        // TODO get rid of $CFG->javascript. We should be able to do everything
+        // with $PAGE->requires.
         ob_start();
         include($CFG->javascript);
         $output .= ob_get_contents();
         ob_end_clean();
         $output .= $this->page->requires->get_head_code();
 
+        // List alternate versions.
         foreach ($this->page->alternateversions as $type => $alt) {
             $output .= $this->output_empty_tag('link', array('rel' => 'alternate',
                     'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
         }
 
         // Add the meta page from the themes if any were requested
-        // TODO kill this.
+        // TODO See if we can get rid of this.
         $PAGE = $this->page;
         $metapage = '';
         if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
@@ -878,13 +870,6 @@
         }
     }
 
-    public function has_started() {
-        if ($this->page->state >= moodle_page::STATE_IN_BODY) {
-            return true;
-        }
-        return false;
-    }
-
     public function redirect($encodedurl, $message, $delay, $messageclass='notifyproblem') {
         global $CFG;
         $url = str_replace('&amp;', '&', $encodedurl);
@@ -945,11 +930,6 @@
         output_starting_hook();
         $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
 
-        // Add any stylesheets required using the horrible legacy mechanism. TODO kill this.
-        foreach ($CFG->stylesheets as $stylesheet) {
-            $this->page->requires->css($stylesheet, true);
-        }
-
         // Find the appropriate page template, based on $this->page->generaltype.
         $templatefile = $this->find_page_template();
         if ($templatefile) {
@@ -1423,6 +1403,251 @@
 
 
 /**
+ * Base class for class that represents the configuration variables of a Moodle theme.
+ *
+ * These properties are normally set by the theme's config.php file, when it is
+ * loaded by {@link moodle_page::load_theme()}.
+ *
+ * @copyright 2009 Tim Hunt
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @since     Moodle 2.0
+ */
+class theme_config {
+    /**
+     * @var array The names of all the stylesheets from this theme that you would
+     * like included, in order.
+     */
+    public $sheets = array('styles_layout', 'styles_fonts', 'styles_color');
+
+    public $standardsheets = true;  
+
+/// This variable can be set to an array containing
+/// filenames from the *STANDARD* theme.  If the 
+/// array exists, it will be used to choose the 
+/// files to include in the standard style sheet.
+/// When false, then no files are used.
+/// When true or NON-EXISTENT, then ALL standard files are used.
+/// This parameter can be used, for example, to prevent 
+/// having to override too many classes.
+/// Note that the trailing .css should not be included
+/// eg $THEME->standardsheets = array('styles_layout','styles_fonts','styles_color');
+////////////////////////////////////////////////////////////////////////////////
+
+
+    public $parent = null;  
+
+/// This variable can be set to the name of a parent theme
+/// which you want to have included before the current theme.
+/// This can make it easy to make modifications to another 
+/// theme without having to actually change the files
+/// If this variable is empty or false then a parent theme 
+/// is not used.
+////////////////////////////////////////////////////////////////////////////////
+
+
+    public $parentsheets = false;  
+
+/// This variable can be set to an array containing
+/// filenames from a chosen *PARENT* theme.  If the 
+/// array exists, it will be used to choose the 
+/// files to include in the standard style sheet.
+/// When false, then no files are used.
+/// When true or NON-EXISTENT, then ALL standard files are used.
+/// This parameter can be used, for example, to prevent 
+/// having to override too many classes.
+/// Note that the trailing .css should not be included
+/// eg $THEME->parentsheets = array('styles_layout','styles_fonts','styles_color');
+////////////////////////////////////////////////////////////////////////////////
+
+
+    public $modsheets = true;  
+
+/// When this is enabled, then this theme will search for 
+/// files named "styles.php" inside all Activity modules and 
+/// include them.   This allows modules to provide some basic 
+/// layouts so they work out of the box.
+/// It is HIGHLY recommended to leave this enabled.
+
+
+    public $blocksheets = true;  
+
+/// When this is enabled, then this theme will search for 
+/// files named "styles.php" inside all Block modules and 
+/// include them.   This allows Blocks to provide some basic 
+/// layouts so they work out of the box.
+/// It is HIGHLY recommended to leave this enabled.
+
+
+    public $langsheets = false;  
+
+/// By setting this to true, then this theme will search for 
+/// a file named "styles.php" inside the current language
+/// directory.  This allows different languages to provide 
+/// different styles.
+
+
+    public $courseformatsheets = true;
+
+/// When this is enabled, this theme will search for files 
+/// named "styles.php" inside all course formats and 
+/// include them.  This allows course formats to provide 
+/// their own default styles.
+
+
+    public $metainclude = false;
+
+/// When this is enabled (or not set!) then Moodle will try 
+/// to include a file meta.php from this theme into the 
+/// <head></head> part of the page.
+
+
+    public $standardmetainclude = true;
+
+
+/// When this is enabled (or not set!) then Moodle will try 
+/// to include a file meta.php from the standard theme into the 
+/// <head></head> part of the page.
+
+
+    public $parentmetainclude = false;
+
+/// When this is enabled (or not set!) then Moodle will try 
+/// to include a file meta.php from the parent theme into the 
+/// <head></head> part of the page.
+
+
+    public $navmenuwidth = 50;
+
+/// You can use this to control the cutoff point for strings 
+/// in the navmenus (list of activities in popup menu etc)
+/// Default is 50 characters wide.
+
+
+    public $makenavmenulist = false;
+
+/// By setting this to true, then you will have access to a
+/// new variable in your header.html and footer.html called
+/// $navmenulist ... this contains a simple XHTML menu of 
+/// all activities in the current course, mostly useful for 
+/// creating popup navigation menus and so on.
+
+
+
+    public $resource_mp3player_colors = 'bgColour=000000&btnColour=ffffff&btnBorderColour=cccccc&iconColour=000000&iconOverColour=00cc00&trackColour=cccccc&handleColour=ffffff&loaderColour=ffffff&font=Arial&fontColour=3333FF&buffer=10&waitForPlay=no&autoPlay=yes';
+
+/// With this you can control the colours of the "big" MP3 player 
+/// that is used for MP3 resources.
+
+
+    public $filter_mediaplugin_colors = 'bgColour=000000&btnColour=ffffff&btnBorderColour=cccccc&iconColour=000000&iconOverColour=00cc00&trackColour=cccccc&handleColour=ffffff&loaderColour=ffffff&waitForPlay=yes';
+
+/// ...And this controls the small embedded player
+
+
+    public $custompix = false;
+
+/// If true, then this theme must have a "pix" 
+/// subdirectory that contains copies of all 
+/// files from the moodle/pix directory, plus a
+/// "pix/mod" directory containing all the icons 
+/// for all the activity modules.
+
+
+///$THEME->rarrow = '&#x25BA;' //OR '&rarr;';
+///$THEME->larrow = '&#x25C4;' //OR '&larr;';
+///$CFG->block_search_button = link_arrow_right(get_string('search'), $url='', $accesshide=true);
+///
+/// Accessibility: Right and left arrow-like characters are
+/// used in the breadcrumb trail, course navigation menu 
+/// (previous/next activity), calendar, and search forum block.
+///
+/// If the theme does not set characters, appropriate defaults
+/// are set by (lib/weblib.php:check_theme_arrows). The suggestions
+/// above are 'silent' in a screen-reader like JAWS. Please DO NOT
+/// use &lt; &gt; &raquo; - these are confusing for blind users.
+////////////////////////////////////////////////////////////////////////////////
+
+
+    public $blockregions = array('side-pre', 'side-post');
+    public $defaultblockregion = 'side-post';
+/// Areas where blocks may appear on any page that uses this theme. For each
+/// region you list in $THEME->blockregions you must call blocks_print_group
+/// with that region id somewhere in header.html or footer.html.
+/// defaultblockregion is the region where new blocks will be added, and
+/// where any blocks in unrecognised regions will be shown. (Suppose someone
+/// added a block when anther theme was selected).
+////////////////////////////////////////////////////////////////////////////////
+
+    /**
+     * @var string the name of this theme. Set automatically.
+     */
+    public $name;
+    /**
+     * @var string the folder where this themes fiels are stored. $CFG->themedir . '/' . $this->name
+     */
+    public $dir;
+
+    public $rendererfactory = 'standard_renderer_factory';
+
+    /**
+     * If you want to do custom processing on the CSS before it is output (for
+     * example, to replace certain variable names with particular values) you can
+     * give the name of a function here.
+     *
+     * There are two functions avaiable that you may wish to use (defined in lib/outputlib.php):
+     *   output_css_replacing_constants
+     *   output_css_for_css_edit
+     * If you wish to write your own function, use those two as examples, and it
+     * should be clear what you have to do.
+     *
+     * @var string the name of a function.
+     */
+    public $customcssoutputfunction = null;
+
+    /**
+     * Get the list of stylesheet URLs that need to go in the header for this theme.
+     * @return array of URLs.
+     */
+    public function get_stylesheet_urls() {
+        global $CFG;
+
+        // Put together the parameters
+        $params = '?for=' . $this->name;
+
+        // Stylesheets, in order (standard, parent, this - some of which may be the same).
+        $stylesheets = array();
+        if ($this->name != 'standard' && $this->standardsheets) {
+            $stylesheets[] = $CFG->httpsthemewww . '/standard/styles.php' . $params;
+        }
+        if (!empty($this->parent)) {
+            $stylesheets[] = $CFG->httpsthemewww . '/' . $this->parent . '/styles.php' . $params;
+        }
+
+        // Pass on the current language, if it will be needed.
+        if (!empty($this->langsheets)) {
+            $params .= '&lang=' . current_language();
+        }
+        $stylesheets[] = $CFG->httpsthemewww . '/' . $this->name . '/styles.php' . $params;
+
+        // Additional styles for right-to-left languages.
+        if (right_to_left()) {
+            $stylesheets[] = $CFG->httpsthemewww . '/standard/rtl.css';
+
+            if (!empty($this->parent) && file_exists($CFG->themedir . '/' . $this->parent . '/rtl.css')) {
+                $stylesheets[] = $CFG->httpsthemewww . '/' . $this->parent . '/rtl.css';
+            }
+
+            if (file_exists($this->dir . '/rtl.css')) {
+                $stylesheets[] = $CFG->httpsthemewww . '/' . $this->name . '/rtl.css';
+            }
+        }
+
+        return $stylesheets;
+    }
+}
+
+
+/**
  * Base class for classes representing HTML elements, like moodle_select_menu.
  *
  * Handles the id and class attribues.
@@ -1714,3 +1939,114 @@
     }
 }
 
+
+/**
+ * Output CSS while replacing constants/variables. See MDL-6798 for details
+ *
+ * Information from Urs Hunkler:
+ *
+ * This is an adaptation of Shaun Inman's "CSS Server-side Constants" for Moodle.
+ * http://www.shauninman.com/post/heap/2005/08/09/css_constants
+ *
+ * To use, specify $THEME->customcssoutputfunction = 'output_css_replacing_constants';
+ * in your theme's config.php file.
+ *
+ * The constant definitions are written into a separate CSS file named like
+ * constants.css and loaded first in config.php. You can use constants for any
+ * CSS properties. The constant definition looks like:
+ * <code>
+ * \@server constants {
+ *   fontColor: #3a2830;
+ *   aLink: #116699;
+ *   aVisited: #AA2200;
+ *   aHover: #779911;
+ *   pageBackground: #FFFFFF;
+ *   backgroundColor: #EEEEEE;
+ *   backgroundSideblockHeader: #a8a4e9;
+ *   fontcolorSideblockHeader: #222222;
+ *   color1: #98818b;
+ *   color2: #bd807b;
+ *   color3: #f9d1d7;
+ *   color4: #e8d4d8;
+ * }
+ * </code>
+ *
+ * The lines in the CSS files using CSS constants look like:
+ * <code>
+ * body {
+ *   font-size: 100%;
+ *   background-color: pageBackground;
+ *   color: fontColor;
+ *   font-family: 'Bitstream Vera Serif', georgia, times, serif;
+ *   margin: 0;
+ *   padding: 0;
+ * }
+ * div#page {
+ *   margin: 0 10px;
+ *   padding-top: 5px;
+ *   border-top-width: 10px;
+ *   border-top-style: solid;
+ *   border-top-color: color3;
+ * }
+ * div.clearer {
+ *   clear: both;
+ * }
+ * a:link {
+ *   color: aLink;
+ * } 
+ * </code>
+ *
+ * @param array $files an arry of the CSS fiels that need to be output.
+ */
+function output_css_replacing_constants($files) {
+    global $CFG;
+    // Get all the CSS.
+    $toreplace = array($CFG->dirroot, $CFG->themedir);
+    ob_start();
+    foreach ($files as $file) {
+        $shortname = str_replace($toreplace, '', $file);
+        echo '/******* ' . $shortname . " start *******/\n\n";
+        @include_once($file);
+        echo '/******* ' . $shortname . " end *******/\n\n";
+    }
+    $css = ob_get_contents();
+    ob_end_clean();
+
+    if (preg_match_all("/@server\s+(?:variables|constants)\s*\{\s*([^\}]+)\s*\}\s*/i", $css, $matches)) {
+        $variables = array();
+        foreach ($matches[0] as $key => $server) {
+            $css = str_replace($server, '', $css);
+            preg_match_all("/([^:\}\s]+)\s*:\s*([^;\}]+);/", $matches[1][$key], $vars);
+            foreach ($vars[1] as $var => $value) {
+                $variables[$value] = $vars[2][$var];
+            }
+        }
+        $css = str_replace(array_keys($variables), array_values($variables), $css);
+    }
+    echo $css;
+}
+
+/**
+ * This CSS output function will link to CSS files rather than including them
+ * inline.
+ *
+ * The single CSS files can then be edited and saved with interactive
+ * CSS editors like CSSEdit. Any files that have a .php extension are still included
+ * inline.
+ *
+ * @param array $files an arry of the CSS fiels that need to be output.
+ */
+function output_css_for_css_edit($files) {
+    global $CFG;
+    $toreplace = array($CFG->dirroot, $CFG->themedir);
+    foreach ($files as $file) {
+        $shortname = str_replace($toreplace, '', $file);
+        echo '/* @group ' . $shortname . " */\n\n";
+        if (strpos($file, '.css') !== false) {
+            echo '@import url("' . $file . '");'."\n\n";
+        } else {
+            @include_once($file);
+        }
+        echo "/* @end */\n\n";
+    }
+}
\ No newline at end of file
Index: lib/moodlelib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/moodlelib.php,v
retrieving revision 1.1223
diff -u -r1.1223 moodlelib.php
--- lib/moodlelib.php	30 Jun 2009 01:59:48 -0000	1.1223
+++ lib/moodlelib.php	30 Jun 2009 12:57:48 -0000
@@ -8213,17 +8213,12 @@
  * @global bool
  */
 function httpsrequired() {
-
     global $CFG, $HTTPSPAGEREQUIRED;
 
     if (!empty($CFG->loginhttps)) {
         $HTTPSPAGEREQUIRED = true;
         $CFG->httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
         $CFG->httpsthemewww = str_replace('http:', 'https:', $CFG->themewww);
-
-        // change theme URLs to https
-        theme_setup();
-
     } else {
         $CFG->httpswwwroot = $CFG->wwwroot;
         $CFG->httpsthemewww = $CFG->themewww;
Index: lib/blocklib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/blocklib.php,v
retrieving revision 1.185
diff -u -r1.185 blocklib.php
--- lib/blocklib.php	12 Jun 2009 11:58:12 -0000	1.185
+++ lib/blocklib.php	30 Jun 2009 12:57:44 -0000
@@ -329,6 +329,10 @@
             return;
         }
 
+        if (!isset($this->defaultregion)) {
+            $this->page->initialise_theme_and_output();
+        }
+
         if (is_null($includeinvisible)) {
             $includeinvisible = $this->page->user_is_editing();
         }
Index: lib/adminlib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/adminlib.php,v
retrieving revision 1.368
diff -u -r1.368 adminlib.php
--- lib/adminlib.php	29 Jun 2009 09:19:53 -0000	1.368
+++ lib/adminlib.php	30 Jun 2009 12:57:43 -0000
@@ -5438,7 +5438,7 @@
  * @return int number of changed settings
  */
 function admin_write_settings($formdata) {
-    global $CFG, $SITE, $PAGE, $DB;
+    global $CFG, $SITE, $DB;
 
     $olddbsessions = !empty($CFG->dbsessions);
     $formdata = (array)$formdata;
@@ -5477,9 +5477,12 @@
         require_logout();
     }
 
-    // now update $SITE - it might have been changed
-    $SITE = $DB->get_record('course', array('id'=>$SITE->id));
-    $PAGE->set_course($SITE);
+    // Now update $SITE - just update the fields, in case other people have a
+    // a reference to it (e.g. $PAGE, $COURSE).
+    $newsite = $DB->get_record('course', array('id'=>$SITE->id));
+    foreach (get_object_vars($newsite) as $field => $value) {
+        $SITE->$field = $value;
+    }
 
     // now reload all settings - some of them might depend on the changed
     admin_get_root(true);
Index: theme/standardwhite/styles.php
===================================================================
RCS file: /cvsroot/moodle/moodle/theme/standardwhite/styles.php,v
retrieving revision 1.41
diff -u -r1.41 styles.php
--- theme/standardwhite/styles.php	14 Sep 2008 08:40:23 -0000	1.41
+++ theme/standardwhite/styles.php	30 Jun 2009 12:57:53 -0000
@@ -1,4 +1,4 @@
-<?PHP /*  $Id: styles.php,v 1.41 2008/09/14 08:40:23 skodak Exp $ */
+<?php
 
 /// Every theme should contain a copy of this script.  It lets us 
 /// set up variables and so on before we include the raw CSS files.
Index: theme/standard/styles.php
===================================================================
RCS file: /cvsroot/moodle/moodle/theme/standard/styles.php,v
retrieving revision 1.67
diff -u -r1.67 styles.php
--- theme/standard/styles.php	14 Sep 2008 08:40:24 -0000	1.67
+++ theme/standard/styles.php	30 Jun 2009 12:57:53 -0000
@@ -1,21 +1,35 @@
-<?PHP /*  $Id: styles.php,v 1.67 2008/09/14 08:40:24 skodak Exp $ */
+<?php
 
-/// Every theme should contain a copy of this script.  It lets us 
-/// set up variables and so on before we include the raw CSS files.
-/// The output of this script should be a completely standard CSS file.
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+
+/**
+ * Serve the CSS for this theme.
+ *
+ * Every theme must contain a copy of this file
+ *
+ * DO NOT MODIFY THIS FILE IT IS IMPORTANT TO THE WORKING OF THE MOODLE THEMES SYSTEM.
+ *
+ * If you are are trying to change something, you should probably be looking at config.php.
+ *
+ * @package   moodlecore
+ * @copyright 2009 Tim Hunt
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
 
-/// THERE SHOULD BE NO NEED TO MODIFY THIS FILE!!  USE CONFIG.PHP INSTEAD.
 
-
-    define('NO_MOODLE_COOKIES', true);                  // session not used here
-    define('NO_UPGRADE_CHECK', true);                   // ignore upgrade check
-
-    require_once("../../config.php");                   // Load up the Moodle libraries
-    $themename   = basename(dirname(__FILE__));           // Name of the folder we are in
-    $forceconfig = optional_param('forceconfig', '', PARAM_FILE);   // Get config from this theme
-    $lang        = optional_param('lang', '', PARAM_FILE);          // Look for styles in this language
-    $lifetime    = 1800;                                   // Seconds to cache this stylesheet
-
-    style_sheet_setup(time(), $lifetime, $themename, $forceconfig, $lang);
-   
-?>
+$themename = basename(dirname(__FILE__));
+require_once('../styles.php');
Index: config-dist.php
===================================================================
RCS file: /cvsroot/moodle/moodle/config-dist.php,v
retrieving revision 1.117
diff -u -r1.117 config-dist.php
--- config-dist.php	31 May 2009 17:33:45 -0000	1.117
+++ config-dist.php	30 Jun 2009 12:57:40 -0000
@@ -291,8 +291,8 @@
 // Set the priority of themes from highest to lowest. This is useful (for
 // example) in sites where the user theme should override all other theme
 // settings for accessibility reasons. You can also disable types of themes
-// by removing them from the array. The default setting is:
-//      $CFG->themeorder = array('page', 'course', 'category', 'session', 'user', 'site');
+// (other than site)  by removing them from the array. The default setting is:
+//      $CFG->themeorder = array('course', 'category', 'session', 'user', 'site');
 // NOTE: course, category, session, user themes still require the
 // respective settings to be enabled
 //
Index: course/category.php
===================================================================
RCS file: /cvsroot/moodle/moodle/course/category.php,v
retrieving revision 1.143
diff -u -r1.143 category.php
--- course/category.php	6 May 2009 08:59:30 -0000	1.143
+++ course/category.php	30 Jun 2009 12:57:40 -0000
@@ -63,11 +63,6 @@
         }
     }
 
-    if(!empty($CFG->allowcategorythemes) && isset($category->theme)) {
-        // specifying theme here saves us some dbqs
-        theme_setup($category->theme);
-    }
-
 /// Print headings
     $numcategories = $DB->count_records('course_categories');
 
Index: theme/styles.php
===================================================================
RCS file: theme/styles.php
diff -N theme/styles.php
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ theme/styles.php	1 Jan 1970 00:00:00 -0000
@@ -0,0 +1,200 @@
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * This file is responsible for serving the CSS of each theme.
+ *
+ * It should not be linked to directly. Instead, it gets included by
+ * theme/themename/styles.php. See theme/standard/styles.php as an example.
+ *
+ * In this script, we are serving the styles for theme $themename, but we are
+ * serving them on behalf of theme $fortheme.
+ *
+ * To understand this, image that the currently selected theme is standardwhite.
+ * This theme uses both its own stylesheets, and also the ones from the standard theme.
+ * So, when we are serving theme/standard/styles.php, we need to use the config in
+ * theme/standardwhite/config.php to control the settings. This is controled by the
+ * for=... parameter in the URL.
+ *
+ * In case you are wondering, in the above scenario, we have to serve the standard
+ * theme CSS with a URL like theme/standard/styles.php, so that relative links from
+ * the CSS to images in the theme folder will work.
+ *
+ * @package   moodlecore
+ * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+
+if (empty($themename)) {
+    die('Direct access to this script is forbidden.');
+    // This script should only be required by theme/themename/styles.php.
+}
+
+// These may already be defined if we got here via style_sheet_setup in lib/deprecatedlib.php
+if (!defined('NO_MOODLE_COOKIES')) {
+    define('NO_MOODLE_COOKIES', true); // Session not used here
+}
+if (!defined('NO_UPGRADE_CHECK')) {
+    define('NO_UPGRADE_CHECK', true);  // Ignore upgrade check
+}
+require_once(dirname(__FILE__) . '/../config.php');
+
+$fortheme = required_param('for', PARAM_FILE);
+$lang = optional_param('lang', '', PARAM_FILE);
+
+$CACHE_LIFETIME = 1800; // Cache stylesheets for half an hour.
+$DEFAULT_SHEET_LIST = array('styles_layout', 'styles_fonts', 'styles_color');
+
+// Fix for IE6 caching - we don't want the filemtime('styles.php'), instead use now.
+$lastmodified = time();
+
+// Set the correct content type. (Should we also be specifying charset here?)
+header('Content-type: text/css'); 
+if (!debugging('', DEBUG_DEVELOPER)) {
+    // Do not send caching headers for developer. (This makes it easy to edit themes.
+    // You don't have to keep clearing the browser cache.)
+    header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastmodified) . ' GMT');
+    header('Expires: ' . gmdate("D, d M Y H:i:s", $lastmodified + $CACHE_LIFETIME) . ' GMT');
+    header('Cache-Control: max-age=' . $lifetime);
+    header('Pragma: ');
+}
+
+if (!empty($showdeprecatedstylesheetsetupwarning)) {
+    echo <<<END
+
+/***************************************************************
+ ***************************************************************
+ ****                                                       ****
+ **** WARNING! This theme uses an old-fashioned styles.php  ****
+ **** file. It should be updated by copying styles.php from ****
+ **** the standard theme of a recent version of Moodle.     ****
+ ****                                                       ****
+ ***************************************************************
+ ***************************************************************/
+
+
+
+END;
+}
+
+// Load the configuration of the selected theme. (See comment at the top of the file.)
+$PAGE->force_theme($fortheme);
+
+// Now work out which stylesheets we shold be serving from this theme.
+if ($themename == $fortheme) {
+    $themesheets = $THEME->sheets;
+
+} else if (!empty($THEME->parent) && $themename == $THEME->parent) {
+    if ($THEME->parentsheets === true) {
+        // Use all the sheets we have.
+        $themesheets = $DEFAULT_SHEET_LIST;
+    } else if (!empty($THEME->parentsheets)) {
+        $themesheets = $THEME->parentsheets;
+    } else {
+        echo "/* The current theme does not require anything from the standard theme. */\n\n";
+        exit;
+    }
+
+} else if ($themename == 'standard') {
+    if ($THEME->standardsheets === true) {
+        // Use all the sheets we have.
+        $themesheets = $DEFAULT_SHEET_LIST;
+    } else if (!empty($THEME->standardsheets)) {
+        $themesheets = $THEME->standardsheets;
+    } else {
+        echo "/* The current theme does not require anything from the standard theme. */\n\n";
+        exit;
+    }
+}
+
+// Conver the sheet names to file names.
+$files = array();
+foreach ($themesheets as $sheet) {
+    $files[] = $CFG->themedir . '/' . $themename . '/' . $sheet . '.css';
+}
+
+// If this is the standard theme, then also include the styles.php files from
+// each of the plugins, as determined by the theme settings.
+if ($themename == 'standard') {
+    if (!empty($THEME->modsheets)) {
+        $files += get_sheets_for_plugin_type('mod');
+    }
+
+    if (!empty($THEME->blocksheets)) {
+        $files += get_sheets_for_plugin_type('block');
+    }
+
+    if (!empty($THEME->courseformatsheets)) {
+        $files += get_sheets_for_plugin_type('format');
+    }
+
+    if (!empty($THEME->gradereportsheets)) {
+        $files += get_sheets_for_plugin_type('gradereport');
+    }
+
+    if (!empty($THEME->langsheets) && $lang) {
+        $file = $CFG->dirroot . '/lang/' . $lang . '/styles.php';
+        if (file_exists($file)) {
+            $files[] = $file;
+        }
+    }
+}
+
+if (empty($files)) {
+    echo "/* The current theme does not require anything from this theme. */\n\n";
+    exit;
+}
+
+// Output a commen with a summary of the included files.
+echo <<<END
+/*
+ * Styles from theme '$themename' for theme '$fortheme'
+ *
+ * Files included here:
+ *
+
+END;
+$toreplace = array($CFG->dirroot, $CFG->themedir);
+foreach ($files as $file) {
+    echo ' *   ' . str_replace($toreplace, '', $file) . "\n";
+}
+echo " */\n\n";
+
+if (!empty($THEME->cssoutputfunction)) {
+    call_user_func($THEME->cssoutputfunction, $files);
+
+} else {
+    foreach ($files as $file) {
+        $shortname = str_replace($toreplace, '', $file);
+        echo '/******* ' . $shortname . " start *******/\n\n";
+        @include_once($file);
+        echo '/******* ' . $shortname . " end *******/\n\n";
+    }
+}
+
+function get_sheets_for_plugin_type($type) {
+    $files = array();
+    $mods = get_plugin_list($type);
+    foreach ($mods as $moddir) {
+        $file = $moddir . '/styles.php';
+        if (file_exists($file)) {
+            $files[] = $file;
+        }
+    }
+    return $files;
+}
