MDL-68430 filter_mathjaxloader: update default CDN to 2.7.8
[moodle.git] / lib / outputlib.php
blob2846d1dba131c530d9087fb25b818b2d73b69177
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 LESS file to compile. When set, the theme will attempt to compile the file itself.
617 * @var bool
619 public $lessfile = false;
622 * The SCSS file to compile (without .scss), located in the scss/ folder of the theme.
623 * Or a Closure, which receives the theme_config as argument and must
624 * return the SCSS content. This setting takes precedence over self::$lessfile.
625 * @var string|Closure
627 public $scss = false;
630 * Local cache of the SCSS property.
631 * @var false|array
633 protected $scsscache = null;
636 * The name of the function to call to get the LESS code to inject.
637 * @var string
639 public $extralesscallback = null;
642 * The name of the function to call to get the SCSS code to inject.
643 * @var string
645 public $extrascsscallback = null;
648 * The name of the function to call to get extra LESS variables.
649 * @var string
651 public $lessvariablescallback = null;
654 * The name of the function to call to get SCSS to prepend.
655 * @var string
657 public $prescsscallback = null;
660 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
661 * Defaults to {@link core_renderer::blocks_for_region()}
662 * @var string
664 public $blockrendermethod = null;
667 * Remember the results of icon remapping for the current page.
668 * @var array
670 public $remapiconcache = [];
673 * The name of the function to call to get precompiled CSS.
674 * @var string
676 public $precompiledcsscallback = null;
679 * Load the config.php file for a particular theme, and return an instance
680 * of this class. (That is, this is a factory method.)
682 * @param string $themename the name of the theme.
683 * @return theme_config an instance of this class.
685 public static function load($themename) {
686 global $CFG;
688 // load theme settings from db
689 try {
690 $settings = get_config('theme_'.$themename);
691 } catch (dml_exception $e) {
692 // most probably moodle tables not created yet
693 $settings = new stdClass();
696 if ($config = theme_config::find_theme_config($themename, $settings)) {
697 return new theme_config($config);
699 } else if ($themename == theme_config::DEFAULT_THEME) {
700 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
702 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
703 debugging('This page should be using theme ' . $themename .
704 ' which cannot be initialised. Falling back to the site theme ' . $CFG->theme, DEBUG_NORMAL);
705 return new theme_config($config);
707 } else {
708 // bad luck, the requested theme has some problems - admin see details in theme config
709 debugging('This page should be using theme ' . $themename .
710 ' which cannot be initialised. Nor can the site theme ' . $CFG->theme .
711 '. Falling back to ' . theme_config::DEFAULT_THEME, DEBUG_NORMAL);
712 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
717 * Theme diagnostic code. It is very problematic to send debug output
718 * to the actual CSS file, instead this functions is supposed to
719 * diagnose given theme and highlights all potential problems.
720 * This information should be available from the theme selection page
721 * or some other debug page for theme designers.
723 * @param string $themename
724 * @return array description of problems
726 public static function diagnose($themename) {
727 //TODO: MDL-21108
728 return array();
732 * Private constructor, can be called only from the factory method.
733 * @param stdClass $config
735 private function __construct($config) {
736 global $CFG; //needed for included lib.php files
738 $this->settings = $config->settings;
739 $this->name = $config->name;
740 $this->dir = $config->dir;
742 if ($this->name != 'bootstrapbase') {
743 $baseconfig = theme_config::find_theme_config('bootstrapbase', $this->settings);
744 } else {
745 $baseconfig = $config;
748 $configurable = array(
749 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'usefallback',
750 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
751 'layouts', 'enable_dock', 'enablecourseajax', 'requiredblocks',
752 'rendererfactory', 'csspostprocess', 'editor_sheets', 'editor_scss', 'rarrow', 'larrow', 'uarrow', 'darrow',
753 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations',
754 'lessfile', 'extralesscallback', 'lessvariablescallback', 'blockrendermethod',
755 'scss', 'extrascsscallback', 'prescsscallback', 'csstreepostprocessor', 'addblockposition',
756 'iconsystem', 'precompiledcsscallback');
758 foreach ($config as $key=>$value) {
759 if (in_array($key, $configurable)) {
760 $this->$key = $value;
764 // verify all parents and load configs and renderers
765 foreach ($this->parents as $parent) {
766 if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
767 // this is not good - better exclude faulty parents
768 continue;
770 $libfile = $parent_config->dir.'/lib.php';
771 if (is_readable($libfile)) {
772 // theme may store various function here
773 include_once($libfile);
775 $renderersfile = $parent_config->dir.'/renderers.php';
776 if (is_readable($renderersfile)) {
777 // may contain core and plugin renderers and renderer factory
778 include_once($renderersfile);
780 $this->parent_configs[$parent] = $parent_config;
782 $libfile = $this->dir.'/lib.php';
783 if (is_readable($libfile)) {
784 // theme may store various function here
785 include_once($libfile);
787 $rendererfile = $this->dir.'/renderers.php';
788 if (is_readable($rendererfile)) {
789 // may contain core and plugin renderers and renderer factory
790 include_once($rendererfile);
791 } else {
792 // check if renderers.php file is missnamed renderer.php
793 if (is_readable($this->dir.'/renderer.php')) {
794 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
795 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
799 // cascade all layouts properly
800 foreach ($baseconfig->layouts as $layout=>$value) {
801 if (!isset($this->layouts[$layout])) {
802 foreach ($this->parent_configs as $parent_config) {
803 if (isset($parent_config->layouts[$layout])) {
804 $this->layouts[$layout] = $parent_config->layouts[$layout];
805 continue 2;
808 $this->layouts[$layout] = $value;
812 //fix arrows if needed
813 $this->check_theme_arrows();
817 * Let the theme initialise the page object (usually $PAGE).
819 * This may be used for example to request jQuery in add-ons.
821 * @param moodle_page $page
823 public function init_page(moodle_page $page) {
824 $themeinitfunction = 'theme_'.$this->name.'_page_init';
825 if (function_exists($themeinitfunction)) {
826 $themeinitfunction($page);
831 * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow, $THEME->darrow have been set (theme/-/config.php).
832 * If not it applies sensible defaults.
834 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
835 * search forum block, etc. Important: these are 'silent' in a screen-reader
836 * (unlike &gt; &raquo;), and must be accompanied by text.
838 private function check_theme_arrows() {
839 if (!isset($this->rarrow) and !isset($this->larrow)) {
840 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
841 // Also OK in Win 9x/2K/IE 5.x
842 $this->rarrow = '&#x25BA;';
843 $this->larrow = '&#x25C4;';
844 $this->uarrow = '&#x25B2;';
845 $this->darrow = '&#x25BC;';
846 if (empty($_SERVER['HTTP_USER_AGENT'])) {
847 $uagent = '';
848 } else {
849 $uagent = $_SERVER['HTTP_USER_AGENT'];
851 if (false !== strpos($uagent, 'Opera')
852 || false !== strpos($uagent, 'Mac')) {
853 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
854 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
855 $this->rarrow = '&#x25B6;&#xFE0E;';
856 $this->larrow = '&#x25C0;&#xFE0E;';
858 elseif ((false !== strpos($uagent, 'Konqueror'))
859 || (false !== strpos($uagent, 'Android'))) {
860 // The fonts on Android don't include the characters required for this to work as expected.
861 // So we use the same ones Konqueror uses.
862 $this->rarrow = '&rarr;';
863 $this->larrow = '&larr;';
864 $this->uarrow = '&uarr;';
865 $this->darrow = '&darr;';
867 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
868 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
869 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
870 // To be safe, non-Unicode browsers!
871 $this->rarrow = '&gt;';
872 $this->larrow = '&lt;';
873 $this->uarrow = '^';
874 $this->darrow = 'v';
877 // RTL support - in RTL languages, swap r and l arrows
878 if (right_to_left()) {
879 $t = $this->rarrow;
880 $this->rarrow = $this->larrow;
881 $this->larrow = $t;
887 * Returns output renderer prefixes, these are used when looking
888 * for the overridden renderers in themes.
890 * @return array
892 public function renderer_prefixes() {
893 global $CFG; // just in case the included files need it
895 $prefixes = array('theme_'.$this->name);
897 foreach ($this->parent_configs as $parent) {
898 $prefixes[] = 'theme_'.$parent->name;
901 return $prefixes;
905 * Returns the stylesheet URL of this editor content
907 * @param bool $encoded false means use & and true use &amp; in URLs
908 * @return moodle_url
910 public function editor_css_url($encoded=true) {
911 global $CFG;
912 $rev = theme_get_revision();
913 if ($rev > -1) {
914 $themesubrevision = theme_get_sub_revision_for_theme($this->name);
916 // Provide the sub revision to allow us to invalidate cached theme CSS
917 // on a per theme basis, rather than globally.
918 if ($themesubrevision && $themesubrevision > 0) {
919 $rev .= "_{$themesubrevision}";
922 $url = new moodle_url("/theme/styles.php");
923 if (!empty($CFG->slasharguments)) {
924 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
925 } else {
926 $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
928 } else {
929 $params = array('theme'=>$this->name, 'type'=>'editor');
930 $url = new moodle_url('/theme/styles_debug.php', $params);
932 return $url;
936 * Returns the content of the CSS to be used in editor content
938 * @return array
940 public function editor_css_files() {
941 $files = array();
943 // First editor plugins.
944 $plugins = core_component::get_plugin_list('editor');
945 foreach ($plugins as $plugin=>$fulldir) {
946 $sheetfile = "$fulldir/editor_styles.css";
947 if (is_readable($sheetfile)) {
948 $files['plugin_'.$plugin] = $sheetfile;
951 // Then parent themes - base first, the immediate parent last.
952 foreach (array_reverse($this->parent_configs) as $parent_config) {
953 if (empty($parent_config->editor_sheets)) {
954 continue;
956 foreach ($parent_config->editor_sheets as $sheet) {
957 $sheetfile = "$parent_config->dir/style/$sheet.css";
958 if (is_readable($sheetfile)) {
959 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
963 // Finally this theme.
964 if (!empty($this->editor_sheets)) {
965 foreach ($this->editor_sheets as $sheet) {
966 $sheetfile = "$this->dir/style/$sheet.css";
967 if (is_readable($sheetfile)) {
968 $files['theme_'.$sheet] = $sheetfile;
973 return $files;
977 * Compiles and returns the content of the SCSS to be used in editor content
979 * @return string Compiled CSS from the editor SCSS
981 public function editor_scss_to_css() {
982 $css = '';
984 if (!empty($this->editor_scss)) {
985 $compiler = new core_scss();
987 foreach ($this->editor_scss as $filename) {
988 $compiler->set_file("{$this->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'));
1080 } else if (!empty($this->lessfile)) {
1081 // No need to define the type as IE here.
1082 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
1084 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
1086 } else {
1087 foreach ($css['plugins'] as $plugin=>$unused) {
1088 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
1090 foreach ($css['parents'] as $parent=>$sheets) {
1091 foreach ($sheets as $sheet=>$unused2) {
1092 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
1095 foreach ($css['theme'] as $sheet => $filename) {
1096 if ($sheet === self::SCSS_KEY) {
1097 // This is the theme SCSS file.
1098 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
1099 } else if ($sheet === $this->lessfile) {
1100 // This is the theme LESS file.
1101 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
1102 } else {
1103 // Sheet first in order to make long urls easier to read.
1104 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
1110 return $urls;
1114 * Get the whole css stylesheet for production mode.
1116 * NOTE: this method is not expected to be used from any addons.
1118 * @return string CSS markup compressed
1120 public function get_css_content() {
1122 $csscontent = '';
1123 foreach ($this->get_css_files(false) as $type => $value) {
1124 foreach ($value as $identifier => $val) {
1125 if (is_array($val)) {
1126 foreach ($val as $v) {
1127 $csscontent .= file_get_contents($v) . "\n";
1129 } else {
1130 if ($type === 'theme' && $identifier === self::SCSS_KEY) {
1131 // We need the content from SCSS because this is the SCSS file from the theme.
1132 if ($compiled = $this->get_css_content_from_scss(false)) {
1133 $csscontent .= $compiled;
1134 } else {
1135 // The compiler failed so default back to any precompiled css that might
1136 // exist.
1137 $csscontent .= $this->get_precompiled_css_content();
1139 } else if ($type === 'theme' && $identifier === $this->lessfile) {
1140 // We need the content from LESS because this is the LESS file from the theme.
1141 $csscontent .= $this->get_css_content_from_less(false);
1142 } else {
1143 $csscontent .= file_get_contents($val) . "\n";
1148 $csscontent = $this->post_process($csscontent);
1149 $csscontent = core_minify::css($csscontent);
1151 return $csscontent;
1154 * Set post processed CSS content cache.
1156 * @param string $csscontent The post processed CSS content.
1157 * @return bool True if the content was successfully cached.
1159 public function set_css_content_cache($csscontent) {
1161 $cache = cache::make('core', 'postprocessedcss');
1162 $key = $this->get_css_cache_key();
1164 return $cache->set($key, $csscontent);
1168 * Return whether the post processed CSS content has been cached.
1170 * @return bool Whether the post-processed CSS is available in the cache.
1172 public function has_css_cached_content() {
1174 $key = $this->get_css_cache_key();
1175 $cache = cache::make('core', 'postprocessedcss');
1177 return $cache->has($key);
1181 * Return cached post processed CSS content.
1183 * @return bool|string The cached css content or false if not found.
1185 public function get_css_cached_content() {
1187 $key = $this->get_css_cache_key();
1188 $cache = cache::make('core', 'postprocessedcss');
1190 return $cache->get($key);
1194 * Generate the css content cache key.
1196 * @return string The post processed css cache key.
1198 public function get_css_cache_key() {
1199 $nosvg = (!$this->use_svg_icons()) ? 'nosvg_' : '';
1200 $rtlmode = ($this->rtlmode == true) ? 'rtl' : 'ltr';
1202 return $nosvg . $this->name . '_' . $rtlmode;
1206 * Get the theme designer css markup,
1207 * the parameters are coming from css_urls().
1209 * NOTE: this method is not expected to be used from any addons.
1211 * @param string $type
1212 * @param string $subtype
1213 * @param string $sheet
1214 * @return string CSS markup
1216 public function get_css_content_debug($type, $subtype, $sheet) {
1218 if ($type === 'scss') {
1219 // The SCSS file of the theme is requested.
1220 $csscontent = $this->get_css_content_from_scss(true);
1221 if ($csscontent !== false) {
1222 return $this->post_process($csscontent);
1224 return '';
1225 } else if ($type === 'less') {
1226 // The LESS file of the theme is requested.
1227 $csscontent = $this->get_css_content_from_less(true);
1228 if ($csscontent !== false) {
1229 return $this->post_process($csscontent);
1231 return '';
1234 $cssfiles = array();
1235 $css = $this->get_css_files(true);
1237 if ($type === 'ie') {
1238 // IE is a sloppy browser with weird limits, sorry.
1239 if ($subtype === 'plugins') {
1240 $cssfiles = $css['plugins'];
1242 } else if ($subtype === 'parents') {
1243 if (empty($sheet)) {
1244 // Do not bother with the empty parent here.
1245 } else {
1246 // Build up the CSS for that parent so we can serve it as one file.
1247 foreach ($css[$subtype][$sheet] as $parent => $css) {
1248 $cssfiles[] = $css;
1251 } else if ($subtype === 'theme') {
1252 $cssfiles = $css['theme'];
1253 foreach ($cssfiles as $key => $value) {
1254 if (in_array($key, [$this->lessfile, self::SCSS_KEY])) {
1255 // Remove the LESS/SCSS file from the theme CSS files.
1256 // The LESS/SCSS files use the type 'less' or 'scss', not 'ie'.
1257 unset($cssfiles[$key]);
1262 } else if ($type === 'plugin') {
1263 if (isset($css['plugins'][$subtype])) {
1264 $cssfiles[] = $css['plugins'][$subtype];
1267 } else if ($type === 'parent') {
1268 if (isset($css['parents'][$subtype][$sheet])) {
1269 $cssfiles[] = $css['parents'][$subtype][$sheet];
1272 } else if ($type === 'theme') {
1273 if (isset($css['theme'][$sheet])) {
1274 $cssfiles[] = $css['theme'][$sheet];
1278 $csscontent = '';
1279 foreach ($cssfiles as $file) {
1280 $contents = file_get_contents($file);
1281 $contents = $this->post_process($contents);
1282 $comment = "/** Path: $type $subtype $sheet.' **/\n";
1283 $stats = '';
1284 $csscontent .= $comment.$stats.$contents."\n\n";
1287 return $csscontent;
1291 * Get the whole css stylesheet for editor iframe.
1293 * NOTE: this method is not expected to be used from any addons.
1295 * @return string CSS markup
1297 public function get_css_content_editor() {
1298 $css = '';
1299 $cssfiles = $this->editor_css_files();
1301 // If editor has static CSS, include it.
1302 foreach ($cssfiles as $file) {
1303 $css .= file_get_contents($file)."\n";
1306 // If editor has SCSS, compile and include it.
1307 if (($convertedscss = $this->editor_scss_to_css())) {
1308 $css .= $convertedscss;
1311 $output = $this->post_process($css);
1313 return $output;
1317 * Returns an array of organised CSS files required for this output.
1319 * @param bool $themedesigner
1320 * @return array nested array of file paths
1322 protected function get_css_files($themedesigner) {
1323 global $CFG;
1325 $cache = null;
1326 $cachekey = 'cssfiles';
1327 if ($themedesigner) {
1328 require_once($CFG->dirroot.'/lib/csslib.php');
1329 // We need some kind of caching here because otherwise the page navigation becomes
1330 // way too slow in theme designer mode. Feel free to create full cache definition later...
1331 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
1332 if ($files = $cache->get($cachekey)) {
1333 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
1334 unset($files['created']);
1335 return $files;
1340 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
1342 // Get all plugin sheets.
1343 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
1344 if ($excludes !== true) {
1345 foreach (core_component::get_plugin_types() as $type=>$unused) {
1346 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
1347 continue;
1349 $plugins = core_component::get_plugin_list($type);
1350 foreach ($plugins as $plugin=>$fulldir) {
1351 if (!empty($excludes[$type]) and is_array($excludes[$type])
1352 and in_array($plugin, $excludes[$type])) {
1353 continue;
1356 // Get the CSS from the plugin.
1357 $sheetfile = "$fulldir/styles.css";
1358 if (is_readable($sheetfile)) {
1359 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
1362 // Create a list of candidate sheets from parents (direct parent last) and current theme.
1363 $candidates = array();
1364 foreach (array_reverse($this->parent_configs) as $parent_config) {
1365 $candidates[] = $parent_config->name;
1367 $candidates[] = $this->name;
1369 // Add the sheets found.
1370 foreach ($candidates as $candidate) {
1371 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1372 if (is_readable($sheetthemefile)) {
1373 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
1380 // Find out wanted parent sheets.
1381 $excludes = $this->resolve_excludes('parents_exclude_sheets');
1382 if ($excludes !== true) {
1383 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1384 $parent = $parent_config->name;
1385 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
1386 continue;
1388 foreach ($parent_config->sheets as $sheet) {
1389 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1390 && in_array($sheet, $excludes[$parent])) {
1391 continue;
1394 // We never refer to the parent LESS files.
1395 $sheetfile = "$parent_config->dir/style/$sheet.css";
1396 if (is_readable($sheetfile)) {
1397 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1404 // Current theme sheets and less file.
1405 // We first add the SCSS, or LESS file because we want the CSS ones to
1406 // be included after the SCSS/LESS code. However, if both the LESS file
1407 // and a CSS file share the same name, the CSS file is ignored.
1408 if ($this->get_scss_property()) {
1409 $cssfiles['theme'][self::SCSS_KEY] = true;
1410 } else if (!empty($this->lessfile)) {
1411 $sheetfile = "{$this->dir}/less/{$this->lessfile}.less";
1412 if (is_readable($sheetfile)) {
1413 $cssfiles['theme'][$this->lessfile] = $sheetfile;
1416 if (is_array($this->sheets)) {
1417 foreach ($this->sheets as $sheet) {
1418 $sheetfile = "$this->dir/style/$sheet.css";
1419 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1420 $cssfiles['theme'][$sheet] = $sheetfile;
1425 if ($cache) {
1426 $files = $cssfiles;
1427 $files['created'] = time();
1428 $cache->set($cachekey, $files);
1430 return $cssfiles;
1434 * Return the CSS content generated from LESS the file.
1436 * @param bool $themedesigner True if theme designer is enabled.
1437 * @return bool|string Return false when the compilation failed. Else the compiled string.
1439 protected function get_css_content_from_less($themedesigner) {
1440 global $CFG;
1442 $lessfile = $this->lessfile;
1443 if (!$lessfile || !is_readable($this->dir . '/less/' . $lessfile . '.less')) {
1444 throw new coding_exception('The theme did not define a LESS file, or it is not readable.');
1447 // We might need more memory/time to do this, so let's play safe.
1448 raise_memory_limit(MEMORY_EXTRA);
1449 core_php_time_limit::raise(300);
1451 // Files list.
1452 $files = $this->get_css_files($themedesigner);
1454 // Get the LESS file path.
1455 $themelessfile = $files['theme'][$lessfile];
1457 // Setup compiler options.
1458 $options = array(
1459 // We need to set the import directory to where $lessfile is.
1460 'import_dirs' => array(dirname($themelessfile) => '/'),
1461 // Always disable default caching.
1462 'cache_method' => false,
1463 // Disable the relative URLs, we have post_process() to handle that.
1464 'relativeUrls' => false,
1467 if ($themedesigner) {
1468 // Add the sourceMap inline to ensure that it is atomically generated.
1469 $options['sourceMap'] = true;
1470 $options['sourceMapBasepath'] = $CFG->dirroot;
1471 $options['sourceMapRootpath'] = $CFG->wwwroot;
1474 // Instantiate the compiler.
1475 $compiler = new core_lessc($options);
1477 try {
1478 $compiler->parse_file_content($themelessfile);
1480 // Get the callbacks.
1481 $compiler->parse($this->get_extra_less_code());
1482 $compiler->ModifyVars($this->get_less_variables());
1484 // Compile the CSS.
1485 $compiled = $compiler->getCss();
1487 } catch (Less_Exception_Parser $e) {
1488 $compiled = false;
1489 debugging('Error while compiling LESS ' . $lessfile . ' file: ' . $e->getMessage(), DEBUG_DEVELOPER);
1492 // Try to save memory.
1493 $compiler = null;
1494 unset($compiler);
1496 return $compiled;
1500 * Return the CSS content generated from the SCSS file.
1502 * @param bool $themedesigner True if theme designer is enabled.
1503 * @return bool|string Return false when the compilation failed. Else the compiled string.
1505 protected function get_css_content_from_scss($themedesigner) {
1506 global $CFG;
1508 list($paths, $scss) = $this->get_scss_property();
1509 if (!$scss) {
1510 throw new coding_exception('The theme did not define a SCSS file, or it is not readable.');
1513 // We might need more memory/time to do this, so let's play safe.
1514 raise_memory_limit(MEMORY_EXTRA);
1515 core_php_time_limit::raise(300);
1517 // Set-up the compiler.
1518 $compiler = new core_scss();
1519 $compiler->prepend_raw_scss($this->get_pre_scss_code());
1520 if (is_string($scss)) {
1521 $compiler->set_file($scss);
1522 } else {
1523 $compiler->append_raw_scss($scss($this));
1524 $compiler->setImportPaths($paths);
1526 $compiler->append_raw_scss($this->get_extra_scss_code());
1528 try {
1529 // Compile!
1530 $compiled = $compiler->to_css();
1532 } catch (\Exception $e) {
1533 $compiled = false;
1534 debugging('Error while compiling SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
1537 // Try to save memory.
1538 $compiler = null;
1539 unset($compiler);
1541 return $compiled;
1545 * Return the precompiled CSS if the precompiledcsscallback exists.
1547 * @return string Return compiled css.
1549 public function get_precompiled_css_content() {
1550 $configs = array_reverse($this->parent_configs) + [$this];
1551 $css = '';
1553 foreach ($configs as $config) {
1554 if (isset($config->precompiledcsscallback)) {
1555 $function = $config->precompiledcsscallback;
1556 if (function_exists($function)) {
1557 $css .= $function($this);
1561 return $css;
1565 * Get the icon system to use.
1567 * @return string
1569 public function get_icon_system() {
1571 // Getting all the candidate functions.
1572 $system = false;
1573 if (isset($this->iconsystem) && \core\output\icon_system::is_valid_system($this->iconsystem)) {
1574 return $this->iconsystem;
1576 foreach ($this->parent_configs as $parent_config) {
1577 if (isset($parent_config->iconsystem) && \core\output\icon_system::is_valid_system($parent_config->iconsystem)) {
1578 return $parent_config->iconsystem;
1581 return \core\output\icon_system::STANDARD;
1585 * Return extra LESS variables to use when compiling.
1587 * @return array Where keys are the variable names (omitting the @), and the values are the value.
1589 protected function get_less_variables() {
1590 $variables = array();
1592 // Getting all the candidate functions.
1593 $candidates = array();
1594 foreach ($this->parent_configs as $parent_config) {
1595 if (!isset($parent_config->lessvariablescallback)) {
1596 continue;
1598 $candidates[] = $parent_config->lessvariablescallback;
1600 $candidates[] = $this->lessvariablescallback;
1602 // Calling the functions.
1603 foreach ($candidates as $function) {
1604 if (function_exists($function)) {
1605 $vars = $function($this);
1606 if (!is_array($vars)) {
1607 debugging('Callback ' . $function . ' did not return an array() as expected', DEBUG_DEVELOPER);
1608 continue;
1610 $variables = array_merge($variables, $vars);
1614 return $variables;
1618 * Return extra LESS code to add when compiling.
1620 * This is intended to be used by themes to inject some LESS code
1621 * before it gets compiled. If you want to inject variables you
1622 * should use {@link self::get_less_variables()}.
1624 * @return string The LESS code to inject.
1626 protected function get_extra_less_code() {
1627 $content = '';
1629 // Getting all the candidate functions.
1630 $candidates = array();
1631 foreach ($this->parent_configs as $parent_config) {
1632 if (!isset($parent_config->extralesscallback)) {
1633 continue;
1635 $candidates[] = $parent_config->extralesscallback;
1637 $candidates[] = $this->extralesscallback;
1639 // Calling the functions.
1640 foreach ($candidates as $function) {
1641 if (function_exists($function)) {
1642 $content .= "\n/** Extra LESS from $function **/\n" . $function($this) . "\n";
1646 return $content;
1650 * Return extra SCSS code to add when compiling.
1652 * This is intended to be used by themes to inject some SCSS code
1653 * before it gets compiled. If you want to inject variables you
1654 * should use {@link self::get_scss_variables()}.
1656 * @return string The SCSS code to inject.
1658 protected function get_extra_scss_code() {
1659 $content = '';
1661 // Getting all the candidate functions.
1662 $candidates = array();
1663 foreach ($this->parent_configs as $parent_config) {
1664 if (!isset($parent_config->extrascsscallback)) {
1665 continue;
1667 $candidates[] = $parent_config->extrascsscallback;
1669 $candidates[] = $this->extrascsscallback;
1671 // Calling the functions.
1672 foreach ($candidates as $function) {
1673 if (function_exists($function)) {
1674 $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n";
1678 return $content;
1682 * SCSS code to prepend when compiling.
1684 * This is intended to be used by themes to inject SCSS code before it gets compiled.
1686 * @return string The SCSS code to inject.
1688 protected function get_pre_scss_code() {
1689 $content = '';
1691 // Getting all the candidate functions.
1692 $candidates = array();
1693 foreach ($this->parent_configs as $parent_config) {
1694 if (!isset($parent_config->prescsscallback)) {
1695 continue;
1697 $candidates[] = $parent_config->prescsscallback;
1699 $candidates[] = $this->prescsscallback;
1701 // Calling the functions.
1702 foreach ($candidates as $function) {
1703 if (function_exists($function)) {
1704 $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n";
1708 return $content;
1712 * Get the SCSS property.
1714 * This resolves whether a SCSS file (or content) has to be used when generating
1715 * the stylesheet for the theme. It will look at parents themes and check the
1716 * SCSS properties there.
1718 * @return False when SCSS is not used.
1719 * An array with the import paths, and the path to the SCSS file or Closure as second.
1721 public function get_scss_property() {
1722 if ($this->scsscache === null) {
1723 $configs = [$this] + $this->parent_configs;
1724 $scss = null;
1726 foreach ($configs as $config) {
1727 $path = "{$config->dir}/scss";
1729 // We collect the SCSS property until we've found one.
1730 if (empty($scss) && !empty($config->scss)) {
1731 $candidate = is_string($config->scss) ? "{$path}/{$config->scss}.scss" : $config->scss;
1732 if ($candidate instanceof Closure) {
1733 $scss = $candidate;
1734 } else if (is_string($candidate) && is_readable($candidate)) {
1735 $scss = $candidate;
1739 // We collect the import paths once we've found a SCSS property.
1740 if ($scss && is_dir($path)) {
1741 $paths[] = $path;
1746 $this->scsscache = $scss !== null ? [$paths, $scss] : false;
1749 return $this->scsscache;
1753 * Generate a URL to the file that serves theme JavaScript files.
1755 * If we determine that the theme has no relevant files, then we return
1756 * early with a null value.
1758 * @param bool $inhead true means head url, false means footer
1759 * @return moodle_url|null
1761 public function javascript_url($inhead) {
1762 global $CFG;
1764 $rev = theme_get_revision();
1765 $params = array('theme'=>$this->name,'rev'=>$rev);
1766 $params['type'] = $inhead ? 'head' : 'footer';
1768 // Return early if there are no files to serve
1769 if (count($this->javascript_files($params['type'])) === 0) {
1770 return null;
1773 if (!empty($CFG->slasharguments) and $rev > 0) {
1774 $url = new moodle_url("/theme/javascript.php");
1775 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
1776 return $url;
1777 } else {
1778 return new moodle_url('/theme/javascript.php', $params);
1783 * Get the URL's for the JavaScript files used by this theme.
1784 * They won't be served directly, instead they'll be mediated through
1785 * theme/javascript.php.
1787 * @param string $type Either javascripts_footer, or javascripts
1788 * @return array
1790 public function javascript_files($type) {
1791 if ($type === 'footer') {
1792 $type = 'javascripts_footer';
1793 } else {
1794 $type = 'javascripts';
1797 $js = array();
1798 // find out wanted parent javascripts
1799 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1800 if ($excludes !== true) {
1801 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1802 $parent = $parent_config->name;
1803 if (empty($parent_config->$type)) {
1804 continue;
1806 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1807 continue;
1809 foreach ($parent_config->$type as $javascript) {
1810 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1811 and in_array($javascript, $excludes[$parent])) {
1812 continue;
1814 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1815 if (is_readable($javascriptfile)) {
1816 $js[] = $javascriptfile;
1822 // current theme javascripts
1823 if (is_array($this->$type)) {
1824 foreach ($this->$type as $javascript) {
1825 $javascriptfile = "$this->dir/javascript/$javascript.js";
1826 if (is_readable($javascriptfile)) {
1827 $js[] = $javascriptfile;
1831 return $js;
1835 * Resolves an exclude setting to the themes setting is applicable or the
1836 * setting of its closest parent.
1838 * @param string $variable The name of the setting the exclude setting to resolve
1839 * @param string $default
1840 * @return mixed
1842 protected function resolve_excludes($variable, $default = null) {
1843 $setting = $default;
1844 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1845 $setting = $this->{$variable};
1846 } else {
1847 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1848 if (!isset($parent_config->{$variable})) {
1849 continue;
1851 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1852 $setting = $parent_config->{$variable};
1853 break;
1857 return $setting;
1861 * Returns the content of the one huge javascript file merged from all theme javascript files.
1863 * @param bool $type
1864 * @return string
1866 public function javascript_content($type) {
1867 $jsfiles = $this->javascript_files($type);
1868 $js = '';
1869 foreach ($jsfiles as $jsfile) {
1870 $js .= file_get_contents($jsfile)."\n";
1872 return $js;
1876 * Post processes CSS.
1878 * This method post processes all of the CSS before it is served for this theme.
1879 * This is done so that things such as image URL's can be swapped in and to
1880 * run any specific CSS post process method the theme has requested.
1881 * This allows themes to use CSS settings.
1883 * @param string $css The CSS to process.
1884 * @return string The processed CSS.
1886 public function post_process($css) {
1887 // now resolve all image locations
1888 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1889 $replaced = array();
1890 foreach ($matches as $match) {
1891 if (isset($replaced[$match[0]])) {
1892 continue;
1894 $replaced[$match[0]] = true;
1895 $imagename = $match[2];
1896 $component = rtrim($match[1], '|');
1897 $imageurl = $this->image_url($imagename, $component)->out(false);
1898 // we do not need full url because the image.php is always in the same dir
1899 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1900 $css = str_replace($match[0], $imageurl, $css);
1904 // Now resolve all font locations.
1905 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1906 $replaced = array();
1907 foreach ($matches as $match) {
1908 if (isset($replaced[$match[0]])) {
1909 continue;
1911 $replaced[$match[0]] = true;
1912 $fontname = $match[2];
1913 $component = rtrim($match[1], '|');
1914 $fonturl = $this->font_url($fontname, $component)->out(false);
1915 // We do not need full url because the font.php is always in the same dir.
1916 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1917 $css = str_replace($match[0], $fonturl, $css);
1921 // Now resolve all theme settings or do any other postprocessing.
1922 // This needs to be done before calling core parser, since the parser strips [[settings]] tags.
1923 $csspostprocess = $this->csspostprocess;
1924 if (function_exists($csspostprocess)) {
1925 $css = $csspostprocess($css, $this);
1928 // Post processing using an object representation of CSS.
1929 $treeprocessor = $this->get_css_tree_post_processor();
1930 $needsparsing = !empty($treeprocessor) || !empty($this->rtlmode);
1931 if ($needsparsing) {
1933 // We might need more memory/time to do this, so let's play safe.
1934 raise_memory_limit(MEMORY_EXTRA);
1935 core_php_time_limit::raise(300);
1937 $parser = new core_cssparser($css);
1938 $csstree = $parser->parse();
1939 unset($parser);
1941 if ($this->rtlmode) {
1942 $this->rtlize($csstree);
1945 if ($treeprocessor) {
1946 $treeprocessor($csstree, $this);
1949 $css = $csstree->render();
1950 unset($csstree);
1953 return $css;
1957 * Flip a stylesheet to RTL.
1959 * @param Object $csstree The parsed CSS tree structure to flip.
1960 * @return void
1962 protected function rtlize($csstree) {
1963 $rtlcss = new core_rtlcss($csstree);
1964 $rtlcss->flip();
1968 * Return the direct URL for an image from the pix folder.
1970 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1972 * @deprecated since Moodle 3.3
1973 * @param string $imagename the name of the icon.
1974 * @param string $component specification of one plugin like in get_string()
1975 * @return moodle_url
1977 public function pix_url($imagename, $component) {
1978 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
1979 return $this->image_url($imagename, $component);
1983 * Return the direct URL for an image from the pix folder.
1985 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1987 * @param string $imagename the name of the icon.
1988 * @param string $component specification of one plugin like in get_string()
1989 * @return moodle_url
1991 public function image_url($imagename, $component) {
1992 global $CFG;
1994 $params = array('theme'=>$this->name);
1995 $svg = $this->use_svg_icons();
1997 if (empty($component) or $component === 'moodle' or $component === 'core') {
1998 $params['component'] = 'core';
1999 } else {
2000 $params['component'] = $component;
2003 $rev = theme_get_revision();
2004 if ($rev != -1) {
2005 $params['rev'] = $rev;
2008 $params['image'] = $imagename;
2010 $url = new moodle_url("/theme/image.php");
2011 if (!empty($CFG->slasharguments) and $rev > 0) {
2012 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
2013 if (!$svg) {
2014 // We add a simple /_s to the start of the path.
2015 // The underscore is used to ensure that it isn't a valid theme name.
2016 $path = '/_s'.$path;
2018 $url->set_slashargument($path, 'noparam', true);
2019 } else {
2020 if (!$svg) {
2021 // We add an SVG param so that we know not to serve SVG images.
2022 // We do this because all modern browsers support SVG and this param will one day be removed.
2023 $params['svg'] = '0';
2025 $url->params($params);
2028 return $url;
2032 * Return the URL for a font
2034 * @param string $font the name of the font (including extension).
2035 * @param string $component specification of one plugin like in get_string()
2036 * @return moodle_url
2038 public function font_url($font, $component) {
2039 global $CFG;
2041 $params = array('theme'=>$this->name);
2043 if (empty($component) or $component === 'moodle' or $component === 'core') {
2044 $params['component'] = 'core';
2045 } else {
2046 $params['component'] = $component;
2049 $rev = theme_get_revision();
2050 if ($rev != -1) {
2051 $params['rev'] = $rev;
2054 $params['font'] = $font;
2056 $url = new moodle_url("/theme/font.php");
2057 if (!empty($CFG->slasharguments) and $rev > 0) {
2058 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
2059 $url->set_slashargument($path, 'noparam', true);
2060 } else {
2061 $url->params($params);
2064 return $url;
2068 * Returns URL to the stored file via pluginfile.php.
2070 * Note the theme must also implement pluginfile.php handler,
2071 * theme revision is used instead of the itemid.
2073 * @param string $setting
2074 * @param string $filearea
2075 * @return string protocol relative URL or null if not present
2077 public function setting_file_url($setting, $filearea) {
2078 global $CFG;
2080 if (empty($this->settings->$setting)) {
2081 return null;
2084 $component = 'theme_'.$this->name;
2085 $itemid = theme_get_revision();
2086 $filepath = $this->settings->$setting;
2087 $syscontext = context_system::instance();
2089 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
2091 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
2092 // Note: unfortunately moodle_url does not support //urls yet.
2094 $url = preg_replace('|^https?://|i', '//', $url->out(false));
2096 return $url;
2100 * Serve the theme setting file.
2102 * @param string $filearea
2103 * @param array $args
2104 * @param bool $forcedownload
2105 * @param array $options
2106 * @return bool may terminate if file not found or donotdie not specified
2108 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
2109 global $CFG;
2110 require_once("$CFG->libdir/filelib.php");
2112 $syscontext = context_system::instance();
2113 $component = 'theme_'.$this->name;
2115 $revision = array_shift($args);
2116 if ($revision < 0) {
2117 $lifetime = 0;
2118 } else {
2119 $lifetime = 60*60*24*60;
2120 // By default, theme files must be cache-able by both browsers and proxies.
2121 if (!array_key_exists('cacheability', $options)) {
2122 $options['cacheability'] = 'public';
2126 $fs = get_file_storage();
2127 $relativepath = implode('/', $args);
2129 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
2130 $fullpath = rtrim($fullpath, '/');
2131 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
2132 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
2133 return true;
2134 } else {
2135 send_file_not_found();
2140 * Resolves the real image location.
2142 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
2143 * and we need a way in which to turn it off.
2144 * By default SVG won't be used unless asked for. This is done for two reasons:
2145 * 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
2146 * browser supports SVG.
2147 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
2148 * by the user due to security concerns.
2150 * @param string $image name of image, may contain relative path
2151 * @param string $component
2152 * @param bool $svg|null Should SVG images also be looked for? If null, resorts to $CFG->svgicons if that is set; falls back to
2153 * auto-detection of browser support otherwise
2154 * @return string full file path
2156 public function resolve_image_location($image, $component, $svg = false) {
2157 global $CFG;
2159 if (!is_bool($svg)) {
2160 // If $svg isn't a bool then we need to decide for ourselves.
2161 $svg = $this->use_svg_icons();
2164 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2165 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
2166 return $imagefile;
2168 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2169 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
2170 return $imagefile;
2173 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
2174 return $imagefile;
2176 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
2177 return $imagefile;
2179 return null;
2181 } else if ($component === 'theme') { //exception
2182 if ($image === 'favicon') {
2183 return "$this->dir/pix/favicon.ico";
2185 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
2186 return $imagefile;
2188 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2189 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
2190 return $imagefile;
2193 return null;
2195 } else {
2196 if (strpos($component, '_') === false) {
2197 $component = 'mod_'.$component;
2199 list($type, $plugin) = explode('_', $component, 2);
2201 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2202 return $imagefile;
2204 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2205 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2206 return $imagefile;
2209 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
2210 return $imagefile;
2212 $dir = core_component::get_plugin_directory($type, $plugin);
2213 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
2214 return $imagefile;
2216 return null;
2221 * Resolves the real font location.
2223 * @param string $font name of font file
2224 * @param string $component
2225 * @return string full file path
2227 public function resolve_font_location($font, $component) {
2228 global $CFG;
2230 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2231 if (file_exists("$this->dir/fonts_core/$font")) {
2232 return "$this->dir/fonts_core/$font";
2234 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2235 if (file_exists("$parent_config->dir/fonts_core/$font")) {
2236 return "$parent_config->dir/fonts_core/$font";
2239 if (file_exists("$CFG->dataroot/fonts/$font")) {
2240 return "$CFG->dataroot/fonts/$font";
2242 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
2243 return "$CFG->dirroot/lib/fonts/$font";
2245 return null;
2247 } else if ($component === 'theme') { // Exception.
2248 if (file_exists("$this->dir/fonts/$font")) {
2249 return "$this->dir/fonts/$font";
2251 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2252 if (file_exists("$parent_config->dir/fonts/$font")) {
2253 return "$parent_config->dir/fonts/$font";
2256 return null;
2258 } else {
2259 if (strpos($component, '_') === false) {
2260 $component = 'mod_'.$component;
2262 list($type, $plugin) = explode('_', $component, 2);
2264 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
2265 return "$this->dir/fonts_plugins/$type/$plugin/$font";
2267 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2268 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
2269 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
2272 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
2273 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
2275 $dir = core_component::get_plugin_directory($type, $plugin);
2276 if (file_exists("$dir/fonts/$font")) {
2277 return "$dir/fonts/$font";
2279 return null;
2284 * Return true if we should look for SVG images as well.
2286 * @return bool
2288 public function use_svg_icons() {
2289 global $CFG;
2290 if ($this->usesvg === null) {
2292 if (!isset($CFG->svgicons)) {
2293 $this->usesvg = core_useragent::supports_svg();
2294 } else {
2295 // Force them on/off depending upon the setting.
2296 $this->usesvg = (bool)$CFG->svgicons;
2299 return $this->usesvg;
2303 * Forces the usesvg setting to either true or false, avoiding any decision making.
2305 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
2306 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
2308 * @param bool $setting True to force the use of svg when available, null otherwise.
2310 public function force_svg_use($setting) {
2311 $this->usesvg = (bool)$setting;
2315 * Set to be in RTL mode.
2317 * This will likely be used when post processing the CSS before serving it.
2319 * @param bool $inrtl True when in RTL mode.
2321 public function set_rtl_mode($inrtl = true) {
2322 $this->rtlmode = $inrtl;
2326 * Whether the theme is being served in RTL mode.
2328 * @return bool True when in RTL mode.
2330 public function get_rtl_mode() {
2331 return $this->rtlmode;
2335 * Checks if file with any image extension exists.
2337 * The order to these images was adjusted prior to the release of 2.4
2338 * At that point the were the following image counts in Moodle core:
2340 * - png = 667 in pix dirs (1499 total)
2341 * - gif = 385 in pix dirs (606 total)
2342 * - jpg = 62 in pix dirs (74 total)
2343 * - jpeg = 0 in pix dirs (1 total)
2345 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
2347 * @param string $filepath
2348 * @param bool $svg If set to true SVG images will also be looked for.
2349 * @return string image name with extension
2351 private static function image_exists($filepath, $svg = false) {
2352 if ($svg && file_exists("$filepath.svg")) {
2353 return "$filepath.svg";
2354 } else if (file_exists("$filepath.png")) {
2355 return "$filepath.png";
2356 } else if (file_exists("$filepath.gif")) {
2357 return "$filepath.gif";
2358 } else if (file_exists("$filepath.jpg")) {
2359 return "$filepath.jpg";
2360 } else if (file_exists("$filepath.jpeg")) {
2361 return "$filepath.jpeg";
2362 } else {
2363 return false;
2368 * Loads the theme config from config.php file.
2370 * @param string $themename
2371 * @param stdClass $settings from config_plugins table
2372 * @param boolean $parentscheck true to also check the parents. .
2373 * @return stdClass The theme configuration
2375 private static function find_theme_config($themename, $settings, $parentscheck = true) {
2376 // We have to use the variable name $THEME (upper case) because that
2377 // is what is used in theme config.php files.
2379 if (!$dir = theme_config::find_theme_location($themename)) {
2380 return null;
2383 $THEME = new stdClass();
2384 $THEME->name = $themename;
2385 $THEME->dir = $dir;
2386 $THEME->settings = $settings;
2388 global $CFG; // just in case somebody tries to use $CFG in theme config
2389 include("$THEME->dir/config.php");
2391 // verify the theme configuration is OK
2392 if (!is_array($THEME->parents)) {
2393 // parents option is mandatory now
2394 return null;
2395 } else {
2396 // We use $parentscheck to only check the direct parents (avoid infinite loop).
2397 if ($parentscheck) {
2398 // Find all parent theme configs.
2399 foreach ($THEME->parents as $parent) {
2400 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
2401 if (empty($parentconfig)) {
2402 return null;
2408 return $THEME;
2412 * Finds the theme location and verifies the theme has all needed files
2413 * and is not obsoleted.
2415 * @param string $themename
2416 * @return string full dir path or null if not found
2418 private static function find_theme_location($themename) {
2419 global $CFG;
2421 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2422 $dir = "$CFG->dirroot/theme/$themename";
2424 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
2425 $dir = "$CFG->themedir/$themename";
2427 } else {
2428 return null;
2431 if (file_exists("$dir/styles.php")) {
2432 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
2433 return null;
2436 return $dir;
2440 * Get the renderer for a part of Moodle for this theme.
2442 * @param moodle_page $page the page we are rendering
2443 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
2444 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
2445 * @param string $target one of rendering target constants
2446 * @return renderer_base the requested renderer.
2448 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
2449 if (is_null($this->rf)) {
2450 $classname = $this->rendererfactory;
2451 $this->rf = new $classname($this);
2454 return $this->rf->get_renderer($page, $component, $subtype, $target);
2458 * Get the information from {@link $layouts} for this type of page.
2460 * @param string $pagelayout the the page layout name.
2461 * @return array the appropriate part of {@link $layouts}.
2463 protected function layout_info_for_page($pagelayout) {
2464 if (array_key_exists($pagelayout, $this->layouts)) {
2465 return $this->layouts[$pagelayout];
2466 } else {
2467 debugging('Invalid page layout specified: ' . $pagelayout);
2468 return $this->layouts['standard'];
2473 * Given the settings of this theme, and the page pagelayout, return the
2474 * full path of the page layout file to use.
2476 * Used by {@link core_renderer::header()}.
2478 * @param string $pagelayout the the page layout name.
2479 * @return string Full path to the lyout file to use
2481 public function layout_file($pagelayout) {
2482 global $CFG;
2484 $layoutinfo = $this->layout_info_for_page($pagelayout);
2485 $layoutfile = $layoutinfo['file'];
2487 if (array_key_exists('theme', $layoutinfo)) {
2488 $themes = array($layoutinfo['theme']);
2489 } else {
2490 $themes = array_merge(array($this->name),$this->parents);
2493 foreach ($themes as $theme) {
2494 if ($dir = $this->find_theme_location($theme)) {
2495 $path = "$dir/layout/$layoutfile";
2497 // Check the template exists, return general base theme template if not.
2498 if (is_readable($path)) {
2499 return $path;
2504 debugging('Can not find layout file for: ' . $pagelayout);
2505 // fallback to standard normal layout
2506 return "$CFG->dirroot/theme/base/layout/general.php";
2510 * Returns auxiliary page layout options specified in layout configuration array.
2512 * @param string $pagelayout
2513 * @return array
2515 public function pagelayout_options($pagelayout) {
2516 $info = $this->layout_info_for_page($pagelayout);
2517 if (!empty($info['options'])) {
2518 return $info['options'];
2520 return array();
2524 * Inform a block_manager about the block regions this theme wants on this
2525 * page layout.
2527 * @param string $pagelayout the general type of the page.
2528 * @param block_manager $blockmanager the block_manger to set up.
2530 public function setup_blocks($pagelayout, $blockmanager) {
2531 $layoutinfo = $this->layout_info_for_page($pagelayout);
2532 if (!empty($layoutinfo['regions'])) {
2533 $blockmanager->add_regions($layoutinfo['regions'], false);
2534 $blockmanager->set_default_region($layoutinfo['defaultregion']);
2539 * Gets the visible name for the requested block region.
2541 * @param string $region The region name to get
2542 * @param string $theme The theme the region belongs to (may come from the parent theme)
2543 * @return string
2545 protected function get_region_name($region, $theme) {
2546 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
2547 // A name exists in this theme, so use it
2548 if (substr($regionstring, 0, 1) != '[') {
2549 return $regionstring;
2552 // Otherwise, try to find one elsewhere
2553 // Check parents, if any
2554 foreach ($this->parents as $parentthemename) {
2555 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
2556 if (substr($regionstring, 0, 1) != '[') {
2557 return $regionstring;
2561 // Last resort, try the bootstrapbase theme for names
2562 return get_string('region-' . $region, 'theme_bootstrapbase');
2566 * Get the list of all block regions known to this theme in all templates.
2568 * @return array internal region name => human readable name.
2570 public function get_all_block_regions() {
2571 $regions = array();
2572 foreach ($this->layouts as $layoutinfo) {
2573 foreach ($layoutinfo['regions'] as $region) {
2574 $regions[$region] = $this->get_region_name($region, $this->name);
2577 return $regions;
2581 * Returns the human readable name of the theme
2583 * @return string
2585 public function get_theme_name() {
2586 return get_string('pluginname', 'theme_'.$this->name);
2590 * Returns the block render method.
2592 * It is set by the theme via:
2593 * $THEME->blockrendermethod = '...';
2595 * It can be one of two values, blocks or blocks_for_region.
2596 * It should be set to the method being used by the theme layouts.
2598 * @return string
2600 public function get_block_render_method() {
2601 if ($this->blockrendermethod) {
2602 // Return the specified block render method.
2603 return $this->blockrendermethod;
2605 // Its not explicitly set, check the parent theme configs.
2606 foreach ($this->parent_configs as $config) {
2607 if (isset($config->blockrendermethod)) {
2608 return $config->blockrendermethod;
2611 // Default it to blocks.
2612 return 'blocks';
2616 * Get the callable for CSS tree post processing.
2618 * @return string|null
2620 public function get_css_tree_post_processor() {
2621 $configs = [$this] + $this->parent_configs;
2622 foreach ($configs as $config) {
2623 if (!empty($config->csstreepostprocessor) && is_callable($config->csstreepostprocessor)) {
2624 return $config->csstreepostprocessor;
2627 return null;
2633 * This class keeps track of which HTML tags are currently open.
2635 * This makes it much easier to always generate well formed XHTML output, even
2636 * if execution terminates abruptly. Any time you output some opening HTML
2637 * without the matching closing HTML, you should push the necessary close tags
2638 * onto the stack.
2640 * @copyright 2009 Tim Hunt
2641 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2642 * @since Moodle 2.0
2643 * @package core
2644 * @category output
2646 class xhtml_container_stack {
2649 * @var array Stores the list of open containers.
2651 protected $opencontainers = array();
2654 * @var array In developer debug mode, stores a stack trace of all opens and
2655 * closes, so we can output helpful error messages when there is a mismatch.
2657 protected $log = array();
2660 * @var boolean Store whether we are developer debug mode. We need this in
2661 * several places including in the destructor where we may not have access to $CFG.
2663 protected $isdebugging;
2666 * Constructor
2668 public function __construct() {
2669 global $CFG;
2670 $this->isdebugging = $CFG->debugdeveloper;
2674 * Push the close HTML for a recently opened container onto the stack.
2676 * @param string $type The type of container. This is checked when {@link pop()}
2677 * is called and must match, otherwise a developer debug warning is output.
2678 * @param string $closehtml The HTML required to close the container.
2680 public function push($type, $closehtml) {
2681 $container = new stdClass;
2682 $container->type = $type;
2683 $container->closehtml = $closehtml;
2684 if ($this->isdebugging) {
2685 $this->log('Open', $type);
2687 array_push($this->opencontainers, $container);
2691 * Pop the HTML for the next closing container from the stack. The $type
2692 * must match the type passed when the container was opened, otherwise a
2693 * warning will be output.
2695 * @param string $type The type of container.
2696 * @return string the HTML required to close the container.
2698 public function pop($type) {
2699 if (empty($this->opencontainers)) {
2700 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2701 $this->output_log(), DEBUG_DEVELOPER);
2702 return;
2705 $container = array_pop($this->opencontainers);
2706 if ($container->type != $type) {
2707 debugging('<p>The type of container to be closed (' . $container->type .
2708 ') does not match the type of the next open container (' . $type .
2709 '). This suggests there is a nesting problem.</p>' .
2710 $this->output_log(), DEBUG_DEVELOPER);
2712 if ($this->isdebugging) {
2713 $this->log('Close', $type);
2715 return $container->closehtml;
2719 * Close all but the last open container. This is useful in places like error
2720 * handling, where you want to close all the open containers (apart from <body>)
2721 * before outputting the error message.
2723 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2724 * developer debug warning if it isn't.
2725 * @return string the HTML required to close any open containers inside <body>.
2727 public function pop_all_but_last($shouldbenone = false) {
2728 if ($shouldbenone && count($this->opencontainers) != 1) {
2729 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2730 $this->output_log(), DEBUG_DEVELOPER);
2732 $output = '';
2733 while (count($this->opencontainers) > 1) {
2734 $container = array_pop($this->opencontainers);
2735 $output .= $container->closehtml;
2737 return $output;
2741 * You can call this function if you want to throw away an instance of this
2742 * class without properly emptying the stack (for example, in a unit test).
2743 * Calling this method stops the destruct method from outputting a developer
2744 * debug warning. After calling this method, the instance can no longer be used.
2746 public function discard() {
2747 $this->opencontainers = null;
2751 * Adds an entry to the log.
2753 * @param string $action The name of the action
2754 * @param string $type The type of action
2756 protected function log($action, $type) {
2757 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
2758 format_backtrace(debug_backtrace()) . '</li>';
2762 * Outputs the log's contents as a HTML list.
2764 * @return string HTML list of the log
2766 protected function output_log() {
2767 return '<ul>' . implode("\n", $this->log) . '</ul>';