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 581 * @param bool $encoded false means use & and true use &amp; in URLs
1eb2b517 582 * @return moodle_url
571fa828 583 */
78946b9b
PS
584 public function editor_css_url($encoded=true) {
585 global $CFG;
78946b9b 586 $rev = theme_get_revision();
78946b9b 587 if ($rev > -1) {
1eb2b517 588 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
7070b7f2 589 if (!empty($CFG->slasharguments)) {
7070b7f2 590 $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
7070b7f2 591 } else {
1eb2b517 592 $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
7070b7f2 593 }
78946b9b
PS
594 } else {
595 $params = array('theme'=>$this->name, 'type'=>'editor');
1eb2b517 596 $url = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
571fa828 597 }
1eb2b517 598 return $url;
571fa828 599 }
600
601 /**
78946b9b 602 * Returns the content of the CSS to be used in editor content
473dd811 603 *
78946b9b 604 * @return string
571fa828 605 */
71be124d 606 public function editor_css_files() {
78946b9b
PS
607 global $CFG;
608
71be124d 609 $files = array();
78946b9b
PS
610
611 // first editor plugins
bd3b3bba 612 $plugins = core_component::get_plugin_list('editor');
78946b9b
PS
613 foreach ($plugins as $plugin=>$fulldir) {
614 $sheetfile = "$fulldir/editor_styles.css";
615 if (is_readable($sheetfile)) {
71be124d 616 $files['plugin_'.$plugin] = $sheetfile;
78946b9b
PS
617 }
618 }
619 // then parent themes
620 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
621 if (empty($parent_config->editor_sheets)) {
622 continue;
623 }
624 foreach ($parent_config->editor_sheets as $sheet) {
ca194849 625 $sheetfile = "$parent_config->dir/style/$sheet.css";
78946b9b 626 if (is_readable($sheetfile)) {
71be124d 627 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
78946b9b
PS
628 }
629 }
630 }
631 // finally this theme
632 if (!empty($this->editor_sheets)) {
633 foreach ($this->editor_sheets as $sheet) {
71be124d 634 $sheetfile = "$this->dir/style/$sheet.css";
78946b9b 635 if (is_readable($sheetfile)) {
71be124d 636 $files['theme_'.$sheet] = $sheetfile;
78946b9b
PS
637 }
638 }
639 }
640
71be124d 641 return $files;
571fa828 642 }
643
644 /**
78946b9b 645 * Get the stylesheet URL of this theme
473dd811
SH
646 *
647 * @param moodle_page $page Not used... deprecated?
38aafea2 648 * @return array of moodle_url
571fa828 649 */
efaa4c08 650 public function css_urls(moodle_page $page) {
78946b9b
PS
651 global $CFG;
652
653 $rev = theme_get_revision();
654
efaa4c08 655 $urls = array();
efaa4c08 656
383b89a1
SH
657 $svg = $this->use_svg_icons();
658
78946b9b 659 if ($rev > -1) {
383b89a1 660 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
1eb2b517
SH
661 $separate = (check_browser_version('MSIE', 5) && !check_browser_version('MSIE', 10));
662 if (!empty($CFG->slasharguments)) {
663 $slashargs = '';
664 if (!$svg) {
665 // We add a simple /_s to the start of the path.
666 // The underscore is used to ensure that it isn't a valid theme name.
667 $slashargs .= '/_s'.$slashargs;
668 }
669 $slashargs .= '/'.$this->name.'/'.$rev.'/all';
670 if ($separate) {
671 $slashargs .= '/chunk0';
672 }
673 $url->set_slashargument($slashargs, 'noparam', true);
537740cb 674 } else {
1eb2b517
SH
675 $params = array('theme' => $this->name,'rev' => $rev, 'type' => 'all');
676 if (!$svg) {
677 // We add an SVG param so that we know not to serve SVG images.
678 // We do this because all modern browsers support SVG and this param will one day be removed.
679 $params['svg'] = '0';
7070b7f2 680 }
1eb2b517
SH
681 if ($separate) {
682 $params['chunk'] = '0';
683 }
684 $url->params($params);
78946b9b 685 }
1eb2b517
SH
686 $urls[] = $url;
687
78946b9b 688 } else {
7829cf79
PS
689 // find out the current CSS and cache it now for 5 seconds
690 // the point is to construct the CSS only once and pass it through the
691 // dataroot to the script that actually serves the sheets
d6b64d15
PS
692 if (!defined('THEME_DESIGNER_CACHE_LIFETIME')) {
693 define('THEME_DESIGNER_CACHE_LIFETIME', 4); // this can be also set in config.php
694 }
bcf7f9f3 695 $candidatedir = "$CFG->cachedir/theme/$this->name";
383b89a1
SH
696 if ($svg) {
697 $candidatesheet = "$candidatedir/designer.ser";
698 } else {
699 $candidatesheet = "$candidatedir/designer_nosvg.ser";
700 }
bcf7f9f3
701 $rebuild = true;
702 if (file_exists($candidatesheet) and filemtime($candidatesheet) > time() - THEME_DESIGNER_CACHE_LIFETIME) {
7829cf79
PS
703 if ($css = file_get_contents($candidatesheet)) {
704 $css = unserialize($css);
bcf7f9f3
705 if (is_array($css)) {
706 $rebuild = false;
707 }
708 }
709 }
710 if ($rebuild) {
711 // Prepare the CSS optimiser if it is to be used,
712 // please note that it may be very slow and is therefore strongly discouraged in theme designer mode.
713 $optimiser = null;
714 if (!empty($CFG->enablecssoptimiser) && $this->supportscssoptimisation) {
715 require_once($CFG->dirroot.'/lib/csslib.php');
716 $optimiser = new css_optimiser;
7829cf79 717 }
b305d623 718 $css = $this->css_content($optimiser);
bcf7f9f3
719
720 // We do not want any errors here because this may fail easily because of the concurrent access.
721 $prevabort = ignore_user_abort(true);
722 check_dir_exists($candidatedir);
723 $tempfile = tempnam($candidatedir, 'tmpdesigner');
724 file_put_contents($tempfile, serialize($css));
725 $reporting = error_reporting(0);
726 chmod($tempfile, $CFG->filepermissions);
727 unlink($candidatesheet); // Do not rely on rename() deleting original, they may decide to change it at any time as usually.
728 rename($tempfile, $candidatesheet);
729 error_reporting($reporting);
730 ignore_user_abort($prevabort);
7829cf79
PS
731 }
732
383b89a1
SH
733 $baseurl = new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php');
734 if (!$svg) {
735 // We add an SVG param so that we know not to serve SVG images.
736 // We do this because all modern browsers support SVG and this param will one day be removed.
737 $baseurl->param('svg', '0');
738 }
c09e1a2c
PS
739 if (check_browser_version('MSIE', 5)) {
740 // lalala, IE does not allow more than 31 linked CSS files from main document
71be124d 741 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
a6338a13
SH
742 foreach ($css['parents'] as $parent=>$sheets) {
743 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096)
71be124d 744 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
a6338a13 745 }
71be124d 746 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
c09e1a2c
PS
747
748 } else {
749 foreach ($css['plugins'] as $plugin=>$unused) {
750 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
751 }
752 foreach ($css['parents'] as $parent=>$sheets) {
753 foreach ($sheets as $sheet=>$unused2) {
754 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
755 }
756 }
757 foreach ($css['theme'] as $sheet=>$unused) {
758 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); // sheet first in order to make long urls easier to read
78946b9b 759 }
78946b9b 760 }
78946b9b 761 }
efaa4c08
PS
762
763 return $urls;
571fa828 764 }
34a2777c 765
ebebf55c 766 /**
045f492c 767 * Returns an array of organised CSS files required for this output
473dd811 768 *
045f492c 769 * @return array
ebebf55c 770 */
045f492c
SH
771 public function css_files() {
772 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
78946b9b 773
8c96c3cb 774 // get all plugin sheets
045f492c 775 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
78946b9b 776 if ($excludes !== true) {
46f6f7f2 777 foreach (core_component::get_plugin_types() as $type=>$unused) {
045f492c 778 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
78946b9b
PS
779 continue;
780 }
bd3b3bba 781 $plugins = core_component::get_plugin_list($type);
78946b9b
PS
782 foreach ($plugins as $plugin=>$fulldir) {
783 if (!empty($excludes[$type]) and is_array($excludes[$type])
784 and in_array($plugin, $excludes[$type])) {
785 continue;
786 }
f8bb9666
SH
787
788 $plugincontent = '';
78946b9b
PS
789 $sheetfile = "$fulldir/styles.css";
790 if (is_readable($sheetfile)) {
045f492c 791 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
f8bb9666
SH
792 }
793 $sheetthemefile = "$fulldir/styles_{$this->name}.css";
794 if (is_readable($sheetthemefile)) {
045f492c 795 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$this->name] = $sheetthemefile;
f8bb9666 796 }
78946b9b
PS
797 }
798 }
799 }
34a2777c 800
78946b9b 801 // find out wanted parent sheets
045f492c 802 $excludes = $this->resolve_excludes('parents_exclude_sheets');
78946b9b
PS
803 if ($excludes !== true) {
804 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
805 $parent = $parent_config->name;
045f492c 806 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
78946b9b
PS
807 continue;
808 }
809 foreach ($parent_config->sheets as $sheet) {
810 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
811 and in_array($sheet, $excludes[$parent])) {
812 continue;
813 }
814 $sheetfile = "$parent_config->dir/style/$sheet.css";
815 if (is_readable($sheetfile)) {
045f492c 816 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
78946b9b
PS
817 }
818 }
819 }
820 }
34a2777c 821
78946b9b
PS
822 // current theme sheets
823 if (is_array($this->sheets)) {
824 foreach ($this->sheets as $sheet) {
825 $sheetfile = "$this->dir/style/$sheet.css";
826 if (is_readable($sheetfile)) {
045f492c 827 $cssfiles['theme'][$sheet] = $sheetfile;
78946b9b 828 }
ebebf55c 829 }
78946b9b
PS
830 }
831
045f492c
SH
832 return $cssfiles;
833 }
834
835 /**
836 * Returns the content of the one huge CSS merged from all style sheets.
473dd811 837 *
b305d623 838 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
045f492c
SH
839 * @return string
840 */
b305d623 841 public function css_content(css_optimiser $optimiser = null) {
71be124d 842 $files = array_merge($this->css_files(), array('editor'=>$this->editor_css_files()));
b305d623 843 $css = $this->css_files_get_contents($files, array(), $optimiser);
78946b9b
PS
844 return $css;
845 }
34a2777c 846
045f492c
SH
847 /**
848 * Given an array of file paths or a single file path loads the contents of
849 * the CSS file, processes it then returns it in the same structure it was given.
850 *
f8129210 851 * Can be used recursively on the results of {@link css_files}
045f492c
SH
852 *
853 * @param array|string $file An array of file paths or a single file path
71c03ac1 854 * @param array $keys An array of previous array keys [recursive addition]
b305d623 855 * @param css_optimiser|null $optimiser A CSS optimiser to use during on the content. Null = don't optimise
045f492c
SH
856 * @return The converted array or the contents of the single file ($file type)
857 */
b305d623
SH
858 protected function css_files_get_contents($file, array $keys, css_optimiser $optimiser = null) {
859 global $CFG;
045f492c 860 if (is_array($file)) {
04cfa387
SH
861 // We use a separate array to keep everything in the exact same order.
862 $return = array();
045f492c 863 foreach ($file as $key=>$f) {
04cfa387 864 $return[clean_param($key, PARAM_SAFEDIR)] = $this->css_files_get_contents($f, array_merge($keys, array($key)), $optimiser);
045f492c 865 }
04cfa387 866 return $return;
045f492c 867 } else {
b305d623
SH
868 $contents = file_get_contents($file);
869 $contents = $this->post_process($contents);
045f492c 870 $comment = '/** Path: '.implode(' ', $keys).' **/'."\n";
b305d623
SH
871 $stats = '';
872 if (!is_null($optimiser)) {
873 $contents = $optimiser->process($contents);
874 if (!empty($CFG->cssoptimiserstats)) {
875 $stats = $optimiser->output_stats_css();
876 }
877 }
878 return $comment.$stats.$contents;
045f492c
SH
879 }
880 }
881
e68c5f36
PS
882
883 /**
473dd811
SH
884 * Generate a URL to the file that serves theme JavaScript files.
885 *
d7656956
ARN
886 * If we determine that the theme has no relevant files, then we return
887 * early with a null value.
888 *
71c03ac1 889 * @param bool $inhead true means head url, false means footer
d7656956 890 * @return moodle_url|null
e68c5f36 891 */
baeb20bb 892 public function javascript_url($inhead) {
e68c5f36
PS
893 global $CFG;
894
895 $rev = theme_get_revision();
e68c5f36 896 $params = array('theme'=>$this->name,'rev'=>$rev);
baeb20bb
PS
897 $params['type'] = $inhead ? 'head' : 'footer';
898
d7656956
ARN
899 // Return early if there are no files to serve
900 if (count($this->javascript_files($params['type'])) === 0) {
901 return null;
902 }
903
ecbad2ad
PS
904 if (!empty($CFG->slasharguments) and $rev > 0) {
905 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
906 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
907 return $url;
908 } else {
909 return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
910 }
e68c5f36
PS
911 }
912
473dd811
SH
913 /**
914 * Get the URL's for the JavaScript files used by this theme.
915 * They won't be served directly, instead they'll be mediated through
916 * theme/javascript.php.
917 *
918 * @param string $type Either javascripts_footer, or javascripts
919 * @return array
920 */
045f492c
SH
921 public function javascript_files($type) {
922 if ($type === 'footer') {
923 $type = 'javascripts_footer';
924 } else {
f856106b 925 $type = 'javascripts';
045f492c 926 }
04c01408 927
358c13cb
PS
928 $js = array();
929 // find out wanted parent javascripts
045f492c 930 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
358c13cb
PS
931 if ($excludes !== true) {
932 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
933 $parent = $parent_config->name;
04c01408 934 if (empty($parent_config->$type)) {
358c13cb
PS
935 continue;
936 }
937 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
938 continue;
939 }
04c01408 940 foreach ($parent_config->$type as $javascript) {
358c13cb
PS
941 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
942 and in_array($javascript, $excludes[$parent])) {
943 continue;
944 }
945 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
946 if (is_readable($javascriptfile)) {
045f492c 947 $js[] = $javascriptfile;
358c13cb
PS
948 }
949 }
950 }
951 }
952
953 // current theme javascripts
04c01408
PS
954 if (is_array($this->$type)) {
955 foreach ($this->$type as $javascript) {
358c13cb
PS
956 $javascriptfile = "$this->dir/javascript/$javascript.js";
957 if (is_readable($javascriptfile)) {
045f492c
SH
958 $js[] = $javascriptfile;
959 }
960 }
961 }
045f492c
SH
962 return $js;
963 }
964
965 /**
3d3fae72 966 * Resolves an exclude setting to the themes setting is applicable or the
045f492c
SH
967 * setting of its closest parent.
968 *
969 * @param string $variable The name of the setting the exclude setting to resolve
f8129210 970 * @param string $default
045f492c
SH
971 * @return mixed
972 */
f8129210 973 protected function resolve_excludes($variable, $default = null) {
045f492c
SH
974 $setting = $default;
975 if (is_array($this->{$variable}) or $this->{$variable} === true) {
976 $setting = $this->{$variable};
977 } else {
978 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
979 if (!isset($parent_config->{$variable})) {
980 continue;
981 }
982 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
983 $setting = $parent_config->{$variable};
984 break;
358c13cb
PS
985 }
986 }
987 }
045f492c
SH
988 return $setting;
989 }
358c13cb 990
045f492c
SH
991 /**
992 * Returns the content of the one huge javascript file merged from all theme javascript files.
473dd811 993 *
f8129210 994 * @param bool $type
045f492c
SH
995 * @return string
996 */
997 public function javascript_content($type) {
998 $jsfiles = $this->javascript_files($type);
999 $js = '';
1000 foreach ($jsfiles as $jsfile) {
1001 $js .= file_get_contents($jsfile)."\n";
1002 }
1003 return $js;
e68c5f36
PS
1004 }
1005
473dd811
SH
1006 /**
1007 * Post processes CSS.
1008 *
1009 * This method post processes all of the CSS before it is served for this theme.
1010 * This is done so that things such as image URL's can be swapped in and to
1011 * run any specific CSS post process method the theme has requested.
3d3fae72 1012 * This allows themes to use CSS settings.
473dd811
SH
1013 *
1014 * @param string $css The CSS to process.
1015 * @return string The processed CSS.
1016 */
045f492c 1017 public function post_process($css) {
78946b9b
PS
1018 // now resolve all image locations
1019 if (preg_match_all('/\[\[pix:([a-z_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1020 $replaced = array();
1021 foreach ($matches as $match) {
1022 if (isset($replaced[$match[0]])) {
1023 continue;
1024 }
1025 $replaced[$match[0]] = true;
1026 $imagename = $match[2];
1027 $component = rtrim($match[1], '|');
b9bc2019 1028 $imageurl = $this->pix_url($imagename, $component)->out(false);
df06c1c4 1029 // we do not need full url because the image.php is always in the same dir
9d473266 1030 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
df06c1c4 1031 $css = str_replace($match[0], $imageurl, $css);
ebebf55c 1032 }
34a2777c 1033 }
17a6649b 1034
78946b9b
PS
1035 // now resolve all theme settings or do any other postprocessing
1036 $csspostprocess = $this->csspostprocess;
1037 if (function_exists($csspostprocess)) {
1038 $css = $csspostprocess($css, $this);
fdeb7fa1 1039 }
1040
78946b9b 1041 return $css;
ebebf55c 1042 }
17a6649b 1043
ebebf55c 1044 /**
78946b9b
PS
1045 * Return the URL for an image
1046 *
1047 * @param string $imagename the name of the icon.
f8129210 1048 * @param string $component specification of one plugin like in get_string()
78946b9b 1049 * @return moodle_url
fdeb7fa1 1050 */
c39e5ba2 1051 public function pix_url($imagename, $component) {
fdeb7fa1 1052 global $CFG;
78946b9b 1053
9d473266 1054 $params = array('theme'=>$this->name);
436dbeec 1055 $svg = $this->use_svg_icons();
9d473266
PS
1056
1057 if (empty($component) or $component === 'moodle' or $component === 'core') {
1058 $params['component'] = 'core';
1059 } else {
1060 $params['component'] = $component;
1061 }
78946b9b
PS
1062
1063 $rev = theme_get_revision();
1064 if ($rev != -1) {
1065 $params['rev'] = $rev;
1066 }
9d473266
PS
1067
1068 $params['image'] = $imagename;
1069
436dbeec 1070 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
9d473266 1071 if (!empty($CFG->slasharguments) and $rev > 0) {
436dbeec
SH
1072 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1073 if (!$svg) {
1074 // We add a simple /_s to the start of the path.
1075 // The underscore is used to ensure that it isn't a valid theme name.
1076 $path = '/_s'.$path;
1077 }
1078 $url->set_slashargument($path, 'noparam', true);
9d473266 1079 } else {
436dbeec
SH
1080 if (!$svg) {
1081 // We add an SVG param so that we know not to serve SVG images.
1082 // We do this because all modern browsers support SVG and this param will one day be removed.
1083 $params['svg'] = '0';
1084 }
1085 $url->params($params);
fdeb7fa1 1086 }
78946b9b 1087
9d473266 1088 return $url;
fdeb7fa1 1089 }
1090
fe7b75f8
PS
1091 /**
1092 * Returns URL to the stored file via pluginfile.php.
1093 *
1094 * Note the theme must also implement pluginfile.php handler,
1095 * theme revision is used instead of the itemid.
1096 *
1097 * @param string $setting
1098 * @param string $filearea
1099 * @return string protocol relative URL or null if not present
1100 */
1101 public function setting_file_url($setting, $filearea) {
1102 global $CFG;
1103
1104 if (empty($this->settings->$setting)) {
1105 return null;
1106 }
1107
1108 $component = 'theme_'.$this->name;
1109 $itemid = theme_get_revision();
1110 $filepath = $this->settings->$setting;
1111 $syscontext = context_system::instance();
1112
1113 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1114
1115 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1116 // Note: unfortunately moodle_url does not support //urls yet.
1117
1118 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1119
1120 return $url;
1121 }
1122
1123 /**
1124 * Serve the theme setting file.
1125 *
1126 * @param string $filearea
1127 * @param array $args
1128 * @param bool $forcedownload
1129 * @param array $options
1130 * @return bool may terminate if file not found or donotdie not specified
1131 */
1132 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1133 global $CFG;
1134 require_once("$CFG->libdir/filelib.php");
1135
1136 $syscontext = context_system::instance();
1137 $component = 'theme_'.$this->name;
1138
1139 $revision = array_shift($args);
1140 if ($revision < 0) {
1141 $lifetime = 0;
1142 } else {
1143 $lifetime = 60*60*24*60;
1144 }
1145
1146 $fs = get_file_storage();
1147 $relativepath = implode('/', $args);
1148
1149 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1150 $fullpath = rtrim($fullpath, '/');
1151 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1152 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1153 return true;
1154 } else {
1155 send_file_not_found();
1156 }
1157 }
1158
fdeb7fa1 1159 /**
78946b9b 1160 * Resolves the real image location.
436dbeec
SH
1161 *
1162 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1163 * and we need a way in which to turn it off.
1164 * By default SVG won't be used unless asked for. This is done for two reasons:
1165 * 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
1166 * browser supports SVG.
1167 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1168 * by the user due to security concerns.
1169 *
78946b9b
PS
1170 * @param string $image name of image, may contain relative path
1171 * @param string $component
436dbeec 1172 * @param bool $svg If set to true SVG images will also be looked for.
78946b9b 1173 * @return string full file path
fdeb7fa1 1174 */
436dbeec 1175 public function resolve_image_location($image, $component, $svg = false) {
78946b9b
PS
1176 global $CFG;
1177
436dbeec
SH
1178 if (!is_bool($svg)) {
1179 // If $svg isn't a bool then we need to decide for ourselves.
1180 $svg = $this->use_svg_icons();
1181 }
1182
78946b9b 1183 if ($component === 'moodle' or $component === 'core' or empty($component)) {
436dbeec 1184 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
78946b9b
PS
1185 return $imagefile;
1186 }
1187 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
436dbeec 1188 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
78946b9b
PS
1189 return $imagefile;
1190 }
1191 }
436dbeec 1192 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
f930cf6b
EM
1193 return $imagefile;
1194 }
436dbeec 1195 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
78946b9b
PS
1196 return $imagefile;
1197 }
1198 return null;
1199
1200 } else if ($component === 'theme') { //exception
1201 if ($image === 'favicon') {
1202 return "$this->dir/pix/favicon.ico";
1203 }
436dbeec 1204 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
78946b9b
PS
1205 return $imagefile;
1206 }
1207 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
436dbeec 1208 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
78946b9b
PS
1209 return $imagefile;
1210 }
1211 }
1212 return null;
1213
78946b9b
PS
1214 } else {
1215 if (strpos($component, '_') === false) {
1216 $component = 'mod_'.$component;
1217 }
1218 list($type, $plugin) = explode('_', $component, 2);
1219
436dbeec 1220 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
78946b9b
PS
1221 return $imagefile;
1222 }
1223 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
436dbeec 1224 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
78946b9b
PS
1225 return $imagefile;
1226 }
1227 }
436dbeec 1228 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
f930cf6b
EM
1229 return $imagefile;
1230 }
1c74b260 1231 $dir = core_component::get_plugin_directory($type, $plugin);
436dbeec 1232 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
78946b9b
PS
1233 return $imagefile;
1234 }
1235 return null;
fdeb7fa1 1236 }
fdeb7fa1 1237 }
1238
436dbeec
SH
1239 /**
1240 * Return true if we should look for SVG images as well.
1241 *
1242 * @staticvar bool $svg
1243 * @return bool
1244 */
1245 public function use_svg_icons() {
1246 global $CFG;
1247 if ($this->usesvg === null) {
1248 if (!isset($CFG->svgicons) || !is_bool($CFG->svgicons)) {
1249 // IE 5 - 8 don't support SVG at all.
1250 if (empty($_SERVER['HTTP_USER_AGENT'])) {
1251 // Can't be sure, just say no.
1252 $this->usesvg = false;
3c1405a1 1253 } else if (check_browser_version('MSIE', 0) and !check_browser_version('MSIE', 9)) {
436dbeec
SH
1254 // IE < 9 doesn't support SVG. Say no.
1255 $this->usesvg = false;
1256 } else if (preg_match('#Android +[0-2]\.#', $_SERVER['HTTP_USER_AGENT'])) {
1257 // Android < 3 doesn't support SVG. Say no.
1258 $this->usesvg = false;
fbbf043c
FM
1259 } else if (check_browser_version('Opera', 0)) {
1260 // Opera 12 still does not support SVG well enough. Say no.
1261 $this->usesvg = false;
436dbeec
SH
1262 } else {
1263 // Presumed fine.
1264 $this->usesvg = true;
1265 }
1266 } else {
1267 // Force them on/off depending upon the setting.
1268 $this->usesvg = $CFG->svgicons;
1269 }
1270 }
1271 return $this->usesvg;
1272 }
1273
f7d6a556
SH
1274 /**
1275 * Forces the usesvg setting to either true or false, avoiding any decision making.
1276 *
1277 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
383b89a1 1278 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
f7d6a556
SH
1279 *
1280 * @param bool $setting True to force the use of svg when available, null otherwise.
1281 */
383b89a1 1282 public function force_svg_use($setting) {
f7d6a556
SH
1283 $this->usesvg = (bool)$setting;
1284 }
1285
d4a03c00 1286 /**
78946b9b 1287 * Checks if file with any image extension exists.
473dd811 1288 *
436dbeec
SH
1289 * The order to these images was adjusted prior to the release of 2.4
1290 * At that point the were the following image counts in Moodle core:
1291 *
1292 * - png = 667 in pix dirs (1499 total)
1293 * - gif = 385 in pix dirs (606 total)
1294 * - jpg = 62 in pix dirs (74 total)
1295 * - jpeg = 0 in pix dirs (1 total)
1296 *
1297 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1298 *
78946b9b 1299 * @param string $filepath
436dbeec 1300 * @param bool $svg If set to true SVG images will also be looked for.
78946b9b 1301 * @return string image name with extension
d4a03c00 1302 */
436dbeec
SH
1303 private static function image_exists($filepath, $svg = false) {
1304 if ($svg && file_exists("$filepath.svg")) {
1305 return "$filepath.svg";
78946b9b
PS
1306 } else if (file_exists("$filepath.png")) {
1307 return "$filepath.png";
436dbeec
SH
1308 } else if (file_exists("$filepath.gif")) {
1309 return "$filepath.gif";
78946b9b
PS
1310 } else if (file_exists("$filepath.jpg")) {
1311 return "$filepath.jpg";
1312 } else if (file_exists("$filepath.jpeg")) {
1313 return "$filepath.jpeg";
d4a03c00 1314 } else {
78946b9b 1315 return false;
d4a03c00 1316 }
1317 }
1318
fdeb7fa1 1319 /**
78946b9b 1320 * Loads the theme config from config.php file.
473dd811 1321 *
78946b9b 1322 * @param string $themename
473dd811
SH
1323 * @param stdClass $settings from config_plugins table
1324 * @return stdClass The theme configuration
fdeb7fa1 1325 */
78946b9b
PS
1326 private static function find_theme_config($themename, $settings) {
1327 // We have to use the variable name $THEME (upper case) because that
1328 // is what is used in theme config.php files.
fdeb7fa1 1329
78946b9b
PS
1330 if (!$dir = theme_config::find_theme_location($themename)) {
1331 return null;
fdeb7fa1 1332 }
2f67a9b3 1333
365a5941 1334 $THEME = new stdClass();
78946b9b
PS
1335 $THEME->name = $themename;
1336 $THEME->dir = $dir;
1337 $THEME->settings = $settings;
1338
1339 global $CFG; // just in case somebody tries to use $CFG in theme config
1340 include("$THEME->dir/config.php");
1341
1342 // verify the theme configuration is OK
1343 if (!is_array($THEME->parents)) {
1344 // parents option is mandatory now
1345 return null;
fdeb7fa1 1346 }
1347
78946b9b 1348 return $THEME;
fdeb7fa1 1349 }
1350
d4a03c00 1351 /**
78946b9b
PS
1352 * Finds the theme location and verifies the theme has all needed files
1353 * and is not obsoleted.
473dd811 1354 *
78946b9b
PS
1355 * @param string $themename
1356 * @return string full dir path or null if not found
d4a03c00 1357 */
78946b9b
PS
1358 private static function find_theme_location($themename) {
1359 global $CFG;
1360
1361 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
1362 $dir = "$CFG->dirroot/theme/$themename";
d4a03c00 1363
3dd1d7e7
DM
1364 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
1365 $dir = "$CFG->themedir/$themename";
1366
7d875874 1367 } else {
78946b9b 1368 return null;
d4a03c00 1369 }
78946b9b
PS
1370
1371 if (file_exists("$dir/styles.php")) {
1372 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
1373 return null;
1374 }
2f67a9b3 1375
78946b9b 1376 return $dir;
d4a03c00 1377 }
1378
1d13c75c 1379 /**
78946b9b 1380 * Get the renderer for a part of Moodle for this theme.
473dd811 1381 *
78946b9b 1382 * @param moodle_page $page the page we are rendering
f8129210 1383 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
78946b9b 1384 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
c927e35c 1385 * @param string $target one of rendering target constants
78946b9b 1386 * @return renderer_base the requested renderer.
1d13c75c 1387 */
c927e35c 1388 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
78946b9b 1389 if (is_null($this->rf)) {
c927e35c 1390 $classname = $this->rendererfactory;
78946b9b 1391 $this->rf = new $classname($this);
1d13c75c 1392 }
78946b9b 1393
c927e35c 1394 return $this->rf->get_renderer($page, $component, $subtype, $target);
1d13c75c 1395 }
1396
fdeb7fa1 1397 /**
78946b9b 1398 * Get the information from {@link $layouts} for this type of page.
473dd811 1399 *
78946b9b
PS
1400 * @param string $pagelayout the the page layout name.
1401 * @return array the appropriate part of {@link $layouts}.
fdeb7fa1 1402 */
78946b9b
PS
1403 protected function layout_info_for_page($pagelayout) {
1404 if (array_key_exists($pagelayout, $this->layouts)) {
1405 return $this->layouts[$pagelayout];
1406 } else {
191b267b
PS
1407 debugging('Invalid page layout specified: ' . $pagelayout);
1408 return $this->layouts['standard'];
fdeb7fa1 1409 }
1410 }
1411
1412 /**
78946b9b
PS
1413 * Given the settings of this theme, and the page pagelayout, return the
1414 * full path of the page layout file to use.
1415 *
1416 * Used by {@link core_renderer::header()}.
1417 *
1418 * @param string $pagelayout the the page layout name.
1419 * @return string Full path to the lyout file to use
ebebf55c 1420 */
78946b9b 1421 public function layout_file($pagelayout) {
ebebf55c 1422 global $CFG;
fdeb7fa1 1423
78946b9b
PS
1424 $layoutinfo = $this->layout_info_for_page($pagelayout);
1425 $layoutfile = $layoutinfo['file'];
fdeb7fa1 1426
84db3ea2
SH
1427 if (array_key_exists('theme', $layoutinfo)) {
1428 $themes = array($layoutinfo['theme']);
1429 } else {
1430 $themes = array_merge(array($this->name),$this->parents);
1431 }
4399b9d5 1432
84db3ea2
SH
1433 foreach ($themes as $theme) {
1434 if ($dir = $this->find_theme_location($theme)) {
1435 $path = "$dir/layout/$layoutfile";
1436
1437 // Check the template exists, return general base theme template if not.
1438 if (is_readable($path)) {
1439 return $path;
1440 }
78946b9b 1441 }
34a2777c 1442 }
1443
191b267b 1444 debugging('Can not find layout file for: ' . $pagelayout);
78946b9b
PS
1445 // fallback to standard normal layout
1446 return "$CFG->dirroot/theme/base/layout/general.php";
1447 }
ebebf55c 1448
78946b9b
PS
1449 /**
1450 * Returns auxiliary page layout options specified in layout configuration array.
473dd811 1451 *
78946b9b
PS
1452 * @param string $pagelayout
1453 * @return array
1454 */
1455 public function pagelayout_options($pagelayout) {
1456 $info = $this->layout_info_for_page($pagelayout);
1457 if (!empty($info['options'])) {
1458 return $info['options'];
34a2777c 1459 }
78946b9b
PS
1460 return array();
1461 }
34a2777c 1462
78946b9b
PS
1463 /**
1464 * Inform a block_manager about the block regions this theme wants on this
1465 * page layout.
473dd811 1466 *
78946b9b
PS
1467 * @param string $pagelayout the general type of the page.
1468 * @param block_manager $blockmanager the block_manger to set up.
78946b9b
PS
1469 */
1470 public function setup_blocks($pagelayout, $blockmanager) {
1471 $layoutinfo = $this->layout_info_for_page($pagelayout);
1472 if (!empty($layoutinfo['regions'])) {
1473 $blockmanager->add_regions($layoutinfo['regions']);
1474 $blockmanager->set_default_region($layoutinfo['defaultregion']);
ebebf55c 1475 }
34a2777c 1476 }
1477
473dd811
SH
1478 /**
1479 * Gets the visible name for the requested block region.
1480 *
1481 * @param string $region The region name to get
1482 * @param string $theme The theme the region belongs to (may come from the parent theme)
1483 * @return string
1484 */
cadc0d28
TH
1485 protected function get_region_name($region, $theme) {
1486 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
1487 // A name exists in this theme, so use it
1488 if (substr($regionstring, 0, 1) != '[') {
1489 return $regionstring;
1490 }
1491
1492 // Otherwise, try to find one elsewhere
1493 // Check parents, if any
1494 foreach ($this->parents as $parentthemename) {
1495 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
1496 if (substr($regionstring, 0, 1) != '[') {
1497 return $regionstring;
1498 }
1499 }
1500
1501 // Last resort, try the base theme for names
1502 return get_string('region-' . $region, 'theme_base');
1503 }
1504
ebebf55c 1505 /**
78946b9b 1506 * Get the list of all block regions known to this theme in all templates.
473dd811 1507 *
78946b9b 1508 * @return array internal region name => human readable name.
ebebf55c 1509 */
78946b9b
PS
1510 public function get_all_block_regions() {
1511 $regions = array();
78946b9b
PS
1512 foreach ($this->layouts as $layoutinfo) {
1513 foreach ($layoutinfo['regions'] as $region) {
a9535f79 1514 $regions[$region] = $this->get_region_name($region, $this->name);
ebebf55c 1515 }
34a2777c 1516 }
78946b9b 1517 return $regions;
34a2777c 1518 }
d609d962
SH
1519
1520 /**
1521 * Returns the human readable name of the theme
1522 *
1523 * @return string
1524 */
1525 public function get_theme_name() {
1526 return get_string('pluginname', 'theme_'.$this->name);
1527 }
ebebf55c 1528}
34a2777c 1529
ebebf55c 1530/**
d9c8f425 1531 * This class keeps track of which HTML tags are currently open.
1532 *
1533 * This makes it much easier to always generate well formed XHTML output, even
1534 * if execution terminates abruptly. Any time you output some opening HTML
1535 * without the matching closing HTML, you should push the necessary close tags
1536 * onto the stack.
ebebf55c 1537 *
1538 * @copyright 2009 Tim Hunt
473dd811
SH
1539 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1540 * @since Moodle 2.0
f8129210 1541 * @package core
76be40cc 1542 * @category output
ebebf55c 1543 */
d9c8f425 1544class xhtml_container_stack {
473dd811
SH
1545
1546 /**
76be40cc 1547 * @var array Stores the list of open containers.
473dd811 1548 */
d9c8f425 1549 protected $opencontainers = array();
473dd811 1550
fa1afe32 1551 /**
76be40cc 1552 * @var array In developer debug mode, stores a stack trace of all opens and
d9c8f425 1553 * closes, so we can output helpful error messages when there is a mismatch.
fa1afe32 1554 */
d9c8f425 1555 protected $log = array();
473dd811 1556
fa1afe32 1557 /**
76be40cc
SH
1558 * @var boolean Store whether we are developer debug mode. We need this in
1559 * several places including in the destructor where we may not have access to $CFG.
fa1afe32 1560 */
d9c8f425 1561 protected $isdebugging;
34a2777c 1562
473dd811
SH
1563 /**
1564 * Constructor
1565 */
d9c8f425 1566 public function __construct() {
1567 $this->isdebugging = debugging('', DEBUG_DEVELOPER);
ebebf55c 1568 }
34a2777c 1569
fa1afe32 1570 /**
d9c8f425 1571 * Push the close HTML for a recently opened container onto the stack.
473dd811 1572 *
d9c8f425 1573 * @param string $type The type of container. This is checked when {@link pop()}
1574 * is called and must match, otherwise a developer debug warning is output.
1575 * @param string $closehtml The HTML required to close the container.
fa1afe32 1576 */
d9c8f425 1577 public function push($type, $closehtml) {
1578 $container = new stdClass;
1579 $container->type = $type;
1580 $container->closehtml = $closehtml;
1581 if ($this->isdebugging) {
1582 $this->log('Open', $type);
3aaa27f4 1583 }
d9c8f425 1584 array_push($this->opencontainers, $container);
ebebf55c 1585 }
34a2777c 1586
fa1afe32 1587 /**
d9c8f425 1588 * Pop the HTML for the next closing container from the stack. The $type
1589 * must match the type passed when the container was opened, otherwise a
1590 * warning will be output.
473dd811 1591 *
d9c8f425 1592 * @param string $type The type of container.
1593 * @return string the HTML required to close the container.
fa1afe32 1594 */
d9c8f425 1595 public function pop($type) {
1596 if (empty($this->opencontainers)) {
1597 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
1598 $this->output_log(), DEBUG_DEVELOPER);
1599 return;
3aaa27f4 1600 }
ebebf55c 1601
d9c8f425 1602 $container = array_pop($this->opencontainers);
1603 if ($container->type != $type) {
1604 debugging('<p>The type of container to be closed (' . $container->type .
1605 ') does not match the type of the next open container (' . $type .
1606 '). This suggests there is a nesting problem.</p>' .
1607 $this->output_log(), DEBUG_DEVELOPER);
ebebf55c 1608 }
d9c8f425 1609 if ($this->isdebugging) {
1610 $this->log('Close', $type);
e8775320 1611 }
d9c8f425 1612 return $container->closehtml;
ebebf55c 1613 }
e8775320 1614
fa1afe32 1615 /**
d9c8f425 1616 * Close all but the last open container. This is useful in places like error
1617 * handling, where you want to close all the open containers (apart from <body>)
1618 * before outputting the error message.
473dd811 1619 *
d9c8f425 1620 * @param bool $shouldbenone assert that the stack should be empty now - causes a
1621 * developer debug warning if it isn't.
1622 * @return string the HTML required to close any open containers inside <body>.
fa1afe32 1623 */
d9c8f425 1624 public function pop_all_but_last($shouldbenone = false) {
1625 if ($shouldbenone && count($this->opencontainers) != 1) {
1626 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
1627 $this->output_log(), DEBUG_DEVELOPER);
1628 }
1629 $output = '';
1630 while (count($this->opencontainers) > 1) {
1631 $container = array_pop($this->opencontainers);
1632 $output .= $container->closehtml;
e8775320 1633 }
d9c8f425 1634 return $output;
e8775320 1635 }
34a2777c 1636
ebebf55c 1637 /**
d9c8f425 1638 * You can call this function if you want to throw away an instance of this
1639 * class without properly emptying the stack (for example, in a unit test).
1640 * Calling this method stops the destruct method from outputting a developer
1641 * debug warning. After calling this method, the instance can no longer be used.
ebebf55c 1642 */
d9c8f425 1643 public function discard() {
1644 $this->opencontainers = null;
ebebf55c 1645 }
d9c8f425 1646
fa1afe32 1647 /**
d9c8f425 1648 * Adds an entry to the log.
473dd811 1649 *
d9c8f425 1650 * @param string $action The name of the action
1651 * @param string $type The type of action
fa1afe32 1652 */
d9c8f425 1653 protected function log($action, $type) {
1654 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
1655 format_backtrace(debug_backtrace()) . '</li>';
ebebf55c 1656 }
34a2777c 1657
fa1afe32 1658 /**
d9c8f425 1659 * Outputs the log's contents as a HTML list.
473dd811 1660 *
d9c8f425 1661 * @return string HTML list of the log
fa1afe32 1662 */
d9c8f425 1663 protected function output_log() {
1664 return '<ul>' . implode("\n", $this->log) . '</ul>';
34a2777c 1665 }
6fc267a0 1666}