2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Functions for generating the HTML that Moodle should output.
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
23 * @copyright 2009 Tim Hunt
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
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');
38 * Returns current theme revision number.
42 function theme_get_revision() {
45 if (empty($CFG->themedesignermode
)) {
46 if (empty($CFG->themerev
)) {
47 // This only happens during install. It doesn't matter what themerev we use as long as it's positive.
50 return $CFG->themerev
;
59 * Returns current theme sub revision number. This is the revision for
60 * this theme exclusively, not the global theme revision.
62 * @param string $themename The non-frankenstyle name of the theme
65 function theme_get_sub_revision_for_theme($themename) {
68 if (empty($CFG->themedesignermode
)) {
69 $pluginname = "theme_{$themename}";
70 $revision = during_initial_install() ?
null : get_config($pluginname, 'themerev');
72 if (empty($revision)) {
73 // This only happens during install. It doesn't matter what themerev we use as long as it's positive.
84 * Calculates and returns the next theme revision number.
88 function theme_get_next_revision() {
92 if (isset($CFG->themerev
) and $next <= $CFG->themerev
and $CFG->themerev
- $next < 60*60) {
93 // This resolves problems when reset is requested repeatedly within 1s,
94 // the < 1h condition prevents accidental switching to future dates
95 // because we might not recover from it.
96 $next = $CFG->themerev+
1;
103 * Calculates and returns the next theme revision number.
105 * @param string $themename The non-frankenstyle name of the theme
108 function theme_get_next_sub_revision_for_theme($themename) {
112 $current = theme_get_sub_revision_for_theme($themename);
113 if ($next <= $current and $current - $next < 60 * 60) {
114 // This resolves problems when reset is requested repeatedly within 1s,
115 // the < 1h condition prevents accidental switching to future dates
116 // because we might not recover from it.
117 $next = $current +
1;
124 * Sets the current theme revision number.
126 * @param int $revision The new theme revision number
128 function theme_set_revision($revision) {
129 set_config('themerev', $revision);
133 * Sets the current theme revision number for a specific theme.
134 * This does not affect the global themerev value.
136 * @param string $themename The non-frankenstyle name of the theme
137 * @param int $revision The new theme revision number
139 function theme_set_sub_revision_for_theme($themename, $revision) {
140 set_config('themerev', $revision, "theme_{$themename}");
144 * Get the path to a theme config.php file.
146 * @param string $themename The non-frankenstyle name of the theme to check
148 function theme_get_config_file_path($themename) {
151 if (file_exists("{$CFG->dirroot}/theme/{$themename}/config.php")) {
152 return "{$CFG->dirroot}/theme/{$themename}/config.php";
153 } else if (!empty($CFG->themedir
) and file_exists("{$CFG->themedir}/{$themename}/config.php")) {
154 return "{$CFG->themedir}/{$themename}/config.php";
161 * Get the path to the local cached CSS file.
163 * @param string $themename The non-frankenstyle theme name.
164 * @param int $globalrevision The global theme revision.
165 * @param int $themerevision The theme specific revision.
166 * @param string $direction Either 'ltr' or 'rtl' (case sensitive).
168 function theme_get_css_filename($themename, $globalrevision, $themerevision, $direction) {
171 $path = "{$CFG->localcachedir}/theme/{$globalrevision}/{$themename}/css";
172 $filename = $direction == 'rtl' ?
"all-rtl_{$themerevision}" : "all_{$themerevision}";
173 return "{$path}/{$filename}.css";
177 * Generates and saves the CSS files for the given theme configs.
179 * @param theme_config[] $themeconfigs An array of theme_config instances.
180 * @param array $directions Must be a subset of ['rtl', 'ltr'].
181 * @param bool $cache Should the generated files be stored in local cache.
183 function theme_build_css_for_themes($themeconfigs = [], $directions = ['rtl', 'ltr'], $cache = true) {
186 if (empty($themeconfigs)) {
190 require_once("{$CFG->libdir}/csslib.php");
193 $themerev = theme_get_revision();
194 // Make sure the local cache directory exists.
195 make_localcache_directory('theme');
197 foreach ($themeconfigs as $themeconfig) {
199 $oldrevision = theme_get_sub_revision_for_theme($themeconfig->name
);
200 $newrevision = theme_get_next_sub_revision_for_theme($themeconfig->name
);
202 // First generate all the new css.
203 foreach ($directions as $direction) {
204 $themeconfig->set_rtl_mode(($direction === 'rtl'));
206 $themecss[$direction] = $themeconfig->get_css_content();
208 $filename = theme_get_css_filename($themeconfig->name
, $themerev, $newrevision, $direction);
209 css_store_css($themeconfig, $filename, $themecss[$direction]);
212 $themescss[] = $themecss;
215 // Only update the theme revision after we've successfully created the
217 theme_set_sub_revision_for_theme($themeconfig->name
, $newrevision);
219 // Now purge old files. We must purge all old files in the local cache
220 // because we've incremented the theme sub revision. This will leave any
221 // files with the old revision inaccessbile so we might as well removed
223 foreach (['ltr', 'rtl'] as $direction) {
224 $oldcss = theme_get_css_filename($themeconfig->name
, $themerev, $oldrevision, $direction);
225 if (file_exists($oldcss)) {
236 * Invalidate all server and client side caches.
238 * This method deletes the physical directory that is used to cache the theme
239 * files used for serving.
240 * Because it deletes the main theme cache directory all themes are reset by
243 function theme_reset_all_caches() {
246 $next = theme_get_next_revision();
247 theme_set_revision($next);
249 if (!empty($CFG->themedesignermode
)) {
250 $cache = cache
::make_from_params(cache_store
::MODE_APPLICATION
, 'core', 'themedesigner');
254 // Purge compiled post processed css.
255 cache
::make('core', 'postprocessedcss')->purge();
258 $PAGE->reload_theme();
263 * Enable or disable theme designer mode.
267 function theme_set_designer_mod($state) {
268 set_config('themedesignermode', (int)!empty($state));
269 // Reset caches after switching mode so that any designer mode caches get purged too.
270 theme_reset_all_caches();
274 * Checks if the given device has a theme defined in config.php.
278 function theme_is_device_locked($device) {
280 $themeconfigname = core_useragent
::get_device_type_cfg_var_name($device);
281 return isset($CFG->config_php_settings
[$themeconfigname]);
285 * Returns the theme named defined in config.php for the given device.
287 * @return string or null
289 function theme_get_locked_theme_for_device($device) {
292 if (!theme_is_device_locked($device)) {
296 $themeconfigname = core_useragent
::get_device_type_cfg_var_name($device);
297 return $CFG->config_php_settings
[$themeconfigname];
301 * This class represents the configuration variables of a Moodle theme.
303 * All the variables with access: public below (with a few exceptions that are marked)
304 * are the properties you can set in your themes config.php file.
306 * There are also some methods and protected variables that are part of the inner
307 * workings of Moodle's themes system. If you are just editing a themes config.php
308 * file, you can just ignore those, and the following information for developers.
310 * Normally, to create an instance of this class, you should use the
311 * {@link theme_config::load()} factory method to load a themes config.php file.
312 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
313 * will create one for you, accessible as $PAGE->theme.
315 * @copyright 2009 Tim Hunt
316 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
324 * @var string Default theme, used when requested theme not found.
326 const DEFAULT_THEME
= 'boost';
328 /** The key under which the SCSS file is stored amongst the CSS files. */
329 const SCSS_KEY
= '__SCSS__';
332 * @var array You can base your theme on other themes by linking to the other theme as
333 * parents. This lets you use the CSS and layouts from the other themes
334 * (see {@link theme_config::$layouts}).
335 * That makes it easy to create a new theme that is similar to another one
336 * but with a few changes. In this themes CSS you only need to override
337 * those rules you want to change.
342 * @var array The names of all the stylesheets from this theme that you would
343 * like included, in order. Give the names of the files without .css.
345 public $sheets = array();
348 * @var array The names of all the stylesheets from parents that should be excluded.
349 * true value may be used to specify all parents or all themes from one parent.
350 * If no value specified value from parent theme used.
352 public $parents_exclude_sheets = null;
355 * @var array List of plugin sheets to be excluded.
356 * If no value specified value from parent theme used.
358 public $plugins_exclude_sheets = null;
361 * @var array List of style sheets that are included in the text editor bodies.
362 * Sheets from parent themes are used automatically and can not be excluded.
364 public $editor_sheets = array();
367 * @var bool Whether a fallback version of the stylesheet will be used
368 * whilst the final version is generated.
370 public $usefallback = false;
373 * @var array The names of all the javascript files this theme that you would
374 * like included from head, in order. Give the names of the files without .js.
376 public $javascripts = array();
379 * @var array The names of all the javascript files this theme that you would
380 * like included from footer, in order. Give the names of the files without .js.
382 public $javascripts_footer = array();
385 * @var array The names of all the javascript files from parents that should
386 * be excluded. true value may be used to specify all parents or all themes
388 * If no value specified value from parent theme used.
390 public $parents_exclude_javascripts = null;
393 * @var array Which file to use for each page layout.
395 * This is an array of arrays. The keys of the outer array are the different layouts.
396 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
397 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
398 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
399 * That file also has a good example of how to set this setting.
401 * For each layout, the value in the outer array is an array that describes
402 * how you want that type of page to look. For example
404 * $THEME->layouts = array(
405 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
406 * 'standard' => array(
407 * 'theme' = 'mytheme',
408 * 'file' => 'normal.php',
409 * 'regions' => array('side-pre', 'side-post'),
410 * 'defaultregion' => 'side-post'
412 * // The site home page.
414 * 'theme' = 'mytheme',
415 * 'file' => 'home.php',
416 * 'regions' => array('side-pre', 'side-post'),
417 * 'defaultregion' => 'side-post'
423 * 'theme' name of the theme where is the layout located
424 * 'file' is the layout file to use for this type of page.
425 * layout files are stored in layout subfolder
426 * 'regions' This lists the regions on the page where blocks may appear. For
427 * each region you list here, your layout file must include a call to
429 * echo $OUTPUT->blocks_for_region($regionname);
431 * or equivalent so that the blocks are actually visible.
433 * 'defaultregion' If the list of regions is non-empty, then you must pick
434 * one of the one of them as 'default'. This has two meanings. First, this is
435 * where new blocks are added. Second, if there are any blocks associated with
436 * the page, but in non-existent regions, they appear here. (Imaging, for example,
437 * that someone added blocks using a different theme that used different region
438 * names, and then switched to this theme.)
440 public $layouts = array();
443 * @var string Name of the renderer factory class to use. Must implement the
444 * {@link renderer_factory} interface.
446 * This is an advanced feature. Moodle output is generated by 'renderers',
447 * you can customise the HTML that is output by writing custom renderers,
448 * and then you need to specify 'renderer factory' so that Moodle can find
451 * There are some renderer factories supplied with Moodle. Please follow these
452 * links to see what they do.
454 * <li>{@link standard_renderer_factory} - the default.</li>
455 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
456 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
459 public $rendererfactory = 'standard_renderer_factory';
462 * @var string Function to do custom CSS post-processing.
464 * This is an advanced feature. If you want to do custom post-processing on the
465 * CSS before it is output (for example, to replace certain variable names
466 * with particular values) you can give the name of a function here.
468 public $csspostprocess = null;
471 * @var string Function to do custom CSS post-processing on a parsed CSS tree.
473 * This is an advanced feature. If you want to do custom post-processing on the
474 * CSS before it is output, you can provide the name of the function here. The
475 * function will receive a CSS tree document as first parameter, and the theme_config
476 * object as second parameter. A return value is not required, the tree can
477 * be edited in place.
479 public $csstreepostprocessor = null;
482 * @var string Accessibility: Right arrow-like character is
483 * used in the breadcrumb trail, course navigation menu
484 * (previous/next activity), calendar, and search forum block.
485 * If the theme does not set characters, appropriate defaults
486 * are set automatically. Please DO NOT
487 * use < > » - these are confusing for blind users.
489 public $rarrow = null;
492 * @var string Accessibility: Left arrow-like character is
493 * used in the breadcrumb trail, course navigation menu
494 * (previous/next activity), calendar, and search forum block.
495 * If the theme does not set characters, appropriate defaults
496 * are set automatically. Please DO NOT
497 * use < > » - these are confusing for blind users.
499 public $larrow = null;
502 * @var string Accessibility: Up arrow-like character is used in
503 * the book heirarchical navigation.
504 * If the theme does not set characters, appropriate defaults
505 * are set automatically. Please DO NOT
506 * use ^ - this is confusing for blind users.
508 public $uarrow = null;
511 * @var string Accessibility: Down arrow-like character.
512 * If the theme does not set characters, appropriate defaults
513 * are set automatically.
515 public $darrow = null;
518 * @var bool Some themes may want to disable ajax course editing.
520 public $enablecourseajax = true;
523 * @var string Determines served document types
524 * - 'html5' the only officially supported doctype in Moodle
525 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
526 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
528 public $doctype = 'html5';
531 * @var string requiredblocks If set to a string, will list the block types that cannot be deleted. Defaults to
532 * navigation and settings.
534 public $requiredblocks = false;
536 //==Following properties are not configurable from theme config.php==
539 * @var string The name of this theme. Set automatically when this theme is
540 * loaded. This can not be set in theme config.php
545 * @var string The folder where this themes files are stored. This is set
546 * automatically. This can not be set in theme config.php
551 * @var stdClass Theme settings stored in config_plugins table.
552 * This can not be set in theme config.php
554 public $settings = null;
557 * @var bool If set to true and the theme enables the dock then blocks will be able
558 * to be moved to the special dock
560 public $enable_dock = false;
563 * @var bool If set to true then this theme will not be shown in the theme selector unless
564 * theme designer mode is turned on.
566 public $hidefromselector = false;
569 * @var array list of YUI CSS modules to be included on each page. This may be used
570 * to remove cssreset and use cssnormalise module instead.
572 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
575 * An associative array of block manipulations that should be made if the user is using an rtl language.
576 * The key is the original block region, and the value is the block region to change to.
577 * This is used when displaying blocks for regions only.
580 public $blockrtlmanipulations = array();
583 * @var renderer_factory Instance of the renderer_factory implementation
584 * we are using. Implementation detail.
586 protected $rf = null;
589 * @var array List of parent config objects.
591 protected $parent_configs = array();
594 * Used to determine whether we can serve SVG images or not.
597 private $usesvg = null;
600 * Whether in RTL mode or not.
603 protected $rtlmode = false;
606 * The LESS file to compile. When set, the theme will attempt to compile the file itself.
609 public $lessfile = false;
612 * The SCSS file to compile (without .scss), located in the scss/ folder of the theme.
613 * Or a Closure, which receives the theme_config as argument and must
614 * return the SCSS content. This setting takes precedence over self::$lessfile.
615 * @var string|Closure
617 public $scss = false;
620 * Local cache of the SCSS property.
623 protected $scsscache = null;
626 * The name of the function to call to get the LESS code to inject.
629 public $extralesscallback = null;
632 * The name of the function to call to get the SCSS code to inject.
635 public $extrascsscallback = null;
638 * The name of the function to call to get extra LESS variables.
641 public $lessvariablescallback = null;
644 * The name of the function to call to get SCSS to prepend.
647 public $prescsscallback = null;
650 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
651 * Defaults to {@link core_renderer::blocks_for_region()}
654 public $blockrendermethod = null;
657 * Remember the results of icon remapping for the current page.
660 public $remapiconcache = [];
663 * Load the config.php file for a particular theme, and return an instance
664 * of this class. (That is, this is a factory method.)
666 * @param string $themename the name of the theme.
667 * @return theme_config an instance of this class.
669 public static function load($themename) {
672 // load theme settings from db
674 $settings = get_config('theme_'.$themename);
675 } catch (dml_exception
$e) {
676 // most probably moodle tables not created yet
677 $settings = new stdClass();
680 if ($config = theme_config
::find_theme_config($themename, $settings)) {
681 return new theme_config($config);
683 } else if ($themename == theme_config
::DEFAULT_THEME
) {
684 throw new coding_exception('Default theme '.theme_config
::DEFAULT_THEME
.' not available or broken!');
686 } else if ($config = theme_config
::find_theme_config($CFG->theme
, $settings)) {
687 debugging('This page should be using theme ' . $themename .
688 ' which cannot be initialised. Falling back to the site theme ' . $CFG->theme
, DEBUG_NORMAL
);
689 return new theme_config($config);
692 // bad luck, the requested theme has some problems - admin see details in theme config
693 debugging('This page should be using theme ' . $themename .
694 ' which cannot be initialised. Nor can the site theme ' . $CFG->theme
.
695 '. Falling back to ' . theme_config
::DEFAULT_THEME
, DEBUG_NORMAL
);
696 return new theme_config(theme_config
::find_theme_config(theme_config
::DEFAULT_THEME
, $settings));
701 * Theme diagnostic code. It is very problematic to send debug output
702 * to the actual CSS file, instead this functions is supposed to
703 * diagnose given theme and highlights all potential problems.
704 * This information should be available from the theme selection page
705 * or some other debug page for theme designers.
707 * @param string $themename
708 * @return array description of problems
710 public static function diagnose($themename) {
716 * Private constructor, can be called only from the factory method.
717 * @param stdClass $config
719 private function __construct($config) {
720 global $CFG; //needed for included lib.php files
722 $this->settings
= $config->settings
;
723 $this->name
= $config->name
;
724 $this->dir
= $config->dir
;
726 if ($this->name
!= 'bootstrapbase') {
727 $baseconfig = theme_config
::find_theme_config('bootstrapbase', $this->settings
);
729 $baseconfig = $config;
732 $configurable = array(
733 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'usefallback',
734 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
735 'layouts', 'enable_dock', 'enablecourseajax', 'requiredblocks',
736 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'uarrow', 'darrow',
737 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations',
738 'lessfile', 'extralesscallback', 'lessvariablescallback', 'blockrendermethod',
739 'scss', 'extrascsscallback', 'prescsscallback', 'csstreepostprocessor', 'addblockposition', 'iconsystem');
741 foreach ($config as $key=>$value) {
742 if (in_array($key, $configurable)) {
743 $this->$key = $value;
747 // verify all parents and load configs and renderers
748 foreach ($this->parents
as $parent) {
749 if (!$parent_config = theme_config
::find_theme_config($parent, $this->settings
)) {
750 // this is not good - better exclude faulty parents
753 $libfile = $parent_config->dir
.'/lib.php';
754 if (is_readable($libfile)) {
755 // theme may store various function here
756 include_once($libfile);
758 $renderersfile = $parent_config->dir
.'/renderers.php';
759 if (is_readable($renderersfile)) {
760 // may contain core and plugin renderers and renderer factory
761 include_once($renderersfile);
763 $this->parent_configs
[$parent] = $parent_config;
765 $libfile = $this->dir
.'/lib.php';
766 if (is_readable($libfile)) {
767 // theme may store various function here
768 include_once($libfile);
770 $rendererfile = $this->dir
.'/renderers.php';
771 if (is_readable($rendererfile)) {
772 // may contain core and plugin renderers and renderer factory
773 include_once($rendererfile);
775 // check if renderers.php file is missnamed renderer.php
776 if (is_readable($this->dir
.'/renderer.php')) {
777 debugging('Developer hint: '.$this->dir
.'/renderer.php should be renamed to ' . $this->dir
."/renderers.php.
778 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER
);
782 // cascade all layouts properly
783 foreach ($baseconfig->layouts
as $layout=>$value) {
784 if (!isset($this->layouts
[$layout])) {
785 foreach ($this->parent_configs
as $parent_config) {
786 if (isset($parent_config->layouts
[$layout])) {
787 $this->layouts
[$layout] = $parent_config->layouts
[$layout];
791 $this->layouts
[$layout] = $value;
795 //fix arrows if needed
796 $this->check_theme_arrows();
800 * Let the theme initialise the page object (usually $PAGE).
802 * This may be used for example to request jQuery in add-ons.
804 * @param moodle_page $page
806 public function init_page(moodle_page
$page) {
807 $themeinitfunction = 'theme_'.$this->name
.'_page_init';
808 if (function_exists($themeinitfunction)) {
809 $themeinitfunction($page);
814 * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow, $THEME->darrow have been set (theme/-/config.php).
815 * If not it applies sensible defaults.
817 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
818 * search forum block, etc. Important: these are 'silent' in a screen-reader
819 * (unlike > »), and must be accompanied by text.
821 private function check_theme_arrows() {
822 if (!isset($this->rarrow
) and !isset($this->larrow
)) {
823 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
824 // Also OK in Win 9x/2K/IE 5.x
825 $this->rarrow
= '►';
826 $this->larrow
= '◄';
827 $this->uarrow
= '▲';
828 $this->darrow
= '▼';
829 if (empty($_SERVER['HTTP_USER_AGENT'])) {
832 $uagent = $_SERVER['HTTP_USER_AGENT'];
834 if (false !== strpos($uagent, 'Opera')
835 ||
false !== strpos($uagent, 'Mac')) {
836 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
837 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
838 $this->rarrow
= '▶︎';
839 $this->larrow
= '◀︎';
841 elseif ((false !== strpos($uagent, 'Konqueror'))
842 ||
(false !== strpos($uagent, 'Android'))) {
843 // The fonts on Android don't include the characters required for this to work as expected.
844 // So we use the same ones Konqueror uses.
845 $this->rarrow
= '→';
846 $this->larrow
= '←';
847 $this->uarrow
= '↑';
848 $this->darrow
= '↓';
850 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
851 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
852 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
853 // To be safe, non-Unicode browsers!
854 $this->rarrow
= '>';
855 $this->larrow
= '<';
860 // RTL support - in RTL languages, swap r and l arrows
861 if (right_to_left()) {
863 $this->rarrow
= $this->larrow
;
870 * Returns output renderer prefixes, these are used when looking
871 * for the overridden renderers in themes.
875 public function renderer_prefixes() {
876 global $CFG; // just in case the included files need it
878 $prefixes = array('theme_'.$this->name
);
880 foreach ($this->parent_configs
as $parent) {
881 $prefixes[] = 'theme_'.$parent->name
;
888 * Returns the stylesheet URL of this editor content
890 * @param bool $encoded false means use & and true use & in URLs
893 public function editor_css_url($encoded=true) {
895 $rev = theme_get_revision();
897 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
898 if (!empty($CFG->slasharguments
)) {
899 $url->set_slashargument('/'.$this->name
.'/'.$rev.'/editor', 'noparam', true);
901 $url->params(array('theme'=>$this->name
,'rev'=>$rev, 'type'=>'editor'));
904 $params = array('theme'=>$this->name
, 'type'=>'editor');
905 $url = new moodle_url($CFG->httpswwwroot
.'/theme/styles_debug.php', $params);
911 * Returns the content of the CSS to be used in editor content
915 public function editor_css_files() {
918 // First editor plugins.
919 $plugins = core_component
::get_plugin_list('editor');
920 foreach ($plugins as $plugin=>$fulldir) {
921 $sheetfile = "$fulldir/editor_styles.css";
922 if (is_readable($sheetfile)) {
923 $files['plugin_'.$plugin] = $sheetfile;
926 // Then parent themes - base first, the immediate parent last.
927 foreach (array_reverse($this->parent_configs
) as $parent_config) {
928 if (empty($parent_config->editor_sheets
)) {
931 foreach ($parent_config->editor_sheets
as $sheet) {
932 $sheetfile = "$parent_config->dir/style/$sheet.css";
933 if (is_readable($sheetfile)) {
934 $files['parent_'.$parent_config->name
.'_'.$sheet] = $sheetfile;
938 // Finally this theme.
939 if (!empty($this->editor_sheets
)) {
940 foreach ($this->editor_sheets
as $sheet) {
941 $sheetfile = "$this->dir/style/$sheet.css";
942 if (is_readable($sheetfile)) {
943 $files['theme_'.$sheet] = $sheetfile;
952 * Get the stylesheet URL of this theme.
954 * @param moodle_page $page Not used... deprecated?
955 * @return moodle_url[]
957 public function css_urls(moodle_page
$page) {
960 $rev = theme_get_revision();
964 $svg = $this->use_svg_icons();
965 $separate = (core_useragent
::is_ie() && !core_useragent
::check_ie_version('10'));
968 $filename = right_to_left() ?
'all-rtl' : 'all';
969 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
970 $themesubrevision = theme_get_sub_revision_for_theme($this->name
);
972 // Provide the sub revision to allow us to invalidate cached theme CSS
973 // on a per theme basis, rather than globally.
974 if ($themesubrevision && $themesubrevision > 0) {
975 $rev .= "_{$themesubrevision}";
978 if (!empty($CFG->slasharguments
)) {
981 // We add a simple /_s to the start of the path.
982 // The underscore is used to ensure that it isn't a valid theme name.
983 $slashargs .= '/_s'.$slashargs;
985 $slashargs .= '/'.$this->name
.'/'.$rev.'/'.$filename;
987 $slashargs .= '/chunk0';
989 $url->set_slashargument($slashargs, 'noparam', true);
991 $params = array('theme' => $this->name
, 'rev' => $rev, 'type' => $filename);
993 // We add an SVG param so that we know not to serve SVG images.
994 // We do this because all modern browsers support SVG and this param will one day be removed.
995 $params['svg'] = '0';
998 $params['chunk'] = '0';
1000 $url->params($params);
1005 $baseurl = new moodle_url($CFG->httpswwwroot
.'/theme/styles_debug.php');
1007 $css = $this->get_css_files(true);
1009 // We add an SVG param so that we know not to serve SVG images.
1010 // We do this because all modern browsers support SVG and this param will one day be removed.
1011 $baseurl->param('svg', '0');
1013 if (right_to_left()) {
1014 $baseurl->param('rtl', 1);
1017 // We might need to chunk long files.
1018 $baseurl->param('chunk', '0');
1020 if (core_useragent
::is_ie()) {
1021 // Lalala, IE does not allow more than 31 linked CSS files from main document.
1022 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
, 'type'=>'ie', 'subtype'=>'plugins'));
1023 foreach ($css['parents'] as $parent=>$sheets) {
1024 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
1025 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
1027 if ($this->get_scss_property()) {
1028 // No need to define the type as IE here.
1029 $urls[] = new moodle_url($baseurl, array('theme' => $this->name
, 'type' => 'scss'));
1030 } else if (!empty($this->lessfile
)) {
1031 // No need to define the type as IE here.
1032 $urls[] = new moodle_url($baseurl, array('theme' => $this->name
, 'type' => 'less'));
1034 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
, 'type'=>'ie', 'subtype'=>'theme'));
1037 foreach ($css['plugins'] as $plugin=>$unused) {
1038 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
,'type'=>'plugin', 'subtype'=>$plugin));
1040 foreach ($css['parents'] as $parent=>$sheets) {
1041 foreach ($sheets as $sheet=>$unused2) {
1042 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
1045 foreach ($css['theme'] as $sheet => $filename) {
1046 if ($sheet === self
::SCSS_KEY
) {
1047 // This is the theme SCSS file.
1048 $urls[] = new moodle_url($baseurl, array('theme' => $this->name
, 'type' => 'scss'));
1049 } else if ($sheet === $this->lessfile
) {
1050 // This is the theme LESS file.
1051 $urls[] = new moodle_url($baseurl, array('theme' => $this->name
, 'type' => 'less'));
1053 // Sheet first in order to make long urls easier to read.
1054 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name
, 'type'=>'theme'));
1064 * Get the whole css stylesheet for production mode.
1066 * NOTE: this method is not expected to be used from any addons.
1068 * @return string CSS markup compressed
1070 public function get_css_content() {
1073 foreach ($this->get_css_files(false) as $type => $value) {
1074 foreach ($value as $identifier => $val) {
1075 if (is_array($val)) {
1076 foreach ($val as $v) {
1077 $csscontent .= file_get_contents($v) . "\n";
1080 if ($type === 'theme' && $identifier === self
::SCSS_KEY
) {
1081 // We need the content from SCSS because this is the SCSS file from the theme.
1082 $csscontent .= $this->get_css_content_from_scss(false);
1083 } else if ($type === 'theme' && $identifier === $this->lessfile
) {
1084 // We need the content from LESS because this is the LESS file from the theme.
1085 $csscontent .= $this->get_css_content_from_less(false);
1087 $csscontent .= file_get_contents($val) . "\n";
1092 $csscontent = $this->post_process($csscontent);
1093 $csscontent = core_minify
::css($csscontent);
1098 * Set post processed CSS content cache.
1100 * @param string $csscontent The post processed CSS content.
1101 * @return bool True if the content was successfully cached.
1103 public function set_css_content_cache($csscontent) {
1105 $cache = cache
::make('core', 'postprocessedcss');
1106 $key = $this->get_css_cache_key();
1108 return $cache->set($key, $csscontent);
1112 * Return whether the post processed CSS content has been cached.
1114 * @return bool Whether the post-processed CSS is available in the cache.
1116 public function has_css_cached_content() {
1118 $key = $this->get_css_cache_key();
1119 $cache = cache
::make('core', 'postprocessedcss');
1121 return $cache->has($key);
1125 * Return cached post processed CSS content.
1127 * @return bool|string The cached css content or false if not found.
1129 public function get_css_cached_content() {
1131 $key = $this->get_css_cache_key();
1132 $cache = cache
::make('core', 'postprocessedcss');
1134 return $cache->get($key);
1138 * Generate the css content cache key.
1140 * @return string The post processed css cache key.
1142 public function get_css_cache_key() {
1143 $nosvg = (!$this->use_svg_icons()) ?
'nosvg_' : '';
1144 $rtlmode = ($this->rtlmode
== true) ?
'rtl' : 'ltr';
1146 return $nosvg . $this->name
. '_' . $rtlmode;
1150 * Get the theme designer css markup,
1151 * the parameters are coming from css_urls().
1153 * NOTE: this method is not expected to be used from any addons.
1155 * @param string $type
1156 * @param string $subtype
1157 * @param string $sheet
1158 * @return string CSS markup
1160 public function get_css_content_debug($type, $subtype, $sheet) {
1162 if ($type === 'scss') {
1163 // The SCSS file of the theme is requested.
1164 $csscontent = $this->get_css_content_from_scss(true);
1165 if ($csscontent !== false) {
1166 return $this->post_process($csscontent);
1169 } else if ($type === 'less') {
1170 // The LESS file of the theme is requested.
1171 $csscontent = $this->get_css_content_from_less(true);
1172 if ($csscontent !== false) {
1173 return $this->post_process($csscontent);
1178 $cssfiles = array();
1179 $css = $this->get_css_files(true);
1181 if ($type === 'ie') {
1182 // IE is a sloppy browser with weird limits, sorry.
1183 if ($subtype === 'plugins') {
1184 $cssfiles = $css['plugins'];
1186 } else if ($subtype === 'parents') {
1187 if (empty($sheet)) {
1188 // Do not bother with the empty parent here.
1190 // Build up the CSS for that parent so we can serve it as one file.
1191 foreach ($css[$subtype][$sheet] as $parent => $css) {
1195 } else if ($subtype === 'theme') {
1196 $cssfiles = $css['theme'];
1197 foreach ($cssfiles as $key => $value) {
1198 if (in_array($key, [$this->lessfile
, self
::SCSS_KEY
])) {
1199 // Remove the LESS/SCSS file from the theme CSS files.
1200 // The LESS/SCSS files use the type 'less' or 'scss', not 'ie'.
1201 unset($cssfiles[$key]);
1206 } else if ($type === 'plugin') {
1207 if (isset($css['plugins'][$subtype])) {
1208 $cssfiles[] = $css['plugins'][$subtype];
1211 } else if ($type === 'parent') {
1212 if (isset($css['parents'][$subtype][$sheet])) {
1213 $cssfiles[] = $css['parents'][$subtype][$sheet];
1216 } else if ($type === 'theme') {
1217 if (isset($css['theme'][$sheet])) {
1218 $cssfiles[] = $css['theme'][$sheet];
1223 foreach ($cssfiles as $file) {
1224 $contents = file_get_contents($file);
1225 $contents = $this->post_process($contents);
1226 $comment = "/** Path: $type $subtype $sheet.' **/\n";
1228 $csscontent .= $comment.$stats.$contents."\n\n";
1235 * Get the whole css stylesheet for editor iframe.
1237 * NOTE: this method is not expected to be used from any addons.
1239 * @return string CSS markup
1241 public function get_css_content_editor() {
1242 // Do not bother to optimise anything here, just very basic stuff.
1243 $cssfiles = $this->editor_css_files();
1245 foreach ($cssfiles as $file) {
1246 $css .= file_get_contents($file)."\n";
1248 return $this->post_process($css);
1252 * Returns an array of organised CSS files required for this output.
1254 * @param bool $themedesigner
1255 * @return array nested array of file paths
1257 protected function get_css_files($themedesigner) {
1261 $cachekey = 'cssfiles';
1262 if ($themedesigner) {
1263 require_once($CFG->dirroot
.'/lib/csslib.php');
1264 // We need some kind of caching here because otherwise the page navigation becomes
1265 // way too slow in theme designer mode. Feel free to create full cache definition later...
1266 $cache = cache
::make_from_params(cache_store
::MODE_APPLICATION
, 'core', 'themedesigner', array('theme' => $this->name
));
1267 if ($files = $cache->get($cachekey)) {
1268 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME
) {
1269 unset($files['created']);
1275 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
1277 // Get all plugin sheets.
1278 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
1279 if ($excludes !== true) {
1280 foreach (core_component
::get_plugin_types() as $type=>$unused) {
1281 if ($type === 'theme' ||
(!empty($excludes[$type]) and $excludes[$type] === true)) {
1284 $plugins = core_component
::get_plugin_list($type);
1285 foreach ($plugins as $plugin=>$fulldir) {
1286 if (!empty($excludes[$type]) and is_array($excludes[$type])
1287 and in_array($plugin, $excludes[$type])) {
1291 // Get the CSS from the plugin.
1292 $sheetfile = "$fulldir/styles.css";
1293 if (is_readable($sheetfile)) {
1294 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
1297 // Create a list of candidate sheets from parents (direct parent last) and current theme.
1298 $candidates = array();
1299 foreach (array_reverse($this->parent_configs
) as $parent_config) {
1300 $candidates[] = $parent_config->name
;
1302 $candidates[] = $this->name
;
1304 // Add the sheets found.
1305 foreach ($candidates as $candidate) {
1306 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1307 if (is_readable($sheetthemefile)) {
1308 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
1315 // Find out wanted parent sheets.
1316 $excludes = $this->resolve_excludes('parents_exclude_sheets');
1317 if ($excludes !== true) {
1318 foreach (array_reverse($this->parent_configs
) as $parent_config) { // Base first, the immediate parent last.
1319 $parent = $parent_config->name
;
1320 if (empty($parent_config->sheets
) ||
(!empty($excludes[$parent]) and $excludes[$parent] === true)) {
1323 foreach ($parent_config->sheets
as $sheet) {
1324 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1325 && in_array($sheet, $excludes[$parent])) {
1329 // We never refer to the parent LESS files.
1330 $sheetfile = "$parent_config->dir/style/$sheet.css";
1331 if (is_readable($sheetfile)) {
1332 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1339 // Current theme sheets and less file.
1340 // We first add the SCSS, or LESS file because we want the CSS ones to
1341 // be included after the SCSS/LESS code. However, if both the LESS file
1342 // and a CSS file share the same name, the CSS file is ignored.
1343 if ($this->get_scss_property()) {
1344 $cssfiles['theme'][self
::SCSS_KEY
] = true;
1345 } else if (!empty($this->lessfile
)) {
1346 $sheetfile = "{$this->dir}/less/{$this->lessfile}.less";
1347 if (is_readable($sheetfile)) {
1348 $cssfiles['theme'][$this->lessfile
] = $sheetfile;
1351 if (is_array($this->sheets
)) {
1352 foreach ($this->sheets
as $sheet) {
1353 $sheetfile = "$this->dir/style/$sheet.css";
1354 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1355 $cssfiles['theme'][$sheet] = $sheetfile;
1362 $files['created'] = time();
1363 $cache->set($cachekey, $files);
1369 * Return the CSS content generated from LESS the file.
1371 * @param bool $themedesigner True if theme designer is enabled.
1372 * @return bool|string Return false when the compilation failed. Else the compiled string.
1374 protected function get_css_content_from_less($themedesigner) {
1377 $lessfile = $this->lessfile
;
1378 if (!$lessfile ||
!is_readable($this->dir
. '/less/' . $lessfile . '.less')) {
1379 throw new coding_exception('The theme did not define a LESS file, or it is not readable.');
1382 // We might need more memory/time to do this, so let's play safe.
1383 raise_memory_limit(MEMORY_EXTRA
);
1384 core_php_time_limit
::raise(300);
1387 $files = $this->get_css_files($themedesigner);
1389 // Get the LESS file path.
1390 $themelessfile = $files['theme'][$lessfile];
1392 // Setup compiler options.
1394 // We need to set the import directory to where $lessfile is.
1395 'import_dirs' => array(dirname($themelessfile) => '/'),
1396 // Always disable default caching.
1397 'cache_method' => false,
1398 // Disable the relative URLs, we have post_process() to handle that.
1399 'relativeUrls' => false,
1402 if ($themedesigner) {
1403 // Add the sourceMap inline to ensure that it is atomically generated.
1404 $options['sourceMap'] = true;
1405 $options['sourceMapBasepath'] = $CFG->dirroot
;
1406 $options['sourceMapRootpath'] = $CFG->wwwroot
;
1409 // Instantiate the compiler.
1410 $compiler = new core_lessc($options);
1413 $compiler->parse_file_content($themelessfile);
1415 // Get the callbacks.
1416 $compiler->parse($this->get_extra_less_code());
1417 $compiler->ModifyVars($this->get_less_variables());
1420 $compiled = $compiler->getCss();
1422 } catch (Less_Exception_Parser
$e) {
1424 debugging('Error while compiling LESS ' . $lessfile . ' file: ' . $e->getMessage(), DEBUG_DEVELOPER
);
1427 // Try to save memory.
1435 * Return the CSS content generated from the SCSS file.
1437 * @param bool $themedesigner True if theme designer is enabled.
1438 * @return bool|string Return false when the compilation failed. Else the compiled string.
1440 protected function get_css_content_from_scss($themedesigner) {
1443 list($paths, $scss) = $this->get_scss_property();
1445 throw new coding_exception('The theme did not define a SCSS file, or it is not readable.');
1448 // We might need more memory/time to do this, so let's play safe.
1449 raise_memory_limit(MEMORY_EXTRA
);
1450 core_php_time_limit
::raise(300);
1452 // Set-up the compiler.
1453 $compiler = new core_scss();
1454 $compiler->prepend_raw_scss($this->get_pre_scss_code());
1455 if (is_string($scss)) {
1456 $compiler->set_file($scss);
1458 $compiler->append_raw_scss($scss($this));
1459 $compiler->setImportPaths($paths);
1461 $compiler->append_raw_scss($this->get_extra_scss_code());
1465 $compiled = $compiler->to_css();
1467 } catch (\Leafo\ScssPhp\Exception
$e) {
1469 debugging('Error while compiling SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER
);
1472 // Try to save memory.
1480 * Get the icon system to use.
1484 public function get_icon_system() {
1486 // Getting all the candidate functions.
1488 if (isset($this->iconsystem
) && \core\output\icon_system
::is_valid_system($this->iconsystem
)) {
1489 return $this->iconsystem
;
1491 foreach ($this->parent_configs
as $parent_config) {
1492 if (isset($parent_config->iconsystem
) && \core\output\icon_system
::is_valid_system($parent_config->iconsystem
)) {
1493 return $parent_config->iconsystem
;
1496 return \core\output\icon_system
::STANDARD
;
1500 * Return extra LESS variables to use when compiling.
1502 * @return array Where keys are the variable names (omitting the @), and the values are the value.
1504 protected function get_less_variables() {
1505 $variables = array();
1507 // Getting all the candidate functions.
1508 $candidates = array();
1509 foreach ($this->parent_configs
as $parent_config) {
1510 if (!isset($parent_config->lessvariablescallback
)) {
1513 $candidates[] = $parent_config->lessvariablescallback
;
1515 $candidates[] = $this->lessvariablescallback
;
1517 // Calling the functions.
1518 foreach ($candidates as $function) {
1519 if (function_exists($function)) {
1520 $vars = $function($this);
1521 if (!is_array($vars)) {
1522 debugging('Callback ' . $function . ' did not return an array() as expected', DEBUG_DEVELOPER
);
1525 $variables = array_merge($variables, $vars);
1533 * Return extra LESS code to add when compiling.
1535 * This is intended to be used by themes to inject some LESS code
1536 * before it gets compiled. If you want to inject variables you
1537 * should use {@link self::get_less_variables()}.
1539 * @return string The LESS code to inject.
1541 protected function get_extra_less_code() {
1544 // Getting all the candidate functions.
1545 $candidates = array();
1546 foreach ($this->parent_configs
as $parent_config) {
1547 if (!isset($parent_config->extralesscallback
)) {
1550 $candidates[] = $parent_config->extralesscallback
;
1552 $candidates[] = $this->extralesscallback
;
1554 // Calling the functions.
1555 foreach ($candidates as $function) {
1556 if (function_exists($function)) {
1557 $content .= "\n/** Extra LESS from $function **/\n" . $function($this) . "\n";
1565 * Return extra SCSS code to add when compiling.
1567 * This is intended to be used by themes to inject some SCSS code
1568 * before it gets compiled. If you want to inject variables you
1569 * should use {@link self::get_scss_variables()}.
1571 * @return string The SCSS code to inject.
1573 protected function get_extra_scss_code() {
1576 // Getting all the candidate functions.
1577 $candidates = array();
1578 foreach ($this->parent_configs
as $parent_config) {
1579 if (!isset($parent_config->extrascsscallback
)) {
1582 $candidates[] = $parent_config->extrascsscallback
;
1584 $candidates[] = $this->extrascsscallback
;
1586 // Calling the functions.
1587 foreach ($candidates as $function) {
1588 if (function_exists($function)) {
1589 $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n";
1597 * SCSS code to prepend when compiling.
1599 * This is intended to be used by themes to inject SCSS code before it gets compiled.
1601 * @return string The SCSS code to inject.
1603 protected function get_pre_scss_code() {
1606 // Getting all the candidate functions.
1607 $candidates = array();
1608 foreach ($this->parent_configs
as $parent_config) {
1609 if (!isset($parent_config->prescsscallback
)) {
1612 $candidates[] = $parent_config->prescsscallback
;
1614 $candidates[] = $this->prescsscallback
;
1616 // Calling the functions.
1617 foreach ($candidates as $function) {
1618 if (function_exists($function)) {
1619 $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n";
1627 * Get the SCSS property.
1629 * This resolves whether a SCSS file (or content) has to be used when generating
1630 * the stylesheet for the theme. It will look at parents themes and check the
1631 * SCSS properties there.
1633 * @return False when SCSS is not used.
1634 * An array with the import paths, and the path to the SCSS file or Closure as second.
1636 public function get_scss_property() {
1637 if ($this->scsscache
=== null) {
1638 $configs = [$this] +
$this->parent_configs
;
1641 foreach ($configs as $config) {
1642 $path = "{$config->dir}/scss";
1644 // We collect the SCSS property until we've found one.
1645 if (empty($scss) && !empty($config->scss
)) {
1646 $candidate = is_string($config->scss
) ?
"{$path}/{$config->scss}.scss" : $config->scss
;
1647 if ($candidate instanceof Closure
) {
1649 } else if (is_string($candidate) && is_readable($candidate)) {
1654 // We collect the import paths once we've found a SCSS property.
1655 if ($scss && is_dir($path)) {
1661 $this->scsscache
= $scss !== null ?
[$paths, $scss] : false;
1664 return $this->scsscache
;
1668 * Generate a URL to the file that serves theme JavaScript files.
1670 * If we determine that the theme has no relevant files, then we return
1671 * early with a null value.
1673 * @param bool $inhead true means head url, false means footer
1674 * @return moodle_url|null
1676 public function javascript_url($inhead) {
1679 $rev = theme_get_revision();
1680 $params = array('theme'=>$this->name
,'rev'=>$rev);
1681 $params['type'] = $inhead ?
'head' : 'footer';
1683 // Return early if there are no files to serve
1684 if (count($this->javascript_files($params['type'])) === 0) {
1688 if (!empty($CFG->slasharguments
) and $rev > 0) {
1689 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
1690 $url->set_slashargument('/'.$this->name
.'/'.$rev.'/'.$params['type'], 'noparam', true);
1693 return new moodle_url($CFG->httpswwwroot
.'/theme/javascript.php', $params);
1698 * Get the URL's for the JavaScript files used by this theme.
1699 * They won't be served directly, instead they'll be mediated through
1700 * theme/javascript.php.
1702 * @param string $type Either javascripts_footer, or javascripts
1705 public function javascript_files($type) {
1706 if ($type === 'footer') {
1707 $type = 'javascripts_footer';
1709 $type = 'javascripts';
1713 // find out wanted parent javascripts
1714 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1715 if ($excludes !== true) {
1716 foreach (array_reverse($this->parent_configs
) as $parent_config) { // base first, the immediate parent last
1717 $parent = $parent_config->name
;
1718 if (empty($parent_config->$type)) {
1721 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1724 foreach ($parent_config->$type as $javascript) {
1725 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1726 and in_array($javascript, $excludes[$parent])) {
1729 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1730 if (is_readable($javascriptfile)) {
1731 $js[] = $javascriptfile;
1737 // current theme javascripts
1738 if (is_array($this->$type)) {
1739 foreach ($this->$type as $javascript) {
1740 $javascriptfile = "$this->dir/javascript/$javascript.js";
1741 if (is_readable($javascriptfile)) {
1742 $js[] = $javascriptfile;
1750 * Resolves an exclude setting to the themes setting is applicable or the
1751 * setting of its closest parent.
1753 * @param string $variable The name of the setting the exclude setting to resolve
1754 * @param string $default
1757 protected function resolve_excludes($variable, $default = null) {
1758 $setting = $default;
1759 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1760 $setting = $this->{$variable};
1762 foreach ($this->parent_configs
as $parent_config) { // the immediate parent first, base last
1763 if (!isset($parent_config->{$variable})) {
1766 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1767 $setting = $parent_config->{$variable};
1776 * Returns the content of the one huge javascript file merged from all theme javascript files.
1781 public function javascript_content($type) {
1782 $jsfiles = $this->javascript_files($type);
1784 foreach ($jsfiles as $jsfile) {
1785 $js .= file_get_contents($jsfile)."\n";
1791 * Post processes CSS.
1793 * This method post processes all of the CSS before it is served for this theme.
1794 * This is done so that things such as image URL's can be swapped in and to
1795 * run any specific CSS post process method the theme has requested.
1796 * This allows themes to use CSS settings.
1798 * @param string $css The CSS to process.
1799 * @return string The processed CSS.
1801 public function post_process($css) {
1802 // now resolve all image locations
1803 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER
)) {
1804 $replaced = array();
1805 foreach ($matches as $match) {
1806 if (isset($replaced[$match[0]])) {
1809 $replaced[$match[0]] = true;
1810 $imagename = $match[2];
1811 $component = rtrim($match[1], '|');
1812 $imageurl = $this->image_url($imagename, $component)->out(false);
1813 // we do not need full url because the image.php is always in the same dir
1814 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1815 $css = str_replace($match[0], $imageurl, $css);
1819 // Now resolve all font locations.
1820 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER
)) {
1821 $replaced = array();
1822 foreach ($matches as $match) {
1823 if (isset($replaced[$match[0]])) {
1826 $replaced[$match[0]] = true;
1827 $fontname = $match[2];
1828 $component = rtrim($match[1], '|');
1829 $fonturl = $this->font_url($fontname, $component)->out(false);
1830 // We do not need full url because the font.php is always in the same dir.
1831 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1832 $css = str_replace($match[0], $fonturl, $css);
1836 // Now resolve all theme settings or do any other postprocessing.
1837 // This needs to be done before calling core parser, since the parser strips [[settings]] tags.
1838 $csspostprocess = $this->csspostprocess
;
1839 if (function_exists($csspostprocess)) {
1840 $css = $csspostprocess($css, $this);
1843 // Post processing using an object representation of CSS.
1844 $treeprocessor = $this->get_css_tree_post_processor();
1845 $needsparsing = !empty($treeprocessor) ||
!empty($this->rtlmode
);
1846 if ($needsparsing) {
1848 // We might need more memory/time to do this, so let's play safe.
1849 raise_memory_limit(MEMORY_EXTRA
);
1850 core_php_time_limit
::raise(300);
1852 $parser = new core_cssparser($css);
1853 $csstree = $parser->parse();
1856 if ($this->rtlmode
) {
1857 $this->rtlize($csstree);
1860 if ($treeprocessor) {
1861 $treeprocessor($csstree, $this);
1864 $css = $csstree->render();
1872 * Flip a stylesheet to RTL.
1874 * @param Object $csstree The parsed CSS tree structure to flip.
1877 protected function rtlize($csstree) {
1878 $rtlcss = new core_rtlcss($csstree);
1883 * Return the direct URL for an image from the pix folder.
1885 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1887 * @deprecated since Moodle 3.3
1888 * @param string $imagename the name of the icon.
1889 * @param string $component specification of one plugin like in get_string()
1890 * @return moodle_url
1892 public function pix_url($imagename, $component) {
1893 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER
);
1894 return $this->image_url($imagename, $component);
1898 * Return the direct URL for an image from the pix folder.
1900 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1902 * @param string $imagename the name of the icon.
1903 * @param string $component specification of one plugin like in get_string()
1904 * @return moodle_url
1906 public function image_url($imagename, $component) {
1909 $params = array('theme'=>$this->name
);
1910 $svg = $this->use_svg_icons();
1912 if (empty($component) or $component === 'moodle' or $component === 'core') {
1913 $params['component'] = 'core';
1915 $params['component'] = $component;
1918 $rev = theme_get_revision();
1920 $params['rev'] = $rev;
1923 $params['image'] = $imagename;
1925 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1926 if (!empty($CFG->slasharguments
) and $rev > 0) {
1927 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1929 // We add a simple /_s to the start of the path.
1930 // The underscore is used to ensure that it isn't a valid theme name.
1931 $path = '/_s'.$path;
1933 $url->set_slashargument($path, 'noparam', true);
1936 // We add an SVG param so that we know not to serve SVG images.
1937 // We do this because all modern browsers support SVG and this param will one day be removed.
1938 $params['svg'] = '0';
1940 $url->params($params);
1947 * Return the URL for a font
1949 * @param string $font the name of the font (including extension).
1950 * @param string $component specification of one plugin like in get_string()
1951 * @return moodle_url
1953 public function font_url($font, $component) {
1956 $params = array('theme'=>$this->name
);
1958 if (empty($component) or $component === 'moodle' or $component === 'core') {
1959 $params['component'] = 'core';
1961 $params['component'] = $component;
1964 $rev = theme_get_revision();
1966 $params['rev'] = $rev;
1969 $params['font'] = $font;
1971 $url = new moodle_url("$CFG->httpswwwroot/theme/font.php");
1972 if (!empty($CFG->slasharguments
) and $rev > 0) {
1973 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1974 $url->set_slashargument($path, 'noparam', true);
1976 $url->params($params);
1983 * Returns URL to the stored file via pluginfile.php.
1985 * Note the theme must also implement pluginfile.php handler,
1986 * theme revision is used instead of the itemid.
1988 * @param string $setting
1989 * @param string $filearea
1990 * @return string protocol relative URL or null if not present
1992 public function setting_file_url($setting, $filearea) {
1995 if (empty($this->settings
->$setting)) {
1999 $component = 'theme_'.$this->name
;
2000 $itemid = theme_get_revision();
2001 $filepath = $this->settings
->$setting;
2002 $syscontext = context_system
::instance();
2004 $url = moodle_url
::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
2006 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
2007 // Note: unfortunately moodle_url does not support //urls yet.
2009 $url = preg_replace('|^https?://|i', '//', $url->out(false));
2015 * Serve the theme setting file.
2017 * @param string $filearea
2018 * @param array $args
2019 * @param bool $forcedownload
2020 * @param array $options
2021 * @return bool may terminate if file not found or donotdie not specified
2023 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
2025 require_once("$CFG->libdir/filelib.php");
2027 $syscontext = context_system
::instance();
2028 $component = 'theme_'.$this->name
;
2030 $revision = array_shift($args);
2031 if ($revision < 0) {
2034 $lifetime = 60*60*24*60;
2035 // By default, theme files must be cache-able by both browsers and proxies.
2036 if (!array_key_exists('cacheability', $options)) {
2037 $options['cacheability'] = 'public';
2041 $fs = get_file_storage();
2042 $relativepath = implode('/', $args);
2044 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
2045 $fullpath = rtrim($fullpath, '/');
2046 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
2047 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
2050 send_file_not_found();
2055 * Resolves the real image location.
2057 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
2058 * and we need a way in which to turn it off.
2059 * By default SVG won't be used unless asked for. This is done for two reasons:
2060 * 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
2061 * browser supports SVG.
2062 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
2063 * by the user due to security concerns.
2065 * @param string $image name of image, may contain relative path
2066 * @param string $component
2067 * @param bool $svg|null Should SVG images also be looked for? If null, resorts to $CFG->svgicons if that is set; falls back to
2068 * auto-detection of browser support otherwise
2069 * @return string full file path
2071 public function resolve_image_location($image, $component, $svg = false) {
2074 if (!is_bool($svg)) {
2075 // If $svg isn't a bool then we need to decide for ourselves.
2076 $svg = $this->use_svg_icons();
2079 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2080 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
2083 foreach (array_reverse($this->parent_configs
) as $parent_config) { // base first, the immediate parent last
2084 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
2088 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
2091 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
2096 } else if ($component === 'theme') { //exception
2097 if ($image === 'favicon') {
2098 return "$this->dir/pix/favicon.ico";
2100 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
2103 foreach (array_reverse($this->parent_configs
) as $parent_config) { // base first, the immediate parent last
2104 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
2111 if (strpos($component, '_') === false) {
2112 $component = 'mod_'.$component;
2114 list($type, $plugin) = explode('_', $component, 2);
2116 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2119 foreach (array_reverse($this->parent_configs
) as $parent_config) { // base first, the immediate parent last
2120 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2124 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
2127 $dir = core_component
::get_plugin_directory($type, $plugin);
2128 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
2136 * Resolves the real font location.
2138 * @param string $font name of font file
2139 * @param string $component
2140 * @return string full file path
2142 public function resolve_font_location($font, $component) {
2145 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2146 if (file_exists("$this->dir/fonts_core/$font")) {
2147 return "$this->dir/fonts_core/$font";
2149 foreach (array_reverse($this->parent_configs
) as $parent_config) { // Base first, the immediate parent last.
2150 if (file_exists("$parent_config->dir/fonts_core/$font")) {
2151 return "$parent_config->dir/fonts_core/$font";
2154 if (file_exists("$CFG->dataroot/fonts/$font")) {
2155 return "$CFG->dataroot/fonts/$font";
2157 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
2158 return "$CFG->dirroot/lib/fonts/$font";
2162 } else if ($component === 'theme') { // Exception.
2163 if (file_exists("$this->dir/fonts/$font")) {
2164 return "$this->dir/fonts/$font";
2166 foreach (array_reverse($this->parent_configs
) as $parent_config) { // Base first, the immediate parent last.
2167 if (file_exists("$parent_config->dir/fonts/$font")) {
2168 return "$parent_config->dir/fonts/$font";
2174 if (strpos($component, '_') === false) {
2175 $component = 'mod_'.$component;
2177 list($type, $plugin) = explode('_', $component, 2);
2179 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
2180 return "$this->dir/fonts_plugins/$type/$plugin/$font";
2182 foreach (array_reverse($this->parent_configs
) as $parent_config) { // Base first, the immediate parent last.
2183 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
2184 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
2187 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
2188 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
2190 $dir = core_component
::get_plugin_directory($type, $plugin);
2191 if (file_exists("$dir/fonts/$font")) {
2192 return "$dir/fonts/$font";
2199 * Return true if we should look for SVG images as well.
2203 public function use_svg_icons() {
2205 if ($this->usesvg
=== null) {
2207 if (!isset($CFG->svgicons
)) {
2208 $this->usesvg
= core_useragent
::supports_svg();
2210 // Force them on/off depending upon the setting.
2211 $this->usesvg
= (bool)$CFG->svgicons
;
2214 return $this->usesvg
;
2218 * Forces the usesvg setting to either true or false, avoiding any decision making.
2220 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
2221 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
2223 * @param bool $setting True to force the use of svg when available, null otherwise.
2225 public function force_svg_use($setting) {
2226 $this->usesvg
= (bool)$setting;
2230 * Set to be in RTL mode.
2232 * This will likely be used when post processing the CSS before serving it.
2234 * @param bool $inrtl True when in RTL mode.
2236 public function set_rtl_mode($inrtl = true) {
2237 $this->rtlmode
= $inrtl;
2241 * Whether the theme is being served in RTL mode.
2243 * @return bool True when in RTL mode.
2245 public function get_rtl_mode() {
2246 return $this->rtlmode
;
2250 * Checks if file with any image extension exists.
2252 * The order to these images was adjusted prior to the release of 2.4
2253 * At that point the were the following image counts in Moodle core:
2255 * - png = 667 in pix dirs (1499 total)
2256 * - gif = 385 in pix dirs (606 total)
2257 * - jpg = 62 in pix dirs (74 total)
2258 * - jpeg = 0 in pix dirs (1 total)
2260 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
2262 * @param string $filepath
2263 * @param bool $svg If set to true SVG images will also be looked for.
2264 * @return string image name with extension
2266 private static function image_exists($filepath, $svg = false) {
2267 if ($svg && file_exists("$filepath.svg")) {
2268 return "$filepath.svg";
2269 } else if (file_exists("$filepath.png")) {
2270 return "$filepath.png";
2271 } else if (file_exists("$filepath.gif")) {
2272 return "$filepath.gif";
2273 } else if (file_exists("$filepath.jpg")) {
2274 return "$filepath.jpg";
2275 } else if (file_exists("$filepath.jpeg")) {
2276 return "$filepath.jpeg";
2283 * Loads the theme config from config.php file.
2285 * @param string $themename
2286 * @param stdClass $settings from config_plugins table
2287 * @param boolean $parentscheck true to also check the parents. .
2288 * @return stdClass The theme configuration
2290 private static function find_theme_config($themename, $settings, $parentscheck = true) {
2291 // We have to use the variable name $THEME (upper case) because that
2292 // is what is used in theme config.php files.
2294 if (!$dir = theme_config
::find_theme_location($themename)) {
2298 $THEME = new stdClass();
2299 $THEME->name
= $themename;
2301 $THEME->settings
= $settings;
2303 global $CFG; // just in case somebody tries to use $CFG in theme config
2304 include("$THEME->dir/config.php");
2306 // verify the theme configuration is OK
2307 if (!is_array($THEME->parents
)) {
2308 // parents option is mandatory now
2311 // We use $parentscheck to only check the direct parents (avoid infinite loop).
2312 if ($parentscheck) {
2313 // Find all parent theme configs.
2314 foreach ($THEME->parents
as $parent) {
2315 $parentconfig = theme_config
::find_theme_config($parent, $settings, false);
2316 if (empty($parentconfig)) {
2327 * Finds the theme location and verifies the theme has all needed files
2328 * and is not obsoleted.
2330 * @param string $themename
2331 * @return string full dir path or null if not found
2333 private static function find_theme_location($themename) {
2336 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2337 $dir = "$CFG->dirroot/theme/$themename";
2339 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$themename/config.php")) {
2340 $dir = "$CFG->themedir/$themename";
2346 if (file_exists("$dir/styles.php")) {
2347 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
2355 * Get the renderer for a part of Moodle for this theme.
2357 * @param moodle_page $page the page we are rendering
2358 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
2359 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
2360 * @param string $target one of rendering target constants
2361 * @return renderer_base the requested renderer.
2363 public function get_renderer(moodle_page
$page, $component, $subtype = null, $target = null) {
2364 if (is_null($this->rf
)) {
2365 $classname = $this->rendererfactory
;
2366 $this->rf
= new $classname($this);
2369 return $this->rf
->get_renderer($page, $component, $subtype, $target);
2373 * Get the information from {@link $layouts} for this type of page.
2375 * @param string $pagelayout the the page layout name.
2376 * @return array the appropriate part of {@link $layouts}.
2378 protected function layout_info_for_page($pagelayout) {
2379 if (array_key_exists($pagelayout, $this->layouts
)) {
2380 return $this->layouts
[$pagelayout];
2382 debugging('Invalid page layout specified: ' . $pagelayout);
2383 return $this->layouts
['standard'];
2388 * Given the settings of this theme, and the page pagelayout, return the
2389 * full path of the page layout file to use.
2391 * Used by {@link core_renderer::header()}.
2393 * @param string $pagelayout the the page layout name.
2394 * @return string Full path to the lyout file to use
2396 public function layout_file($pagelayout) {
2399 $layoutinfo = $this->layout_info_for_page($pagelayout);
2400 $layoutfile = $layoutinfo['file'];
2402 if (array_key_exists('theme', $layoutinfo)) {
2403 $themes = array($layoutinfo['theme']);
2405 $themes = array_merge(array($this->name
),$this->parents
);
2408 foreach ($themes as $theme) {
2409 if ($dir = $this->find_theme_location($theme)) {
2410 $path = "$dir/layout/$layoutfile";
2412 // Check the template exists, return general base theme template if not.
2413 if (is_readable($path)) {
2419 debugging('Can not find layout file for: ' . $pagelayout);
2420 // fallback to standard normal layout
2421 return "$CFG->dirroot/theme/base/layout/general.php";
2425 * Returns auxiliary page layout options specified in layout configuration array.
2427 * @param string $pagelayout
2430 public function pagelayout_options($pagelayout) {
2431 $info = $this->layout_info_for_page($pagelayout);
2432 if (!empty($info['options'])) {
2433 return $info['options'];
2439 * Inform a block_manager about the block regions this theme wants on this
2442 * @param string $pagelayout the general type of the page.
2443 * @param block_manager $blockmanager the block_manger to set up.
2445 public function setup_blocks($pagelayout, $blockmanager) {
2446 $layoutinfo = $this->layout_info_for_page($pagelayout);
2447 if (!empty($layoutinfo['regions'])) {
2448 $blockmanager->add_regions($layoutinfo['regions'], false);
2449 $blockmanager->set_default_region($layoutinfo['defaultregion']);
2454 * Gets the visible name for the requested block region.
2456 * @param string $region The region name to get
2457 * @param string $theme The theme the region belongs to (may come from the parent theme)
2460 protected function get_region_name($region, $theme) {
2461 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
2462 // A name exists in this theme, so use it
2463 if (substr($regionstring, 0, 1) != '[') {
2464 return $regionstring;
2467 // Otherwise, try to find one elsewhere
2468 // Check parents, if any
2469 foreach ($this->parents
as $parentthemename) {
2470 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
2471 if (substr($regionstring, 0, 1) != '[') {
2472 return $regionstring;
2476 // Last resort, try the bootstrapbase theme for names
2477 return get_string('region-' . $region, 'theme_bootstrapbase');
2481 * Get the list of all block regions known to this theme in all templates.
2483 * @return array internal region name => human readable name.
2485 public function get_all_block_regions() {
2487 foreach ($this->layouts
as $layoutinfo) {
2488 foreach ($layoutinfo['regions'] as $region) {
2489 $regions[$region] = $this->get_region_name($region, $this->name
);
2496 * Returns the human readable name of the theme
2500 public function get_theme_name() {
2501 return get_string('pluginname', 'theme_'.$this->name
);
2505 * Returns the block render method.
2507 * It is set by the theme via:
2508 * $THEME->blockrendermethod = '...';
2510 * It can be one of two values, blocks or blocks_for_region.
2511 * It should be set to the method being used by the theme layouts.
2515 public function get_block_render_method() {
2516 if ($this->blockrendermethod
) {
2517 // Return the specified block render method.
2518 return $this->blockrendermethod
;
2520 // Its not explicitly set, check the parent theme configs.
2521 foreach ($this->parent_configs
as $config) {
2522 if (isset($config->blockrendermethod
)) {
2523 return $config->blockrendermethod
;
2526 // Default it to blocks.
2531 * Get the callable for CSS tree post processing.
2533 * @return string|null
2535 public function get_css_tree_post_processor() {
2536 $configs = [$this] +
$this->parent_configs
;
2537 foreach ($configs as $config) {
2538 if (!empty($config->csstreepostprocessor
) && is_callable($config->csstreepostprocessor
)) {
2539 return $config->csstreepostprocessor
;
2548 * This class keeps track of which HTML tags are currently open.
2550 * This makes it much easier to always generate well formed XHTML output, even
2551 * if execution terminates abruptly. Any time you output some opening HTML
2552 * without the matching closing HTML, you should push the necessary close tags
2555 * @copyright 2009 Tim Hunt
2556 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2561 class xhtml_container_stack
{
2564 * @var array Stores the list of open containers.
2566 protected $opencontainers = array();
2569 * @var array In developer debug mode, stores a stack trace of all opens and
2570 * closes, so we can output helpful error messages when there is a mismatch.
2572 protected $log = array();
2575 * @var boolean Store whether we are developer debug mode. We need this in
2576 * several places including in the destructor where we may not have access to $CFG.
2578 protected $isdebugging;
2583 public function __construct() {
2585 $this->isdebugging
= $CFG->debugdeveloper
;
2589 * Push the close HTML for a recently opened container onto the stack.
2591 * @param string $type The type of container. This is checked when {@link pop()}
2592 * is called and must match, otherwise a developer debug warning is output.
2593 * @param string $closehtml The HTML required to close the container.
2595 public function push($type, $closehtml) {
2596 $container = new stdClass
;
2597 $container->type
= $type;
2598 $container->closehtml
= $closehtml;
2599 if ($this->isdebugging
) {
2600 $this->log('Open', $type);
2602 array_push($this->opencontainers
, $container);
2606 * Pop the HTML for the next closing container from the stack. The $type
2607 * must match the type passed when the container was opened, otherwise a
2608 * warning will be output.
2610 * @param string $type The type of container.
2611 * @return string the HTML required to close the container.
2613 public function pop($type) {
2614 if (empty($this->opencontainers
)) {
2615 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2616 $this->output_log(), DEBUG_DEVELOPER
);
2620 $container = array_pop($this->opencontainers
);
2621 if ($container->type
!= $type) {
2622 debugging('<p>The type of container to be closed (' . $container->type
.
2623 ') does not match the type of the next open container (' . $type .
2624 '). This suggests there is a nesting problem.</p>' .
2625 $this->output_log(), DEBUG_DEVELOPER
);
2627 if ($this->isdebugging
) {
2628 $this->log('Close', $type);
2630 return $container->closehtml
;
2634 * Close all but the last open container. This is useful in places like error
2635 * handling, where you want to close all the open containers (apart from <body>)
2636 * before outputting the error message.
2638 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2639 * developer debug warning if it isn't.
2640 * @return string the HTML required to close any open containers inside <body>.
2642 public function pop_all_but_last($shouldbenone = false) {
2643 if ($shouldbenone && count($this->opencontainers
) != 1) {
2644 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2645 $this->output_log(), DEBUG_DEVELOPER
);
2648 while (count($this->opencontainers
) > 1) {
2649 $container = array_pop($this->opencontainers
);
2650 $output .= $container->closehtml
;
2656 * You can call this function if you want to throw away an instance of this
2657 * class without properly emptying the stack (for example, in a unit test).
2658 * Calling this method stops the destruct method from outputting a developer
2659 * debug warning. After calling this method, the instance can no longer be used.
2661 public function discard() {
2662 $this->opencontainers
= null;
2666 * Adds an entry to the log.
2668 * @param string $action The name of the action
2669 * @param string $type The type of action
2671 protected function log($action, $type) {
2672 $this->log
[] = '<li>' . $action . ' ' . $type . ' at:' .
2673 format_backtrace(debug_backtrace()) . '</li>';
2677 * Outputs the log's contents as a HTML list.
2679 * @return string HTML list of the log
2681 protected function output_log() {
2682 return '<ul>' . implode("\n", $this->log
) . '</ul>';