Merge branch 'm22_MDL-33053_AICC_flattened_TOC' of git://github.com/scara/moodle...
[moodle.git] / lib / outputlib.php
blob285085e78eb235572d42923e6b47c10610210396
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Functions for generating the HTML that Moodle should output.
21 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
22 * for an overview.
24 * @package core
25 * @subpackage lib
26 * @copyright 2009 Tim Hunt
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 defined('MOODLE_INTERNAL') || die();
32 require_once($CFG->libdir.'/outputcomponents.php');
33 require_once($CFG->libdir.'/outputactions.php');
34 require_once($CFG->libdir.'/outputfactories.php');
35 require_once($CFG->libdir.'/outputrenderers.php');
36 require_once($CFG->libdir.'/outputrequirementslib.php');
38 /**
39 * Invalidate all server and client side caches.
40 * @return void
42 function theme_reset_all_caches() {
43 global $CFG;
44 require_once("$CFG->libdir/filelib.php");
46 set_config('themerev', empty($CFG->themerev) ? 1 : $CFG->themerev+1);
47 fulldelete("$CFG->cachedir/theme");
50 /**
51 * Enable or disable theme designer mode.
52 * @param bool $state
53 * @return void
55 function theme_set_designer_mod($state) {
56 theme_reset_all_caches();
57 set_config('themedesignermode', (int)!empty($state));
60 /**
61 * Returns current theme revision number.
62 * @return int
64 function theme_get_revision() {
65 global $CFG;
67 if (empty($CFG->themedesignermode)) {
68 if (empty($CFG->themerev)) {
69 return -1;
70 } else {
71 return $CFG->themerev;
74 } else {
75 return -1;
80 /**
81 * This class represents the configuration variables of a Moodle theme.
83 * All the variables with access: public below (with a few exceptions that are marked)
84 * are the properties you can set in your theme's config.php file.
86 * There are also some methods and protected variables that are part of the inner
87 * workings of Moodle's themes system. If you are just editing a theme's config.php
88 * file, you can just ignore those, and the following information for developers.
90 * Normally, to create an instance of this class, you should use the
91 * {@link theme_config::load()} factory method to load a themes config.php file.
92 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
93 * will create one for you, accessible as $PAGE->theme.
95 * @copyright 2009 Tim Hunt
96 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
97 * @since Moodle 2.0
99 class theme_config {
101 * @var string default theme, used when requested theme not found
103 const DEFAULT_THEME = 'standard';
106 * You can base your theme on other themes by linking to the other theme as
107 * parents. This lets you use the CSS and layouts from the other themes
108 * (see {@link $layouts}).
109 * That makes it easy to create a new theme that is similar to another one
110 * but with a few changes. In this theme's CSS you only need to override
111 * those rules you want to change.
113 * @var array
115 public $parents;
118 * The names of all the stylesheets from this theme that you would
119 * like included, in order. Give the names of the files without .css.
121 * @var array
123 public $sheets = array();
126 * The names of all the stylesheets from parents that should be excluded.
127 * true value may be used to specify all parents or all themes from one parent.
128 * If no value specified value from parent theme used.
130 * @var array or arrays, true means all, null means use value from parent
132 public $parents_exclude_sheets = null;
135 * List of plugin sheets to be excluded.
136 * If no value specified value from parent theme used.
138 * @var array of full plugin names, null means use value from parent
140 public $plugins_exclude_sheets = null;
143 * List of style sheets that are included in the text editor bodies.
144 * Sheets from parent themes are used automatically and can not be excluded.
146 * @var array
148 public $editor_sheets = array();
151 * The names of all the javascript files this theme that you would
152 * like included from head, in order. Give the names of the files without .js.
154 * @var array
156 public $javascripts = array();
159 * The names of all the javascript files this theme that you would
160 * like included from footer, in order. Give the names of the files without .js.
162 * @var array
164 public $javascripts_footer = array();
167 * The names of all the javascript files from parents that should be excluded.
168 * true value may be used to specify all parents or all themes from one parent.
169 * If no value specified value from parent theme used.
171 * @var array or arrays, true means all, null means use value from parent
173 public $parents_exclude_javascripts = null;
176 * 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 * @var array
225 public $layouts = array();
228 * Name of the renderer factory class to use.
230 * This is an advanced feature. Moodle output is generated by 'renderers',
231 * you can customise the HTML that is output by writing custom renderers,
232 * and then you need to specify 'renderer factory' so that Moodle can find
233 * your renderers.
235 * There are some renderer factories supplied with Moodle. Please follow these
236 * links to see what they do.
237 * <ul>
238 * <li>{@link standard_renderer_factory} - the default.</li>
239 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
240 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
241 * </ul>
243 * @var string name of a class implementing the {@link renderer_factory} interface.
245 public $rendererfactory = 'standard_renderer_factory';
248 * Function to do custom CSS post-processing.
250 * This is an advanced feature. If you want to do custom post-processing on the
251 * CSS before it is output (for example, to replace certain variable names
252 * with particular values) you can give the name of a function here.
254 * @var string the name of a function.
256 public $csspostprocess = null;
259 * Accessibility: Right arrow-like character is
260 * used in the breadcrumb trail, course navigation menu
261 * (previous/next activity), calendar, and search forum block.
262 * If the theme does not set characters, appropriate defaults
263 * are set automatically. Please DO NOT
264 * use &lt; &gt; &raquo; - these are confusing for blind users.
266 * @var string
268 public $rarrow = null;
271 * Accessibility: Right arrow-like character is
272 * used in the breadcrumb trail, course navigation menu
273 * (previous/next activity), calendar, and search forum block.
274 * If the theme does not set characters, appropriate defaults
275 * are set automatically. Please DO NOT
276 * use &lt; &gt; &raquo; - these are confusing for blind users.
278 * @var string
280 public $larrow = null;
283 * Some themes may want to disable ajax course editing.
284 * @var bool
286 public $enablecourseajax = true;
288 //==Following properties are not configurable from theme config.php==
291 * The name of this theme. Set automatically when this theme is
292 * loaded. This can not be set in theme config.php
293 * @var string
295 public $name;
298 * the folder where this themes files are stored. This is set
299 * automatically. This can not be set in theme config.php
300 * @var string
302 public $dir;
305 * Theme settings stored in config_plugins table.
306 * This can not be set in theme config.php
307 * @var object
309 public $setting = null;
312 * If set to true and the theme enables the dock then blocks will be able
313 * to be moved to the special dock
314 * @var bool
316 public $enable_dock = false;
319 * If set to true then this theme will not be shown in the theme selector unless
320 * theme designer mode is turned on.
321 * @var bool
323 public $hidefromselector = false;
326 * Instance of the renderer_factory implementation
327 * we are using. Implementation detail.
328 * @var renderer_factory
330 protected $rf = null;
333 * List of parent config objects.
334 * @var array list of parent configs
336 protected $parent_configs = array();
339 * Load the config.php file for a particular theme, and return an instance
340 * of this class. (That is, this is a factory method.)
342 * @param string $themename the name of the theme.
343 * @return theme_config an instance of this class.
345 public static function load($themename) {
346 global $CFG;
348 // load theme settings from db
349 try {
350 $settings = get_config('theme_'.$themename);
351 } catch (dml_exception $e) {
352 // most probably moodle tables not created yet
353 $settings = new stdClass();
356 if ($config = theme_config::find_theme_config($themename, $settings)) {
357 return new theme_config($config);
359 } else if ($themename == theme_config::DEFAULT_THEME) {
360 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
362 } else {
363 // bad luck, the requested theme has some problems - admin see details in theme config
364 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
369 * Theme diagnostic code. It is very problematic to send debug output
370 * to the actual CSS file, instead this functions is supposed to
371 * diagnose given theme and highlights all potential problems.
372 * This information should be available from the theme selection page
373 * or some other debug page for theme designers.
375 * @param string $themename
376 * @return array description of problems
378 public static function diagnose($themename) {
379 //TODO: MDL-21108
380 return array();
384 * Private constructor, can be called only from the factory method.
385 * @param stdClass $config
387 private function __construct($config) {
388 global $CFG; //needed for included lib.php files
390 $this->settings = $config->settings;
391 $this->name = $config->name;
392 $this->dir = $config->dir;
394 if ($this->name != 'base') {
395 $baseconfig = theme_config::find_theme_config('base', $this->settings);
396 } else {
397 $baseconfig = $config;
400 $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer',
401 'parents_exclude_javascripts', 'layouts', 'enable_dock', 'enablecourseajax',
402 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector');
404 foreach ($config as $key=>$value) {
405 if (in_array($key, $configurable)) {
406 $this->$key = $value;
410 // verify all parents and load configs and renderers
411 foreach ($this->parents as $parent) {
412 if ($parent == 'base') {
413 $parent_config = $baseconfig;
414 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
415 // this is not good - better exclude faulty parents
416 continue;
418 $libfile = $parent_config->dir.'/lib.php';
419 if (is_readable($libfile)) {
420 // theme may store various function here
421 include_once($libfile);
423 $renderersfile = $parent_config->dir.'/renderers.php';
424 if (is_readable($renderersfile)) {
425 // may contain core and plugin renderers and renderer factory
426 include_once($renderersfile);
428 $this->parent_configs[$parent] = $parent_config;
429 $rendererfile = $parent_config->dir.'/renderers.php';
430 if (is_readable($rendererfile)) {
431 // may contain core and plugin renderers and renderer factory
432 include_once($rendererfile);
435 $libfile = $this->dir.'/lib.php';
436 if (is_readable($libfile)) {
437 // theme may store various function here
438 include_once($libfile);
440 $rendererfile = $this->dir.'/renderers.php';
441 if (is_readable($rendererfile)) {
442 // may contain core and plugin renderers and renderer factory
443 include_once($rendererfile);
444 } else {
445 // check if renderers.php file is missnamed renderer.php
446 if (is_readable($this->dir.'/renderer.php')) {
447 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
448 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
452 // cascade all layouts properly
453 foreach ($baseconfig->layouts as $layout=>$value) {
454 if (!isset($this->layouts[$layout])) {
455 foreach ($this->parent_configs as $parent_config) {
456 if (isset($parent_config->layouts[$layout])) {
457 $this->layouts[$layout] = $parent_config->layouts[$layout];
458 continue 2;
461 $this->layouts[$layout] = $value;
465 //fix arrows if needed
466 $this->check_theme_arrows();
470 * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
471 * If not it applies sensible defaults.
473 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
474 * search forum block, etc. Important: these are 'silent' in a screen-reader
475 * (unlike &gt; &raquo;), and must be accompanied by text.
477 private function check_theme_arrows() {
478 if (!isset($this->rarrow) and !isset($this->larrow)) {
479 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
480 // Also OK in Win 9x/2K/IE 5.x
481 $this->rarrow = '&#x25BA;';
482 $this->larrow = '&#x25C4;';
483 if (empty($_SERVER['HTTP_USER_AGENT'])) {
484 $uagent = '';
485 } else {
486 $uagent = $_SERVER['HTTP_USER_AGENT'];
488 if (false !== strpos($uagent, 'Opera')
489 || false !== strpos($uagent, 'Mac')) {
490 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
491 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
492 $this->rarrow = '&#x25B6;';
493 $this->larrow = '&#x25C0;';
495 elseif (false !== strpos($uagent, 'Konqueror')) {
496 $this->rarrow = '&rarr;';
497 $this->larrow = '&larr;';
499 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
500 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
501 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
502 // To be safe, non-Unicode browsers!
503 $this->rarrow = '&gt;';
504 $this->larrow = '&lt;';
507 /// RTL support - in RTL languages, swap r and l arrows
508 if (right_to_left()) {
509 $t = $this->rarrow;
510 $this->rarrow = $this->larrow;
511 $this->larrow = $t;
517 * Returns output renderer prefixes, these are used when looking
518 * for the overridden renderers in themes.
519 * @return array
521 public function renderer_prefixes() {
522 global $CFG; // just in case the included files need it
524 $prefixes = array('theme_'.$this->name);
526 foreach ($this->parent_configs as $parent) {
527 $prefixes[] = 'theme_'.$parent->name;
530 return $prefixes;
534 * Returns the stylesheet URL of this editor content
535 * @param bool $encoded false means use & and true use &amp; in URLs
536 * @return string
538 public function editor_css_url($encoded=true) {
539 global $CFG;
541 $rev = theme_get_revision();
543 if ($rev > -1) {
544 $params = array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor');
545 return new moodle_url($CFG->httpswwwroot.'/theme/styles.php', $params);
546 } else {
547 $params = array('theme'=>$this->name, 'type'=>'editor');
548 return new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
553 * 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
596 * @param bool $encoded false means use & and true use &amp; in URLs
597 * @return array of moodle_url
599 public function css_urls(moodle_page $page) {
600 global $CFG;
602 $rev = theme_get_revision();
604 $urls = array();
606 if ($rev > -1) {
607 if (check_browser_version('MSIE', 5)) {
608 // We need to split the CSS files for IE
609 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'plugins'));
610 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'parents'));
611 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'theme'));
612 } else {
613 $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev));
615 } else {
616 // find out the current CSS and cache it now for 5 seconds
617 // the point is to construct the CSS only once and pass it through the
618 // dataroot to the script that actually serves the sheets
619 if (!defined('THEME_DESIGNER_CACHE_LIFETIME')) {
620 define('THEME_DESIGNER_CACHE_LIFETIME', 4); // this can be also set in config.php
622 $candidatesheet = "$CFG->cachedir/theme/$this->name/designer.ser";
623 if (!file_exists($candidatesheet)) {
624 $css = $this->css_content();
625 check_dir_exists(dirname($candidatesheet));
626 file_put_contents($candidatesheet, serialize($css));
628 } else if (filemtime($candidatesheet) > time() - THEME_DESIGNER_CACHE_LIFETIME) {
629 if ($css = file_get_contents($candidatesheet)) {
630 $css = unserialize($css);
631 } else {
632 unlink($candidatesheet);
633 $css = $this->css_content();
636 } else {
637 unlink($candidatesheet);
638 $css = $this->css_content();
639 file_put_contents($candidatesheet, serialize($css));
642 $baseurl = $CFG->httpswwwroot.'/theme/styles_debug.php';
644 if (check_browser_version('MSIE', 5)) {
645 // lalala, IE does not allow more than 31 linked CSS files from main document
646 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
647 foreach ($css['parents'] as $parent=>$sheets) {
648 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096)
649 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
651 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
653 } else {
654 foreach ($css['plugins'] as $plugin=>$unused) {
655 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
657 foreach ($css['parents'] as $parent=>$sheets) {
658 foreach ($sheets as $sheet=>$unused2) {
659 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
662 foreach ($css['theme'] as $sheet=>$unused) {
663 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); // sheet first in order to make long urls easier to read
668 return $urls;
672 * Returns an array of organised CSS files required for this output
673 * @return array
675 public function css_files() {
676 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
678 // get all plugin sheets
679 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
680 if ($excludes !== true) {
681 foreach (get_plugin_types() as $type=>$unused) {
682 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
683 continue;
685 $plugins = get_plugin_list($type);
686 foreach ($plugins as $plugin=>$fulldir) {
687 if (!empty($excludes[$type]) and is_array($excludes[$type])
688 and in_array($plugin, $excludes[$type])) {
689 continue;
692 $plugincontent = '';
693 $sheetfile = "$fulldir/styles.css";
694 if (is_readable($sheetfile)) {
695 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
697 $sheetthemefile = "$fulldir/styles_{$this->name}.css";
698 if (is_readable($sheetthemefile)) {
699 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$this->name] = $sheetthemefile;
705 // find out wanted parent sheets
706 $excludes = $this->resolve_excludes('parents_exclude_sheets');
707 if ($excludes !== true) {
708 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
709 $parent = $parent_config->name;
710 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
711 continue;
713 foreach ($parent_config->sheets as $sheet) {
714 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
715 and in_array($sheet, $excludes[$parent])) {
716 continue;
718 $sheetfile = "$parent_config->dir/style/$sheet.css";
719 if (is_readable($sheetfile)) {
720 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
726 // current theme sheets
727 if (is_array($this->sheets)) {
728 foreach ($this->sheets as $sheet) {
729 $sheetfile = "$this->dir/style/$sheet.css";
730 if (is_readable($sheetfile)) {
731 $cssfiles['theme'][$sheet] = $sheetfile;
736 return $cssfiles;
740 * Returns the content of the one huge CSS merged from all style sheets.
741 * @return string
743 public function css_content() {
744 $files = array_merge($this->css_files(), array('editor'=>$this->editor_css_files()));
745 $css = $this->css_files_get_contents($files, array());
746 return $css;
750 * Given an array of file paths or a single file path loads the contents of
751 * the CSS file, processes it then returns it in the same structure it was given.
753 * Can be used recursively on the results of {@see css_files}
755 * @param array|string $file An array of file paths or a single file path
756 * @param array $keys An array of previous array keys [recursive addition]
757 * @return The converted array or the contents of the single file ($file type)
759 protected function css_files_get_contents($file, array $keys) {
760 if (is_array($file)) {
761 foreach ($file as $key=>$f) {
762 $file[$key] = $this->css_files_get_contents($f, array_merge($keys, array($key)));
764 return $file;
765 } else {
766 $comment = '/** Path: '.implode(' ', $keys).' **/'."\n";
767 return $comment.$this->post_process(file_get_contents($file));
773 * Get the javascript URL of this theme
774 * @param bool $inhead true means head url, false means footer
775 * @return moodle_url
777 public function javascript_url($inhead) {
778 global $CFG;
780 $rev = theme_get_revision();
781 $params = array('theme'=>$this->name,'rev'=>$rev);
782 $params['type'] = $inhead ? 'head' : 'footer';
784 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
787 public function javascript_files($type) {
788 if ($type === 'footer') {
789 $type = 'javascripts_footer';
790 } else {
791 $type = 'javascripts';
794 $js = array();
795 // find out wanted parent javascripts
796 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
797 if ($excludes !== true) {
798 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
799 $parent = $parent_config->name;
800 if (empty($parent_config->$type)) {
801 continue;
803 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
804 continue;
806 foreach ($parent_config->$type as $javascript) {
807 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
808 and in_array($javascript, $excludes[$parent])) {
809 continue;
811 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
812 if (is_readable($javascriptfile)) {
813 $js[] = $javascriptfile;
819 // current theme javascripts
820 if (is_array($this->$type)) {
821 foreach ($this->$type as $javascript) {
822 $javascriptfile = "$this->dir/javascript/$javascript.js";
823 if (is_readable($javascriptfile)) {
824 $js[] = $javascriptfile;
829 return $js;
833 * Resolves an exclude setting to the theme's setting is applicable or the
834 * setting of its closest parent.
836 * @param string $variable The name of the setting the exclude setting to resolve
837 * @return mixed
839 protected function resolve_excludes($variable, $default=null) {
840 $setting = $default;
841 if (is_array($this->{$variable}) or $this->{$variable} === true) {
842 $setting = $this->{$variable};
843 } else {
844 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
845 if (!isset($parent_config->{$variable})) {
846 continue;
848 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
849 $setting = $parent_config->{$variable};
850 break;
854 return $setting;
858 * Returns the content of the one huge javascript file merged from all theme javascript files.
859 * @param bool $inhead
860 * @return string
862 public function javascript_content($type) {
863 $jsfiles = $this->javascript_files($type);
864 $js = '';
865 foreach ($jsfiles as $jsfile) {
866 $js .= file_get_contents($jsfile)."\n";
868 return $js;
871 public function post_process($css) {
872 global $CFG;
874 // now resolve all image locations
875 if (preg_match_all('/\[\[pix:([a-z_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
876 $replaced = array();
877 foreach ($matches as $match) {
878 if (isset($replaced[$match[0]])) {
879 continue;
881 $replaced[$match[0]] = true;
882 $imagename = $match[2];
883 $component = rtrim($match[1], '|');
884 $imageurl = $this->pix_url($imagename, $component)->out(false);
885 // we do not need full url because the image.php is always in the same dir
886 $imageurl = str_replace("$CFG->httpswwwroot/theme/", '', $imageurl);
887 $css = str_replace($match[0], $imageurl, $css);
891 // now resolve all theme settings or do any other postprocessing
892 $csspostprocess = $this->csspostprocess;
893 if (function_exists($csspostprocess)) {
894 $css = $csspostprocess($css, $this);
897 return $css;
901 * Return the URL for an image
903 * @param string $imagename the name of the icon.
904 * @param string $component, specification of one plugin like in get_string()
905 * @return moodle_url
907 public function pix_url($imagename, $component) {
908 global $CFG;
910 $params = array('theme'=>$this->name, 'image'=>$imagename);
912 $rev = theme_get_revision();
913 if ($rev != -1) {
914 $params['rev'] = $rev;
916 if (!empty($component) and $component !== 'moodle'and $component !== 'core') {
917 $params['component'] = $component;
920 return new moodle_url("$CFG->httpswwwroot/theme/image.php", $params);
924 * Resolves the real image location.
925 * @param string $image name of image, may contain relative path
926 * @param string $component
927 * @return string full file path
929 public function resolve_image_location($image, $component) {
930 global $CFG;
932 if ($component === 'moodle' or $component === 'core' or empty($component)) {
933 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image")) {
934 return $imagefile;
936 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
937 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image")) {
938 return $imagefile;
941 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image")) {
942 return $imagefile;
944 return null;
946 } else if ($component === 'theme') { //exception
947 if ($image === 'favicon') {
948 return "$this->dir/pix/favicon.ico";
950 if ($imagefile = $this->image_exists("$this->dir/pix/$image")) {
951 return $imagefile;
953 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
954 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image")) {
955 return $imagefile;
958 return null;
960 } else {
961 if (strpos($component, '_') === false) {
962 $component = 'mod_'.$component;
964 list($type, $plugin) = explode('_', $component, 2);
966 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image")) {
967 return $imagefile;
969 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
970 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image")) {
971 return $imagefile;
974 $dir = get_plugin_directory($type, $plugin);
975 if ($imagefile = $this->image_exists("$dir/pix/$image")) {
976 return $imagefile;
978 return null;
983 * Checks if file with any image extension exists.
984 * @param string $filepath
985 * @return string image name with extension
987 private static function image_exists($filepath) {
988 if (file_exists("$filepath.gif")) {
989 return "$filepath.gif";
990 } else if (file_exists("$filepath.png")) {
991 return "$filepath.png";
992 } else if (file_exists("$filepath.jpg")) {
993 return "$filepath.jpg";
994 } else if (file_exists("$filepath.jpeg")) {
995 return "$filepath.jpeg";
996 } else {
997 return false;
1002 * Loads the theme config from config.php file.
1003 * @param string $themename
1004 * @param object $settings from config_plugins table
1005 * @return object
1007 private static function find_theme_config($themename, $settings) {
1008 // We have to use the variable name $THEME (upper case) because that
1009 // is what is used in theme config.php files.
1011 if (!$dir = theme_config::find_theme_location($themename)) {
1012 return null;
1015 $THEME = new stdClass();
1016 $THEME->name = $themename;
1017 $THEME->dir = $dir;
1018 $THEME->settings = $settings;
1020 global $CFG; // just in case somebody tries to use $CFG in theme config
1021 include("$THEME->dir/config.php");
1023 // verify the theme configuration is OK
1024 if (!is_array($THEME->parents)) {
1025 // parents option is mandatory now
1026 return null;
1029 return $THEME;
1033 * Finds the theme location and verifies the theme has all needed files
1034 * 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.
1061 * @param moodle_page $page the page we are rendering
1062 * @param string $module the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1063 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1064 * @param string $target one of rendering target constants
1065 * @return renderer_base the requested renderer.
1067 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1068 if (is_null($this->rf)) {
1069 $classname = $this->rendererfactory;
1070 $this->rf = new $classname($this);
1073 return $this->rf->get_renderer($page, $component, $subtype, $target);
1077 * Get the information from {@link $layouts} for this type of page.
1078 * @param string $pagelayout the the page layout name.
1079 * @return array the appropriate part of {@link $layouts}.
1081 protected function layout_info_for_page($pagelayout) {
1082 if (array_key_exists($pagelayout, $this->layouts)) {
1083 return $this->layouts[$pagelayout];
1084 } else {
1085 debugging('Invalid page layout specified: ' . $pagelayout);
1086 return $this->layouts['standard'];
1091 * Given the settings of this theme, and the page pagelayout, return the
1092 * full path of the page layout file to use.
1094 * Used by {@link core_renderer::header()}.
1096 * @param string $pagelayout the the page layout name.
1097 * @return string Full path to the lyout file to use
1099 public function layout_file($pagelayout) {
1100 global $CFG;
1102 $layoutinfo = $this->layout_info_for_page($pagelayout);
1103 $layoutfile = $layoutinfo['file'];
1105 if (array_key_exists('theme', $layoutinfo)) {
1106 $themes = array($layoutinfo['theme']);
1107 } else {
1108 $themes = array_merge(array($this->name),$this->parents);
1111 foreach ($themes as $theme) {
1112 if ($dir = $this->find_theme_location($theme)) {
1113 $path = "$dir/layout/$layoutfile";
1115 // Check the template exists, return general base theme template if not.
1116 if (is_readable($path)) {
1117 return $path;
1122 debugging('Can not find layout file for: ' . $pagelayout);
1123 // fallback to standard normal layout
1124 return "$CFG->dirroot/theme/base/layout/general.php";
1128 * Returns auxiliary page layout options specified in layout configuration array.
1129 * @param string $pagelayout
1130 * @return array
1132 public function pagelayout_options($pagelayout) {
1133 $info = $this->layout_info_for_page($pagelayout);
1134 if (!empty($info['options'])) {
1135 return $info['options'];
1137 return array();
1141 * Inform a block_manager about the block regions this theme wants on this
1142 * page layout.
1143 * @param string $pagelayout the general type of the page.
1144 * @param block_manager $blockmanager the block_manger to set up.
1145 * @return void
1147 public function setup_blocks($pagelayout, $blockmanager) {
1148 $layoutinfo = $this->layout_info_for_page($pagelayout);
1149 if (!empty($layoutinfo['regions'])) {
1150 $blockmanager->add_regions($layoutinfo['regions']);
1151 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1155 protected function get_region_name($region, $theme) {
1156 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1157 // A name exists in this theme, so use it
1158 if (substr($regionstring, 0, 1) != '[') {
1159 return $regionstring;
1162 // Otherwise, try to find one elsewhere
1163 // Check parents, if any
1164 foreach ($this->parents as $parentthemename) {
1165 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1166 if (substr($regionstring, 0, 1) != '[') {
1167 return $regionstring;
1171 // Last resort, try the base theme for names
1172 return get_string('region-' . $region, 'theme_base');
1176 * Get the list of all block regions known to this theme in all templates.
1177 * @return array internal region name => human readable name.
1179 public function get_all_block_regions() {
1180 $regions = array();
1181 foreach ($this->layouts as $layoutinfo) {
1182 foreach ($layoutinfo['regions'] as $region) {
1183 $regions[$region] = $this->get_region_name($region, $this->name);
1186 return $regions;
1190 * Returns the human readable name of the theme
1192 * @return string
1194 public function get_theme_name() {
1195 return get_string('pluginname', 'theme_'.$this->name);
1201 * This class keeps track of which HTML tags are currently open.
1203 * This makes it much easier to always generate well formed XHTML output, even
1204 * if execution terminates abruptly. Any time you output some opening HTML
1205 * without the matching closing HTML, you should push the necessary close tags
1206 * onto the stack.
1208 * @copyright 2009 Tim Hunt
1209 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1210 * @since Moodle 2.0
1212 class xhtml_container_stack {
1213 /** @var array stores the list of open containers. */
1214 protected $opencontainers = array();
1216 * @var array in developer debug mode, stores a stack trace of all opens and
1217 * closes, so we can output helpful error messages when there is a mismatch.
1219 protected $log = array();
1221 * Store whether we are developer debug mode. We need this in several places
1222 * including in the destructor where we may not have access to $CFG.
1223 * @var boolean
1225 protected $isdebugging;
1227 public function __construct() {
1228 $this->isdebugging = debugging('', DEBUG_DEVELOPER);
1232 * Push the close HTML for a recently opened container onto the stack.
1233 * @param string $type The type of container. This is checked when {@link pop()}
1234 * is called and must match, otherwise a developer debug warning is output.
1235 * @param string $closehtml The HTML required to close the container.
1236 * @return void
1238 public function push($type, $closehtml) {
1239 $container = new stdClass;
1240 $container->type = $type;
1241 $container->closehtml = $closehtml;
1242 if ($this->isdebugging) {
1243 $this->log('Open', $type);
1245 array_push($this->opencontainers, $container);
1249 * Pop the HTML for the next closing container from the stack. The $type
1250 * must match the type passed when the container was opened, otherwise a
1251 * warning will be output.
1252 * @param string $type The type of container.
1253 * @return string the HTML required to close the container.
1255 public function pop($type) {
1256 if (empty($this->opencontainers)) {
1257 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1258 $this->output_log(), DEBUG_DEVELOPER);
1259 return;
1262 $container = array_pop($this->opencontainers);
1263 if ($container->type != $type) {
1264 debugging('<p>The type of container to be closed (' . $container->type .
1265 ') does not match the type of the next open container (' . $type .
1266 '). This suggests there is a nesting problem.</p>' .
1267 $this->output_log(), DEBUG_DEVELOPER);
1269 if ($this->isdebugging) {
1270 $this->log('Close', $type);
1272 return $container->closehtml;
1276 * Close all but the last open container. This is useful in places like error
1277 * handling, where you want to close all the open containers (apart from <body>)
1278 * before outputting the error message.
1279 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1280 * developer debug warning if it isn't.
1281 * @return string the HTML required to close any open containers inside <body>.
1283 public function pop_all_but_last($shouldbenone = false) {
1284 if ($shouldbenone && count($this->opencontainers) != 1) {
1285 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1286 $this->output_log(), DEBUG_DEVELOPER);
1288 $output = '';
1289 while (count($this->opencontainers) > 1) {
1290 $container = array_pop($this->opencontainers);
1291 $output .= $container->closehtml;
1293 return $output;
1297 * You can call this function if you want to throw away an instance of this
1298 * class without properly emptying the stack (for example, in a unit test).
1299 * Calling this method stops the destruct method from outputting a developer
1300 * debug warning. After calling this method, the instance can no longer be used.
1301 * @return void
1303 public function discard() {
1304 $this->opencontainers = null;
1308 * Adds an entry to the log.
1309 * @param string $action The name of the action
1310 * @param string $type The type of action
1311 * @return void
1313 protected function log($action, $type) {
1314 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1315 format_backtrace(debug_backtrace()) . '</li>';
1319 * Outputs the log's contents as a HTML list.
1320 * @return string HTML list of the log
1322 protected function output_log() {
1323 return '<ul>' . implode("\n", $this->log) . '</ul>';