Merge branch 'MDL-52763-30' of git://github.com/danpoltawski/moodle into MOODLE_30_STABLE
[moodle.git] / lib / outputlib.php
blob64e02997da42490c91ea38c2180fd14adb446d13
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 = 'clean';
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 Accessibility: Right arrow-like character is
289 * used in the breadcrumb trail, course navigation menu
290 * (previous/next activity), calendar, and search forum block.
291 * If the theme does not set characters, appropriate defaults
292 * are set automatically. Please DO NOT
293 * use &lt; &gt; &raquo; - these are confusing for blind users.
295 public $rarrow = null;
298 * @var string Accessibility: Left arrow-like character is
299 * used in the breadcrumb trail, course navigation menu
300 * (previous/next activity), calendar, and search forum block.
301 * If the theme does not set characters, appropriate defaults
302 * are set automatically. Please DO NOT
303 * use &lt; &gt; &raquo; - these are confusing for blind users.
305 public $larrow = null;
308 * @var string Accessibility: Up arrow-like character is used in
309 * the book heirarchical navigation.
310 * If the theme does not set characters, appropriate defaults
311 * are set automatically. Please DO NOT
312 * use ^ - this is confusing for blind users.
314 public $uarrow = null;
317 * @var bool Some themes may want to disable ajax course editing.
319 public $enablecourseajax = true;
322 * @var string Determines served document types
323 * - 'html5' the only officially supported doctype in Moodle
324 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
325 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
327 public $doctype = 'html5';
329 //==Following properties are not configurable from theme config.php==
332 * @var string The name of this theme. Set automatically when this theme is
333 * loaded. This can not be set in theme config.php
335 public $name;
338 * @var string The folder where this themes files are stored. This is set
339 * automatically. This can not be set in theme config.php
341 public $dir;
344 * @var stdClass Theme settings stored in config_plugins table.
345 * This can not be set in theme config.php
347 public $setting = null;
350 * @var bool If set to true and the theme enables the dock then blocks will be able
351 * to be moved to the special dock
353 public $enable_dock = false;
356 * @var bool If set to true then this theme will not be shown in the theme selector unless
357 * theme designer mode is turned on.
359 public $hidefromselector = false;
362 * @var array list of YUI CSS modules to be included on each page. This may be used
363 * to remove cssreset and use cssnormalise module instead.
365 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
368 * An associative array of block manipulations that should be made if the user is using an rtl language.
369 * The key is the original block region, and the value is the block region to change to.
370 * This is used when displaying blocks for regions only.
371 * @var array
373 public $blockrtlmanipulations = array();
376 * @var renderer_factory Instance of the renderer_factory implementation
377 * we are using. Implementation detail.
379 protected $rf = null;
382 * @var array List of parent config objects.
384 protected $parent_configs = array();
387 * @var bool If set to true then the theme is safe to run through the optimiser (if it is enabled)
388 * If set to false then we know either the theme has already been optimised and the CSS optimiser is not needed
389 * or the theme is not compatible with the CSS optimiser. In both cases even if enabled the CSS optimiser will not
390 * be used with this theme if set to false.
392 public $supportscssoptimisation = true;
395 * Used to determine whether we can serve SVG images or not.
396 * @var bool
398 private $usesvg = null;
401 * The LESS file to compile. When set, the theme will attempt to compile the file itself.
402 * @var bool
404 public $lessfile = false;
407 * The name of the function to call to get the LESS code to inject.
408 * @var string
410 public $extralesscallback = null;
413 * The name of the function to call to get extra LESS variables.
414 * @var string
416 public $lessvariablescallback = null;
419 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
420 * Defaults to {@link core_renderer::blocks_for_region()}
421 * @var string
423 public $blockrendermethod = null;
426 * Load the config.php file for a particular theme, and return an instance
427 * of this class. (That is, this is a factory method.)
429 * @param string $themename the name of the theme.
430 * @return theme_config an instance of this class.
432 public static function load($themename) {
433 global $CFG;
435 // load theme settings from db
436 try {
437 $settings = get_config('theme_'.$themename);
438 } catch (dml_exception $e) {
439 // most probably moodle tables not created yet
440 $settings = new stdClass();
443 if ($config = theme_config::find_theme_config($themename, $settings)) {
444 return new theme_config($config);
446 } else if ($themename == theme_config::DEFAULT_THEME) {
447 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
449 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
450 return new theme_config($config);
452 } else {
453 // bad luck, the requested theme has some problems - admin see details in theme config
454 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
459 * Theme diagnostic code. It is very problematic to send debug output
460 * to the actual CSS file, instead this functions is supposed to
461 * diagnose given theme and highlights all potential problems.
462 * This information should be available from the theme selection page
463 * or some other debug page for theme designers.
465 * @param string $themename
466 * @return array description of problems
468 public static function diagnose($themename) {
469 //TODO: MDL-21108
470 return array();
474 * Private constructor, can be called only from the factory method.
475 * @param stdClass $config
477 private function __construct($config) {
478 global $CFG; //needed for included lib.php files
480 $this->settings = $config->settings;
481 $this->name = $config->name;
482 $this->dir = $config->dir;
484 if ($this->name != 'base') {
485 $baseconfig = theme_config::find_theme_config('base', $this->settings);
486 } else {
487 $baseconfig = $config;
490 $configurable = array(
491 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets',
492 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
493 'layouts', 'enable_dock', 'enablecourseajax', 'supportscssoptimisation',
494 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'uarrow',
495 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations',
496 'lessfile', 'extralesscallback', 'lessvariablescallback', 'blockrendermethod');
498 foreach ($config as $key=>$value) {
499 if (in_array($key, $configurable)) {
500 $this->$key = $value;
504 // verify all parents and load configs and renderers
505 foreach ($this->parents as $parent) {
506 if ($parent == 'base') {
507 $parent_config = $baseconfig;
508 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
509 // this is not good - better exclude faulty parents
510 continue;
512 $libfile = $parent_config->dir.'/lib.php';
513 if (is_readable($libfile)) {
514 // theme may store various function here
515 include_once($libfile);
517 $renderersfile = $parent_config->dir.'/renderers.php';
518 if (is_readable($renderersfile)) {
519 // may contain core and plugin renderers and renderer factory
520 include_once($renderersfile);
522 $this->parent_configs[$parent] = $parent_config;
524 $libfile = $this->dir.'/lib.php';
525 if (is_readable($libfile)) {
526 // theme may store various function here
527 include_once($libfile);
529 $rendererfile = $this->dir.'/renderers.php';
530 if (is_readable($rendererfile)) {
531 // may contain core and plugin renderers and renderer factory
532 include_once($rendererfile);
533 } else {
534 // check if renderers.php file is missnamed renderer.php
535 if (is_readable($this->dir.'/renderer.php')) {
536 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
537 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
541 // cascade all layouts properly
542 foreach ($baseconfig->layouts as $layout=>$value) {
543 if (!isset($this->layouts[$layout])) {
544 foreach ($this->parent_configs as $parent_config) {
545 if (isset($parent_config->layouts[$layout])) {
546 $this->layouts[$layout] = $parent_config->layouts[$layout];
547 continue 2;
550 $this->layouts[$layout] = $value;
554 //fix arrows if needed
555 $this->check_theme_arrows();
559 * Let the theme initialise the page object (usually $PAGE).
561 * This may be used for example to request jQuery in add-ons.
563 * @param moodle_page $page
565 public function init_page(moodle_page $page) {
566 $themeinitfunction = 'theme_'.$this->name.'_page_init';
567 if (function_exists($themeinitfunction)) {
568 $themeinitfunction($page);
573 * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow have been set (theme/-/config.php).
574 * If not it applies sensible defaults.
576 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
577 * search forum block, etc. Important: these are 'silent' in a screen-reader
578 * (unlike &gt; &raquo;), and must be accompanied by text.
580 private function check_theme_arrows() {
581 if (!isset($this->rarrow) and !isset($this->larrow)) {
582 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
583 // Also OK in Win 9x/2K/IE 5.x
584 $this->rarrow = '&#x25BA;';
585 $this->larrow = '&#x25C4;';
586 $this->uarrow = '&#x25B2;';
587 if (empty($_SERVER['HTTP_USER_AGENT'])) {
588 $uagent = '';
589 } else {
590 $uagent = $_SERVER['HTTP_USER_AGENT'];
592 if (false !== strpos($uagent, 'Opera')
593 || false !== strpos($uagent, 'Mac')) {
594 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
595 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
596 $this->rarrow = '&#x25B6;&#xFE0E;';
597 $this->larrow = '&#x25C0;&#xFE0E;';
599 elseif ((false !== strpos($uagent, 'Konqueror'))
600 || (false !== strpos($uagent, 'Android'))) {
601 // The fonts on Android don't include the characters required for this to work as expected.
602 // So we use the same ones Konqueror uses.
603 $this->rarrow = '&rarr;';
604 $this->larrow = '&larr;';
605 $this->uarrow = '&uarr;';
607 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
608 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
609 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
610 // To be safe, non-Unicode browsers!
611 $this->rarrow = '&gt;';
612 $this->larrow = '&lt;';
613 $this->uarrow = '^';
616 // RTL support - in RTL languages, swap r and l arrows
617 if (right_to_left()) {
618 $t = $this->rarrow;
619 $this->rarrow = $this->larrow;
620 $this->larrow = $t;
626 * Returns output renderer prefixes, these are used when looking
627 * for the overridden renderers in themes.
629 * @return array
631 public function renderer_prefixes() {
632 global $CFG; // just in case the included files need it
634 $prefixes = array('theme_'.$this->name);
636 foreach ($this->parent_configs as $parent) {
637 $prefixes[] = 'theme_'.$parent->name;
640 return $prefixes;
644 * Returns the stylesheet URL of this editor content
646 * @param bool $encoded false means use & and true use &amp; in URLs
647 * @return moodle_url
649 public function editor_css_url($encoded=true) {
650 global $CFG;
651 $rev = theme_get_revision();
652 if ($rev > -1) {
653 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
654 if (!empty($CFG->slasharguments)) {
655 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
656 } else {
657 $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
659 } else {
660 $params = array('theme'=>$this->name, 'type'=>'editor');
661 $url = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
663 return $url;
667 * Returns the content of the CSS to be used in editor content
669 * @return array
671 public function editor_css_files() {
672 $files = array();
674 // First editor plugins.
675 $plugins = core_component::get_plugin_list('editor');
676 foreach ($plugins as $plugin=>$fulldir) {
677 $sheetfile = "$fulldir/editor_styles.css";
678 if (is_readable($sheetfile)) {
679 $files['plugin_'.$plugin] = $sheetfile;
682 // Then parent themes - base first, the immediate parent last.
683 foreach (array_reverse($this->parent_configs) as $parent_config) {
684 if (empty($parent_config->editor_sheets)) {
685 continue;
687 foreach ($parent_config->editor_sheets as $sheet) {
688 $sheetfile = "$parent_config->dir/style/$sheet.css";
689 if (is_readable($sheetfile)) {
690 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
694 // Finally this theme.
695 if (!empty($this->editor_sheets)) {
696 foreach ($this->editor_sheets as $sheet) {
697 $sheetfile = "$this->dir/style/$sheet.css";
698 if (is_readable($sheetfile)) {
699 $files['theme_'.$sheet] = $sheetfile;
704 return $files;
708 * Get the stylesheet URL of this theme.
710 * @param moodle_page $page Not used... deprecated?
711 * @return moodle_url[]
713 public function css_urls(moodle_page $page) {
714 global $CFG;
716 $rev = theme_get_revision();
718 $urls = array();
720 $svg = $this->use_svg_icons();
721 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
723 if ($rev > -1) {
724 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
725 if (!empty($CFG->slasharguments)) {
726 $slashargs = '';
727 if (!$svg) {
728 // We add a simple /_s to the start of the path.
729 // The underscore is used to ensure that it isn't a valid theme name.
730 $slashargs .= '/_s'.$slashargs;
732 $slashargs .= '/'.$this->name.'/'.$rev.'/all';
733 if ($separate) {
734 $slashargs .= '/chunk0';
736 $url->set_slashargument($slashargs, 'noparam', true);
737 } else {
738 $params = array('theme' => $this->name,'rev' => $rev, 'type' => 'all');
739 if (!$svg) {
740 // We add an SVG param so that we know not to serve SVG images.
741 // We do this because all modern browsers support SVG and this param will one day be removed.
742 $params['svg'] = '0';
744 if ($separate) {
745 $params['chunk'] = '0';
747 $url->params($params);
749 $urls[] = $url;
751 } else {
752 $baseurl = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php');
754 $css = $this->get_css_files(true);
755 if (!$svg) {
756 // We add an SVG param so that we know not to serve SVG images.
757 // We do this because all modern browsers support SVG and this param will one day be removed.
758 $baseurl->param('svg', '0');
760 if ($separate) {
761 // We might need to chunk long files.
762 $baseurl->param('chunk', '0');
764 if (core_useragent::is_ie()) {
765 // Lalala, IE does not allow more than 31 linked CSS files from main document.
766 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
767 foreach ($css['parents'] as $parent=>$sheets) {
768 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
769 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
771 if (!empty($this->lessfile)) {
772 // No need to define the type as IE here.
773 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
775 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
777 } else {
778 foreach ($css['plugins'] as $plugin=>$unused) {
779 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
781 foreach ($css['parents'] as $parent=>$sheets) {
782 foreach ($sheets as $sheet=>$unused2) {
783 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
786 foreach ($css['theme'] as $sheet => $filename) {
787 if ($sheet === $this->lessfile) {
788 // This is the theme LESS file.
789 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
790 } else {
791 // Sheet first in order to make long urls easier to read.
792 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
798 return $urls;
802 * Get the whole css stylesheet for production mode.
804 * NOTE: this method is not expected to be used from any addons.
806 * @return string CSS markup, already optimised and compressed
808 public function get_css_content() {
809 global $CFG;
810 require_once($CFG->dirroot.'/lib/csslib.php');
812 $csscontent = '';
813 foreach ($this->get_css_files(false) as $type => $value) {
814 foreach ($value as $identifier => $val) {
815 if (is_array($val)) {
816 foreach ($val as $v) {
817 $csscontent .= file_get_contents($v) . "\n";
819 } else {
820 if ($type === 'theme' && $identifier === $this->lessfile) {
821 // We need the content from LESS because this is the LESS file from the theme.
822 $csscontent .= $this->get_css_content_from_less(false);
823 } else {
824 $csscontent .= file_get_contents($val) . "\n";
829 $csscontent = $this->post_process($csscontent);
831 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
832 // This is an experimental feature introduced in Moodle 2.3
833 // The CSS optimiser organises the CSS in order to reduce the overall number
834 // of rules and styles being sent to the client. It does this by collating
835 // the CSS before it is cached removing excess styles and rules and stripping
836 // out any extraneous content such as comments and empty rules.
837 $optimiser = new css_optimiser();
838 $csscontent = $optimiser->process($csscontent);
840 } else {
841 $csscontent = core_minify::css($csscontent);
844 return $csscontent;
848 * Get the theme designer css markup,
849 * the parameters are coming from css_urls().
851 * NOTE: this method is not expected to be used from any addons.
853 * @param string $type
854 * @param string $subtype
855 * @param string $sheet
856 * @return string CSS markup
858 public function get_css_content_debug($type, $subtype, $sheet) {
859 global $CFG;
860 require_once($CFG->dirroot.'/lib/csslib.php');
862 // The LESS file of the theme is requested.
863 if ($type === 'less') {
864 $csscontent = $this->get_css_content_from_less(true);
865 if ($csscontent !== false) {
866 return $csscontent;
868 return '';
871 $optimiser = null;
872 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
873 // This is an experimental feature introduced in Moodle 2.3
874 // The CSS optimiser organises the CSS in order to reduce the overall number
875 // of rules and styles being sent to the client. It does this by collating
876 // the CSS before it is cached removing excess styles and rules and stripping
877 // out any extraneous content such as comments and empty rules.
878 $optimiser = new css_optimiser();
881 $cssfiles = array();
882 $css = $this->get_css_files(true);
884 if ($type === 'ie') {
885 // IE is a sloppy browser with weird limits, sorry.
886 if ($subtype === 'plugins') {
887 $cssfiles = $css['plugins'];
889 } else if ($subtype === 'parents') {
890 if (empty($sheet)) {
891 // Do not bother with the empty parent here.
892 } else {
893 // Build up the CSS for that parent so we can serve it as one file.
894 foreach ($css[$subtype][$sheet] as $parent => $css) {
895 $cssfiles[] = $css;
898 } else if ($subtype === 'theme') {
899 $cssfiles = $css['theme'];
900 foreach ($cssfiles as $key => $value) {
901 if ($this->lessfile && $key === $this->lessfile) {
902 // Remove the LESS file from the theme CSS files.
903 // The LESS files use the type 'less', not 'ie'.
904 unset($cssfiles[$key]);
909 } else if ($type === 'plugin') {
910 if (isset($css['plugins'][$subtype])) {
911 $cssfiles[] = $css['plugins'][$subtype];
914 } else if ($type === 'parent') {
915 if (isset($css['parents'][$subtype][$sheet])) {
916 $cssfiles[] = $css['parents'][$subtype][$sheet];
919 } else if ($type === 'theme') {
920 if (isset($css['theme'][$sheet])) {
921 $cssfiles[] = $css['theme'][$sheet];
925 $csscontent = '';
926 foreach ($cssfiles as $file) {
927 $contents = file_get_contents($file);
928 $contents = $this->post_process($contents);
929 $comment = "/** Path: $type $subtype $sheet.' **/\n";
930 $stats = '';
931 if ($optimiser) {
932 $contents = $optimiser->process($contents);
933 if (!empty($CFG->cssoptimiserstats)) {
934 $stats = $optimiser->output_stats_css();
937 $csscontent .= $comment.$stats.$contents."\n\n";
940 return $csscontent;
944 * Get the whole css stylesheet for editor iframe.
946 * NOTE: this method is not expected to be used from any addons.
948 * @return string CSS markup
950 public function get_css_content_editor() {
951 // Do not bother to optimise anything here, just very basic stuff.
952 $cssfiles = $this->editor_css_files();
953 $css = '';
954 foreach ($cssfiles as $file) {
955 $css .= file_get_contents($file)."\n";
957 return $this->post_process($css);
961 * Returns an array of organised CSS files required for this output.
963 * @param bool $themedesigner
964 * @return array nested array of file paths
966 protected function get_css_files($themedesigner) {
967 global $CFG;
969 $cache = null;
970 $cachekey = 'cssfiles';
971 if ($themedesigner) {
972 require_once($CFG->dirroot.'/lib/csslib.php');
973 // We need some kind of caching here because otherwise the page navigation becomes
974 // way too slow in theme designer mode. Feel free to create full cache definition later...
975 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
976 if ($files = $cache->get($cachekey)) {
977 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
978 unset($files['created']);
979 return $files;
984 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
986 // Get all plugin sheets.
987 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
988 if ($excludes !== true) {
989 foreach (core_component::get_plugin_types() as $type=>$unused) {
990 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
991 continue;
993 $plugins = core_component::get_plugin_list($type);
994 foreach ($plugins as $plugin=>$fulldir) {
995 if (!empty($excludes[$type]) and is_array($excludes[$type])
996 and in_array($plugin, $excludes[$type])) {
997 continue;
1000 // Get the CSS from the plugin.
1001 $sheetfile = "$fulldir/styles.css";
1002 if (is_readable($sheetfile)) {
1003 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
1006 // Create a list of candidate sheets from parents (direct parent last) and current theme.
1007 $candidates = array();
1008 foreach (array_reverse($this->parent_configs) as $parent_config) {
1009 $candidates[] = $parent_config->name;
1011 $candidates[] = $this->name;
1013 // Add the sheets found.
1014 foreach ($candidates as $candidate) {
1015 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1016 if (is_readable($sheetthemefile)) {
1017 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
1024 // Find out wanted parent sheets.
1025 $excludes = $this->resolve_excludes('parents_exclude_sheets');
1026 if ($excludes !== true) {
1027 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1028 $parent = $parent_config->name;
1029 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
1030 continue;
1032 foreach ($parent_config->sheets as $sheet) {
1033 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1034 && in_array($sheet, $excludes[$parent])) {
1035 continue;
1038 // We never refer to the parent LESS files.
1039 $sheetfile = "$parent_config->dir/style/$sheet.css";
1040 if (is_readable($sheetfile)) {
1041 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1047 // Current theme sheets and less file.
1048 // We first add the LESS files because we want the CSS ones to be included after the
1049 // LESS code. However, if both the LESS file and the CSS file share the same name,
1050 // the CSS file is ignored.
1051 if (!empty($this->lessfile)) {
1052 $sheetfile = "{$this->dir}/less/{$this->lessfile}.less";
1053 if (is_readable($sheetfile)) {
1054 $cssfiles['theme'][$this->lessfile] = $sheetfile;
1057 if (is_array($this->sheets)) {
1058 foreach ($this->sheets as $sheet) {
1059 $sheetfile = "$this->dir/style/$sheet.css";
1060 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1061 $cssfiles['theme'][$sheet] = $sheetfile;
1066 if ($cache) {
1067 $files = $cssfiles;
1068 $files['created'] = time();
1069 $cache->set($cachekey, $files);
1071 return $cssfiles;
1075 * Return the CSS content generated from LESS the file.
1077 * @param bool $themedesigner True if theme designer is enabled.
1078 * @return bool|string Return false when the compilation failed. Else the compiled string.
1080 protected function get_css_content_from_less($themedesigner) {
1081 global $CFG;
1083 $lessfile = $this->lessfile;
1084 if (!$lessfile || !is_readable($this->dir . '/less/' . $lessfile . '.less')) {
1085 throw new coding_exception('The theme did not define a LESS file, or it is not readable.');
1088 // We might need more memory to do this, so let's play safe.
1089 raise_memory_limit(MEMORY_EXTRA);
1091 // Files list.
1092 $files = $this->get_css_files($themedesigner);
1094 // Get the LESS file path.
1095 $themelessfile = $files['theme'][$lessfile];
1097 // Setup compiler options.
1098 $options = array(
1099 // We need to set the import directory to where $lessfile is.
1100 'import_dirs' => array(dirname($themelessfile) => '/'),
1101 // Always disable default caching.
1102 'cache_method' => false,
1103 // Disable the relative URLs, we have post_process() to handle that.
1104 'relativeUrls' => false,
1107 if ($themedesigner) {
1108 // Add the sourceMap inline to ensure that it is atomically generated.
1109 $options['sourceMap'] = true;
1110 $options['sourceMapBasepath'] = $CFG->dirroot;
1111 $options['sourceMapRootpath'] = $CFG->wwwroot;
1114 // Instantiate the compiler.
1115 $compiler = new core_lessc($options);
1117 try {
1118 $compiler->parse_file_content($themelessfile);
1120 // Get the callbacks.
1121 $compiler->parse($this->get_extra_less_code());
1122 $compiler->ModifyVars($this->get_less_variables());
1124 // Compile the CSS.
1125 $compiled = $compiler->getCss();
1127 // Post process the entire thing.
1128 $compiled = $this->post_process($compiled);
1129 } catch (Less_Exception_Parser $e) {
1130 $compiled = false;
1131 debugging('Error while compiling LESS ' . $lessfile . ' file: ' . $e->getMessage(), DEBUG_DEVELOPER);
1134 // Try to save memory.
1135 $compiler = null;
1136 unset($compiler);
1138 return $compiled;
1142 * Return extra LESS variables to use when compiling.
1144 * @return array Where keys are the variable names (omitting the @), and the values are the value.
1146 protected function get_less_variables() {
1147 $variables = array();
1149 // Getting all the candidate functions.
1150 $candidates = array();
1151 foreach ($this->parent_configs as $parent_config) {
1152 if (!isset($parent_config->lessvariablescallback)) {
1153 continue;
1155 $candidates[] = $parent_config->lessvariablescallback;
1157 $candidates[] = $this->lessvariablescallback;
1159 // Calling the functions.
1160 foreach ($candidates as $function) {
1161 if (function_exists($function)) {
1162 $vars = $function($this);
1163 if (!is_array($vars)) {
1164 debugging('Callback ' . $function . ' did not return an array() as expected', DEBUG_DEVELOPER);
1165 continue;
1167 $variables = array_merge($variables, $vars);
1171 return $variables;
1175 * Return extra LESS code to add when compiling.
1177 * This is intended to be used by themes to inject some LESS code
1178 * before it gets compiled. If you want to inject variables you
1179 * should use {@link self::get_less_variables()}.
1181 * @return string The LESS code to inject.
1183 protected function get_extra_less_code() {
1184 $content = '';
1186 // Getting all the candidate functions.
1187 $candidates = array();
1188 foreach ($this->parent_configs as $parent_config) {
1189 if (!isset($parent_config->extralesscallback)) {
1190 continue;
1192 $candidates[] = $parent_config->extralesscallback;
1194 $candidates[] = $this->extralesscallback;
1196 // Calling the functions.
1197 foreach ($candidates as $function) {
1198 if (function_exists($function)) {
1199 $content .= "\n/** Extra LESS from $function **/\n" . $function($this) . "\n";
1203 return $content;
1207 * Generate a URL to the file that serves theme JavaScript files.
1209 * If we determine that the theme has no relevant files, then we return
1210 * early with a null value.
1212 * @param bool $inhead true means head url, false means footer
1213 * @return moodle_url|null
1215 public function javascript_url($inhead) {
1216 global $CFG;
1218 $rev = theme_get_revision();
1219 $params = array('theme'=>$this->name,'rev'=>$rev);
1220 $params['type'] = $inhead ? 'head' : 'footer';
1222 // Return early if there are no files to serve
1223 if (count($this->javascript_files($params['type'])) === 0) {
1224 return null;
1227 if (!empty($CFG->slasharguments) and $rev > 0) {
1228 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
1229 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
1230 return $url;
1231 } else {
1232 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
1237 * Get the URL's for the JavaScript files used by this theme.
1238 * They won't be served directly, instead they'll be mediated through
1239 * theme/javascript.php.
1241 * @param string $type Either javascripts_footer, or javascripts
1242 * @return array
1244 public function javascript_files($type) {
1245 if ($type === 'footer') {
1246 $type = 'javascripts_footer';
1247 } else {
1248 $type = 'javascripts';
1251 $js = array();
1252 // find out wanted parent javascripts
1253 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1254 if ($excludes !== true) {
1255 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1256 $parent = $parent_config->name;
1257 if (empty($parent_config->$type)) {
1258 continue;
1260 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1261 continue;
1263 foreach ($parent_config->$type as $javascript) {
1264 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1265 and in_array($javascript, $excludes[$parent])) {
1266 continue;
1268 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1269 if (is_readable($javascriptfile)) {
1270 $js[] = $javascriptfile;
1276 // current theme javascripts
1277 if (is_array($this->$type)) {
1278 foreach ($this->$type as $javascript) {
1279 $javascriptfile = "$this->dir/javascript/$javascript.js";
1280 if (is_readable($javascriptfile)) {
1281 $js[] = $javascriptfile;
1285 return $js;
1289 * Resolves an exclude setting to the themes setting is applicable or the
1290 * setting of its closest parent.
1292 * @param string $variable The name of the setting the exclude setting to resolve
1293 * @param string $default
1294 * @return mixed
1296 protected function resolve_excludes($variable, $default = null) {
1297 $setting = $default;
1298 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1299 $setting = $this->{$variable};
1300 } else {
1301 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1302 if (!isset($parent_config->{$variable})) {
1303 continue;
1305 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1306 $setting = $parent_config->{$variable};
1307 break;
1311 return $setting;
1315 * Returns the content of the one huge javascript file merged from all theme javascript files.
1317 * @param bool $type
1318 * @return string
1320 public function javascript_content($type) {
1321 $jsfiles = $this->javascript_files($type);
1322 $js = '';
1323 foreach ($jsfiles as $jsfile) {
1324 $js .= file_get_contents($jsfile)."\n";
1326 return $js;
1330 * Post processes CSS.
1332 * This method post processes all of the CSS before it is served for this theme.
1333 * This is done so that things such as image URL's can be swapped in and to
1334 * run any specific CSS post process method the theme has requested.
1335 * This allows themes to use CSS settings.
1337 * @param string $css The CSS to process.
1338 * @return string The processed CSS.
1340 public function post_process($css) {
1341 // now resolve all image locations
1342 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1343 $replaced = array();
1344 foreach ($matches as $match) {
1345 if (isset($replaced[$match[0]])) {
1346 continue;
1348 $replaced[$match[0]] = true;
1349 $imagename = $match[2];
1350 $component = rtrim($match[1], '|');
1351 $imageurl = $this->pix_url($imagename, $component)->out(false);
1352 // we do not need full url because the image.php is always in the same dir
1353 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1354 $css = str_replace($match[0], $imageurl, $css);
1358 // Now resolve all font locations.
1359 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1360 $replaced = array();
1361 foreach ($matches as $match) {
1362 if (isset($replaced[$match[0]])) {
1363 continue;
1365 $replaced[$match[0]] = true;
1366 $fontname = $match[2];
1367 $component = rtrim($match[1], '|');
1368 $fonturl = $this->font_url($fontname, $component)->out(false);
1369 // We do not need full url because the font.php is always in the same dir.
1370 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1371 $css = str_replace($match[0], $fonturl, $css);
1375 // now resolve all theme settings or do any other postprocessing
1376 $csspostprocess = $this->csspostprocess;
1377 if (function_exists($csspostprocess)) {
1378 $css = $csspostprocess($css, $this);
1381 return $css;
1385 * Return the URL for an image
1387 * @param string $imagename the name of the icon.
1388 * @param string $component specification of one plugin like in get_string()
1389 * @return moodle_url
1391 public function pix_url($imagename, $component) {
1392 global $CFG;
1394 $params = array('theme'=>$this->name);
1395 $svg = $this->use_svg_icons();
1397 if (empty($component) or $component === 'moodle' or $component === 'core') {
1398 $params['component'] = 'core';
1399 } else {
1400 $params['component'] = $component;
1403 $rev = theme_get_revision();
1404 if ($rev != -1) {
1405 $params['rev'] = $rev;
1408 $params['image'] = $imagename;
1410 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1411 if (!empty($CFG->slasharguments) and $rev > 0) {
1412 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1413 if (!$svg) {
1414 // We add a simple /_s to the start of the path.
1415 // The underscore is used to ensure that it isn't a valid theme name.
1416 $path = '/_s'.$path;
1418 $url->set_slashargument($path, 'noparam', true);
1419 } else {
1420 if (!$svg) {
1421 // We add an SVG param so that we know not to serve SVG images.
1422 // We do this because all modern browsers support SVG and this param will one day be removed.
1423 $params['svg'] = '0';
1425 $url->params($params);
1428 return $url;
1432 * Return the URL for a font
1434 * @param string $font the name of the font (including extension).
1435 * @param string $component specification of one plugin like in get_string()
1436 * @return moodle_url
1438 public function font_url($font, $component) {
1439 global $CFG;
1441 $params = array('theme'=>$this->name);
1443 if (empty($component) or $component === 'moodle' or $component === 'core') {
1444 $params['component'] = 'core';
1445 } else {
1446 $params['component'] = $component;
1449 $rev = theme_get_revision();
1450 if ($rev != -1) {
1451 $params['rev'] = $rev;
1454 $params['font'] = $font;
1456 $url = new moodle_url("$CFG->httpswwwroot/theme/font.php");
1457 if (!empty($CFG->slasharguments) and $rev > 0) {
1458 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1459 $url->set_slashargument($path, 'noparam', true);
1460 } else {
1461 $url->params($params);
1464 return $url;
1468 * Returns URL to the stored file via pluginfile.php.
1470 * Note the theme must also implement pluginfile.php handler,
1471 * theme revision is used instead of the itemid.
1473 * @param string $setting
1474 * @param string $filearea
1475 * @return string protocol relative URL or null if not present
1477 public function setting_file_url($setting, $filearea) {
1478 global $CFG;
1480 if (empty($this->settings->$setting)) {
1481 return null;
1484 $component = 'theme_'.$this->name;
1485 $itemid = theme_get_revision();
1486 $filepath = $this->settings->$setting;
1487 $syscontext = context_system::instance();
1489 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1491 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1492 // Note: unfortunately moodle_url does not support //urls yet.
1494 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1496 return $url;
1500 * Serve the theme setting file.
1502 * @param string $filearea
1503 * @param array $args
1504 * @param bool $forcedownload
1505 * @param array $options
1506 * @return bool may terminate if file not found or donotdie not specified
1508 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1509 global $CFG;
1510 require_once("$CFG->libdir/filelib.php");
1512 $syscontext = context_system::instance();
1513 $component = 'theme_'.$this->name;
1515 $revision = array_shift($args);
1516 if ($revision < 0) {
1517 $lifetime = 0;
1518 } else {
1519 $lifetime = 60*60*24*60;
1520 // By default, theme files must be cache-able by both browsers and proxies.
1521 if (!array_key_exists('cacheability', $options)) {
1522 $options['cacheability'] = 'public';
1526 $fs = get_file_storage();
1527 $relativepath = implode('/', $args);
1529 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1530 $fullpath = rtrim($fullpath, '/');
1531 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1532 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1533 return true;
1534 } else {
1535 send_file_not_found();
1540 * Resolves the real image location.
1542 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1543 * and we need a way in which to turn it off.
1544 * By default SVG won't be used unless asked for. This is done for two reasons:
1545 * 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
1546 * browser supports SVG.
1547 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1548 * by the user due to security concerns.
1550 * @param string $image name of image, may contain relative path
1551 * @param string $component
1552 * @param bool $svg If set to true SVG images will also be looked for.
1553 * @return string full file path
1555 public function resolve_image_location($image, $component, $svg = false) {
1556 global $CFG;
1558 if (!is_bool($svg)) {
1559 // If $svg isn't a bool then we need to decide for ourselves.
1560 $svg = $this->use_svg_icons();
1563 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1564 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1565 return $imagefile;
1567 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1568 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1569 return $imagefile;
1572 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1573 return $imagefile;
1575 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1576 return $imagefile;
1578 return null;
1580 } else if ($component === 'theme') { //exception
1581 if ($image === 'favicon') {
1582 return "$this->dir/pix/favicon.ico";
1584 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1585 return $imagefile;
1587 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1588 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1589 return $imagefile;
1592 return null;
1594 } else {
1595 if (strpos($component, '_') === false) {
1596 $component = 'mod_'.$component;
1598 list($type, $plugin) = explode('_', $component, 2);
1600 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1601 return $imagefile;
1603 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1604 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1605 return $imagefile;
1608 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1609 return $imagefile;
1611 $dir = core_component::get_plugin_directory($type, $plugin);
1612 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1613 return $imagefile;
1615 return null;
1620 * Resolves the real font location.
1622 * @param string $font name of font file
1623 * @param string $component
1624 * @return string full file path
1626 public function resolve_font_location($font, $component) {
1627 global $CFG;
1629 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1630 if (file_exists("$this->dir/fonts_core/$font")) {
1631 return "$this->dir/fonts_core/$font";
1633 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1634 if (file_exists("$parent_config->dir/fonts_core/$font")) {
1635 return "$parent_config->dir/fonts_core/$font";
1638 if (file_exists("$CFG->dataroot/fonts/$font")) {
1639 return "$CFG->dataroot/fonts/$font";
1641 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
1642 return "$CFG->dirroot/lib/fonts/$font";
1644 return null;
1646 } else if ($component === 'theme') { // Exception.
1647 if (file_exists("$this->dir/fonts/$font")) {
1648 return "$this->dir/fonts/$font";
1650 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1651 if (file_exists("$parent_config->dir/fonts/$font")) {
1652 return "$parent_config->dir/fonts/$font";
1655 return null;
1657 } else {
1658 if (strpos($component, '_') === false) {
1659 $component = 'mod_'.$component;
1661 list($type, $plugin) = explode('_', $component, 2);
1663 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
1664 return "$this->dir/fonts_plugins/$type/$plugin/$font";
1666 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1667 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
1668 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
1671 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
1672 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
1674 $dir = core_component::get_plugin_directory($type, $plugin);
1675 if (file_exists("$dir/fonts/$font")) {
1676 return "$dir/fonts/$font";
1678 return null;
1683 * Return true if we should look for SVG images as well.
1685 * @return bool
1687 public function use_svg_icons() {
1688 global $CFG;
1689 if ($this->usesvg === null) {
1691 if (!isset($CFG->svgicons)) {
1692 $this->usesvg = core_useragent::supports_svg();
1693 } else {
1694 // Force them on/off depending upon the setting.
1695 $this->usesvg = (bool)$CFG->svgicons;
1698 return $this->usesvg;
1702 * Forces the usesvg setting to either true or false, avoiding any decision making.
1704 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
1705 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
1707 * @param bool $setting True to force the use of svg when available, null otherwise.
1709 public function force_svg_use($setting) {
1710 $this->usesvg = (bool)$setting;
1714 * Checks if file with any image extension exists.
1716 * The order to these images was adjusted prior to the release of 2.4
1717 * At that point the were the following image counts in Moodle core:
1719 * - png = 667 in pix dirs (1499 total)
1720 * - gif = 385 in pix dirs (606 total)
1721 * - jpg = 62 in pix dirs (74 total)
1722 * - jpeg = 0 in pix dirs (1 total)
1724 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1726 * @param string $filepath
1727 * @param bool $svg If set to true SVG images will also be looked for.
1728 * @return string image name with extension
1730 private static function image_exists($filepath, $svg = false) {
1731 if ($svg && file_exists("$filepath.svg")) {
1732 return "$filepath.svg";
1733 } else if (file_exists("$filepath.png")) {
1734 return "$filepath.png";
1735 } else if (file_exists("$filepath.gif")) {
1736 return "$filepath.gif";
1737 } else if (file_exists("$filepath.jpg")) {
1738 return "$filepath.jpg";
1739 } else if (file_exists("$filepath.jpeg")) {
1740 return "$filepath.jpeg";
1741 } else {
1742 return false;
1747 * Loads the theme config from config.php file.
1749 * @param string $themename
1750 * @param stdClass $settings from config_plugins table
1751 * @param boolean $parentscheck true to also check the parents. .
1752 * @return stdClass The theme configuration
1754 private static function find_theme_config($themename, $settings, $parentscheck = true) {
1755 // We have to use the variable name $THEME (upper case) because that
1756 // is what is used in theme config.php files.
1758 if (!$dir = theme_config::find_theme_location($themename)) {
1759 return null;
1762 $THEME = new stdClass();
1763 $THEME->name = $themename;
1764 $THEME->dir = $dir;
1765 $THEME->settings = $settings;
1767 global $CFG; // just in case somebody tries to use $CFG in theme config
1768 include("$THEME->dir/config.php");
1770 // verify the theme configuration is OK
1771 if (!is_array($THEME->parents)) {
1772 // parents option is mandatory now
1773 return null;
1774 } else {
1775 // We use $parentscheck to only check the direct parents (avoid infinite loop).
1776 if ($parentscheck) {
1777 // Find all parent theme configs.
1778 foreach ($THEME->parents as $parent) {
1779 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
1780 if (empty($parentconfig)) {
1781 return null;
1787 return $THEME;
1791 * Finds the theme location and verifies the theme has all needed files
1792 * and is not obsoleted.
1794 * @param string $themename
1795 * @return string full dir path or null if not found
1797 private static function find_theme_location($themename) {
1798 global $CFG;
1800 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1801 $dir = "$CFG->dirroot/theme/$themename";
1803 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1804 $dir = "$CFG->themedir/$themename";
1806 } else {
1807 return null;
1810 if (file_exists("$dir/styles.php")) {
1811 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1812 return null;
1815 return $dir;
1819 * Get the renderer for a part of Moodle for this theme.
1821 * @param moodle_page $page the page we are rendering
1822 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1823 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1824 * @param string $target one of rendering target constants
1825 * @return renderer_base the requested renderer.
1827 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1828 if (is_null($this->rf)) {
1829 $classname = $this->rendererfactory;
1830 $this->rf = new $classname($this);
1833 return $this->rf->get_renderer($page, $component, $subtype, $target);
1837 * Get the information from {@link $layouts} for this type of page.
1839 * @param string $pagelayout the the page layout name.
1840 * @return array the appropriate part of {@link $layouts}.
1842 protected function layout_info_for_page($pagelayout) {
1843 if (array_key_exists($pagelayout, $this->layouts)) {
1844 return $this->layouts[$pagelayout];
1845 } else {
1846 debugging('Invalid page layout specified: ' . $pagelayout);
1847 return $this->layouts['standard'];
1852 * Given the settings of this theme, and the page pagelayout, return the
1853 * full path of the page layout file to use.
1855 * Used by {@link core_renderer::header()}.
1857 * @param string $pagelayout the the page layout name.
1858 * @return string Full path to the lyout file to use
1860 public function layout_file($pagelayout) {
1861 global $CFG;
1863 $layoutinfo = $this->layout_info_for_page($pagelayout);
1864 $layoutfile = $layoutinfo['file'];
1866 if (array_key_exists('theme', $layoutinfo)) {
1867 $themes = array($layoutinfo['theme']);
1868 } else {
1869 $themes = array_merge(array($this->name),$this->parents);
1872 foreach ($themes as $theme) {
1873 if ($dir = $this->find_theme_location($theme)) {
1874 $path = "$dir/layout/$layoutfile";
1876 // Check the template exists, return general base theme template if not.
1877 if (is_readable($path)) {
1878 return $path;
1883 debugging('Can not find layout file for: ' . $pagelayout);
1884 // fallback to standard normal layout
1885 return "$CFG->dirroot/theme/base/layout/general.php";
1889 * Returns auxiliary page layout options specified in layout configuration array.
1891 * @param string $pagelayout
1892 * @return array
1894 public function pagelayout_options($pagelayout) {
1895 $info = $this->layout_info_for_page($pagelayout);
1896 if (!empty($info['options'])) {
1897 return $info['options'];
1899 return array();
1903 * Inform a block_manager about the block regions this theme wants on this
1904 * page layout.
1906 * @param string $pagelayout the general type of the page.
1907 * @param block_manager $blockmanager the block_manger to set up.
1909 public function setup_blocks($pagelayout, $blockmanager) {
1910 $layoutinfo = $this->layout_info_for_page($pagelayout);
1911 if (!empty($layoutinfo['regions'])) {
1912 $blockmanager->add_regions($layoutinfo['regions'], false);
1913 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1918 * Gets the visible name for the requested block region.
1920 * @param string $region The region name to get
1921 * @param string $theme The theme the region belongs to (may come from the parent theme)
1922 * @return string
1924 protected function get_region_name($region, $theme) {
1925 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1926 // A name exists in this theme, so use it
1927 if (substr($regionstring, 0, 1) != '[') {
1928 return $regionstring;
1931 // Otherwise, try to find one elsewhere
1932 // Check parents, if any
1933 foreach ($this->parents as $parentthemename) {
1934 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1935 if (substr($regionstring, 0, 1) != '[') {
1936 return $regionstring;
1940 // Last resort, try the base theme for names
1941 return get_string('region-' . $region, 'theme_base');
1945 * Get the list of all block regions known to this theme in all templates.
1947 * @return array internal region name => human readable name.
1949 public function get_all_block_regions() {
1950 $regions = array();
1951 foreach ($this->layouts as $layoutinfo) {
1952 foreach ($layoutinfo['regions'] as $region) {
1953 $regions[$region] = $this->get_region_name($region, $this->name);
1956 return $regions;
1960 * Returns the human readable name of the theme
1962 * @return string
1964 public function get_theme_name() {
1965 return get_string('pluginname', 'theme_'.$this->name);
1969 * Returns the block render method.
1971 * It is set by the theme via:
1972 * $THEME->blockrendermethod = '...';
1974 * It can be one of two values, blocks or blocks_for_region.
1975 * It should be set to the method being used by the theme layouts.
1977 * @return string
1979 public function get_block_render_method() {
1980 if ($this->blockrendermethod) {
1981 // Return the specified block render method.
1982 return $this->blockrendermethod;
1984 // Its not explicitly set, check the parent theme configs.
1985 foreach ($this->parent_configs as $config) {
1986 if (isset($config->blockrendermethod)) {
1987 return $config->blockrendermethod;
1990 // Default it to blocks.
1991 return 'blocks';
1996 * This class keeps track of which HTML tags are currently open.
1998 * This makes it much easier to always generate well formed XHTML output, even
1999 * if execution terminates abruptly. Any time you output some opening HTML
2000 * without the matching closing HTML, you should push the necessary close tags
2001 * onto the stack.
2003 * @copyright 2009 Tim Hunt
2004 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2005 * @since Moodle 2.0
2006 * @package core
2007 * @category output
2009 class xhtml_container_stack {
2012 * @var array Stores the list of open containers.
2014 protected $opencontainers = array();
2017 * @var array In developer debug mode, stores a stack trace of all opens and
2018 * closes, so we can output helpful error messages when there is a mismatch.
2020 protected $log = array();
2023 * @var boolean Store whether we are developer debug mode. We need this in
2024 * several places including in the destructor where we may not have access to $CFG.
2026 protected $isdebugging;
2029 * Constructor
2031 public function __construct() {
2032 global $CFG;
2033 $this->isdebugging = $CFG->debugdeveloper;
2037 * Push the close HTML for a recently opened container onto the stack.
2039 * @param string $type The type of container. This is checked when {@link pop()}
2040 * is called and must match, otherwise a developer debug warning is output.
2041 * @param string $closehtml The HTML required to close the container.
2043 public function push($type, $closehtml) {
2044 $container = new stdClass;
2045 $container->type = $type;
2046 $container->closehtml = $closehtml;
2047 if ($this->isdebugging) {
2048 $this->log('Open', $type);
2050 array_push($this->opencontainers, $container);
2054 * Pop the HTML for the next closing container from the stack. The $type
2055 * must match the type passed when the container was opened, otherwise a
2056 * warning will be output.
2058 * @param string $type The type of container.
2059 * @return string the HTML required to close the container.
2061 public function pop($type) {
2062 if (empty($this->opencontainers)) {
2063 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2064 $this->output_log(), DEBUG_DEVELOPER);
2065 return;
2068 $container = array_pop($this->opencontainers);
2069 if ($container->type != $type) {
2070 debugging('<p>The type of container to be closed (' . $container->type .
2071 ') does not match the type of the next open container (' . $type .
2072 '). This suggests there is a nesting problem.</p>' .
2073 $this->output_log(), DEBUG_DEVELOPER);
2075 if ($this->isdebugging) {
2076 $this->log('Close', $type);
2078 return $container->closehtml;
2082 * Close all but the last open container. This is useful in places like error
2083 * handling, where you want to close all the open containers (apart from <body>)
2084 * before outputting the error message.
2086 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2087 * developer debug warning if it isn't.
2088 * @return string the HTML required to close any open containers inside <body>.
2090 public function pop_all_but_last($shouldbenone = false) {
2091 if ($shouldbenone && count($this->opencontainers) != 1) {
2092 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2093 $this->output_log(), DEBUG_DEVELOPER);
2095 $output = '';
2096 while (count($this->opencontainers) > 1) {
2097 $container = array_pop($this->opencontainers);
2098 $output .= $container->closehtml;
2100 return $output;
2104 * You can call this function if you want to throw away an instance of this
2105 * class without properly emptying the stack (for example, in a unit test).
2106 * Calling this method stops the destruct method from outputting a developer
2107 * debug warning. After calling this method, the instance can no longer be used.
2109 public function discard() {
2110 $this->opencontainers = null;
2114 * Adds an entry to the log.
2116 * @param string $action The name of the action
2117 * @param string $type The type of action
2119 protected function log($action, $type) {
2120 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
2121 format_backtrace(debug_backtrace()) . '</li>';
2125 * Outputs the log's contents as a HTML list.
2127 * @return string HTML list of the log
2129 protected function output_log() {
2130 return '<ul>' . implode("\n", $this->log) . '</ul>';