MDL-59261 theme_boost: compiled css fallback
[moodle.git] / lib / outputlib.php
blobf57428047521e7849131835b5728a4c5e158a8a7
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;
249 $next = theme_get_next_revision();
250 theme_set_revision($next);
252 if (!empty($CFG->themedesignermode)) {
253 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner');
254 $cache->purge();
257 // Purge compiled post processed css.
258 cache::make('core', 'postprocessedcss')->purge();
260 if ($PAGE) {
261 $PAGE->reload_theme();
266 * Enable or disable theme designer mode.
268 * @param bool $state
270 function theme_set_designer_mod($state) {
271 set_config('themedesignermode', (int)!empty($state));
272 // Reset caches after switching mode so that any designer mode caches get purged too.
273 theme_reset_all_caches();
277 * Checks if the given device has a theme defined in config.php.
279 * @return bool
281 function theme_is_device_locked($device) {
282 global $CFG;
283 $themeconfigname = core_useragent::get_device_type_cfg_var_name($device);
284 return isset($CFG->config_php_settings[$themeconfigname]);
288 * Returns the theme named defined in config.php for the given device.
290 * @return string or null
292 function theme_get_locked_theme_for_device($device) {
293 global $CFG;
295 if (!theme_is_device_locked($device)) {
296 return null;
299 $themeconfigname = core_useragent::get_device_type_cfg_var_name($device);
300 return $CFG->config_php_settings[$themeconfigname];
304 * This class represents the configuration variables of a Moodle theme.
306 * All the variables with access: public below (with a few exceptions that are marked)
307 * are the properties you can set in your themes config.php file.
309 * There are also some methods and protected variables that are part of the inner
310 * workings of Moodle's themes system. If you are just editing a themes config.php
311 * file, you can just ignore those, and the following information for developers.
313 * Normally, to create an instance of this class, you should use the
314 * {@link theme_config::load()} factory method to load a themes config.php file.
315 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
316 * will create one for you, accessible as $PAGE->theme.
318 * @copyright 2009 Tim Hunt
319 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
320 * @since Moodle 2.0
321 * @package core
322 * @category output
324 class theme_config {
327 * @var string Default theme, used when requested theme not found.
329 const DEFAULT_THEME = 'boost';
331 /** The key under which the SCSS file is stored amongst the CSS files. */
332 const SCSS_KEY = '__SCSS__';
335 * @var array You can base your theme on other themes by linking to the other theme as
336 * parents. This lets you use the CSS and layouts from the other themes
337 * (see {@link theme_config::$layouts}).
338 * That makes it easy to create a new theme that is similar to another one
339 * but with a few changes. In this themes CSS you only need to override
340 * those rules you want to change.
342 public $parents;
345 * @var array The names of all the stylesheets from this theme that you would
346 * like included, in order. Give the names of the files without .css.
348 public $sheets = array();
351 * @var array The names of all the stylesheets from parents that should be excluded.
352 * true value may be used to specify all parents or all themes from one parent.
353 * If no value specified value from parent theme used.
355 public $parents_exclude_sheets = null;
358 * @var array List of plugin sheets to be excluded.
359 * If no value specified value from parent theme used.
361 public $plugins_exclude_sheets = null;
364 * @var array List of style sheets that are included in the text editor bodies.
365 * Sheets from parent themes are used automatically and can not be excluded.
367 public $editor_sheets = array();
370 * @var bool Whether a fallback version of the stylesheet will be used
371 * whilst the final version is generated.
373 public $usefallback = false;
376 * @var array The names of all the javascript files this theme that you would
377 * like included from head, in order. Give the names of the files without .js.
379 public $javascripts = array();
382 * @var array The names of all the javascript files this theme that you would
383 * like included from footer, in order. Give the names of the files without .js.
385 public $javascripts_footer = array();
388 * @var array The names of all the javascript files from parents that should
389 * be excluded. true value may be used to specify all parents or all themes
390 * from one parent.
391 * If no value specified value from parent theme used.
393 public $parents_exclude_javascripts = null;
396 * @var array Which file to use for each page layout.
398 * This is an array of arrays. The keys of the outer array are the different layouts.
399 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
400 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
401 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
402 * That file also has a good example of how to set this setting.
404 * For each layout, the value in the outer array is an array that describes
405 * how you want that type of page to look. For example
406 * <pre>
407 * $THEME->layouts = array(
408 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
409 * 'standard' => array(
410 * 'theme' = 'mytheme',
411 * 'file' => 'normal.php',
412 * 'regions' => array('side-pre', 'side-post'),
413 * 'defaultregion' => 'side-post'
414 * ),
415 * // The site home page.
416 * 'home' => array(
417 * 'theme' = 'mytheme',
418 * 'file' => 'home.php',
419 * 'regions' => array('side-pre', 'side-post'),
420 * 'defaultregion' => 'side-post'
421 * ),
422 * // ...
423 * );
424 * </pre>
426 * 'theme' name of the theme where is the layout located
427 * 'file' is the layout file to use for this type of page.
428 * layout files are stored in layout subfolder
429 * 'regions' This lists the regions on the page where blocks may appear. For
430 * each region you list here, your layout file must include a call to
431 * <pre>
432 * echo $OUTPUT->blocks_for_region($regionname);
433 * </pre>
434 * or equivalent so that the blocks are actually visible.
436 * 'defaultregion' If the list of regions is non-empty, then you must pick
437 * one of the one of them as 'default'. This has two meanings. First, this is
438 * where new blocks are added. Second, if there are any blocks associated with
439 * the page, but in non-existent regions, they appear here. (Imaging, for example,
440 * that someone added blocks using a different theme that used different region
441 * names, and then switched to this theme.)
443 public $layouts = array();
446 * @var string Name of the renderer factory class to use. Must implement the
447 * {@link renderer_factory} interface.
449 * This is an advanced feature. Moodle output is generated by 'renderers',
450 * you can customise the HTML that is output by writing custom renderers,
451 * and then you need to specify 'renderer factory' so that Moodle can find
452 * your renderers.
454 * There are some renderer factories supplied with Moodle. Please follow these
455 * links to see what they do.
456 * <ul>
457 * <li>{@link standard_renderer_factory} - the default.</li>
458 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
459 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
460 * </ul>
462 public $rendererfactory = 'standard_renderer_factory';
465 * @var string Function to do custom CSS post-processing.
467 * This is an advanced feature. If you want to do custom post-processing on the
468 * CSS before it is output (for example, to replace certain variable names
469 * with particular values) you can give the name of a function here.
471 public $csspostprocess = null;
474 * @var string Function to do custom CSS post-processing on a parsed CSS tree.
476 * This is an advanced feature. If you want to do custom post-processing on the
477 * CSS before it is output, you can provide the name of the function here. The
478 * function will receive a CSS tree document as first parameter, and the theme_config
479 * object as second parameter. A return value is not required, the tree can
480 * be edited in place.
482 public $csstreepostprocessor = null;
485 * @var string Accessibility: Right arrow-like character is
486 * used in the breadcrumb trail, course navigation menu
487 * (previous/next activity), calendar, and search forum block.
488 * If the theme does not set characters, appropriate defaults
489 * are set automatically. Please DO NOT
490 * use &lt; &gt; &raquo; - these are confusing for blind users.
492 public $rarrow = null;
495 * @var string Accessibility: Left arrow-like character is
496 * used in the breadcrumb trail, course navigation menu
497 * (previous/next activity), calendar, and search forum block.
498 * If the theme does not set characters, appropriate defaults
499 * are set automatically. Please DO NOT
500 * use &lt; &gt; &raquo; - these are confusing for blind users.
502 public $larrow = null;
505 * @var string Accessibility: Up arrow-like character is used in
506 * the book heirarchical navigation.
507 * If the theme does not set characters, appropriate defaults
508 * are set automatically. Please DO NOT
509 * use ^ - this is confusing for blind users.
511 public $uarrow = null;
514 * @var string Accessibility: Down arrow-like character.
515 * If the theme does not set characters, appropriate defaults
516 * are set automatically.
518 public $darrow = null;
521 * @var bool Some themes may want to disable ajax course editing.
523 public $enablecourseajax = true;
526 * @var string Determines served document types
527 * - 'html5' the only officially supported doctype in Moodle
528 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
529 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
531 public $doctype = 'html5';
534 * @var string requiredblocks If set to a string, will list the block types that cannot be deleted. Defaults to
535 * navigation and settings.
537 public $requiredblocks = false;
539 //==Following properties are not configurable from theme config.php==
542 * @var string The name of this theme. Set automatically when this theme is
543 * loaded. This can not be set in theme config.php
545 public $name;
548 * @var string The folder where this themes files are stored. This is set
549 * automatically. This can not be set in theme config.php
551 public $dir;
554 * @var stdClass Theme settings stored in config_plugins table.
555 * This can not be set in theme config.php
557 public $settings = null;
560 * @var bool If set to true and the theme enables the dock then blocks will be able
561 * to be moved to the special dock
563 public $enable_dock = false;
566 * @var bool If set to true then this theme will not be shown in the theme selector unless
567 * theme designer mode is turned on.
569 public $hidefromselector = false;
572 * @var array list of YUI CSS modules to be included on each page. This may be used
573 * to remove cssreset and use cssnormalise module instead.
575 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
578 * An associative array of block manipulations that should be made if the user is using an rtl language.
579 * The key is the original block region, and the value is the block region to change to.
580 * This is used when displaying blocks for regions only.
581 * @var array
583 public $blockrtlmanipulations = array();
586 * @var renderer_factory Instance of the renderer_factory implementation
587 * we are using. Implementation detail.
589 protected $rf = null;
592 * @var array List of parent config objects.
594 protected $parent_configs = array();
597 * Used to determine whether we can serve SVG images or not.
598 * @var bool
600 private $usesvg = null;
603 * Whether in RTL mode or not.
604 * @var bool
606 protected $rtlmode = false;
609 * The LESS file to compile. When set, the theme will attempt to compile the file itself.
610 * @var bool
612 public $lessfile = false;
615 * The SCSS file to compile (without .scss), located in the scss/ folder of the theme.
616 * Or a Closure, which receives the theme_config as argument and must
617 * return the SCSS content. This setting takes precedence over self::$lessfile.
618 * @var string|Closure
620 public $scss = false;
623 * Local cache of the SCSS property.
624 * @var false|array
626 protected $scsscache = null;
629 * The name of the function to call to get the LESS code to inject.
630 * @var string
632 public $extralesscallback = null;
635 * The name of the function to call to get the SCSS code to inject.
636 * @var string
638 public $extrascsscallback = null;
641 * The name of the function to call to get extra LESS variables.
642 * @var string
644 public $lessvariablescallback = null;
647 * The name of the function to call to get SCSS to prepend.
648 * @var string
650 public $prescsscallback = null;
653 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
654 * Defaults to {@link core_renderer::blocks_for_region()}
655 * @var string
657 public $blockrendermethod = null;
660 * Remember the results of icon remapping for the current page.
661 * @var array
663 public $remapiconcache = [];
666 * The name of the function to call to get precompiled CSS.
667 * @var string
669 public $precompiledcsscallback = null;
672 * Load the config.php file for a particular theme, and return an instance
673 * of this class. (That is, this is a factory method.)
675 * @param string $themename the name of the theme.
676 * @return theme_config an instance of this class.
678 public static function load($themename) {
679 global $CFG;
681 // load theme settings from db
682 try {
683 $settings = get_config('theme_'.$themename);
684 } catch (dml_exception $e) {
685 // most probably moodle tables not created yet
686 $settings = new stdClass();
689 if ($config = theme_config::find_theme_config($themename, $settings)) {
690 return new theme_config($config);
692 } else if ($themename == theme_config::DEFAULT_THEME) {
693 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
695 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
696 debugging('This page should be using theme ' . $themename .
697 ' which cannot be initialised. Falling back to the site theme ' . $CFG->theme, DEBUG_NORMAL);
698 return new theme_config($config);
700 } else {
701 // bad luck, the requested theme has some problems - admin see details in theme config
702 debugging('This page should be using theme ' . $themename .
703 ' which cannot be initialised. Nor can the site theme ' . $CFG->theme .
704 '. Falling back to ' . theme_config::DEFAULT_THEME, DEBUG_NORMAL);
705 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
710 * Theme diagnostic code. It is very problematic to send debug output
711 * to the actual CSS file, instead this functions is supposed to
712 * diagnose given theme and highlights all potential problems.
713 * This information should be available from the theme selection page
714 * or some other debug page for theme designers.
716 * @param string $themename
717 * @return array description of problems
719 public static function diagnose($themename) {
720 //TODO: MDL-21108
721 return array();
725 * Private constructor, can be called only from the factory method.
726 * @param stdClass $config
728 private function __construct($config) {
729 global $CFG; //needed for included lib.php files
731 $this->settings = $config->settings;
732 $this->name = $config->name;
733 $this->dir = $config->dir;
735 if ($this->name != 'bootstrapbase') {
736 $baseconfig = theme_config::find_theme_config('bootstrapbase', $this->settings);
737 } else {
738 $baseconfig = $config;
741 $configurable = array(
742 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'usefallback',
743 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
744 'layouts', 'enable_dock', 'enablecourseajax', 'requiredblocks',
745 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'uarrow', 'darrow',
746 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations',
747 'lessfile', 'extralesscallback', 'lessvariablescallback', 'blockrendermethod',
748 'scss', 'extrascsscallback', 'prescsscallback', 'csstreepostprocessor', 'addblockposition',
749 'iconsystem', 'precompiledcsscallback');
751 foreach ($config as $key=>$value) {
752 if (in_array($key, $configurable)) {
753 $this->$key = $value;
757 // verify all parents and load configs and renderers
758 foreach ($this->parents as $parent) {
759 if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
760 // this is not good - better exclude faulty parents
761 continue;
763 $libfile = $parent_config->dir.'/lib.php';
764 if (is_readable($libfile)) {
765 // theme may store various function here
766 include_once($libfile);
768 $renderersfile = $parent_config->dir.'/renderers.php';
769 if (is_readable($renderersfile)) {
770 // may contain core and plugin renderers and renderer factory
771 include_once($renderersfile);
773 $this->parent_configs[$parent] = $parent_config;
775 $libfile = $this->dir.'/lib.php';
776 if (is_readable($libfile)) {
777 // theme may store various function here
778 include_once($libfile);
780 $rendererfile = $this->dir.'/renderers.php';
781 if (is_readable($rendererfile)) {
782 // may contain core and plugin renderers and renderer factory
783 include_once($rendererfile);
784 } else {
785 // check if renderers.php file is missnamed renderer.php
786 if (is_readable($this->dir.'/renderer.php')) {
787 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
788 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
792 // cascade all layouts properly
793 foreach ($baseconfig->layouts as $layout=>$value) {
794 if (!isset($this->layouts[$layout])) {
795 foreach ($this->parent_configs as $parent_config) {
796 if (isset($parent_config->layouts[$layout])) {
797 $this->layouts[$layout] = $parent_config->layouts[$layout];
798 continue 2;
801 $this->layouts[$layout] = $value;
805 //fix arrows if needed
806 $this->check_theme_arrows();
810 * Let the theme initialise the page object (usually $PAGE).
812 * This may be used for example to request jQuery in add-ons.
814 * @param moodle_page $page
816 public function init_page(moodle_page $page) {
817 $themeinitfunction = 'theme_'.$this->name.'_page_init';
818 if (function_exists($themeinitfunction)) {
819 $themeinitfunction($page);
824 * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow, $THEME->darrow have been set (theme/-/config.php).
825 * If not it applies sensible defaults.
827 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
828 * search forum block, etc. Important: these are 'silent' in a screen-reader
829 * (unlike &gt; &raquo;), and must be accompanied by text.
831 private function check_theme_arrows() {
832 if (!isset($this->rarrow) and !isset($this->larrow)) {
833 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
834 // Also OK in Win 9x/2K/IE 5.x
835 $this->rarrow = '&#x25BA;';
836 $this->larrow = '&#x25C4;';
837 $this->uarrow = '&#x25B2;';
838 $this->darrow = '&#x25BC;';
839 if (empty($_SERVER['HTTP_USER_AGENT'])) {
840 $uagent = '';
841 } else {
842 $uagent = $_SERVER['HTTP_USER_AGENT'];
844 if (false !== strpos($uagent, 'Opera')
845 || false !== strpos($uagent, 'Mac')) {
846 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
847 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
848 $this->rarrow = '&#x25B6;&#xFE0E;';
849 $this->larrow = '&#x25C0;&#xFE0E;';
851 elseif ((false !== strpos($uagent, 'Konqueror'))
852 || (false !== strpos($uagent, 'Android'))) {
853 // The fonts on Android don't include the characters required for this to work as expected.
854 // So we use the same ones Konqueror uses.
855 $this->rarrow = '&rarr;';
856 $this->larrow = '&larr;';
857 $this->uarrow = '&uarr;';
858 $this->darrow = '&darr;';
860 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
861 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
862 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
863 // To be safe, non-Unicode browsers!
864 $this->rarrow = '&gt;';
865 $this->larrow = '&lt;';
866 $this->uarrow = '^';
867 $this->darrow = 'v';
870 // RTL support - in RTL languages, swap r and l arrows
871 if (right_to_left()) {
872 $t = $this->rarrow;
873 $this->rarrow = $this->larrow;
874 $this->larrow = $t;
880 * Returns output renderer prefixes, these are used when looking
881 * for the overridden renderers in themes.
883 * @return array
885 public function renderer_prefixes() {
886 global $CFG; // just in case the included files need it
888 $prefixes = array('theme_'.$this->name);
890 foreach ($this->parent_configs as $parent) {
891 $prefixes[] = 'theme_'.$parent->name;
894 return $prefixes;
898 * Returns the stylesheet URL of this editor content
900 * @param bool $encoded false means use & and true use &amp; in URLs
901 * @return moodle_url
903 public function editor_css_url($encoded=true) {
904 global $CFG;
905 $rev = theme_get_revision();
906 if ($rev > -1) {
907 $themesubrevision = theme_get_sub_revision_for_theme($this->name);
909 // Provide the sub revision to allow us to invalidate cached theme CSS
910 // on a per theme basis, rather than globally.
911 if ($themesubrevision && $themesubrevision > 0) {
912 $rev .= "_{$themesubrevision}";
915 $url = new moodle_url("/theme/styles.php");
916 if (!empty($CFG->slasharguments)) {
917 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
918 } else {
919 $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
921 } else {
922 $params = array('theme'=>$this->name, 'type'=>'editor');
923 $url = new moodle_url('/theme/styles_debug.php', $params);
925 return $url;
929 * Returns the content of the CSS to be used in editor content
931 * @return array
933 public function editor_css_files() {
934 $files = array();
936 // First editor plugins.
937 $plugins = core_component::get_plugin_list('editor');
938 foreach ($plugins as $plugin=>$fulldir) {
939 $sheetfile = "$fulldir/editor_styles.css";
940 if (is_readable($sheetfile)) {
941 $files['plugin_'.$plugin] = $sheetfile;
944 // Then parent themes - base first, the immediate parent last.
945 foreach (array_reverse($this->parent_configs) as $parent_config) {
946 if (empty($parent_config->editor_sheets)) {
947 continue;
949 foreach ($parent_config->editor_sheets as $sheet) {
950 $sheetfile = "$parent_config->dir/style/$sheet.css";
951 if (is_readable($sheetfile)) {
952 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
956 // Finally this theme.
957 if (!empty($this->editor_sheets)) {
958 foreach ($this->editor_sheets as $sheet) {
959 $sheetfile = "$this->dir/style/$sheet.css";
960 if (is_readable($sheetfile)) {
961 $files['theme_'.$sheet] = $sheetfile;
966 return $files;
970 * Get the stylesheet URL of this theme.
972 * @param moodle_page $page Not used... deprecated?
973 * @return moodle_url[]
975 public function css_urls(moodle_page $page) {
976 global $CFG;
978 $rev = theme_get_revision();
980 $urls = array();
982 $svg = $this->use_svg_icons();
983 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
985 if ($rev > -1) {
986 $filename = right_to_left() ? 'all-rtl' : 'all';
987 $url = new moodle_url("/theme/styles.php");
988 $themesubrevision = theme_get_sub_revision_for_theme($this->name);
990 // Provide the sub revision to allow us to invalidate cached theme CSS
991 // on a per theme basis, rather than globally.
992 if ($themesubrevision && $themesubrevision > 0) {
993 $rev .= "_{$themesubrevision}";
996 if (!empty($CFG->slasharguments)) {
997 $slashargs = '';
998 if (!$svg) {
999 // We add a simple /_s to the start of the path.
1000 // The underscore is used to ensure that it isn't a valid theme name.
1001 $slashargs .= '/_s'.$slashargs;
1003 $slashargs .= '/'.$this->name.'/'.$rev.'/'.$filename;
1004 if ($separate) {
1005 $slashargs .= '/chunk0';
1007 $url->set_slashargument($slashargs, 'noparam', true);
1008 } else {
1009 $params = array('theme' => $this->name, 'rev' => $rev, 'type' => $filename);
1010 if (!$svg) {
1011 // We add an SVG param so that we know not to serve SVG images.
1012 // We do this because all modern browsers support SVG and this param will one day be removed.
1013 $params['svg'] = '0';
1015 if ($separate) {
1016 $params['chunk'] = '0';
1018 $url->params($params);
1020 $urls[] = $url;
1022 } else {
1023 $baseurl = new moodle_url('/theme/styles_debug.php');
1025 $css = $this->get_css_files(true);
1026 if (!$svg) {
1027 // We add an SVG param so that we know not to serve SVG images.
1028 // We do this because all modern browsers support SVG and this param will one day be removed.
1029 $baseurl->param('svg', '0');
1031 if (right_to_left()) {
1032 $baseurl->param('rtl', 1);
1034 if ($separate) {
1035 // We might need to chunk long files.
1036 $baseurl->param('chunk', '0');
1038 if (core_useragent::is_ie()) {
1039 // Lalala, IE does not allow more than 31 linked CSS files from main document.
1040 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
1041 foreach ($css['parents'] as $parent=>$sheets) {
1042 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
1043 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
1045 if ($this->get_scss_property()) {
1046 // No need to define the type as IE here.
1047 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
1048 } else if (!empty($this->lessfile)) {
1049 // No need to define the type as IE here.
1050 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
1052 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
1054 } else {
1055 foreach ($css['plugins'] as $plugin=>$unused) {
1056 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
1058 foreach ($css['parents'] as $parent=>$sheets) {
1059 foreach ($sheets as $sheet=>$unused2) {
1060 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
1063 foreach ($css['theme'] as $sheet => $filename) {
1064 if ($sheet === self::SCSS_KEY) {
1065 // This is the theme SCSS file.
1066 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
1067 } else if ($sheet === $this->lessfile) {
1068 // This is the theme LESS file.
1069 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
1070 } else {
1071 // Sheet first in order to make long urls easier to read.
1072 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
1078 return $urls;
1082 * Get the whole css stylesheet for production mode.
1084 * NOTE: this method is not expected to be used from any addons.
1086 * @return string CSS markup compressed
1088 public function get_css_content() {
1090 $csscontent = '';
1091 foreach ($this->get_css_files(false) as $type => $value) {
1092 foreach ($value as $identifier => $val) {
1093 if (is_array($val)) {
1094 foreach ($val as $v) {
1095 $csscontent .= file_get_contents($v) . "\n";
1097 } else {
1098 if ($type === 'theme' && $identifier === self::SCSS_KEY) {
1099 // We need the content from SCSS because this is the SCSS file from the theme.
1100 if ($compiled = $this->get_css_content_from_scss(false)) {
1101 $csscontent .= $compiled;
1102 } else {
1103 // The compiler failed so default back to any precompiled css that might
1104 // exist.
1105 $csscontent .= $this->get_precompiled_css_content();
1107 } else if ($type === 'theme' && $identifier === $this->lessfile) {
1108 // We need the content from LESS because this is the LESS file from the theme.
1109 $csscontent .= $this->get_css_content_from_less(false);
1110 } else {
1111 $csscontent .= file_get_contents($val) . "\n";
1116 $csscontent = $this->post_process($csscontent);
1117 $csscontent = core_minify::css($csscontent);
1119 return $csscontent;
1122 * Set post processed CSS content cache.
1124 * @param string $csscontent The post processed CSS content.
1125 * @return bool True if the content was successfully cached.
1127 public function set_css_content_cache($csscontent) {
1129 $cache = cache::make('core', 'postprocessedcss');
1130 $key = $this->get_css_cache_key();
1132 return $cache->set($key, $csscontent);
1136 * Return whether the post processed CSS content has been cached.
1138 * @return bool Whether the post-processed CSS is available in the cache.
1140 public function has_css_cached_content() {
1142 $key = $this->get_css_cache_key();
1143 $cache = cache::make('core', 'postprocessedcss');
1145 return $cache->has($key);
1149 * Return cached post processed CSS content.
1151 * @return bool|string The cached css content or false if not found.
1153 public function get_css_cached_content() {
1155 $key = $this->get_css_cache_key();
1156 $cache = cache::make('core', 'postprocessedcss');
1158 return $cache->get($key);
1162 * Generate the css content cache key.
1164 * @return string The post processed css cache key.
1166 public function get_css_cache_key() {
1167 $nosvg = (!$this->use_svg_icons()) ? 'nosvg_' : '';
1168 $rtlmode = ($this->rtlmode == true) ? 'rtl' : 'ltr';
1170 return $nosvg . $this->name . '_' . $rtlmode;
1174 * Get the theme designer css markup,
1175 * the parameters are coming from css_urls().
1177 * NOTE: this method is not expected to be used from any addons.
1179 * @param string $type
1180 * @param string $subtype
1181 * @param string $sheet
1182 * @return string CSS markup
1184 public function get_css_content_debug($type, $subtype, $sheet) {
1186 if ($type === 'scss') {
1187 // The SCSS file of the theme is requested.
1188 $csscontent = $this->get_css_content_from_scss(true);
1189 if ($csscontent !== false) {
1190 return $this->post_process($csscontent);
1192 return '';
1193 } else if ($type === 'less') {
1194 // The LESS file of the theme is requested.
1195 $csscontent = $this->get_css_content_from_less(true);
1196 if ($csscontent !== false) {
1197 return $this->post_process($csscontent);
1199 return '';
1202 $cssfiles = array();
1203 $css = $this->get_css_files(true);
1205 if ($type === 'ie') {
1206 // IE is a sloppy browser with weird limits, sorry.
1207 if ($subtype === 'plugins') {
1208 $cssfiles = $css['plugins'];
1210 } else if ($subtype === 'parents') {
1211 if (empty($sheet)) {
1212 // Do not bother with the empty parent here.
1213 } else {
1214 // Build up the CSS for that parent so we can serve it as one file.
1215 foreach ($css[$subtype][$sheet] as $parent => $css) {
1216 $cssfiles[] = $css;
1219 } else if ($subtype === 'theme') {
1220 $cssfiles = $css['theme'];
1221 foreach ($cssfiles as $key => $value) {
1222 if (in_array($key, [$this->lessfile, self::SCSS_KEY])) {
1223 // Remove the LESS/SCSS file from the theme CSS files.
1224 // The LESS/SCSS files use the type 'less' or 'scss', not 'ie'.
1225 unset($cssfiles[$key]);
1230 } else if ($type === 'plugin') {
1231 if (isset($css['plugins'][$subtype])) {
1232 $cssfiles[] = $css['plugins'][$subtype];
1235 } else if ($type === 'parent') {
1236 if (isset($css['parents'][$subtype][$sheet])) {
1237 $cssfiles[] = $css['parents'][$subtype][$sheet];
1240 } else if ($type === 'theme') {
1241 if (isset($css['theme'][$sheet])) {
1242 $cssfiles[] = $css['theme'][$sheet];
1246 $csscontent = '';
1247 foreach ($cssfiles as $file) {
1248 $contents = file_get_contents($file);
1249 $contents = $this->post_process($contents);
1250 $comment = "/** Path: $type $subtype $sheet.' **/\n";
1251 $stats = '';
1252 $csscontent .= $comment.$stats.$contents."\n\n";
1255 return $csscontent;
1259 * Get the whole css stylesheet for editor iframe.
1261 * NOTE: this method is not expected to be used from any addons.
1263 * @return string CSS markup
1265 public function get_css_content_editor() {
1266 // Do not bother to optimise anything here, just very basic stuff.
1267 $cssfiles = $this->editor_css_files();
1268 $css = '';
1269 foreach ($cssfiles as $file) {
1270 $css .= file_get_contents($file)."\n";
1272 return $this->post_process($css);
1276 * Returns an array of organised CSS files required for this output.
1278 * @param bool $themedesigner
1279 * @return array nested array of file paths
1281 protected function get_css_files($themedesigner) {
1282 global $CFG;
1284 $cache = null;
1285 $cachekey = 'cssfiles';
1286 if ($themedesigner) {
1287 require_once($CFG->dirroot.'/lib/csslib.php');
1288 // We need some kind of caching here because otherwise the page navigation becomes
1289 // way too slow in theme designer mode. Feel free to create full cache definition later...
1290 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
1291 if ($files = $cache->get($cachekey)) {
1292 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
1293 unset($files['created']);
1294 return $files;
1299 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
1301 // Get all plugin sheets.
1302 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
1303 if ($excludes !== true) {
1304 foreach (core_component::get_plugin_types() as $type=>$unused) {
1305 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
1306 continue;
1308 $plugins = core_component::get_plugin_list($type);
1309 foreach ($plugins as $plugin=>$fulldir) {
1310 if (!empty($excludes[$type]) and is_array($excludes[$type])
1311 and in_array($plugin, $excludes[$type])) {
1312 continue;
1315 // Get the CSS from the plugin.
1316 $sheetfile = "$fulldir/styles.css";
1317 if (is_readable($sheetfile)) {
1318 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
1321 // Create a list of candidate sheets from parents (direct parent last) and current theme.
1322 $candidates = array();
1323 foreach (array_reverse($this->parent_configs) as $parent_config) {
1324 $candidates[] = $parent_config->name;
1326 $candidates[] = $this->name;
1328 // Add the sheets found.
1329 foreach ($candidates as $candidate) {
1330 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1331 if (is_readable($sheetthemefile)) {
1332 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
1339 // Find out wanted parent sheets.
1340 $excludes = $this->resolve_excludes('parents_exclude_sheets');
1341 if ($excludes !== true) {
1342 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1343 $parent = $parent_config->name;
1344 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
1345 continue;
1347 foreach ($parent_config->sheets as $sheet) {
1348 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1349 && in_array($sheet, $excludes[$parent])) {
1350 continue;
1353 // We never refer to the parent LESS files.
1354 $sheetfile = "$parent_config->dir/style/$sheet.css";
1355 if (is_readable($sheetfile)) {
1356 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1363 // Current theme sheets and less file.
1364 // We first add the SCSS, or LESS file because we want the CSS ones to
1365 // be included after the SCSS/LESS code. However, if both the LESS file
1366 // and a CSS file share the same name, the CSS file is ignored.
1367 if ($this->get_scss_property()) {
1368 $cssfiles['theme'][self::SCSS_KEY] = true;
1369 } else if (!empty($this->lessfile)) {
1370 $sheetfile = "{$this->dir}/less/{$this->lessfile}.less";
1371 if (is_readable($sheetfile)) {
1372 $cssfiles['theme'][$this->lessfile] = $sheetfile;
1375 if (is_array($this->sheets)) {
1376 foreach ($this->sheets as $sheet) {
1377 $sheetfile = "$this->dir/style/$sheet.css";
1378 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1379 $cssfiles['theme'][$sheet] = $sheetfile;
1384 if ($cache) {
1385 $files = $cssfiles;
1386 $files['created'] = time();
1387 $cache->set($cachekey, $files);
1389 return $cssfiles;
1393 * Return the CSS content generated from LESS the file.
1395 * @param bool $themedesigner True if theme designer is enabled.
1396 * @return bool|string Return false when the compilation failed. Else the compiled string.
1398 protected function get_css_content_from_less($themedesigner) {
1399 global $CFG;
1401 $lessfile = $this->lessfile;
1402 if (!$lessfile || !is_readable($this->dir . '/less/' . $lessfile . '.less')) {
1403 throw new coding_exception('The theme did not define a LESS file, or it is not readable.');
1406 // We might need more memory/time to do this, so let's play safe.
1407 raise_memory_limit(MEMORY_EXTRA);
1408 core_php_time_limit::raise(300);
1410 // Files list.
1411 $files = $this->get_css_files($themedesigner);
1413 // Get the LESS file path.
1414 $themelessfile = $files['theme'][$lessfile];
1416 // Setup compiler options.
1417 $options = array(
1418 // We need to set the import directory to where $lessfile is.
1419 'import_dirs' => array(dirname($themelessfile) => '/'),
1420 // Always disable default caching.
1421 'cache_method' => false,
1422 // Disable the relative URLs, we have post_process() to handle that.
1423 'relativeUrls' => false,
1426 if ($themedesigner) {
1427 // Add the sourceMap inline to ensure that it is atomically generated.
1428 $options['sourceMap'] = true;
1429 $options['sourceMapBasepath'] = $CFG->dirroot;
1430 $options['sourceMapRootpath'] = $CFG->wwwroot;
1433 // Instantiate the compiler.
1434 $compiler = new core_lessc($options);
1436 try {
1437 $compiler->parse_file_content($themelessfile);
1439 // Get the callbacks.
1440 $compiler->parse($this->get_extra_less_code());
1441 $compiler->ModifyVars($this->get_less_variables());
1443 // Compile the CSS.
1444 $compiled = $compiler->getCss();
1446 } catch (Less_Exception_Parser $e) {
1447 $compiled = false;
1448 debugging('Error while compiling LESS ' . $lessfile . ' file: ' . $e->getMessage(), DEBUG_DEVELOPER);
1451 // Try to save memory.
1452 $compiler = null;
1453 unset($compiler);
1455 return $compiled;
1459 * Return the CSS content generated from the SCSS file.
1461 * @param bool $themedesigner True if theme designer is enabled.
1462 * @return bool|string Return false when the compilation failed. Else the compiled string.
1464 protected function get_css_content_from_scss($themedesigner) {
1465 global $CFG;
1467 list($paths, $scss) = $this->get_scss_property();
1468 if (!$scss) {
1469 throw new coding_exception('The theme did not define a SCSS file, or it is not readable.');
1472 // We might need more memory/time to do this, so let's play safe.
1473 raise_memory_limit(MEMORY_EXTRA);
1474 core_php_time_limit::raise(300);
1476 // Set-up the compiler.
1477 $compiler = new core_scss();
1478 $compiler->prepend_raw_scss($this->get_pre_scss_code());
1479 if (is_string($scss)) {
1480 $compiler->set_file($scss);
1481 } else {
1482 $compiler->append_raw_scss($scss($this));
1483 $compiler->setImportPaths($paths);
1485 $compiler->append_raw_scss($this->get_extra_scss_code());
1487 try {
1488 // Compile!
1489 $compiled = $compiler->to_css();
1491 } catch (\Exception $e) {
1492 $compiled = false;
1493 debugging('Error while compiling SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
1496 // Try to save memory.
1497 $compiler = null;
1498 unset($compiler);
1500 return $compiled;
1504 * Return the precompiled CSS if the precompiledcsscallback exists.
1506 * @return string Return compiled css.
1508 public function get_precompiled_css_content() {
1509 $configs = [$this] + $this->parent_configs;
1510 $css = '';
1512 foreach ($configs as $config) {
1513 if (isset($config->precompiledcsscallback)) {
1514 $function = $config->precompiledcsscallback;
1515 if (function_exists($function)) {
1516 $css .= $function($this);
1520 return $css;
1524 * Get the icon system to use.
1526 * @return string
1528 public function get_icon_system() {
1530 // Getting all the candidate functions.
1531 $system = false;
1532 if (isset($this->iconsystem) && \core\output\icon_system::is_valid_system($this->iconsystem)) {
1533 return $this->iconsystem;
1535 foreach ($this->parent_configs as $parent_config) {
1536 if (isset($parent_config->iconsystem) && \core\output\icon_system::is_valid_system($parent_config->iconsystem)) {
1537 return $parent_config->iconsystem;
1540 return \core\output\icon_system::STANDARD;
1544 * Return extra LESS variables to use when compiling.
1546 * @return array Where keys are the variable names (omitting the @), and the values are the value.
1548 protected function get_less_variables() {
1549 $variables = array();
1551 // Getting all the candidate functions.
1552 $candidates = array();
1553 foreach ($this->parent_configs as $parent_config) {
1554 if (!isset($parent_config->lessvariablescallback)) {
1555 continue;
1557 $candidates[] = $parent_config->lessvariablescallback;
1559 $candidates[] = $this->lessvariablescallback;
1561 // Calling the functions.
1562 foreach ($candidates as $function) {
1563 if (function_exists($function)) {
1564 $vars = $function($this);
1565 if (!is_array($vars)) {
1566 debugging('Callback ' . $function . ' did not return an array() as expected', DEBUG_DEVELOPER);
1567 continue;
1569 $variables = array_merge($variables, $vars);
1573 return $variables;
1577 * Return extra LESS code to add when compiling.
1579 * This is intended to be used by themes to inject some LESS code
1580 * before it gets compiled. If you want to inject variables you
1581 * should use {@link self::get_less_variables()}.
1583 * @return string The LESS code to inject.
1585 protected function get_extra_less_code() {
1586 $content = '';
1588 // Getting all the candidate functions.
1589 $candidates = array();
1590 foreach ($this->parent_configs as $parent_config) {
1591 if (!isset($parent_config->extralesscallback)) {
1592 continue;
1594 $candidates[] = $parent_config->extralesscallback;
1596 $candidates[] = $this->extralesscallback;
1598 // Calling the functions.
1599 foreach ($candidates as $function) {
1600 if (function_exists($function)) {
1601 $content .= "\n/** Extra LESS from $function **/\n" . $function($this) . "\n";
1605 return $content;
1609 * Return extra SCSS code to add when compiling.
1611 * This is intended to be used by themes to inject some SCSS code
1612 * before it gets compiled. If you want to inject variables you
1613 * should use {@link self::get_scss_variables()}.
1615 * @return string The SCSS code to inject.
1617 protected function get_extra_scss_code() {
1618 $content = '';
1620 // Getting all the candidate functions.
1621 $candidates = array();
1622 foreach ($this->parent_configs as $parent_config) {
1623 if (!isset($parent_config->extrascsscallback)) {
1624 continue;
1626 $candidates[] = $parent_config->extrascsscallback;
1628 $candidates[] = $this->extrascsscallback;
1630 // Calling the functions.
1631 foreach ($candidates as $function) {
1632 if (function_exists($function)) {
1633 $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n";
1637 return $content;
1641 * SCSS code to prepend when compiling.
1643 * This is intended to be used by themes to inject SCSS code before it gets compiled.
1645 * @return string The SCSS code to inject.
1647 protected function get_pre_scss_code() {
1648 $content = '';
1650 // Getting all the candidate functions.
1651 $candidates = array();
1652 foreach ($this->parent_configs as $parent_config) {
1653 if (!isset($parent_config->prescsscallback)) {
1654 continue;
1656 $candidates[] = $parent_config->prescsscallback;
1658 $candidates[] = $this->prescsscallback;
1660 // Calling the functions.
1661 foreach ($candidates as $function) {
1662 if (function_exists($function)) {
1663 $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n";
1667 return $content;
1671 * Get the SCSS property.
1673 * This resolves whether a SCSS file (or content) has to be used when generating
1674 * the stylesheet for the theme. It will look at parents themes and check the
1675 * SCSS properties there.
1677 * @return False when SCSS is not used.
1678 * An array with the import paths, and the path to the SCSS file or Closure as second.
1680 public function get_scss_property() {
1681 if ($this->scsscache === null) {
1682 $configs = [$this] + $this->parent_configs;
1683 $scss = null;
1685 foreach ($configs as $config) {
1686 $path = "{$config->dir}/scss";
1688 // We collect the SCSS property until we've found one.
1689 if (empty($scss) && !empty($config->scss)) {
1690 $candidate = is_string($config->scss) ? "{$path}/{$config->scss}.scss" : $config->scss;
1691 if ($candidate instanceof Closure) {
1692 $scss = $candidate;
1693 } else if (is_string($candidate) && is_readable($candidate)) {
1694 $scss = $candidate;
1698 // We collect the import paths once we've found a SCSS property.
1699 if ($scss && is_dir($path)) {
1700 $paths[] = $path;
1705 $this->scsscache = $scss !== null ? [$paths, $scss] : false;
1708 return $this->scsscache;
1712 * Generate a URL to the file that serves theme JavaScript files.
1714 * If we determine that the theme has no relevant files, then we return
1715 * early with a null value.
1717 * @param bool $inhead true means head url, false means footer
1718 * @return moodle_url|null
1720 public function javascript_url($inhead) {
1721 global $CFG;
1723 $rev = theme_get_revision();
1724 $params = array('theme'=>$this->name,'rev'=>$rev);
1725 $params['type'] = $inhead ? 'head' : 'footer';
1727 // Return early if there are no files to serve
1728 if (count($this->javascript_files($params['type'])) === 0) {
1729 return null;
1732 if (!empty($CFG->slasharguments) and $rev > 0) {
1733 $url = new moodle_url("/theme/javascript.php");
1734 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
1735 return $url;
1736 } else {
1737 return new moodle_url('/theme/javascript.php', $params);
1742 * Get the URL's for the JavaScript files used by this theme.
1743 * They won't be served directly, instead they'll be mediated through
1744 * theme/javascript.php.
1746 * @param string $type Either javascripts_footer, or javascripts
1747 * @return array
1749 public function javascript_files($type) {
1750 if ($type === 'footer') {
1751 $type = 'javascripts_footer';
1752 } else {
1753 $type = 'javascripts';
1756 $js = array();
1757 // find out wanted parent javascripts
1758 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1759 if ($excludes !== true) {
1760 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1761 $parent = $parent_config->name;
1762 if (empty($parent_config->$type)) {
1763 continue;
1765 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1766 continue;
1768 foreach ($parent_config->$type as $javascript) {
1769 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1770 and in_array($javascript, $excludes[$parent])) {
1771 continue;
1773 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1774 if (is_readable($javascriptfile)) {
1775 $js[] = $javascriptfile;
1781 // current theme javascripts
1782 if (is_array($this->$type)) {
1783 foreach ($this->$type as $javascript) {
1784 $javascriptfile = "$this->dir/javascript/$javascript.js";
1785 if (is_readable($javascriptfile)) {
1786 $js[] = $javascriptfile;
1790 return $js;
1794 * Resolves an exclude setting to the themes setting is applicable or the
1795 * setting of its closest parent.
1797 * @param string $variable The name of the setting the exclude setting to resolve
1798 * @param string $default
1799 * @return mixed
1801 protected function resolve_excludes($variable, $default = null) {
1802 $setting = $default;
1803 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1804 $setting = $this->{$variable};
1805 } else {
1806 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1807 if (!isset($parent_config->{$variable})) {
1808 continue;
1810 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1811 $setting = $parent_config->{$variable};
1812 break;
1816 return $setting;
1820 * Returns the content of the one huge javascript file merged from all theme javascript files.
1822 * @param bool $type
1823 * @return string
1825 public function javascript_content($type) {
1826 $jsfiles = $this->javascript_files($type);
1827 $js = '';
1828 foreach ($jsfiles as $jsfile) {
1829 $js .= file_get_contents($jsfile)."\n";
1831 return $js;
1835 * Post processes CSS.
1837 * This method post processes all of the CSS before it is served for this theme.
1838 * This is done so that things such as image URL's can be swapped in and to
1839 * run any specific CSS post process method the theme has requested.
1840 * This allows themes to use CSS settings.
1842 * @param string $css The CSS to process.
1843 * @return string The processed CSS.
1845 public function post_process($css) {
1846 // now resolve all image locations
1847 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1848 $replaced = array();
1849 foreach ($matches as $match) {
1850 if (isset($replaced[$match[0]])) {
1851 continue;
1853 $replaced[$match[0]] = true;
1854 $imagename = $match[2];
1855 $component = rtrim($match[1], '|');
1856 $imageurl = $this->image_url($imagename, $component)->out(false);
1857 // we do not need full url because the image.php is always in the same dir
1858 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1859 $css = str_replace($match[0], $imageurl, $css);
1863 // Now resolve all font locations.
1864 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1865 $replaced = array();
1866 foreach ($matches as $match) {
1867 if (isset($replaced[$match[0]])) {
1868 continue;
1870 $replaced[$match[0]] = true;
1871 $fontname = $match[2];
1872 $component = rtrim($match[1], '|');
1873 $fonturl = $this->font_url($fontname, $component)->out(false);
1874 // We do not need full url because the font.php is always in the same dir.
1875 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1876 $css = str_replace($match[0], $fonturl, $css);
1880 // Now resolve all theme settings or do any other postprocessing.
1881 // This needs to be done before calling core parser, since the parser strips [[settings]] tags.
1882 $csspostprocess = $this->csspostprocess;
1883 if (function_exists($csspostprocess)) {
1884 $css = $csspostprocess($css, $this);
1887 // Post processing using an object representation of CSS.
1888 $treeprocessor = $this->get_css_tree_post_processor();
1889 $needsparsing = !empty($treeprocessor) || !empty($this->rtlmode);
1890 if ($needsparsing) {
1892 // We might need more memory/time to do this, so let's play safe.
1893 raise_memory_limit(MEMORY_EXTRA);
1894 core_php_time_limit::raise(300);
1896 $parser = new core_cssparser($css);
1897 $csstree = $parser->parse();
1898 unset($parser);
1900 if ($this->rtlmode) {
1901 $this->rtlize($csstree);
1904 if ($treeprocessor) {
1905 $treeprocessor($csstree, $this);
1908 $css = $csstree->render();
1909 unset($csstree);
1912 return $css;
1916 * Flip a stylesheet to RTL.
1918 * @param Object $csstree The parsed CSS tree structure to flip.
1919 * @return void
1921 protected function rtlize($csstree) {
1922 $rtlcss = new core_rtlcss($csstree);
1923 $rtlcss->flip();
1927 * Return the direct URL for an image from the pix folder.
1929 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1931 * @deprecated since Moodle 3.3
1932 * @param string $imagename the name of the icon.
1933 * @param string $component specification of one plugin like in get_string()
1934 * @return moodle_url
1936 public function pix_url($imagename, $component) {
1937 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
1938 return $this->image_url($imagename, $component);
1942 * Return the direct URL for an image from the pix folder.
1944 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1946 * @param string $imagename the name of the icon.
1947 * @param string $component specification of one plugin like in get_string()
1948 * @return moodle_url
1950 public function image_url($imagename, $component) {
1951 global $CFG;
1953 $params = array('theme'=>$this->name);
1954 $svg = $this->use_svg_icons();
1956 if (empty($component) or $component === 'moodle' or $component === 'core') {
1957 $params['component'] = 'core';
1958 } else {
1959 $params['component'] = $component;
1962 $rev = theme_get_revision();
1963 if ($rev != -1) {
1964 $params['rev'] = $rev;
1967 $params['image'] = $imagename;
1969 $url = new moodle_url("/theme/image.php");
1970 if (!empty($CFG->slasharguments) and $rev > 0) {
1971 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1972 if (!$svg) {
1973 // We add a simple /_s to the start of the path.
1974 // The underscore is used to ensure that it isn't a valid theme name.
1975 $path = '/_s'.$path;
1977 $url->set_slashargument($path, 'noparam', true);
1978 } else {
1979 if (!$svg) {
1980 // We add an SVG param so that we know not to serve SVG images.
1981 // We do this because all modern browsers support SVG and this param will one day be removed.
1982 $params['svg'] = '0';
1984 $url->params($params);
1987 return $url;
1991 * Return the URL for a font
1993 * @param string $font the name of the font (including extension).
1994 * @param string $component specification of one plugin like in get_string()
1995 * @return moodle_url
1997 public function font_url($font, $component) {
1998 global $CFG;
2000 $params = array('theme'=>$this->name);
2002 if (empty($component) or $component === 'moodle' or $component === 'core') {
2003 $params['component'] = 'core';
2004 } else {
2005 $params['component'] = $component;
2008 $rev = theme_get_revision();
2009 if ($rev != -1) {
2010 $params['rev'] = $rev;
2013 $params['font'] = $font;
2015 $url = new moodle_url("/theme/font.php");
2016 if (!empty($CFG->slasharguments) and $rev > 0) {
2017 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
2018 $url->set_slashargument($path, 'noparam', true);
2019 } else {
2020 $url->params($params);
2023 return $url;
2027 * Returns URL to the stored file via pluginfile.php.
2029 * Note the theme must also implement pluginfile.php handler,
2030 * theme revision is used instead of the itemid.
2032 * @param string $setting
2033 * @param string $filearea
2034 * @return string protocol relative URL or null if not present
2036 public function setting_file_url($setting, $filearea) {
2037 global $CFG;
2039 if (empty($this->settings->$setting)) {
2040 return null;
2043 $component = 'theme_'.$this->name;
2044 $itemid = theme_get_revision();
2045 $filepath = $this->settings->$setting;
2046 $syscontext = context_system::instance();
2048 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
2050 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
2051 // Note: unfortunately moodle_url does not support //urls yet.
2053 $url = preg_replace('|^https?://|i', '//', $url->out(false));
2055 return $url;
2059 * Serve the theme setting file.
2061 * @param string $filearea
2062 * @param array $args
2063 * @param bool $forcedownload
2064 * @param array $options
2065 * @return bool may terminate if file not found or donotdie not specified
2067 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
2068 global $CFG;
2069 require_once("$CFG->libdir/filelib.php");
2071 $syscontext = context_system::instance();
2072 $component = 'theme_'.$this->name;
2074 $revision = array_shift($args);
2075 if ($revision < 0) {
2076 $lifetime = 0;
2077 } else {
2078 $lifetime = 60*60*24*60;
2079 // By default, theme files must be cache-able by both browsers and proxies.
2080 if (!array_key_exists('cacheability', $options)) {
2081 $options['cacheability'] = 'public';
2085 $fs = get_file_storage();
2086 $relativepath = implode('/', $args);
2088 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
2089 $fullpath = rtrim($fullpath, '/');
2090 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
2091 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
2092 return true;
2093 } else {
2094 send_file_not_found();
2099 * Resolves the real image location.
2101 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
2102 * and we need a way in which to turn it off.
2103 * By default SVG won't be used unless asked for. This is done for two reasons:
2104 * 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
2105 * browser supports SVG.
2106 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
2107 * by the user due to security concerns.
2109 * @param string $image name of image, may contain relative path
2110 * @param string $component
2111 * @param bool $svg|null Should SVG images also be looked for? If null, resorts to $CFG->svgicons if that is set; falls back to
2112 * auto-detection of browser support otherwise
2113 * @return string full file path
2115 public function resolve_image_location($image, $component, $svg = false) {
2116 global $CFG;
2118 if (!is_bool($svg)) {
2119 // If $svg isn't a bool then we need to decide for ourselves.
2120 $svg = $this->use_svg_icons();
2123 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2124 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
2125 return $imagefile;
2127 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2128 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
2129 return $imagefile;
2132 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
2133 return $imagefile;
2135 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
2136 return $imagefile;
2138 return null;
2140 } else if ($component === 'theme') { //exception
2141 if ($image === 'favicon') {
2142 return "$this->dir/pix/favicon.ico";
2144 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
2145 return $imagefile;
2147 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2148 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
2149 return $imagefile;
2152 return null;
2154 } else {
2155 if (strpos($component, '_') === false) {
2156 $component = 'mod_'.$component;
2158 list($type, $plugin) = explode('_', $component, 2);
2160 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2161 return $imagefile;
2163 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
2164 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
2165 return $imagefile;
2168 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
2169 return $imagefile;
2171 $dir = core_component::get_plugin_directory($type, $plugin);
2172 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
2173 return $imagefile;
2175 return null;
2180 * Resolves the real font location.
2182 * @param string $font name of font file
2183 * @param string $component
2184 * @return string full file path
2186 public function resolve_font_location($font, $component) {
2187 global $CFG;
2189 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2190 if (file_exists("$this->dir/fonts_core/$font")) {
2191 return "$this->dir/fonts_core/$font";
2193 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2194 if (file_exists("$parent_config->dir/fonts_core/$font")) {
2195 return "$parent_config->dir/fonts_core/$font";
2198 if (file_exists("$CFG->dataroot/fonts/$font")) {
2199 return "$CFG->dataroot/fonts/$font";
2201 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
2202 return "$CFG->dirroot/lib/fonts/$font";
2204 return null;
2206 } else if ($component === 'theme') { // Exception.
2207 if (file_exists("$this->dir/fonts/$font")) {
2208 return "$this->dir/fonts/$font";
2210 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2211 if (file_exists("$parent_config->dir/fonts/$font")) {
2212 return "$parent_config->dir/fonts/$font";
2215 return null;
2217 } else {
2218 if (strpos($component, '_') === false) {
2219 $component = 'mod_'.$component;
2221 list($type, $plugin) = explode('_', $component, 2);
2223 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
2224 return "$this->dir/fonts_plugins/$type/$plugin/$font";
2226 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2227 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
2228 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
2231 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
2232 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
2234 $dir = core_component::get_plugin_directory($type, $plugin);
2235 if (file_exists("$dir/fonts/$font")) {
2236 return "$dir/fonts/$font";
2238 return null;
2243 * Return true if we should look for SVG images as well.
2245 * @return bool
2247 public function use_svg_icons() {
2248 global $CFG;
2249 if ($this->usesvg === null) {
2251 if (!isset($CFG->svgicons)) {
2252 $this->usesvg = core_useragent::supports_svg();
2253 } else {
2254 // Force them on/off depending upon the setting.
2255 $this->usesvg = (bool)$CFG->svgicons;
2258 return $this->usesvg;
2262 * Forces the usesvg setting to either true or false, avoiding any decision making.
2264 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
2265 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
2267 * @param bool $setting True to force the use of svg when available, null otherwise.
2269 public function force_svg_use($setting) {
2270 $this->usesvg = (bool)$setting;
2274 * Set to be in RTL mode.
2276 * This will likely be used when post processing the CSS before serving it.
2278 * @param bool $inrtl True when in RTL mode.
2280 public function set_rtl_mode($inrtl = true) {
2281 $this->rtlmode = $inrtl;
2285 * Whether the theme is being served in RTL mode.
2287 * @return bool True when in RTL mode.
2289 public function get_rtl_mode() {
2290 return $this->rtlmode;
2294 * Checks if file with any image extension exists.
2296 * The order to these images was adjusted prior to the release of 2.4
2297 * At that point the were the following image counts in Moodle core:
2299 * - png = 667 in pix dirs (1499 total)
2300 * - gif = 385 in pix dirs (606 total)
2301 * - jpg = 62 in pix dirs (74 total)
2302 * - jpeg = 0 in pix dirs (1 total)
2304 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
2306 * @param string $filepath
2307 * @param bool $svg If set to true SVG images will also be looked for.
2308 * @return string image name with extension
2310 private static function image_exists($filepath, $svg = false) {
2311 if ($svg && file_exists("$filepath.svg")) {
2312 return "$filepath.svg";
2313 } else if (file_exists("$filepath.png")) {
2314 return "$filepath.png";
2315 } else if (file_exists("$filepath.gif")) {
2316 return "$filepath.gif";
2317 } else if (file_exists("$filepath.jpg")) {
2318 return "$filepath.jpg";
2319 } else if (file_exists("$filepath.jpeg")) {
2320 return "$filepath.jpeg";
2321 } else {
2322 return false;
2327 * Loads the theme config from config.php file.
2329 * @param string $themename
2330 * @param stdClass $settings from config_plugins table
2331 * @param boolean $parentscheck true to also check the parents. .
2332 * @return stdClass The theme configuration
2334 private static function find_theme_config($themename, $settings, $parentscheck = true) {
2335 // We have to use the variable name $THEME (upper case) because that
2336 // is what is used in theme config.php files.
2338 if (!$dir = theme_config::find_theme_location($themename)) {
2339 return null;
2342 $THEME = new stdClass();
2343 $THEME->name = $themename;
2344 $THEME->dir = $dir;
2345 $THEME->settings = $settings;
2347 global $CFG; // just in case somebody tries to use $CFG in theme config
2348 include("$THEME->dir/config.php");
2350 // verify the theme configuration is OK
2351 if (!is_array($THEME->parents)) {
2352 // parents option is mandatory now
2353 return null;
2354 } else {
2355 // We use $parentscheck to only check the direct parents (avoid infinite loop).
2356 if ($parentscheck) {
2357 // Find all parent theme configs.
2358 foreach ($THEME->parents as $parent) {
2359 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
2360 if (empty($parentconfig)) {
2361 return null;
2367 return $THEME;
2371 * Finds the theme location and verifies the theme has all needed files
2372 * and is not obsoleted.
2374 * @param string $themename
2375 * @return string full dir path or null if not found
2377 private static function find_theme_location($themename) {
2378 global $CFG;
2380 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2381 $dir = "$CFG->dirroot/theme/$themename";
2383 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
2384 $dir = "$CFG->themedir/$themename";
2386 } else {
2387 return null;
2390 if (file_exists("$dir/styles.php")) {
2391 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
2392 return null;
2395 return $dir;
2399 * Get the renderer for a part of Moodle for this theme.
2401 * @param moodle_page $page the page we are rendering
2402 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
2403 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
2404 * @param string $target one of rendering target constants
2405 * @return renderer_base the requested renderer.
2407 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
2408 if (is_null($this->rf)) {
2409 $classname = $this->rendererfactory;
2410 $this->rf = new $classname($this);
2413 return $this->rf->get_renderer($page, $component, $subtype, $target);
2417 * Get the information from {@link $layouts} for this type of page.
2419 * @param string $pagelayout the the page layout name.
2420 * @return array the appropriate part of {@link $layouts}.
2422 protected function layout_info_for_page($pagelayout) {
2423 if (array_key_exists($pagelayout, $this->layouts)) {
2424 return $this->layouts[$pagelayout];
2425 } else {
2426 debugging('Invalid page layout specified: ' . $pagelayout);
2427 return $this->layouts['standard'];
2432 * Given the settings of this theme, and the page pagelayout, return the
2433 * full path of the page layout file to use.
2435 * Used by {@link core_renderer::header()}.
2437 * @param string $pagelayout the the page layout name.
2438 * @return string Full path to the lyout file to use
2440 public function layout_file($pagelayout) {
2441 global $CFG;
2443 $layoutinfo = $this->layout_info_for_page($pagelayout);
2444 $layoutfile = $layoutinfo['file'];
2446 if (array_key_exists('theme', $layoutinfo)) {
2447 $themes = array($layoutinfo['theme']);
2448 } else {
2449 $themes = array_merge(array($this->name),$this->parents);
2452 foreach ($themes as $theme) {
2453 if ($dir = $this->find_theme_location($theme)) {
2454 $path = "$dir/layout/$layoutfile";
2456 // Check the template exists, return general base theme template if not.
2457 if (is_readable($path)) {
2458 return $path;
2463 debugging('Can not find layout file for: ' . $pagelayout);
2464 // fallback to standard normal layout
2465 return "$CFG->dirroot/theme/base/layout/general.php";
2469 * Returns auxiliary page layout options specified in layout configuration array.
2471 * @param string $pagelayout
2472 * @return array
2474 public function pagelayout_options($pagelayout) {
2475 $info = $this->layout_info_for_page($pagelayout);
2476 if (!empty($info['options'])) {
2477 return $info['options'];
2479 return array();
2483 * Inform a block_manager about the block regions this theme wants on this
2484 * page layout.
2486 * @param string $pagelayout the general type of the page.
2487 * @param block_manager $blockmanager the block_manger to set up.
2489 public function setup_blocks($pagelayout, $blockmanager) {
2490 $layoutinfo = $this->layout_info_for_page($pagelayout);
2491 if (!empty($layoutinfo['regions'])) {
2492 $blockmanager->add_regions($layoutinfo['regions'], false);
2493 $blockmanager->set_default_region($layoutinfo['defaultregion']);
2498 * Gets the visible name for the requested block region.
2500 * @param string $region The region name to get
2501 * @param string $theme The theme the region belongs to (may come from the parent theme)
2502 * @return string
2504 protected function get_region_name($region, $theme) {
2505 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
2506 // A name exists in this theme, so use it
2507 if (substr($regionstring, 0, 1) != '[') {
2508 return $regionstring;
2511 // Otherwise, try to find one elsewhere
2512 // Check parents, if any
2513 foreach ($this->parents as $parentthemename) {
2514 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
2515 if (substr($regionstring, 0, 1) != '[') {
2516 return $regionstring;
2520 // Last resort, try the bootstrapbase theme for names
2521 return get_string('region-' . $region, 'theme_bootstrapbase');
2525 * Get the list of all block regions known to this theme in all templates.
2527 * @return array internal region name => human readable name.
2529 public function get_all_block_regions() {
2530 $regions = array();
2531 foreach ($this->layouts as $layoutinfo) {
2532 foreach ($layoutinfo['regions'] as $region) {
2533 $regions[$region] = $this->get_region_name($region, $this->name);
2536 return $regions;
2540 * Returns the human readable name of the theme
2542 * @return string
2544 public function get_theme_name() {
2545 return get_string('pluginname', 'theme_'.$this->name);
2549 * Returns the block render method.
2551 * It is set by the theme via:
2552 * $THEME->blockrendermethod = '...';
2554 * It can be one of two values, blocks or blocks_for_region.
2555 * It should be set to the method being used by the theme layouts.
2557 * @return string
2559 public function get_block_render_method() {
2560 if ($this->blockrendermethod) {
2561 // Return the specified block render method.
2562 return $this->blockrendermethod;
2564 // Its not explicitly set, check the parent theme configs.
2565 foreach ($this->parent_configs as $config) {
2566 if (isset($config->blockrendermethod)) {
2567 return $config->blockrendermethod;
2570 // Default it to blocks.
2571 return 'blocks';
2575 * Get the callable for CSS tree post processing.
2577 * @return string|null
2579 public function get_css_tree_post_processor() {
2580 $configs = [$this] + $this->parent_configs;
2581 foreach ($configs as $config) {
2582 if (!empty($config->csstreepostprocessor) && is_callable($config->csstreepostprocessor)) {
2583 return $config->csstreepostprocessor;
2586 return null;
2592 * This class keeps track of which HTML tags are currently open.
2594 * This makes it much easier to always generate well formed XHTML output, even
2595 * if execution terminates abruptly. Any time you output some opening HTML
2596 * without the matching closing HTML, you should push the necessary close tags
2597 * onto the stack.
2599 * @copyright 2009 Tim Hunt
2600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2601 * @since Moodle 2.0
2602 * @package core
2603 * @category output
2605 class xhtml_container_stack {
2608 * @var array Stores the list of open containers.
2610 protected $opencontainers = array();
2613 * @var array In developer debug mode, stores a stack trace of all opens and
2614 * closes, so we can output helpful error messages when there is a mismatch.
2616 protected $log = array();
2619 * @var boolean Store whether we are developer debug mode. We need this in
2620 * several places including in the destructor where we may not have access to $CFG.
2622 protected $isdebugging;
2625 * Constructor
2627 public function __construct() {
2628 global $CFG;
2629 $this->isdebugging = $CFG->debugdeveloper;
2633 * Push the close HTML for a recently opened container onto the stack.
2635 * @param string $type The type of container. This is checked when {@link pop()}
2636 * is called and must match, otherwise a developer debug warning is output.
2637 * @param string $closehtml The HTML required to close the container.
2639 public function push($type, $closehtml) {
2640 $container = new stdClass;
2641 $container->type = $type;
2642 $container->closehtml = $closehtml;
2643 if ($this->isdebugging) {
2644 $this->log('Open', $type);
2646 array_push($this->opencontainers, $container);
2650 * Pop the HTML for the next closing container from the stack. The $type
2651 * must match the type passed when the container was opened, otherwise a
2652 * warning will be output.
2654 * @param string $type The type of container.
2655 * @return string the HTML required to close the container.
2657 public function pop($type) {
2658 if (empty($this->opencontainers)) {
2659 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2660 $this->output_log(), DEBUG_DEVELOPER);
2661 return;
2664 $container = array_pop($this->opencontainers);
2665 if ($container->type != $type) {
2666 debugging('<p>The type of container to be closed (' . $container->type .
2667 ') does not match the type of the next open container (' . $type .
2668 '). This suggests there is a nesting problem.</p>' .
2669 $this->output_log(), DEBUG_DEVELOPER);
2671 if ($this->isdebugging) {
2672 $this->log('Close', $type);
2674 return $container->closehtml;
2678 * Close all but the last open container. This is useful in places like error
2679 * handling, where you want to close all the open containers (apart from <body>)
2680 * before outputting the error message.
2682 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2683 * developer debug warning if it isn't.
2684 * @return string the HTML required to close any open containers inside <body>.
2686 public function pop_all_but_last($shouldbenone = false) {
2687 if ($shouldbenone && count($this->opencontainers) != 1) {
2688 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2689 $this->output_log(), DEBUG_DEVELOPER);
2691 $output = '';
2692 while (count($this->opencontainers) > 1) {
2693 $container = array_pop($this->opencontainers);
2694 $output .= $container->closehtml;
2696 return $output;
2700 * You can call this function if you want to throw away an instance of this
2701 * class without properly emptying the stack (for example, in a unit test).
2702 * Calling this method stops the destruct method from outputting a developer
2703 * debug warning. After calling this method, the instance can no longer be used.
2705 public function discard() {
2706 $this->opencontainers = null;
2710 * Adds an entry to the log.
2712 * @param string $action The name of the action
2713 * @param string $type The type of action
2715 protected function log($action, $type) {
2716 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
2717 format_backtrace(debug_backtrace()) . '</li>';
2721 * Outputs the log's contents as a HTML list.
2723 * @return string HTML list of the log
2725 protected function output_log() {
2726 return '<ul>' . implode("\n", $this->log) . '</ul>';