Merge branch 'MDL-81073' of https://github.com/paulholden/moodle
[moodle.git] / lib / outputlib.php
blob63e2376b57a9294ada35e7084e75f222dc20d581
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.
182 * @return array The built theme content in a multi-dimensional array of name => direction => content
184 function theme_build_css_for_themes($themeconfigs = [], $directions = ['rtl', 'ltr'],
185 $cache = true, $mtraceprogress = false): array {
186 global $CFG;
188 if (empty($themeconfigs)) {
189 return [];
192 require_once("{$CFG->libdir}/csslib.php");
194 $themescss = [];
195 $themerev = theme_get_revision();
196 // Make sure the local cache directory exists.
197 make_localcache_directory('theme');
199 foreach ($themeconfigs as $themeconfig) {
200 $themecss = [];
201 $oldrevision = theme_get_sub_revision_for_theme($themeconfig->name);
202 $newrevision = theme_get_next_sub_revision_for_theme($themeconfig->name);
204 // First generate all the new css.
205 foreach ($directions as $direction) {
206 if ($mtraceprogress) {
207 $timestart = microtime(true);
208 mtrace('Building theme CSS for ' . $themeconfig->name . ' [' .
209 $direction . '] ...', '');
211 // Lock it on. Technically we should build all themes for SVG and no SVG - but ie9 is out of support.
212 $themeconfig->force_svg_use(true);
213 $themeconfig->set_rtl_mode(($direction === 'rtl'));
215 $themecss[$direction] = $themeconfig->get_css_content();
216 if ($cache) {
217 $themeconfig->set_css_content_cache($themecss[$direction]);
218 $filename = theme_get_css_filename($themeconfig->name, $themerev, $newrevision, $direction);
219 css_store_css($themeconfig, $filename, $themecss[$direction]);
221 if ($mtraceprogress) {
222 mtrace(' done in ' . round(microtime(true) - $timestart, 2) . ' seconds.');
225 $themescss[$themeconfig->name] = $themecss;
227 if ($cache) {
228 // Only update the theme revision after we've successfully created the
229 // new CSS cache.
230 theme_set_sub_revision_for_theme($themeconfig->name, $newrevision);
232 // Now purge old files. We must purge all old files in the local cache
233 // because we've incremented the theme sub revision. This will leave any
234 // files with the old revision inaccessbile so we might as well removed
235 // them from disk.
236 foreach (['ltr', 'rtl'] as $direction) {
237 $oldcss = theme_get_css_filename($themeconfig->name, $themerev, $oldrevision, $direction);
238 if (file_exists($oldcss)) {
239 unlink($oldcss);
245 return $themescss;
249 * Invalidate all server and client side caches.
251 * This method deletes the physical directory that is used to cache the theme
252 * files used for serving.
253 * Because it deletes the main theme cache directory all themes are reset by
254 * this function.
256 function theme_reset_all_caches() {
257 global $CFG, $PAGE;
258 require_once("{$CFG->libdir}/filelib.php");
260 $next = theme_get_next_revision();
261 theme_set_revision($next);
263 if (!empty($CFG->themedesignermode)) {
264 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner');
265 $cache->purge();
268 // Purge compiled post processed css.
269 cache::make('core', 'postprocessedcss')->purge();
271 // Delete all old theme localcaches.
272 $themecachedirs = glob("{$CFG->localcachedir}/theme/*", GLOB_ONLYDIR);
273 foreach ($themecachedirs as $localcachedir) {
274 fulldelete($localcachedir);
277 if ($PAGE) {
278 $PAGE->reload_theme();
283 * Reset static caches.
285 * This method indicates that all running cron processes should exit at the
286 * next opportunity.
288 function theme_reset_static_caches() {
289 \core\task\manager::clear_static_caches();
293 * Enable or disable theme designer mode.
295 * @param bool $state
297 function theme_set_designer_mod($state) {
298 set_config('themedesignermode', (int)!empty($state));
299 // Reset caches after switching mode so that any designer mode caches get purged too.
300 theme_reset_all_caches();
304 * Purge theme used in context caches.
306 function theme_purge_used_in_context_caches() {
307 \cache::make('core', 'theme_usedincontext')->purge();
311 * Delete theme used in context cache for a particular theme.
313 * When switching themes, both old and new theme caches are deleted.
314 * This gives the query the opportunity to recache accurate results for both themes.
316 * @param string $newtheme The incoming new theme.
317 * @param string $oldtheme The theme that was already set.
319 function theme_delete_used_in_context_cache(string $newtheme, string $oldtheme): void {
320 if ((strlen($newtheme) > 0) && (strlen($oldtheme) > 0)) {
321 // Theme -> theme.
322 \cache::make('core', 'theme_usedincontext')->delete($oldtheme);
323 \cache::make('core', 'theme_usedincontext')->delete($newtheme);
324 } else {
325 // No theme -> theme, or theme -> no theme.
326 \cache::make('core', 'theme_usedincontext')->delete($newtheme . $oldtheme);
331 * This class represents the configuration variables of a Moodle theme.
333 * All the variables with access: public below (with a few exceptions that are marked)
334 * are the properties you can set in your themes config.php file.
336 * There are also some methods and protected variables that are part of the inner
337 * workings of Moodle's themes system. If you are just editing a themes config.php
338 * file, you can just ignore those, and the following information for developers.
340 * Normally, to create an instance of this class, you should use the
341 * {@link theme_config::load()} factory method to load a themes config.php file.
342 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
343 * will create one for you, accessible as $PAGE->theme.
345 * @copyright 2009 Tim Hunt
346 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
347 * @since Moodle 2.0
348 * @package core
349 * @category output
351 class theme_config {
354 * @var string Default theme, used when requested theme not found.
356 const DEFAULT_THEME = 'boost';
358 /** The key under which the SCSS file is stored amongst the CSS files. */
359 const SCSS_KEY = '__SCSS__';
362 * @var array You can base your theme on other themes by linking to the other theme as
363 * parents. This lets you use the CSS and layouts from the other themes
364 * (see {@link theme_config::$layouts}).
365 * That makes it easy to create a new theme that is similar to another one
366 * but with a few changes. In this themes CSS you only need to override
367 * those rules you want to change.
369 public $parents;
372 * @var array The names of all the stylesheets from this theme that you would
373 * like included, in order. Give the names of the files without .css.
375 public $sheets = array();
378 * @var array The names of all the stylesheets from parents that should be excluded.
379 * true value may be used to specify all parents or all themes from one parent.
380 * If no value specified value from parent theme used.
382 public $parents_exclude_sheets = null;
385 * @var array List of plugin sheets to be excluded.
386 * If no value specified value from parent theme used.
388 public $plugins_exclude_sheets = null;
391 * @var array List of style sheets that are included in the text editor bodies.
392 * Sheets from parent themes are used automatically and can not be excluded.
394 public $editor_sheets = array();
397 * @var bool Whether a fallback version of the stylesheet will be used
398 * whilst the final version is generated.
400 public $usefallback = false;
403 * @var array The names of all the javascript files this theme that you would
404 * like included from head, in order. Give the names of the files without .js.
406 public $javascripts = array();
409 * @var array The names of all the javascript files this theme that you would
410 * like included from footer, in order. Give the names of the files without .js.
412 public $javascripts_footer = array();
415 * @var array The names of all the javascript files from parents that should
416 * be excluded. true value may be used to specify all parents or all themes
417 * from one parent.
418 * If no value specified value from parent theme used.
420 public $parents_exclude_javascripts = null;
423 * @var array Which file to use for each page layout.
425 * This is an array of arrays. The keys of the outer array are the different layouts.
426 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
427 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
428 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
429 * That file also has a good example of how to set this setting.
431 * For each layout, the value in the outer array is an array that describes
432 * how you want that type of page to look. For example
433 * <pre>
434 * $THEME->layouts = array(
435 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
436 * 'standard' => array(
437 * 'theme' = 'mytheme',
438 * 'file' => 'normal.php',
439 * 'regions' => array('side-pre', 'side-post'),
440 * 'defaultregion' => 'side-post'
441 * ),
442 * // The site home page.
443 * 'home' => array(
444 * 'theme' = 'mytheme',
445 * 'file' => 'home.php',
446 * 'regions' => array('side-pre', 'side-post'),
447 * 'defaultregion' => 'side-post'
448 * ),
449 * // ...
450 * );
451 * </pre>
453 * 'theme' name of the theme where is the layout located
454 * 'file' is the layout file to use for this type of page.
455 * layout files are stored in layout subfolder
456 * 'regions' This lists the regions on the page where blocks may appear. For
457 * each region you list here, your layout file must include a call to
458 * <pre>
459 * echo $OUTPUT->blocks_for_region($regionname);
460 * </pre>
461 * or equivalent so that the blocks are actually visible.
463 * 'defaultregion' If the list of regions is non-empty, then you must pick
464 * one of the one of them as 'default'. This has two meanings. First, this is
465 * where new blocks are added. Second, if there are any blocks associated with
466 * the page, but in non-existent regions, they appear here. (Imaging, for example,
467 * that someone added blocks using a different theme that used different region
468 * names, and then switched to this theme.)
470 public $layouts = array();
473 * @var string Name of the renderer factory class to use. Must implement the
474 * {@link renderer_factory} interface.
476 * This is an advanced feature. Moodle output is generated by 'renderers',
477 * you can customise the HTML that is output by writing custom renderers,
478 * and then you need to specify 'renderer factory' so that Moodle can find
479 * your renderers.
481 * There are some renderer factories supplied with Moodle. Please follow these
482 * links to see what they do.
483 * <ul>
484 * <li>{@link standard_renderer_factory} - the default.</li>
485 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
486 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
487 * </ul>
489 public $rendererfactory = 'standard_renderer_factory';
492 * @var string Function to do custom CSS post-processing.
494 * This is an advanced feature. If you want to do custom post-processing on the
495 * CSS before it is output (for example, to replace certain variable names
496 * with particular values) you can give the name of a function here.
498 public $csspostprocess = null;
501 * @var string Function to do custom CSS post-processing on a parsed CSS tree.
503 * This is an advanced feature. If you want to do custom post-processing on the
504 * CSS before it is output, you can provide the name of the function here. The
505 * function will receive a CSS tree document as first parameter, and the theme_config
506 * object as second parameter. A return value is not required, the tree can
507 * be edited in place.
509 public $csstreepostprocessor = null;
512 * @var string Accessibility: Right arrow-like character is
513 * used in the breadcrumb trail, course navigation menu
514 * (previous/next activity), calendar, and search forum block.
515 * If the theme does not set characters, appropriate defaults
516 * are set automatically. Please DO NOT
517 * use &lt; &gt; &raquo; - these are confusing for blind users.
519 public $rarrow = null;
522 * @var string Accessibility: Left arrow-like character is
523 * used in the breadcrumb trail, course navigation menu
524 * (previous/next activity), calendar, and search forum block.
525 * If the theme does not set characters, appropriate defaults
526 * are set automatically. Please DO NOT
527 * use &lt; &gt; &raquo; - these are confusing for blind users.
529 public $larrow = null;
532 * @var string Accessibility: Up arrow-like character is used in
533 * the book heirarchical navigation.
534 * If the theme does not set characters, appropriate defaults
535 * are set automatically. Please DO NOT
536 * use ^ - this is confusing for blind users.
538 public $uarrow = null;
541 * @var string Accessibility: Down arrow-like character.
542 * If the theme does not set characters, appropriate defaults
543 * are set automatically.
545 public $darrow = null;
548 * @var bool Some themes may want to disable ajax course editing.
550 public $enablecourseajax = true;
553 * @var string Determines served document types
554 * - 'html5' the only officially supported doctype in Moodle
555 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
556 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
558 public $doctype = 'html5';
561 * @var string requiredblocks If set to a string, will list the block types that cannot be deleted. Defaults to
562 * navigation and settings.
564 public $requiredblocks = false;
566 //==Following properties are not configurable from theme config.php==
569 * @var string The name of this theme. Set automatically when this theme is
570 * loaded. This can not be set in theme config.php
572 public $name;
575 * @var string The folder where this themes files are stored. This is set
576 * automatically. This can not be set in theme config.php
578 public $dir;
581 * @var stdClass Theme settings stored in config_plugins table.
582 * This can not be set in theme config.php
584 public $settings = null;
587 * @var bool If set to true and the theme enables the dock then blocks will be able
588 * to be moved to the special dock
590 public $enable_dock = false;
593 * @var bool If set to true then this theme will not be shown in the theme selector unless
594 * theme designer mode is turned on.
596 public $hidefromselector = false;
599 * @var array list of YUI CSS modules to be included on each page. This may be used
600 * to remove cssreset and use cssnormalise module instead.
602 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
605 * An associative array of block manipulations that should be made if the user is using an rtl language.
606 * The key is the original block region, and the value is the block region to change to.
607 * This is used when displaying blocks for regions only.
608 * @var array
610 public $blockrtlmanipulations = array();
613 * @var renderer_factory Instance of the renderer_factory implementation
614 * we are using. Implementation detail.
616 protected $rf = null;
619 * @var array List of parent config objects.
621 protected $parent_configs = array();
624 * Used to determine whether we can serve SVG images or not.
625 * @var bool
627 private $usesvg = null;
630 * Whether in RTL mode or not.
631 * @var bool
633 protected $rtlmode = false;
636 * The SCSS file to compile (without .scss), located in the scss/ folder of the theme.
637 * Or a Closure, which receives the theme_config as argument and must
638 * return the SCSS content.
639 * @var string|Closure
641 public $scss = false;
644 * Local cache of the SCSS property.
645 * @var false|array
647 protected $scsscache = null;
650 * The name of the function to call to get the SCSS code to inject.
651 * @var string
653 public $extrascsscallback = null;
656 * The name of the function to call to get SCSS to prepend.
657 * @var string
659 public $prescsscallback = null;
662 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
663 * Defaults to {@link core_renderer::blocks_for_region()}
664 * @var string
666 public $blockrendermethod = null;
669 * Remember the results of icon remapping for the current page.
670 * @var array
672 public $remapiconcache = [];
675 * The name of the function to call to get precompiled CSS.
676 * @var string
678 public $precompiledcsscallback = null;
681 * Whether the theme uses course index.
682 * @var bool
684 public $usescourseindex = false;
687 * Configuration for the page activity header
688 * @var array
690 public $activityheaderconfig = [];
693 * For backward compatibility with old themes.
694 * BLOCK_ADDBLOCK_POSITION_DEFAULT, BLOCK_ADDBLOCK_POSITION_FLATNAV.
695 * @var int
697 public $addblockposition;
700 * editor_scss file(s) provided by this theme.
701 * @var array
703 public $editor_scss;
706 * Name of the class extending \core\output\icon_system.
707 * @var string
709 public $iconsystem;
712 * Theme defines its own editing mode switch.
713 * @var bool
715 public $haseditswitch = false;
718 * Allows a theme to customise primary navigation by specifying the list of items to remove.
719 * @var array
721 public $removedprimarynavitems = [];
724 * Load the config.php file for a particular theme, and return an instance
725 * of this class. (That is, this is a factory method.)
727 * @param string $themename the name of the theme.
728 * @return theme_config an instance of this class.
730 public static function load($themename) {
731 global $CFG;
733 // load theme settings from db
734 try {
735 $settings = get_config('theme_'.$themename);
736 } catch (dml_exception $e) {
737 // most probably moodle tables not created yet
738 $settings = new stdClass();
741 if ($config = theme_config::find_theme_config($themename, $settings)) {
742 return new theme_config($config);
744 } else if ($themename == theme_config::DEFAULT_THEME) {
745 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
747 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
748 debugging('This page should be using theme ' . $themename .
749 ' which cannot be initialised. Falling back to the site theme ' . $CFG->theme, DEBUG_NORMAL);
750 return new theme_config($config);
752 } else {
753 // bad luck, the requested theme has some problems - admin see details in theme config
754 debugging('This page should be using theme ' . $themename .
755 ' which cannot be initialised. Nor can the site theme ' . $CFG->theme .
756 '. Falling back to ' . theme_config::DEFAULT_THEME, DEBUG_NORMAL);
757 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
762 * Theme diagnostic code. It is very problematic to send debug output
763 * to the actual CSS file, instead this functions is supposed to
764 * diagnose given theme and highlights all potential problems.
765 * This information should be available from the theme selection page
766 * or some other debug page for theme designers.
768 * @param string $themename
769 * @return array description of problems
771 public static function diagnose($themename) {
772 //TODO: MDL-21108
773 return array();
777 * Private constructor, can be called only from the factory method.
778 * @param stdClass $config
780 private function __construct($config) {
781 global $CFG; //needed for included lib.php files
783 $this->settings = $config->settings;
784 $this->name = $config->name;
785 $this->dir = $config->dir;
787 if ($this->name != self::DEFAULT_THEME) {
788 $baseconfig = self::find_theme_config(self::DEFAULT_THEME, $this->settings);
789 } else {
790 $baseconfig = $config;
793 // Ensure that each of the configurable properties defined below are also defined at the class level.
794 $configurable = [
795 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'usefallback',
796 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
797 'layouts', 'enablecourseajax', 'requiredblocks',
798 'rendererfactory', 'csspostprocess', 'editor_sheets', 'editor_scss', 'rarrow', 'larrow', 'uarrow', 'darrow',
799 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations', 'blockrendermethod',
800 'scss', 'extrascsscallback', 'prescsscallback', 'csstreepostprocessor', 'addblockposition',
801 'iconsystem', 'precompiledcsscallback', 'haseditswitch', 'usescourseindex', 'activityheaderconfig',
802 'removedprimarynavitems',
805 foreach ($config as $key=>$value) {
806 if (in_array($key, $configurable)) {
807 $this->$key = $value;
811 // verify all parents and load configs and renderers
812 foreach ($this->parents as $parent) {
813 if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
814 // this is not good - better exclude faulty parents
815 continue;
817 $libfile = $parent_config->dir.'/lib.php';
818 if (is_readable($libfile)) {
819 // theme may store various function here
820 include_once($libfile);
822 $renderersfile = $parent_config->dir.'/renderers.php';
823 if (is_readable($renderersfile)) {
824 // may contain core and plugin renderers and renderer factory
825 include_once($renderersfile);
827 $this->parent_configs[$parent] = $parent_config;
829 $libfile = $this->dir.'/lib.php';
830 if (is_readable($libfile)) {
831 // theme may store various function here
832 include_once($libfile);
834 $rendererfile = $this->dir.'/renderers.php';
835 if (is_readable($rendererfile)) {
836 // may contain core and plugin renderers and renderer factory
837 include_once($rendererfile);
838 } else {
839 // check if renderers.php file is missnamed renderer.php
840 if (is_readable($this->dir.'/renderer.php')) {
841 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
842 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
846 // cascade all layouts properly
847 foreach ($baseconfig->layouts as $layout=>$value) {
848 if (!isset($this->layouts[$layout])) {
849 foreach ($this->parent_configs as $parent_config) {
850 if (isset($parent_config->layouts[$layout])) {
851 $this->layouts[$layout] = $parent_config->layouts[$layout];
852 continue 2;
855 $this->layouts[$layout] = $value;
859 //fix arrows if needed
860 $this->check_theme_arrows();
864 * Let the theme initialise the page object (usually $PAGE).
866 * This may be used for example to request jQuery in add-ons.
868 * @param moodle_page $page
870 public function init_page(moodle_page $page) {
871 $themeinitfunction = 'theme_'.$this->name.'_page_init';
872 if (function_exists($themeinitfunction)) {
873 $themeinitfunction($page);
878 * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow, $THEME->darrow have been set (theme/-/config.php).
879 * If not it applies sensible defaults.
881 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
882 * search forum block, etc. Important: these are 'silent' in a screen-reader
883 * (unlike &gt; &raquo;), and must be accompanied by text.
885 private function check_theme_arrows() {
886 if (!isset($this->rarrow) and !isset($this->larrow)) {
887 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
888 // Also OK in Win 9x/2K/IE 5.x
889 $this->rarrow = '&#x25BA;';
890 $this->larrow = '&#x25C4;';
891 $this->uarrow = '&#x25B2;';
892 $this->darrow = '&#x25BC;';
893 if (empty($_SERVER['HTTP_USER_AGENT'])) {
894 $uagent = '';
895 } else {
896 $uagent = $_SERVER['HTTP_USER_AGENT'];
898 if (false !== strpos($uagent, 'Opera')
899 || false !== strpos($uagent, 'Mac')) {
900 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
901 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
902 $this->rarrow = '&#x25B6;&#xFE0E;';
903 $this->larrow = '&#x25C0;&#xFE0E;';
905 elseif ((false !== strpos($uagent, 'Konqueror'))
906 || (false !== strpos($uagent, 'Android'))) {
907 // The fonts on Android don't include the characters required for this to work as expected.
908 // So we use the same ones Konqueror uses.
909 $this->rarrow = '&rarr;';
910 $this->larrow = '&larr;';
911 $this->uarrow = '&uarr;';
912 $this->darrow = '&darr;';
914 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
915 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
916 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
917 // To be safe, non-Unicode browsers!
918 $this->rarrow = '&gt;';
919 $this->larrow = '&lt;';
920 $this->uarrow = '^';
921 $this->darrow = 'v';
924 // RTL support - in RTL languages, swap r and l arrows
925 if (right_to_left()) {
926 $t = $this->rarrow;
927 $this->rarrow = $this->larrow;
928 $this->larrow = $t;
934 * Returns output renderer prefixes, these are used when looking
935 * for the overridden renderers in themes.
937 * @return array
939 public function renderer_prefixes() {
940 global $CFG; // just in case the included files need it
942 $prefixes = array('theme_'.$this->name);
944 foreach ($this->parent_configs as $parent) {
945 $prefixes[] = 'theme_'.$parent->name;
948 return $prefixes;
952 * Returns the stylesheet URL of this editor content
954 * @param bool $encoded false means use & and true use &amp; in URLs
955 * @return moodle_url
957 public function editor_css_url($encoded=true) {
958 global $CFG;
959 $rev = theme_get_revision();
960 $type = 'editor';
961 if (right_to_left()) {
962 $type .= '-rtl';
965 if ($rev > -1) {
966 $themesubrevision = theme_get_sub_revision_for_theme($this->name);
968 // Provide the sub revision to allow us to invalidate cached theme CSS
969 // on a per theme basis, rather than globally.
970 if ($themesubrevision && $themesubrevision > 0) {
971 $rev .= "_{$themesubrevision}";
974 $url = new moodle_url("/theme/styles.php");
975 if (!empty($CFG->slasharguments)) {
976 $url->set_slashargument("/{$this->name}/{$rev}/{$type}", 'noparam', true);
977 } else {
978 $url->params([
979 'theme' => $this->name,
980 'rev' => $rev,
981 'type' => $type,
984 } else {
985 $url = new moodle_url('/theme/styles_debug.php', [
986 'theme' => $this->name,
987 'type' => $type,
990 return $url;
994 * Returns the content of the CSS to be used in editor content
996 * @return array
998 public function editor_css_files() {
999 $files = array();
1001 // First editor plugins.
1002 $plugins = core_component::get_plugin_list('editor');
1003 foreach ($plugins as $plugin => $fulldir) {
1004 $sheetfile = "$fulldir/editor_styles.css";
1005 if (is_readable($sheetfile)) {
1006 $files['plugin_'.$plugin] = $sheetfile;
1009 $subplugintypes = core_component::get_subplugins("editor_{$plugin}") ?? [];
1010 // Fetch sheets for any editor subplugins.
1011 foreach ($subplugintypes as $plugintype => $subplugins) {
1012 foreach ($subplugins as $subplugin) {
1013 $plugindir = core_component::get_plugin_directory($plugintype, $subplugin);
1014 $sheetfile = "{$plugindir}/editor_styles.css";
1015 if (is_readable($sheetfile)) {
1016 $files["{$plugintype}_{$subplugin}"] = $sheetfile;
1022 // Then parent themes - base first, the immediate parent last.
1023 foreach (array_reverse($this->parent_configs) as $parent_config) {
1024 if (empty($parent_config->editor_sheets)) {
1025 continue;
1027 foreach ($parent_config->editor_sheets as $sheet) {
1028 $sheetfile = "$parent_config->dir/style/$sheet.css";
1029 if (is_readable($sheetfile)) {
1030 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
1034 // Finally this theme.
1035 if (!empty($this->editor_sheets)) {
1036 foreach ($this->editor_sheets as $sheet) {
1037 $sheetfile = "$this->dir/style/$sheet.css";
1038 if (is_readable($sheetfile)) {
1039 $files['theme_'.$sheet] = $sheetfile;
1044 return $files;
1048 * Compiles and returns the content of the SCSS to be used in editor content
1050 * @return string Compiled CSS from the editor SCSS
1052 public function editor_scss_to_css() {
1053 $css = '';
1054 $dir = $this->dir;
1055 $filenames = [];
1057 // Use editor_scss file(s) provided by this theme if set.
1058 if (!empty($this->editor_scss)) {
1059 $filenames = $this->editor_scss;
1060 } else {
1061 // If no editor_scss set, move up theme hierarchy until one is found (if at all).
1062 // This is so child themes only need to set editor_scss if an override is required.
1063 foreach (array_reverse($this->parent_configs) as $parentconfig) {
1064 if (!empty($parentconfig->editor_scss)) {
1065 $dir = $parentconfig->dir;
1066 $filenames = $parentconfig->editor_scss;
1068 // Config found, stop looking.
1069 break;
1074 if (!empty($filenames)) {
1075 $compiler = new core_scss();
1077 foreach ($filenames as $filename) {
1078 $compiler->set_file("{$dir}/scss/{$filename}.scss");
1080 try {
1081 $css .= $compiler->to_css();
1082 } catch (\Exception $e) {
1083 debugging('Error while compiling editor SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
1088 return $css;
1092 * Get the stylesheet URL of this theme.
1094 * @param moodle_page $page Not used... deprecated?
1095 * @return moodle_url[]
1097 public function css_urls(moodle_page $page) {
1098 global $CFG;
1100 $rev = theme_get_revision();
1102 $urls = array();
1104 $svg = $this->use_svg_icons();
1105 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
1107 if ($rev > -1) {
1108 $filename = right_to_left() ? 'all-rtl' : 'all';
1109 $url = new moodle_url("/theme/styles.php");
1110 $themesubrevision = theme_get_sub_revision_for_theme($this->name);
1112 // Provide the sub revision to allow us to invalidate cached theme CSS
1113 // on a per theme basis, rather than globally.
1114 if ($themesubrevision && $themesubrevision > 0) {
1115 $rev .= "_{$themesubrevision}";
1118 if (!empty($CFG->slasharguments)) {
1119 $slashargs = '';
1120 if (!$svg) {
1121 // We add a simple /_s to the start of the path.
1122 // The underscore is used to ensure that it isn't a valid theme name.
1123 $slashargs .= '/_s'.$slashargs;
1125 $slashargs .= '/'.$this->name.'/'.$rev.'/'.$filename;
1126 if ($separate) {
1127 $slashargs .= '/chunk0';
1129 $url->set_slashargument($slashargs, 'noparam', true);
1130 } else {
1131 $params = array('theme' => $this->name, 'rev' => $rev, 'type' => $filename);
1132 if (!$svg) {
1133 // We add an SVG param so that we know not to serve SVG images.
1134 // We do this because all modern browsers support SVG and this param will one day be removed.
1135 $params['svg'] = '0';
1137 if ($separate) {
1138 $params['chunk'] = '0';
1140 $url->params($params);
1142 $urls[] = $url;
1144 } else {
1145 $baseurl = new moodle_url('/theme/styles_debug.php');
1147 $css = $this->get_css_files(true);
1148 if (!$svg) {
1149 // We add an SVG param so that we know not to serve SVG images.
1150 // We do this because all modern browsers support SVG and this param will one day be removed.
1151 $baseurl->param('svg', '0');
1153 if (right_to_left()) {
1154 $baseurl->param('rtl', 1);
1156 if ($separate) {
1157 // We might need to chunk long files.
1158 $baseurl->param('chunk', '0');
1160 if (core_useragent::is_ie()) {
1161 // Lalala, IE does not allow more than 31 linked CSS files from main document.
1162 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
1163 foreach ($css['parents'] as $parent=>$sheets) {
1164 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
1165 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
1167 if ($this->get_scss_property()) {
1168 // No need to define the type as IE here.
1169 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
1171 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
1173 } else {
1174 foreach ($css['plugins'] as $plugin=>$unused) {
1175 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
1177 foreach ($css['parents'] as $parent=>$sheets) {
1178 foreach ($sheets as $sheet=>$unused2) {
1179 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
1182 foreach ($css['theme'] as $sheet => $filename) {
1183 if ($sheet === self::SCSS_KEY) {
1184 // This is the theme SCSS file.
1185 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
1186 } else {
1187 // Sheet first in order to make long urls easier to read.
1188 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
1194 // Allow themes to change the css url to something like theme/mytheme/mycss.php.
1195 component_callback('theme_' . $this->name, 'alter_css_urls', [&$urls]);
1196 return $urls;
1200 * Get the whole css stylesheet for production mode.
1202 * NOTE: this method is not expected to be used from any addons.
1204 * @return string CSS markup compressed
1206 public function get_css_content() {
1208 $csscontent = '';
1209 foreach ($this->get_css_files(false) as $type => $value) {
1210 foreach ($value as $identifier => $val) {
1211 if (is_array($val)) {
1212 foreach ($val as $v) {
1213 $csscontent .= file_get_contents($v) . "\n";
1215 } else {
1216 if ($type === 'theme' && $identifier === self::SCSS_KEY) {
1217 // We need the content from SCSS because this is the SCSS file from the theme.
1218 if ($compiled = $this->get_css_content_from_scss(false)) {
1219 $csscontent .= $compiled;
1220 } else {
1221 // The compiler failed so default back to any precompiled css that might
1222 // exist.
1223 $csscontent .= $this->get_precompiled_css_content();
1225 } else {
1226 $csscontent .= file_get_contents($val) . "\n";
1231 $csscontent = $this->post_process($csscontent);
1232 $csscontent = core_minify::css($csscontent);
1234 return $csscontent;
1237 * Set post processed CSS content cache.
1239 * @param string $csscontent The post processed CSS content.
1240 * @return bool True if the content was successfully cached.
1242 public function set_css_content_cache($csscontent) {
1244 $cache = cache::make('core', 'postprocessedcss');
1245 $key = $this->get_css_cache_key();
1247 return $cache->set($key, $csscontent);
1251 * Return whether the post processed CSS content has been cached.
1253 * @return bool Whether the post-processed CSS is available in the cache.
1255 public function has_css_cached_content() {
1257 $key = $this->get_css_cache_key();
1258 $cache = cache::make('core', 'postprocessedcss');
1260 return $cache->has($key);
1264 * Return cached post processed CSS content.
1266 * @return bool|string The cached css content or false if not found.
1268 public function get_css_cached_content() {
1270 $key = $this->get_css_cache_key();
1271 $cache = cache::make('core', 'postprocessedcss');
1273 return $cache->get($key);
1277 * Generate the css content cache key.
1279 * @return string The post processed css cache key.
1281 public function get_css_cache_key() {
1282 $nosvg = (!$this->use_svg_icons()) ? 'nosvg_' : '';
1283 $rtlmode = ($this->rtlmode == true) ? 'rtl' : 'ltr';
1285 return $nosvg . $this->name . '_' . $rtlmode;
1289 * Get the theme designer css markup,
1290 * the parameters are coming from css_urls().
1292 * NOTE: this method is not expected to be used from any addons.
1294 * @param string $type
1295 * @param string $subtype
1296 * @param string $sheet
1297 * @return string CSS markup
1299 public function get_css_content_debug($type, $subtype, $sheet) {
1300 if ($type === 'scss') {
1301 // The SCSS file of the theme is requested.
1302 $csscontent = $this->get_css_content_from_scss(true);
1303 if ($csscontent !== false) {
1304 return $this->post_process($csscontent);
1306 return '';
1309 $cssfiles = array();
1310 $css = $this->get_css_files(true);
1312 if ($type === 'ie') {
1313 // IE is a sloppy browser with weird limits, sorry.
1314 if ($subtype === 'plugins') {
1315 $cssfiles = $css['plugins'];
1317 } else if ($subtype === 'parents') {
1318 if (empty($sheet)) {
1319 // Do not bother with the empty parent here.
1320 } else {
1321 // Build up the CSS for that parent so we can serve it as one file.
1322 foreach ($css[$subtype][$sheet] as $parent => $css) {
1323 $cssfiles[] = $css;
1326 } else if ($subtype === 'theme') {
1327 $cssfiles = $css['theme'];
1328 foreach ($cssfiles as $key => $value) {
1329 if (in_array($key, [self::SCSS_KEY])) {
1330 // Remove the SCSS file from the theme CSS files.
1331 // The SCSS files use the type 'scss', not 'ie'.
1332 unset($cssfiles[$key]);
1337 } else if ($type === 'plugin') {
1338 if (isset($css['plugins'][$subtype])) {
1339 $cssfiles[] = $css['plugins'][$subtype];
1342 } else if ($type === 'parent') {
1343 if (isset($css['parents'][$subtype][$sheet])) {
1344 $cssfiles[] = $css['parents'][$subtype][$sheet];
1347 } else if ($type === 'theme') {
1348 if (isset($css['theme'][$sheet])) {
1349 $cssfiles[] = $css['theme'][$sheet];
1353 $csscontent = '';
1354 foreach ($cssfiles as $file) {
1355 $contents = file_get_contents($file);
1356 $contents = $this->post_process($contents);
1357 $comment = "/** Path: $type $subtype $sheet.' **/\n";
1358 $stats = '';
1359 $csscontent .= $comment.$stats.$contents."\n\n";
1362 return $csscontent;
1366 * Get the whole css stylesheet for editor iframe.
1368 * NOTE: this method is not expected to be used from any addons.
1370 * @return string CSS markup
1372 public function get_css_content_editor() {
1373 $css = '';
1374 $cssfiles = $this->editor_css_files();
1376 // If editor has static CSS, include it.
1377 foreach ($cssfiles as $file) {
1378 $css .= file_get_contents($file)."\n";
1381 // If editor has SCSS, compile and include it.
1382 if (($convertedscss = $this->editor_scss_to_css())) {
1383 $css .= $convertedscss;
1386 $output = $this->post_process($css);
1388 return $output;
1392 * Returns an array of organised CSS files required for this output.
1394 * @param bool $themedesigner
1395 * @return array nested array of file paths
1397 protected function get_css_files($themedesigner) {
1398 global $CFG;
1400 $cache = null;
1401 $cachekey = 'cssfiles';
1402 if ($themedesigner) {
1403 require_once($CFG->dirroot.'/lib/csslib.php');
1404 // We need some kind of caching here because otherwise the page navigation becomes
1405 // way too slow in theme designer mode. Feel free to create full cache definition later...
1406 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
1407 if ($files = $cache->get($cachekey)) {
1408 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
1409 unset($files['created']);
1410 return $files;
1415 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
1417 // Get all plugin sheets.
1418 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
1419 if ($excludes !== true) {
1420 foreach (core_component::get_plugin_types() as $type=>$unused) {
1421 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
1422 continue;
1424 $plugins = core_component::get_plugin_list($type);
1425 foreach ($plugins as $plugin=>$fulldir) {
1426 if (!empty($excludes[$type]) and is_array($excludes[$type])
1427 and in_array($plugin, $excludes[$type])) {
1428 continue;
1431 // Get the CSS from the plugin.
1432 $sheetfile = "$fulldir/styles.css";
1433 if (is_readable($sheetfile)) {
1434 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
1437 // Create a list of candidate sheets from parents (direct parent last) and current theme.
1438 $candidates = array();
1439 foreach (array_reverse($this->parent_configs) as $parent_config) {
1440 $candidates[] = $parent_config->name;
1442 $candidates[] = $this->name;
1444 // Add the sheets found.
1445 foreach ($candidates as $candidate) {
1446 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1447 if (is_readable($sheetthemefile)) {
1448 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
1455 // Find out wanted parent sheets.
1456 $excludes = $this->resolve_excludes('parents_exclude_sheets');
1457 if ($excludes !== true) {
1458 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1459 $parent = $parent_config->name;
1460 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
1461 continue;
1463 foreach ($parent_config->sheets as $sheet) {
1464 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1465 && in_array($sheet, $excludes[$parent])) {
1466 continue;
1469 // We never refer to the parent LESS files.
1470 $sheetfile = "$parent_config->dir/style/$sheet.css";
1471 if (is_readable($sheetfile)) {
1472 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1479 // Current theme sheets.
1480 // We first add the SCSS file because we want the CSS ones to
1481 // be included after the SCSS code.
1482 if ($this->get_scss_property()) {
1483 $cssfiles['theme'][self::SCSS_KEY] = true;
1485 if (is_array($this->sheets)) {
1486 foreach ($this->sheets as $sheet) {
1487 $sheetfile = "$this->dir/style/$sheet.css";
1488 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1489 $cssfiles['theme'][$sheet] = $sheetfile;
1494 if ($cache) {
1495 $files = $cssfiles;
1496 $files['created'] = time();
1497 $cache->set($cachekey, $files);
1499 return $cssfiles;
1503 * Return the CSS content generated from the SCSS file.
1505 * @param bool $themedesigner True if theme designer is enabled.
1506 * @return bool|string Return false when the compilation failed. Else the compiled string.
1508 protected function get_css_content_from_scss($themedesigner) {
1509 global $CFG;
1511 list($paths, $scss) = $this->get_scss_property();
1512 if (!$scss) {
1513 throw new coding_exception('The theme did not define a SCSS file, or it is not readable.');
1516 // We might need more memory/time to do this, so let's play safe.
1517 raise_memory_limit(MEMORY_EXTRA);
1518 core_php_time_limit::raise(300);
1520 // TODO: MDL-62757 When changing anything in this method please do not forget to check
1521 // if the validate() method in class admin_setting_configthemepreset needs updating too.
1523 $cachedir = make_localcache_directory('scsscache-' . $this->name, false);
1524 $cacheoptions = [];
1525 if ($themedesigner) {
1526 $cacheoptions = array(
1527 'cacheDir' => $cachedir,
1528 'prefix' => 'scssphp_',
1529 'forceRefresh' => false,
1531 } else {
1532 if (file_exists($cachedir)) {
1533 remove_dir($cachedir);
1537 // Set-up the compiler.
1538 $compiler = new core_scss($cacheoptions);
1540 if ($this->supports_source_maps($themedesigner)) {
1541 // Enable source maps.
1542 $compiler->setSourceMapOptions([
1543 'sourceMapBasepath' => str_replace('\\', '/', $CFG->dirroot),
1544 'sourceMapRootpath' => $CFG->wwwroot . '/'
1546 $compiler->setSourceMap($compiler::SOURCE_MAP_INLINE);
1549 $compiler->prepend_raw_scss($this->get_pre_scss_code());
1550 if (is_string($scss)) {
1551 $compiler->set_file($scss);
1552 } else {
1553 $compiler->append_raw_scss($scss($this));
1554 $compiler->setImportPaths($paths);
1556 $compiler->append_raw_scss($this->get_extra_scss_code());
1558 try {
1559 // Compile!
1560 $compiled = $compiler->to_css();
1562 } catch (\Exception $e) {
1563 $compiled = false;
1564 debugging('Error while compiling SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
1567 // Try to save memory.
1568 $compiler = null;
1569 unset($compiler);
1571 return $compiled;
1575 * Return the precompiled CSS if the precompiledcsscallback exists.
1577 * @return string Return compiled css.
1579 public function get_precompiled_css_content() {
1580 $configs = array_reverse($this->parent_configs) + [$this];
1581 $css = '';
1583 foreach ($configs as $config) {
1584 if (isset($config->precompiledcsscallback)) {
1585 $function = $config->precompiledcsscallback;
1586 if (function_exists($function)) {
1587 $css .= $function($this);
1591 return $css;
1595 * Get the icon system to use.
1597 * @return string
1599 public function get_icon_system() {
1601 // Getting all the candidate functions.
1602 $system = false;
1603 if (isset($this->iconsystem) && \core\output\icon_system::is_valid_system($this->iconsystem)) {
1604 return $this->iconsystem;
1606 foreach ($this->parent_configs as $parent_config) {
1607 if (isset($parent_config->iconsystem) && \core\output\icon_system::is_valid_system($parent_config->iconsystem)) {
1608 return $parent_config->iconsystem;
1611 return \core\output\icon_system::STANDARD;
1615 * Return extra SCSS code to add when compiling.
1617 * This is intended to be used by themes to inject some SCSS code
1618 * before it gets compiled. If you want to inject variables you
1619 * should use {@link self::get_scss_variables()}.
1621 * @return string The SCSS code to inject.
1623 public function get_extra_scss_code() {
1624 $content = '';
1626 // Getting all the candidate functions.
1627 $candidates = array();
1628 foreach (array_reverse($this->parent_configs) as $parent_config) {
1629 if (!isset($parent_config->extrascsscallback)) {
1630 continue;
1632 $candidates[] = $parent_config->extrascsscallback;
1635 if (isset($this->extrascsscallback)) {
1636 $candidates[] = $this->extrascsscallback;
1639 // Calling the functions.
1640 foreach ($candidates as $function) {
1641 if (function_exists($function)) {
1642 $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n";
1646 return $content;
1650 * SCSS code to prepend when compiling.
1652 * This is intended to be used by themes to inject SCSS code before it gets compiled.
1654 * @return string The SCSS code to inject.
1656 public function get_pre_scss_code() {
1657 $content = '';
1659 // Getting all the candidate functions.
1660 $candidates = array();
1661 foreach (array_reverse($this->parent_configs) as $parent_config) {
1662 if (!isset($parent_config->prescsscallback)) {
1663 continue;
1665 $candidates[] = $parent_config->prescsscallback;
1668 if (isset($this->prescsscallback)) {
1669 $candidates[] = $this->prescsscallback;
1672 // Calling the functions.
1673 foreach ($candidates as $function) {
1674 if (function_exists($function)) {
1675 $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n";
1679 return $content;
1683 * Get the SCSS property.
1685 * This resolves whether a SCSS file (or content) has to be used when generating
1686 * the stylesheet for the theme. It will look at parents themes and check the
1687 * SCSS properties there.
1689 * @return False when SCSS is not used.
1690 * An array with the import paths, and the path to the SCSS file or Closure as second.
1692 public function get_scss_property() {
1693 if ($this->scsscache === null) {
1694 $configs = [$this] + $this->parent_configs;
1695 $scss = null;
1697 foreach ($configs as $config) {
1698 $path = "{$config->dir}/scss";
1700 // We collect the SCSS property until we've found one.
1701 if (empty($scss) && !empty($config->scss)) {
1702 $candidate = is_string($config->scss) ? "{$path}/{$config->scss}.scss" : $config->scss;
1703 if ($candidate instanceof Closure) {
1704 $scss = $candidate;
1705 } else if (is_string($candidate) && is_readable($candidate)) {
1706 $scss = $candidate;
1710 // We collect the import paths once we've found a SCSS property.
1711 if ($scss && is_dir($path)) {
1712 $paths[] = $path;
1717 $this->scsscache = $scss !== null ? [$paths, $scss] : false;
1720 return $this->scsscache;
1724 * Generate a URL to the file that serves theme JavaScript files.
1726 * If we determine that the theme has no relevant files, then we return
1727 * early with a null value.
1729 * @param bool $inhead true means head url, false means footer
1730 * @return moodle_url|null
1732 public function javascript_url($inhead) {
1733 global $CFG;
1735 $rev = theme_get_revision();
1736 $params = array('theme'=>$this->name,'rev'=>$rev);
1737 $params['type'] = $inhead ? 'head' : 'footer';
1739 // Return early if there are no files to serve
1740 if (count($this->javascript_files($params['type'])) === 0) {
1741 return null;
1744 if (!empty($CFG->slasharguments) and $rev > 0) {
1745 $url = new moodle_url("/theme/javascript.php");
1746 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
1747 return $url;
1748 } else {
1749 return new moodle_url('/theme/javascript.php', $params);
1754 * Get the URL's for the JavaScript files used by this theme.
1755 * They won't be served directly, instead they'll be mediated through
1756 * theme/javascript.php.
1758 * @param string $type Either javascripts_footer, or javascripts
1759 * @return array
1761 public function javascript_files($type) {
1762 if ($type === 'footer') {
1763 $type = 'javascripts_footer';
1764 } else {
1765 $type = 'javascripts';
1768 $js = array();
1769 // find out wanted parent javascripts
1770 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1771 if ($excludes !== true) {
1772 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1773 $parent = $parent_config->name;
1774 if (empty($parent_config->$type)) {
1775 continue;
1777 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1778 continue;
1780 foreach ($parent_config->$type as $javascript) {
1781 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1782 and in_array($javascript, $excludes[$parent])) {
1783 continue;
1785 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1786 if (is_readable($javascriptfile)) {
1787 $js[] = $javascriptfile;
1793 // current theme javascripts
1794 if (is_array($this->$type)) {
1795 foreach ($this->$type as $javascript) {
1796 $javascriptfile = "$this->dir/javascript/$javascript.js";
1797 if (is_readable($javascriptfile)) {
1798 $js[] = $javascriptfile;
1802 return $js;
1806 * Resolves an exclude setting to the themes setting is applicable or the
1807 * setting of its closest parent.
1809 * @param string $variable The name of the setting the exclude setting to resolve
1810 * @param string $default
1811 * @return mixed
1813 protected function resolve_excludes($variable, $default = null) {
1814 $setting = $default;
1815 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1816 $setting = $this->{$variable};
1817 } else {
1818 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1819 if (!isset($parent_config->{$variable})) {
1820 continue;
1822 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1823 $setting = $parent_config->{$variable};
1824 break;
1828 return $setting;
1832 * Returns the content of the one huge javascript file merged from all theme javascript files.
1834 * @param bool $type
1835 * @return string
1837 public function javascript_content($type) {
1838 $jsfiles = $this->javascript_files($type);
1839 $js = '';
1840 foreach ($jsfiles as $jsfile) {
1841 $js .= file_get_contents($jsfile)."\n";
1843 return $js;
1847 * Post processes CSS.
1849 * This method post processes all of the CSS before it is served for this theme.
1850 * This is done so that things such as image URL's can be swapped in and to
1851 * run any specific CSS post process method the theme has requested.
1852 * This allows themes to use CSS settings.
1854 * @param string $css The CSS to process.
1855 * @return string The processed CSS.
1857 public function post_process($css) {
1858 // now resolve all image locations
1859 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1860 $replaced = array();
1861 foreach ($matches as $match) {
1862 if (isset($replaced[$match[0]])) {
1863 continue;
1865 $replaced[$match[0]] = true;
1866 $imagename = $match[2];
1867 $component = rtrim($match[1], '|');
1868 $imageurl = $this->image_url($imagename, $component)->out(false);
1869 // we do not need full url because the image.php is always in the same dir
1870 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1871 $css = str_replace($match[0], $imageurl, $css);
1875 // Now resolve all font locations.
1876 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1877 $replaced = array();
1878 foreach ($matches as $match) {
1879 if (isset($replaced[$match[0]])) {
1880 continue;
1882 $replaced[$match[0]] = true;
1883 $fontname = $match[2];
1884 $component = rtrim($match[1], '|');
1885 $fonturl = $this->font_url($fontname, $component)->out(false);
1886 // We do not need full url because the font.php is always in the same dir.
1887 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1888 $css = str_replace($match[0], $fonturl, $css);
1892 // Now resolve all theme settings or do any other postprocessing.
1893 // This needs to be done before calling core parser, since the parser strips [[settings]] tags.
1894 $csspostprocess = $this->csspostprocess;
1895 if ($csspostprocess && function_exists($csspostprocess)) {
1896 $css = $csspostprocess($css, $this);
1899 // Post processing using an object representation of CSS.
1900 $treeprocessor = $this->get_css_tree_post_processor();
1901 $needsparsing = !empty($treeprocessor) || !empty($this->rtlmode);
1902 if ($needsparsing) {
1904 // We might need more memory/time to do this, so let's play safe.
1905 raise_memory_limit(MEMORY_EXTRA);
1906 core_php_time_limit::raise(300);
1908 $parser = new core_cssparser($css);
1909 $csstree = $parser->parse();
1910 unset($parser);
1912 if ($this->rtlmode) {
1913 $this->rtlize($csstree);
1916 if ($treeprocessor) {
1917 $treeprocessor($csstree, $this);
1920 $css = $csstree->render();
1921 unset($csstree);
1924 return $css;
1928 * Flip a stylesheet to RTL.
1930 * @param Object $csstree The parsed CSS tree structure to flip.
1931 * @return void
1933 protected function rtlize($csstree) {
1934 $rtlcss = new core_rtlcss($csstree);
1935 $rtlcss->flip();
1939 * Return the direct URL for an image from the pix folder.
1941 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1943 * @deprecated since Moodle 3.3
1944 * @param string $imagename the name of the icon.
1945 * @param string $component specification of one plugin like in get_string()
1946 * @return moodle_url
1948 public function pix_url($imagename, $component) {
1949 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
1950 return $this->image_url($imagename, $component);
1954 * Return the direct URL for an image from the pix folder.
1956 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1958 * @param string $imagename the name of the icon.
1959 * @param string $component specification of one plugin like in get_string()
1960 * @return moodle_url
1962 public function image_url($imagename, $component) {
1963 global $CFG;
1965 $params = array('theme'=>$this->name);
1966 $svg = $this->use_svg_icons();
1968 if (empty($component) or $component === 'moodle' or $component === 'core') {
1969 $params['component'] = 'core';
1970 } else {
1971 $params['component'] = $component;
1974 $rev = theme_get_revision();
1975 if ($rev != -1) {
1976 $params['rev'] = $rev;
1979 $params['image'] = $imagename;
1981 $url = new moodle_url("/theme/image.php");
1982 if (!empty($CFG->slasharguments) and $rev > 0) {
1983 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1984 if (!$svg) {
1985 // We add a simple /_s to the start of the path.
1986 // The underscore is used to ensure that it isn't a valid theme name.
1987 $path = '/_s'.$path;
1989 $url->set_slashargument($path, 'noparam', true);
1990 } else {
1991 if (!$svg) {
1992 // We add an SVG param so that we know not to serve SVG images.
1993 // We do this because all modern browsers support SVG and this param will one day be removed.
1994 $params['svg'] = '0';
1996 $url->params($params);
1999 return $url;
2003 * Return the URL for a font
2005 * @param string $font the name of the font (including extension).
2006 * @param string $component specification of one plugin like in get_string()
2007 * @return moodle_url
2009 public function font_url($font, $component) {
2010 global $CFG;
2012 $params = array('theme'=>$this->name);
2014 if (empty($component) or $component === 'moodle' or $component === 'core') {
2015 $params['component'] = 'core';
2016 } else {
2017 $params['component'] = $component;
2020 $rev = theme_get_revision();
2021 if ($rev != -1) {
2022 $params['rev'] = $rev;
2025 $params['font'] = $font;
2027 $url = new moodle_url("/theme/font.php");
2028 if (!empty($CFG->slasharguments) and $rev > 0) {
2029 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
2030 $url->set_slashargument($path, 'noparam', true);
2031 } else {
2032 $url->params($params);
2035 return $url;
2039 * Returns URL to the stored file via pluginfile.php.
2041 * Note the theme must also implement pluginfile.php handler,
2042 * theme revision is used instead of the itemid.
2044 * @param string $setting
2045 * @param string $filearea
2046 * @return string protocol relative URL or null if not present
2048 public function setting_file_url($setting, $filearea) {
2049 global $CFG;
2051 if (empty($this->settings->$setting)) {
2052 return null;
2055 $component = 'theme_'.$this->name;
2056 $itemid = theme_get_revision();
2057 $filepath = $this->settings->$setting;
2058 $syscontext = context_system::instance();
2060 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
2062 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
2063 // Note: unfortunately moodle_url does not support //urls yet.
2065 $url = preg_replace('|^https?://|i', '//', $url->out(false));
2067 return $url;
2071 * Serve the theme setting file.
2073 * @param string $filearea
2074 * @param array $args
2075 * @param bool $forcedownload
2076 * @param array $options
2077 * @return bool may terminate if file not found or donotdie not specified
2079 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
2080 global $CFG;
2081 require_once("$CFG->libdir/filelib.php");
2083 $syscontext = context_system::instance();
2084 $component = 'theme_'.$this->name;
2086 $revision = array_shift($args);
2087 if ($revision < 0) {
2088 $lifetime = 0;
2089 } else {
2090 $lifetime = 60*60*24*60;
2091 // By default, theme files must be cache-able by both browsers and proxies.
2092 if (!array_key_exists('cacheability', $options)) {
2093 $options['cacheability'] = 'public';
2097 $fs = get_file_storage();
2098 $relativepath = implode('/', $args);
2100 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
2101 $fullpath = rtrim($fullpath, '/');
2102 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
2103 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
2104 return true;
2105 } else {
2106 send_file_not_found();
2111 * Resolves the real image location.
2113 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
2114 * and we need a way in which to turn it off.
2115 * By default SVG won't be used unless asked for. This is done for two reasons:
2116 * 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
2117 * browser supports SVG.
2118 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
2119 * by the user due to security concerns.
2121 * @param string $image name of image, may contain relative path
2122 * @param string $component
2123 * @param bool $svg|null Should SVG images also be looked for? If null, falls back to auto-detection of browser support
2124 * @return string full file path
2126 public function resolve_image_location($image, $component, $svg = false) {
2127 global $CFG;
2129 if (!is_bool($svg)) {
2130 // If $svg isn't a bool then we need to decide for ourselves.
2131 $svg = $this->use_svg_icons();
2134 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2135 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
2136 return $imagefile;
2138 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2139 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
2140 return $imagefile;
2143 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
2144 return $imagefile;
2146 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
2147 return $imagefile;
2149 return null;
2151 } else if ($component === 'theme') { //exception
2152 if ($image === 'favicon') {
2153 return "$this->dir/pix/favicon.ico";
2155 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
2156 return $imagefile;
2158 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2159 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
2160 return $imagefile;
2163 return null;
2165 } else {
2166 if (strpos($component, '_') === false) {
2167 $component = "mod_{$component}";
2169 list($type, $plugin) = explode('_', $component, 2);
2171 // In Moodle 4.0 we introduced a new image format.
2172 // Support that image format here.
2173 $candidates = [$image];
2175 if ($type === 'mod') {
2176 if ($image === 'icon' || $image === 'monologo') {
2177 $candidates = ['monologo', 'icon'];
2178 if ($image === 'icon') {
2179 debugging(
2180 "The 'icon' image for activity modules has been replaced with a new 'monologo'. " .
2181 "Please update your calling code to fetch the new icon where possible. " .
2182 "Called for component {$component}.",
2183 DEBUG_DEVELOPER
2188 foreach ($candidates as $image) {
2189 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2190 return $imagefile;
2193 // Base first, the immediate parent last.
2194 foreach (array_reverse($this->parent_configs) as $parentconfig) {
2195 if ($imagefile = $this->image_exists("$parentconfig->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2196 return $imagefile;
2199 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
2200 return $imagefile;
2202 $dir = core_component::get_plugin_directory($type, $plugin);
2203 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
2204 return $imagefile;
2207 return null;
2212 * Resolves the real font location.
2214 * @param string $font name of font file
2215 * @param string $component
2216 * @return string full file path
2218 public function resolve_font_location($font, $component) {
2219 global $CFG;
2221 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2222 if (file_exists("$this->dir/fonts_core/$font")) {
2223 return "$this->dir/fonts_core/$font";
2225 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2226 if (file_exists("$parent_config->dir/fonts_core/$font")) {
2227 return "$parent_config->dir/fonts_core/$font";
2230 if (file_exists("$CFG->dataroot/fonts/$font")) {
2231 return "$CFG->dataroot/fonts/$font";
2233 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
2234 return "$CFG->dirroot/lib/fonts/$font";
2236 return null;
2238 } else if ($component === 'theme') { // Exception.
2239 if (file_exists("$this->dir/fonts/$font")) {
2240 return "$this->dir/fonts/$font";
2242 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2243 if (file_exists("$parent_config->dir/fonts/$font")) {
2244 return "$parent_config->dir/fonts/$font";
2247 return null;
2249 } else {
2250 if (strpos($component, '_') === false) {
2251 $component = 'mod_'.$component;
2253 list($type, $plugin) = explode('_', $component, 2);
2255 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
2256 return "$this->dir/fonts_plugins/$type/$plugin/$font";
2258 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2259 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
2260 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
2263 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
2264 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
2266 $dir = core_component::get_plugin_directory($type, $plugin);
2267 if (file_exists("$dir/fonts/$font")) {
2268 return "$dir/fonts/$font";
2270 return null;
2275 * Return true if we should look for SVG images as well.
2277 * @return bool
2279 public function use_svg_icons() {
2280 if ($this->usesvg === null) {
2281 $this->usesvg = core_useragent::supports_svg();
2284 return $this->usesvg;
2288 * Forces the usesvg setting to either true or false, avoiding any decision making.
2290 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
2291 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
2293 * @param bool $setting True to force the use of svg when available, null otherwise.
2295 public function force_svg_use($setting) {
2296 $this->usesvg = (bool)$setting;
2300 * Set to be in RTL mode.
2302 * This will likely be used when post processing the CSS before serving it.
2304 * @param bool $inrtl True when in RTL mode.
2306 public function set_rtl_mode($inrtl = true) {
2307 $this->rtlmode = $inrtl;
2311 * Checks if source maps are supported
2313 * @param bool $themedesigner True if theme designer is enabled.
2314 * @return boolean True if source maps are supported.
2316 public function supports_source_maps($themedesigner): bool {
2317 if (empty($this->rtlmode) && $themedesigner) {
2318 return true;
2320 return false;
2324 * Whether the theme is being served in RTL mode.
2326 * @return bool True when in RTL mode.
2328 public function get_rtl_mode() {
2329 return $this->rtlmode;
2333 * Checks if file with any image extension exists.
2335 * The order to these images was adjusted prior to the release of 2.4
2336 * At that point the were the following image counts in Moodle core:
2338 * - png = 667 in pix dirs (1499 total)
2339 * - gif = 385 in pix dirs (606 total)
2340 * - jpg = 62 in pix dirs (74 total)
2341 * - jpeg = 0 in pix dirs (1 total)
2343 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
2345 * @param string $filepath
2346 * @param bool $svg If set to true SVG images will also be looked for.
2347 * @return string image name with extension
2349 private static function image_exists($filepath, $svg = false) {
2350 if ($svg && file_exists("$filepath.svg")) {
2351 return "$filepath.svg";
2352 } else if (file_exists("$filepath.png")) {
2353 return "$filepath.png";
2354 } else if (file_exists("$filepath.gif")) {
2355 return "$filepath.gif";
2356 } else if (file_exists("$filepath.jpg")) {
2357 return "$filepath.jpg";
2358 } else if (file_exists("$filepath.jpeg")) {
2359 return "$filepath.jpeg";
2360 } else {
2361 return false;
2366 * Loads the theme config from config.php file.
2368 * @param string $themename
2369 * @param stdClass $settings from config_plugins table
2370 * @param boolean $parentscheck true to also check the parents. .
2371 * @return stdClass The theme configuration
2373 private static function find_theme_config($themename, $settings, $parentscheck = true) {
2374 // We have to use the variable name $THEME (upper case) because that
2375 // is what is used in theme config.php files.
2377 if (!$dir = theme_config::find_theme_location($themename)) {
2378 return null;
2381 $THEME = new stdClass();
2382 $THEME->name = $themename;
2383 $THEME->dir = $dir;
2384 $THEME->settings = $settings;
2386 global $CFG; // just in case somebody tries to use $CFG in theme config
2387 include("$THEME->dir/config.php");
2389 // verify the theme configuration is OK
2390 if (!is_array($THEME->parents)) {
2391 // parents option is mandatory now
2392 return null;
2393 } else {
2394 // We use $parentscheck to only check the direct parents (avoid infinite loop).
2395 if ($parentscheck) {
2396 // Find all parent theme configs.
2397 foreach ($THEME->parents as $parent) {
2398 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
2399 if (empty($parentconfig)) {
2400 return null;
2406 return $THEME;
2410 * Finds the theme location and verifies the theme has all needed files
2411 * and is not obsoleted.
2413 * @param string $themename
2414 * @return string full dir path or null if not found
2416 private static function find_theme_location($themename) {
2417 global $CFG;
2419 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2420 $dir = "$CFG->dirroot/theme/$themename";
2422 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
2423 $dir = "$CFG->themedir/$themename";
2425 } else {
2426 return null;
2429 if (file_exists("$dir/styles.php")) {
2430 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
2431 return null;
2434 return $dir;
2438 * Get the renderer for a part of Moodle for this theme.
2440 * @param moodle_page $page the page we are rendering
2441 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
2442 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
2443 * @param string $target one of rendering target constants
2444 * @return renderer_base the requested renderer.
2446 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
2447 if (is_null($this->rf)) {
2448 $classname = $this->rendererfactory;
2449 $this->rf = new $classname($this);
2452 return $this->rf->get_renderer($page, $component, $subtype, $target);
2456 * Get the information from {@link $layouts} for this type of page.
2458 * @param string $pagelayout the the page layout name.
2459 * @return array the appropriate part of {@link $layouts}.
2461 protected function layout_info_for_page($pagelayout) {
2462 if (array_key_exists($pagelayout, $this->layouts)) {
2463 return $this->layouts[$pagelayout];
2464 } else {
2465 debugging('Invalid page layout specified: ' . $pagelayout);
2466 return $this->layouts['standard'];
2471 * Given the settings of this theme, and the page pagelayout, return the
2472 * full path of the page layout file to use.
2474 * Used by {@link core_renderer::header()}.
2476 * @param string $pagelayout the the page layout name.
2477 * @return string Full path to the lyout file to use
2479 public function layout_file($pagelayout) {
2480 global $CFG;
2482 $layoutinfo = $this->layout_info_for_page($pagelayout);
2483 $layoutfile = $layoutinfo['file'];
2485 if (array_key_exists('theme', $layoutinfo)) {
2486 $themes = array($layoutinfo['theme']);
2487 } else {
2488 $themes = array_merge(array($this->name),$this->parents);
2491 foreach ($themes as $theme) {
2492 if ($dir = $this->find_theme_location($theme)) {
2493 $path = "$dir/layout/$layoutfile";
2495 // Check the template exists, return general base theme template if not.
2496 if (is_readable($path)) {
2497 return $path;
2502 debugging('Can not find layout file for: ' . $pagelayout);
2503 // fallback to standard normal layout
2504 return "$CFG->dirroot/theme/base/layout/general.php";
2508 * Returns auxiliary page layout options specified in layout configuration array.
2510 * @param string $pagelayout
2511 * @return array
2513 public function pagelayout_options($pagelayout) {
2514 $info = $this->layout_info_for_page($pagelayout);
2515 if (!empty($info['options'])) {
2516 return $info['options'];
2518 return array();
2522 * Inform a block_manager about the block regions this theme wants on this
2523 * page layout.
2525 * @param string $pagelayout the general type of the page.
2526 * @param block_manager $blockmanager the block_manger to set up.
2528 public function setup_blocks($pagelayout, $blockmanager) {
2529 $layoutinfo = $this->layout_info_for_page($pagelayout);
2530 if (!empty($layoutinfo['regions'])) {
2531 $blockmanager->add_regions($layoutinfo['regions'], false);
2532 $blockmanager->set_default_region($layoutinfo['defaultregion']);
2537 * Gets the visible name for the requested block region.
2539 * @param string $region The region name to get
2540 * @param string $theme The theme the region belongs to (may come from the parent theme)
2541 * @return string
2543 protected function get_region_name($region, $theme) {
2545 $stringman = get_string_manager();
2547 // Check if the name is defined in the theme.
2548 if ($stringman->string_exists('region-' . $region, 'theme_' . $theme)) {
2549 return get_string('region-' . $region, 'theme_' . $theme);
2552 // Check the theme parents.
2553 foreach ($this->parents as $parentthemename) {
2554 if ($stringman->string_exists('region-' . $region, 'theme_' . $parentthemename)) {
2555 return get_string('region-' . $region, 'theme_' . $parentthemename);
2559 // Last resort, try the boost theme for names.
2560 return get_string('region-' . $region, 'theme_boost');
2564 * Get the list of all block regions known to this theme in all templates.
2566 * @return array internal region name => human readable name.
2568 public function get_all_block_regions() {
2569 $regions = array();
2570 foreach ($this->layouts as $layoutinfo) {
2571 foreach ($layoutinfo['regions'] as $region) {
2572 $regions[$region] = $this->get_region_name($region, $this->name);
2575 return $regions;
2579 * Returns the human readable name of the theme
2581 * @return string
2583 public function get_theme_name() {
2584 return get_string('pluginname', 'theme_'.$this->name);
2588 * Returns the block render method.
2590 * It is set by the theme via:
2591 * $THEME->blockrendermethod = '...';
2593 * It can be one of two values, blocks or blocks_for_region.
2594 * It should be set to the method being used by the theme layouts.
2596 * @return string
2598 public function get_block_render_method() {
2599 if ($this->blockrendermethod) {
2600 // Return the specified block render method.
2601 return $this->blockrendermethod;
2603 // Its not explicitly set, check the parent theme configs.
2604 foreach ($this->parent_configs as $config) {
2605 if (isset($config->blockrendermethod)) {
2606 return $config->blockrendermethod;
2609 // Default it to blocks.
2610 return 'blocks';
2614 * Get the callable for CSS tree post processing.
2616 * @return string|null
2618 public function get_css_tree_post_processor() {
2619 $configs = [$this] + $this->parent_configs;
2620 foreach ($configs as $config) {
2621 if (!empty($config->csstreepostprocessor) && is_callable($config->csstreepostprocessor)) {
2622 return $config->csstreepostprocessor;
2625 return null;
2631 * This class keeps track of which HTML tags are currently open.
2633 * This makes it much easier to always generate well formed XHTML output, even
2634 * if execution terminates abruptly. Any time you output some opening HTML
2635 * without the matching closing HTML, you should push the necessary close tags
2636 * onto the stack.
2638 * @copyright 2009 Tim Hunt
2639 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2640 * @since Moodle 2.0
2641 * @package core
2642 * @category output
2644 class xhtml_container_stack {
2647 * @var array Stores the list of open containers.
2649 protected $opencontainers = array();
2652 * @var array In developer debug mode, stores a stack trace of all opens and
2653 * closes, so we can output helpful error messages when there is a mismatch.
2655 protected $log = array();
2658 * @var boolean Store whether we are developer debug mode. We need this in
2659 * several places including in the destructor where we may not have access to $CFG.
2661 protected $isdebugging;
2664 * Constructor
2666 public function __construct() {
2667 global $CFG;
2668 $this->isdebugging = $CFG->debugdeveloper;
2672 * Push the close HTML for a recently opened container onto the stack.
2674 * @param string $type The type of container. This is checked when {@link pop()}
2675 * is called and must match, otherwise a developer debug warning is output.
2676 * @param string $closehtml The HTML required to close the container.
2678 public function push($type, $closehtml) {
2679 $container = new stdClass;
2680 $container->type = $type;
2681 $container->closehtml = $closehtml;
2682 if ($this->isdebugging) {
2683 $this->log('Open', $type);
2685 array_push($this->opencontainers, $container);
2689 * Pop the HTML for the next closing container from the stack. The $type
2690 * must match the type passed when the container was opened, otherwise a
2691 * warning will be output.
2693 * @param string $type The type of container.
2694 * @return string the HTML required to close the container.
2696 public function pop($type) {
2697 if (empty($this->opencontainers)) {
2698 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2699 $this->output_log(), DEBUG_DEVELOPER);
2700 return;
2703 $container = array_pop($this->opencontainers);
2704 if ($container->type != $type) {
2705 debugging('<p>The type of container to be closed (' . $container->type .
2706 ') does not match the type of the next open container (' . $type .
2707 '). This suggests there is a nesting problem.</p>' .
2708 $this->output_log(), DEBUG_DEVELOPER);
2710 if ($this->isdebugging) {
2711 $this->log('Close', $type);
2713 return $container->closehtml;
2717 * Close all but the last open container. This is useful in places like error
2718 * handling, where you want to close all the open containers (apart from <body>)
2719 * before outputting the error message.
2721 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2722 * developer debug warning if it isn't.
2723 * @return string the HTML required to close any open containers inside <body>.
2725 public function pop_all_but_last($shouldbenone = false) {
2726 if ($shouldbenone && count($this->opencontainers) != 1) {
2727 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2728 $this->output_log(), DEBUG_DEVELOPER);
2730 $output = '';
2731 while (count($this->opencontainers) > 1) {
2732 $container = array_pop($this->opencontainers);
2733 $output .= $container->closehtml;
2735 return $output;
2739 * You can call this function if you want to throw away an instance of this
2740 * class without properly emptying the stack (for example, in a unit test).
2741 * Calling this method stops the destruct method from outputting a developer
2742 * debug warning. After calling this method, the instance can no longer be used.
2744 public function discard() {
2745 $this->opencontainers = null;
2749 * Adds an entry to the log.
2751 * @param string $action The name of the action
2752 * @param string $type The type of action
2754 protected function log($action, $type) {
2755 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
2756 format_backtrace(debug_backtrace()) . '</li>';
2760 * Outputs the log's contents as a HTML list.
2762 * @return string HTML list of the log
2764 protected function output_log() {
2765 return '<ul>' . implode("\n", $this->log) . '</ul>';