Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
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
 
17
namespace core\output;
18
 
19
use block_manager;
20
use cache;
21
use cache_store;
22
use core_component;
23
use core_cssparser;
24
use core_minify;
25
use core_php_time_limit;
26
use core_rtlcss;
27
use core_scss;
28
use core_useragent;
29
use core\context\system as context_system;
30
use core\exception\coding_exception;
31
use core\output\renderer_factory\renderer_factory_interface as renderer_factory;
32
use core\output\renderer_factory\standard_renderer_factory;
33
use dml_exception;
34
use moodle_page;
35
use moodle_url;
36
use stdClass;
37
 
38
// phpcs:disable moodle.NamingConventions.ValidVariableName.VariableNameUnderscore
39
// phpcs:disable moodle.NamingConventions.ValidVariableName.MemberNameUnderscore
40
 
41
/**
42
 * This class represents the configuration variables of a Moodle theme.
43
 *
44
 * All the variables with access: public below (with a few exceptions that are marked)
45
 * are the properties you can set in your themes config.php file.
46
 *
47
 * There are also some methods and protected variables that are part of the inner
48
 * workings of Moodle's themes system. If you are just editing a themes config.php
49
 * file, you can just ignore those, and the following information for developers.
50
 *
51
 * Normally, to create an instance of this class, you should use the
52
 * {@see theme_config::load()} factory method to load a themes config.php file.
53
 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
54
 * will create one for you, accessible as $PAGE->theme.
55
 *
56
 * @copyright 2009 Tim Hunt
57
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
58
 * @package core
59
 * @category output
60
 */
