Merge branch 'MDL-39790_master' of git://github.com/totara/openbadges into MOODLE_25_...
[moodle.git] / lib / outputlib.php
blob414f51dbaaa201462e78deaee26a49241ccef52d
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions for generating the HTML that Moodle should output.
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
21 * for an overview.
23 * @copyright 2009 Tim Hunt
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * @package core
26 * @category output
29 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->libdir.'/outputcomponents.php');
32 require_once($CFG->libdir.'/outputactions.php');
33 require_once($CFG->libdir.'/outputfactories.php');
34 require_once($CFG->libdir.'/outputrenderers.php');
35 require_once($CFG->libdir.'/outputrequirementslib.php');
37 /**
38 * Invalidate all server and client side caches.
40 * This method deletes the physical directory that is used to cache the theme
41 * files used for serving.
42 * Because it deletes the main theme cache directory all themes are reset by
43 * this function.
45 function theme_reset_all_caches() {
46 global $CFG, $PAGE;
47 require_once("$CFG->libdir/filelib.php");
49 $next = time();
50 if (isset($CFG->themerev) and $next <= $CFG->themerev and $CFG->themerev - $next < 60*60) {
51 // This resolves problems when reset is requested repeatedly within 1s,
52 // the < 1h condition prevents accidental switching to future dates
53 // because we might not recover from it.
54 $next = $CFG->themerev+1;
57 set_config('themerev', $next); // time is unique even when you reset/switch database
58 fulldelete("$CFG->cachedir/theme");
60 if ($PAGE) {
61 $PAGE->reload_theme();
65 /**
66 * Enable or disable theme designer mode.
68 * @param bool $state
70 function theme_set_designer_mod($state) {
71 theme_reset_all_caches();
72 set_config('themedesignermode', (int)!empty($state));
75 /**
76 * Returns current theme revision number.
78 * @return int
80 function theme_get_revision() {
81 global $CFG;
83 if (empty($CFG->themedesignermode)) {
84 if (empty($CFG->themerev)) {
85 return -1;
86 } else {
87 return $CFG->themerev;
90 } else {
91 return -1;
96 /**
97 * This class represents the configuration variables of a Moodle theme.
99 * All the variables with access: public below (with a few exceptions that are marked)
100 * are the properties you can set in your themes config.php file.
102 * There are also some methods and protected variables that are part of the inner
103 * workings of Moodle's themes system. If you are just editing a themes config.php
104 * file, you can just ignore those, and the following information for developers.
106 * Normally, to create an instance of this class, you should use the
107 * {@link theme_config::load()} factory method to load a themes config.php file.
108 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
109 * will create one for you, accessible as $PAGE->theme.
111 * @copyright 2009 Tim Hunt
112 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
113 * @since Moodle 2.0
114 * @package core
115 * @category output
117 class theme_config {
120 * @var string Default theme, used when requested theme not found.
122 const DEFAULT_THEME = 'standard';
125 * @var array You can base your theme on other themes by linking to the other theme as
126 * parents. This lets you use the CSS and layouts from the other themes
127 * (see {@link theme_config::$layouts}).
128 * That makes it easy to create a new theme that is similar to another one
129 * but with a few changes. In this themes CSS you only need to override
130 * those rules you want to change.
132 public $parents;
135 * @var array The names of all the stylesheets from this theme that you would
136 * like included, in order. Give the names of the files without .css.
138 public $sheets = array();
141 * @var array The names of all the stylesheets from parents that should be excluded.
142 * true value may be used to specify all parents or all themes from one parent.
143 * If no value specified value from parent theme used.
145 public $parents_exclude_sheets = null;
148 * @var array List of plugin sheets to be excluded.
149 * If no value specified value from parent theme used.
151 public $plugins_exclude_sheets = null;
154 * @var array List of style sheets that are included in the text editor bodies.
155 * Sheets from parent themes are used automatically and can not be excluded.
157 public $editor_sheets = array();
160 * @var array The names of all the javascript files this theme that you would
161 * like included from head, in order. Give the names of the files without .js.
163 public $javascripts = array();
166 * @var array The names of all the javascript files this theme that you would
167 * like included from footer, in order. Give the names of the files without .js.
169 public $javascripts_footer = array();
172 * @var array The names of all the javascript files from parents that should
173 * be excluded. true value may be used to specify all parents or all themes
174 * from one parent.
175 * If no value specified value from parent theme used.
177 public $parents_exclude_javascripts = null;
180 * @var array Which file to use for each page layout.
182 * This is an array of arrays. The keys of the outer array are the different layouts.
183 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
184 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
185 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
186 * That file also has a good example of how to set this setting.
188 * For each layout, the value in the outer array is an array that describes
189 * how you want that type of page to look. For example
190 * <pre>
191 * $THEME->layouts = array(
192 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
193 * 'standard' => array(
194 * 'theme' = 'mytheme',
195 * 'file' => 'normal.php',
196 * 'regions' => array('side-pre', 'side-post'),
197 * 'defaultregion' => 'side-post'
198 * ),
199 * // The site home page.
200 * 'home' => array(
201 * 'theme' = 'mytheme',
202 * 'file' => 'home.php',
203 * 'regions' => array('side-pre', 'side-post'),
204 * 'defaultregion' => 'side-post'
205 * ),
206 * // ...
207 * );
208 * </pre>
210 * 'theme' name of the theme where is the layout located
211 * 'file' is the layout file to use for this type of page.
212 * layout files are stored in layout subfolder
213 * 'regions' This lists the regions on the page where blocks may appear. For
214 * each region you list here, your layout file must include a call to
215 * <pre>
216 * echo $OUTPUT->blocks_for_region($regionname);
217 * </pre>
218 * or equivalent so that the blocks are actually visible.
220 * 'defaultregion' If the list of regions is non-empty, then you must pick
221 * one of the one of them as 'default'. This has two meanings. First, this is
222 * where new blocks are added. Second, if there are any blocks associated with
223 * the page, but in non-existent regions, they appear here. (Imaging, for example,
224 * that someone added blocks using a different theme that used different region
225 * names, and then switched to this theme.)
227 public $layouts = array();
230 * @var string Name of the renderer factory class to use. Must implement the
231 * {@link renderer_factory} interface.
233 * This is an advanced feature. Moodle output is generated by 'renderers',
234 * you can customise the HTML that is output by writing custom renderers,
235 * and then you need to specify 'renderer factory' so that Moodle can find
236 * your renderers.
238 * There are some renderer factories supplied with Moodle. Please follow these
239 * links to see what they do.
240 * <ul>
241 * <li>{@link standard_renderer_factory} - the default.</li>
242 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
243 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
244 * </ul>
246 public $rendererfactory = 'standard_renderer_factory';
249 * @var string Function to do custom CSS post-processing.
251 * This is an advanced feature. If you want to do custom post-processing on the
252 * CSS before it is output (for example, to replace certain variable names
253 * with particular values) you can give the name of a function here.
255 public $csspostprocess = null;
258 * @var string Accessibility: Right arrow-like character is
259 * used in the breadcrumb trail, course navigation menu
260 * (previous/next activity), calendar, and search forum block.
261 * If the theme does not set characters, appropriate defaults
262 * are set automatically. Please DO NOT
263 * use &lt; &gt; &raquo; - these are confusing for blind users.
265 public $rarrow = null;
268 * @var string Accessibility: Right arrow-like character is
269 * used in the breadcrumb trail, course navigation menu
270 * (previous/next activity), calendar, and search forum block.
271 * If the theme does not set characters, appropriate defaults
272 * are set automatically. Please DO NOT
273 * use &lt; &gt; &raquo; - these are confusing for blind users.
275 public $larrow = null;
278 * @var bool Some themes may want to disable ajax course editing.
280 public $enablecourseajax = true;
283 * @var string Determines served document types
284 * - 'html5' the only officially supported doctype in Moodle
285 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
286 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
288 public $doctype = 'html5';
290 //==Following properties are not configurable from theme config.php==
293 * @var string The name of this theme. Set automatically when this theme is
294 * loaded. This can not be set in theme config.php
296 public $name;
299 * @var string The folder where this themes files are stored. This is set
300 * automatically. This can not be set in theme config.php
302 public $dir;
305 * @var stdClass Theme settings stored in config_plugins table.
306 * This can not be set in theme config.php
308 public $setting = null;
311 * @var bool If set to true and the theme enables the dock then blocks will be able
312 * to be moved to the special dock
314 public $enable_dock = false;
317 * @var bool If set to true then this theme will not be shown in the theme selector unless
318 * theme designer mode is turned on.
320 public $hidefromselector = false;
323 * @var array list of YUI CSS modules to be included on each page. This may be used
324 * to remove cssreset and use cssnormalise module instead.
326 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
329 * @var renderer_factory Instance of the renderer_factory implementation
330 * we are using. Implementation detail.
332 protected $rf = null;
335 * @var array List of parent config objects.
337 protected $parent_configs = array();
340 * @var bool If set to true then the theme is safe to run through the optimiser (if it is enabled)
341 * If set to false then we know either the theme has already been optimised and the CSS optimiser is not needed
342 * or the theme is not compatible with the CSS optimiser. In both cases even if enabled the CSS optimiser will not
343 * be used with this theme if set to false.
345 public $supportscssoptimisation = true;
348 * Used to determine whether we can serve SVG images or not.
349 * @var bool
351 private $usesvg = null;
354 * Load the config.php file for a particular theme, and return an instance
355 * of this class. (That is, this is a factory method.)
357 * @param string $themename the name of the theme.
358 * @return theme_config an instance of this class.
360 public static function load($themename) {
361 global $CFG;
363 // load theme settings from db
364 try {
365 $settings = get_config('theme_'.$themename);
366 } catch (dml_exception $e) {
367 // most probably moodle tables not created yet
368 $settings = new stdClass();
371 if ($config = theme_config::find_theme_config($themename, $settings)) {
372 return new theme_config($config);
374 } else if ($themename == theme_config::DEFAULT_THEME) {
375 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
377 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
378 return new theme_config($config);
380 } else {
381 // bad luck, the requested theme has some problems - admin see details in theme config
382 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
387 * Theme diagnostic code. It is very problematic to send debug output
388 * to the actual CSS file, instead this functions is supposed to
389 * diagnose given theme and highlights all potential problems.
390 * This information should be available from the theme selection page
391 * or some other debug page for theme designers.
393 * @param string $themename
394 * @return array description of problems
396 public static function diagnose($themename) {
397 //TODO: MDL-21108
398 return array();
402 * Private constructor, can be called only from the factory method.
403 * @param stdClass $config
405 private function __construct($config) {
406 global $CFG; //needed for included lib.php files
408 $this->settings = $config->settings;
409 $this->name = $config->name;
410 $this->dir = $config->dir;
412 if ($this->name != 'base') {
413 $baseconfig = theme_config::find_theme_config('base', $this->settings);
414 } else {
415 $baseconfig = $config;
418 $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer',
419 'parents_exclude_javascripts', 'layouts', 'enable_dock', 'enablecourseajax', 'supportscssoptimisation',
420 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector', 'doctype',
421 'yuicssmodules');
423 foreach ($config as $key=>$value) {
424 if (in_array($key, $configurable)) {
425 $this->$key = $value;
429 // verify all parents and load configs and renderers
430 foreach ($this->parents as $parent) {
431 if ($parent == 'base') {
432 $parent_config = $baseconfig;
433 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
434 // this is not good - better exclude faulty parents
435 continue;
437 $libfile = $parent_config->dir.'/lib.php';
438 if (is_readable($libfile)) {
439 // theme may store various function here
440 include_once($libfile);
442 $renderersfile = $parent_config->dir.'/renderers.php';
443 if (is_readable($renderersfile)) {
444 // may contain core and plugin renderers and renderer factory
445 include_once($renderersfile);
447 $this->parent_configs[$parent] = $parent_config;
448 $rendererfile = $parent_config->dir.'/renderers.php';
449 if (is_readable($rendererfile)) {
450 // may contain core and plugin renderers and renderer factory
451 include_once($rendererfile);
454 $libfile = $this->dir.'/lib.php';
455 if (is_readable($libfile)) {
456 // theme may store various function here
457 include_once($libfile);
459 $rendererfile = $this->dir.'/renderers.php';
460 if (is_readable($rendererfile)) {
461 // may contain core and plugin renderers and renderer factory
462 include_once($rendererfile);
463 } else {
464 // check if renderers.php file is missnamed renderer.php
465 if (is_readable($this->dir.'/renderer.php')) {
466 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
467 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
471 // cascade all layouts properly
472 foreach ($baseconfig->layouts as $layout=>$value) {
473 if (!isset($this->layouts[$layout])) {
474 foreach ($this->parent_configs as $parent_config) {
475 if (isset($parent_config->layouts[$layout])) {
476 $this->layouts[$layout] = $parent_config->layouts[$layout];
477 continue 2;
480 $this->layouts[$layout] = $value;
484 //fix arrows if needed
485 $this->check_theme_arrows();
489 * Let the theme initialise the page object (usually $PAGE).
491 * This may be used for example to request jQuery in add-ons.
493 * @param moodle_page $page
495 public function init_page(moodle_page $page) {
496 $themeinitfunction = 'theme_'.$this->name.'_page_init';
497 if (function_exists($themeinitfunction)) {
498 $themeinitfunction($page);
503 * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
504 * If not it applies sensible defaults.
506 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
507 * search forum block, etc. Important: these are 'silent' in a screen-reader
508 * (unlike &gt; &raquo;), and must be accompanied by text.
510 private function check_theme_arrows() {
511 if (!isset($this->rarrow) and !isset($this->larrow)) {
512 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
513 // Also OK in Win 9x/2K/IE 5.x
514 $this->rarrow = '&#x25BA;';
515 $this->larrow = '&#x25C4;';
516 if (empty($_SERVER['HTTP_USER_AGENT'])) {
517 $uagent = '';
518 } else {
519 $uagent = $_SERVER['HTTP_USER_AGENT'];
521 if (false !== strpos($uagent, 'Opera')
522 || false !== strpos($uagent, 'Mac')) {
523 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
524 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
525 $this->rarrow = '&#x25B6;';
526 $this->larrow = '&#x25C0;';
528 elseif (false !== strpos($uagent, 'Konqueror')) {
529 $this->rarrow = '&rarr;';
530 $this->larrow = '&larr;';
532 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
533 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
534 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
535 // To be safe, non-Unicode browsers!
536 $this->rarrow = '&gt;';
537 $this->larrow = '&lt;';
540 // RTL support - in RTL languages, swap r and l arrows
541 if (right_to_left()) {
542 $t = $this->rarrow;
543 $this->rarrow = $this->larrow;
544 $this->larrow = $t;
550 * Returns output renderer prefixes, these are used when looking
551 * for the overridden renderers in themes.
553 * @return array
555 public function renderer_prefixes() {
556 global $CFG; // just in case the included files need it
558 $prefixes = array('theme_'.$this->name);
560 foreach ($this->parent_configs as $parent) {
561 $prefixes[] = 'theme_'.$parent->name;
564 return $prefixes;
568 * Returns the stylesheet URL of this editor content
570 * @param bool $encoded false means use & and true use &amp; in URLs
571 * @return string
573 public function editor_css_url($encoded=true) {
574 global $CFG;
576 $rev = theme_get_revision();
578 if ($rev > -1) {
579 if (!empty($CFG->slasharguments)) {
580 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
581 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
582 return $url;
583 } else {
584 $params = array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor');
585 return new moodle_url($CFG->httpswwwroot.'/theme/styles.php', $params);
587 } else {
588 $params = array('theme'=>$this->name, 'type'=>'editor');
589 return new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
594 * Returns the content of the CSS to be used in editor content
596 * @return string
598 public function editor_css_files() {
599 global $CFG;
601 $files = array();
603 // first editor plugins
604 $plugins = get_plugin_list('editor');
605 foreach ($plugins as $plugin=>$fulldir) {
606 $sheetfile = "$fulldir/editor_styles.css";
607 if (is_readable($sheetfile)) {
608 $files['plugin_'.$plugin] = $sheetfile;
611 // then parent themes
612 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
613 if (empty($parent_config->editor_sheets)) {
614 continue;
616 foreach ($parent_config->editor_sheets as $sheet) {
617 $sheetfile = "$parent_config->dir/style/$sheet.css";
618 if (is_readable($sheetfile)) {
619 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
623 // finally this theme
624 if (!empty($this->editor_sheets)) {
625 foreach ($this->editor_sheets as $sheet) {
626 $sheetfile = "$this->dir/style/$sheet.css";
627 if (is_readable($sheetfile)) {
628 $files['theme_'.$sheet] = $sheetfile;
633 return $files;
637 * Get the stylesheet URL of this theme
639 * @param moodle_page $page Not used... deprecated?
640 * @return array of moodle_url
642 public function css_urls(moodle_page $page) {
643 global $CFG;
645 $rev = theme_get_revision();
647 $urls = array();
649 $svg = $this->use_svg_icons();
651 if ($rev > -1) {
652 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
653 if (check_browser_version('MSIE', 5)) {
654 // We need to split the CSS files for IE
655 $urls[] = new moodle_url($url, array('theme' => $this->name,'rev' => $rev, 'type' => 'plugins', 'svg' => '0'));
656 $urls[] = new moodle_url($url, array('theme' => $this->name,'rev' => $rev, 'type' => 'parents', 'svg' => '0'));
657 $urls[] = new moodle_url($url, array('theme' => $this->name,'rev' => $rev, 'type' => 'theme', 'svg' => '0'));
658 } else {
659 if (!empty($CFG->slasharguments)) {
660 $slashargs = '/'.$this->name.'/'.$rev.'/all';
661 if (!$svg) {
662 // We add a simple /_s to the start of the path.
663 // The underscore is used to ensure that it isn't a valid theme name.
664 $slashargs = '/_s'.$slashargs;
666 $url->set_slashargument($slashargs, 'noparam', true);
667 } else {
668 $params = array('theme' => $this->name,'rev' => $rev, 'type' => 'all');
669 if (!$svg) {
670 // We add an SVG param so that we know not to serve SVG images.
671 // We do this because all modern browsers support SVG and this param will one day be removed.
672 $params['svg'] = '0';
674 $url->params($params);
676 $urls[] = $url;
678 } else {
679 // find out the current CSS and cache it now for 5 seconds
680 // the point is to construct the CSS only once and pass it through the
681 // dataroot to the script that actually serves the sheets
682 if (!defined('THEME_DESIGNER_CACHE_LIFETIME')) {
683 define('THEME_DESIGNER_CACHE_LIFETIME', 4); // this can be also set in config.php
685 $candidatedir = "$CFG->cachedir/theme/$this->name";
686 if ($svg) {
687 $candidatesheet = "$candidatedir/designer.ser";
688 } else {
689 $candidatesheet = "$candidatedir/designer_nosvg.ser";
691 $rebuild = true;
692 if (file_exists($candidatesheet) and filemtime($candidatesheet) > time() - THEME_DESIGNER_CACHE_LIFETIME) {
693 if ($css = file_get_contents($candidatesheet)) {
694 $css = unserialize($css);
695 if (is_array($css)) {
696 $rebuild = false;
700 if ($rebuild) {
701 // Prepare the CSS optimiser if it is to be used,
702 // please note that it may be very slow and is therefore strongly discouraged in theme designer mode.
703 $optimiser = null;
704 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
705 require_once($CFG->dirroot.'/lib/csslib.php');
706 $optimiser = new css_optimiser;
708 $css = $this->css_content($optimiser);
710 // We do not want any errors here because this may fail easily because of the concurrent access.
711 $prevabort = ignore_user_abort(true);
712 check_dir_exists($candidatedir);
713 $tempfile = tempnam($candidatedir, 'tmpdesigner');
714 file_put_contents($tempfile, serialize($css));
715 $reporting = error_reporting(0);
716 chmod($tempfile, $CFG->filepermissions);
717 unlink($candidatesheet); // Do not rely on rename() deleting original, they may decide to change it at any time as usually.
718 rename($tempfile, $candidatesheet);
719 error_reporting($reporting);
720 ignore_user_abort($prevabort);
723 $baseurl = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php');
724 if (!$svg) {
725 // We add an SVG param so that we know not to serve SVG images.
726 // We do this because all modern browsers support SVG and this param will one day be removed.
727 $baseurl->param('svg', '0');
729 if (check_browser_version('MSIE', 5)) {
730 // lalala, IE does not allow more than 31 linked CSS files from main document
731 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
732 foreach ($css['parents'] as $parent=>$sheets) {
733 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096)
734 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
736 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
738 } else {
739 foreach ($css['plugins'] as $plugin=>$unused) {
740 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
742 foreach ($css['parents'] as $parent=>$sheets) {
743 foreach ($sheets as $sheet=>$unused2) {
744 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
747 foreach ($css['theme'] as $sheet=>$unused) {
748 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); // sheet first in order to make long urls easier to read
753 return $urls;
757 * Returns an array of organised CSS files required for this output
759 * @return array
761 public function css_files() {
762 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
764 // get all plugin sheets
765 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
766 if ($excludes !== true) {
767 foreach (get_plugin_types() as $type=>$unused) {
768 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
769 continue;
771 $plugins = get_plugin_list($type);
772 foreach ($plugins as $plugin=>$fulldir) {
773 if (!empty($excludes[$type]) and is_array($excludes[$type])
774 and in_array($plugin, $excludes[$type])) {
775 continue;
778 $plugincontent = '';
779 $sheetfile = "$fulldir/styles.css";
780 if (is_readable($sheetfile)) {
781 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
783 $sheetthemefile = "$fulldir/styles_{$this->name}.css";
784 if (is_readable($sheetthemefile)) {
785 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$this->name] = $sheetthemefile;
791 // find out wanted parent sheets
792 $excludes = $this->resolve_excludes('parents_exclude_sheets');
793 if ($excludes !== true) {
794 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
795 $parent = $parent_config->name;
796 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
797 continue;
799 foreach ($parent_config->sheets as $sheet) {
800 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
801 and in_array($sheet, $excludes[$parent])) {
802 continue;
804 $sheetfile = "$parent_config->dir/style/$sheet.css";
805 if (is_readable($sheetfile)) {
806 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
812 // current theme sheets
813 if (is_array($this->sheets)) {
814 foreach ($this->sheets as $sheet) {
815 $sheetfile = "$this->dir/style/$sheet.css";
816 if (is_readable($sheetfile)) {
817 $cssfiles['theme'][$sheet] = $sheetfile;
822 return $cssfiles;
826 * Returns the content of the one huge CSS merged from all style sheets.
828 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
829 * @return string
831 public function css_content(css_optimiser $optimiser = null) {
832 $files = array_merge($this->css_files(), array('editor'=>$this->editor_css_files()));
833 $css = $this->css_files_get_contents($files, array(), $optimiser);
834 return $css;
838 * Given an array of file paths or a single file path loads the contents of
839 * the CSS file, processes it then returns it in the same structure it was given.
841 * Can be used recursively on the results of {@link css_files}
843 * @param array|string $file An array of file paths or a single file path
844 * @param array $keys An array of previous array keys [recursive addition]
845 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
846 * @return The converted array or the contents of the single file ($file type)
848 protected function css_files_get_contents($file, array $keys, css_optimiser $optimiser = null) {
849 global $CFG;
850 if (is_array($file)) {
851 // We use a separate array to keep everything in the exact same order.
852 $return = array();
853 foreach ($file as $key=>$f) {
854 $return[clean_param($key, PARAM_SAFEDIR)] = $this->css_files_get_contents($f, array_merge($keys, array($key)), $optimiser);
856 return $return;
857 } else {
858 $contents = file_get_contents($file);
859 $contents = $this->post_process($contents);
860 $comment = '/** Path: '.implode(' ', $keys).' **/'."\n";
861 $stats = '';
862 if (!is_null($optimiser)) {
863 $contents = $optimiser->process($contents);
864 if (!empty($CFG->cssoptimiserstats)) {
865 $stats = $optimiser->output_stats_css();
868 return $comment.$stats.$contents;
874 * Generate a URL to the file that serves theme JavaScript files.
876 * If we determine that the theme has no relevant files, then we return
877 * early with a null value.
879 * @param bool $inhead true means head url, false means footer
880 * @return moodle_url|null
882 public function javascript_url($inhead) {
883 global $CFG;
885 $rev = theme_get_revision();
886 $params = array('theme'=>$this->name,'rev'=>$rev);
887 $params['type'] = $inhead ? 'head' : 'footer';
889 // Return early if there are no files to serve
890 if (count($this->javascript_files($params['type'])) === 0) {
891 return null;
894 if (!empty($CFG->slasharguments) and $rev > 0) {
895 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
896 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
897 return $url;
898 } else {
899 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
904 * Get the URL's for the JavaScript files used by this theme.
905 * They won't be served directly, instead they'll be mediated through
906 * theme/javascript.php.
908 * @param string $type Either javascripts_footer, or javascripts
909 * @return array
911 public function javascript_files($type) {
912 if ($type === 'footer') {
913 $type = 'javascripts_footer';
914 } else {
915 $type = 'javascripts';
918 $js = array();
919 // find out wanted parent javascripts
920 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
921 if ($excludes !== true) {
922 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
923 $parent = $parent_config->name;
924 if (empty($parent_config->$type)) {
925 continue;
927 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
928 continue;
930 foreach ($parent_config->$type as $javascript) {
931 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
932 and in_array($javascript, $excludes[$parent])) {
933 continue;
935 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
936 if (is_readable($javascriptfile)) {
937 $js[] = $javascriptfile;
943 // current theme javascripts
944 if (is_array($this->$type)) {
945 foreach ($this->$type as $javascript) {
946 $javascriptfile = "$this->dir/javascript/$javascript.js";
947 if (is_readable($javascriptfile)) {
948 $js[] = $javascriptfile;
952 return $js;
956 * Resolves an exclude setting to the themes setting is applicable or the
957 * setting of its closest parent.
959 * @param string $variable The name of the setting the exclude setting to resolve
960 * @param string $default
961 * @return mixed
963 protected function resolve_excludes($variable, $default = null) {
964 $setting = $default;
965 if (is_array($this->{$variable}) or $this->{$variable} === true) {
966 $setting = $this->{$variable};
967 } else {
968 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
969 if (!isset($parent_config->{$variable})) {
970 continue;
972 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
973 $setting = $parent_config->{$variable};
974 break;
978 return $setting;
982 * Returns the content of the one huge javascript file merged from all theme javascript files.
984 * @param bool $type
985 * @return string
987 public function javascript_content($type) {
988 $jsfiles = $this->javascript_files($type);
989 $js = '';
990 foreach ($jsfiles as $jsfile) {
991 $js .= file_get_contents($jsfile)."\n";
993 return $js;
997 * Post processes CSS.
999 * This method post processes all of the CSS before it is served for this theme.
1000 * This is done so that things such as image URL's can be swapped in and to
1001 * run any specific CSS post process method the theme has requested.
1002 * This allows themes to use CSS settings.
1004 * @param string $css The CSS to process.
1005 * @return string The processed CSS.
1007 public function post_process($css) {
1008 // now resolve all image locations
1009 if (preg_match_all('/\[\[pix:([a-z_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1010 $replaced = array();
1011 foreach ($matches as $match) {
1012 if (isset($replaced[$match[0]])) {
1013 continue;
1015 $replaced[$match[0]] = true;
1016 $imagename = $match[2];
1017 $component = rtrim($match[1], '|');
1018 $imageurl = $this->pix_url($imagename, $component)->out(false);
1019 // we do not need full url because the image.php is always in the same dir
1020 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1021 $css = str_replace($match[0], $imageurl, $css);
1025 // now resolve all theme settings or do any other postprocessing
1026 $csspostprocess = $this->csspostprocess;
1027 if (function_exists($csspostprocess)) {
1028 $css = $csspostprocess($css, $this);
1031 return $css;
1035 * Return the URL for an image
1037 * @param string $imagename the name of the icon.
1038 * @param string $component specification of one plugin like in get_string()
1039 * @return moodle_url
1041 public function pix_url($imagename, $component) {
1042 global $CFG;
1044 $params = array('theme'=>$this->name);
1045 $svg = $this->use_svg_icons();
1047 if (empty($component) or $component === 'moodle' or $component === 'core') {
1048 $params['component'] = 'core';
1049 } else {
1050 $params['component'] = $component;
1053 $rev = theme_get_revision();
1054 if ($rev != -1) {
1055 $params['rev'] = $rev;
1058 $params['image'] = $imagename;
1060 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1061 if (!empty($CFG->slasharguments) and $rev > 0) {
1062 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1063 if (!$svg) {
1064 // We add a simple /_s to the start of the path.
1065 // The underscore is used to ensure that it isn't a valid theme name.
1066 $path = '/_s'.$path;
1068 $url->set_slashargument($path, 'noparam', true);
1069 } else {
1070 if (!$svg) {
1071 // We add an SVG param so that we know not to serve SVG images.
1072 // We do this because all modern browsers support SVG and this param will one day be removed.
1073 $params['svg'] = '0';
1075 $url->params($params);
1078 return $url;
1082 * Returns URL to the stored file via pluginfile.php.
1084 * Note the theme must also implement pluginfile.php handler,
1085 * theme revision is used instead of the itemid.
1087 * @param string $setting
1088 * @param string $filearea
1089 * @return string protocol relative URL or null if not present
1091 public function setting_file_url($setting, $filearea) {
1092 global $CFG;
1094 if (empty($this->settings->$setting)) {
1095 return null;
1098 $component = 'theme_'.$this->name;
1099 $itemid = theme_get_revision();
1100 $filepath = $this->settings->$setting;
1101 $syscontext = context_system::instance();
1103 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1105 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1106 // Note: unfortunately moodle_url does not support //urls yet.
1108 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1110 return $url;
1114 * Serve the theme setting file.
1116 * @param string $filearea
1117 * @param array $args
1118 * @param bool $forcedownload
1119 * @param array $options
1120 * @return bool may terminate if file not found or donotdie not specified
1122 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1123 global $CFG;
1124 require_once("$CFG->libdir/filelib.php");
1126 $syscontext = context_system::instance();
1127 $component = 'theme_'.$this->name;
1129 $revision = array_shift($args);
1130 if ($revision < 0) {
1131 $lifetime = 0;
1132 } else {
1133 $lifetime = 60*60*24*60;
1136 $fs = get_file_storage();
1137 $relativepath = implode('/', $args);
1139 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1140 $fullpath = rtrim($fullpath, '/');
1141 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1142 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1143 return true;
1144 } else {
1145 send_file_not_found();
1150 * Resolves the real image location.
1152 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1153 * and we need a way in which to turn it off.
1154 * By default SVG won't be used unless asked for. This is done for two reasons:
1155 * 1. It ensures that we don't serve svg images unless we really want to. The admin has selected to force them, of the users
1156 * browser supports SVG.
1157 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1158 * by the user due to security concerns.
1160 * @param string $image name of image, may contain relative path
1161 * @param string $component
1162 * @param bool $svg If set to true SVG images will also be looked for.
1163 * @return string full file path
1165 public function resolve_image_location($image, $component, $svg = false) {
1166 global $CFG;
1168 if (!is_bool($svg)) {
1169 // If $svg isn't a bool then we need to decide for ourselves.
1170 $svg = $this->use_svg_icons();
1173 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1174 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1175 return $imagefile;
1177 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1178 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1179 return $imagefile;
1182 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1183 return $imagefile;
1185 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1186 return $imagefile;
1188 return null;
1190 } else if ($component === 'theme') { //exception
1191 if ($image === 'favicon') {
1192 return "$this->dir/pix/favicon.ico";
1194 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1195 return $imagefile;
1197 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1198 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1199 return $imagefile;
1202 return null;
1204 } else {
1205 if (strpos($component, '_') === false) {
1206 $component = 'mod_'.$component;
1208 list($type, $plugin) = explode('_', $component, 2);
1210 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1211 return $imagefile;
1213 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1214 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1215 return $imagefile;
1218 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1219 return $imagefile;
1221 $dir = get_plugin_directory($type, $plugin);
1222 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1223 return $imagefile;
1225 return null;
1230 * Return true if we should look for SVG images as well.
1232 * @staticvar bool $svg
1233 * @return bool
1235 public function use_svg_icons() {
1236 global $CFG;
1237 if ($this->usesvg === null) {
1238 if (!isset($CFG->svgicons) || !is_bool($CFG->svgicons)) {
1239 // IE 5 - 8 don't support SVG at all.
1240 if (empty($_SERVER['HTTP_USER_AGENT'])) {
1241 // Can't be sure, just say no.
1242 $this->usesvg = false;
1243 } else if (check_browser_version('MSIE', 0) and !check_browser_version('MSIE', 9)) {
1244 // IE < 9 doesn't support SVG. Say no.
1245 $this->usesvg = false;
1246 } else if (preg_match('#Android +[0-2]\.#', $_SERVER['HTTP_USER_AGENT'])) {
1247 // Android < 3 doesn't support SVG. Say no.
1248 $this->usesvg = false;
1249 } else if (check_browser_version('Opera', 0)) {
1250 // Opera 12 still does not support SVG well enough. Say no.
1251 $this->usesvg = false;
1252 } else {
1253 // Presumed fine.
1254 $this->usesvg = true;
1256 } else {
1257 // Force them on/off depending upon the setting.
1258 $this->usesvg = $CFG->svgicons;
1261 return $this->usesvg;
1265 * Forces the usesvg setting to either true or false, avoiding any decision making.
1267 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
1268 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
1270 * @param bool $setting True to force the use of svg when available, null otherwise.
1272 public function force_svg_use($setting) {
1273 $this->usesvg = (bool)$setting;
1277 * Checks if file with any image extension exists.
1279 * The order to these images was adjusted prior to the release of 2.4
1280 * At that point the were the following image counts in Moodle core:
1282 * - png = 667 in pix dirs (1499 total)
1283 * - gif = 385 in pix dirs (606 total)
1284 * - jpg = 62 in pix dirs (74 total)
1285 * - jpeg = 0 in pix dirs (1 total)
1287 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1289 * @param string $filepath
1290 * @param bool $svg If set to true SVG images will also be looked for.
1291 * @return string image name with extension
1293 private static function image_exists($filepath, $svg = false) {
1294 if ($svg && file_exists("$filepath.svg")) {
1295 return "$filepath.svg";
1296 } else if (file_exists("$filepath.png")) {
1297 return "$filepath.png";
1298 } else if (file_exists("$filepath.gif")) {
1299 return "$filepath.gif";
1300 } else if (file_exists("$filepath.jpg")) {
1301 return "$filepath.jpg";
1302 } else if (file_exists("$filepath.jpeg")) {
1303 return "$filepath.jpeg";
1304 } else {
1305 return false;
1310 * Loads the theme config from config.php file.
1312 * @param string $themename
1313 * @param stdClass $settings from config_plugins table
1314 * @return stdClass The theme configuration
1316 private static function find_theme_config($themename, $settings) {
1317 // We have to use the variable name $THEME (upper case) because that
1318 // is what is used in theme config.php files.
1320 if (!$dir = theme_config::find_theme_location($themename)) {
1321 return null;
1324 $THEME = new stdClass();
1325 $THEME->name = $themename;
1326 $THEME->dir = $dir;
1327 $THEME->settings = $settings;
1329 global $CFG; // just in case somebody tries to use $CFG in theme config
1330 include("$THEME->dir/config.php");
1332 // verify the theme configuration is OK
1333 if (!is_array($THEME->parents)) {
1334 // parents option is mandatory now
1335 return null;
1338 return $THEME;
1342 * Finds the theme location and verifies the theme has all needed files
1343 * and is not obsoleted.
1345 * @param string $themename
1346 * @return string full dir path or null if not found
1348 private static function find_theme_location($themename) {
1349 global $CFG;
1351 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1352 $dir = "$CFG->dirroot/theme/$themename";
1354 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1355 $dir = "$CFG->themedir/$themename";
1357 } else {
1358 return null;
1361 if (file_exists("$dir/styles.php")) {
1362 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1363 return null;
1366 return $dir;
1370 * Get the renderer for a part of Moodle for this theme.
1372 * @param moodle_page $page the page we are rendering
1373 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1374 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1375 * @param string $target one of rendering target constants
1376 * @return renderer_base the requested renderer.
1378 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1379 if (is_null($this->rf)) {
1380 $classname = $this->rendererfactory;
1381 $this->rf = new $classname($this);
1384 return $this->rf->get_renderer($page, $component, $subtype, $target);
1388 * Get the information from {@link $layouts} for this type of page.
1390 * @param string $pagelayout the the page layout name.
1391 * @return array the appropriate part of {@link $layouts}.
1393 protected function layout_info_for_page($pagelayout) {
1394 if (array_key_exists($pagelayout, $this->layouts)) {
1395 return $this->layouts[$pagelayout];
1396 } else {
1397 debugging('Invalid page layout specified: ' . $pagelayout);
1398 return $this->layouts['standard'];
1403 * Given the settings of this theme, and the page pagelayout, return the
1404 * full path of the page layout file to use.
1406 * Used by {@link core_renderer::header()}.
1408 * @param string $pagelayout the the page layout name.
1409 * @return string Full path to the lyout file to use
1411 public function layout_file($pagelayout) {
1412 global $CFG;
1414 $layoutinfo = $this->layout_info_for_page($pagelayout);
1415 $layoutfile = $layoutinfo['file'];
1417 if (array_key_exists('theme', $layoutinfo)) {
1418 $themes = array($layoutinfo['theme']);
1419 } else {
1420 $themes = array_merge(array($this->name),$this->parents);
1423 foreach ($themes as $theme) {
1424 if ($dir = $this->find_theme_location($theme)) {
1425 $path = "$dir/layout/$layoutfile";
1427 // Check the template exists, return general base theme template if not.
1428 if (is_readable($path)) {
1429 return $path;
1434 debugging('Can not find layout file for: ' . $pagelayout);
1435 // fallback to standard normal layout
1436 return "$CFG->dirroot/theme/base/layout/general.php";
1440 * Returns auxiliary page layout options specified in layout configuration array.
1442 * @param string $pagelayout
1443 * @return array
1445 public function pagelayout_options($pagelayout) {
1446 $info = $this->layout_info_for_page($pagelayout);
1447 if (!empty($info['options'])) {
1448 return $info['options'];
1450 return array();
1454 * Inform a block_manager about the block regions this theme wants on this
1455 * page layout.
1457 * @param string $pagelayout the general type of the page.
1458 * @param block_manager $blockmanager the block_manger to set up.
1460 public function setup_blocks($pagelayout, $blockmanager) {
1461 $layoutinfo = $this->layout_info_for_page($pagelayout);
1462 if (!empty($layoutinfo['regions'])) {
1463 $blockmanager->add_regions($layoutinfo['regions']);
1464 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1469 * Gets the visible name for the requested block region.
1471 * @param string $region The region name to get
1472 * @param string $theme The theme the region belongs to (may come from the parent theme)
1473 * @return string
1475 protected function get_region_name($region, $theme) {
1476 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1477 // A name exists in this theme, so use it
1478 if (substr($regionstring, 0, 1) != '[') {
1479 return $regionstring;
1482 // Otherwise, try to find one elsewhere
1483 // Check parents, if any
1484 foreach ($this->parents as $parentthemename) {
1485 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1486 if (substr($regionstring, 0, 1) != '[') {
1487 return $regionstring;
1491 // Last resort, try the base theme for names
1492 return get_string('region-' . $region, 'theme_base');
1496 * Get the list of all block regions known to this theme in all templates.
1498 * @return array internal region name => human readable name.
1500 public function get_all_block_regions() {
1501 $regions = array();
1502 foreach ($this->layouts as $layoutinfo) {
1503 foreach ($layoutinfo['regions'] as $region) {
1504 $regions[$region] = $this->get_region_name($region, $this->name);
1507 return $regions;
1511 * Returns the human readable name of the theme
1513 * @return string
1515 public function get_theme_name() {
1516 return get_string('pluginname', 'theme_'.$this->name);
1521 * This class keeps track of which HTML tags are currently open.
1523 * This makes it much easier to always generate well formed XHTML output, even
1524 * if execution terminates abruptly. Any time you output some opening HTML
1525 * without the matching closing HTML, you should push the necessary close tags
1526 * onto the stack.
1528 * @copyright 2009 Tim Hunt
1529 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1530 * @since Moodle 2.0
1531 * @package core
1532 * @category output
1534 class xhtml_container_stack {
1537 * @var array Stores the list of open containers.
1539 protected $opencontainers = array();
1542 * @var array In developer debug mode, stores a stack trace of all opens and
1543 * closes, so we can output helpful error messages when there is a mismatch.
1545 protected $log = array();
1548 * @var boolean Store whether we are developer debug mode. We need this in
1549 * several places including in the destructor where we may not have access to $CFG.
1551 protected $isdebugging;
1554 * Constructor
1556 public function __construct() {
1557 $this->isdebugging = debugging('', DEBUG_DEVELOPER);
1561 * Push the close HTML for a recently opened container onto the stack.
1563 * @param string $type The type of container. This is checked when {@link pop()}
1564 * is called and must match, otherwise a developer debug warning is output.
1565 * @param string $closehtml The HTML required to close the container.
1567 public function push($type, $closehtml) {
1568 $container = new stdClass;
1569 $container->type = $type;
1570 $container->closehtml = $closehtml;
1571 if ($this->isdebugging) {
1572 $this->log('Open', $type);
1574 array_push($this->opencontainers, $container);
1578 * Pop the HTML for the next closing container from the stack. The $type
1579 * must match the type passed when the container was opened, otherwise a
1580 * warning will be output.
1582 * @param string $type The type of container.
1583 * @return string the HTML required to close the container.
1585 public function pop($type) {
1586 if (empty($this->opencontainers)) {
1587 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1588 $this->output_log(), DEBUG_DEVELOPER);
1589 return;
1592 $container = array_pop($this->opencontainers);
1593 if ($container->type != $type) {
1594 debugging('<p>The type of container to be closed (' . $container->type .
1595 ') does not match the type of the next open container (' . $type .
1596 '). This suggests there is a nesting problem.</p>' .
1597 $this->output_log(), DEBUG_DEVELOPER);
1599 if ($this->isdebugging) {
1600 $this->log('Close', $type);
1602 return $container->closehtml;
1606 * Close all but the last open container. This is useful in places like error
1607 * handling, where you want to close all the open containers (apart from <body>)
1608 * before outputting the error message.
1610 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1611 * developer debug warning if it isn't.
1612 * @return string the HTML required to close any open containers inside <body>.
1614 public function pop_all_but_last($shouldbenone = false) {
1615 if ($shouldbenone && count($this->opencontainers) != 1) {
1616 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1617 $this->output_log(), DEBUG_DEVELOPER);
1619 $output = '';
1620 while (count($this->opencontainers) > 1) {
1621 $container = array_pop($this->opencontainers);
1622 $output .= $container->closehtml;
1624 return $output;
1628 * You can call this function if you want to throw away an instance of this
1629 * class without properly emptying the stack (for example, in a unit test).
1630 * Calling this method stops the destruct method from outputting a developer
1631 * debug warning. After calling this method, the instance can no longer be used.
1633 public function discard() {
1634 $this->opencontainers = null;
1638 * Adds an entry to the log.
1640 * @param string $action The name of the action
1641 * @param string $type The type of action
1643 protected function log($action, $type) {
1644 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1645 format_backtrace(debug_backtrace()) . '</li>';
1649 * Outputs the log's contents as a HTML list.
1651 * @return string HTML list of the log
1653 protected function output_log() {
1654 return '<ul>' . implode("\n", $this->log) . '</ul>';