MDL-62757 themes: validate theme preset files
[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 = '';
964
965 if (!empty($this->editor_scss)) {
966 $compiler = new core_scss();
967
968 foreach ($this->editor_scss as $filename) {
969 $compiler->set_file("{$this->dir}/scss/{$filename}.scss");
970
971 try {
972 $css .= $compiler->to_css();
973 } catch (\Exception $e) {
974 debugging('Error while compiling editor SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
975 }
976 }
977 }
978
979 return $css;
980 }
981
571fa828 982 /**
98245a84 983 * Get the stylesheet URL of this theme.
473dd811
SH
984 *
985 * @param moodle_page $page Not used... deprecated?
98245a84 986 * @return moodle_url[]
571fa828 987 */
efaa4c08 988 public function css_urls(moodle_page $page) {
78946b9b
PS
989 global $CFG;
990
991 $rev = theme_get_revision();
992
efaa4c08 993 $urls = array();
efaa4c08 994
383b89a1 995 $svg = $this->use_svg_icons();
06a9e103 996 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
383b89a1 997
78946b9b 998 if ($rev > -1) {
1d987cae 999 $filename = right_to_left() ? 'all-rtl' : 'all';
7eb50b32 1000 $url = new moodle_url("/theme/styles.php");
5dd40ec4
RW
1001 $themesubrevision = theme_get_sub_revision_for_theme($this->name);
1002
1003 // Provide the sub revision to allow us to invalidate cached theme CSS
1004 // on a per theme basis, rather than globally.
1005 if ($themesubrevision && $themesubrevision > 0) {
1006 $rev .= "_{$themesubrevision}";
1007 }
1008
1eb2b517
SH
1009 if (!empty($CFG->slasharguments)) {
1010 $slashargs = '';
1011 if (!$svg) {
1012 // We add a simple /_s to the start of the path.
1013 // The underscore is used to ensure that it isn't a valid theme name.
1014 $slashargs .= '/_s'.$slashargs;
1015 }
1d987cae 1016 $slashargs .= '/'.$this->name.'/'.$rev.'/'.$filename;
1eb2b517
SH
1017 if ($separate) {
1018 $slashargs .= '/chunk0';
1019 }
1020 $url->set_slashargument($slashargs, 'noparam', true);
537740cb 1021 } else {
e584e6ae 1022 $params = array('theme' => $this->name, 'rev' => $rev, 'type' => $filename);
1eb2b517
SH
1023 if (!$svg) {
1024 // We add an SVG param so that we know not to serve SVG images.
1025 // We do this because all modern browsers support SVG and this param will one day be removed.
1026 $params['svg'] = '0';
7070b7f2 1027 }
1eb2b517
SH
1028 if ($separate) {
1029 $params['chunk'] = '0';
1030 }
1031 $url->params($params);
78946b9b 1032 }
1eb2b517
SH
1033 $urls[] = $url;
1034
78946b9b 1035 } else {
7eb50b32 1036 $baseurl = new moodle_url('/theme/styles_debug.php');
c09e1a2c 1037
08823e5f 1038 $css = $this->get_css_files(true);
383b89a1
SH
1039 if (!$svg) {
1040 // We add an SVG param so that we know not to serve SVG images.
1041 // We do this because all modern browsers support SVG and this param will one day be removed.
1042 $baseurl->param('svg', '0');
1043 }
1d987cae
FM
1044 if (right_to_left()) {
1045 $baseurl->param('rtl', 1);
1046 }
06a9e103
FM
1047 if ($separate) {
1048 // We might need to chunk long files.
1049 $baseurl->param('chunk', '0');
1050 }
378b3eac 1051 if (core_useragent::is_ie()) {
98245a84 1052 // Lalala, IE does not allow more than 31 linked CSS files from main document.
71be124d 1053 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
a6338a13 1054 foreach ($css['parents'] as $parent=>$sheets) {
98245a84 1055 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
71be124d 1056 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
a6338a13 1057 }
41b973bc 1058 if ($this->get_scss_property()) {
65b8336e
FM
1059 // No need to define the type as IE here.
1060 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
29d73d27 1061 }
71be124d 1062 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
c09e1a2c
PS
1063
1064 } else {
1065 foreach ($css['plugins'] as $plugin=>$unused) {
1066 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
1067 }
1068 foreach ($css['parents'] as $parent=>$sheets) {
1069 foreach ($sheets as $sheet=>$unused2) {
1070 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
1071 }
1072 }
08823e5f 1073 foreach ($css['theme'] as $sheet => $filename) {
41b973bc 1074 if ($sheet === self::SCSS_KEY) {
65b8336e
FM
1075 // This is the theme SCSS file.
1076 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
08823e5f 1077 } else {
d433cf37
FM
1078 // Sheet first in order to make long urls easier to read.
1079 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
c09e1a2c 1080 }
78946b9b 1081 }
78946b9b 1082 }
78946b9b 1083 }
efaa4c08 1084
66bd0f6c
BB
1085 // Allow themes to change the css url to something like theme/mytheme/mycss.php.
1086 component_callback('theme_' . $this->name, 'alter_css_urls', [&$urls]);
efaa4c08 1087 return $urls;
571fa828 1088 }
34a2777c 1089
ebebf55c 1090 /**
98245a84 1091 * Get the whole css stylesheet for production mode.
473dd811 1092 *
31f28b6a
1093 * NOTE: this method is not expected to be used from any addons.
1094 *
d52ebf11 1095 * @return string CSS markup compressed
98245a84
PS
1096 */
1097 public function get_css_content() {
98245a84
PS
1098
1099 $csscontent = '';
08823e5f
FM
1100 foreach ($this->get_css_files(false) as $type => $value) {
1101 foreach ($value as $identifier => $val) {
98245a84
PS
1102 if (is_array($val)) {
1103 foreach ($val as $v) {
1104 $csscontent .= file_get_contents($v) . "\n";
1105 }
1106 } else {
41b973bc 1107 if ($type === 'theme' && $identifier === self::SCSS_KEY) {
65b8336e 1108 // We need the content from SCSS because this is the SCSS file from the theme.
af9edb2e
BB
1109 if ($compiled = $this->get_css_content_from_scss(false)) {
1110 $csscontent .= $compiled;
1111 } else {
1112 // The compiler failed so default back to any precompiled css that might
1113 // exist.
1114 $csscontent .= $this->get_precompiled_css_content();
1115 }
d433cf37
FM
1116 } else {
1117 $csscontent .= file_get_contents($val) . "\n";
98245a84 1118 }
98245a84
PS
1119 }
1120 }
1121 }
1122 $csscontent = $this->post_process($csscontent);
d52ebf11 1123 $csscontent = core_minify::css($csscontent);
98245a84
PS
1124
1125 return $csscontent;
1126 }
4cc2f33b
SL
1127 /**
1128 * Set post processed CSS content cache.
1129 *
1130 * @param string $csscontent The post processed CSS content.
1131 * @return bool True if the content was successfully cached.
1132 */
1133 public function set_css_content_cache($csscontent) {
1134
1135 $cache = cache::make('core', 'postprocessedcss');
1136 $key = $this->get_css_cache_key();
1137
1138 return $cache->set($key, $csscontent);
1139 }
1140
0e9911e1
AN
1141 /**
1142 * Return whether the post processed CSS content has been cached.
1143 *
1144 * @return bool Whether the post-processed CSS is available in the cache.
1145 */
1146 public function has_css_cached_content() {
1147
1148 $key = $this->get_css_cache_key();
1149 $cache = cache::make('core', 'postprocessedcss');
1150
1151 return $cache->has($key);
1152 }
1153
4cc2f33b
SL
1154 /**
1155 * Return cached post processed CSS content.
1156 *
1157 * @return bool|string The cached css content or false if not found.
1158 */
1159 public function get_css_cached_content() {
1160
1161 $key = $this->get_css_cache_key();
1162 $cache = cache::make('core', 'postprocessedcss');
1163
1164 return $cache->get($key);
1165 }
1166
1167 /**
1168 * Generate the css content cache key.
1169 *
1170 * @return string The post processed css cache key.
1171 */
1172 public function get_css_cache_key() {
1173 $nosvg = (!$this->use_svg_icons()) ? 'nosvg_' : '';
1174 $rtlmode = ($this->rtlmode == true) ? 'rtl' : 'ltr';
1175
1176 return $nosvg . $this->name . '_' . $rtlmode;
1177 }
98245a84
PS
1178
1179 /**
1180 * Get the theme designer css markup,
1181 * the parameters are coming from css_urls().
1182 *
31f28b6a
1183 * NOTE: this method is not expected to be used from any addons.
1184 *
98245a84
PS
1185 * @param string $type
1186 * @param string $subtype
1187 * @param string $sheet
1188 * @return string CSS markup
ebebf55c 1189 */
98245a84 1190 public function get_css_content_debug($type, $subtype, $sheet) {
98245a84 1191
65b8336e
FM
1192 if ($type === 'scss') {
1193 // The SCSS file of the theme is requested.
1194 $csscontent = $this->get_css_content_from_scss(true);
1195 if ($csscontent !== false) {
1d987cae 1196 return $this->post_process($csscontent);
65b8336e
FM
1197 }
1198 return '';
08823e5f
FM
1199 }
1200
98245a84
PS
1201 $cssfiles = array();
1202 $css = $this->get_css_files(true);
1203
1204 if ($type === 'ie') {
1205 // IE is a sloppy browser with weird limits, sorry.
1206 if ($subtype === 'plugins') {
1207 $cssfiles = $css['plugins'];
1208
1209 } else if ($subtype === 'parents') {
1210 if (empty($sheet)) {
1211 // Do not bother with the empty parent here.
1212 } else {
1213 // Build up the CSS for that parent so we can serve it as one file.
1214 foreach ($css[$subtype][$sheet] as $parent => $css) {
1215 $cssfiles[] = $css;
1216 }
1217 }
1218 } else if ($subtype === 'theme') {
1219 $cssfiles = $css['theme'];
da283760 1220 foreach ($cssfiles as $key => $value) {
655b994a
MM
1221 if (in_array($key, [self::SCSS_KEY])) {
1222 // Remove the SCSS file from the theme CSS files.
1223 // The SCSS files use the type 'scss', not 'ie'.
da283760
FM
1224 unset($cssfiles[$key]);
1225 }
1226 }
98245a84
PS
1227 }
1228
1229 } else if ($type === 'plugin') {
1230 if (isset($css['plugins'][$subtype])) {
1231 $cssfiles[] = $css['plugins'][$subtype];
1232 }
1233
1234 } else if ($type === 'parent') {
1235 if (isset($css['parents'][$subtype][$sheet])) {
1236 $cssfiles[] = $css['parents'][$subtype][$sheet];
1237 }
1238
1239 } else if ($type === 'theme') {
1240 if (isset($css['theme'][$sheet])) {
1241 $cssfiles[] = $css['theme'][$sheet];
1242 }
1243 }
1244
1245 $csscontent = '';
1246 foreach ($cssfiles as $file) {
1247 $contents = file_get_contents($file);
1248 $contents = $this->post_process($contents);
1249 $comment = "/** Path: $type $subtype $sheet.' **/\n";
1250 $stats = '';
98245a84
PS
1251 $csscontent .= $comment.$stats.$contents."\n\n";
1252 }
1253
1254 return $csscontent;
1255 }
1256
1257 /**
1258 * Get the whole css stylesheet for editor iframe.
31f28b6a
1259 *
1260 * NOTE: this method is not expected to be used from any addons.
1261 *
98245a84
PS
1262 * @return string CSS markup
1263 */
1264 public function get_css_content_editor() {
98245a84 1265 $css = '';
341070d5
MH
1266 $cssfiles = $this->editor_css_files();
1267
1268 // If editor has static CSS, include it.
98245a84
PS
1269 foreach ($cssfiles as $file) {
1270 $css .= file_get_contents($file)."\n";
1271 }
341070d5
MH
1272
1273 // If editor has SCSS, compile and include it.
1274 if (($convertedscss = $this->editor_scss_to_css())) {
1275 $css .= $convertedscss;
1276 }
1277
1278 $output = $this->post_process($css);
1279
1280 return $output;
98245a84
PS
1281 }
1282
1283 /**
1284 * Returns an array of organised CSS files required for this output.
1285 *
1286 * @param bool $themedesigner
1287 * @return array nested array of file paths
1288 */
1289 protected function get_css_files($themedesigner) {
1290 global $CFG;
1291
1292 $cache = null;
08823e5f 1293 $cachekey = 'cssfiles';
98245a84
PS
1294 if ($themedesigner) {
1295 require_once($CFG->dirroot.'/lib/csslib.php');
1296 // We need some kind of caching here because otherwise the page navigation becomes
1297 // way too slow in theme designer mode. Feel free to create full cache definition later...
1298 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
d433cf37 1299 if ($files = $cache->get($cachekey)) {
98245a84
PS
1300 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
1301 unset($files['created']);
1302 return $files;
1303 }
1304 }
1305 }
1306
045f492c 1307 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
78946b9b 1308
98245a84 1309 // Get all plugin sheets.
045f492c 1310 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
78946b9b 1311 if ($excludes !== true) {
46f6f7f2 1312 foreach (core_component::get_plugin_types() as $type=>$unused) {
045f492c 1313 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
78946b9b
PS
1314 continue;
1315 }
bd3b3bba 1316 $plugins = core_component::get_plugin_list($type);
78946b9b
PS
1317 foreach ($plugins as $plugin=>$fulldir) {
1318 if (!empty($excludes[$type]) and is_array($excludes[$type])
22c5c6e6 1319 and in_array($plugin, $excludes[$type])) {
78946b9b
PS
1320 continue;
1321 }
f8bb9666 1322
08823e5f 1323 // Get the CSS from the plugin.
78946b9b
PS
1324 $sheetfile = "$fulldir/styles.css";
1325 if (is_readable($sheetfile)) {
045f492c 1326 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
f8bb9666 1327 }
22c5c6e6
FM
1328
1329 // Create a list of candidate sheets from parents (direct parent last) and current theme.
1330 $candidates = array();
1331 foreach (array_reverse($this->parent_configs) as $parent_config) {
1332 $candidates[] = $parent_config->name;
f8bb9666 1333 }
22c5c6e6
FM
1334 $candidates[] = $this->name;
1335
1336 // Add the sheets found.
1337 foreach ($candidates as $candidate) {
1338 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1339 if (is_readable($sheetthemefile)) {
1340 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
1341 }
78946b9b
PS
1342 }
1343 }
1344 }
22c5c6e6 1345 }
34a2777c 1346
98245a84 1347 // Find out wanted parent sheets.
045f492c 1348 $excludes = $this->resolve_excludes('parents_exclude_sheets');
78946b9b 1349 if ($excludes !== true) {
98245a84 1350 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
78946b9b 1351 $parent = $parent_config->name;
045f492c 1352 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
78946b9b
PS
1353 continue;
1354 }
1355 foreach ($parent_config->sheets as $sheet) {
d433cf37
FM
1356 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1357 && in_array($sheet, $excludes[$parent])) {
78946b9b
PS
1358 continue;
1359 }
d433cf37
FM
1360
1361 // We never refer to the parent LESS files.
78946b9b
PS
1362 $sheetfile = "$parent_config->dir/style/$sheet.css";
1363 if (is_readable($sheetfile)) {
045f492c 1364 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
78946b9b
PS
1365 }
1366 }
1367 }
1368 }
34a2777c 1369
41b973bc 1370
655b994a
MM
1371 // Current theme sheets.
1372 // We first add the SCSS file because we want the CSS ones to
1373 // be included after the SCSS code.
41b973bc
FM
1374 if ($this->get_scss_property()) {
1375 $cssfiles['theme'][self::SCSS_KEY] = true;
d433cf37 1376 }
78946b9b
PS
1377 if (is_array($this->sheets)) {
1378 foreach ($this->sheets as $sheet) {
1379 $sheetfile = "$this->dir/style/$sheet.css";
d433cf37 1380 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
045f492c 1381 $cssfiles['theme'][$sheet] = $sheetfile;
78946b9b 1382 }
ebebf55c 1383 }
78946b9b
PS
1384 }
1385
98245a84
PS
1386 if ($cache) {
1387 $files = $cssfiles;
1388 $files['created'] = time();
d433cf37 1389 $cache->set($cachekey, $files);
045f492c 1390 }
98245a84
PS
1391 return $cssfiles;
1392 }
e68c5f36 1393
65b8336e
FM
1394 /**
1395 * Return the CSS content generated from the SCSS file.
1396 *
1397 * @param bool $themedesigner True if theme designer is enabled.
1398 * @return bool|string Return false when the compilation failed. Else the compiled string.
1399 */
1400 protected function get_css_content_from_scss($themedesigner) {
1401 global $CFG;
1402
41b973bc
FM
1403 list($paths, $scss) = $this->get_scss_property();
1404 if (!$scss) {
65b8336e
FM
1405 throw new coding_exception('The theme did not define a SCSS file, or it is not readable.');
1406 }
1407
1081de20 1408 // We might need more memory/time to do this, so let's play safe.
65b8336e 1409 raise_memory_limit(MEMORY_EXTRA);
1081de20 1410 core_php_time_limit::raise(300);
65b8336e 1411
8040fafa
BB
1412 // TODO: MDL-62757 When changing anything in this method please do not forget to check
1413 // if the validate() method in class admin_setting_configthemepreset needs updating too.
1414
65b8336e
FM
1415 // Set-up the compiler.
1416 $compiler = new core_scss();
258143e3 1417 $compiler->prepend_raw_scss($this->get_pre_scss_code());
41b973bc
FM
1418 if (is_string($scss)) {
1419 $compiler->set_file($scss);
1420 } else {
1421 $compiler->append_raw_scss($scss($this));
1422 $compiler->setImportPaths($paths);
1423 }
65b8336e 1424 $compiler->append_raw_scss($this->get_extra_scss_code());
65b8336e
FM
1425
1426 try {
1427 // Compile!
1428 $compiled = $compiler->to_css();
65b8336e 1429
eadebb24 1430 } catch (\Exception $e) {
65b8336e 1431 $compiled = false;
41b973bc 1432 debugging('Error while compiling SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
65b8336e
FM
1433 }
1434
1435 // Try to save memory.
1436 $compiler = null;
1437 unset($compiler);
1438
1439 return $compiled;
1440 }
1441
af9edb2e
BB
1442 /**
1443 * Return the precompiled CSS if the precompiledcsscallback exists.
1444 *
1445 * @return string Return compiled css.
1446 */
1447 public function get_precompiled_css_content() {
0f7f0537 1448 $configs = array_reverse($this->parent_configs) + [$this];
af9edb2e
BB
1449 $css = '';
1450
1451 foreach ($configs as $config) {
1452 if (isset($config->precompiledcsscallback)) {
1453 $function = $config->precompiledcsscallback;
1454 if (function_exists($function)) {
1455 $css .= $function($this);
1456 }
1457 }
1458 }
1459 return $css;
1460 }
1461
95b06c13
DW
1462 /**
1463 * Get the icon system to use.
1464 *
1465 * @return string
1466 */
1467 public function get_icon_system() {
1468
1469 // Getting all the candidate functions.
1470 $system = false;
1471 if (isset($this->iconsystem) && \core\output\icon_system::is_valid_system($this->iconsystem)) {
1472 return $this->iconsystem;
1473 }
1474 foreach ($this->parent_configs as $parent_config) {
1475 if (isset($parent_config->iconsystem) && \core\output\icon_system::is_valid_system($parent_config->iconsystem)) {
1476 return $parent_config->iconsystem;
1477 }
1478 }
8857c715 1479 return \core\output\icon_system::STANDARD;
95b06c13
DW
1480 }
1481
d433cf37 1482 /**
258143e3 1483 * Return extra SCSS code to add when compiling.
d433cf37 1484 *
258143e3 1485 * This is intended to be used by themes to inject some SCSS code
d433cf37 1486 * before it gets compiled. If you want to inject variables you
258143e3 1487 * should use {@link self::get_scss_variables()}.
d433cf37 1488 *
258143e3 1489 * @return string The SCSS code to inject.
d433cf37 1490 */
8040fafa 1491 public function get_extra_scss_code() {
d433cf37
FM
1492 $content = '';
1493
1494 // Getting all the candidate functions.
1495 $candidates = array();
1496 foreach ($this->parent_configs as $parent_config) {
258143e3 1497 if (!isset($parent_config->extrascsscallback)) {
d433cf37
FM
1498 continue;
1499 }
258143e3 1500 $candidates[] = $parent_config->extrascsscallback;
d433cf37 1501 }
258143e3 1502 $candidates[] = $this->extrascsscallback;
d433cf37
FM
1503
1504 // Calling the functions.
1505 foreach ($candidates as $function) {
1506 if (function_exists($function)) {
258143e3 1507 $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n";
d433cf37
FM
1508 }
1509 }
1510
1511 return $content;
1512 }
1513
65b8336e 1514 /**
258143e3 1515 * SCSS code to prepend when compiling.
65b8336e 1516 *
258143e3 1517 * This is intended to be used by themes to inject SCSS code before it gets compiled.
65b8336e
FM
1518 *
1519 * @return string The SCSS code to inject.
1520 */
8040fafa 1521 public function get_pre_scss_code() {
65b8336e
FM
1522 $content = '';
1523
1524 // Getting all the candidate functions.
1525 $candidates = array();
1526 foreach ($this->parent_configs as $parent_config) {
258143e3 1527 if (!isset($parent_config->prescsscallback)) {
65b8336e
FM
1528 continue;
1529 }
258143e3 1530 $candidates[] = $parent_config->prescsscallback;
65b8336e 1531 }
258143e3 1532 $candidates[] = $this->prescsscallback;
65b8336e
FM
1533
1534 // Calling the functions.
1535 foreach ($candidates as $function) {
1536 if (function_exists($function)) {
258143e3 1537 $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n";
65b8336e
FM
1538 }
1539 }
1540
1541 return $content;
1542 }
1543
41b973bc
FM
1544 /**
1545 * Get the SCSS property.
1546 *
1547 * This resolves whether a SCSS file (or content) has to be used when generating
1548 * the stylesheet for the theme. It will look at parents themes and check the
1549 * SCSS properties there.
1550 *
1551 * @return False when SCSS is not used.
1552 * An array with the import paths, and the path to the SCSS file or Closure as second.
1553 */
1554 public function get_scss_property() {
1555 if ($this->scsscache === null) {
1556 $configs = [$this] + $this->parent_configs;
1557 $scss = null;
1558
1559 foreach ($configs as $config) {
1560 $path = "{$config->dir}/scss";
1561
1562 // We collect the SCSS property until we've found one.
1563 if (empty($scss) && !empty($config->scss)) {
1564 $candidate = is_string($config->scss) ? "{$path}/{$config->scss}.scss" : $config->scss;
1565 if ($candidate instanceof Closure) {
1566 $scss = $candidate;
1567 } else if (is_string($candidate) && is_readable($candidate)) {
1568 $scss = $candidate;
1569 }
1570 }
1571
1572 // We collect the import paths once we've found a SCSS property.
1573 if ($scss && is_dir($path)) {
1574 $paths[] = $path;
1575 }
1576
1577 }
1578
1579 $this->scsscache = $scss !== null ? [$paths, $scss] : false;
1580 }
1581
1582 return $this->scsscache;
1583 }
1584
e68c5f36 1585 /**
473dd811
SH
1586 * Generate a URL to the file that serves theme JavaScript files.
1587 *
d7656956
ARN
1588 * If we determine that the theme has no relevant files, then we return
1589 * early with a null value.
1590 *
71c03ac1 1591 * @param bool $inhead true means head url, false means footer
d7656956 1592 * @return moodle_url|null
e68c5f36 1593 */
baeb20bb 1594 public function javascript_url($inhead) {
e68c5f36
PS
1595 global $CFG;
1596
1597 $rev = theme_get_revision();
e68c5f36 1598 $params = array('theme'=>$this->name,'rev'=>$rev);
baeb20bb
PS
1599 $params['type'] = $inhead ? 'head' : 'footer';
1600
d7656956
ARN
1601 // Return early if there are no files to serve
1602 if (count($this->javascript_files($params['type'])) === 0) {
1603 return null;
1604 }
1605
ecbad2ad 1606 if (!empty($CFG->slasharguments) and $rev > 0) {
7eb50b32 1607 $url = new moodle_url("/theme/javascript.php");
ecbad2ad
PS
1608 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true);
1609 return $url;
1610 } else {
7eb50b32 1611 return new moodle_url('/theme/javascript.php', $params);
ecbad2ad 1612 }
e68c5f36
PS
1613 }
1614
473dd811
SH
1615 /**
1616 * Get the URL's for the JavaScript files used by this theme.
1617 * They won't be served directly, instead they'll be mediated through
1618 * theme/javascript.php.
1619 *
1620 * @param string $type Either javascripts_footer, or javascripts
1621 * @return array
1622 */
045f492c
SH
1623 public function javascript_files($type) {
1624 if ($type === 'footer') {
1625 $type = 'javascripts_footer';
1626 } else {
f856106b 1627 $type = 'javascripts';
045f492c 1628 }
04c01408 1629
358c13cb
PS
1630 $js = array();
1631 // find out wanted parent javascripts
045f492c 1632 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
358c13cb
PS
1633 if ($excludes !== true) {
1634 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
1635 $parent = $parent_config->name;
04c01408 1636 if (empty($parent_config->$type)) {
358c13cb
PS
1637 continue;
1638 }
1639 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1640 continue;
1641 }
04c01408 1642 foreach ($parent_config->$type as $javascript) {
358c13cb
PS
1643 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1644 and in_array($javascript, $excludes[$parent])) {
1645 continue;
1646 }
1647 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1648 if (is_readable($javascriptfile)) {
045f492c 1649 $js[] = $javascriptfile;
358c13cb
PS
1650 }
1651 }
1652 }
1653 }
1654
1655 // current theme javascripts
04c01408
PS
1656 if (is_array($this->$type)) {
1657 foreach ($this->$type as $javascript) {
358c13cb
PS
1658 $javascriptfile = "$this->dir/javascript/$javascript.js";
1659 if (is_readable($javascriptfile)) {
045f492c
SH
1660 $js[] = $javascriptfile;
1661 }
1662 }
1663 }
045f492c
SH
1664 return $js;
1665 }
1666
1667 /**
3d3fae72 1668 * Resolves an exclude setting to the themes setting is applicable or the
045f492c
SH
1669 * setting of its closest parent.
1670 *
1671 * @param string $variable The name of the setting the exclude setting to resolve
f8129210 1672 * @param string $default
045f492c
SH
1673 * @return mixed
1674 */
f8129210 1675 protected function resolve_excludes($variable, $default = null) {
045f492c
SH
1676 $setting = $default;
1677 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1678 $setting = $this->{$variable};
1679 } else {
1680 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
1681 if (!isset($parent_config->{$variable})) {
1682 continue;
1683 }
1684 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1685 $setting = $parent_config->{$variable};
1686 break;
358c13cb
PS
1687 }
1688 }
1689 }
045f492c
SH
1690 return $setting;
1691 }
358c13cb 1692
045f492c
SH
1693 /**
1694 * Returns the content of the one huge javascript file merged from all theme javascript files.
473dd811 1695 *
f8129210 1696 * @param bool $type
045f492c
SH
1697 * @return string
1698 */
1699 public function javascript_content($type) {
1700 $jsfiles = $this->javascript_files($type);
1701 $js = '';
1702 foreach ($jsfiles as $jsfile) {
1703 $js .= file_get_contents($jsfile)."\n";
1704 }
1705 return $js;
e68c5f36
PS
1706 }
1707
473dd811
SH
1708 /**
1709 * Post processes CSS.
1710 *
1711 * This method post processes all of the CSS before it is served for this theme.
1712 * This is done so that things such as image URL's can be swapped in and to
1713 * run any specific CSS post process method the theme has requested.
3d3fae72 1714 * This allows themes to use CSS settings.
473dd811
SH
1715 *
1716 * @param string $css The CSS to process.
1717 * @return string The processed CSS.
1718 */
045f492c 1719 public function post_process($css) {
78946b9b 1720 // now resolve all image locations
37824e73 1721 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
78946b9b
PS
1722 $replaced = array();
1723 foreach ($matches as $match) {
1724 if (isset($replaced[$match[0]])) {
1725 continue;
1726 }
1727 $replaced[$match[0]] = true;
1728 $imagename = $match[2];
1729 $component = rtrim($match[1], '|');
663640f5 1730 $imageurl = $this->image_url($imagename, $component)->out(false);
df06c1c4 1731 // we do not need full url because the image.php is always in the same dir
9d473266 1732 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
df06c1c4 1733 $css = str_replace($match[0], $imageurl, $css);
ebebf55c 1734 }
34a2777c 1735 }
17a6649b 1736
9ba6076c 1737 // Now resolve all font locations.
37824e73 1738 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
9ba6076c
PS
1739 $replaced = array();
1740 foreach ($matches as $match) {
1741 if (isset($replaced[$match[0]])) {
1742 continue;
1743 }
1744 $replaced[$match[0]] = true;
1745 $fontname = $match[2];
1746 $component = rtrim($match[1], '|');
1747 $fonturl = $this->font_url($fontname, $component)->out(false);
1748 // We do not need full url because the font.php is always in the same dir.
1749 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1750 $css = str_replace($match[0], $fonturl, $css);
1751 }
1752 }
1753
dc48cc0a
AA
1754 // Now resolve all theme settings or do any other postprocessing.
1755 // This needs to be done before calling core parser, since the parser strips [[settings]] tags.
1756 $csspostprocess = $this->csspostprocess;
1757 if (function_exists($csspostprocess)) {
1758 $css = $csspostprocess($css, $this);
1759 }
1760
1d987cae 1761 // Post processing using an object representation of CSS.
493ef66e
FM
1762 $treeprocessor = $this->get_css_tree_post_processor();
1763 $needsparsing = !empty($treeprocessor) || !empty($this->rtlmode);
1d987cae 1764 if ($needsparsing) {
061a39ac 1765
1081de20 1766 // We might need more memory/time to do this, so let's play safe.
061a39ac 1767 raise_memory_limit(MEMORY_EXTRA);
1081de20 1768 core_php_time_limit::raise(300);
061a39ac 1769
1d987cae
FM
1770 $parser = new core_cssparser($css);
1771 $csstree = $parser->parse();
1772 unset($parser);
1d987cae 1773
d8f90ec6
FM
1774 if ($this->rtlmode) {
1775 $this->rtlize($csstree);
1776 }
1777
493ef66e
FM
1778 if ($treeprocessor) {
1779 $treeprocessor($csstree, $this);
d8f90ec6 1780 }
1d987cae 1781
1d987cae
FM
1782 $css = $csstree->render();
1783 unset($csstree);
1784 }
1785
78946b9b 1786 return $css;
ebebf55c 1787 }
17a6649b 1788
1d987cae
FM
1789 /**
1790 * Flip a stylesheet to RTL.
1791 *
1792 * @param Object $csstree The parsed CSS tree structure to flip.
1793 * @return void
1794 */
1795 protected function rtlize($csstree) {
1796 $rtlcss = new core_rtlcss($csstree);
1797 $rtlcss->flip();
1798 }
1799
ebebf55c 1800 /**
c266d256
DW
1801 * Return the direct URL for an image from the pix folder.
1802 *
1803 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
78946b9b 1804 *
088598ba 1805 * @deprecated since Moodle 3.3
78946b9b 1806 * @param string $imagename the name of the icon.
f8129210 1807 * @param string $component specification of one plugin like in get_string()
78946b9b 1808 * @return moodle_url
fdeb7fa1 1809 */
c39e5ba2 1810 public function pix_url($imagename, $component) {
088598ba 1811 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
c266d256
DW
1812 return $this->image_url($imagename, $component);
1813 }
1814
1815 /**
1816 * Return the direct URL for an image from the pix folder.
1817 *
1818 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1819 *
1820 * @param string $imagename the name of the icon.
1821 * @param string $component specification of one plugin like in get_string()
1822 * @return moodle_url
1823 */
1824 public function image_url($imagename, $component) {
fdeb7fa1 1825 global $CFG;
78946b9b 1826
9d473266 1827 $params = array('theme'=>$this->name);
436dbeec 1828 $svg = $this->use_svg_icons();
9d473266
PS
1829
1830 if (empty($component) or $component === 'moodle' or $component === 'core') {
1831 $params['component'] = 'core';
1832 } else {
1833 $params['component'] = $component;
1834 }
78946b9b
PS
1835
1836 $rev = theme_get_revision();
1837 if ($rev != -1) {
1838 $params['rev'] = $rev;
1839 }
9d473266
PS
1840
1841 $params['image'] = $imagename;
1842
7eb50b32 1843 $url = new moodle_url("/theme/image.php");
9d473266 1844 if (!empty($CFG->slasharguments) and $rev > 0) {
436dbeec
SH
1845 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1846 if (!$svg) {
1847 // We add a simple /_s to the start of the path.
1848 // The underscore is used to ensure that it isn't a valid theme name.
1849 $path = '/_s'.$path;
1850 }
1851 $url->set_slashargument($path, 'noparam', true);
9d473266 1852 } else {
436dbeec
SH
1853 if (!$svg) {
1854 // We add an SVG param so that we know not to serve SVG images.
1855 // We do this because all modern browsers support SVG and this param will one day be removed.
1856 $params['svg'] = '0';
1857 }
1858 $url->params($params);
fdeb7fa1 1859 }
78946b9b 1860
9d473266 1861 return $url;
fdeb7fa1 1862 }
1863
9ba6076c
PS
1864 /**
1865 * Return the URL for a font
1866 *
1867 * @param string $font the name of the font (including extension).
1868 * @param string $component specification of one plugin like in get_string()
1869 * @return moodle_url
1870 */
1871 public function font_url($font, $component) {
1872 global $CFG;
1873
1874 $params = array('theme'=>$this->name);
1875
1876 if (empty($component) or $component === 'moodle' or $component === 'core') {
1877 $params['component'] = 'core';
1878 } else {
1879 $params['component'] = $component;
1880 }
1881
1882 $rev = theme_get_revision();
1883 if ($rev != -1) {
1884 $params['rev'] = $rev;
1885 }
1886
1887 $params['font'] = $font;
1888
7eb50b32 1889 $url = new moodle_url("/theme/font.php");
9ba6076c
PS
1890 if (!empty($CFG->slasharguments) and $rev > 0) {
1891 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1892 $url->set_slashargument($path, 'noparam', true);
1893 } else {
1894 $url->params($params);
1895 }
1896
1897 return $url;
1898 }
1899
fe7b75f8
PS
1900 /**
1901 * Returns URL to the stored file via pluginfile.php.
1902 *
1903 * Note the theme must also implement pluginfile.php handler,
1904 * theme revision is used instead of the itemid.
1905 *
1906 * @param string $setting
1907 * @param string $filearea
1908 * @return string protocol relative URL or null if not present
1909 */
1910 public function setting_file_url($setting, $filearea) {
1911 global $CFG;
1912
1913 if (empty($this->settings->$setting)) {
1914 return null;
1915 }
1916
1917 $component = 'theme_'.$this->name;
1918 $itemid = theme_get_revision();
1919 $filepath = $this->settings->$setting;
1920 $syscontext = context_system::instance();
1921
1922 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1923
1924 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1925 // Note: unfortunately moodle_url does not support //urls yet.
1926
1927 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1928
1929 return $url;
1930 }
1931
1932 /**
1933 * Serve the theme setting file.
1934 *
1935 * @param string $filearea
1936 * @param array $args
1937 * @param bool $forcedownload
1938 * @param array $options
1939 * @return bool may terminate if file not found or donotdie not specified
1940 */
1941 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1942 global $CFG;
1943 require_once("$CFG->libdir/filelib.php");
1944
1945 $syscontext = context_system::instance();
1946 $component = 'theme_'.$this->name;
1947
1948 $revision = array_shift($args);
1949 if ($revision < 0) {
1950 $lifetime = 0;
1951 } else {
1952 $lifetime = 60*60*24*60;
bb8ed60a
MS
1953 // By default, theme files must be cache-able by both browsers and proxies.
1954 if (!array_key_exists('cacheability', $options)) {
1955 $options['cacheability'] = 'public';
1956 }
fe7b75f8
PS
1957 }
1958
1959 $fs = get_file_storage();
1960 $relativepath = implode('/', $args);
1961
1962 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1963 $fullpath = rtrim($fullpath, '/');
1964 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1965 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1966 return true;
1967 } else {
1968 send_file_not_found();
1969 }
1970 }
1971
fdeb7fa1 1972 /**
78946b9b 1973 * Resolves the real image location.
436dbeec
SH
1974 *
1975 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1976 * and we need a way in which to turn it off.
1977 * By default SVG won't be used unless asked for. This is done for two reasons:
1978 * 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
1979 * browser supports SVG.
1980 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1981 * by the user due to security concerns.
1982 *
78946b9b
PS
1983 * @param string $image name of image, may contain relative path
1984 * @param string $component
62306cdf
JD
1985 * @param bool $svg|null Should SVG images also be looked for? If null, resorts to $CFG->svgicons if that is set; falls back to
1986 * auto-detection of browser support otherwise
78946b9b 1987 * @return string full file path
fdeb7fa1 1988 */
436dbeec 1989 public function resolve_image_location($image, $component, $svg = false) {
78946b9b
PS
1990 global $CFG;
1991
436dbeec
SH
1992 if (!is_bool($svg)) {
1993 // If $svg isn't a bool then we need to decide for ourselves.
1994 $svg = $this->use_svg_icons();
1995 }
1996
78946b9b 1997 if ($component === 'moodle' or $component === 'core' or empty($component)) {
436dbeec 1998 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
78946b9b
PS
1999 return $imagefile;
2000 }
2001 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
436dbeec 2002 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
78946b9b
PS
2003 return $imagefile;
2004 }
2005 }
436dbeec 2006 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
f930cf6b
EM
2007 return $imagefile;
2008 }
436dbeec 2009 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
78946b9b
PS
2010 return $imagefile;
2011 }
2012 return null;
2013
2014 } else if ($component === 'theme') { //exception
2015 if ($image === 'favicon') {
2016 return "$this->dir/pix/favicon.ico";
2017 }
436dbeec 2018 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
78946b9b
PS
2019 return $imagefile;
2020 }
2021 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
436dbeec 2022 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
78946b9b
PS
2023 return $imagefile;
2024 }
2025 }
2026 return null;
2027
78946b9b
PS
2028 } else {
2029 if (strpos($component, '_') === false) {
2030 $component = 'mod_'.$component;
2031 }
2032 list($type, $plugin) = explode('_', $component, 2);
2033
436dbeec 2034 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
78946b9b
PS
2035 return $imagefile;
2036 }
2037 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
436dbeec 2038 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
78946b9b
PS
2039 return $imagefile;
2040 }
2041 }
436dbeec 2042 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
f930cf6b
EM
2043 return $imagefile;
2044 }
1c74b260 2045 $dir = core_component::get_plugin_directory($type, $plugin);
436dbeec 2046 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
78946b9b
PS
2047 return $imagefile;
2048 }
2049 return null;
fdeb7fa1 2050 }
fdeb7fa1 2051 }
2052
9ba6076c
PS
2053 /**
2054 * Resolves the real font location.
2055 *
2056 * @param string $font name of font file
2057 * @param string $component
2058 * @return string full file path
2059 */
2060 public function resolve_font_location($font, $component) {
2061 global $CFG;
2062
2063 if ($component === 'moodle' or $component === 'core' or empty($component)) {
2064 if (file_exists("$this->dir/fonts_core/$font")) {
2065 return "$this->dir/fonts_core/$font";
2066 }
2067 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2068 if (file_exists("$parent_config->dir/fonts_core/$font")) {
2069 return "$parent_config->dir/fonts_core/$font";
2070 }
2071 }
2072 if (file_exists("$CFG->dataroot/fonts/$font")) {
2073 return "$CFG->dataroot/fonts/$font";
2074 }
2075 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
2076 return "$CFG->dirroot/lib/fonts/$font";
2077 }
2078 return null;
2079
2080 } else if ($component === 'theme') { // Exception.
2081 if (file_exists("$this->dir/fonts/$font")) {
2082 return "$this->dir/fonts/$font";
2083 }
2084 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2085 if (file_exists("$parent_config->dir/fonts/$font")) {
2086 return "$parent_config->dir/fonts/$font";
2087 }
2088 }
2089 return null;
2090
2091 } else {
2092 if (strpos($component, '_') === false) {
2093 $component = 'mod_'.$component;
2094 }
2095 list($type, $plugin) = explode('_', $component, 2);
2096
2097 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
2098 return "$this->dir/fonts_plugins/$type/$plugin/$font";
2099 }
2100 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
2101 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
2102 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
2103 }
2104 }
2105 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
2106 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
2107 }
2108 $dir = core_component::get_plugin_directory($type, $plugin);
2109 if (file_exists("$dir/fonts/$font")) {
2110 return "$dir/fonts/$font";
2111 }
2112 return null;
2113 }
2114 }
2115
436dbeec
SH
2116 /**
2117 * Return true if we should look for SVG images as well.
2118 *
436dbeec
SH
2119 * @return bool
2120 */
2121 public function use_svg_icons() {
2122 global $CFG;
2123 if ($this->usesvg === null) {
c3d2fbf9 2124
ba2ad431 2125 if (!isset($CFG->svgicons)) {
c3d2fbf9 2126 $this->usesvg = core_useragent::supports_svg();
436dbeec
SH
2127 } else {
2128 // Force them on/off depending upon the setting.
ba2ad431 2129 $this->usesvg = (bool)$CFG->svgicons;
436dbeec
SH
2130 }
2131 }
2132 return $this->usesvg;
2133 }
2134
f7d6a556
SH
2135 /**
2136 * Forces the usesvg setting to either true or false, avoiding any decision making.
2137 *
2138 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
383b89a1 2139 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
f7d6a556
SH
2140 *
2141 * @param bool $setting True to force the use of svg when available, null otherwise.
2142 */
383b89a1 2143 public function force_svg_use($setting) {
f7d6a556
SH
2144 $this->usesvg = (bool)$setting;
2145 }
2146
1d987cae
FM
2147 /**
2148 * Set to be in RTL mode.
2149 *
2150 * This will likely be used when post processing the CSS before serving it.
2151 *
2152 * @param bool $inrtl True when in RTL mode.
2153 */
2154 public function set_rtl_mode($inrtl = true) {
2155 $this->rtlmode = $inrtl;
2156 }
2157
0e9911e1
AN
2158 /**
2159 * Whether the theme is being served in RTL mode.
2160 *
2161 * @return bool True when in RTL mode.
2162 */
2163 public function get_rtl_mode() {
2164 return $this->rtlmode;
2165 }
2166
d4a03c00 2167 /**
78946b9b 2168 * Checks if file with any image extension exists.
473dd811 2169 *
436dbeec
SH
2170 * The order to these images was adjusted prior to the release of 2.4
2171 * At that point the were the following image counts in Moodle core:
2172 *
2173 * - png = 667 in pix dirs (1499 total)
2174 * - gif = 385 in pix dirs (606 total)
2175 * - jpg = 62 in pix dirs (74 total)
2176 * - jpeg = 0 in pix dirs (1 total)
2177 *
2178 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
2179 *
78946b9b 2180 * @param string $filepath
436dbeec 2181 * @param bool $svg If set to true SVG images will also be looked for.
78946b9b 2182 * @return string image name with extension
d4a03c00 2183 */
436dbeec
SH
2184 private static function image_exists($filepath, $svg = false) {
2185 if ($svg && file_exists("$filepath.svg")) {
2186 return "$filepath.svg";
78946b9b
PS
2187 } else if (file_exists("$filepath.png")) {
2188 return "$filepath.png";
436dbeec
SH
2189 } else if (file_exists("$filepath.gif")) {
2190 return "$filepath.gif";
78946b9b
PS
2191 } else if (file_exists("$filepath.jpg")) {
2192 return "$filepath.jpg";
2193 } else if (file_exists("$filepath.jpeg")) {
2194 return "$filepath.jpeg";
d4a03c00 2195 } else {
78946b9b 2196 return false;
d4a03c00 2197 }
2198 }
2199
fdeb7fa1 2200 /**
78946b9b 2201 * Loads the theme config from config.php file.
473dd811 2202 *
78946b9b 2203 * @param string $themename
473dd811 2204 * @param stdClass $settings from config_plugins table
b0ec47fb 2205 * @param boolean $parentscheck true to also check the parents. .
473dd811 2206 * @return stdClass The theme configuration
fdeb7fa1 2207 */
b0ec47fb 2208 private static function find_theme_config($themename, $settings, $parentscheck = true) {
78946b9b
PS
2209 // We have to use the variable name $THEME (upper case) because that
2210 // is what is used in theme config.php files.
fdeb7fa1 2211
78946b9b
PS
2212 if (!$dir = theme_config::find_theme_location($themename)) {
2213 return null;
fdeb7fa1 2214 }
2f67a9b3 2215
365a5941 2216 $THEME = new stdClass();
78946b9b
PS
2217 $THEME->name = $themename;
2218 $THEME->dir = $dir;
2219 $THEME->settings = $settings;
2220
2221 global $CFG; // just in case somebody tries to use $CFG in theme config
2222 include("$THEME->dir/config.php");
2223
2224 // verify the theme configuration is OK
2225 if (!is_array($THEME->parents)) {
2226 // parents option is mandatory now
2227 return null;
b0ec47fb
JM
2228 } else {
2229 // We use $parentscheck to only check the direct parents (avoid infinite loop).
2230 if ($parentscheck) {
2231 // Find all parent theme configs.
2232 foreach ($THEME->parents as $parent) {
2233 $parentconfig = theme_config::find_theme_config($parent, $settings, false);
2234 if (empty($parentconfig)) {
2235 return null;
2236 }
2237 }
2238 }
fdeb7fa1 2239 }
2240
78946b9b 2241 return $THEME;
fdeb7fa1 2242 }
2243
d4a03c00 2244 /**
78946b9b
PS
2245 * Finds the theme location and verifies the theme has all needed files
2246 * and is not obsoleted.
473dd811 2247 *
78946b9b
PS
2248 * @param string $themename
2249 * @return string full dir path or null if not found
d4a03c00 2250 */
78946b9b
PS
2251 private static function find_theme_location($themename) {
2252 global $CFG;
2253
2254 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2255 $dir = "$CFG->dirroot/theme/$themename";
d4a03c00 2256
3dd1d7e7
DM
2257 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
2258 $dir = "$CFG->themedir/$themename";
2259
7d875874 2260 } else {
78946b9b 2261 return null;
d4a03c00 2262 }
78946b9b
PS
2263
2264 if (file_exists("$dir/styles.php")) {
2265 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
2266 return null;
2267 }
2f67a9b3 2268
78946b9b 2269 return $dir;
d4a03c00 2270 }
2271
1d13c75c 2272 /**
78946b9b 2273 * Get the renderer for a part of Moodle for this theme.
473dd811 2274 *
78946b9b 2275 * @param moodle_page $page the page we are rendering
f8129210 2276 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
78946b9b 2277 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
c927e35c 2278 * @param string $target one of rendering target constants
78946b9b 2279 * @return renderer_base the requested renderer.
1d13c75c 2280 */
c927e35c 2281 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
78946b9b 2282 if (is_null($this->rf)) {
c927e35c 2283 $classname = $this->rendererfactory;
78946b9b 2284 $this->rf = new $classname($this);
1d13c75c 2285 }
78946b9b 2286
c927e35c 2287 return $this->rf->get_renderer($page, $component, $subtype, $target);
1d13c75c 2288 }
2289
fdeb7fa1 2290 /**
78946b9b 2291 * Get the information from {@link $layouts} for this type of page.
473dd811 2292 *
78946b9b
PS
2293 * @param string $pagelayout the the page layout name.
2294 * @return array the appropriate part of {@link $layouts}.
fdeb7fa1 2295 */
78946b9b
PS
2296 protected function layout_info_for_page($pagelayout) {
2297 if (array_key_exists($pagelayout, $this->layouts)) {
2298 return $this->layouts[$pagelayout];
2299 } else {
191b267b
PS
2300 debugging('Invalid page layout specified: ' . $pagelayout);
2301 return $this->layouts['standard'];
fdeb7fa1 2302 }
2303 }
2304
2305 /**
78946b9b
PS
2306 * Given the settings of this theme, and the page pagelayout, return the
2307 * full path of the page layout file to use.
2308 *
2309 * Used by {@link core_renderer::header()}.
2310 *
2311 * @param string $pagelayout the the page layout name.
2312 * @return string Full path to the lyout file to use
ebebf55c 2313 */
78946b9b 2314 public function layout_file($pagelayout) {
ebebf55c 2315 global $CFG;
fdeb7fa1 2316
78946b9b
PS
2317 $layoutinfo = $this->layout_info_for_page($pagelayout);
2318 $layoutfile = $layoutinfo['file'];
fdeb7fa1 2319
84db3ea2
SH
2320 if (array_key_exists('theme', $layoutinfo)) {
2321 $themes = array($layoutinfo['theme']);
2322 } else {
2323 $themes = array_merge(array($this->name),$this->parents);
2324 }
4399b9d5 2325
84db3ea2
SH
2326 foreach ($themes as $theme) {
2327 if ($dir = $this->find_theme_location($theme)) {
2328 $path = "$dir/layout/$layoutfile";
2329
2330 // Check the template exists, return general base theme template if not.
2331 if (is_readable($path)) {
2332 return $path;
2333 }
78946b9b 2334 }
34a2777c 2335 }
2336
191b267b 2337 debugging('Can not find layout file for: ' . $pagelayout);
78946b9b
PS
2338 // fallback to standard normal layout
2339 return "$CFG->dirroot/theme/base/layout/general.php";
2340 }
ebebf55c 2341
78946b9b
PS
2342 /**
2343 * Returns auxiliary page layout options specified in layout configuration array.
473dd811 2344 *
78946b9b
PS
2345 * @param string $pagelayout
2346 * @return array
2347 */
2348 public function pagelayout_options($pagelayout) {
2349 $info = $this->layout_info_for_page($pagelayout);
2350 if (!empty($info['options'])) {
2351 return $info['options'];
34a2777c 2352 }
78946b9b
PS
2353 return array();
2354 }
34a2777c 2355
78946b9b
PS
2356 /**
2357 * Inform a block_manager about the block regions this theme wants on this
2358 * page layout.
473dd811 2359 *
78946b9b
PS
2360 * @param string $pagelayout the general type of the page.
2361 * @param block_manager $blockmanager the block_manger to set up.
78946b9b
PS
2362 */
2363 public function setup_blocks($pagelayout, $blockmanager) {
2364 $layoutinfo = $this->layout_info_for_page($pagelayout);
2365 if (!empty($layoutinfo['regions'])) {
292dcf04 2366 $blockmanager->add_regions($layoutinfo['regions'], false);
78946b9b 2367 $blockmanager->set_default_region($layoutinfo['defaultregion']);
ebebf55c 2368 }
34a2777c 2369 }
2370
473dd811
SH
2371 /**
2372 * Gets the visible name for the requested block region.
2373 *
2374 * @param string $region The region name to get
2375 * @param string $theme The theme the region belongs to (may come from the parent theme)
2376 * @return string
2377 */
cadc0d28
TH
2378 protected function get_region_name($region, $theme) {
2379 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
2380 // A name exists in this theme, so use it
2381 if (substr($regionstring, 0, 1) != '[') {
2382 return $regionstring;
2383 }
2384
2385 // Otherwise, try to find one elsewhere
2386 // Check parents, if any
2387 foreach ($this->parents as $parentthemename) {
2388 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
2389 if (substr($regionstring, 0, 1) != '[') {
2390 return $regionstring;
2391 }
2392 }
2393
a5a6df54
MM
2394 // Last resort, try the boost theme for names
2395 return get_string('region-' . $region, 'theme_boost');
cadc0d28
TH
2396 }
2397
ebebf55c 2398 /**
78946b9b 2399 * Get the list of all block regions known to this theme in all templates.
473dd811 2400 *
78946b9b 2401 * @return array internal region name => human readable name.
ebebf55c 2402 */
78946b9b
PS
2403 public function get_all_block_regions() {
2404 $regions = array();
78946b9b
PS
2405 foreach ($this->layouts as $layoutinfo) {
2406 foreach ($layoutinfo['regions'] as $region) {
a9535f79 2407 $regions[$region] = $this->get_region_name($region, $this->name);
ebebf55c 2408 }
34a2777c 2409 }
78946b9b 2410 return $regions;
34a2777c 2411 }
d609d962
SH
2412
2413 /**
2414 * Returns the human readable name of the theme
2415 *
2416 * @return string
2417 */
2418 public function get_theme_name() {
2419 return get_string('pluginname', 'theme_'.$this->name);
2420 }
225c418f
SH
2421
2422 /**
2423 * Returns the block render method.
2424 *
2425 * It is set by the theme via:
2426 * $THEME->blockrendermethod = '...';
2427 *
2428 * It can be one of two values, blocks or blocks_for_region.
2429 * It should be set to the method being used by the theme layouts.
2430 *
2431 * @return string
2432 */
2433 public function get_block_render_method() {
2434 if ($this->blockrendermethod) {
2435 // Return the specified block render method.
2436 return $this->blockrendermethod;
2437 }
2438 // Its not explicitly set, check the parent theme configs.
2439 foreach ($this->parent_configs as $config) {
2440 if (isset($config->blockrendermethod)) {
2441 return $config->blockrendermethod;
2442 }
2443 }
2444 // Default it to blocks.
2445 return 'blocks';
2446 }
493ef66e
FM
2447
2448 /**
2449 * Get the callable for CSS tree post processing.
2450 *
2451 * @return string|null
2452 */
2453 public function get_css_tree_post_processor() {
2454 $configs = [$this] + $this->parent_configs;
2455 foreach ($configs as $config) {
755b013f 2456 if (!empty($config->csstreepostprocessor) && is_callable($config->csstreepostprocessor)) {
493ef66e
FM
2457 return $config->csstreepostprocessor;
2458 }
2459 }
2460 return null;
2461 }
a26ce248 2462
ebebf55c 2463}
34a2777c 2464
ebebf55c 2465/**
d9c8f425 2466 * This class keeps track of which HTML tags are currently open.
2467 *
2468 * This makes it much easier to always generate well formed XHTML output, even
2469 * if execution terminates abruptly. Any time you output some opening HTML
2470 * without the matching closing HTML, you should push the necessary close tags
2471 * onto the stack.
ebebf55c 2472 *
2473 * @copyright 2009 Tim Hunt
473dd811
SH
2474 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2475 * @since Moodle 2.0
f8129210 2476 * @package core
76be40cc 2477 * @category output
ebebf55c 2478 */
d9c8f425 2479class xhtml_container_stack {
473dd811
SH
2480
2481 /**
76be40cc 2482 * @var array Stores the list of open containers.
473dd811 2483 */
d9c8f425 2484 protected $opencontainers = array();
473dd811 2485
fa1afe32 2486 /**
76be40cc 2487 * @var array In developer debug mode, stores a stack trace of all opens and
d9c8f425 2488 * closes, so we can output helpful error messages when there is a mismatch.
fa1afe32 2489 */
d9c8f425 2490 protected $log = array();
473dd811 2491
fa1afe32 2492 /**
76be40cc
SH
2493 * @var boolean Store whether we are developer debug mode. We need this in
2494 * several places including in the destructor where we may not have access to $CFG.
fa1afe32 2495 */
d9c8f425 2496 protected $isdebugging;
34a2777c 2497
473dd811
SH
2498 /**
2499 * Constructor
2500 */
d9c8f425 2501 public function __construct() {
96f81ea3
PS
2502 global $CFG;
2503 $this->isdebugging = $CFG->debugdeveloper;
ebebf55c 2504 }
34a2777c 2505
fa1afe32 2506 /**
d9c8f425 2507 * Push the close HTML for a recently opened container onto the stack.
473dd811 2508 *
d9c8f425 2509 * @param string $type The type of container. This is checked when {@link pop()}
2510 * is called and must match, otherwise a developer debug warning is output.
2511 * @param string $closehtml The HTML required to close the container.
fa1afe32 2512 */
d9c8f425 2513 public function push($type, $closehtml) {
2514 $container = new stdClass;
2515 $container->type = $type;
2516 $container->closehtml = $closehtml;
2517 if ($this->isdebugging) {
2518 $this->log('Open', $type);
3aaa27f4 2519 }
d9c8f425 2520 array_push($this->opencontainers, $container);
ebebf55c 2521 }
34a2777c 2522
fa1afe32 2523 /**
d9c8f425 2524 * Pop the HTML for the next closing container from the stack. The $type
2525 * must match the type passed when the container was opened, otherwise a
2526 * warning will be output.
473dd811 2527 *
d9c8f425 2528 * @param string $type The type of container.
2529 * @return string the HTML required to close the container.
fa1afe32 2530 */
d9c8f425 2531 public function pop($type) {
2532 if (empty($this->opencontainers)) {
2533 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2534 $this->output_log(), DEBUG_DEVELOPER);
2535 return;
3aaa27f4 2536 }
ebebf55c 2537
d9c8f425 2538 $container = array_pop($this->opencontainers);
2539 if ($container->type != $type) {
2540 debugging('<p>The type of container to be closed (' . $container->type .
2541 ') does not match the type of the next open container (' . $type .
2542 '). This suggests there is a nesting problem.</p>' .
2543 $this->output_log(), DEBUG_DEVELOPER);
ebebf55c 2544 }
d9c8f425 2545 if ($this->isdebugging) {
2546 $this->log('Close', $type);
e8775320 2547 }
d9c8f425 2548 return $container->closehtml;
ebebf55c 2549 }
e8775320 2550
fa1afe32 2551 /**
d9c8f425 2552 * Close all but the last open container. This is useful in places like error
2553 * handling, where you want to close all the open containers (apart from <body>)
2554 * before outputting the error message.
473dd811 2555 *
d9c8f425 2556 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2557 * developer debug warning if it isn't.
2558 * @return string the HTML required to close any open containers inside <body>.
fa1afe32 2559 */
d9c8f425 2560 public function pop_all_but_last($shouldbenone = false) {
2561 if ($shouldbenone && count($this->opencontainers) != 1) {
2562 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2563 $this->output_log(), DEBUG_DEVELOPER);
2564 }
2565 $output = '';
2566 while (count($this->opencontainers) > 1) {
2567 $container = array_pop($this->opencontainers);
2568 $output .= $container->closehtml;
e8775320 2569 }
d9c8f425 2570 return $output;
e8775320 2571 }
34a2777c 2572
ebebf55c 2573 /**
d9c8f425 2574 * You can call this function if you want to throw away an instance of this
2575 * class without properly emptying the stack (for example, in a unit test).
2576 * Calling this method stops the destruct method from outputting a developer
2577 * debug warning. After calling this method, the instance can no longer be used.
ebebf55c 2578 */
d9c8f425 2579 public function discard() {
2580 $this->opencontainers = null;
ebebf55c 2581 }
d9c8f425 2582
fa1afe32 2583 /**
d9c8f425 2584 * Adds an entry to the log.
473dd811 2585 *
d9c8f425 2586 * @param string $action The name of the action
2587 * @param string $type The type of action
fa1afe32 2588 */
d9c8f425 2589 protected function log($action, $type) {
2590 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
2591 format_backtrace(debug_backtrace()) . '</li>';
ebebf55c 2592 }
34a2777c 2593
fa1afe32 2594 /**
d9c8f425 2595 * Outputs the log's contents as a HTML list.
473dd811 2596 *
d9c8f425 2597 * @return string HTML list of the log
fa1afe32 2598 */
d9c8f425 2599 protected function output_log() {
2600 return '<ul>' . implode("\n", $this->log) . '</ul>';
34a2777c 2601 }
6fc267a0 2602}