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.
182 * @return array The built theme content in a multi-dimensional array of name => direction => content
184 function theme_build_css_for_themes($themeconfigs = [], $directions = ['rtl', 'ltr'],
185 $cache = true, $mtraceprogress = false): array {
188 if (empty($themeconfigs)) {
192 require_once("{$CFG->libdir}/csslib.php");
195 $themerev = theme_get_revision();
196 // Make sure the local cache directory exists.
197 make_localcache_directory('theme');
199 foreach ($themeconfigs as $themeconfig) {
201 $oldrevision = theme_get_sub_revision_for_theme($themeconfig->name
);
202 $newrevision = theme_get_next_sub_revision_for_theme($themeconfig->name
);
204 // First generate all the new css.
205 foreach ($directions as $direction) {
206 if ($mtraceprogress) {
207 $timestart = microtime(true);
208 mtrace('Building theme CSS for ' . $themeconfig->name
. ' [' .
209 $direction . '] ...', '');
211 // Lock it on. Technically we should build all themes for SVG and no SVG - but ie9 is out of support.
212 $themeconfig->force_svg_use(true);
213 $themeconfig->set_rtl_mode(($direction === 'rtl'));
215 $themecss[$direction] = $themeconfig->get_css_content();
217 $themeconfig->set_css_content_cache($themecss[$direction]);
218 $filename = theme_get_css_filename($themeconfig->name
, $themerev, $newrevision, $direction);
219 css_store_css($themeconfig, $filename, $themecss[$direction]);
221 if ($mtraceprogress) {
222 mtrace(' done in ' . round(microtime(true) - $timestart, 2) . ' seconds.');
225 $themescss[$themeconfig->name
] = $themecss;
228 // Only update the theme revision after we've successfully created the
230 theme_set_sub_revision_for_theme($themeconfig->name
, $newrevision);
232 // Now purge old files. We must purge all old files in the local cache
233 // because we've incremented the theme sub revision. This will leave any
234 // files with the old revision inaccessbile so we might as well removed
236 foreach (['ltr', 'rtl'] as $direction) {
237 $oldcss = theme_get_css_filename($themeconfig->name
, $themerev, $oldrevision, $direction);
238 if (file_exists($oldcss)) {
249 * Invalidate all server and client side caches.
251 * This method deletes the physical directory that is used to cache the theme
252 * files used for serving.
253 * Because it deletes the main theme cache directory all themes are reset by
256 function theme_reset_all_caches() {
258 require_once("{$CFG->libdir}/filelib.php");
260 $next = theme_get_next_revision();
261 theme_set_revision($next);
263 if (!empty($CFG->themedesignermode
)) {
264 $cache = cache
::make_from_params(cache_store
::MODE_APPLICATION
, 'core', 'themedesigner');
268 // Purge compiled post processed css.
269 cache
::make('core', 'postprocessedcss')->purge();
271 // Delete all old theme localcaches.
272 $themecachedirs = glob("{$CFG->localcachedir}/theme/*", GLOB_ONLYDIR
);
273 foreach ($themecachedirs as $localcachedir) {
274 fulldelete($localcachedir);
278 $PAGE->reload_theme();
283 * Reset static caches.
285 * This method indicates that all running cron processes should exit at the
288 function theme_reset_static_caches() {
289 \core\task\manager
::clear_static_caches();
293 * Enable or disable theme designer mode.
297 function theme_set_designer_mod($state) {
298 set_config('themedesignermode', (int)!empty($state));
299 // Reset caches after switching mode so that any designer mode caches get purged too.
300 theme_reset_all_caches();
304 * Checks if the given device has a theme defined in config.php.
308 function theme_is_device_locked($device) {
310 $themeconfigname = core_useragent
::get_device_type_cfg_var_name($device);
311 return isset($CFG->config_php_settings
[$themeconfigname]);
315 * Returns the theme named defined in config.php for the given device.
317 * @return string or null
319 function theme_get_locked_theme_for_device($device) {
322 if (!theme_is_device_locked($device)) {
326 $themeconfigname = core_useragent
::get_device_type_cfg_var_name($device);
327 return $CFG->config_php_settings
[$themeconfigname];
331 * This class represents the configuration variables of a Moodle theme.
333 * All the variables with access: public below (with a few exceptions that are marked)
334 * are the properties you can set in your themes config.php file.
336 * There are also some methods and protected variables that are part of the inner
337 * workings of Moodle's themes system. If you are just editing a themes config.php
338 * file, you can just ignore those, and the following information for developers.
340 * Normally, to create an instance of this class, you should use the
341 * {@link theme_config::load()} factory method to load a themes config.php file.
342 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
343 * will create one for you, accessible as $PAGE->theme.
345 * @copyright 2009 Tim Hunt
346 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
354 * @var string Default theme, used when requested theme not found.
356 const DEFAULT_THEME
= 'boost';
358 /** The key under which the SCSS file is stored amongst the CSS files. */
359 const SCSS_KEY
= '__SCSS__';
362 * @var array You can base your theme on other themes by linking to the other theme as
363 * parents. This lets you use the CSS and layouts from the other themes
364 * (see {@link theme_config::$layouts}).
365 * That makes it easy to create a new theme that is similar to another one
366 * but with a few changes. In this themes CSS you only need to override
367 * those rules you want to change.
372 * @var array The names of all the stylesheets from this theme that you would
373 * like included, in order. Give the names of the files without .css.
375 public $sheets = array();
378 * @var array The names of all the stylesheets from parents that should be excluded.
379 * true value may be used to specify all parents or all themes from one parent.
380 * If no value specified value from parent theme used.
382 public $parents_exclude_sheets = null;
385 * @var array List of plugin sheets to be excluded.
386 * If no value specified value from parent theme used.
388 public $plugins_exclude_sheets = null;
391 * @var array List of style sheets that are included in the text editor bodies.
392 * Sheets from parent themes are used automatically and can not be excluded.
394 public $editor_sheets = array();
397 * @var bool Whether a fallback version of the stylesheet will be used
398 * whilst the final version is generated.
400 public $usefallback = false;
403 * @var array The names of all the javascript files this theme that you would
404 * like included from head, in order. Give the names of the files without .js.
406 public $javascripts = array();
409 * @var array The names of all the javascript files this theme that you would
410 * like included from footer, in order. Give the names of the files without .js.
412 public $javascripts_footer = array();
415 * @var array The names of all the javascript files from parents that should
416 * be excluded. true value may be used to specify all parents or all themes
418 * If no value specified value from parent theme used.
420 public $parents_exclude_javascripts = null;
423 * @var array Which file to use for each page layout.
425 * This is an array of arrays. The keys of the outer array are the different layouts.
426 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
427 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
428 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
429 * That file also has a good example of how to set this setting.
431 * For each layout, the value in the outer array is an array that describes
432 * how you want that type of page to look. For example
434 * $THEME->layouts = array(
435 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
436 * 'standard' => array(
437 * 'theme' = 'mytheme',
438 * 'file' => 'normal.php',
439 * 'regions' => array('side-pre', 'side-post'),
440 * 'defaultregion' => 'side-post'
442 * // The site home page.
444 * 'theme' = 'mytheme',
445 * 'file' => 'home.php',
446 * 'regions' => array('side-pre', 'side-post'),
447 * 'defaultregion' => 'side-post'
453 * 'theme' name of the theme where is the layout located
454 * 'file' is the layout file to use for this type of page.
455 * layout files are stored in layout subfolder
456 * 'regions' This lists the regions on the page where blocks may appear. For
457 * each region you list here, your layout file must include a call to
459 * echo $OUTPUT->blocks_for_region($regionname);
461 * or equivalent so that the blocks are actually visible.
463 * 'defaultregion' If the list of regions is non-empty, then you must pick
464 * one of the one of them as 'default'. This has two meanings. First, this is
465 * where new blocks are added. Second, if there are any blocks associated with
466 * the page, but in non-existent regions, they appear here. (Imaging, for example,
467 * that someone added blocks using a different theme that used different region
468 * names, and then switched to this theme.)
470 public $layouts = array();
473 * @var string Name of the renderer factory class to use. Must implement the
474 * {@link renderer_factory} interface.
476 * This is an advanced feature. Moodle output is generated by 'renderers',
477 * you can customise the HTML that is output by writing custom renderers,
478 * and then you need to specify 'renderer factory' so that Moodle can find
481 * There are some renderer factories supplied with Moodle. Please follow these
482 * links to see what they do.
484 * <li>{@link standard_renderer_factory} - the default.</li>
485 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
486 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
489 public $rendererfactory = 'standard_renderer_factory';
492 * @var string Function to do custom CSS post-processing.
494 * This is an advanced feature. If you want to do custom post-processing on the
495 * CSS before it is output (for example, to replace certain variable names
496 * with particular values) you can give the name of a function here.
498 public $csspostprocess = null;
501 * @var string Function to do custom CSS post-processing on a parsed CSS tree.
503 * This is an advanced feature. If you want to do custom post-processing on the
504 * CSS before it is output, you can provide the name of the function here. The
505 * function will receive a CSS tree document as first parameter, and the theme_config
506 * object as second parameter. A return value is not required, the tree can
507 * be edited in place.
509 public $csstreepostprocessor = null;
512 * @var string Accessibility: Right arrow-like character is
513 * used in the breadcrumb trail, course navigation menu
514 * (previous/next activity), calendar, and search forum block.
515 * If the theme does not set characters, appropriate defaults
516 * are set automatically. Please DO NOT
517 * use < > » - these are confusing for blind users.
519 public $rarrow = null;
522 * @var string Accessibility: Left arrow-like character is
523 * used in the breadcrumb trail, course navigation menu
524 * (previous/next activity), calendar, and search forum block.
525 * If the theme does not set characters, appropriate defaults
526 * are set automatically. Please DO NOT
527 * use < > » - these are confusing for blind users.
529 public $larrow = null;
532 * @var string Accessibility: Up arrow-like character is used in
533 * the book heirarchical navigation.
534 * If the theme does not set characters, appropriate defaults
535 * are set automatically. Please DO NOT
536 * use ^ - this is confusing for blind users.
538 public $uarrow = null;
541 * @var string Accessibility: Down arrow-like character.
542 * If the theme does not set characters, appropriate defaults
543 * are set automatically.
545 public $darrow = null;
548 * @var bool Some themes may want to disable ajax course editing.
550 public $enablecourseajax = true;
553 * @var string Determines served document types
554 * - 'html5' the only officially supported doctype in Moodle
555 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
556 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
558 public $doctype = 'html5';
561 * @var string requiredblocks If set to a string, will list the block types that cannot be deleted. Defaults to
562 * navigation and settings.
564 public $requiredblocks = false;
566 //==Following properties are not configurable from theme config.php==
569 * @var string The name of this theme. Set automatically when this theme is
570 * loaded. This can not be set in theme config.php
575 * @var string The folder where this themes files are stored. This is set
576 * automatically. This can not be set in theme config.php
581 * @var stdClass Theme settings stored in config_plugins table.
582 * This can not be set in theme config.php
584 public $settings = null;
587 * @var bool If set to true and the theme enables the dock then blocks will be able
588 * to be moved to the special dock
590 public $enable_dock = false;
593 * @var bool If set to true then this theme will not be shown in the theme selector unless
594 * theme designer mode is turned on.
596 public $hidefromselector = false;
599 * @var array list of YUI CSS modules to be included on each page. This may be used
600 * to remove cssreset and use cssnormalise module instead.
602 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
605 * An associative array of block manipulations that should be made if the user is using an rtl language.
606 * The key is the original block region, and the value is the block region to change to.
607 * This is used when displaying blocks for regions only.
610 public $blockrtlmanipulations = array();
613 * @var renderer_factory Instance of the renderer_factory implementation
614 * we are using. Implementation detail.
616 protected $rf = null;
619 * @var array List of parent config objects.
621 protected $parent_configs = array();
624 * Used to determine whether we can serve SVG images or not.
627 private $usesvg = null;
630 * Whether in RTL mode or not.
633 protected $rtlmode = false;
636 * The SCSS file to compile (without .scss), located in the scss/ folder of the theme.
637 * Or a Closure, which receives the theme_config as argument and must
638 * return the SCSS content.
639 * @var string|Closure
641 public $scss = false;
644 * Local cache of the SCSS property.
647 protected $scsscache = null;
650 * The name of the function to call to get the SCSS code to inject.
653 public $extrascsscallback = null;
656 * The name of the function to call to get SCSS to prepend.
659 public $prescsscallback = null;
662 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
663 * Defaults to {@link core_renderer::blocks_for_region()}
666 public $blockrendermethod = null;
669 * Remember the results of icon remapping for the current page.
672 public $remapiconcache = [];
675 * The name of the function to call to get precompiled CSS.
678 public $precompiledcsscallback = null;
681 * Whether the theme uses course index.
684 public $usescourseindex = false;
687 * Configuration for the page activity header
690 public $activityheaderconfig = [];
693 * Load the config.php file for a particular theme, and return an instance
694 * of this class. (That is, this is a factory method.)
696 * @param string $themename the name of the theme.
697 * @return theme_config an instance of this class.
699 public static function load($themename) {
702 // load theme settings from db
704 $settings = get_config('theme_'.$themename);
705 } catch (dml_exception
$e) {
706 // most probably moodle tables not created yet
707 $settings = new stdClass();
710 if ($config = theme_config
::find_theme_config($themename, $settings)) {
711 return new theme_config($config);
713 } else if ($themename == theme_config
::DEFAULT_THEME
) {
714 throw new coding_exception('Default theme '.theme_config
::DEFAULT_THEME
.' not available or broken!');
716 } else if ($config = theme_config
::find_theme_config($CFG->theme
, $settings)) {
717 debugging('This page should be using theme ' . $themename .
718 ' which cannot be initialised. Falling back to the site theme ' . $CFG->theme
, DEBUG_NORMAL
);
719 return new theme_config($config);
722 // bad luck, the requested theme has some problems - admin see details in theme config
723 debugging('This page should be using theme ' . $themename .
724 ' which cannot be initialised. Nor can the site theme ' . $CFG->theme
.
725 '. Falling back to ' . theme_config
::DEFAULT_THEME
, DEBUG_NORMAL
);
726 return new theme_config(theme_config
::find_theme_config(theme_config
::DEFAULT_THEME
, $settings));
731 * Theme diagnostic code. It is very problematic to send debug output
732 * to the actual CSS file, instead this functions is supposed to
733 * diagnose given theme and highlights all potential problems.
734 * This information should be available from the theme selection page
735 * or some other debug page for theme designers.
737 * @param string $themename
738 * @return array description of problems
740 public static function diagnose($themename) {
746 * Private constructor, can be called only from the factory method.
747 * @param stdClass $config
749 private function __construct($config) {
750 global $CFG; //needed for included lib.php files
752 $this->settings
= $config->settings
;
753 $this->name
= $config->name
;
754 $this->dir
= $config->dir
;
756 if ($this->name
!= self
::DEFAULT_THEME
) {
757 $baseconfig = self
::find_theme_config(self
::DEFAULT_THEME
, $this->settings
);
759 $baseconfig = $config;
763 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'usefallback',
764 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
765 'layouts', 'enablecourseajax', 'requiredblocks',
766 'rendererfactory', 'csspostprocess', 'editor_sheets', 'editor_scss', 'rarrow', 'larrow', 'uarrow', 'darrow',
767 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations', 'blockrendermethod',
768 'scss', 'extrascsscallback', 'prescsscallback', 'csstreepostprocessor', 'addblockposition',
769 'iconsystem', 'precompiledcsscallback', 'haseditswitch', 'usescourseindex', 'activityheaderconfig',
770 'removedprimarynavitems',
773 foreach ($config as $key=>$value) {
774 if (in_array($key, $configurable)) {
775 $this->$key = $value;
779 // verify all parents and load configs and renderers
780 foreach ($this->parents
as $parent) {
781 if (!$parent_config = theme_config
::find_theme_config($parent, $this->settings
)) {
782 // this is not good - better exclude faulty parents
785 $libfile = $parent_config->dir
.'/lib.php';
786 if (is_readable($libfile)) {
787 // theme may store various function here
788 include_once($libfile);
790 $renderersfile = $parent_config->dir
.'/renderers.php';
791 if (is_readable($renderersfile)) {
792 // may contain core and plugin renderers and renderer factory
793 include_once($renderersfile);
795 $this->parent_configs
[$parent] = $parent_config;
797 $libfile = $this->dir
.'/lib.php';
798 if (is_readable($libfile)) {
799 // theme may store various function here
800 include_once($libfile);
802 $rendererfile = $this->dir
.'/renderers.php';
803 if (is_readable($rendererfile)) {
804 // may contain core and plugin renderers and renderer factory
805 include_once($rendererfile);
807 // check if renderers.php file is missnamed renderer.php
808 if (is_readable($this->dir
.'/renderer.php')) {
809 debugging('Developer hint: '.$this->dir
.'/renderer.php should be renamed to ' . $this->dir
."/renderers.php.
810 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER
);
814 // cascade all layouts properly
815 foreach ($baseconfig->layouts
as $layout=>$value) {
816 if (!isset($this->layouts
[$layout])) {
817 foreach ($this->parent_configs
as $parent_config) {
818 if (isset($parent_config->layouts
[$layout])) {
819 $this->layouts
[$layout] = $parent_config->layouts
[$layout];
823 $this->layouts
[$layout] = $value;
827 //fix arrows if needed
828 $this->check_theme_arrows();
832 * Let the theme initialise the page object (usually $PAGE).
834 * This may be used for example to request jQuery in add-ons.
836 * @param moodle_page $page
838 public function init_page(moodle_page
$page) {
839 $themeinitfunction = 'theme_'.$this->name
.'_page_init';
840 if (function_exists($themeinitfunction)) {
841 $themeinitfunction($page);
846 * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow, $THEME->darrow have been set (theme/-/config.php).
847 * If not it applies sensible defaults.
849 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
850 * search forum block, etc. Important: these are 'silent' in a screen-reader
851 * (unlike > »), and must be accompanied by text.
853 private function check_theme_arrows() {
854 if (!isset($this->rarrow
) and !isset($this->larrow
)) {
855 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
856 // Also OK in Win 9x/2K/IE 5.x
857 $this->rarrow
= '►';
858 $this->larrow
= '◄';
859 $this->uarrow
= '▲';
860 $this->darrow
= '▼';
861 if (empty($_SERVER['HTTP_USER_AGENT'])) {
864 $uagent = $_SERVER['HTTP_USER_AGENT'];
866 if (false !== strpos($uagent, 'Opera')
867 ||
false !== strpos($uagent, 'Mac')) {
868 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
869 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
870 $this->rarrow
= '▶︎';
871 $this->larrow
= '◀︎';
873 elseif ((false !== strpos($uagent, 'Konqueror'))
874 ||
(false !== strpos($uagent, 'Android'))) {
875 // The fonts on Android don't include the characters required for this to work as expected.
876 // So we use the same ones Konqueror uses.
877 $this->rarrow
= '→';
878 $this->larrow
= '←';
879 $this->uarrow
= '↑';
880 $this->darrow
= '↓';
882 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
883 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
884 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
885 // To be safe, non-Unicode browsers!
886 $this->rarrow
= '>';
887 $this->larrow
= '<';
892 // RTL support - in RTL languages, swap r and l arrows
893 if (right_to_left()) {
895 $this->rarrow
= $this->larrow
;
902 * Returns output renderer prefixes, these are used when looking
903 * for the overridden renderers in themes.
907 public function renderer_prefixes() {
908 global $CFG; // just in case the included files need it
910 $prefixes = array('theme_'.$this->name
);
912 foreach ($this->parent_configs
as $parent) {
913 $prefixes[] = 'theme_'.$parent->name
;
920 * Returns the stylesheet URL of this editor content
922 * @param bool $encoded false means use & and true use & in URLs
925 public function editor_css_url($encoded=true) {
927 $rev = theme_get_revision();
929 $themesubrevision = theme_get_sub_revision_for_theme($this->name
);
931 // Provide the sub revision to allow us to invalidate cached theme CSS
932 // on a per theme basis, rather than globally.
933 if ($themesubrevision && $themesubrevision > 0) {
934 $rev .= "_{$themesubrevision}";
937 $url = new moodle_url("/theme/styles.php");
938 if (!empty($CFG->slasharguments
)) {
939 $url->set_slashargument('/'.$this->name
.'/'.$rev.'/editor', 'noparam', true);
941 $url->params(array('theme'=>$this->name
,'rev'=>$rev, 'type'=>'editor'));
944 $params = array('theme'=>$this->name
, 'type'=>'editor');
945 $url = new moodle_url('/theme/styles_debug.php', $params);
951 * Returns the content of the CSS to be used in editor content
955 public function editor_css_files() {
958 // First editor plugins.
959 $plugins = core_component
::get_plugin_list('editor');
960 foreach ($plugins as $plugin => $fulldir) {
961 $sheetfile = "$fulldir/editor_styles.css";
962 if (is_readable($sheetfile)) {
963 $files['plugin_'.$plugin] = $sheetfile;
966 $subplugintypes = core_component
::get_subplugins("editor_{$plugin}");
967 // Fetch sheets for any editor subplugins.
968 foreach ($subplugintypes as $plugintype => $subplugins) {
969 foreach ($subplugins as $subplugin) {
970 $plugindir = core_component
::get_plugin_directory($plugintype, $subplugin);
971 $sheetfile = "{$plugindir}/editor_styles.css";
972 if (is_readable($sheetfile)) {
973 $files["{$plugintype}_{$subplugin}"] = $sheetfile;
979 // Then parent themes - base first, the immediate parent last.
980 foreach (array_reverse($this->parent_configs
) as $parent_config) {
981 if (empty($parent_config->editor_sheets
)) {
984 foreach ($parent_config->editor_sheets
as $sheet) {
985 $sheetfile = "$parent_config->dir/style/$sheet.css";
986 if (is_readable($sheetfile)) {
987 $files['parent_'.$parent_config->name
.'_'.$sheet] = $sheetfile;
991 // Finally this theme.
992 if (!empty($this->editor_sheets
)) {
993 foreach ($this->editor_sheets
as $sheet) {
994 $sheetfile = "$this->dir/style/$sheet.css";
995 if (is_readable($sheetfile)) {
996 $files['theme_'.$sheet] = $sheetfile;
1005 * Compiles and returns the content of the SCSS to be used in editor content
1007 * @return string Compiled CSS from the editor SCSS
1009 public function editor_scss_to_css() {
1014 // Use editor_scss file(s) provided by this theme if set.
1015 if (!empty($this->editor_scss
)) {
1016 $filenames = $this->editor_scss
;
1018 // If no editor_scss set, move up theme hierarchy until one is found (if at all).
1019 // This is so child themes only need to set editor_scss if an override is required.
1020 foreach (array_reverse($this->parent_configs
) as $parentconfig) {
1021 if (!empty($parentconfig->editor_scss
)) {
1022 $dir = $parentconfig->dir
;
1023 $filenames = $parentconfig->editor_scss
;
1025 // Config found, stop looking.
1031 if (!empty($filenames)) {
1032 $compiler = new core_scss();
1034 foreach ($filenames as $filename) {
1035 $compiler->set_file("{$dir}/scss/{$filename}.scss");
1038 $css .= $compiler->to_css();
1039 } catch (\Exception
$e) {
1040 debugging('Error while compiling editor SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER
);
1049 * Get the stylesheet URL of this theme.
1051 * @param moodle_page $page Not used... deprecated?
1052 * @return moodle_url[]
1054 public function css_urls(moodle_page
$page) {
1057 $rev = theme_get_revision();
1061 $svg = $this->use_svg_icons();
1062 $separate = (core_useragent
::is_ie() && !core_useragent
::check_ie_version('10'));
1065 $filename = right_to_left() ?
'all-rtl' : 'all';
1066 $url = new moodle_url("/theme/styles.php");
1067 $themesubrevision = theme_get_sub_revision_for_theme($this->name
);
1069 // Provide the sub revision to allow us to invalidate cached theme CSS
1070 // on a per theme basis, rather than globally.
1071 if ($themesubrevision && $themesubrevision > 0) {
1072 $rev .= "_{$themesubrevision}";
1075 if (!empty($CFG->slasharguments
)) {
1078 // We add a simple /_s to the start of the path.
1079 // The underscore is used to ensure that it isn't a valid theme name.
1080 $slashargs .= '/_s'.$slashargs;
1082 $slashargs .= '/'.$this->name
.'/'.$rev.'/'.$filename;
1084 $slashargs .= '/chunk0';
1086 $url->set_slashargument($slashargs, 'noparam', true);
1088 $params = array('theme' => $this->name
, 'rev' => $rev, 'type' => $filename);
1090 // We add an SVG param so that we know not to serve SVG images.
1091 // We do this because all modern browsers support SVG and this param will one day be removed.
1092 $params['svg'] = '0';
1095 $params['chunk'] = '0';
1097 $url->params($params);
1102 $baseurl = new moodle_url('/theme/styles_debug.php');
1104 $css = $this->get_css_files(true);
1106 // We add an SVG param so that we know not to serve SVG images.
1107 // We do this because all modern browsers support SVG and this param will one day be removed.
1108 $baseurl->param('svg', '0');
1110 if (right_to_left()) {
1111 $baseurl->param('rtl', 1);
1114 // We might need to chunk long files.
1115 $baseurl->param('chunk', '0');
1117 if (core_useragent
::is_ie()) {
1118 // Lalala, IE does not allow more than 31 linked CSS files from main document.
1119 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
, 'type'=>'ie', 'subtype'=>'plugins'));
1120 foreach ($css['parents'] as $parent=>$sheets) {
1121 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
1122 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
1124 if ($this->get_scss_property()) {
1125 // No need to define the type as IE here.
1126 $urls[] = new moodle_url($baseurl, array('theme' => $this->name
, 'type' => 'scss'));
1128 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
, 'type'=>'ie', 'subtype'=>'theme'));
1131 foreach ($css['plugins'] as $plugin=>$unused) {
1132 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
,'type'=>'plugin', 'subtype'=>$plugin));
1134 foreach ($css['parents'] as $parent=>$sheets) {
1135 foreach ($sheets as $sheet=>$unused2) {
1136 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
1139 foreach ($css['theme'] as $sheet => $filename) {
1140 if ($sheet === self
::SCSS_KEY
) {
1141 // This is the theme SCSS file.
1142 $urls[] = new moodle_url($baseurl, array('theme' => $this->name
, 'type' => 'scss'));
1144 // Sheet first in order to make long urls easier to read.
1145 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name
, 'type'=>'theme'));
1151 // Allow themes to change the css url to something like theme/mytheme/mycss.php.
1152 component_callback('theme_' . $this->name
, 'alter_css_urls', [&$urls]);
1157 * Get the whole css stylesheet for production mode.
1159 * NOTE: this method is not expected to be used from any addons.
1161 * @return string CSS markup compressed
1163 public function get_css_content() {
1166 foreach ($this->get_css_files(false) as $type => $value) {
1167 foreach ($value as $identifier => $val) {
1168 if (is_array($val)) {
1169 foreach ($val as $v) {
1170 $csscontent .= file_get_contents($v) . "\n";
1173 if ($type === 'theme' && $identifier === self
::SCSS_KEY
) {
1174 // We need the content from SCSS because this is the SCSS file from the theme.
1175 if ($compiled = $this->get_css_content_from_scss(false)) {
1176 $csscontent .= $compiled;
1178 // The compiler failed so default back to any precompiled css that might
1180 $csscontent .= $this->get_precompiled_css_content();
1183 $csscontent .= file_get_contents($val) . "\n";
1188 $csscontent = $this->post_process($csscontent);
1189 $csscontent = core_minify
::css($csscontent);
1194 * Set post processed CSS content cache.
1196 * @param string $csscontent The post processed CSS content.
1197 * @return bool True if the content was successfully cached.
1199 public function set_css_content_cache($csscontent) {
1201 $cache = cache
::make('core', 'postprocessedcss');
1202 $key = $this->get_css_cache_key();
1204 return $cache->set($key, $csscontent);
1208 * Return whether the post processed CSS content has been cached.
1210 * @return bool Whether the post-processed CSS is available in the cache.
1212 public function has_css_cached_content() {
1214 $key = $this->get_css_cache_key();
1215 $cache = cache
::make('core', 'postprocessedcss');
1217 return $cache->has($key);
1221 * Return cached post processed CSS content.
1223 * @return bool|string The cached css content or false if not found.
1225 public function get_css_cached_content() {
1227 $key = $this->get_css_cache_key();
1228 $cache = cache
::make('core', 'postprocessedcss');
1230 return $cache->get($key);
1234 * Generate the css content cache key.
1236 * @return string The post processed css cache key.
1238 public function get_css_cache_key() {
1239 $nosvg = (!$this->use_svg_icons()) ?
'nosvg_' : '';
1240 $rtlmode = ($this->rtlmode
== true) ?
'rtl' : 'ltr';
1242 return $nosvg . $this->name
. '_' . $rtlmode;
1246 * Get the theme designer css markup,
1247 * the parameters are coming from css_urls().
1249 * NOTE: this method is not expected to be used from any addons.
1251 * @param string $type
1252 * @param string $subtype
1253 * @param string $sheet
1254 * @return string CSS markup
1256 public function get_css_content_debug($type, $subtype, $sheet) {
1257 if ($type === 'scss') {
1258 // The SCSS file of the theme is requested.
1259 $csscontent = $this->get_css_content_from_scss(true);
1260 if ($csscontent !== false) {
1261 return $this->post_process($csscontent);
1266 $cssfiles = array();
1267 $css = $this->get_css_files(true);
1269 if ($type === 'ie') {
1270 // IE is a sloppy browser with weird limits, sorry.
1271 if ($subtype === 'plugins') {
1272 $cssfiles = $css['plugins'];
1274 } else if ($subtype === 'parents') {
1275 if (empty($sheet)) {
1276 // Do not bother with the empty parent here.
1278 // Build up the CSS for that parent so we can serve it as one file.
1279 foreach ($css[$subtype][$sheet] as $parent => $css) {
1283 } else if ($subtype === 'theme') {
1284 $cssfiles = $css['theme'];
1285 foreach ($cssfiles as $key => $value) {
1286 if (in_array($key, [self
::SCSS_KEY
])) {
1287 // Remove the SCSS file from the theme CSS files.
1288 // The SCSS files use the type 'scss', not 'ie'.
1289 unset($cssfiles[$key]);
1294 } else if ($type === 'plugin') {
1295 if (isset($css['plugins'][$subtype])) {
1296 $cssfiles[] = $css['plugins'][$subtype];
1299 } else if ($type === 'parent') {
1300 if (isset($css['parents'][$subtype][$sheet])) {
1301 $cssfiles[] = $css['parents'][$subtype][$sheet];
1304 } else if ($type === 'theme') {
1305 if (isset($css['theme'][$sheet])) {
1306 $cssfiles[] = $css['theme'][$sheet];
1311 foreach ($cssfiles as $file) {
1312 $contents = file_get_contents($file);
1313 $contents = $this->post_process($contents);
1314 $comment = "/** Path: $type $subtype $sheet.' **/\n";
1316 $csscontent .= $comment.$stats.$contents."\n\n";
1323 * Get the whole css stylesheet for editor iframe.
1325 * NOTE: this method is not expected to be used from any addons.
1327 * @return string CSS markup
1329 public function get_css_content_editor() {
1331 $cssfiles = $this->editor_css_files();
1333 // If editor has static CSS, include it.
1334 foreach ($cssfiles as $file) {
1335 $css .= file_get_contents($file)."\n";
1338 // If editor has SCSS, compile and include it.
1339 if (($convertedscss = $this->editor_scss_to_css())) {
1340 $css .= $convertedscss;
1343 $output = $this->post_process($css);
1349 * Returns an array of organised CSS files required for this output.
1351 * @param bool $themedesigner
1352 * @return array nested array of file paths
1354 protected function get_css_files($themedesigner) {
1358 $cachekey = 'cssfiles';
1359 if ($themedesigner) {
1360 require_once($CFG->dirroot
.'/lib/csslib.php');
1361 // We need some kind of caching here because otherwise the page navigation becomes
1362 // way too slow in theme designer mode. Feel free to create full cache definition later...
1363 $cache = cache
::make_from_params(cache_store
::MODE_APPLICATION
, 'core', 'themedesigner', array('theme' => $this->name
));
1364 if ($files = $cache->get($cachekey)) {
1365 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME
) {
1366 unset($files['created']);
1372 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
1374 // Get all plugin sheets.
1375 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
1376 if ($excludes !== true) {
1377 foreach (core_component
::get_plugin_types() as $type=>$unused) {
1378 if ($type === 'theme' ||
(!empty($excludes[$type]) and $excludes[$type] === true)) {
1381 $plugins = core_component
::get_plugin_list($type);
1382 foreach ($plugins as $plugin=>$fulldir) {
1383 if (!empty($excludes[$type]) and is_array($excludes[$type])
1384 and in_array($plugin, $excludes[$type])) {
1388 // Get the CSS from the plugin.
1389 $sheetfile = "$fulldir/styles.css";
1390 if (is_readable($sheetfile)) {
1391 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
1394 // Create a list of candidate sheets from parents (direct parent last) and current theme.
1395 $candidates = array();
1396 foreach (array_reverse($this->parent_configs
) as $parent_config) {
1397 $candidates[] = $parent_config->name
;
1399 $candidates[] = $this->name
;
1401 // Add the sheets found.
1402 foreach ($candidates as $candidate) {
1403 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1404 if (is_readable($sheetthemefile)) {
1405 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
1412 // Find out wanted parent sheets.
1413 $excludes = $this->resolve_excludes('parents_exclude_sheets');
1414 if ($excludes !== true) {
1415 foreach (array_reverse($this->parent_configs
) as $parent_config) { // Base first, the immediate parent last.
1416 $parent = $parent_config->name
;
1417 if (empty($parent_config->sheets
) ||
(!empty($excludes[$parent]) and $excludes[$parent] === true)) {
1420 foreach ($parent_config->sheets
as $sheet) {
1421 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1422 && in_array($sheet, $excludes[$parent])) {
1426 // We never refer to the parent LESS files.
1427 $sheetfile = "$parent_config->dir/style/$sheet.css";
1428 if (is_readable($sheetfile)) {
1429 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1436 // Current theme sheets.
1437 // We first add the SCSS file because we want the CSS ones to
1438 // be included after the SCSS code.
1439 if ($this->get_scss_property()) {
1440 $cssfiles['theme'][self
::SCSS_KEY
] = true;
1442 if (is_array($this->sheets
)) {
1443 foreach ($this->sheets
as $sheet) {
1444 $sheetfile = "$this->dir/style/$sheet.css";
1445 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1446 $cssfiles['theme'][$sheet] = $sheetfile;
1453 $files['created'] = time();
1454 $cache->set($cachekey, $files);
1460 * Return the CSS content generated from the SCSS file.
1462 * @param bool $themedesigner True if theme designer is enabled.
1463 * @return bool|string Return false when the compilation failed. Else the compiled string.
1465 protected function get_css_content_from_scss($themedesigner) {
1468 list($paths, $scss) = $this->get_scss_property();
1470 throw new coding_exception('The theme did not define a SCSS file, or it is not readable.');
1473 // We might need more memory/time to do this, so let's play safe.
1474 raise_memory_limit(MEMORY_EXTRA
);
1475 core_php_time_limit
::raise(300);
1477 // TODO: MDL-62757 When changing anything in this method please do not forget to check
1478 // if the validate() method in class admin_setting_configthemepreset needs updating too.
1480 $cachedir = make_localcache_directory('scsscache-' . $this->name
, false);
1482 if ($themedesigner) {
1483 $cacheoptions = array(
1484 'cacheDir' => $cachedir,
1485 'prefix' => 'scssphp_',
1486 'forceRefresh' => false,
1489 if (file_exists($cachedir)) {
1490 remove_dir($cachedir);
1494 // Set-up the compiler.
1495 $compiler = new core_scss($cacheoptions);
1497 if ($this->supports_source_maps($themedesigner)) {
1498 // Enable source maps.
1499 $compiler->setSourceMapOptions([
1500 'sourceMapBasepath' => str_replace('\\', '/', $CFG->dirroot
),
1501 'sourceMapRootpath' => $CFG->wwwroot
. '/'
1503 $compiler->setSourceMap($compiler::SOURCE_MAP_INLINE
);
1506 $compiler->prepend_raw_scss($this->get_pre_scss_code());
1507 if (is_string($scss)) {
1508 $compiler->set_file($scss);
1510 $compiler->append_raw_scss($scss($this));
1511 $compiler->setImportPaths($paths);
1513 $compiler->append_raw_scss($this->get_extra_scss_code());
1517 $compiled = $compiler->to_css();
1519 } catch (\Exception
$e) {
1521 debugging('Error while compiling SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER
);
1524 // Try to save memory.
1532 * Return the precompiled CSS if the precompiledcsscallback exists.
1534 * @return string Return compiled css.
1536 public function get_precompiled_css_content() {
1537 $configs = array_reverse($this->parent_configs
) +
[$this];
1540 foreach ($configs as $config) {
1541 if (isset($config->precompiledcsscallback
)) {
1542 $function = $config->precompiledcsscallback
;
1543 if (function_exists($function)) {
1544 $css .= $function($this);
1552 * Get the icon system to use.
1556 public function get_icon_system() {
1558 // Getting all the candidate functions.
1560 if (isset($this->iconsystem
) && \core\output\icon_system
::is_valid_system($this->iconsystem
)) {
1561 return $this->iconsystem
;
1563 foreach ($this->parent_configs
as $parent_config) {
1564 if (isset($parent_config->iconsystem
) && \core\output\icon_system
::is_valid_system($parent_config->iconsystem
)) {
1565 return $parent_config->iconsystem
;
1568 return \core\output\icon_system
::STANDARD
;
1572 * Return extra SCSS code to add when compiling.
1574 * This is intended to be used by themes to inject some SCSS code
1575 * before it gets compiled. If you want to inject variables you
1576 * should use {@link self::get_scss_variables()}.
1578 * @return string The SCSS code to inject.
1580 public function get_extra_scss_code() {
1583 // Getting all the candidate functions.
1584 $candidates = array();
1585 foreach ($this->parent_configs
as $parent_config) {
1586 if (!isset($parent_config->extrascsscallback
)) {
1589 $candidates[] = $parent_config->extrascsscallback
;
1591 $candidates[] = $this->extrascsscallback
;
1593 // Calling the functions.
1594 foreach ($candidates as $function) {
1595 if (function_exists($function)) {
1596 $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n";
1604 * SCSS code to prepend when compiling.
1606 * This is intended to be used by themes to inject SCSS code before it gets compiled.
1608 * @return string The SCSS code to inject.
1610 public function get_pre_scss_code() {
1613 // Getting all the candidate functions.
1614 $candidates = array();
1615 foreach ($this->parent_configs
as $parent_config) {
1616 if (!isset($parent_config->prescsscallback
)) {
1619 $candidates[] = $parent_config->prescsscallback
;
1621 $candidates[] = $this->prescsscallback
;
1623 // Calling the functions.
1624 foreach ($candidates as $function) {
1625 if (function_exists($function)) {
1626 $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n";
1634 * Get the SCSS property.
1636 * This resolves whether a SCSS file (or content) has to be used when generating
1637 * the stylesheet for the theme. It will look at parents themes and check the
1638 * SCSS properties there.
1640 * @return False when SCSS is not used.
1641 * An array with the import paths, and the path to the SCSS file or Closure as second.
1643 public function get_scss_property() {
1644 if ($this->scsscache
=== null) {
1645 $configs = [$this] +
$this->parent_configs
;
1648 foreach ($configs as $config) {
1649 $path = "{$config->dir}/scss";
1651 // We collect the SCSS property until we've found one.
1652 if (empty($scss) && !empty($config->scss
)) {
1653 $candidate = is_string($config->scss
) ?
"{$path}/{$config->scss}.scss" : $config->scss
;
1654 if ($candidate instanceof Closure
) {
1656 } else if (is_string($candidate) && is_readable($candidate)) {
1661 // We collect the import paths once we've found a SCSS property.
1662 if ($scss && is_dir($path)) {
1668 $this->scsscache
= $scss !== null ?
[$paths, $scss] : false;
1671 return $this->scsscache
;
1675 * Generate a URL to the file that serves theme JavaScript files.
1677 * If we determine that the theme has no relevant files, then we return
1678 * early with a null value.
1680 * @param bool $inhead true means head url, false means footer
1681 * @return moodle_url|null
1683 public function javascript_url($inhead) {
1686 $rev = theme_get_revision();
1687 $params = array('theme'=>$this->name
,'rev'=>$rev);
1688 $params['type'] = $inhead ?
'head' : 'footer';
1690 // Return early if there are no files to serve
1691 if (count($this->javascript_files($params['type'])) === 0) {
1695 if (!empty($CFG->slasharguments
) and $rev > 0) {
1696 $url = new moodle_url("/theme/javascript.php");
1697 $url->set_slashargument('/'.$this->name
.'/'.$rev.'/'.$params['type'], 'noparam', true);
1700 return new moodle_url('/theme/javascript.php', $params);
1705 * Get the URL's for the JavaScript files used by this theme.
1706 * They won't be served directly, instead they'll be mediated through
1707 * theme/javascript.php.
1709 * @param string $type Either javascripts_footer, or javascripts
1712 public function javascript_files($type) {
1713 if ($type === 'footer') {
1714 $type = 'javascripts_footer';
1716 $type = 'javascripts';
1720 // find out wanted parent javascripts
1721 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1722 if ($excludes !== true) {
1723 foreach (array_reverse($this->parent_configs
) as $parent_config) { // base first, the immediate parent last
1724 $parent = $parent_config->name
;
1725 if (empty($parent_config->$type)) {
1728 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1731 foreach ($parent_config->$type as $javascript) {
1732 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1733 and in_array($javascript, $excludes[$parent])) {
1736 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1737 if (is_readable($javascriptfile)) {
1738 $js[] = $javascriptfile;
1744 // current theme javascripts
1745 if (is_array($this->$type)) {
1746 foreach ($this->$type as $javascript) {
1747 $javascriptfile = "$this->dir/javascript/$javascript.js";
1748 if (is_readable($javascriptfile)) {
1749 $js[] = $javascriptfile;
1757 * Resolves an exclude setting to the themes setting is applicable or the
1758 * setting of its closest parent.
1760 * @param string $variable The name of the setting the exclude setting to resolve
1761 * @param string $default
1764 protected function resolve_excludes($variable, $default = null) {
1765 $setting = $default;
1766 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1767 $setting = $this->{$variable};
1769 foreach ($this->parent_configs
as $parent_config) { // the immediate parent first, base last
1770 if (!isset($parent_config->{$variable})) {
1773 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1774 $setting = $parent_config->{$variable};
1783 * Returns the content of the one huge javascript file merged from all theme javascript files.
1788 public function javascript_content($type) {
1789 $jsfiles = $this->javascript_files($type);
1791 foreach ($jsfiles as $jsfile) {
1792 $js .= file_get_contents($jsfile)."\n";
1798 * Post processes CSS.
1800 * This method post processes all of the CSS before it is served for this theme.
1801 * This is done so that things such as image URL's can be swapped in and to
1802 * run any specific CSS post process method the theme has requested.
1803 * This allows themes to use CSS settings.
1805 * @param string $css The CSS to process.
1806 * @return string The processed CSS.
1808 public function post_process($css) {
1809 // now resolve all image locations
1810 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER
)) {
1811 $replaced = array();
1812 foreach ($matches as $match) {
1813 if (isset($replaced[$match[0]])) {
1816 $replaced[$match[0]] = true;
1817 $imagename = $match[2];
1818 $component = rtrim($match[1], '|');
1819 $imageurl = $this->image_url($imagename, $component)->out(false);
1820 // we do not need full url because the image.php is always in the same dir
1821 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1822 $css = str_replace($match[0], $imageurl, $css);
1826 // Now resolve all font locations.
1827 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER
)) {
1828 $replaced = array();
1829 foreach ($matches as $match) {
1830 if (isset($replaced[$match[0]])) {
1833 $replaced[$match[0]] = true;
1834 $fontname = $match[2];
1835 $component = rtrim($match[1], '|');
1836 $fonturl = $this->font_url($fontname, $component)->out(false);
1837 // We do not need full url because the font.php is always in the same dir.
1838 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1839 $css = str_replace($match[0], $fonturl, $css);
1843 // Now resolve all theme settings or do any other postprocessing.
1844 // This needs to be done before calling core parser, since the parser strips [[settings]] tags.
1845 $csspostprocess = $this->csspostprocess
;
1846 if (function_exists($csspostprocess)) {
1847 $css = $csspostprocess($css, $this);
1850 // Post processing using an object representation of CSS.
1851 $treeprocessor = $this->get_css_tree_post_processor();
1852 $needsparsing = !empty($treeprocessor) ||
!empty($this->rtlmode
);
1853 if ($needsparsing) {
1855 // We might need more memory/time to do this, so let's play safe.
1856 raise_memory_limit(MEMORY_EXTRA
);
1857 core_php_time_limit
::raise(300);
1859 $parser = new core_cssparser($css);
1860 $csstree = $parser->parse();
1863 if ($this->rtlmode
) {
1864 $this->rtlize($csstree);
1867 if ($treeprocessor) {
1868 $treeprocessor($csstree, $this);
1871 $css = $csstree->render();
1879 * Flip a stylesheet to RTL.
1881 * @param Object $csstree The parsed CSS tree structure to flip.
1884 protected function rtlize($csstree) {
1885 $rtlcss = new core_rtlcss($csstree);
1890 * Return the direct URL for an image from the pix folder.
1892 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1894 * @deprecated since Moodle 3.3
1895 * @param string $imagename the name of the icon.
1896 * @param string $component specification of one plugin like in get_string()
1897 * @return moodle_url
1899 public function pix_url($imagename, $component) {
1900 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER
);
1901 return $this->image_url($imagename, $component);
1905 * Return the direct URL for an image from the pix folder.
1907 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1909 * @param string $imagename the name of the icon.
1910 * @param string $component specification of one plugin like in get_string()
1911 * @return moodle_url
1913 public function image_url($imagename, $component) {
1916 $params = array('theme'=>$this->name
);
1917 $svg = $this->use_svg_icons();
1919 if (empty($component) or $component === 'moodle' or $component === 'core') {
1920 $params['component'] = 'core';
1922 $params['component'] = $component;
1925 $rev = theme_get_revision();
1927 $params['rev'] = $rev;
1930 $params['image'] = $imagename;
1932 $url = new moodle_url("/theme/image.php");
1933 if (!empty($CFG->slasharguments
) and $rev > 0) {
1934 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1936 // We add a simple /_s to the start of the path.
1937 // The underscore is used to ensure that it isn't a valid theme name.
1938 $path = '/_s'.$path;
1940 $url->set_slashargument($path, 'noparam', true);
1943 // We add an SVG param so that we know not to serve SVG images.
1944 // We do this because all modern browsers support SVG and this param will one day be removed.
1945 $params['svg'] = '0';
1947 $url->params($params);
1954 * Return the URL for a font
1956 * @param string $font the name of the font (including extension).
1957 * @param string $component specification of one plugin like in get_string()
1958 * @return moodle_url
1960 public function font_url($font, $component) {
1963 $params = array('theme'=>$this->name
);
1965 if (empty($component) or $component === 'moodle' or $component === 'core') {
1966 $params['component'] = 'core';
1968 $params['component'] = $component;
1971 $rev = theme_get_revision();
1973 $params['rev'] = $rev;
1976 $params['font'] = $font;
1978 $url = new moodle_url("/theme/font.php");
1979 if (!empty($CFG->slasharguments
) and $rev > 0) {
1980 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1981 $url->set_slashargument($path, 'noparam', true);
1983 $url->params($params);
1990 * Returns URL to the stored file via pluginfile.php.
1992 * Note the theme must also implement pluginfile.php handler,
1993 * theme revision is used instead of the itemid.
1995 * @param string $setting
1996 * @param string $filearea
1997 * @return string protocol relative URL or null if not present
1999 public function setting_file_url($setting, $filearea) {
2002 if (empty($this->settings
->$setting)) {
2006 $component = 'theme_'.$this->name
;
2007 $itemid = theme_get_revision();
2008 $filepath = $this->settings
->$setting;
2009 $syscontext = context_system
::instance();
2011 $url = moodle_url
::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
2013 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
2014 // Note: unfortunately moodle_url does not support //urls yet.
2016 $url = preg_replace('|^https?://|i', '//', $url->out(false));
2022 * Serve the theme setting file.
2024 * @param string $filearea
2025 * @param array $args
2026 * @param bool $forcedownload
2027 * @param array $options
2028 * @return bool may terminate if file not found or donotdie not specified
2030 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
2032 require_once("$CFG->libdir/filelib.php");
2034 $syscontext = context_system
::instance();
2035 $component = 'theme_'.$this->name
;
2037 $revision = array_shift($args);
2038 if ($revision < 0) {
2041 $lifetime = 60*60*24*60;
2042 // By default, theme files must be cache-able by both browsers and proxies.
2043 if (!array_key_exists('cacheability', $options)) {
2044 $options['cacheability'] = 'public';
2048 $fs = get_file_storage();
2049 $relativepath = implode('/', $args);
2051 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
2052 $fullpath = rtrim($fullpath, '/');
2053 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
2054 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
2057 send_file_not_found();
2062 * Resolves the real image location.
2064 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
2065 * and we need a way in which to turn it off.
2066 * By default SVG won't be used unless asked for. This is done for two reasons:
2067 * 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
2068 * browser supports SVG.
2069 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
2070 * by the user due to security concerns.
2072 * @param string $image name of image, may contain relative path
2073 * @param string $component
2074 * @param bool $svg|null Should SVG images also be looked for? If null, resorts to $CFG->svgicons if that is set; falls back to
2075 * auto-detection of browser support otherwise
2076 * @return string full file path
2078 public function resolve_image_location($image, $component, $svg = false) {
2081 if (!is_bool($svg)) {
2082 // If $svg isn't a bool then we need to decide for ourselves.
2083 $svg = $this->use_svg_icons();
2086 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2087 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
2090 foreach (array_reverse($this->parent_configs
) as $parent_config) { // base first, the immediate parent last
2091 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
2095 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
2098 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
2103 } else if ($component === 'theme') { //exception
2104 if ($image === 'favicon') {
2105 return "$this->dir/pix/favicon.ico";
2107 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
2110 foreach (array_reverse($this->parent_configs
) as $parent_config) { // base first, the immediate parent last
2111 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
2118 if (strpos($component, '_') === false) {
2119 $component = "mod_{$component}";
2121 list($type, $plugin) = explode('_', $component, 2);
2123 // In Moodle 4.0 we introduced a new image format.
2124 // Support that image format here.
2125 $candidates = [$image];
2127 if ($type === 'mod') {
2128 if ($image === 'icon' ||
$image === 'monologo') {
2129 $candidates = ['monologo', 'icon'];
2130 if ($image === 'icon') {
2132 "The 'icon' image for activity modules has been replaced with a new 'monologo'. " .
2133 "Please update your calling code to fetch the new icon where possible. " .
2134 "Called for component {$component}.",
2140 foreach ($candidates as $image) {
2141 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2145 // Base first, the immediate parent last.
2146 foreach (array_reverse($this->parent_configs
) as $parentconfig) {
2147 if ($imagefile = $this->image_exists("$parentconfig->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2151 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
2154 $dir = core_component
::get_plugin_directory($type, $plugin);
2155 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
2164 * Resolves the real font location.
2166 * @param string $font name of font file
2167 * @param string $component
2168 * @return string full file path
2170 public function resolve_font_location($font, $component) {
2173 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2174 if (file_exists("$this->dir/fonts_core/$font")) {
2175 return "$this->dir/fonts_core/$font";
2177 foreach (array_reverse($this->parent_configs
) as $parent_config) { // Base first, the immediate parent last.
2178 if (file_exists("$parent_config->dir/fonts_core/$font")) {
2179 return "$parent_config->dir/fonts_core/$font";
2182 if (file_exists("$CFG->dataroot/fonts/$font")) {
2183 return "$CFG->dataroot/fonts/$font";
2185 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
2186 return "$CFG->dirroot/lib/fonts/$font";
2190 } else if ($component === 'theme') { // Exception.
2191 if (file_exists("$this->dir/fonts/$font")) {
2192 return "$this->dir/fonts/$font";
2194 foreach (array_reverse($this->parent_configs
) as $parent_config) { // Base first, the immediate parent last.
2195 if (file_exists("$parent_config->dir/fonts/$font")) {
2196 return "$parent_config->dir/fonts/$font";
2202 if (strpos($component, '_') === false) {
2203 $component = 'mod_'.$component;
2205 list($type, $plugin) = explode('_', $component, 2);
2207 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
2208 return "$this->dir/fonts_plugins/$type/$plugin/$font";
2210 foreach (array_reverse($this->parent_configs
) as $parent_config) { // Base first, the immediate parent last.
2211 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
2212 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
2215 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
2216 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
2218 $dir = core_component
::get_plugin_directory($type, $plugin);
2219 if (file_exists("$dir/fonts/$font")) {
2220 return "$dir/fonts/$font";
2227 * Return true if we should look for SVG images as well.
2231 public function use_svg_icons() {
2233 if ($this->usesvg
=== null) {
2235 if (!isset($CFG->svgicons
)) {
2236 $this->usesvg
= core_useragent
::supports_svg();
2238 // Force them on/off depending upon the setting.
2239 $this->usesvg
= (bool)$CFG->svgicons
;
2242 return $this->usesvg
;
2246 * Forces the usesvg setting to either true or false, avoiding any decision making.
2248 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
2249 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
2251 * @param bool $setting True to force the use of svg when available, null otherwise.
2253 public function force_svg_use($setting) {
2254 $this->usesvg
= (bool)$setting;
2258 * Set to be in RTL mode.
2260 * This will likely be used when post processing the CSS before serving it.
2262 * @param bool $inrtl True when in RTL mode.
2264 public function set_rtl_mode($inrtl = true) {
2265 $this->rtlmode
= $inrtl;
2269 * Checks if source maps are supported
2271 * @param bool $themedesigner True if theme designer is enabled.
2272 * @return boolean True if source maps are supported.
2274 public function supports_source_maps($themedesigner): bool {
2275 if (empty($this->rtlmode
) && $themedesigner) {
2282 * Whether the theme is being served in RTL mode.
2284 * @return bool True when in RTL mode.
2286 public function get_rtl_mode() {
2287 return $this->rtlmode
;
2291 * Checks if file with any image extension exists.
2293 * The order to these images was adjusted prior to the release of 2.4
2294 * At that point the were the following image counts in Moodle core:
2296 * - png = 667 in pix dirs (1499 total)
2297 * - gif = 385 in pix dirs (606 total)
2298 * - jpg = 62 in pix dirs (74 total)
2299 * - jpeg = 0 in pix dirs (1 total)
2301 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
2303 * @param string $filepath
2304 * @param bool $svg If set to true SVG images will also be looked for.
2305 * @return string image name with extension
2307 private static function image_exists($filepath, $svg = false) {
2308 if ($svg && file_exists("$filepath.svg")) {
2309 return "$filepath.svg";
2310 } else if (file_exists("$filepath.png")) {
2311 return "$filepath.png";
2312 } else if (file_exists("$filepath.gif")) {
2313 return "$filepath.gif";
2314 } else if (file_exists("$filepath.jpg")) {
2315 return "$filepath.jpg";
2316 } else if (file_exists("$filepath.jpeg")) {
2317 return "$filepath.jpeg";
2324 * Loads the theme config from config.php file.
2326 * @param string $themename
2327 * @param stdClass $settings from config_plugins table
2328 * @param boolean $parentscheck true to also check the parents. .
2329 * @return stdClass The theme configuration
2331 private static function find_theme_config($themename, $settings, $parentscheck = true) {
2332 // We have to use the variable name $THEME (upper case) because that
2333 // is what is used in theme config.php files.
2335 if (!$dir = theme_config
::find_theme_location($themename)) {
2339 $THEME = new stdClass();
2340 $THEME->name
= $themename;
2342 $THEME->settings
= $settings;
2344 global $CFG; // just in case somebody tries to use $CFG in theme config
2345 include("$THEME->dir/config.php");
2347 // verify the theme configuration is OK
2348 if (!is_array($THEME->parents
)) {
2349 // parents option is mandatory now
2352 // We use $parentscheck to only check the direct parents (avoid infinite loop).
2353 if ($parentscheck) {
2354 // Find all parent theme configs.
2355 foreach ($THEME->parents
as $parent) {
2356 $parentconfig = theme_config
::find_theme_config($parent, $settings, false);
2357 if (empty($parentconfig)) {
2368 * Finds the theme location and verifies the theme has all needed files
2369 * and is not obsoleted.
2371 * @param string $themename
2372 * @return string full dir path or null if not found
2374 private static function find_theme_location($themename) {
2377 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2378 $dir = "$CFG->dirroot/theme/$themename";
2380 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$themename/config.php")) {
2381 $dir = "$CFG->themedir/$themename";
2387 if (file_exists("$dir/styles.php")) {
2388 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
2396 * Get the renderer for a part of Moodle for this theme.
2398 * @param moodle_page $page the page we are rendering
2399 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
2400 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
2401 * @param string $target one of rendering target constants
2402 * @return renderer_base the requested renderer.
2404 public function get_renderer(moodle_page
$page, $component, $subtype = null, $target = null) {
2405 if (is_null($this->rf
)) {
2406 $classname = $this->rendererfactory
;
2407 $this->rf
= new $classname($this);
2410 return $this->rf
->get_renderer($page, $component, $subtype, $target);
2414 * Get the information from {@link $layouts} for this type of page.
2416 * @param string $pagelayout the the page layout name.
2417 * @return array the appropriate part of {@link $layouts}.
2419 protected function layout_info_for_page($pagelayout) {
2420 if (array_key_exists($pagelayout, $this->layouts
)) {
2421 return $this->layouts
[$pagelayout];
2423 debugging('Invalid page layout specified: ' . $pagelayout);
2424 return $this->layouts
['standard'];
2429 * Given the settings of this theme, and the page pagelayout, return the
2430 * full path of the page layout file to use.
2432 * Used by {@link core_renderer::header()}.
2434 * @param string $pagelayout the the page layout name.
2435 * @return string Full path to the lyout file to use
2437 public function layout_file($pagelayout) {
2440 $layoutinfo = $this->layout_info_for_page($pagelayout);
2441 $layoutfile = $layoutinfo['file'];
2443 if (array_key_exists('theme', $layoutinfo)) {
2444 $themes = array($layoutinfo['theme']);
2446 $themes = array_merge(array($this->name
),$this->parents
);
2449 foreach ($themes as $theme) {
2450 if ($dir = $this->find_theme_location($theme)) {
2451 $path = "$dir/layout/$layoutfile";
2453 // Check the template exists, return general base theme template if not.
2454 if (is_readable($path)) {
2460 debugging('Can not find layout file for: ' . $pagelayout);
2461 // fallback to standard normal layout
2462 return "$CFG->dirroot/theme/base/layout/general.php";
2466 * Returns auxiliary page layout options specified in layout configuration array.
2468 * @param string $pagelayout
2471 public function pagelayout_options($pagelayout) {
2472 $info = $this->layout_info_for_page($pagelayout);
2473 if (!empty($info['options'])) {
2474 return $info['options'];
2480 * Inform a block_manager about the block regions this theme wants on this
2483 * @param string $pagelayout the general type of the page.
2484 * @param block_manager $blockmanager the block_manger to set up.
2486 public function setup_blocks($pagelayout, $blockmanager) {
2487 $layoutinfo = $this->layout_info_for_page($pagelayout);
2488 if (!empty($layoutinfo['regions'])) {
2489 $blockmanager->add_regions($layoutinfo['regions'], false);
2490 $blockmanager->set_default_region($layoutinfo['defaultregion']);
2495 * Gets the visible name for the requested block region.
2497 * @param string $region The region name to get
2498 * @param string $theme The theme the region belongs to (may come from the parent theme)
2501 protected function get_region_name($region, $theme) {
2503 $stringman = get_string_manager();
2505 // Check if the name is defined in the theme.
2506 if ($stringman->string_exists('region-' . $region, 'theme_' . $theme)) {
2507 return get_string('region-' . $region, 'theme_' . $theme);
2510 // Check the theme parents.
2511 foreach ($this->parents
as $parentthemename) {
2512 if ($stringman->string_exists('region-' . $region, 'theme_' . $parentthemename)) {
2513 return get_string('region-' . $region, 'theme_' . $parentthemename);
2517 // Last resort, try the boost theme for names.
2518 return get_string('region-' . $region, 'theme_boost');
2522 * Get the list of all block regions known to this theme in all templates.
2524 * @return array internal region name => human readable name.
2526 public function get_all_block_regions() {
2528 foreach ($this->layouts
as $layoutinfo) {
2529 foreach ($layoutinfo['regions'] as $region) {
2530 $regions[$region] = $this->get_region_name($region, $this->name
);
2537 * Returns the human readable name of the theme
2541 public function get_theme_name() {
2542 return get_string('pluginname', 'theme_'.$this->name
);
2546 * Returns the block render method.
2548 * It is set by the theme via:
2549 * $THEME->blockrendermethod = '...';
2551 * It can be one of two values, blocks or blocks_for_region.
2552 * It should be set to the method being used by the theme layouts.
2556 public function get_block_render_method() {
2557 if ($this->blockrendermethod
) {
2558 // Return the specified block render method.
2559 return $this->blockrendermethod
;
2561 // Its not explicitly set, check the parent theme configs.
2562 foreach ($this->parent_configs
as $config) {
2563 if (isset($config->blockrendermethod
)) {
2564 return $config->blockrendermethod
;
2567 // Default it to blocks.
2572 * Get the callable for CSS tree post processing.
2574 * @return string|null
2576 public function get_css_tree_post_processor() {
2577 $configs = [$this] +
$this->parent_configs
;
2578 foreach ($configs as $config) {
2579 if (!empty($config->csstreepostprocessor
) && is_callable($config->csstreepostprocessor
)) {
2580 return $config->csstreepostprocessor
;
2589 * This class keeps track of which HTML tags are currently open.
2591 * This makes it much easier to always generate well formed XHTML output, even
2592 * if execution terminates abruptly. Any time you output some opening HTML
2593 * without the matching closing HTML, you should push the necessary close tags
2596 * @copyright 2009 Tim Hunt
2597 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2602 class xhtml_container_stack
{
2605 * @var array Stores the list of open containers.
2607 protected $opencontainers = array();
2610 * @var array In developer debug mode, stores a stack trace of all opens and
2611 * closes, so we can output helpful error messages when there is a mismatch.
2613 protected $log = array();
2616 * @var boolean Store whether we are developer debug mode. We need this in
2617 * several places including in the destructor where we may not have access to $CFG.
2619 protected $isdebugging;
2624 public function __construct() {
2626 $this->isdebugging
= $CFG->debugdeveloper
;
2630 * Push the close HTML for a recently opened container onto the stack.
2632 * @param string $type The type of container. This is checked when {@link pop()}
2633 * is called and must match, otherwise a developer debug warning is output.
2634 * @param string $closehtml The HTML required to close the container.
2636 public function push($type, $closehtml) {
2637 $container = new stdClass
;
2638 $container->type
= $type;
2639 $container->closehtml
= $closehtml;
2640 if ($this->isdebugging
) {
2641 $this->log('Open', $type);
2643 array_push($this->opencontainers
, $container);
2647 * Pop the HTML for the next closing container from the stack. The $type
2648 * must match the type passed when the container was opened, otherwise a
2649 * warning will be output.
2651 * @param string $type The type of container.
2652 * @return string the HTML required to close the container.
2654 public function pop($type) {
2655 if (empty($this->opencontainers
)) {
2656 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2657 $this->output_log(), DEBUG_DEVELOPER
);
2661 $container = array_pop($this->opencontainers
);
2662 if ($container->type
!= $type) {
2663 debugging('<p>The type of container to be closed (' . $container->type
.
2664 ') does not match the type of the next open container (' . $type .
2665 '). This suggests there is a nesting problem.</p>' .
2666 $this->output_log(), DEBUG_DEVELOPER
);
2668 if ($this->isdebugging
) {
2669 $this->log('Close', $type);
2671 return $container->closehtml
;
2675 * Close all but the last open container. This is useful in places like error
2676 * handling, where you want to close all the open containers (apart from <body>)
2677 * before outputting the error message.
2679 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2680 * developer debug warning if it isn't.
2681 * @return string the HTML required to close any open containers inside <body>.
2683 public function pop_all_but_last($shouldbenone = false) {
2684 if ($shouldbenone && count($this->opencontainers
) != 1) {
2685 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2686 $this->output_log(), DEBUG_DEVELOPER
);
2689 while (count($this->opencontainers
) > 1) {
2690 $container = array_pop($this->opencontainers
);
2691 $output .= $container->closehtml
;
2697 * You can call this function if you want to throw away an instance of this
2698 * class without properly emptying the stack (for example, in a unit test).
2699 * Calling this method stops the destruct method from outputting a developer
2700 * debug warning. After calling this method, the instance can no longer be used.
2702 public function discard() {
2703 $this->opencontainers
= null;
2707 * Adds an entry to the log.
2709 * @param string $action The name of the action
2710 * @param string $type The type of action
2712 protected function log($action, $type) {
2713 $this->log
[] = '<li>' . $action . ' ' . $type . ' at:' .
2714 format_backtrace(debug_backtrace()) . '</li>';
2718 * Outputs the log's contents as a HTML list.
2720 * @return string HTML list of the log
2722 protected function output_log() {
2723 return '<ul>' . implode("\n", $this->log
) . '</ul>';