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