61
class theme_config {
62
    /**
63
     * @var string Default theme, used when requested theme not found.
64
     */
65
    const DEFAULT_THEME = 'boost';
66
 
67
    /** The key under which the SCSS file is stored amongst the CSS files. */
68
    const SCSS_KEY = '__SCSS__';
69
 
70
    /**
71
     * @var array You can base your theme on other themes by linking to the other theme as
72
     * parents. This lets you use the CSS and layouts from the other themes
73
     * (see {@see theme_config::$layouts}).
74
     * That makes it easy to create a new theme that is similar to another one
75
     * but with a few changes. In this themes CSS you only need to override
76
     * those rules you want to change.
77
     */
78
    public $parents;
79
 
80
    /**
81
     * @var array The names of all the stylesheets from this theme that you would
82
     * like included, in order. Give the names of the files without .css.
83
     */
84
    public $sheets = [];
85
 
86
    /**
87
     * @var array The names of all the stylesheets from parents that should be excluded.
88
     * true value may be used to specify all parents or all themes from one parent.
89
     * If no value specified value from parent theme used.
90
     */
91
    public $parents_exclude_sheets = null;
92
 
93
    /**
94
     * @var array List of plugin sheets to be excluded.
95
     * If no value specified value from parent theme used.
96
     */
97
    public $plugins_exclude_sheets = null;
98
 
99
    /**
100
     * @var array List of style sheets that are included in the text editor bodies.
101
     * Sheets from parent themes are used automatically and can not be excluded.
102
     */
103
    public $editor_sheets = [];
104
 
105
    /**
106
     * @var bool Whether a fallback version of the stylesheet will be used
107
     * whilst the final version is generated.
108
     */
109
    public $usefallback = false;
110
 
111
    /**
112
     * @var array The names of all the javascript files this theme that you would
113
     * like included from head, in order. Give the names of the files without .js.
114
     */
115
    public $javascripts = [];
116
 
117
    /**
118
     * @var array The names of all the javascript files this theme that you would
119
     * like included from footer, in order. Give the names of the files without .js.
120
     */
121
    public $javascripts_footer = [];
122
 
123
    /**
124
     * @var array The names of all the javascript files from parents that should
125
     * be excluded. true value may be used to specify all parents or all themes
126
     * from one parent.
127
     * If no value specified value from parent theme used.
128
     */
129
    public $parents_exclude_javascripts = null;
130
 
131
    /**
132
     * @var array Which file to use for each page layout.
133
     *
134
     * This is an array of arrays. The keys of the outer array are the different layouts.
135
     * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
136
     * 'popup', 'form', .... The most reliable way to get a complete list is to look at
137
     * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
138
     * That file also has a good example of how to set this setting.
139
     *
140
     * For each layout, the value in the outer array is an array that describes
141
     * how you want that type of page to look. For example
142
     * <pre>
143
     *   $THEME->layouts = array(
144
     *       // Most pages - if we encounter an unknown or a missing page type, this one is used.
145
     *       'standard' => array(
146
     *           'theme' = 'mytheme',
147
     *           'file' => 'normal.php',
148
     *           'regions' => array('side-pre', 'side-post'),
149
     *           'defaultregion' => 'side-post'
150
     *       ),
151
     *       // The site home page.
152
     *       'home' => array(
153
     *           'theme' = 'mytheme',
154
     *           'file' => 'home.php',
155
     *           'regions' => array('side-pre', 'side-post'),
156
     *           'defaultregion' => 'side-post'
157
     *       ),
158
     *       // ...
159
     *   );
160
     * </pre>
161
     *
162
     * 'theme' name of the theme where is the layout located
163
     * 'file' is the layout file to use for this type of page.
164
     * layout files are stored in layout subfolder
165
     * 'regions' This lists the regions on the page where blocks may appear. For
166
     * each region you list here, your layout file must include a call to
167
     * <pre>
168
     *   echo $OUTPUT->blocks_for_region($regionname);
169
     * </pre>
170
     * or equivalent so that the blocks are actually visible.
171
     *
172
     * 'defaultregion' If the list of regions is non-empty, then you must pick
173
     * one of the one of them as 'default'. This has two meanings. First, this is
174
     * where new blocks are added. Second, if there are any blocks associated with
175
     * the page, but in non-existent regions, they appear here. (Imaging, for example,
176
     * that someone added blocks using a different theme that used different region
177
     * names, and then switched to this theme.)
178
     */
179
    public $layouts = [];
180
 
181
    /**
182
     * @var string Name of the renderer factory class to use. Must implement the
183
     * {@see renderer_factory} interface.
184
     *
185
     * This is an advanced feature. Moodle output is generated by 'renderers',
186
     * you can customise the HTML that is output by writing custom renderers,
187
     * and then you need to specify 'renderer factory' so that Moodle can find
188
     * your renderers.
189
     *
190
     * There are some renderer factories supplied with Moodle. Please follow these
191
     * links to see what they do.
192
     * <ul>
193
     * <li>{@see standard_renderer_factory} - the default.</li>
194
     * <li>{@see theme_overridden_renderer_factory} - use this if you want to write
195
     *      your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
196
     * </ul>
197
     */
198
    public $rendererfactory = standard_renderer_factory::class;
199
 
200
    /**
201
     * @var string Function to do custom CSS post-processing.
202
     *
203
     * This is an advanced feature. If you want to do custom post-processing on the
204
     * CSS before it is output (for example, to replace certain variable names
205
     * with particular values) you can give the name of a function here.
206
     */
207
    public $csspostprocess = null;
208
 
209
    /**
210
     * @var string Function to do custom CSS post-processing on a parsed CSS tree.
211
     *
212
     * This is an advanced feature. If you want to do custom post-processing on the
213
     * CSS before it is output, you can provide the name of the function here. The
214
     * function will receive a CSS tree document as first parameter, and the theme_config
215
     * object as second parameter. A return value is not required, the tree can
216
     * be edited in place.
217
     */
218
    public $csstreepostprocessor = null;
219
 
220
    /**
221
     * @var string Accessibility: Right arrow-like character is
222
     * used in the breadcrumb trail, course navigation menu
223
     * (previous/next activity), calendar, and search forum block.
224
     * If the theme does not set characters, appropriate defaults
225
     * are set automatically. Please DO NOT
226
     * use &lt; &gt; &raquo; - these are confusing for blind users.
227
     */
228
    public $rarrow = null;
229
 
230
    /**
231
     * @var string Accessibility: Left arrow-like character is
232
     * used in the breadcrumb trail, course navigation menu
233
     * (previous/next activity), calendar, and search forum block.
234
     * If the theme does not set characters, appropriate defaults
235
     * are set automatically. Please DO NOT
236
     * use &lt; &gt; &raquo; - these are confusing for blind users.
237
     */
238
    public $larrow = null;
239
 
240
    /**
241
     * @var string Accessibility: Up arrow-like character is used in
242
     * the book heirarchical navigation.
243
     * If the theme does not set characters, appropriate defaults
244
     * are set automatically. Please DO NOT
245
     * use ^ - this is confusing for blind users.
246
     */
247
    public $uarrow = null;
248
 
249
    /**
250
     * @var string Accessibility: Down arrow-like character.
251
     * If the theme does not set characters, appropriate defaults
252
     * are set automatically.
253
     */
254
    public $darrow = null;
255
 
256
    /**
257
     * @var bool Some themes may want to disable ajax course editing.
258
     */
259
    public $enablecourseajax = true;
260
 
261
    /**
262
     * @var string Determines served document types
263
     *  - 'html5' the only officially supported doctype in Moodle
264
     *  - 'xhtml5' may be used in development for validation (not intended for production servers!)
265
     *  - 'xhtml' XHTML 1.0 Strict for legacy themes only
266
     */
267
    public $doctype = 'html5';
268
 
269
    /**
270
     * @var string|false requiredblocks If set to a string, will list the block types that cannot be deleted. Defaults to
271
     *                                   navigation and settings.
272
     */
273
    public $requiredblocks = false;
274
 
275
    // The Following properties are not configurable from theme config.php.
276
 
277
    /**
278
     * @var string The name of this theme. Set automatically when this theme is
279
     * loaded. This can not be set in theme config.php
280
     */
281
    public $name;
282
 
283
    /**
284
     * @var string The folder where this themes files are stored. This is set
285
     * automatically. This can not be set in theme config.php
286
     */
287
    public $dir;
288
 
289
    /**
290
     * @var stdClass Theme settings stored in config_plugins table.
291
     * This can not be set in theme config.php
292
     */
293
    public $settings = null;
294
 
295
    /**
296
     * @var bool If set to true and the theme enables the dock then  blocks will be able
297
     * to be moved to the special dock
298
     */
299
    public $enable_dock = false;
300
 
301
    /**
302
     * @var bool If set to true then this theme will not be shown in the theme selector unless
303
     * theme designer mode is turned on.
304
     */
305
    public $hidefromselector = false;
306
 
307
    /**
308
     * @var array list of YUI CSS modules to be included on each page. This may be used
309
     * to remove cssreset and use cssnormalise module instead.
310
     */
311
    public $yuicssmodules = ['cssreset', 'cssfonts', 'cssgrids', 'cssbase'];
312
 
313
    /**
314
     * An associative array of block manipulations that should be made if the user is using an rtl language.
315
     * The key is the original block region, and the value is the block region to change to.
316
     * This is used when displaying blocks for regions only.
317
     * @var array
318
     */
319
    public $blockrtlmanipulations = [];
320
 
321
    /**
322
     * @var renderer_factory Instance of the renderer_factory implementation
323
     * we are using. Implementation detail.
324
     */
325
    protected $rf = null;
326
 
327
    /**
328
     * @var array List of parent config objects.
329
     **/
330
    protected $parent_configs = [];
331
 
332
    /**
333
     * Used to determine whether we can serve SVG images or not.
334
     * @var bool
335
     */
336
    private $usesvg = null;
337
 
338
    /**
339
     * Whether in RTL mode or not.
340
     * @var bool
341
     */
342
    protected $rtlmode = false;
343
 
344
    /**
345
     * The SCSS file to compile (without .scss), located in the scss/ folder of the theme.
346
     * Or a Closure, which receives the theme_config as argument and must
347
     * return the SCSS content.
348
     * @var string|Closure
349
     */
350
    public $scss = false;
351
 
352
    /**
353
     * Local cache of the SCSS property.
354
     * @var false|array
355
     */
356
    protected $scsscache = null;
357
 
358
    /**
359
     * The name of the function to call to get the SCSS code to inject.
360
     * @var string
361
     */
362
    public $extrascsscallback = null;
363
 
364
    /**
365
     * The name of the function to call to get SCSS to prepend.
366
     * @var string
367
     */
368
    public $prescsscallback = null;
369
 
370
    /**
371
     * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
372
     * Defaults to {@see core_renderer::blocks_for_region()}
373
     * @var string
374
     */
375
    public $blockrendermethod = null;
376
 
377
    /**
378
     * Remember the results of icon remapping for the current page.
379
     * @var array
380
     */
381
    public $remapiconcache = [];
382
 
383
    /**
384
     * The name of the function to call to get precompiled CSS.
385
     * @var string
386
     */
387
    public $precompiledcsscallback = null;
388
 
389
    /**
390
     * Whether the theme uses course index.
391
     * @var bool
392
     */
393
    public $usescourseindex = false;
394
 
395
    /**
396
     * Configuration for the page activity header
397
     * @var array
398
     */
399
    public $activityheaderconfig = [];
400
 
401
    /**
402
     * For backward compatibility with old themes.
403
     * BLOCK_ADDBLOCK_POSITION_DEFAULT, BLOCK_ADDBLOCK_POSITION_FLATNAV.
404
     * @var int
405
     */
406
    public $addblockposition;
407
 
408
    /**
409
     * editor_scss file(s) provided by this theme.
410
     * @var array
411
     */
412
    public $editor_scss;
413
 
414
    /**
415
     * Name of the class extending \core\output\icon_system.
416
     * @var string
417
     */
418
    public $iconsystem;
419
 
420
    /**
421
     * Theme defines its own editing mode switch.
422
     * @var bool
423
     */
424
    public $haseditswitch = false;
425
 
426
    /**
427
     * Allows a theme to customise primary navigation by specifying the list of items to remove.
428
     * @var array
429
     */
430
    public $removedprimarynavitems = [];
431
 
432
    /**
433
     * Load the config.php file for a particular theme, and return an instance
434
     * of this class. (That is, this is a factory method.)
435
     *
436
     * @param string $themename the name of the theme.
437
     * @return theme_config an instance of this class.
438
     */
439
    public static function load($themename) {
440
        global $CFG;
441
 
442
        // Load theme settings from db.
443
        try {
444
            $settings = get_config('theme_' . $themename);
445
        } catch (dml_exception $e) {
446
            // Most probably moodle tables not created yet.
447
            $settings = new stdClass();
448
        }
449
 
450
        if ($config = self::find_theme_config($themename, $settings)) {
451
            return new self($config);
452
        } else if ($themename == self::DEFAULT_THEME) {
453
            throw new coding_exception('Default theme ' . self::DEFAULT_THEME . ' not available or broken!');
454
        } else if ($config = self::find_theme_config($CFG->theme, $settings)) {
455
            debugging('This page should be using theme ' . $themename .
456
                    ' which cannot be initialised. Falling back to the site theme ' . $CFG->theme, DEBUG_NORMAL);
457
            return new self($config);
458
        } else {
459
            // Bad luck, the requested theme has some problems - admin see details in theme config.
460
            debugging('This page should be using theme ' . $themename .
461
                    ' which cannot be initialised. Nor can the site theme ' . $CFG->theme .
462
                    '. Falling back to ' . self::DEFAULT_THEME, DEBUG_NORMAL);
463
            return new self(self::find_theme_config(self::DEFAULT_THEME, $settings));
464
        }
465
    }
466
 
467
    /**
468
     * Theme diagnostic code. It is very problematic to send debug output
469
     * to the actual CSS file, instead this functions is supposed to
470
     * diagnose given theme and highlights all potential problems.
471
     * This information should be available from the theme selection page
472
     * or some other debug page for theme designers.
473
     *
474
     * @param string $themename
475
     * @return array description of problems
476
     */
477
    public static function diagnose($themename) {
478
        // TODO: MDL-21108.
479
        return [];
480
    }
481
 
482
    /**
483
     * Private constructor, can be called only from the factory method.
484
     * @param stdClass $config
485
     */
486
    private function __construct($config) {
487
        global $CFG; // Needed for included lib.php files.
488
 
489
        $this->settings = $config->settings;
490
        $this->name     = $config->name;
491
        $this->dir      = $config->dir;
492
 
493
        if ($this->name != self::DEFAULT_THEME) {
494
            $baseconfig = self::find_theme_config(self::DEFAULT_THEME, $this->settings);
495
        } else {
496
            $baseconfig = $config;
497
        }
498
 
499
        // Ensure that each of the configurable properties defined below are also defined at the class level.
500
        $configurable = [
501
            'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'usefallback',
502
            'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
503
            'layouts', 'enablecourseajax', 'requiredblocks',
504
            'rendererfactory', 'csspostprocess', 'editor_sheets', 'editor_scss', 'rarrow', 'larrow', 'uarrow', 'darrow',
505
            'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations', 'blockrendermethod',
506
            'scss', 'extrascsscallback', 'prescsscallback', 'csstreepostprocessor', 'addblockposition',
507
            'iconsystem', 'precompiledcsscallback', 'haseditswitch', 'usescourseindex', 'activityheaderconfig',
508
            'removedprimarynavitems',
509
        ];
510
 
511
        foreach ($config as $key => $value) {
512
            if (in_array($key, $configurable)) {
513
                $this->$key = $value;
514
            }
515
        }
516
 
517
        // Verify all parents and load configs and renderers.
518
        foreach ($this->parents as $parent) {
519
            if (!$parent_config = self::find_theme_config($parent, $this->settings)) {
520
                // This is not good - better exclude faulty parents.
521
                continue;
522
            }
523
            $libfile = $parent_config->dir . '/lib.php';
524
            if (is_readable($libfile)) {
525
                // Theme may store various function here.
526
                include_once($libfile);
527
            }
528
            $renderersfile = $parent_config->dir . '/renderers.php';
529
            if (is_readable($renderersfile)) {
530
                // May contain core and plugin renderers and renderer factory.
531
                include_once($renderersfile);
532
            }
533
            $this->parent_configs[$parent] = $parent_config;
534
        }
535
        $libfile = $this->dir . '/lib.php';
536
        if (is_readable($libfile)) {
537
            // Theme may store various function here.
538
            include_once($libfile);
539
        }
540
        $rendererfile = $this->dir . '/renderers.php';
541
        if (is_readable($rendererfile)) {
542
            // May contain core and plugin renderers and renderer factory.
543
            include_once($rendererfile);
544
        } else {
545
            // Check if renderers.php file is missnamed renderer.php.
546
            if (is_readable($this->dir . '/renderer.php')) {
547
                debugging('Developer hint: ' . $this->dir . '/renderer.php should be renamed to ' . $this->dir . "/renderers.php.
548
                    See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
549
            }
550
        }
551
 
552
        // Cascade all layouts properly.
553
        foreach ($baseconfig->layouts as $layout => $value) {
554
            if (!isset($this->layouts[$layout])) {
555
                foreach ($this->parent_configs as $parent_config) {
556
                    if (isset($parent_config->layouts[$layout])) {
557
                        $this->layouts[$layout] = $parent_config->layouts[$layout];
558
                        continue 2;
559
                    }
560
                }
561
                $this->layouts[$layout] = $value;
562
            }
563
        }
564
 
565
        // Fix arrows if needed.
566
        $this->check_theme_arrows();
567
    }
568
 
569
    /**
570
     * Let the theme initialise the page object (usually $PAGE).
571
     *
572
     * This may be used for example to request jQuery in add-ons.
573
     *
574
     * @param moodle_page $page
575
     */
576
    public function init_page(moodle_page $page) {
577
        $themeinitfunction = 'theme_' . $this->name . '_page_init';
578
        if (function_exists($themeinitfunction)) {
579
            $themeinitfunction($page);
580
        }
581
    }
582
 
583
    /**
584
     * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow, $THEME->darrow have been set (theme/-/config.php).
585
     * If not it applies sensible defaults.
586
     *
587
     * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
588
     * search forum block, etc. Important: these are 'silent' in a screen-reader
589
     * (unlike &gt; &raquo;), and must be accompanied by text.
590
     */
591
    private function check_theme_arrows() {
592
        if (!isset($this->rarrow) && !isset($this->larrow)) {
593
            // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
594
            // Also OK in Win 9x/2K/IE 5.x.
595
            $this->rarrow = '&#x25BA;';
596
            $this->larrow = '&#x25C4;';
597
            $this->uarrow = '&#x25B2;';
598
            $this->darrow = '&#x25BC;';
599
            if (empty($_SERVER['HTTP_USER_AGENT'])) {
600
                $uagent = '';
601
            } else {
602
                $uagent = $_SERVER['HTTP_USER_AGENT'];
603
            }
604
            if (
605
                false !== strpos($uagent, 'Opera')
606
                || false !== strpos($uagent, 'Mac')
607
            ) {
608
                // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
609
                // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
610
                $this->rarrow = '&#x25B6;&#xFE0E;';
611
                $this->larrow = '&#x25C0;&#xFE0E;';
612
            } else if (
613
                (false !== strpos($uagent, 'Konqueror'))
614
                || (false !== strpos($uagent, 'Android'))
615
            ) {
616
                // The fonts on Android don't include the characters required for this to work as expected.
617
                // So we use the same ones Konqueror uses.
618
                $this->rarrow = '&rarr;';
619
                $this->larrow = '&larr;';
620
                $this->uarrow = '&uarr;';
621
                $this->darrow = '&darr;';
622
            } else if (
623
                isset($_SERVER['HTTP_ACCEPT_CHARSET'])
624
                && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')
625
            ) {
626
                // Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.
627
                // To be safe, non-Unicode browsers!
628
                $this->rarrow = '&gt;';
629
                $this->larrow = '&lt;';
630
                $this->uarrow = '^';
631
                $this->darrow = 'v';
632
            }
633
 
634
            // RTL support - in RTL languages, swap r and l arrows.
635
            if (right_to_left()) {
636
                $t = $this->rarrow;
637
                $this->rarrow = $this->larrow;
638
                $this->larrow = $t;
639
            }
640
        }
641
    }
642
 
643
    /**
644
     * Returns output renderer prefixes, these are used when looking
645
     * for the overridden renderers in themes.
646
     *
647
     * @return array
648
     */
649
    public function renderer_prefixes() {
650
        global $CFG; // Just in case the included files need it.
651
 
652
        $prefixes = ['theme_' . $this->name];
653
 
654
        foreach ($this->parent_configs as $parent) {
655
            $prefixes[] = 'theme_' . $parent->name;
656
        }
657
 
658
        return $prefixes;
659
    }
660
 
661
    /**
662
     * Returns the stylesheet URL of this editor content
663
     *
664
     * @param bool $encoded false means use & and true use &amp; in URLs
665
     * @return moodle_url
666
     */
667
    public function editor_css_url($encoded = true) {
668
        global $CFG;
669
        $rev = theme_get_revision();
670
        $type = 'editor';
671
        if (right_to_left()) {
672
            $type .= '-rtl';
673
        }
674
 
675
        if ($rev > -1) {
676
            $themesubrevision = theme_get_sub_revision_for_theme($this->name);
677
 
678
            // Provide the sub revision to allow us to invalidate cached theme CSS
679
            // on a per theme basis, rather than globally.
680
            if ($themesubrevision && $themesubrevision > 0) {
681
                $rev .= "_{$themesubrevision}";
682
            }
683
 
684
            $url = new moodle_url("/theme/styles.php");
685
            if (!empty($CFG->slasharguments)) {
686
                $url->set_slashargument("/{$this->name}/{$rev}/{$type}", 'noparam', true);
687
            } else {
688
                $url->params([
689
                    'theme' => $this->name,
690
                    'rev' => $rev,
691
                    'type' => $type,
692
                ]);
693
            }
694
        } else {
695
            $url = new moodle_url('/theme/styles_debug.php', [
696
                'theme' => $this->name,
697
                'type' => $type,
698
            ]);
699
        }
700
        return $url;
701
    }
702
 
703
    /**
704
     * Returns the content of the CSS to be used in editor content
705
     *
706
     * @return array
707
     */
708
    public function editor_css_files() {
709
        $files = [];
710
 
711
        // First editor plugins.
712
        $plugins = core_component::get_plugin_list('editor');
713
        foreach ($plugins as $plugin => $fulldir) {
714
            $sheetfile = "$fulldir/editor_styles.css";
715
            if (is_readable($sheetfile)) {
716
                $files['plugin_' . $plugin] = $sheetfile;
717
            }
718
 
719
            $subplugintypes = core_component::get_subplugins("editor_{$plugin}") ?? [];
720
            // Fetch sheets for any editor subplugins.
721
            foreach ($subplugintypes as $plugintype => $subplugins) {
722
                foreach ($subplugins as $subplugin) {
723
                    $plugindir = core_component::get_plugin_directory($plugintype, $subplugin);
724
                    $sheetfile = "{$plugindir}/editor_styles.css";
725
                    if (is_readable($sheetfile)) {
726
                        $files["{$plugintype}_{$subplugin}"] = $sheetfile;
727
                    }
728
                }
729
            }
730
        }
731
 
732
        // Then parent themes - base first, the immediate parent last.
733
        foreach (array_reverse($this->parent_configs) as $parent_config) {
734
            if (empty($parent_config->editor_sheets)) {
735
                continue;
736
            }
737
            foreach ($parent_config->editor_sheets as $sheet) {
738
                $sheetfile = "$parent_config->dir/style/$sheet.css";
739
                if (is_readable($sheetfile)) {
740
                    $files['parent_' . $parent_config->name . '_' . $sheet] = $sheetfile;
741
                }
742
            }
743
        }
744
        // Finally this theme.
745
        if (!empty($this->editor_sheets)) {
746
            foreach ($this->editor_sheets as $sheet) {
747
                $sheetfile = "$this->dir/style/$sheet.css";
748
                if (is_readable($sheetfile)) {
749
                    $files['theme_' . $sheet] = $sheetfile;
750
                }
751
            }
752
        }
753
 
754
        return $files;
755
    }
756
 
757
    /**
758
     * Compiles and returns the content of the SCSS to be used in editor content
759
     *
760
     * @return string Compiled CSS from the editor SCSS
761
     */
762
    public function editor_scss_to_css() {
763
        $css = '';
764
        $dir = $this->dir;
765
        $filenames = [];
766
 
767
        // Use editor_scss file(s) provided by this theme if set.
768
        if (!empty($this->editor_scss)) {
769
            $filenames = $this->editor_scss;
770
        } else {
771
            // If no editor_scss set, move up theme hierarchy until one is found (if at all).
772
            // This is so child themes only need to set editor_scss if an override is required.
773
            foreach (array_reverse($this->parent_configs) as $parentconfig) {
774
                if (!empty($parentconfig->editor_scss)) {
775
                    $dir = $parentconfig->dir;
776
                    $filenames = $parentconfig->editor_scss;
777
 
778
                    // Config found, stop looking.
779
                    break;
780
                }
781
            }
782
        }
783
 
784
        if (!empty($filenames)) {
785
            $compiler = new core_scss();
786
 
787
            foreach ($filenames as $filename) {
788
                $compiler->set_file("{$dir}/scss/{$filename}.scss");
789
 
790
                try {
791
                    $css .= $compiler->to_css();
792
                } catch (\Exception $e) {
793
                    debugging('Error while compiling editor SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
794
                }
795
            }
796
        }
797
 
798
        return $css;
799
    }
800
 
801
    /**
802
     * Get the stylesheet URL of this theme.
803
     *
804
     * @param moodle_page $page Not used... deprecated?
805
     * @return moodle_url[]
806
     */
807
    public function css_urls(moodle_page $page) {
808
        global $CFG;
809
 
810
        $rev = theme_get_revision();
811
 
812
        $urls = [];
813
 
814
        $svg = $this->use_svg_icons();
815
        $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
816
 
817
        if ($rev > -1) {
818
            $filename = right_to_left() ? 'all-rtl' : 'all';
819
            $url = new moodle_url("/theme/styles.php");
820
            $themesubrevision = theme_get_sub_revision_for_theme($this->name);
821
 
822
            // Provide the sub revision to allow us to invalidate cached theme CSS
823
            // on a per theme basis, rather than globally.
824
            if ($themesubrevision && $themesubrevision > 0) {
825
                $rev .= "_{$themesubrevision}";
826
            }
827
 
828
            if (!empty($CFG->slasharguments)) {
829
                $slashargs = '';
830
                if (!$svg) {
831
                    // We add a simple /_s to the start of the path.
832
                    // The underscore is used to ensure that it isn't a valid theme name.
833
                    $slashargs .= '/_s' . $slashargs;
834
                }
835
                $slashargs .= '/' . $this->name . '/' . $rev . '/' . $filename;
836
                if ($separate) {
837
                    $slashargs .= '/chunk0';
838
                }
839
                $url->set_slashargument($slashargs, 'noparam', true);
840
            } else {
841
                $params = ['theme' => $this->name, 'rev' => $rev, 'type' => $filename];
842
                if (!$svg) {
843
                    // We add an SVG param so that we know not to serve SVG images.
844
                    // We do this because all modern browsers support SVG and this param will one day be removed.
845
                    $params['svg'] = '0';
846
                }
847
                if ($separate) {
848
                    $params['chunk'] = '0';
849
                }
850
                $url->params($params);
851
            }
852
            $urls[] = $url;
853
        } else {
854
            $baseurl = new moodle_url('/theme/styles_debug.php');
855
 
856
            $css = $this->get_css_files(true);
857
            if (!$svg) {
858
                // We add an SVG param so that we know not to serve SVG images.
859
                // We do this because all modern browsers support SVG and this param will one day be removed.
860
                $baseurl->param('svg', '0');
861
            }
862
            if (right_to_left()) {
863
                $baseurl->param('rtl', 1);
864
            }
865
            if ($separate) {
866
                // We might need to chunk long files.
867
                $baseurl->param('chunk', '0');
868
            }
869
            if (core_useragent::is_ie()) {
870
                // Lalala, IE does not allow more than 31 linked CSS files from main document.
871
                $urls[] = new moodle_url($baseurl, ['theme' => $this->name, 'type' => 'ie', 'subtype' => 'plugins']);
872
                foreach ($css['parents'] as $parent => $sheets) {
873
                    // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
874
                    $urls[] = new moodle_url($baseurl, [
875
                        'theme' => $this->name,
876
                        'type' => 'ie',
877
                        'subtype' => 'parents',
878
                        'sheet' => $parent,
879
                    ]);
880
                }
881
                if ($this->get_scss_property()) {
882
                    // No need to define the type as IE here.
883
                    $urls[] = new moodle_url($baseurl, ['theme' => $this->name, 'type' => 'scss']);
884
                }
885
                $urls[] = new moodle_url($baseurl, ['theme' => $this->name, 'type' => 'ie', 'subtype' => 'theme']);
886
            } else {
887
                foreach ($css['plugins'] as $plugin => $unused) {
888
                    $urls[] = new moodle_url($baseurl, ['theme' => $this->name, 'type' => 'plugin', 'subtype' => $plugin]);
889
                }
890
                foreach ($css['parents'] as $parent => $sheets) {
891
                    foreach ($sheets as $sheet => $unused2) {
892
                        $urls[] = new moodle_url($baseurl, [
893
                            'theme' => $this->name,
894
                            'type' => 'parent',
895
                            'subtype' => $parent,
896
                            'sheet' => $sheet,
897
                        ]);
898
                    }
899
                }
900
                foreach ($css['theme'] as $sheet => $filename) {
901
                    if ($sheet === self::SCSS_KEY) {
902
                        // This is the theme SCSS file.
903
                        $urls[] = new moodle_url($baseurl, ['theme' => $this->name, 'type' => 'scss']);
904
                    } else {
905
                        // Sheet first in order to make long urls easier to read.
906
                        $urls[] = new moodle_url($baseurl, ['sheet' => $sheet, 'theme' => $this->name, 'type' => 'theme']);
907
                    }
908
                }
909
            }
910
        }
911
 
912
        // Allow themes to change the css url to something like theme/mytheme/mycss.php.
913
        component_callback('theme_' . $this->name, 'alter_css_urls', [&$urls]);
914
        return $urls;
915
    }
916
 
917
    /**
918
     * Get the whole css stylesheet for production mode.
919
     *
920
     * NOTE: this method is not expected to be used from any addons.
921
     *
922
     * @return string CSS markup compressed
923
     */
924
    public function get_css_content() {
925
 
926
        $csscontent = '';
927
        foreach ($this->get_css_files(false) as $type => $value) {
928
            foreach ($value as $identifier => $val) {
929
                if (is_array($val)) {
930
                    foreach ($val as $v) {
931
                        $csscontent .= file_get_contents($v) . "\n";
932
                    }
933
                } else {
934
                    if ($type === 'theme' && $identifier === self::SCSS_KEY) {
935
                        // We need the content from SCSS because this is the SCSS file from the theme.
936
                        if ($compiled = $this->get_css_content_from_scss(false)) {
937
                            $csscontent .= $compiled;
938
                        } else {
939
                            // The compiler failed so default back to any precompiled css that might
940
                            // exist.
941
                            $csscontent .= $this->get_precompiled_css_content();
942
                        }
943
                    } else {
944
                        $csscontent .= file_get_contents($val) . "\n";
945
                    }
946
                }
947
            }
948
        }
949
        $csscontent = $this->post_process($csscontent);
950
        $csscontent = core_minify::css($csscontent);
951
 
952
        return $csscontent;
953
    }
954
    /**
955
     * Set post processed CSS content cache.
956
     *
957
     * @param string $csscontent The post processed CSS content.
958
     * @return bool True if the content was successfully cached.
959
     */
960
    public function set_css_content_cache($csscontent) {
961
 
962
        $cache = cache::make('core', 'postprocessedcss');
963
        $key = $this->get_css_cache_key();
964
 
965
        return $cache->set($key, $csscontent);
966
    }
967
 
968
    /**
969
     * Return whether the post processed CSS content has been cached.
970
     *
971
     * @return bool Whether the post-processed CSS is available in the cache.
972
     */
973
    public function has_css_cached_content() {
974
 
975
        $key = $this->get_css_cache_key();
976
        $cache = cache::make('core', 'postprocessedcss');
977
 
978
        return $cache->has($key);
979
    }
980
 
981
    /**
982
     * Return cached post processed CSS content.
983
     *
984
     * @return bool|string The cached css content or false if not found.
985
     */
986
    public function get_css_cached_content() {
987
 
988
        $key = $this->get_css_cache_key();
989
        $cache = cache::make('core', 'postprocessedcss');
990
 
991
        return $cache->get($key);
992
    }
993
 
994
    /**
995
     * Generate the css content cache key.
996
     *
997
     * @return string The post processed css cache key.
998
     */
999
    public function get_css_cache_key() {
1000
        $nosvg = (!$this->use_svg_icons()) ? 'nosvg_' : '';
1001
        $rtlmode = ($this->rtlmode == true) ? 'rtl' : 'ltr';
1002
 
1003
        return $nosvg . $this->name . '_' . $rtlmode;
1004
    }
1005
 
1006
    /**
1007
     * Get the theme designer css markup,
1008
     * the parameters are coming from css_urls().
1009
     *
1010
     * NOTE: this method is not expected to be used from any addons.
1011
     *
1012
     * @param string $type
1013
     * @param string $subtype
1014
     * @param string $sheet
1015
     * @return string CSS markup
1016
     */
1017
    public function get_css_content_debug($type, $subtype, $sheet) {
1018
        if ($type === 'scss') {
1019
            // The SCSS file of the theme is requested.
1020
            $csscontent = $this->get_css_content_from_scss(true);
1021
            if ($csscontent !== false) {
1022
                return $this->post_process($csscontent);
1023
            }
1024
            return '';
1025
        }
1026
 
1027
        $cssfiles = [];
1028
        $css = $this->get_css_files(true);
1029
 
1030
        if ($type === 'ie') {
1031
            // IE is a sloppy browser with weird limits, sorry.
1032
            if ($subtype === 'plugins') {
1033
                $cssfiles = $css['plugins'];
1034
            } else if ($subtype === 'parents') {
1035
                if (empty($sheet)) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf
1036
                    // Do not bother with the empty parent here.
1037
                } else {
1038
                    // Build up the CSS for that parent so we can serve it as one file.
1039
                    foreach ($css[$subtype][$sheet] as $parent => $css) {
1040
                        $cssfiles[] = $css;
1041
                    }
1042
                }
1043
            } else if ($subtype === 'theme') {
1044
                $cssfiles = $css['theme'];
1045
                foreach ($cssfiles as $key => $value) {
1046
                    if (in_array($key, [self::SCSS_KEY])) {
1047
                        // Remove the SCSS file from the theme CSS files.
1048
                        // The SCSS files use the type 'scss', not 'ie'.
1049
                        unset($cssfiles[$key]);
1050
                    }
1051
                }
1052
            }
1053
        } else if ($type === 'plugin') {
1054
            if (isset($css['plugins'][$subtype])) {
1055
                $cssfiles[] = $css['plugins'][$subtype];
1056
            }
1057
        } else if ($type === 'parent') {
1058
            if (isset($css['parents'][$subtype][$sheet])) {
1059
                $cssfiles[] = $css['parents'][$subtype][$sheet];
1060
            }
1061
        } else if ($type === 'theme') {
1062
            if (isset($css['theme'][$sheet])) {
1063
                $cssfiles[] = $css['theme'][$sheet];
1064
            }
1065
        }
1066
 
1067
        $csscontent = '';
1068
        foreach ($cssfiles as $file) {
1069
            $contents = file_get_contents($file);
1070
            $contents = $this->post_process($contents);
1071
            $comment = "/** Path: $type $subtype $sheet.' **/\n";
1072
            $stats = '';
1073
            $csscontent .= $comment . $stats . $contents . "\n\n";
1074
        }
1075
 
1076
        return $csscontent;
1077
    }
1078
 
1079
    /**
1080
     * Get the whole css stylesheet for editor iframe.
1081
     *
1082
     * NOTE: this method is not expected to be used from any addons.
1083
     *
1084
     * @return string CSS markup
1085
     */
1086
    public function get_css_content_editor() {
1087
        $css = '';
1088
        $cssfiles = $this->editor_css_files();
1089
 
1090
        // If editor has static CSS, include it.
1091
        foreach ($cssfiles as $file) {
1092
            $css .= file_get_contents($file) . "\n";
1093
        }
1094
 
1095
        // If editor has SCSS, compile and include it.
1096
        if (($convertedscss = $this->editor_scss_to_css())) {
1097
            $css .= $convertedscss;
1098
        }
1099
 
1100
        $output = $this->post_process($css);
1101
 
1102
        return $output;
1103
    }
1104
 
1105
    /**
1106
     * Returns an array of organised CSS files required for this output.
1107
     *
1108
     * @param bool $themedesigner
1109
     * @return array nested array of file paths
1110
     */
1111
    protected function get_css_files($themedesigner) {
1112
        global $CFG;
1113
 
1114
        $cache = null;
1115
        $cachekey = 'cssfiles';
1116
        if ($themedesigner) {
1117
            require_once($CFG->dirroot . '/lib/csslib.php');
1118
            // We need some kind of caching here because otherwise the page navigation becomes
1119
            // way too slow in theme designer mode. Feel free to create full cache definition later...
1120
            $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', ['theme' => $this->name]);
1121
            if ($files = $cache->get($cachekey)) {
1122
                if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
1123
                    unset($files['created']);
1124
                    return $files;
1125
                }
1126
            }
1127
        }
1128
 
1129
        $cssfiles = ['plugins' => [], 'parents' => [], 'theme' => []];
1130
 
1131
        // Get all plugin sheets.
1132
        $excludes = $this->resolve_excludes('plugins_exclude_sheets');
1133
        if ($excludes !== true) {
1134
            foreach (core_component::get_plugin_types() as $type => $unused) {
1135
                if ($type === 'theme' || (!empty($excludes[$type]) && $excludes[$type] === true)) {
1136
                    continue;
1137
                }
1138
                $plugins = core_component::get_plugin_list($type);
1139
                foreach ($plugins as $plugin => $fulldir) {
1140
                    if (
1141
                        !empty($excludes[$type])
1142
                        && is_array($excludes[$type])
1143
                        && in_array($plugin, $excludes[$type])
1144
                    ) {
1145
                        continue;
1146
                    }
1147
 
1148
                    // Get the CSS from the plugin.
1149
                    $sheetfile = "$fulldir/styles.css";
1150
                    if (is_readable($sheetfile)) {
1151
                        $cssfiles['plugins'][$type . '_' . $plugin] = $sheetfile;
1152
                    }
1153
 
1154
                    // Create a list of candidate sheets from parents (direct parent last) and current theme.
1155
                    $candidates = [];
1156
                    foreach (array_reverse($this->parent_configs) as $parent_config) {
1157
                        $candidates[] = $parent_config->name;
1158
                    }
1159
                    $candidates[] = $this->name;
1160
 
1161
                    // Add the sheets found.
1162
                    foreach ($candidates as $candidate) {
1163
                        $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1164
                        if (is_readable($sheetthemefile)) {
1165
                            $cssfiles['plugins'][$type . '_' . $plugin . '_' . $candidate] = $sheetthemefile;
1166
                        }
1167
                    }
1168
                }
1169
            }
1170
        }
1171
 
1172
        // Find out wanted parent sheets.
1173
        $excludes = $this->resolve_excludes('parents_exclude_sheets');
1174
        if ($excludes !== true) {
1175
            foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1176
                $parent = $parent_config->name;
1177
                if (empty($parent_config->sheets) || (!empty($excludes[$parent]) && $excludes[$parent] === true)) {
1178
                    continue;
1179
                }
1180
                foreach ($parent_config->sheets as $sheet) {
1181
                    if (
1182
                        !empty($excludes[$parent]) && is_array($excludes[$parent])
1183
                            && in_array($sheet, $excludes[$parent])
1184
                    ) {
1185
                        continue;
1186
                    }
1187
 
1188
                    // We never refer to the parent LESS files.
1189
                    $sheetfile = "$parent_config->dir/style/$sheet.css";
1190
                    if (is_readable($sheetfile)) {
1191
                        $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1192
                    }
1193
                }
1194
            }
1195
        }
1196
 
1197
        // Current theme sheets.
1198
        // We first add the SCSS file because we want the CSS ones to
1199
        // be included after the SCSS code.
1200
        if ($this->get_scss_property()) {
1201
            $cssfiles['theme'][self::SCSS_KEY] = true;
1202
        }
1203
        if (is_array($this->sheets)) {
1204
            foreach ($this->sheets as $sheet) {
1205
                $sheetfile = "$this->dir/style/$sheet.css";
1206
                if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1207
                    $cssfiles['theme'][$sheet] = $sheetfile;
1208
                }
1209
            }
1210
        }
