Merge branch 'MDL-38424_m23' of git://github.com/kordan/moodle into MOODLE_23_STABLE
[moodle.git] / lib / outputlib.php
blob8246b2c5fd89520c86205ba4c30dcd46722213cd
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;
47 require_once("$CFG->libdir/filelib.php");
49 $next = time();
50 if (isset($CFG->themerev) and $next <= $CFG->themerev and $CFG->themerev - $next < 60*60) {
51 // This resolves problems when reset is requested repeatedly within 1s,
52 // the < 1h condition prevents accidental switching to future dates
53 // because we might not recover from it.
54 $next = $CFG->themerev+1;
57 set_config('themerev', $next); // time is unique even when you reset/switch database
58 fulldelete("$CFG->cachedir/theme");
61 /**
62 * Enable or disable theme designer mode.
64 * @param bool $state
66 function theme_set_designer_mod($state) {
67 theme_reset_all_caches();
68 set_config('themedesignermode', (int)!empty($state));
71 /**
72 * Returns current theme revision number.
74 * @return int
76 function theme_get_revision() {
77 global $CFG;
79 if (empty($CFG->themedesignermode)) {
80 if (empty($CFG->themerev)) {
81 return -1;
82 } else {
83 return $CFG->themerev;
86 } else {
87 return -1;
92 /**
93 * This class represents the configuration variables of a Moodle theme.
95 * All the variables with access: public below (with a few exceptions that are marked)
96 * are the properties you can set in your themes config.php file.
98 * There are also some methods and protected variables that are part of the inner
99 * workings of Moodle's themes system. If you are just editing a themes config.php
100 * file, you can just ignore those, and the following information for developers.
102 * Normally, to create an instance of this class, you should use the
103 * {@link theme_config::load()} factory method to load a themes config.php file.
104 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
105 * will create one for you, accessible as $PAGE->theme.
107 * @copyright 2009 Tim Hunt
108 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
109 * @since Moodle 2.0
110 * @package core
111 * @category output
113 class theme_config {
116 * @var string Default theme, used when requested theme not found.
118 const DEFAULT_THEME = 'standard';
121 * @var array You can base your theme on other themes by linking to the other theme as
122 * parents. This lets you use the CSS and layouts from the other themes
123 * (see {@link theme_config::$layouts}).
124 * That makes it easy to create a new theme that is similar to another one
125 * but with a few changes. In this themes CSS you only need to override
126 * those rules you want to change.
128 public $parents;
131 * @var array The names of all the stylesheets from this theme that you would
132 * like included, in order. Give the names of the files without .css.
134 public $sheets = array();
137 * @var array The names of all the stylesheets from parents that should be excluded.
138 * true value may be used to specify all parents or all themes from one parent.
139 * If no value specified value from parent theme used.
141 public $parents_exclude_sheets = null;
144 * @var array List of plugin sheets to be excluded.
145 * If no value specified value from parent theme used.
147 public $plugins_exclude_sheets = null;
150 * @var array List of style sheets that are included in the text editor bodies.
151 * Sheets from parent themes are used automatically and can not be excluded.
153 public $editor_sheets = array();
156 * @var array The names of all the javascript files this theme that you would
157 * like included from head, in order. Give the names of the files without .js.
159 public $javascripts = array();
162 * @var array The names of all the javascript files this theme that you would
163 * like included from footer, in order. Give the names of the files without .js.
165 public $javascripts_footer = array();
168 * @var array The names of all the javascript files from parents that should
169 * be excluded. true value may be used to specify all parents or all themes
170 * from one parent.
171 * If no value specified value from parent theme used.
173 public $parents_exclude_javascripts = null;
176 * @var array Which file to use for each page layout.
178 * This is an array of arrays. The keys of the outer array are the different layouts.
179 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
180 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
181 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
182 * That file also has a good example of how to set this setting.
184 * For each layout, the value in the outer array is an array that describes
185 * how you want that type of page to look. For example
186 * <pre>
187 * $THEME->layouts = array(
188 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
189 * 'standard' => array(
190 * 'theme' = 'mytheme',
191 * 'file' => 'normal.php',
192 * 'regions' => array('side-pre', 'side-post'),
193 * 'defaultregion' => 'side-post'
194 * ),
195 * // The site home page.
196 * 'home' => array(
197 * 'theme' = 'mytheme',
198 * 'file' => 'home.php',
199 * 'regions' => array('side-pre', 'side-post'),
200 * 'defaultregion' => 'side-post'
201 * ),
202 * // ...
203 * );
204 * </pre>
206 * 'theme' name of the theme where is the layout located
207 * 'file' is the layout file to use for this type of page.
208 * layout files are stored in layout subfolder
209 * 'regions' This lists the regions on the page where blocks may appear. For
210 * each region you list here, your layout file must include a call to
211 * <pre>
212 * echo $OUTPUT->blocks_for_region($regionname);
213 * </pre>
214 * or equivalent so that the blocks are actually visible.
216 * 'defaultregion' If the list of regions is non-empty, then you must pick
217 * one of the one of them as 'default'. This has two meanings. First, this is
218 * where new blocks are added. Second, if there are any blocks associated with
219 * the page, but in non-existent regions, they appear here. (Imaging, for example,
220 * that someone added blocks using a different theme that used different region
221 * names, and then switched to this theme.)
223 public $layouts = array();
226 * @var string Name of the renderer factory class to use. Must implement the
227 * {@link renderer_factory} interface.
229 * This is an advanced feature. Moodle output is generated by 'renderers',
230 * you can customise the HTML that is output by writing custom renderers,
231 * and then you need to specify 'renderer factory' so that Moodle can find
232 * your renderers.
234 * There are some renderer factories supplied with Moodle. Please follow these
235 * links to see what they do.
236 * <ul>
237 * <li>{@link standard_renderer_factory} - the default.</li>
238 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
239 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
240 * </ul>
242 public $rendererfactory = 'standard_renderer_factory';
245 * @var string Function to do custom CSS post-processing.
247 * This is an advanced feature. If you want to do custom post-processing on the
248 * CSS before it is output (for example, to replace certain variable names
249 * with particular values) you can give the name of a function here.
251 public $csspostprocess = null;
254 * @var string Accessibility: Right arrow-like character is
255 * used in the breadcrumb trail, course navigation menu
256 * (previous/next activity), calendar, and search forum block.
257 * If the theme does not set characters, appropriate defaults
258 * are set automatically. Please DO NOT
259 * use &lt; &gt; &raquo; - these are confusing for blind users.
261 public $rarrow = null;
264 * @var string Accessibility: Right arrow-like character is
265 * used in the breadcrumb trail, course navigation menu
266 * (previous/next activity), calendar, and search forum block.
267 * If the theme does not set characters, appropriate defaults
268 * are set automatically. Please DO NOT
269 * use &lt; &gt; &raquo; - these are confusing for blind users.
271 public $larrow = null;
274 * @var bool Some themes may want to disable ajax course editing.
276 public $enablecourseajax = true;
278 //==Following properties are not configurable from theme config.php==
281 * @var string The name of this theme. Set automatically when this theme is
282 * loaded. This can not be set in theme config.php
284 public $name;
287 * @var string The folder where this themes files are stored. This is set
288 * automatically. This can not be set in theme config.php
290 public $dir;
293 * @var stdClass Theme settings stored in config_plugins table.
294 * This can not be set in theme config.php
296 public $setting = null;
299 * @var bool If set to true and the theme enables the dock then blocks will be able
300 * to be moved to the special dock
302 public $enable_dock = false;
305 * @var bool If set to true then this theme will not be shown in the theme selector unless
306 * theme designer mode is turned on.
308 public $hidefromselector = false;
311 * @var renderer_factory Instance of the renderer_factory implementation
312 * we are using. Implementation detail.
314 protected $rf = null;
317 * @var array List of parent config objects.
319 protected $parent_configs = array();
322 * @var bool If set to true then the theme is safe to run through the optimiser (if it is enabled)
323 * If set to false then we know either the theme has already been optimised and the CSS optimiser is not needed
324 * or the theme is not compatible with the CSS optimiser. In both cases even if enabled the CSS optimiser will not
325 * be used with this theme if set to false.
327 public $supportscssoptimisation = true;
330 * Load the config.php file for a particular theme, and return an instance
331 * of this class. (That is, this is a factory method.)
333 * @param string $themename the name of the theme.
334 * @return theme_config an instance of this class.
336 public static function load($themename) {
337 global $CFG;
339 // load theme settings from db
340 try {
341 $settings = get_config('theme_'.$themename);
342 } catch (dml_exception $e) {
343 // most probably moodle tables not created yet
344 $settings = new stdClass();
347 if ($config = theme_config::find_theme_config($themename, $settings)) {
348 return new theme_config($config);
350 } else if ($themename == theme_config::DEFAULT_THEME) {
351 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
353 } else {
354 // bad luck, the requested theme has some problems - admin see details in theme config
355 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
360 * Theme diagnostic code. It is very problematic to send debug output
361 * to the actual CSS file, instead this functions is supposed to
362 * diagnose given theme and highlights all potential problems.
363 * This information should be available from the theme selection page
364 * or some other debug page for theme designers.
366 * @param string $themename
367 * @return array description of problems
369 public static function diagnose($themename) {
370 //TODO: MDL-21108
371 return array();
375 * Private constructor, can be called only from the factory method.
376 * @param stdClass $config
378 private function __construct($config) {
379 global $CFG; //needed for included lib.php files
381 $this->settings = $config->settings;
382 $this->name = $config->name;
383 $this->dir = $config->dir;
385 if ($this->name != 'base') {
386 $baseconfig = theme_config::find_theme_config('base', $this->settings);
387 } else {
388 $baseconfig = $config;
391 $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer',
392 'parents_exclude_javascripts', 'layouts', 'enable_dock', 'enablecourseajax', 'supportscssoptimisation',
393 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector');
395 foreach ($config as $key=>$value) {
396 if (in_array($key, $configurable)) {
397 $this->$key = $value;
401 // verify all parents and load configs and renderers
402 foreach ($this->parents as $parent) {
403 if ($parent == 'base') {
404 $parent_config = $baseconfig;
405 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
406 // this is not good - better exclude faulty parents
407 continue;
409 $libfile = $parent_config->dir.'/lib.php';
410 if (is_readable($libfile)) {
411 // theme may store various function here
412 include_once($libfile);
414 $renderersfile = $parent_config->dir.'/renderers.php';
415 if (is_readable($renderersfile)) {
416 // may contain core and plugin renderers and renderer factory
417 include_once($renderersfile);
419 $this->parent_configs[$parent] = $parent_config;
420 $rendererfile = $parent_config->dir.'/renderers.php';
421 if (is_readable($rendererfile)) {
422 // may contain core and plugin renderers and renderer factory
423 include_once($rendererfile);
426 $libfile = $this->dir.'/lib.php';
427 if (is_readable($libfile)) {
428 // theme may store various function here
429 include_once($libfile);
431 $rendererfile = $this->dir.'/renderers.php';
432 if (is_readable($rendererfile)) {
433 // may contain core and plugin renderers and renderer factory
434 include_once($rendererfile);
435 } else {
436 // check if renderers.php file is missnamed renderer.php
437 if (is_readable($this->dir.'/renderer.php')) {
438 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
439 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
443 // cascade all layouts properly
444 foreach ($baseconfig->layouts as $layout=>$value) {
445 if (!isset($this->layouts[$layout])) {
446 foreach ($this->parent_configs as $parent_config) {
447 if (isset($parent_config->layouts[$layout])) {
448 $this->layouts[$layout] = $parent_config->layouts[$layout];
449 continue 2;
452 $this->layouts[$layout] = $value;
456 //fix arrows if needed
457 $this->check_theme_arrows();
461 * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
462 * If not it applies sensible defaults.
464 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
465 * search forum block, etc. Important: these are 'silent' in a screen-reader
466 * (unlike &gt; &raquo;), and must be accompanied by text.
468 private function check_theme_arrows() {
469 if (!isset($this->rarrow) and !isset($this->larrow)) {
470 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
471 // Also OK in Win 9x/2K/IE 5.x
472 $this->rarrow = '&#x25BA;';
473 $this->larrow = '&#x25C4;';
474 if (empty($_SERVER['HTTP_USER_AGENT'])) {
475 $uagent = '';
476 } else {
477 $uagent = $_SERVER['HTTP_USER_AGENT'];
479 if (false !== strpos($uagent, 'Opera')
480 || false !== strpos($uagent, 'Mac')) {
481 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
482 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
483 $this->rarrow = '&#x25B6;';
484 $this->larrow = '&#x25C0;';
486 elseif (false !== strpos($uagent, 'Konqueror')) {
487 $this->rarrow = '&rarr;';
488 $this->larrow = '&larr;';
490 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
491 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
492 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
493 // To be safe, non-Unicode browsers!
494 $this->rarrow = '&gt;';
495 $this->larrow = '&lt;';
498 // RTL support - in RTL languages, swap r and l arrows
499 if (right_to_left()) {
500 $t = $this->rarrow;
501 $this->rarrow = $this->larrow;
502 $this->larrow = $t;
508 * Returns output renderer prefixes, these are used when looking
509 * for the overridden renderers in themes.
511 * @return array
513 public function renderer_prefixes() {
514 global $CFG; // just in case the included files need it
516 $prefixes = array('theme_'.$this->name);
518 foreach ($this->parent_configs as $parent) {
519 $prefixes[] = 'theme_'.$parent->name;
522 return $prefixes;
526 * Returns the stylesheet URL of this editor content
528 * @param bool $encoded false means use & and true use &amp; in URLs
529 * @return string
531 public function editor_css_url($encoded=true) {
532 global $CFG;
534 $rev = theme_get_revision();
536 if ($rev > -1) {
537 if (!empty($CFG->slasharguments)) {
538 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
539 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
540 return $url;
541 } else {
542 $params = array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor');
543 return new moodle_url($CFG->httpswwwroot.'/theme/styles.php', $params);
545 } else {
546 $params = array('theme'=>$this->name, 'type'=>'editor');
547 return new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
552 * Returns the content of the CSS to be used in editor content
554 * @return string
556 public function editor_css_files() {
557 global $CFG;
559 $files = array();
561 // first editor plugins
562 $plugins = get_plugin_list('editor');
563 foreach ($plugins as $plugin=>$fulldir) {
564 $sheetfile = "$fulldir/editor_styles.css";
565 if (is_readable($sheetfile)) {
566 $files['plugin_'.$plugin] = $sheetfile;
569 // then parent themes
570 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
571 if (empty($parent_config->editor_sheets)) {
572 continue;
574 foreach ($parent_config->editor_sheets as $sheet) {
575 $sheetfile = "$parent_config->dir/style/$sheet.css";
576 if (is_readable($sheetfile)) {
577 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
581 // finally this theme
582 if (!empty($this->editor_sheets)) {
583 foreach ($this->editor_sheets as $sheet) {
584 $sheetfile = "$this->dir/style/$sheet.css";
585 if (is_readable($sheetfile)) {
586 $files['theme_'.$sheet] = $sheetfile;
591 return $files;
595 * Get the stylesheet URL of this theme
597 * @param moodle_page $page Not used... deprecated?
598 * @return array of moodle_url
600 public function css_urls(moodle_page $page) {
601 global $CFG;
603 $rev = theme_get_revision();
605 $urls = array();
607 if ($rev > -1) {
608 if (check_browser_version('MSIE', 5)) {
609 // We need to split the CSS files for IE
610 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'plugins'));
611 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'parents'));
612 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'theme'));
613 } else {
614 if (!empty($CFG->slasharguments)) {
615 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
616 $url->set_slashargument('/'.$this->name.'/'.$rev.'/all', 'noparam', true);
617 $urls[] = $url;
618 } else {
619 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'all'));
622 } else {
623 // find out the current CSS and cache it now for 5 seconds
624 // the point is to construct the CSS only once and pass it through the
625 // dataroot to the script that actually serves the sheets
626 if (!defined('THEME_DESIGNER_CACHE_LIFETIME')) {
627 define('THEME_DESIGNER_CACHE_LIFETIME', 4); // this can be also set in config.php
629 // Prepare the CSS optimiser if it is to be used
630 $optimiser = null;
631 $candidatesheet = "$CFG->cachedir/theme/$this->name/designer.ser";
632 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
633 require_once($CFG->dirroot.'/lib/csslib.php');
634 $optimiser = new css_optimiser;
636 if (!file_exists($candidatesheet)) {
637 $css = $this->css_content($optimiser);
638 check_dir_exists(dirname($candidatesheet));
639 file_put_contents($candidatesheet, serialize($css));
641 } else if (filemtime($candidatesheet) > time() - THEME_DESIGNER_CACHE_LIFETIME) {
642 if ($css = file_get_contents($candidatesheet)) {
643 $css = unserialize($css);
644 } else {
645 unlink($candidatesheet);
646 $css = $this->css_content($optimiser);
649 } else {
650 unlink($candidatesheet);
651 $css = $this->css_content($optimiser);
652 file_put_contents($candidatesheet, serialize($css));
655 $baseurl = $CFG->httpswwwroot.'/theme/styles_debug.php';
657 if (check_browser_version('MSIE', 5)) {
658 // lalala, IE does not allow more than 31 linked CSS files from main document
659 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
660 foreach ($css['parents'] as $parent=>$sheets) {
661 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096)
662 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
664 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
666 } else {
667 foreach ($css['plugins'] as $plugin=>$unused) {
668 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
670 foreach ($css['parents'] as $parent=>$sheets) {
671 foreach ($sheets as $sheet=>$unused2) {
672 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
675 foreach ($css['theme'] as $sheet=>$unused) {
676 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); // sheet first in order to make long urls easier to read
681 return $urls;
685 * Returns an array of organised CSS files required for this output
687 * @return array
689 public function css_files() {
690 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
692 // get all plugin sheets
693 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
694 if ($excludes !== true) {
695 foreach (get_plugin_types() as $type=>$unused) {
696 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
697 continue;
699 $plugins = get_plugin_list($type);
700 foreach ($plugins as $plugin=>$fulldir) {
701 if (!empty($excludes[$type]) and is_array($excludes[$type])
702 and in_array($plugin, $excludes[$type])) {
703 continue;
706 $plugincontent = '';
707 $sheetfile = "$fulldir/styles.css";
708 if (is_readable($sheetfile)) {
709 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
711 $sheetthemefile = "$fulldir/styles_{$this->name}.css";
712 if (is_readable($sheetthemefile)) {
713 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$this->name] = $sheetthemefile;
719 // find out wanted parent sheets
720 $excludes = $this->resolve_excludes('parents_exclude_sheets');
721 if ($excludes !== true) {
722 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
723 $parent = $parent_config->name;
724 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
725 continue;
727 foreach ($parent_config->sheets as $sheet) {
728 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
729 and in_array($sheet, $excludes[$parent])) {
730 continue;
732 $sheetfile = "$parent_config->dir/style/$sheet.css";
733 if (is_readable($sheetfile)) {
734 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
740 // current theme sheets
741 if (is_array($this->sheets)) {
742 foreach ($this->sheets as $sheet) {
743 $sheetfile = "$this->dir/style/$sheet.css";
744 if (is_readable($sheetfile)) {
745 $cssfiles['theme'][$sheet] = $sheetfile;
750 return $cssfiles;
754 * Returns the content of the one huge CSS merged from all style sheets.
756 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
757 * @return string
759 public function css_content(css_optimiser $optimiser = null) {
760 $files = array_merge($this->css_files(), array('editor'=>$this->editor_css_files()));
761 $css = $this->css_files_get_contents($files, array(), $optimiser);
762 return $css;
766 * Given an array of file paths or a single file path loads the contents of
767 * the CSS file, processes it then returns it in the same structure it was given.
769 * Can be used recursively on the results of {@link css_files}
771 * @param array|string $file An array of file paths or a single file path
772 * @param array $keys An array of previous array keys [recursive addition]
773 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
774 * @return The converted array or the contents of the single file ($file type)
776 protected function css_files_get_contents($file, array $keys, css_optimiser $optimiser = null) {
777 global $CFG;
778 if (is_array($file)) {
779 // We use a separate array to keep everything in the exact same order.
780 $return = array();
781 foreach ($file as $key=>$f) {
782 $return[clean_param($key, PARAM_SAFEDIR)] = $this->css_files_get_contents($f, array_merge($keys, array($key)), $optimiser);
784 return $return;
785 } else {
786 $contents = file_get_contents($file);
787 $contents = $this->post_process($contents);
788 $comment = '/** Path: '.implode(' ', $keys).' **/'."\n";
789 $stats = '';
790 if (!is_null($optimiser)) {
791 $contents = $optimiser->process($contents);
792 if (!empty($CFG->cssoptimiserstats)) {
793 $stats = $optimiser->output_stats_css();
796 return $comment.$stats.$contents;
802 * Generate a URL to the file that serves theme JavaScript files.
804 * @param bool $inhead true means head url, false means footer
805 * @return moodle_url
807 public function javascript_url($inhead) {
808 global $CFG;
810 $rev = theme_get_revision();
811 $params = array('theme'=>$this->name,'rev'=>$rev);
812 $params['type'] = $inhead ? 'head' : 'footer';
814 if (!empty($CFG->slasharguments) and $rev > 0) {
815 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
816 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
817 return $url;
818 } else {
819 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
824 * Get the URL's for the JavaScript files used by this theme.
825 * They won't be served directly, instead they'll be mediated through
826 * theme/javascript.php.
828 * @param string $type Either javascripts_footer, or javascripts
829 * @return array
831 public function javascript_files($type) {
832 if ($type === 'footer') {
833 $type = 'javascripts_footer';
834 } else {
835 $type = 'javascripts';
838 $js = array();
839 // find out wanted parent javascripts
840 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
841 if ($excludes !== true) {
842 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
843 $parent = $parent_config->name;
844 if (empty($parent_config->$type)) {
845 continue;
847 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
848 continue;
850 foreach ($parent_config->$type as $javascript) {
851 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
852 and in_array($javascript, $excludes[$parent])) {
853 continue;
855 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
856 if (is_readable($javascriptfile)) {
857 $js[] = $javascriptfile;
863 // current theme javascripts
864 if (is_array($this->$type)) {
865 foreach ($this->$type as $javascript) {
866 $javascriptfile = "$this->dir/javascript/$javascript.js";
867 if (is_readable($javascriptfile)) {
868 $js[] = $javascriptfile;
872 return $js;
876 * Resolves an exclude setting to the themes setting is applicable or the
877 * setting of its closest parent.
879 * @param string $variable The name of the setting the exclude setting to resolve
880 * @param string $default
881 * @return mixed
883 protected function resolve_excludes($variable, $default = null) {
884 $setting = $default;
885 if (is_array($this->{$variable}) or $this->{$variable} === true) {
886 $setting = $this->{$variable};
887 } else {
888 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
889 if (!isset($parent_config->{$variable})) {
890 continue;
892 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
893 $setting = $parent_config->{$variable};
894 break;
898 return $setting;
902 * Returns the content of the one huge javascript file merged from all theme javascript files.
904 * @param bool $type
905 * @return string
907 public function javascript_content($type) {
908 $jsfiles = $this->javascript_files($type);
909 $js = '';
910 foreach ($jsfiles as $jsfile) {
911 $js .= file_get_contents($jsfile)."\n";
913 return $js;
917 * Post processes CSS.
919 * This method post processes all of the CSS before it is served for this theme.
920 * This is done so that things such as image URL's can be swapped in and to
921 * run any specific CSS post process method the theme has requested.
922 * This allows themes to use CSS settings.
924 * @param string $css The CSS to process.
925 * @return string The processed CSS.
927 public function post_process($css) {
928 // now resolve all image locations
929 if (preg_match_all('/\[\[pix:([a-z_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
930 $replaced = array();
931 foreach ($matches as $match) {
932 if (isset($replaced[$match[0]])) {
933 continue;
935 $replaced[$match[0]] = true;
936 $imagename = $match[2];
937 $component = rtrim($match[1], '|');
938 $imageurl = $this->pix_url($imagename, $component)->out(false);
939 // we do not need full url because the image.php is always in the same dir
940 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
941 $css = str_replace($match[0], $imageurl, $css);
945 // now resolve all theme settings or do any other postprocessing
946 $csspostprocess = $this->csspostprocess;
947 if (function_exists($csspostprocess)) {
948 $css = $csspostprocess($css, $this);
951 return $css;
955 * Return the URL for an image
957 * @param string $imagename the name of the icon.
958 * @param string $component specification of one plugin like in get_string()
959 * @return moodle_url
961 public function pix_url($imagename, $component) {
962 global $CFG;
964 $params = array('theme'=>$this->name);
966 if (empty($component) or $component === 'moodle' or $component === 'core') {
967 $params['component'] = 'core';
968 } else {
969 $params['component'] = $component;
972 $rev = theme_get_revision();
973 if ($rev != -1) {
974 $params['rev'] = $rev;
977 $params['image'] = $imagename;
979 if (!empty($CFG->slasharguments) and $rev > 0) {
980 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
981 $url->set_slashargument('/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'], 'noparam', true);
982 } else {
983 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php", $params);
986 return $url;
990 * Resolves the real image location.
991 * @param string $image name of image, may contain relative path
992 * @param string $component
993 * @return string full file path
995 public function resolve_image_location($image, $component) {
996 global $CFG;
998 if ($component === 'moodle' or $component === 'core' or empty($component)) {
999 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image")) {
1000 return $imagefile;
1002 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1003 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image")) {
1004 return $imagefile;
1007 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image")) {
1008 return $imagefile;
1010 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image")) {
1011 return $imagefile;
1013 return null;
1015 } else if ($component === 'theme') { //exception
1016 if ($image === 'favicon') {
1017 return "$this->dir/pix/favicon.ico";
1019 if ($imagefile = $this->image_exists("$this->dir/pix/$image")) {
1020 return $imagefile;
1022 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1023 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image")) {
1024 return $imagefile;
1027 return null;
1029 } else {
1030 if (strpos($component, '_') === false) {
1031 $component = 'mod_'.$component;
1033 list($type, $plugin) = explode('_', $component, 2);
1035 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image")) {
1036 return $imagefile;
1038 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1039 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image")) {
1040 return $imagefile;
1043 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image")) {
1044 return $imagefile;
1046 $dir = get_plugin_directory($type, $plugin);
1047 if ($imagefile = $this->image_exists("$dir/pix/$image")) {
1048 return $imagefile;
1050 return null;
1055 * Checks if file with any image extension exists.
1057 * @param string $filepath
1058 * @return string image name with extension
1060 private static function image_exists($filepath) {
1061 if (file_exists("$filepath.gif")) {
1062 return "$filepath.gif";
1063 } else if (file_exists("$filepath.png")) {
1064 return "$filepath.png";
1065 } else if (file_exists("$filepath.jpg")) {
1066 return "$filepath.jpg";
1067 } else if (file_exists("$filepath.jpeg")) {
1068 return "$filepath.jpeg";
1069 } else {
1070 return false;
1075 * Loads the theme config from config.php file.
1077 * @param string $themename
1078 * @param stdClass $settings from config_plugins table
1079 * @return stdClass The theme configuration
1081 private static function find_theme_config($themename, $settings) {
1082 // We have to use the variable name $THEME (upper case) because that
1083 // is what is used in theme config.php files.
1085 if (!$dir = theme_config::find_theme_location($themename)) {
1086 return null;
1089 $THEME = new stdClass();
1090 $THEME->name = $themename;
1091 $THEME->dir = $dir;
1092 $THEME->settings = $settings;
1094 global $CFG; // just in case somebody tries to use $CFG in theme config
1095 include("$THEME->dir/config.php");
1097 // verify the theme configuration is OK
1098 if (!is_array($THEME->parents)) {
1099 // parents option is mandatory now
1100 return null;
1103 return $THEME;
1107 * Finds the theme location and verifies the theme has all needed files
1108 * and is not obsoleted.
1110 * @param string $themename
1111 * @return string full dir path or null if not found
1113 private static function find_theme_location($themename) {
1114 global $CFG;
1116 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1117 $dir = "$CFG->dirroot/theme/$themename";
1119 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1120 $dir = "$CFG->themedir/$themename";
1122 } else {
1123 return null;
1126 if (file_exists("$dir/styles.php")) {
1127 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1128 return null;
1131 return $dir;
1135 * Get the renderer for a part of Moodle for this theme.
1137 * @param moodle_page $page the page we are rendering
1138 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1139 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1140 * @param string $target one of rendering target constants
1141 * @return renderer_base the requested renderer.
1143 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1144 if (is_null($this->rf)) {
1145 $classname = $this->rendererfactory;
1146 $this->rf = new $classname($this);
1149 return $this->rf->get_renderer($page, $component, $subtype, $target);
1153 * Get the information from {@link $layouts} for this type of page.
1155 * @param string $pagelayout the the page layout name.
1156 * @return array the appropriate part of {@link $layouts}.
1158 protected function layout_info_for_page($pagelayout) {
1159 if (array_key_exists($pagelayout, $this->layouts)) {
1160 return $this->layouts[$pagelayout];
1161 } else {
1162 debugging('Invalid page layout specified: ' . $pagelayout);
1163 return $this->layouts['standard'];
1168 * Given the settings of this theme, and the page pagelayout, return the
1169 * full path of the page layout file to use.
1171 * Used by {@link core_renderer::header()}.
1173 * @param string $pagelayout the the page layout name.
1174 * @return string Full path to the lyout file to use
1176 public function layout_file($pagelayout) {
1177 global $CFG;
1179 $layoutinfo = $this->layout_info_for_page($pagelayout);
1180 $layoutfile = $layoutinfo['file'];
1182 if (array_key_exists('theme', $layoutinfo)) {
1183 $themes = array($layoutinfo['theme']);
1184 } else {
1185 $themes = array_merge(array($this->name),$this->parents);
1188 foreach ($themes as $theme) {
1189 if ($dir = $this->find_theme_location($theme)) {
1190 $path = "$dir/layout/$layoutfile";
1192 // Check the template exists, return general base theme template if not.
1193 if (is_readable($path)) {
1194 return $path;
1199 debugging('Can not find layout file for: ' . $pagelayout);
1200 // fallback to standard normal layout
1201 return "$CFG->dirroot/theme/base/layout/general.php";
1205 * Returns auxiliary page layout options specified in layout configuration array.
1207 * @param string $pagelayout
1208 * @return array
1210 public function pagelayout_options($pagelayout) {
1211 $info = $this->layout_info_for_page($pagelayout);
1212 if (!empty($info['options'])) {
1213 return $info['options'];
1215 return array();
1219 * Inform a block_manager about the block regions this theme wants on this
1220 * page layout.
1222 * @param string $pagelayout the general type of the page.
1223 * @param block_manager $blockmanager the block_manger to set up.
1225 public function setup_blocks($pagelayout, $blockmanager) {
1226 $layoutinfo = $this->layout_info_for_page($pagelayout);
1227 if (!empty($layoutinfo['regions'])) {
1228 $blockmanager->add_regions($layoutinfo['regions']);
1229 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1234 * Gets the visible name for the requested block region.
1236 * @param string $region The region name to get
1237 * @param string $theme The theme the region belongs to (may come from the parent theme)
1238 * @return string
1240 protected function get_region_name($region, $theme) {
1241 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1242 // A name exists in this theme, so use it
1243 if (substr($regionstring, 0, 1) != '[') {
1244 return $regionstring;
1247 // Otherwise, try to find one elsewhere
1248 // Check parents, if any
1249 foreach ($this->parents as $parentthemename) {
1250 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1251 if (substr($regionstring, 0, 1) != '[') {
1252 return $regionstring;
1256 // Last resort, try the base theme for names
1257 return get_string('region-' . $region, 'theme_base');
1261 * Get the list of all block regions known to this theme in all templates.
1263 * @return array internal region name => human readable name.
1265 public function get_all_block_regions() {
1266 $regions = array();
1267 foreach ($this->layouts as $layoutinfo) {
1268 foreach ($layoutinfo['regions'] as $region) {
1269 $regions[$region] = $this->get_region_name($region, $this->name);
1272 return $regions;
1276 * Returns the human readable name of the theme
1278 * @return string
1280 public function get_theme_name() {
1281 return get_string('pluginname', 'theme_'.$this->name);
1286 * This class keeps track of which HTML tags are currently open.
1288 * This makes it much easier to always generate well formed XHTML output, even
1289 * if execution terminates abruptly. Any time you output some opening HTML
1290 * without the matching closing HTML, you should push the necessary close tags
1291 * onto the stack.
1293 * @copyright 2009 Tim Hunt
1294 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1295 * @since Moodle 2.0
1296 * @package core
1297 * @category output
1299 class xhtml_container_stack {
1302 * @var array Stores the list of open containers.
1304 protected $opencontainers = array();
1307 * @var array In developer debug mode, stores a stack trace of all opens and
1308 * closes, so we can output helpful error messages when there is a mismatch.
1310 protected $log = array();
1313 * @var boolean Store whether we are developer debug mode. We need this in
1314 * several places including in the destructor where we may not have access to $CFG.
1316 protected $isdebugging;
1319 * Constructor
1321 public function __construct() {
1322 $this->isdebugging = debugging('', DEBUG_DEVELOPER);
1326 * Push the close HTML for a recently opened container onto the stack.
1328 * @param string $type The type of container. This is checked when {@link pop()}
1329 * is called and must match, otherwise a developer debug warning is output.
1330 * @param string $closehtml The HTML required to close the container.
1332 public function push($type, $closehtml) {
1333 $container = new stdClass;
1334 $container->type = $type;
1335 $container->closehtml = $closehtml;
1336 if ($this->isdebugging) {
1337 $this->log('Open', $type);
1339 array_push($this->opencontainers, $container);
1343 * Pop the HTML for the next closing container from the stack. The $type
1344 * must match the type passed when the container was opened, otherwise a
1345 * warning will be output.
1347 * @param string $type The type of container.
1348 * @return string the HTML required to close the container.
1350 public function pop($type) {
1351 if (empty($this->opencontainers)) {
1352 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1353 $this->output_log(), DEBUG_DEVELOPER);
1354 return;
1357 $container = array_pop($this->opencontainers);
1358 if ($container->type != $type) {
1359 debugging('<p>The type of container to be closed (' . $container->type .
1360 ') does not match the type of the next open container (' . $type .
1361 '). This suggests there is a nesting problem.</p>' .
1362 $this->output_log(), DEBUG_DEVELOPER);
1364 if ($this->isdebugging) {
1365 $this->log('Close', $type);
1367 return $container->closehtml;
1371 * Close all but the last open container. This is useful in places like error
1372 * handling, where you want to close all the open containers (apart from <body>)
1373 * before outputting the error message.
1375 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1376 * developer debug warning if it isn't.
1377 * @return string the HTML required to close any open containers inside <body>.
1379 public function pop_all_but_last($shouldbenone = false) {
1380 if ($shouldbenone && count($this->opencontainers) != 1) {
1381 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1382 $this->output_log(), DEBUG_DEVELOPER);
1384 $output = '';
1385 while (count($this->opencontainers) > 1) {
1386 $container = array_pop($this->opencontainers);
1387 $output .= $container->closehtml;
1389 return $output;
1393 * You can call this function if you want to throw away an instance of this
1394 * class without properly emptying the stack (for example, in a unit test).
1395 * Calling this method stops the destruct method from outputting a developer
1396 * debug warning. After calling this method, the instance can no longer be used.
1398 public function discard() {
1399 $this->opencontainers = null;
1403 * Adds an entry to the log.
1405 * @param string $action The name of the action
1406 * @param string $type The type of action
1408 protected function log($action, $type) {
1409 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1410 format_backtrace(debug_backtrace()) . '</li>';
1414 * Outputs the log's contents as a HTML list.
1416 * @return string HTML list of the log
1418 protected function output_log() {
1419 return '<ul>' . implode("\n", $this->log) . '</ul>';