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