MDL-30988 Fixed phpdocs during integration review
[moodle.git] / lib / outputlib.php
blob9d53be731410de5cc2aa203fe0a3de4fe439f681
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 phsyical directory that is used to cache the theme
41 * files used for serving.
42 * Because it deletes the main theme cache directoy 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 set_config('themerev', empty($CFG->themerev) ? 1 : $CFG->themerev+1);
50 fulldelete("$CFG->cachedir/theme");
53 /**
54 * Enable or disable theme designer mode.
56 * @param bool $state
58 function theme_set_designer_mod($state) {
59 theme_reset_all_caches();
60 set_config('themedesignermode', (int)!empty($state));
63 /**
64 * Returns current theme revision number.
66 * @return int
68 function theme_get_revision() {
69 global $CFG;
71 if (empty($CFG->themedesignermode)) {
72 if (empty($CFG->themerev)) {
73 return -1;
74 } else {
75 return $CFG->themerev;
78 } else {
79 return -1;
84 /**
85 * This class represents the configuration variables of a Moodle theme.
87 * All the variables with access: public below (with a few exceptions that are marked)
88 * are the properties you can set in your themes config.php file.
90 * There are also some methods and protected variables that are part of the inner
91 * workings of Moodle's themes system. If you are just editing a themes config.php
92 * file, you can just ignore those, and the following information for developers.
94 * Normally, to create an instance of this class, you should use the
95 * {@link theme_config::load()} factory method to load a themes config.php file.
96 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
97 * will create one for you, accessible as $PAGE->theme.
99 * @copyright 2009 Tim Hunt
100 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
101 * @since Moodle 2.0
102 * @package core
103 * @category output
105 class theme_config {
108 * @var string Default theme, used when requested theme not found.
110 const DEFAULT_THEME = 'standard';
113 * @var array You can base your theme on other themes by linking to the other theme as
114 * parents. This lets you use the CSS and layouts from the other themes
115 * (see {@link theme_config::$layouts}).
116 * That makes it easy to create a new theme that is similar to another one
117 * but with a few changes. In this themes CSS you only need to override
118 * those rules you want to change.
120 public $parents;
123 * @var array The names of all the stylesheets from this theme that you would
124 * like included, in order. Give the names of the files without .css.
126 public $sheets = array();
129 * @var array The names of all the stylesheets from parents that should be excluded.
130 * true value may be used to specify all parents or all themes from one parent.
131 * If no value specified value from parent theme used.
133 public $parents_exclude_sheets = null;
136 * @var array List of plugin sheets to be excluded.
137 * If no value specified value from parent theme used.
139 public $plugins_exclude_sheets = null;
142 * @var array List of style sheets that are included in the text editor bodies.
143 * Sheets from parent themes are used automatically and can not be excluded.
145 public $editor_sheets = array();
148 * @var array The names of all the javascript files this theme that you would
149 * like included from head, in order. Give the names of the files without .js.
151 public $javascripts = array();
154 * @var array The names of all the javascript files this theme that you would
155 * like included from footer, in order. Give the names of the files without .js.
157 public $javascripts_footer = array();
160 * @var array The names of all the javascript files from parents that should
161 * be excluded. true value may be used to specify all parents or all themes
162 * from one parent.
163 * If no value specified value from parent theme used.
165 public $parents_exclude_javascripts = null;
168 * @var array Which file to use for each page layout.
170 * This is an array of arrays. The keys of the outer array are the different layouts.
171 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
172 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
173 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
174 * That file also has a good example of how to set this setting.
176 * For each layout, the value in the outer array is an array that describes
177 * how you want that type of page to look. For example
178 * <pre>
179 * $THEME->layouts = array(
180 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
181 * 'standard' => array(
182 * 'theme' = 'mytheme',
183 * 'file' => 'normal.php',
184 * 'regions' => array('side-pre', 'side-post'),
185 * 'defaultregion' => 'side-post'
186 * ),
187 * // The site home page.
188 * 'home' => array(
189 * 'theme' = 'mytheme',
190 * 'file' => 'home.php',
191 * 'regions' => array('side-pre', 'side-post'),
192 * 'defaultregion' => 'side-post'
193 * ),
194 * // ...
195 * );
196 * </pre>
198 * 'theme' name of the theme where is the layout located
199 * 'file' is the layout file to use for this type of page.
200 * layout files are stored in layout subfolder
201 * 'regions' This lists the regions on the page where blocks may appear. For
202 * each region you list here, your layout file must include a call to
203 * <pre>
204 * echo $OUTPUT->blocks_for_region($regionname);
205 * </pre>
206 * or equivalent so that the blocks are actually visible.
208 * 'defaultregion' If the list of regions is non-empty, then you must pick
209 * one of the one of them as 'default'. This has two meanings. First, this is
210 * where new blocks are added. Second, if there are any blocks associated with
211 * the page, but in non-existent regions, they appear here. (Imaging, for example,
212 * that someone added blocks using a different theme that used different region
213 * names, and then switched to this theme.)
215 public $layouts = array();
218 * @var string Name of the renderer factory class to use. Must implement the
219 * {@link renderer_factory} interface.
221 * This is an advanced feature. Moodle output is generated by 'renderers',
222 * you can customise the HTML that is output by writing custom renderers,
223 * and then you need to specify 'renderer factory' so that Moodle can find
224 * your renderers.
226 * There are some renderer factories supplied with Moodle. Please follow these
227 * links to see what they do.
228 * <ul>
229 * <li>{@link standard_renderer_factory} - the default.</li>
230 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
231 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
232 * </ul>
234 public $rendererfactory = 'standard_renderer_factory';
237 * @var string Function to do custom CSS post-processing.
239 * This is an advanced feature. If you want to do custom post-processing on the
240 * CSS before it is output (for example, to replace certain variable names
241 * with particular values) you can give the name of a function here.
243 public $csspostprocess = null;
246 * @var string Accessibility: Right arrow-like character is
247 * used in the breadcrumb trail, course navigation menu
248 * (previous/next activity), calendar, and search forum block.
249 * If the theme does not set characters, appropriate defaults
250 * are set automatically. Please DO NOT
251 * use &lt; &gt; &raquo; - these are confusing for blind users.
253 public $rarrow = null;
256 * @var string Accessibility: Right arrow-like character is
257 * used in the breadcrumb trail, course navigation menu
258 * (previous/next activity), calendar, and search forum block.
259 * If the theme does not set characters, appropriate defaults
260 * are set automatically. Please DO NOT
261 * use &lt; &gt; &raquo; - these are confusing for blind users.
263 public $larrow = null;
266 * @var bool Some themes may want to disable ajax course editing.
268 public $enablecourseajax = true;
270 //==Following properties are not configurable from theme config.php==
273 * @var string The name of this theme. Set automatically when this theme is
274 * loaded. This can not be set in theme config.php
276 public $name;
279 * @var string The folder where this themes files are stored. This is set
280 * automatically. This can not be set in theme config.php
282 public $dir;
285 * @var stdClass Theme settings stored in config_plugins table.
286 * This can not be set in theme config.php
288 public $setting = null;
291 * @var bool If set to true and the theme enables the dock then blocks will be able
292 * to be moved to the special dock
294 public $enable_dock = false;
297 * @var bool If set to true then this theme will not be shown in the theme selector unless
298 * theme designer mode is turned on.
300 public $hidefromselector = false;
303 * @var renderer_factory Instance of the renderer_factory implementation
304 * we are using. Implementation detail.
306 protected $rf = null;
309 * @var array List of parent config objects.
311 protected $parent_configs = array();
314 * Load the config.php file for a particular theme, and return an instance
315 * of this class. (That is, this is a factory method.)
317 * @param string $themename the name of the theme.
318 * @return theme_config an instance of this class.
320 public static function load($themename) {
321 global $CFG;
323 // load theme settings from db
324 try {
325 $settings = get_config('theme_'.$themename);
326 } catch (dml_exception $e) {
327 // most probably moodle tables not created yet
328 $settings = new stdClass();
331 if ($config = theme_config::find_theme_config($themename, $settings)) {
332 return new theme_config($config);
334 } else if ($themename == theme_config::DEFAULT_THEME) {
335 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
337 } else {
338 // bad luck, the requested theme has some problems - admin see details in theme config
339 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
344 * Theme diagnostic code. It is very problematic to send debug output
345 * to the actual CSS file, instead this functions is supposed to
346 * diagnose given theme and highlights all potential problems.
347 * This information should be available from the theme selection page
348 * or some other debug page for theme designers.
350 * @param string $themename
351 * @return array description of problems
353 public static function diagnose($themename) {
354 //TODO: MDL-21108
355 return array();
359 * Private constructor, can be called only from the factory method.
360 * @param stdClass $config
362 private function __construct($config) {
363 global $CFG; //needed for included lib.php files
365 $this->settings = $config->settings;
366 $this->name = $config->name;
367 $this->dir = $config->dir;
369 if ($this->name != 'base') {
370 $baseconfig = theme_config::find_theme_config('base', $this->settings);
371 } else {
372 $baseconfig = $config;
375 $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer',
376 'parents_exclude_javascripts', 'layouts', 'enable_dock', 'enablecourseajax',
377 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector');
379 foreach ($config as $key=>$value) {
380 if (in_array($key, $configurable)) {
381 $this->$key = $value;
385 // verify all parents and load configs and renderers
386 foreach ($this->parents as $parent) {
387 if ($parent == 'base') {
388 $parent_config = $baseconfig;
389 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
390 // this is not good - better exclude faulty parents
391 continue;
393 $libfile = $parent_config->dir.'/lib.php';
394 if (is_readable($libfile)) {
395 // theme may store various function here
396 include_once($libfile);
398 $renderersfile = $parent_config->dir.'/renderers.php';
399 if (is_readable($renderersfile)) {
400 // may contain core and plugin renderers and renderer factory
401 include_once($renderersfile);
403 $this->parent_configs[$parent] = $parent_config;
404 $rendererfile = $parent_config->dir.'/renderers.php';
405 if (is_readable($rendererfile)) {
406 // may contain core and plugin renderers and renderer factory
407 include_once($rendererfile);
410 $libfile = $this->dir.'/lib.php';
411 if (is_readable($libfile)) {
412 // theme may store various function here
413 include_once($libfile);
415 $rendererfile = $this->dir.'/renderers.php';
416 if (is_readable($rendererfile)) {
417 // may contain core and plugin renderers and renderer factory
418 include_once($rendererfile);
421 // cascade all layouts properly
422 foreach ($baseconfig->layouts as $layout=>$value) {
423 if (!isset($this->layouts[$layout])) {
424 foreach ($this->parent_configs as $parent_config) {
425 if (isset($parent_config->layouts[$layout])) {
426 $this->layouts[$layout] = $parent_config->layouts[$layout];
427 continue 2;
430 $this->layouts[$layout] = $value;
434 //fix arrows if needed
435 $this->check_theme_arrows();
439 * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
440 * If not it applies sensible defaults.
442 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
443 * search forum block, etc. Important: these are 'silent' in a screen-reader
444 * (unlike &gt; &raquo;), and must be accompanied by text.
446 private function check_theme_arrows() {
447 if (!isset($this->rarrow) and !isset($this->larrow)) {
448 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
449 // Also OK in Win 9x/2K/IE 5.x
450 $this->rarrow = '&#x25BA;';
451 $this->larrow = '&#x25C4;';
452 if (empty($_SERVER['HTTP_USER_AGENT'])) {
453 $uagent = '';
454 } else {
455 $uagent = $_SERVER['HTTP_USER_AGENT'];
457 if (false !== strpos($uagent, 'Opera')
458 || false !== strpos($uagent, 'Mac')) {
459 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
460 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
461 $this->rarrow = '&#x25B6;';
462 $this->larrow = '&#x25C0;';
464 elseif (false !== strpos($uagent, 'Konqueror')) {
465 $this->rarrow = '&rarr;';
466 $this->larrow = '&larr;';
468 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
469 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
470 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
471 // To be safe, non-Unicode browsers!
472 $this->rarrow = '&gt;';
473 $this->larrow = '&lt;';
476 // RTL support - in RTL languages, swap r and l arrows
477 if (right_to_left()) {
478 $t = $this->rarrow;
479 $this->rarrow = $this->larrow;
480 $this->larrow = $t;
486 * Returns output renderer prefixes, these are used when looking
487 * for the overridden renderers in themes.
489 * @return array
491 public function renderer_prefixes() {
492 global $CFG; // just in case the included files need it
494 $prefixes = array('theme_'.$this->name);
496 foreach ($this->parent_configs as $parent) {
497 $prefixes[] = 'theme_'.$parent->name;
500 return $prefixes;
504 * Returns the stylesheet URL of this editor content
506 * @param bool $encoded false means use & and true use &amp; in URLs
507 * @return string
509 public function editor_css_url($encoded=true) {
510 global $CFG;
512 $rev = theme_get_revision();
514 if ($rev > -1) {
515 $params = array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor');
516 return new moodle_url($CFG->httpswwwroot.'/theme/styles.php', $params);
517 } else {
518 $params = array('theme'=>$this->name, 'type'=>'editor');
519 return new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
524 * Returns the content of the CSS to be used in editor content
526 * @return string
528 public function editor_css_files() {
529 global $CFG;
531 $files = array();
533 // first editor plugins
534 $plugins = get_plugin_list('editor');
535 foreach ($plugins as $plugin=>$fulldir) {
536 $sheetfile = "$fulldir/editor_styles.css";
537 if (is_readable($sheetfile)) {
538 $files['plugin_'.$plugin] = $sheetfile;
541 // then parent themes
542 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
543 if (empty($parent_config->editor_sheets)) {
544 continue;
546 foreach ($parent_config->editor_sheets as $sheet) {
547 $sheetfile = "$parent_config->dir/style/$sheet.css";
548 if (is_readable($sheetfile)) {
549 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
553 // finally this theme
554 if (!empty($this->editor_sheets)) {
555 foreach ($this->editor_sheets as $sheet) {
556 $sheetfile = "$this->dir/style/$sheet.css";
557 if (is_readable($sheetfile)) {
558 $files['theme_'.$sheet] = $sheetfile;
563 return $files;
567 * Get the stylesheet URL of this theme
569 * @param moodle_page $page Not used... deprecated?
570 * @return array of moodle_url
572 public function css_urls(moodle_page $page) {
573 global $CFG;
575 $rev = theme_get_revision();
577 $urls = array();
579 if ($rev > -1) {
580 if (check_browser_version('MSIE', 5)) {
581 // We need to split the CSS files for IE
582 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'plugins'));
583 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'parents'));
584 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'theme'));
585 } else {
586 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev));
588 } else {
589 // find out the current CSS and cache it now for 5 seconds
590 // the point is to construct the CSS only once and pass it through the
591 // dataroot to the script that actually serves the sheets
592 if (!defined('THEME_DESIGNER_CACHE_LIFETIME')) {
593 define('THEME_DESIGNER_CACHE_LIFETIME', 4); // this can be also set in config.php
595 $candidatesheet = "$CFG->cachedir/theme/$this->name/designer.ser";
596 if (!file_exists($candidatesheet)) {
597 $css = $this->css_content();
598 check_dir_exists(dirname($candidatesheet));
599 file_put_contents($candidatesheet, serialize($css));
601 } else if (filemtime($candidatesheet) > time() - THEME_DESIGNER_CACHE_LIFETIME) {
602 if ($css = file_get_contents($candidatesheet)) {
603 $css = unserialize($css);
604 } else {
605 unlink($candidatesheet);
606 $css = $this->css_content();
609 } else {
610 unlink($candidatesheet);
611 $css = $this->css_content();
612 file_put_contents($candidatesheet, serialize($css));
615 $baseurl = $CFG->httpswwwroot.'/theme/styles_debug.php';
617 if (check_browser_version('MSIE', 5)) {
618 // lalala, IE does not allow more than 31 linked CSS files from main document
619 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
620 foreach ($css['parents'] as $parent=>$sheets) {
621 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096)
622 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
624 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
626 } else {
627 foreach ($css['plugins'] as $plugin=>$unused) {
628 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
630 foreach ($css['parents'] as $parent=>$sheets) {
631 foreach ($sheets as $sheet=>$unused2) {
632 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
635 foreach ($css['theme'] as $sheet=>$unused) {
636 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); // sheet first in order to make long urls easier to read
641 return $urls;
645 * Returns an array of organised CSS files required for this output
647 * @return array
649 public function css_files() {
650 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
652 // get all plugin sheets
653 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
654 if ($excludes !== true) {
655 foreach (get_plugin_types() as $type=>$unused) {
656 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
657 continue;
659 $plugins = get_plugin_list($type);
660 foreach ($plugins as $plugin=>$fulldir) {
661 if (!empty($excludes[$type]) and is_array($excludes[$type])
662 and in_array($plugin, $excludes[$type])) {
663 continue;
666 $plugincontent = '';
667 $sheetfile = "$fulldir/styles.css";
668 if (is_readable($sheetfile)) {
669 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
671 $sheetthemefile = "$fulldir/styles_{$this->name}.css";
672 if (is_readable($sheetthemefile)) {
673 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$this->name] = $sheetthemefile;
679 // find out wanted parent sheets
680 $excludes = $this->resolve_excludes('parents_exclude_sheets');
681 if ($excludes !== true) {
682 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
683 $parent = $parent_config->name;
684 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
685 continue;
687 foreach ($parent_config->sheets as $sheet) {
688 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
689 and in_array($sheet, $excludes[$parent])) {
690 continue;
692 $sheetfile = "$parent_config->dir/style/$sheet.css";
693 if (is_readable($sheetfile)) {
694 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
700 // current theme sheets
701 if (is_array($this->sheets)) {
702 foreach ($this->sheets as $sheet) {
703 $sheetfile = "$this->dir/style/$sheet.css";
704 if (is_readable($sheetfile)) {
705 $cssfiles['theme'][$sheet] = $sheetfile;
710 return $cssfiles;
714 * Returns the content of the one huge CSS merged from all style sheets.
716 * @return string
718 public function css_content() {
719 $files = array_merge($this->css_files(), array('editor'=>$this->editor_css_files()));
720 $css = $this->css_files_get_contents($files, array());
721 return $css;
725 * Given an array of file paths or a single file path loads the contents of
726 * the CSS file, processes it then returns it in the same structure it was given.
728 * Can be used recursively on the results of {@link css_files}
730 * @param array|string $file An array of file paths or a single file path
731 * @param array $keys An array of previous array keys [recursive addition]
732 * @return The converted array or the contents of the single file ($file type)
734 protected function css_files_get_contents($file, array $keys) {
735 if (is_array($file)) {
736 foreach ($file as $key=>$f) {
737 $file[$key] = $this->css_files_get_contents($f, array_merge($keys, array($key)));
739 return $file;
740 } else {
741 $comment = '/** Path: '.implode(' ', $keys).' **/'."\n";
742 return $comment.$this->post_process(file_get_contents($file));
748 * Generate a URL to the file that serves theme JavaScript files.
750 * @param bool $inhead true means head url, false means footer
751 * @return moodle_url
753 public function javascript_url($inhead) {
754 global $CFG;
756 $rev = theme_get_revision();
757 $params = array('theme'=>$this->name,'rev'=>$rev);
758 $params['type'] = $inhead ? 'head' : 'footer';
760 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
764 * Get the URL's for the JavaScript files used by this theme.
765 * They won't be served directly, instead they'll be mediated through
766 * theme/javascript.php.
768 * @param string $type Either javascripts_footer, or javascripts
769 * @return array
771 public function javascript_files($type) {
772 if ($type === 'footer') {
773 $type = 'javascripts_footer';
774 } else {
775 $type = 'javascripts';
778 $js = array();
779 // find out wanted parent javascripts
780 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
781 if ($excludes !== true) {
782 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
783 $parent = $parent_config->name;
784 if (empty($parent_config->$type)) {
785 continue;
787 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
788 continue;
790 foreach ($parent_config->$type as $javascript) {
791 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
792 and in_array($javascript, $excludes[$parent])) {
793 continue;
795 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
796 if (is_readable($javascriptfile)) {
797 $js[] = $javascriptfile;
803 // current theme javascripts
804 if (is_array($this->$type)) {
805 foreach ($this->$type as $javascript) {
806 $javascriptfile = "$this->dir/javascript/$javascript.js";
807 if (is_readable($javascriptfile)) {
808 $js[] = $javascriptfile;
813 return $js;
817 * Resolves an exclude setting to the themes setting is applicable or the
818 * setting of its closest parent.
820 * @param string $variable The name of the setting the exclude setting to resolve
821 * @param string $default
822 * @return mixed
824 protected function resolve_excludes($variable, $default = null) {
825 $setting = $default;
826 if (is_array($this->{$variable}) or $this->{$variable} === true) {
827 $setting = $this->{$variable};
828 } else {
829 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
830 if (!isset($parent_config->{$variable})) {
831 continue;
833 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
834 $setting = $parent_config->{$variable};
835 break;
839 return $setting;
843 * Returns the content of the one huge javascript file merged from all theme javascript files.
845 * @param bool $type
846 * @return string
848 public function javascript_content($type) {
849 $jsfiles = $this->javascript_files($type);
850 $js = '';
851 foreach ($jsfiles as $jsfile) {
852 $js .= file_get_contents($jsfile)."\n";
854 return $js;
858 * Post processes CSS.
860 * This method post processes all of the CSS before it is served for this theme.
861 * This is done so that things such as image URL's can be swapped in and to
862 * run any specific CSS post process method the theme has requested.
863 * This allows themes to use CSS settings.
865 * @param string $css The CSS to process.
866 * @return string The processed CSS.
868 public function post_process($css) {
869 global $CFG;
871 // now resolve all image locations
872 if (preg_match_all('/\[\[pix:([a-z_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
873 $replaced = array();
874 foreach ($matches as $match) {
875 if (isset($replaced[$match[0]])) {
876 continue;
878 $replaced[$match[0]] = true;
879 $imagename = $match[2];
880 $component = rtrim($match[1], '|');
881 $imageurl = $this->pix_url($imagename, $component)->out(false);
882 // we do not need full url because the image.php is always in the same dir
883 $imageurl = str_replace("$CFG->httpswwwroot/theme/", '', $imageurl);
884 $css = str_replace($match[0], $imageurl, $css);
888 // now resolve all theme settings or do any other postprocessing
889 $csspostprocess = $this->csspostprocess;
890 if (function_exists($csspostprocess)) {
891 $css = $csspostprocess($css, $this);
894 return $css;
898 * Return the URL for an image
900 * @param string $imagename the name of the icon.
901 * @param string $component specification of one plugin like in get_string()
902 * @return moodle_url
904 public function pix_url($imagename, $component) {
905 global $CFG;
907 $params = array('theme'=>$this->name, 'image'=>$imagename);
909 $rev = theme_get_revision();
910 if ($rev != -1) {
911 $params['rev'] = $rev;
913 if (!empty($component) and $component !== 'moodle'and $component !== 'core') {
914 $params['component'] = $component;
917 return new moodle_url("$CFG->httpswwwroot/theme/image.php", $params);
921 * Resolves the real image location.
922 * @param string $image name of image, may contain relative path
923 * @param string $component
924 * @return string full file path
926 public function resolve_image_location($image, $component) {
927 global $CFG;
929 if ($component === 'moodle' or $component === 'core' or empty($component)) {
930 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image")) {
931 return $imagefile;
933 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
934 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image")) {
935 return $imagefile;
938 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image")) {
939 return $imagefile;
941 return null;
943 } else if ($component === 'theme') { //exception
944 if ($image === 'favicon') {
945 return "$this->dir/pix/favicon.ico";
947 if ($imagefile = $this->image_exists("$this->dir/pix/$image")) {
948 return $imagefile;
950 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
951 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image")) {
952 return $imagefile;
955 return null;
957 } else {
958 if (strpos($component, '_') === false) {
959 $component = 'mod_'.$component;
961 list($type, $plugin) = explode('_', $component, 2);
963 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image")) {
964 return $imagefile;
966 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
967 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image")) {
968 return $imagefile;
971 $dir = get_plugin_directory($type, $plugin);
972 if ($imagefile = $this->image_exists("$dir/pix/$image")) {
973 return $imagefile;
975 return null;
980 * Checks if file with any image extension exists.
982 * @param string $filepath
983 * @return string image name with extension
985 private static function image_exists($filepath) {
986 if (file_exists("$filepath.gif")) {
987 return "$filepath.gif";
988 } else if (file_exists("$filepath.png")) {
989 return "$filepath.png";
990 } else if (file_exists("$filepath.jpg")) {
991 return "$filepath.jpg";
992 } else if (file_exists("$filepath.jpeg")) {
993 return "$filepath.jpeg";
994 } else {
995 return false;
1000 * Loads the theme config from config.php file.
1002 * @param string $themename
1003 * @param stdClass $settings from config_plugins table
1004 * @return stdClass The theme configuration
1006 private static function find_theme_config($themename, $settings) {
1007 // We have to use the variable name $THEME (upper case) because that
1008 // is what is used in theme config.php files.
1010 if (!$dir = theme_config::find_theme_location($themename)) {
1011 return null;
1014 $THEME = new stdClass();
1015 $THEME->name = $themename;
1016 $THEME->dir = $dir;
1017 $THEME->settings = $settings;
1019 global $CFG; // just in case somebody tries to use $CFG in theme config
1020 include("$THEME->dir/config.php");
1022 // verify the theme configuration is OK
1023 if (!is_array($THEME->parents)) {
1024 // parents option is mandatory now
1025 return null;
1028 return $THEME;
1032 * Finds the theme location and verifies the theme has all needed files
1033 * and is not obsoleted.
1035 * @param string $themename
1036 * @return string full dir path or null if not found
1038 private static function find_theme_location($themename) {
1039 global $CFG;
1041 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1042 $dir = "$CFG->dirroot/theme/$themename";
1044 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1045 $dir = "$CFG->themedir/$themename";
1047 } else {
1048 return null;
1051 if (file_exists("$dir/styles.php")) {
1052 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1053 return null;
1056 return $dir;
1060 * Get the renderer for a part of Moodle for this theme.
1062 * @param moodle_page $page the page we are rendering
1063 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1064 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1065 * @param string $target one of rendering target constants
1066 * @return renderer_base the requested renderer.
1068 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1069 if (is_null($this->rf)) {
1070 $classname = $this->rendererfactory;
1071 $this->rf = new $classname($this);
1074 return $this->rf->get_renderer($page, $component, $subtype, $target);
1078 * Get the information from {@link $layouts} for this type of page.
1080 * @param string $pagelayout the the page layout name.
1081 * @return array the appropriate part of {@link $layouts}.
1083 protected function layout_info_for_page($pagelayout) {
1084 if (array_key_exists($pagelayout, $this->layouts)) {
1085 return $this->layouts[$pagelayout];
1086 } else {
1087 debugging('Invalid page layout specified: ' . $pagelayout);
1088 return $this->layouts['standard'];
1093 * Given the settings of this theme, and the page pagelayout, return the
1094 * full path of the page layout file to use.
1096 * Used by {@link core_renderer::header()}.
1098 * @param string $pagelayout the the page layout name.
1099 * @return string Full path to the lyout file to use
1101 public function layout_file($pagelayout) {
1102 global $CFG;
1104 $layoutinfo = $this->layout_info_for_page($pagelayout);
1105 $layoutfile = $layoutinfo['file'];
1107 if (array_key_exists('theme', $layoutinfo)) {
1108 $themes = array($layoutinfo['theme']);
1109 } else {
1110 $themes = array_merge(array($this->name),$this->parents);
1113 foreach ($themes as $theme) {
1114 if ($dir = $this->find_theme_location($theme)) {
1115 $path = "$dir/layout/$layoutfile";
1117 // Check the template exists, return general base theme template if not.
1118 if (is_readable($path)) {
1119 return $path;
1124 debugging('Can not find layout file for: ' . $pagelayout);
1125 // fallback to standard normal layout
1126 return "$CFG->dirroot/theme/base/layout/general.php";
1130 * Returns auxiliary page layout options specified in layout configuration array.
1132 * @param string $pagelayout
1133 * @return array
1135 public function pagelayout_options($pagelayout) {
1136 $info = $this->layout_info_for_page($pagelayout);
1137 if (!empty($info['options'])) {
1138 return $info['options'];
1140 return array();
1144 * Inform a block_manager about the block regions this theme wants on this
1145 * page layout.
1147 * @param string $pagelayout the general type of the page.
1148 * @param block_manager $blockmanager the block_manger to set up.
1150 public function setup_blocks($pagelayout, $blockmanager) {
1151 $layoutinfo = $this->layout_info_for_page($pagelayout);
1152 if (!empty($layoutinfo['regions'])) {
1153 $blockmanager->add_regions($layoutinfo['regions']);
1154 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1159 * Gets the visible name for the requested block region.
1161 * @param string $region The region name to get
1162 * @param string $theme The theme the region belongs to (may come from the parent theme)
1163 * @return string
1165 protected function get_region_name($region, $theme) {
1166 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1167 // A name exists in this theme, so use it
1168 if (substr($regionstring, 0, 1) != '[') {
1169 return $regionstring;
1172 // Otherwise, try to find one elsewhere
1173 // Check parents, if any
1174 foreach ($this->parents as $parentthemename) {
1175 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1176 if (substr($regionstring, 0, 1) != '[') {
1177 return $regionstring;
1181 // Last resort, try the base theme for names
1182 return get_string('region-' . $region, 'theme_base');
1186 * Get the list of all block regions known to this theme in all templates.
1188 * @return array internal region name => human readable name.
1190 public function get_all_block_regions() {
1191 $regions = array();
1192 foreach ($this->layouts as $layoutinfo) {
1193 foreach ($layoutinfo['regions'] as $region) {
1194 $regions[$region] = $this->get_region_name($region, $this->name);
1197 return $regions;
1201 * Returns the human readable name of the theme
1203 * @return string
1205 public function get_theme_name() {
1206 return get_string('pluginname', 'theme_'.$this->name);
1211 * This class keeps track of which HTML tags are currently open.
1213 * This makes it much easier to always generate well formed XHTML output, even
1214 * if execution terminates abruptly. Any time you output some opening HTML
1215 * without the matching closing HTML, you should push the necessary close tags
1216 * onto the stack.
1218 * @copyright 2009 Tim Hunt
1219 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1220 * @since Moodle 2.0
1221 * @package core
1222 * @category output
1224 class xhtml_container_stack {
1227 * @var array Stores the list of open containers.
1229 protected $opencontainers = array();
1232 * @var array In developer debug mode, stores a stack trace of all opens and
1233 * closes, so we can output helpful error messages when there is a mismatch.
1235 protected $log = array();
1238 * @var boolean Store whether we are developer debug mode. We need this in
1239 * several places including in the destructor where we may not have access to $CFG.
1241 protected $isdebugging;
1244 * Constructor
1246 public function __construct() {
1247 $this->isdebugging = debugging('', DEBUG_DEVELOPER);
1251 * Push the close HTML for a recently opened container onto the stack.
1253 * @param string $type The type of container. This is checked when {@link pop()}
1254 * is called and must match, otherwise a developer debug warning is output.
1255 * @param string $closehtml The HTML required to close the container.
1257 public function push($type, $closehtml) {
1258 $container = new stdClass;
1259 $container->type = $type;
1260 $container->closehtml = $closehtml;
1261 if ($this->isdebugging) {
1262 $this->log('Open', $type);
1264 array_push($this->opencontainers, $container);
1268 * Pop the HTML for the next closing container from the stack. The $type
1269 * must match the type passed when the container was opened, otherwise a
1270 * warning will be output.
1272 * @param string $type The type of container.
1273 * @return string the HTML required to close the container.
1275 public function pop($type) {
1276 if (empty($this->opencontainers)) {
1277 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1278 $this->output_log(), DEBUG_DEVELOPER);
1279 return;
1282 $container = array_pop($this->opencontainers);
1283 if ($container->type != $type) {
1284 debugging('<p>The type of container to be closed (' . $container->type .
1285 ') does not match the type of the next open container (' . $type .
1286 '). This suggests there is a nesting problem.</p>' .
1287 $this->output_log(), DEBUG_DEVELOPER);
1289 if ($this->isdebugging) {
1290 $this->log('Close', $type);
1292 return $container->closehtml;
1296 * Close all but the last open container. This is useful in places like error
1297 * handling, where you want to close all the open containers (apart from <body>)
1298 * before outputting the error message.
1300 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1301 * developer debug warning if it isn't.
1302 * @return string the HTML required to close any open containers inside <body>.
1304 public function pop_all_but_last($shouldbenone = false) {
1305 if ($shouldbenone && count($this->opencontainers) != 1) {
1306 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1307 $this->output_log(), DEBUG_DEVELOPER);
1309 $output = '';
1310 while (count($this->opencontainers) > 1) {
1311 $container = array_pop($this->opencontainers);
1312 $output .= $container->closehtml;
1314 return $output;
1318 * You can call this function if you want to throw away an instance of this
1319 * class without properly emptying the stack (for example, in a unit test).
1320 * Calling this method stops the destruct method from outputting a developer
1321 * debug warning. After calling this method, the instance can no longer be used.
1323 public function discard() {
1324 $this->opencontainers = null;
1328 * Adds an entry to the log.
1330 * @param string $action The name of the action
1331 * @param string $type The type of action
1333 protected function log($action, $type) {
1334 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1335 format_backtrace(debug_backtrace()) . '</li>';
1339 * Outputs the log's contents as a HTML list.
1341 * @return string HTML list of the log
1343 protected function output_log() {
1344 return '<ul>' . implode("\n", $this->log) . '</ul>';