1211
 
1212
        if ($cache) {
1213
            $files = $cssfiles;
1214
            $files['created'] = time();
1215
            $cache->set($cachekey, $files);
1216
        }
1217
        return $cssfiles;
1218
    }
1219
 
1220
    /**
1221
     * Return the CSS content generated from the SCSS file.
1222
     *
1223
     * @param bool $themedesigner True if theme designer is enabled.
1224
     * @return bool|string Return false when the compilation failed. Else the compiled string.
1225
     */
1226
    protected function get_css_content_from_scss($themedesigner) {
1227
        global $CFG;
1228
 
1229
        [$paths, $scss] = $this->get_scss_property();
1230
        if (!$scss) {
1231
            throw new coding_exception('The theme did not define a SCSS file, or it is not readable.');
1232
        }
1233
 
1234
        // We might need more memory/time to do this, so let's play safe.
1235
        raise_memory_limit(MEMORY_EXTRA);
1236
        core_php_time_limit::raise(300);
1237
 
1238
        // TODO: MDL-62757 When changing anything in this method please do not forget to check
1239
        // if the validate() method in class admin_setting_configthemepreset needs updating too.
1240
 
1241
        $cachedir = make_localcache_directory('scsscache-' . $this->name, false);
1242
        $cacheoptions = [];
1243
        if ($themedesigner) {
1244
            $cacheoptions = [
1245
                  'cacheDir' => $cachedir,
1246
                  'prefix' => 'scssphp_',
1247
                  'forceRefresh' => false,
1248
            ];
1249
        } else {
1250
            if (file_exists($cachedir)) {
1251
                remove_dir($cachedir);
1252
            }
1253
        }
1254
 
1255
        // Set-up the compiler.
1256
        $compiler = new core_scss($cacheoptions);
1257
 
1258
        if ($this->supports_source_maps($themedesigner)) {
1259
            // Enable source maps.
1260
            $compiler->setSourceMapOptions([
1261
                'sourceMapBasepath' => str_replace('\\', '/', $CFG->dirroot),
1262
                'sourceMapRootpath' => $CFG->wwwroot . '/',
1263
            ]);
1264
            $compiler->setSourceMap($compiler::SOURCE_MAP_INLINE);
1265
        }
1266
 
1267
        $compiler->prepend_raw_scss($this->get_pre_scss_code());
1268
        if (is_string($scss)) {
1269
            $compiler->set_file($scss);
1270
        } else {
1271
            $compiler->append_raw_scss($scss($this));
1272
            $compiler->setImportPaths($paths);
1273
        }
1274
        $compiler->append_raw_scss($this->get_extra_scss_code());
1275
 
1276
        try {
1277
            // Compile!
1278
            $compiled = $compiler->to_css();
1279
        } catch (\Exception $e) {
1280
            $compiled = false;
1281
            debugging('Error while compiling SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
1282
        }
1283
 
1284
        // Try to save memory.
1285
        $compiler = null;
1286
        unset($compiler);
1287
 
1288
        return $compiled;
1289
    }
1290
 
1291
    /**
1292
     * Return the precompiled CSS if the precompiledcsscallback exists.
1293
     *
1294
     * @return string Return compiled css.
1295
     */
1296
    public function get_precompiled_css_content() {
1297
        $configs = array_reverse($this->parent_configs) + [$this];
1298
        $css = '';
1299
 
1300
        foreach ($configs as $config) {
1301
            if (isset($config->precompiledcsscallback)) {
1302
                $function = $config->precompiledcsscallback;
1303
                if (function_exists($function)) {
1304
                    $css .= $function($this);
1305
                }
1306
            }
1307
        }
1308
        return $css;
1309
    }
1310
 
1311
    /**
1312
     * Get the icon system to use.
1313
     *
1314
     * @return string
1315
     */
1316
    public function get_icon_system() {
1317
 
1318
        // Getting all the candidate functions.
1319
        $system = false;
1320
        if (isset($this->iconsystem) && icon_system::is_valid_system($this->iconsystem)) {
1321
            return $this->iconsystem;
1322
        }
1323
        foreach ($this->parent_configs as $parent_config) {
1324
            if (isset($parent_config->iconsystem) && icon_system::is_valid_system($parent_config->iconsystem)) {
1325
                return $parent_config->iconsystem;
1326
            }
1327
        }
1328
        return icon_system::STANDARD;
1329
    }
1330
 
1331
    /**
1332
     * Return extra SCSS code to add when compiling.
1333
     *
1334
     * This is intended to be used by themes to inject some SCSS code
1335
     * before it gets compiled. If you want to inject variables you
1336
     * should use {@see self::get_scss_variables()}.
1337
     *
1338
     * @return string The SCSS code to inject.
1339
     */
1340
    public function get_extra_scss_code() {
1341
        $content = '';
1342
 
1343
        // Getting all the candidate functions.
1344
        $candidates = [];
1345
        foreach (array_reverse($this->parent_configs) as $parent_config) {
1346
            if (!isset($parent_config->extrascsscallback)) {
1347
                continue;
1348
            }
1349
            $candidates[] = $parent_config->extrascsscallback;
1350
        }
1351
 
1352
        if (isset($this->extrascsscallback)) {
1353
            $candidates[] = $this->extrascsscallback;
1354
        }
1355
 
1356
        // Calling the functions.
1357
        foreach ($candidates as $function) {
1358
            if (function_exists($function)) {
1359
                $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n";
1360
            }
1361
        }
1362
 
1363
        return $content;
1364
    }
1365
 
1366
    /**
1367
     * SCSS code to prepend when compiling.
1368
     *
1369
     * This is intended to be used by themes to inject SCSS code before it gets compiled.
1370
     *
1371
     * @return string The SCSS code to inject.
1372
     */
1373
    public function get_pre_scss_code() {
1374
        $content = '';
1375
 
1376
        // Getting all the candidate functions.
1377
        $candidates = [];
1378
        foreach (array_reverse($this->parent_configs) as $parent_config) {
1379
            if (!isset($parent_config->prescsscallback)) {
1380
                continue;
1381
            }
1382
            $candidates[] = $parent_config->prescsscallback;
1383
        }
1384
 
1385
        if (isset($this->prescsscallback)) {
1386
            $candidates[] = $this->prescsscallback;
1387
        }
1388
 
1389
        // Calling the functions.
1390
        foreach ($candidates as $function) {
1391
            if (function_exists($function)) {
1392
                $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n";
1393
            }
1394
        }
1395
 
1396
        return $content;
1397
    }
1398
 
1399
    /**
1400
     * Get the SCSS property.
1401
     *
1402
     * This resolves whether a SCSS file (or content) has to be used when generating
1403
     * the stylesheet for the theme. It will look at parents themes and check the
1404
     * SCSS properties there.
1405
     *
1406
     * @return array|false False when SCSS is not used.
1407
     *         An array with the import paths, and the path to the SCSS file or Closure as second.
1408
     */
1409
    public function get_scss_property() {
1410
        if ($this->scsscache === null) {
1411
            $configs = [$this] + $this->parent_configs;
1412
            $scss = null;
1413
 
1414
            foreach ($configs as $config) {
1415
                $path = "{$config->dir}/scss";
1416
 
1417
                // We collect the SCSS property until we've found one.
1418
                if (empty($scss) && !empty($config->scss)) {
1419
                    $candidate = is_string($config->scss) ? "{$path}/{$config->scss}.scss" : $config->scss;
1420
                    if ($candidate instanceof \Closure) {
1421
                        $scss = $candidate;
1422
                    } else if (is_string($candidate) && is_readable($candidate)) {
1423
                        $scss = $candidate;
1424
                    }
1425
                }
1426
 
1427
                // We collect the import paths once we've found a SCSS property.
1428
                if ($scss && is_dir($path)) {
1429
                    $paths[] = $path;
1430
                }
1431
            }
1432
 
1433
            $this->scsscache = $scss !== null ? [$paths, $scss] : false;
1434
        }
1435
 
1436
        return $this->scsscache;
1437
    }
1438
 
1439
    /**
1440
     * Generate a URL to the file that serves theme JavaScript files.
1441
     *
1442
     * If we determine that the theme has no relevant files, then we return
1443
     * early with a null value.
1444
     *
1445
     * @param bool $inhead true means head url, false means footer
1446
     * @return moodle_url|null
1447
     */
1448
    public function javascript_url($inhead) {
1449
        global $CFG;
1450
 
1451
        $rev = theme_get_revision();
1452
        $params = ['theme' => $this->name, 'rev' => $rev];
1453
        $params['type'] = $inhead ? 'head' : 'footer';
1454
 
1455
        // Return early if there are no files to serve.
1456
        if (count($this->javascript_files($params['type'])) === 0) {
1457
            return null;
1458
        }
1459
 
1460
        if (!empty($CFG->slasharguments) && $rev > 0) {
1461
            $url = new moodle_url("/theme/javascript.php");
1462
            $url->set_slashargument('/' . $this->name . '/' . $rev . '/' . $params['type'], 'noparam', true);
1463
            return $url;
1464
        } else {
1465
            return new moodle_url('/theme/javascript.php', $params);
1466
        }
1467
    }
1468
 
1469
    /**
1470
     * Get the URL's for the JavaScript files used by this theme.
1471
     * They won't be served directly, instead they'll be mediated through
1472
     * theme/javascript.php.
1473
     *
1474
     * @param string $type Either javascripts_footer, or javascripts
1475
     * @return array
1476
     */
1477
    public function javascript_files($type) {
1478
        if ($type === 'footer') {
1479
            $type = 'javascripts_footer';
1480
        } else {
1481
            $type = 'javascripts';
1482
        }
1483
 
1484
        $js = [];
1485
        // Find out wanted parent javascripts.
1486
        $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1487
        if ($excludes !== true) {
1488
            foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1489
                $parent = $parent_config->name;
1490
                if (empty($parent_config->$type)) {
1491
                    continue;
1492
                }
1493
                if (!empty($excludes[$parent]) && $excludes[$parent] === true) {
1494
                    continue;
1495
                }
1496
                foreach ($parent_config->$type as $javascript) {
1497
                    if (
1498
                        !empty($excludes[$parent])
1499
                        && is_array($excludes[$parent])
1500
                        && in_array($javascript, $excludes[$parent])
1501
                    ) {
1502
                        continue;
1503
                    }
1504
                    $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1505
                    if (is_readable($javascriptfile)) {
1506
                        $js[] = $javascriptfile;
1507
                    }
1508
                }
1509
            }
1510
        }
1511
 
1512
        // Current theme javascripts.
1513
        if (is_array($this->$type)) {
1514
            foreach ($this->$type as $javascript) {
1515
                $javascriptfile = "$this->dir/javascript/$javascript.js";
1516
                if (is_readable($javascriptfile)) {
1517
                    $js[] = $javascriptfile;
1518
                }
1519
            }
1520
        }
1521
        return $js;
1522
    }
