Merge branch 'MDL-32780-CLEAN' of git://github.com/netspotau/moodle-mod_assign
[moodle.git] / lib / outputlib.php
blob7cd7abe073380fa2a508a83f145b9b6789898da0
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);
419 } else {
420 // check if renderers.php file is missnamed renderer.php
421 if (is_readable($this->dir.'/renderer.php')) {
422 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
423 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
427 // cascade all layouts properly
428 foreach ($baseconfig->layouts as $layout=>$value) {
429 if (!isset($this->layouts[$layout])) {
430 foreach ($this->parent_configs as $parent_config) {
431 if (isset($parent_config->layouts[$layout])) {
432 $this->layouts[$layout] = $parent_config->layouts[$layout];
433 continue 2;
436 $this->layouts[$layout] = $value;
440 //fix arrows if needed
441 $this->check_theme_arrows();
445 * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
446 * If not it applies sensible defaults.
448 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
449 * search forum block, etc. Important: these are 'silent' in a screen-reader
450 * (unlike &gt; &raquo;), and must be accompanied by text.
452 private function check_theme_arrows() {
453 if (!isset($this->rarrow) and !isset($this->larrow)) {
454 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
455 // Also OK in Win 9x/2K/IE 5.x
456 $this->rarrow = '&#x25BA;';
457 $this->larrow = '&#x25C4;';
458 if (empty($_SERVER['HTTP_USER_AGENT'])) {
459 $uagent = '';
460 } else {
461 $uagent = $_SERVER['HTTP_USER_AGENT'];
463 if (false !== strpos($uagent, 'Opera')
464 || false !== strpos($uagent, 'Mac')) {
465 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
466 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
467 $this->rarrow = '&#x25B6;';
468 $this->larrow = '&#x25C0;';
470 elseif (false !== strpos($uagent, 'Konqueror')) {
471 $this->rarrow = '&rarr;';
472 $this->larrow = '&larr;';
474 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
475 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
476 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
477 // To be safe, non-Unicode browsers!
478 $this->rarrow = '&gt;';
479 $this->larrow = '&lt;';
482 // RTL support - in RTL languages, swap r and l arrows
483 if (right_to_left()) {
484 $t = $this->rarrow;
485 $this->rarrow = $this->larrow;
486 $this->larrow = $t;
492 * Returns output renderer prefixes, these are used when looking
493 * for the overridden renderers in themes.
495 * @return array
497 public function renderer_prefixes() {
498 global $CFG; // just in case the included files need it
500 $prefixes = array('theme_'.$this->name);
502 foreach ($this->parent_configs as $parent) {
503 $prefixes[] = 'theme_'.$parent->name;
506 return $prefixes;
510 * Returns the stylesheet URL of this editor content
512 * @param bool $encoded false means use & and true use &amp; in URLs
513 * @return string
515 public function editor_css_url($encoded=true) {
516 global $CFG;
518 $rev = theme_get_revision();
520 if ($rev > -1) {
521 if (!empty($CFG->slasharguments)) {
522 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
523 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
524 return $url;
525 } else {
526 $params = array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor');
527 return new moodle_url($CFG->httpswwwroot.'/theme/styles.php', $params);
529 } else {
530 $params = array('theme'=>$this->name, 'type'=>'editor');
531 return new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
536 * Returns the content of the CSS to be used in editor content
538 * @return string
540 public function editor_css_files() {
541 global $CFG;
543 $files = array();
545 // first editor plugins
546 $plugins = get_plugin_list('editor');
547 foreach ($plugins as $plugin=>$fulldir) {
548 $sheetfile = "$fulldir/editor_styles.css";
549 if (is_readable($sheetfile)) {
550 $files['plugin_'.$plugin] = $sheetfile;
553 // then parent themes
554 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
555 if (empty($parent_config->editor_sheets)) {
556 continue;
558 foreach ($parent_config->editor_sheets as $sheet) {
559 $sheetfile = "$parent_config->dir/style/$sheet.css";
560 if (is_readable($sheetfile)) {
561 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
565 // finally this theme
566 if (!empty($this->editor_sheets)) {
567 foreach ($this->editor_sheets as $sheet) {
568 $sheetfile = "$this->dir/style/$sheet.css";
569 if (is_readable($sheetfile)) {
570 $files['theme_'.$sheet] = $sheetfile;
575 return $files;
579 * Get the stylesheet URL of this theme
581 * @param moodle_page $page Not used... deprecated?
582 * @return array of moodle_url
584 public function css_urls(moodle_page $page) {
585 global $CFG;
587 $rev = theme_get_revision();
589 $urls = array();
591 if ($rev > -1) {
592 if (check_browser_version('MSIE', 5)) {
593 // We need to split the CSS files for IE
594 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'plugins'));
595 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'parents'));
596 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'theme'));
597 } else {
598 if (!empty($CFG->slasharguments)) {
599 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
600 $url->set_slashargument('/'.$this->name.'/'.$rev.'/all', 'noparam', true);
601 $urls[] = $url;
602 } else {
603 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'all'));
606 } else {
607 // find out the current CSS and cache it now for 5 seconds
608 // the point is to construct the CSS only once and pass it through the
609 // dataroot to the script that actually serves the sheets
610 if (!defined('THEME_DESIGNER_CACHE_LIFETIME')) {
611 define('THEME_DESIGNER_CACHE_LIFETIME', 4); // this can be also set in config.php
613 $candidatesheet = "$CFG->cachedir/theme/$this->name/designer.ser";
614 if (!file_exists($candidatesheet)) {
615 $css = $this->css_content();
616 check_dir_exists(dirname($candidatesheet));
617 file_put_contents($candidatesheet, serialize($css));
619 } else if (filemtime($candidatesheet) > time() - THEME_DESIGNER_CACHE_LIFETIME) {
620 if ($css = file_get_contents($candidatesheet)) {
621 $css = unserialize($css);
622 } else {
623 unlink($candidatesheet);
624 $css = $this->css_content();
627 } else {
628 unlink($candidatesheet);
629 $css = $this->css_content();
630 file_put_contents($candidatesheet, serialize($css));
633 $baseurl = $CFG->httpswwwroot.'/theme/styles_debug.php';
635 if (check_browser_version('MSIE', 5)) {
636 // lalala, IE does not allow more than 31 linked CSS files from main document
637 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
638 foreach ($css['parents'] as $parent=>$sheets) {
639 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096)
640 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
642 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
644 } else {
645 foreach ($css['plugins'] as $plugin=>$unused) {
646 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
648 foreach ($css['parents'] as $parent=>$sheets) {
649 foreach ($sheets as $sheet=>$unused2) {
650 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
653 foreach ($css['theme'] as $sheet=>$unused) {
654 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); // sheet first in order to make long urls easier to read
659 return $urls;
663 * Returns an array of organised CSS files required for this output
665 * @return array
667 public function css_files() {
668 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
670 // get all plugin sheets
671 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
672 if ($excludes !== true) {
673 foreach (get_plugin_types() as $type=>$unused) {
674 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
675 continue;
677 $plugins = get_plugin_list($type);
678 foreach ($plugins as $plugin=>$fulldir) {
679 if (!empty($excludes[$type]) and is_array($excludes[$type])
680 and in_array($plugin, $excludes[$type])) {
681 continue;
684 $plugincontent = '';
685 $sheetfile = "$fulldir/styles.css";
686 if (is_readable($sheetfile)) {
687 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
689 $sheetthemefile = "$fulldir/styles_{$this->name}.css";
690 if (is_readable($sheetthemefile)) {
691 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$this->name] = $sheetthemefile;
697 // find out wanted parent sheets
698 $excludes = $this->resolve_excludes('parents_exclude_sheets');
699 if ($excludes !== true) {
700 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
701 $parent = $parent_config->name;
702 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
703 continue;
705 foreach ($parent_config->sheets as $sheet) {
706 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
707 and in_array($sheet, $excludes[$parent])) {
708 continue;
710 $sheetfile = "$parent_config->dir/style/$sheet.css";
711 if (is_readable($sheetfile)) {
712 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
718 // current theme sheets
719 if (is_array($this->sheets)) {
720 foreach ($this->sheets as $sheet) {
721 $sheetfile = "$this->dir/style/$sheet.css";
722 if (is_readable($sheetfile)) {
723 $cssfiles['theme'][$sheet] = $sheetfile;
728 return $cssfiles;
732 * Returns the content of the one huge CSS merged from all style sheets.
734 * @return string
736 public function css_content() {
737 $files = array_merge($this->css_files(), array('editor'=>$this->editor_css_files()));
738 $css = $this->css_files_get_contents($files, array());
739 return $css;
743 * Given an array of file paths or a single file path loads the contents of
744 * the CSS file, processes it then returns it in the same structure it was given.
746 * Can be used recursively on the results of {@link css_files}
748 * @param array|string $file An array of file paths or a single file path
749 * @param array $keys An array of previous array keys [recursive addition]
750 * @return The converted array or the contents of the single file ($file type)
752 protected function css_files_get_contents($file, array $keys) {
753 if (is_array($file)) {
754 foreach ($file as $key=>$f) {
755 $file[$key] = $this->css_files_get_contents($f, array_merge($keys, array($key)));
757 return $file;
758 } else {
759 $comment = '/** Path: '.implode(' ', $keys).' **/'."\n";
760 return $comment.$this->post_process(file_get_contents($file));
766 * Generate a URL to the file that serves theme JavaScript files.
768 * @param bool $inhead true means head url, false means footer
769 * @return moodle_url
771 public function javascript_url($inhead) {
772 global $CFG;
774 $rev = theme_get_revision();
775 $params = array('theme'=>$this->name,'rev'=>$rev);
776 $params['type'] = $inhead ? 'head' : 'footer';
778 if (!empty($CFG->slasharguments) and $rev > 0) {
779 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
780 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
781 return $url;
782 } else {
783 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
788 * Get the URL's for the JavaScript files used by this theme.
789 * They won't be served directly, instead they'll be mediated through
790 * theme/javascript.php.
792 * @param string $type Either javascripts_footer, or javascripts
793 * @return array
795 public function javascript_files($type) {
796 if ($type === 'footer') {
797 $type = 'javascripts_footer';
798 } else {
799 $type = 'javascripts';
802 $js = array();
803 // find out wanted parent javascripts
804 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
805 if ($excludes !== true) {
806 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
807 $parent = $parent_config->name;
808 if (empty($parent_config->$type)) {
809 continue;
811 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
812 continue;
814 foreach ($parent_config->$type as $javascript) {
815 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
816 and in_array($javascript, $excludes[$parent])) {
817 continue;
819 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
820 if (is_readable($javascriptfile)) {
821 $js[] = $javascriptfile;
827 // current theme javascripts
828 if (is_array($this->$type)) {
829 foreach ($this->$type as $javascript) {
830 $javascriptfile = "$this->dir/javascript/$javascript.js";
831 if (is_readable($javascriptfile)) {
832 $js[] = $javascriptfile;
837 return $js;
841 * Resolves an exclude setting to the themes setting is applicable or the
842 * setting of its closest parent.
844 * @param string $variable The name of the setting the exclude setting to resolve
845 * @param string $default
846 * @return mixed
848 protected function resolve_excludes($variable, $default = null) {
849 $setting = $default;
850 if (is_array($this->{$variable}) or $this->{$variable} === true) {
851 $setting = $this->{$variable};
852 } else {
853 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
854 if (!isset($parent_config->{$variable})) {
855 continue;
857 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
858 $setting = $parent_config->{$variable};
859 break;
863 return $setting;
867 * Returns the content of the one huge javascript file merged from all theme javascript files.
869 * @param bool $type
870 * @return string
872 public function javascript_content($type) {
873 $jsfiles = $this->javascript_files($type);
874 $js = '';
875 foreach ($jsfiles as $jsfile) {
876 $js .= file_get_contents($jsfile)."\n";
878 return $js;
882 * Post processes CSS.
884 * This method post processes all of the CSS before it is served for this theme.
885 * This is done so that things such as image URL's can be swapped in and to
886 * run any specific CSS post process method the theme has requested.
887 * This allows themes to use CSS settings.
889 * @param string $css The CSS to process.
890 * @return string The processed CSS.
892 public function post_process($css) {
893 // now resolve all image locations
894 if (preg_match_all('/\[\[pix:([a-z_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
895 $replaced = array();
896 foreach ($matches as $match) {
897 if (isset($replaced[$match[0]])) {
898 continue;
900 $replaced[$match[0]] = true;
901 $imagename = $match[2];
902 $component = rtrim($match[1], '|');
903 $imageurl = $this->pix_url($imagename, $component)->out(false);
904 // we do not need full url because the image.php is always in the same dir
905 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
906 $css = str_replace($match[0], $imageurl, $css);
910 // now resolve all theme settings or do any other postprocessing
911 $csspostprocess = $this->csspostprocess;
912 if (function_exists($csspostprocess)) {
913 $css = $csspostprocess($css, $this);
916 return $css;
920 * Return the URL for an image
922 * @param string $imagename the name of the icon.
923 * @param string $component specification of one plugin like in get_string()
924 * @return moodle_url
926 public function pix_url($imagename, $component) {
927 global $CFG;
929 $params = array('theme'=>$this->name);
931 if (empty($component) or $component === 'moodle' or $component === 'core') {
932 $params['component'] = 'core';
933 } else {
934 $params['component'] = $component;
937 $rev = theme_get_revision();
938 if ($rev != -1) {
939 $params['rev'] = $rev;
942 $params['image'] = $imagename;
944 if (!empty($CFG->slasharguments) and $rev > 0) {
945 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
946 $url->set_slashargument('/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'], 'noparam', true);
947 } else {
948 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php", $params);
951 return $url;
955 * Resolves the real image location.
956 * @param string $image name of image, may contain relative path
957 * @param string $component
958 * @return string full file path
960 public function resolve_image_location($image, $component) {
961 global $CFG;
963 if ($component === 'moodle' or $component === 'core' or empty($component)) {
964 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image")) {
965 return $imagefile;
967 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
968 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image")) {
969 return $imagefile;
972 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image")) {
973 return $imagefile;
975 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image")) {
976 return $imagefile;
978 return null;
980 } else if ($component === 'theme') { //exception
981 if ($image === 'favicon') {
982 return "$this->dir/pix/favicon.ico";
984 if ($imagefile = $this->image_exists("$this->dir/pix/$image")) {
985 return $imagefile;
987 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
988 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image")) {
989 return $imagefile;
992 return null;
994 } else {
995 if (strpos($component, '_') === false) {
996 $component = 'mod_'.$component;
998 list($type, $plugin) = explode('_', $component, 2);
1000 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image")) {
1001 return $imagefile;
1003 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1004 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image")) {
1005 return $imagefile;
1008 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image")) {
1009 return $imagefile;
1011 $dir = get_plugin_directory($type, $plugin);
1012 if ($imagefile = $this->image_exists("$dir/pix/$image")) {
1013 return $imagefile;
1015 return null;
1020 * Checks if file with any image extension exists.
1022 * @param string $filepath
1023 * @return string image name with extension
1025 private static function image_exists($filepath) {
1026 if (file_exists("$filepath.gif")) {
1027 return "$filepath.gif";
1028 } else if (file_exists("$filepath.png")) {
1029 return "$filepath.png";
1030 } else if (file_exists("$filepath.jpg")) {
1031 return "$filepath.jpg";
1032 } else if (file_exists("$filepath.jpeg")) {
1033 return "$filepath.jpeg";
1034 } else {
1035 return false;
1040 * Loads the theme config from config.php file.
1042 * @param string $themename
1043 * @param stdClass $settings from config_plugins table
1044 * @return stdClass The theme configuration
1046 private static function find_theme_config($themename, $settings) {
1047 // We have to use the variable name $THEME (upper case) because that
1048 // is what is used in theme config.php files.
1050 if (!$dir = theme_config::find_theme_location($themename)) {
1051 return null;
1054 $THEME = new stdClass();
1055 $THEME->name = $themename;
1056 $THEME->dir = $dir;
1057 $THEME->settings = $settings;
1059 global $CFG; // just in case somebody tries to use $CFG in theme config
1060 include("$THEME->dir/config.php");
1062 // verify the theme configuration is OK
1063 if (!is_array($THEME->parents)) {
1064 // parents option is mandatory now
1065 return null;
1068 return $THEME;
1072 * Finds the theme location and verifies the theme has all needed files
1073 * and is not obsoleted.
1075 * @param string $themename
1076 * @return string full dir path or null if not found
1078 private static function find_theme_location($themename) {
1079 global $CFG;
1081 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1082 $dir = "$CFG->dirroot/theme/$themename";
1084 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1085 $dir = "$CFG->themedir/$themename";
1087 } else {
1088 return null;
1091 if (file_exists("$dir/styles.php")) {
1092 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1093 return null;
1096 return $dir;
1100 * Get the renderer for a part of Moodle for this theme.
1102 * @param moodle_page $page the page we are rendering
1103 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1104 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1105 * @param string $target one of rendering target constants
1106 * @return renderer_base the requested renderer.
1108 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1109 if (is_null($this->rf)) {
1110 $classname = $this->rendererfactory;
1111 $this->rf = new $classname($this);
1114 return $this->rf->get_renderer($page, $component, $subtype, $target);
1118 * Get the information from {@link $layouts} for this type of page.
1120 * @param string $pagelayout the the page layout name.
1121 * @return array the appropriate part of {@link $layouts}.
1123 protected function layout_info_for_page($pagelayout) {
1124 if (array_key_exists($pagelayout, $this->layouts)) {
1125 return $this->layouts[$pagelayout];
1126 } else {
1127 debugging('Invalid page layout specified: ' . $pagelayout);
1128 return $this->layouts['standard'];
1133 * Given the settings of this theme, and the page pagelayout, return the
1134 * full path of the page layout file to use.
1136 * Used by {@link core_renderer::header()}.
1138 * @param string $pagelayout the the page layout name.
1139 * @return string Full path to the lyout file to use
1141 public function layout_file($pagelayout) {
1142 global $CFG;
1144 $layoutinfo = $this->layout_info_for_page($pagelayout);
1145 $layoutfile = $layoutinfo['file'];
1147 if (array_key_exists('theme', $layoutinfo)) {
1148 $themes = array($layoutinfo['theme']);
1149 } else {
1150 $themes = array_merge(array($this->name),$this->parents);
1153 foreach ($themes as $theme) {
1154 if ($dir = $this->find_theme_location($theme)) {
1155 $path = "$dir/layout/$layoutfile";
1157 // Check the template exists, return general base theme template if not.
1158 if (is_readable($path)) {
1159 return $path;
1164 debugging('Can not find layout file for: ' . $pagelayout);
1165 // fallback to standard normal layout
1166 return "$CFG->dirroot/theme/base/layout/general.php";
1170 * Returns auxiliary page layout options specified in layout configuration array.
1172 * @param string $pagelayout
1173 * @return array
1175 public function pagelayout_options($pagelayout) {
1176 $info = $this->layout_info_for_page($pagelayout);
1177 if (!empty($info['options'])) {
1178 return $info['options'];
1180 return array();
1184 * Inform a block_manager about the block regions this theme wants on this
1185 * page layout.
1187 * @param string $pagelayout the general type of the page.
1188 * @param block_manager $blockmanager the block_manger to set up.
1190 public function setup_blocks($pagelayout, $blockmanager) {
1191 $layoutinfo = $this->layout_info_for_page($pagelayout);
1192 if (!empty($layoutinfo['regions'])) {
1193 $blockmanager->add_regions($layoutinfo['regions']);
1194 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1199 * Gets the visible name for the requested block region.
1201 * @param string $region The region name to get
1202 * @param string $theme The theme the region belongs to (may come from the parent theme)
1203 * @return string
1205 protected function get_region_name($region, $theme) {
1206 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1207 // A name exists in this theme, so use it
1208 if (substr($regionstring, 0, 1) != '[') {
1209 return $regionstring;
1212 // Otherwise, try to find one elsewhere
1213 // Check parents, if any
1214 foreach ($this->parents as $parentthemename) {
1215 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1216 if (substr($regionstring, 0, 1) != '[') {
1217 return $regionstring;
1221 // Last resort, try the base theme for names
1222 return get_string('region-' . $region, 'theme_base');
1226 * Get the list of all block regions known to this theme in all templates.
1228 * @return array internal region name => human readable name.
1230 public function get_all_block_regions() {
1231 $regions = array();
1232 foreach ($this->layouts as $layoutinfo) {
1233 foreach ($layoutinfo['regions'] as $region) {
1234 $regions[$region] = $this->get_region_name($region, $this->name);
1237 return $regions;
1241 * Returns the human readable name of the theme
1243 * @return string
1245 public function get_theme_name() {
1246 return get_string('pluginname', 'theme_'.$this->name);
1251 * This class keeps track of which HTML tags are currently open.
1253 * This makes it much easier to always generate well formed XHTML output, even
1254 * if execution terminates abruptly. Any time you output some opening HTML
1255 * without the matching closing HTML, you should push the necessary close tags
1256 * onto the stack.
1258 * @copyright 2009 Tim Hunt
1259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1260 * @since Moodle 2.0
1261 * @package core
1262 * @category output
1264 class xhtml_container_stack {
1267 * @var array Stores the list of open containers.
1269 protected $opencontainers = array();
1272 * @var array In developer debug mode, stores a stack trace of all opens and
1273 * closes, so we can output helpful error messages when there is a mismatch.
1275 protected $log = array();
1278 * @var boolean Store whether we are developer debug mode. We need this in
1279 * several places including in the destructor where we may not have access to $CFG.
1281 protected $isdebugging;
1284 * Constructor
1286 public function __construct() {
1287 $this->isdebugging = debugging('', DEBUG_DEVELOPER);
1291 * Push the close HTML for a recently opened container onto the stack.
1293 * @param string $type The type of container. This is checked when {@link pop()}
1294 * is called and must match, otherwise a developer debug warning is output.
1295 * @param string $closehtml The HTML required to close the container.
1297 public function push($type, $closehtml) {
1298 $container = new stdClass;
1299 $container->type = $type;
1300 $container->closehtml = $closehtml;
1301 if ($this->isdebugging) {
1302 $this->log('Open', $type);
1304 array_push($this->opencontainers, $container);
1308 * Pop the HTML for the next closing container from the stack. The $type
1309 * must match the type passed when the container was opened, otherwise a
1310 * warning will be output.
1312 * @param string $type The type of container.
1313 * @return string the HTML required to close the container.
1315 public function pop($type) {
1316 if (empty($this->opencontainers)) {
1317 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1318 $this->output_log(), DEBUG_DEVELOPER);
1319 return;
1322 $container = array_pop($this->opencontainers);
1323 if ($container->type != $type) {
1324 debugging('<p>The type of container to be closed (' . $container->type .
1325 ') does not match the type of the next open container (' . $type .
1326 '). This suggests there is a nesting problem.</p>' .
1327 $this->output_log(), DEBUG_DEVELOPER);
1329 if ($this->isdebugging) {
1330 $this->log('Close', $type);
1332 return $container->closehtml;
1336 * Close all but the last open container. This is useful in places like error
1337 * handling, where you want to close all the open containers (apart from <body>)
1338 * before outputting the error message.
1340 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1341 * developer debug warning if it isn't.
1342 * @return string the HTML required to close any open containers inside <body>.
1344 public function pop_all_but_last($shouldbenone = false) {
1345 if ($shouldbenone && count($this->opencontainers) != 1) {
1346 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1347 $this->output_log(), DEBUG_DEVELOPER);
1349 $output = '';
1350 while (count($this->opencontainers) > 1) {
1351 $container = array_pop($this->opencontainers);
1352 $output .= $container->closehtml;
1354 return $output;
1358 * You can call this function if you want to throw away an instance of this
1359 * class without properly emptying the stack (for example, in a unit test).
1360 * Calling this method stops the destruct method from outputting a developer
1361 * debug warning. After calling this method, the instance can no longer be used.
1363 public function discard() {
1364 $this->opencontainers = null;
1368 * Adds an entry to the log.
1370 * @param string $action The name of the action
1371 * @param string $type The type of action
1373 protected function log($action, $type) {
1374 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1375 format_backtrace(debug_backtrace()) . '</li>';
1379 * Outputs the log's contents as a HTML list.
1381 * @return string HTML list of the log
1383 protected function output_log() {
1384 return '<ul>' . implode("\n", $this->log) . '</ul>';