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