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