1523
 
1524
    /**
1525
     * Resolves an exclude setting to the themes setting is applicable or the
1526
     * setting of its closest parent.
1527
     *
1528
     * @param string $variable The name of the setting the exclude setting to resolve
1529
     * @param string $default
1530
     * @return mixed
1531
     */
1532
    protected function resolve_excludes($variable, $default = null) {
1533
        $setting = $default;
1534
        if (is_array($this->{$variable}) || $this->{$variable} === true) {
1535
            $setting = $this->{$variable};
1536
        } else {
1537
            foreach ($this->parent_configs as $parent_config) { // The immediate parent first, base last.
1538
                if (!isset($parent_config->{$variable})) {
1539
                    continue;
1540
                }
1541
                if (is_array($parent_config->{$variable}) || $parent_config->{$variable} === true) {
1542
                    $setting = $parent_config->{$variable};
1543
                    break;
1544
                }
1545
            }
1546
        }
1547
        return $setting;
1548
    }
1549
 
1550
    /**
1551
     * Returns the content of the one huge javascript file merged from all theme javascript files.
1552
     *
1553
     * @param bool $type
1554
     * @return string
1555
     */
1556
    public function javascript_content($type) {
1557
        $jsfiles = $this->javascript_files($type);
1558
        $js = '';
1559
        foreach ($jsfiles as $jsfile) {
1560
            $js .= file_get_contents($jsfile) . "\n";
1561
        }
1562
        return $js;
1563
    }
