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