Merge branch 'MDL-48202-M30' of git://github.com/lazydaisy/moodle
[moodle.git] / lib / outputlib.php
blob35e2f34a5220ede54777a10e0f203e9786b2eb92
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions for generating the HTML that Moodle should output.
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
21 * for an overview.
23 * @copyright 2009 Tim Hunt
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * @package core
26 * @category output
29 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->libdir.'/outputcomponents.php');
32 require_once($CFG->libdir.'/outputactions.php');
33 require_once($CFG->libdir.'/outputfactories.php');
34 require_once($CFG->libdir.'/outputrenderers.php');
35 require_once($CFG->libdir.'/outputrequirementslib.php');
37 /**
38 * Invalidate all server and client side caches.
40 * This method deletes the physical directory that is used to cache the theme
41 * files used for serving.
42 * Because it deletes the main theme cache directory all themes are reset by
43 * this function.
45 function theme_reset_all_caches() {
46 global $CFG, $PAGE;
48 $next = time();
49 if (isset($CFG->themerev) and $next <= $CFG->themerev and $CFG->themerev - $next < 60*60) {
50 // This resolves problems when reset is requested repeatedly within 1s,
51 // the < 1h condition prevents accidental switching to future dates
52 // because we might not recover from it.
53 $next = $CFG->themerev+1;
56 set_config('themerev', $next); // time is unique even when you reset/switch database
58 if (!empty($CFG->themedesignermode)) {
59 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner');
60 $cache->purge();
63 if ($PAGE) {
64 $PAGE->reload_theme();
68 /**
69 * Enable or disable theme designer mode.
71 * @param bool $state
73 function theme_set_designer_mod($state) {
74 set_config('themedesignermode', (int)!empty($state));
75 // Reset caches after switching mode so that any designer mode caches get purged too.
76 theme_reset_all_caches();
79 /**
80 * Returns current theme revision number.
82 * @return int
84 function theme_get_revision() {
85 global $CFG;
87 if (empty($CFG->themedesignermode)) {
88 if (empty($CFG->themerev)) {
89 return -1;
90 } else {
91 return $CFG->themerev;
94 } else {
95 return -1;
101 * This class represents the configuration variables of a Moodle theme.
103 * All the variables with access: public below (with a few exceptions that are marked)
104 * are the properties you can set in your themes config.php file.
106 * There are also some methods and protected variables that are part of the inner
107 * workings of Moodle's themes system. If you are just editing a themes config.php
108 * file, you can just ignore those, and the following information for developers.
110 * Normally, to create an instance of this class, you should use the
111 * {@link theme_config::load()} factory method to load a themes config.php file.
112 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
113 * will create one for you, accessible as $PAGE->theme.
115 * @copyright 2009 Tim Hunt
116 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
117 * @since Moodle 2.0
118 * @package core
119 * @category output
121 class theme_config {
124 * @var string Default theme, used when requested theme not found.
126 const DEFAULT_THEME = 'clean';
129 * @var array You can base your theme on other themes by linking to the other theme as
130 * parents. This lets you use the CSS and layouts from the other themes
131 * (see {@link theme_config::$layouts}).
132 * That makes it easy to create a new theme that is similar to another one
133 * but with a few changes. In this themes CSS you only need to override
134 * those rules you want to change.
136 public $parents;
139 * @var array The names of all the stylesheets from this theme that you would
140 * like included, in order. Give the names of the files without .css.
142 public $sheets = array();
145 * @var array The names of all the stylesheets from parents that should be excluded.
146 * true value may be used to specify all parents or all themes from one parent.
147 * If no value specified value from parent theme used.
149 public $parents_exclude_sheets = null;
152 * @var array List of plugin sheets to be excluded.
153 * If no value specified value from parent theme used.
155 public $plugins_exclude_sheets = null;
158 * @var array List of style sheets that are included in the text editor bodies.
159 * Sheets from parent themes are used automatically and can not be excluded.
161 public $editor_sheets = array();
164 * @var array The names of all the javascript files this theme that you would
165 * like included from head, in order. Give the names of the files without .js.
167 public $javascripts = array();
170 * @var array The names of all the javascript files this theme that you would
171 * like included from footer, in order. Give the names of the files without .js.
173 public $javascripts_footer = array();
176 * @var array The names of all the javascript files from parents that should
177 * be excluded. true value may be used to specify all parents or all themes
178 * from one parent.
179 * If no value specified value from parent theme used.
181 public $parents_exclude_javascripts = null;
184 * @var array Which file to use for each page layout.
186 * This is an array of arrays. The keys of the outer array are the different layouts.
187 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
188 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
189 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
190 * That file also has a good example of how to set this setting.
192 * For each layout, the value in the outer array is an array that describes
193 * how you want that type of page to look. For example
194 * <pre>
195 * $THEME->layouts = array(
196 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
197 * 'standard' => array(
198 * 'theme' = 'mytheme',
199 * 'file' => 'normal.php',
200 * 'regions' => array('side-pre', 'side-post'),
201 * 'defaultregion' => 'side-post'
202 * ),
203 * // The site home page.
204 * 'home' => array(
205 * 'theme' = 'mytheme',
206 * 'file' => 'home.php',
207 * 'regions' => array('side-pre', 'side-post'),
208 * 'defaultregion' => 'side-post'
209 * ),
210 * // ...
211 * );
212 * </pre>
214 * 'theme' name of the theme where is the layout located
215 * 'file' is the layout file to use for this type of page.
216 * layout files are stored in layout subfolder
217 * 'regions' This lists the regions on the page where blocks may appear. For
218 * each region you list here, your layout file must include a call to
219 * <pre>
220 * echo $OUTPUT->blocks_for_region($regionname);
221 * </pre>
222 * or equivalent so that the blocks are actually visible.
224 * 'defaultregion' If the list of regions is non-empty, then you must pick
225 * one of the one of them as 'default'. This has two meanings. First, this is
226 * where new blocks are added. Second, if there are any blocks associated with
227 * the page, but in non-existent regions, they appear here. (Imaging, for example,
228 * that someone added blocks using a different theme that used different region
229 * names, and then switched to this theme.)
231 public $layouts = array();
234 * @var string Name of the renderer factory class to use. Must implement the
235 * {@link renderer_factory} interface.
237 * This is an advanced feature. Moodle output is generated by 'renderers',
238 * you can customise the HTML that is output by writing custom renderers,
239 * and then you need to specify 'renderer factory' so that Moodle can find
240 * your renderers.
242 * There are some renderer factories supplied with Moodle. Please follow these
243 * links to see what they do.
244 * <ul>
245 * <li>{@link standard_renderer_factory} - the default.</li>
246 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
247 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
248 * </ul>
250 public $rendererfactory = 'standard_renderer_factory';
253 * @var string Function to do custom CSS post-processing.
255 * This is an advanced feature. If you want to do custom post-processing on the
256 * CSS before it is output (for example, to replace certain variable names
257 * with particular values) you can give the name of a function here.
259 public $csspostprocess = null;
262 * @var string Accessibility: Right arrow-like character is
263 * used in the breadcrumb trail, course navigation menu
264 * (previous/next activity), calendar, and search forum block.
265 * If the theme does not set characters, appropriate defaults
266 * are set automatically. Please DO NOT
267 * use &lt; &gt; &raquo; - these are confusing for blind users.
269 public $rarrow = null;
272 * @var string Accessibility: Left arrow-like character is
273 * used in the breadcrumb trail, course navigation menu
274 * (previous/next activity), calendar, and search forum block.
275 * If the theme does not set characters, appropriate defaults
276 * are set automatically. Please DO NOT
277 * use &lt; &gt; &raquo; - these are confusing for blind users.
279 public $larrow = null;
282 * @var string Accessibility: Up arrow-like character is used in
283 * the book heirarchical navigation.
284 * If the theme does not set characters, appropriate defaults
285 * are set automatically. Please DO NOT
286 * use ^ - this is confusing for blind users.
288 public $uarrow = null;
291 * @var bool Some themes may want to disable ajax course editing.
293 public $enablecourseajax = true;
296 * @var string Determines served document types
297 * - 'html5' the only officially supported doctype in Moodle
298 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
299 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
301 public $doctype = 'html5';
303 //==Following properties are not configurable from theme config.php==
306 * @var string The name of this theme. Set automatically when this theme is
307 * loaded. This can not be set in theme config.php
309 public $name;
312 * @var string The folder where this themes files are stored. This is set
313 * automatically. This can not be set in theme config.php
315 public $dir;
318 * @var stdClass Theme settings stored in config_plugins table.
319 * This can not be set in theme config.php
321 public $setting = null;
324 * @var bool If set to true and the theme enables the dock then blocks will be able
325 * to be moved to the special dock
327 public $enable_dock = false;
330 * @var bool If set to true then this theme will not be shown in the theme selector unless
331 * theme designer mode is turned on.
333 public $hidefromselector = false;
336 * @var array list of YUI CSS modules to be included on each page. This may be used
337 * to remove cssreset and use cssnormalise module instead.
339 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
342 * An associative array of block manipulations that should be made if the user is using an rtl language.
343 * The key is the original block region, and the value is the block region to change to.
344 * This is used when displaying blocks for regions only.
345 * @var array
347 public $blockrtlmanipulations = array();
350 * @var renderer_factory Instance of the renderer_factory implementation
351 * we are using. Implementation detail.
353 protected $rf = null;
356 * @var array List of parent config objects.
358 protected $parent_configs = array();
361 * @var bool If set to true then the theme is safe to run through the optimiser (if it is enabled)
362 * If set to false then we know either the theme has already been optimised and the CSS optimiser is not needed
363 * or the theme is not compatible with the CSS optimiser. In both cases even if enabled the CSS optimiser will not
364 * be used with this theme if set to false.
366 public $supportscssoptimisation = true;
369 * Used to determine whether we can serve SVG images or not.
370 * @var bool
372 private $usesvg = null;
375 * The LESS file to compile. When set, the theme will attempt to compile the file itself.
376 * @var bool
378 public $lessfile = false;
381 * The name of the function to call to get the LESS code to inject.
382 * @var string
384 public $extralesscallback = null;
387 * The name of the function to call to get extra LESS variables.
388 * @var string
390 public $lessvariablescallback = null;
393 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
394 * Defaults to {@link core_renderer::blocks_for_region()}
395 * @var string
397 public $blockrendermethod = null;
400 * Load the config.php file for a particular theme, and return an instance
401 * of this class. (That is, this is a factory method.)
403 * @param string $themename the name of the theme.
404 * @return theme_config an instance of this class.
406 public static function load($themename) {
407 global $CFG;
409 // load theme settings from db
410 try {
411 $settings = get_config('theme_'.$themename);
412 } catch (dml_exception $e) {
413 // most probably moodle tables not created yet
414 $settings = new stdClass();
417 if ($config = theme_config::find_theme_config($themename, $settings)) {
418 return new theme_config($config);
420 } else if ($themename == theme_config::DEFAULT_THEME) {
421 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
423 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
424 return new theme_config($config);
426 } else {
427 // bad luck, the requested theme has some problems - admin see details in theme config
428 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
433 * Theme diagnostic code. It is very problematic to send debug output
434 * to the actual CSS file, instead this functions is supposed to
435 * diagnose given theme and highlights all potential problems.
436 * This information should be available from the theme selection page
437 * or some other debug page for theme designers.
439 * @param string $themename
440 * @return array description of problems
442 public static function diagnose($themename) {
443 //TODO: MDL-21108
444 return array();
448 * Private constructor, can be called only from the factory method.
449 * @param stdClass $config
451 private function __construct($config) {
452 global $CFG; //needed for included lib.php files
454 $this->settings = $config->settings;
455 $this->name = $config->name;
456 $this->dir = $config->dir;
458 if ($this->name != 'base') {
459 $baseconfig = theme_config::find_theme_config('base', $this->settings);
460 } else {
461 $baseconfig = $config;
464 $configurable = array(
465 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets',
466 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
467 'layouts', 'enable_dock', 'enablecourseajax', 'supportscssoptimisation',
468 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'uarrow',
469 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations',
470 'lessfile', 'extralesscallback', 'lessvariablescallback', 'blockrendermethod');
472 foreach ($config as $key=>$value) {
473 if (in_array($key, $configurable)) {
474 $this->$key = $value;
478 // verify all parents and load configs and renderers
479 foreach ($this->parents as $parent) {
480 if ($parent == 'base') {
481 $parent_config = $baseconfig;
482 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
483 // this is not good - better exclude faulty parents
484 continue;
486 $libfile = $parent_config->dir.'/lib.php';
487 if (is_readable($libfile)) {
488 // theme may store various function here
489 include_once($libfile);
491 $renderersfile = $parent_config->dir.'/renderers.php';
492 if (is_readable($renderersfile)) {
493 // may contain core and plugin renderers and renderer factory
494 include_once($renderersfile);
496 $this->parent_configs[$parent] = $parent_config;
498 $libfile = $this->dir.'/lib.php';
499 if (is_readable($libfile)) {
500 // theme may store various function here
501 include_once($libfile);
503 $rendererfile = $this->dir.'/renderers.php';
504 if (is_readable($rendererfile)) {
505 // may contain core and plugin renderers and renderer factory
506 include_once($rendererfile);
507 } else {
508 // check if renderers.php file is missnamed renderer.php
509 if (is_readable($this->dir.'/renderer.php')) {
510 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
511 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
515 // cascade all layouts properly
516 foreach ($baseconfig->layouts as $layout=>$value) {
517 if (!isset($this->layouts[$layout])) {
518 foreach ($this->parent_configs as $parent_config) {
519 if (isset($parent_config->layouts[$layout])) {
520 $this->layouts[$layout] = $parent_config->layouts[$layout];
521 continue 2;
524 $this->layouts[$layout] = $value;
528 //fix arrows if needed
529 $this->check_theme_arrows();
533 * Let the theme initialise the page object (usually $PAGE).
535 * This may be used for example to request jQuery in add-ons.
537 * @param moodle_page $page
539 public function init_page(moodle_page $page) {
540 $themeinitfunction = 'theme_'.$this->name.'_page_init';
541 if (function_exists($themeinitfunction)) {
542 $themeinitfunction($page);
547 * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow have been set (theme/-/config.php).
548 * If not it applies sensible defaults.
550 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
551 * search forum block, etc. Important: these are 'silent' in a screen-reader
552 * (unlike &gt; &raquo;), and must be accompanied by text.
554 private function check_theme_arrows() {
555 if (!isset($this->rarrow) and !isset($this->larrow)) {
556 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
557 // Also OK in Win 9x/2K/IE 5.x
558 $this->rarrow = '&#x25BA;';
559 $this->larrow = '&#x25C4;';
560 $this->uarrow = '&#x25B2;';
561 if (empty($_SERVER['HTTP_USER_AGENT'])) {
562 $uagent = '';
563 } else {
564 $uagent = $_SERVER['HTTP_USER_AGENT'];
566 if (false !== strpos($uagent, 'Opera')
567 || false !== strpos($uagent, 'Mac')) {
568 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
569 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
570 $this->rarrow = '&#x25B6;&#xFE0E;';
571 $this->larrow = '&#x25C0;&#xFE0E;';
573 elseif ((false !== strpos($uagent, 'Konqueror'))
574 || (false !== strpos($uagent, 'Android'))) {
575 // The fonts on Android don't include the characters required for this to work as expected.
576 // So we use the same ones Konqueror uses.
577 $this->rarrow = '&rarr;';
578 $this->larrow = '&larr;';
579 $this->uarrow = '&uarr;';
581 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
582 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
583 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
584 // To be safe, non-Unicode browsers!
585 $this->rarrow = '&gt;';
586 $this->larrow = '&lt;';
587 $this->uarrow = '^';
590 // RTL support - in RTL languages, swap r and l arrows
591 if (right_to_left()) {
592 $t = $this->rarrow;
593 $this->rarrow = $this->larrow;
594 $this->larrow = $t;
600 * Returns output renderer prefixes, these are used when looking
601 * for the overridden renderers in themes.
603 * @return array
605 public function renderer_prefixes() {
606 global $CFG; // just in case the included files need it
608 $prefixes = array('theme_'.$this->name);
610 foreach ($this->parent_configs as $parent) {
611 $prefixes[] = 'theme_'.$parent->name;
614 return $prefixes;
618 * Returns the stylesheet URL of this editor content
620 * @param bool $encoded false means use & and true use &amp; in URLs
621 * @return moodle_url
623 public function editor_css_url($encoded=true) {
624 global $CFG;
625 $rev = theme_get_revision();
626 if ($rev > -1) {
627 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
628 if (!empty($CFG->slasharguments)) {
629 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
630 } else {
631 $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
633 } else {
634 $params = array('theme'=>$this->name, 'type'=>'editor');
635 $url = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
637 return $url;
641 * Returns the content of the CSS to be used in editor content
643 * @return array
645 public function editor_css_files() {
646 $files = array();
648 // First editor plugins.
649 $plugins = core_component::get_plugin_list('editor');
650 foreach ($plugins as $plugin=>$fulldir) {
651 $sheetfile = "$fulldir/editor_styles.css";
652 if (is_readable($sheetfile)) {
653 $files['plugin_'.$plugin] = $sheetfile;
656 // Then parent themes - base first, the immediate parent last.
657 foreach (array_reverse($this->parent_configs) as $parent_config) {
658 if (empty($parent_config->editor_sheets)) {
659 continue;
661 foreach ($parent_config->editor_sheets as $sheet) {
662 $sheetfile = "$parent_config->dir/style/$sheet.css";
663 if (is_readable($sheetfile)) {
664 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
668 // Finally this theme.
669 if (!empty($this->editor_sheets)) {
670 foreach ($this->editor_sheets as $sheet) {
671 $sheetfile = "$this->dir/style/$sheet.css";
672 if (is_readable($sheetfile)) {
673 $files['theme_'.$sheet] = $sheetfile;
678 return $files;
682 * Get the stylesheet URL of this theme.
684 * @param moodle_page $page Not used... deprecated?
685 * @return moodle_url[]
687 public function css_urls(moodle_page $page) {
688 global $CFG;
690 $rev = theme_get_revision();
692 $urls = array();
694 $svg = $this->use_svg_icons();
695 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
697 if ($rev > -1) {
698 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
699 if (!empty($CFG->slasharguments)) {
700 $slashargs = '';
701 if (!$svg) {
702 // We add a simple /_s to the start of the path.
703 // The underscore is used to ensure that it isn't a valid theme name.
704 $slashargs .= '/_s'.$slashargs;
706 $slashargs .= '/'.$this->name.'/'.$rev.'/all';
707 if ($separate) {
708 $slashargs .= '/chunk0';
710 $url->set_slashargument($slashargs, 'noparam', true);
711 } else {
712 $params = array('theme' => $this->name,'rev' => $rev, 'type' => 'all');
713 if (!$svg) {
714 // We add an SVG param so that we know not to serve SVG images.
715 // We do this because all modern browsers support SVG and this param will one day be removed.
716 $params['svg'] = '0';
718 if ($separate) {
719 $params['chunk'] = '0';
721 $url->params($params);
723 $urls[] = $url;
725 } else {
726 $baseurl = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php');
728 $css = $this->get_css_files(true);
729 if (!$svg) {
730 // We add an SVG param so that we know not to serve SVG images.
731 // We do this because all modern browsers support SVG and this param will one day be removed.
732 $baseurl->param('svg', '0');
734 if ($separate) {
735 // We might need to chunk long files.
736 $baseurl->param('chunk', '0');
738 if (core_useragent::is_ie()) {
739 // Lalala, IE does not allow more than 31 linked CSS files from main document.
740 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
741 foreach ($css['parents'] as $parent=>$sheets) {
742 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
743 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
745 if (!empty($this->lessfile)) {
746 // No need to define the type as IE here.
747 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
749 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
751 } else {
752 foreach ($css['plugins'] as $plugin=>$unused) {
753 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
755 foreach ($css['parents'] as $parent=>$sheets) {
756 foreach ($sheets as $sheet=>$unused2) {
757 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
760 foreach ($css['theme'] as $sheet => $filename) {
761 if ($sheet === $this->lessfile) {
762 // This is the theme LESS file.
763 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'less'));
764 } else {
765 // Sheet first in order to make long urls easier to read.
766 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
772 return $urls;
776 * Get the whole css stylesheet for production mode.
778 * NOTE: this method is not expected to be used from any addons.
780 * @return string CSS markup, already optimised and compressed
782 public function get_css_content() {
783 global $CFG;
784 require_once($CFG->dirroot.'/lib/csslib.php');
786 $csscontent = '';
787 foreach ($this->get_css_files(false) as $type => $value) {
788 foreach ($value as $identifier => $val) {
789 if (is_array($val)) {
790 foreach ($val as $v) {
791 $csscontent .= file_get_contents($v) . "\n";
793 } else {
794 if ($type === 'theme' && $identifier === $this->lessfile) {
795 // We need the content from LESS because this is the LESS file from the theme.
796 $csscontent .= $this->get_css_content_from_less(false);
797 } else {
798 $csscontent .= file_get_contents($val) . "\n";
803 $csscontent = $this->post_process($csscontent);
805 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
806 // This is an experimental feature introduced in Moodle 2.3
807 // The CSS optimiser organises the CSS in order to reduce the overall number
808 // of rules and styles being sent to the client. It does this by collating
809 // the CSS before it is cached removing excess styles and rules and stripping
810 // out any extraneous content such as comments and empty rules.
811 $optimiser = new css_optimiser();
812 $csscontent = $optimiser->process($csscontent);
814 } else {
815 $csscontent = core_minify::css($csscontent);
818 return $csscontent;
822 * Get the theme designer css markup,
823 * the parameters are coming from css_urls().
825 * NOTE: this method is not expected to be used from any addons.
827 * @param string $type
828 * @param string $subtype
829 * @param string $sheet
830 * @return string CSS markup
832 public function get_css_content_debug($type, $subtype, $sheet) {
833 global $CFG;
834 require_once($CFG->dirroot.'/lib/csslib.php');
836 // The LESS file of the theme is requested.
837 if ($type === 'less') {
838 $csscontent = $this->get_css_content_from_less(true);
839 if ($csscontent !== false) {
840 return $csscontent;
842 return '';
845 $optimiser = null;
846 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
847 // This is an experimental feature introduced in Moodle 2.3
848 // The CSS optimiser organises the CSS in order to reduce the overall number
849 // of rules and styles being sent to the client. It does this by collating
850 // the CSS before it is cached removing excess styles and rules and stripping
851 // out any extraneous content such as comments and empty rules.
852 $optimiser = new css_optimiser();
855 $cssfiles = array();
856 $css = $this->get_css_files(true);
858 if ($type === 'ie') {
859 // IE is a sloppy browser with weird limits, sorry.
860 if ($subtype === 'plugins') {
861 $cssfiles = $css['plugins'];
863 } else if ($subtype === 'parents') {
864 if (empty($sheet)) {
865 // Do not bother with the empty parent here.
866 } else {
867 // Build up the CSS for that parent so we can serve it as one file.
868 foreach ($css[$subtype][$sheet] as $parent => $css) {
869 $cssfiles[] = $css;
872 } else if ($subtype === 'theme') {
873 $cssfiles = $css['theme'];
874 foreach ($cssfiles as $key => $value) {
875 if ($this->lessfile && $key === $this->lessfile) {
876 // Remove the LESS file from the theme CSS files.
877 // The LESS files use the type 'less', not 'ie'.
878 unset($cssfiles[$key]);
883 } else if ($type === 'plugin') {
884 if (isset($css['plugins'][$subtype])) {
885 $cssfiles[] = $css['plugins'][$subtype];
888 } else if ($type === 'parent') {
889 if (isset($css['parents'][$subtype][$sheet])) {
890 $cssfiles[] = $css['parents'][$subtype][$sheet];
893 } else if ($type === 'theme') {
894 if (isset($css['theme'][$sheet])) {
895 $cssfiles[] = $css['theme'][$sheet];
899 $csscontent = '';
900 foreach ($cssfiles as $file) {
901 $contents = file_get_contents($file);
902 $contents = $this->post_process($contents);
903 $comment = "/** Path: $type $subtype $sheet.' **/\n";
904 $stats = '';
905 if ($optimiser) {
906 $contents = $optimiser->process($contents);
907 if (!empty($CFG->cssoptimiserstats)) {
908 $stats = $optimiser->output_stats_css();
911 $csscontent .= $comment.$stats.$contents."\n\n";
914 return $csscontent;
918 * Get the whole css stylesheet for editor iframe.
920 * NOTE: this method is not expected to be used from any addons.
922 * @return string CSS markup
924 public function get_css_content_editor() {
925 // Do not bother to optimise anything here, just very basic stuff.
926 $cssfiles = $this->editor_css_files();
927 $css = '';
928 foreach ($cssfiles as $file) {
929 $css .= file_get_contents($file)."\n";
931 return $this->post_process($css);
935 * Returns an array of organised CSS files required for this output.
937 * @param bool $themedesigner
938 * @return array nested array of file paths
940 protected function get_css_files($themedesigner) {
941 global $CFG;
943 $cache = null;
944 $cachekey = 'cssfiles';
945 if ($themedesigner) {
946 require_once($CFG->dirroot.'/lib/csslib.php');
947 // We need some kind of caching here because otherwise the page navigation becomes
948 // way too slow in theme designer mode. Feel free to create full cache definition later...
949 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
950 if ($files = $cache->get($cachekey)) {
951 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
952 unset($files['created']);
953 return $files;
958 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
960 // Get all plugin sheets.
961 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
962 if ($excludes !== true) {
963 foreach (core_component::get_plugin_types() as $type=>$unused) {
964 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
965 continue;
967 $plugins = core_component::get_plugin_list($type);
968 foreach ($plugins as $plugin=>$fulldir) {
969 if (!empty($excludes[$type]) and is_array($excludes[$type])
970 and in_array($plugin, $excludes[$type])) {
971 continue;
974 // Get the CSS from the plugin.
975 $sheetfile = "$fulldir/styles.css";
976 if (is_readable($sheetfile)) {
977 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
980 // Create a list of candidate sheets from parents (direct parent last) and current theme.
981 $candidates = array();
982 foreach (array_reverse($this->parent_configs) as $parent_config) {
983 $candidates[] = $parent_config->name;
985 $candidates[] = $this->name;
987 // Add the sheets found.
988 foreach ($candidates as $candidate) {
989 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
990 if (is_readable($sheetthemefile)) {
991 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
998 // Find out wanted parent sheets.
999 $excludes = $this->resolve_excludes('parents_exclude_sheets');
1000 if ($excludes !== true) {
1001 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1002 $parent = $parent_config->name;
1003 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
1004 continue;
1006 foreach ($parent_config->sheets as $sheet) {
1007 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1008 && in_array($sheet, $excludes[$parent])) {
1009 continue;
1012 // We never refer to the parent LESS files.
1013 $sheetfile = "$parent_config->dir/style/$sheet.css";
1014 if (is_readable($sheetfile)) {
1015 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1021 // Current theme sheets and less file.
1022 // We first add the LESS files because we want the CSS ones to be included after the
1023 // LESS code. However, if both the LESS file and the CSS file share the same name,
1024 // the CSS file is ignored.
1025 if (!empty($this->lessfile)) {
1026 $sheetfile = "{$this->dir}/less/{$this->lessfile}.less";
1027 if (is_readable($sheetfile)) {
1028 $cssfiles['theme'][$this->lessfile] = $sheetfile;
1031 if (is_array($this->sheets)) {
1032 foreach ($this->sheets as $sheet) {
1033 $sheetfile = "$this->dir/style/$sheet.css";
1034 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1035 $cssfiles['theme'][$sheet] = $sheetfile;
1040 if ($cache) {
1041 $files = $cssfiles;
1042 $files['created'] = time();
1043 $cache->set($cachekey, $files);
1045 return $cssfiles;
1049 * Return the CSS content generated from LESS the file.
1051 * @param bool $themedesigner True if theme designer is enabled.
1052 * @return bool|string Return false when the compilation failed. Else the compiled string.
1054 protected function get_css_content_from_less($themedesigner) {
1056 $lessfile = $this->lessfile;
1057 if (!$lessfile || !is_readable($this->dir . '/less/' . $lessfile . '.less')) {
1058 throw new coding_exception('The theme did not define a LESS file, or it is not readable.');
1061 // We might need more memory to do this, so let's play safe.
1062 raise_memory_limit(MEMORY_EXTRA);
1064 // Files list.
1065 $files = $this->get_css_files($themedesigner);
1067 // Get the LESS file path.
1068 $themelessfile = $files['theme'][$lessfile];
1070 // Setup compiler options.
1071 $options = array(
1072 // We need to set the import directory to where $lessfile is.
1073 'import_dirs' => array(dirname($themelessfile) => '/'),
1074 // Always disable default caching.
1075 'cache_method' => false,
1076 // Disable the relative URLs, we have post_process() to handle that.
1077 'relativeUrls' => false,
1080 if ($themedesigner) {
1081 // Add the sourceMap inline to ensure that it is atomically generated.
1082 $options['sourceMap'] = true;
1083 $options['sourceRoot'] = 'theme';
1086 // Instantiate the compiler.
1087 $compiler = new core_lessc($options);
1089 try {
1090 $compiler->parse_file_content($themelessfile);
1092 // Get the callbacks.
1093 $compiler->parse($this->get_extra_less_code());
1094 $compiler->ModifyVars($this->get_less_variables());
1096 // Compile the CSS.
1097 $compiled = $compiler->getCss();
1099 // Post process the entire thing.
1100 $compiled = $this->post_process($compiled);
1101 } catch (Less_Exception_Parser $e) {
1102 $compiled = false;
1103 debugging('Error while compiling LESS ' . $lessfile . ' file: ' . $e->getMessage(), DEBUG_DEVELOPER);
1106 // Try to save memory.
1107 $compiler = null;
1108 unset($compiler);
1110 return $compiled;
1114 * Return extra LESS variables to use when compiling.
1116 * @return array Where keys are the variable names (omitting the @), and the values are the value.
1118 protected function get_less_variables() {
1119 $variables = array();
1121 // Getting all the candidate functions.
1122 $candidates = array();
1123 foreach ($this->parent_configs as $parent_config) {
1124 if (!isset($parent_config->lessvariablescallback)) {
1125 continue;
1127 $candidates[] = $parent_config->lessvariablescallback;
1129 $candidates[] = $this->lessvariablescallback;
1131 // Calling the functions.
1132 foreach ($candidates as $function) {
1133 if (function_exists($function)) {
1134 $vars = $function($this);
1135 if (!is_array($vars)) {
1136 debugging('Callback ' . $function . ' did not return an array() as expected', DEBUG_DEVELOPER);
1137 continue;
1139 $variables = array_merge($variables, $vars);
1143 return $variables;
1147 * Return extra LESS code to add when compiling.
1149 * This is intended to be used by themes to inject some LESS code
1150 * before it gets compiled. If you want to inject variables you
1151 * should use {@link self::get_less_variables()}.
1153 * @return string The LESS code to inject.
1155 protected function get_extra_less_code() {
1156 $content = '';
1158 // Getting all the candidate functions.
1159 $candidates = array();
1160 foreach ($this->parent_configs as $parent_config) {
1161 if (!isset($parent_config->extralesscallback)) {
1162 continue;
1164 $candidates[] = $parent_config->extralesscallback;
1166 $candidates[] = $this->extralesscallback;
1168 // Calling the functions.
1169 foreach ($candidates as $function) {
1170 if (function_exists($function)) {
1171 $content .= "\n/** Extra LESS from $function **/\n" . $function($this) . "\n";
1175 return $content;
1179 * Generate a URL to the file that serves theme JavaScript files.
1181 * If we determine that the theme has no relevant files, then we return
1182 * early with a null value.
1184 * @param bool $inhead true means head url, false means footer
1185 * @return moodle_url|null
1187 public function javascript_url($inhead) {
1188 global $CFG;
1190 $rev = theme_get_revision();
1191 $params = array('theme'=>$this->name,'rev'=>$rev);
1192 $params['type'] = $inhead ? 'head' : 'footer';
1194 // Return early if there are no files to serve
1195 if (count($this->javascript_files($params['type'])) === 0) {
1196 return null;
1199 if (!empty($CFG->slasharguments) and $rev > 0) {
1200 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
1201 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
1202 return $url;
1203 } else {
1204 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
1209 * Get the URL's for the JavaScript files used by this theme.
1210 * They won't be served directly, instead they'll be mediated through
1211 * theme/javascript.php.
1213 * @param string $type Either javascripts_footer, or javascripts
1214 * @return array
1216 public function javascript_files($type) {
1217 if ($type === 'footer') {
1218 $type = 'javascripts_footer';
1219 } else {
1220 $type = 'javascripts';
1223 $js = array();
1224 // find out wanted parent javascripts
1225 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1226 if ($excludes !== true) {
1227 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1228 $parent = $parent_config->name;
1229 if (empty($parent_config->$type)) {
1230 continue;
1232 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1233 continue;
1235 foreach ($parent_config->$type as $javascript) {
1236 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1237 and in_array($javascript, $excludes[$parent])) {
1238 continue;
1240 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1241 if (is_readable($javascriptfile)) {
1242 $js[] = $javascriptfile;
1248 // current theme javascripts
1249 if (is_array($this->$type)) {
1250 foreach ($this->$type as $javascript) {
1251 $javascriptfile = "$this->dir/javascript/$javascript.js";
1252 if (is_readable($javascriptfile)) {
1253 $js[] = $javascriptfile;
1257 return $js;
1261 * Resolves an exclude setting to the themes setting is applicable or the
1262 * setting of its closest parent.
1264 * @param string $variable The name of the setting the exclude setting to resolve
1265 * @param string $default
1266 * @return mixed
1268 protected function resolve_excludes($variable, $default = null) {
1269 $setting = $default;
1270 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1271 $setting = $this->{$variable};
1272 } else {
1273 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1274 if (!isset($parent_config->{$variable})) {
1275 continue;
1277 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1278 $setting = $parent_config->{$variable};
1279 break;
1283 return $setting;
1287 * Returns the content of the one huge javascript file merged from all theme javascript files.
1289 * @param bool $type
1290 * @return string
1292 public function javascript_content($type) {
1293 $jsfiles = $this->javascript_files($type);
1294 $js = '';
1295 foreach ($jsfiles as $jsfile) {
1296 $js .= file_get_contents($jsfile)."\n";
1298 return $js;
1302 * Post processes CSS.
1304 * This method post processes all of the CSS before it is served for this theme.
1305 * This is done so that things such as image URL's can be swapped in and to
1306 * run any specific CSS post process method the theme has requested.
1307 * This allows themes to use CSS settings.
1309 * @param string $css The CSS to process.
1310 * @return string The processed CSS.
1312 public function post_process($css) {
1313 // now resolve all image locations
1314 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1315 $replaced = array();
1316 foreach ($matches as $match) {
1317 if (isset($replaced[$match[0]])) {
1318 continue;
1320 $replaced[$match[0]] = true;
1321 $imagename = $match[2];
1322 $component = rtrim($match[1], '|');
1323 $imageurl = $this->pix_url($imagename, $component)->out(false);
1324 // we do not need full url because the image.php is always in the same dir
1325 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1326 $css = str_replace($match[0], $imageurl, $css);
1330 // Now resolve all font locations.
1331 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1332 $replaced = array();
1333 foreach ($matches as $match) {
1334 if (isset($replaced[$match[0]])) {
1335 continue;
1337 $replaced[$match[0]] = true;
1338 $fontname = $match[2];
1339 $component = rtrim($match[1], '|');
1340 $fonturl = $this->font_url($fontname, $component)->out(false);
1341 // We do not need full url because the font.php is always in the same dir.
1342 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1343 $css = str_replace($match[0], $fonturl, $css);
1347 // now resolve all theme settings or do any other postprocessing
1348 $csspostprocess = $this->csspostprocess;
1349 if (function_exists($csspostprocess)) {
1350 $css = $csspostprocess($css, $this);
1353 return $css;
1357 * Return the URL for an image
1359 * @param string $imagename the name of the icon.
1360 * @param string $component specification of one plugin like in get_string()
1361 * @return moodle_url
1363 public function pix_url($imagename, $component) {
1364 global $CFG;
1366 $params = array('theme'=>$this->name);
1367 $svg = $this->use_svg_icons();
1369 if (empty($component) or $component === 'moodle' or $component === 'core') {
1370 $params['component'] = 'core';
1371 } else {
1372 $params['component'] = $component;
1375 $rev = theme_get_revision();
1376 if ($rev != -1) {
1377 $params['rev'] = $rev;
1380 $params['image'] = $imagename;
1382 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1383 if (!empty($CFG->slasharguments) and $rev > 0) {
1384 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1385 if (!$svg) {
1386 // We add a simple /_s to the start of the path.
1387 // The underscore is used to ensure that it isn't a valid theme name.
1388 $path = '/_s'.$path;
1390 $url->set_slashargument($path, 'noparam', true);
1391 } else {
1392 if (!$svg) {
1393 // We add an SVG param so that we know not to serve SVG images.
1394 // We do this because all modern browsers support SVG and this param will one day be removed.
1395 $params['svg'] = '0';
1397 $url->params($params);
1400 return $url;
1404 * Return the URL for a font
1406 * @param string $font the name of the font (including extension).
1407 * @param string $component specification of one plugin like in get_string()
1408 * @return moodle_url
1410 public function font_url($font, $component) {
1411 global $CFG;
1413 $params = array('theme'=>$this->name);
1415 if (empty($component) or $component === 'moodle' or $component === 'core') {
1416 $params['component'] = 'core';
1417 } else {
1418 $params['component'] = $component;
1421 $rev = theme_get_revision();
1422 if ($rev != -1) {
1423 $params['rev'] = $rev;
1426 $params['font'] = $font;
1428 $url = new moodle_url("$CFG->httpswwwroot/theme/font.php");
1429 if (!empty($CFG->slasharguments) and $rev > 0) {
1430 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1431 $url->set_slashargument($path, 'noparam', true);
1432 } else {
1433 $url->params($params);
1436 return $url;
1440 * Returns URL to the stored file via pluginfile.php.
1442 * Note the theme must also implement pluginfile.php handler,
1443 * theme revision is used instead of the itemid.
1445 * @param string $setting
1446 * @param string $filearea
1447 * @return string protocol relative URL or null if not present
1449 public function setting_file_url($setting, $filearea) {
1450 global $CFG;
1452 if (empty($this->settings->$setting)) {
1453 return null;
1456 $component = 'theme_'.$this->name;
1457 $itemid = theme_get_revision();
1458 $filepath = $this->settings->$setting;
1459 $syscontext = context_system::instance();
1461 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1463 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1464 // Note: unfortunately moodle_url does not support //urls yet.
1466 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1468 return $url;
1472 * Serve the theme setting file.
1474 * @param string $filearea
1475 * @param array $args
1476 * @param bool $forcedownload
1477 * @param array $options
1478 * @return bool may terminate if file not found or donotdie not specified
1480 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1481 global $CFG;
1482 require_once("$CFG->libdir/filelib.php");
1484 $syscontext = context_system::instance();
1485 $component = 'theme_'.$this->name;
1487 $revision = array_shift($args);
1488 if ($revision < 0) {
1489 $lifetime = 0;
1490 } else {
1491 $lifetime = 60*60*24*60;
1492 // By default, theme files must be cache-able by both browsers and proxies.
1493 if (!array_key_exists('cacheability', $options)) {
1494 $options['cacheability'] = 'public';
1498 $fs = get_file_storage();
1499 $relativepath = implode('/', $args);
1501 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1502 $fullpath = rtrim($fullpath, '/');
1503 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1504 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1505 return true;
1506 } else {
1507 send_file_not_found();
1512 * Resolves the real image location.
1514 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1515 * and we need a way in which to turn it off.
1516 * By default SVG won't be used unless asked for. This is done for two reasons:
1517 * 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
1518 * browser supports SVG.
1519 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1520 * by the user due to security concerns.
1522 * @param string $image name of image, may contain relative path
1523 * @param string $component
1524 * @param bool $svg If set to true SVG images will also be looked for.
1525 * @return string full file path
1527 public function resolve_image_location($image, $component, $svg = false) {
1528 global $CFG;
1530 if (!is_bool($svg)) {
1531 // If $svg isn't a bool then we need to decide for ourselves.
1532 $svg = $this->use_svg_icons();
1535 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1536 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1537 return $imagefile;
1539 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1540 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1541 return $imagefile;
1544 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1545 return $imagefile;
1547 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1548 return $imagefile;
1550 return null;
1552 } else if ($component === 'theme') { //exception
1553 if ($image === 'favicon') {
1554 return "$this->dir/pix/favicon.ico";
1556 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1557 return $imagefile;
1559 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1560 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1561 return $imagefile;
1564 return null;
1566 } else {
1567 if (strpos($component, '_') === false) {
1568 $component = 'mod_'.$component;
1570 list($type, $plugin) = explode('_', $component, 2);
1572 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1573 return $imagefile;
1575 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1576 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1577 return $imagefile;
1580 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1581 return $imagefile;
1583 $dir = core_component::get_plugin_directory($type, $plugin);
1584 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1585 return $imagefile;
1587 return null;
1592 * Resolves the real font location.
1594 * @param string $font name of font file
1595 * @param string $component
1596 * @return string full file path
1598 public function resolve_font_location($font, $component) {
1599 global $CFG;
1601 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1602 if (file_exists("$this->dir/fonts_core/$font")) {
1603 return "$this->dir/fonts_core/$font";
1605 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1606 if (file_exists("$parent_config->dir/fonts_core/$font")) {
1607 return "$parent_config->dir/fonts_core/$font";
1610 if (file_exists("$CFG->dataroot/fonts/$font")) {
1611 return "$CFG->dataroot/fonts/$font";
1613 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
1614 return "$CFG->dirroot/lib/fonts/$font";
1616 return null;
1618 } else if ($component === 'theme') { // Exception.
1619 if (file_exists("$this->dir/fonts/$font")) {
1620 return "$this->dir/fonts/$font";
1622 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1623 if (file_exists("$parent_config->dir/fonts/$font")) {
1624 return "$parent_config->dir/fonts/$font";
1627 return null;
1629 } else {
1630 if (strpos($component, '_') === false) {
1631 $component = 'mod_'.$component;
1633 list($type, $plugin) = explode('_', $component, 2);
1635 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
1636 return "$this->dir/fonts_plugins/$type/$plugin/$font";
1638 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1639 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
1640 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
1643 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
1644 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
1646 $dir = core_component::get_plugin_directory($type, $plugin);
1647 if (file_exists("$dir/fonts/$font")) {
1648 return "$dir/fonts/$font";
1650 return null;
1655 * Return true if we should look for SVG images as well.
1657 * @return bool
1659 public function use_svg_icons() {
1660 global $CFG;
1661 if ($this->usesvg === null) {
1663 if (!isset($CFG->svgicons) || !is_bool($CFG->svgicons)) {
1664 $this->usesvg = core_useragent::supports_svg();
1665 } else {
1666 // Force them on/off depending upon the setting.
1667 $this->usesvg = $CFG->svgicons;
1670 return $this->usesvg;
1674 * Forces the usesvg setting to either true or false, avoiding any decision making.
1676 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
1677 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
1679 * @param bool $setting True to force the use of svg when available, null otherwise.
1681 public function force_svg_use($setting) {
1682 $this->usesvg = (bool)$setting;
1686 * Checks if file with any image extension exists.
1688 * The order to these images was adjusted prior to the release of 2.4
1689 * At that point the were the following image counts in Moodle core:
1691 * - png = 667 in pix dirs (1499 total)
1692 * - gif = 385 in pix dirs (606 total)
1693 * - jpg = 62 in pix dirs (74 total)
1694 * - jpeg = 0 in pix dirs (1 total)
1696 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1698 * @param string $filepath
1699 * @param bool $svg If set to true SVG images will also be looked for.
1700 * @return string image name with extension
1702 private static function image_exists($filepath, $svg = false) {
1703 if ($svg && file_exists("$filepath.svg")) {
1704 return "$filepath.svg";
1705 } else if (file_exists("$filepath.png")) {
1706 return "$filepath.png";
1707 } else if (file_exists("$filepath.gif")) {
1708 return "$filepath.gif";
1709 } else if (file_exists("$filepath.jpg")) {
1710 return "$filepath.jpg";
1711 } else if (file_exists("$filepath.jpeg")) {
1712 return "$filepath.jpeg";
1713 } else {
1714 return false;
1719 * Loads the theme config from config.php file.
1721 * @param string $themename
1722 * @param stdClass $settings from config_plugins table
1723 * @param boolean $parentscheck true to also check the parents. .
1724 * @return stdClass The theme configuration
1726 private static function find_theme_config($themename, $settings, $parentscheck = true) {
1727 // We have to use the variable name $THEME (upper case) because that
1728 // is what is used in theme config.php files.
1730 if (!$dir = theme_config::find_theme_location($themename)) {
1731 return null;
1734 $THEME = new stdClass();
1735 $THEME->name = $themename;
1736 $THEME->dir = $dir;
1737 $THEME->settings = $settings;
1739 global $CFG; // just in case somebody tries to use $CFG in theme config
1740 include("$THEME->dir/config.php");
1742 // verify the theme configuration is OK
1743 if (!is_array($THEME->parents)) {
1744 // parents option is mandatory now
1745 return null;
1746 } else {
1747 // We use $parentscheck to only check the direct parents (avoid infinite loop).
1748 if ($parentscheck) {
1749 // Find all parent theme configs.
1750 foreach ($THEME->parents as $parent) {
1751 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
1752 if (empty($parentconfig)) {
1753 return null;
1759 return $THEME;
1763 * Finds the theme location and verifies the theme has all needed files
1764 * and is not obsoleted.
1766 * @param string $themename
1767 * @return string full dir path or null if not found
1769 private static function find_theme_location($themename) {
1770 global $CFG;
1772 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1773 $dir = "$CFG->dirroot/theme/$themename";
1775 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1776 $dir = "$CFG->themedir/$themename";
1778 } else {
1779 return null;
1782 if (file_exists("$dir/styles.php")) {
1783 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1784 return null;
1787 return $dir;
1791 * Get the renderer for a part of Moodle for this theme.
1793 * @param moodle_page $page the page we are rendering
1794 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1795 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1796 * @param string $target one of rendering target constants
1797 * @return renderer_base the requested renderer.
1799 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1800 if (is_null($this->rf)) {
1801 $classname = $this->rendererfactory;
1802 $this->rf = new $classname($this);
1805 return $this->rf->get_renderer($page, $component, $subtype, $target);
1809 * Get the information from {@link $layouts} for this type of page.
1811 * @param string $pagelayout the the page layout name.
1812 * @return array the appropriate part of {@link $layouts}.
1814 protected function layout_info_for_page($pagelayout) {
1815 if (array_key_exists($pagelayout, $this->layouts)) {
1816 return $this->layouts[$pagelayout];
1817 } else {
1818 debugging('Invalid page layout specified: ' . $pagelayout);
1819 return $this->layouts['standard'];
1824 * Given the settings of this theme, and the page pagelayout, return the
1825 * full path of the page layout file to use.
1827 * Used by {@link core_renderer::header()}.
1829 * @param string $pagelayout the the page layout name.
1830 * @return string Full path to the lyout file to use
1832 public function layout_file($pagelayout) {
1833 global $CFG;
1835 $layoutinfo = $this->layout_info_for_page($pagelayout);
1836 $layoutfile = $layoutinfo['file'];
1838 if (array_key_exists('theme', $layoutinfo)) {
1839 $themes = array($layoutinfo['theme']);
1840 } else {
1841 $themes = array_merge(array($this->name),$this->parents);
1844 foreach ($themes as $theme) {
1845 if ($dir = $this->find_theme_location($theme)) {
1846 $path = "$dir/layout/$layoutfile";
1848 // Check the template exists, return general base theme template if not.
1849 if (is_readable($path)) {
1850 return $path;
1855 debugging('Can not find layout file for: ' . $pagelayout);
1856 // fallback to standard normal layout
1857 return "$CFG->dirroot/theme/base/layout/general.php";
1861 * Returns auxiliary page layout options specified in layout configuration array.
1863 * @param string $pagelayout
1864 * @return array
1866 public function pagelayout_options($pagelayout) {
1867 $info = $this->layout_info_for_page($pagelayout);
1868 if (!empty($info['options'])) {
1869 return $info['options'];
1871 return array();
1875 * Inform a block_manager about the block regions this theme wants on this
1876 * page layout.
1878 * @param string $pagelayout the general type of the page.
1879 * @param block_manager $blockmanager the block_manger to set up.
1881 public function setup_blocks($pagelayout, $blockmanager) {
1882 $layoutinfo = $this->layout_info_for_page($pagelayout);
1883 if (!empty($layoutinfo['regions'])) {
1884 $blockmanager->add_regions($layoutinfo['regions'], false);
1885 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1890 * Gets the visible name for the requested block region.
1892 * @param string $region The region name to get
1893 * @param string $theme The theme the region belongs to (may come from the parent theme)
1894 * @return string
1896 protected function get_region_name($region, $theme) {
1897 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1898 // A name exists in this theme, so use it
1899 if (substr($regionstring, 0, 1) != '[') {
1900 return $regionstring;
1903 // Otherwise, try to find one elsewhere
1904 // Check parents, if any
1905 foreach ($this->parents as $parentthemename) {
1906 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1907 if (substr($regionstring, 0, 1) != '[') {
1908 return $regionstring;
1912 // Last resort, try the base theme for names
1913 return get_string('region-' . $region, 'theme_base');
1917 * Get the list of all block regions known to this theme in all templates.
1919 * @return array internal region name => human readable name.
1921 public function get_all_block_regions() {
1922 $regions = array();
1923 foreach ($this->layouts as $layoutinfo) {
1924 foreach ($layoutinfo['regions'] as $region) {
1925 $regions[$region] = $this->get_region_name($region, $this->name);
1928 return $regions;
1932 * Returns the human readable name of the theme
1934 * @return string
1936 public function get_theme_name() {
1937 return get_string('pluginname', 'theme_'.$this->name);
1941 * Returns the block render method.
1943 * It is set by the theme via:
1944 * $THEME->blockrendermethod = '...';
1946 * It can be one of two values, blocks or blocks_for_region.
1947 * It should be set to the method being used by the theme layouts.
1949 * @return string
1951 public function get_block_render_method() {
1952 if ($this->blockrendermethod) {
1953 // Return the specified block render method.
1954 return $this->blockrendermethod;
1956 // Its not explicitly set, check the parent theme configs.
1957 foreach ($this->parent_configs as $config) {
1958 if (isset($config->blockrendermethod)) {
1959 return $config->blockrendermethod;
1962 // Default it to blocks.
1963 return 'blocks';
1968 * This class keeps track of which HTML tags are currently open.
1970 * This makes it much easier to always generate well formed XHTML output, even
1971 * if execution terminates abruptly. Any time you output some opening HTML
1972 * without the matching closing HTML, you should push the necessary close tags
1973 * onto the stack.
1975 * @copyright 2009 Tim Hunt
1976 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1977 * @since Moodle 2.0
1978 * @package core
1979 * @category output
1981 class xhtml_container_stack {
1984 * @var array Stores the list of open containers.
1986 protected $opencontainers = array();
1989 * @var array In developer debug mode, stores a stack trace of all opens and
1990 * closes, so we can output helpful error messages when there is a mismatch.
1992 protected $log = array();
1995 * @var boolean Store whether we are developer debug mode. We need this in
1996 * several places including in the destructor where we may not have access to $CFG.
1998 protected $isdebugging;
2001 * Constructor
2003 public function __construct() {
2004 global $CFG;
2005 $this->isdebugging = $CFG->debugdeveloper;
2009 * Push the close HTML for a recently opened container onto the stack.
2011 * @param string $type The type of container. This is checked when {@link pop()}
2012 * is called and must match, otherwise a developer debug warning is output.
2013 * @param string $closehtml The HTML required to close the container.
2015 public function push($type, $closehtml) {
2016 $container = new stdClass;
2017 $container->type = $type;
2018 $container->closehtml = $closehtml;
2019 if ($this->isdebugging) {
2020 $this->log('Open', $type);
2022 array_push($this->opencontainers, $container);
2026 * Pop the HTML for the next closing container from the stack. The $type
2027 * must match the type passed when the container was opened, otherwise a
2028 * warning will be output.
2030 * @param string $type The type of container.
2031 * @return string the HTML required to close the container.
2033 public function pop($type) {
2034 if (empty($this->opencontainers)) {
2035 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2036 $this->output_log(), DEBUG_DEVELOPER);
2037 return;
2040 $container = array_pop($this->opencontainers);
2041 if ($container->type != $type) {
2042 debugging('<p>The type of container to be closed (' . $container->type .
2043 ') does not match the type of the next open container (' . $type .
2044 '). This suggests there is a nesting problem.</p>' .
2045 $this->output_log(), DEBUG_DEVELOPER);
2047 if ($this->isdebugging) {
2048 $this->log('Close', $type);
2050 return $container->closehtml;
2054 * Close all but the last open container. This is useful in places like error
2055 * handling, where you want to close all the open containers (apart from <body>)
2056 * before outputting the error message.
2058 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2059 * developer debug warning if it isn't.
2060 * @return string the HTML required to close any open containers inside <body>.
2062 public function pop_all_but_last($shouldbenone = false) {
2063 if ($shouldbenone && count($this->opencontainers) != 1) {
2064 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2065 $this->output_log(), DEBUG_DEVELOPER);
2067 $output = '';
2068 while (count($this->opencontainers) > 1) {
2069 $container = array_pop($this->opencontainers);
2070 $output .= $container->closehtml;
2072 return $output;
2076 * You can call this function if you want to throw away an instance of this
2077 * class without properly emptying the stack (for example, in a unit test).
2078 * Calling this method stops the destruct method from outputting a developer
2079 * debug warning. After calling this method, the instance can no longer be used.
2081 public function discard() {
2082 $this->opencontainers = null;
2086 * Adds an entry to the log.
2088 * @param string $action The name of the action
2089 * @param string $type The type of action
2091 protected function log($action, $type) {
2092 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
2093 format_backtrace(debug_backtrace()) . '</li>';
2097 * Outputs the log's contents as a HTML list.
2099 * @return string HTML list of the log
2101 protected function output_log() {
2102 return '<ul>' . implode("\n", $this->log) . '</ul>';