1564
 
1565
    /**
1566
     * Post processes CSS.
1567
     *
1568
     * This method post processes all of the CSS before it is served for this theme.
1569
     * This is done so that things such as image URL's can be swapped in and to
1570
     * run any specific CSS post process method the theme has requested.
1571
     * This allows themes to use CSS settings.
1572
     *
1573
     * @param string $css The CSS to process.
1574
     * @return string The processed CSS.
1575
     */
1576
    public function post_process($css) {
1577
        // Now resolve all image locations.
1578
        if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1579
            $replaced = [];
1580
            foreach ($matches as $match) {
1581
                if (isset($replaced[$match[0]])) {
1582
                    continue;
1583
                }
1584
                $replaced[$match[0]] = true;
1585
                $imagename = $match[2];
1586
                $component = rtrim($match[1], '|');
1587
                $imageurl = $this->image_url($imagename, $component)->out(false);
1588
                // We do not need full url because the image.php is always in the same dir.
1589
                $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1590
                $css = str_replace($match[0], $imageurl, $css);
1591
            }
1592
        }
1593
 
1594
        // Now resolve all font locations.
1595
        if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
1596
            $replaced = [];
1597
            foreach ($matches as $match) {
1598
                if (isset($replaced[$match[0]])) {
1599
                    continue;
1600
                }
1601
                $replaced[$match[0]] = true;
1602
                $fontname = $match[2];
1603
                $component = rtrim($match[1], '|');
1604
                $fonturl = $this->font_url($fontname, $component)->out(false);
1605
                // We do not need full url because the font.php is always in the same dir.
1606
                $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1607
                $css = str_replace($match[0], $fonturl, $css);
1608
            }
