Merge branch 'MDL-37523_M23' of git://github.com/lazydaisy/moodle into MOODLE_23_STABLE
[moodle.git] / lib / outputlib.php
blob7d963f30198ffe6e058f8a35c2cbfd451e7868cf
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 foreach ($file as $key=>$f) {
780 $file[$key] = $this->css_files_get_contents($f, array_merge($keys, array($key)), $optimiser);
782 return $file;
783 } else {
784 $contents = file_get_contents($file);
785 $contents = $this->post_process($contents);
786 $comment = '/** Path: '.implode(' ', $keys).' **/'."\n";
787 $stats = '';
788 if (!is_null($optimiser)) {
789 $contents = $optimiser->process($contents);
790 if (!empty($CFG->cssoptimiserstats)) {
791 $stats = $optimiser->output_stats_css();
794 return $comment.$stats.$contents;
800 * Generate a URL to the file that serves theme JavaScript files.
802 * @param bool $inhead true means head url, false means footer
803 * @return moodle_url
805 public function javascript_url($inhead) {
806 global $CFG;
808 $rev = theme_get_revision();
809 $params = array('theme'=>$this->name,'rev'=>$rev);
810 $params['type'] = $inhead ? 'head' : 'footer';
812 if (!empty($CFG->slasharguments) and $rev > 0) {
813 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
814 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
815 return $url;
816 } else {
817 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
822 * Get the URL's for the JavaScript files used by this theme.
823 * They won't be served directly, instead they'll be mediated through
824 * theme/javascript.php.
826 * @param string $type Either javascripts_footer, or javascripts
827 * @return array
829 public function javascript_files($type) {
830 if ($type === 'footer') {
831 $type = 'javascripts_footer';
832 } else {
833 $type = 'javascripts';
836 $js = array();
837 // find out wanted parent javascripts
838 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
839 if ($excludes !== true) {
840 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
841 $parent = $parent_config->name;
842 if (empty($parent_config->$type)) {
843 continue;
845 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
846 continue;
848 foreach ($parent_config->$type as $javascript) {
849 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
850 and in_array($javascript, $excludes[$parent])) {
851 continue;
853 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
854 if (is_readable($javascriptfile)) {
855 $js[] = $javascriptfile;
861 // current theme javascripts
862 if (is_array($this->$type)) {
863 foreach ($this->$type as $javascript) {
864 $javascriptfile = "$this->dir/javascript/$javascript.js";
865 if (is_readable($javascriptfile)) {
866 $js[] = $javascriptfile;
871 return $js;
875 * Resolves an exclude setting to the themes setting is applicable or the
876 * setting of its closest parent.
878 * @param string $variable The name of the setting the exclude setting to resolve
879 * @param string $default
880 * @return mixed
882 protected function resolve_excludes($variable, $default = null) {
883 $setting = $default;
884 if (is_array($this->{$variable}) or $this->{$variable} === true) {
885 $setting = $this->{$variable};
886 } else {
887 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
888 if (!isset($parent_config->{$variable})) {
889 continue;
891 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
892 $setting = $parent_config->{$variable};
893 break;
897 return $setting;
901 * Returns the content of the one huge javascript file merged from all theme javascript files.
903 * @param bool $type
904 * @return string
906 public function javascript_content($type) {
907 $jsfiles = $this->javascript_files($type);
908 $js = '';
909 foreach ($jsfiles as $jsfile) {
910 $js .= file_get_contents($jsfile)."\n";
912 return $js;
916 * Post processes CSS.
918 * This method post processes all of the CSS before it is served for this theme.
919 * This is done so that things such as image URL's can be swapped in and to
920 * run any specific CSS post process method the theme has requested.
921 * This allows themes to use CSS settings.
923 * @param string $css The CSS to process.
924 * @return string The processed CSS.
926 public function post_process($css) {
927 // now resolve all image locations
928 if (preg_match_all('/\[\[pix:([a-z_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
929 $replaced = array();
930 foreach ($matches as $match) {
931 if (isset($replaced[$match[0]])) {
932 continue;
934 $replaced[$match[0]] = true;
935 $imagename = $match[2];
936 $component = rtrim($match[1], '|');
937 $imageurl = $this->pix_url($imagename, $component)->out(false);
938 // we do not need full url because the image.php is always in the same dir
939 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
940 $css = str_replace($match[0], $imageurl, $css);
944 // now resolve all theme settings or do any other postprocessing
945 $csspostprocess = $this->csspostprocess;
946 if (function_exists($csspostprocess)) {
947 $css = $csspostprocess($css, $this);
950 return $css;
954 * Return the URL for an image
956 * @param string $imagename the name of the icon.
957 * @param string $component specification of one plugin like in get_string()
958 * @return moodle_url
960 public function pix_url($imagename, $component) {
961 global $CFG;
963 $params = array('theme'=>$this->name);
965 if (empty($component) or $component === 'moodle' or $component === 'core') {
966 $params['component'] = 'core';
967 } else {
968 $params['component'] = $component;
971 $rev = theme_get_revision();
972 if ($rev != -1) {
973 $params['rev'] = $rev;
976 $params['image'] = $imagename;
978 if (!empty($CFG->slasharguments) and $rev > 0) {
979 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
980 $url->set_slashargument('/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'], 'noparam', true);
981 } else {
982 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php", $params);
985 return $url;
989 * Resolves the real image location.
990 * @param string $image name of image, may contain relative path
991 * @param string $component
992 * @return string full file path
994 public function resolve_image_location($image, $component) {
995 global $CFG;
997 if ($component === 'moodle' or $component === 'core' or empty($component)) {
998 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image")) {
999 return $imagefile;
1001 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1002 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image")) {
1003 return $imagefile;
1006 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image")) {
1007 return $imagefile;
1009 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image")) {
1010 return $imagefile;
1012 return null;
1014 } else if ($component === 'theme') { //exception
1015 if ($image === 'favicon') {
1016 return "$this->dir/pix/favicon.ico";
1018 if ($imagefile = $this->image_exists("$this->dir/pix/$image")) {
1019 return $imagefile;
1021 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1022 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image")) {
1023 return $imagefile;
1026 return null;
1028 } else {
1029 if (strpos($component, '_') === false) {
1030 $component = 'mod_'.$component;
1032 list($type, $plugin) = explode('_', $component, 2);
1034 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image")) {
1035 return $imagefile;
1037 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1038 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image")) {
1039 return $imagefile;
1042 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image")) {
1043 return $imagefile;
1045 $dir = get_plugin_directory($type, $plugin);
1046 if ($imagefile = $this->image_exists("$dir/pix/$image")) {
1047 return $imagefile;
1049 return null;
1054 * Checks if file with any image extension exists.
1056 * @param string $filepath
1057 * @return string image name with extension
1059 private static function image_exists($filepath) {
1060 if (file_exists("$filepath.gif")) {
1061 return "$filepath.gif";
1062 } else if (file_exists("$filepath.png")) {
1063 return "$filepath.png";
1064 } else if (file_exists("$filepath.jpg")) {
1065 return "$filepath.jpg";
1066 } else if (file_exists("$filepath.jpeg")) {
1067 return "$filepath.jpeg";
1068 } else {
1069 return false;
1074 * Loads the theme config from config.php file.
1076 * @param string $themename
1077 * @param stdClass $settings from config_plugins table
1078 * @return stdClass The theme configuration
1080 private static function find_theme_config($themename, $settings) {
1081 // We have to use the variable name $THEME (upper case) because that
1082 // is what is used in theme config.php files.
1084 if (!$dir = theme_config::find_theme_location($themename)) {
1085 return null;
1088 $THEME = new stdClass();
1089 $THEME->name = $themename;
1090 $THEME->dir = $dir;
1091 $THEME->settings = $settings;
1093 global $CFG; // just in case somebody tries to use $CFG in theme config
1094 include("$THEME->dir/config.php");
1096 // verify the theme configuration is OK
1097 if (!is_array($THEME->parents)) {
1098 // parents option is mandatory now
1099 return null;
1102 return $THEME;
1106 * Finds the theme location and verifies the theme has all needed files
1107 * and is not obsoleted.
1109 * @param string $themename
1110 * @return string full dir path or null if not found
1112 private static function find_theme_location($themename) {
1113 global $CFG;
1115 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1116 $dir = "$CFG->dirroot/theme/$themename";
1118 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1119 $dir = "$CFG->themedir/$themename";
1121 } else {
1122 return null;
1125 if (file_exists("$dir/styles.php")) {
1126 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1127 return null;
1130 return $dir;
1134 * Get the renderer for a part of Moodle for this theme.
1136 * @param moodle_page $page the page we are rendering
1137 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1138 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1139 * @param string $target one of rendering target constants
1140 * @return renderer_base the requested renderer.
1142 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1143 if (is_null($this->rf)) {
1144 $classname = $this->rendererfactory;
1145 $this->rf = new $classname($this);
1148 return $this->rf->get_renderer($page, $component, $subtype, $target);
1152 * Get the information from {@link $layouts} for this type of page.
1154 * @param string $pagelayout the the page layout name.
1155 * @return array the appropriate part of {@link $layouts}.
1157 protected function layout_info_for_page($pagelayout) {
1158 if (array_key_exists($pagelayout, $this->layouts)) {
1159 return $this->layouts[$pagelayout];
1160 } else {
1161 debugging('Invalid page layout specified: ' . $pagelayout);
1162 return $this->layouts['standard'];
1167 * Given the settings of this theme, and the page pagelayout, return the
1168 * full path of the page layout file to use.
1170 * Used by {@link core_renderer::header()}.
1172 * @param string $pagelayout the the page layout name.
1173 * @return string Full path to the lyout file to use
1175 public function layout_file($pagelayout) {
1176 global $CFG;
1178 $layoutinfo = $this->layout_info_for_page($pagelayout);
1179 $layoutfile = $layoutinfo['file'];
1181 if (array_key_exists('theme', $layoutinfo)) {
1182 $themes = array($layoutinfo['theme']);
1183 } else {
1184 $themes = array_merge(array($this->name),$this->parents);
1187 foreach ($themes as $theme) {
1188 if ($dir = $this->find_theme_location($theme)) {
1189 $path = "$dir/layout/$layoutfile";
1191 // Check the template exists, return general base theme template if not.
1192 if (is_readable($path)) {
1193 return $path;
1198 debugging('Can not find layout file for: ' . $pagelayout);
1199 // fallback to standard normal layout
1200 return "$CFG->dirroot/theme/base/layout/general.php";
1204 * Returns auxiliary page layout options specified in layout configuration array.
1206 * @param string $pagelayout
1207 * @return array
1209 public function pagelayout_options($pagelayout) {
1210 $info = $this->layout_info_for_page($pagelayout);
1211 if (!empty($info['options'])) {
1212 return $info['options'];
1214 return array();
1218 * Inform a block_manager about the block regions this theme wants on this
1219 * page layout.
1221 * @param string $pagelayout the general type of the page.
1222 * @param block_manager $blockmanager the block_manger to set up.
1224 public function setup_blocks($pagelayout, $blockmanager) {
1225 $layoutinfo = $this->layout_info_for_page($pagelayout);
1226 if (!empty($layoutinfo['regions'])) {
1227 $blockmanager->add_regions($layoutinfo['regions']);
1228 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1233 * Gets the visible name for the requested block region.
1235 * @param string $region The region name to get
1236 * @param string $theme The theme the region belongs to (may come from the parent theme)
1237 * @return string
1239 protected function get_region_name($region, $theme) {
1240 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1241 // A name exists in this theme, so use it
1242 if (substr($regionstring, 0, 1) != '[') {
1243 return $regionstring;
1246 // Otherwise, try to find one elsewhere
1247 // Check parents, if any
1248 foreach ($this->parents as $parentthemename) {
1249 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1250 if (substr($regionstring, 0, 1) != '[') {
1251 return $regionstring;
1255 // Last resort, try the base theme for names
1256 return get_string('region-' . $region, 'theme_base');
1260 * Get the list of all block regions known to this theme in all templates.
1262 * @return array internal region name => human readable name.
1264 public function get_all_block_regions() {
1265 $regions = array();
1266 foreach ($this->layouts as $layoutinfo) {
1267 foreach ($layoutinfo['regions'] as $region) {
1268 $regions[$region] = $this->get_region_name($region, $this->name);
1271 return $regions;
1275 * Returns the human readable name of the theme
1277 * @return string
1279 public function get_theme_name() {
1280 return get_string('pluginname', 'theme_'.$this->name);
1285 * This class keeps track of which HTML tags are currently open.
1287 * This makes it much easier to always generate well formed XHTML output, even
1288 * if execution terminates abruptly. Any time you output some opening HTML
1289 * without the matching closing HTML, you should push the necessary close tags
1290 * onto the stack.
1292 * @copyright 2009 Tim Hunt
1293 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1294 * @since Moodle 2.0
1295 * @package core
1296 * @category output
1298 class xhtml_container_stack {
1301 * @var array Stores the list of open containers.
1303 protected $opencontainers = array();
1306 * @var array In developer debug mode, stores a stack trace of all opens and
1307 * closes, so we can output helpful error messages when there is a mismatch.
1309 protected $log = array();
1312 * @var boolean Store whether we are developer debug mode. We need this in
1313 * several places including in the destructor where we may not have access to $CFG.
1315 protected $isdebugging;
1318 * Constructor
1320 public function __construct() {
1321 $this->isdebugging = debugging('', DEBUG_DEVELOPER);
1325 * Push the close HTML for a recently opened container onto the stack.
1327 * @param string $type The type of container. This is checked when {@link pop()}
1328 * is called and must match, otherwise a developer debug warning is output.
1329 * @param string $closehtml The HTML required to close the container.
1331 public function push($type, $closehtml) {
1332 $container = new stdClass;
1333 $container->type = $type;
1334 $container->closehtml = $closehtml;
1335 if ($this->isdebugging) {
1336 $this->log('Open', $type);
1338 array_push($this->opencontainers, $container);
1342 * Pop the HTML for the next closing container from the stack. The $type
1343 * must match the type passed when the container was opened, otherwise a
1344 * warning will be output.
1346 * @param string $type The type of container.
1347 * @return string the HTML required to close the container.
1349 public function pop($type) {
1350 if (empty($this->opencontainers)) {
1351 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1352 $this->output_log(), DEBUG_DEVELOPER);
1353 return;
1356 $container = array_pop($this->opencontainers);
1357 if ($container->type != $type) {
1358 debugging('<p>The type of container to be closed (' . $container->type .
1359 ') does not match the type of the next open container (' . $type .
1360 '). This suggests there is a nesting problem.</p>' .
1361 $this->output_log(), DEBUG_DEVELOPER);
1363 if ($this->isdebugging) {
1364 $this->log('Close', $type);
1366 return $container->closehtml;
1370 * Close all but the last open container. This is useful in places like error
1371 * handling, where you want to close all the open containers (apart from <body>)
1372 * before outputting the error message.
1374 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1375 * developer debug warning if it isn't.
1376 * @return string the HTML required to close any open containers inside <body>.
1378 public function pop_all_but_last($shouldbenone = false) {
1379 if ($shouldbenone && count($this->opencontainers) != 1) {
1380 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1381 $this->output_log(), DEBUG_DEVELOPER);
1383 $output = '';
1384 while (count($this->opencontainers) > 1) {
1385 $container = array_pop($this->opencontainers);
1386 $output .= $container->closehtml;
1388 return $output;
1392 * You can call this function if you want to throw away an instance of this
1393 * class without properly emptying the stack (for example, in a unit test).
1394 * Calling this method stops the destruct method from outputting a developer
1395 * debug warning. After calling this method, the instance can no longer be used.
1397 public function discard() {
1398 $this->opencontainers = null;
1402 * Adds an entry to the log.
1404 * @param string $action The name of the action
1405 * @param string $type The type of action
1407 protected function log($action, $type) {
1408 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1409 format_backtrace(debug_backtrace()) . '</li>';
1413 * Outputs the log's contents as a HTML list.
1415 * @return string HTML list of the log
1417 protected function output_log() {
1418 return '<ul>' . implode("\n", $this->log) . '</ul>';