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