1609
        }
1610
 
1611
        // Now resolve all theme settings or do any other postprocessing.
1612
        // This needs to be done before calling core parser, since the parser strips [[settings]] tags.
1613
        $csspostprocess = $this->csspostprocess;
1614
        if ($csspostprocess && function_exists($csspostprocess)) {
1615
            $css = $csspostprocess($css, $this);
1616
        }
1617
 
1618
        // Post processing using an object representation of CSS.
1619
        $treeprocessor = $this->get_css_tree_post_processor();
1620
        $needsparsing = !empty($treeprocessor) || !empty($this->rtlmode);
1621
        if ($needsparsing) {
1622
            // We might need more memory/time to do this, so let's play safe.
1623
            raise_memory_limit(MEMORY_EXTRA);
1624
            core_php_time_limit::raise(300);
1625
 
1626
            $parser = new core_cssparser($css);
1627
            $csstree = $parser->parse();
1628
            unset($parser);
1629
 
1630
            if ($this->rtlmode) {
1631
                $this->rtlize($csstree);
1632
            }
1633
 
1634
            if ($treeprocessor) {
1635
                $treeprocessor($csstree, $this);
1636
            }
1637
 
1638
            $css = $csstree->render();
1639
            unset($csstree);
1640
        }
1641
 
1642
        return $css;
1643
    }
1644
 
1645
    /**
1646
     * Flip a stylesheet to RTL.
1647
     *
1648
     * @param mixed $csstree The parsed CSS tree structure to flip.
1649
     * @return void
1650
     */
1651
    protected function rtlize($csstree) {
1652
        $rtlcss = new core_rtlcss($csstree);
1653
        $rtlcss->flip();
1654
    }
1655
 
1656
    /**
1657
     * Return the direct URL for an image from the pix folder.
1658
     *
1659
     * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1660
     *
1661
     * @deprecated since Moodle 3.3
1662
     * @param string $imagename the name of the icon.
1663
     * @param string $component specification of one plugin like in get_string()
1664
     * @return moodle_url
1665
     */
1666
    public function pix_url($imagename, $component) {
1667
        debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
1668
        return $this->image_url($imagename, $component);
1669
    }
1670
 
1671
    /**
1672
     * Return the direct URL for an image from the pix folder.
1673
     *
1674
     * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
1675
     *
1676
     * @param string $imagename the name of the icon.
1677
     * @param string $component specification of one plugin like in get_string()
1678
     * @return moodle_url
1679
     */
1680
    public function image_url($imagename, $component) {
1681
        global $CFG;
1682
 
1683
        $params = ['theme' => $this->name];
1684
        $svg = $this->use_svg_icons();
1685
 
1686
        if (empty($component) || $component === 'moodle' || $component === 'core') {
1687
            $params['component'] = 'core';
1688
        } else {
1689
            $params['component'] = $component;
1690
        }
1691
 
1692
        $rev = theme_get_revision();
1693
        if ($rev != -1) {
1694
            $params['rev'] = $rev;
1695
        }
1696
 
1697
        $params['image'] = $imagename;
1698
 
1699
        $url = new moodle_url("/theme/image.php");
1700
        if (!empty($CFG->slasharguments) && $rev > 0) {
1701
            $path = '/' . $params['theme'] . '/' . $params['component'] . '/' . $params['rev'] . '/' . $params['image'];
1702
            if (!$svg) {
1703
                // We add a simple /_s to the start of the path.
1704
                // The underscore is used to ensure that it isn't a valid theme name.
1705
                $path = '/_s' . $path;
1706
            }
1707
            $url->set_slashargument($path, 'noparam', true);
1708
        } else {
1709
            if (!$svg) {
1710
                // We add an SVG param so that we know not to serve SVG images.
1711
                // We do this because all modern browsers support SVG and this param will one day be removed.
1712
                $params['svg'] = '0';
1713
            }
1714
            $url->params($params);
1715
        }
1716
 
1717
        return $url;
1718
    }
1719
 
1720
    /**
1721
     * Return the URL for a font
1722
     *
1723
     * @param string $font the name of the font (including extension).
1724
     * @param string $component specification of one plugin like in get_string()
1725
     * @return moodle_url
1726
     */
