MDL-36721 make upgrade queries cross-db
[moodle.git] / lib / outputlib.php
blob3f833d053cc584f790e0f68f91f52cfd1f86aad0
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;
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");
61 /**
62 * Enable or disable theme designer mode.
64 * @param bool $state
66 function theme_set_designer_mod($state) {
67 theme_reset_all_caches();
68 set_config('themedesignermode', (int)!empty($state));
71 /**
72 * Returns current theme revision number.
74 * @return int
76 function theme_get_revision() {
77 global $CFG;
79 if (empty($CFG->themedesignermode)) {
80 if (empty($CFG->themerev)) {
81 return -1;
82 } else {
83 return $CFG->themerev;
86 } else {
87 return -1;
92 /**
93 * This class represents the configuration variables of a Moodle theme.
95 * All the variables with access: public below (with a few exceptions that are marked)
96 * are the properties you can set in your themes config.php file.
98 * There are also some methods and protected variables that are part of the inner
99 * workings of Moodle's themes system. If you are just editing a themes config.php
100 * file, you can just ignore those, and the following information for developers.
102 * Normally, to create an instance of this class, you should use the
103 * {@link theme_config::load()} factory method to load a themes config.php file.
104 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
105 * will create one for you, accessible as $PAGE->theme.
107 * @copyright 2009 Tim Hunt
108 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
109 * @since Moodle 2.0
110 * @package core
111 * @category output
113 class theme_config {
116 * @var string Default theme, used when requested theme not found.
118 const DEFAULT_THEME = 'standard';
121 * @var array You can base your theme on other themes by linking to the other theme as
122 * parents. This lets you use the CSS and layouts from the other themes
123 * (see {@link theme_config::$layouts}).
124 * That makes it easy to create a new theme that is similar to another one
125 * but with a few changes. In this themes CSS you only need to override
126 * those rules you want to change.
128 public $parents;
131 * @var array The names of all the stylesheets from this theme that you would
132 * like included, in order. Give the names of the files without .css.
134 public $sheets = array();
137 * @var array The names of all the stylesheets from parents that should be excluded.
138 * true value may be used to specify all parents or all themes from one parent.
139 * If no value specified value from parent theme used.
141 public $parents_exclude_sheets = null;
144 * @var array List of plugin sheets to be excluded.
145 * If no value specified value from parent theme used.
147 public $plugins_exclude_sheets = null;
150 * @var array List of style sheets that are included in the text editor bodies.
151 * Sheets from parent themes are used automatically and can not be excluded.
153 public $editor_sheets = array();
156 * @var array The names of all the javascript files this theme that you would
157 * like included from head, in order. Give the names of the files without .js.
159 public $javascripts = array();
162 * @var array The names of all the javascript files this theme that you would
163 * like included from footer, in order. Give the names of the files without .js.
165 public $javascripts_footer = array();
168 * @var array The names of all the javascript files from parents that should
169 * be excluded. true value may be used to specify all parents or all themes
170 * from one parent.
171 * If no value specified value from parent theme used.
173 public $parents_exclude_javascripts = null;
176 * @var array Which file to use for each page layout.
178 * This is an array of arrays. The keys of the outer array are the different layouts.
179 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
180 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
181 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
182 * That file also has a good example of how to set this setting.
184 * For each layout, the value in the outer array is an array that describes
185 * how you want that type of page to look. For example
186 * <pre>
187 * $THEME->layouts = array(
188 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
189 * 'standard' => array(
190 * 'theme' = 'mytheme',
191 * 'file' => 'normal.php',
192 * 'regions' => array('side-pre', 'side-post'),
193 * 'defaultregion' => 'side-post'
194 * ),
195 * // The site home page.
196 * 'home' => array(
197 * 'theme' = 'mytheme',
198 * 'file' => 'home.php',
199 * 'regions' => array('side-pre', 'side-post'),
200 * 'defaultregion' => 'side-post'
201 * ),
202 * // ...
203 * );
204 * </pre>
206 * 'theme' name of the theme where is the layout located
207 * 'file' is the layout file to use for this type of page.
208 * layout files are stored in layout subfolder
209 * 'regions' This lists the regions on the page where blocks may appear. For
210 * each region you list here, your layout file must include a call to
211 * <pre>
212 * echo $OUTPUT->blocks_for_region($regionname);
213 * </pre>
214 * or equivalent so that the blocks are actually visible.
216 * 'defaultregion' If the list of regions is non-empty, then you must pick
217 * one of the one of them as 'default'. This has two meanings. First, this is
218 * where new blocks are added. Second, if there are any blocks associated with
219 * the page, but in non-existent regions, they appear here. (Imaging, for example,
220 * that someone added blocks using a different theme that used different region
221 * names, and then switched to this theme.)
223 public $layouts = array();
226 * @var string Name of the renderer factory class to use. Must implement the
227 * {@link renderer_factory} interface.
229 * This is an advanced feature. Moodle output is generated by 'renderers',
230 * you can customise the HTML that is output by writing custom renderers,
231 * and then you need to specify 'renderer factory' so that Moodle can find
232 * your renderers.
234 * There are some renderer factories supplied with Moodle. Please follow these
235 * links to see what they do.
236 * <ul>
237 * <li>{@link standard_renderer_factory} - the default.</li>
238 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
239 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
240 * </ul>
242 public $rendererfactory = 'standard_renderer_factory';
245 * @var string Function to do custom CSS post-processing.
247 * This is an advanced feature. If you want to do custom post-processing on the
248 * CSS before it is output (for example, to replace certain variable names
249 * with particular values) you can give the name of a function here.
251 public $csspostprocess = null;
254 * @var string Accessibility: Right arrow-like character is
255 * used in the breadcrumb trail, course navigation menu
256 * (previous/next activity), calendar, and search forum block.
257 * If the theme does not set characters, appropriate defaults
258 * are set automatically. Please DO NOT
259 * use &lt; &gt; &raquo; - these are confusing for blind users.
261 public $rarrow = null;
264 * @var string Accessibility: Right arrow-like character is
265 * used in the breadcrumb trail, course navigation menu
266 * (previous/next activity), calendar, and search forum block.
267 * If the theme does not set characters, appropriate defaults
268 * are set automatically. Please DO NOT
269 * use &lt; &gt; &raquo; - these are confusing for blind users.
271 public $larrow = null;
274 * @var bool Some themes may want to disable ajax course editing.
276 public $enablecourseajax = true;
279 * @var string Determines served document types
280 * - 'html5' the only officially supported doctype in Moodle
281 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
282 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
284 public $doctype = 'html5';
286 //==Following properties are not configurable from theme config.php==
289 * @var string The name of this theme. Set automatically when this theme is
290 * loaded. This can not be set in theme config.php
292 public $name;
295 * @var string The folder where this themes files are stored. This is set
296 * automatically. This can not be set in theme config.php
298 public $dir;
301 * @var stdClass Theme settings stored in config_plugins table.
302 * This can not be set in theme config.php
304 public $setting = null;
307 * @var bool If set to true and the theme enables the dock then blocks will be able
308 * to be moved to the special dock
310 public $enable_dock = false;
313 * @var bool If set to true then this theme will not be shown in the theme selector unless
314 * theme designer mode is turned on.
316 public $hidefromselector = false;
319 * @var renderer_factory Instance of the renderer_factory implementation
320 * we are using. Implementation detail.
322 protected $rf = null;
325 * @var array List of parent config objects.
327 protected $parent_configs = array();
330 * @var bool If set to true then the theme is safe to run through the optimiser (if it is enabled)
331 * If set to false then we know either the theme has already been optimised and the CSS optimiser is not needed
332 * or the theme is not compatible with the CSS optimiser. In both cases even if enabled the CSS optimiser will not
333 * be used with this theme if set to false.
335 public $supportscssoptimisation = true;
338 * Used to determine whether we can serve SVG images or not.
339 * @var bool
341 private $usesvg = null;
344 * Load the config.php file for a particular theme, and return an instance
345 * of this class. (That is, this is a factory method.)
347 * @param string $themename the name of the theme.
348 * @return theme_config an instance of this class.
350 public static function load($themename) {
351 global $CFG;
353 // load theme settings from db
354 try {
355 $settings = get_config('theme_'.$themename);
356 } catch (dml_exception $e) {
357 // most probably moodle tables not created yet
358 $settings = new stdClass();
361 if ($config = theme_config::find_theme_config($themename, $settings)) {
362 return new theme_config($config);
364 } else if ($themename == theme_config::DEFAULT_THEME) {
365 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
367 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
368 return new theme_config($config);
370 } else {
371 // bad luck, the requested theme has some problems - admin see details in theme config
372 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
377 * Theme diagnostic code. It is very problematic to send debug output
378 * to the actual CSS file, instead this functions is supposed to
379 * diagnose given theme and highlights all potential problems.
380 * This information should be available from the theme selection page
381 * or some other debug page for theme designers.
383 * @param string $themename
384 * @return array description of problems
386 public static function diagnose($themename) {
387 //TODO: MDL-21108
388 return array();
392 * Private constructor, can be called only from the factory method.
393 * @param stdClass $config
395 private function __construct($config) {
396 global $CFG; //needed for included lib.php files
398 $this->settings = $config->settings;
399 $this->name = $config->name;
400 $this->dir = $config->dir;
402 if ($this->name != 'base') {
403 $baseconfig = theme_config::find_theme_config('base', $this->settings);
404 } else {
405 $baseconfig = $config;
408 $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer',
409 'parents_exclude_javascripts', 'layouts', 'enable_dock', 'enablecourseajax', 'supportscssoptimisation',
410 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector', 'doctype');
412 foreach ($config as $key=>$value) {
413 if (in_array($key, $configurable)) {
414 $this->$key = $value;
418 // verify all parents and load configs and renderers
419 foreach ($this->parents as $parent) {
420 if ($parent == 'base') {
421 $parent_config = $baseconfig;
422 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
423 // this is not good - better exclude faulty parents
424 continue;
426 $libfile = $parent_config->dir.'/lib.php';
427 if (is_readable($libfile)) {
428 // theme may store various function here
429 include_once($libfile);
431 $renderersfile = $parent_config->dir.'/renderers.php';
432 if (is_readable($renderersfile)) {
433 // may contain core and plugin renderers and renderer factory
434 include_once($renderersfile);
436 $this->parent_configs[$parent] = $parent_config;
437 $rendererfile = $parent_config->dir.'/renderers.php';
438 if (is_readable($rendererfile)) {
439 // may contain core and plugin renderers and renderer factory
440 include_once($rendererfile);
443 $libfile = $this->dir.'/lib.php';
444 if (is_readable($libfile)) {
445 // theme may store various function here
446 include_once($libfile);
448 $rendererfile = $this->dir.'/renderers.php';
449 if (is_readable($rendererfile)) {
450 // may contain core and plugin renderers and renderer factory
451 include_once($rendererfile);
452 } else {
453 // check if renderers.php file is missnamed renderer.php
454 if (is_readable($this->dir.'/renderer.php')) {
455 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
456 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
460 // cascade all layouts properly
461 foreach ($baseconfig->layouts as $layout=>$value) {
462 if (!isset($this->layouts[$layout])) {
463 foreach ($this->parent_configs as $parent_config) {
464 if (isset($parent_config->layouts[$layout])) {
465 $this->layouts[$layout] = $parent_config->layouts[$layout];
466 continue 2;
469 $this->layouts[$layout] = $value;
473 //fix arrows if needed
474 $this->check_theme_arrows();
478 * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
479 * If not it applies sensible defaults.
481 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
482 * search forum block, etc. Important: these are 'silent' in a screen-reader
483 * (unlike &gt; &raquo;), and must be accompanied by text.
485 private function check_theme_arrows() {
486 if (!isset($this->rarrow) and !isset($this->larrow)) {
487 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
488 // Also OK in Win 9x/2K/IE 5.x
489 $this->rarrow = '&#x25BA;';
490 $this->larrow = '&#x25C4;';
491 if (empty($_SERVER['HTTP_USER_AGENT'])) {
492 $uagent = '';
493 } else {
494 $uagent = $_SERVER['HTTP_USER_AGENT'];
496 if (false !== strpos($uagent, 'Opera')
497 || false !== strpos($uagent, 'Mac')) {
498 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
499 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
500 $this->rarrow = '&#x25B6;';
501 $this->larrow = '&#x25C0;';
503 elseif ((false !== strpos($uagent, 'Konqueror'))
504 || (false !== strpos($uagent, 'Android'))) {
505 // The fonts on Android don't include the characters required for this to work as expected.
506 // So we use the same ones Konqueror uses.
507 $this->rarrow = '&rarr;';
508 $this->larrow = '&larr;';
510 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
511 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
512 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
513 // To be safe, non-Unicode browsers!
514 $this->rarrow = '&gt;';
515 $this->larrow = '&lt;';
518 // RTL support - in RTL languages, swap r and l arrows
519 if (right_to_left()) {
520 $t = $this->rarrow;
521 $this->rarrow = $this->larrow;
522 $this->larrow = $t;
528 * Returns output renderer prefixes, these are used when looking
529 * for the overridden renderers in themes.
531 * @return array
533 public function renderer_prefixes() {
534 global $CFG; // just in case the included files need it
536 $prefixes = array('theme_'.$this->name);
538 foreach ($this->parent_configs as $parent) {
539 $prefixes[] = 'theme_'.$parent->name;
542 return $prefixes;
546 * Returns the stylesheet URL of this editor content
548 * @param bool $encoded false means use & and true use &amp; in URLs
549 * @return string
551 public function editor_css_url($encoded=true) {
552 global $CFG;
554 $rev = theme_get_revision();
556 if ($rev > -1) {
557 if (!empty($CFG->slasharguments)) {
558 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
559 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
560 return $url;
561 } else {
562 $params = array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor');
563 return new moodle_url($CFG->httpswwwroot.'/theme/styles.php', $params);
565 } else {
566 $params = array('theme'=>$this->name, 'type'=>'editor');
567 return new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
572 * Returns the content of the CSS to be used in editor content
574 * @return string
576 public function editor_css_files() {
577 global $CFG;
579 $files = array();
581 // first editor plugins
582 $plugins = get_plugin_list('editor');
583 foreach ($plugins as $plugin=>$fulldir) {
584 $sheetfile = "$fulldir/editor_styles.css";
585 if (is_readable($sheetfile)) {
586 $files['plugin_'.$plugin] = $sheetfile;
589 // then parent themes
590 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
591 if (empty($parent_config->editor_sheets)) {
592 continue;
594 foreach ($parent_config->editor_sheets as $sheet) {
595 $sheetfile = "$parent_config->dir/style/$sheet.css";
596 if (is_readable($sheetfile)) {
597 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
601 // finally this theme
602 if (!empty($this->editor_sheets)) {
603 foreach ($this->editor_sheets as $sheet) {
604 $sheetfile = "$this->dir/style/$sheet.css";
605 if (is_readable($sheetfile)) {
606 $files['theme_'.$sheet] = $sheetfile;
611 return $files;
615 * Get the stylesheet URL of this theme
617 * @param moodle_page $page Not used... deprecated?
618 * @return array of moodle_url
620 public function css_urls(moodle_page $page) {
621 global $CFG;
623 $rev = theme_get_revision();
625 $urls = array();
627 $svg = $this->use_svg_icons();
629 if ($rev > -1) {
630 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
631 if (check_browser_version('MSIE', 5)) {
632 // We need to split the CSS files for IE
633 $urls[] = new moodle_url($url, array('theme' => $this->name,'rev' => $rev, 'type' => 'plugins', 'svg' => '0'));
634 $urls[] = new moodle_url($url, array('theme' => $this->name,'rev' => $rev, 'type' => 'parents', 'svg' => '0'));
635 $urls[] = new moodle_url($url, array('theme' => $this->name,'rev' => $rev, 'type' => 'theme', 'svg' => '0'));
636 } else {
637 if (!empty($CFG->slasharguments)) {
638 $slashargs = '/'.$this->name.'/'.$rev.'/all';
639 if (!$svg) {
640 // We add a simple /_s to the start of the path.
641 // The underscore is used to ensure that it isn't a valid theme name.
642 $slashargs = '/_s'.$slashargs;
644 $url->set_slashargument($slashargs, 'noparam', true);
645 } else {
646 $params = array('theme' => $this->name,'rev' => $rev, 'type' => 'all');
647 if (!$svg) {
648 // We add an SVG param so that we know not to serve SVG images.
649 // We do this because all modern browsers support SVG and this param will one day be removed.
650 $params['svg'] = '0';
652 $url->params($params);
654 $urls[] = $url;
656 } else {
657 // find out the current CSS and cache it now for 5 seconds
658 // the point is to construct the CSS only once and pass it through the
659 // dataroot to the script that actually serves the sheets
660 if (!defined('THEME_DESIGNER_CACHE_LIFETIME')) {
661 define('THEME_DESIGNER_CACHE_LIFETIME', 4); // this can be also set in config.php
663 $candidatedir = "$CFG->cachedir/theme/$this->name";
664 if ($svg) {
665 $candidatesheet = "$candidatedir/designer.ser";
666 } else {
667 $candidatesheet = "$candidatedir/designer_nosvg.ser";
669 $rebuild = true;
670 if (file_exists($candidatesheet) and filemtime($candidatesheet) > time() - THEME_DESIGNER_CACHE_LIFETIME) {
671 if ($css = file_get_contents($candidatesheet)) {
672 $css = unserialize($css);
673 if (is_array($css)) {
674 $rebuild = false;
678 if ($rebuild) {
679 // Prepare the CSS optimiser if it is to be used,
680 // please note that it may be very slow and is therefore strongly discouraged in theme designer mode.
681 $optimiser = null;
682 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
683 require_once($CFG->dirroot.'/lib/csslib.php');
684 $optimiser = new css_optimiser;
686 $css = $this->css_content($optimiser);
688 // We do not want any errors here because this may fail easily because of the concurrent access.
689 $prevabort = ignore_user_abort(true);
690 check_dir_exists($candidatedir);
691 $tempfile = tempnam($candidatedir, 'tmpdesigner');
692 file_put_contents($tempfile, serialize($css));
693 $reporting = error_reporting(0);
694 chmod($tempfile, $CFG->filepermissions);
695 unlink($candidatesheet); // Do not rely on rename() deleting original, they may decide to change it at any time as usually.
696 rename($tempfile, $candidatesheet);
697 error_reporting($reporting);
698 ignore_user_abort($prevabort);
701 $baseurl = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php');
702 if (!$svg) {
703 // We add an SVG param so that we know not to serve SVG images.
704 // We do this because all modern browsers support SVG and this param will one day be removed.
705 $baseurl->param('svg', '0');
707 if (check_browser_version('MSIE', 5)) {
708 // lalala, IE does not allow more than 31 linked CSS files from main document
709 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
710 foreach ($css['parents'] as $parent=>$sheets) {
711 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096)
712 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
714 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
716 } else {
717 foreach ($css['plugins'] as $plugin=>$unused) {
718 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
720 foreach ($css['parents'] as $parent=>$sheets) {
721 foreach ($sheets as $sheet=>$unused2) {
722 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
725 foreach ($css['theme'] as $sheet=>$unused) {
726 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); // sheet first in order to make long urls easier to read
731 return $urls;
735 * Returns an array of organised CSS files required for this output
737 * @return array
739 public function css_files() {
740 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
742 // get all plugin sheets
743 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
744 if ($excludes !== true) {
745 foreach (get_plugin_types() as $type=>$unused) {
746 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
747 continue;
749 $plugins = get_plugin_list($type);
750 foreach ($plugins as $plugin=>$fulldir) {
751 if (!empty($excludes[$type]) and is_array($excludes[$type])
752 and in_array($plugin, $excludes[$type])) {
753 continue;
756 $plugincontent = '';
757 $sheetfile = "$fulldir/styles.css";
758 if (is_readable($sheetfile)) {
759 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
761 $sheetthemefile = "$fulldir/styles_{$this->name}.css";
762 if (is_readable($sheetthemefile)) {
763 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$this->name] = $sheetthemefile;
769 // find out wanted parent sheets
770 $excludes = $this->resolve_excludes('parents_exclude_sheets');
771 if ($excludes !== true) {
772 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
773 $parent = $parent_config->name;
774 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
775 continue;
777 foreach ($parent_config->sheets as $sheet) {
778 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
779 and in_array($sheet, $excludes[$parent])) {
780 continue;
782 $sheetfile = "$parent_config->dir/style/$sheet.css";
783 if (is_readable($sheetfile)) {
784 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
790 // current theme sheets
791 if (is_array($this->sheets)) {
792 foreach ($this->sheets as $sheet) {
793 $sheetfile = "$this->dir/style/$sheet.css";
794 if (is_readable($sheetfile)) {
795 $cssfiles['theme'][$sheet] = $sheetfile;
800 return $cssfiles;
804 * Returns the content of the one huge CSS merged from all style sheets.
806 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
807 * @return string
809 public function css_content(css_optimiser $optimiser = null) {
810 $files = array_merge($this->css_files(), array('editor'=>$this->editor_css_files()));
811 $css = $this->css_files_get_contents($files, array(), $optimiser);
812 return $css;
816 * Given an array of file paths or a single file path loads the contents of
817 * the CSS file, processes it then returns it in the same structure it was given.
819 * Can be used recursively on the results of {@link css_files}
821 * @param array|string $file An array of file paths or a single file path
822 * @param array $keys An array of previous array keys [recursive addition]
823 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
824 * @return The converted array or the contents of the single file ($file type)
826 protected function css_files_get_contents($file, array $keys, css_optimiser $optimiser = null) {
827 global $CFG;
828 if (is_array($file)) {
829 // We use a separate array to keep everything in the exact same order.
830 $return = array();
831 foreach ($file as $key=>$f) {
832 $return[clean_param($key, PARAM_SAFEDIR)] = $this->css_files_get_contents($f, array_merge($keys, array($key)), $optimiser);
834 return $return;
835 } else {
836 $contents = file_get_contents($file);
837 $contents = $this->post_process($contents);
838 $comment = '/** Path: '.implode(' ', $keys).' **/'."\n";
839 $stats = '';
840 if (!is_null($optimiser)) {
841 $contents = $optimiser->process($contents);
842 if (!empty($CFG->cssoptimiserstats)) {
843 $stats = $optimiser->output_stats_css();
846 return $comment.$stats.$contents;
852 * Generate a URL to the file that serves theme JavaScript files.
854 * @param bool $inhead true means head url, false means footer
855 * @return moodle_url
857 public function javascript_url($inhead) {
858 global $CFG;
860 $rev = theme_get_revision();
861 $params = array('theme'=>$this->name,'rev'=>$rev);
862 $params['type'] = $inhead ? 'head' : 'footer';
864 if (!empty($CFG->slasharguments) and $rev > 0) {
865 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
866 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
867 return $url;
868 } else {
869 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
874 * Get the URL's for the JavaScript files used by this theme.
875 * They won't be served directly, instead they'll be mediated through
876 * theme/javascript.php.
878 * @param string $type Either javascripts_footer, or javascripts
879 * @return array
881 public function javascript_files($type) {
882 if ($type === 'footer') {
883 $type = 'javascripts_footer';
884 } else {
885 $type = 'javascripts';
888 $js = array();
889 // find out wanted parent javascripts
890 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
891 if ($excludes !== true) {
892 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
893 $parent = $parent_config->name;
894 if (empty($parent_config->$type)) {
895 continue;
897 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
898 continue;
900 foreach ($parent_config->$type as $javascript) {
901 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
902 and in_array($javascript, $excludes[$parent])) {
903 continue;
905 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
906 if (is_readable($javascriptfile)) {
907 $js[] = $javascriptfile;
913 // current theme javascripts
914 if (is_array($this->$type)) {
915 foreach ($this->$type as $javascript) {
916 $javascriptfile = "$this->dir/javascript/$javascript.js";
917 if (is_readable($javascriptfile)) {
918 $js[] = $javascriptfile;
922 return $js;
926 * Resolves an exclude setting to the themes setting is applicable or the
927 * setting of its closest parent.
929 * @param string $variable The name of the setting the exclude setting to resolve
930 * @param string $default
931 * @return mixed
933 protected function resolve_excludes($variable, $default = null) {
934 $setting = $default;
935 if (is_array($this->{$variable}) or $this->{$variable} === true) {
936 $setting = $this->{$variable};
937 } else {
938 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
939 if (!isset($parent_config->{$variable})) {
940 continue;
942 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
943 $setting = $parent_config->{$variable};
944 break;
948 return $setting;
952 * Returns the content of the one huge javascript file merged from all theme javascript files.
954 * @param bool $type
955 * @return string
957 public function javascript_content($type) {
958 $jsfiles = $this->javascript_files($type);
959 $js = '';
960 foreach ($jsfiles as $jsfile) {
961 $js .= file_get_contents($jsfile)."\n";
963 return $js;
967 * Post processes CSS.
969 * This method post processes all of the CSS before it is served for this theme.
970 * This is done so that things such as image URL's can be swapped in and to
971 * run any specific CSS post process method the theme has requested.
972 * This allows themes to use CSS settings.
974 * @param string $css The CSS to process.
975 * @return string The processed CSS.
977 public function post_process($css) {
978 // now resolve all image locations
979 if (preg_match_all('/\[\[pix:([a-z_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
980 $replaced = array();
981 foreach ($matches as $match) {
982 if (isset($replaced[$match[0]])) {
983 continue;
985 $replaced[$match[0]] = true;
986 $imagename = $match[2];
987 $component = rtrim($match[1], '|');
988 $imageurl = $this->pix_url($imagename, $component)->out(false);
989 // we do not need full url because the image.php is always in the same dir
990 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
991 $css = str_replace($match[0], $imageurl, $css);
995 // now resolve all theme settings or do any other postprocessing
996 $csspostprocess = $this->csspostprocess;
997 if (function_exists($csspostprocess)) {
998 $css = $csspostprocess($css, $this);
1001 return $css;
1005 * Return the URL for an image
1007 * @param string $imagename the name of the icon.
1008 * @param string $component specification of one plugin like in get_string()
1009 * @return moodle_url
1011 public function pix_url($imagename, $component) {
1012 global $CFG;
1014 $params = array('theme'=>$this->name);
1015 $svg = $this->use_svg_icons();
1017 if (empty($component) or $component === 'moodle' or $component === 'core') {
1018 $params['component'] = 'core';
1019 } else {
1020 $params['component'] = $component;
1023 $rev = theme_get_revision();
1024 if ($rev != -1) {
1025 $params['rev'] = $rev;
1028 $params['image'] = $imagename;
1030 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1031 if (!empty($CFG->slasharguments) and $rev > 0) {
1032 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1033 if (!$svg) {
1034 // We add a simple /_s to the start of the path.
1035 // The underscore is used to ensure that it isn't a valid theme name.
1036 $path = '/_s'.$path;
1038 $url->set_slashargument($path, 'noparam', true);
1039 } else {
1040 if (!$svg) {
1041 // We add an SVG param so that we know not to serve SVG images.
1042 // We do this because all modern browsers support SVG and this param will one day be removed.
1043 $params['svg'] = '0';
1045 $url->params($params);
1048 return $url;
1052 * Resolves the real image location.
1054 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1055 * and we need a way in which to turn it off.
1056 * By default SVG won't be used unless asked for. This is done for two reasons:
1057 * 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
1058 * browser supports SVG.
1059 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1060 * by the user due to security concerns.
1062 * @param string $image name of image, may contain relative path
1063 * @param string $component
1064 * @param bool $svg If set to true SVG images will also be looked for.
1065 * @return string full file path
1067 public function resolve_image_location($image, $component, $svg = false) {
1068 global $CFG;
1070 if (!is_bool($svg)) {
1071 // If $svg isn't a bool then we need to decide for ourselves.
1072 $svg = $this->use_svg_icons();
1075 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1076 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1077 return $imagefile;
1079 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1080 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1081 return $imagefile;
1084 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1085 return $imagefile;
1087 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1088 return $imagefile;
1090 return null;
1092 } else if ($component === 'theme') { //exception
1093 if ($image === 'favicon') {
1094 return "$this->dir/pix/favicon.ico";
1096 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1097 return $imagefile;
1099 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1100 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1101 return $imagefile;
1104 return null;
1106 } else {
1107 if (strpos($component, '_') === false) {
1108 $component = 'mod_'.$component;
1110 list($type, $plugin) = explode('_', $component, 2);
1112 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1113 return $imagefile;
1115 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1116 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1117 return $imagefile;
1120 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1121 return $imagefile;
1123 $dir = get_plugin_directory($type, $plugin);
1124 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1125 return $imagefile;
1127 return null;
1132 * Return true if we should look for SVG images as well.
1134 * @staticvar bool $svg
1135 * @return bool
1137 public function use_svg_icons() {
1138 global $CFG;
1139 if ($this->usesvg === null) {
1140 if (!isset($CFG->svgicons) || !is_bool($CFG->svgicons)) {
1141 // IE 5 - 8 don't support SVG at all.
1142 if (empty($_SERVER['HTTP_USER_AGENT'])) {
1143 // Can't be sure, just say no.
1144 $this->usesvg = false;
1145 } else if (check_browser_version('MSIE', 0) and !check_browser_version('MSIE', 9)) {
1146 // IE < 9 doesn't support SVG. Say no.
1147 $this->usesvg = false;
1148 } else if (check_browser_version('MSIE', 0) and !check_browser_version('MSIE', 10) and
1149 // IE running in Compatibility View?
1150 (preg_match("/MSIE 7.0/", $_SERVER['HTTP_USER_AGENT']) && preg_match("/Trident\/([0-9\.]+)/", $_SERVER['HTTP_USER_AGENT']))) {
1151 // IE 9 Compatibility View doesn't support SVG. Say no.
1152 $this->usesvg = false;
1153 } else if (preg_match('#Android +[0-2]\.#', $_SERVER['HTTP_USER_AGENT'])) {
1154 // Android < 3 doesn't support SVG. Say no.
1155 $this->usesvg = false;
1156 } else if (check_browser_version('Opera', 0)) {
1157 // Opera 12 still does not support SVG well enough. Say no.
1158 $this->usesvg = false;
1159 } else {
1160 // Presumed fine.
1161 $this->usesvg = true;
1163 } else {
1164 // Force them on/off depending upon the setting.
1165 $this->usesvg = $CFG->svgicons;
1168 return $this->usesvg;
1172 * Forces the usesvg setting to either true or false, avoiding any decision making.
1174 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
1175 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
1177 * @param bool $setting True to force the use of svg when available, null otherwise.
1179 public function force_svg_use($setting) {
1180 $this->usesvg = (bool)$setting;
1184 * Checks if file with any image extension exists.
1186 * The order to these images was adjusted prior to the release of 2.4
1187 * At that point the were the following image counts in Moodle core:
1189 * - png = 667 in pix dirs (1499 total)
1190 * - gif = 385 in pix dirs (606 total)
1191 * - jpg = 62 in pix dirs (74 total)
1192 * - jpeg = 0 in pix dirs (1 total)
1194 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1196 * @param string $filepath
1197 * @param bool $svg If set to true SVG images will also be looked for.
1198 * @return string image name with extension
1200 private static function image_exists($filepath, $svg = false) {
1201 if ($svg && file_exists("$filepath.svg")) {
1202 return "$filepath.svg";
1203 } else if (file_exists("$filepath.png")) {
1204 return "$filepath.png";
1205 } else if (file_exists("$filepath.gif")) {
1206 return "$filepath.gif";
1207 } else if (file_exists("$filepath.jpg")) {
1208 return "$filepath.jpg";
1209 } else if (file_exists("$filepath.jpeg")) {
1210 return "$filepath.jpeg";
1211 } else {
1212 return false;
1217 * Loads the theme config from config.php file.
1219 * @param string $themename
1220 * @param stdClass $settings from config_plugins table
1221 * @return stdClass The theme configuration
1223 private static function find_theme_config($themename, $settings) {
1224 // We have to use the variable name $THEME (upper case) because that
1225 // is what is used in theme config.php files.
1227 if (!$dir = theme_config::find_theme_location($themename)) {
1228 return null;
1231 $THEME = new stdClass();
1232 $THEME->name = $themename;
1233 $THEME->dir = $dir;
1234 $THEME->settings = $settings;
1236 global $CFG; // just in case somebody tries to use $CFG in theme config
1237 include("$THEME->dir/config.php");
1239 // verify the theme configuration is OK
1240 if (!is_array($THEME->parents)) {
1241 // parents option is mandatory now
1242 return null;
1245 return $THEME;
1249 * Finds the theme location and verifies the theme has all needed files
1250 * and is not obsoleted.
1252 * @param string $themename
1253 * @return string full dir path or null if not found
1255 private static function find_theme_location($themename) {
1256 global $CFG;
1258 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1259 $dir = "$CFG->dirroot/theme/$themename";
1261 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1262 $dir = "$CFG->themedir/$themename";
1264 } else {
1265 return null;
1268 if (file_exists("$dir/styles.php")) {
1269 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1270 return null;
1273 return $dir;
1277 * Get the renderer for a part of Moodle for this theme.
1279 * @param moodle_page $page the page we are rendering
1280 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1281 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1282 * @param string $target one of rendering target constants
1283 * @return renderer_base the requested renderer.
1285 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1286 if (is_null($this->rf)) {
1287 $classname = $this->rendererfactory;
1288 $this->rf = new $classname($this);
1291 return $this->rf->get_renderer($page, $component, $subtype, $target);
1295 * Get the information from {@link $layouts} for this type of page.
1297 * @param string $pagelayout the the page layout name.
1298 * @return array the appropriate part of {@link $layouts}.
1300 protected function layout_info_for_page($pagelayout) {
1301 if (array_key_exists($pagelayout, $this->layouts)) {
1302 return $this->layouts[$pagelayout];
1303 } else {
1304 debugging('Invalid page layout specified: ' . $pagelayout);
1305 return $this->layouts['standard'];
1310 * Given the settings of this theme, and the page pagelayout, return the
1311 * full path of the page layout file to use.
1313 * Used by {@link core_renderer::header()}.
1315 * @param string $pagelayout the the page layout name.
1316 * @return string Full path to the lyout file to use
1318 public function layout_file($pagelayout) {
1319 global $CFG;
1321 $layoutinfo = $this->layout_info_for_page($pagelayout);
1322 $layoutfile = $layoutinfo['file'];
1324 if (array_key_exists('theme', $layoutinfo)) {
1325 $themes = array($layoutinfo['theme']);
1326 } else {
1327 $themes = array_merge(array($this->name),$this->parents);
1330 foreach ($themes as $theme) {
1331 if ($dir = $this->find_theme_location($theme)) {
1332 $path = "$dir/layout/$layoutfile";
1334 // Check the template exists, return general base theme template if not.
1335 if (is_readable($path)) {
1336 return $path;
1341 debugging('Can not find layout file for: ' . $pagelayout);
1342 // fallback to standard normal layout
1343 return "$CFG->dirroot/theme/base/layout/general.php";
1347 * Returns auxiliary page layout options specified in layout configuration array.
1349 * @param string $pagelayout
1350 * @return array
1352 public function pagelayout_options($pagelayout) {
1353 $info = $this->layout_info_for_page($pagelayout);
1354 if (!empty($info['options'])) {
1355 return $info['options'];
1357 return array();
1361 * Inform a block_manager about the block regions this theme wants on this
1362 * page layout.
1364 * @param string $pagelayout the general type of the page.
1365 * @param block_manager $blockmanager the block_manger to set up.
1367 public function setup_blocks($pagelayout, $blockmanager) {
1368 $layoutinfo = $this->layout_info_for_page($pagelayout);
1369 if (!empty($layoutinfo['regions'])) {
1370 $blockmanager->add_regions($layoutinfo['regions']);
1371 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1376 * Gets the visible name for the requested block region.
1378 * @param string $region The region name to get
1379 * @param string $theme The theme the region belongs to (may come from the parent theme)
1380 * @return string
1382 protected function get_region_name($region, $theme) {
1383 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1384 // A name exists in this theme, so use it
1385 if (substr($regionstring, 0, 1) != '[') {
1386 return $regionstring;
1389 // Otherwise, try to find one elsewhere
1390 // Check parents, if any
1391 foreach ($this->parents as $parentthemename) {
1392 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1393 if (substr($regionstring, 0, 1) != '[') {
1394 return $regionstring;
1398 // Last resort, try the base theme for names
1399 return get_string('region-' . $region, 'theme_base');
1403 * Get the list of all block regions known to this theme in all templates.
1405 * @return array internal region name => human readable name.
1407 public function get_all_block_regions() {
1408 $regions = array();
1409 foreach ($this->layouts as $layoutinfo) {
1410 foreach ($layoutinfo['regions'] as $region) {
1411 $regions[$region] = $this->get_region_name($region, $this->name);
1414 return $regions;
1418 * Returns the human readable name of the theme
1420 * @return string
1422 public function get_theme_name() {
1423 return get_string('pluginname', 'theme_'.$this->name);
1428 * This class keeps track of which HTML tags are currently open.
1430 * This makes it much easier to always generate well formed XHTML output, even
1431 * if execution terminates abruptly. Any time you output some opening HTML
1432 * without the matching closing HTML, you should push the necessary close tags
1433 * onto the stack.
1435 * @copyright 2009 Tim Hunt
1436 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1437 * @since Moodle 2.0
1438 * @package core
1439 * @category output
1441 class xhtml_container_stack {
1444 * @var array Stores the list of open containers.
1446 protected $opencontainers = array();
1449 * @var array In developer debug mode, stores a stack trace of all opens and
1450 * closes, so we can output helpful error messages when there is a mismatch.
1452 protected $log = array();
1455 * @var boolean Store whether we are developer debug mode. We need this in
1456 * several places including in the destructor where we may not have access to $CFG.
1458 protected $isdebugging;
1461 * Constructor
1463 public function __construct() {
1464 $this->isdebugging = debugging('', DEBUG_DEVELOPER);
1468 * Push the close HTML for a recently opened container onto the stack.
1470 * @param string $type The type of container. This is checked when {@link pop()}
1471 * is called and must match, otherwise a developer debug warning is output.
1472 * @param string $closehtml The HTML required to close the container.
1474 public function push($type, $closehtml) {
1475 $container = new stdClass;
1476 $container->type = $type;
1477 $container->closehtml = $closehtml;
1478 if ($this->isdebugging) {
1479 $this->log('Open', $type);
1481 array_push($this->opencontainers, $container);
1485 * Pop the HTML for the next closing container from the stack. The $type
1486 * must match the type passed when the container was opened, otherwise a
1487 * warning will be output.
1489 * @param string $type The type of container.
1490 * @return string the HTML required to close the container.
1492 public function pop($type) {
1493 if (empty($this->opencontainers)) {
1494 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1495 $this->output_log(), DEBUG_DEVELOPER);
1496 return;
1499 $container = array_pop($this->opencontainers);
1500 if ($container->type != $type) {
1501 debugging('<p>The type of container to be closed (' . $container->type .
1502 ') does not match the type of the next open container (' . $type .
1503 '). This suggests there is a nesting problem.</p>' .
1504 $this->output_log(), DEBUG_DEVELOPER);
1506 if ($this->isdebugging) {
1507 $this->log('Close', $type);
1509 return $container->closehtml;
1513 * Close all but the last open container. This is useful in places like error
1514 * handling, where you want to close all the open containers (apart from <body>)
1515 * before outputting the error message.
1517 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1518 * developer debug warning if it isn't.
1519 * @return string the HTML required to close any open containers inside <body>.
1521 public function pop_all_but_last($shouldbenone = false) {
1522 if ($shouldbenone && count($this->opencontainers) != 1) {
1523 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1524 $this->output_log(), DEBUG_DEVELOPER);
1526 $output = '';
1527 while (count($this->opencontainers) > 1) {
1528 $container = array_pop($this->opencontainers);
1529 $output .= $container->closehtml;
1531 return $output;
1535 * You can call this function if you want to throw away an instance of this
1536 * class without properly emptying the stack (for example, in a unit test).
1537 * Calling this method stops the destruct method from outputting a developer
1538 * debug warning. After calling this method, the instance can no longer be used.
1540 public function discard() {
1541 $this->opencontainers = null;
1545 * Adds an entry to the log.
1547 * @param string $action The name of the action
1548 * @param string $type The type of action
1550 protected function log($action, $type) {
1551 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1552 format_backtrace(debug_backtrace()) . '</li>';
1556 * Outputs the log's contents as a HTML list.
1558 * @return string HTML list of the log
1560 protected function output_log() {
1561 return '<ul>' . implode("\n", $this->log) . '</ul>';