MDL-56911 themes: Resolve settings before calling parser
[moodle.git] / lib / outputlib.php
blob4e5e58ec084b8033db4bdcb189607dcaad51c147
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 * Invalidate all server and client side caches.
40 * This method deletes the physical directory that is used to cache the theme
41 * files used for serving.
42 * Because it deletes the main theme cache directory all themes are reset by
43 * this function.
45 function theme_reset_all_caches() {
46 global $CFG, $PAGE;
48 $next = time();
49 if (isset($CFG->themerev) and $next <= $CFG->themerev and $CFG->themerev - $next < 60*60) {
50 // This resolves problems when reset is requested repeatedly within 1s,
51 // the < 1h condition prevents accidental switching to future dates
52 // because we might not recover from it.
53 $next = $CFG->themerev+1;
56 set_config('themerev', $next); // time is unique even when you reset/switch database
58 if (!empty($CFG->themedesignermode)) {
59 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner');
60 $cache->purge();
63 if ($PAGE) {
64 $PAGE->reload_theme();
68 /**
69 * Enable or disable theme designer mode.
71 * @param bool $state
73 function theme_set_designer_mod($state) {
74 set_config('themedesignermode', (int)!empty($state));
75 // Reset caches after switching mode so that any designer mode caches get purged too.
76 theme_reset_all_caches();
79 /**
80 * Returns current theme revision number.
82 * @return int
84 function theme_get_revision() {
85 global $CFG;
87 if (empty($CFG->themedesignermode)) {
88 if (empty($CFG->themerev)) {
89 // This only happens during install. It doesn't matter what themerev we use as long as it's positive.
90 return 1;
91 } else {
92 return $CFG->themerev;
95 } else {
96 return -1;
101 * Checks if the given device has a theme defined in config.php.
103 * @return bool
105 function theme_is_device_locked($device) {
106 global $CFG;
107 $themeconfigname = core_useragent::get_device_type_cfg_var_name($device);
108 return isset($CFG->config_php_settings[$themeconfigname]);
112 * Returns the theme named defined in config.php for the given device.
114 * @return string or null
116 function theme_get_locked_theme_for_device($device) {
117 global $CFG;
119 if (!theme_is_device_locked($device)) {
120 return null;
123 $themeconfigname = core_useragent::get_device_type_cfg_var_name($device);
124 return $CFG->config_php_settings[$themeconfigname];
128 * This class represents the configuration variables of a Moodle theme.
130 * All the variables with access: public below (with a few exceptions that are marked)
131 * are the properties you can set in your themes config.php file.
133 * There are also some methods and protected variables that are part of the inner
134 * workings of Moodle's themes system. If you are just editing a themes config.php
135 * file, you can just ignore those, and the following information for developers.
137 * Normally, to create an instance of this class, you should use the
138 * {@link theme_config::load()} factory method to load a themes config.php file.
139 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
140 * will create one for you, accessible as $PAGE->theme.
142 * @copyright 2009 Tim Hunt
143 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
144 * @since Moodle 2.0
145 * @package core
146 * @category output
148 class theme_config {
151 * @var string Default theme, used when requested theme not found.
153 const DEFAULT_THEME = 'boost';
156 * @var array You can base your theme on other themes by linking to the other theme as
157 * parents. This lets you use the CSS and layouts from the other themes
158 * (see {@link theme_config::$layouts}).
159 * That makes it easy to create a new theme that is similar to another one
160 * but with a few changes. In this themes CSS you only need to override
161 * those rules you want to change.
163 public $parents;
166 * @var array The names of all the stylesheets from this theme that you would
167 * like included, in order. Give the names of the files without .css.
169 public $sheets = array();
172 * @var array The names of all the stylesheets from parents that should be excluded.
173 * true value may be used to specify all parents or all themes from one parent.
174 * If no value specified value from parent theme used.
176 public $parents_exclude_sheets = null;
179 * @var array List of plugin sheets to be excluded.
180 * If no value specified value from parent theme used.
182 public $plugins_exclude_sheets = null;
185 * @var array List of style sheets that are included in the text editor bodies.
186 * Sheets from parent themes are used automatically and can not be excluded.
188 public $editor_sheets = array();
191 * @var array The names of all the javascript files this theme that you would
192 * like included from head, in order. Give the names of the files without .js.
194 public $javascripts = array();
197 * @var array The names of all the javascript files this theme that you would
198 * like included from footer, in order. Give the names of the files without .js.
200 public $javascripts_footer = array();
203 * @var array The names of all the javascript files from parents that should
204 * be excluded. true value may be used to specify all parents or all themes
205 * from one parent.
206 * If no value specified value from parent theme used.
208 public $parents_exclude_javascripts = null;
211 * @var array Which file to use for each page layout.
213 * This is an array of arrays. The keys of the outer array are the different layouts.
214 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
215 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
216 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
217 * That file also has a good example of how to set this setting.
219 * For each layout, the value in the outer array is an array that describes
220 * how you want that type of page to look. For example
221 * <pre>
222 * $THEME->layouts = array(
223 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
224 * 'standard' => array(
225 * 'theme' = 'mytheme',
226 * 'file' => 'normal.php',
227 * 'regions' => array('side-pre', 'side-post'),
228 * 'defaultregion' => 'side-post'
229 * ),
230 * // The site home page.
231 * 'home' => array(
232 * 'theme' = 'mytheme',
233 * 'file' => 'home.php',
234 * 'regions' => array('side-pre', 'side-post'),
235 * 'defaultregion' => 'side-post'
236 * ),
237 * // ...
238 * );
239 * </pre>
241 * 'theme' name of the theme where is the layout located
242 * 'file' is the layout file to use for this type of page.
243 * layout files are stored in layout subfolder
244 * 'regions' This lists the regions on the page where blocks may appear. For
245 * each region you list here, your layout file must include a call to
246 * <pre>
247 * echo $OUTPUT->blocks_for_region($regionname);
248 * </pre>
249 * or equivalent so that the blocks are actually visible.
251 * 'defaultregion' If the list of regions is non-empty, then you must pick
252 * one of the one of them as 'default'. This has two meanings. First, this is
253 * where new blocks are added. Second, if there are any blocks associated with
254 * the page, but in non-existent regions, they appear here. (Imaging, for example,
255 * that someone added blocks using a different theme that used different region
256 * names, and then switched to this theme.)
258 public $layouts = array();
261 * @var string Name of the renderer factory class to use. Must implement the
262 * {@link renderer_factory} interface.
264 * This is an advanced feature. Moodle output is generated by 'renderers',
265 * you can customise the HTML that is output by writing custom renderers,
266 * and then you need to specify 'renderer factory' so that Moodle can find
267 * your renderers.
269 * There are some renderer factories supplied with Moodle. Please follow these
270 * links to see what they do.
271 * <ul>
272 * <li>{@link standard_renderer_factory} - the default.</li>
273 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
274 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
275 * </ul>
277 public $rendererfactory = 'standard_renderer_factory';
280 * @var string Function to do custom CSS post-processing.
282 * This is an advanced feature. If you want to do custom post-processing on the
283 * CSS before it is output (for example, to replace certain variable names
284 * with particular values) you can give the name of a function here.
286 public $csspostprocess = null;
289 * @var string Function to do custom CSS post-processing on a parsed CSS tree.
291 * This is an advanced feature. If you want to do custom post-processing on the
292 * CSS before it is output, you can provide the name of the function here. The
293 * function will receive a CSS tree document as first parameter, and the theme_config
294 * object as second parameter. A return value is not required, the tree can
295 * be edited in place.
297 public $csstreepostprocess = null;
300 * @var string Accessibility: Right arrow-like character is
301 * used in the breadcrumb trail, course navigation menu
302 * (previous/next activity), calendar, and search forum block.
303 * If the theme does not set characters, appropriate defaults
304 * are set automatically. Please DO NOT
305 * use &lt; &gt; &raquo; - these are confusing for blind users.
307 public $rarrow = null;
310 * @var string Accessibility: Left arrow-like character is
311 * used in the breadcrumb trail, course navigation menu
312 * (previous/next activity), calendar, and search forum block.
313 * If the theme does not set characters, appropriate defaults
314 * are set automatically. Please DO NOT
315 * use &lt; &gt; &raquo; - these are confusing for blind users.
317 public $larrow = null;
320 * @var string Accessibility: Up arrow-like character is used in
321 * the book heirarchical navigation.
322 * If the theme does not set characters, appropriate defaults
323 * are set automatically. Please DO NOT
324 * use ^ - this is confusing for blind users.
326 public $uarrow = null;
329 * @var string Accessibility: Down arrow-like character.
330 * If the theme does not set characters, appropriate defaults
331 * are set automatically.
333 public $darrow = null;
336 * @var bool Some themes may want to disable ajax course editing.
338 public $enablecourseajax = true;
341 * @var string Determines served document types
342 * - 'html5' the only officially supported doctype in Moodle
343 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
344 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
346 public $doctype = 'html5';
349 * @var string undeletableblocktypes If set to a string, will list the block types that cannot be deleted. Defaults to
350 * navigation and settings.
352 public $undeletableblocktypes = false;
354 //==Following properties are not configurable from theme config.php==
357 * @var string The name of this theme. Set automatically when this theme is
358 * loaded. This can not be set in theme config.php
360 public $name;
363 * @var string The folder where this themes files are stored. This is set
364 * automatically. This can not be set in theme config.php
366 public $dir;
369 * @var stdClass Theme settings stored in config_plugins table.
370 * This can not be set in theme config.php
372 public $setting = null;
375 * @var bool If set to true and the theme enables the dock then blocks will be able
376 * to be moved to the special dock
378 public $enable_dock = false;
381 * @var bool If set to true then this theme will not be shown in the theme selector unless
382 * theme designer mode is turned on.
384 public $hidefromselector = false;
387 * @var array list of YUI CSS modules to be included on each page. This may be used
388 * to remove cssreset and use cssnormalise module instead.
390 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
393 * An associative array of block manipulations that should be made if the user is using an rtl language.
394 * The key is the original block region, and the value is the block region to change to.
395 * This is used when displaying blocks for regions only.
396 * @var array
398 public $blockrtlmanipulations = array();
401 * @var renderer_factory Instance of the renderer_factory implementation
402 * we are using. Implementation detail.
404 protected $rf = null;
407 * @var array List of parent config objects.
409 protected $parent_configs = array();
412 * Used to determine whether we can serve SVG images or not.
413 * @var bool
415 private $usesvg = null;
418 * Whether in RTL mode or not.
419 * @var bool
421 protected $rtlmode = false;
424 * The LESS file to compile. When set, the theme will attempt to compile the file itself.
425 * @var bool
427 public $lessfile = false;
430 * The SCSS file to compile. This takes precedence over the LESS file.
431 * @var string
433 public $scssfile = false;
436 * The name of the function to call to get the LESS code to inject.
437 * @var string
439 public $extralesscallback = null;
442 * The name of the function to call to get the SCSS code to inject.
443 * @var string
445 public $extrascsscallback = null;
448 * The name of the function to call to get extra LESS variables.
449 * @var string
451 public $lessvariablescallback = null;
454 * The name of the function to call to get SCSS to prepend.
455 * @var string
457 public $prescsscallback = null;
460 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
461 * Defaults to {@link core_renderer::blocks_for_region()}
462 * @var string
464 public $blockrendermethod = null;
467 * Load the config.php file for a particular theme, and return an instance
468 * of this class. (That is, this is a factory method.)
470 * @param string $themename the name of the theme.
471 * @return theme_config an instance of this class.
473 public static function load($themename) {
474 global $CFG;
476 // load theme settings from db
477 try {
478 $settings = get_config('theme_'.$themename);
479 } catch (dml_exception $e) {
480 // most probably moodle tables not created yet
481 $settings = new stdClass();
484 if ($config = theme_config::find_theme_config($themename, $settings)) {
485 return new theme_config($config);
487 } else if ($themename == theme_config::DEFAULT_THEME) {
488 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
490 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
491 return new theme_config($config);
493 } else {
494 // bad luck, the requested theme has some problems - admin see details in theme config
495 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
500 * Theme diagnostic code. It is very problematic to send debug output
501 * to the actual CSS file, instead this functions is supposed to
502 * diagnose given theme and highlights all potential problems.
503 * This information should be available from the theme selection page
504 * or some other debug page for theme designers.
506 * @param string $themename
507 * @return array description of problems
509 public static function diagnose($themename) {
510 //TODO: MDL-21108
511 return array();
515 * Private constructor, can be called only from the factory method.
516 * @param stdClass $config
518 private function __construct($config) {
519 global $CFG; //needed for included lib.php files
521 $this->settings = $config->settings;
522 $this->name = $config->name;
523 $this->dir = $config->dir;
525 if ($this->name != 'bootstrapbase') {
526 $baseconfig = theme_config::find_theme_config('bootstrapbase', $this->settings);
527 } else {
528 $baseconfig = $config;
531 $configurable = array(
532 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets',
533 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
534 'layouts', 'enable_dock', 'enablecourseajax', 'undeletableblocktypes',
535 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'uarrow', 'darrow',
536 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations',
537 'lessfile', 'extralesscallback', 'lessvariablescallback', 'blockrendermethod',
538 'scssfile', 'extrascsscallback', 'prescsscallback', 'csstreepostprocessor');
540 foreach ($config as $key=>$value) {
541 if (in_array($key, $configurable)) {
542 $this->$key = $value;
546 // verify all parents and load configs and renderers
547 foreach ($this->parents as $parent) {
548 if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
549 // this is not good - better exclude faulty parents
550 continue;
552 $libfile = $parent_config->dir.'/lib.php';
553 if (is_readable($libfile)) {
554 // theme may store various function here
555 include_once($libfile);
557 $renderersfile = $parent_config->dir.'/renderers.php';
558 if (is_readable($renderersfile)) {
559 // may contain core and plugin renderers and renderer factory
560 include_once($renderersfile);
562 $this->parent_configs[$parent] = $parent_config;
564 $libfile = $this->dir.'/lib.php';
565 if (is_readable($libfile)) {
566 // theme may store various function here
567 include_once($libfile);
569 $rendererfile = $this->dir.'/renderers.php';
570 if (is_readable($rendererfile)) {
571 // may contain core and plugin renderers and renderer factory
572 include_once($rendererfile);
573 } else {
574 // check if renderers.php file is missnamed renderer.php
575 if (is_readable($this->dir.'/renderer.php')) {
576 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
577 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
581 // cascade all layouts properly
582 foreach ($baseconfig->layouts as $layout=>$value) {
583 if (!isset($this->layouts[$layout])) {
584 foreach ($this->parent_configs as $parent_config) {
585 if (isset($parent_config->layouts[$layout])) {
586 $this->layouts[$layout] = $parent_config->layouts[$layout];
587 continue 2;
590 $this->layouts[$layout] = $value;
594 //fix arrows if needed
595 $this->check_theme_arrows();
599 * Let the theme initialise the page object (usually $PAGE).
601 * This may be used for example to request jQuery in add-ons.
603 * @param moodle_page $page
605 public function init_page(moodle_page $page) {
606 $themeinitfunction = 'theme_'.$this->name.'_page_init';
607 if (function_exists($themeinitfunction)) {
608 $themeinitfunction($page);
613 * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow, $THEME->darrow have been set (theme/-/config.php).
614 * If not it applies sensible defaults.
616 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
617 * search forum block, etc. Important: these are 'silent' in a screen-reader
618 * (unlike &gt; &raquo;), and must be accompanied by text.
620 private function check_theme_arrows() {
621 if (!isset($this->rarrow) and !isset($this->larrow)) {
622 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
623 // Also OK in Win 9x/2K/IE 5.x
624 $this->rarrow = '&#x25BA;';
625 $this->larrow = '&#x25C4;';
626 $this->uarrow = '&#x25B2;';
627 $this->darrow = '&#x25BC;';
628 if (empty($_SERVER['HTTP_USER_AGENT'])) {
629 $uagent = '';
630 } else {
631 $uagent = $_SERVER['HTTP_USER_AGENT'];
633 if (false !== strpos($uagent, 'Opera')
634 || false !== strpos($uagent, 'Mac')) {
635 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
636 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
637 $this->rarrow = '&#x25B6;&#xFE0E;';
638 $this->larrow = '&#x25C0;&#xFE0E;';
640 elseif ((false !== strpos($uagent, 'Konqueror'))
641 || (false !== strpos($uagent, 'Android'))) {
642 // The fonts on Android don't include the characters required for this to work as expected.
643 // So we use the same ones Konqueror uses.
644 $this->rarrow = '&rarr;';
645 $this->larrow = '&larr;';
646 $this->uarrow = '&uarr;';
647 $this->darrow = '&darr;';
649 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
650 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
651 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
652 // To be safe, non-Unicode browsers!
653 $this->rarrow = '&gt;';
654 $this->larrow = '&lt;';
655 $this->uarrow = '^';
656 $this->darrow = 'v';
659 // RTL support - in RTL languages, swap r and l arrows
660 if (right_to_left()) {
661 $t = $this->rarrow;
662 $this->rarrow = $this->larrow;
663 $this->larrow = $t;
669 * Returns output renderer prefixes, these are used when looking
670 * for the overridden renderers in themes.
672 * @return array
674 public function renderer_prefixes() {
675 global $CFG; // just in case the included files need it
677 $prefixes = array('theme_'.$this->name);
679 foreach ($this->parent_configs as $parent) {
680 $prefixes[] = 'theme_'.$parent->name;
683 return $prefixes;
687 * Returns the stylesheet URL of this editor content
689 * @param bool $encoded false means use & and true use &amp; in URLs
690 * @return moodle_url
692 public function editor_css_url($encoded=true) {
693 global $CFG;
694 $rev = theme_get_revision();
695 if ($rev > -1) {
696 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
697 if (!empty($CFG->slasharguments)) {
698 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
699 } else {
700 $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
702 } else {
703 $params = array('theme'=>$this->name, 'type'=>'editor');
704 $url = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
706 return $url;
710 * Returns the content of the CSS to be used in editor content
712 * @return array
714 public function editor_css_files() {
715 $files = array();
717 // First editor plugins.
718 $plugins = core_component::get_plugin_list('editor');
719 foreach ($plugins as $plugin=>$fulldir) {
720 $sheetfile = "$fulldir/editor_styles.css";
721 if (is_readable($sheetfile)) {
722 $files['plugin_'.$plugin] = $sheetfile;
725 // Then parent themes - base first, the immediate parent last.
726 foreach (array_reverse($this->parent_configs) as $parent_config) {
727 if (empty($parent_config->editor_sheets)) {
728 continue;
730 foreach ($parent_config->editor_sheets as $sheet) {
731 $sheetfile = "$parent_config->dir/style/$sheet.css";
732 if (is_readable($sheetfile)) {
733 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
737 // Finally this theme.
738 if (!empty($this->editor_sheets)) {
739 foreach ($this->editor_sheets as $sheet) {
740 $sheetfile = "$this->dir/style/$sheet.css";
741 if (is_readable($sheetfile)) {
742 $files['theme_'.$sheet] = $sheetfile;
747 return $files;
751 * Get the stylesheet URL of this theme.
753 * @param moodle_page $page Not used... deprecated?
754 * @return moodle_url[]
756 public function css_urls(moodle_page $page) {
757 global $CFG;
759 $rev = theme_get_revision();
761 $urls = array();
763 $svg = $this->use_svg_icons();
764 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
766 if ($rev > -1) {
767 $filename = right_to_left() ? 'all-rtl' : 'all';
768 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
769 if (!empty($CFG->slasharguments)) {
770 $slashargs = '';
771 if (!$svg) {
772 // We add a simple /_s to the start of the path.
773 // The underscore is used to ensure that it isn't a valid theme name.
774 $slashargs .= '/_s'.$slashargs;
776 $slashargs .= '/'.$this->name.'/'.$rev.'/'.$filename;
777 if ($separate) {
778 $slashargs .= '/chunk0';
780 $url->set_slashargument($slashargs, 'noparam', true);
781 } else {
782 $params = array('theme' => $this->name, 'rev' => $rev, 'type' => $filename);
783 if (!$svg) {
784 // We add an SVG param so that we know not to serve SVG images.
785 // We do this because all modern browsers support SVG and this param will one day be removed.
786 $params['svg'] = '0';
788 if ($separate) {
789 $params['chunk'] = '0';
791 $url->params($params);
793 $urls[] = $url;
795 } else {
796 $baseurl = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php');
798 $css = $this->get_css_files(true);
799 if (!$svg) {
800 // We add an SVG param so that we know not to serve SVG images.
801 // We do this because all modern browsers support SVG and this param will one day be removed.
802 $baseurl->param('svg', '0');
804 if (right_to_left()) {
805 $baseurl->param('rtl', 1);
807 if ($separate) {
808 // We might need to chunk long files.
809 $baseurl->param('chunk', '0');
811 if (core_useragent::is_ie()) {
812 // Lalala, IE does not allow more than 31 linked CSS files from main document.
813 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
814 foreach ($css['parents'] as $parent=>$sheets) {
815 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
816 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
818 if (!empty($this->scssfile)) {
819 // No need to define the type as IE here.
820 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
821 } else if (!empty($this->lessfile)) {
822 // No need to define the type as IE here.
823 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
825 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
827 } else {
828 foreach ($css['plugins'] as $plugin=>$unused) {
829 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
831 foreach ($css['parents'] as $parent=>$sheets) {
832 foreach ($sheets as $sheet=>$unused2) {
833 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
836 foreach ($css['theme'] as $sheet => $filename) {
837 if ($sheet === $this->scssfile) {
838 // This is the theme SCSS file.
839 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
840 } else if ($sheet === $this->lessfile) {
841 // This is the theme LESS file.
842 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
843 } else {
844 // Sheet first in order to make long urls easier to read.
845 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
851 return $urls;
855 * Get the whole css stylesheet for production mode.
857 * NOTE: this method is not expected to be used from any addons.
859 * @return string CSS markup compressed
861 public function get_css_content() {
863 $csscontent = '';
864 foreach ($this->get_css_files(false) as $type => $value) {
865 foreach ($value as $identifier => $val) {
866 if (is_array($val)) {
867 foreach ($val as $v) {
868 $csscontent .= file_get_contents($v) . "\n";
870 } else {
871 if ($type === 'theme' && $identifier === $this->scssfile) {
872 // We need the content from SCSS because this is the SCSS file from the theme.
873 $csscontent .= $this->get_css_content_from_scss(false);
874 } else if ($type === 'theme' && $identifier === $this->lessfile) {
875 // We need the content from LESS because this is the LESS file from the theme.
876 $csscontent .= $this->get_css_content_from_less(false);
877 } else {
878 $csscontent .= file_get_contents($val) . "\n";
883 $csscontent = $this->post_process($csscontent);
884 $csscontent = core_minify::css($csscontent);
886 return $csscontent;
890 * Get the theme designer css markup,
891 * the parameters are coming from css_urls().
893 * NOTE: this method is not expected to be used from any addons.
895 * @param string $type
896 * @param string $subtype
897 * @param string $sheet
898 * @return string CSS markup
900 public function get_css_content_debug($type, $subtype, $sheet) {
902 if ($type === 'scss') {
903 // The SCSS file of the theme is requested.
904 $csscontent = $this->get_css_content_from_scss(true);
905 if ($csscontent !== false) {
906 return $this->post_process($csscontent);
908 return '';
909 } else if ($type === 'less') {
910 // The LESS file of the theme is requested.
911 $csscontent = $this->get_css_content_from_less(true);
912 if ($csscontent !== false) {
913 return $this->post_process($csscontent);
915 return '';
918 $cssfiles = array();
919 $css = $this->get_css_files(true);
921 if ($type === 'ie') {
922 // IE is a sloppy browser with weird limits, sorry.
923 if ($subtype === 'plugins') {
924 $cssfiles = $css['plugins'];
926 } else if ($subtype === 'parents') {
927 if (empty($sheet)) {
928 // Do not bother with the empty parent here.
929 } else {
930 // Build up the CSS for that parent so we can serve it as one file.
931 foreach ($css[$subtype][$sheet] as $parent => $css) {
932 $cssfiles[] = $css;
935 } else if ($subtype === 'theme') {
936 $cssfiles = $css['theme'];
937 foreach ($cssfiles as $key => $value) {
938 if (in_array($key, [$this->lessfile, $this->scssfile])) {
939 // Remove the LESS/SCSS file from the theme CSS files.
940 // The LESS/SCSS files use the type 'less' or 'scss', not 'ie'.
941 unset($cssfiles[$key]);
946 } else if ($type === 'plugin') {
947 if (isset($css['plugins'][$subtype])) {
948 $cssfiles[] = $css['plugins'][$subtype];
951 } else if ($type === 'parent') {
952 if (isset($css['parents'][$subtype][$sheet])) {
953 $cssfiles[] = $css['parents'][$subtype][$sheet];
956 } else if ($type === 'theme') {
957 if (isset($css['theme'][$sheet])) {
958 $cssfiles[] = $css['theme'][$sheet];
962 $csscontent = '';
963 foreach ($cssfiles as $file) {
964 $contents = file_get_contents($file);
965 $contents = $this->post_process($contents);
966 $comment = "/** Path: $type $subtype $sheet.' **/\n";
967 $stats = '';
968 $csscontent .= $comment.$stats.$contents."\n\n";
971 return $csscontent;
975 * Get the whole css stylesheet for editor iframe.
977 * NOTE: this method is not expected to be used from any addons.
979 * @return string CSS markup
981 public function get_css_content_editor() {
982 // Do not bother to optimise anything here, just very basic stuff.
983 $cssfiles = $this->editor_css_files();
984 $css = '';
985 foreach ($cssfiles as $file) {
986 $css .= file_get_contents($file)."\n";
988 return $this->post_process($css);
992 * Returns an array of organised CSS files required for this output.
994 * @param bool $themedesigner
995 * @return array nested array of file paths
997 protected function get_css_files($themedesigner) {
998 global $CFG;
1000 $cache = null;
1001 $cachekey = 'cssfiles';
1002 if ($themedesigner) {
1003 require_once($CFG->dirroot.'/lib/csslib.php');
1004 // We need some kind of caching here because otherwise the page navigation becomes
1005 // way too slow in theme designer mode. Feel free to create full cache definition later...
1006 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
1007 if ($files = $cache->get($cachekey)) {
1008 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
1009 unset($files['created']);
1010 return $files;
1015 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
1017 // Get all plugin sheets.
1018 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
1019 if ($excludes !== true) {
1020 foreach (core_component::get_plugin_types() as $type=>$unused) {
1021 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
1022 continue;
1024 $plugins = core_component::get_plugin_list($type);
1025 foreach ($plugins as $plugin=>$fulldir) {
1026 if (!empty($excludes[$type]) and is_array($excludes[$type])
1027 and in_array($plugin, $excludes[$type])) {
1028 continue;
1031 // Get the CSS from the plugin.
1032 $sheetfile = "$fulldir/styles.css";
1033 if (is_readable($sheetfile)) {
1034 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
1037 // Create a list of candidate sheets from parents (direct parent last) and current theme.
1038 $candidates = array();
1039 foreach (array_reverse($this->parent_configs) as $parent_config) {
1040 $candidates[] = $parent_config->name;
1042 $candidates[] = $this->name;
1044 // Add the sheets found.
1045 foreach ($candidates as $candidate) {
1046 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1047 if (is_readable($sheetthemefile)) {
1048 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
1055 // Find out wanted parent sheets.
1056 $excludes = $this->resolve_excludes('parents_exclude_sheets');
1057 if ($excludes !== true) {
1058 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1059 $parent = $parent_config->name;
1060 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
1061 continue;
1063 foreach ($parent_config->sheets as $sheet) {
1064 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1065 && in_array($sheet, $excludes[$parent])) {
1066 continue;
1069 // We never refer to the parent LESS files.
1070 $sheetfile = "$parent_config->dir/style/$sheet.css";
1071 if (is_readable($sheetfile)) {
1072 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1078 // Current theme sheets and less file.
1079 // We first add the SCSS, or LESS file because we want the CSS ones to
1080 // be included after the SCSS/LESS code. However, if both the SCSS/LESS file
1081 // and a CSS file share the same name, the CSS file is ignored.
1082 if (!empty($this->scssfile)) {
1083 $sheetfile = "{$this->dir}/scss/{$this->scssfile}.scss";
1084 if (is_readable($sheetfile)) {
1085 $cssfiles['theme'][$this->scssfile] = $sheetfile;
1087 } else if (!empty($this->lessfile)) {
1088 $sheetfile = "{$this->dir}/less/{$this->lessfile}.less";
1089 if (is_readable($sheetfile)) {
1090 $cssfiles['theme'][$this->lessfile] = $sheetfile;
1093 if (is_array($this->sheets)) {
1094 foreach ($this->sheets as $sheet) {
1095 $sheetfile = "$this->dir/style/$sheet.css";
1096 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1097 $cssfiles['theme'][$sheet] = $sheetfile;
1102 if ($cache) {
1103 $files = $cssfiles;
1104 $files['created'] = time();
1105 $cache->set($cachekey, $files);
1107 return $cssfiles;
1111 * Return the CSS content generated from LESS the file.
1113 * @param bool $themedesigner True if theme designer is enabled.
1114 * @return bool|string Return false when the compilation failed. Else the compiled string.
1116 protected function get_css_content_from_less($themedesigner) {
1117 global $CFG;
1119 $lessfile = $this->lessfile;
1120 if (!$lessfile || !is_readable($this->dir . '/less/' . $lessfile . '.less')) {
1121 throw new coding_exception('The theme did not define a LESS file, or it is not readable.');
1124 // We might need more memory to do this, so let's play safe.
1125 raise_memory_limit(MEMORY_EXTRA);
1127 // Files list.
1128 $files = $this->get_css_files($themedesigner);
1130 // Get the LESS file path.
1131 $themelessfile = $files['theme'][$lessfile];
1133 // Setup compiler options.
1134 $options = array(
1135 // We need to set the import directory to where $lessfile is.
1136 'import_dirs' => array(dirname($themelessfile) => '/'),
1137 // Always disable default caching.
1138 'cache_method' => false,
1139 // Disable the relative URLs, we have post_process() to handle that.
1140 'relativeUrls' => false,
1143 if ($themedesigner) {
1144 // Add the sourceMap inline to ensure that it is atomically generated.
1145 $options['sourceMap'] = true;
1146 $options['sourceMapBasepath'] = $CFG->dirroot;
1147 $options['sourceMapRootpath'] = $CFG->wwwroot;
1150 // Instantiate the compiler.
1151 $compiler = new core_lessc($options);
1153 try {
1154 $compiler->parse_file_content($themelessfile);
1156 // Get the callbacks.
1157 $compiler->parse($this->get_extra_less_code());
1158 $compiler->ModifyVars($this->get_less_variables());
1160 // Compile the CSS.
1161 $compiled = $compiler->getCss();
1163 } catch (Less_Exception_Parser $e) {
1164 $compiled = false;
1165 debugging('Error while compiling LESS ' . $lessfile . ' file: ' . $e->getMessage(), DEBUG_DEVELOPER);
1168 // Try to save memory.
1169 $compiler = null;
1170 unset($compiler);
1172 return $compiled;
1176 * Return the CSS content generated from the SCSS file.
1178 * @param bool $themedesigner True if theme designer is enabled.
1179 * @return bool|string Return false when the compilation failed. Else the compiled string.
1181 protected function get_css_content_from_scss($themedesigner) {
1182 global $CFG;
1184 $scssfile = $this->scssfile;
1185 if (!$scssfile || !is_readable($this->dir . '/scss/' . $scssfile . '.scss')) {
1186 throw new coding_exception('The theme did not define a SCSS file, or it is not readable.');
1189 // We might need more memory to do this, so let's play safe.
1190 raise_memory_limit(MEMORY_EXTRA);
1192 // Files list.
1193 $files = $this->get_css_files($themedesigner);
1195 // Get the SCSS file path.
1196 $themescssfile = $files['theme'][$scssfile];
1198 // Set-up the compiler.
1199 $compiler = new core_scss();
1200 $compiler->prepend_raw_scss($this->get_pre_scss_code());
1201 $compiler->set_file($themescssfile);
1202 $compiler->append_raw_scss($this->get_extra_scss_code());
1204 try {
1205 // Compile!
1206 $compiled = $compiler->to_css();
1208 } catch (\Leafo\ScssPhp\Exception $e) {
1209 $compiled = false;
1210 debugging('Error while compiling SCSS ' . $scssfile . ' file: ' . $e->getMessage(), DEBUG_DEVELOPER);
1213 // Try to save memory.
1214 $compiler = null;
1215 unset($compiler);
1217 return $compiled;
1221 * Return extra LESS variables to use when compiling.
1223 * @return array Where keys are the variable names (omitting the @), and the values are the value.
1225 protected function get_less_variables() {
1226 $variables = array();
1228 // Getting all the candidate functions.
1229 $candidates = array();
1230 foreach ($this->parent_configs as $parent_config) {
1231 if (!isset($parent_config->lessvariablescallback)) {
1232 continue;
1234 $candidates[] = $parent_config->lessvariablescallback;
1236 $candidates[] = $this->lessvariablescallback;
1238 // Calling the functions.
1239 foreach ($candidates as $function) {
1240 if (function_exists($function)) {
1241 $vars = $function($this);
1242 if (!is_array($vars)) {
1243 debugging('Callback ' . $function . ' did not return an array() as expected', DEBUG_DEVELOPER);
1244 continue;
1246 $variables = array_merge($variables, $vars);
1250 return $variables;
1254 * Return extra LESS code to add when compiling.
1256 * This is intended to be used by themes to inject some LESS code
1257 * before it gets compiled. If you want to inject variables you
1258 * should use {@link self::get_less_variables()}.
1260 * @return string The LESS code to inject.
1262 protected function get_extra_less_code() {
1263 $content = '';
1265 // Getting all the candidate functions.
1266 $candidates = array();
1267 foreach ($this->parent_configs as $parent_config) {
1268 if (!isset($parent_config->extralesscallback)) {
1269 continue;
1271 $candidates[] = $parent_config->extralesscallback;
1273 $candidates[] = $this->extralesscallback;
1275 // Calling the functions.
1276 foreach ($candidates as $function) {
1277 if (function_exists($function)) {
1278 $content .= "\n/** Extra LESS from $function **/\n" . $function($this) . "\n";
1282 return $content;
1286 * Return extra SCSS code to add when compiling.
1288 * This is intended to be used by themes to inject some SCSS code
1289 * before it gets compiled. If you want to inject variables you
1290 * should use {@link self::get_scss_variables()}.
1292 * @return string The SCSS code to inject.
1294 protected function get_extra_scss_code() {
1295 $content = '';
1297 // Getting all the candidate functions.
1298 $candidates = array();
1299 foreach ($this->parent_configs as $parent_config) {
1300 if (!isset($parent_config->extrascsscallback)) {
1301 continue;
1303 $candidates[] = $parent_config->extrascsscallback;
1305 $candidates[] = $this->extrascsscallback;
1307 // Calling the functions.
1308 foreach ($candidates as $function) {
1309 if (function_exists($function)) {
1310 $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n";
1314 return $content;
1318 * SCSS code to prepend when compiling.
1320 * This is intended to be used by themes to inject SCSS code before it gets compiled.
1322 * @return string The SCSS code to inject.
1324 protected function get_pre_scss_code() {
1325 $content = '';
1327 // Getting all the candidate functions.
1328 $candidates = array();
1329 foreach ($this->parent_configs as $parent_config) {
1330 if (!isset($parent_config->prescsscallback)) {
1331 continue;
1333 $candidates[] = $parent_config->prescsscallback;
1335 $candidates[] = $this->prescsscallback;
1337 // Calling the functions.
1338 foreach ($candidates as $function) {
1339 if (function_exists($function)) {
1340 $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n";
1344 return $content;
1348 * Generate a URL to the file that serves theme JavaScript files.
1350 * If we determine that the theme has no relevant files, then we return
1351 * early with a null value.
1353 * @param bool $inhead true means head url, false means footer
1354 * @return moodle_url|null
1356 public function javascript_url($inhead) {
1357 global $CFG;
1359 $rev = theme_get_revision();
1360 $params = array('theme'=>$this->name,'rev'=>$rev);
1361 $params['type'] = $inhead ? 'head' : 'footer';
1363 // Return early if there are no files to serve
1364 if (count($this->javascript_files($params['type'])) === 0) {
1365 return null;
1368 if (!empty($CFG->slasharguments) and $rev > 0) {
1369 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
1370 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
1371 return $url;
1372 } else {
1373 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
1378 * Get the URL's for the JavaScript files used by this theme.
1379 * They won't be served directly, instead they'll be mediated through
1380 * theme/javascript.php.
1382 * @param string $type Either javascripts_footer, or javascripts
1383 * @return array
1385 public function javascript_files($type) {
1386 if ($type === 'footer') {
1387 $type = 'javascripts_footer';
1388 } else {
1389 $type = 'javascripts';
1392 $js = array();
1393 // find out wanted parent javascripts
1394 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1395 if ($excludes !== true) {
1396 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1397 $parent = $parent_config->name;
1398 if (empty($parent_config->$type)) {
1399 continue;
1401 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1402 continue;
1404 foreach ($parent_config->$type as $javascript) {
1405 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1406 and in_array($javascript, $excludes[$parent])) {
1407 continue;
1409 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1410 if (is_readable($javascriptfile)) {
1411 $js[] = $javascriptfile;
1417 // current theme javascripts
1418 if (is_array($this->$type)) {
1419 foreach ($this->$type as $javascript) {
1420 $javascriptfile = "$this->dir/javascript/$javascript.js";
1421 if (is_readable($javascriptfile)) {
1422 $js[] = $javascriptfile;
1426 return $js;
1430 * Resolves an exclude setting to the themes setting is applicable or the
1431 * setting of its closest parent.
1433 * @param string $variable The name of the setting the exclude setting to resolve
1434 * @param string $default
1435 * @return mixed
1437 protected function resolve_excludes($variable, $default = null) {
1438 $setting = $default;
1439 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1440 $setting = $this->{$variable};
1441 } else {
1442 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1443 if (!isset($parent_config->{$variable})) {
1444 continue;
1446 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1447 $setting = $parent_config->{$variable};
1448 break;
1452 return $setting;
1456 * Returns the content of the one huge javascript file merged from all theme javascript files.
1458 * @param bool $type
1459 * @return string
1461 public function javascript_content($type) {
1462 $jsfiles = $this->javascript_files($type);
1463 $js = '';
1464 foreach ($jsfiles as $jsfile) {
1465 $js .= file_get_contents($jsfile)."\n";
1467 return $js;
1471 * Post processes CSS.
1473 * This method post processes all of the CSS before it is served for this theme.
1474 * This is done so that things such as image URL's can be swapped in and to
1475 * run any specific CSS post process method the theme has requested.
1476 * This allows themes to use CSS settings.
1478 * @param string $css The CSS to process.
1479 * @return string The processed CSS.
1481 public function post_process($css) {
1482 // now resolve all image locations
1483 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1484 $replaced = array();
1485 foreach ($matches as $match) {
1486 if (isset($replaced[$match[0]])) {
1487 continue;
1489 $replaced[$match[0]] = true;
1490 $imagename = $match[2];
1491 $component = rtrim($match[1], '|');
1492 $imageurl = $this->pix_url($imagename, $component)->out(false);
1493 // we do not need full url because the image.php is always in the same dir
1494 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1495 $css = str_replace($match[0], $imageurl, $css);
1499 // Now resolve all font locations.
1500 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1501 $replaced = array();
1502 foreach ($matches as $match) {
1503 if (isset($replaced[$match[0]])) {
1504 continue;
1506 $replaced[$match[0]] = true;
1507 $fontname = $match[2];
1508 $component = rtrim($match[1], '|');
1509 $fonturl = $this->font_url($fontname, $component)->out(false);
1510 // We do not need full url because the font.php is always in the same dir.
1511 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1512 $css = str_replace($match[0], $fonturl, $css);
1516 // Now resolve all theme settings or do any other postprocessing.
1517 // This needs to be done before calling core parser, since the parser strips [[settings]] tags.
1518 $csspostprocess = $this->csspostprocess;
1519 if (function_exists($csspostprocess)) {
1520 $css = $csspostprocess($css, $this);
1523 // Post processing using an object representation of CSS.
1524 $hastreeprocessor = !empty($this->csstreepostprocessor) && function_exists($this->csstreepostprocessor);
1525 $needsparsing = $hastreeprocessor || !empty($this->rtlmode);
1526 if ($needsparsing) {
1527 $parser = new core_cssparser($css);
1528 $csstree = $parser->parse();
1529 unset($parser);
1531 if ($this->rtlmode) {
1532 $this->rtlize($csstree);
1535 if ($hastreeprocessor) {
1536 $fn = $this->csstreepostprocessor;
1537 $fn($csstree, $this);
1540 $css = $csstree->render();
1541 unset($csstree);
1544 return $css;
1548 * Flip a stylesheet to RTL.
1550 * @param Object $csstree The parsed CSS tree structure to flip.
1551 * @return void
1553 protected function rtlize($csstree) {
1554 $rtlcss = new core_rtlcss($csstree);
1555 $rtlcss->flip();
1559 * Return the URL for an image
1561 * @param string $imagename the name of the icon.
1562 * @param string $component specification of one plugin like in get_string()
1563 * @return moodle_url
1565 public function pix_url($imagename, $component) {
1566 global $CFG;
1568 $params = array('theme'=>$this->name);
1569 $svg = $this->use_svg_icons();
1571 if (empty($component) or $component === 'moodle' or $component === 'core') {
1572 $params['component'] = 'core';
1573 } else {
1574 $params['component'] = $component;
1577 $rev = theme_get_revision();
1578 if ($rev != -1) {
1579 $params['rev'] = $rev;
1582 $params['image'] = $imagename;
1584 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1585 if (!empty($CFG->slasharguments) and $rev > 0) {
1586 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1587 if (!$svg) {
1588 // We add a simple /_s to the start of the path.
1589 // The underscore is used to ensure that it isn't a valid theme name.
1590 $path = '/_s'.$path;
1592 $url->set_slashargument($path, 'noparam', true);
1593 } else {
1594 if (!$svg) {
1595 // We add an SVG param so that we know not to serve SVG images.
1596 // We do this because all modern browsers support SVG and this param will one day be removed.
1597 $params['svg'] = '0';
1599 $url->params($params);
1602 return $url;
1606 * Return the URL for a font
1608 * @param string $font the name of the font (including extension).
1609 * @param string $component specification of one plugin like in get_string()
1610 * @return moodle_url
1612 public function font_url($font, $component) {
1613 global $CFG;
1615 $params = array('theme'=>$this->name);
1617 if (empty($component) or $component === 'moodle' or $component === 'core') {
1618 $params['component'] = 'core';
1619 } else {
1620 $params['component'] = $component;
1623 $rev = theme_get_revision();
1624 if ($rev != -1) {
1625 $params['rev'] = $rev;
1628 $params['font'] = $font;
1630 $url = new moodle_url("$CFG->httpswwwroot/theme/font.php");
1631 if (!empty($CFG->slasharguments) and $rev > 0) {
1632 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1633 $url->set_slashargument($path, 'noparam', true);
1634 } else {
1635 $url->params($params);
1638 return $url;
1642 * Returns URL to the stored file via pluginfile.php.
1644 * Note the theme must also implement pluginfile.php handler,
1645 * theme revision is used instead of the itemid.
1647 * @param string $setting
1648 * @param string $filearea
1649 * @return string protocol relative URL or null if not present
1651 public function setting_file_url($setting, $filearea) {
1652 global $CFG;
1654 if (empty($this->settings->$setting)) {
1655 return null;
1658 $component = 'theme_'.$this->name;
1659 $itemid = theme_get_revision();
1660 $filepath = $this->settings->$setting;
1661 $syscontext = context_system::instance();
1663 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1665 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1666 // Note: unfortunately moodle_url does not support //urls yet.
1668 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1670 return $url;
1674 * Serve the theme setting file.
1676 * @param string $filearea
1677 * @param array $args
1678 * @param bool $forcedownload
1679 * @param array $options
1680 * @return bool may terminate if file not found or donotdie not specified
1682 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1683 global $CFG;
1684 require_once("$CFG->libdir/filelib.php");
1686 $syscontext = context_system::instance();
1687 $component = 'theme_'.$this->name;
1689 $revision = array_shift($args);
1690 if ($revision < 0) {
1691 $lifetime = 0;
1692 } else {
1693 $lifetime = 60*60*24*60;
1694 // By default, theme files must be cache-able by both browsers and proxies.
1695 if (!array_key_exists('cacheability', $options)) {
1696 $options['cacheability'] = 'public';
1700 $fs = get_file_storage();
1701 $relativepath = implode('/', $args);
1703 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1704 $fullpath = rtrim($fullpath, '/');
1705 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1706 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1707 return true;
1708 } else {
1709 send_file_not_found();
1714 * Resolves the real image location.
1716 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1717 * and we need a way in which to turn it off.
1718 * By default SVG won't be used unless asked for. This is done for two reasons:
1719 * 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
1720 * browser supports SVG.
1721 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1722 * by the user due to security concerns.
1724 * @param string $image name of image, may contain relative path
1725 * @param string $component
1726 * @param bool $svg If set to true SVG images will also be looked for.
1727 * @return string full file path
1729 public function resolve_image_location($image, $component, $svg = false) {
1730 global $CFG;
1732 if (!is_bool($svg)) {
1733 // If $svg isn't a bool then we need to decide for ourselves.
1734 $svg = $this->use_svg_icons();
1737 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1738 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1739 return $imagefile;
1741 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1742 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1743 return $imagefile;
1746 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1747 return $imagefile;
1749 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1750 return $imagefile;
1752 return null;
1754 } else if ($component === 'theme') { //exception
1755 if ($image === 'favicon') {
1756 return "$this->dir/pix/favicon.ico";
1758 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1759 return $imagefile;
1761 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1762 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1763 return $imagefile;
1766 return null;
1768 } else {
1769 if (strpos($component, '_') === false) {
1770 $component = 'mod_'.$component;
1772 list($type, $plugin) = explode('_', $component, 2);
1774 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1775 return $imagefile;
1777 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1778 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1779 return $imagefile;
1782 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1783 return $imagefile;
1785 $dir = core_component::get_plugin_directory($type, $plugin);
1786 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1787 return $imagefile;
1789 return null;
1794 * Resolves the real font location.
1796 * @param string $font name of font file
1797 * @param string $component
1798 * @return string full file path
1800 public function resolve_font_location($font, $component) {
1801 global $CFG;
1803 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1804 if (file_exists("$this->dir/fonts_core/$font")) {
1805 return "$this->dir/fonts_core/$font";
1807 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1808 if (file_exists("$parent_config->dir/fonts_core/$font")) {
1809 return "$parent_config->dir/fonts_core/$font";
1812 if (file_exists("$CFG->dataroot/fonts/$font")) {
1813 return "$CFG->dataroot/fonts/$font";
1815 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
1816 return "$CFG->dirroot/lib/fonts/$font";
1818 return null;
1820 } else if ($component === 'theme') { // Exception.
1821 if (file_exists("$this->dir/fonts/$font")) {
1822 return "$this->dir/fonts/$font";
1824 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1825 if (file_exists("$parent_config->dir/fonts/$font")) {
1826 return "$parent_config->dir/fonts/$font";
1829 return null;
1831 } else {
1832 if (strpos($component, '_') === false) {
1833 $component = 'mod_'.$component;
1835 list($type, $plugin) = explode('_', $component, 2);
1837 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
1838 return "$this->dir/fonts_plugins/$type/$plugin/$font";
1840 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1841 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
1842 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
1845 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
1846 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
1848 $dir = core_component::get_plugin_directory($type, $plugin);
1849 if (file_exists("$dir/fonts/$font")) {
1850 return "$dir/fonts/$font";
1852 return null;
1857 * Return true if we should look for SVG images as well.
1859 * @return bool
1861 public function use_svg_icons() {
1862 global $CFG;
1863 if ($this->usesvg === null) {
1865 if (!isset($CFG->svgicons)) {
1866 $this->usesvg = core_useragent::supports_svg();
1867 } else {
1868 // Force them on/off depending upon the setting.
1869 $this->usesvg = (bool)$CFG->svgicons;
1872 return $this->usesvg;
1876 * Forces the usesvg setting to either true or false, avoiding any decision making.
1878 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
1879 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
1881 * @param bool $setting True to force the use of svg when available, null otherwise.
1883 public function force_svg_use($setting) {
1884 $this->usesvg = (bool)$setting;
1888 * Set to be in RTL mode.
1890 * This will likely be used when post processing the CSS before serving it.
1892 * @param bool $inrtl True when in RTL mode.
1894 public function set_rtl_mode($inrtl = true) {
1895 $this->rtlmode = $inrtl;
1899 * Checks if file with any image extension exists.
1901 * The order to these images was adjusted prior to the release of 2.4
1902 * At that point the were the following image counts in Moodle core:
1904 * - png = 667 in pix dirs (1499 total)
1905 * - gif = 385 in pix dirs (606 total)
1906 * - jpg = 62 in pix dirs (74 total)
1907 * - jpeg = 0 in pix dirs (1 total)
1909 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1911 * @param string $filepath
1912 * @param bool $svg If set to true SVG images will also be looked for.
1913 * @return string image name with extension
1915 private static function image_exists($filepath, $svg = false) {
1916 if ($svg && file_exists("$filepath.svg")) {
1917 return "$filepath.svg";
1918 } else if (file_exists("$filepath.png")) {
1919 return "$filepath.png";
1920 } else if (file_exists("$filepath.gif")) {
1921 return "$filepath.gif";
1922 } else if (file_exists("$filepath.jpg")) {
1923 return "$filepath.jpg";
1924 } else if (file_exists("$filepath.jpeg")) {
1925 return "$filepath.jpeg";
1926 } else {
1927 return false;
1932 * Loads the theme config from config.php file.
1934 * @param string $themename
1935 * @param stdClass $settings from config_plugins table
1936 * @param boolean $parentscheck true to also check the parents. .
1937 * @return stdClass The theme configuration
1939 private static function find_theme_config($themename, $settings, $parentscheck = true) {
1940 // We have to use the variable name $THEME (upper case) because that
1941 // is what is used in theme config.php files.
1943 if (!$dir = theme_config::find_theme_location($themename)) {
1944 return null;
1947 $THEME = new stdClass();
1948 $THEME->name = $themename;
1949 $THEME->dir = $dir;
1950 $THEME->settings = $settings;
1952 global $CFG; // just in case somebody tries to use $CFG in theme config
1953 include("$THEME->dir/config.php");
1955 // verify the theme configuration is OK
1956 if (!is_array($THEME->parents)) {
1957 // parents option is mandatory now
1958 return null;
1959 } else {
1960 // We use $parentscheck to only check the direct parents (avoid infinite loop).
1961 if ($parentscheck) {
1962 // Find all parent theme configs.
1963 foreach ($THEME->parents as $parent) {
1964 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
1965 if (empty($parentconfig)) {
1966 return null;
1972 return $THEME;
1976 * Finds the theme location and verifies the theme has all needed files
1977 * and is not obsoleted.
1979 * @param string $themename
1980 * @return string full dir path or null if not found
1982 private static function find_theme_location($themename) {
1983 global $CFG;
1985 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1986 $dir = "$CFG->dirroot/theme/$themename";
1988 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1989 $dir = "$CFG->themedir/$themename";
1991 } else {
1992 return null;
1995 if (file_exists("$dir/styles.php")) {
1996 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1997 return null;
2000 return $dir;
2004 * Get the renderer for a part of Moodle for this theme.
2006 * @param moodle_page $page the page we are rendering
2007 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
2008 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
2009 * @param string $target one of rendering target constants
2010 * @return renderer_base the requested renderer.
2012 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
2013 if (is_null($this->rf)) {
2014 $classname = $this->rendererfactory;
2015 $this->rf = new $classname($this);
2018 return $this->rf->get_renderer($page, $component, $subtype, $target);
2022 * Get the information from {@link $layouts} for this type of page.
2024 * @param string $pagelayout the the page layout name.
2025 * @return array the appropriate part of {@link $layouts}.
2027 protected function layout_info_for_page($pagelayout) {
2028 if (array_key_exists($pagelayout, $this->layouts)) {
2029 return $this->layouts[$pagelayout];
2030 } else {
2031 debugging('Invalid page layout specified: ' . $pagelayout);
2032 return $this->layouts['standard'];
2037 * Given the settings of this theme, and the page pagelayout, return the
2038 * full path of the page layout file to use.
2040 * Used by {@link core_renderer::header()}.
2042 * @param string $pagelayout the the page layout name.
2043 * @return string Full path to the lyout file to use
2045 public function layout_file($pagelayout) {
2046 global $CFG;
2048 $layoutinfo = $this->layout_info_for_page($pagelayout);
2049 $layoutfile = $layoutinfo['file'];
2051 if (array_key_exists('theme', $layoutinfo)) {
2052 $themes = array($layoutinfo['theme']);
2053 } else {
2054 $themes = array_merge(array($this->name),$this->parents);
2057 foreach ($themes as $theme) {
2058 if ($dir = $this->find_theme_location($theme)) {
2059 $path = "$dir/layout/$layoutfile";
2061 // Check the template exists, return general base theme template if not.
2062 if (is_readable($path)) {
2063 return $path;
2068 debugging('Can not find layout file for: ' . $pagelayout);
2069 // fallback to standard normal layout
2070 return "$CFG->dirroot/theme/base/layout/general.php";
2074 * Returns auxiliary page layout options specified in layout configuration array.
2076 * @param string $pagelayout
2077 * @return array
2079 public function pagelayout_options($pagelayout) {
2080 $info = $this->layout_info_for_page($pagelayout);
2081 if (!empty($info['options'])) {
2082 return $info['options'];
2084 return array();
2088 * Inform a block_manager about the block regions this theme wants on this
2089 * page layout.
2091 * @param string $pagelayout the general type of the page.
2092 * @param block_manager $blockmanager the block_manger to set up.
2094 public function setup_blocks($pagelayout, $blockmanager) {
2095 $layoutinfo = $this->layout_info_for_page($pagelayout);
2096 if (!empty($layoutinfo['regions'])) {
2097 $blockmanager->add_regions($layoutinfo['regions'], false);
2098 $blockmanager->set_default_region($layoutinfo['defaultregion']);
2103 * Gets the visible name for the requested block region.
2105 * @param string $region The region name to get
2106 * @param string $theme The theme the region belongs to (may come from the parent theme)
2107 * @return string
2109 protected function get_region_name($region, $theme) {
2110 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
2111 // A name exists in this theme, so use it
2112 if (substr($regionstring, 0, 1) != '[') {
2113 return $regionstring;
2116 // Otherwise, try to find one elsewhere
2117 // Check parents, if any
2118 foreach ($this->parents as $parentthemename) {
2119 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
2120 if (substr($regionstring, 0, 1) != '[') {
2121 return $regionstring;
2125 // Last resort, try the bootstrapbase theme for names
2126 return get_string('region-' . $region, 'theme_bootstrapbase');
2130 * Get the list of all block regions known to this theme in all templates.
2132 * @return array internal region name => human readable name.
2134 public function get_all_block_regions() {
2135 $regions = array();
2136 foreach ($this->layouts as $layoutinfo) {
2137 foreach ($layoutinfo['regions'] as $region) {
2138 $regions[$region] = $this->get_region_name($region, $this->name);
2141 return $regions;
2145 * Returns the human readable name of the theme
2147 * @return string
2149 public function get_theme_name() {
2150 return get_string('pluginname', 'theme_'.$this->name);
2154 * Returns the block render method.
2156 * It is set by the theme via:
2157 * $THEME->blockrendermethod = '...';
2159 * It can be one of two values, blocks or blocks_for_region.
2160 * It should be set to the method being used by the theme layouts.
2162 * @return string
2164 public function get_block_render_method() {
2165 if ($this->blockrendermethod) {
2166 // Return the specified block render method.
2167 return $this->blockrendermethod;
2169 // Its not explicitly set, check the parent theme configs.
2170 foreach ($this->parent_configs as $config) {
2171 if (isset($config->blockrendermethod)) {
2172 return $config->blockrendermethod;
2175 // Default it to blocks.
2176 return 'blocks';
2181 * This class keeps track of which HTML tags are currently open.
2183 * This makes it much easier to always generate well formed XHTML output, even
2184 * if execution terminates abruptly. Any time you output some opening HTML
2185 * without the matching closing HTML, you should push the necessary close tags
2186 * onto the stack.
2188 * @copyright 2009 Tim Hunt
2189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2190 * @since Moodle 2.0
2191 * @package core
2192 * @category output
2194 class xhtml_container_stack {
2197 * @var array Stores the list of open containers.
2199 protected $opencontainers = array();
2202 * @var array In developer debug mode, stores a stack trace of all opens and
2203 * closes, so we can output helpful error messages when there is a mismatch.
2205 protected $log = array();
2208 * @var boolean Store whether we are developer debug mode. We need this in
2209 * several places including in the destructor where we may not have access to $CFG.
2211 protected $isdebugging;
2214 * Constructor
2216 public function __construct() {
2217 global $CFG;
2218 $this->isdebugging = $CFG->debugdeveloper;
2222 * Push the close HTML for a recently opened container onto the stack.
2224 * @param string $type The type of container. This is checked when {@link pop()}
2225 * is called and must match, otherwise a developer debug warning is output.
2226 * @param string $closehtml The HTML required to close the container.
2228 public function push($type, $closehtml) {
2229 $container = new stdClass;
2230 $container->type = $type;
2231 $container->closehtml = $closehtml;
2232 if ($this->isdebugging) {
2233 $this->log('Open', $type);
2235 array_push($this->opencontainers, $container);
2239 * Pop the HTML for the next closing container from the stack. The $type
2240 * must match the type passed when the container was opened, otherwise a
2241 * warning will be output.
2243 * @param string $type The type of container.
2244 * @return string the HTML required to close the container.
2246 public function pop($type) {
2247 if (empty($this->opencontainers)) {
2248 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2249 $this->output_log(), DEBUG_DEVELOPER);
2250 return;
2253 $container = array_pop($this->opencontainers);
2254 if ($container->type != $type) {
2255 debugging('<p>The type of container to be closed (' . $container->type .
2256 ') does not match the type of the next open container (' . $type .
2257 '). This suggests there is a nesting problem.</p>' .
2258 $this->output_log(), DEBUG_DEVELOPER);
2260 if ($this->isdebugging) {
2261 $this->log('Close', $type);
2263 return $container->closehtml;
2267 * Close all but the last open container. This is useful in places like error
2268 * handling, where you want to close all the open containers (apart from <body>)
2269 * before outputting the error message.
2271 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2272 * developer debug warning if it isn't.
2273 * @return string the HTML required to close any open containers inside <body>.
2275 public function pop_all_but_last($shouldbenone = false) {
2276 if ($shouldbenone && count($this->opencontainers) != 1) {
2277 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2278 $this->output_log(), DEBUG_DEVELOPER);
2280 $output = '';
2281 while (count($this->opencontainers) > 1) {
2282 $container = array_pop($this->opencontainers);
2283 $output .= $container->closehtml;
2285 return $output;
2289 * You can call this function if you want to throw away an instance of this
2290 * class without properly emptying the stack (for example, in a unit test).
2291 * Calling this method stops the destruct method from outputting a developer
2292 * debug warning. After calling this method, the instance can no longer be used.
2294 public function discard() {
2295 $this->opencontainers = null;
2299 * Adds an entry to the log.
2301 * @param string $action The name of the action
2302 * @param string $type The type of action
2304 protected function log($action, $type) {
2305 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
2306 format_backtrace(debug_backtrace()) . '</li>';
2310 * Outputs the log's contents as a HTML list.
2312 * @return string HTML list of the log
2314 protected function output_log() {
2315 return '<ul>' . implode("\n", $this->log) . '</ul>';