1727
    public function font_url($font, $component) {
1728
        global $CFG;
1729
 
1730
        $params = ['theme' => $this->name];
1731
 
1732
        if (empty($component) || $component === 'moodle' || $component === 'core') {
1733
            $params['component'] = 'core';
1734
        } else {
1735
            $params['component'] = $component;
1736
        }
1737
 
1738
        $rev = theme_get_revision();
1739
        if ($rev != -1) {
1740
            $params['rev'] = $rev;
1741
        }
1742
 
1743
        $params['font'] = $font;
1744
 
1745
        $url = new moodle_url("/theme/font.php");
1746
        if (!empty($CFG->slasharguments) && $rev > 0) {
1747
            $path = '/' . $params['theme'] . '/' . $params['component'] . '/' . $params['rev'] . '/' . $params['font'];
1748
            $url->set_slashargument($path, 'noparam', true);
1749
        } else {
1750
            $url->params($params);
1751
        }
1752
 
1753
        return $url;
1754
    }
1755
 
1756
    /**
1757
     * Returns URL to the stored file via pluginfile.php.
1758
     *
1759
     * Note the theme must also implement pluginfile.php handler,
1760
     * theme revision is used instead of the itemid.
1761
     *
1762
     * @param string $setting
1763
     * @param string $filearea
1764
     * @return string protocol relative URL or null if not present
1765
     */
1766
    public function setting_file_url($setting, $filearea) {
1767
        global $CFG;
1768
 
1769
        if (empty($this->settings->$setting)) {
1770
            return null;
1771
        }
1772
 
1773
        $component = 'theme_' . $this->name;
1774
        $itemid = theme_get_revision();
1775
        $filepath = $this->settings->$setting;
1776
        $syscontext = context_system::instance();
1777
 
1778
        $url = moodle_url::make_file_url(
1779
            "$CFG->wwwroot/pluginfile.php",
1780
            "/$syscontext->id/$component/$filearea/$itemid" . $filepath,
1781
        );
1782
 
1783
        // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1784
        // Note: unfortunately moodle_url does not support //urls yet.
1785
 
1786
        $url = preg_replace('|^https?://|i', '//', $url->out(false));
1787
 
1788
        return $url;
1789
    }
1790
 
1791
    /**
1792
     * Serve the theme setting file.
1793
     *
1794
     * @param string $filearea
1795
     * @param array $args
1796
     * @param bool $forcedownload
1797
     * @param array $options
1798
     * @return bool may terminate if file not found or donotdie not specified
1799
     */
1800
    public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1801
        global $CFG;
1802
        require_once("$CFG->libdir/filelib.php");
1803
 
1804
        $syscontext = context_system::instance();
1805
        $component = 'theme_' . $this->name;
1806
 
1807
        $revision = array_shift($args);
1808
        if ($revision < 0) {
1809
            $lifetime = 0;
1810
        } else {
1811
            $lifetime = 60 * 60 * 24 * 60;
1812
            // By default, theme files must be cache-able by both browsers and proxies.
1813
            if (!array_key_exists('cacheability', $options)) {
1814
                $options['cacheability'] = 'public';
1815
            }
1816
        }
1817
 
1818
        $fs = get_file_storage();
1819
        $relativepath = implode('/', $args);
1820
 
1821
        $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1822
        $fullpath = rtrim($fullpath, '/');
1823
        if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1824
            send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1825
            return true;
1826
        } else {
1827
            send_file_not_found();
1828
        }
1829
    }
1830
 
1831
    /**
1832
     * Resolves the real image location.
1833
     *
1834
     * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1835
     * and we need a way in which to turn it off.
1836
     * By default SVG won't be used unless asked for. This is done for two reasons:
1837
     *   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
1838
     *      browser supports SVG.
1839
     *   2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1840
     *      by the user due to security concerns.
1841
     *
1842
     * @param string $image name of image, may contain relative path
1843
     * @param string $component
1844
     * @param bool|null $svg Should SVG images also be looked for? If null, falls back to auto-detection of browser support
1845
     * @return string full file path
1846
     */
1847
    public function resolve_image_location($image, $component, $svg = false) {
1848
        global $CFG;
1849
 
1850
        if (!is_bool($svg)) {
1851
            // If $svg isn't a bool then we need to decide for ourselves.
1852
            $svg = $this->use_svg_icons();
1853
        }
1854
 
1855
        if ($component === 'moodle' || $component === 'core' || empty($component)) {
1856
            if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1857
                return $imagefile;
1858
            }
1859
            foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1860
                if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1861
                    return $imagefile;
1862
                }
1863
            }
1864
            if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1865
                return $imagefile;
1866
            }
1867
            if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1868
                return $imagefile;
1869
            }
1870
            return null;
1871
        } else if ($component === 'theme') { // Exception.
1872
            if ($image === 'favicon') {
1873
                return "$this->dir/pix/favicon.ico";
1874
            }
1875
            if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1876
                return $imagefile;
1877
            }
1878
            foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1879
                if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1880
                    return $imagefile;
1881
                }
1882
            }
1883
            return null;
1884
        } else {
1885
            if (strpos($component, '_') === false) {
1886
                $component = "mod_{$component}";
1887
            }
1888
            [$type, $plugin] = explode('_', $component, 2);
1889
 
1890
            // In Moodle 4.0 we introduced a new image format.
1891
            // Support that image format here.
1892
            $candidates = [$image];
1893
 
1894
            if ($type === 'mod') {
1895
                if ($image === 'icon' || $image === 'monologo') {
1896
                    $candidates = ['monologo', 'icon'];
1897
                    if ($image === 'icon') {
1898
                        debugging(
1899
                            "The 'icon' image for activity modules has been replaced with a new 'monologo'. " .
1900
                                "Please update your calling code to fetch the new icon where possible. " .
1901
                                "Called for component {$component}.",
1902
                            DEBUG_DEVELOPER
1903
                        );
1904
                    }
1905
                }
1906
            }
1907
            foreach ($candidates as $image) {
1908
                if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1909
                    return $imagefile;
1910
                }
1911
 
1912
                // Base first, the immediate parent last.
1913
                foreach (array_reverse($this->parent_configs) as $parentconfig) {
1914
                    if ($imagefile = $this->image_exists("$parentconfig->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1915
                        return $imagefile;
1916
                    }
1917
                }
1918
                if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1919
                    return $imagefile;
1920
                }
1921
                $dir = core_component::get_plugin_directory($type, $plugin);
1922
                if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1923
                    return $imagefile;
1924
                }
1925
            }
1926
            return null;
1927
        }
1928
    }
1929
 
1930
    /**
1931
     * Resolves the real font location.
1932
     *
1933
     * @param string $font name of font file
1934
     * @param string $component
1935
     * @return string full file path
1936
     */
1937
    public function resolve_font_location($font, $component) {
1938
        global $CFG;
1939
 
1940
        if ($component === 'moodle' || $component === 'core' || empty($component)) {
1941
            if (file_exists("$this->dir/fonts_core/$font")) {
1942
                return "$this->dir/fonts_core/$font";
1943
            }
1944
            foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1945
                if (file_exists("$parent_config->dir/fonts_core/$font")) {
1946
                    return "$parent_config->dir/fonts_core/$font";
1947
                }
1948
            }
1949
            if (file_exists("$CFG->dataroot/fonts/$font")) {
1950
                return "$CFG->dataroot/fonts/$font";
1951
            }
1952
            if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
1953
                return "$CFG->dirroot/lib/fonts/$font";
1954
            }
1955
            return null;
1956
        } else if ($component === 'theme') { // Exception.
1957
            if (file_exists("$this->dir/fonts/$font")) {
1958
                return "$this->dir/fonts/$font";
1959
            }
1960
            foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1961
                if (file_exists("$parent_config->dir/fonts/$font")) {
1962
                    return "$parent_config->dir/fonts/$font";
1963
                }
1964
            }
1965
            return null;
1966
        } else {
1967
            if (strpos($component, '_') === false) {
1968
                $component = 'mod_' . $component;
1969
            }
1970
            [$type, $plugin] = explode('_', $component, 2);
1971
 
1972
            if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
1973
                return "$this->dir/fonts_plugins/$type/$plugin/$font";
1974
            }
1975
            foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last.
1976
                if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
1977
                    return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
1978
                }
1979
            }
1980
            if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
1981
                return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
1982
            }
1983
            $dir = core_component::get_plugin_directory($type, $plugin);
1984
            if (file_exists("$dir/fonts/$font")) {
1985
                return "$dir/fonts/$font";
1986
            }
1987
            return null;
1988
        }
1989
    }
1990
 
1991
    /**
1992
     * Return true if we should look for SVG images as well.
1993
     *
1994
     * @return bool
1995
     */
1996
    public function use_svg_icons() {
1997
        if ($this->usesvg === null) {
1998
            $this->usesvg = core_useragent::supports_svg();
1999
        }
2000
 
2001
        return $this->usesvg;
2002
    }
2003
 
2004
    /**
2005
     * Forces the usesvg setting to either true or false, avoiding any decision making.
2006
     *
2007
     * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
2008
     * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
2009
     *
2010
     * @param bool $setting True to force the use of svg when available, null otherwise.
2011
     */
2012
    public function force_svg_use($setting) {
2013
        $this->usesvg = (bool)$setting;
2014
    }
2015
 
2016
    /**
2017
     * Set to be in RTL mode.
2018
     *
2019
     * This will likely be used when post processing the CSS before serving it.
2020
     *
2021
     * @param bool $inrtl True when in RTL mode.
2022
     */
2023
    public function set_rtl_mode($inrtl = true) {
2024
        $this->rtlmode = $inrtl;
2025
    }
2026
 
2027
    /**
2028
     * Checks if source maps are supported
2029
     *
2030
     * @param bool $themedesigner True if theme designer is enabled.
2031
     * @return boolean True if source maps are supported.
2032
     */
2033
    public function supports_source_maps($themedesigner): bool {
2034
        if (empty($this->rtlmode) && $themedesigner) {
2035
            return true;
2036
        }
2037
        return false;
2038
    }
2039
 
2040
    /**
2041
     * Whether the theme is being served in RTL mode.
2042
     *
2043
     * @return bool True when in RTL mode.
2044
     */
2045
    public function get_rtl_mode() {
2046
        return $this->rtlmode;
2047
    }
2048
 
2049
    /**
2050
     * Checks if file with any image extension exists.
2051
     *
2052
     * The order to these images was adjusted prior to the release of 2.4
2053
     * At that point the were the following image counts in Moodle core:
2054
     *
2055
     *     - png = 667 in pix dirs (1499 total)
2056
     *     - gif = 385 in pix dirs (606 total)
2057
     *     - jpg = 62  in pix dirs (74 total)
2058
     *     - jpeg = 0  in pix dirs (1 total)
2059
     *
2060
     * There is work in progress to move towards SVG presently hence that has been prioritiesed.
2061
     *
2062
     * @param string $filepath
2063
     * @param bool $svg If set to true SVG images will also be looked for.
2064
     * @return string image name with extension
2065
     */
