Merge branch '43675-27' of git://github.com/samhemelryk/moodle
[moodle.git] / lib / outputlib.php
blob04c6988dd2561f99ccb263f3c7ed4b0f1775d7a9
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions for generating the HTML that Moodle should output.
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
21 * for an overview.
23 * @copyright 2009 Tim Hunt
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * @package core
26 * @category output
29 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->libdir.'/outputcomponents.php');
32 require_once($CFG->libdir.'/outputactions.php');
33 require_once($CFG->libdir.'/outputfactories.php');
34 require_once($CFG->libdir.'/outputrenderers.php');
35 require_once($CFG->libdir.'/outputrequirementslib.php');
37 /**
38 * Invalidate all server and client side caches.
40 * This method deletes the physical directory that is used to cache the theme
41 * files used for serving.
42 * Because it deletes the main theme cache directory all themes are reset by
43 * this function.
45 function theme_reset_all_caches() {
46 global $CFG, $PAGE;
48 $next = time();
49 if (isset($CFG->themerev) and $next <= $CFG->themerev and $CFG->themerev - $next < 60*60) {
50 // This resolves problems when reset is requested repeatedly within 1s,
51 // the < 1h condition prevents accidental switching to future dates
52 // because we might not recover from it.
53 $next = $CFG->themerev+1;
56 set_config('themerev', $next); // time is unique even when you reset/switch database
58 if ($PAGE) {
59 $PAGE->reload_theme();
63 /**
64 * Enable or disable theme designer mode.
66 * @param bool $state
68 function theme_set_designer_mod($state) {
69 theme_reset_all_caches();
70 set_config('themedesignermode', (int)!empty($state));
73 /**
74 * Returns current theme revision number.
76 * @return int
78 function theme_get_revision() {
79 global $CFG;
81 if (empty($CFG->themedesignermode)) {
82 if (empty($CFG->themerev)) {
83 return -1;
84 } else {
85 return $CFG->themerev;
88 } else {
89 return -1;
94 /**
95 * This class represents the configuration variables of a Moodle theme.
97 * All the variables with access: public below (with a few exceptions that are marked)
98 * are the properties you can set in your themes config.php file.
100 * There are also some methods and protected variables that are part of the inner
101 * workings of Moodle's themes system. If you are just editing a themes config.php
102 * file, you can just ignore those, and the following information for developers.
104 * Normally, to create an instance of this class, you should use the
105 * {@link theme_config::load()} factory method to load a themes config.php file.
106 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
107 * will create one for you, accessible as $PAGE->theme.
109 * @copyright 2009 Tim Hunt
110 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
111 * @since Moodle 2.0
112 * @package core
113 * @category output
115 class theme_config {
118 * @var string Default theme, used when requested theme not found.
120 const DEFAULT_THEME = 'standard';
123 * @var array You can base your theme on other themes by linking to the other theme as
124 * parents. This lets you use the CSS and layouts from the other themes
125 * (see {@link theme_config::$layouts}).
126 * That makes it easy to create a new theme that is similar to another one
127 * but with a few changes. In this themes CSS you only need to override
128 * those rules you want to change.
130 public $parents;
133 * @var array The names of all the stylesheets from this theme that you would
134 * like included, in order. Give the names of the files without .css.
136 public $sheets = array();
139 * @var array The names of all the stylesheets from parents that should be excluded.
140 * true value may be used to specify all parents or all themes from one parent.
141 * If no value specified value from parent theme used.
143 public $parents_exclude_sheets = null;
146 * @var array List of plugin sheets to be excluded.
147 * If no value specified value from parent theme used.
149 public $plugins_exclude_sheets = null;
152 * @var array List of style sheets that are included in the text editor bodies.
153 * Sheets from parent themes are used automatically and can not be excluded.
155 public $editor_sheets = array();
158 * @var array The names of all the javascript files this theme that you would
159 * like included from head, in order. Give the names of the files without .js.
161 public $javascripts = array();
164 * @var array The names of all the javascript files this theme that you would
165 * like included from footer, in order. Give the names of the files without .js.
167 public $javascripts_footer = array();
170 * @var array The names of all the javascript files from parents that should
171 * be excluded. true value may be used to specify all parents or all themes
172 * from one parent.
173 * If no value specified value from parent theme used.
175 public $parents_exclude_javascripts = null;
178 * @var array Which file to use for each page layout.
180 * This is an array of arrays. The keys of the outer array are the different layouts.
181 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
182 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
183 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
184 * That file also has a good example of how to set this setting.
186 * For each layout, the value in the outer array is an array that describes
187 * how you want that type of page to look. For example
188 * <pre>
189 * $THEME->layouts = array(
190 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
191 * 'standard' => array(
192 * 'theme' = 'mytheme',
193 * 'file' => 'normal.php',
194 * 'regions' => array('side-pre', 'side-post'),
195 * 'defaultregion' => 'side-post'
196 * ),
197 * // The site home page.
198 * 'home' => array(
199 * 'theme' = 'mytheme',
200 * 'file' => 'home.php',
201 * 'regions' => array('side-pre', 'side-post'),
202 * 'defaultregion' => 'side-post'
203 * ),
204 * // ...
205 * );
206 * </pre>
208 * 'theme' name of the theme where is the layout located
209 * 'file' is the layout file to use for this type of page.
210 * layout files are stored in layout subfolder
211 * 'regions' This lists the regions on the page where blocks may appear. For
212 * each region you list here, your layout file must include a call to
213 * <pre>
214 * echo $OUTPUT->blocks_for_region($regionname);
215 * </pre>
216 * or equivalent so that the blocks are actually visible.
218 * 'defaultregion' If the list of regions is non-empty, then you must pick
219 * one of the one of them as 'default'. This has two meanings. First, this is
220 * where new blocks are added. Second, if there are any blocks associated with
221 * the page, but in non-existent regions, they appear here. (Imaging, for example,
222 * that someone added blocks using a different theme that used different region
223 * names, and then switched to this theme.)
225 public $layouts = array();
228 * @var string Name of the renderer factory class to use. Must implement the
229 * {@link renderer_factory} interface.
231 * This is an advanced feature. Moodle output is generated by 'renderers',
232 * you can customise the HTML that is output by writing custom renderers,
233 * and then you need to specify 'renderer factory' so that Moodle can find
234 * your renderers.
236 * There are some renderer factories supplied with Moodle. Please follow these
237 * links to see what they do.
238 * <ul>
239 * <li>{@link standard_renderer_factory} - the default.</li>
240 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
241 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
242 * </ul>
244 public $rendererfactory = 'standard_renderer_factory';
247 * @var string Function to do custom CSS post-processing.
249 * This is an advanced feature. If you want to do custom post-processing on the
250 * CSS before it is output (for example, to replace certain variable names
251 * with particular values) you can give the name of a function here.
253 public $csspostprocess = 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 $rarrow = null;
266 * @var string Accessibility: Right arrow-like character is
267 * used in the breadcrumb trail, course navigation menu
268 * (previous/next activity), calendar, and search forum block.
269 * If the theme does not set characters, appropriate defaults
270 * are set automatically. Please DO NOT
271 * use &lt; &gt; &raquo; - these are confusing for blind users.
273 public $larrow = null;
276 * @var bool Some themes may want to disable ajax course editing.
278 public $enablecourseajax = true;
281 * @var string Determines served document types
282 * - 'html5' the only officially supported doctype in Moodle
283 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
284 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
286 public $doctype = 'html5';
288 //==Following properties are not configurable from theme config.php==
291 * @var string The name of this theme. Set automatically when this theme is
292 * loaded. This can not be set in theme config.php
294 public $name;
297 * @var string The folder where this themes files are stored. This is set
298 * automatically. This can not be set in theme config.php
300 public $dir;
303 * @var stdClass Theme settings stored in config_plugins table.
304 * This can not be set in theme config.php
306 public $setting = null;
309 * @var bool If set to true and the theme enables the dock then blocks will be able
310 * to be moved to the special dock
312 public $enable_dock = false;
315 * @var bool If set to true then this theme will not be shown in the theme selector unless
316 * theme designer mode is turned on.
318 public $hidefromselector = false;
321 * @var array list of YUI CSS modules to be included on each page. This may be used
322 * to remove cssreset and use cssnormalise module instead.
324 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
327 * An associative array of block manipulations that should be made if the user is using an rtl language.
328 * The key is the original block region, and the value is the block region to change to.
329 * This is used when displaying blocks for regions only.
330 * @var array
332 public $blockrtlmanipulations = array();
335 * @var renderer_factory Instance of the renderer_factory implementation
336 * we are using. Implementation detail.
338 protected $rf = null;
341 * @var array List of parent config objects.
343 protected $parent_configs = array();
346 * @var bool If set to true then the theme is safe to run through the optimiser (if it is enabled)
347 * If set to false then we know either the theme has already been optimised and the CSS optimiser is not needed
348 * or the theme is not compatible with the CSS optimiser. In both cases even if enabled the CSS optimiser will not
349 * be used with this theme if set to false.
351 public $supportscssoptimisation = true;
354 * Used to determine whether we can serve SVG images or not.
355 * @var bool
357 private $usesvg = null;
360 * Load the config.php file for a particular theme, and return an instance
361 * of this class. (That is, this is a factory method.)
363 * @param string $themename the name of the theme.
364 * @return theme_config an instance of this class.
366 public static function load($themename) {
367 global $CFG;
369 // load theme settings from db
370 try {
371 $settings = get_config('theme_'.$themename);
372 } catch (dml_exception $e) {
373 // most probably moodle tables not created yet
374 $settings = new stdClass();
377 if ($config = theme_config::find_theme_config($themename, $settings)) {
378 return new theme_config($config);
380 } else if ($themename == theme_config::DEFAULT_THEME) {
381 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
383 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
384 return new theme_config($config);
386 } else {
387 // bad luck, the requested theme has some problems - admin see details in theme config
388 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
393 * Theme diagnostic code. It is very problematic to send debug output
394 * to the actual CSS file, instead this functions is supposed to
395 * diagnose given theme and highlights all potential problems.
396 * This information should be available from the theme selection page
397 * or some other debug page for theme designers.
399 * @param string $themename
400 * @return array description of problems
402 public static function diagnose($themename) {
403 //TODO: MDL-21108
404 return array();
408 * Private constructor, can be called only from the factory method.
409 * @param stdClass $config
411 private function __construct($config) {
412 global $CFG; //needed for included lib.php files
414 $this->settings = $config->settings;
415 $this->name = $config->name;
416 $this->dir = $config->dir;
418 if ($this->name != 'base') {
419 $baseconfig = theme_config::find_theme_config('base', $this->settings);
420 } else {
421 $baseconfig = $config;
424 $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer',
425 'parents_exclude_javascripts', 'layouts', 'enable_dock', 'enablecourseajax', 'supportscssoptimisation',
426 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector', 'doctype',
427 'yuicssmodules', 'blockrtlmanipulations');
429 foreach ($config as $key=>$value) {
430 if (in_array($key, $configurable)) {
431 $this->$key = $value;
435 // verify all parents and load configs and renderers
436 foreach ($this->parents as $parent) {
437 if ($parent == 'base') {
438 $parent_config = $baseconfig;
439 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
440 // this is not good - better exclude faulty parents
441 continue;
443 $libfile = $parent_config->dir.'/lib.php';
444 if (is_readable($libfile)) {
445 // theme may store various function here
446 include_once($libfile);
448 $renderersfile = $parent_config->dir.'/renderers.php';
449 if (is_readable($renderersfile)) {
450 // may contain core and plugin renderers and renderer factory
451 include_once($renderersfile);
453 $this->parent_configs[$parent] = $parent_config;
455 $libfile = $this->dir.'/lib.php';
456 if (is_readable($libfile)) {
457 // theme may store various function here
458 include_once($libfile);
460 $rendererfile = $this->dir.'/renderers.php';
461 if (is_readable($rendererfile)) {
462 // may contain core and plugin renderers and renderer factory
463 include_once($rendererfile);
464 } else {
465 // check if renderers.php file is missnamed renderer.php
466 if (is_readable($this->dir.'/renderer.php')) {
467 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
468 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
472 // cascade all layouts properly
473 foreach ($baseconfig->layouts as $layout=>$value) {
474 if (!isset($this->layouts[$layout])) {
475 foreach ($this->parent_configs as $parent_config) {
476 if (isset($parent_config->layouts[$layout])) {
477 $this->layouts[$layout] = $parent_config->layouts[$layout];
478 continue 2;
481 $this->layouts[$layout] = $value;
485 //fix arrows if needed
486 $this->check_theme_arrows();
490 * Let the theme initialise the page object (usually $PAGE).
492 * This may be used for example to request jQuery in add-ons.
494 * @param moodle_page $page
496 public function init_page(moodle_page $page) {
497 $themeinitfunction = 'theme_'.$this->name.'_page_init';
498 if (function_exists($themeinitfunction)) {
499 $themeinitfunction($page);
504 * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
505 * If not it applies sensible defaults.
507 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
508 * search forum block, etc. Important: these are 'silent' in a screen-reader
509 * (unlike &gt; &raquo;), and must be accompanied by text.
511 private function check_theme_arrows() {
512 if (!isset($this->rarrow) and !isset($this->larrow)) {
513 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
514 // Also OK in Win 9x/2K/IE 5.x
515 $this->rarrow = '&#x25BA;';
516 $this->larrow = '&#x25C4;';
517 if (empty($_SERVER['HTTP_USER_AGENT'])) {
518 $uagent = '';
519 } else {
520 $uagent = $_SERVER['HTTP_USER_AGENT'];
522 if (false !== strpos($uagent, 'Opera')
523 || false !== strpos($uagent, 'Mac')) {
524 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
525 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
526 $this->rarrow = '&#x25B6;';
527 $this->larrow = '&#x25C0;';
529 elseif ((false !== strpos($uagent, 'Konqueror'))
530 || (false !== strpos($uagent, 'Android'))) {
531 // The fonts on Android don't include the characters required for this to work as expected.
532 // So we use the same ones Konqueror uses.
533 $this->rarrow = '&rarr;';
534 $this->larrow = '&larr;';
536 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
537 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
538 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
539 // To be safe, non-Unicode browsers!
540 $this->rarrow = '&gt;';
541 $this->larrow = '&lt;';
544 // RTL support - in RTL languages, swap r and l arrows
545 if (right_to_left()) {
546 $t = $this->rarrow;
547 $this->rarrow = $this->larrow;
548 $this->larrow = $t;
554 * Returns output renderer prefixes, these are used when looking
555 * for the overridden renderers in themes.
557 * @return array
559 public function renderer_prefixes() {
560 global $CFG; // just in case the included files need it
562 $prefixes = array('theme_'.$this->name);
564 foreach ($this->parent_configs as $parent) {
565 $prefixes[] = 'theme_'.$parent->name;
568 return $prefixes;
572 * Returns the stylesheet URL of this editor content
574 * @param bool $encoded false means use & and true use &amp; in URLs
575 * @return moodle_url
577 public function editor_css_url($encoded=true) {
578 global $CFG;
579 $rev = theme_get_revision();
580 if ($rev > -1) {
581 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
582 if (!empty($CFG->slasharguments)) {
583 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
584 } else {
585 $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
587 } else {
588 $params = array('theme'=>$this->name, 'type'=>'editor');
589 $url = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
591 return $url;
595 * Returns the content of the CSS to be used in editor content
597 * @return string
599 public function editor_css_files() {
600 global $CFG;
602 $files = array();
604 // first editor plugins
605 $plugins = core_component::get_plugin_list('editor');
606 foreach ($plugins as $plugin=>$fulldir) {
607 $sheetfile = "$fulldir/editor_styles.css";
608 if (is_readable($sheetfile)) {
609 $files['plugin_'.$plugin] = $sheetfile;
612 // then parent themes
613 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
614 if (empty($parent_config->editor_sheets)) {
615 continue;
617 foreach ($parent_config->editor_sheets as $sheet) {
618 $sheetfile = "$parent_config->dir/style/$sheet.css";
619 if (is_readable($sheetfile)) {
620 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
624 // finally this theme
625 if (!empty($this->editor_sheets)) {
626 foreach ($this->editor_sheets as $sheet) {
627 $sheetfile = "$this->dir/style/$sheet.css";
628 if (is_readable($sheetfile)) {
629 $files['theme_'.$sheet] = $sheetfile;
634 return $files;
638 * Get the stylesheet URL of this theme
640 * @param moodle_page $page Not used... deprecated?
641 * @return array of moodle_url
643 public function css_urls(moodle_page $page) {
644 global $CFG;
646 $rev = theme_get_revision();
648 $urls = array();
650 $svg = $this->use_svg_icons();
652 if ($rev > -1) {
653 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
654 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
655 if (!empty($CFG->slasharguments)) {
656 $slashargs = '';
657 if (!$svg) {
658 // We add a simple /_s to the start of the path.
659 // The underscore is used to ensure that it isn't a valid theme name.
660 $slashargs .= '/_s'.$slashargs;
662 $slashargs .= '/'.$this->name.'/'.$rev.'/all';
663 if ($separate) {
664 $slashargs .= '/chunk0';
666 $url->set_slashargument($slashargs, 'noparam', true);
667 } else {
668 $params = array('theme' => $this->name,'rev' => $rev, 'type' => 'all');
669 if (!$svg) {
670 // We add an SVG param so that we know not to serve SVG images.
671 // We do this because all modern browsers support SVG and this param will one day be removed.
672 $params['svg'] = '0';
674 if ($separate) {
675 $params['chunk'] = '0';
677 $url->params($params);
679 $urls[] = $url;
681 } else {
682 // find out the current CSS and cache it now for 5 seconds
683 // the point is to construct the CSS only once and pass it through the
684 // dataroot to the script that actually serves the sheets
685 if (!defined('THEME_DESIGNER_CACHE_LIFETIME')) {
686 define('THEME_DESIGNER_CACHE_LIFETIME', 4); // this can be also set in config.php
688 $candidatedir = "$CFG->cachedir/theme/$this->name";
689 if ($svg) {
690 $candidatesheet = "$candidatedir/designer.ser";
691 } else {
692 $candidatesheet = "$candidatedir/designer_nosvg.ser";
694 $rebuild = true;
695 if (file_exists($candidatesheet) and filemtime($candidatesheet) > time() - THEME_DESIGNER_CACHE_LIFETIME) {
696 if ($css = file_get_contents($candidatesheet)) {
697 $css = unserialize($css);
698 if (is_array($css)) {
699 $rebuild = false;
703 if ($rebuild) {
704 // Prepare the CSS optimiser if it is to be used,
705 // please note that it may be very slow and is therefore strongly discouraged in theme designer mode.
706 $optimiser = null;
707 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
708 require_once($CFG->dirroot.'/lib/csslib.php');
709 $optimiser = new css_optimiser;
711 $css = $this->css_content($optimiser);
713 // We do not want any errors here because this may fail easily because of the concurrent access.
714 $prevabort = ignore_user_abort(true);
715 check_dir_exists($candidatedir);
716 $tempfile = tempnam($candidatedir, 'tmpdesigner');
717 file_put_contents($tempfile, serialize($css));
718 $reporting = error_reporting(0);
719 chmod($tempfile, $CFG->filepermissions);
720 unlink($candidatesheet); // Do not rely on rename() deleting original, they may decide to change it at any time as usually.
721 rename($tempfile, $candidatesheet);
722 error_reporting($reporting);
723 ignore_user_abort($prevabort);
726 $baseurl = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php');
727 if (!$svg) {
728 // We add an SVG param so that we know not to serve SVG images.
729 // We do this because all modern browsers support SVG and this param will one day be removed.
730 $baseurl->param('svg', '0');
732 if (core_useragent::is_ie()) {
733 // lalala, IE does not allow more than 31 linked CSS files from main document
734 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
735 foreach ($css['parents'] as $parent=>$sheets) {
736 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096)
737 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
739 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
741 } else {
742 foreach ($css['plugins'] as $plugin=>$unused) {
743 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
745 foreach ($css['parents'] as $parent=>$sheets) {
746 foreach ($sheets as $sheet=>$unused2) {
747 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
750 foreach ($css['theme'] as $sheet=>$unused) {
751 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); // sheet first in order to make long urls easier to read
756 return $urls;
760 * Returns an array of organised CSS files required for this output
762 * @return array
764 public function css_files() {
765 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
767 // get all plugin sheets
768 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
769 if ($excludes !== true) {
770 foreach (core_component::get_plugin_types() as $type=>$unused) {
771 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
772 continue;
774 $plugins = core_component::get_plugin_list($type);
775 foreach ($plugins as $plugin=>$fulldir) {
776 if (!empty($excludes[$type]) and is_array($excludes[$type])
777 and in_array($plugin, $excludes[$type])) {
778 continue;
781 $plugincontent = '';
782 $sheetfile = "$fulldir/styles.css";
783 if (is_readable($sheetfile)) {
784 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
786 $sheetthemefile = "$fulldir/styles_{$this->name}.css";
787 if (is_readable($sheetthemefile)) {
788 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$this->name] = $sheetthemefile;
794 // find out wanted parent sheets
795 $excludes = $this->resolve_excludes('parents_exclude_sheets');
796 if ($excludes !== true) {
797 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
798 $parent = $parent_config->name;
799 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
800 continue;
802 foreach ($parent_config->sheets as $sheet) {
803 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
804 and in_array($sheet, $excludes[$parent])) {
805 continue;
807 $sheetfile = "$parent_config->dir/style/$sheet.css";
808 if (is_readable($sheetfile)) {
809 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
815 // current theme sheets
816 if (is_array($this->sheets)) {
817 foreach ($this->sheets as $sheet) {
818 $sheetfile = "$this->dir/style/$sheet.css";
819 if (is_readable($sheetfile)) {
820 $cssfiles['theme'][$sheet] = $sheetfile;
825 return $cssfiles;
829 * Returns the content of the one huge CSS merged from all style sheets.
831 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
832 * @return string
834 public function css_content(css_optimiser $optimiser = null) {
835 $files = array_merge($this->css_files(), array('editor'=>$this->editor_css_files()));
836 $css = $this->css_files_get_contents($files, array(), $optimiser);
837 return $css;
841 * Given an array of file paths or a single file path loads the contents of
842 * the CSS file, processes it then returns it in the same structure it was given.
844 * Can be used recursively on the results of {@link css_files}
846 * @param array|string $file An array of file paths or a single file path
847 * @param array $keys An array of previous array keys [recursive addition]
848 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
849 * @return The converted array or the contents of the single file ($file type)
851 protected function css_files_get_contents($file, array $keys, css_optimiser $optimiser = null) {
852 global $CFG;
853 if (is_array($file)) {
854 // We use a separate array to keep everything in the exact same order.
855 $return = array();
856 foreach ($file as $key=>$f) {
857 $return[clean_param($key, PARAM_SAFEDIR)] = $this->css_files_get_contents($f, array_merge($keys, array($key)), $optimiser);
859 return $return;
860 } else {
861 $contents = file_get_contents($file);
862 $contents = $this->post_process($contents);
863 $comment = '/** Path: '.implode(' ', $keys).' **/'."\n";
864 $stats = '';
865 if (!is_null($optimiser)) {
866 $contents = $optimiser->process($contents);
867 if (!empty($CFG->cssoptimiserstats)) {
868 $stats = $optimiser->output_stats_css();
871 return $comment.$stats.$contents;
877 * Generate a URL to the file that serves theme JavaScript files.
879 * If we determine that the theme has no relevant files, then we return
880 * early with a null value.
882 * @param bool $inhead true means head url, false means footer
883 * @return moodle_url|null
885 public function javascript_url($inhead) {
886 global $CFG;
888 $rev = theme_get_revision();
889 $params = array('theme'=>$this->name,'rev'=>$rev);
890 $params['type'] = $inhead ? 'head' : 'footer';
892 // Return early if there are no files to serve
893 if (count($this->javascript_files($params['type'])) === 0) {
894 return null;
897 if (!empty($CFG->slasharguments) and $rev > 0) {
898 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
899 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
900 return $url;
901 } else {
902 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
907 * Get the URL's for the JavaScript files used by this theme.
908 * They won't be served directly, instead they'll be mediated through
909 * theme/javascript.php.
911 * @param string $type Either javascripts_footer, or javascripts
912 * @return array
914 public function javascript_files($type) {
915 if ($type === 'footer') {
916 $type = 'javascripts_footer';
917 } else {
918 $type = 'javascripts';
921 $js = array();
922 // find out wanted parent javascripts
923 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
924 if ($excludes !== true) {
925 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
926 $parent = $parent_config->name;
927 if (empty($parent_config->$type)) {
928 continue;
930 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
931 continue;
933 foreach ($parent_config->$type as $javascript) {
934 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
935 and in_array($javascript, $excludes[$parent])) {
936 continue;
938 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
939 if (is_readable($javascriptfile)) {
940 $js[] = $javascriptfile;
946 // current theme javascripts
947 if (is_array($this->$type)) {
948 foreach ($this->$type as $javascript) {
949 $javascriptfile = "$this->dir/javascript/$javascript.js";
950 if (is_readable($javascriptfile)) {
951 $js[] = $javascriptfile;
955 return $js;
959 * Resolves an exclude setting to the themes setting is applicable or the
960 * setting of its closest parent.
962 * @param string $variable The name of the setting the exclude setting to resolve
963 * @param string $default
964 * @return mixed
966 protected function resolve_excludes($variable, $default = null) {
967 $setting = $default;
968 if (is_array($this->{$variable}) or $this->{$variable} === true) {
969 $setting = $this->{$variable};
970 } else {
971 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
972 if (!isset($parent_config->{$variable})) {
973 continue;
975 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
976 $setting = $parent_config->{$variable};
977 break;
981 return $setting;
985 * Returns the content of the one huge javascript file merged from all theme javascript files.
987 * @param bool $type
988 * @return string
990 public function javascript_content($type) {
991 $jsfiles = $this->javascript_files($type);
992 $js = '';
993 foreach ($jsfiles as $jsfile) {
994 $js .= file_get_contents($jsfile)."\n";
996 return $js;
1000 * Post processes CSS.
1002 * This method post processes all of the CSS before it is served for this theme.
1003 * This is done so that things such as image URL's can be swapped in and to
1004 * run any specific CSS post process method the theme has requested.
1005 * This allows themes to use CSS settings.
1007 * @param string $css The CSS to process.
1008 * @return string The processed CSS.
1010 public function post_process($css) {
1011 // now resolve all image locations
1012 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1013 $replaced = array();
1014 foreach ($matches as $match) {
1015 if (isset($replaced[$match[0]])) {
1016 continue;
1018 $replaced[$match[0]] = true;
1019 $imagename = $match[2];
1020 $component = rtrim($match[1], '|');
1021 $imageurl = $this->pix_url($imagename, $component)->out(false);
1022 // we do not need full url because the image.php is always in the same dir
1023 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1024 $css = str_replace($match[0], $imageurl, $css);
1028 // Now resolve all font locations.
1029 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1030 $replaced = array();
1031 foreach ($matches as $match) {
1032 if (isset($replaced[$match[0]])) {
1033 continue;
1035 $replaced[$match[0]] = true;
1036 $fontname = $match[2];
1037 $component = rtrim($match[1], '|');
1038 $fonturl = $this->font_url($fontname, $component)->out(false);
1039 // We do not need full url because the font.php is always in the same dir.
1040 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1041 $css = str_replace($match[0], $fonturl, $css);
1045 // now resolve all theme settings or do any other postprocessing
1046 $csspostprocess = $this->csspostprocess;
1047 if (function_exists($csspostprocess)) {
1048 $css = $csspostprocess($css, $this);
1051 return $css;
1055 * Return the URL for an image
1057 * @param string $imagename the name of the icon.
1058 * @param string $component specification of one plugin like in get_string()
1059 * @return moodle_url
1061 public function pix_url($imagename, $component) {
1062 global $CFG;
1064 $params = array('theme'=>$this->name);
1065 $svg = $this->use_svg_icons();
1067 if (empty($component) or $component === 'moodle' or $component === 'core') {
1068 $params['component'] = 'core';
1069 } else {
1070 $params['component'] = $component;
1073 $rev = theme_get_revision();
1074 if ($rev != -1) {
1075 $params['rev'] = $rev;
1078 $params['image'] = $imagename;
1080 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1081 if (!empty($CFG->slasharguments) and $rev > 0) {
1082 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1083 if (!$svg) {
1084 // We add a simple /_s to the start of the path.
1085 // The underscore is used to ensure that it isn't a valid theme name.
1086 $path = '/_s'.$path;
1088 $url->set_slashargument($path, 'noparam', true);
1089 } else {
1090 if (!$svg) {
1091 // We add an SVG param so that we know not to serve SVG images.
1092 // We do this because all modern browsers support SVG and this param will one day be removed.
1093 $params['svg'] = '0';
1095 $url->params($params);
1098 return $url;
1102 * Return the URL for a font
1104 * @param string $font the name of the font (including extension).
1105 * @param string $component specification of one plugin like in get_string()
1106 * @return moodle_url
1108 public function font_url($font, $component) {
1109 global $CFG;
1111 $params = array('theme'=>$this->name);
1113 if (empty($component) or $component === 'moodle' or $component === 'core') {
1114 $params['component'] = 'core';
1115 } else {
1116 $params['component'] = $component;
1119 $rev = theme_get_revision();
1120 if ($rev != -1) {
1121 $params['rev'] = $rev;
1124 $params['font'] = $font;
1126 $url = new moodle_url("$CFG->httpswwwroot/theme/font.php");
1127 if (!empty($CFG->slasharguments) and $rev > 0) {
1128 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1129 $url->set_slashargument($path, 'noparam', true);
1130 } else {
1131 $url->params($params);
1134 return $url;
1138 * Returns URL to the stored file via pluginfile.php.
1140 * Note the theme must also implement pluginfile.php handler,
1141 * theme revision is used instead of the itemid.
1143 * @param string $setting
1144 * @param string $filearea
1145 * @return string protocol relative URL or null if not present
1147 public function setting_file_url($setting, $filearea) {
1148 global $CFG;
1150 if (empty($this->settings->$setting)) {
1151 return null;
1154 $component = 'theme_'.$this->name;
1155 $itemid = theme_get_revision();
1156 $filepath = $this->settings->$setting;
1157 $syscontext = context_system::instance();
1159 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1161 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1162 // Note: unfortunately moodle_url does not support //urls yet.
1164 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1166 return $url;
1170 * Serve the theme setting file.
1172 * @param string $filearea
1173 * @param array $args
1174 * @param bool $forcedownload
1175 * @param array $options
1176 * @return bool may terminate if file not found or donotdie not specified
1178 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1179 global $CFG;
1180 require_once("$CFG->libdir/filelib.php");
1182 $syscontext = context_system::instance();
1183 $component = 'theme_'.$this->name;
1185 $revision = array_shift($args);
1186 if ($revision < 0) {
1187 $lifetime = 0;
1188 } else {
1189 $lifetime = 60*60*24*60;
1192 $fs = get_file_storage();
1193 $relativepath = implode('/', $args);
1195 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1196 $fullpath = rtrim($fullpath, '/');
1197 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1198 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1199 return true;
1200 } else {
1201 send_file_not_found();
1206 * Resolves the real image location.
1208 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1209 * and we need a way in which to turn it off.
1210 * By default SVG won't be used unless asked for. This is done for two reasons:
1211 * 1. It ensures that we don't serve svg images unless we really want to. The admin has selected to force them, of the users
1212 * browser supports SVG.
1213 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1214 * by the user due to security concerns.
1216 * @param string $image name of image, may contain relative path
1217 * @param string $component
1218 * @param bool $svg If set to true SVG images will also be looked for.
1219 * @return string full file path
1221 public function resolve_image_location($image, $component, $svg = false) {
1222 global $CFG;
1224 if (!is_bool($svg)) {
1225 // If $svg isn't a bool then we need to decide for ourselves.
1226 $svg = $this->use_svg_icons();
1229 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1230 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1231 return $imagefile;
1233 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1234 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1235 return $imagefile;
1238 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1239 return $imagefile;
1241 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1242 return $imagefile;
1244 return null;
1246 } else if ($component === 'theme') { //exception
1247 if ($image === 'favicon') {
1248 return "$this->dir/pix/favicon.ico";
1250 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1251 return $imagefile;
1253 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1254 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1255 return $imagefile;
1258 return null;
1260 } else {
1261 if (strpos($component, '_') === false) {
1262 $component = 'mod_'.$component;
1264 list($type, $plugin) = explode('_', $component, 2);
1266 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1267 return $imagefile;
1269 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1270 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1271 return $imagefile;
1274 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1275 return $imagefile;
1277 $dir = core_component::get_plugin_directory($type, $plugin);
1278 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1279 return $imagefile;
1281 return null;
1286 * Resolves the real font location.
1288 * @param string $font name of font file
1289 * @param string $component
1290 * @return string full file path
1292 public function resolve_font_location($font, $component) {
1293 global $CFG;
1295 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1296 if (file_exists("$this->dir/fonts_core/$font")) {
1297 return "$this->dir/fonts_core/$font";
1299 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1300 if (file_exists("$parent_config->dir/fonts_core/$font")) {
1301 return "$parent_config->dir/fonts_core/$font";
1304 if (file_exists("$CFG->dataroot/fonts/$font")) {
1305 return "$CFG->dataroot/fonts/$font";
1307 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
1308 return "$CFG->dirroot/lib/fonts/$font";
1310 return null;
1312 } else if ($component === 'theme') { // Exception.
1313 if (file_exists("$this->dir/fonts/$font")) {
1314 return "$this->dir/fonts/$font";
1316 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1317 if (file_exists("$parent_config->dir/fonts/$font")) {
1318 return "$parent_config->dir/fonts/$font";
1321 return null;
1323 } else {
1324 if (strpos($component, '_') === false) {
1325 $component = 'mod_'.$component;
1327 list($type, $plugin) = explode('_', $component, 2);
1329 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
1330 return "$this->dir/fonts_plugins/$type/$plugin/$font";
1332 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1333 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
1334 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
1337 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
1338 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
1340 $dir = core_component::get_plugin_directory($type, $plugin);
1341 if (file_exists("$dir/fonts/$font")) {
1342 return "$dir/fonts/$font";
1344 return null;
1349 * Return true if we should look for SVG images as well.
1351 * @staticvar bool $svg
1352 * @return bool
1354 public function use_svg_icons() {
1355 global $CFG;
1356 if ($this->usesvg === null) {
1358 if (!isset($CFG->svgicons) || !is_bool($CFG->svgicons)) {
1359 $this->usesvg = core_useragent::supports_svg();
1360 } else {
1361 // Force them on/off depending upon the setting.
1362 $this->usesvg = $CFG->svgicons;
1365 return $this->usesvg;
1369 * Forces the usesvg setting to either true or false, avoiding any decision making.
1371 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
1372 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
1374 * @param bool $setting True to force the use of svg when available, null otherwise.
1376 public function force_svg_use($setting) {
1377 $this->usesvg = (bool)$setting;
1381 * Checks if file with any image extension exists.
1383 * The order to these images was adjusted prior to the release of 2.4
1384 * At that point the were the following image counts in Moodle core:
1386 * - png = 667 in pix dirs (1499 total)
1387 * - gif = 385 in pix dirs (606 total)
1388 * - jpg = 62 in pix dirs (74 total)
1389 * - jpeg = 0 in pix dirs (1 total)
1391 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1393 * @param string $filepath
1394 * @param bool $svg If set to true SVG images will also be looked for.
1395 * @return string image name with extension
1397 private static function image_exists($filepath, $svg = false) {
1398 if ($svg && file_exists("$filepath.svg")) {
1399 return "$filepath.svg";
1400 } else if (file_exists("$filepath.png")) {
1401 return "$filepath.png";
1402 } else if (file_exists("$filepath.gif")) {
1403 return "$filepath.gif";
1404 } else if (file_exists("$filepath.jpg")) {
1405 return "$filepath.jpg";
1406 } else if (file_exists("$filepath.jpeg")) {
1407 return "$filepath.jpeg";
1408 } else {
1409 return false;
1414 * Loads the theme config from config.php file.
1416 * @param string $themename
1417 * @param stdClass $settings from config_plugins table
1418 * @param boolean $parentscheck true to also check the parents. .
1419 * @return stdClass The theme configuration
1421 private static function find_theme_config($themename, $settings, $parentscheck = true) {
1422 // We have to use the variable name $THEME (upper case) because that
1423 // is what is used in theme config.php files.
1425 if (!$dir = theme_config::find_theme_location($themename)) {
1426 return null;
1429 $THEME = new stdClass();
1430 $THEME->name = $themename;
1431 $THEME->dir = $dir;
1432 $THEME->settings = $settings;
1434 global $CFG; // just in case somebody tries to use $CFG in theme config
1435 include("$THEME->dir/config.php");
1437 // verify the theme configuration is OK
1438 if (!is_array($THEME->parents)) {
1439 // parents option is mandatory now
1440 return null;
1441 } else {
1442 // We use $parentscheck to only check the direct parents (avoid infinite loop).
1443 if ($parentscheck) {
1444 // Find all parent theme configs.
1445 foreach ($THEME->parents as $parent) {
1446 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
1447 if (empty($parentconfig)) {
1448 return null;
1454 return $THEME;
1458 * Finds the theme location and verifies the theme has all needed files
1459 * and is not obsoleted.
1461 * @param string $themename
1462 * @return string full dir path or null if not found
1464 private static function find_theme_location($themename) {
1465 global $CFG;
1467 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1468 $dir = "$CFG->dirroot/theme/$themename";
1470 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1471 $dir = "$CFG->themedir/$themename";
1473 } else {
1474 return null;
1477 if (file_exists("$dir/styles.php")) {
1478 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1479 return null;
1482 return $dir;
1486 * Get the renderer for a part of Moodle for this theme.
1488 * @param moodle_page $page the page we are rendering
1489 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1490 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1491 * @param string $target one of rendering target constants
1492 * @return renderer_base the requested renderer.
1494 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1495 if (is_null($this->rf)) {
1496 $classname = $this->rendererfactory;
1497 $this->rf = new $classname($this);
1500 return $this->rf->get_renderer($page, $component, $subtype, $target);
1504 * Get the information from {@link $layouts} for this type of page.
1506 * @param string $pagelayout the the page layout name.
1507 * @return array the appropriate part of {@link $layouts}.
1509 protected function layout_info_for_page($pagelayout) {
1510 if (array_key_exists($pagelayout, $this->layouts)) {
1511 return $this->layouts[$pagelayout];
1512 } else {
1513 debugging('Invalid page layout specified: ' . $pagelayout);
1514 return $this->layouts['standard'];
1519 * Given the settings of this theme, and the page pagelayout, return the
1520 * full path of the page layout file to use.
1522 * Used by {@link core_renderer::header()}.
1524 * @param string $pagelayout the the page layout name.
1525 * @return string Full path to the lyout file to use
1527 public function layout_file($pagelayout) {
1528 global $CFG;
1530 $layoutinfo = $this->layout_info_for_page($pagelayout);
1531 $layoutfile = $layoutinfo['file'];
1533 if (array_key_exists('theme', $layoutinfo)) {
1534 $themes = array($layoutinfo['theme']);
1535 } else {
1536 $themes = array_merge(array($this->name),$this->parents);
1539 foreach ($themes as $theme) {
1540 if ($dir = $this->find_theme_location($theme)) {
1541 $path = "$dir/layout/$layoutfile";
1543 // Check the template exists, return general base theme template if not.
1544 if (is_readable($path)) {
1545 return $path;
1550 debugging('Can not find layout file for: ' . $pagelayout);
1551 // fallback to standard normal layout
1552 return "$CFG->dirroot/theme/base/layout/general.php";
1556 * Returns auxiliary page layout options specified in layout configuration array.
1558 * @param string $pagelayout
1559 * @return array
1561 public function pagelayout_options($pagelayout) {
1562 $info = $this->layout_info_for_page($pagelayout);
1563 if (!empty($info['options'])) {
1564 return $info['options'];
1566 return array();
1570 * Inform a block_manager about the block regions this theme wants on this
1571 * page layout.
1573 * @param string $pagelayout the general type of the page.
1574 * @param block_manager $blockmanager the block_manger to set up.
1576 public function setup_blocks($pagelayout, $blockmanager) {
1577 $layoutinfo = $this->layout_info_for_page($pagelayout);
1578 if (!empty($layoutinfo['regions'])) {
1579 $blockmanager->add_regions($layoutinfo['regions']);
1580 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1585 * Gets the visible name for the requested block region.
1587 * @param string $region The region name to get
1588 * @param string $theme The theme the region belongs to (may come from the parent theme)
1589 * @return string
1591 protected function get_region_name($region, $theme) {
1592 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1593 // A name exists in this theme, so use it
1594 if (substr($regionstring, 0, 1) != '[') {
1595 return $regionstring;
1598 // Otherwise, try to find one elsewhere
1599 // Check parents, if any
1600 foreach ($this->parents as $parentthemename) {
1601 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1602 if (substr($regionstring, 0, 1) != '[') {
1603 return $regionstring;
1607 // Last resort, try the base theme for names
1608 return get_string('region-' . $region, 'theme_base');
1612 * Get the list of all block regions known to this theme in all templates.
1614 * @return array internal region name => human readable name.
1616 public function get_all_block_regions() {
1617 $regions = array();
1618 foreach ($this->layouts as $layoutinfo) {
1619 foreach ($layoutinfo['regions'] as $region) {
1620 $regions[$region] = $this->get_region_name($region, $this->name);
1623 return $regions;
1627 * Returns the human readable name of the theme
1629 * @return string
1631 public function get_theme_name() {
1632 return get_string('pluginname', 'theme_'.$this->name);
1637 * This class keeps track of which HTML tags are currently open.
1639 * This makes it much easier to always generate well formed XHTML output, even
1640 * if execution terminates abruptly. Any time you output some opening HTML
1641 * without the matching closing HTML, you should push the necessary close tags
1642 * onto the stack.
1644 * @copyright 2009 Tim Hunt
1645 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1646 * @since Moodle 2.0
1647 * @package core
1648 * @category output
1650 class xhtml_container_stack {
1653 * @var array Stores the list of open containers.
1655 protected $opencontainers = array();
1658 * @var array In developer debug mode, stores a stack trace of all opens and
1659 * closes, so we can output helpful error messages when there is a mismatch.
1661 protected $log = array();
1664 * @var boolean Store whether we are developer debug mode. We need this in
1665 * several places including in the destructor where we may not have access to $CFG.
1667 protected $isdebugging;
1670 * Constructor
1672 public function __construct() {
1673 global $CFG;
1674 $this->isdebugging = $CFG->debugdeveloper;
1678 * Push the close HTML for a recently opened container onto the stack.
1680 * @param string $type The type of container. This is checked when {@link pop()}
1681 * is called and must match, otherwise a developer debug warning is output.
1682 * @param string $closehtml The HTML required to close the container.
1684 public function push($type, $closehtml) {
1685 $container = new stdClass;
1686 $container->type = $type;
1687 $container->closehtml = $closehtml;
1688 if ($this->isdebugging) {
1689 $this->log('Open', $type);
1691 array_push($this->opencontainers, $container);
1695 * Pop the HTML for the next closing container from the stack. The $type
1696 * must match the type passed when the container was opened, otherwise a
1697 * warning will be output.
1699 * @param string $type The type of container.
1700 * @return string the HTML required to close the container.
1702 public function pop($type) {
1703 if (empty($this->opencontainers)) {
1704 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1705 $this->output_log(), DEBUG_DEVELOPER);
1706 return;
1709 $container = array_pop($this->opencontainers);
1710 if ($container->type != $type) {
1711 debugging('<p>The type of container to be closed (' . $container->type .
1712 ') does not match the type of the next open container (' . $type .
1713 '). This suggests there is a nesting problem.</p>' .
1714 $this->output_log(), DEBUG_DEVELOPER);
1716 if ($this->isdebugging) {
1717 $this->log('Close', $type);
1719 return $container->closehtml;
1723 * Close all but the last open container. This is useful in places like error
1724 * handling, where you want to close all the open containers (apart from <body>)
1725 * before outputting the error message.
1727 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1728 * developer debug warning if it isn't.
1729 * @return string the HTML required to close any open containers inside <body>.
1731 public function pop_all_but_last($shouldbenone = false) {
1732 if ($shouldbenone && count($this->opencontainers) != 1) {
1733 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1734 $this->output_log(), DEBUG_DEVELOPER);
1736 $output = '';
1737 while (count($this->opencontainers) > 1) {
1738 $container = array_pop($this->opencontainers);
1739 $output .= $container->closehtml;
1741 return $output;
1745 * You can call this function if you want to throw away an instance of this
1746 * class without properly emptying the stack (for example, in a unit test).
1747 * Calling this method stops the destruct method from outputting a developer
1748 * debug warning. After calling this method, the instance can no longer be used.
1750 public function discard() {
1751 $this->opencontainers = null;
1755 * Adds an entry to the log.
1757 * @param string $action The name of the action
1758 * @param string $type The type of action
1760 protected function log($action, $type) {
1761 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1762 format_backtrace(debug_backtrace()) . '</li>';
1766 * Outputs the log's contents as a HTML list.
1768 * @return string HTML list of the log
1770 protected function output_log() {
1771 return '<ul>' . implode("\n", $this->log) . '</ul>';