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