3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Functions for generating the HTML that Moodle should output.
21 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 require_once($CFG->libdir.'/outputcomponents.php');
30 require_once($CFG->libdir.'/outputactions.php');
31 require_once($CFG->libdir.'/outputfactories.php');
32 require_once($CFG->libdir.'/outputrenderers.php');
33 require_once($CFG->libdir.'/outputrequirementslib.php');
36 * Invalidate all server and client side caches.
39 function theme_reset_all_caches() {
41 require_once("$CFG->libdir/filelib.php");
43 set_config('themerev', empty($CFG->themerev) ? 1 : $CFG->themerev+1);
44 fulldelete("$CFG->dataroot/cache/theme");
48 * Enable or disable theme designer mode.
52 function theme_set_designer_mod($state) {
53 theme_reset_all_caches();
54 set_config('themedesignermode', (int)!empty($state));
58 * Returns current theme revision number.
61 function theme_get_revision() {
64 if (empty($CFG->themedesignermode)) {
65 if (empty($CFG->themerev)) {
68 return $CFG->themerev;
78 * This class represents the configuration variables of a Moodle theme.
80 * All the variables with access: public below (with a few exceptions that are marked)
81 * are the properties you can set in your theme's config.php file.
83 * There are also some methods and protected variables that are part of the inner
84 * workings of Moodle's themes system. If you are just editing a theme's config.php
85 * file, you can just ignore those, and the following information for developers.
87 * Normally, to create an instance of this class, you should use the
88 * {@link theme_config::load()} factory method to load a themes config.php file.
89 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
90 * will create one for you, accessible as $PAGE->theme.
92 * @copyright 2009 Tim Hunt
93 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
98 * @var string default theme, used when requested theme not found
100 const DEFAULT_THEME = 'standard';
103 * You can base your theme on other themes by linking to the other theme as
104 * parents. This lets you use the CSS and layouts from the other themes
105 * (see {@link $layouts}).
106 * That makes it easy to create a new theme that is similar to another one
107 * but with a few changes. In this theme's CSS you only need to override
108 * those rules you want to change.
115 * The names of all the stylesheets from this theme that you would
116 * like included, in order. Give the names of the files without .css.
120 public $sheets = array();
123 * The names of all the stylesheets from parents that should be excluded.
124 * true value may be used to specify all parents or all themes from one parent.
125 * If no value specified value from parent theme used.
127 * @var array or arrays, true means all, null means use value from parent
129 public $parents_exclude_sheets = null;
132 * List of plugin sheets to be excluded.
133 * If no value specified value from parent theme used.
135 * @var array of full plugin names, null means use value from parent
137 public $plugins_exclude_sheets = null;
140 * List of style sheets that are included in the text editor bodies.
141 * Sheets from parent themes are used automatically and can not be excluded.
145 public $editor_sheets = array();
148 * The names of all the javascript files this theme that you would
149 * like included from head, in order. Give the names of the files without .js.
153 public $javascripts = array();
156 * The names of all the javascript files this theme that you would
157 * like included from footer, in order. Give the names of the files without .js.
161 public $javascripts_footer = array();
164 * The names of all the javascript files from parents that should be excluded.
165 * true value may be used to specify all parents or all themes from one parent.
166 * If no value specified value from parent theme used.
168 * @var array or arrays, true means all, null means use value from parent
170 public $parents_exclude_javascripts = null;
173 * Which file to use for each page layout.
175 * This is an array of arrays. The keys of the outer array are the different layouts.
176 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
177 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
178 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
179 * That file also has a good example of how to set this setting.
181 * For each layout, the value in the outer array is an array that describes
182 * how you want that type of page to look. For example
184 * $THEME->layouts = array(
185 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
186 * 'standard' => array(
187 * 'theme' = 'mytheme',
188 * 'file' => 'normal.php',
189 * 'regions' => array('side-pre', 'side-post'),
190 * 'defaultregion' => 'side-post'
192 * // The site home page.
194 * 'theme' = 'mytheme',
195 * 'file' => 'home.php',
196 * 'regions' => array('side-pre', 'side-post'),
197 * 'defaultregion' => 'side-post'
203 * 'theme' name of the theme where is the layout located
204 * 'file' is the layout file to use for this type of page.
205 * layout files are stored in layout subfolder
206 * 'regions' This lists the regions on the page where blocks may appear. For
207 * each region you list here, your layout file must include a call to
209 * echo $OUTPUT->blocks_for_region($regionname);
211 * or equivalent so that the blocks are actually visible.
213 * 'defaultregion' If the list of regions is non-empty, then you must pick
214 * one of the one of them as 'default'. This has two meanings. First, this is
215 * where new blocks are added. Second, if there are any blocks associated with
216 * the page, but in non-existent regions, they appear here. (Imaging, for example,
217 * that someone added blocks using a different theme that used different region
218 * names, and then switched to this theme.)
222 public $layouts = array();
225 * With this you can control the colours of the big MP3 player
226 * that is used for MP3 resources.
230 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';
233 * With this you can control the colours of the small MP3 player
234 * that is used elsewhere.
238 public $filter_mediaplugin_colors = 'bgColour=000000&btnColour=ffffff&btnBorderColour=cccccc&iconColour=000000&iconOverColour=00cc00&trackColour=cccccc&handleColour=ffffff&loaderColour=ffffff&waitForPlay=yes';
241 * Name of the renderer factory class to use.
243 * This is an advanced feature. Moodle output is generated by 'renderers',
244 * you can customise the HTML that is output by writing custom renderers,
245 * and then you need to specify 'renderer factory' so that Moodle can find
248 * There are some renderer factories supplied with Moodle. Please follow these
249 * links to see what they do.
251 * <li>{@link standard_renderer_factory} - the default.</li>
252 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
253 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
256 * @var string name of a class implementing the {@link renderer_factory} interface.
258 public $rendererfactory = 'standard_renderer_factory';
261 * Function to do custom CSS post-processing.
263 * This is an advanced feature. If you want to do custom post-processing on the
264 * CSS before it is output (for example, to replace certain variable names
265 * with particular values) you can give the name of a function here.
267 * @var string the name of a function.
269 public $csspostprocess = null;
272 * Accessibility: Right arrow-like character is
273 * used in the breadcrumb trail, course navigation menu
274 * (previous/next activity), calendar, and search forum block.
275 * If the theme does not set characters, appropriate defaults
276 * are set automatically. Please DO NOT
277 * use < > » - these are confusing for blind users.
281 public $rarrow = null;
284 * Accessibility: Right arrow-like character is
285 * used in the breadcrumb trail, course navigation menu
286 * (previous/next activity), calendar, and search forum block.
287 * If the theme does not set characters, appropriate defaults
288 * are set automatically. Please DO NOT
289 * use < > » - these are confusing for blind users.
293 public $larrow = null;
296 //==Following properties are not configurable from theme config.php==
299 * The name of this theme. Set automatically when this theme is
300 * loaded. This can not be set in theme config.php
306 * the folder where this themes files are stored. This is set
307 * automatically. This can not be set in theme config.php
313 * Theme settings stored in config_plugins table.
314 * This can not be set in theme config.php
317 public $setting = null;
320 * If set to true and the theme enables the dock then blocks will be able
321 * to be moved to the special dock
324 public $enable_dock = false;
327 * Instance of the renderer_factory implementation
328 * we are using. Implementation detail.
329 * @var renderer_factory
331 protected $rf = null;
334 * List of parent config objects.
335 * @var array list of parent configs
337 protected $parent_configs = array();
340 * Load the config.php file for a particular theme, and return an instance
341 * of this class. (That is, this is a factory method.)
343 * @param string $themename the name of the theme.
344 * @return theme_config an instance of this class.
346 public static function load($themename) {
349 // load theme settings from db
351 $settings = get_config('theme_'.$themename);
352 } catch (dml_exception $e) {
353 // most probably moodle tables not created yet
354 $settings = new object();
357 if ($config = theme_config::find_theme_config($themename, $settings)) {
358 return new theme_config($config);
360 } else if ($themename == theme_config::DEFAULT_THEME) {
361 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
364 // bad luck, the requested theme has some problems - admin see details in theme config
365 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
370 * Theme diagnostic code. It is very problematic to send debug output
371 * to the actual CSS file, instead this functions is supposed to
372 * diagnose given theme and highlights all potential problems.
373 * This information should be available from the theme selection page
374 * or some other debug page for theme designers.
376 * @param string $themename
377 * @return array description of problems
379 public static function diagnose($themename) {
385 * Private constructor, can be called only from the factory method.
386 * @param stdClass $config
388 private function __construct($config) {
389 global $CFG; //needed for included lib.php files
391 $this->settings = $config->settings;
392 $this->name = $config->name;
393 $this->dir = $config->dir;
395 if ($this->name != 'base') {
396 $baseconfig = theme_config::find_theme_config('base', $this->settings);
398 $baseconfig = $config;
401 $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer',
402 'parents_exclude_javascripts', 'layouts', 'resource_mp3player_colors', 'enable_dock',
403 'filter_mediaplugin_colors', 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow');
405 foreach ($config as $key=>$value) {
406 if (in_array($key, $configurable)) {
407 $this->$key = $value;
411 // verify all parents and load configs and renderers
412 foreach ($this->parents as $parent) {
413 if ($parent == 'base') {
414 $parent_config = $baseconfig;
415 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
416 // this is not good - better exclude faulty parents
419 $libfile = $parent_config->dir.'/lib.php';
420 if (is_readable($libfile)) {
421 // theme may store various function here
422 include_once($libfile);
424 $renderersfile = $parent_config->dir.'/renderers.php';
425 if (is_readable($renderersfile)) {
426 // may contain core and plugin renderers and renderer factory
427 include_once($renderersfile);
429 $this->parent_configs[$parent] = $parent_config;
430 $rendererfile = $parent_config->dir.'/renderers.php';
431 if (is_readable($rendererfile)) {
432 // may contain core and plugin renderers and renderer factory
433 include_once($rendererfile);
436 $libfile = $this->dir.'/lib.php';
437 if (is_readable($libfile)) {
438 // theme may store various function here
439 include_once($libfile);
441 $rendererfile = $this->dir.'/renderers.php';
442 if (is_readable($rendererfile)) {
443 // may contain core and plugin renderers and renderer factory
444 include_once($rendererfile);
447 // cascade all layouts properly
448 foreach ($baseconfig->layouts as $layout=>$value) {
449 if (!isset($this->layouts[$layout])) {
450 foreach ($this->parent_configs as $parent_config) {
451 if (isset($parent_config->layouts[$layout])) {
452 $this->layouts[$layout] = $parent_config->layouts[$layout];
456 $this->layouts[$layout] = $value;
460 //fix arrows if needed
461 $this->check_theme_arrows();
465 * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
466 * If not it applies sensible defaults.
468 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
469 * search forum block, etc. Important: these are 'silent' in a screen-reader
470 * (unlike > »), and must be accompanied by text.
472 private function check_theme_arrows() {
473 if (!isset($this->rarrow) and !isset($this->larrow)) {
474 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
475 // Also OK in Win 9x/2K/IE 5.x
476 $this->rarrow = '►';
477 $this->larrow = '◄';
478 if (empty($_SERVER['HTTP_USER_AGENT'])) {
481 $uagent = $_SERVER['HTTP_USER_AGENT'];
483 if (false !== strpos($uagent, 'Opera')
484 || false !== strpos($uagent, 'Mac')) {
485 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
486 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
487 $this->rarrow = '▶';
488 $this->larrow = '◀';
490 elseif (false !== strpos($uagent, 'Konqueror')) {
491 $this->rarrow = '→';
492 $this->larrow = '←';
494 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
495 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
496 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
497 // To be safe, non-Unicode browsers!
498 $this->rarrow = '>';
499 $this->larrow = '<';
502 /// RTL support - in RTL languages, swap r and l arrows
503 if (right_to_left()) {
505 $this->rarrow = $this->larrow;
512 * Returns output renderer prefixes, these are used when looking
513 * for the overriden renderers in themes.
516 public function renderer_prefixes() {
517 global $CFG; // just in case the included files need it
519 $prefixes = array('theme_'.$this->name);
521 foreach ($this->parent_configs as $parent) {
522 $prefixes[] = 'theme_'.$parent->name;
529 * Returns the stylesheet URL of this editor content
530 * @param bool $encoded false means use & and true use & in URLs
533 public function editor_css_url($encoded=true) {
536 $rev = theme_get_revision();
539 $params = array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor');
540 return new moodle_url($CFG->httpswwwroot.'/theme/styles.php', $params);
542 $params = array('theme'=>$this->name, 'type'=>'editor');
543 return new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
548 * Returns the content of the CSS to be used in editor content
551 public function editor_css_content() {
556 // first editor plugins
557 $plugins = get_plugin_list('editor');
558 foreach ($plugins as $plugin=>$fulldir) {
559 $sheetfile = "$fulldir/editor_styles.css";
560 if (is_readable($sheetfile)) {
561 $css .= "/*** Editor $plugin content CSS ***/\n\n" . file_get_contents($sheetfile) . "\n\n";
564 // then parent themes
565 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
566 if (empty($parent_config->editor_sheets)) {
569 foreach ($parent_config->editor_sheets as $sheet) {
570 $sheetfile = "$parent_config->dir/$sheet.css";
571 if (is_readable($sheetfile)) {
572 $css .= "/*** Parent theme $parent/$sheet ***/\n\n" . file_get_contents($sheetfile) . "\n\n";
576 // finally this theme
577 if (!empty($this->editor_sheets)) {
578 foreach ($this->editor_sheets as $sheet) {
579 $sheetfile = "$this->dir/$sheet.css";
580 if (is_readable($sheetfile)) {
581 $css .= "/*** Theme $sheet ***/\n\n" . file_get_contents($sheetfile) . "\n\n";
586 return $this->post_process($css);
590 * Get the stylesheet URL of this theme
591 * @param bool $encoded false means use & and true use & in URLs
592 * @return array of moodle_url
594 public function css_urls(moodle_page $page) {
597 $rev = theme_get_revision();
602 $params = array('theme'=>$this->name,'rev'=>$rev);
603 if (check_browser_version('MSIE', 5) and !check_browser_version('MSIE', 8)) {
604 $params['type'] = 'ie';
606 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', $params);
609 // find out the current CSS and cache it now for 5 seconds
610 // the point is to construct the CSS only once and pass it through the
611 // dataroot to the script that actually serves the sheets
612 if (!defined('THEME_DESIGNER_CACHE_LIFETIME')) {
613 define('THEME_DESIGNER_CACHE_LIFETIME', 4); // this can be also set in config.php
615 $candidatesheet = "$CFG->dataroot/cache/theme/$this->name/designer.ser";
616 if (!file_exists($candidatesheet)) {
617 $css = $this->css_content();
618 check_dir_exists(dirname($candidatesheet), true, true);
619 file_put_contents($candidatesheet, serialize($css));
621 } else if (filemtime($candidatesheet) > time() - THEME_DESIGNER_CACHE_LIFETIME) {
622 if ($css = file_get_contents($candidatesheet)) {
623 $css = unserialize($css);
625 unlink($candidatesheet);
626 $css = $this->css_content();
630 unlink($candidatesheet);
631 $css = $this->css_content();
632 file_put_contents($candidatesheet, serialize($css));
635 $baseurl = $CFG->httpswwwroot.'/theme/styles_debug.php';
637 if (check_browser_version('MSIE', 5)) {
638 // lalala, IE does not allow more than 31 linked CSS files from main document
639 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', array('theme'=>$this->name, 'type'=>'ie'));
642 foreach ($css['plugins'] as $plugin=>$unused) {
643 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
645 foreach ($css['parents'] as $parent=>$sheets) {
646 foreach ($sheets as $sheet=>$unused2) {
647 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
650 foreach ($css['theme'] as $sheet=>$unused) {
651 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); // sheet first in order to make long urls easier to read
660 * Returns the content of the one huge CSS merged from all style sheets.
663 public function css_content() {
666 $css = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
668 // get all plugin sheets
670 if (is_array($this->plugins_exclude_sheets) or $this->plugins_exclude_sheets === true) {
671 $excludes = $this->plugins_exclude_sheets;
673 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
674 if (!isset($parent_config->plugins_exclude_sheets)) {
677 if (is_array($parent_config->plugins_exclude_sheets) or $parent_config->plugins_exclude_sheets === true) {
678 $excludes = $parent_config->plugins_exclude_sheets;
683 if ($excludes !== true) {
684 foreach (get_plugin_types() as $type=>$unused) {
685 if ($type === 'theme') {
688 if (!empty($excludes[$type]) and $excludes[$type] === true) {
691 $plugins = get_plugin_list($type);
692 foreach ($plugins as $plugin=>$fulldir) {
693 if (!empty($excludes[$type]) and is_array($excludes[$type])
694 and in_array($plugin, $excludes[$type])) {
699 $sheetfile = "$fulldir/styles.css";
700 if (is_readable($sheetfile)) {
701 $plugincontent .= "/*** Standard plugin $type/$plugin ***/\n\n";
702 $plugincontent .= file_get_contents($sheetfile);
704 $sheetthemefile = "$fulldir/styles_{$this->name}.css";
705 if (is_readable($sheetthemefile)) {
706 $plugincontent .= "\n/*** Standard plugin $type/$plugin for the {$this->name} theme ***/\n\n";
707 $plugincontent .= file_get_contents($sheetthemefile);
709 if (!empty($plugincontent)) {
710 $css['plugins'][$type.'_'.$plugin] = $this->post_process($plugincontent);
716 // find out wanted parent sheets
718 if (is_array($this->parents_exclude_sheets) or $this->parents_exclude_sheets === true) {
719 $excludes = $this->parents_exclude_sheets;
721 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
722 if (!isset($parent_config->parents_exclude_sheets)) {
725 if (is_array($parent_config->parents_exclude_sheets) or $parent_config->parents_exclude_sheets === true) {
726 $excludes = $parent_config->parents_exclude_sheets;
731 if ($excludes !== true) {
732 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
733 $parent = $parent_config->name;
734 if (empty($parent_config->sheets)) {
737 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
740 foreach ($parent_config->sheets as $sheet) {
741 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
742 and in_array($sheet, $excludes[$parent])) {
745 $sheetfile = "$parent_config->dir/style/$sheet.css";
746 if (is_readable($sheetfile)) {
747 $css['parents'][$parent][$sheet] = $this->post_process("/*** Parent theme $parent/style/$sheet.css ***/\n\n" . file_get_contents($sheetfile));
753 // current theme sheets
754 if (is_array($this->sheets)) {
755 foreach ($this->sheets as $sheet) {
756 $sheetfile = "$this->dir/style/$sheet.css";
757 if (is_readable($sheetfile)) {
758 $css['theme'][$sheet] = $this->post_process("/*** This theme $this->name/style/$sheet ***/\n\n" . file_get_contents($sheetfile));
768 * Get the javascript URL of this theme
769 * @param bool $inhead true means haed url, false means footer
772 public function javascript_url($inhead) {
775 $rev = theme_get_revision();
776 $params = array('theme'=>$this->name,'rev'=>$rev);
777 $params['type'] = $inhead ? 'head' : 'footer';
779 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
783 * Returns the content of the one huge javascript file merged from all theme javascript files.
784 * @param bool $inhead
787 public function javascript_content($type) {
788 $type = ($type === 'footer') ? 'javascripts_footer' : 'javascripts';
791 // find out wanted parent javascripts
793 if (is_array($this->parents_exclude_javascripts) or $this->parents_exclude_javascripts === true) {
794 $excludes = $this->parents_exclude_javascripts;
796 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
797 if (!isset($parent_config->parents_exclude_javascripts)) {
800 if (is_array($parent_config->parents_exclude_javascripts) or $parent_config->parents_exclude_javascripts === true) {
801 $excludes = $parent_config->parents_exclude_javascripts;
806 if ($excludes !== true) {
807 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
808 $parent = $parent_config->name;
809 if (empty($parent_config->$type)) {
812 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
815 foreach ($parent_config->$type as $javascript) {
816 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
817 and in_array($javascript, $excludes[$parent])) {
820 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
821 if (is_readable($javascriptfile)) {
822 $js[] = "/*** Parent theme $parent/javascript/$javascript.js ***/\n\n" . file_get_contents($javascriptfile);
828 // current theme javascripts
829 if (is_array($this->$type)) {
830 foreach ($this->$type as $javascript) {
831 $javascriptfile = "$this->dir/javascript/$javascript.js";
832 if (is_readable($javascriptfile)) {
833 $js[] = "/*** This theme $this->name/javascript/$javascript.js ***/\n\n" . file_get_contents($javascriptfile);
838 return implode("\n\n", $js);
841 protected function post_process($css) {
844 // now resolve all image locations
845 if (preg_match_all('/\[\[pix:([a-z_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
847 foreach ($matches as $match) {
848 if (isset($replaced[$match[0]])) {
851 $replaced[$match[0]] = true;
852 $imagename = $match[2];
853 $component = rtrim($match[1], '|');
854 $imageurl = $this->pix_url($imagename, $component)->out(false);
855 // we do not need full url because the image.php is always in the same dir
856 $imageurl = str_replace("$CFG->httpswwwroot/theme/", '', $imageurl);
857 $css = str_replace($match[0], $imageurl, $css);
861 // now resolve all theme settings or do any other postprocessing
862 $csspostprocess = $this->csspostprocess;
863 if (function_exists($csspostprocess)) {
864 $css = $csspostprocess($css, $this);
871 * Return the URL for an image
873 * @param string $imagename the name of the icon.
874 * @param string $component, specification of one plugin like in get_string()
877 public function pix_url($imagename, $component) {
880 $params = array('theme'=>$this->name, 'image'=>$imagename);
882 $rev = theme_get_revision();
884 $params['rev'] = $rev;
886 if (!empty($component) and $component !== 'moodle'and $component !== 'core') {
887 $params['component'] = $component;
890 return new moodle_url("$CFG->httpswwwroot/theme/image.php", $params);
894 * Resolves the real image location.
895 * @param string $image name of image, may contain relative path
896 * @param string $component
897 * @return string full file path
899 public function resolve_image_location($image, $component) {
902 if ($component === 'moodle' or $component === 'core' or empty($component)) {
903 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image")) {
906 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
907 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image")) {
911 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image")) {
916 } else if ($component === 'theme') { //exception
917 if ($image === 'favicon') {
918 return "$this->dir/pix/favicon.ico";
920 if ($imagefile = $this->image_exists("$this->dir/pix/$image")) {
923 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
924 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image")) {
931 if (strpos($component, '_') === false) {
932 $component = 'mod_'.$component;
934 list($type, $plugin) = explode('_', $component, 2);
936 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image")) {
939 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
940 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image")) {
944 $dir = get_plugin_directory($type, $plugin);
945 if ($imagefile = $this->image_exists("$dir/pix/$image")) {
953 * Checks if file with any image extension exists.
954 * @param string $filepath
955 * @return string image name with extension
957 private static function image_exists($filepath) {
958 if (file_exists("$filepath.gif")) {
959 return "$filepath.gif";
960 } else if (file_exists("$filepath.png")) {
961 return "$filepath.png";
962 } else if (file_exists("$filepath.jpg")) {
963 return "$filepath.jpg";
964 } else if (file_exists("$filepath.jpeg")) {
965 return "$filepath.jpeg";
972 * Loads the theme config from config.php file.
973 * @param string $themename
974 * @param object $settings from config_plugins table
977 private static function find_theme_config($themename, $settings) {
978 // We have to use the variable name $THEME (upper case) because that
979 // is what is used in theme config.php files.
981 if (!$dir = theme_config::find_theme_location($themename)) {
985 $THEME = new object();
986 $THEME->name = $themename;
988 $THEME->settings = $settings;
990 global $CFG; // just in case somebody tries to use $CFG in theme config
991 include("$THEME->dir/config.php");
993 // verify the theme configuration is OK
994 if (!is_array($THEME->parents)) {
995 // parents option is mandatory now
1003 * Finds the theme location and verifies the theme has all needed files
1004 * and is not obsoleted.
1005 * @param string $themename
1006 * @return string full dir path or null if not found
1008 private static function find_theme_location($themename) {
1011 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1012 $dir = "$CFG->dirroot/theme/$themename";
1018 if (file_exists("$dir/styles.php")) {
1019 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1027 * Get the renderer for a part of Moodle for this theme.
1028 * @param moodle_page $page the page we are rendering
1029 * @param string $module the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1030 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1031 * @param string $target one of rendering target constants
1032 * @return renderer_base the requested renderer.
1034 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1035 if (is_null($this->rf)) {
1036 $classname = $this->rendererfactory;
1037 $this->rf = new $classname($this);
1040 return $this->rf->get_renderer($page, $component, $subtype, $target);
1044 * Get the information from {@link $layouts} for this type of page.
1045 * @param string $pagelayout the the page layout name.
1046 * @return array the appropriate part of {@link $layouts}.
1048 protected function layout_info_for_page($pagelayout) {
1049 if (array_key_exists($pagelayout, $this->layouts)) {
1050 return $this->layouts[$pagelayout];
1052 debugging('Invalid page layout specified: ' . $pagelayout);
1053 return $this->layouts['standard'];
1058 * Given the settings of this theme, and the page pagelayout, return the
1059 * full path of the page layout file to use.
1061 * Used by {@link core_renderer::header()}.
1063 * @param string $pagelayout the the page layout name.
1064 * @return string Full path to the lyout file to use
1066 public function layout_file($pagelayout) {
1069 $layoutinfo = $this->layout_info_for_page($pagelayout);
1070 $layoutfile = $layoutinfo['file'];
1071 $theme = $layoutinfo['theme'];
1073 if ($dir = $this->find_theme_location($theme)) {
1074 $path = "$dir/layout/$layoutfile";
1076 // Check the template exists, return general base theme template if not.
1077 if (is_readable($path)) {
1082 debugging('Can not find layout file for: ' . $pagelayout);
1083 // fallback to standard normal layout
1084 return "$CFG->dirroot/theme/base/layout/general.php";
1088 * Returns auxiliary page layout options specified in layout configuration array.
1089 * @param string $pagelayout
1092 public function pagelayout_options($pagelayout) {
1093 $info = $this->layout_info_for_page($pagelayout);
1094 if (!empty($info['options'])) {
1095 return $info['options'];
1101 * Inform a block_manager about the block regions this theme wants on this
1103 * @param string $pagelayout the general type of the page.
1104 * @param block_manager $blockmanager the block_manger to set up.
1107 public function setup_blocks($pagelayout, $blockmanager) {
1108 $layoutinfo = $this->layout_info_for_page($pagelayout);
1109 if (!empty($layoutinfo['regions'])) {
1110 $blockmanager->add_regions($layoutinfo['regions']);
1111 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1115 protected function get_region_name($region, $theme) {
1116 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1117 // A name exists in this theme, so use it
1118 if (substr($regionstring, 0, 1) != '[') {
1119 return $regionstring;
1122 // Otherwise, try to find one elsewhere
1123 // Check parents, if any
1124 foreach ($this->parents as $parentthemename) {
1125 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1126 if (substr($regionstring, 0, 1) != '[') {
1127 return $regionstring;
1131 // Last resort, try the base theme for names
1132 return get_string('region-' . $region, 'theme_base');
1136 * Get the list of all block regions known to this theme in all templates.
1137 * @return array internal region name => human readable name.
1139 public function get_all_block_regions() {
1141 foreach ($this->layouts as $layoutinfo) {
1142 foreach ($layoutinfo['regions'] as $region) {
1143 $regions[$region] = $this->get_region_name($region, $layoutinfo['theme']);
1152 * This class keeps track of which HTML tags are currently open.
1154 * This makes it much easier to always generate well formed XHTML output, even
1155 * if execution terminates abruptly. Any time you output some opening HTML
1156 * without the matching closing HTML, you should push the necessary close tags
1159 * @copyright 2009 Tim Hunt
1160 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1163 class xhtml_container_stack {
1164 /** @var array stores the list of open containers. */
1165 protected $opencontainers = array();
1167 * @var array in developer debug mode, stores a stack trace of all opens and
1168 * closes, so we can output helpful error messages when there is a mismatch.
1170 protected $log = array();
1172 * Store whether we are developer debug mode. We need this in several places
1173 * including in the destructor where we may no thave access to $CFG.
1176 protected $isdebugging;
1178 public function __construct() {
1179 $this->isdebugging = debugging('', DEBUG_DEVELOPER);
1183 * Push the close HTML for a recently opened container onto the stack.
1184 * @param string $type The type of container. This is checked when {@link pop()}
1185 * is called and must match, otherwise a developer debug warning is output.
1186 * @param string $closehtml The HTML required to close the container.
1189 public function push($type, $closehtml) {
1190 $container = new stdClass;
1191 $container->type = $type;
1192 $container->closehtml = $closehtml;
1193 if ($this->isdebugging) {
1194 $this->log('Open', $type);
1196 array_push($this->opencontainers, $container);
1200 * Pop the HTML for the next closing container from the stack. The $type
1201 * must match the type passed when the container was opened, otherwise a
1202 * warning will be output.
1203 * @param string $type The type of container.
1204 * @return string the HTML required to close the container.
1206 public function pop($type) {
1207 if (empty($this->opencontainers)) {
1208 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1209 $this->output_log(), DEBUG_DEVELOPER);
1213 $container = array_pop($this->opencontainers);
1214 if ($container->type != $type) {
1215 debugging('<p>The type of container to be closed (' . $container->type .
1216 ') does not match the type of the next open container (' . $type .
1217 '). This suggests there is a nesting problem.</p>' .
1218 $this->output_log(), DEBUG_DEVELOPER);
1220 if ($this->isdebugging) {
1221 $this->log('Close', $type);
1223 return $container->closehtml;
1227 * Close all but the last open container. This is useful in places like error
1228 * handling, where you want to close all the open containers (apart from <body>)
1229 * before outputting the error message.
1230 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1231 * developer debug warning if it isn't.
1232 * @return string the HTML required to close any open containers inside <body>.
1234 public function pop_all_but_last($shouldbenone = false) {
1235 if ($shouldbenone && count($this->opencontainers) != 1) {
1236 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1237 $this->output_log(), DEBUG_DEVELOPER);
1240 while (count($this->opencontainers) > 1) {
1241 $container = array_pop($this->opencontainers);
1242 $output .= $container->closehtml;
1248 * You can call this function if you want to throw away an instance of this
1249 * class without properly emptying the stack (for example, in a unit test).
1250 * Calling this method stops the destruct method from outputting a developer
1251 * debug warning. After calling this method, the instance can no longer be used.
1254 public function discard() {
1255 $this->opencontainers = null;
1259 * Adds an entry to the log.
1260 * @param string $action The name of the action
1261 * @param string $type The type of action
1264 protected function log($action, $type) {
1265 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1266 format_backtrace(debug_backtrace()) . '</li>';
1270 * Outputs the log's contents as a HTML list.
1271 * @return string HTML list of the log
1273 protected function output_log() {
1274 return '<ul>' . implode("\n", $this->log) . '</ul>';