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