2066
    private static function image_exists($filepath, $svg = false) {
2067
        if ($svg && file_exists("$filepath.svg")) {
2068
            return "$filepath.svg";
2069
        } else if (file_exists("$filepath.png")) {
2070
            return "$filepath.png";
2071
        } else if (file_exists("$filepath.gif")) {
2072
            return "$filepath.gif";
2073
        } else if (file_exists("$filepath.jpg")) {
2074
            return "$filepath.jpg";
2075
        } else if (file_exists("$filepath.jpeg")) {
2076
            return "$filepath.jpeg";
2077
        } else {
2078
            return false;
2079
        }
2080
    }
2081
 
2082
    /**
2083
     * Loads the theme config from config.php file.
2084
     *
2085
     * @param string $themename
2086
     * @param stdClass $settings from config_plugins table
2087
     * @param boolean $parentscheck true to also check the parents.    .
2088
     * @return ?stdClass The theme configuration
2089
     */
2090
    private static function find_theme_config($themename, $settings, $parentscheck = true) {
2091
        // We have to use the variable name $THEME (upper case) because that
2092
        // is what is used in theme config.php files.
2093
 
2094
        if (!$dir = self::find_theme_location($themename)) {
2095
            return null;
2096
        }
2097
 
2098
        $THEME = new stdClass();
2099
        $THEME->name     = $themename;
2100
        $THEME->dir      = $dir;
2101
        $THEME->settings = $settings;
2102
 
2103
        global $CFG; // Just in case somebody tries to use $CFG in theme config.
2104
        include("$THEME->dir/config.php");
2105
 
2106
        // Verify the theme configuration is OK.
2107
        if (!is_array($THEME->parents)) {
2108
            // Parents option is mandatory now.
2109
            return null;
2110
        } else {
2111
            // We use $parentscheck to only check the direct parents (avoid infinite loop).
2112
            if ($parentscheck) {
2113
                // Find all parent theme configs.
2114
                foreach ($THEME->parents as $parent) {
2115
                    $parentconfig = self::find_theme_config($parent, $settings, false);
2116
                    if (empty($parentconfig)) {
2117
                        return null;
2118
                    }
2119
                }
2120
            }
2121
        }
2122
 
2123
        return $THEME;
2124
    }
2125
 
2126
    /**
2127
     * Finds the theme location and verifies the theme has all needed files
2128
     * and is not obsoleted.
2129
     *
2130
     * @param string $themename
2131
     * @return string full dir path or null if not found
2132
     */
2133
    private static function find_theme_location($themename) {
2134
        global $CFG;
2135
 
2136
        if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2137
            $dir = "$CFG->dirroot/theme/$themename";
2138
        } else if (!empty($CFG->themedir) && file_exists("$CFG->themedir/$themename/config.php")) {
2139
            $dir = "$CFG->themedir/$themename";
2140
        } else {
2141
            return null;
2142
        }
2143
 
2144
        if (file_exists("$dir/styles.php")) {
2145
            // Legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page.
2146
            return null;
2147
        }
2148
 
2149
        return $dir;
2150
    }
2151
 
2152
    /**
2153
     * Get the renderer for a part of Moodle for this theme.
2154
     *
2155
     * @param moodle_page $page the page we are rendering
2156
     * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
2157
     * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
2158
     * @param string $target one of rendering target constants
2159
     * @return renderer_base the requested renderer.
2160
     */
2161
    public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
2162
        if (is_null($this->rf)) {
2163
            $classname = $this->rendererfactory;
2164
            $this->rf = new $classname($this);
2165
        }
2166
 
2167
        return $this->rf->get_renderer($page, $component, $subtype, $target);
2168
    }
2169
 
2170
    /**
2171
     * Get the information from {@see $layouts} for this type of page.
2172
     *
2173
     * @param string $pagelayout the the page layout name.
2174
     * @return array the appropriate part of {@see $layouts}.
2175
     */
2176
    protected function layout_info_for_page($pagelayout) {
2177
        if (array_key_exists($pagelayout, $this->layouts)) {
2178
            return $this->layouts[$pagelayout];
2179
        } else {
2180
            debugging('Invalid page layout specified: ' . $pagelayout);
2181
            return $this->layouts['standard'];
2182
        }
2183
    }
2184
 
2185
    /**
2186
     * Given the settings of this theme, and the page pagelayout, return the
2187
     * full path of the page layout file to use.
2188
     *
2189
     * Used by {@see core_renderer::header()}.
2190
     *
2191
     * @param string $pagelayout the the page layout name.
2192
     * @return string Full path to the lyout file to use
2193
     */
2194
    public function layout_file($pagelayout) {
2195
        global $CFG;
2196
 
2197
        $layoutinfo = $this->layout_info_for_page($pagelayout);
2198
        $layoutfile = $layoutinfo['file'];
2199
 
2200
        if (array_key_exists('theme', $layoutinfo)) {
2201
            $themes = [$layoutinfo['theme']];
2202
        } else {
2203
            $themes = array_merge([$this->name], $this->parents);
2204
        }
2205
 
2206
        foreach ($themes as $theme) {
2207
            if ($dir = $this->find_theme_location($theme)) {
2208
                $path = "$dir/layout/$layoutfile";
2209
 
2210
                // Check the template exists, return general base theme template if not.
2211
                if (is_readable($path)) {
2212
                    return $path;
2213
                }
2214
            }
2215
        }
2216
 
2217
        throw new coding_exception('Can not find layout file for: ' . $pagelayout . ' (' . $layoutfile . ')');
2218
    }
2219
 
2220
    /**
2221
     * Returns auxiliary page layout options specified in layout configuration array.
2222
     *
2223
     * @param string $pagelayout
2224
     * @return array
2225
     */
2226
    public function pagelayout_options($pagelayout) {
2227
        $info = $this->layout_info_for_page($pagelayout);
2228
        if (!empty($info['options'])) {
2229
            return $info['options'];
2230
        }
2231
        return [];
2232
    }
2233
 
2234
    /**
2235
     * Inform a block_manager about the block regions this theme wants on this
2236
     * page layout.
2237
     *
2238
     * @param string $pagelayout the general type of the page.
2239
     * @param block_manager $blockmanager the block_manger to set up.
2240
     */
2241
    public function setup_blocks($pagelayout, $blockmanager) {
2242
        $layoutinfo = $this->layout_info_for_page($pagelayout);
2243
        if (!empty($layoutinfo['regions'])) {
2244
            $blockmanager->add_regions($layoutinfo['regions'], false);
2245
            $blockmanager->set_default_region($layoutinfo['defaultregion']);
2246
        }
2247
    }
2248
 
2249
    /**
2250
     * Gets the visible name for the requested block region.
2251
     *
2252
     * @param string $region The region name to get
2253
     * @param string $theme The theme the region belongs to (may come from the parent theme)
2254
     * @return string
2255
     */
2256
    protected function get_region_name($region, $theme) {
2257
 
2258
        $stringman = get_string_manager();
2259
 
2260
        // Check if the name is defined in the theme.
2261
        if ($stringman->string_exists('region-' . $region, 'theme_' . $theme)) {
2262
            return get_string('region-' . $region, 'theme_' . $theme);
2263
        }
2264
 
2265
        // Check the theme parents.
2266
        foreach ($this->parents as $parentthemename) {
2267
            if ($stringman->string_exists('region-' . $region, 'theme_' . $parentthemename)) {
2268
                return get_string('region-' . $region, 'theme_' . $parentthemename);
2269
            }
2270
        }
2271
 
2272
        // Last resort, try the boost theme for names.
2273
        return get_string('region-' . $region, 'theme_boost');
2274
    }
2275
 
2276
    /**
2277
     * Get the list of all block regions known to this theme in all templates.
2278
     *
2279
     * @return array internal region name => human readable name.
2280
     */
2281
    public function get_all_block_regions() {
2282
        $regions = [];
2283
        foreach ($this->layouts as $layoutinfo) {
2284
            foreach ($layoutinfo['regions'] as $region) {
2285
                $regions[$region] = $this->get_region_name($region, $this->name);
2286
            }
2287
        }
2288
        return $regions;
2289
    }
2290
 
2291
    /**
2292
     * Returns the human readable name of the theme
2293
     *
2294
     * @return string
2295
     */
2296
    public function get_theme_name() {
2297
        return get_string('pluginname', 'theme_' . $this->name);
2298
    }
2299
 
2300
    /**
2301
     * Returns the block render method.
2302
     *
2303
     * It is set by the theme via:
2304
     *     $THEME->blockrendermethod = '...';
2305
     *
2306
     * It can be one of two values, blocks or blocks_for_region.
2307
     * It should be set to the method being used by the theme layouts.
2308
     *
2309
     * @return string
2310
     */
2311
    public function get_block_render_method() {
2312
        if ($this->blockrendermethod) {
2313
            // Return the specified block render method.
2314
            return $this->blockrendermethod;
2315
        }
2316
        // Its not explicitly set, check the parent theme configs.
2317
        foreach ($this->parent_configs as $config) {
2318
            if (isset($config->blockrendermethod)) {
2319
                return $config->blockrendermethod;
2320
            }
2321
        }
2322
        // Default it to blocks.
2323
        return 'blocks';
2324
    }
2325
 
2326
    /**
2327
     * Get the callable for CSS tree post processing.
2328
     *
2329
     * @return string|null
2330
     */
2331
    public function get_css_tree_post_processor() {
2332
        $configs = [$this] + $this->parent_configs;
2333
        foreach ($configs as $config) {
2334
            if (!empty($config->csstreepostprocessor) && is_callable($config->csstreepostprocessor)) {
2335
                return $config->csstreepostprocessor;
2336
            }
2337
        }
2338
        return null;
2339
    }
2340
}
2341
// Alias this class to the old name.
2342
// This file will be autoloaded by the legacyclasses autoload system.
2343
// In future all uses of this class will be corrected and the legacy references will be removed.
2344
class_alias(theme_config::class, \theme_config::class);