Merge branch 'MDL-56673-fix' of git://github.com/danpoltawski/moodle
[moodle.git] / lib / outputlib.php
blob4daeab811578cd247e9f8fffe5b89a89218403e8
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 return -1;
90 } else {
91 return $CFG->themerev;
94 } else {
95 return -1;
99 /**
100 * Checks if the given device has a theme defined in config.php.
102 * @return bool
104 function theme_is_device_locked($device) {
105 global $CFG;
106 $themeconfigname = core_useragent::get_device_type_cfg_var_name($device);
107 return isset($CFG->config_php_settings[$themeconfigname]);
111 * Returns the theme named defined in config.php for the given device.
113 * @return string or null
115 function theme_get_locked_theme_for_device($device) {
116 global $CFG;
118 if (!theme_is_device_locked($device)) {
119 return null;
122 $themeconfigname = core_useragent::get_device_type_cfg_var_name($device);
123 return $CFG->config_php_settings[$themeconfigname];
127 * This class represents the configuration variables of a Moodle theme.
129 * All the variables with access: public below (with a few exceptions that are marked)
130 * are the properties you can set in your themes config.php file.
132 * There are also some methods and protected variables that are part of the inner
133 * workings of Moodle's themes system. If you are just editing a themes config.php
134 * file, you can just ignore those, and the following information for developers.
136 * Normally, to create an instance of this class, you should use the
137 * {@link theme_config::load()} factory method to load a themes config.php file.
138 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
139 * will create one for you, accessible as $PAGE->theme.
141 * @copyright 2009 Tim Hunt
142 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
143 * @since Moodle 2.0
144 * @package core
145 * @category output
147 class theme_config {
150 * @var string Default theme, used when requested theme not found.
152 const DEFAULT_THEME = 'boost';
155 * @var array You can base your theme on other themes by linking to the other theme as
156 * parents. This lets you use the CSS and layouts from the other themes
157 * (see {@link theme_config::$layouts}).
158 * That makes it easy to create a new theme that is similar to another one
159 * but with a few changes. In this themes CSS you only need to override
160 * those rules you want to change.
162 public $parents;
165 * @var array The names of all the stylesheets from this theme that you would
166 * like included, in order. Give the names of the files without .css.
168 public $sheets = array();
171 * @var array The names of all the stylesheets from parents that should be excluded.
172 * true value may be used to specify all parents or all themes from one parent.
173 * If no value specified value from parent theme used.
175 public $parents_exclude_sheets = null;
178 * @var array List of plugin sheets to be excluded.
179 * If no value specified value from parent theme used.
181 public $plugins_exclude_sheets = null;
184 * @var array List of style sheets that are included in the text editor bodies.
185 * Sheets from parent themes are used automatically and can not be excluded.
187 public $editor_sheets = array();
190 * @var array The names of all the javascript files this theme that you would
191 * like included from head, in order. Give the names of the files without .js.
193 public $javascripts = array();
196 * @var array The names of all the javascript files this theme that you would
197 * like included from footer, in order. Give the names of the files without .js.
199 public $javascripts_footer = array();
202 * @var array The names of all the javascript files from parents that should
203 * be excluded. true value may be used to specify all parents or all themes
204 * from one parent.
205 * If no value specified value from parent theme used.
207 public $parents_exclude_javascripts = null;
210 * @var array Which file to use for each page layout.
212 * This is an array of arrays. The keys of the outer array are the different layouts.
213 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
214 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
215 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
216 * That file also has a good example of how to set this setting.
218 * For each layout, the value in the outer array is an array that describes
219 * how you want that type of page to look. For example
220 * <pre>
221 * $THEME->layouts = array(
222 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
223 * 'standard' => array(
224 * 'theme' = 'mytheme',
225 * 'file' => 'normal.php',
226 * 'regions' => array('side-pre', 'side-post'),
227 * 'defaultregion' => 'side-post'
228 * ),
229 * // The site home page.
230 * 'home' => array(
231 * 'theme' = 'mytheme',
232 * 'file' => 'home.php',
233 * 'regions' => array('side-pre', 'side-post'),
234 * 'defaultregion' => 'side-post'
235 * ),
236 * // ...
237 * );
238 * </pre>
240 * 'theme' name of the theme where is the layout located
241 * 'file' is the layout file to use for this type of page.
242 * layout files are stored in layout subfolder
243 * 'regions' This lists the regions on the page where blocks may appear. For
244 * each region you list here, your layout file must include a call to
245 * <pre>
246 * echo $OUTPUT->blocks_for_region($regionname);
247 * </pre>
248 * or equivalent so that the blocks are actually visible.
250 * 'defaultregion' If the list of regions is non-empty, then you must pick
251 * one of the one of them as 'default'. This has two meanings. First, this is
252 * where new blocks are added. Second, if there are any blocks associated with
253 * the page, but in non-existent regions, they appear here. (Imaging, for example,
254 * that someone added blocks using a different theme that used different region
255 * names, and then switched to this theme.)
257 public $layouts = array();
260 * @var string Name of the renderer factory class to use. Must implement the
261 * {@link renderer_factory} interface.
263 * This is an advanced feature. Moodle output is generated by 'renderers',
264 * you can customise the HTML that is output by writing custom renderers,
265 * and then you need to specify 'renderer factory' so that Moodle can find
266 * your renderers.
268 * There are some renderer factories supplied with Moodle. Please follow these
269 * links to see what they do.
270 * <ul>
271 * <li>{@link standard_renderer_factory} - the default.</li>
272 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
273 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
274 * </ul>
276 public $rendererfactory = 'standard_renderer_factory';
279 * @var string Function to do custom CSS post-processing.
281 * This is an advanced feature. If you want to do custom post-processing on the
282 * CSS before it is output (for example, to replace certain variable names
283 * with particular values) you can give the name of a function here.
285 public $csspostprocess = null;
288 * @var string Function to do custom CSS post-processing on a parsed CSS tree.
290 * This is an advanced feature. If you want to do custom post-processing on the
291 * CSS before it is output, you can provide the name of the function here. The
292 * function will receive a CSS tree document as first parameter, and the theme_config
293 * object as second parameter. A return value is not required, the tree can
294 * be edited in place.
296 public $csstreepostprocess = null;
299 * @var string Accessibility: Right arrow-like character is
300 * used in the breadcrumb trail, course navigation menu
301 * (previous/next activity), calendar, and search forum block.
302 * If the theme does not set characters, appropriate defaults
303 * are set automatically. Please DO NOT
304 * use &lt; &gt; &raquo; - these are confusing for blind users.
306 public $rarrow = null;
309 * @var string Accessibility: Left arrow-like character is
310 * used in the breadcrumb trail, course navigation menu
311 * (previous/next activity), calendar, and search forum block.
312 * If the theme does not set characters, appropriate defaults
313 * are set automatically. Please DO NOT
314 * use &lt; &gt; &raquo; - these are confusing for blind users.
316 public $larrow = null;
319 * @var string Accessibility: Up arrow-like character is used in
320 * the book heirarchical navigation.
321 * If the theme does not set characters, appropriate defaults
322 * are set automatically. Please DO NOT
323 * use ^ - this is confusing for blind users.
325 public $uarrow = null;
328 * @var string Accessibility: Down arrow-like character.
329 * If the theme does not set characters, appropriate defaults
330 * are set automatically.
332 public $darrow = null;
335 * @var bool Some themes may want to disable ajax course editing.
337 public $enablecourseajax = true;
340 * @var string Determines served document types
341 * - 'html5' the only officially supported doctype in Moodle
342 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
343 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
345 public $doctype = 'html5';
348 * @var string undeletableblocktypes If set to a string, will list the block types that cannot be deleted. Defaults to
349 * navigation and settings.
351 public $undeletableblocktypes = false;
353 //==Following properties are not configurable from theme config.php==
356 * @var string The name of this theme. Set automatically when this theme is
357 * loaded. This can not be set in theme config.php
359 public $name;
362 * @var string The folder where this themes files are stored. This is set
363 * automatically. This can not be set in theme config.php
365 public $dir;
368 * @var stdClass Theme settings stored in config_plugins table.
369 * This can not be set in theme config.php
371 public $setting = null;
374 * @var bool If set to true and the theme enables the dock then blocks will be able
375 * to be moved to the special dock
377 public $enable_dock = false;
380 * @var bool If set to true then this theme will not be shown in the theme selector unless
381 * theme designer mode is turned on.
383 public $hidefromselector = false;
386 * @var array list of YUI CSS modules to be included on each page. This may be used
387 * to remove cssreset and use cssnormalise module instead.
389 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
392 * An associative array of block manipulations that should be made if the user is using an rtl language.
393 * The key is the original block region, and the value is the block region to change to.
394 * This is used when displaying blocks for regions only.
395 * @var array
397 public $blockrtlmanipulations = array();
400 * @var renderer_factory Instance of the renderer_factory implementation
401 * we are using. Implementation detail.
403 protected $rf = null;
406 * @var array List of parent config objects.
408 protected $parent_configs = array();
411 * Used to determine whether we can serve SVG images or not.
412 * @var bool
414 private $usesvg = null;
417 * Whether in RTL mode or not.
418 * @var bool
420 protected $rtlmode = false;
423 * The LESS file to compile. When set, the theme will attempt to compile the file itself.
424 * @var bool
426 public $lessfile = false;
429 * The SCSS file to compile. This takes precedence over the LESS file.
430 * @var string
432 public $scssfile = false;
435 * The name of the function to call to get the LESS code to inject.
436 * @var string
438 public $extralesscallback = null;
441 * The name of the function to call to get the SCSS code to inject.
442 * @var string
444 public $extrascsscallback = null;
447 * The name of the function to call to get extra LESS variables.
448 * @var string
450 public $lessvariablescallback = null;
453 * The name of the function to call to get SCSS to prepend.
454 * @var string
456 public $prescsscallback = null;
459 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
460 * Defaults to {@link core_renderer::blocks_for_region()}
461 * @var string
463 public $blockrendermethod = null;
466 * Load the config.php file for a particular theme, and return an instance
467 * of this class. (That is, this is a factory method.)
469 * @param string $themename the name of the theme.
470 * @return theme_config an instance of this class.
472 public static function load($themename) {
473 global $CFG;
475 // load theme settings from db
476 try {
477 $settings = get_config('theme_'.$themename);
478 } catch (dml_exception $e) {
479 // most probably moodle tables not created yet
480 $settings = new stdClass();
483 if ($config = theme_config::find_theme_config($themename, $settings)) {
484 return new theme_config($config);
486 } else if ($themename == theme_config::DEFAULT_THEME) {
487 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
489 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
490 return new theme_config($config);
492 } else {
493 // bad luck, the requested theme has some problems - admin see details in theme config
494 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
499 * Theme diagnostic code. It is very problematic to send debug output
500 * to the actual CSS file, instead this functions is supposed to
501 * diagnose given theme and highlights all potential problems.
502 * This information should be available from the theme selection page
503 * or some other debug page for theme designers.
505 * @param string $themename
506 * @return array description of problems
508 public static function diagnose($themename) {
509 //TODO: MDL-21108
510 return array();
514 * Private constructor, can be called only from the factory method.
515 * @param stdClass $config
517 private function __construct($config) {
518 global $CFG; //needed for included lib.php files
520 $this->settings = $config->settings;
521 $this->name = $config->name;
522 $this->dir = $config->dir;
524 if ($this->name != 'bootstrapbase') {
525 $baseconfig = theme_config::find_theme_config('bootstrapbase', $this->settings);
526 } else {
527 $baseconfig = $config;
530 $configurable = array(
531 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets',
532 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
533 'layouts', 'enable_dock', 'enablecourseajax', 'undeletableblocktypes',
534 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'uarrow', 'darrow',
535 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations',
536 'lessfile', 'extralesscallback', 'lessvariablescallback', 'blockrendermethod',
537 'scssfile', 'extrascsscallback', 'prescsscallback', 'csstreepostprocessor');
539 foreach ($config as $key=>$value) {
540 if (in_array($key, $configurable)) {
541 $this->$key = $value;
545 // verify all parents and load configs and renderers
546 foreach ($this->parents as $parent) {
547 if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
548 // this is not good - better exclude faulty parents
549 continue;
551 $libfile = $parent_config->dir.'/lib.php';
552 if (is_readable($libfile)) {
553 // theme may store various function here
554 include_once($libfile);
556 $renderersfile = $parent_config->dir.'/renderers.php';
557 if (is_readable($renderersfile)) {
558 // may contain core and plugin renderers and renderer factory
559 include_once($renderersfile);
561 $this->parent_configs[$parent] = $parent_config;
563 $libfile = $this->dir.'/lib.php';
564 if (is_readable($libfile)) {
565 // theme may store various function here
566 include_once($libfile);
568 $rendererfile = $this->dir.'/renderers.php';
569 if (is_readable($rendererfile)) {
570 // may contain core and plugin renderers and renderer factory
571 include_once($rendererfile);
572 } else {
573 // check if renderers.php file is missnamed renderer.php
574 if (is_readable($this->dir.'/renderer.php')) {
575 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
576 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
580 // cascade all layouts properly
581 foreach ($baseconfig->layouts as $layout=>$value) {
582 if (!isset($this->layouts[$layout])) {
583 foreach ($this->parent_configs as $parent_config) {
584 if (isset($parent_config->layouts[$layout])) {
585 $this->layouts[$layout] = $parent_config->layouts[$layout];
586 continue 2;
589 $this->layouts[$layout] = $value;
593 //fix arrows if needed
594 $this->check_theme_arrows();
598 * Let the theme initialise the page object (usually $PAGE).
600 * This may be used for example to request jQuery in add-ons.
602 * @param moodle_page $page
604 public function init_page(moodle_page $page) {
605 $themeinitfunction = 'theme_'.$this->name.'_page_init';
606 if (function_exists($themeinitfunction)) {
607 $themeinitfunction($page);
612 * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow, $THEME->darrow have been set (theme/-/config.php).
613 * If not it applies sensible defaults.
615 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
616 * search forum block, etc. Important: these are 'silent' in a screen-reader
617 * (unlike &gt; &raquo;), and must be accompanied by text.
619 private function check_theme_arrows() {
620 if (!isset($this->rarrow) and !isset($this->larrow)) {
621 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
622 // Also OK in Win 9x/2K/IE 5.x
623 $this->rarrow = '&#x25BA;';
624 $this->larrow = '&#x25C4;';
625 $this->uarrow = '&#x25B2;';
626 $this->darrow = '&#x25BC;';
627 if (empty($_SERVER['HTTP_USER_AGENT'])) {
628 $uagent = '';
629 } else {
630 $uagent = $_SERVER['HTTP_USER_AGENT'];
632 if (false !== strpos($uagent, 'Opera')
633 || false !== strpos($uagent, 'Mac')) {
634 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
635 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
636 $this->rarrow = '&#x25B6;&#xFE0E;';
637 $this->larrow = '&#x25C0;&#xFE0E;';
639 elseif ((false !== strpos($uagent, 'Konqueror'))
640 || (false !== strpos($uagent, 'Android'))) {
641 // The fonts on Android don't include the characters required for this to work as expected.
642 // So we use the same ones Konqueror uses.
643 $this->rarrow = '&rarr;';
644 $this->larrow = '&larr;';
645 $this->uarrow = '&uarr;';
646 $this->darrow = '&darr;';
648 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
649 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
650 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
651 // To be safe, non-Unicode browsers!
652 $this->rarrow = '&gt;';
653 $this->larrow = '&lt;';
654 $this->uarrow = '^';
655 $this->darrow = 'v';
658 // RTL support - in RTL languages, swap r and l arrows
659 if (right_to_left()) {
660 $t = $this->rarrow;
661 $this->rarrow = $this->larrow;
662 $this->larrow = $t;
668 * Returns output renderer prefixes, these are used when looking
669 * for the overridden renderers in themes.
671 * @return array
673 public function renderer_prefixes() {
674 global $CFG; // just in case the included files need it
676 $prefixes = array('theme_'.$this->name);
678 foreach ($this->parent_configs as $parent) {
679 $prefixes[] = 'theme_'.$parent->name;
682 return $prefixes;
686 * Returns the stylesheet URL of this editor content
688 * @param bool $encoded false means use & and true use &amp; in URLs
689 * @return moodle_url
691 public function editor_css_url($encoded=true) {
692 global $CFG;
693 $rev = theme_get_revision();
694 if ($rev > -1) {
695 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
696 if (!empty($CFG->slasharguments)) {
697 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
698 } else {
699 $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
701 } else {
702 $params = array('theme'=>$this->name, 'type'=>'editor');
703 $url = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
705 return $url;
709 * Returns the content of the CSS to be used in editor content
711 * @return array
713 public function editor_css_files() {
714 $files = array();
716 // First editor plugins.
717 $plugins = core_component::get_plugin_list('editor');
718 foreach ($plugins as $plugin=>$fulldir) {
719 $sheetfile = "$fulldir/editor_styles.css";
720 if (is_readable($sheetfile)) {
721 $files['plugin_'.$plugin] = $sheetfile;
724 // Then parent themes - base first, the immediate parent last.
725 foreach (array_reverse($this->parent_configs) as $parent_config) {
726 if (empty($parent_config->editor_sheets)) {
727 continue;
729 foreach ($parent_config->editor_sheets as $sheet) {
730 $sheetfile = "$parent_config->dir/style/$sheet.css";
731 if (is_readable($sheetfile)) {
732 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
736 // Finally this theme.
737 if (!empty($this->editor_sheets)) {
738 foreach ($this->editor_sheets as $sheet) {
739 $sheetfile = "$this->dir/style/$sheet.css";
740 if (is_readable($sheetfile)) {
741 $files['theme_'.$sheet] = $sheetfile;
746 return $files;
750 * Get the stylesheet URL of this theme.
752 * @param moodle_page $page Not used... deprecated?
753 * @return moodle_url[]
755 public function css_urls(moodle_page $page) {
756 global $CFG;
758 $rev = theme_get_revision();
760 $urls = array();
762 $svg = $this->use_svg_icons();
763 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
765 if ($rev > -1) {
766 $filename = right_to_left() ? 'all-rtl' : 'all';
767 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
768 if (!empty($CFG->slasharguments)) {
769 $slashargs = '';
770 if (!$svg) {
771 // We add a simple /_s to the start of the path.
772 // The underscore is used to ensure that it isn't a valid theme name.
773 $slashargs .= '/_s'.$slashargs;
775 $slashargs .= '/'.$this->name.'/'.$rev.'/'.$filename;
776 if ($separate) {
777 $slashargs .= '/chunk0';
779 $url->set_slashargument($slashargs, 'noparam', true);
780 } else {
781 $params = array('theme' => $this->name, 'rev' => $rev, 'type' => $filename);
782 if (!$svg) {
783 // We add an SVG param so that we know not to serve SVG images.
784 // We do this because all modern browsers support SVG and this param will one day be removed.
785 $params['svg'] = '0';
787 if ($separate) {
788 $params['chunk'] = '0';
790 $url->params($params);
792 $urls[] = $url;
794 } else {
795 $baseurl = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php');
797 $css = $this->get_css_files(true);
798 if (!$svg) {
799 // We add an SVG param so that we know not to serve SVG images.
800 // We do this because all modern browsers support SVG and this param will one day be removed.
801 $baseurl->param('svg', '0');
803 if (right_to_left()) {
804 $baseurl->param('rtl', 1);
806 if ($separate) {
807 // We might need to chunk long files.
808 $baseurl->param('chunk', '0');
810 if (core_useragent::is_ie()) {
811 // Lalala, IE does not allow more than 31 linked CSS files from main document.
812 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
813 foreach ($css['parents'] as $parent=>$sheets) {
814 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
815 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
817 if (!empty($this->scssfile)) {
818 // No need to define the type as IE here.
819 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
820 } else if (!empty($this->lessfile)) {
821 // No need to define the type as IE here.
822 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
824 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
826 } else {
827 foreach ($css['plugins'] as $plugin=>$unused) {
828 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
830 foreach ($css['parents'] as $parent=>$sheets) {
831 foreach ($sheets as $sheet=>$unused2) {
832 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
835 foreach ($css['theme'] as $sheet => $filename) {
836 if ($sheet === $this->scssfile) {
837 // This is the theme SCSS file.
838 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
839 } else if ($sheet === $this->lessfile) {
840 // This is the theme LESS file.
841 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
842 } else {
843 // Sheet first in order to make long urls easier to read.
844 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
850 return $urls;
854 * Get the whole css stylesheet for production mode.
856 * NOTE: this method is not expected to be used from any addons.
858 * @return string CSS markup compressed
860 public function get_css_content() {
862 $csscontent = '';
863 foreach ($this->get_css_files(false) as $type => $value) {
864 foreach ($value as $identifier => $val) {
865 if (is_array($val)) {
866 foreach ($val as $v) {
867 $csscontent .= file_get_contents($v) . "\n";
869 } else {
870 if ($type === 'theme' && $identifier === $this->scssfile) {
871 // We need the content from SCSS because this is the SCSS file from the theme.
872 $csscontent .= $this->get_css_content_from_scss(false);
873 } else if ($type === 'theme' && $identifier === $this->lessfile) {
874 // We need the content from LESS because this is the LESS file from the theme.
875 $csscontent .= $this->get_css_content_from_less(false);
876 } else {
877 $csscontent .= file_get_contents($val) . "\n";
882 $csscontent = $this->post_process($csscontent);
883 $csscontent = core_minify::css($csscontent);
885 return $csscontent;
889 * Get the theme designer css markup,
890 * the parameters are coming from css_urls().
892 * NOTE: this method is not expected to be used from any addons.
894 * @param string $type
895 * @param string $subtype
896 * @param string $sheet
897 * @return string CSS markup
899 public function get_css_content_debug($type, $subtype, $sheet) {
901 if ($type === 'scss') {
902 // The SCSS file of the theme is requested.
903 $csscontent = $this->get_css_content_from_scss(true);
904 if ($csscontent !== false) {
905 return $this->post_process($csscontent);
907 return '';
908 } else if ($type === 'less') {
909 // The LESS file of the theme is requested.
910 $csscontent = $this->get_css_content_from_less(true);
911 if ($csscontent !== false) {
912 return $this->post_process($csscontent);
914 return '';
917 $cssfiles = array();
918 $css = $this->get_css_files(true);
920 if ($type === 'ie') {
921 // IE is a sloppy browser with weird limits, sorry.
922 if ($subtype === 'plugins') {
923 $cssfiles = $css['plugins'];
925 } else if ($subtype === 'parents') {
926 if (empty($sheet)) {
927 // Do not bother with the empty parent here.
928 } else {
929 // Build up the CSS for that parent so we can serve it as one file.
930 foreach ($css[$subtype][$sheet] as $parent => $css) {
931 $cssfiles[] = $css;
934 } else if ($subtype === 'theme') {
935 $cssfiles = $css['theme'];
936 foreach ($cssfiles as $key => $value) {
937 if (in_array($key, [$this->lessfile, $this->scssfile])) {
938 // Remove the LESS/SCSS file from the theme CSS files.
939 // The LESS/SCSS files use the type 'less' or 'scss', not 'ie'.
940 unset($cssfiles[$key]);
945 } else if ($type === 'plugin') {
946 if (isset($css['plugins'][$subtype])) {
947 $cssfiles[] = $css['plugins'][$subtype];
950 } else if ($type === 'parent') {
951 if (isset($css['parents'][$subtype][$sheet])) {
952 $cssfiles[] = $css['parents'][$subtype][$sheet];
955 } else if ($type === 'theme') {
956 if (isset($css['theme'][$sheet])) {
957 $cssfiles[] = $css['theme'][$sheet];
961 $csscontent = '';
962 foreach ($cssfiles as $file) {
963 $contents = file_get_contents($file);
964 $contents = $this->post_process($contents);
965 $comment = "/** Path: $type $subtype $sheet.' **/\n";
966 $stats = '';
967 $csscontent .= $comment.$stats.$contents."\n\n";
970 return $csscontent;
974 * Get the whole css stylesheet for editor iframe.
976 * NOTE: this method is not expected to be used from any addons.
978 * @return string CSS markup
980 public function get_css_content_editor() {
981 // Do not bother to optimise anything here, just very basic stuff.
982 $cssfiles = $this->editor_css_files();
983 $css = '';
984 foreach ($cssfiles as $file) {
985 $css .= file_get_contents($file)."\n";
987 return $this->post_process($css);
991 * Returns an array of organised CSS files required for this output.
993 * @param bool $themedesigner
994 * @return array nested array of file paths
996 protected function get_css_files($themedesigner) {
997 global $CFG;
999 $cache = null;
1000 $cachekey = 'cssfiles';
1001 if ($themedesigner) {
1002 require_once($CFG->dirroot.'/lib/csslib.php');
1003 // We need some kind of caching here because otherwise the page navigation becomes
1004 // way too slow in theme designer mode. Feel free to create full cache definition later...
1005 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
1006 if ($files = $cache->get($cachekey)) {
1007 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
1008 unset($files['created']);
1009 return $files;
1014 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
1016 // Get all plugin sheets.
1017 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
1018 if ($excludes !== true) {
1019 foreach (core_component::get_plugin_types() as $type=>$unused) {
1020 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
1021 continue;
1023 $plugins = core_component::get_plugin_list($type);
1024 foreach ($plugins as $plugin=>$fulldir) {
1025 if (!empty($excludes[$type]) and is_array($excludes[$type])
1026 and in_array($plugin, $excludes[$type])) {
1027 continue;
1030 // Get the CSS from the plugin.
1031 $sheetfile = "$fulldir/styles.css";
1032 if (is_readable($sheetfile)) {
1033 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
1036 // Create a list of candidate sheets from parents (direct parent last) and current theme.
1037 $candidates = array();
1038 foreach (array_reverse($this->parent_configs) as $parent_config) {
1039 $candidates[] = $parent_config->name;
1041 $candidates[] = $this->name;
1043 // Add the sheets found.
1044 foreach ($candidates as $candidate) {
1045 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1046 if (is_readable($sheetthemefile)) {
1047 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
1054 // Find out wanted parent sheets.
1055 $excludes = $this->resolve_excludes('parents_exclude_sheets');
1056 if ($excludes !== true) {
1057 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1058 $parent = $parent_config->name;
1059 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
1060 continue;
1062 foreach ($parent_config->sheets as $sheet) {
1063 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1064 && in_array($sheet, $excludes[$parent])) {
1065 continue;
1068 // We never refer to the parent LESS files.
1069 $sheetfile = "$parent_config->dir/style/$sheet.css";
1070 if (is_readable($sheetfile)) {
1071 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1077 // Current theme sheets and less file.
1078 // We first add the SCSS, or LESS file because we want the CSS ones to
1079 // be included after the SCSS/LESS code. However, if both the SCSS/LESS file
1080 // and a CSS file share the same name, the CSS file is ignored.
1081 if (!empty($this->scssfile)) {
1082 $sheetfile = "{$this->dir}/scss/{$this->scssfile}.scss";
1083 if (is_readable($sheetfile)) {
1084 $cssfiles['theme'][$this->scssfile] = $sheetfile;
1086 } else if (!empty($this->lessfile)) {
1087 $sheetfile = "{$this->dir}/less/{$this->lessfile}.less";
1088 if (is_readable($sheetfile)) {
1089 $cssfiles['theme'][$this->lessfile] = $sheetfile;
1092 if (is_array($this->sheets)) {
1093 foreach ($this->sheets as $sheet) {
1094 $sheetfile = "$this->dir/style/$sheet.css";
1095 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1096 $cssfiles['theme'][$sheet] = $sheetfile;
1101 if ($cache) {
1102 $files = $cssfiles;
1103 $files['created'] = time();
1104 $cache->set($cachekey, $files);
1106 return $cssfiles;
1110 * Return the CSS content generated from LESS the file.
1112 * @param bool $themedesigner True if theme designer is enabled.
1113 * @return bool|string Return false when the compilation failed. Else the compiled string.
1115 protected function get_css_content_from_less($themedesigner) {
1116 global $CFG;
1118 $lessfile = $this->lessfile;
1119 if (!$lessfile || !is_readable($this->dir . '/less/' . $lessfile . '.less')) {
1120 throw new coding_exception('The theme did not define a LESS file, or it is not readable.');
1123 // We might need more memory to do this, so let's play safe.
1124 raise_memory_limit(MEMORY_EXTRA);
1126 // Files list.
1127 $files = $this->get_css_files($themedesigner);
1129 // Get the LESS file path.
1130 $themelessfile = $files['theme'][$lessfile];
1132 // Setup compiler options.
1133 $options = array(
1134 // We need to set the import directory to where $lessfile is.
1135 'import_dirs' => array(dirname($themelessfile) => '/'),
1136 // Always disable default caching.
1137 'cache_method' => false,
1138 // Disable the relative URLs, we have post_process() to handle that.
1139 'relativeUrls' => false,
1142 if ($themedesigner) {
1143 // Add the sourceMap inline to ensure that it is atomically generated.
1144 $options['sourceMap'] = true;
1145 $options['sourceMapBasepath'] = $CFG->dirroot;
1146 $options['sourceMapRootpath'] = $CFG->wwwroot;
1149 // Instantiate the compiler.
1150 $compiler = new core_lessc($options);
1152 try {
1153 $compiler->parse_file_content($themelessfile);
1155 // Get the callbacks.
1156 $compiler->parse($this->get_extra_less_code());
1157 $compiler->ModifyVars($this->get_less_variables());
1159 // Compile the CSS.
1160 $compiled = $compiler->getCss();
1162 } catch (Less_Exception_Parser $e) {
1163 $compiled = false;
1164 debugging('Error while compiling LESS ' . $lessfile . ' file: ' . $e->getMessage(), DEBUG_DEVELOPER);
1167 // Try to save memory.
1168 $compiler = null;
1169 unset($compiler);
1171 return $compiled;
1175 * Return the CSS content generated from the SCSS file.
1177 * @param bool $themedesigner True if theme designer is enabled.
1178 * @return bool|string Return false when the compilation failed. Else the compiled string.
1180 protected function get_css_content_from_scss($themedesigner) {
1181 global $CFG;
1183 $scssfile = $this->scssfile;
1184 if (!$scssfile || !is_readable($this->dir . '/scss/' . $scssfile . '.scss')) {
1185 throw new coding_exception('The theme did not define a SCSS file, or it is not readable.');
1188 // We might need more memory to do this, so let's play safe.
1189 raise_memory_limit(MEMORY_EXTRA);
1191 // Files list.
1192 $files = $this->get_css_files($themedesigner);
1194 // Get the SCSS file path.
1195 $themescssfile = $files['theme'][$scssfile];
1197 // Set-up the compiler.
1198 $compiler = new core_scss();
1199 $compiler->prepend_raw_scss($this->get_pre_scss_code());
1200 $compiler->set_file($themescssfile);
1201 $compiler->append_raw_scss($this->get_extra_scss_code());
1203 try {
1204 // Compile!
1205 $compiled = $compiler->to_css();
1207 } catch (\Leafo\ScssPhp\Exception $e) {
1208 $compiled = false;
1209 debugging('Error while compiling SCSS ' . $scssfile . ' file: ' . $e->getMessage(), DEBUG_DEVELOPER);
1212 // Try to save memory.
1213 $compiler = null;
1214 unset($compiler);
1216 return $compiled;
1220 * Return extra LESS variables to use when compiling.
1222 * @return array Where keys are the variable names (omitting the @), and the values are the value.
1224 protected function get_less_variables() {
1225 $variables = array();
1227 // Getting all the candidate functions.
1228 $candidates = array();
1229 foreach ($this->parent_configs as $parent_config) {
1230 if (!isset($parent_config->lessvariablescallback)) {
1231 continue;
1233 $candidates[] = $parent_config->lessvariablescallback;
1235 $candidates[] = $this->lessvariablescallback;
1237 // Calling the functions.
1238 foreach ($candidates as $function) {
1239 if (function_exists($function)) {
1240 $vars = $function($this);
1241 if (!is_array($vars)) {
1242 debugging('Callback ' . $function . ' did not return an array() as expected', DEBUG_DEVELOPER);
1243 continue;
1245 $variables = array_merge($variables, $vars);
1249 return $variables;
1253 * Return extra LESS code to add when compiling.
1255 * This is intended to be used by themes to inject some LESS code
1256 * before it gets compiled. If you want to inject variables you
1257 * should use {@link self::get_less_variables()}.
1259 * @return string The LESS code to inject.
1261 protected function get_extra_less_code() {
1262 $content = '';
1264 // Getting all the candidate functions.
1265 $candidates = array();
1266 foreach ($this->parent_configs as $parent_config) {
1267 if (!isset($parent_config->extralesscallback)) {
1268 continue;
1270 $candidates[] = $parent_config->extralesscallback;
1272 $candidates[] = $this->extralesscallback;
1274 // Calling the functions.
1275 foreach ($candidates as $function) {
1276 if (function_exists($function)) {
1277 $content .= "\n/** Extra LESS from $function **/\n" . $function($this) . "\n";
1281 return $content;
1285 * Return extra SCSS code to add when compiling.
1287 * This is intended to be used by themes to inject some SCSS code
1288 * before it gets compiled. If you want to inject variables you
1289 * should use {@link self::get_scss_variables()}.
1291 * @return string The SCSS code to inject.
1293 protected function get_extra_scss_code() {
1294 $content = '';
1296 // Getting all the candidate functions.
1297 $candidates = array();
1298 foreach ($this->parent_configs as $parent_config) {
1299 if (!isset($parent_config->extrascsscallback)) {
1300 continue;
1302 $candidates[] = $parent_config->extrascsscallback;
1304 $candidates[] = $this->extrascsscallback;
1306 // Calling the functions.
1307 foreach ($candidates as $function) {
1308 if (function_exists($function)) {
1309 $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n";
1313 return $content;
1317 * SCSS code to prepend when compiling.
1319 * This is intended to be used by themes to inject SCSS code before it gets compiled.
1321 * @return string The SCSS code to inject.
1323 protected function get_pre_scss_code() {
1324 $content = '';
1326 // Getting all the candidate functions.
1327 $candidates = array();
1328 foreach ($this->parent_configs as $parent_config) {
1329 if (!isset($parent_config->prescsscallback)) {
1330 continue;
1332 $candidates[] = $parent_config->prescsscallback;
1334 $candidates[] = $this->prescsscallback;
1336 // Calling the functions.
1337 foreach ($candidates as $function) {
1338 if (function_exists($function)) {
1339 $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n";
1343 return $content;
1347 * Generate a URL to the file that serves theme JavaScript files.
1349 * If we determine that the theme has no relevant files, then we return
1350 * early with a null value.
1352 * @param bool $inhead true means head url, false means footer
1353 * @return moodle_url|null
1355 public function javascript_url($inhead) {
1356 global $CFG;
1358 $rev = theme_get_revision();
1359 $params = array('theme'=>$this->name,'rev'=>$rev);
1360 $params['type'] = $inhead ? 'head' : 'footer';
1362 // Return early if there are no files to serve
1363 if (count($this->javascript_files($params['type'])) === 0) {
1364 return null;
1367 if (!empty($CFG->slasharguments) and $rev > 0) {
1368 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
1369 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
1370 return $url;
1371 } else {
1372 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
1377 * Get the URL's for the JavaScript files used by this theme.
1378 * They won't be served directly, instead they'll be mediated through
1379 * theme/javascript.php.
1381 * @param string $type Either javascripts_footer, or javascripts
1382 * @return array
1384 public function javascript_files($type) {
1385 if ($type === 'footer') {
1386 $type = 'javascripts_footer';
1387 } else {
1388 $type = 'javascripts';
1391 $js = array();
1392 // find out wanted parent javascripts
1393 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1394 if ($excludes !== true) {
1395 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1396 $parent = $parent_config->name;
1397 if (empty($parent_config->$type)) {
1398 continue;
1400 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1401 continue;
1403 foreach ($parent_config->$type as $javascript) {
1404 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1405 and in_array($javascript, $excludes[$parent])) {
1406 continue;
1408 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1409 if (is_readable($javascriptfile)) {
1410 $js[] = $javascriptfile;
1416 // current theme javascripts
1417 if (is_array($this->$type)) {
1418 foreach ($this->$type as $javascript) {
1419 $javascriptfile = "$this->dir/javascript/$javascript.js";
1420 if (is_readable($javascriptfile)) {
1421 $js[] = $javascriptfile;
1425 return $js;
1429 * Resolves an exclude setting to the themes setting is applicable or the
1430 * setting of its closest parent.
1432 * @param string $variable The name of the setting the exclude setting to resolve
1433 * @param string $default
1434 * @return mixed
1436 protected function resolve_excludes($variable, $default = null) {
1437 $setting = $default;
1438 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1439 $setting = $this->{$variable};
1440 } else {
1441 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1442 if (!isset($parent_config->{$variable})) {
1443 continue;
1445 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1446 $setting = $parent_config->{$variable};
1447 break;
1451 return $setting;
1455 * Returns the content of the one huge javascript file merged from all theme javascript files.
1457 * @param bool $type
1458 * @return string
1460 public function javascript_content($type) {
1461 $jsfiles = $this->javascript_files($type);
1462 $js = '';
1463 foreach ($jsfiles as $jsfile) {
1464 $js .= file_get_contents($jsfile)."\n";
1466 return $js;
1470 * Post processes CSS.
1472 * This method post processes all of the CSS before it is served for this theme.
1473 * This is done so that things such as image URL's can be swapped in and to
1474 * run any specific CSS post process method the theme has requested.
1475 * This allows themes to use CSS settings.
1477 * @param string $css The CSS to process.
1478 * @return string The processed CSS.
1480 public function post_process($css) {
1481 // now resolve all image locations
1482 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1483 $replaced = array();
1484 foreach ($matches as $match) {
1485 if (isset($replaced[$match[0]])) {
1486 continue;
1488 $replaced[$match[0]] = true;
1489 $imagename = $match[2];
1490 $component = rtrim($match[1], '|');
1491 $imageurl = $this->pix_url($imagename, $component)->out(false);
1492 // we do not need full url because the image.php is always in the same dir
1493 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1494 $css = str_replace($match[0], $imageurl, $css);
1498 // Now resolve all font locations.
1499 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1500 $replaced = array();
1501 foreach ($matches as $match) {
1502 if (isset($replaced[$match[0]])) {
1503 continue;
1505 $replaced[$match[0]] = true;
1506 $fontname = $match[2];
1507 $component = rtrim($match[1], '|');
1508 $fonturl = $this->font_url($fontname, $component)->out(false);
1509 // We do not need full url because the font.php is always in the same dir.
1510 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1511 $css = str_replace($match[0], $fonturl, $css);
1515 // Post processing using an object representation of CSS.
1516 $hastreeprocessor = !empty($this->csstreepostprocessor) && function_exists($this->csstreepostprocessor);
1517 $needsparsing = $hastreeprocessor || !empty($this->rtlmode);
1518 if ($needsparsing) {
1519 $parser = new core_cssparser($css);
1520 $csstree = $parser->parse();
1521 unset($parser);
1523 if ($this->rtlmode) {
1524 $this->rtlize($csstree);
1527 if ($hastreeprocessor) {
1528 $fn = $this->csstreepostprocessor;
1529 $fn($csstree, $this);
1532 $css = $csstree->render();
1533 unset($csstree);
1536 // now resolve all theme settings or do any other postprocessing
1537 $csspostprocess = $this->csspostprocess;
1538 if (function_exists($csspostprocess)) {
1539 $css = $csspostprocess($css, $this);
1542 return $css;
1546 * Flip a stylesheet to RTL.
1548 * @param Object $csstree The parsed CSS tree structure to flip.
1549 * @return void
1551 protected function rtlize($csstree) {
1552 $rtlcss = new core_rtlcss($csstree);
1553 $rtlcss->flip();
1557 * Return the URL for an image
1559 * @param string $imagename the name of the icon.
1560 * @param string $component specification of one plugin like in get_string()
1561 * @return moodle_url
1563 public function pix_url($imagename, $component) {
1564 global $CFG;
1566 $params = array('theme'=>$this->name);
1567 $svg = $this->use_svg_icons();
1569 if (empty($component) or $component === 'moodle' or $component === 'core') {
1570 $params['component'] = 'core';
1571 } else {
1572 $params['component'] = $component;
1575 $rev = theme_get_revision();
1576 if ($rev != -1) {
1577 $params['rev'] = $rev;
1580 $params['image'] = $imagename;
1582 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1583 if (!empty($CFG->slasharguments) and $rev > 0) {
1584 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1585 if (!$svg) {
1586 // We add a simple /_s to the start of the path.
1587 // The underscore is used to ensure that it isn't a valid theme name.
1588 $path = '/_s'.$path;
1590 $url->set_slashargument($path, 'noparam', true);
1591 } else {
1592 if (!$svg) {
1593 // We add an SVG param so that we know not to serve SVG images.
1594 // We do this because all modern browsers support SVG and this param will one day be removed.
1595 $params['svg'] = '0';
1597 $url->params($params);
1600 return $url;
1604 * Return the URL for a font
1606 * @param string $font the name of the font (including extension).
1607 * @param string $component specification of one plugin like in get_string()
1608 * @return moodle_url
1610 public function font_url($font, $component) {
1611 global $CFG;
1613 $params = array('theme'=>$this->name);
1615 if (empty($component) or $component === 'moodle' or $component === 'core') {
1616 $params['component'] = 'core';
1617 } else {
1618 $params['component'] = $component;
1621 $rev = theme_get_revision();
1622 if ($rev != -1) {
1623 $params['rev'] = $rev;
1626 $params['font'] = $font;
1628 $url = new moodle_url("$CFG->httpswwwroot/theme/font.php");
1629 if (!empty($CFG->slasharguments) and $rev > 0) {
1630 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1631 $url->set_slashargument($path, 'noparam', true);
1632 } else {
1633 $url->params($params);
1636 return $url;
1640 * Returns URL to the stored file via pluginfile.php.
1642 * Note the theme must also implement pluginfile.php handler,
1643 * theme revision is used instead of the itemid.
1645 * @param string $setting
1646 * @param string $filearea
1647 * @return string protocol relative URL or null if not present
1649 public function setting_file_url($setting, $filearea) {
1650 global $CFG;
1652 if (empty($this->settings->$setting)) {
1653 return null;
1656 $component = 'theme_'.$this->name;
1657 $itemid = theme_get_revision();
1658 $filepath = $this->settings->$setting;
1659 $syscontext = context_system::instance();
1661 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1663 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1664 // Note: unfortunately moodle_url does not support //urls yet.
1666 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1668 return $url;
1672 * Serve the theme setting file.
1674 * @param string $filearea
1675 * @param array $args
1676 * @param bool $forcedownload
1677 * @param array $options
1678 * @return bool may terminate if file not found or donotdie not specified
1680 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1681 global $CFG;
1682 require_once("$CFG->libdir/filelib.php");
1684 $syscontext = context_system::instance();
1685 $component = 'theme_'.$this->name;
1687 $revision = array_shift($args);
1688 if ($revision < 0) {
1689 $lifetime = 0;
1690 } else {
1691 $lifetime = 60*60*24*60;
1692 // By default, theme files must be cache-able by both browsers and proxies.
1693 if (!array_key_exists('cacheability', $options)) {
1694 $options['cacheability'] = 'public';
1698 $fs = get_file_storage();
1699 $relativepath = implode('/', $args);
1701 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1702 $fullpath = rtrim($fullpath, '/');
1703 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1704 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1705 return true;
1706 } else {
1707 send_file_not_found();
1712 * Resolves the real image location.
1714 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1715 * and we need a way in which to turn it off.
1716 * By default SVG won't be used unless asked for. This is done for two reasons:
1717 * 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
1718 * browser supports SVG.
1719 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1720 * by the user due to security concerns.
1722 * @param string $image name of image, may contain relative path
1723 * @param string $component
1724 * @param bool $svg If set to true SVG images will also be looked for.
1725 * @return string full file path
1727 public function resolve_image_location($image, $component, $svg = false) {
1728 global $CFG;
1730 if (!is_bool($svg)) {
1731 // If $svg isn't a bool then we need to decide for ourselves.
1732 $svg = $this->use_svg_icons();
1735 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1736 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1737 return $imagefile;
1739 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1740 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1741 return $imagefile;
1744 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1745 return $imagefile;
1747 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1748 return $imagefile;
1750 return null;
1752 } else if ($component === 'theme') { //exception
1753 if ($image === 'favicon') {
1754 return "$this->dir/pix/favicon.ico";
1756 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1757 return $imagefile;
1759 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1760 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1761 return $imagefile;
1764 return null;
1766 } else {
1767 if (strpos($component, '_') === false) {
1768 $component = 'mod_'.$component;
1770 list($type, $plugin) = explode('_', $component, 2);
1772 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1773 return $imagefile;
1775 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1776 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1777 return $imagefile;
1780 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1781 return $imagefile;
1783 $dir = core_component::get_plugin_directory($type, $plugin);
1784 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1785 return $imagefile;
1787 return null;
1792 * Resolves the real font location.
1794 * @param string $font name of font file
1795 * @param string $component
1796 * @return string full file path
1798 public function resolve_font_location($font, $component) {
1799 global $CFG;
1801 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1802 if (file_exists("$this->dir/fonts_core/$font")) {
1803 return "$this->dir/fonts_core/$font";
1805 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1806 if (file_exists("$parent_config->dir/fonts_core/$font")) {
1807 return "$parent_config->dir/fonts_core/$font";
1810 if (file_exists("$CFG->dataroot/fonts/$font")) {
1811 return "$CFG->dataroot/fonts/$font";
1813 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
1814 return "$CFG->dirroot/lib/fonts/$font";
1816 return null;
1818 } else if ($component === 'theme') { // Exception.
1819 if (file_exists("$this->dir/fonts/$font")) {
1820 return "$this->dir/fonts/$font";
1822 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1823 if (file_exists("$parent_config->dir/fonts/$font")) {
1824 return "$parent_config->dir/fonts/$font";
1827 return null;
1829 } else {
1830 if (strpos($component, '_') === false) {
1831 $component = 'mod_'.$component;
1833 list($type, $plugin) = explode('_', $component, 2);
1835 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
1836 return "$this->dir/fonts_plugins/$type/$plugin/$font";
1838 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1839 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
1840 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
1843 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
1844 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
1846 $dir = core_component::get_plugin_directory($type, $plugin);
1847 if (file_exists("$dir/fonts/$font")) {
1848 return "$dir/fonts/$font";
1850 return null;
1855 * Return true if we should look for SVG images as well.
1857 * @return bool
1859 public function use_svg_icons() {
1860 global $CFG;
1861 if ($this->usesvg === null) {
1863 if (!isset($CFG->svgicons)) {
1864 $this->usesvg = core_useragent::supports_svg();
1865 } else {
1866 // Force them on/off depending upon the setting.
1867 $this->usesvg = (bool)$CFG->svgicons;
1870 return $this->usesvg;
1874 * Forces the usesvg setting to either true or false, avoiding any decision making.
1876 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
1877 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
1879 * @param bool $setting True to force the use of svg when available, null otherwise.
1881 public function force_svg_use($setting) {
1882 $this->usesvg = (bool)$setting;
1886 * Set to be in RTL mode.
1888 * This will likely be used when post processing the CSS before serving it.
1890 * @param bool $inrtl True when in RTL mode.
1892 public function set_rtl_mode($inrtl = true) {
1893 $this->rtlmode = $inrtl;
1897 * Checks if file with any image extension exists.
1899 * The order to these images was adjusted prior to the release of 2.4
1900 * At that point the were the following image counts in Moodle core:
1902 * - png = 667 in pix dirs (1499 total)
1903 * - gif = 385 in pix dirs (606 total)
1904 * - jpg = 62 in pix dirs (74 total)
1905 * - jpeg = 0 in pix dirs (1 total)
1907 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1909 * @param string $filepath
1910 * @param bool $svg If set to true SVG images will also be looked for.
1911 * @return string image name with extension
1913 private static function image_exists($filepath, $svg = false) {
1914 if ($svg && file_exists("$filepath.svg")) {
1915 return "$filepath.svg";
1916 } else if (file_exists("$filepath.png")) {
1917 return "$filepath.png";
1918 } else if (file_exists("$filepath.gif")) {
1919 return "$filepath.gif";
1920 } else if (file_exists("$filepath.jpg")) {
1921 return "$filepath.jpg";
1922 } else if (file_exists("$filepath.jpeg")) {
1923 return "$filepath.jpeg";
1924 } else {
1925 return false;
1930 * Loads the theme config from config.php file.
1932 * @param string $themename
1933 * @param stdClass $settings from config_plugins table
1934 * @param boolean $parentscheck true to also check the parents. .
1935 * @return stdClass The theme configuration
1937 private static function find_theme_config($themename, $settings, $parentscheck = true) {
1938 // We have to use the variable name $THEME (upper case) because that
1939 // is what is used in theme config.php files.
1941 if (!$dir = theme_config::find_theme_location($themename)) {
1942 return null;
1945 $THEME = new stdClass();
1946 $THEME->name = $themename;
1947 $THEME->dir = $dir;
1948 $THEME->settings = $settings;
1950 global $CFG; // just in case somebody tries to use $CFG in theme config
1951 include("$THEME->dir/config.php");
1953 // verify the theme configuration is OK
1954 if (!is_array($THEME->parents)) {
1955 // parents option is mandatory now
1956 return null;
1957 } else {
1958 // We use $parentscheck to only check the direct parents (avoid infinite loop).
1959 if ($parentscheck) {
1960 // Find all parent theme configs.
1961 foreach ($THEME->parents as $parent) {
1962 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
1963 if (empty($parentconfig)) {
1964 return null;
1970 return $THEME;
1974 * Finds the theme location and verifies the theme has all needed files
1975 * and is not obsoleted.
1977 * @param string $themename
1978 * @return string full dir path or null if not found
1980 private static function find_theme_location($themename) {
1981 global $CFG;
1983 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1984 $dir = "$CFG->dirroot/theme/$themename";
1986 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1987 $dir = "$CFG->themedir/$themename";
1989 } else {
1990 return null;
1993 if (file_exists("$dir/styles.php")) {
1994 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1995 return null;
1998 return $dir;
2002 * Get the renderer for a part of Moodle for this theme.
2004 * @param moodle_page $page the page we are rendering
2005 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
2006 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
2007 * @param string $target one of rendering target constants
2008 * @return renderer_base the requested renderer.
2010 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
2011 if (is_null($this->rf)) {
2012 $classname = $this->rendererfactory;
2013 $this->rf = new $classname($this);
2016 return $this->rf->get_renderer($page, $component, $subtype, $target);
2020 * Get the information from {@link $layouts} for this type of page.
2022 * @param string $pagelayout the the page layout name.
2023 * @return array the appropriate part of {@link $layouts}.
2025 protected function layout_info_for_page($pagelayout) {
2026 if (array_key_exists($pagelayout, $this->layouts)) {
2027 return $this->layouts[$pagelayout];
2028 } else {
2029 debugging('Invalid page layout specified: ' . $pagelayout);
2030 return $this->layouts['standard'];
2035 * Given the settings of this theme, and the page pagelayout, return the
2036 * full path of the page layout file to use.
2038 * Used by {@link core_renderer::header()}.
2040 * @param string $pagelayout the the page layout name.
2041 * @return string Full path to the lyout file to use
2043 public function layout_file($pagelayout) {
2044 global $CFG;
2046 $layoutinfo = $this->layout_info_for_page($pagelayout);
2047 $layoutfile = $layoutinfo['file'];
2049 if (array_key_exists('theme', $layoutinfo)) {
2050 $themes = array($layoutinfo['theme']);
2051 } else {
2052 $themes = array_merge(array($this->name),$this->parents);
2055 foreach ($themes as $theme) {
2056 if ($dir = $this->find_theme_location($theme)) {
2057 $path = "$dir/layout/$layoutfile";
2059 // Check the template exists, return general base theme template if not.
2060 if (is_readable($path)) {
2061 return $path;
2066 debugging('Can not find layout file for: ' . $pagelayout);
2067 // fallback to standard normal layout
2068 return "$CFG->dirroot/theme/base/layout/general.php";
2072 * Returns auxiliary page layout options specified in layout configuration array.
2074 * @param string $pagelayout
2075 * @return array
2077 public function pagelayout_options($pagelayout) {
2078 $info = $this->layout_info_for_page($pagelayout);
2079 if (!empty($info['options'])) {
2080 return $info['options'];
2082 return array();
2086 * Inform a block_manager about the block regions this theme wants on this
2087 * page layout.
2089 * @param string $pagelayout the general type of the page.
2090 * @param block_manager $blockmanager the block_manger to set up.
2092 public function setup_blocks($pagelayout, $blockmanager) {
2093 $layoutinfo = $this->layout_info_for_page($pagelayout);
2094 if (!empty($layoutinfo['regions'])) {
2095 $blockmanager->add_regions($layoutinfo['regions'], false);
2096 $blockmanager->set_default_region($layoutinfo['defaultregion']);
2101 * Gets the visible name for the requested block region.
2103 * @param string $region The region name to get
2104 * @param string $theme The theme the region belongs to (may come from the parent theme)
2105 * @return string
2107 protected function get_region_name($region, $theme) {
2108 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
2109 // A name exists in this theme, so use it
2110 if (substr($regionstring, 0, 1) != '[') {
2111 return $regionstring;
2114 // Otherwise, try to find one elsewhere
2115 // Check parents, if any
2116 foreach ($this->parents as $parentthemename) {
2117 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
2118 if (substr($regionstring, 0, 1) != '[') {
2119 return $regionstring;
2123 // Last resort, try the bootstrapbase theme for names
2124 return get_string('region-' . $region, 'theme_bootstrapbase');
2128 * Get the list of all block regions known to this theme in all templates.
2130 * @return array internal region name => human readable name.
2132 public function get_all_block_regions() {
2133 $regions = array();
2134 foreach ($this->layouts as $layoutinfo) {
2135 foreach ($layoutinfo['regions'] as $region) {
2136 $regions[$region] = $this->get_region_name($region, $this->name);
2139 return $regions;
2143 * Returns the human readable name of the theme
2145 * @return string
2147 public function get_theme_name() {
2148 return get_string('pluginname', 'theme_'.$this->name);
2152 * Returns the block render method.
2154 * It is set by the theme via:
2155 * $THEME->blockrendermethod = '...';
2157 * It can be one of two values, blocks or blocks_for_region.
2158 * It should be set to the method being used by the theme layouts.
2160 * @return string
2162 public function get_block_render_method() {
2163 if ($this->blockrendermethod) {
2164 // Return the specified block render method.
2165 return $this->blockrendermethod;
2167 // Its not explicitly set, check the parent theme configs.
2168 foreach ($this->parent_configs as $config) {
2169 if (isset($config->blockrendermethod)) {
2170 return $config->blockrendermethod;
2173 // Default it to blocks.
2174 return 'blocks';
2179 * This class keeps track of which HTML tags are currently open.
2181 * This makes it much easier to always generate well formed XHTML output, even
2182 * if execution terminates abruptly. Any time you output some opening HTML
2183 * without the matching closing HTML, you should push the necessary close tags
2184 * onto the stack.
2186 * @copyright 2009 Tim Hunt
2187 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2188 * @since Moodle 2.0
2189 * @package core
2190 * @category output
2192 class xhtml_container_stack {
2195 * @var array Stores the list of open containers.
2197 protected $opencontainers = array();
2200 * @var array In developer debug mode, stores a stack trace of all opens and
2201 * closes, so we can output helpful error messages when there is a mismatch.
2203 protected $log = array();
2206 * @var boolean Store whether we are developer debug mode. We need this in
2207 * several places including in the destructor where we may not have access to $CFG.
2209 protected $isdebugging;
2212 * Constructor
2214 public function __construct() {
2215 global $CFG;
2216 $this->isdebugging = $CFG->debugdeveloper;
2220 * Push the close HTML for a recently opened container onto the stack.
2222 * @param string $type The type of container. This is checked when {@link pop()}
2223 * is called and must match, otherwise a developer debug warning is output.
2224 * @param string $closehtml The HTML required to close the container.
2226 public function push($type, $closehtml) {
2227 $container = new stdClass;
2228 $container->type = $type;
2229 $container->closehtml = $closehtml;
2230 if ($this->isdebugging) {
2231 $this->log('Open', $type);
2233 array_push($this->opencontainers, $container);
2237 * Pop the HTML for the next closing container from the stack. The $type
2238 * must match the type passed when the container was opened, otherwise a
2239 * warning will be output.
2241 * @param string $type The type of container.
2242 * @return string the HTML required to close the container.
2244 public function pop($type) {
2245 if (empty($this->opencontainers)) {
2246 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2247 $this->output_log(), DEBUG_DEVELOPER);
2248 return;
2251 $container = array_pop($this->opencontainers);
2252 if ($container->type != $type) {
2253 debugging('<p>The type of container to be closed (' . $container->type .
2254 ') does not match the type of the next open container (' . $type .
2255 '). This suggests there is a nesting problem.</p>' .
2256 $this->output_log(), DEBUG_DEVELOPER);
2258 if ($this->isdebugging) {
2259 $this->log('Close', $type);
2261 return $container->closehtml;
2265 * Close all but the last open container. This is useful in places like error
2266 * handling, where you want to close all the open containers (apart from <body>)
2267 * before outputting the error message.
2269 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2270 * developer debug warning if it isn't.
2271 * @return string the HTML required to close any open containers inside <body>.
2273 public function pop_all_but_last($shouldbenone = false) {
2274 if ($shouldbenone && count($this->opencontainers) != 1) {
2275 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2276 $this->output_log(), DEBUG_DEVELOPER);
2278 $output = '';
2279 while (count($this->opencontainers) > 1) {
2280 $container = array_pop($this->opencontainers);
2281 $output .= $container->closehtml;
2283 return $output;
2287 * You can call this function if you want to throw away an instance of this
2288 * class without properly emptying the stack (for example, in a unit test).
2289 * Calling this method stops the destruct method from outputting a developer
2290 * debug warning. After calling this method, the instance can no longer be used.
2292 public function discard() {
2293 $this->opencontainers = null;
2297 * Adds an entry to the log.
2299 * @param string $action The name of the action
2300 * @param string $type The type of action
2302 protected function log($action, $type) {
2303 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
2304 format_backtrace(debug_backtrace()) . '</li>';
2308 * Outputs the log's contents as a HTML list.
2310 * @return string HTML list of the log
2312 protected function output_log() {
2313 return '<ul>' . implode("\n", $this->log) . '</ul>';