weekly release 3.9dev
[moodle.git] / lib / outputlib.php
blob56a1110b15d1f9c93c75892971ac530c5172506c
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions for generating the HTML that Moodle should output.
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
21 * for an overview.
23 * @copyright 2009 Tim Hunt
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * @package core
26 * @category output
29 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->libdir.'/outputcomponents.php');
32 require_once($CFG->libdir.'/outputactions.php');
33 require_once($CFG->libdir.'/outputfactories.php');
34 require_once($CFG->libdir.'/outputrenderers.php');
35 require_once($CFG->libdir.'/outputrequirementslib.php');
37 /**
38 * Returns current theme revision number.
40 * @return int
42 function theme_get_revision() {
43 global $CFG;
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.
48 return 1;
49 } else {
50 return $CFG->themerev;
53 } else {
54 return -1;
58 /**
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
63 * @return int
65 function theme_get_sub_revision_for_theme($themename) {
66 global $CFG;
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.
74 return 1;
75 } else {
76 return $revision;
78 } else {
79 return -1;
83 /**
84 * Calculates and returns the next theme revision number.
86 * @return int
88 function theme_get_next_revision() {
89 global $CFG;
91 $next = time();
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;
99 return $next;
103 * Calculates and returns the next theme revision number.
105 * @param string $themename The non-frankenstyle name of the theme
106 * @return int
108 function theme_get_next_sub_revision_for_theme($themename) {
109 global $CFG;
111 $next = time();
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;
120 return $next;
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) {
149 global $CFG;
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";
155 } else {
156 return null;
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) {
169 global $CFG;
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) {
184 global $CFG;
186 if (empty($themeconfigs)) {
187 return;
190 require_once("{$CFG->libdir}/csslib.php");
192 $themescss = [];
193 $themerev = theme_get_revision();
194 // Make sure the local cache directory exists.
195 make_localcache_directory('theme');
197 foreach ($themeconfigs as $themeconfig) {
198 $themecss = [];
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 // Lock it on. Technically we should build all themes for SVG and no SVG - but ie9 is out of support.
205 $themeconfig->force_svg_use(true);
206 $themeconfig->set_rtl_mode(($direction === 'rtl'));
208 $themecss[$direction] = $themeconfig->get_css_content();
209 if ($cache) {
210 $themeconfig->set_css_content_cache($themecss[$direction]);
211 $filename = theme_get_css_filename($themeconfig->name, $themerev, $newrevision, $direction);
212 css_store_css($themeconfig, $filename, $themecss[$direction]);
215 $themescss[] = $themecss;
217 if ($cache) {
218 // Only update the theme revision after we've successfully created the
219 // new CSS cache.
220 theme_set_sub_revision_for_theme($themeconfig->name, $newrevision);
222 // Now purge old files. We must purge all old files in the local cache
223 // because we've incremented the theme sub revision. This will leave any
224 // files with the old revision inaccessbile so we might as well removed
225 // them from disk.
226 foreach (['ltr', 'rtl'] as $direction) {
227 $oldcss = theme_get_css_filename($themeconfig->name, $themerev, $oldrevision, $direction);
228 if (file_exists($oldcss)) {
229 unlink($oldcss);
235 return $themescss;
239 * Invalidate all server and client side caches.
241 * This method deletes the physical directory that is used to cache the theme
242 * files used for serving.
243 * Because it deletes the main theme cache directory all themes are reset by
244 * this function.
246 function theme_reset_all_caches() {
247 global $CFG, $PAGE;
248 require_once("{$CFG->libdir}/filelib.php");
250 $next = theme_get_next_revision();
251 theme_set_revision($next);
253 if (!empty($CFG->themedesignermode)) {
254 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner');
255 $cache->purge();
258 // Purge compiled post processed css.
259 cache::make('core', 'postprocessedcss')->purge();
261 // Delete all old theme localcaches.
262 $themecachedirs = glob("{$CFG->localcachedir}/theme/*", GLOB_ONLYDIR);
263 foreach ($themecachedirs as $localcachedir) {
264 fulldelete($localcachedir);
267 if ($PAGE) {
268 $PAGE->reload_theme();
273 * Enable or disable theme designer mode.
275 * @param bool $state
277 function theme_set_designer_mod($state) {
278 set_config('themedesignermode', (int)!empty($state));
279 // Reset caches after switching mode so that any designer mode caches get purged too.
280 theme_reset_all_caches();
284 * Checks if the given device has a theme defined in config.php.
286 * @return bool
288 function theme_is_device_locked($device) {
289 global $CFG;
290 $themeconfigname = core_useragent::get_device_type_cfg_var_name($device);
291 return isset($CFG->config_php_settings[$themeconfigname]);
295 * Returns the theme named defined in config.php for the given device.
297 * @return string or null
299 function theme_get_locked_theme_for_device($device) {
300 global $CFG;
302 if (!theme_is_device_locked($device)) {
303 return null;
306 $themeconfigname = core_useragent::get_device_type_cfg_var_name($device);
307 return $CFG->config_php_settings[$themeconfigname];
311 * This class represents the configuration variables of a Moodle theme.
313 * All the variables with access: public below (with a few exceptions that are marked)
314 * are the properties you can set in your themes config.php file.
316 * There are also some methods and protected variables that are part of the inner
317 * workings of Moodle's themes system. If you are just editing a themes config.php
318 * file, you can just ignore those, and the following information for developers.
320 * Normally, to create an instance of this class, you should use the
321 * {@link theme_config::load()} factory method to load a themes config.php file.
322 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
323 * will create one for you, accessible as $PAGE->theme.
325 * @copyright 2009 Tim Hunt
326 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
327 * @since Moodle 2.0
328 * @package core
329 * @category output
331 class theme_config {
334 * @var string Default theme, used when requested theme not found.
336 const DEFAULT_THEME = 'boost';
338 /** The key under which the SCSS file is stored amongst the CSS files. */
339 const SCSS_KEY = '__SCSS__';
342 * @var array You can base your theme on other themes by linking to the other theme as
343 * parents. This lets you use the CSS and layouts from the other themes
344 * (see {@link theme_config::$layouts}).
345 * That makes it easy to create a new theme that is similar to another one
346 * but with a few changes. In this themes CSS you only need to override
347 * those rules you want to change.
349 public $parents;
352 * @var array The names of all the stylesheets from this theme that you would
353 * like included, in order. Give the names of the files without .css.
355 public $sheets = array();
358 * @var array The names of all the stylesheets from parents that should be excluded.
359 * true value may be used to specify all parents or all themes from one parent.
360 * If no value specified value from parent theme used.
362 public $parents_exclude_sheets = null;
365 * @var array List of plugin sheets to be excluded.
366 * If no value specified value from parent theme used.
368 public $plugins_exclude_sheets = null;
371 * @var array List of style sheets that are included in the text editor bodies.
372 * Sheets from parent themes are used automatically and can not be excluded.
374 public $editor_sheets = array();
377 * @var bool Whether a fallback version of the stylesheet will be used
378 * whilst the final version is generated.
380 public $usefallback = false;
383 * @var array The names of all the javascript files this theme that you would
384 * like included from head, in order. Give the names of the files without .js.
386 public $javascripts = array();
389 * @var array The names of all the javascript files this theme that you would
390 * like included from footer, in order. Give the names of the files without .js.
392 public $javascripts_footer = array();
395 * @var array The names of all the javascript files from parents that should
396 * be excluded. true value may be used to specify all parents or all themes
397 * from one parent.
398 * If no value specified value from parent theme used.
400 public $parents_exclude_javascripts = null;
403 * @var array Which file to use for each page layout.
405 * This is an array of arrays. The keys of the outer array are the different layouts.
406 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
407 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
408 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
409 * That file also has a good example of how to set this setting.
411 * For each layout, the value in the outer array is an array that describes
412 * how you want that type of page to look. For example
413 * <pre>
414 * $THEME->layouts = array(
415 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
416 * 'standard' => array(
417 * 'theme' = 'mytheme',
418 * 'file' => 'normal.php',
419 * 'regions' => array('side-pre', 'side-post'),
420 * 'defaultregion' => 'side-post'
421 * ),
422 * // The site home page.
423 * 'home' => array(
424 * 'theme' = 'mytheme',
425 * 'file' => 'home.php',
426 * 'regions' => array('side-pre', 'side-post'),
427 * 'defaultregion' => 'side-post'
428 * ),
429 * // ...
430 * );
431 * </pre>
433 * 'theme' name of the theme where is the layout located
434 * 'file' is the layout file to use for this type of page.
435 * layout files are stored in layout subfolder
436 * 'regions' This lists the regions on the page where blocks may appear. For
437 * each region you list here, your layout file must include a call to
438 * <pre>
439 * echo $OUTPUT->blocks_for_region($regionname);
440 * </pre>
441 * or equivalent so that the blocks are actually visible.
443 * 'defaultregion' If the list of regions is non-empty, then you must pick
444 * one of the one of them as 'default'. This has two meanings. First, this is
445 * where new blocks are added. Second, if there are any blocks associated with
446 * the page, but in non-existent regions, they appear here. (Imaging, for example,
447 * that someone added blocks using a different theme that used different region
448 * names, and then switched to this theme.)
450 public $layouts = array();
453 * @var string Name of the renderer factory class to use. Must implement the
454 * {@link renderer_factory} interface.
456 * This is an advanced feature. Moodle output is generated by 'renderers',
457 * you can customise the HTML that is output by writing custom renderers,
458 * and then you need to specify 'renderer factory' so that Moodle can find
459 * your renderers.
461 * There are some renderer factories supplied with Moodle. Please follow these
462 * links to see what they do.
463 * <ul>
464 * <li>{@link standard_renderer_factory} - the default.</li>
465 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
466 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
467 * </ul>
469 public $rendererfactory = 'standard_renderer_factory';
472 * @var string Function to do custom CSS post-processing.
474 * This is an advanced feature. If you want to do custom post-processing on the
475 * CSS before it is output (for example, to replace certain variable names
476 * with particular values) you can give the name of a function here.
478 public $csspostprocess = null;
481 * @var string Function to do custom CSS post-processing on a parsed CSS tree.
483 * This is an advanced feature. If you want to do custom post-processing on the
484 * CSS before it is output, you can provide the name of the function here. The
485 * function will receive a CSS tree document as first parameter, and the theme_config
486 * object as second parameter. A return value is not required, the tree can
487 * be edited in place.
489 public $csstreepostprocessor = null;
492 * @var string Accessibility: Right 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 &lt; &gt; &raquo; - these are confusing for blind users.
499 public $rarrow = null;
502 * @var string Accessibility: Left arrow-like character is
503 * used in the breadcrumb trail, course navigation menu
504 * (previous/next activity), calendar, and search forum block.
505 * If the theme does not set characters, appropriate defaults
506 * are set automatically. Please DO NOT
507 * use &lt; &gt; &raquo; - these are confusing for blind users.
509 public $larrow = null;
512 * @var string Accessibility: Up arrow-like character is used in
513 * the book heirarchical navigation.
514 * If the theme does not set characters, appropriate defaults
515 * are set automatically. Please DO NOT
516 * use ^ - this is confusing for blind users.
518 public $uarrow = null;
521 * @var string Accessibility: Down arrow-like character.
522 * If the theme does not set characters, appropriate defaults
523 * are set automatically.
525 public $darrow = null;
528 * @var bool Some themes may want to disable ajax course editing.
530 public $enablecourseajax = true;
533 * @var string Determines served document types
534 * - 'html5' the only officially supported doctype in Moodle
535 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
536 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
538 public $doctype = 'html5';
541 * @var string requiredblocks If set to a string, will list the block types that cannot be deleted. Defaults to
542 * navigation and settings.
544 public $requiredblocks = false;
546 //==Following properties are not configurable from theme config.php==
549 * @var string The name of this theme. Set automatically when this theme is
550 * loaded. This can not be set in theme config.php
552 public $name;
555 * @var string The folder where this themes files are stored. This is set
556 * automatically. This can not be set in theme config.php
558 public $dir;
561 * @var stdClass Theme settings stored in config_plugins table.
562 * This can not be set in theme config.php
564 public $settings = null;
567 * @var bool If set to true and the theme enables the dock then blocks will be able
568 * to be moved to the special dock
570 public $enable_dock = false;
573 * @var bool If set to true then this theme will not be shown in the theme selector unless
574 * theme designer mode is turned on.
576 public $hidefromselector = false;
579 * @var array list of YUI CSS modules to be included on each page. This may be used
580 * to remove cssreset and use cssnormalise module instead.
582 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
585 * An associative array of block manipulations that should be made if the user is using an rtl language.
586 * The key is the original block region, and the value is the block region to change to.
587 * This is used when displaying blocks for regions only.
588 * @var array
590 public $blockrtlmanipulations = array();
593 * @var renderer_factory Instance of the renderer_factory implementation
594 * we are using. Implementation detail.
596 protected $rf = null;
599 * @var array List of parent config objects.
601 protected $parent_configs = array();
604 * Used to determine whether we can serve SVG images or not.
605 * @var bool
607 private $usesvg = null;
610 * Whether in RTL mode or not.
611 * @var bool
613 protected $rtlmode = false;
616 * The SCSS file to compile (without .scss), located in the scss/ folder of the theme.
617 * Or a Closure, which receives the theme_config as argument and must
618 * return the SCSS content.
619 * @var string|Closure
621 public $scss = false;
624 * Local cache of the SCSS property.
625 * @var false|array
627 protected $scsscache = null;
630 * The name of the function to call to get the SCSS code to inject.
631 * @var string
633 public $extrascsscallback = null;
636 * The name of the function to call to get SCSS to prepend.
637 * @var string
639 public $prescsscallback = null;
642 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
643 * Defaults to {@link core_renderer::blocks_for_region()}
644 * @var string
646 public $blockrendermethod = null;
649 * Remember the results of icon remapping for the current page.
650 * @var array
652 public $remapiconcache = [];
655 * The name of the function to call to get precompiled CSS.
656 * @var string
658 public $precompiledcsscallback = null;
661 * Load the config.php file for a particular theme, and return an instance
662 * of this class. (That is, this is a factory method.)
664 * @param string $themename the name of the theme.
665 * @return theme_config an instance of this class.
667 public static function load($themename) {
668 global $CFG;
670 // load theme settings from db
671 try {
672 $settings = get_config('theme_'.$themename);
673 } catch (dml_exception $e) {
674 // most probably moodle tables not created yet
675 $settings = new stdClass();
678 if ($config = theme_config::find_theme_config($themename, $settings)) {
679 return new theme_config($config);
681 } else if ($themename == theme_config::DEFAULT_THEME) {
682 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
684 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
685 debugging('This page should be using theme ' . $themename .
686 ' which cannot be initialised. Falling back to the site theme ' . $CFG->theme, DEBUG_NORMAL);
687 return new theme_config($config);
689 } else {
690 // bad luck, the requested theme has some problems - admin see details in theme config
691 debugging('This page should be using theme ' . $themename .
692 ' which cannot be initialised. Nor can the site theme ' . $CFG->theme .
693 '. Falling back to ' . theme_config::DEFAULT_THEME, DEBUG_NORMAL);
694 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
699 * Theme diagnostic code. It is very problematic to send debug output
700 * to the actual CSS file, instead this functions is supposed to
701 * diagnose given theme and highlights all potential problems.
702 * This information should be available from the theme selection page
703 * or some other debug page for theme designers.
705 * @param string $themename
706 * @return array description of problems
708 public static function diagnose($themename) {
709 //TODO: MDL-21108
710 return array();
714 * Private constructor, can be called only from the factory method.
715 * @param stdClass $config
717 private function __construct($config) {
718 global $CFG; //needed for included lib.php files
720 $this->settings = $config->settings;
721 $this->name = $config->name;
722 $this->dir = $config->dir;
724 if ($this->name != self::DEFAULT_THEME) {
725 $baseconfig = self::find_theme_config(self::DEFAULT_THEME, $this->settings);
726 } else {
727 $baseconfig = $config;
730 $configurable = array(
731 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'usefallback',
732 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
733 'layouts', 'enablecourseajax', 'requiredblocks',
734 'rendererfactory', 'csspostprocess', 'editor_sheets', 'editor_scss', 'rarrow', 'larrow', 'uarrow', 'darrow',
735 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations', 'blockrendermethod',
736 'scss', 'extrascsscallback', 'prescsscallback', 'csstreepostprocessor', 'addblockposition',
737 'iconsystem', 'precompiledcsscallback');
739 foreach ($config as $key=>$value) {
740 if (in_array($key, $configurable)) {
741 $this->$key = $value;
745 // verify all parents and load configs and renderers
746 foreach ($this->parents as $parent) {
747 if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
748 // this is not good - better exclude faulty parents
749 continue;
751 $libfile = $parent_config->dir.'/lib.php';
752 if (is_readable($libfile)) {
753 // theme may store various function here
754 include_once($libfile);
756 $renderersfile = $parent_config->dir.'/renderers.php';
757 if (is_readable($renderersfile)) {
758 // may contain core and plugin renderers and renderer factory
759 include_once($renderersfile);
761 $this->parent_configs[$parent] = $parent_config;
763 $libfile = $this->dir.'/lib.php';
764 if (is_readable($libfile)) {
765 // theme may store various function here
766 include_once($libfile);
768 $rendererfile = $this->dir.'/renderers.php';
769 if (is_readable($rendererfile)) {
770 // may contain core and plugin renderers and renderer factory
771 include_once($rendererfile);
772 } else {
773 // check if renderers.php file is missnamed renderer.php
774 if (is_readable($this->dir.'/renderer.php')) {
775 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
776 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
780 // cascade all layouts properly
781 foreach ($baseconfig->layouts as $layout=>$value) {
782 if (!isset($this->layouts[$layout])) {
783 foreach ($this->parent_configs as $parent_config) {
784 if (isset($parent_config->layouts[$layout])) {
785 $this->layouts[$layout] = $parent_config->layouts[$layout];
786 continue 2;
789 $this->layouts[$layout] = $value;
793 //fix arrows if needed
794 $this->check_theme_arrows();
798 * Let the theme initialise the page object (usually $PAGE).
800 * This may be used for example to request jQuery in add-ons.
802 * @param moodle_page $page
804 public function init_page(moodle_page $page) {
805 $themeinitfunction = 'theme_'.$this->name.'_page_init';
806 if (function_exists($themeinitfunction)) {
807 $themeinitfunction($page);
812 * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow, $THEME->darrow have been set (theme/-/config.php).
813 * If not it applies sensible defaults.
815 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
816 * search forum block, etc. Important: these are 'silent' in a screen-reader
817 * (unlike &gt; &raquo;), and must be accompanied by text.
819 private function check_theme_arrows() {
820 if (!isset($this->rarrow) and !isset($this->larrow)) {
821 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
822 // Also OK in Win 9x/2K/IE 5.x
823 $this->rarrow = '&#x25BA;';
824 $this->larrow = '&#x25C4;';
825 $this->uarrow = '&#x25B2;';
826 $this->darrow = '&#x25BC;';
827 if (empty($_SERVER['HTTP_USER_AGENT'])) {
828 $uagent = '';
829 } else {
830 $uagent = $_SERVER['HTTP_USER_AGENT'];
832 if (false !== strpos($uagent, 'Opera')
833 || false !== strpos($uagent, 'Mac')) {
834 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
835 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
836 $this->rarrow = '&#x25B6;&#xFE0E;';
837 $this->larrow = '&#x25C0;&#xFE0E;';
839 elseif ((false !== strpos($uagent, 'Konqueror'))
840 || (false !== strpos($uagent, 'Android'))) {
841 // The fonts on Android don't include the characters required for this to work as expected.
842 // So we use the same ones Konqueror uses.
843 $this->rarrow = '&rarr;';
844 $this->larrow = '&larr;';
845 $this->uarrow = '&uarr;';
846 $this->darrow = '&darr;';
848 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
849 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
850 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
851 // To be safe, non-Unicode browsers!
852 $this->rarrow = '&gt;';
853 $this->larrow = '&lt;';
854 $this->uarrow = '^';
855 $this->darrow = 'v';
858 // RTL support - in RTL languages, swap r and l arrows
859 if (right_to_left()) {
860 $t = $this->rarrow;
861 $this->rarrow = $this->larrow;
862 $this->larrow = $t;
868 * Returns output renderer prefixes, these are used when looking
869 * for the overridden renderers in themes.
871 * @return array
873 public function renderer_prefixes() {
874 global $CFG; // just in case the included files need it
876 $prefixes = array('theme_'.$this->name);
878 foreach ($this->parent_configs as $parent) {
879 $prefixes[] = 'theme_'.$parent->name;
882 return $prefixes;
886 * Returns the stylesheet URL of this editor content
888 * @param bool $encoded false means use & and true use &amp; in URLs
889 * @return moodle_url
891 public function editor_css_url($encoded=true) {
892 global $CFG;
893 $rev = theme_get_revision();
894 if ($rev > -1) {
895 $themesubrevision = theme_get_sub_revision_for_theme($this->name);
897 // Provide the sub revision to allow us to invalidate cached theme CSS
898 // on a per theme basis, rather than globally.
899 if ($themesubrevision && $themesubrevision > 0) {
900 $rev .= "_{$themesubrevision}";
903 $url = new moodle_url("/theme/styles.php");
904 if (!empty($CFG->slasharguments)) {
905 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
906 } else {
907 $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
909 } else {
910 $params = array('theme'=>$this->name, 'type'=>'editor');
911 $url = new moodle_url('/theme/styles_debug.php', $params);
913 return $url;
917 * Returns the content of the CSS to be used in editor content
919 * @return array
921 public function editor_css_files() {
922 $files = array();
924 // First editor plugins.
925 $plugins = core_component::get_plugin_list('editor');
926 foreach ($plugins as $plugin=>$fulldir) {
927 $sheetfile = "$fulldir/editor_styles.css";
928 if (is_readable($sheetfile)) {
929 $files['plugin_'.$plugin] = $sheetfile;
932 // Then parent themes - base first, the immediate parent last.
933 foreach (array_reverse($this->parent_configs) as $parent_config) {
934 if (empty($parent_config->editor_sheets)) {
935 continue;
937 foreach ($parent_config->editor_sheets as $sheet) {
938 $sheetfile = "$parent_config->dir/style/$sheet.css";
939 if (is_readable($sheetfile)) {
940 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
944 // Finally this theme.
945 if (!empty($this->editor_sheets)) {
946 foreach ($this->editor_sheets as $sheet) {
947 $sheetfile = "$this->dir/style/$sheet.css";
948 if (is_readable($sheetfile)) {
949 $files['theme_'.$sheet] = $sheetfile;
954 return $files;
958 * Compiles and returns the content of the SCSS to be used in editor content
960 * @return string Compiled CSS from the editor SCSS
962 public function editor_scss_to_css() {
963 $css = '';
965 if (!empty($this->editor_scss)) {
966 $compiler = new core_scss();
968 foreach ($this->editor_scss as $filename) {
969 $compiler->set_file("{$this->dir}/scss/{$filename}.scss");
971 try {
972 $css .= $compiler->to_css();
973 } catch (\Exception $e) {
974 debugging('Error while compiling editor SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
979 return $css;
983 * Get the stylesheet URL of this theme.
985 * @param moodle_page $page Not used... deprecated?
986 * @return moodle_url[]
988 public function css_urls(moodle_page $page) {
989 global $CFG;
991 $rev = theme_get_revision();
993 $urls = array();
995 $svg = $this->use_svg_icons();
996 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
998 if ($rev > -1) {
999 $filename = right_to_left() ? 'all-rtl' : 'all';
1000 $url = new moodle_url("/theme/styles.php");
1001 $themesubrevision = theme_get_sub_revision_for_theme($this->name);
1003 // Provide the sub revision to allow us to invalidate cached theme CSS
1004 // on a per theme basis, rather than globally.
1005 if ($themesubrevision && $themesubrevision > 0) {
1006 $rev .= "_{$themesubrevision}";
1009 if (!empty($CFG->slasharguments)) {
1010 $slashargs = '';
1011 if (!$svg) {
1012 // We add a simple /_s to the start of the path.
1013 // The underscore is used to ensure that it isn't a valid theme name.
1014 $slashargs .= '/_s'.$slashargs;
1016 $slashargs .= '/'.$this->name.'/'.$rev.'/'.$filename;
1017 if ($separate) {
1018 $slashargs .= '/chunk0';
1020 $url->set_slashargument($slashargs, 'noparam', true);
1021 } else {
1022 $params = array('theme' => $this->name, 'rev' => $rev, 'type' => $filename);
1023 if (!$svg) {
1024 // We add an SVG param so that we know not to serve SVG images.
1025 // We do this because all modern browsers support SVG and this param will one day be removed.
1026 $params['svg'] = '0';
1028 if ($separate) {
1029 $params['chunk'] = '0';
1031 $url->params($params);
1033 $urls[] = $url;
1035 } else {
1036 $baseurl = new moodle_url('/theme/styles_debug.php');
1038 $css = $this->get_css_files(true);
1039 if (!$svg) {
1040 // We add an SVG param so that we know not to serve SVG images.
1041 // We do this because all modern browsers support SVG and this param will one day be removed.
1042 $baseurl->param('svg', '0');
1044 if (right_to_left()) {
1045 $baseurl->param('rtl', 1);
1047 if ($separate) {
1048 // We might need to chunk long files.
1049 $baseurl->param('chunk', '0');
1051 if (core_useragent::is_ie()) {
1052 // Lalala, IE does not allow more than 31 linked CSS files from main document.
1053 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
1054 foreach ($css['parents'] as $parent=>$sheets) {
1055 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
1056 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
1058 if ($this->get_scss_property()) {
1059 // No need to define the type as IE here.
1060 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
1062 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
1064 } else {
1065 foreach ($css['plugins'] as $plugin=>$unused) {
1066 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
1068 foreach ($css['parents'] as $parent=>$sheets) {
1069 foreach ($sheets as $sheet=>$unused2) {
1070 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
1073 foreach ($css['theme'] as $sheet => $filename) {
1074 if ($sheet === self::SCSS_KEY) {
1075 // This is the theme SCSS file.
1076 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
1077 } else {
1078 // Sheet first in order to make long urls easier to read.
1079 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
1085 // Allow themes to change the css url to something like theme/mytheme/mycss.php.
1086 component_callback('theme_' . $this->name, 'alter_css_urls', [&$urls]);
1087 return $urls;
1091 * Get the whole css stylesheet for production mode.
1093 * NOTE: this method is not expected to be used from any addons.
1095 * @return string CSS markup compressed
1097 public function get_css_content() {
1099 $csscontent = '';
1100 foreach ($this->get_css_files(false) as $type => $value) {
1101 foreach ($value as $identifier => $val) {
1102 if (is_array($val)) {
1103 foreach ($val as $v) {
1104 $csscontent .= file_get_contents($v) . "\n";
1106 } else {
1107 if ($type === 'theme' && $identifier === self::SCSS_KEY) {
1108 // We need the content from SCSS because this is the SCSS file from the theme.
1109 if ($compiled = $this->get_css_content_from_scss(false)) {
1110 $csscontent .= $compiled;
1111 } else {
1112 // The compiler failed so default back to any precompiled css that might
1113 // exist.
1114 $csscontent .= $this->get_precompiled_css_content();
1116 } else {
1117 $csscontent .= file_get_contents($val) . "\n";
1122 $csscontent = $this->post_process($csscontent);
1123 $csscontent = core_minify::css($csscontent);
1125 return $csscontent;
1128 * Set post processed CSS content cache.
1130 * @param string $csscontent The post processed CSS content.
1131 * @return bool True if the content was successfully cached.
1133 public function set_css_content_cache($csscontent) {
1135 $cache = cache::make('core', 'postprocessedcss');
1136 $key = $this->get_css_cache_key();
1138 return $cache->set($key, $csscontent);
1142 * Return whether the post processed CSS content has been cached.
1144 * @return bool Whether the post-processed CSS is available in the cache.
1146 public function has_css_cached_content() {
1148 $key = $this->get_css_cache_key();
1149 $cache = cache::make('core', 'postprocessedcss');
1151 return $cache->has($key);
1155 * Return cached post processed CSS content.
1157 * @return bool|string The cached css content or false if not found.
1159 public function get_css_cached_content() {
1161 $key = $this->get_css_cache_key();
1162 $cache = cache::make('core', 'postprocessedcss');
1164 return $cache->get($key);
1168 * Generate the css content cache key.
1170 * @return string The post processed css cache key.
1172 public function get_css_cache_key() {
1173 $nosvg = (!$this->use_svg_icons()) ? 'nosvg_' : '';
1174 $rtlmode = ($this->rtlmode == true) ? 'rtl' : 'ltr';
1176 return $nosvg . $this->name . '_' . $rtlmode;
1180 * Get the theme designer css markup,
1181 * the parameters are coming from css_urls().
1183 * NOTE: this method is not expected to be used from any addons.
1185 * @param string $type
1186 * @param string $subtype
1187 * @param string $sheet
1188 * @return string CSS markup
1190 public function get_css_content_debug($type, $subtype, $sheet) {
1192 if ($type === 'scss') {
1193 // The SCSS file of the theme is requested.
1194 $csscontent = $this->get_css_content_from_scss(true);
1195 if ($csscontent !== false) {
1196 return $this->post_process($csscontent);
1198 return '';
1201 $cssfiles = array();
1202 $css = $this->get_css_files(true);
1204 if ($type === 'ie') {
1205 // IE is a sloppy browser with weird limits, sorry.
1206 if ($subtype === 'plugins') {
1207 $cssfiles = $css['plugins'];
1209 } else if ($subtype === 'parents') {
1210 if (empty($sheet)) {
1211 // Do not bother with the empty parent here.
1212 } else {
1213 // Build up the CSS for that parent so we can serve it as one file.
1214 foreach ($css[$subtype][$sheet] as $parent => $css) {
1215 $cssfiles[] = $css;
1218 } else if ($subtype === 'theme') {
1219 $cssfiles = $css['theme'];
1220 foreach ($cssfiles as $key => $value) {
1221 if (in_array($key, [self::SCSS_KEY])) {
1222 // Remove the SCSS file from the theme CSS files.
1223 // The SCSS files use the type 'scss', not 'ie'.
1224 unset($cssfiles[$key]);
1229 } else if ($type === 'plugin') {
1230 if (isset($css['plugins'][$subtype])) {
1231 $cssfiles[] = $css['plugins'][$subtype];
1234 } else if ($type === 'parent') {
1235 if (isset($css['parents'][$subtype][$sheet])) {
1236 $cssfiles[] = $css['parents'][$subtype][$sheet];
1239 } else if ($type === 'theme') {
1240 if (isset($css['theme'][$sheet])) {
1241 $cssfiles[] = $css['theme'][$sheet];
1245 $csscontent = '';
1246 foreach ($cssfiles as $file) {
1247 $contents = file_get_contents($file);
1248 $contents = $this->post_process($contents);
1249 $comment = "/** Path: $type $subtype $sheet.' **/\n";
1250 $stats = '';
1251 $csscontent .= $comment.$stats.$contents."\n\n";
1254 return $csscontent;
1258 * Get the whole css stylesheet for editor iframe.
1260 * NOTE: this method is not expected to be used from any addons.
1262 * @return string CSS markup
1264 public function get_css_content_editor() {
1265 $css = '';
1266 $cssfiles = $this->editor_css_files();
1268 // If editor has static CSS, include it.
1269 foreach ($cssfiles as $file) {
1270 $css .= file_get_contents($file)."\n";
1273 // If editor has SCSS, compile and include it.
1274 if (($convertedscss = $this->editor_scss_to_css())) {
1275 $css .= $convertedscss;
1278 $output = $this->post_process($css);
1280 return $output;
1284 * Returns an array of organised CSS files required for this output.
1286 * @param bool $themedesigner
1287 * @return array nested array of file paths
1289 protected function get_css_files($themedesigner) {
1290 global $CFG;
1292 $cache = null;
1293 $cachekey = 'cssfiles';
1294 if ($themedesigner) {
1295 require_once($CFG->dirroot.'/lib/csslib.php');
1296 // We need some kind of caching here because otherwise the page navigation becomes
1297 // way too slow in theme designer mode. Feel free to create full cache definition later...
1298 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
1299 if ($files = $cache->get($cachekey)) {
1300 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
1301 unset($files['created']);
1302 return $files;
1307 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
1309 // Get all plugin sheets.
1310 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
1311 if ($excludes !== true) {
1312 foreach (core_component::get_plugin_types() as $type=>$unused) {
1313 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
1314 continue;
1316 $plugins = core_component::get_plugin_list($type);
1317 foreach ($plugins as $plugin=>$fulldir) {
1318 if (!empty($excludes[$type]) and is_array($excludes[$type])
1319 and in_array($plugin, $excludes[$type])) {
1320 continue;
1323 // Get the CSS from the plugin.
1324 $sheetfile = "$fulldir/styles.css";
1325 if (is_readable($sheetfile)) {
1326 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
1329 // Create a list of candidate sheets from parents (direct parent last) and current theme.
1330 $candidates = array();
1331 foreach (array_reverse($this->parent_configs) as $parent_config) {
1332 $candidates[] = $parent_config->name;
1334 $candidates[] = $this->name;
1336 // Add the sheets found.
1337 foreach ($candidates as $candidate) {
1338 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1339 if (is_readable($sheetthemefile)) {
1340 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
1347 // Find out wanted parent sheets.
1348 $excludes = $this->resolve_excludes('parents_exclude_sheets');
1349 if ($excludes !== true) {
1350 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1351 $parent = $parent_config->name;
1352 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
1353 continue;
1355 foreach ($parent_config->sheets as $sheet) {
1356 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1357 && in_array($sheet, $excludes[$parent])) {
1358 continue;
1361 // We never refer to the parent LESS files.
1362 $sheetfile = "$parent_config->dir/style/$sheet.css";
1363 if (is_readable($sheetfile)) {
1364 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1371 // Current theme sheets.
1372 // We first add the SCSS file because we want the CSS ones to
1373 // be included after the SCSS code.
1374 if ($this->get_scss_property()) {
1375 $cssfiles['theme'][self::SCSS_KEY] = true;
1377 if (is_array($this->sheets)) {
1378 foreach ($this->sheets as $sheet) {
1379 $sheetfile = "$this->dir/style/$sheet.css";
1380 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1381 $cssfiles['theme'][$sheet] = $sheetfile;
1386 if ($cache) {
1387 $files = $cssfiles;
1388 $files['created'] = time();
1389 $cache->set($cachekey, $files);
1391 return $cssfiles;
1395 * Return the CSS content generated from the SCSS file.
1397 * @param bool $themedesigner True if theme designer is enabled.
1398 * @return bool|string Return false when the compilation failed. Else the compiled string.
1400 protected function get_css_content_from_scss($themedesigner) {
1401 global $CFG;
1403 list($paths, $scss) = $this->get_scss_property();
1404 if (!$scss) {
1405 throw new coding_exception('The theme did not define a SCSS file, or it is not readable.');
1408 // We might need more memory/time to do this, so let's play safe.
1409 raise_memory_limit(MEMORY_EXTRA);
1410 core_php_time_limit::raise(300);
1412 // TODO: MDL-62757 When changing anything in this method please do not forget to check
1413 // if the validate() method in class admin_setting_configthemepreset needs updating too.
1415 // Set-up the compiler.
1416 $compiler = new core_scss();
1417 $compiler->prepend_raw_scss($this->get_pre_scss_code());
1418 if (is_string($scss)) {
1419 $compiler->set_file($scss);
1420 } else {
1421 $compiler->append_raw_scss($scss($this));
1422 $compiler->setImportPaths($paths);
1424 $compiler->append_raw_scss($this->get_extra_scss_code());
1426 try {
1427 // Compile!
1428 $compiled = $compiler->to_css();
1430 } catch (\Exception $e) {
1431 $compiled = false;
1432 debugging('Error while compiling SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
1435 // Try to save memory.
1436 $compiler = null;
1437 unset($compiler);
1439 return $compiled;
1443 * Return the precompiled CSS if the precompiledcsscallback exists.
1445 * @return string Return compiled css.
1447 public function get_precompiled_css_content() {
1448 $configs = array_reverse($this->parent_configs) + [$this];
1449 $css = '';
1451 foreach ($configs as $config) {
1452 if (isset($config->precompiledcsscallback)) {
1453 $function = $config->precompiledcsscallback;
1454 if (function_exists($function)) {
1455 $css .= $function($this);
1459 return $css;
1463 * Get the icon system to use.
1465 * @return string
1467 public function get_icon_system() {
1469 // Getting all the candidate functions.
1470 $system = false;
1471 if (isset($this->iconsystem) && \core\output\icon_system::is_valid_system($this->iconsystem)) {
1472 return $this->iconsystem;
1474 foreach ($this->parent_configs as $parent_config) {
1475 if (isset($parent_config->iconsystem) && \core\output\icon_system::is_valid_system($parent_config->iconsystem)) {
1476 return $parent_config->iconsystem;
1479 return \core\output\icon_system::STANDARD;
1483 * Return extra SCSS code to add when compiling.
1485 * This is intended to be used by themes to inject some SCSS code
1486 * before it gets compiled. If you want to inject variables you
1487 * should use {@link self::get_scss_variables()}.
1489 * @return string The SCSS code to inject.
1491 public function get_extra_scss_code() {
1492 $content = '';
1494 // Getting all the candidate functions.
1495 $candidates = array();
1496 foreach ($this->parent_configs as $parent_config) {
1497 if (!isset($parent_config->extrascsscallback)) {
1498 continue;
1500 $candidates[] = $parent_config->extrascsscallback;
1502 $candidates[] = $this->extrascsscallback;
1504 // Calling the functions.
1505 foreach ($candidates as $function) {
1506 if (function_exists($function)) {
1507 $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n";
1511 return $content;
1515 * SCSS code to prepend when compiling.
1517 * This is intended to be used by themes to inject SCSS code before it gets compiled.
1519 * @return string The SCSS code to inject.
1521 public function get_pre_scss_code() {
1522 $content = '';
1524 // Getting all the candidate functions.
1525 $candidates = array();
1526 foreach ($this->parent_configs as $parent_config) {
1527 if (!isset($parent_config->prescsscallback)) {
1528 continue;
1530 $candidates[] = $parent_config->prescsscallback;
1532 $candidates[] = $this->prescsscallback;
1534 // Calling the functions.
1535 foreach ($candidates as $function) {
1536 if (function_exists($function)) {
1537 $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n";
1541 return $content;
1545 * Get the SCSS property.
1547 * This resolves whether a SCSS file (or content) has to be used when generating
1548 * the stylesheet for the theme. It will look at parents themes and check the
1549 * SCSS properties there.
1551 * @return False when SCSS is not used.
1552 * An array with the import paths, and the path to the SCSS file or Closure as second.
1554 public function get_scss_property() {
1555 if ($this->scsscache === null) {
1556 $configs = [$this] + $this->parent_configs;
1557 $scss = null;
1559 foreach ($configs as $config) {
1560 $path = "{$config->dir}/scss";
1562 // We collect the SCSS property until we've found one.
1563 if (empty($scss) && !empty($config->scss)) {
1564 $candidate = is_string($config->scss) ? "{$path}/{$config->scss}.scss" : $config->scss;
1565 if ($candidate instanceof Closure) {
1566 $scss = $candidate;
1567 } else if (is_string($candidate) && is_readable($candidate)) {
1568 $scss = $candidate;
1572 // We collect the import paths once we've found a SCSS property.
1573 if ($scss && is_dir($path)) {
1574 $paths[] = $path;
1579 $this->scsscache = $scss !== null ? [$paths, $scss] : false;
1582 return $this->scsscache;
1586 * Generate a URL to the file that serves theme JavaScript files.
1588 * If we determine that the theme has no relevant files, then we return
1589 * early with a null value.
1591 * @param bool $inhead true means head url, false means footer
1592 * @return moodle_url|null
1594 public function javascript_url($inhead) {
1595 global $CFG;
1597 $rev = theme_get_revision();
1598 $params = array('theme'=>$this->name,'rev'=>$rev);
1599 $params['type'] = $inhead ? 'head' : 'footer';
1601 // Return early if there are no files to serve
1602 if (count($this->javascript_files($params['type'])) === 0) {
1603 return null;
1606 if (!empty($CFG->slasharguments) and $rev > 0) {
1607 $url = new moodle_url("/theme/javascript.php");
1608 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
1609 return $url;
1610 } else {
1611 return new moodle_url('/theme/javascript.php', $params);
1616 * Get the URL's for the JavaScript files used by this theme.
1617 * They won't be served directly, instead they'll be mediated through
1618 * theme/javascript.php.
1620 * @param string $type Either javascripts_footer, or javascripts
1621 * @return array
1623 public function javascript_files($type) {
1624 if ($type === 'footer') {
1625 $type = 'javascripts_footer';
1626 } else {
1627 $type = 'javascripts';
1630 $js = array();
1631 // find out wanted parent javascripts
1632 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1633 if ($excludes !== true) {
1634 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1635 $parent = $parent_config->name;
1636 if (empty($parent_config->$type)) {
1637 continue;
1639 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1640 continue;
1642 foreach ($parent_config->$type as $javascript) {
1643 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1644 and in_array($javascript, $excludes[$parent])) {
1645 continue;
1647 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1648 if (is_readable($javascriptfile)) {
1649 $js[] = $javascriptfile;
1655 // current theme javascripts
1656 if (is_array($this->$type)) {
1657 foreach ($this->$type as $javascript) {
1658 $javascriptfile = "$this->dir/javascript/$javascript.js";
1659 if (is_readable($javascriptfile)) {
1660 $js[] = $javascriptfile;
1664 return $js;
1668 * Resolves an exclude setting to the themes setting is applicable or the
1669 * setting of its closest parent.
1671 * @param string $variable The name of the setting the exclude setting to resolve
1672 * @param string $default
1673 * @return mixed
1675 protected function resolve_excludes($variable, $default = null) {
1676 $setting = $default;
1677 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1678 $setting = $this->{$variable};
1679 } else {
1680 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1681 if (!isset($parent_config->{$variable})) {
1682 continue;
1684 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1685 $setting = $parent_config->{$variable};
1686 break;
1690 return $setting;
1694 * Returns the content of the one huge javascript file merged from all theme javascript files.
1696 * @param bool $type
1697 * @return string
1699 public function javascript_content($type) {
1700 $jsfiles = $this->javascript_files($type);
1701 $js = '';
1702 foreach ($jsfiles as $jsfile) {
1703 $js .= file_get_contents($jsfile)."\n";
1705 return $js;
1709 * Post processes CSS.
1711 * This method post processes all of the CSS before it is served for this theme.
1712 * This is done so that things such as image URL's can be swapped in and to
1713 * run any specific CSS post process method the theme has requested.
1714 * This allows themes to use CSS settings.
1716 * @param string $css The CSS to process.
1717 * @return string The processed CSS.
1719 public function post_process($css) {
1720 // now resolve all image locations
1721 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1722 $replaced = array();
1723 foreach ($matches as $match) {
1724 if (isset($replaced[$match[0]])) {
1725 continue;
1727 $replaced[$match[0]] = true;
1728 $imagename = $match[2];
1729 $component = rtrim($match[1], '|');
1730 $imageurl = $this->image_url($imagename, $component)->out(false);
1731 // we do not need full url because the image.php is always in the same dir
1732 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1733 $css = str_replace($match[0], $imageurl, $css);
1737 // Now resolve all font locations.
1738 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1739 $replaced = array();
1740 foreach ($matches as $match) {
1741 if (isset($replaced[$match[0]])) {
1742 continue;
1744 $replaced[$match[0]] = true;
1745 $fontname = $match[2];
1746 $component = rtrim($match[1], '|');
1747 $fonturl = $this->font_url($fontname, $component)->out(false);
1748 // We do not need full url because the font.php is always in the same dir.
1749 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1750 $css = str_replace($match[0], $fonturl, $css);
1754 // Now resolve all theme settings or do any other postprocessing.
1755 // This needs to be done before calling core parser, since the parser strips [[settings]] tags.
1756 $csspostprocess = $this->csspostprocess;
1757 if (function_exists($csspostprocess)) {
1758 $css = $csspostprocess($css, $this);
1761 // Post processing using an object representation of CSS.
1762 $treeprocessor = $this->get_css_tree_post_processor();
1763 $needsparsing = !empty($treeprocessor) || !empty($this->rtlmode);
1764 if ($needsparsing) {
1766 // We might need more memory/time to do this, so let's play safe.
1767 raise_memory_limit(MEMORY_EXTRA);
1768 core_php_time_limit::raise(300);
1770 $parser = new core_cssparser($css);
1771 $csstree = $parser->parse();
1772 unset($parser);
1774 if ($this->rtlmode) {
1775 $this->rtlize($csstree);
1778 if ($treeprocessor) {
1779 $treeprocessor($csstree, $this);
1782 $css = $csstree->render();
1783 unset($csstree);
1786 return $css;
1790 * Flip a stylesheet to RTL.
1792 * @param Object $csstree The parsed CSS tree structure to flip.
1793 * @return void
1795 protected function rtlize($csstree) {
1796 $rtlcss = new core_rtlcss($csstree);
1797 $rtlcss->flip();
1801 * Return the direct URL for an image from the pix folder.
1803 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1805 * @deprecated since Moodle 3.3
1806 * @param string $imagename the name of the icon.
1807 * @param string $component specification of one plugin like in get_string()
1808 * @return moodle_url
1810 public function pix_url($imagename, $component) {
1811 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
1812 return $this->image_url($imagename, $component);
1816 * Return the direct URL for an image from the pix folder.
1818 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1820 * @param string $imagename the name of the icon.
1821 * @param string $component specification of one plugin like in get_string()
1822 * @return moodle_url
1824 public function image_url($imagename, $component) {
1825 global $CFG;
1827 $params = array('theme'=>$this->name);
1828 $svg = $this->use_svg_icons();
1830 if (empty($component) or $component === 'moodle' or $component === 'core') {
1831 $params['component'] = 'core';
1832 } else {
1833 $params['component'] = $component;
1836 $rev = theme_get_revision();
1837 if ($rev != -1) {
1838 $params['rev'] = $rev;
1841 $params['image'] = $imagename;
1843 $url = new moodle_url("/theme/image.php");
1844 if (!empty($CFG->slasharguments) and $rev > 0) {
1845 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1846 if (!$svg) {
1847 // We add a simple /_s to the start of the path.
1848 // The underscore is used to ensure that it isn't a valid theme name.
1849 $path = '/_s'.$path;
1851 $url->set_slashargument($path, 'noparam', true);
1852 } else {
1853 if (!$svg) {
1854 // We add an SVG param so that we know not to serve SVG images.
1855 // We do this because all modern browsers support SVG and this param will one day be removed.
1856 $params['svg'] = '0';
1858 $url->params($params);
1861 return $url;
1865 * Return the URL for a font
1867 * @param string $font the name of the font (including extension).
1868 * @param string $component specification of one plugin like in get_string()
1869 * @return moodle_url
1871 public function font_url($font, $component) {
1872 global $CFG;
1874 $params = array('theme'=>$this->name);
1876 if (empty($component) or $component === 'moodle' or $component === 'core') {
1877 $params['component'] = 'core';
1878 } else {
1879 $params['component'] = $component;
1882 $rev = theme_get_revision();
1883 if ($rev != -1) {
1884 $params['rev'] = $rev;
1887 $params['font'] = $font;
1889 $url = new moodle_url("/theme/font.php");
1890 if (!empty($CFG->slasharguments) and $rev > 0) {
1891 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1892 $url->set_slashargument($path, 'noparam', true);
1893 } else {
1894 $url->params($params);
1897 return $url;
1901 * Returns URL to the stored file via pluginfile.php.
1903 * Note the theme must also implement pluginfile.php handler,
1904 * theme revision is used instead of the itemid.
1906 * @param string $setting
1907 * @param string $filearea
1908 * @return string protocol relative URL or null if not present
1910 public function setting_file_url($setting, $filearea) {
1911 global $CFG;
1913 if (empty($this->settings->$setting)) {
1914 return null;
1917 $component = 'theme_'.$this->name;
1918 $itemid = theme_get_revision();
1919 $filepath = $this->settings->$setting;
1920 $syscontext = context_system::instance();
1922 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1924 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1925 // Note: unfortunately moodle_url does not support //urls yet.
1927 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1929 return $url;
1933 * Serve the theme setting file.
1935 * @param string $filearea
1936 * @param array $args
1937 * @param bool $forcedownload
1938 * @param array $options
1939 * @return bool may terminate if file not found or donotdie not specified
1941 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1942 global $CFG;
1943 require_once("$CFG->libdir/filelib.php");
1945 $syscontext = context_system::instance();
1946 $component = 'theme_'.$this->name;
1948 $revision = array_shift($args);
1949 if ($revision < 0) {
1950 $lifetime = 0;
1951 } else {
1952 $lifetime = 60*60*24*60;
1953 // By default, theme files must be cache-able by both browsers and proxies.
1954 if (!array_key_exists('cacheability', $options)) {
1955 $options['cacheability'] = 'public';
1959 $fs = get_file_storage();
1960 $relativepath = implode('/', $args);
1962 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1963 $fullpath = rtrim($fullpath, '/');
1964 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1965 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1966 return true;
1967 } else {
1968 send_file_not_found();
1973 * Resolves the real image location.
1975 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1976 * and we need a way in which to turn it off.
1977 * By default SVG won't be used unless asked for. This is done for two reasons:
1978 * 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
1979 * browser supports SVG.
1980 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1981 * by the user due to security concerns.
1983 * @param string $image name of image, may contain relative path
1984 * @param string $component
1985 * @param bool $svg|null Should SVG images also be looked for? If null, resorts to $CFG->svgicons if that is set; falls back to
1986 * auto-detection of browser support otherwise
1987 * @return string full file path
1989 public function resolve_image_location($image, $component, $svg = false) {
1990 global $CFG;
1992 if (!is_bool($svg)) {
1993 // If $svg isn't a bool then we need to decide for ourselves.
1994 $svg = $this->use_svg_icons();
1997 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1998 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1999 return $imagefile;
2001 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2002 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
2003 return $imagefile;
2006 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
2007 return $imagefile;
2009 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
2010 return $imagefile;
2012 return null;
2014 } else if ($component === 'theme') { //exception
2015 if ($image === 'favicon') {
2016 return "$this->dir/pix/favicon.ico";
2018 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
2019 return $imagefile;
2021 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2022 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
2023 return $imagefile;
2026 return null;
2028 } else {
2029 if (strpos($component, '_') === false) {
2030 $component = 'mod_'.$component;
2032 list($type, $plugin) = explode('_', $component, 2);
2034 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2035 return $imagefile;
2037 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2038 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2039 return $imagefile;
2042 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
2043 return $imagefile;
2045 $dir = core_component::get_plugin_directory($type, $plugin);
2046 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
2047 return $imagefile;
2049 return null;
2054 * Resolves the real font location.
2056 * @param string $font name of font file
2057 * @param string $component
2058 * @return string full file path
2060 public function resolve_font_location($font, $component) {
2061 global $CFG;
2063 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2064 if (file_exists("$this->dir/fonts_core/$font")) {
2065 return "$this->dir/fonts_core/$font";
2067 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2068 if (file_exists("$parent_config->dir/fonts_core/$font")) {
2069 return "$parent_config->dir/fonts_core/$font";
2072 if (file_exists("$CFG->dataroot/fonts/$font")) {
2073 return "$CFG->dataroot/fonts/$font";
2075 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
2076 return "$CFG->dirroot/lib/fonts/$font";
2078 return null;
2080 } else if ($component === 'theme') { // Exception.
2081 if (file_exists("$this->dir/fonts/$font")) {
2082 return "$this->dir/fonts/$font";
2084 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2085 if (file_exists("$parent_config->dir/fonts/$font")) {
2086 return "$parent_config->dir/fonts/$font";
2089 return null;
2091 } else {
2092 if (strpos($component, '_') === false) {
2093 $component = 'mod_'.$component;
2095 list($type, $plugin) = explode('_', $component, 2);
2097 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
2098 return "$this->dir/fonts_plugins/$type/$plugin/$font";
2100 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2101 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
2102 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
2105 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
2106 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
2108 $dir = core_component::get_plugin_directory($type, $plugin);
2109 if (file_exists("$dir/fonts/$font")) {
2110 return "$dir/fonts/$font";
2112 return null;
2117 * Return true if we should look for SVG images as well.
2119 * @return bool
2121 public function use_svg_icons() {
2122 global $CFG;
2123 if ($this->usesvg === null) {
2125 if (!isset($CFG->svgicons)) {
2126 $this->usesvg = core_useragent::supports_svg();
2127 } else {
2128 // Force them on/off depending upon the setting.
2129 $this->usesvg = (bool)$CFG->svgicons;
2132 return $this->usesvg;
2136 * Forces the usesvg setting to either true or false, avoiding any decision making.
2138 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
2139 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
2141 * @param bool $setting True to force the use of svg when available, null otherwise.
2143 public function force_svg_use($setting) {
2144 $this->usesvg = (bool)$setting;
2148 * Set to be in RTL mode.
2150 * This will likely be used when post processing the CSS before serving it.
2152 * @param bool $inrtl True when in RTL mode.
2154 public function set_rtl_mode($inrtl = true) {
2155 $this->rtlmode = $inrtl;
2159 * Whether the theme is being served in RTL mode.
2161 * @return bool True when in RTL mode.
2163 public function get_rtl_mode() {
2164 return $this->rtlmode;
2168 * Checks if file with any image extension exists.
2170 * The order to these images was adjusted prior to the release of 2.4
2171 * At that point the were the following image counts in Moodle core:
2173 * - png = 667 in pix dirs (1499 total)
2174 * - gif = 385 in pix dirs (606 total)
2175 * - jpg = 62 in pix dirs (74 total)
2176 * - jpeg = 0 in pix dirs (1 total)
2178 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
2180 * @param string $filepath
2181 * @param bool $svg If set to true SVG images will also be looked for.
2182 * @return string image name with extension
2184 private static function image_exists($filepath, $svg = false) {
2185 if ($svg && file_exists("$filepath.svg")) {
2186 return "$filepath.svg";
2187 } else if (file_exists("$filepath.png")) {
2188 return "$filepath.png";
2189 } else if (file_exists("$filepath.gif")) {
2190 return "$filepath.gif";
2191 } else if (file_exists("$filepath.jpg")) {
2192 return "$filepath.jpg";
2193 } else if (file_exists("$filepath.jpeg")) {
2194 return "$filepath.jpeg";
2195 } else {
2196 return false;
2201 * Loads the theme config from config.php file.
2203 * @param string $themename
2204 * @param stdClass $settings from config_plugins table
2205 * @param boolean $parentscheck true to also check the parents. .
2206 * @return stdClass The theme configuration
2208 private static function find_theme_config($themename, $settings, $parentscheck = true) {
2209 // We have to use the variable name $THEME (upper case) because that
2210 // is what is used in theme config.php files.
2212 if (!$dir = theme_config::find_theme_location($themename)) {
2213 return null;
2216 $THEME = new stdClass();
2217 $THEME->name = $themename;
2218 $THEME->dir = $dir;
2219 $THEME->settings = $settings;
2221 global $CFG; // just in case somebody tries to use $CFG in theme config
2222 include("$THEME->dir/config.php");
2224 // verify the theme configuration is OK
2225 if (!is_array($THEME->parents)) {
2226 // parents option is mandatory now
2227 return null;
2228 } else {
2229 // We use $parentscheck to only check the direct parents (avoid infinite loop).
2230 if ($parentscheck) {
2231 // Find all parent theme configs.
2232 foreach ($THEME->parents as $parent) {
2233 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
2234 if (empty($parentconfig)) {
2235 return null;
2241 return $THEME;
2245 * Finds the theme location and verifies the theme has all needed files
2246 * and is not obsoleted.
2248 * @param string $themename
2249 * @return string full dir path or null if not found
2251 private static function find_theme_location($themename) {
2252 global $CFG;
2254 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2255 $dir = "$CFG->dirroot/theme/$themename";
2257 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
2258 $dir = "$CFG->themedir/$themename";
2260 } else {
2261 return null;
2264 if (file_exists("$dir/styles.php")) {
2265 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
2266 return null;
2269 return $dir;
2273 * Get the renderer for a part of Moodle for this theme.
2275 * @param moodle_page $page the page we are rendering
2276 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
2277 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
2278 * @param string $target one of rendering target constants
2279 * @return renderer_base the requested renderer.
2281 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
2282 if (is_null($this->rf)) {
2283 $classname = $this->rendererfactory;
2284 $this->rf = new $classname($this);
2287 return $this->rf->get_renderer($page, $component, $subtype, $target);
2291 * Get the information from {@link $layouts} for this type of page.
2293 * @param string $pagelayout the the page layout name.
2294 * @return array the appropriate part of {@link $layouts}.
2296 protected function layout_info_for_page($pagelayout) {
2297 if (array_key_exists($pagelayout, $this->layouts)) {
2298 return $this->layouts[$pagelayout];
2299 } else {
2300 debugging('Invalid page layout specified: ' . $pagelayout);
2301 return $this->layouts['standard'];
2306 * Given the settings of this theme, and the page pagelayout, return the
2307 * full path of the page layout file to use.
2309 * Used by {@link core_renderer::header()}.
2311 * @param string $pagelayout the the page layout name.
2312 * @return string Full path to the lyout file to use
2314 public function layout_file($pagelayout) {
2315 global $CFG;
2317 $layoutinfo = $this->layout_info_for_page($pagelayout);
2318 $layoutfile = $layoutinfo['file'];
2320 if (array_key_exists('theme', $layoutinfo)) {
2321 $themes = array($layoutinfo['theme']);
2322 } else {
2323 $themes = array_merge(array($this->name),$this->parents);
2326 foreach ($themes as $theme) {
2327 if ($dir = $this->find_theme_location($theme)) {
2328 $path = "$dir/layout/$layoutfile";
2330 // Check the template exists, return general base theme template if not.
2331 if (is_readable($path)) {
2332 return $path;
2337 debugging('Can not find layout file for: ' . $pagelayout);
2338 // fallback to standard normal layout
2339 return "$CFG->dirroot/theme/base/layout/general.php";
2343 * Returns auxiliary page layout options specified in layout configuration array.
2345 * @param string $pagelayout
2346 * @return array
2348 public function pagelayout_options($pagelayout) {
2349 $info = $this->layout_info_for_page($pagelayout);
2350 if (!empty($info['options'])) {
2351 return $info['options'];
2353 return array();
2357 * Inform a block_manager about the block regions this theme wants on this
2358 * page layout.
2360 * @param string $pagelayout the general type of the page.
2361 * @param block_manager $blockmanager the block_manger to set up.
2363 public function setup_blocks($pagelayout, $blockmanager) {
2364 $layoutinfo = $this->layout_info_for_page($pagelayout);
2365 if (!empty($layoutinfo['regions'])) {
2366 $blockmanager->add_regions($layoutinfo['regions'], false);
2367 $blockmanager->set_default_region($layoutinfo['defaultregion']);
2372 * Gets the visible name for the requested block region.
2374 * @param string $region The region name to get
2375 * @param string $theme The theme the region belongs to (may come from the parent theme)
2376 * @return string
2378 protected function get_region_name($region, $theme) {
2379 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
2380 // A name exists in this theme, so use it
2381 if (substr($regionstring, 0, 1) != '[') {
2382 return $regionstring;
2385 // Otherwise, try to find one elsewhere
2386 // Check parents, if any
2387 foreach ($this->parents as $parentthemename) {
2388 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
2389 if (substr($regionstring, 0, 1) != '[') {
2390 return $regionstring;
2394 // Last resort, try the boost theme for names
2395 return get_string('region-' . $region, 'theme_boost');
2399 * Get the list of all block regions known to this theme in all templates.
2401 * @return array internal region name => human readable name.
2403 public function get_all_block_regions() {
2404 $regions = array();
2405 foreach ($this->layouts as $layoutinfo) {
2406 foreach ($layoutinfo['regions'] as $region) {
2407 $regions[$region] = $this->get_region_name($region, $this->name);
2410 return $regions;
2414 * Returns the human readable name of the theme
2416 * @return string
2418 public function get_theme_name() {
2419 return get_string('pluginname', 'theme_'.$this->name);
2423 * Returns the block render method.
2425 * It is set by the theme via:
2426 * $THEME->blockrendermethod = '...';
2428 * It can be one of two values, blocks or blocks_for_region.
2429 * It should be set to the method being used by the theme layouts.
2431 * @return string
2433 public function get_block_render_method() {
2434 if ($this->blockrendermethod) {
2435 // Return the specified block render method.
2436 return $this->blockrendermethod;
2438 // Its not explicitly set, check the parent theme configs.
2439 foreach ($this->parent_configs as $config) {
2440 if (isset($config->blockrendermethod)) {
2441 return $config->blockrendermethod;
2444 // Default it to blocks.
2445 return 'blocks';
2449 * Get the callable for CSS tree post processing.
2451 * @return string|null
2453 public function get_css_tree_post_processor() {
2454 $configs = [$this] + $this->parent_configs;
2455 foreach ($configs as $config) {
2456 if (!empty($config->csstreepostprocessor) && is_callable($config->csstreepostprocessor)) {
2457 return $config->csstreepostprocessor;
2460 return null;
2466 * This class keeps track of which HTML tags are currently open.
2468 * This makes it much easier to always generate well formed XHTML output, even
2469 * if execution terminates abruptly. Any time you output some opening HTML
2470 * without the matching closing HTML, you should push the necessary close tags
2471 * onto the stack.
2473 * @copyright 2009 Tim Hunt
2474 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2475 * @since Moodle 2.0
2476 * @package core
2477 * @category output
2479 class xhtml_container_stack {
2482 * @var array Stores the list of open containers.
2484 protected $opencontainers = array();
2487 * @var array In developer debug mode, stores a stack trace of all opens and
2488 * closes, so we can output helpful error messages when there is a mismatch.
2490 protected $log = array();
2493 * @var boolean Store whether we are developer debug mode. We need this in
2494 * several places including in the destructor where we may not have access to $CFG.
2496 protected $isdebugging;
2499 * Constructor
2501 public function __construct() {
2502 global $CFG;
2503 $this->isdebugging = $CFG->debugdeveloper;
2507 * Push the close HTML for a recently opened container onto the stack.
2509 * @param string $type The type of container. This is checked when {@link pop()}
2510 * is called and must match, otherwise a developer debug warning is output.
2511 * @param string $closehtml The HTML required to close the container.
2513 public function push($type, $closehtml) {
2514 $container = new stdClass;
2515 $container->type = $type;
2516 $container->closehtml = $closehtml;
2517 if ($this->isdebugging) {
2518 $this->log('Open', $type);
2520 array_push($this->opencontainers, $container);
2524 * Pop the HTML for the next closing container from the stack. The $type
2525 * must match the type passed when the container was opened, otherwise a
2526 * warning will be output.
2528 * @param string $type The type of container.
2529 * @return string the HTML required to close the container.
2531 public function pop($type) {
2532 if (empty($this->opencontainers)) {
2533 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2534 $this->output_log(), DEBUG_DEVELOPER);
2535 return;
2538 $container = array_pop($this->opencontainers);
2539 if ($container->type != $type) {
2540 debugging('<p>The type of container to be closed (' . $container->type .
2541 ') does not match the type of the next open container (' . $type .
2542 '). This suggests there is a nesting problem.</p>' .
2543 $this->output_log(), DEBUG_DEVELOPER);
2545 if ($this->isdebugging) {
2546 $this->log('Close', $type);
2548 return $container->closehtml;
2552 * Close all but the last open container. This is useful in places like error
2553 * handling, where you want to close all the open containers (apart from <body>)
2554 * before outputting the error message.
2556 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2557 * developer debug warning if it isn't.
2558 * @return string the HTML required to close any open containers inside <body>.
2560 public function pop_all_but_last($shouldbenone = false) {
2561 if ($shouldbenone && count($this->opencontainers) != 1) {
2562 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2563 $this->output_log(), DEBUG_DEVELOPER);
2565 $output = '';
2566 while (count($this->opencontainers) > 1) {
2567 $container = array_pop($this->opencontainers);
2568 $output .= $container->closehtml;
2570 return $output;
2574 * You can call this function if you want to throw away an instance of this
2575 * class without properly emptying the stack (for example, in a unit test).
2576 * Calling this method stops the destruct method from outputting a developer
2577 * debug warning. After calling this method, the instance can no longer be used.
2579 public function discard() {
2580 $this->opencontainers = null;
2584 * Adds an entry to the log.
2586 * @param string $action The name of the action
2587 * @param string $type The type of action
2589 protected function log($action, $type) {
2590 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
2591 format_backtrace(debug_backtrace()) . '</li>';
2595 * Outputs the log's contents as a HTML list.
2597 * @return string HTML list of the log
2599 protected function output_log() {
2600 return '<ul>' . implode("\n", $this->log) . '</ul>';