Moodle release 3.0rc4
[moodle.git] / lib / outputlib.php
blobe1ada8ac80021e211e7ca8f4c1f21bad4a283307
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) {
1082 $lessfile = $this->lessfile;
1083 if (!$lessfile || !is_readable($this->dir . '/less/' . $lessfile . '.less')) {
1084 throw new coding_exception('The theme did not define a LESS file, or it is not readable.');
1087 // We might need more memory to do this, so let's play safe.
1088 raise_memory_limit(MEMORY_EXTRA);
1090 // Files list.
1091 $files = $this->get_css_files($themedesigner);
1093 // Get the LESS file path.
1094 $themelessfile = $files['theme'][$lessfile];
1096 // Setup compiler options.
1097 $options = array(
1098 // We need to set the import directory to where $lessfile is.
1099 'import_dirs' => array(dirname($themelessfile) => '/'),
1100 // Always disable default caching.
1101 'cache_method' => false,
1102 // Disable the relative URLs, we have post_process() to handle that.
1103 'relativeUrls' => false,
1106 if ($themedesigner) {
1107 // Add the sourceMap inline to ensure that it is atomically generated.
1108 $options['sourceMap'] = true;
1109 $options['sourceRoot'] = 'theme';
1112 // Instantiate the compiler.
1113 $compiler = new core_lessc($options);
1115 try {
1116 $compiler->parse_file_content($themelessfile);
1118 // Get the callbacks.
1119 $compiler->parse($this->get_extra_less_code());
1120 $compiler->ModifyVars($this->get_less_variables());
1122 // Compile the CSS.
1123 $compiled = $compiler->getCss();
1125 // Post process the entire thing.
1126 $compiled = $this->post_process($compiled);
1127 } catch (Less_Exception_Parser $e) {
1128 $compiled = false;
1129 debugging('Error while compiling LESS ' . $lessfile . ' file: ' . $e->getMessage(), DEBUG_DEVELOPER);
1132 // Try to save memory.
1133 $compiler = null;
1134 unset($compiler);
1136 return $compiled;
1140 * Return extra LESS variables to use when compiling.
1142 * @return array Where keys are the variable names (omitting the @), and the values are the value.
1144 protected function get_less_variables() {
1145 $variables = array();
1147 // Getting all the candidate functions.
1148 $candidates = array();
1149 foreach ($this->parent_configs as $parent_config) {
1150 if (!isset($parent_config->lessvariablescallback)) {
1151 continue;
1153 $candidates[] = $parent_config->lessvariablescallback;
1155 $candidates[] = $this->lessvariablescallback;
1157 // Calling the functions.
1158 foreach ($candidates as $function) {
1159 if (function_exists($function)) {
1160 $vars = $function($this);
1161 if (!is_array($vars)) {
1162 debugging('Callback ' . $function . ' did not return an array() as expected', DEBUG_DEVELOPER);
1163 continue;
1165 $variables = array_merge($variables, $vars);
1169 return $variables;
1173 * Return extra LESS code to add when compiling.
1175 * This is intended to be used by themes to inject some LESS code
1176 * before it gets compiled. If you want to inject variables you
1177 * should use {@link self::get_less_variables()}.
1179 * @return string The LESS code to inject.
1181 protected function get_extra_less_code() {
1182 $content = '';
1184 // Getting all the candidate functions.
1185 $candidates = array();
1186 foreach ($this->parent_configs as $parent_config) {
1187 if (!isset($parent_config->extralesscallback)) {
1188 continue;
1190 $candidates[] = $parent_config->extralesscallback;
1192 $candidates[] = $this->extralesscallback;
1194 // Calling the functions.
1195 foreach ($candidates as $function) {
1196 if (function_exists($function)) {
1197 $content .= "\n/** Extra LESS from $function **/\n" . $function($this) . "\n";
1201 return $content;
1205 * Generate a URL to the file that serves theme JavaScript files.
1207 * If we determine that the theme has no relevant files, then we return
1208 * early with a null value.
1210 * @param bool $inhead true means head url, false means footer
1211 * @return moodle_url|null
1213 public function javascript_url($inhead) {
1214 global $CFG;
1216 $rev = theme_get_revision();
1217 $params = array('theme'=>$this->name,'rev'=>$rev);
1218 $params['type'] = $inhead ? 'head' : 'footer';
1220 // Return early if there are no files to serve
1221 if (count($this->javascript_files($params['type'])) === 0) {
1222 return null;
1225 if (!empty($CFG->slasharguments) and $rev > 0) {
1226 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
1227 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
1228 return $url;
1229 } else {
1230 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
1235 * Get the URL's for the JavaScript files used by this theme.
1236 * They won't be served directly, instead they'll be mediated through
1237 * theme/javascript.php.
1239 * @param string $type Either javascripts_footer, or javascripts
1240 * @return array
1242 public function javascript_files($type) {
1243 if ($type === 'footer') {
1244 $type = 'javascripts_footer';
1245 } else {
1246 $type = 'javascripts';
1249 $js = array();
1250 // find out wanted parent javascripts
1251 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1252 if ($excludes !== true) {
1253 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1254 $parent = $parent_config->name;
1255 if (empty($parent_config->$type)) {
1256 continue;
1258 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1259 continue;
1261 foreach ($parent_config->$type as $javascript) {
1262 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1263 and in_array($javascript, $excludes[$parent])) {
1264 continue;
1266 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1267 if (is_readable($javascriptfile)) {
1268 $js[] = $javascriptfile;
1274 // current theme javascripts
1275 if (is_array($this->$type)) {
1276 foreach ($this->$type as $javascript) {
1277 $javascriptfile = "$this->dir/javascript/$javascript.js";
1278 if (is_readable($javascriptfile)) {
1279 $js[] = $javascriptfile;
1283 return $js;
1287 * Resolves an exclude setting to the themes setting is applicable or the
1288 * setting of its closest parent.
1290 * @param string $variable The name of the setting the exclude setting to resolve
1291 * @param string $default
1292 * @return mixed
1294 protected function resolve_excludes($variable, $default = null) {
1295 $setting = $default;
1296 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1297 $setting = $this->{$variable};
1298 } else {
1299 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1300 if (!isset($parent_config->{$variable})) {
1301 continue;
1303 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1304 $setting = $parent_config->{$variable};
1305 break;
1309 return $setting;
1313 * Returns the content of the one huge javascript file merged from all theme javascript files.
1315 * @param bool $type
1316 * @return string
1318 public function javascript_content($type) {
1319 $jsfiles = $this->javascript_files($type);
1320 $js = '';
1321 foreach ($jsfiles as $jsfile) {
1322 $js .= file_get_contents($jsfile)."\n";
1324 return $js;
1328 * Post processes CSS.
1330 * This method post processes all of the CSS before it is served for this theme.
1331 * This is done so that things such as image URL's can be swapped in and to
1332 * run any specific CSS post process method the theme has requested.
1333 * This allows themes to use CSS settings.
1335 * @param string $css The CSS to process.
1336 * @return string The processed CSS.
1338 public function post_process($css) {
1339 // now resolve all image locations
1340 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1341 $replaced = array();
1342 foreach ($matches as $match) {
1343 if (isset($replaced[$match[0]])) {
1344 continue;
1346 $replaced[$match[0]] = true;
1347 $imagename = $match[2];
1348 $component = rtrim($match[1], '|');
1349 $imageurl = $this->pix_url($imagename, $component)->out(false);
1350 // we do not need full url because the image.php is always in the same dir
1351 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1352 $css = str_replace($match[0], $imageurl, $css);
1356 // Now resolve all font locations.
1357 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1358 $replaced = array();
1359 foreach ($matches as $match) {
1360 if (isset($replaced[$match[0]])) {
1361 continue;
1363 $replaced[$match[0]] = true;
1364 $fontname = $match[2];
1365 $component = rtrim($match[1], '|');
1366 $fonturl = $this->font_url($fontname, $component)->out(false);
1367 // We do not need full url because the font.php is always in the same dir.
1368 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1369 $css = str_replace($match[0], $fonturl, $css);
1373 // now resolve all theme settings or do any other postprocessing
1374 $csspostprocess = $this->csspostprocess;
1375 if (function_exists($csspostprocess)) {
1376 $css = $csspostprocess($css, $this);
1379 return $css;
1383 * Return the URL for an image
1385 * @param string $imagename the name of the icon.
1386 * @param string $component specification of one plugin like in get_string()
1387 * @return moodle_url
1389 public function pix_url($imagename, $component) {
1390 global $CFG;
1392 $params = array('theme'=>$this->name);
1393 $svg = $this->use_svg_icons();
1395 if (empty($component) or $component === 'moodle' or $component === 'core') {
1396 $params['component'] = 'core';
1397 } else {
1398 $params['component'] = $component;
1401 $rev = theme_get_revision();
1402 if ($rev != -1) {
1403 $params['rev'] = $rev;
1406 $params['image'] = $imagename;
1408 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1409 if (!empty($CFG->slasharguments) and $rev > 0) {
1410 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1411 if (!$svg) {
1412 // We add a simple /_s to the start of the path.
1413 // The underscore is used to ensure that it isn't a valid theme name.
1414 $path = '/_s'.$path;
1416 $url->set_slashargument($path, 'noparam', true);
1417 } else {
1418 if (!$svg) {
1419 // We add an SVG param so that we know not to serve SVG images.
1420 // We do this because all modern browsers support SVG and this param will one day be removed.
1421 $params['svg'] = '0';
1423 $url->params($params);
1426 return $url;
1430 * Return the URL for a font
1432 * @param string $font the name of the font (including extension).
1433 * @param string $component specification of one plugin like in get_string()
1434 * @return moodle_url
1436 public function font_url($font, $component) {
1437 global $CFG;
1439 $params = array('theme'=>$this->name);
1441 if (empty($component) or $component === 'moodle' or $component === 'core') {
1442 $params['component'] = 'core';
1443 } else {
1444 $params['component'] = $component;
1447 $rev = theme_get_revision();
1448 if ($rev != -1) {
1449 $params['rev'] = $rev;
1452 $params['font'] = $font;
1454 $url = new moodle_url("$CFG->httpswwwroot/theme/font.php");
1455 if (!empty($CFG->slasharguments) and $rev > 0) {
1456 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1457 $url->set_slashargument($path, 'noparam', true);
1458 } else {
1459 $url->params($params);
1462 return $url;
1466 * Returns URL to the stored file via pluginfile.php.
1468 * Note the theme must also implement pluginfile.php handler,
1469 * theme revision is used instead of the itemid.
1471 * @param string $setting
1472 * @param string $filearea
1473 * @return string protocol relative URL or null if not present
1475 public function setting_file_url($setting, $filearea) {
1476 global $CFG;
1478 if (empty($this->settings->$setting)) {
1479 return null;
1482 $component = 'theme_'.$this->name;
1483 $itemid = theme_get_revision();
1484 $filepath = $this->settings->$setting;
1485 $syscontext = context_system::instance();
1487 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1489 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1490 // Note: unfortunately moodle_url does not support //urls yet.
1492 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1494 return $url;
1498 * Serve the theme setting file.
1500 * @param string $filearea
1501 * @param array $args
1502 * @param bool $forcedownload
1503 * @param array $options
1504 * @return bool may terminate if file not found or donotdie not specified
1506 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1507 global $CFG;
1508 require_once("$CFG->libdir/filelib.php");
1510 $syscontext = context_system::instance();
1511 $component = 'theme_'.$this->name;
1513 $revision = array_shift($args);
1514 if ($revision < 0) {
1515 $lifetime = 0;
1516 } else {
1517 $lifetime = 60*60*24*60;
1518 // By default, theme files must be cache-able by both browsers and proxies.
1519 if (!array_key_exists('cacheability', $options)) {
1520 $options['cacheability'] = 'public';
1524 $fs = get_file_storage();
1525 $relativepath = implode('/', $args);
1527 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1528 $fullpath = rtrim($fullpath, '/');
1529 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1530 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1531 return true;
1532 } else {
1533 send_file_not_found();
1538 * Resolves the real image location.
1540 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1541 * and we need a way in which to turn it off.
1542 * By default SVG won't be used unless asked for. This is done for two reasons:
1543 * 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
1544 * browser supports SVG.
1545 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1546 * by the user due to security concerns.
1548 * @param string $image name of image, may contain relative path
1549 * @param string $component
1550 * @param bool $svg If set to true SVG images will also be looked for.
1551 * @return string full file path
1553 public function resolve_image_location($image, $component, $svg = false) {
1554 global $CFG;
1556 if (!is_bool($svg)) {
1557 // If $svg isn't a bool then we need to decide for ourselves.
1558 $svg = $this->use_svg_icons();
1561 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1562 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1563 return $imagefile;
1565 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1566 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1567 return $imagefile;
1570 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1571 return $imagefile;
1573 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1574 return $imagefile;
1576 return null;
1578 } else if ($component === 'theme') { //exception
1579 if ($image === 'favicon') {
1580 return "$this->dir/pix/favicon.ico";
1582 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1583 return $imagefile;
1585 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1586 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1587 return $imagefile;
1590 return null;
1592 } else {
1593 if (strpos($component, '_') === false) {
1594 $component = 'mod_'.$component;
1596 list($type, $plugin) = explode('_', $component, 2);
1598 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1599 return $imagefile;
1601 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1602 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1603 return $imagefile;
1606 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1607 return $imagefile;
1609 $dir = core_component::get_plugin_directory($type, $plugin);
1610 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1611 return $imagefile;
1613 return null;
1618 * Resolves the real font location.
1620 * @param string $font name of font file
1621 * @param string $component
1622 * @return string full file path
1624 public function resolve_font_location($font, $component) {
1625 global $CFG;
1627 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1628 if (file_exists("$this->dir/fonts_core/$font")) {
1629 return "$this->dir/fonts_core/$font";
1631 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1632 if (file_exists("$parent_config->dir/fonts_core/$font")) {
1633 return "$parent_config->dir/fonts_core/$font";
1636 if (file_exists("$CFG->dataroot/fonts/$font")) {
1637 return "$CFG->dataroot/fonts/$font";
1639 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
1640 return "$CFG->dirroot/lib/fonts/$font";
1642 return null;
1644 } else if ($component === 'theme') { // Exception.
1645 if (file_exists("$this->dir/fonts/$font")) {
1646 return "$this->dir/fonts/$font";
1648 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1649 if (file_exists("$parent_config->dir/fonts/$font")) {
1650 return "$parent_config->dir/fonts/$font";
1653 return null;
1655 } else {
1656 if (strpos($component, '_') === false) {
1657 $component = 'mod_'.$component;
1659 list($type, $plugin) = explode('_', $component, 2);
1661 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
1662 return "$this->dir/fonts_plugins/$type/$plugin/$font";
1664 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1665 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
1666 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
1669 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
1670 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
1672 $dir = core_component::get_plugin_directory($type, $plugin);
1673 if (file_exists("$dir/fonts/$font")) {
1674 return "$dir/fonts/$font";
1676 return null;
1681 * Return true if we should look for SVG images as well.
1683 * @return bool
1685 public function use_svg_icons() {
1686 global $CFG;
1687 if ($this->usesvg === null) {
1689 if (!isset($CFG->svgicons)) {
1690 $this->usesvg = core_useragent::supports_svg();
1691 } else {
1692 // Force them on/off depending upon the setting.
1693 $this->usesvg = (bool)$CFG->svgicons;
1696 return $this->usesvg;
1700 * Forces the usesvg setting to either true or false, avoiding any decision making.
1702 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
1703 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
1705 * @param bool $setting True to force the use of svg when available, null otherwise.
1707 public function force_svg_use($setting) {
1708 $this->usesvg = (bool)$setting;
1712 * Checks if file with any image extension exists.
1714 * The order to these images was adjusted prior to the release of 2.4
1715 * At that point the were the following image counts in Moodle core:
1717 * - png = 667 in pix dirs (1499 total)
1718 * - gif = 385 in pix dirs (606 total)
1719 * - jpg = 62 in pix dirs (74 total)
1720 * - jpeg = 0 in pix dirs (1 total)
1722 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1724 * @param string $filepath
1725 * @param bool $svg If set to true SVG images will also be looked for.
1726 * @return string image name with extension
1728 private static function image_exists($filepath, $svg = false) {
1729 if ($svg && file_exists("$filepath.svg")) {
1730 return "$filepath.svg";
1731 } else if (file_exists("$filepath.png")) {
1732 return "$filepath.png";
1733 } else if (file_exists("$filepath.gif")) {
1734 return "$filepath.gif";
1735 } else if (file_exists("$filepath.jpg")) {
1736 return "$filepath.jpg";
1737 } else if (file_exists("$filepath.jpeg")) {
1738 return "$filepath.jpeg";
1739 } else {
1740 return false;
1745 * Loads the theme config from config.php file.
1747 * @param string $themename
1748 * @param stdClass $settings from config_plugins table
1749 * @param boolean $parentscheck true to also check the parents. .
1750 * @return stdClass The theme configuration
1752 private static function find_theme_config($themename, $settings, $parentscheck = true) {
1753 // We have to use the variable name $THEME (upper case) because that
1754 // is what is used in theme config.php files.
1756 if (!$dir = theme_config::find_theme_location($themename)) {
1757 return null;
1760 $THEME = new stdClass();
1761 $THEME->name = $themename;
1762 $THEME->dir = $dir;
1763 $THEME->settings = $settings;
1765 global $CFG; // just in case somebody tries to use $CFG in theme config
1766 include("$THEME->dir/config.php");
1768 // verify the theme configuration is OK
1769 if (!is_array($THEME->parents)) {
1770 // parents option is mandatory now
1771 return null;
1772 } else {
1773 // We use $parentscheck to only check the direct parents (avoid infinite loop).
1774 if ($parentscheck) {
1775 // Find all parent theme configs.
1776 foreach ($THEME->parents as $parent) {
1777 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
1778 if (empty($parentconfig)) {
1779 return null;
1785 return $THEME;
1789 * Finds the theme location and verifies the theme has all needed files
1790 * and is not obsoleted.
1792 * @param string $themename
1793 * @return string full dir path or null if not found
1795 private static function find_theme_location($themename) {
1796 global $CFG;
1798 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1799 $dir = "$CFG->dirroot/theme/$themename";
1801 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1802 $dir = "$CFG->themedir/$themename";
1804 } else {
1805 return null;
1808 if (file_exists("$dir/styles.php")) {
1809 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1810 return null;
1813 return $dir;
1817 * Get the renderer for a part of Moodle for this theme.
1819 * @param moodle_page $page the page we are rendering
1820 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1821 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1822 * @param string $target one of rendering target constants
1823 * @return renderer_base the requested renderer.
1825 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1826 if (is_null($this->rf)) {
1827 $classname = $this->rendererfactory;
1828 $this->rf = new $classname($this);
1831 return $this->rf->get_renderer($page, $component, $subtype, $target);
1835 * Get the information from {@link $layouts} for this type of page.
1837 * @param string $pagelayout the the page layout name.
1838 * @return array the appropriate part of {@link $layouts}.
1840 protected function layout_info_for_page($pagelayout) {
1841 if (array_key_exists($pagelayout, $this->layouts)) {
1842 return $this->layouts[$pagelayout];
1843 } else {
1844 debugging('Invalid page layout specified: ' . $pagelayout);
1845 return $this->layouts['standard'];
1850 * Given the settings of this theme, and the page pagelayout, return the
1851 * full path of the page layout file to use.
1853 * Used by {@link core_renderer::header()}.
1855 * @param string $pagelayout the the page layout name.
1856 * @return string Full path to the lyout file to use
1858 public function layout_file($pagelayout) {
1859 global $CFG;
1861 $layoutinfo = $this->layout_info_for_page($pagelayout);
1862 $layoutfile = $layoutinfo['file'];
1864 if (array_key_exists('theme', $layoutinfo)) {
1865 $themes = array($layoutinfo['theme']);
1866 } else {
1867 $themes = array_merge(array($this->name),$this->parents);
1870 foreach ($themes as $theme) {
1871 if ($dir = $this->find_theme_location($theme)) {
1872 $path = "$dir/layout/$layoutfile";
1874 // Check the template exists, return general base theme template if not.
1875 if (is_readable($path)) {
1876 return $path;
1881 debugging('Can not find layout file for: ' . $pagelayout);
1882 // fallback to standard normal layout
1883 return "$CFG->dirroot/theme/base/layout/general.php";
1887 * Returns auxiliary page layout options specified in layout configuration array.
1889 * @param string $pagelayout
1890 * @return array
1892 public function pagelayout_options($pagelayout) {
1893 $info = $this->layout_info_for_page($pagelayout);
1894 if (!empty($info['options'])) {
1895 return $info['options'];
1897 return array();
1901 * Inform a block_manager about the block regions this theme wants on this
1902 * page layout.
1904 * @param string $pagelayout the general type of the page.
1905 * @param block_manager $blockmanager the block_manger to set up.
1907 public function setup_blocks($pagelayout, $blockmanager) {
1908 $layoutinfo = $this->layout_info_for_page($pagelayout);
1909 if (!empty($layoutinfo['regions'])) {
1910 $blockmanager->add_regions($layoutinfo['regions'], false);
1911 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1916 * Gets the visible name for the requested block region.
1918 * @param string $region The region name to get
1919 * @param string $theme The theme the region belongs to (may come from the parent theme)
1920 * @return string
1922 protected function get_region_name($region, $theme) {
1923 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1924 // A name exists in this theme, so use it
1925 if (substr($regionstring, 0, 1) != '[') {
1926 return $regionstring;
1929 // Otherwise, try to find one elsewhere
1930 // Check parents, if any
1931 foreach ($this->parents as $parentthemename) {
1932 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1933 if (substr($regionstring, 0, 1) != '[') {
1934 return $regionstring;
1938 // Last resort, try the base theme for names
1939 return get_string('region-' . $region, 'theme_base');
1943 * Get the list of all block regions known to this theme in all templates.
1945 * @return array internal region name => human readable name.
1947 public function get_all_block_regions() {
1948 $regions = array();
1949 foreach ($this->layouts as $layoutinfo) {
1950 foreach ($layoutinfo['regions'] as $region) {
1951 $regions[$region] = $this->get_region_name($region, $this->name);
1954 return $regions;
1958 * Returns the human readable name of the theme
1960 * @return string
1962 public function get_theme_name() {
1963 return get_string('pluginname', 'theme_'.$this->name);
1967 * Returns the block render method.
1969 * It is set by the theme via:
1970 * $THEME->blockrendermethod = '...';
1972 * It can be one of two values, blocks or blocks_for_region.
1973 * It should be set to the method being used by the theme layouts.
1975 * @return string
1977 public function get_block_render_method() {
1978 if ($this->blockrendermethod) {
1979 // Return the specified block render method.
1980 return $this->blockrendermethod;
1982 // Its not explicitly set, check the parent theme configs.
1983 foreach ($this->parent_configs as $config) {
1984 if (isset($config->blockrendermethod)) {
1985 return $config->blockrendermethod;
1988 // Default it to blocks.
1989 return 'blocks';
1994 * This class keeps track of which HTML tags are currently open.
1996 * This makes it much easier to always generate well formed XHTML output, even
1997 * if execution terminates abruptly. Any time you output some opening HTML
1998 * without the matching closing HTML, you should push the necessary close tags
1999 * onto the stack.
2001 * @copyright 2009 Tim Hunt
2002 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2003 * @since Moodle 2.0
2004 * @package core
2005 * @category output
2007 class xhtml_container_stack {
2010 * @var array Stores the list of open containers.
2012 protected $opencontainers = array();
2015 * @var array In developer debug mode, stores a stack trace of all opens and
2016 * closes, so we can output helpful error messages when there is a mismatch.
2018 protected $log = array();
2021 * @var boolean Store whether we are developer debug mode. We need this in
2022 * several places including in the destructor where we may not have access to $CFG.
2024 protected $isdebugging;
2027 * Constructor
2029 public function __construct() {
2030 global $CFG;
2031 $this->isdebugging = $CFG->debugdeveloper;
2035 * Push the close HTML for a recently opened container onto the stack.
2037 * @param string $type The type of container. This is checked when {@link pop()}
2038 * is called and must match, otherwise a developer debug warning is output.
2039 * @param string $closehtml The HTML required to close the container.
2041 public function push($type, $closehtml) {
2042 $container = new stdClass;
2043 $container->type = $type;
2044 $container->closehtml = $closehtml;
2045 if ($this->isdebugging) {
2046 $this->log('Open', $type);
2048 array_push($this->opencontainers, $container);
2052 * Pop the HTML for the next closing container from the stack. The $type
2053 * must match the type passed when the container was opened, otherwise a
2054 * warning will be output.
2056 * @param string $type The type of container.
2057 * @return string the HTML required to close the container.
2059 public function pop($type) {
2060 if (empty($this->opencontainers)) {
2061 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2062 $this->output_log(), DEBUG_DEVELOPER);
2063 return;
2066 $container = array_pop($this->opencontainers);
2067 if ($container->type != $type) {
2068 debugging('<p>The type of container to be closed (' . $container->type .
2069 ') does not match the type of the next open container (' . $type .
2070 '). This suggests there is a nesting problem.</p>' .
2071 $this->output_log(), DEBUG_DEVELOPER);
2073 if ($this->isdebugging) {
2074 $this->log('Close', $type);
2076 return $container->closehtml;
2080 * Close all but the last open container. This is useful in places like error
2081 * handling, where you want to close all the open containers (apart from <body>)
2082 * before outputting the error message.
2084 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2085 * developer debug warning if it isn't.
2086 * @return string the HTML required to close any open containers inside <body>.
2088 public function pop_all_but_last($shouldbenone = false) {
2089 if ($shouldbenone && count($this->opencontainers) != 1) {
2090 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2091 $this->output_log(), DEBUG_DEVELOPER);
2093 $output = '';
2094 while (count($this->opencontainers) > 1) {
2095 $container = array_pop($this->opencontainers);
2096 $output .= $container->closehtml;
2098 return $output;
2102 * You can call this function if you want to throw away an instance of this
2103 * class without properly emptying the stack (for example, in a unit test).
2104 * Calling this method stops the destruct method from outputting a developer
2105 * debug warning. After calling this method, the instance can no longer be used.
2107 public function discard() {
2108 $this->opencontainers = null;
2112 * Adds an entry to the log.
2114 * @param string $action The name of the action
2115 * @param string $type The type of action
2117 protected function log($action, $type) {
2118 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
2119 format_backtrace(debug_backtrace()) . '</li>';
2123 * Outputs the log's contents as a HTML list.
2125 * @return string HTML list of the log
2127 protected function output_log() {
2128 return '<ul>' . implode("\n", $this->log) . '</ul>';