Merge branch 'wip-MDL-44501-26' of git://github.com/abgreeve/moodle into MOODLE_26_STABLE
[moodle.git] / lib / outputlib.php
blob631ae0653365747c6cadc3438b01e9cdcbce7fb0
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 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
361 * Defaults to {@link core_renderer::blocks_for_region()}
362 * @var string
364 public $blockrendermethod = null;
367 * Load the config.php file for a particular theme, and return an instance
368 * of this class. (That is, this is a factory method.)
370 * @param string $themename the name of the theme.
371 * @return theme_config an instance of this class.
373 public static function load($themename) {
374 global $CFG;
376 // load theme settings from db
377 try {
378 $settings = get_config('theme_'.$themename);
379 } catch (dml_exception $e) {
380 // most probably moodle tables not created yet
381 $settings = new stdClass();
384 if ($config = theme_config::find_theme_config($themename, $settings)) {
385 return new theme_config($config);
387 } else if ($themename == theme_config::DEFAULT_THEME) {
388 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
390 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
391 return new theme_config($config);
393 } else {
394 // bad luck, the requested theme has some problems - admin see details in theme config
395 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
400 * Theme diagnostic code. It is very problematic to send debug output
401 * to the actual CSS file, instead this functions is supposed to
402 * diagnose given theme and highlights all potential problems.
403 * This information should be available from the theme selection page
404 * or some other debug page for theme designers.
406 * @param string $themename
407 * @return array description of problems
409 public static function diagnose($themename) {
410 //TODO: MDL-21108
411 return array();
415 * Private constructor, can be called only from the factory method.
416 * @param stdClass $config
418 private function __construct($config) {
419 global $CFG; //needed for included lib.php files
421 $this->settings = $config->settings;
422 $this->name = $config->name;
423 $this->dir = $config->dir;
425 if ($this->name != 'base') {
426 $baseconfig = theme_config::find_theme_config('base', $this->settings);
427 } else {
428 $baseconfig = $config;
431 $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer',
432 'parents_exclude_javascripts', 'layouts', 'enable_dock', 'enablecourseajax', 'supportscssoptimisation',
433 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector', 'doctype',
434 'yuicssmodules', 'blockrtlmanipulations', 'blockrendermethod');
436 foreach ($config as $key=>$value) {
437 if (in_array($key, $configurable)) {
438 $this->$key = $value;
442 // verify all parents and load configs and renderers
443 foreach ($this->parents as $parent) {
444 if ($parent == 'base') {
445 $parent_config = $baseconfig;
446 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
447 // this is not good - better exclude faulty parents
448 continue;
450 $libfile = $parent_config->dir.'/lib.php';
451 if (is_readable($libfile)) {
452 // theme may store various function here
453 include_once($libfile);
455 $renderersfile = $parent_config->dir.'/renderers.php';
456 if (is_readable($renderersfile)) {
457 // may contain core and plugin renderers and renderer factory
458 include_once($renderersfile);
460 $this->parent_configs[$parent] = $parent_config;
462 $libfile = $this->dir.'/lib.php';
463 if (is_readable($libfile)) {
464 // theme may store various function here
465 include_once($libfile);
467 $rendererfile = $this->dir.'/renderers.php';
468 if (is_readable($rendererfile)) {
469 // may contain core and plugin renderers and renderer factory
470 include_once($rendererfile);
471 } else {
472 // check if renderers.php file is missnamed renderer.php
473 if (is_readable($this->dir.'/renderer.php')) {
474 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
475 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
479 // cascade all layouts properly
480 foreach ($baseconfig->layouts as $layout=>$value) {
481 if (!isset($this->layouts[$layout])) {
482 foreach ($this->parent_configs as $parent_config) {
483 if (isset($parent_config->layouts[$layout])) {
484 $this->layouts[$layout] = $parent_config->layouts[$layout];
485 continue 2;
488 $this->layouts[$layout] = $value;
492 //fix arrows if needed
493 $this->check_theme_arrows();
497 * Let the theme initialise the page object (usually $PAGE).
499 * This may be used for example to request jQuery in add-ons.
501 * @param moodle_page $page
503 public function init_page(moodle_page $page) {
504 $themeinitfunction = 'theme_'.$this->name.'_page_init';
505 if (function_exists($themeinitfunction)) {
506 $themeinitfunction($page);
511 * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
512 * If not it applies sensible defaults.
514 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
515 * search forum block, etc. Important: these are 'silent' in a screen-reader
516 * (unlike &gt; &raquo;), and must be accompanied by text.
518 private function check_theme_arrows() {
519 if (!isset($this->rarrow) and !isset($this->larrow)) {
520 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
521 // Also OK in Win 9x/2K/IE 5.x
522 $this->rarrow = '&#x25BA;';
523 $this->larrow = '&#x25C4;';
524 if (empty($_SERVER['HTTP_USER_AGENT'])) {
525 $uagent = '';
526 } else {
527 $uagent = $_SERVER['HTTP_USER_AGENT'];
529 if (false !== strpos($uagent, 'Opera')
530 || false !== strpos($uagent, 'Mac')) {
531 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
532 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
533 $this->rarrow = '&#x25B6;';
534 $this->larrow = '&#x25C0;';
536 elseif ((false !== strpos($uagent, 'Konqueror'))
537 || (false !== strpos($uagent, 'Android'))) {
538 // The fonts on Android don't include the characters required for this to work as expected.
539 // So we use the same ones Konqueror uses.
540 $this->rarrow = '&rarr;';
541 $this->larrow = '&larr;';
543 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
544 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
545 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
546 // To be safe, non-Unicode browsers!
547 $this->rarrow = '&gt;';
548 $this->larrow = '&lt;';
551 // RTL support - in RTL languages, swap r and l arrows
552 if (right_to_left()) {
553 $t = $this->rarrow;
554 $this->rarrow = $this->larrow;
555 $this->larrow = $t;
561 * Returns output renderer prefixes, these are used when looking
562 * for the overridden renderers in themes.
564 * @return array
566 public function renderer_prefixes() {
567 global $CFG; // just in case the included files need it
569 $prefixes = array('theme_'.$this->name);
571 foreach ($this->parent_configs as $parent) {
572 $prefixes[] = 'theme_'.$parent->name;
575 return $prefixes;
579 * Returns the stylesheet URL of this editor content
581 * @param bool $encoded false means use & and true use &amp; in URLs
582 * @return moodle_url
584 public function editor_css_url($encoded=true) {
585 global $CFG;
586 $rev = theme_get_revision();
587 if ($rev > -1) {
588 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
589 if (!empty($CFG->slasharguments)) {
590 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
591 } else {
592 $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
594 } else {
595 $params = array('theme'=>$this->name, 'type'=>'editor');
596 $url = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
598 return $url;
602 * Returns the content of the CSS to be used in editor content
604 * @return string
606 public function editor_css_files() {
607 global $CFG;
609 $files = array();
611 // first editor plugins
612 $plugins = core_component::get_plugin_list('editor');
613 foreach ($plugins as $plugin=>$fulldir) {
614 $sheetfile = "$fulldir/editor_styles.css";
615 if (is_readable($sheetfile)) {
616 $files['plugin_'.$plugin] = $sheetfile;
619 // then parent themes
620 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
621 if (empty($parent_config->editor_sheets)) {
622 continue;
624 foreach ($parent_config->editor_sheets as $sheet) {
625 $sheetfile = "$parent_config->dir/style/$sheet.css";
626 if (is_readable($sheetfile)) {
627 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
631 // finally this theme
632 if (!empty($this->editor_sheets)) {
633 foreach ($this->editor_sheets as $sheet) {
634 $sheetfile = "$this->dir/style/$sheet.css";
635 if (is_readable($sheetfile)) {
636 $files['theme_'.$sheet] = $sheetfile;
641 return $files;
645 * Get the stylesheet URL of this theme
647 * @param moodle_page $page Not used... deprecated?
648 * @return array of moodle_url
650 public function css_urls(moodle_page $page) {
651 global $CFG;
653 $rev = theme_get_revision();
655 $urls = array();
657 $svg = $this->use_svg_icons();
659 if ($rev > -1) {
660 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
661 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
662 if (!empty($CFG->slasharguments)) {
663 $slashargs = '';
664 if (!$svg) {
665 // We add a simple /_s to the start of the path.
666 // The underscore is used to ensure that it isn't a valid theme name.
667 $slashargs .= '/_s'.$slashargs;
669 $slashargs .= '/'.$this->name.'/'.$rev.'/all';
670 if ($separate) {
671 $slashargs .= '/chunk0';
673 $url->set_slashargument($slashargs, 'noparam', true);
674 } else {
675 $params = array('theme' => $this->name,'rev' => $rev, 'type' => 'all');
676 if (!$svg) {
677 // We add an SVG param so that we know not to serve SVG images.
678 // We do this because all modern browsers support SVG and this param will one day be removed.
679 $params['svg'] = '0';
681 if ($separate) {
682 $params['chunk'] = '0';
684 $url->params($params);
686 $urls[] = $url;
688 } else {
689 // find out the current CSS and cache it now for 5 seconds
690 // the point is to construct the CSS only once and pass it through the
691 // dataroot to the script that actually serves the sheets
692 if (!defined('THEME_DESIGNER_CACHE_LIFETIME')) {
693 define('THEME_DESIGNER_CACHE_LIFETIME', 4); // this can be also set in config.php
695 $candidatedir = "$CFG->cachedir/theme/$this->name";
696 if ($svg) {
697 $candidatesheet = "$candidatedir/designer.ser";
698 } else {
699 $candidatesheet = "$candidatedir/designer_nosvg.ser";
701 $rebuild = true;
702 if (file_exists($candidatesheet) and filemtime($candidatesheet) > time() - THEME_DESIGNER_CACHE_LIFETIME) {
703 if ($css = file_get_contents($candidatesheet)) {
704 $css = unserialize($css);
705 if (is_array($css)) {
706 $rebuild = false;
710 if ($rebuild) {
711 // Prepare the CSS optimiser if it is to be used,
712 // please note that it may be very slow and is therefore strongly discouraged in theme designer mode.
713 $optimiser = null;
714 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
715 require_once($CFG->dirroot.'/lib/csslib.php');
716 $optimiser = new css_optimiser;
718 $css = $this->css_content($optimiser);
720 // We do not want any errors here because this may fail easily because of the concurrent access.
721 $prevabort = ignore_user_abort(true);
722 check_dir_exists($candidatedir);
723 $tempfile = tempnam($candidatedir, 'tmpdesigner');
724 file_put_contents($tempfile, serialize($css));
725 $reporting = error_reporting(0);
726 chmod($tempfile, $CFG->filepermissions);
727 unlink($candidatesheet); // Do not rely on rename() deleting original, they may decide to change it at any time as usually.
728 rename($tempfile, $candidatesheet);
729 error_reporting($reporting);
730 ignore_user_abort($prevabort);
733 $baseurl = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php');
734 if (!$svg) {
735 // We add an SVG param so that we know not to serve SVG images.
736 // We do this because all modern browsers support SVG and this param will one day be removed.
737 $baseurl->param('svg', '0');
739 if (core_useragent::is_ie()) {
740 // lalala, IE does not allow more than 31 linked CSS files from main document
741 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
742 foreach ($css['parents'] as $parent=>$sheets) {
743 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096)
744 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
746 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
748 } else {
749 foreach ($css['plugins'] as $plugin=>$unused) {
750 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
752 foreach ($css['parents'] as $parent=>$sheets) {
753 foreach ($sheets as $sheet=>$unused2) {
754 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
757 foreach ($css['theme'] as $sheet=>$unused) {
758 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); // sheet first in order to make long urls easier to read
763 return $urls;
767 * Returns an array of organised CSS files required for this output
769 * @return array
771 public function css_files() {
772 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
774 // get all plugin sheets
775 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
776 if ($excludes !== true) {
777 foreach (core_component::get_plugin_types() as $type=>$unused) {
778 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
779 continue;
781 $plugins = core_component::get_plugin_list($type);
782 foreach ($plugins as $plugin=>$fulldir) {
783 if (!empty($excludes[$type]) and is_array($excludes[$type])
784 and in_array($plugin, $excludes[$type])) {
785 continue;
788 // Add main stylesheet.
789 $sheetfile = "$fulldir/styles.css";
790 if (is_readable($sheetfile)) {
791 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
794 // Create a list of candidate sheets from parents (direct parent last) and current theme.
795 $candidates = array();
796 foreach (array_reverse($this->parent_configs) as $parent_config) {
797 $candidates[] = $parent_config->name;
799 $candidates[] = $this->name;
801 // Add the sheets found.
802 foreach ($candidates as $candidate) {
803 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
804 if (is_readable($sheetthemefile)) {
805 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
812 // find out wanted parent sheets
813 $excludes = $this->resolve_excludes('parents_exclude_sheets');
814 if ($excludes !== true) {
815 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
816 $parent = $parent_config->name;
817 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
818 continue;
820 foreach ($parent_config->sheets as $sheet) {
821 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
822 and in_array($sheet, $excludes[$parent])) {
823 continue;
825 $sheetfile = "$parent_config->dir/style/$sheet.css";
826 if (is_readable($sheetfile)) {
827 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
833 // current theme sheets
834 if (is_array($this->sheets)) {
835 foreach ($this->sheets as $sheet) {
836 $sheetfile = "$this->dir/style/$sheet.css";
837 if (is_readable($sheetfile)) {
838 $cssfiles['theme'][$sheet] = $sheetfile;
843 return $cssfiles;
847 * Returns the content of the one huge CSS merged from all style sheets.
849 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
850 * @return string
852 public function css_content(css_optimiser $optimiser = null) {
853 $files = array_merge($this->css_files(), array('editor'=>$this->editor_css_files()));
854 $css = $this->css_files_get_contents($files, array(), $optimiser);
855 return $css;
859 * Given an array of file paths or a single file path loads the contents of
860 * the CSS file, processes it then returns it in the same structure it was given.
862 * Can be used recursively on the results of {@link css_files}
864 * @param array|string $file An array of file paths or a single file path
865 * @param array $keys An array of previous array keys [recursive addition]
866 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
867 * @return The converted array or the contents of the single file ($file type)
869 protected function css_files_get_contents($file, array $keys, css_optimiser $optimiser = null) {
870 global $CFG;
871 if (is_array($file)) {
872 // We use a separate array to keep everything in the exact same order.
873 $return = array();
874 foreach ($file as $key=>$f) {
875 $return[clean_param($key, PARAM_SAFEDIR)] = $this->css_files_get_contents($f, array_merge($keys, array($key)), $optimiser);
877 return $return;
878 } else {
879 $contents = file_get_contents($file);
880 $contents = $this->post_process($contents);
881 $comment = '/** Path: '.implode(' ', $keys).' **/'."\n";
882 $stats = '';
883 if (!is_null($optimiser)) {
884 $contents = $optimiser->process($contents);
885 if (!empty($CFG->cssoptimiserstats)) {
886 $stats = $optimiser->output_stats_css();
889 return $comment.$stats.$contents;
895 * Generate a URL to the file that serves theme JavaScript files.
897 * If we determine that the theme has no relevant files, then we return
898 * early with a null value.
900 * @param bool $inhead true means head url, false means footer
901 * @return moodle_url|null
903 public function javascript_url($inhead) {
904 global $CFG;
906 $rev = theme_get_revision();
907 $params = array('theme'=>$this->name,'rev'=>$rev);
908 $params['type'] = $inhead ? 'head' : 'footer';
910 // Return early if there are no files to serve
911 if (count($this->javascript_files($params['type'])) === 0) {
912 return null;
915 if (!empty($CFG->slasharguments) and $rev > 0) {
916 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
917 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
918 return $url;
919 } else {
920 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
925 * Get the URL's for the JavaScript files used by this theme.
926 * They won't be served directly, instead they'll be mediated through
927 * theme/javascript.php.
929 * @param string $type Either javascripts_footer, or javascripts
930 * @return array
932 public function javascript_files($type) {
933 if ($type === 'footer') {
934 $type = 'javascripts_footer';
935 } else {
936 $type = 'javascripts';
939 $js = array();
940 // find out wanted parent javascripts
941 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
942 if ($excludes !== true) {
943 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
944 $parent = $parent_config->name;
945 if (empty($parent_config->$type)) {
946 continue;
948 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
949 continue;
951 foreach ($parent_config->$type as $javascript) {
952 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
953 and in_array($javascript, $excludes[$parent])) {
954 continue;
956 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
957 if (is_readable($javascriptfile)) {
958 $js[] = $javascriptfile;
964 // current theme javascripts
965 if (is_array($this->$type)) {
966 foreach ($this->$type as $javascript) {
967 $javascriptfile = "$this->dir/javascript/$javascript.js";
968 if (is_readable($javascriptfile)) {
969 $js[] = $javascriptfile;
973 return $js;
977 * Resolves an exclude setting to the themes setting is applicable or the
978 * setting of its closest parent.
980 * @param string $variable The name of the setting the exclude setting to resolve
981 * @param string $default
982 * @return mixed
984 protected function resolve_excludes($variable, $default = null) {
985 $setting = $default;
986 if (is_array($this->{$variable}) or $this->{$variable} === true) {
987 $setting = $this->{$variable};
988 } else {
989 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
990 if (!isset($parent_config->{$variable})) {
991 continue;
993 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
994 $setting = $parent_config->{$variable};
995 break;
999 return $setting;
1003 * Returns the content of the one huge javascript file merged from all theme javascript files.
1005 * @param bool $type
1006 * @return string
1008 public function javascript_content($type) {
1009 $jsfiles = $this->javascript_files($type);
1010 $js = '';
1011 foreach ($jsfiles as $jsfile) {
1012 $js .= file_get_contents($jsfile)."\n";
1014 return $js;
1018 * Post processes CSS.
1020 * This method post processes all of the CSS before it is served for this theme.
1021 * This is done so that things such as image URL's can be swapped in and to
1022 * run any specific CSS post process method the theme has requested.
1023 * This allows themes to use CSS settings.
1025 * @param string $css The CSS to process.
1026 * @return string The processed CSS.
1028 public function post_process($css) {
1029 // now resolve all image locations
1030 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1031 $replaced = array();
1032 foreach ($matches as $match) {
1033 if (isset($replaced[$match[0]])) {
1034 continue;
1036 $replaced[$match[0]] = true;
1037 $imagename = $match[2];
1038 $component = rtrim($match[1], '|');
1039 $imageurl = $this->pix_url($imagename, $component)->out(false);
1040 // we do not need full url because the image.php is always in the same dir
1041 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1042 $css = str_replace($match[0], $imageurl, $css);
1046 // Now resolve all font locations.
1047 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1048 $replaced = array();
1049 foreach ($matches as $match) {
1050 if (isset($replaced[$match[0]])) {
1051 continue;
1053 $replaced[$match[0]] = true;
1054 $fontname = $match[2];
1055 $component = rtrim($match[1], '|');
1056 $fonturl = $this->font_url($fontname, $component)->out(false);
1057 // We do not need full url because the font.php is always in the same dir.
1058 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1059 $css = str_replace($match[0], $fonturl, $css);
1063 // now resolve all theme settings or do any other postprocessing
1064 $csspostprocess = $this->csspostprocess;
1065 if (function_exists($csspostprocess)) {
1066 $css = $csspostprocess($css, $this);
1069 return $css;
1073 * Return the URL for an image
1075 * @param string $imagename the name of the icon.
1076 * @param string $component specification of one plugin like in get_string()
1077 * @return moodle_url
1079 public function pix_url($imagename, $component) {
1080 global $CFG;
1082 $params = array('theme'=>$this->name);
1083 $svg = $this->use_svg_icons();
1085 if (empty($component) or $component === 'moodle' or $component === 'core') {
1086 $params['component'] = 'core';
1087 } else {
1088 $params['component'] = $component;
1091 $rev = theme_get_revision();
1092 if ($rev != -1) {
1093 $params['rev'] = $rev;
1096 $params['image'] = $imagename;
1098 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1099 if (!empty($CFG->slasharguments) and $rev > 0) {
1100 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1101 if (!$svg) {
1102 // We add a simple /_s to the start of the path.
1103 // The underscore is used to ensure that it isn't a valid theme name.
1104 $path = '/_s'.$path;
1106 $url->set_slashargument($path, 'noparam', true);
1107 } else {
1108 if (!$svg) {
1109 // We add an SVG param so that we know not to serve SVG images.
1110 // We do this because all modern browsers support SVG and this param will one day be removed.
1111 $params['svg'] = '0';
1113 $url->params($params);
1116 return $url;
1120 * Return the URL for a font
1122 * @param string $font the name of the font (including extension).
1123 * @param string $component specification of one plugin like in get_string()
1124 * @return moodle_url
1126 public function font_url($font, $component) {
1127 global $CFG;
1129 $params = array('theme'=>$this->name);
1131 if (empty($component) or $component === 'moodle' or $component === 'core') {
1132 $params['component'] = 'core';
1133 } else {
1134 $params['component'] = $component;
1137 $rev = theme_get_revision();
1138 if ($rev != -1) {
1139 $params['rev'] = $rev;
1142 $params['font'] = $font;
1144 $url = new moodle_url("$CFG->httpswwwroot/theme/font.php");
1145 if (!empty($CFG->slasharguments) and $rev > 0) {
1146 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1147 $url->set_slashargument($path, 'noparam', true);
1148 } else {
1149 $url->params($params);
1152 return $url;
1156 * Returns URL to the stored file via pluginfile.php.
1158 * Note the theme must also implement pluginfile.php handler,
1159 * theme revision is used instead of the itemid.
1161 * @param string $setting
1162 * @param string $filearea
1163 * @return string protocol relative URL or null if not present
1165 public function setting_file_url($setting, $filearea) {
1166 global $CFG;
1168 if (empty($this->settings->$setting)) {
1169 return null;
1172 $component = 'theme_'.$this->name;
1173 $itemid = theme_get_revision();
1174 $filepath = $this->settings->$setting;
1175 $syscontext = context_system::instance();
1177 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1179 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1180 // Note: unfortunately moodle_url does not support //urls yet.
1182 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1184 return $url;
1188 * Serve the theme setting file.
1190 * @param string $filearea
1191 * @param array $args
1192 * @param bool $forcedownload
1193 * @param array $options
1194 * @return bool may terminate if file not found or donotdie not specified
1196 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1197 global $CFG;
1198 require_once("$CFG->libdir/filelib.php");
1200 $syscontext = context_system::instance();
1201 $component = 'theme_'.$this->name;
1203 $revision = array_shift($args);
1204 if ($revision < 0) {
1205 $lifetime = 0;
1206 } else {
1207 $lifetime = 60*60*24*60;
1210 $fs = get_file_storage();
1211 $relativepath = implode('/', $args);
1213 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1214 $fullpath = rtrim($fullpath, '/');
1215 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1216 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1217 return true;
1218 } else {
1219 send_file_not_found();
1224 * Resolves the real image location.
1226 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1227 * and we need a way in which to turn it off.
1228 * By default SVG won't be used unless asked for. This is done for two reasons:
1229 * 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
1230 * browser supports SVG.
1231 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1232 * by the user due to security concerns.
1234 * @param string $image name of image, may contain relative path
1235 * @param string $component
1236 * @param bool $svg If set to true SVG images will also be looked for.
1237 * @return string full file path
1239 public function resolve_image_location($image, $component, $svg = false) {
1240 global $CFG;
1242 if (!is_bool($svg)) {
1243 // If $svg isn't a bool then we need to decide for ourselves.
1244 $svg = $this->use_svg_icons();
1247 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1248 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1249 return $imagefile;
1251 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1252 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1253 return $imagefile;
1256 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1257 return $imagefile;
1259 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1260 return $imagefile;
1262 return null;
1264 } else if ($component === 'theme') { //exception
1265 if ($image === 'favicon') {
1266 return "$this->dir/pix/favicon.ico";
1268 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1269 return $imagefile;
1271 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1272 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1273 return $imagefile;
1276 return null;
1278 } else {
1279 if (strpos($component, '_') === false) {
1280 $component = 'mod_'.$component;
1282 list($type, $plugin) = explode('_', $component, 2);
1284 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1285 return $imagefile;
1287 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1288 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1289 return $imagefile;
1292 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1293 return $imagefile;
1295 $dir = core_component::get_plugin_directory($type, $plugin);
1296 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1297 return $imagefile;
1299 return null;
1304 * Resolves the real font location.
1306 * @param string $font name of font file
1307 * @param string $component
1308 * @return string full file path
1310 public function resolve_font_location($font, $component) {
1311 global $CFG;
1313 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1314 if (file_exists("$this->dir/fonts_core/$font")) {
1315 return "$this->dir/fonts_core/$font";
1317 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1318 if (file_exists("$parent_config->dir/fonts_core/$font")) {
1319 return "$parent_config->dir/fonts_core/$font";
1322 if (file_exists("$CFG->dataroot/fonts/$font")) {
1323 return "$CFG->dataroot/fonts/$font";
1325 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
1326 return "$CFG->dirroot/lib/fonts/$font";
1328 return null;
1330 } else if ($component === 'theme') { // Exception.
1331 if (file_exists("$this->dir/fonts/$font")) {
1332 return "$this->dir/fonts/$font";
1334 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1335 if (file_exists("$parent_config->dir/fonts/$font")) {
1336 return "$parent_config->dir/fonts/$font";
1339 return null;
1341 } else {
1342 if (strpos($component, '_') === false) {
1343 $component = 'mod_'.$component;
1345 list($type, $plugin) = explode('_', $component, 2);
1347 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
1348 return "$this->dir/fonts_plugins/$type/$plugin/$font";
1350 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1351 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
1352 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
1355 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
1356 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
1358 $dir = core_component::get_plugin_directory($type, $plugin);
1359 if (file_exists("$dir/fonts/$font")) {
1360 return "$dir/fonts/$font";
1362 return null;
1367 * Return true if we should look for SVG images as well.
1369 * @staticvar bool $svg
1370 * @return bool
1372 public function use_svg_icons() {
1373 global $CFG;
1374 if ($this->usesvg === null) {
1376 if (!isset($CFG->svgicons) || !is_bool($CFG->svgicons)) {
1377 $this->usesvg = core_useragent::supports_svg();
1378 } else {
1379 // Force them on/off depending upon the setting.
1380 $this->usesvg = $CFG->svgicons;
1383 return $this->usesvg;
1387 * Forces the usesvg setting to either true or false, avoiding any decision making.
1389 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
1390 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
1392 * @param bool $setting True to force the use of svg when available, null otherwise.
1394 public function force_svg_use($setting) {
1395 $this->usesvg = (bool)$setting;
1399 * Checks if file with any image extension exists.
1401 * The order to these images was adjusted prior to the release of 2.4
1402 * At that point the were the following image counts in Moodle core:
1404 * - png = 667 in pix dirs (1499 total)
1405 * - gif = 385 in pix dirs (606 total)
1406 * - jpg = 62 in pix dirs (74 total)
1407 * - jpeg = 0 in pix dirs (1 total)
1409 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1411 * @param string $filepath
1412 * @param bool $svg If set to true SVG images will also be looked for.
1413 * @return string image name with extension
1415 private static function image_exists($filepath, $svg = false) {
1416 if ($svg && file_exists("$filepath.svg")) {
1417 return "$filepath.svg";
1418 } else if (file_exists("$filepath.png")) {
1419 return "$filepath.png";
1420 } else if (file_exists("$filepath.gif")) {
1421 return "$filepath.gif";
1422 } else if (file_exists("$filepath.jpg")) {
1423 return "$filepath.jpg";
1424 } else if (file_exists("$filepath.jpeg")) {
1425 return "$filepath.jpeg";
1426 } else {
1427 return false;
1432 * Loads the theme config from config.php file.
1434 * @param string $themename
1435 * @param stdClass $settings from config_plugins table
1436 * @param boolean $parentscheck true to also check the parents. .
1437 * @return stdClass The theme configuration
1439 private static function find_theme_config($themename, $settings, $parentscheck = true) {
1440 // We have to use the variable name $THEME (upper case) because that
1441 // is what is used in theme config.php files.
1443 if (!$dir = theme_config::find_theme_location($themename)) {
1444 return null;
1447 $THEME = new stdClass();
1448 $THEME->name = $themename;
1449 $THEME->dir = $dir;
1450 $THEME->settings = $settings;
1452 global $CFG; // just in case somebody tries to use $CFG in theme config
1453 include("$THEME->dir/config.php");
1455 // verify the theme configuration is OK
1456 if (!is_array($THEME->parents)) {
1457 // parents option is mandatory now
1458 return null;
1459 } else {
1460 // We use $parentscheck to only check the direct parents (avoid infinite loop).
1461 if ($parentscheck) {
1462 // Find all parent theme configs.
1463 foreach ($THEME->parents as $parent) {
1464 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
1465 if (empty($parentconfig)) {
1466 return null;
1472 return $THEME;
1476 * Finds the theme location and verifies the theme has all needed files
1477 * and is not obsoleted.
1479 * @param string $themename
1480 * @return string full dir path or null if not found
1482 private static function find_theme_location($themename) {
1483 global $CFG;
1485 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1486 $dir = "$CFG->dirroot/theme/$themename";
1488 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1489 $dir = "$CFG->themedir/$themename";
1491 } else {
1492 return null;
1495 if (file_exists("$dir/styles.php")) {
1496 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1497 return null;
1500 return $dir;
1504 * Get the renderer for a part of Moodle for this theme.
1506 * @param moodle_page $page the page we are rendering
1507 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
1508 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1509 * @param string $target one of rendering target constants
1510 * @return renderer_base the requested renderer.
1512 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
1513 if (is_null($this->rf)) {
1514 $classname = $this->rendererfactory;
1515 $this->rf = new $classname($this);
1518 return $this->rf->get_renderer($page, $component, $subtype, $target);
1522 * Get the information from {@link $layouts} for this type of page.
1524 * @param string $pagelayout the the page layout name.
1525 * @return array the appropriate part of {@link $layouts}.
1527 protected function layout_info_for_page($pagelayout) {
1528 if (array_key_exists($pagelayout, $this->layouts)) {
1529 return $this->layouts[$pagelayout];
1530 } else {
1531 debugging('Invalid page layout specified: ' . $pagelayout);
1532 return $this->layouts['standard'];
1537 * Given the settings of this theme, and the page pagelayout, return the
1538 * full path of the page layout file to use.
1540 * Used by {@link core_renderer::header()}.
1542 * @param string $pagelayout the the page layout name.
1543 * @return string Full path to the lyout file to use
1545 public function layout_file($pagelayout) {
1546 global $CFG;
1548 $layoutinfo = $this->layout_info_for_page($pagelayout);
1549 $layoutfile = $layoutinfo['file'];
1551 if (array_key_exists('theme', $layoutinfo)) {
1552 $themes = array($layoutinfo['theme']);
1553 } else {
1554 $themes = array_merge(array($this->name),$this->parents);
1557 foreach ($themes as $theme) {
1558 if ($dir = $this->find_theme_location($theme)) {
1559 $path = "$dir/layout/$layoutfile";
1561 // Check the template exists, return general base theme template if not.
1562 if (is_readable($path)) {
1563 return $path;
1568 debugging('Can not find layout file for: ' . $pagelayout);
1569 // fallback to standard normal layout
1570 return "$CFG->dirroot/theme/base/layout/general.php";
1574 * Returns auxiliary page layout options specified in layout configuration array.
1576 * @param string $pagelayout
1577 * @return array
1579 public function pagelayout_options($pagelayout) {
1580 $info = $this->layout_info_for_page($pagelayout);
1581 if (!empty($info['options'])) {
1582 return $info['options'];
1584 return array();
1588 * Inform a block_manager about the block regions this theme wants on this
1589 * page layout.
1591 * @param string $pagelayout the general type of the page.
1592 * @param block_manager $blockmanager the block_manger to set up.
1594 public function setup_blocks($pagelayout, $blockmanager) {
1595 $layoutinfo = $this->layout_info_for_page($pagelayout);
1596 if (!empty($layoutinfo['regions'])) {
1597 $blockmanager->add_regions($layoutinfo['regions'], false);
1598 $blockmanager->set_default_region($layoutinfo['defaultregion']);
1603 * Gets the visible name for the requested block region.
1605 * @param string $region The region name to get
1606 * @param string $theme The theme the region belongs to (may come from the parent theme)
1607 * @return string
1609 protected function get_region_name($region, $theme) {
1610 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1611 // A name exists in this theme, so use it
1612 if (substr($regionstring, 0, 1) != '[') {
1613 return $regionstring;
1616 // Otherwise, try to find one elsewhere
1617 // Check parents, if any
1618 foreach ($this->parents as $parentthemename) {
1619 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1620 if (substr($regionstring, 0, 1) != '[') {
1621 return $regionstring;
1625 // Last resort, try the base theme for names
1626 return get_string('region-' . $region, 'theme_base');
1630 * Get the list of all block regions known to this theme in all templates.
1632 * @return array internal region name => human readable name.
1634 public function get_all_block_regions() {
1635 $regions = array();
1636 foreach ($this->layouts as $layoutinfo) {
1637 foreach ($layoutinfo['regions'] as $region) {
1638 $regions[$region] = $this->get_region_name($region, $this->name);
1641 return $regions;
1645 * Returns the human readable name of the theme
1647 * @return string
1649 public function get_theme_name() {
1650 return get_string('pluginname', 'theme_'.$this->name);
1654 * Returns the block render method.
1656 * It is set by the theme via:
1657 * $THEME->blockrendermethod = '...';
1659 * It can be one of two values, blocks or blocks_for_region.
1660 * It should be set to the method being used by the theme layouts.
1662 * @return string
1664 public function get_block_render_method() {
1665 if ($this->blockrendermethod) {
1666 // Return the specified block render method.
1667 return $this->blockrendermethod;
1669 // Its not explicitly set, check the parent theme configs.
1670 foreach ($this->parent_configs as $config) {
1671 if (isset($config->blockrendermethod)) {
1672 return $config->blockrendermethod;
1675 // Default it to blocks.
1676 return 'blocks';
1681 * This class keeps track of which HTML tags are currently open.
1683 * This makes it much easier to always generate well formed XHTML output, even
1684 * if execution terminates abruptly. Any time you output some opening HTML
1685 * without the matching closing HTML, you should push the necessary close tags
1686 * onto the stack.
1688 * @copyright 2009 Tim Hunt
1689 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1690 * @since Moodle 2.0
1691 * @package core
1692 * @category output
1694 class xhtml_container_stack {
1697 * @var array Stores the list of open containers.
1699 protected $opencontainers = array();
1702 * @var array In developer debug mode, stores a stack trace of all opens and
1703 * closes, so we can output helpful error messages when there is a mismatch.
1705 protected $log = array();
1708 * @var boolean Store whether we are developer debug mode. We need this in
1709 * several places including in the destructor where we may not have access to $CFG.
1711 protected $isdebugging;
1714 * Constructor
1716 public function __construct() {
1717 global $CFG;
1718 $this->isdebugging = $CFG->debugdeveloper;
1722 * Push the close HTML for a recently opened container onto the stack.
1724 * @param string $type The type of container. This is checked when {@link pop()}
1725 * is called and must match, otherwise a developer debug warning is output.
1726 * @param string $closehtml The HTML required to close the container.
1728 public function push($type, $closehtml) {
1729 $container = new stdClass;
1730 $container->type = $type;
1731 $container->closehtml = $closehtml;
1732 if ($this->isdebugging) {
1733 $this->log('Open', $type);
1735 array_push($this->opencontainers, $container);
1739 * Pop the HTML for the next closing container from the stack. The $type
1740 * must match the type passed when the container was opened, otherwise a
1741 * warning will be output.
1743 * @param string $type The type of container.
1744 * @return string the HTML required to close the container.
1746 public function pop($type) {
1747 if (empty($this->opencontainers)) {
1748 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1749 $this->output_log(), DEBUG_DEVELOPER);
1750 return;
1753 $container = array_pop($this->opencontainers);
1754 if ($container->type != $type) {
1755 debugging('<p>The type of container to be closed (' . $container->type .
1756 ') does not match the type of the next open container (' . $type .
1757 '). This suggests there is a nesting problem.</p>' .
1758 $this->output_log(), DEBUG_DEVELOPER);
1760 if ($this->isdebugging) {
1761 $this->log('Close', $type);
1763 return $container->closehtml;
1767 * Close all but the last open container. This is useful in places like error
1768 * handling, where you want to close all the open containers (apart from <body>)
1769 * before outputting the error message.
1771 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1772 * developer debug warning if it isn't.
1773 * @return string the HTML required to close any open containers inside <body>.
1775 public function pop_all_but_last($shouldbenone = false) {
1776 if ($shouldbenone && count($this->opencontainers) != 1) {
1777 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1778 $this->output_log(), DEBUG_DEVELOPER);
1780 $output = '';
1781 while (count($this->opencontainers) > 1) {
1782 $container = array_pop($this->opencontainers);
1783 $output .= $container->closehtml;
1785 return $output;
1789 * You can call this function if you want to throw away an instance of this
1790 * class without properly emptying the stack (for example, in a unit test).
1791 * Calling this method stops the destruct method from outputting a developer
1792 * debug warning. After calling this method, the instance can no longer be used.
1794 public function discard() {
1795 $this->opencontainers = null;
1799 * Adds an entry to the log.
1801 * @param string $action The name of the action
1802 * @param string $type The type of action
1804 protected function log($action, $type) {
1805 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1806 format_backtrace(debug_backtrace()) . '</li>';
1810 * Outputs the log's contents as a HTML list.
1812 * @return string HTML list of the log
1814 protected function output_log() {
1815 return '<ul>' . implode("\n", $this->log) . '</ul>';