weekly release 2.7dev
[moodle.git] / lib / outputlib.php
CommitLineData
571fa828 1<?php
571fa828 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.
13//
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/>.
16
78946b9b
PS
17/**
18 * Functions for generating the HTML that Moodle should output.
19 *
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
21 * for an overview.
22 *
473dd811
SH
23 * @copyright 2009 Tim Hunt
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
f8129210 25 * @package core
76be40cc 26 * @category output
78946b9b
PS
27 */
28
78bfb562
PS
29defined('MOODLE_INTERNAL') || die();
30
d9c8f425 31require_once($CFG->libdir.'/outputcomponents.php');
32require_once($CFG->libdir.'/outputactions.php');
33require_once($CFG->libdir.'/outputfactories.php');
d9c8f425 34require_once($CFG->libdir.'/outputrenderers.php');
0bb38e8c 35require_once($CFG->libdir.'/outputrequirementslib.php');
d9c8f425 36
571fa828 37/**
78946b9b 38 * Invalidate all server and client side caches.
473dd811 39 *
f11db1a6 40 * This method deletes the physical directory that is used to cache the theme
473dd811 41 * files used for serving.
f11db1a6 42 * Because it deletes the main theme cache directory all themes are reset by
473dd811 43 * this function.
78946b9b
PS
44 */
45function theme_reset_all_caches() {
fe7b75f8 46 global $CFG, $PAGE;
78946b9b 47
f11db1a6
PS
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;
54 }
55
56 set_config('themerev', $next); // time is unique even when you reset/switch database
fe7b75f8 57
98245a84
PS
58 if (!empty($CFG->themedesignermode)) {
59 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner');
60 $cache->purge();
61 }
62
fe7b75f8
PS
63 if ($PAGE) {
64 $PAGE->reload_theme();
65 }
78946b9b
PS
66}
67
68/**
69 * Enable or disable theme designer mode.
473dd811 70 *
78946b9b 71 * @param bool $state
78946b9b
PS
72 */
73function theme_set_designer_mod($state) {
78946b9b 74 set_config('themedesignermode', (int)!empty($state));
98245a84
PS
75 // Reset caches after switching mode so that any designer mode caches get purged too.
76 theme_reset_all_caches();
78946b9b
PS
77}
78
79/**
80 * Returns current theme revision number.
473dd811 81 *
78946b9b 82 * @return int
571fa828 83 */
78946b9b
PS
84function theme_get_revision() {
85 global $CFG;
86
87 if (empty($CFG->themedesignermode)) {
88 if (empty($CFG->themerev)) {
89 return -1;
90 } else {
91 return $CFG->themerev;
92 }
93
94 } else {
95 return -1;
96 }
97}
98
571fa828 99
571fa828 100/**
fdeb7fa1 101 * This class represents the configuration variables of a Moodle theme.
102 *
103 * All the variables with access: public below (with a few exceptions that are marked)
3d3fae72 104 * are the properties you can set in your themes config.php file.
fdeb7fa1 105 *
106 * There are also some methods and protected variables that are part of the inner
3d3fae72 107 * workings of Moodle's themes system. If you are just editing a themes config.php
fa1afe32 108 * file, you can just ignore those, and the following information for developers.
ebebf55c 109 *
110 * Normally, to create an instance of this class, you should use the
111 * {@link theme_config::load()} factory method to load a themes config.php file.
fa1afe32 112 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
fdeb7fa1 113 * will create one for you, accessible as $PAGE->theme.
571fa828 114 *
115 * @copyright 2009 Tim Hunt
473dd811
SH
116 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
117 * @since Moodle 2.0
f8129210 118 * @package core
76be40cc 119 * @category output
571fa828 120 */
ebebf55c 121class theme_config {
473dd811 122
5f0baa43 123 /**
76be40cc 124 * @var string Default theme, used when requested theme not found.
5f0baa43 125 */
90723839 126 const DEFAULT_THEME = 'standard';
5f0baa43 127
ebebf55c 128 /**
76be40cc 129 * @var array You can base your theme on other themes by linking to the other theme as
78946b9b 130 * parents. This lets you use the CSS and layouts from the other themes
f8129210 131 * (see {@link theme_config::$layouts}).
fdeb7fa1 132 * That makes it easy to create a new theme that is similar to another one
3d3fae72 133 * but with a few changes. In this themes CSS you only need to override
fdeb7fa1 134 * those rules you want to change.
fdeb7fa1 135 */
78946b9b 136 public $parents;
571fa828 137
fdeb7fa1 138 /**
76be40cc 139 * @var array The names of all the stylesheets from this theme that you would
78946b9b 140 * like included, in order. Give the names of the files without .css.
fdeb7fa1 141 */
78946b9b 142 public $sheets = array();
571fa828 143
fdeb7fa1 144 /**
76be40cc 145 * @var array The names of all the stylesheets from parents that should be excluded.
78946b9b
PS
146 * true value may be used to specify all parents or all themes from one parent.
147 * If no value specified value from parent theme used.
fdeb7fa1 148 */
78946b9b 149 public $parents_exclude_sheets = null;
571fa828 150
fdeb7fa1 151 /**
76be40cc 152 * @var array List of plugin sheets to be excluded.
78946b9b 153 * If no value specified value from parent theme used.
fdeb7fa1 154 */
78946b9b 155 public $plugins_exclude_sheets = null;
571fa828 156
fdeb7fa1 157 /**
76be40cc 158 * @var array List of style sheets that are included in the text editor bodies.
78946b9b 159 * Sheets from parent themes are used automatically and can not be excluded.
fdeb7fa1 160 */
78946b9b 161 public $editor_sheets = array();
571fa828 162
38aafea2 163 /**
76be40cc 164 * @var array The names of all the javascript files this theme that you would
04c01408 165 * like included from head, in order. Give the names of the files without .js.
38aafea2
PS
166 */
167 public $javascripts = array();
168
04c01408 169 /**
76be40cc 170 * @var array The names of all the javascript files this theme that you would
04c01408 171 * like included from footer, in order. Give the names of the files without .js.
04c01408
PS
172 */
173 public $javascripts_footer = array();
4399b9d5 174
38aafea2 175 /**
76be40cc
SH
176 * @var array The names of all the javascript files from parents that should
177 * be excluded. true value may be used to specify all parents or all themes
178 * from one parent.
38aafea2 179 * If no value specified value from parent theme used.
38aafea2
PS
180 */
181 public $parents_exclude_javascripts = null;
182
fdeb7fa1 183 /**
76be40cc 184 * @var array Which file to use for each page layout.
fdeb7fa1 185 *
78946b9b
PS
186 * This is an array of arrays. The keys of the outer array are the different layouts.
187 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
188 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
189 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
d4a03c00 190 * That file also has a good example of how to set this setting.
fdeb7fa1 191 *
78946b9b 192 * For each layout, the value in the outer array is an array that describes
d4a03c00 193 * how you want that type of page to look. For example
194 * <pre>
195 * $THEME->layouts = array(
39df78bf 196 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
191b267b 197 * 'standard' => array(
78946b9b
PS
198 * 'theme' = 'mytheme',
199 * 'file' => 'normal.php',
d4a03c00 200 * 'regions' => array('side-pre', 'side-post'),
201 * 'defaultregion' => 'side-post'
202 * ),
203 * // The site home page.
204 * 'home' => array(
78946b9b
PS
205 * 'theme' = 'mytheme',
206 * 'file' => 'home.php',
d4a03c00 207 * 'regions' => array('side-pre', 'side-post'),
208 * 'defaultregion' => 'side-post'
209 * ),
210 * // ...
211 * );
212 * </pre>
fdeb7fa1 213 *
78946b9b
PS
214 * 'theme' name of the theme where is the layout located
215 * 'file' is the layout file to use for this type of page.
216 * layout files are stored in layout subfolder
d4a03c00 217 * 'regions' This lists the regions on the page where blocks may appear. For
218 * each region you list here, your layout file must include a call to
219 * <pre>
220 * echo $OUTPUT->blocks_for_region($regionname);
221 * </pre>
222 * or equivalent so that the blocks are actually visible.
fdeb7fa1 223 *
d4a03c00 224 * 'defaultregion' If the list of regions is non-empty, then you must pick
225 * one of the one of them as 'default'. This has two meanings. First, this is
226 * where new blocks are added. Second, if there are any blocks associated with
fa1afe32 227 * the page, but in non-existent regions, they appear here. (Imaging, for example,
d4a03c00 228 * that someone added blocks using a different theme that used different region
229 * names, and then switched to this theme.)
fdeb7fa1 230 */
d4a03c00 231 public $layouts = array();
571fa828 232
fdeb7fa1 233 /**
76be40cc
SH
234 * @var string Name of the renderer factory class to use. Must implement the
235 * {@link renderer_factory} interface.
fdeb7fa1 236 *
237 * This is an advanced feature. Moodle output is generated by 'renderers',
238 * you can customise the HTML that is output by writing custom renderers,
239 * and then you need to specify 'renderer factory' so that Moodle can find
240 * your renderers.
241 *
242 * There are some renderer factories supplied with Moodle. Please follow these
243 * links to see what they do.
244 * <ul>
245 * <li>{@link standard_renderer_factory} - the default.</li>
246 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
78946b9b 247 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
fdeb7fa1 248 * </ul>
fdeb7fa1 249 */
ebebf55c 250 public $rendererfactory = 'standard_renderer_factory';
ebebf55c 251
fdeb7fa1 252 /**
76be40cc 253 * @var string Function to do custom CSS post-processing.
fdeb7fa1 254 *
78946b9b
PS
255 * This is an advanced feature. If you want to do custom post-processing on the
256 * CSS before it is output (for example, to replace certain variable names
257 * with particular values) you can give the name of a function here.
fdeb7fa1 258 */
78946b9b 259 public $csspostprocess = null;
571fa828 260
261 /**
76be40cc 262 * @var string Accessibility: Right arrow-like character is
78946b9b
PS
263 * used in the breadcrumb trail, course navigation menu
264 * (previous/next activity), calendar, and search forum block.
265 * If the theme does not set characters, appropriate defaults
266 * are set automatically. Please DO NOT
267 * use &lt; &gt; &raquo; - these are confusing for blind users.
78946b9b
PS
268 */
269 public $rarrow = null;
270
271 /**
76be40cc 272 * @var string Accessibility: Right arrow-like character is
78946b9b
PS
273 * used in the breadcrumb trail, course navigation menu
274 * (previous/next activity), calendar, and search forum block.
275 * If the theme does not set characters, appropriate defaults
276 * are set automatically. Please DO NOT
277 * use &lt; &gt; &raquo; - these are confusing for blind users.
571fa828 278 */
78946b9b
PS
279 public $larrow = null;
280
03276af6 281 /**
76be40cc 282 * @var bool Some themes may want to disable ajax course editing.
03276af6
DM
283 */
284 public $enablecourseajax = true;
78946b9b 285
13725b37
PS
286 /**
287 * @var string Determines served document types
288 * - 'html5' the only officially supported doctype in Moodle
289 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
290 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
291 */
292 public $doctype = 'html5';
293
78946b9b 294 //==Following properties are not configurable from theme config.php==
571fa828 295
fdeb7fa1 296 /**
76be40cc 297 * @var string The name of this theme. Set automatically when this theme is
78946b9b 298 * loaded. This can not be set in theme config.php
fdeb7fa1 299 */
78946b9b 300 public $name;
fdeb7fa1 301
302 /**
76be40cc 303 * @var string The folder where this themes files are stored. This is set
78946b9b 304 * automatically. This can not be set in theme config.php
fdeb7fa1 305 */
78946b9b 306 public $dir;
fdeb7fa1 307
308 /**
76be40cc 309 * @var stdClass Theme settings stored in config_plugins table.
78946b9b 310 * This can not be set in theme config.php
78946b9b
PS
311 */
312 public $setting = null;
313
d2c394f3 314 /**
76be40cc 315 * @var bool If set to true and the theme enables the dock then blocks will be able
d2c394f3 316 * to be moved to the special dock
d2c394f3
SH
317 */
318 public $enable_dock = false;
319
4d56ee95 320 /**
76be40cc 321 * @var bool If set to true then this theme will not be shown in the theme selector unless
4d56ee95 322 * theme designer mode is turned on.
4d56ee95
SH
323 */
324 public $hidefromselector = false;
325
97dbc8f2
PS
326 /**
327 * @var array list of YUI CSS modules to be included on each page. This may be used
328 * to remove cssreset and use cssnormalise module instead.
329 */
330 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
331
36b77e3a
SH
332 /**
333 * An associative array of block manipulations that should be made if the user is using an rtl language.
334 * The key is the original block region, and the value is the block region to change to.
335 * This is used when displaying blocks for regions only.
336 * @var array
337 */
e2ad11d8 338 public $blockrtlmanipulations = array();
36b77e3a 339
78946b9b 340 /**
76be40cc 341 * @var renderer_factory Instance of the renderer_factory implementation
fdeb7fa1 342 * we are using. Implementation detail.
343 */
344 protected $rf = null;
345
346 /**
76be40cc 347 * @var array List of parent config objects.
78946b9b
PS
348 **/
349 protected $parent_configs = array();
fdeb7fa1 350
b305d623
SH
351 /**
352 * @var bool If set to true then the theme is safe to run through the optimiser (if it is enabled)
353 * If set to false then we know either the theme has already been optimised and the CSS optimiser is not needed
354 * or the theme is not compatible with the CSS optimiser. In both cases even if enabled the CSS optimiser will not
355 * be used with this theme if set to false.
356 */
357 public $supportscssoptimisation = true;
358
436dbeec
SH
359 /**
360 * Used to determine whether we can serve SVG images or not.
361 * @var bool
362 */
363 private $usesvg = null;
364
571fa828 365 /**
ebebf55c 366 * Load the config.php file for a particular theme, and return an instance
367 * of this class. (That is, this is a factory method.)
368 *
369 * @param string $themename the name of the theme.
370 * @return theme_config an instance of this class.
571fa828 371 */
ebebf55c 372 public static function load($themename) {
373 global $CFG;
571fa828 374
78946b9b
PS
375 // load theme settings from db
376 try {
377 $settings = get_config('theme_'.$themename);
378 } catch (dml_exception $e) {
da0c0e25 379 // most probably moodle tables not created yet
365a5941 380 $settings = new stdClass();
78946b9b 381 }
ebebf55c 382
78946b9b
PS
383 if ($config = theme_config::find_theme_config($themename, $settings)) {
384 return new theme_config($config);
5f0baa43
PS
385
386 } else if ($themename == theme_config::DEFAULT_THEME) {
387 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
388
2211f504
MA
389 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
390 return new theme_config($config);
391
78946b9b
PS
392 } else {
393 // bad luck, the requested theme has some problems - admin see details in theme config
5f0baa43 394 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
78946b9b
PS
395 }
396 }
ebebf55c 397
78946b9b
PS
398 /**
399 * Theme diagnostic code. It is very problematic to send debug output
400 * to the actual CSS file, instead this functions is supposed to
ae5b6801 401 * diagnose given theme and highlights all potential problems.
78946b9b
PS
402 * This information should be available from the theme selection page
403 * or some other debug page for theme designers.
404 *
405 * @param string $themename
406 * @return array description of problems
407 */
408 public static function diagnose($themename) {
5ef719e7 409 //TODO: MDL-21108
78946b9b
PS
410 return array();
411 }
412
413 /**
414 * Private constructor, can be called only from the factory method.
415 * @param stdClass $config
416 */
417 private function __construct($config) {
418 global $CFG; //needed for included lib.php files
419
420 $this->settings = $config->settings;
421 $this->name = $config->name;
422 $this->dir = $config->dir;
423
424 if ($this->name != 'base') {
425 $baseconfig = theme_config::find_theme_config('base', $this->settings);
426 } else {
427 $baseconfig = $config;
571fa828 428 }
ebebf55c 429
fef27578 430 $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer',
b305d623 431 'parents_exclude_javascripts', 'layouts', 'enable_dock', 'enablecourseajax', 'supportscssoptimisation',
97dbc8f2 432 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector', 'doctype',
36b77e3a 433 'yuicssmodules', 'blockrtlmanipulations');
ebebf55c 434
78946b9b
PS
435 foreach ($config as $key=>$value) {
436 if (in_array($key, $configurable)) {
437 $this->$key = $value;
438 }
439 }
440
441 // verify all parents and load configs and renderers
442 foreach ($this->parents as $parent) {
443 if ($parent == 'base') {
444 $parent_config = $baseconfig;
445 } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
446 // this is not good - better exclude faulty parents
447 continue;
448 }
449 $libfile = $parent_config->dir.'/lib.php';
450 if (is_readable($libfile)) {
451 // theme may store various function here
452 include_once($libfile);
453 }
454 $renderersfile = $parent_config->dir.'/renderers.php';
455 if (is_readable($renderersfile)) {
456 // may contain core and plugin renderers and renderer factory
457 include_once($renderersfile);
458 }
459 $this->parent_configs[$parent] = $parent_config;
78946b9b
PS
460 }
461 $libfile = $this->dir.'/lib.php';
462 if (is_readable($libfile)) {
463 // theme may store various function here
464 include_once($libfile);
465 }
466 $rendererfile = $this->dir.'/renderers.php';
467 if (is_readable($rendererfile)) {
468 // may contain core and plugin renderers and renderer factory
469 include_once($rendererfile);
6fc267a0
BJ
470 } else {
471 // check if renderers.php file is missnamed renderer.php
472 if (is_readable($this->dir.'/renderer.php')) {
473 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
11c0ecce 474 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
6fc267a0 475 }
78946b9b 476 }
4399b9d5 477
78946b9b
PS
478 // cascade all layouts properly
479 foreach ($baseconfig->layouts as $layout=>$value) {
480 if (!isset($this->layouts[$layout])) {
481 foreach ($this->parent_configs as $parent_config) {
482 if (isset($parent_config->layouts[$layout])) {
483 $this->layouts[$layout] = $parent_config->layouts[$layout];
484 continue 2;
485 }
486 }
487 $this->layouts[$layout] = $value;
488 }
489 }
490
491 //fix arrows if needed
492 $this->check_theme_arrows();
571fa828 493 }
494
63c88397
PS
495 /**
496 * Let the theme initialise the page object (usually $PAGE).
497 *
498 * This may be used for example to request jQuery in add-ons.
499 *
500 * @param moodle_page $page
501 */
502 public function init_page(moodle_page $page) {
503 $themeinitfunction = 'theme_'.$this->name.'_page_init';
504 if (function_exists($themeinitfunction)) {
505 $themeinitfunction($page);
506 }
507 }
508
f8129210 509 /**
78946b9b
PS
510 * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
511 * If not it applies sensible defaults.
512 *
513 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
514 * search forum block, etc. Important: these are 'silent' in a screen-reader
515 * (unlike &gt; &raquo;), and must be accompanied by text.
34a2777c 516 */
78946b9b
PS
517 private function check_theme_arrows() {
518 if (!isset($this->rarrow) and !isset($this->larrow)) {
519 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
520 // Also OK in Win 9x/2K/IE 5.x
521 $this->rarrow = '&#x25BA;';
522 $this->larrow = '&#x25C4;';
523 if (empty($_SERVER['HTTP_USER_AGENT'])) {
524 $uagent = '';
ebebf55c 525 } else {
78946b9b
PS
526 $uagent = $_SERVER['HTTP_USER_AGENT'];
527 }
528 if (false !== strpos($uagent, 'Opera')
529 || false !== strpos($uagent, 'Mac')) {
530 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
531 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
532 $this->rarrow = '&#x25B6;';
533 $this->larrow = '&#x25C0;';
534 }
f04721e2 535 elseif ((false !== strpos($uagent, 'Konqueror'))
0179d6be
JF
536 || (false !== strpos($uagent, 'Android'))) {
537 // The fonts on Android don't include the characters required for this to work as expected.
538 // So we use the same ones Konqueror uses.
78946b9b
PS
539 $this->rarrow = '&rarr;';
540 $this->larrow = '&larr;';
541 }
542 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
543 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
544 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
545 // To be safe, non-Unicode browsers!
546 $this->rarrow = '&gt;';
547 $this->larrow = '&lt;';
548 }
549
f8129210 550 // RTL support - in RTL languages, swap r and l arrows
78946b9b
PS
551 if (right_to_left()) {
552 $t = $this->rarrow;
553 $this->rarrow = $this->larrow;
554 $this->larrow = $t;
ebebf55c 555 }
ebebf55c 556 }
78946b9b 557 }
ebebf55c 558
78946b9b
PS
559 /**
560 * Returns output renderer prefixes, these are used when looking
71c03ac1 561 * for the overridden renderers in themes.
473dd811 562 *
78946b9b
PS
563 * @return array
564 */
565 public function renderer_prefixes() {
566 global $CFG; // just in case the included files need it
567
596af93a 568 $prefixes = array('theme_'.$this->name);
78946b9b
PS
569
570 foreach ($this->parent_configs as $parent) {
571 $prefixes[] = 'theme_'.$parent->name;
572 }
573
574 return $prefixes;
34a2777c 575 }
576
571fa828 577 /**
78946b9b 578 * Returns the stylesheet URL of this editor content
473dd811 579 *
78946b9b 580 * @param bool $encoded false means use & and true use &amp; in URLs
1eb2b517 581 * @return moodle_url
571fa828 582 */
78946b9b
PS
583 public function editor_css_url($encoded=true) {
584 global $CFG;
78946b9b 585 $rev = theme_get_revision();
78946b9b 586 if ($rev > -1) {
1eb2b517 587 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
7070b7f2 588 if (!empty($CFG->slasharguments)) {
7070b7f2 589 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
7070b7f2 590 } else {
1eb2b517 591 $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
7070b7f2 592 }
78946b9b
PS
593 } else {
594 $params = array('theme'=>$this->name, 'type'=>'editor');
1eb2b517 595 $url = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
571fa828 596 }
1eb2b517 597 return $url;
571fa828 598 }
599
600 /**
78946b9b 601 * Returns the content of the CSS to be used in editor content
473dd811 602 *
98245a84 603 * @return array
571fa828 604 */
71be124d 605 public function editor_css_files() {
71be124d 606 $files = array();
78946b9b 607
98245a84 608 // First editor plugins.
bd3b3bba 609 $plugins = core_component::get_plugin_list('editor');
78946b9b
PS
610 foreach ($plugins as $plugin=>$fulldir) {
611 $sheetfile = "$fulldir/editor_styles.css";
612 if (is_readable($sheetfile)) {
71be124d 613 $files['plugin_'.$plugin] = $sheetfile;
78946b9b
PS
614 }
615 }
98245a84
PS
616 // Then parent themes - base first, the immediate parent last.
617 foreach (array_reverse($this->parent_configs) as $parent_config) {
78946b9b
PS
618 if (empty($parent_config->editor_sheets)) {
619 continue;
620 }
621 foreach ($parent_config->editor_sheets as $sheet) {
ca194849 622 $sheetfile = "$parent_config->dir/style/$sheet.css";
78946b9b 623 if (is_readable($sheetfile)) {
71be124d 624 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
78946b9b
PS
625 }
626 }
627 }
98245a84 628 // Finally this theme.
78946b9b
PS
629 if (!empty($this->editor_sheets)) {
630 foreach ($this->editor_sheets as $sheet) {
71be124d 631 $sheetfile = "$this->dir/style/$sheet.css";
78946b9b 632 if (is_readable($sheetfile)) {
71be124d 633 $files['theme_'.$sheet] = $sheetfile;
78946b9b
PS
634 }
635 }
636 }
637
71be124d 638 return $files;
571fa828 639 }
640
641 /**
98245a84 642 * Get the stylesheet URL of this theme.
473dd811
SH
643 *
644 * @param moodle_page $page Not used... deprecated?
98245a84 645 * @return moodle_url[]
571fa828 646 */
efaa4c08 647 public function css_urls(moodle_page $page) {
78946b9b
PS
648 global $CFG;
649
650 $rev = theme_get_revision();
651
efaa4c08 652 $urls = array();
efaa4c08 653
383b89a1
SH
654 $svg = $this->use_svg_icons();
655
78946b9b 656 if ($rev > -1) {
383b89a1 657 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
378b3eac 658 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
1eb2b517
SH
659 if (!empty($CFG->slasharguments)) {
660 $slashargs = '';
661 if (!$svg) {
662 // We add a simple /_s to the start of the path.
663 // The underscore is used to ensure that it isn't a valid theme name.
664 $slashargs .= '/_s'.$slashargs;
665 }
666 $slashargs .= '/'.$this->name.'/'.$rev.'/all';
667 if ($separate) {
668 $slashargs .= '/chunk0';
669 }
670 $url->set_slashargument($slashargs, 'noparam', true);
537740cb 671 } else {
1eb2b517
SH
672 $params = array('theme' => $this->name,'rev' => $rev, 'type' => 'all');
673 if (!$svg) {
674 // We add an SVG param so that we know not to serve SVG images.
675 // We do this because all modern browsers support SVG and this param will one day be removed.
676 $params['svg'] = '0';
7070b7f2 677 }
1eb2b517
SH
678 if ($separate) {
679 $params['chunk'] = '0';
680 }
681 $url->params($params);
78946b9b 682 }
1eb2b517
SH
683 $urls[] = $url;
684
78946b9b 685 } else {
98245a84 686 $css = $this->get_css_files(true);
383b89a1
SH
687 $baseurl = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php');
688 if (!$svg) {
689 // We add an SVG param so that we know not to serve SVG images.
690 // We do this because all modern browsers support SVG and this param will one day be removed.
691 $baseurl->param('svg', '0');
692 }
378b3eac 693 if (core_useragent::is_ie()) {
98245a84 694 // Lalala, IE does not allow more than 31 linked CSS files from main document.
71be124d 695 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
a6338a13 696 foreach ($css['parents'] as $parent=>$sheets) {
98245a84 697 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
71be124d 698 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
a6338a13 699 }
71be124d 700 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
c09e1a2c
PS
701
702 } else {
703 foreach ($css['plugins'] as $plugin=>$unused) {
704 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
705 }
706 foreach ($css['parents'] as $parent=>$sheets) {
707 foreach ($sheets as $sheet=>$unused2) {
708 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
709 }
710 }
711 foreach ($css['theme'] as $sheet=>$unused) {
98245a84
PS
712 // Sheet first in order to make long urls easier to read.
713 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
78946b9b 714 }
78946b9b 715 }
78946b9b 716 }
efaa4c08
PS
717
718 return $urls;
571fa828 719 }
34a2777c 720
ebebf55c 721 /**
98245a84 722 * Get the whole css stylesheet for production mode.
473dd811 723 *
31f28b6a
724 * NOTE: this method is not expected to be used from any addons.
725 *
98245a84
PS
726 * @return string CSS markup, already optimised and compressed
727 */
728 public function get_css_content() {
729 global $CFG;
730 require_once($CFG->dirroot.'/lib/csslib.php');
731
732 $csscontent = '';
733 foreach ($this->get_css_files(false) as $value) {
734 foreach ($value as $val) {
735 if (is_array($val)) {
736 foreach ($val as $v) {
737 $csscontent .= file_get_contents($v) . "\n";
738 }
739 } else {
740 $csscontent .= file_get_contents($val) . "\n";
741 }
742 }
743 }
744 $csscontent = $this->post_process($csscontent);
745
746 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
747 // This is an experimental feature introduced in Moodle 2.3
748 // The CSS optimiser organises the CSS in order to reduce the overall number
749 // of rules and styles being sent to the client. It does this by collating
750 // the CSS before it is cached removing excess styles and rules and stripping
751 // out any extraneous content such as comments and empty rules.
752 $optimiser = new css_optimiser();
753 $csscontent = $optimiser->process($csscontent);
754
755 } else {
756 $csscontent = core_minify::css($csscontent);
757 }
758
759 return $csscontent;
760 }
761
762 /**
763 * Get the theme designer css markup,
764 * the parameters are coming from css_urls().
765 *
31f28b6a
766 * NOTE: this method is not expected to be used from any addons.
767 *
98245a84
PS
768 * @param string $type
769 * @param string $subtype
770 * @param string $sheet
771 * @return string CSS markup
ebebf55c 772 */
98245a84
PS
773 public function get_css_content_debug($type, $subtype, $sheet) {
774 global $CFG;
775 require_once($CFG->dirroot.'/lib/csslib.php');
776
777 $optimiser = null;
778 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
779 // This is an experimental feature introduced in Moodle 2.3
780 // The CSS optimiser organises the CSS in order to reduce the overall number
781 // of rules and styles being sent to the client. It does this by collating
782 // the CSS before it is cached removing excess styles and rules and stripping
783 // out any extraneous content such as comments and empty rules.
784 $optimiser = new css_optimiser();
785 }
786
787 $cssfiles = array();
788 $css = $this->get_css_files(true);
789
790 if ($type === 'ie') {
791 // IE is a sloppy browser with weird limits, sorry.
792 if ($subtype === 'plugins') {
793 $cssfiles = $css['plugins'];
794
795 } else if ($subtype === 'parents') {
796 if (empty($sheet)) {
797 // Do not bother with the empty parent here.
798 } else {
799 // Build up the CSS for that parent so we can serve it as one file.
800 foreach ($css[$subtype][$sheet] as $parent => $css) {
801 $cssfiles[] = $css;
802 }
803 }
804 } else if ($subtype === 'theme') {
805 $cssfiles = $css['theme'];
806 }
807
808 } else if ($type === 'plugin') {
809 if (isset($css['plugins'][$subtype])) {
810 $cssfiles[] = $css['plugins'][$subtype];
811 }
812
813 } else if ($type === 'parent') {
814 if (isset($css['parents'][$subtype][$sheet])) {
815 $cssfiles[] = $css['parents'][$subtype][$sheet];
816 }
817
818 } else if ($type === 'theme') {
819 if (isset($css['theme'][$sheet])) {
820 $cssfiles[] = $css['theme'][$sheet];
821 }
822 }
823
824 $csscontent = '';
825 foreach ($cssfiles as $file) {
826 $contents = file_get_contents($file);
827 $contents = $this->post_process($contents);
828 $comment = "/** Path: $type $subtype $sheet.' **/\n";
829 $stats = '';
830 if ($optimiser) {
831 $contents = $optimiser->process($contents);
832 if (!empty($CFG->cssoptimiserstats)) {
833 $stats = $optimiser->output_stats_css();
834 }
835 }
836 $csscontent .= $comment.$stats.$contents."\n\n";
837 }
838
839 return $csscontent;
840 }
841
842 /**
843 * Get the whole css stylesheet for editor iframe.
31f28b6a
844 *
845 * NOTE: this method is not expected to be used from any addons.
846 *
98245a84
PS
847 * @return string CSS markup
848 */
849 public function get_css_content_editor() {
850 // Do not bother to optimise anything here, just very basic stuff.
851 $cssfiles = $this->editor_css_files();
852 $css = '';
853 foreach ($cssfiles as $file) {
854 $css .= file_get_contents($file)."\n";
855 }
856 return $this->post_process($css);
857 }
858
859 /**
860 * Returns an array of organised CSS files required for this output.
861 *
862 * @param bool $themedesigner
863 * @return array nested array of file paths
864 */
865 protected function get_css_files($themedesigner) {
866 global $CFG;
867
868 $cache = null;
869 if ($themedesigner) {
870 require_once($CFG->dirroot.'/lib/csslib.php');
871 // We need some kind of caching here because otherwise the page navigation becomes
872 // way too slow in theme designer mode. Feel free to create full cache definition later...
873 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
874 if ($files = $cache->get('cssfiles')) {
875 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
876 unset($files['created']);
877 return $files;
878 }
879 }
880 }
881
045f492c 882 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
78946b9b 883
98245a84 884 // Get all plugin sheets.
045f492c 885 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
78946b9b 886 if ($excludes !== true) {
46f6f7f2 887 foreach (core_component::get_plugin_types() as $type=>$unused) {
045f492c 888 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
78946b9b
PS
889 continue;
890 }
bd3b3bba 891 $plugins = core_component::get_plugin_list($type);
78946b9b
PS
892 foreach ($plugins as $plugin=>$fulldir) {
893 if (!empty($excludes[$type]) and is_array($excludes[$type])
22c5c6e6 894 and in_array($plugin, $excludes[$type])) {
78946b9b
PS
895 continue;
896 }
f8bb9666 897
22c5c6e6 898 // Add main stylesheet.
78946b9b
PS
899 $sheetfile = "$fulldir/styles.css";
900 if (is_readable($sheetfile)) {
045f492c 901 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
f8bb9666 902 }
22c5c6e6
FM
903
904 // Create a list of candidate sheets from parents (direct parent last) and current theme.
905 $candidates = array();
906 foreach (array_reverse($this->parent_configs) as $parent_config) {
907 $candidates[] = $parent_config->name;
f8bb9666 908 }
22c5c6e6
FM
909 $candidates[] = $this->name;
910
911 // Add the sheets found.
912 foreach ($candidates as $candidate) {
913 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
914 if (is_readable($sheetthemefile)) {
915 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
916 }
78946b9b
PS
917 }
918 }
919 }
22c5c6e6 920 }
34a2777c 921
98245a84 922 // Find out wanted parent sheets.
045f492c 923 $excludes = $this->resolve_excludes('parents_exclude_sheets');
78946b9b 924 if ($excludes !== true) {
98245a84 925 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
78946b9b 926 $parent = $parent_config->name;
045f492c 927 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
78946b9b
PS
928 continue;
929 }
930 foreach ($parent_config->sheets as $sheet) {
931 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
932 and in_array($sheet, $excludes[$parent])) {
933 continue;
934 }
935 $sheetfile = "$parent_config->dir/style/$sheet.css";
936 if (is_readable($sheetfile)) {
045f492c 937 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
78946b9b
PS
938 }
939 }
940 }
941 }
34a2777c 942
98245a84 943 // Current theme sheets.
78946b9b
PS
944 if (is_array($this->sheets)) {
945 foreach ($this->sheets as $sheet) {
946 $sheetfile = "$this->dir/style/$sheet.css";
947 if (is_readable($sheetfile)) {
045f492c 948 $cssfiles['theme'][$sheet] = $sheetfile;
78946b9b 949 }
ebebf55c 950 }
78946b9b
PS
951 }
952
98245a84
PS
953 if ($cache) {
954 $files = $cssfiles;
955 $files['created'] = time();
956 $cache->set('cssfiles', $files);
045f492c 957 }
045f492c 958
98245a84
PS
959 return $cssfiles;
960 }
e68c5f36
PS
961
962 /**
473dd811
SH
963 * Generate a URL to the file that serves theme JavaScript files.
964 *
d7656956
ARN
965 * If we determine that the theme has no relevant files, then we return
966 * early with a null value.
967 *
71c03ac1 968 * @param bool $inhead true means head url, false means footer
d7656956 969 * @return moodle_url|null
e68c5f36 970 */
baeb20bb 971 public function javascript_url($inhead) {
e68c5f36
PS
972 global $CFG;
973
974 $rev = theme_get_revision();
e68c5f36 975 $params = array('theme'=>$this->name,'rev'=>$rev);
baeb20bb
PS
976 $params['type'] = $inhead ? 'head' : 'footer';
977
d7656956
ARN
978 // Return early if there are no files to serve
979 if (count($this->javascript_files($params['type'])) === 0) {
980 return null;
981 }
982
ecbad2ad
PS
983 if (!empty($CFG->slasharguments) and $rev > 0) {
984 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
985 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
986 return $url;
987 } else {
988 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
989 }
e68c5f36
PS
990 }
991
473dd811
SH
992 /**
993 * Get the URL's for the JavaScript files used by this theme.
994 * They won't be served directly, instead they'll be mediated through
995 * theme/javascript.php.
996 *
997 * @param string $type Either javascripts_footer, or javascripts
998 * @return array
999 */
045f492c
SH
1000 public function javascript_files($type) {
1001 if ($type === 'footer') {
1002 $type = 'javascripts_footer';
1003 } else {
f856106b 1004 $type = 'javascripts';
045f492c 1005 }
04c01408 1006
358c13cb
PS
1007 $js = array();
1008 // find out wanted parent javascripts
045f492c 1009 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
358c13cb
PS
1010 if ($excludes !== true) {
1011 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1012 $parent = $parent_config->name;
04c01408 1013 if (empty($parent_config->$type)) {
358c13cb
PS
1014 continue;
1015 }
1016 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1017 continue;
1018 }
04c01408 1019 foreach ($parent_config->$type as $javascript) {
358c13cb
PS
1020 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1021 and in_array($javascript, $excludes[$parent])) {
1022 continue;
1023 }
1024 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1025 if (is_readable($javascriptfile)) {
045f492c 1026 $js[] = $javascriptfile;
358c13cb
PS
1027 }
1028 }
1029 }
1030 }
1031
1032 // current theme javascripts
04c01408
PS
1033 if (is_array($this->$type)) {
1034 foreach ($this->$type as $javascript) {
358c13cb
PS
1035 $javascriptfile = "$this->dir/javascript/$javascript.js";
1036 if (is_readable($javascriptfile)) {
045f492c
SH
1037 $js[] = $javascriptfile;
1038 }
1039 }
1040 }
045f492c
SH
1041 return $js;
1042 }
1043
1044 /**
3d3fae72 1045 * Resolves an exclude setting to the themes setting is applicable or the
045f492c
SH
1046 * setting of its closest parent.
1047 *
1048 * @param string $variable The name of the setting the exclude setting to resolve
f8129210 1049 * @param string $default
045f492c
SH
1050 * @return mixed
1051 */
f8129210 1052 protected function resolve_excludes($variable, $default = null) {
045f492c
SH
1053 $setting = $default;
1054 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1055 $setting = $this->{$variable};
1056 } else {
1057 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1058 if (!isset($parent_config->{$variable})) {
1059 continue;
1060 }
1061 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1062 $setting = $parent_config->{$variable};
1063 break;
358c13cb
PS
1064 }
1065 }
1066 }
045f492c
SH
1067 return $setting;
1068 }
358c13cb 1069
045f492c
SH
1070 /**
1071 * Returns the content of the one huge javascript file merged from all theme javascript files.
473dd811 1072 *
f8129210 1073 * @param bool $type
045f492c
SH
1074 * @return string
1075 */
1076 public function javascript_content($type) {
1077 $jsfiles = $this->javascript_files($type);
1078 $js = '';
1079 foreach ($jsfiles as $jsfile) {
1080 $js .= file_get_contents($jsfile)."\n";
1081 }
1082 return $js;
e68c5f36
PS
1083 }
1084
473dd811
SH
1085 /**
1086 * Post processes CSS.
1087 *
1088 * This method post processes all of the CSS before it is served for this theme.
1089 * This is done so that things such as image URL's can be swapped in and to
1090 * run any specific CSS post process method the theme has requested.
3d3fae72 1091 * This allows themes to use CSS settings.
473dd811
SH
1092 *
1093 * @param string $css The CSS to process.
1094 * @return string The processed CSS.
1095 */
045f492c 1096 public function post_process($css) {
78946b9b 1097 // now resolve all image locations
37824e73 1098 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
78946b9b
PS
1099 $replaced = array();
1100 foreach ($matches as $match) {
1101 if (isset($replaced[$match[0]])) {
1102 continue;
1103 }
1104 $replaced[$match[0]] = true;
1105 $imagename = $match[2];
1106 $component = rtrim($match[1], '|');
b9bc2019 1107 $imageurl = $this->pix_url($imagename, $component)->out(false);
df06c1c4 1108 // we do not need full url because the image.php is always in the same dir
9d473266 1109 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
df06c1c4 1110 $css = str_replace($match[0], $imageurl, $css);
ebebf55c 1111 }
34a2777c 1112 }
17a6649b 1113
9ba6076c 1114 // Now resolve all font locations.
37824e73 1115 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
9ba6076c
PS
1116 $replaced = array();
1117 foreach ($matches as $match) {
1118 if (isset($replaced[$match[0]])) {
1119 continue;
1120 }
1121 $replaced[$match[0]] = true;
1122 $fontname = $match[2];
1123 $component = rtrim($match[1], '|');
1124 $fonturl = $this->font_url($fontname, $component)->out(false);
1125 // We do not need full url because the font.php is always in the same dir.
1126 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1127 $css = str_replace($match[0], $fonturl, $css);
1128 }
1129 }
1130
78946b9b
PS
1131 // now resolve all theme settings or do any other postprocessing
1132 $csspostprocess = $this->csspostprocess;
1133 if (function_exists($csspostprocess)) {
1134 $css = $csspostprocess($css, $this);
fdeb7fa1 1135 }
1136
78946b9b 1137 return $css;
ebebf55c 1138 }
17a6649b 1139
ebebf55c 1140 /**
78946b9b
PS
1141 * Return the URL for an image
1142 *
1143 * @param string $imagename the name of the icon.
f8129210 1144 * @param string $component specification of one plugin like in get_string()
78946b9b 1145 * @return moodle_url
fdeb7fa1 1146 */
c39e5ba2 1147 public function pix_url($imagename, $component) {
fdeb7fa1 1148 global $CFG;
78946b9b 1149
9d473266 1150 $params = array('theme'=>$this->name);
436dbeec 1151 $svg = $this->use_svg_icons();
9d473266
PS
1152
1153 if (empty($component) or $component === 'moodle' or $component === 'core') {
1154 $params['component'] = 'core';
1155 } else {
1156 $params['component'] = $component;
1157 }
78946b9b
PS
1158
1159 $rev = theme_get_revision();
1160 if ($rev != -1) {
1161 $params['rev'] = $rev;
1162 }
9d473266
PS
1163
1164 $params['image'] = $imagename;
1165
436dbeec 1166 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
9d473266 1167 if (!empty($CFG->slasharguments) and $rev > 0) {
436dbeec
SH
1168 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1169 if (!$svg) {
1170 // We add a simple /_s to the start of the path.
1171 // The underscore is used to ensure that it isn't a valid theme name.
1172 $path = '/_s'.$path;
1173 }
1174 $url->set_slashargument($path, 'noparam', true);
9d473266 1175 } else {
436dbeec
SH
1176 if (!$svg) {
1177 // We add an SVG param so that we know not to serve SVG images.
1178 // We do this because all modern browsers support SVG and this param will one day be removed.
1179 $params['svg'] = '0';
1180 }
1181 $url->params($params);
fdeb7fa1 1182 }
78946b9b 1183
9d473266 1184 return $url;
fdeb7fa1 1185 }
1186
9ba6076c
PS
1187 /**
1188 * Return the URL for a font
1189 *
1190 * @param string $font the name of the font (including extension).
1191 * @param string $component specification of one plugin like in get_string()
1192 * @return moodle_url
1193 */
1194 public function font_url($font, $component) {
1195 global $CFG;
1196
1197 $params = array('theme'=>$this->name);
1198
1199 if (empty($component) or $component === 'moodle' or $component === 'core') {
1200 $params['component'] = 'core';
1201 } else {
1202 $params['component'] = $component;
1203 }
1204
1205 $rev = theme_get_revision();
1206 if ($rev != -1) {
1207 $params['rev'] = $rev;
1208 }
1209
1210 $params['font'] = $font;
1211
1212 $url = new moodle_url("$CFG->httpswwwroot/theme/font.php");
1213 if (!empty($CFG->slasharguments) and $rev > 0) {
1214 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1215 $url->set_slashargument($path, 'noparam', true);
1216 } else {
1217 $url->params($params);
1218 }
1219
1220 return $url;
1221 }
1222
fe7b75f8
PS
1223 /**
1224 * Returns URL to the stored file via pluginfile.php.
1225 *
1226 * Note the theme must also implement pluginfile.php handler,
1227 * theme revision is used instead of the itemid.
1228 *
1229 * @param string $setting
1230 * @param string $filearea
1231 * @return string protocol relative URL or null if not present
1232 */
1233 public function setting_file_url($setting, $filearea) {
1234 global $CFG;
1235
1236 if (empty($this->settings->$setting)) {
1237 return null;
1238 }
1239
1240 $component = 'theme_'.$this->name;
1241 $itemid = theme_get_revision();
1242 $filepath = $this->settings->$setting;
1243 $syscontext = context_system::instance();
1244
1245 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1246
1247 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1248 // Note: unfortunately moodle_url does not support //urls yet.
1249
1250 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1251
1252 return $url;
1253 }
1254
1255 /**
1256 * Serve the theme setting file.
1257 *
1258 * @param string $filearea
1259 * @param array $args
1260 * @param bool $forcedownload
1261 * @param array $options
1262 * @return bool may terminate if file not found or donotdie not specified
1263 */
1264 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1265 global $CFG;
1266 require_once("$CFG->libdir/filelib.php");
1267
1268 $syscontext = context_system::instance();
1269 $component = 'theme_'.$this->name;
1270
1271 $revision = array_shift($args);
1272 if ($revision < 0) {
1273 $lifetime = 0;
1274 } else {
1275 $lifetime = 60*60*24*60;
1276 }
1277
1278 $fs = get_file_storage();
1279 $relativepath = implode('/', $args);
1280
1281 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1282 $fullpath = rtrim($fullpath, '/');
1283 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1284 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1285 return true;
1286 } else {
1287 send_file_not_found();
1288 }
1289 }
1290
fdeb7fa1 1291 /**
78946b9b 1292 * Resolves the real image location.
436dbeec
SH
1293 *
1294 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1295 * and we need a way in which to turn it off.
1296 * By default SVG won't be used unless asked for. This is done for two reasons:
1297 * 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
1298 * browser supports SVG.
1299 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1300 * by the user due to security concerns.
1301 *
78946b9b
PS
1302 * @param string $image name of image, may contain relative path
1303 * @param string $component
436dbeec 1304 * @param bool $svg If set to true SVG images will also be looked for.
78946b9b 1305 * @return string full file path
fdeb7fa1 1306 */
436dbeec 1307 public function resolve_image_location($image, $component, $svg = false) {
78946b9b
PS
1308 global $CFG;
1309
436dbeec
SH
1310 if (!is_bool($svg)) {
1311 // If $svg isn't a bool then we need to decide for ourselves.
1312 $svg = $this->use_svg_icons();
1313 }
1314
78946b9b 1315 if ($component === 'moodle' or $component === 'core' or empty($component)) {
436dbeec 1316 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
78946b9b
PS
1317 return $imagefile;
1318 }
1319 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
436dbeec 1320 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
78946b9b
PS
1321 return $imagefile;
1322 }
1323 }
436dbeec 1324 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
f930cf6b
EM
1325 return $imagefile;
1326 }
436dbeec 1327 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
78946b9b
PS
1328 return $imagefile;
1329 }
1330 return null;
1331
1332 } else if ($component === 'theme') { //exception
1333 if ($image === 'favicon') {
1334 return "$this->dir/pix/favicon.ico";
1335 }
436dbeec 1336 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
78946b9b
PS
1337 return $imagefile;
1338 }
1339 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
436dbeec 1340 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
78946b9b
PS
1341 return $imagefile;
1342 }
1343 }
1344 return null;
1345
78946b9b
PS
1346 } else {
1347 if (strpos($component, '_') === false) {
1348 $component = 'mod_'.$component;
1349 }
1350 list($type, $plugin) = explode('_', $component, 2);
1351
436dbeec 1352 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
78946b9b
PS
1353 return $imagefile;
1354 }
1355 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
436dbeec 1356 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
78946b9b
PS
1357 return $imagefile;
1358 }
1359 }
436dbeec 1360 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
f930cf6b
EM
1361 return $imagefile;
1362 }
1c74b260 1363 $dir = core_component::get_plugin_directory($type, $plugin);
436dbeec 1364 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
78946b9b
PS
1365 return $imagefile;
1366 }
1367 return null;
fdeb7fa1 1368 }
fdeb7fa1 1369 }
1370
9ba6076c
PS
1371 /**
1372 * Resolves the real font location.
1373 *
1374 * @param string $font name of font file
1375 * @param string $component
1376 * @return string full file path
1377 */
1378 public function resolve_font_location($font, $component) {
1379 global $CFG;
1380
1381 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1382 if (file_exists("$this->dir/fonts_core/$font")) {
1383 return "$this->dir/fonts_core/$font";
1384 }
1385 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1386 if (file_exists("$parent_config->dir/fonts_core/$font")) {
1387 return "$parent_config->dir/fonts_core/$font";
1388 }
1389 }
1390 if (file_exists("$CFG->dataroot/fonts/$font")) {
1391 return "$CFG->dataroot/fonts/$font";
1392 }
1393 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
1394 return "$CFG->dirroot/lib/fonts/$font";
1395 }
1396 return null;
1397
1398 } else if ($component === 'theme') { // Exception.
1399 if (file_exists("$this->dir/fonts/$font")) {
1400 return "$this->dir/fonts/$font";
1401 }
1402 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1403 if (file_exists("$parent_config->dir/fonts/$font")) {
1404 return "$parent_config->dir/fonts/$font";
1405 }
1406 }
1407 return null;
1408
1409 } else {
1410 if (strpos($component, '_') === false) {
1411 $component = 'mod_'.$component;
1412 }
1413 list($type, $plugin) = explode('_', $component, 2);
1414
1415 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
1416 return "$this->dir/fonts_plugins/$type/$plugin/$font";
1417 }
1418 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1419 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
1420 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
1421 }
1422 }
1423 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
1424 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
1425 }
1426 $dir = core_component::get_plugin_directory($type, $plugin);
1427 if (file_exists("$dir/fonts/$font")) {
1428 return "$dir/fonts/$font";
1429 }
1430 return null;
1431 }
1432 }
1433
436dbeec
SH
1434 /**
1435 * Return true if we should look for SVG images as well.
1436 *
436dbeec
SH
1437 * @return bool
1438 */
1439 public function use_svg_icons() {
1440 global $CFG;
1441 if ($this->usesvg === null) {
c3d2fbf9 1442
436dbeec 1443 if (!isset($CFG->svgicons) || !is_bool($CFG->svgicons)) {
c3d2fbf9 1444 $this->usesvg = core_useragent::supports_svg();
436dbeec
SH
1445 } else {
1446 // Force them on/off depending upon the setting.
1447 $this->usesvg = $CFG->svgicons;
1448 }
1449 }
1450 return $this->usesvg;
1451 }
1452
f7d6a556
SH
1453 /**
1454 * Forces the usesvg setting to either true or false, avoiding any decision making.
1455 *
1456 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
383b89a1 1457 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
f7d6a556
SH
1458 *
1459 * @param bool $setting True to force the use of svg when available, null otherwise.
1460 */
383b89a1 1461 public function force_svg_use($setting) {
f7d6a556
SH
1462 $this->usesvg = (bool)$setting;
1463 }
1464
d4a03c00 1465 /**
78946b9b 1466 * Checks if file with any image extension exists.
473dd811 1467 *
436dbeec
SH
1468 * The order to these images was adjusted prior to the release of 2.4
1469 * At that point the were the following image counts in Moodle core:
1470 *
1471 * - png = 667 in pix dirs (1499 total)
1472 * - gif = 385 in pix dirs (606 total)
1473 * - jpg = 62 in pix dirs (74 total)
1474 * - jpeg = 0 in pix dirs (1 total)
1475 *
1476 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1477 *
78946b9b 1478 * @param string $filepath
436dbeec 1479 * @param bool $svg If set to true SVG images will also be looked for.
78946b9b 1480 * @return string image name with extension
d4a03c00 1481 */
436dbeec
SH
1482 private static function image_exists($filepath, $svg = false) {
1483 if ($svg && file_exists("$filepath.svg")) {
1484 return "$filepath.svg";
78946b9b
PS
1485 } else if (file_exists("$filepath.png")) {
1486 return "$filepath.png";
436dbeec
SH
1487 } else if (file_exists("$filepath.gif")) {
1488 return "$filepath.gif";
78946b9b
PS
1489 } else if (file_exists("$filepath.jpg")) {
1490 return "$filepath.jpg";
1491 } else if (file_exists("$filepath.jpeg")) {
1492 return "$filepath.jpeg";
d4a03c00 1493 } else {
78946b9b 1494 return false;
d4a03c00 1495 }
1496 }
1497
fdeb7fa1 1498 /**
78946b9b 1499 * Loads the theme config from config.php file.
473dd811 1500 *
78946b9b 1501 * @param string $themename
473dd811 1502 * @param stdClass $settings from config_plugins table
b0ec47fb 1503 * @param boolean $parentscheck true to also check the parents. .
473dd811 1504 * @return stdClass The theme configuration
fdeb7fa1 1505 */
b0ec47fb 1506 private static function find_theme_config($themename, $settings, $parentscheck = true) {
78946b9b
PS
1507 // We have to use the variable name $THEME (upper case) because that
1508 // is what is used in theme config.php files.
fdeb7fa1 1509
78946b9b
PS
1510 if (!$dir = theme_config::find_theme_location($themename)) {
1511 return null;
fdeb7fa1 1512 }
2f67a9b3 1513
365a5941 1514 $THEME = new stdClass();
78946b9b
PS
1515 $THEME->name = $themename;
1516 $THEME->dir = $dir;
1517 $THEME->settings = $settings;
1518
1519 global $CFG; // just in case somebody tries to use $CFG in theme config
1520 include("$THEME->dir/config.php");
1521
1522 // verify the theme configuration is OK
1523 if (!is_array($THEME->parents)) {
1524 // parents option is mandatory now
1525 return null;
b0ec47fb
JM
1526 } else {
1527 // We use $parentscheck to only check the direct parents (avoid infinite loop).
1528 if ($parentscheck) {
1529 // Find all parent theme configs.
1530 foreach ($THEME->parents as $parent) {
1531 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
1532 if (empty($parentconfig)) {
1533 return null;
1534 }
1535 }
1536 }
fdeb7fa1 1537 }
1538
78946b9b 1539 return $THEME;
fdeb7fa1 1540 }
1541
d4a03c00 1542 /**
78946b9b
PS
1543 * Finds the theme location and verifies the theme has all needed files
1544 * and is not obsoleted.
473dd811 1545 *
78946b9b
PS
1546 * @param string $themename
1547 * @return string full dir path or null if not found
d4a03c00 1548 */
78946b9b
PS
1549 private static function find_theme_location($themename) {
1550 global $CFG;
1551
1552 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1553 $dir = "$CFG->dirroot/theme/$themename";
d4a03c00 1554
3dd1d7e7
DM
1555 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1556 $dir = "$CFG->themedir/$themename";
1557
7d875874 1558 } else {
78946b9b 1559 return null;
d4a03c00 1560 }
78946b9b
PS
1561
1562 if (file_exists("$dir/styles.php")) {
1563 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1564 return null;
1565 }
2f67a9b3 1566
78946b9b 1567 return $dir;
d4a03c00 1568 }
1569
1d13c75c 1570 /**
78946b9b 1571 * Get the renderer for a part of Moodle for this theme.
473dd811 1572 *
78946b9b 1573 * @param moodle_page $page the page we are rendering
f8129210 1574 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
78946b9b 1575 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
c927e35c 1576 * @param string $target one of rendering target constants
78946b9b 1577 * @return renderer_base the requested renderer.
1d13c75c 1578 */
c927e35c 1579 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
78946b9b 1580 if (is_null($this->rf)) {
c927e35c 1581 $classname = $this->rendererfactory;
78946b9b 1582 $this->rf = new $classname($this);
1d13c75c 1583 }
78946b9b 1584
c927e35c 1585 return $this->rf->get_renderer($page, $component, $subtype, $target);
1d13c75c 1586 }
1587
fdeb7fa1 1588 /**
78946b9b 1589 * Get the information from {@link $layouts} for this type of page.
473dd811 1590 *
78946b9b
PS
1591 * @param string $pagelayout the the page layout name.
1592 * @return array the appropriate part of {@link $layouts}.
fdeb7fa1 1593 */
78946b9b
PS
1594 protected function layout_info_for_page($pagelayout) {
1595 if (array_key_exists($pagelayout, $this->layouts)) {
1596 return $this->layouts[$pagelayout];
1597 } else {
191b267b
PS
1598 debugging('Invalid page layout specified: ' . $pagelayout);
1599 return $this->layouts['standard'];
fdeb7fa1 1600 }
1601 }
1602
1603 /**
78946b9b
PS
1604 * Given the settings of this theme, and the page pagelayout, return the
1605 * full path of the page layout file to use.
1606 *
1607 * Used by {@link core_renderer::header()}.
1608 *
1609 * @param string $pagelayout the the page layout name.
1610 * @return string Full path to the lyout file to use
ebebf55c 1611 */
78946b9b 1612 public function layout_file($pagelayout) {
ebebf55c 1613 global $CFG;
fdeb7fa1 1614
78946b9b
PS
1615 $layoutinfo = $this->layout_info_for_page($pagelayout);
1616 $layoutfile = $layoutinfo['file'];
fdeb7fa1 1617
84db3ea2
SH
1618 if (array_key_exists('theme', $layoutinfo)) {
1619 $themes = array($layoutinfo['theme']);
1620 } else {
1621 $themes = array_merge(array($this->name),$this->parents);
1622 }
4399b9d5 1623
84db3ea2
SH
1624 foreach ($themes as $theme) {
1625 if ($dir = $this->find_theme_location($theme)) {
1626 $path = "$dir/layout/$layoutfile";
1627
1628 // Check the template exists, return general base theme template if not.
1629 if (is_readable($path)) {
1630 return $path;
1631 }
78946b9b 1632 }
34a2777c 1633 }
1634
191b267b 1635 debugging('Can not find layout file for: ' . $pagelayout);
78946b9b
PS
1636 // fallback to standard normal layout
1637 return "$CFG->dirroot/theme/base/layout/general.php";
1638 }
ebebf55c 1639
78946b9b
PS
1640 /**
1641 * Returns auxiliary page layout options specified in layout configuration array.
473dd811 1642 *
78946b9b
PS
1643 * @param string $pagelayout
1644 * @return array
1645 */
1646 public function pagelayout_options($pagelayout) {
1647 $info = $this->layout_info_for_page($pagelayout);
1648 if (!empty($info['options'])) {
1649 return $info['options'];
34a2777c 1650 }
78946b9b
PS
1651 return array();
1652 }
34a2777c 1653
78946b9b
PS
1654 /**
1655 * Inform a block_manager about the block regions this theme wants on this
1656 * page layout.
473dd811 1657 *
78946b9b
PS
1658 * @param string $pagelayout the general type of the page.
1659 * @param block_manager $blockmanager the block_manger to set up.
78946b9b
PS
1660 */
1661 public function setup_blocks($pagelayout, $blockmanager) {
1662 $layoutinfo = $this->layout_info_for_page($pagelayout);
1663 if (!empty($layoutinfo['regions'])) {
1664 $blockmanager->add_regions($layoutinfo['regions']);
1665 $blockmanager->set_default_region($layoutinfo['defaultregion']);
ebebf55c 1666 }
34a2777c 1667 }
1668
473dd811
SH
1669 /**
1670 * Gets the visible name for the requested block region.
1671 *
1672 * @param string $region The region name to get
1673 * @param string $theme The theme the region belongs to (may come from the parent theme)
1674 * @return string
1675 */
cadc0d28
TH
1676 protected function get_region_name($region, $theme) {
1677 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1678 // A name exists in this theme, so use it
1679 if (substr($regionstring, 0, 1) != '[') {
1680 return $regionstring;
1681 }
1682
1683 // Otherwise, try to find one elsewhere
1684 // Check parents, if any
1685 foreach ($this->parents as $parentthemename) {
1686 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1687 if (substr($regionstring, 0, 1) != '[') {
1688 return $regionstring;
1689 }
1690 }
1691
1692 // Last resort, try the base theme for names
1693 return get_string('region-' . $region, 'theme_base');
1694 }
1695
ebebf55c 1696 /**
78946b9b 1697 * Get the list of all block regions known to this theme in all templates.
473dd811 1698 *
78946b9b 1699 * @return array internal region name => human readable name.
ebebf55c 1700 */
78946b9b
PS
1701 public function get_all_block_regions() {
1702 $regions = array();
78946b9b
PS
1703 foreach ($this->layouts as $layoutinfo) {
1704 foreach ($layoutinfo['regions'] as $region) {
a9535f79 1705 $regions[$region] = $this->get_region_name($region, $this->name);
ebebf55c 1706 }
34a2777c 1707 }
78946b9b 1708 return $regions;
34a2777c 1709 }
d609d962
SH
1710
1711 /**
1712 * Returns the human readable name of the theme
1713 *
1714 * @return string
1715 */
1716 public function get_theme_name() {
1717 return get_string('pluginname', 'theme_'.$this->name);
1718 }
ebebf55c 1719}
34a2777c 1720
ebebf55c 1721/**
d9c8f425 1722 * This class keeps track of which HTML tags are currently open.
1723 *
1724 * This makes it much easier to always generate well formed XHTML output, even
1725 * if execution terminates abruptly. Any time you output some opening HTML
1726 * without the matching closing HTML, you should push the necessary close tags
1727 * onto the stack.
ebebf55c 1728 *
1729 * @copyright 2009 Tim Hunt
473dd811
SH
1730 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1731 * @since Moodle 2.0
f8129210 1732 * @package core
76be40cc 1733 * @category output
ebebf55c 1734 */
d9c8f425 1735class xhtml_container_stack {
473dd811
SH
1736
1737 /**
76be40cc 1738 * @var array Stores the list of open containers.
473dd811 1739 */
d9c8f425 1740 protected $opencontainers = array();
473dd811 1741
fa1afe32 1742 /**
76be40cc 1743 * @var array In developer debug mode, stores a stack trace of all opens and
d9c8f425 1744 * closes, so we can output helpful error messages when there is a mismatch.
fa1afe32 1745 */
d9c8f425 1746 protected $log = array();
473dd811 1747
fa1afe32 1748 /**
76be40cc
SH
1749 * @var boolean Store whether we are developer debug mode. We need this in
1750 * several places including in the destructor where we may not have access to $CFG.
fa1afe32 1751 */
d9c8f425 1752 protected $isdebugging;
34a2777c 1753
473dd811
SH
1754 /**
1755 * Constructor
1756 */
d9c8f425 1757 public function __construct() {
96f81ea3
PS
1758 global $CFG;
1759 $this->isdebugging = $CFG->debugdeveloper;
ebebf55c 1760 }
34a2777c 1761
fa1afe32 1762 /**
d9c8f425 1763 * Push the close HTML for a recently opened container onto the stack.
473dd811 1764 *
d9c8f425 1765 * @param string $type The type of container. This is checked when {@link pop()}
1766 * is called and must match, otherwise a developer debug warning is output.
1767 * @param string $closehtml The HTML required to close the container.
fa1afe32 1768 */
d9c8f425 1769 public function push($type, $closehtml) {
1770 $container = new stdClass;
1771 $container->type = $type;
1772 $container->closehtml = $closehtml;
1773 if ($this->isdebugging) {
1774 $this->log('Open', $type);
3aaa27f4 1775 }
d9c8f425 1776 array_push($this->opencontainers, $container);
ebebf55c 1777 }
34a2777c 1778
fa1afe32 1779 /**
d9c8f425 1780 * Pop the HTML for the next closing container from the stack. The $type
1781 * must match the type passed when the container was opened, otherwise a
1782 * warning will be output.
473dd811 1783 *
d9c8f425 1784 * @param string $type The type of container.
1785 * @return string the HTML required to close the container.
fa1afe32 1786 */
d9c8f425 1787 public function pop($type) {
1788 if (empty($this->opencontainers)) {
1789 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1790 $this->output_log(), DEBUG_DEVELOPER);
1791 return;
3aaa27f4 1792 }
ebebf55c 1793
d9c8f425 1794 $container = array_pop($this->opencontainers);
1795 if ($container->type != $type) {
1796 debugging('<p>The type of container to be closed (' . $container->type .
1797 ') does not match the type of the next open container (' . $type .
1798 '). This suggests there is a nesting problem.</p>' .
1799 $this->output_log(), DEBUG_DEVELOPER);
ebebf55c 1800 }
d9c8f425 1801 if ($this->isdebugging) {
1802 $this->log('Close', $type);
e8775320 1803 }
d9c8f425 1804 return $container->closehtml;
ebebf55c 1805 }
e8775320 1806
fa1afe32 1807 /**
d9c8f425 1808 * Close all but the last open container. This is useful in places like error
1809 * handling, where you want to close all the open containers (apart from <body>)
1810 * before outputting the error message.
473dd811 1811 *
d9c8f425 1812 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1813 * developer debug warning if it isn't.
1814 * @return string the HTML required to close any open containers inside <body>.
fa1afe32 1815 */
d9c8f425 1816 public function pop_all_but_last($shouldbenone = false) {
1817 if ($shouldbenone && count($this->opencontainers) != 1) {
1818 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1819 $this->output_log(), DEBUG_DEVELOPER);
1820 }
1821 $output = '';
1822 while (count($this->opencontainers) > 1) {
1823 $container = array_pop($this->opencontainers);
1824 $output .= $container->closehtml;
e8775320 1825 }
d9c8f425 1826 return $output;
e8775320 1827 }
34a2777c 1828
ebebf55c 1829 /**
d9c8f425 1830 * You can call this function if you want to throw away an instance of this
1831 * class without properly emptying the stack (for example, in a unit test).
1832 * Calling this method stops the destruct method from outputting a developer
1833 * debug warning. After calling this method, the instance can no longer be used.
ebebf55c 1834 */
d9c8f425 1835 public function discard() {
1836 $this->opencontainers = null;
ebebf55c 1837 }
d9c8f425 1838
fa1afe32 1839 /**
d9c8f425 1840 * Adds an entry to the log.
473dd811 1841 *
d9c8f425 1842 * @param string $action The name of the action
1843 * @param string $type The type of action
fa1afe32 1844 */
d9c8f425 1845 protected function log($action, $type) {
1846 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1847 format_backtrace(debug_backtrace()) . '</li>';
ebebf55c 1848 }
34a2777c 1849
fa1afe32 1850 /**
d9c8f425 1851 * Outputs the log's contents as a HTML list.
473dd811 1852 *
d9c8f425 1853 * @return string HTML list of the log
fa1afe32 1854 */
d9c8f425 1855 protected function output_log() {
1856 return '<ul>' . implode("\n", $this->log) . '</ul>';
34a2777c 1857 }
6fc267a0 1858}