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