Merge branch 'MDL-68861-master' of git://github.com/vmdef/moodle
[moodle.git] / lib / outputlib.php
blobe7cb41e7c390a48bb052b47ef9a1a6b0a7270f8f
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 = '';
964 $dir = $this->dir;
965 $filenames = [];
967 // Use editor_scss file(s) provided by this theme if set.
968 if (!empty($this->editor_scss)) {
969 $filenames = $this->editor_scss;
970 } else {
971 // If no editor_scss set, move up theme hierarchy until one is found (if at all).
972 // This is so child themes only need to set editor_scss if an override is required.
973 foreach (array_reverse($this->parent_configs) as $parentconfig) {
974 if (!empty($parentconfig->editor_scss)) {
975 $dir = $parentconfig->dir;
976 $filenames = $parentconfig->editor_scss;
978 // Config found, stop looking.
979 break;
984 if (!empty($filenames)) {
985 $compiler = new core_scss();
987 foreach ($filenames as $filename) {
988 $compiler->set_file("{$dir}/scss/{$filename}.scss");
990 try {
991 $css .= $compiler->to_css();
992 } catch (\Exception $e) {
993 debugging('Error while compiling editor SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
998 return $css;
1002 * Get the stylesheet URL of this theme.
1004 * @param moodle_page $page Not used... deprecated?
1005 * @return moodle_url[]
1007 public function css_urls(moodle_page $page) {
1008 global $CFG;
1010 $rev = theme_get_revision();
1012 $urls = array();
1014 $svg = $this->use_svg_icons();
1015 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
1017 if ($rev > -1) {
1018 $filename = right_to_left() ? 'all-rtl' : 'all';
1019 $url = new moodle_url("/theme/styles.php");
1020 $themesubrevision = theme_get_sub_revision_for_theme($this->name);
1022 // Provide the sub revision to allow us to invalidate cached theme CSS
1023 // on a per theme basis, rather than globally.
1024 if ($themesubrevision && $themesubrevision > 0) {
1025 $rev .= "_{$themesubrevision}";
1028 if (!empty($CFG->slasharguments)) {
1029 $slashargs = '';
1030 if (!$svg) {
1031 // We add a simple /_s to the start of the path.
1032 // The underscore is used to ensure that it isn't a valid theme name.
1033 $slashargs .= '/_s'.$slashargs;
1035 $slashargs .= '/'.$this->name.'/'.$rev.'/'.$filename;
1036 if ($separate) {
1037 $slashargs .= '/chunk0';
1039 $url->set_slashargument($slashargs, 'noparam', true);
1040 } else {
1041 $params = array('theme' => $this->name, 'rev' => $rev, 'type' => $filename);
1042 if (!$svg) {
1043 // We add an SVG param so that we know not to serve SVG images.
1044 // We do this because all modern browsers support SVG and this param will one day be removed.
1045 $params['svg'] = '0';
1047 if ($separate) {
1048 $params['chunk'] = '0';
1050 $url->params($params);
1052 $urls[] = $url;
1054 } else {
1055 $baseurl = new moodle_url('/theme/styles_debug.php');
1057 $css = $this->get_css_files(true);
1058 if (!$svg) {
1059 // We add an SVG param so that we know not to serve SVG images.
1060 // We do this because all modern browsers support SVG and this param will one day be removed.
1061 $baseurl->param('svg', '0');
1063 if (right_to_left()) {
1064 $baseurl->param('rtl', 1);
1066 if ($separate) {
1067 // We might need to chunk long files.
1068 $baseurl->param('chunk', '0');
1070 if (core_useragent::is_ie()) {
1071 // Lalala, IE does not allow more than 31 linked CSS files from main document.
1072 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
1073 foreach ($css['parents'] as $parent=>$sheets) {
1074 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
1075 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
1077 if ($this->get_scss_property()) {
1078 // No need to define the type as IE here.
1079 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
1081 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
1083 } else {
1084 foreach ($css['plugins'] as $plugin=>$unused) {
1085 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
1087 foreach ($css['parents'] as $parent=>$sheets) {
1088 foreach ($sheets as $sheet=>$unused2) {
1089 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
1092 foreach ($css['theme'] as $sheet => $filename) {
1093 if ($sheet === self::SCSS_KEY) {
1094 // This is the theme SCSS file.
1095 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
1096 } else {
1097 // Sheet first in order to make long urls easier to read.
1098 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
1104 // Allow themes to change the css url to something like theme/mytheme/mycss.php.
1105 component_callback('theme_' . $this->name, 'alter_css_urls', [&$urls]);
1106 return $urls;
1110 * Get the whole css stylesheet for production mode.
1112 * NOTE: this method is not expected to be used from any addons.
1114 * @return string CSS markup compressed
1116 public function get_css_content() {
1118 $csscontent = '';
1119 foreach ($this->get_css_files(false) as $type => $value) {
1120 foreach ($value as $identifier => $val) {
1121 if (is_array($val)) {
1122 foreach ($val as $v) {
1123 $csscontent .= file_get_contents($v) . "\n";
1125 } else {
1126 if ($type === 'theme' && $identifier === self::SCSS_KEY) {
1127 // We need the content from SCSS because this is the SCSS file from the theme.
1128 if ($compiled = $this->get_css_content_from_scss(false)) {
1129 $csscontent .= $compiled;
1130 } else {
1131 // The compiler failed so default back to any precompiled css that might
1132 // exist.
1133 $csscontent .= $this->get_precompiled_css_content();
1135 } else {
1136 $csscontent .= file_get_contents($val) . "\n";
1141 $csscontent = $this->post_process($csscontent);
1142 $csscontent = core_minify::css($csscontent);
1144 return $csscontent;
1147 * Set post processed CSS content cache.
1149 * @param string $csscontent The post processed CSS content.
1150 * @return bool True if the content was successfully cached.
1152 public function set_css_content_cache($csscontent) {
1154 $cache = cache::make('core', 'postprocessedcss');
1155 $key = $this->get_css_cache_key();
1157 return $cache->set($key, $csscontent);
1161 * Return whether the post processed CSS content has been cached.
1163 * @return bool Whether the post-processed CSS is available in the cache.
1165 public function has_css_cached_content() {
1167 $key = $this->get_css_cache_key();
1168 $cache = cache::make('core', 'postprocessedcss');
1170 return $cache->has($key);
1174 * Return cached post processed CSS content.
1176 * @return bool|string The cached css content or false if not found.
1178 public function get_css_cached_content() {
1180 $key = $this->get_css_cache_key();
1181 $cache = cache::make('core', 'postprocessedcss');
1183 return $cache->get($key);
1187 * Generate the css content cache key.
1189 * @return string The post processed css cache key.
1191 public function get_css_cache_key() {
1192 $nosvg = (!$this->use_svg_icons()) ? 'nosvg_' : '';
1193 $rtlmode = ($this->rtlmode == true) ? 'rtl' : 'ltr';
1195 return $nosvg . $this->name . '_' . $rtlmode;
1199 * Get the theme designer css markup,
1200 * the parameters are coming from css_urls().
1202 * NOTE: this method is not expected to be used from any addons.
1204 * @param string $type
1205 * @param string $subtype
1206 * @param string $sheet
1207 * @return string CSS markup
1209 public function get_css_content_debug($type, $subtype, $sheet) {
1210 if ($type === 'scss') {
1211 // The SCSS file of the theme is requested.
1212 $csscontent = $this->get_css_content_from_scss(true);
1213 if ($csscontent !== false) {
1214 return $this->post_process($csscontent);
1216 return '';
1219 $cssfiles = array();
1220 $css = $this->get_css_files(true);
1222 if ($type === 'ie') {
1223 // IE is a sloppy browser with weird limits, sorry.
1224 if ($subtype === 'plugins') {
1225 $cssfiles = $css['plugins'];
1227 } else if ($subtype === 'parents') {
1228 if (empty($sheet)) {
1229 // Do not bother with the empty parent here.
1230 } else {
1231 // Build up the CSS for that parent so we can serve it as one file.
1232 foreach ($css[$subtype][$sheet] as $parent => $css) {
1233 $cssfiles[] = $css;
1236 } else if ($subtype === 'theme') {
1237 $cssfiles = $css['theme'];
1238 foreach ($cssfiles as $key => $value) {
1239 if (in_array($key, [self::SCSS_KEY])) {
1240 // Remove the SCSS file from the theme CSS files.
1241 // The SCSS files use the type 'scss', not 'ie'.
1242 unset($cssfiles[$key]);
1247 } else if ($type === 'plugin') {
1248 if (isset($css['plugins'][$subtype])) {
1249 $cssfiles[] = $css['plugins'][$subtype];
1252 } else if ($type === 'parent') {
1253 if (isset($css['parents'][$subtype][$sheet])) {
1254 $cssfiles[] = $css['parents'][$subtype][$sheet];
1257 } else if ($type === 'theme') {
1258 if (isset($css['theme'][$sheet])) {
1259 $cssfiles[] = $css['theme'][$sheet];
1263 $csscontent = '';
1264 foreach ($cssfiles as $file) {
1265 $contents = file_get_contents($file);
1266 $contents = $this->post_process($contents);
1267 $comment = "/** Path: $type $subtype $sheet.' **/\n";
1268 $stats = '';
1269 $csscontent .= $comment.$stats.$contents."\n\n";
1272 return $csscontent;
1276 * Get the whole css stylesheet for editor iframe.
1278 * NOTE: this method is not expected to be used from any addons.
1280 * @return string CSS markup
1282 public function get_css_content_editor() {
1283 $css = '';
1284 $cssfiles = $this->editor_css_files();
1286 // If editor has static CSS, include it.
1287 foreach ($cssfiles as $file) {
1288 $css .= file_get_contents($file)."\n";
1291 // If editor has SCSS, compile and include it.
1292 if (($convertedscss = $this->editor_scss_to_css())) {
1293 $css .= $convertedscss;
1296 $output = $this->post_process($css);
1298 return $output;
1302 * Returns an array of organised CSS files required for this output.
1304 * @param bool $themedesigner
1305 * @return array nested array of file paths
1307 protected function get_css_files($themedesigner) {
1308 global $CFG;
1310 $cache = null;
1311 $cachekey = 'cssfiles';
1312 if ($themedesigner) {
1313 require_once($CFG->dirroot.'/lib/csslib.php');
1314 // We need some kind of caching here because otherwise the page navigation becomes
1315 // way too slow in theme designer mode. Feel free to create full cache definition later...
1316 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
1317 if ($files = $cache->get($cachekey)) {
1318 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
1319 unset($files['created']);
1320 return $files;
1325 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
1327 // Get all plugin sheets.
1328 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
1329 if ($excludes !== true) {
1330 foreach (core_component::get_plugin_types() as $type=>$unused) {
1331 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
1332 continue;
1334 $plugins = core_component::get_plugin_list($type);
1335 foreach ($plugins as $plugin=>$fulldir) {
1336 if (!empty($excludes[$type]) and is_array($excludes[$type])
1337 and in_array($plugin, $excludes[$type])) {
1338 continue;
1341 // Get the CSS from the plugin.
1342 $sheetfile = "$fulldir/styles.css";
1343 if (is_readable($sheetfile)) {
1344 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
1347 // Create a list of candidate sheets from parents (direct parent last) and current theme.
1348 $candidates = array();
1349 foreach (array_reverse($this->parent_configs) as $parent_config) {
1350 $candidates[] = $parent_config->name;
1352 $candidates[] = $this->name;
1354 // Add the sheets found.
1355 foreach ($candidates as $candidate) {
1356 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1357 if (is_readable($sheetthemefile)) {
1358 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
1365 // Find out wanted parent sheets.
1366 $excludes = $this->resolve_excludes('parents_exclude_sheets');
1367 if ($excludes !== true) {
1368 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1369 $parent = $parent_config->name;
1370 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
1371 continue;
1373 foreach ($parent_config->sheets as $sheet) {
1374 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1375 && in_array($sheet, $excludes[$parent])) {
1376 continue;
1379 // We never refer to the parent LESS files.
1380 $sheetfile = "$parent_config->dir/style/$sheet.css";
1381 if (is_readable($sheetfile)) {
1382 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1389 // Current theme sheets.
1390 // We first add the SCSS file because we want the CSS ones to
1391 // be included after the SCSS code.
1392 if ($this->get_scss_property()) {
1393 $cssfiles['theme'][self::SCSS_KEY] = true;
1395 if (is_array($this->sheets)) {
1396 foreach ($this->sheets as $sheet) {
1397 $sheetfile = "$this->dir/style/$sheet.css";
1398 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1399 $cssfiles['theme'][$sheet] = $sheetfile;
1404 if ($cache) {
1405 $files = $cssfiles;
1406 $files['created'] = time();
1407 $cache->set($cachekey, $files);
1409 return $cssfiles;
1413 * Return the CSS content generated from the SCSS file.
1415 * @param bool $themedesigner True if theme designer is enabled.
1416 * @return bool|string Return false when the compilation failed. Else the compiled string.
1418 protected function get_css_content_from_scss($themedesigner) {
1419 global $CFG;
1421 list($paths, $scss) = $this->get_scss_property();
1422 if (!$scss) {
1423 throw new coding_exception('The theme did not define a SCSS file, or it is not readable.');
1426 // We might need more memory/time to do this, so let's play safe.
1427 raise_memory_limit(MEMORY_EXTRA);
1428 core_php_time_limit::raise(300);
1430 // TODO: MDL-62757 When changing anything in this method please do not forget to check
1431 // if the validate() method in class admin_setting_configthemepreset needs updating too.
1432 $cacheoptions = '';
1433 if ($themedesigner) {
1434 $scsscachedir = $CFG->localcachedir . '/scsscache/';
1435 $cacheoptions = array(
1436 'cacheDir' => $scsscachedir,
1437 'prefix' => 'scssphp_',
1438 'forceRefresh' => false,
1441 // Set-up the compiler.
1442 $compiler = new core_scss($cacheoptions);
1443 $compiler->prepend_raw_scss($this->get_pre_scss_code());
1444 if (is_string($scss)) {
1445 $compiler->set_file($scss);
1446 } else {
1447 $compiler->append_raw_scss($scss($this));
1448 $compiler->setImportPaths($paths);
1450 $compiler->append_raw_scss($this->get_extra_scss_code());
1452 try {
1453 // Compile!
1454 $compiled = $compiler->to_css();
1456 } catch (\Exception $e) {
1457 $compiled = false;
1458 debugging('Error while compiling SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
1461 // Try to save memory.
1462 $compiler = null;
1463 unset($compiler);
1465 return $compiled;
1469 * Return the precompiled CSS if the precompiledcsscallback exists.
1471 * @return string Return compiled css.
1473 public function get_precompiled_css_content() {
1474 $configs = array_reverse($this->parent_configs) + [$this];
1475 $css = '';
1477 foreach ($configs as $config) {
1478 if (isset($config->precompiledcsscallback)) {
1479 $function = $config->precompiledcsscallback;
1480 if (function_exists($function)) {
1481 $css .= $function($this);
1485 return $css;
1489 * Get the icon system to use.
1491 * @return string
1493 public function get_icon_system() {
1495 // Getting all the candidate functions.
1496 $system = false;
1497 if (isset($this->iconsystem) && \core\output\icon_system::is_valid_system($this->iconsystem)) {
1498 return $this->iconsystem;
1500 foreach ($this->parent_configs as $parent_config) {
1501 if (isset($parent_config->iconsystem) && \core\output\icon_system::is_valid_system($parent_config->iconsystem)) {
1502 return $parent_config->iconsystem;
1505 return \core\output\icon_system::STANDARD;
1509 * Return extra SCSS code to add when compiling.
1511 * This is intended to be used by themes to inject some SCSS code
1512 * before it gets compiled. If you want to inject variables you
1513 * should use {@link self::get_scss_variables()}.
1515 * @return string The SCSS code to inject.
1517 public function get_extra_scss_code() {
1518 $content = '';
1520 // Getting all the candidate functions.
1521 $candidates = array();
1522 foreach ($this->parent_configs as $parent_config) {
1523 if (!isset($parent_config->extrascsscallback)) {
1524 continue;
1526 $candidates[] = $parent_config->extrascsscallback;
1528 $candidates[] = $this->extrascsscallback;
1530 // Calling the functions.
1531 foreach ($candidates as $function) {
1532 if (function_exists($function)) {
1533 $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n";
1537 return $content;
1541 * SCSS code to prepend when compiling.
1543 * This is intended to be used by themes to inject SCSS code before it gets compiled.
1545 * @return string The SCSS code to inject.
1547 public function get_pre_scss_code() {
1548 $content = '';
1550 // Getting all the candidate functions.
1551 $candidates = array();
1552 foreach ($this->parent_configs as $parent_config) {
1553 if (!isset($parent_config->prescsscallback)) {
1554 continue;
1556 $candidates[] = $parent_config->prescsscallback;
1558 $candidates[] = $this->prescsscallback;
1560 // Calling the functions.
1561 foreach ($candidates as $function) {
1562 if (function_exists($function)) {
1563 $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n";
1567 return $content;
1571 * Get the SCSS property.
1573 * This resolves whether a SCSS file (or content) has to be used when generating
1574 * the stylesheet for the theme. It will look at parents themes and check the
1575 * SCSS properties there.
1577 * @return False when SCSS is not used.
1578 * An array with the import paths, and the path to the SCSS file or Closure as second.
1580 public function get_scss_property() {
1581 if ($this->scsscache === null) {
1582 $configs = [$this] + $this->parent_configs;
1583 $scss = null;
1585 foreach ($configs as $config) {
1586 $path = "{$config->dir}/scss";
1588 // We collect the SCSS property until we've found one.
1589 if (empty($scss) && !empty($config->scss)) {
1590 $candidate = is_string($config->scss) ? "{$path}/{$config->scss}.scss" : $config->scss;
1591 if ($candidate instanceof Closure) {
1592 $scss = $candidate;
1593 } else if (is_string($candidate) && is_readable($candidate)) {
1594 $scss = $candidate;
1598 // We collect the import paths once we've found a SCSS property.
1599 if ($scss && is_dir($path)) {
1600 $paths[] = $path;
1605 $this->scsscache = $scss !== null ? [$paths, $scss] : false;
1608 return $this->scsscache;
1612 * Generate a URL to the file that serves theme JavaScript files.
1614 * If we determine that the theme has no relevant files, then we return
1615 * early with a null value.
1617 * @param bool $inhead true means head url, false means footer
1618 * @return moodle_url|null
1620 public function javascript_url($inhead) {
1621 global $CFG;
1623 $rev = theme_get_revision();
1624 $params = array('theme'=>$this->name,'rev'=>$rev);
1625 $params['type'] = $inhead ? 'head' : 'footer';
1627 // Return early if there are no files to serve
1628 if (count($this->javascript_files($params['type'])) === 0) {
1629 return null;
1632 if (!empty($CFG->slasharguments) and $rev > 0) {
1633 $url = new moodle_url("/theme/javascript.php");
1634 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
1635 return $url;
1636 } else {
1637 return new moodle_url('/theme/javascript.php', $params);
1642 * Get the URL's for the JavaScript files used by this theme.
1643 * They won't be served directly, instead they'll be mediated through
1644 * theme/javascript.php.
1646 * @param string $type Either javascripts_footer, or javascripts
1647 * @return array
1649 public function javascript_files($type) {
1650 if ($type === 'footer') {
1651 $type = 'javascripts_footer';
1652 } else {
1653 $type = 'javascripts';
1656 $js = array();
1657 // find out wanted parent javascripts
1658 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1659 if ($excludes !== true) {
1660 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1661 $parent = $parent_config->name;
1662 if (empty($parent_config->$type)) {
1663 continue;
1665 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1666 continue;
1668 foreach ($parent_config->$type as $javascript) {
1669 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1670 and in_array($javascript, $excludes[$parent])) {
1671 continue;
1673 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1674 if (is_readable($javascriptfile)) {
1675 $js[] = $javascriptfile;
1681 // current theme javascripts
1682 if (is_array($this->$type)) {
1683 foreach ($this->$type as $javascript) {
1684 $javascriptfile = "$this->dir/javascript/$javascript.js";
1685 if (is_readable($javascriptfile)) {
1686 $js[] = $javascriptfile;
1690 return $js;
1694 * Resolves an exclude setting to the themes setting is applicable or the
1695 * setting of its closest parent.
1697 * @param string $variable The name of the setting the exclude setting to resolve
1698 * @param string $default
1699 * @return mixed
1701 protected function resolve_excludes($variable, $default = null) {
1702 $setting = $default;
1703 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1704 $setting = $this->{$variable};
1705 } else {
1706 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1707 if (!isset($parent_config->{$variable})) {
1708 continue;
1710 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1711 $setting = $parent_config->{$variable};
1712 break;
1716 return $setting;
1720 * Returns the content of the one huge javascript file merged from all theme javascript files.
1722 * @param bool $type
1723 * @return string
1725 public function javascript_content($type) {
1726 $jsfiles = $this->javascript_files($type);
1727 $js = '';
1728 foreach ($jsfiles as $jsfile) {
1729 $js .= file_get_contents($jsfile)."\n";
1731 return $js;
1735 * Post processes CSS.
1737 * This method post processes all of the CSS before it is served for this theme.
1738 * This is done so that things such as image URL's can be swapped in and to
1739 * run any specific CSS post process method the theme has requested.
1740 * This allows themes to use CSS settings.
1742 * @param string $css The CSS to process.
1743 * @return string The processed CSS.
1745 public function post_process($css) {
1746 // now resolve all image locations
1747 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1748 $replaced = array();
1749 foreach ($matches as $match) {
1750 if (isset($replaced[$match[0]])) {
1751 continue;
1753 $replaced[$match[0]] = true;
1754 $imagename = $match[2];
1755 $component = rtrim($match[1], '|');
1756 $imageurl = $this->image_url($imagename, $component)->out(false);
1757 // we do not need full url because the image.php is always in the same dir
1758 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1759 $css = str_replace($match[0], $imageurl, $css);
1763 // Now resolve all font locations.
1764 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1765 $replaced = array();
1766 foreach ($matches as $match) {
1767 if (isset($replaced[$match[0]])) {
1768 continue;
1770 $replaced[$match[0]] = true;
1771 $fontname = $match[2];
1772 $component = rtrim($match[1], '|');
1773 $fonturl = $this->font_url($fontname, $component)->out(false);
1774 // We do not need full url because the font.php is always in the same dir.
1775 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1776 $css = str_replace($match[0], $fonturl, $css);
1780 // Now resolve all theme settings or do any other postprocessing.
1781 // This needs to be done before calling core parser, since the parser strips [[settings]] tags.
1782 $csspostprocess = $this->csspostprocess;
1783 if (function_exists($csspostprocess)) {
1784 $css = $csspostprocess($css, $this);
1787 // Post processing using an object representation of CSS.
1788 $treeprocessor = $this->get_css_tree_post_processor();
1789 $needsparsing = !empty($treeprocessor) || !empty($this->rtlmode);
1790 if ($needsparsing) {
1792 // We might need more memory/time to do this, so let's play safe.
1793 raise_memory_limit(MEMORY_EXTRA);
1794 core_php_time_limit::raise(300);
1796 $parser = new core_cssparser($css);
1797 $csstree = $parser->parse();
1798 unset($parser);
1800 if ($this->rtlmode) {
1801 $this->rtlize($csstree);
1804 if ($treeprocessor) {
1805 $treeprocessor($csstree, $this);
1808 $css = $csstree->render();
1809 unset($csstree);
1812 return $css;
1816 * Flip a stylesheet to RTL.
1818 * @param Object $csstree The parsed CSS tree structure to flip.
1819 * @return void
1821 protected function rtlize($csstree) {
1822 $rtlcss = new core_rtlcss($csstree);
1823 $rtlcss->flip();
1827 * Return the direct URL for an image from the pix folder.
1829 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1831 * @deprecated since Moodle 3.3
1832 * @param string $imagename the name of the icon.
1833 * @param string $component specification of one plugin like in get_string()
1834 * @return moodle_url
1836 public function pix_url($imagename, $component) {
1837 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
1838 return $this->image_url($imagename, $component);
1842 * Return the direct URL for an image from the pix folder.
1844 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1846 * @param string $imagename the name of the icon.
1847 * @param string $component specification of one plugin like in get_string()
1848 * @return moodle_url
1850 public function image_url($imagename, $component) {
1851 global $CFG;
1853 $params = array('theme'=>$this->name);
1854 $svg = $this->use_svg_icons();
1856 if (empty($component) or $component === 'moodle' or $component === 'core') {
1857 $params['component'] = 'core';
1858 } else {
1859 $params['component'] = $component;
1862 $rev = theme_get_revision();
1863 if ($rev != -1) {
1864 $params['rev'] = $rev;
1867 $params['image'] = $imagename;
1869 $url = new moodle_url("/theme/image.php");
1870 if (!empty($CFG->slasharguments) and $rev > 0) {
1871 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1872 if (!$svg) {
1873 // We add a simple /_s to the start of the path.
1874 // The underscore is used to ensure that it isn't a valid theme name.
1875 $path = '/_s'.$path;
1877 $url->set_slashargument($path, 'noparam', true);
1878 } else {
1879 if (!$svg) {
1880 // We add an SVG param so that we know not to serve SVG images.
1881 // We do this because all modern browsers support SVG and this param will one day be removed.
1882 $params['svg'] = '0';
1884 $url->params($params);
1887 return $url;
1891 * Return the URL for a font
1893 * @param string $font the name of the font (including extension).
1894 * @param string $component specification of one plugin like in get_string()
1895 * @return moodle_url
1897 public function font_url($font, $component) {
1898 global $CFG;
1900 $params = array('theme'=>$this->name);
1902 if (empty($component) or $component === 'moodle' or $component === 'core') {
1903 $params['component'] = 'core';
1904 } else {
1905 $params['component'] = $component;
1908 $rev = theme_get_revision();
1909 if ($rev != -1) {
1910 $params['rev'] = $rev;
1913 $params['font'] = $font;
1915 $url = new moodle_url("/theme/font.php");
1916 if (!empty($CFG->slasharguments) and $rev > 0) {
1917 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1918 $url->set_slashargument($path, 'noparam', true);
1919 } else {
1920 $url->params($params);
1923 return $url;
1927 * Returns URL to the stored file via pluginfile.php.
1929 * Note the theme must also implement pluginfile.php handler,
1930 * theme revision is used instead of the itemid.
1932 * @param string $setting
1933 * @param string $filearea
1934 * @return string protocol relative URL or null if not present
1936 public function setting_file_url($setting, $filearea) {
1937 global $CFG;
1939 if (empty($this->settings->$setting)) {
1940 return null;
1943 $component = 'theme_'.$this->name;
1944 $itemid = theme_get_revision();
1945 $filepath = $this->settings->$setting;
1946 $syscontext = context_system::instance();
1948 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1950 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1951 // Note: unfortunately moodle_url does not support //urls yet.
1953 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1955 return $url;
1959 * Serve the theme setting file.
1961 * @param string $filearea
1962 * @param array $args
1963 * @param bool $forcedownload
1964 * @param array $options
1965 * @return bool may terminate if file not found or donotdie not specified
1967 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1968 global $CFG;
1969 require_once("$CFG->libdir/filelib.php");
1971 $syscontext = context_system::instance();
1972 $component = 'theme_'.$this->name;
1974 $revision = array_shift($args);
1975 if ($revision < 0) {
1976 $lifetime = 0;
1977 } else {
1978 $lifetime = 60*60*24*60;
1979 // By default, theme files must be cache-able by both browsers and proxies.
1980 if (!array_key_exists('cacheability', $options)) {
1981 $options['cacheability'] = 'public';
1985 $fs = get_file_storage();
1986 $relativepath = implode('/', $args);
1988 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1989 $fullpath = rtrim($fullpath, '/');
1990 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1991 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1992 return true;
1993 } else {
1994 send_file_not_found();
1999 * Resolves the real image location.
2001 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
2002 * and we need a way in which to turn it off.
2003 * By default SVG won't be used unless asked for. This is done for two reasons:
2004 * 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
2005 * browser supports SVG.
2006 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
2007 * by the user due to security concerns.
2009 * @param string $image name of image, may contain relative path
2010 * @param string $component
2011 * @param bool $svg|null Should SVG images also be looked for? If null, resorts to $CFG->svgicons if that is set; falls back to
2012 * auto-detection of browser support otherwise
2013 * @return string full file path
2015 public function resolve_image_location($image, $component, $svg = false) {
2016 global $CFG;
2018 if (!is_bool($svg)) {
2019 // If $svg isn't a bool then we need to decide for ourselves.
2020 $svg = $this->use_svg_icons();
2023 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2024 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
2025 return $imagefile;
2027 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2028 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
2029 return $imagefile;
2032 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
2033 return $imagefile;
2035 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
2036 return $imagefile;
2038 return null;
2040 } else if ($component === 'theme') { //exception
2041 if ($image === 'favicon') {
2042 return "$this->dir/pix/favicon.ico";
2044 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
2045 return $imagefile;
2047 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2048 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
2049 return $imagefile;
2052 return null;
2054 } else {
2055 if (strpos($component, '_') === false) {
2056 $component = 'mod_'.$component;
2058 list($type, $plugin) = explode('_', $component, 2);
2060 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2061 return $imagefile;
2063 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2064 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2065 return $imagefile;
2068 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
2069 return $imagefile;
2071 $dir = core_component::get_plugin_directory($type, $plugin);
2072 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
2073 return $imagefile;
2075 return null;
2080 * Resolves the real font location.
2082 * @param string $font name of font file
2083 * @param string $component
2084 * @return string full file path
2086 public function resolve_font_location($font, $component) {
2087 global $CFG;
2089 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2090 if (file_exists("$this->dir/fonts_core/$font")) {
2091 return "$this->dir/fonts_core/$font";
2093 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2094 if (file_exists("$parent_config->dir/fonts_core/$font")) {
2095 return "$parent_config->dir/fonts_core/$font";
2098 if (file_exists("$CFG->dataroot/fonts/$font")) {
2099 return "$CFG->dataroot/fonts/$font";
2101 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
2102 return "$CFG->dirroot/lib/fonts/$font";
2104 return null;
2106 } else if ($component === 'theme') { // Exception.
2107 if (file_exists("$this->dir/fonts/$font")) {
2108 return "$this->dir/fonts/$font";
2110 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2111 if (file_exists("$parent_config->dir/fonts/$font")) {
2112 return "$parent_config->dir/fonts/$font";
2115 return null;
2117 } else {
2118 if (strpos($component, '_') === false) {
2119 $component = 'mod_'.$component;
2121 list($type, $plugin) = explode('_', $component, 2);
2123 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
2124 return "$this->dir/fonts_plugins/$type/$plugin/$font";
2126 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2127 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
2128 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
2131 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
2132 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
2134 $dir = core_component::get_plugin_directory($type, $plugin);
2135 if (file_exists("$dir/fonts/$font")) {
2136 return "$dir/fonts/$font";
2138 return null;
2143 * Return true if we should look for SVG images as well.
2145 * @return bool
2147 public function use_svg_icons() {
2148 global $CFG;
2149 if ($this->usesvg === null) {
2151 if (!isset($CFG->svgicons)) {
2152 $this->usesvg = core_useragent::supports_svg();
2153 } else {
2154 // Force them on/off depending upon the setting.
2155 $this->usesvg = (bool)$CFG->svgicons;
2158 return $this->usesvg;
2162 * Forces the usesvg setting to either true or false, avoiding any decision making.
2164 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
2165 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
2167 * @param bool $setting True to force the use of svg when available, null otherwise.
2169 public function force_svg_use($setting) {
2170 $this->usesvg = (bool)$setting;
2174 * Set to be in RTL mode.
2176 * This will likely be used when post processing the CSS before serving it.
2178 * @param bool $inrtl True when in RTL mode.
2180 public function set_rtl_mode($inrtl = true) {
2181 $this->rtlmode = $inrtl;
2185 * Whether the theme is being served in RTL mode.
2187 * @return bool True when in RTL mode.
2189 public function get_rtl_mode() {
2190 return $this->rtlmode;
2194 * Checks if file with any image extension exists.
2196 * The order to these images was adjusted prior to the release of 2.4
2197 * At that point the were the following image counts in Moodle core:
2199 * - png = 667 in pix dirs (1499 total)
2200 * - gif = 385 in pix dirs (606 total)
2201 * - jpg = 62 in pix dirs (74 total)
2202 * - jpeg = 0 in pix dirs (1 total)
2204 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
2206 * @param string $filepath
2207 * @param bool $svg If set to true SVG images will also be looked for.
2208 * @return string image name with extension
2210 private static function image_exists($filepath, $svg = false) {
2211 if ($svg && file_exists("$filepath.svg")) {
2212 return "$filepath.svg";
2213 } else if (file_exists("$filepath.png")) {
2214 return "$filepath.png";
2215 } else if (file_exists("$filepath.gif")) {
2216 return "$filepath.gif";
2217 } else if (file_exists("$filepath.jpg")) {
2218 return "$filepath.jpg";
2219 } else if (file_exists("$filepath.jpeg")) {
2220 return "$filepath.jpeg";
2221 } else {
2222 return false;
2227 * Loads the theme config from config.php file.
2229 * @param string $themename
2230 * @param stdClass $settings from config_plugins table
2231 * @param boolean $parentscheck true to also check the parents. .
2232 * @return stdClass The theme configuration
2234 private static function find_theme_config($themename, $settings, $parentscheck = true) {
2235 // We have to use the variable name $THEME (upper case) because that
2236 // is what is used in theme config.php files.
2238 if (!$dir = theme_config::find_theme_location($themename)) {
2239 return null;
2242 $THEME = new stdClass();
2243 $THEME->name = $themename;
2244 $THEME->dir = $dir;
2245 $THEME->settings = $settings;
2247 global $CFG; // just in case somebody tries to use $CFG in theme config
2248 include("$THEME->dir/config.php");
2250 // verify the theme configuration is OK
2251 if (!is_array($THEME->parents)) {
2252 // parents option is mandatory now
2253 return null;
2254 } else {
2255 // We use $parentscheck to only check the direct parents (avoid infinite loop).
2256 if ($parentscheck) {
2257 // Find all parent theme configs.
2258 foreach ($THEME->parents as $parent) {
2259 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
2260 if (empty($parentconfig)) {
2261 return null;
2267 return $THEME;
2271 * Finds the theme location and verifies the theme has all needed files
2272 * and is not obsoleted.
2274 * @param string $themename
2275 * @return string full dir path or null if not found
2277 private static function find_theme_location($themename) {
2278 global $CFG;
2280 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2281 $dir = "$CFG->dirroot/theme/$themename";
2283 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
2284 $dir = "$CFG->themedir/$themename";
2286 } else {
2287 return null;
2290 if (file_exists("$dir/styles.php")) {
2291 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
2292 return null;
2295 return $dir;
2299 * Get the renderer for a part of Moodle for this theme.
2301 * @param moodle_page $page the page we are rendering
2302 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
2303 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
2304 * @param string $target one of rendering target constants
2305 * @return renderer_base the requested renderer.
2307 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
2308 if (is_null($this->rf)) {
2309 $classname = $this->rendererfactory;
2310 $this->rf = new $classname($this);
2313 return $this->rf->get_renderer($page, $component, $subtype, $target);
2317 * Get the information from {@link $layouts} for this type of page.
2319 * @param string $pagelayout the the page layout name.
2320 * @return array the appropriate part of {@link $layouts}.
2322 protected function layout_info_for_page($pagelayout) {
2323 if (array_key_exists($pagelayout, $this->layouts)) {
2324 return $this->layouts[$pagelayout];
2325 } else {
2326 debugging('Invalid page layout specified: ' . $pagelayout);
2327 return $this->layouts['standard'];
2332 * Given the settings of this theme, and the page pagelayout, return the
2333 * full path of the page layout file to use.
2335 * Used by {@link core_renderer::header()}.
2337 * @param string $pagelayout the the page layout name.
2338 * @return string Full path to the lyout file to use
2340 public function layout_file($pagelayout) {
2341 global $CFG;
2343 $layoutinfo = $this->layout_info_for_page($pagelayout);
2344 $layoutfile = $layoutinfo['file'];
2346 if (array_key_exists('theme', $layoutinfo)) {
2347 $themes = array($layoutinfo['theme']);
2348 } else {
2349 $themes = array_merge(array($this->name),$this->parents);
2352 foreach ($themes as $theme) {
2353 if ($dir = $this->find_theme_location($theme)) {
2354 $path = "$dir/layout/$layoutfile";
2356 // Check the template exists, return general base theme template if not.
2357 if (is_readable($path)) {
2358 return $path;
2363 debugging('Can not find layout file for: ' . $pagelayout);
2364 // fallback to standard normal layout
2365 return "$CFG->dirroot/theme/base/layout/general.php";
2369 * Returns auxiliary page layout options specified in layout configuration array.
2371 * @param string $pagelayout
2372 * @return array
2374 public function pagelayout_options($pagelayout) {
2375 $info = $this->layout_info_for_page($pagelayout);
2376 if (!empty($info['options'])) {
2377 return $info['options'];
2379 return array();
2383 * Inform a block_manager about the block regions this theme wants on this
2384 * page layout.
2386 * @param string $pagelayout the general type of the page.
2387 * @param block_manager $blockmanager the block_manger to set up.
2389 public function setup_blocks($pagelayout, $blockmanager) {
2390 $layoutinfo = $this->layout_info_for_page($pagelayout);
2391 if (!empty($layoutinfo['regions'])) {
2392 $blockmanager->add_regions($layoutinfo['regions'], false);
2393 $blockmanager->set_default_region($layoutinfo['defaultregion']);
2398 * Gets the visible name for the requested block region.
2400 * @param string $region The region name to get
2401 * @param string $theme The theme the region belongs to (may come from the parent theme)
2402 * @return string
2404 protected function get_region_name($region, $theme) {
2405 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
2406 // A name exists in this theme, so use it
2407 if (substr($regionstring, 0, 1) != '[') {
2408 return $regionstring;
2411 // Otherwise, try to find one elsewhere
2412 // Check parents, if any
2413 foreach ($this->parents as $parentthemename) {
2414 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
2415 if (substr($regionstring, 0, 1) != '[') {
2416 return $regionstring;
2420 // Last resort, try the boost theme for names
2421 return get_string('region-' . $region, 'theme_boost');
2425 * Get the list of all block regions known to this theme in all templates.
2427 * @return array internal region name => human readable name.
2429 public function get_all_block_regions() {
2430 $regions = array();
2431 foreach ($this->layouts as $layoutinfo) {
2432 foreach ($layoutinfo['regions'] as $region) {
2433 $regions[$region] = $this->get_region_name($region, $this->name);
2436 return $regions;
2440 * Returns the human readable name of the theme
2442 * @return string
2444 public function get_theme_name() {
2445 return get_string('pluginname', 'theme_'.$this->name);
2449 * Returns the block render method.
2451 * It is set by the theme via:
2452 * $THEME->blockrendermethod = '...';
2454 * It can be one of two values, blocks or blocks_for_region.
2455 * It should be set to the method being used by the theme layouts.
2457 * @return string
2459 public function get_block_render_method() {
2460 if ($this->blockrendermethod) {
2461 // Return the specified block render method.
2462 return $this->blockrendermethod;
2464 // Its not explicitly set, check the parent theme configs.
2465 foreach ($this->parent_configs as $config) {
2466 if (isset($config->blockrendermethod)) {
2467 return $config->blockrendermethod;
2470 // Default it to blocks.
2471 return 'blocks';
2475 * Get the callable for CSS tree post processing.
2477 * @return string|null
2479 public function get_css_tree_post_processor() {
2480 $configs = [$this] + $this->parent_configs;
2481 foreach ($configs as $config) {
2482 if (!empty($config->csstreepostprocessor) && is_callable($config->csstreepostprocessor)) {
2483 return $config->csstreepostprocessor;
2486 return null;
2492 * This class keeps track of which HTML tags are currently open.
2494 * This makes it much easier to always generate well formed XHTML output, even
2495 * if execution terminates abruptly. Any time you output some opening HTML
2496 * without the matching closing HTML, you should push the necessary close tags
2497 * onto the stack.
2499 * @copyright 2009 Tim Hunt
2500 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2501 * @since Moodle 2.0
2502 * @package core
2503 * @category output
2505 class xhtml_container_stack {
2508 * @var array Stores the list of open containers.
2510 protected $opencontainers = array();
2513 * @var array In developer debug mode, stores a stack trace of all opens and
2514 * closes, so we can output helpful error messages when there is a mismatch.
2516 protected $log = array();
2519 * @var boolean Store whether we are developer debug mode. We need this in
2520 * several places including in the destructor where we may not have access to $CFG.
2522 protected $isdebugging;
2525 * Constructor
2527 public function __construct() {
2528 global $CFG;
2529 $this->isdebugging = $CFG->debugdeveloper;
2533 * Push the close HTML for a recently opened container onto the stack.
2535 * @param string $type The type of container. This is checked when {@link pop()}
2536 * is called and must match, otherwise a developer debug warning is output.
2537 * @param string $closehtml The HTML required to close the container.
2539 public function push($type, $closehtml) {
2540 $container = new stdClass;
2541 $container->type = $type;
2542 $container->closehtml = $closehtml;
2543 if ($this->isdebugging) {
2544 $this->log('Open', $type);
2546 array_push($this->opencontainers, $container);
2550 * Pop the HTML for the next closing container from the stack. The $type
2551 * must match the type passed when the container was opened, otherwise a
2552 * warning will be output.
2554 * @param string $type The type of container.
2555 * @return string the HTML required to close the container.
2557 public function pop($type) {
2558 if (empty($this->opencontainers)) {
2559 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2560 $this->output_log(), DEBUG_DEVELOPER);
2561 return;
2564 $container = array_pop($this->opencontainers);
2565 if ($container->type != $type) {
2566 debugging('<p>The type of container to be closed (' . $container->type .
2567 ') does not match the type of the next open container (' . $type .
2568 '). This suggests there is a nesting problem.</p>' .
2569 $this->output_log(), DEBUG_DEVELOPER);
2571 if ($this->isdebugging) {
2572 $this->log('Close', $type);
2574 return $container->closehtml;
2578 * Close all but the last open container. This is useful in places like error
2579 * handling, where you want to close all the open containers (apart from <body>)
2580 * before outputting the error message.
2582 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2583 * developer debug warning if it isn't.
2584 * @return string the HTML required to close any open containers inside <body>.
2586 public function pop_all_but_last($shouldbenone = false) {
2587 if ($shouldbenone && count($this->opencontainers) != 1) {
2588 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2589 $this->output_log(), DEBUG_DEVELOPER);
2591 $output = '';
2592 while (count($this->opencontainers) > 1) {
2593 $container = array_pop($this->opencontainers);
2594 $output .= $container->closehtml;
2596 return $output;
2600 * You can call this function if you want to throw away an instance of this
2601 * class without properly emptying the stack (for example, in a unit test).
2602 * Calling this method stops the destruct method from outputting a developer
2603 * debug warning. After calling this method, the instance can no longer be used.
2605 public function discard() {
2606 $this->opencontainers = null;
2610 * Adds an entry to the log.
2612 * @param string $action The name of the action
2613 * @param string $type The type of action
2615 protected function log($action, $type) {
2616 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
2617 format_backtrace(debug_backtrace()) . '</li>';
2621 * Outputs the log's contents as a HTML list.
2623 * @return string HTML list of the log
2625 protected function output_log() {
2626 return '<ul>' . implode("\n", $this->log) . '</ul>';