MDL-48624 behat: Added extended timeout to ensure step pass
[moodle.git] / lib / outputlib.php
blobba75fe3b9930039c1a3fd2e0476157d65392e1fa
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;
101 * This class represents the configuration variables of a Moodle theme.
103 * All the variables with access: public below (with a few exceptions that are marked)
104 * are the properties you can set in your themes config.php file.
106 * There are also some methods and protected variables that are part of the inner
107 * workings of Moodle's themes system. If you are just editing a themes config.php
108 * file, you can just ignore those, and the following information for developers.
110 * Normally, to create an instance of this class, you should use the
111 * {@link theme_config::load()} factory method to load a themes config.php file.
112 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
113 * will create one for you, accessible as $PAGE->theme.
115 * @copyright 2009 Tim Hunt
116 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
117 * @since Moodle 2.0
118 * @package core
119 * @category output
121 class theme_config {
124 * @var string Default theme, used when requested theme not found.
126 const DEFAULT_THEME = 'clean';
129 * @var array You can base your theme on other themes by linking to the other theme as
130 * parents. This lets you use the CSS and layouts from the other themes
131 * (see {@link theme_config::$layouts}).
132 * That makes it easy to create a new theme that is similar to another one
133 * but with a few changes. In this themes CSS you only need to override
134 * those rules you want to change.
136 public $parents;
139 * @var array The names of all the stylesheets from this theme that you would
140 * like included, in order. Give the names of the files without .css.
142 public $sheets = array();
145 * @var array The names of all the stylesheets from parents that should be excluded.
146 * true value may be used to specify all parents or all themes from one parent.
147 * If no value specified value from parent theme used.
149 public $parents_exclude_sheets = null;
152 * @var array List of plugin sheets to be excluded.
153 * If no value specified value from parent theme used.
155 public $plugins_exclude_sheets = null;
158 * @var array List of style sheets that are included in the text editor bodies.
159 * Sheets from parent themes are used automatically and can not be excluded.
161 public $editor_sheets = array();
164 * @var array The names of all the javascript files this theme that you would
165 * like included from head, in order. Give the names of the files without .js.
167 public $javascripts = array();
170 * @var array The names of all the javascript files this theme that you would
171 * like included from footer, in order. Give the names of the files without .js.
173 public $javascripts_footer = array();
176 * @var array The names of all the javascript files from parents that should
177 * be excluded. true value may be used to specify all parents or all themes
178 * from one parent.
179 * If no value specified value from parent theme used.
181 public $parents_exclude_javascripts = null;
184 * @var array Which file to use for each page layout.
186 * This is an array of arrays. The keys of the outer array are the different layouts.
187 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
188 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
189 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
190 * That file also has a good example of how to set this setting.
192 * For each layout, the value in the outer array is an array that describes
193 * how you want that type of page to look. For example
194 * <pre>
195 * $THEME->layouts = array(
196 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
197 * 'standard' => array(
198 * 'theme' = 'mytheme',
199 * 'file' => 'normal.php',
200 * 'regions' => array('side-pre', 'side-post'),
201 * 'defaultregion' => 'side-post'
202 * ),
203 * // The site home page.
204 * 'home' => array(
205 * 'theme' = 'mytheme',
206 * 'file' => 'home.php',
207 * 'regions' => array('side-pre', 'side-post'),
208 * 'defaultregion' => 'side-post'
209 * ),
210 * // ...
211 * );
212 * </pre>
214 * 'theme' name of the theme where is the layout located
215 * 'file' is the layout file to use for this type of page.
216 * layout files are stored in layout subfolder
217 * 'regions' This lists the regions on the page where blocks may appear. For
218 * each region you list here, your layout file must include a call to
219 * <pre>
220 * echo $OUTPUT->blocks_for_region($regionname);
221 * </pre>
222 * or equivalent so that the blocks are actually visible.
224 * 'defaultregion' If the list of regions is non-empty, then you must pick
225 * one of the one of them as 'default'. This has two meanings. First, this is
226 * where new blocks are added. Second, if there are any blocks associated with
227 * the page, but in non-existent regions, they appear here. (Imaging, for example,
228 * that someone added blocks using a different theme that used different region
229 * names, and then switched to this theme.)
231 public $layouts = array();
234 * @var string Name of the renderer factory class to use. Must implement the
235 * {@link renderer_factory} interface.
237 * This is an advanced feature. Moodle output is generated by 'renderers',
238 * you can customise the HTML that is output by writing custom renderers,
239 * and then you need to specify 'renderer factory' so that Moodle can find
240 * your renderers.
242 * There are some renderer factories supplied with Moodle. Please follow these
243 * links to see what they do.
244 * <ul>
245 * <li>{@link standard_renderer_factory} - the default.</li>
246 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
247 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
248 * </ul>
250 public $rendererfactory = 'standard_renderer_factory';
253 * @var string Function to do custom CSS post-processing.
255 * This is an advanced feature. If you want to do custom post-processing on the
256 * CSS before it is output (for example, to replace certain variable names
257 * with particular values) you can give the name of a function here.
259 public $csspostprocess = null;
262 * @var string Accessibility: Right arrow-like character is
263 * used in the breadcrumb trail, course navigation menu
264 * (previous/next activity), calendar, and search forum block.
265 * If the theme does not set characters, appropriate defaults
266 * are set automatically. Please DO NOT
267 * use &lt; &gt; &raquo; - these are confusing for blind users.
269 public $rarrow = null;
272 * @var string Accessibility: Left arrow-like character is
273 * used in the breadcrumb trail, course navigation menu
274 * (previous/next activity), calendar, and search forum block.
275 * If the theme does not set characters, appropriate defaults
276 * are set automatically. Please DO NOT
277 * use &lt; &gt; &raquo; - these are confusing for blind users.
279 public $larrow = null;
282 * @var bool Some themes may want to disable ajax course editing.
284 public $enablecourseajax = true;
287 * @var string Determines served document types
288 * - 'html5' the only officially supported doctype in Moodle
289 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
290 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
292 public $doctype = 'html5';
294 //==Following properties are not configurable from theme config.php==
297 * @var string The name of this theme. Set automatically when this theme is
298 * loaded. This can not be set in theme config.php
300 public $name;
303 * @var string The folder where this themes files are stored. This is set
304 * automatically. This can not be set in theme config.php
306 public $dir;
309 * @var stdClass Theme settings stored in config_plugins table.
310 * This can not be set in theme config.php
312 public $setting = null;
315 * @var bool If set to true and the theme enables the dock then blocks will be able
316 * to be moved to the special dock
318 public $enable_dock = false;
321 * @var bool If set to true then this theme will not be shown in the theme selector unless
322 * theme designer mode is turned on.
324 public $hidefromselector = false;
327 * @var array list of YUI CSS modules to be included on each page. This may be used
328 * to remove cssreset and use cssnormalise module instead.
330 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
333 * An associative array of block manipulations that should be made if the user is using an rtl language.
334 * The key is the original block region, and the value is the block region to change to.
335 * This is used when displaying blocks for regions only.
336 * @var array
338 public $blockrtlmanipulations = array();
341 * @var renderer_factory Instance of the renderer_factory implementation
342 * we are using. Implementation detail.
344 protected $rf = null;
347 * @var array List of parent config objects.
349 protected $parent_configs = array();
352 * @var bool If set to true then the theme is safe to run through the optimiser (if it is enabled)
353 * If set to false then we know either the theme has already been optimised and the CSS optimiser is not needed
354 * or the theme is not compatible with the CSS optimiser. In both cases even if enabled the CSS optimiser will not
355 * be used with this theme if set to false.
357 public $supportscssoptimisation = true;
360 * Used to determine whether we can serve SVG images or not.
361 * @var bool
363 private $usesvg = null;
366 * The LESS file to compile. When set, the theme will attempt to compile the file itself.
367 * @var bool
369 public $lessfile = false;
372 * The name of the function to call to get the LESS code to inject.
373 * @var string
375 public $extralesscallback = null;
378 * The name of the function to call to get extra LESS variables.
379 * @var string
381 public $lessvariablescallback = null;
384 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
385 * Defaults to {@link core_renderer::blocks_for_region()}
386 * @var string
388 public $blockrendermethod = null;
391 * Load the config.php file for a particular theme, and return an instance
392 * of this class. (That is, this is a factory method.)
394 * @param string $themename the name of the theme.
395 * @return theme_config an instance of this class.
397 public static function load($themename) {
398 global $CFG;
400 // load theme settings from db
401 try {
402 $settings = get_config('theme_'.$themename);
403 } catch (dml_exception $e) {
404 // most probably moodle tables not created yet
405 $settings = new stdClass();
408 if ($config = theme_config::find_theme_config($themename, $settings)) {
409 return new theme_config($config);
411 } else if ($themename == theme_config::DEFAULT_THEME) {
412 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
414 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
415 return new theme_config($config);
417 } else {
418 // bad luck, the requested theme has some problems - admin see details in theme config
419 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
424 * Theme diagnostic code. It is very problematic to send debug output
425 * to the actual CSS file, instead this functions is supposed to
426 * diagnose given theme and highlights all potential problems.
427 * This information should be available from the theme selection page
428 * or some other debug page for theme designers.
430 * @param string $themename
431 * @return array description of problems
433 public static function diagnose($themename) {
434 //TODO: MDL-21108
435 return array();
439 * Private constructor, can be called only from the factory method.
440 * @param stdClass $config
442 private function __construct($config) {
443 global $CFG; //needed for included lib.php files
445 $this->settings = $config->settings;
446 $this->name = $config->name;
447 $this->dir = $config->dir;
449 if ($this->name != 'base') {
450 $baseconfig = theme_config::find_theme_config('base', $this->settings);
451 } else {
452 $baseconfig = $config;
455 $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer',
456 'parents_exclude_javascripts', 'layouts', 'enable_dock', 'enablecourseajax', 'supportscssoptimisation',
457 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector', 'doctype',
458 'yuicssmodules', 'blockrtlmanipulations', 'lessfile', 'extralesscallback', 'lessvariablescallback',
459 'blockrendermethod');
461 foreach ($config as $key=>$value) {
462 if (in_array($key, $configurable)) {
463 $this->$key = $value;
467 // verify all parents and load configs and renderers
468 foreach ($this->parents as $parent) {
469 if ($parent == 'base') {
470 $parent_config = $baseconfig;
471 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
472 // this is not good - better exclude faulty parents
473 continue;
475 $libfile = $parent_config->dir.'/lib.php';
476 if (is_readable($libfile)) {
477 // theme may store various function here
478 include_once($libfile);
480 $renderersfile = $parent_config->dir.'/renderers.php';
481 if (is_readable($renderersfile)) {
482 // may contain core and plugin renderers and renderer factory
483 include_once($renderersfile);
485 $this->parent_configs[$parent] = $parent_config;
487 $libfile = $this->dir.'/lib.php';
488 if (is_readable($libfile)) {
489 // theme may store various function here
490 include_once($libfile);
492 $rendererfile = $this->dir.'/renderers.php';
493 if (is_readable($rendererfile)) {
494 // may contain core and plugin renderers and renderer factory
495 include_once($rendererfile);
496 } else {
497 // check if renderers.php file is missnamed renderer.php
498 if (is_readable($this->dir.'/renderer.php')) {
499 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
500 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
504 // cascade all layouts properly
505 foreach ($baseconfig->layouts as $layout=>$value) {
506 if (!isset($this->layouts[$layout])) {
507 foreach ($this->parent_configs as $parent_config) {
508 if (isset($parent_config->layouts[$layout])) {
509 $this->layouts[$layout] = $parent_config->layouts[$layout];
510 continue 2;
513 $this->layouts[$layout] = $value;
517 //fix arrows if needed
518 $this->check_theme_arrows();
522 * Let the theme initialise the page object (usually $PAGE).
524 * This may be used for example to request jQuery in add-ons.
526 * @param moodle_page $page
528 public function init_page(moodle_page $page) {
529 $themeinitfunction = 'theme_'.$this->name.'_page_init';
530 if (function_exists($themeinitfunction)) {
531 $themeinitfunction($page);
536 * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
537 * If not it applies sensible defaults.
539 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
540 * search forum block, etc. Important: these are 'silent' in a screen-reader
541 * (unlike &gt; &raquo;), and must be accompanied by text.
543 private function check_theme_arrows() {
544 if (!isset($this->rarrow) and !isset($this->larrow)) {
545 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
546 // Also OK in Win 9x/2K/IE 5.x
547 $this->rarrow = '&#x25BA;';
548 $this->larrow = '&#x25C4;';
549 if (empty($_SERVER['HTTP_USER_AGENT'])) {
550 $uagent = '';
551 } else {
552 $uagent = $_SERVER['HTTP_USER_AGENT'];
554 if (false !== strpos($uagent, 'Opera')
555 || false !== strpos($uagent, 'Mac')) {
556 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
557 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
558 $this->rarrow = '&#x25B6;';
559 $this->larrow = '&#x25C0;';
561 elseif ((false !== strpos($uagent, 'Konqueror'))
562 || (false !== strpos($uagent, 'Android'))) {
563 // The fonts on Android don't include the characters required for this to work as expected.
564 // So we use the same ones Konqueror uses.
565 $this->rarrow = '&rarr;';
566 $this->larrow = '&larr;';
568 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
569 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
570 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
571 // To be safe, non-Unicode browsers!
572 $this->rarrow = '&gt;';
573 $this->larrow = '&lt;';
576 // RTL support - in RTL languages, swap r and l arrows
577 if (right_to_left()) {
578 $t = $this->rarrow;
579 $this->rarrow = $this->larrow;
580 $this->larrow = $t;
586 * Returns output renderer prefixes, these are used when looking
587 * for the overridden renderers in themes.
589 * @return array
591 public function renderer_prefixes() {
592 global $CFG; // just in case the included files need it
594 $prefixes = array('theme_'.$this->name);
596 foreach ($this->parent_configs as $parent) {
597 $prefixes[] = 'theme_'.$parent->name;
600 return $prefixes;
604 * Returns the stylesheet URL of this editor content
606 * @param bool $encoded false means use & and true use &amp; in URLs
607 * @return moodle_url
609 public function editor_css_url($encoded=true) {
610 global $CFG;
611 $rev = theme_get_revision();
612 if ($rev > -1) {
613 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
614 if (!empty($CFG->slasharguments)) {
615 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
616 } else {
617 $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
619 } else {
620 $params = array('theme'=>$this->name, 'type'=>'editor');
621 $url = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
623 return $url;
627 * Returns the content of the CSS to be used in editor content
629 * @return array
631 public function editor_css_files() {
632 $files = array();
634 // First editor plugins.
635 $plugins = core_component::get_plugin_list('editor');
636 foreach ($plugins as $plugin=>$fulldir) {
637 $sheetfile = "$fulldir/editor_styles.css";
638 if (is_readable($sheetfile)) {
639 $files['plugin_'.$plugin] = $sheetfile;
642 // Then parent themes - base first, the immediate parent last.
643 foreach (array_reverse($this->parent_configs) as $parent_config) {
644 if (empty($parent_config->editor_sheets)) {
645 continue;
647 foreach ($parent_config->editor_sheets as $sheet) {
648 $sheetfile = "$parent_config->dir/style/$sheet.css";
649 if (is_readable($sheetfile)) {
650 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
654 // Finally this theme.
655 if (!empty($this->editor_sheets)) {
656 foreach ($this->editor_sheets as $sheet) {
657 $sheetfile = "$this->dir/style/$sheet.css";
658 if (is_readable($sheetfile)) {
659 $files['theme_'.$sheet] = $sheetfile;
664 return $files;
668 * Get the stylesheet URL of this theme.
670 * @param moodle_page $page Not used... deprecated?
671 * @return moodle_url[]
673 public function css_urls(moodle_page $page) {
674 global $CFG;
676 $rev = theme_get_revision();
678 $urls = array();
680 $svg = $this->use_svg_icons();
681 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
683 if ($rev > -1) {
684 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
685 if (!empty($CFG->slasharguments)) {
686 $slashargs = '';
687 if (!$svg) {
688 // We add a simple /_s to the start of the path.
689 // The underscore is used to ensure that it isn't a valid theme name.
690 $slashargs .= '/_s'.$slashargs;
692 $slashargs .= '/'.$this->name.'/'.$rev.'/all';
693 if ($separate) {
694 $slashargs .= '/chunk0';
696 $url->set_slashargument($slashargs, 'noparam', true);
697 } else {
698 $params = array('theme' => $this->name,'rev' => $rev, 'type' => 'all');
699 if (!$svg) {
700 // We add an SVG param so that we know not to serve SVG images.
701 // We do this because all modern browsers support SVG and this param will one day be removed.
702 $params['svg'] = '0';
704 if ($separate) {
705 $params['chunk'] = '0';
707 $url->params($params);
709 $urls[] = $url;
711 } else {
712 $baseurl = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php');
714 $css = $this->get_css_files(true);
715 if (!$svg) {
716 // We add an SVG param so that we know not to serve SVG images.
717 // We do this because all modern browsers support SVG and this param will one day be removed.
718 $baseurl->param('svg', '0');
720 if ($separate) {
721 // We might need to chunk long files.
722 $baseurl->param('chunk', '0');
724 if (core_useragent::is_ie()) {
725 // Lalala, IE does not allow more than 31 linked CSS files from main document.
726 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
727 foreach ($css['parents'] as $parent=>$sheets) {
728 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
729 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
731 if (!empty($this->lessfile)) {
732 // No need to define the type as IE here.
733 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
735 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
737 } else {
738 foreach ($css['plugins'] as $plugin=>$unused) {
739 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
741 foreach ($css['parents'] as $parent=>$sheets) {
742 foreach ($sheets as $sheet=>$unused2) {
743 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
746 foreach ($css['theme'] as $sheet => $filename) {
747 if ($sheet === $this->lessfile) {
748 // This is the theme LESS file.
749 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
750 } else {
751 // Sheet first in order to make long urls easier to read.
752 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
758 return $urls;
762 * Get the whole css stylesheet for production mode.
764 * NOTE: this method is not expected to be used from any addons.
766 * @return string CSS markup, already optimised and compressed
768 public function get_css_content() {
769 global $CFG;
770 require_once($CFG->dirroot.'/lib/csslib.php');
772 $csscontent = '';
773 foreach ($this->get_css_files(false) as $type => $value) {
774 foreach ($value as $identifier => $val) {
775 if (is_array($val)) {
776 foreach ($val as $v) {
777 $csscontent .= file_get_contents($v) . "\n";
779 } else {
780 if ($type === 'theme' && $identifier === $this->lessfile) {
781 // We need the content from LESS because this is the LESS file from the theme.
782 $csscontent .= $this->get_css_content_from_less(false);
783 } else {
784 $csscontent .= file_get_contents($val) . "\n";
789 $csscontent = $this->post_process($csscontent);
791 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
792 // This is an experimental feature introduced in Moodle 2.3
793 // The CSS optimiser organises the CSS in order to reduce the overall number
794 // of rules and styles being sent to the client. It does this by collating
795 // the CSS before it is cached removing excess styles and rules and stripping
796 // out any extraneous content such as comments and empty rules.
797 $optimiser = new css_optimiser();
798 $csscontent = $optimiser->process($csscontent);
800 } else {
801 $csscontent = core_minify::css($csscontent);
804 return $csscontent;
808 * Get the theme designer css markup,
809 * the parameters are coming from css_urls().
811 * NOTE: this method is not expected to be used from any addons.
813 * @param string $type
814 * @param string $subtype
815 * @param string $sheet
816 * @return string CSS markup
818 public function get_css_content_debug($type, $subtype, $sheet) {
819 global $CFG;
820 require_once($CFG->dirroot.'/lib/csslib.php');
822 // The LESS file of the theme is requested.
823 if ($type === 'less') {
824 $csscontent = $this->get_css_content_from_less(true);
825 if ($csscontent !== false) {
826 return $csscontent;
828 return '';
831 $optimiser = null;
832 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
833 // This is an experimental feature introduced in Moodle 2.3
834 // The CSS optimiser organises the CSS in order to reduce the overall number
835 // of rules and styles being sent to the client. It does this by collating
836 // the CSS before it is cached removing excess styles and rules and stripping
837 // out any extraneous content such as comments and empty rules.
838 $optimiser = new css_optimiser();
841 $cssfiles = array();
842 $css = $this->get_css_files(true);
844 if ($type === 'ie') {
845 // IE is a sloppy browser with weird limits, sorry.
846 if ($subtype === 'plugins') {
847 $cssfiles = $css['plugins'];
849 } else if ($subtype === 'parents') {
850 if (empty($sheet)) {
851 // Do not bother with the empty parent here.
852 } else {
853 // Build up the CSS for that parent so we can serve it as one file.
854 foreach ($css[$subtype][$sheet] as $parent => $css) {
855 $cssfiles[] = $css;
858 } else if ($subtype === 'theme') {
859 $cssfiles = $css['theme'];
860 foreach ($cssfiles as $key => $value) {
861 if ($this->lessfile && $key === $this->lessfile) {
862 // Remove the LESS file from the theme CSS files.
863 // The LESS files use the type 'less', not 'ie'.
864 unset($cssfiles[$key]);
869 } else if ($type === 'plugin') {
870 if (isset($css['plugins'][$subtype])) {
871 $cssfiles[] = $css['plugins'][$subtype];
874 } else if ($type === 'parent') {
875 if (isset($css['parents'][$subtype][$sheet])) {
876 $cssfiles[] = $css['parents'][$subtype][$sheet];
879 } else if ($type === 'theme') {
880 if (isset($css['theme'][$sheet])) {
881 $cssfiles[] = $css['theme'][$sheet];
885 $csscontent = '';
886 foreach ($cssfiles as $file) {
887 $contents = file_get_contents($file);
888 $contents = $this->post_process($contents);
889 $comment = "/** Path: $type $subtype $sheet.' **/\n";
890 $stats = '';
891 if ($optimiser) {
892 $contents = $optimiser->process($contents);
893 if (!empty($CFG->cssoptimiserstats)) {
894 $stats = $optimiser->output_stats_css();
897 $csscontent .= $comment.$stats.$contents."\n\n";
900 return $csscontent;
904 * Get the whole css stylesheet for editor iframe.
906 * NOTE: this method is not expected to be used from any addons.
908 * @return string CSS markup
910 public function get_css_content_editor() {
911 // Do not bother to optimise anything here, just very basic stuff.
912 $cssfiles = $this->editor_css_files();
913 $css = '';
914 foreach ($cssfiles as $file) {
915 $css .= file_get_contents($file)."\n";
917 return $this->post_process($css);
921 * Returns an array of organised CSS files required for this output.
923 * @param bool $themedesigner
924 * @return array nested array of file paths
926 protected function get_css_files($themedesigner) {
927 global $CFG;
929 $cache = null;
930 $cachekey = 'cssfiles';
931 if ($themedesigner) {
932 require_once($CFG->dirroot.'/lib/csslib.php');
933 // We need some kind of caching here because otherwise the page navigation becomes
934 // way too slow in theme designer mode. Feel free to create full cache definition later...
935 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
936 if ($files = $cache->get($cachekey)) {
937 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
938 unset($files['created']);
939 return $files;
944 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
946 // Get all plugin sheets.
947 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
948 if ($excludes !== true) {
949 foreach (core_component::get_plugin_types() as $type=>$unused) {
950 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
951 continue;
953 $plugins = core_component::get_plugin_list($type);
954 foreach ($plugins as $plugin=>$fulldir) {
955 if (!empty($excludes[$type]) and is_array($excludes[$type])
956 and in_array($plugin, $excludes[$type])) {
957 continue;
960 // Get the CSS from the plugin.
961 $sheetfile = "$fulldir/styles.css";
962 if (is_readable($sheetfile)) {
963 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
966 // Create a list of candidate sheets from parents (direct parent last) and current theme.
967 $candidates = array();
968 foreach (array_reverse($this->parent_configs) as $parent_config) {
969 $candidates[] = $parent_config->name;
971 $candidates[] = $this->name;
973 // Add the sheets found.
974 foreach ($candidates as $candidate) {
975 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
976 if (is_readable($sheetthemefile)) {
977 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
984 // Find out wanted parent sheets.
985 $excludes = $this->resolve_excludes('parents_exclude_sheets');
986 if ($excludes !== true) {
987 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
988 $parent = $parent_config->name;
989 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
990 continue;
992 foreach ($parent_config->sheets as $sheet) {
993 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
994 && in_array($sheet, $excludes[$parent])) {
995 continue;
998 // We never refer to the parent LESS files.
999 $sheetfile = "$parent_config->dir/style/$sheet.css";
1000 if (is_readable($sheetfile)) {
1001 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1007 // Current theme sheets and less file.
1008 // We first add the LESS files because we want the CSS ones to be included after the
1009 // LESS code. However, if both the LESS file and the CSS file share the same name,
1010 // the CSS file is ignored.
1011 if (!empty($this->lessfile)) {
1012 $sheetfile = "{$this->dir}/less/{$this->lessfile}.less";
1013 if (is_readable($sheetfile)) {
1014 $cssfiles['theme'][$this->lessfile] = $sheetfile;
1017 if (is_array($this->sheets)) {
1018 foreach ($this->sheets as $sheet) {
1019 $sheetfile = "$this->dir/style/$sheet.css";
1020 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1021 $cssfiles['theme'][$sheet] = $sheetfile;
1026 if ($cache) {
1027 $files = $cssfiles;
1028 $files['created'] = time();
1029 $cache->set($cachekey, $files);
1031 return $cssfiles;
1035 * Return the CSS content generated from LESS the file.
1037 * @param bool $themedesigner True if theme designer is enabled.
1038 * @return bool|string Return false when the compilation failed. Else the compiled string.
1040 protected function get_css_content_from_less($themedesigner) {
1042 $lessfile = $this->lessfile;
1043 if (!$lessfile || !is_readable($this->dir . '/less/' . $lessfile . '.less')) {
1044 throw new coding_exception('The theme did not define a LESS file, or it is not readable.');
1047 // We might need more memory to do this, so let's play safe.
1048 raise_memory_limit(MEMORY_EXTRA);
1050 // Files list.
1051 $files = $this->get_css_files($themedesigner);
1053 // Get the LESS file path.
1054 $themelessfile = $files['theme'][$lessfile];
1056 // Setup compiler options.
1057 $options = array(
1058 // We need to set the import directory to where $lessfile is.
1059 'import_dirs' => array(dirname($themelessfile) => '/'),
1060 // Always disable default caching.
1061 'cache_method' => false,
1062 // Disable the relative URLs, we have post_process() to handle that.
1063 'relativeUrls' => false,
1066 if ($themedesigner) {
1067 // Add the sourceMap inline to ensure that it is atomically generated.
1068 $options['sourceMap'] = true;
1069 $options['sourceRoot'] = 'theme';
1072 // Instantiate the compiler.
1073 $compiler = new core_lessc($options);
1075 try {
1076 $compiler->parse_file_content($themelessfile);
1078 // Get the callbacks.
1079 $compiler->parse($this->get_extra_less_code());
1080 $compiler->ModifyVars($this->get_less_variables());
1082 // Compile the CSS.
1083 $compiled = $compiler->getCss();
1085 // Post process the entire thing.
1086 $compiled = $this->post_process($compiled);
1087 } catch (Less_Exception_Parser $e) {
1088 $compiled = false;
1089 debugging('Error while compiling LESS ' . $lessfile . ' file: ' . $e->getMessage(), DEBUG_DEVELOPER);
1092 // Try to save memory.
1093 $compiler = null;
1094 unset($compiler);
1096 return $compiled;
1100 * Return extra LESS variables to use when compiling.
1102 * @return array Where keys are the variable names (omitting the @), and the values are the value.
1104 protected function get_less_variables() {
1105 $variables = array();
1107 // Getting all the candidate functions.
1108 $candidates = array();
1109 foreach ($this->parent_configs as $parent_config) {
1110 if (!isset($parent_config->lessvariablescallback)) {
1111 continue;
1113 $candidates[] = $parent_config->lessvariablescallback;
1115 $candidates[] = $this->lessvariablescallback;
1117 // Calling the functions.
1118 foreach ($candidates as $function) {
1119 if (function_exists($function)) {
1120 $vars = $function($this);
1121 if (!is_array($vars)) {
1122 debugging('Callback ' . $function . ' did not return an array() as expected', DEBUG_DEVELOPER);
1123 continue;
1125 $variables = array_merge($variables, $vars);
1129 return $variables;
1133 * Return extra LESS code to add when compiling.
1135 * This is intended to be used by themes to inject some LESS code
1136 * before it gets compiled. If you want to inject variables you
1137 * should use {@link self::get_less_variables()}.
1139 * @return string The LESS code to inject.
1141 protected function get_extra_less_code() {
1142 $content = '';
1144 // Getting all the candidate functions.
1145 $candidates = array();
1146 foreach ($this->parent_configs as $parent_config) {
1147 if (!isset($parent_config->extralesscallback)) {
1148 continue;
1150 $candidates[] = $parent_config->extralesscallback;
1152 $candidates[] = $this->extralesscallback;
1154 // Calling the functions.
1155 foreach ($candidates as $function) {
1156 if (function_exists($function)) {
1157 $content .= "\n/** Extra LESS from $function **/\n" . $function($this) . "\n";
1161 return $content;
1165 * Generate a URL to the file that serves theme JavaScript files.
1167 * If we determine that the theme has no relevant files, then we return
1168 * early with a null value.
1170 * @param bool $inhead true means head url, false means footer
1171 * @return moodle_url|null
1173 public function javascript_url($inhead) {
1174 global $CFG;
1176 $rev = theme_get_revision();
1177 $params = array('theme'=>$this->name,'rev'=>$rev);
1178 $params['type'] = $inhead ? 'head' : 'footer';
1180 // Return early if there are no files to serve
1181 if (count($this->javascript_files($params['type'])) === 0) {
1182 return null;
1185 if (!empty($CFG->slasharguments) and $rev > 0) {
1186 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
1187 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
1188 return $url;
1189 } else {
1190 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
1195 * Get the URL's for the JavaScript files used by this theme.
1196 * They won't be served directly, instead they'll be mediated through
1197 * theme/javascript.php.
1199 * @param string $type Either javascripts_footer, or javascripts
1200 * @return array
1202 public function javascript_files($type) {
1203 if ($type === 'footer') {
1204 $type = 'javascripts_footer';
1205 } else {
1206 $type = 'javascripts';
1209 $js = array();
1210 // find out wanted parent javascripts
1211 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1212 if ($excludes !== true) {
1213 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1214 $parent = $parent_config->name;
1215 if (empty($parent_config->$type)) {
1216 continue;
1218 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1219 continue;
1221 foreach ($parent_config->$type as $javascript) {
1222 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1223 and in_array($javascript, $excludes[$parent])) {
1224 continue;
1226 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1227 if (is_readable($javascriptfile)) {
1228 $js[] = $javascriptfile;
1234 // current theme javascripts
1235 if (is_array($this->$type)) {
1236 foreach ($this->$type as $javascript) {
1237 $javascriptfile = "$this->dir/javascript/$javascript.js";
1238 if (is_readable($javascriptfile)) {
1239 $js[] = $javascriptfile;
1243 return $js;
1247 * Resolves an exclude setting to the themes setting is applicable or the
1248 * setting of its closest parent.
1250 * @param string $variable The name of the setting the exclude setting to resolve
1251 * @param string $default
1252 * @return mixed
1254 protected function resolve_excludes($variable, $default = null) {
1255 $setting = $default;
1256 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1257 $setting = $this->{$variable};
1258 } else {
1259 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1260 if (!isset($parent_config->{$variable})) {
1261 continue;
1263 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1264 $setting = $parent_config->{$variable};
1265 break;
1269 return $setting;
1273 * Returns the content of the one huge javascript file merged from all theme javascript files.
1275 * @param bool $type
1276 * @return string
1278 public function javascript_content($type) {
1279 $jsfiles = $this->javascript_files($type);
1280 $js = '';
1281 foreach ($jsfiles as $jsfile) {
1282 $js .= file_get_contents($jsfile)."\n";
1284 return $js;
1288 * Post processes CSS.
1290 * This method post processes all of the CSS before it is served for this theme.
1291 * This is done so that things such as image URL's can be swapped in and to
1292 * run any specific CSS post process method the theme has requested.
1293 * This allows themes to use CSS settings.
1295 * @param string $css The CSS to process.
1296 * @return string The processed CSS.
1298 public function post_process($css) {
1299 // now resolve all image locations
1300 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1301 $replaced = array();
1302 foreach ($matches as $match) {
1303 if (isset($replaced[$match[0]])) {
1304 continue;
1306 $replaced[$match[0]] = true;
1307 $imagename = $match[2];
1308 $component = rtrim($match[1], '|');
1309 $imageurl = $this->pix_url($imagename, $component)->out(false);
1310 // we do not need full url because the image.php is always in the same dir
1311 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1312 $css = str_replace($match[0], $imageurl, $css);
1316 // Now resolve all font locations.
1317 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1318 $replaced = array();
1319 foreach ($matches as $match) {
1320 if (isset($replaced[$match[0]])) {
1321 continue;
1323 $replaced[$match[0]] = true;
1324 $fontname = $match[2];
1325 $component = rtrim($match[1], '|');
1326 $fonturl = $this->font_url($fontname, $component)->out(false);
1327 // We do not need full url because the font.php is always in the same dir.
1328 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1329 $css = str_replace($match[0], $fonturl, $css);
1333 // now resolve all theme settings or do any other postprocessing
1334 $csspostprocess = $this->csspostprocess;
1335 if (function_exists($csspostprocess)) {
1336 $css = $csspostprocess($css, $this);
1339 return $css;
1343 * Return the URL for an image
1345 * @param string $imagename the name of the icon.
1346 * @param string $component specification of one plugin like in get_string()
1347 * @return moodle_url
1349 public function pix_url($imagename, $component) {
1350 global $CFG;
1352 $params = array('theme'=>$this->name);
1353 $svg = $this->use_svg_icons();
1355 if (empty($component) or $component === 'moodle' or $component === 'core') {
1356 $params['component'] = 'core';
1357 } else {
1358 $params['component'] = $component;
1361 $rev = theme_get_revision();
1362 if ($rev != -1) {
1363 $params['rev'] = $rev;
1366 $params['image'] = $imagename;
1368 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1369 if (!empty($CFG->slasharguments) and $rev > 0) {
1370 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1371 if (!$svg) {
1372 // We add a simple /_s to the start of the path.
1373 // The underscore is used to ensure that it isn't a valid theme name.
1374 $path = '/_s'.$path;
1376 $url->set_slashargument($path, 'noparam', true);
1377 } else {
1378 if (!$svg) {
1379 // We add an SVG param so that we know not to serve SVG images.
1380 // We do this because all modern browsers support SVG and this param will one day be removed.
1381 $params['svg'] = '0';
1383 $url->params($params);
1386 return $url;
1390 * Return the URL for a font
1392 * @param string $font the name of the font (including extension).
1393 * @param string $component specification of one plugin like in get_string()
1394 * @return moodle_url
1396 public function font_url($font, $component) {
1397 global $CFG;
1399 $params = array('theme'=>$this->name);
1401 if (empty($component) or $component === 'moodle' or $component === 'core') {
1402 $params['component'] = 'core';
1403 } else {
1404 $params['component'] = $component;
1407 $rev = theme_get_revision();
1408 if ($rev != -1) {
1409 $params['rev'] = $rev;
1412 $params['font'] = $font;
1414 $url = new moodle_url("$CFG->httpswwwroot/theme/font.php");
1415 if (!empty($CFG->slasharguments) and $rev > 0) {
1416 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1417 $url->set_slashargument($path, 'noparam', true);
1418 } else {
1419 $url->params($params);
1422 return $url;
1426 * Returns URL to the stored file via pluginfile.php.
1428 * Note the theme must also implement pluginfile.php handler,
1429 * theme revision is used instead of the itemid.
1431 * @param string $setting
1432 * @param string $filearea
1433 * @return string protocol relative URL or null if not present
1435 public function setting_file_url($setting, $filearea) {
1436 global $CFG;
1438 if (empty($this->settings->$setting)) {
1439 return null;
1442 $component = 'theme_'.$this->name;
1443 $itemid = theme_get_revision();
1444 $filepath = $this->settings->$setting;
1445 $syscontext = context_system::instance();
1447 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1449 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1450 // Note: unfortunately moodle_url does not support //urls yet.
1452 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1454 return $url;
1458 * Serve the theme setting file.
1460 * @param string $filearea
1461 * @param array $args
1462 * @param bool $forcedownload
1463 * @param array $options
1464 * @return bool may terminate if file not found or donotdie not specified
1466 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1467 global $CFG;
1468 require_once("$CFG->libdir/filelib.php");
1470 $syscontext = context_system::instance();
1471 $component = 'theme_'.$this->name;
1473 $revision = array_shift($args);
1474 if ($revision < 0) {
1475 $lifetime = 0;
1476 } else {
1477 $lifetime = 60*60*24*60;
1478 // By default, theme files must be cache-able by both browsers and proxies.
1479 if (!array_key_exists('cacheability', $options)) {
1480 $options['cacheability'] = 'public';
1484 $fs = get_file_storage();
1485 $relativepath = implode('/', $args);
1487 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1488 $fullpath = rtrim($fullpath, '/');
1489 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1490 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1491 return true;
1492 } else {
1493 send_file_not_found();
1498 * Resolves the real image location.
1500 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1501 * and we need a way in which to turn it off.
1502 * By default SVG won't be used unless asked for. This is done for two reasons:
1503 * 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
1504 * browser supports SVG.
1505 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1506 * by the user due to security concerns.
1508 * @param string $image name of image, may contain relative path
1509 * @param string $component
1510 * @param bool $svg If set to true SVG images will also be looked for.
1511 * @return string full file path
1513 public function resolve_image_location($image, $component, $svg = false) {
1514 global $CFG;
1516 if (!is_bool($svg)) {
1517 // If $svg isn't a bool then we need to decide for ourselves.
1518 $svg = $this->use_svg_icons();
1521 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1522 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1523 return $imagefile;
1525 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1526 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1527 return $imagefile;
1530 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1531 return $imagefile;
1533 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1534 return $imagefile;
1536 return null;
1538 } else if ($component === 'theme') { //exception
1539 if ($image === 'favicon') {
1540 return "$this->dir/pix/favicon.ico";
1542 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1543 return $imagefile;
1545 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1546 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1547 return $imagefile;
1550 return null;
1552 } else {
1553 if (strpos($component, '_') === false) {
1554 $component = 'mod_'.$component;
1556 list($type, $plugin) = explode('_', $component, 2);
1558 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1559 return $imagefile;
1561 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1562 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1563 return $imagefile;
1566 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1567 return $imagefile;
1569 $dir = core_component::get_plugin_directory($type, $plugin);
1570 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1571 return $imagefile;
1573 return null;
1578 * Resolves the real font location.
1580 * @param string $font name of font file
1581 * @param string $component
1582 * @return string full file path
1584 public function resolve_font_location($font, $component) {
1585 global $CFG;
1587 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1588 if (file_exists("$this->dir/fonts_core/$font")) {
1589 return "$this->dir/fonts_core/$font";
1591 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1592 if (file_exists("$parent_config->dir/fonts_core/$font")) {
1593 return "$parent_config->dir/fonts_core/$font";
1596 if (file_exists("$CFG->dataroot/fonts/$font")) {
1597 return "$CFG->dataroot/fonts/$font";
1599 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
1600 return "$CFG->dirroot/lib/fonts/$font";
1602 return null;
1604 } else if ($component === 'theme') { // Exception.
1605 if (file_exists("$this->dir/fonts/$font")) {
1606 return "$this->dir/fonts/$font";
1608 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1609 if (file_exists("$parent_config->dir/fonts/$font")) {
1610 return "$parent_config->dir/fonts/$font";
1613 return null;
1615 } else {
1616 if (strpos($component, '_') === false) {
1617 $component = 'mod_'.$component;
1619 list($type, $plugin) = explode('_', $component, 2);
1621 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
1622 return "$this->dir/fonts_plugins/$type/$plugin/$font";
1624 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1625 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
1626 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
1629 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
1630 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
1632 $dir = core_component::get_plugin_directory($type, $plugin);
1633 if (file_exists("$dir/fonts/$font")) {
1634 return "$dir/fonts/$font";
1636 return null;
1641 * Return true if we should look for SVG images as well.
1643 * @return bool
1645 public function use_svg_icons() {
1646 global $CFG;
1647 if ($this->usesvg === null) {
1649 if (!isset($CFG->svgicons) || !is_bool($CFG->svgicons)) {
1650 $this->usesvg = core_useragent::supports_svg();
1651 } else {
1652 // Force them on/off depending upon the setting.
1653 $this->usesvg = $CFG->svgicons;
1656 return $this->usesvg;
1660 * Forces the usesvg setting to either true or false, avoiding any decision making.
1662 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
1663 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
1665 * @param bool $setting True to force the use of svg when available, null otherwise.
1667 public function force_svg_use($setting) {
1668 $this->usesvg = (bool)$setting;
1672 * Checks if file with any image extension exists.
1674 * The order to these images was adjusted prior to the release of 2.4
1675 * At that point the were the following image counts in Moodle core:
1677 * - png = 667 in pix dirs (1499 total)
1678 * - gif = 385 in pix dirs (606 total)
1679 * - jpg = 62 in pix dirs (74 total)
1680 * - jpeg = 0 in pix dirs (1 total)
1682 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1684 * @param string $filepath
1685 * @param bool $svg If set to true SVG images will also be looked for.
1686 * @return string image name with extension
1688 private static function image_exists($filepath, $svg = false) {
1689 if ($svg && file_exists("$filepath.svg")) {
1690 return "$filepath.svg";
1691 } else if (file_exists("$filepath.png")) {
1692 return "$filepath.png";
1693 } else if (file_exists("$filepath.gif")) {
1694 return "$filepath.gif";
1695 } else if (file_exists("$filepath.jpg")) {
1696 return "$filepath.jpg";
1697 } else if (file_exists("$filepath.jpeg")) {
1698 return "$filepath.jpeg";
1699 } else {
1700 return false;
1705 * Loads the theme config from config.php file.
1707 * @param string $themename
1708 * @param stdClass $settings from config_plugins table
1709 * @param boolean $parentscheck true to also check the parents. .
1710 * @return stdClass The theme configuration
1712 private static function find_theme_config($themename, $settings, $parentscheck = true) {
1713 // We have to use the variable name $THEME (upper case) because that
1714 // is what is used in theme config.php files.
1716 if (!$dir = theme_config::find_theme_location($themename)) {
1717 return null;
1720 $THEME = new stdClass();
1721 $THEME->name = $themename;
1722 $THEME->dir = $dir;
1723 $THEME->settings = $settings;
1725 global $CFG; // just in case somebody tries to use $CFG in theme config
1726 include("$THEME->dir/config.php");
1728 // verify the theme configuration is OK
1729 if (!is_array($THEME->parents)) {
1730 // parents option is mandatory now
1731 return null;
1732 } else {
1733 // We use $parentscheck to only check the direct parents (avoid infinite loop).
1734 if ($parentscheck) {
1735 // Find all parent theme configs.
1736 foreach ($THEME->parents as $parent) {
1737 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
1738 if (empty($parentconfig)) {
1739 return null;
1745 return $THEME;
1749 * Finds the theme location and verifies the theme has all needed files
1750 * and is not obsoleted.
1752 * @param string $themename
1753 * @return string full dir path or null if not found
1755 private static function find_theme_location($themename) {
1756 global $CFG;
1758 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1759 $dir = "$CFG->dirroot/theme/$themename";
1761 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1762 $dir = "$CFG->themedir/$themename";
1764 } else {
1765 return null;
1768 if (file_exists("$dir/styles.php")) {
1769 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1770 return null;
1773 return $dir;
1777 * Get the renderer for a part of Moodle for this theme.
1779 * @param moodle_page $page the page we are rendering
1780 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1781 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1782 * @param string $target one of rendering target constants
1783 * @return renderer_base the requested renderer.
1785 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1786 if (is_null($this->rf)) {
1787 $classname = $this->rendererfactory;
1788 $this->rf = new $classname($this);
1791 return $this->rf->get_renderer($page, $component, $subtype, $target);
1795 * Get the information from {@link $layouts} for this type of page.
1797 * @param string $pagelayout the the page layout name.
1798 * @return array the appropriate part of {@link $layouts}.
1800 protected function layout_info_for_page($pagelayout) {
1801 if (array_key_exists($pagelayout, $this->layouts)) {
1802 return $this->layouts[$pagelayout];
1803 } else {
1804 debugging('Invalid page layout specified: ' . $pagelayout);
1805 return $this->layouts['standard'];
1810 * Given the settings of this theme, and the page pagelayout, return the
1811 * full path of the page layout file to use.
1813 * Used by {@link core_renderer::header()}.
1815 * @param string $pagelayout the the page layout name.
1816 * @return string Full path to the lyout file to use
1818 public function layout_file($pagelayout) {
1819 global $CFG;
1821 $layoutinfo = $this->layout_info_for_page($pagelayout);
1822 $layoutfile = $layoutinfo['file'];
1824 if (array_key_exists('theme', $layoutinfo)) {
1825 $themes = array($layoutinfo['theme']);
1826 } else {
1827 $themes = array_merge(array($this->name),$this->parents);
1830 foreach ($themes as $theme) {
1831 if ($dir = $this->find_theme_location($theme)) {
1832 $path = "$dir/layout/$layoutfile";
1834 // Check the template exists, return general base theme template if not.
1835 if (is_readable($path)) {
1836 return $path;
1841 debugging('Can not find layout file for: ' . $pagelayout);
1842 // fallback to standard normal layout
1843 return "$CFG->dirroot/theme/base/layout/general.php";
1847 * Returns auxiliary page layout options specified in layout configuration array.
1849 * @param string $pagelayout
1850 * @return array
1852 public function pagelayout_options($pagelayout) {
1853 $info = $this->layout_info_for_page($pagelayout);
1854 if (!empty($info['options'])) {
1855 return $info['options'];
1857 return array();
1861 * Inform a block_manager about the block regions this theme wants on this
1862 * page layout.
1864 * @param string $pagelayout the general type of the page.
1865 * @param block_manager $blockmanager the block_manger to set up.
1867 public function setup_blocks($pagelayout, $blockmanager) {
1868 $layoutinfo = $this->layout_info_for_page($pagelayout);
1869 if (!empty($layoutinfo['regions'])) {
1870 $blockmanager->add_regions($layoutinfo['regions'], false);
1871 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1876 * Gets the visible name for the requested block region.
1878 * @param string $region The region name to get
1879 * @param string $theme The theme the region belongs to (may come from the parent theme)
1880 * @return string
1882 protected function get_region_name($region, $theme) {
1883 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1884 // A name exists in this theme, so use it
1885 if (substr($regionstring, 0, 1) != '[') {
1886 return $regionstring;
1889 // Otherwise, try to find one elsewhere
1890 // Check parents, if any
1891 foreach ($this->parents as $parentthemename) {
1892 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1893 if (substr($regionstring, 0, 1) != '[') {
1894 return $regionstring;
1898 // Last resort, try the base theme for names
1899 return get_string('region-' . $region, 'theme_base');
1903 * Get the list of all block regions known to this theme in all templates.
1905 * @return array internal region name => human readable name.
1907 public function get_all_block_regions() {
1908 $regions = array();
1909 foreach ($this->layouts as $layoutinfo) {
1910 foreach ($layoutinfo['regions'] as $region) {
1911 $regions[$region] = $this->get_region_name($region, $this->name);
1914 return $regions;
1918 * Returns the human readable name of the theme
1920 * @return string
1922 public function get_theme_name() {
1923 return get_string('pluginname', 'theme_'.$this->name);
1927 * Returns the block render method.
1929 * It is set by the theme via:
1930 * $THEME->blockrendermethod = '...';
1932 * It can be one of two values, blocks or blocks_for_region.
1933 * It should be set to the method being used by the theme layouts.
1935 * @return string
1937 public function get_block_render_method() {
1938 if ($this->blockrendermethod) {
1939 // Return the specified block render method.
1940 return $this->blockrendermethod;
1942 // Its not explicitly set, check the parent theme configs.
1943 foreach ($this->parent_configs as $config) {
1944 if (isset($config->blockrendermethod)) {
1945 return $config->blockrendermethod;
1948 // Default it to blocks.
1949 return 'blocks';
1954 * This class keeps track of which HTML tags are currently open.
1956 * This makes it much easier to always generate well formed XHTML output, even
1957 * if execution terminates abruptly. Any time you output some opening HTML
1958 * without the matching closing HTML, you should push the necessary close tags
1959 * onto the stack.
1961 * @copyright 2009 Tim Hunt
1962 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1963 * @since Moodle 2.0
1964 * @package core
1965 * @category output
1967 class xhtml_container_stack {
1970 * @var array Stores the list of open containers.
1972 protected $opencontainers = array();
1975 * @var array In developer debug mode, stores a stack trace of all opens and
1976 * closes, so we can output helpful error messages when there is a mismatch.
1978 protected $log = array();
1981 * @var boolean Store whether we are developer debug mode. We need this in
1982 * several places including in the destructor where we may not have access to $CFG.
1984 protected $isdebugging;
1987 * Constructor
1989 public function __construct() {
1990 global $CFG;
1991 $this->isdebugging = $CFG->debugdeveloper;
1995 * Push the close HTML for a recently opened container onto the stack.
1997 * @param string $type The type of container. This is checked when {@link pop()}
1998 * is called and must match, otherwise a developer debug warning is output.
1999 * @param string $closehtml The HTML required to close the container.
2001 public function push($type, $closehtml) {
2002 $container = new stdClass;
2003 $container->type = $type;
2004 $container->closehtml = $closehtml;
2005 if ($this->isdebugging) {
2006 $this->log('Open', $type);
2008 array_push($this->opencontainers, $container);
2012 * Pop the HTML for the next closing container from the stack. The $type
2013 * must match the type passed when the container was opened, otherwise a
2014 * warning will be output.
2016 * @param string $type The type of container.
2017 * @return string the HTML required to close the container.
2019 public function pop($type) {
2020 if (empty($this->opencontainers)) {
2021 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2022 $this->output_log(), DEBUG_DEVELOPER);
2023 return;
2026 $container = array_pop($this->opencontainers);
2027 if ($container->type != $type) {
2028 debugging('<p>The type of container to be closed (' . $container->type .
2029 ') does not match the type of the next open container (' . $type .
2030 '). This suggests there is a nesting problem.</p>' .
2031 $this->output_log(), DEBUG_DEVELOPER);
2033 if ($this->isdebugging) {
2034 $this->log('Close', $type);
2036 return $container->closehtml;
2040 * Close all but the last open container. This is useful in places like error
2041 * handling, where you want to close all the open containers (apart from <body>)
2042 * before outputting the error message.
2044 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2045 * developer debug warning if it isn't.
2046 * @return string the HTML required to close any open containers inside <body>.
2048 public function pop_all_but_last($shouldbenone = false) {
2049 if ($shouldbenone && count($this->opencontainers) != 1) {
2050 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2051 $this->output_log(), DEBUG_DEVELOPER);
2053 $output = '';
2054 while (count($this->opencontainers) > 1) {
2055 $container = array_pop($this->opencontainers);
2056 $output .= $container->closehtml;
2058 return $output;
2062 * You can call this function if you want to throw away an instance of this
2063 * class without properly emptying the stack (for example, in a unit test).
2064 * Calling this method stops the destruct method from outputting a developer
2065 * debug warning. After calling this method, the instance can no longer be used.
2067 public function discard() {
2068 $this->opencontainers = null;
2072 * Adds an entry to the log.
2074 * @param string $action The name of the action
2075 * @param string $type The type of action
2077 protected function log($action, $type) {
2078 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
2079 format_backtrace(debug_backtrace()) . '</li>';
2083 * Outputs the log's contents as a HTML list.
2085 * @return string HTML list of the log
2087 protected function output_log() {
2088 return '<ul>' . implode("\n", $this->log) . '</ul>';