Merge branch 'm25_MDL-40200_Notices_When_Viewing_Profile_Invalid_UserId' of https...
[moodle.git] / lib / outputlib.php
blob9b37027fca536b3b5312f0e208a5bc84012d7327
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 * An associative array of block manipulations that should be made if the user is using an rtl language.
330 * The key is the original block region, and the value is the block region to change to.
331 * This is used when displaying blocks for regions only.
332 * @var array
334 public $blockrtlmanipulations = array();
337 * @var renderer_factory Instance of the renderer_factory implementation
338 * we are using. Implementation detail.
340 protected $rf = null;
343 * @var array List of parent config objects.
345 protected $parent_configs = array();
348 * @var bool If set to true then the theme is safe to run through the optimiser (if it is enabled)
349 * If set to false then we know either the theme has already been optimised and the CSS optimiser is not needed
350 * or the theme is not compatible with the CSS optimiser. In both cases even if enabled the CSS optimiser will not
351 * be used with this theme if set to false.
353 public $supportscssoptimisation = true;
356 * Used to determine whether we can serve SVG images or not.
357 * @var bool
359 private $usesvg = null;
362 * Load the config.php file for a particular theme, and return an instance
363 * of this class. (That is, this is a factory method.)
365 * @param string $themename the name of the theme.
366 * @return theme_config an instance of this class.
368 public static function load($themename) {
369 global $CFG;
371 // load theme settings from db
372 try {
373 $settings = get_config('theme_'.$themename);
374 } catch (dml_exception $e) {
375 // most probably moodle tables not created yet
376 $settings = new stdClass();
379 if ($config = theme_config::find_theme_config($themename, $settings)) {
380 return new theme_config($config);
382 } else if ($themename == theme_config::DEFAULT_THEME) {
383 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
385 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
386 return new theme_config($config);
388 } else {
389 // bad luck, the requested theme has some problems - admin see details in theme config
390 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
395 * Theme diagnostic code. It is very problematic to send debug output
396 * to the actual CSS file, instead this functions is supposed to
397 * diagnose given theme and highlights all potential problems.
398 * This information should be available from the theme selection page
399 * or some other debug page for theme designers.
401 * @param string $themename
402 * @return array description of problems
404 public static function diagnose($themename) {
405 //TODO: MDL-21108
406 return array();
410 * Private constructor, can be called only from the factory method.
411 * @param stdClass $config
413 private function __construct($config) {
414 global $CFG; //needed for included lib.php files
416 $this->settings = $config->settings;
417 $this->name = $config->name;
418 $this->dir = $config->dir;
420 if ($this->name != 'base') {
421 $baseconfig = theme_config::find_theme_config('base', $this->settings);
422 } else {
423 $baseconfig = $config;
426 $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer',
427 'parents_exclude_javascripts', 'layouts', 'enable_dock', 'enablecourseajax', 'supportscssoptimisation',
428 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector', 'doctype',
429 'yuicssmodules', 'blockrtlmanipulations');
431 foreach ($config as $key=>$value) {
432 if (in_array($key, $configurable)) {
433 $this->$key = $value;
437 // verify all parents and load configs and renderers
438 foreach ($this->parents as $parent) {
439 if ($parent == 'base') {
440 $parent_config = $baseconfig;
441 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
442 // this is not good - better exclude faulty parents
443 continue;
445 $libfile = $parent_config->dir.'/lib.php';
446 if (is_readable($libfile)) {
447 // theme may store various function here
448 include_once($libfile);
450 $renderersfile = $parent_config->dir.'/renderers.php';
451 if (is_readable($renderersfile)) {
452 // may contain core and plugin renderers and renderer factory
453 include_once($renderersfile);
455 $this->parent_configs[$parent] = $parent_config;
456 $rendererfile = $parent_config->dir.'/renderers.php';
457 if (is_readable($rendererfile)) {
458 // may contain core and plugin renderers and renderer factory
459 include_once($rendererfile);
462 $libfile = $this->dir.'/lib.php';
463 if (is_readable($libfile)) {
464 // theme may store various function here
465 include_once($libfile);
467 $rendererfile = $this->dir.'/renderers.php';
468 if (is_readable($rendererfile)) {
469 // may contain core and plugin renderers and renderer factory
470 include_once($rendererfile);
471 } else {
472 // check if renderers.php file is missnamed renderer.php
473 if (is_readable($this->dir.'/renderer.php')) {
474 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
475 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
479 // cascade all layouts properly
480 foreach ($baseconfig->layouts as $layout=>$value) {
481 if (!isset($this->layouts[$layout])) {
482 foreach ($this->parent_configs as $parent_config) {
483 if (isset($parent_config->layouts[$layout])) {
484 $this->layouts[$layout] = $parent_config->layouts[$layout];
485 continue 2;
488 $this->layouts[$layout] = $value;
492 //fix arrows if needed
493 $this->check_theme_arrows();
497 * Let the theme initialise the page object (usually $PAGE).
499 * This may be used for example to request jQuery in add-ons.
501 * @param moodle_page $page
503 public function init_page(moodle_page $page) {
504 $themeinitfunction = 'theme_'.$this->name.'_page_init';
505 if (function_exists($themeinitfunction)) {
506 $themeinitfunction($page);
511 * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
512 * If not it applies sensible defaults.
514 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
515 * search forum block, etc. Important: these are 'silent' in a screen-reader
516 * (unlike &gt; &raquo;), and must be accompanied by text.
518 private function check_theme_arrows() {
519 if (!isset($this->rarrow) and !isset($this->larrow)) {
520 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
521 // Also OK in Win 9x/2K/IE 5.x
522 $this->rarrow = '&#x25BA;';
523 $this->larrow = '&#x25C4;';
524 if (empty($_SERVER['HTTP_USER_AGENT'])) {
525 $uagent = '';
526 } else {
527 $uagent = $_SERVER['HTTP_USER_AGENT'];
529 if (false !== strpos($uagent, 'Opera')
530 || false !== strpos($uagent, 'Mac')) {
531 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
532 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
533 $this->rarrow = '&#x25B6;';
534 $this->larrow = '&#x25C0;';
536 elseif ((false !== strpos($uagent, 'Konqueror'))
537 || (false !== strpos($uagent, 'Android'))) {
538 // The fonts on Android don't include the characters required for this to work as expected.
539 // So we use the same ones Konqueror uses.
540 $this->rarrow = '&rarr;';
541 $this->larrow = '&larr;';
543 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
544 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
545 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
546 // To be safe, non-Unicode browsers!
547 $this->rarrow = '&gt;';
548 $this->larrow = '&lt;';
551 // RTL support - in RTL languages, swap r and l arrows
552 if (right_to_left()) {
553 $t = $this->rarrow;
554 $this->rarrow = $this->larrow;
555 $this->larrow = $t;
561 * Returns output renderer prefixes, these are used when looking
562 * for the overridden renderers in themes.
564 * @return array
566 public function renderer_prefixes() {
567 global $CFG; // just in case the included files need it
569 $prefixes = array('theme_'.$this->name);
571 foreach ($this->parent_configs as $parent) {
572 $prefixes[] = 'theme_'.$parent->name;
575 return $prefixes;
579 * Returns the stylesheet URL of this editor content
581 * @param bool $encoded false means use & and true use &amp; in URLs
582 * @return string
584 public function editor_css_url($encoded=true) {
585 global $CFG;
587 $rev = theme_get_revision();
589 if ($rev > -1) {
590 if (!empty($CFG->slasharguments)) {
591 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
592 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
593 return $url;
594 } else {
595 $params = array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor');
596 return new moodle_url($CFG->httpswwwroot.'/theme/styles.php', $params);
598 } else {
599 $params = array('theme'=>$this->name, 'type'=>'editor');
600 return new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
605 * Returns the content of the CSS to be used in editor content
607 * @return string
609 public function editor_css_files() {
610 global $CFG;
612 $files = array();
614 // first editor plugins
615 $plugins = get_plugin_list('editor');
616 foreach ($plugins as $plugin=>$fulldir) {
617 $sheetfile = "$fulldir/editor_styles.css";
618 if (is_readable($sheetfile)) {
619 $files['plugin_'.$plugin] = $sheetfile;
622 // then parent themes
623 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
624 if (empty($parent_config->editor_sheets)) {
625 continue;
627 foreach ($parent_config->editor_sheets as $sheet) {
628 $sheetfile = "$parent_config->dir/style/$sheet.css";
629 if (is_readable($sheetfile)) {
630 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
634 // finally this theme
635 if (!empty($this->editor_sheets)) {
636 foreach ($this->editor_sheets as $sheet) {
637 $sheetfile = "$this->dir/style/$sheet.css";
638 if (is_readable($sheetfile)) {
639 $files['theme_'.$sheet] = $sheetfile;
644 return $files;
648 * Get the stylesheet URL of this theme
650 * @param moodle_page $page Not used... deprecated?
651 * @return array of moodle_url
653 public function css_urls(moodle_page $page) {
654 global $CFG;
656 $rev = theme_get_revision();
658 $urls = array();
660 $svg = $this->use_svg_icons();
662 if ($rev > -1) {
663 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
664 if (check_browser_version('MSIE', 5)) {
665 // We need to split the CSS files for IE
666 $urls[] = new moodle_url($url, array('theme' => $this->name,'rev' => $rev, 'type' => 'plugins', 'svg' => '0'));
667 $urls[] = new moodle_url($url, array('theme' => $this->name,'rev' => $rev, 'type' => 'parents', 'svg' => '0'));
668 $urls[] = new moodle_url($url, array('theme' => $this->name,'rev' => $rev, 'type' => 'theme', 'svg' => '0'));
669 } else {
670 if (!empty($CFG->slasharguments)) {
671 $slashargs = '/'.$this->name.'/'.$rev.'/all';
672 if (!$svg) {
673 // We add a simple /_s to the start of the path.
674 // The underscore is used to ensure that it isn't a valid theme name.
675 $slashargs = '/_s'.$slashargs;
677 $url->set_slashargument($slashargs, 'noparam', true);
678 } else {
679 $params = array('theme' => $this->name,'rev' => $rev, 'type' => 'all');
680 if (!$svg) {
681 // We add an SVG param so that we know not to serve SVG images.
682 // We do this because all modern browsers support SVG and this param will one day be removed.
683 $params['svg'] = '0';
685 $url->params($params);
687 $urls[] = $url;
689 } else {
690 // find out the current CSS and cache it now for 5 seconds
691 // the point is to construct the CSS only once and pass it through the
692 // dataroot to the script that actually serves the sheets
693 if (!defined('THEME_DESIGNER_CACHE_LIFETIME')) {
694 define('THEME_DESIGNER_CACHE_LIFETIME', 4); // this can be also set in config.php
696 $candidatedir = "$CFG->cachedir/theme/$this->name";
697 if ($svg) {
698 $candidatesheet = "$candidatedir/designer.ser";
699 } else {
700 $candidatesheet = "$candidatedir/designer_nosvg.ser";
702 $rebuild = true;
703 if (file_exists($candidatesheet) and filemtime($candidatesheet) > time() - THEME_DESIGNER_CACHE_LIFETIME) {
704 if ($css = file_get_contents($candidatesheet)) {
705 $css = unserialize($css);
706 if (is_array($css)) {
707 $rebuild = false;
711 if ($rebuild) {
712 // Prepare the CSS optimiser if it is to be used,
713 // please note that it may be very slow and is therefore strongly discouraged in theme designer mode.
714 $optimiser = null;
715 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
716 require_once($CFG->dirroot.'/lib/csslib.php');
717 $optimiser = new css_optimiser;
719 $css = $this->css_content($optimiser);
721 // We do not want any errors here because this may fail easily because of the concurrent access.
722 $prevabort = ignore_user_abort(true);
723 check_dir_exists($candidatedir);
724 $tempfile = tempnam($candidatedir, 'tmpdesigner');
725 file_put_contents($tempfile, serialize($css));
726 $reporting = error_reporting(0);
727 chmod($tempfile, $CFG->filepermissions);
728 unlink($candidatesheet); // Do not rely on rename() deleting original, they may decide to change it at any time as usually.
729 rename($tempfile, $candidatesheet);
730 error_reporting($reporting);
731 ignore_user_abort($prevabort);
734 $baseurl = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php');
735 if (!$svg) {
736 // We add an SVG param so that we know not to serve SVG images.
737 // We do this because all modern browsers support SVG and this param will one day be removed.
738 $baseurl->param('svg', '0');
740 if (check_browser_version('MSIE', 5)) {
741 // lalala, IE does not allow more than 31 linked CSS files from main document
742 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
743 foreach ($css['parents'] as $parent=>$sheets) {
744 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096)
745 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
747 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
749 } else {
750 foreach ($css['plugins'] as $plugin=>$unused) {
751 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
753 foreach ($css['parents'] as $parent=>$sheets) {
754 foreach ($sheets as $sheet=>$unused2) {
755 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
758 foreach ($css['theme'] as $sheet=>$unused) {
759 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); // sheet first in order to make long urls easier to read
764 return $urls;
768 * Returns an array of organised CSS files required for this output
770 * @return array
772 public function css_files() {
773 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
775 // get all plugin sheets
776 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
777 if ($excludes !== true) {
778 foreach (get_plugin_types() as $type=>$unused) {
779 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
780 continue;
782 $plugins = get_plugin_list($type);
783 foreach ($plugins as $plugin=>$fulldir) {
784 if (!empty($excludes[$type]) and is_array($excludes[$type])
785 and in_array($plugin, $excludes[$type])) {
786 continue;
789 $plugincontent = '';
790 $sheetfile = "$fulldir/styles.css";
791 if (is_readable($sheetfile)) {
792 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
794 $sheetthemefile = "$fulldir/styles_{$this->name}.css";
795 if (is_readable($sheetthemefile)) {
796 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$this->name] = $sheetthemefile;
802 // find out wanted parent sheets
803 $excludes = $this->resolve_excludes('parents_exclude_sheets');
804 if ($excludes !== true) {
805 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
806 $parent = $parent_config->name;
807 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
808 continue;
810 foreach ($parent_config->sheets as $sheet) {
811 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
812 and in_array($sheet, $excludes[$parent])) {
813 continue;
815 $sheetfile = "$parent_config->dir/style/$sheet.css";
816 if (is_readable($sheetfile)) {
817 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
823 // current theme sheets
824 if (is_array($this->sheets)) {
825 foreach ($this->sheets as $sheet) {
826 $sheetfile = "$this->dir/style/$sheet.css";
827 if (is_readable($sheetfile)) {
828 $cssfiles['theme'][$sheet] = $sheetfile;
833 return $cssfiles;
837 * Returns the content of the one huge CSS merged from all style sheets.
839 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
840 * @return string
842 public function css_content(css_optimiser $optimiser = null) {
843 $files = array_merge($this->css_files(), array('editor'=>$this->editor_css_files()));
844 $css = $this->css_files_get_contents($files, array(), $optimiser);
845 return $css;
849 * Given an array of file paths or a single file path loads the contents of
850 * the CSS file, processes it then returns it in the same structure it was given.
852 * Can be used recursively on the results of {@link css_files}
854 * @param array|string $file An array of file paths or a single file path
855 * @param array $keys An array of previous array keys [recursive addition]
856 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
857 * @return The converted array or the contents of the single file ($file type)
859 protected function css_files_get_contents($file, array $keys, css_optimiser $optimiser = null) {
860 global $CFG;
861 if (is_array($file)) {
862 // We use a separate array to keep everything in the exact same order.
863 $return = array();
864 foreach ($file as $key=>$f) {
865 $return[clean_param($key, PARAM_SAFEDIR)] = $this->css_files_get_contents($f, array_merge($keys, array($key)), $optimiser);
867 return $return;
868 } else {
869 $contents = file_get_contents($file);
870 $contents = $this->post_process($contents);
871 $comment = '/** Path: '.implode(' ', $keys).' **/'."\n";
872 $stats = '';
873 if (!is_null($optimiser)) {
874 $contents = $optimiser->process($contents);
875 if (!empty($CFG->cssoptimiserstats)) {
876 $stats = $optimiser->output_stats_css();
879 return $comment.$stats.$contents;
885 * Generate a URL to the file that serves theme JavaScript files.
887 * If we determine that the theme has no relevant files, then we return
888 * early with a null value.
890 * @param bool $inhead true means head url, false means footer
891 * @return moodle_url|null
893 public function javascript_url($inhead) {
894 global $CFG;
896 $rev = theme_get_revision();
897 $params = array('theme'=>$this->name,'rev'=>$rev);
898 $params['type'] = $inhead ? 'head' : 'footer';
900 // Return early if there are no files to serve
901 if (count($this->javascript_files($params['type'])) === 0) {
902 return null;
905 if (!empty($CFG->slasharguments) and $rev > 0) {
906 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
907 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
908 return $url;
909 } else {
910 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
915 * Get the URL's for the JavaScript files used by this theme.
916 * They won't be served directly, instead they'll be mediated through
917 * theme/javascript.php.
919 * @param string $type Either javascripts_footer, or javascripts
920 * @return array
922 public function javascript_files($type) {
923 if ($type === 'footer') {
924 $type = 'javascripts_footer';
925 } else {
926 $type = 'javascripts';
929 $js = array();
930 // find out wanted parent javascripts
931 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
932 if ($excludes !== true) {
933 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
934 $parent = $parent_config->name;
935 if (empty($parent_config->$type)) {
936 continue;
938 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
939 continue;
941 foreach ($parent_config->$type as $javascript) {
942 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
943 and in_array($javascript, $excludes[$parent])) {
944 continue;
946 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
947 if (is_readable($javascriptfile)) {
948 $js[] = $javascriptfile;
954 // current theme javascripts
955 if (is_array($this->$type)) {
956 foreach ($this->$type as $javascript) {
957 $javascriptfile = "$this->dir/javascript/$javascript.js";
958 if (is_readable($javascriptfile)) {
959 $js[] = $javascriptfile;
963 return $js;
967 * Resolves an exclude setting to the themes setting is applicable or the
968 * setting of its closest parent.
970 * @param string $variable The name of the setting the exclude setting to resolve
971 * @param string $default
972 * @return mixed
974 protected function resolve_excludes($variable, $default = null) {
975 $setting = $default;
976 if (is_array($this->{$variable}) or $this->{$variable} === true) {
977 $setting = $this->{$variable};
978 } else {
979 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
980 if (!isset($parent_config->{$variable})) {
981 continue;
983 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
984 $setting = $parent_config->{$variable};
985 break;
989 return $setting;
993 * Returns the content of the one huge javascript file merged from all theme javascript files.
995 * @param bool $type
996 * @return string
998 public function javascript_content($type) {
999 $jsfiles = $this->javascript_files($type);
1000 $js = '';
1001 foreach ($jsfiles as $jsfile) {
1002 $js .= file_get_contents($jsfile)."\n";
1004 return $js;
1008 * Post processes CSS.
1010 * This method post processes all of the CSS before it is served for this theme.
1011 * This is done so that things such as image URL's can be swapped in and to
1012 * run any specific CSS post process method the theme has requested.
1013 * This allows themes to use CSS settings.
1015 * @param string $css The CSS to process.
1016 * @return string The processed CSS.
1018 public function post_process($css) {
1019 // now resolve all image locations
1020 if (preg_match_all('/\[\[pix:([a-z_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1021 $replaced = array();
1022 foreach ($matches as $match) {
1023 if (isset($replaced[$match[0]])) {
1024 continue;
1026 $replaced[$match[0]] = true;
1027 $imagename = $match[2];
1028 $component = rtrim($match[1], '|');
1029 $imageurl = $this->pix_url($imagename, $component)->out(false);
1030 // we do not need full url because the image.php is always in the same dir
1031 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1032 $css = str_replace($match[0], $imageurl, $css);
1036 // now resolve all theme settings or do any other postprocessing
1037 $csspostprocess = $this->csspostprocess;
1038 if (function_exists($csspostprocess)) {
1039 $css = $csspostprocess($css, $this);
1042 return $css;
1046 * Return the URL for an image
1048 * @param string $imagename the name of the icon.
1049 * @param string $component specification of one plugin like in get_string()
1050 * @return moodle_url
1052 public function pix_url($imagename, $component) {
1053 global $CFG;
1055 $params = array('theme'=>$this->name);
1056 $svg = $this->use_svg_icons();
1058 if (empty($component) or $component === 'moodle' or $component === 'core') {
1059 $params['component'] = 'core';
1060 } else {
1061 $params['component'] = $component;
1064 $rev = theme_get_revision();
1065 if ($rev != -1) {
1066 $params['rev'] = $rev;
1069 $params['image'] = $imagename;
1071 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1072 if (!empty($CFG->slasharguments) and $rev > 0) {
1073 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1074 if (!$svg) {
1075 // We add a simple /_s to the start of the path.
1076 // The underscore is used to ensure that it isn't a valid theme name.
1077 $path = '/_s'.$path;
1079 $url->set_slashargument($path, 'noparam', true);
1080 } else {
1081 if (!$svg) {
1082 // We add an SVG param so that we know not to serve SVG images.
1083 // We do this because all modern browsers support SVG and this param will one day be removed.
1084 $params['svg'] = '0';
1086 $url->params($params);
1089 return $url;
1093 * Returns URL to the stored file via pluginfile.php.
1095 * Note the theme must also implement pluginfile.php handler,
1096 * theme revision is used instead of the itemid.
1098 * @param string $setting
1099 * @param string $filearea
1100 * @return string protocol relative URL or null if not present
1102 public function setting_file_url($setting, $filearea) {
1103 global $CFG;
1105 if (empty($this->settings->$setting)) {
1106 return null;
1109 $component = 'theme_'.$this->name;
1110 $itemid = theme_get_revision();
1111 $filepath = $this->settings->$setting;
1112 $syscontext = context_system::instance();
1114 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1116 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1117 // Note: unfortunately moodle_url does not support //urls yet.
1119 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1121 return $url;
1125 * Serve the theme setting file.
1127 * @param string $filearea
1128 * @param array $args
1129 * @param bool $forcedownload
1130 * @param array $options
1131 * @return bool may terminate if file not found or donotdie not specified
1133 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1134 global $CFG;
1135 require_once("$CFG->libdir/filelib.php");
1137 $syscontext = context_system::instance();
1138 $component = 'theme_'.$this->name;
1140 $revision = array_shift($args);
1141 if ($revision < 0) {
1142 $lifetime = 0;
1143 } else {
1144 $lifetime = 60*60*24*60;
1147 $fs = get_file_storage();
1148 $relativepath = implode('/', $args);
1150 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1151 $fullpath = rtrim($fullpath, '/');
1152 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1153 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1154 return true;
1155 } else {
1156 send_file_not_found();
1161 * Resolves the real image location.
1163 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1164 * and we need a way in which to turn it off.
1165 * By default SVG won't be used unless asked for. This is done for two reasons:
1166 * 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
1167 * browser supports SVG.
1168 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1169 * by the user due to security concerns.
1171 * @param string $image name of image, may contain relative path
1172 * @param string $component
1173 * @param bool $svg If set to true SVG images will also be looked for.
1174 * @return string full file path
1176 public function resolve_image_location($image, $component, $svg = false) {
1177 global $CFG;
1179 if (!is_bool($svg)) {
1180 // If $svg isn't a bool then we need to decide for ourselves.
1181 $svg = $this->use_svg_icons();
1184 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1185 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1186 return $imagefile;
1188 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1189 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1190 return $imagefile;
1193 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1194 return $imagefile;
1196 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1197 return $imagefile;
1199 return null;
1201 } else if ($component === 'theme') { //exception
1202 if ($image === 'favicon') {
1203 return "$this->dir/pix/favicon.ico";
1205 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1206 return $imagefile;
1208 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1209 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1210 return $imagefile;
1213 return null;
1215 } else {
1216 if (strpos($component, '_') === false) {
1217 $component = 'mod_'.$component;
1219 list($type, $plugin) = explode('_', $component, 2);
1221 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1222 return $imagefile;
1224 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1225 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1226 return $imagefile;
1229 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1230 return $imagefile;
1232 $dir = get_plugin_directory($type, $plugin);
1233 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1234 return $imagefile;
1236 return null;
1241 * Return true if we should look for SVG images as well.
1243 * @staticvar bool $svg
1244 * @return bool
1246 public function use_svg_icons() {
1247 global $CFG;
1248 if ($this->usesvg === null) {
1249 if (!isset($CFG->svgicons) || !is_bool($CFG->svgicons)) {
1250 // IE 5 - 8 don't support SVG at all.
1251 if (empty($_SERVER['HTTP_USER_AGENT'])) {
1252 // Can't be sure, just say no.
1253 $this->usesvg = false;
1254 } else if (check_browser_version('MSIE', 0) and !check_browser_version('MSIE', 9)) {
1255 // IE < 9 doesn't support SVG. Say no.
1256 $this->usesvg = false;
1257 } else if (preg_match('#Android +[0-2]\.#', $_SERVER['HTTP_USER_AGENT'])) {
1258 // Android < 3 doesn't support SVG. Say no.
1259 $this->usesvg = false;
1260 } else if (check_browser_version('Opera', 0)) {
1261 // Opera 12 still does not support SVG well enough. Say no.
1262 $this->usesvg = false;
1263 } else {
1264 // Presumed fine.
1265 $this->usesvg = true;
1267 } else {
1268 // Force them on/off depending upon the setting.
1269 $this->usesvg = $CFG->svgicons;
1272 return $this->usesvg;
1276 * Forces the usesvg setting to either true or false, avoiding any decision making.
1278 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
1279 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
1281 * @param bool $setting True to force the use of svg when available, null otherwise.
1283 public function force_svg_use($setting) {
1284 $this->usesvg = (bool)$setting;
1288 * Checks if file with any image extension exists.
1290 * The order to these images was adjusted prior to the release of 2.4
1291 * At that point the were the following image counts in Moodle core:
1293 * - png = 667 in pix dirs (1499 total)
1294 * - gif = 385 in pix dirs (606 total)
1295 * - jpg = 62 in pix dirs (74 total)
1296 * - jpeg = 0 in pix dirs (1 total)
1298 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1300 * @param string $filepath
1301 * @param bool $svg If set to true SVG images will also be looked for.
1302 * @return string image name with extension
1304 private static function image_exists($filepath, $svg = false) {
1305 if ($svg && file_exists("$filepath.svg")) {
1306 return "$filepath.svg";
1307 } else if (file_exists("$filepath.png")) {
1308 return "$filepath.png";
1309 } else if (file_exists("$filepath.gif")) {
1310 return "$filepath.gif";
1311 } else if (file_exists("$filepath.jpg")) {
1312 return "$filepath.jpg";
1313 } else if (file_exists("$filepath.jpeg")) {
1314 return "$filepath.jpeg";
1315 } else {
1316 return false;
1321 * Loads the theme config from config.php file.
1323 * @param string $themename
1324 * @param stdClass $settings from config_plugins table
1325 * @return stdClass The theme configuration
1327 private static function find_theme_config($themename, $settings) {
1328 // We have to use the variable name $THEME (upper case) because that
1329 // is what is used in theme config.php files.
1331 if (!$dir = theme_config::find_theme_location($themename)) {
1332 return null;
1335 $THEME = new stdClass();
1336 $THEME->name = $themename;
1337 $THEME->dir = $dir;
1338 $THEME->settings = $settings;
1340 global $CFG; // just in case somebody tries to use $CFG in theme config
1341 include("$THEME->dir/config.php");
1343 // verify the theme configuration is OK
1344 if (!is_array($THEME->parents)) {
1345 // parents option is mandatory now
1346 return null;
1349 return $THEME;
1353 * Finds the theme location and verifies the theme has all needed files
1354 * and is not obsoleted.
1356 * @param string $themename
1357 * @return string full dir path or null if not found
1359 private static function find_theme_location($themename) {
1360 global $CFG;
1362 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1363 $dir = "$CFG->dirroot/theme/$themename";
1365 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1366 $dir = "$CFG->themedir/$themename";
1368 } else {
1369 return null;
1372 if (file_exists("$dir/styles.php")) {
1373 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1374 return null;
1377 return $dir;
1381 * Get the renderer for a part of Moodle for this theme.
1383 * @param moodle_page $page the page we are rendering
1384 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1385 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1386 * @param string $target one of rendering target constants
1387 * @return renderer_base the requested renderer.
1389 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1390 if (is_null($this->rf)) {
1391 $classname = $this->rendererfactory;
1392 $this->rf = new $classname($this);
1395 return $this->rf->get_renderer($page, $component, $subtype, $target);
1399 * Get the information from {@link $layouts} for this type of page.
1401 * @param string $pagelayout the the page layout name.
1402 * @return array the appropriate part of {@link $layouts}.
1404 protected function layout_info_for_page($pagelayout) {
1405 if (array_key_exists($pagelayout, $this->layouts)) {
1406 return $this->layouts[$pagelayout];
1407 } else {
1408 debugging('Invalid page layout specified: ' . $pagelayout);
1409 return $this->layouts['standard'];
1414 * Given the settings of this theme, and the page pagelayout, return the
1415 * full path of the page layout file to use.
1417 * Used by {@link core_renderer::header()}.
1419 * @param string $pagelayout the the page layout name.
1420 * @return string Full path to the lyout file to use
1422 public function layout_file($pagelayout) {
1423 global $CFG;
1425 $layoutinfo = $this->layout_info_for_page($pagelayout);
1426 $layoutfile = $layoutinfo['file'];
1428 if (array_key_exists('theme', $layoutinfo)) {
1429 $themes = array($layoutinfo['theme']);
1430 } else {
1431 $themes = array_merge(array($this->name),$this->parents);
1434 foreach ($themes as $theme) {
1435 if ($dir = $this->find_theme_location($theme)) {
1436 $path = "$dir/layout/$layoutfile";
1438 // Check the template exists, return general base theme template if not.
1439 if (is_readable($path)) {
1440 return $path;
1445 debugging('Can not find layout file for: ' . $pagelayout);
1446 // fallback to standard normal layout
1447 return "$CFG->dirroot/theme/base/layout/general.php";
1451 * Returns auxiliary page layout options specified in layout configuration array.
1453 * @param string $pagelayout
1454 * @return array
1456 public function pagelayout_options($pagelayout) {
1457 $info = $this->layout_info_for_page($pagelayout);
1458 if (!empty($info['options'])) {
1459 return $info['options'];
1461 return array();
1465 * Inform a block_manager about the block regions this theme wants on this
1466 * page layout.
1468 * @param string $pagelayout the general type of the page.
1469 * @param block_manager $blockmanager the block_manger to set up.
1471 public function setup_blocks($pagelayout, $blockmanager) {
1472 $layoutinfo = $this->layout_info_for_page($pagelayout);
1473 if (!empty($layoutinfo['regions'])) {
1474 $blockmanager->add_regions($layoutinfo['regions']);
1475 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1480 * Gets the visible name for the requested block region.
1482 * @param string $region The region name to get
1483 * @param string $theme The theme the region belongs to (may come from the parent theme)
1484 * @return string
1486 protected function get_region_name($region, $theme) {
1487 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1488 // A name exists in this theme, so use it
1489 if (substr($regionstring, 0, 1) != '[') {
1490 return $regionstring;
1493 // Otherwise, try to find one elsewhere
1494 // Check parents, if any
1495 foreach ($this->parents as $parentthemename) {
1496 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1497 if (substr($regionstring, 0, 1) != '[') {
1498 return $regionstring;
1502 // Last resort, try the base theme for names
1503 return get_string('region-' . $region, 'theme_base');
1507 * Get the list of all block regions known to this theme in all templates.
1509 * @return array internal region name => human readable name.
1511 public function get_all_block_regions() {
1512 $regions = array();
1513 foreach ($this->layouts as $layoutinfo) {
1514 foreach ($layoutinfo['regions'] as $region) {
1515 $regions[$region] = $this->get_region_name($region, $this->name);
1518 return $regions;
1522 * Returns the human readable name of the theme
1524 * @return string
1526 public function get_theme_name() {
1527 return get_string('pluginname', 'theme_'.$this->name);
1532 * This class keeps track of which HTML tags are currently open.
1534 * This makes it much easier to always generate well formed XHTML output, even
1535 * if execution terminates abruptly. Any time you output some opening HTML
1536 * without the matching closing HTML, you should push the necessary close tags
1537 * onto the stack.
1539 * @copyright 2009 Tim Hunt
1540 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1541 * @since Moodle 2.0
1542 * @package core
1543 * @category output
1545 class xhtml_container_stack {
1548 * @var array Stores the list of open containers.
1550 protected $opencontainers = array();
1553 * @var array In developer debug mode, stores a stack trace of all opens and
1554 * closes, so we can output helpful error messages when there is a mismatch.
1556 protected $log = array();
1559 * @var boolean Store whether we are developer debug mode. We need this in
1560 * several places including in the destructor where we may not have access to $CFG.
1562 protected $isdebugging;
1565 * Constructor
1567 public function __construct() {
1568 $this->isdebugging = debugging('', DEBUG_DEVELOPER);
1572 * Push the close HTML for a recently opened container onto the stack.
1574 * @param string $type The type of container. This is checked when {@link pop()}
1575 * is called and must match, otherwise a developer debug warning is output.
1576 * @param string $closehtml The HTML required to close the container.
1578 public function push($type, $closehtml) {
1579 $container = new stdClass;
1580 $container->type = $type;
1581 $container->closehtml = $closehtml;
1582 if ($this->isdebugging) {
1583 $this->log('Open', $type);
1585 array_push($this->opencontainers, $container);
1589 * Pop the HTML for the next closing container from the stack. The $type
1590 * must match the type passed when the container was opened, otherwise a
1591 * warning will be output.
1593 * @param string $type The type of container.
1594 * @return string the HTML required to close the container.
1596 public function pop($type) {
1597 if (empty($this->opencontainers)) {
1598 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1599 $this->output_log(), DEBUG_DEVELOPER);
1600 return;
1603 $container = array_pop($this->opencontainers);
1604 if ($container->type != $type) {
1605 debugging('<p>The type of container to be closed (' . $container->type .
1606 ') does not match the type of the next open container (' . $type .
1607 '). This suggests there is a nesting problem.</p>' .
1608 $this->output_log(), DEBUG_DEVELOPER);
1610 if ($this->isdebugging) {
1611 $this->log('Close', $type);
1613 return $container->closehtml;
1617 * Close all but the last open container. This is useful in places like error
1618 * handling, where you want to close all the open containers (apart from <body>)
1619 * before outputting the error message.
1621 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1622 * developer debug warning if it isn't.
1623 * @return string the HTML required to close any open containers inside <body>.
1625 public function pop_all_but_last($shouldbenone = false) {
1626 if ($shouldbenone && count($this->opencontainers) != 1) {
1627 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1628 $this->output_log(), DEBUG_DEVELOPER);
1630 $output = '';
1631 while (count($this->opencontainers) > 1) {
1632 $container = array_pop($this->opencontainers);
1633 $output .= $container->closehtml;
1635 return $output;
1639 * You can call this function if you want to throw away an instance of this
1640 * class without properly emptying the stack (for example, in a unit test).
1641 * Calling this method stops the destruct method from outputting a developer
1642 * debug warning. After calling this method, the instance can no longer be used.
1644 public function discard() {
1645 $this->opencontainers = null;
1649 * Adds an entry to the log.
1651 * @param string $action The name of the action
1652 * @param string $type The type of action
1654 protected function log($action, $type) {
1655 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1656 format_backtrace(debug_backtrace()) . '</li>';
1660 * Outputs the log's contents as a HTML list.
1662 * @return string HTML list of the log
1664 protected function output_log() {
1665 return '<ul>' . implode("\n", $this->log) . '</ul>';