2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Functions for generating the HTML that Moodle should output.
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
23 * @copyright 2009 Tim Hunt
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') ||
die();
31 require_once($CFG->libdir
.'/outputcomponents.php');
32 require_once($CFG->libdir
.'/outputactions.php');
33 require_once($CFG->libdir
.'/outputfactories.php');
34 require_once($CFG->libdir
.'/outputrenderers.php');
35 require_once($CFG->libdir
.'/outputrequirementslib.php');
38 * Invalidate all server and client side caches.
40 * This method deletes the physical directory that is used to cache the theme
41 * files used for serving.
42 * Because it deletes the main theme cache directory all themes are reset by
45 function theme_reset_all_caches() {
49 if (isset($CFG->themerev
) and $next <= $CFG->themerev
and $CFG->themerev
- $next < 60*60) {
50 // This resolves problems when reset is requested repeatedly within 1s,
51 // the < 1h condition prevents accidental switching to future dates
52 // because we might not recover from it.
53 $next = $CFG->themerev+
1;
56 set_config('themerev', $next); // time is unique even when you reset/switch database
58 if (!empty($CFG->themedesignermode
)) {
59 $cache = cache
::make_from_params(cache_store
::MODE_APPLICATION
, 'core', 'themedesigner');
64 $PAGE->reload_theme();
69 * Enable or disable theme designer mode.
73 function theme_set_designer_mod($state) {
74 set_config('themedesignermode', (int)!empty($state));
75 // Reset caches after switching mode so that any designer mode caches get purged too.
76 theme_reset_all_caches();
80 * Returns current theme revision number.
84 function theme_get_revision() {
87 if (empty($CFG->themedesignermode
)) {
88 if (empty($CFG->themerev
)) {
89 // This only happens during install. It doesn't matter what themerev we use as long as it's positive.
92 return $CFG->themerev
;
101 * Checks if the given device has a theme defined in config.php.
105 function theme_is_device_locked($device) {
107 $themeconfigname = core_useragent
::get_device_type_cfg_var_name($device);
108 return isset($CFG->config_php_settings
[$themeconfigname]);
112 * Returns the theme named defined in config.php for the given device.
114 * @return string or null
116 function theme_get_locked_theme_for_device($device) {
119 if (!theme_is_device_locked($device)) {
123 $themeconfigname = core_useragent
::get_device_type_cfg_var_name($device);
124 return $CFG->config_php_settings
[$themeconfigname];
128 * This class represents the configuration variables of a Moodle theme.
130 * All the variables with access: public below (with a few exceptions that are marked)
131 * are the properties you can set in your themes config.php file.
133 * There are also some methods and protected variables that are part of the inner
134 * workings of Moodle's themes system. If you are just editing a themes config.php
135 * file, you can just ignore those, and the following information for developers.
137 * Normally, to create an instance of this class, you should use the
138 * {@link theme_config::load()} factory method to load a themes config.php file.
139 * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
140 * will create one for you, accessible as $PAGE->theme.
142 * @copyright 2009 Tim Hunt
143 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
151 * @var string Default theme, used when requested theme not found.
153 const DEFAULT_THEME
= 'boost';
155 /** The key under which the SCSS file is stored amongst the CSS files. */
156 const SCSS_KEY
= '__SCSS__';
159 * @var array You can base your theme on other themes by linking to the other theme as
160 * parents. This lets you use the CSS and layouts from the other themes
161 * (see {@link theme_config::$layouts}).
162 * That makes it easy to create a new theme that is similar to another one
163 * but with a few changes. In this themes CSS you only need to override
164 * those rules you want to change.
169 * @var array The names of all the stylesheets from this theme that you would
170 * like included, in order. Give the names of the files without .css.
172 public $sheets = array();
175 * @var array The names of all the stylesheets from parents that should be excluded.
176 * true value may be used to specify all parents or all themes from one parent.
177 * If no value specified value from parent theme used.
179 public $parents_exclude_sheets = null;
182 * @var array List of plugin sheets to be excluded.
183 * If no value specified value from parent theme used.
185 public $plugins_exclude_sheets = null;
188 * @var array List of style sheets that are included in the text editor bodies.
189 * Sheets from parent themes are used automatically and can not be excluded.
191 public $editor_sheets = array();
194 * @var array The names of all the javascript files this theme that you would
195 * like included from head, in order. Give the names of the files without .js.
197 public $javascripts = array();
200 * @var array The names of all the javascript files this theme that you would
201 * like included from footer, in order. Give the names of the files without .js.
203 public $javascripts_footer = array();
206 * @var array The names of all the javascript files from parents that should
207 * be excluded. true value may be used to specify all parents or all themes
209 * If no value specified value from parent theme used.
211 public $parents_exclude_javascripts = null;
214 * @var array Which file to use for each page layout.
216 * This is an array of arrays. The keys of the outer array are the different layouts.
217 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
218 * 'popup', 'form', .... The most reliable way to get a complete list is to look at
219 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
220 * That file also has a good example of how to set this setting.
222 * For each layout, the value in the outer array is an array that describes
223 * how you want that type of page to look. For example
225 * $THEME->layouts = array(
226 * // Most pages - if we encounter an unknown or a missing page type, this one is used.
227 * 'standard' => array(
228 * 'theme' = 'mytheme',
229 * 'file' => 'normal.php',
230 * 'regions' => array('side-pre', 'side-post'),
231 * 'defaultregion' => 'side-post'
233 * // The site home page.
235 * 'theme' = 'mytheme',
236 * 'file' => 'home.php',
237 * 'regions' => array('side-pre', 'side-post'),
238 * 'defaultregion' => 'side-post'
244 * 'theme' name of the theme where is the layout located
245 * 'file' is the layout file to use for this type of page.
246 * layout files are stored in layout subfolder
247 * 'regions' This lists the regions on the page where blocks may appear. For
248 * each region you list here, your layout file must include a call to
250 * echo $OUTPUT->blocks_for_region($regionname);
252 * or equivalent so that the blocks are actually visible.
254 * 'defaultregion' If the list of regions is non-empty, then you must pick
255 * one of the one of them as 'default'. This has two meanings. First, this is
256 * where new blocks are added. Second, if there are any blocks associated with
257 * the page, but in non-existent regions, they appear here. (Imaging, for example,
258 * that someone added blocks using a different theme that used different region
259 * names, and then switched to this theme.)
261 public $layouts = array();
264 * @var string Name of the renderer factory class to use. Must implement the
265 * {@link renderer_factory} interface.
267 * This is an advanced feature. Moodle output is generated by 'renderers',
268 * you can customise the HTML that is output by writing custom renderers,
269 * and then you need to specify 'renderer factory' so that Moodle can find
272 * There are some renderer factories supplied with Moodle. Please follow these
273 * links to see what they do.
275 * <li>{@link standard_renderer_factory} - the default.</li>
276 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
277 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
280 public $rendererfactory = 'standard_renderer_factory';
283 * @var string Function to do custom CSS post-processing.
285 * This is an advanced feature. If you want to do custom post-processing on the
286 * CSS before it is output (for example, to replace certain variable names
287 * with particular values) you can give the name of a function here.
289 public $csspostprocess = null;
292 * @var string Function to do custom CSS post-processing on a parsed CSS tree.
294 * This is an advanced feature. If you want to do custom post-processing on the
295 * CSS before it is output, you can provide the name of the function here. The
296 * function will receive a CSS tree document as first parameter, and the theme_config
297 * object as second parameter. A return value is not required, the tree can
298 * be edited in place.
300 public $csstreepostprocessor = null;
303 * @var string Accessibility: Right arrow-like character is
304 * used in the breadcrumb trail, course navigation menu
305 * (previous/next activity), calendar, and search forum block.
306 * If the theme does not set characters, appropriate defaults
307 * are set automatically. Please DO NOT
308 * use < > » - these are confusing for blind users.
310 public $rarrow = null;
313 * @var string Accessibility: Left arrow-like character is
314 * used in the breadcrumb trail, course navigation menu
315 * (previous/next activity), calendar, and search forum block.
316 * If the theme does not set characters, appropriate defaults
317 * are set automatically. Please DO NOT
318 * use < > » - these are confusing for blind users.
320 public $larrow = null;
323 * @var string Accessibility: Up arrow-like character is used in
324 * the book heirarchical navigation.
325 * If the theme does not set characters, appropriate defaults
326 * are set automatically. Please DO NOT
327 * use ^ - this is confusing for blind users.
329 public $uarrow = null;
332 * @var string Accessibility: Down arrow-like character.
333 * If the theme does not set characters, appropriate defaults
334 * are set automatically.
336 public $darrow = null;
339 * @var bool Some themes may want to disable ajax course editing.
341 public $enablecourseajax = true;
344 * @var string Determines served document types
345 * - 'html5' the only officially supported doctype in Moodle
346 * - 'xhtml5' may be used in development for validation (not intended for production servers!)
347 * - 'xhtml' XHTML 1.0 Strict for legacy themes only
349 public $doctype = 'html5';
352 * @var string requiredblocks If set to a string, will list the block types that cannot be deleted. Defaults to
353 * navigation and settings.
355 public $requiredblocks = false;
357 //==Following properties are not configurable from theme config.php==
360 * @var string The name of this theme. Set automatically when this theme is
361 * loaded. This can not be set in theme config.php
366 * @var string The folder where this themes files are stored. This is set
367 * automatically. This can not be set in theme config.php
372 * @var stdClass Theme settings stored in config_plugins table.
373 * This can not be set in theme config.php
375 public $setting = null;
378 * @var bool If set to true and the theme enables the dock then blocks will be able
379 * to be moved to the special dock
381 public $enable_dock = false;
384 * @var bool If set to true then this theme will not be shown in the theme selector unless
385 * theme designer mode is turned on.
387 public $hidefromselector = false;
390 * @var array list of YUI CSS modules to be included on each page. This may be used
391 * to remove cssreset and use cssnormalise module instead.
393 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
396 * An associative array of block manipulations that should be made if the user is using an rtl language.
397 * The key is the original block region, and the value is the block region to change to.
398 * This is used when displaying blocks for regions only.
401 public $blockrtlmanipulations = array();
404 * @var renderer_factory Instance of the renderer_factory implementation
405 * we are using. Implementation detail.
407 protected $rf = null;
410 * @var array List of parent config objects.
412 protected $parent_configs = array();
415 * Used to determine whether we can serve SVG images or not.
418 private $usesvg = null;
421 * Whether in RTL mode or not.
424 protected $rtlmode = false;
427 * The LESS file to compile. When set, the theme will attempt to compile the file itself.
430 public $lessfile = false;
433 * The SCSS file to compile (without .scss), located in the scss/ folder of the theme.
434 * Or a Closure, which receives the theme_config as argument and must
435 * return the SCSS content. This setting takes precedence over self::$lessfile.
436 * @var string|Closure
438 public $scss = false;
441 * Local cache of the SCSS property.
444 protected $scsscache = null;
447 * The name of the function to call to get the LESS code to inject.
450 public $extralesscallback = null;
453 * The name of the function to call to get the SCSS code to inject.
456 public $extrascsscallback = null;
459 * The name of the function to call to get extra LESS variables.
462 public $lessvariablescallback = null;
465 * The name of the function to call to get SCSS to prepend.
468 public $prescsscallback = null;
471 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
472 * Defaults to {@link core_renderer::blocks_for_region()}
475 public $blockrendermethod = null;
478 * Load the config.php file for a particular theme, and return an instance
479 * of this class. (That is, this is a factory method.)
481 * @param string $themename the name of the theme.
482 * @return theme_config an instance of this class.
484 public static function load($themename) {
487 // load theme settings from db
489 $settings = get_config('theme_'.$themename);
490 } catch (dml_exception
$e) {
491 // most probably moodle tables not created yet
492 $settings = new stdClass();
495 if ($config = theme_config
::find_theme_config($themename, $settings)) {
496 return new theme_config($config);
498 } else if ($themename == theme_config
::DEFAULT_THEME
) {
499 throw new coding_exception('Default theme '.theme_config
::DEFAULT_THEME
.' not available or broken!');
501 } else if ($config = theme_config
::find_theme_config($CFG->theme
, $settings)) {
502 return new theme_config($config);
505 // bad luck, the requested theme has some problems - admin see details in theme config
506 return new theme_config(theme_config
::find_theme_config(theme_config
::DEFAULT_THEME
, $settings));
511 * Theme diagnostic code. It is very problematic to send debug output
512 * to the actual CSS file, instead this functions is supposed to
513 * diagnose given theme and highlights all potential problems.
514 * This information should be available from the theme selection page
515 * or some other debug page for theme designers.
517 * @param string $themename
518 * @return array description of problems
520 public static function diagnose($themename) {
526 * Private constructor, can be called only from the factory method.
527 * @param stdClass $config
529 private function __construct($config) {
530 global $CFG; //needed for included lib.php files
532 $this->settings
= $config->settings
;
533 $this->name
= $config->name
;
534 $this->dir
= $config->dir
;
536 if ($this->name
!= 'bootstrapbase') {
537 $baseconfig = theme_config
::find_theme_config('bootstrapbase', $this->settings
);
539 $baseconfig = $config;
542 $configurable = array(
543 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets',
544 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
545 'layouts', 'enable_dock', 'enablecourseajax', 'requiredblocks',
546 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'uarrow', 'darrow',
547 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations',
548 'lessfile', 'extralesscallback', 'lessvariablescallback', 'blockrendermethod',
549 'scss', 'extrascsscallback', 'prescsscallback', 'csstreepostprocessor', 'addblockposition');
551 foreach ($config as $key=>$value) {
552 if (in_array($key, $configurable)) {
553 $this->$key = $value;
557 // verify all parents and load configs and renderers
558 foreach ($this->parents
as $parent) {
559 if (!$parent_config = theme_config
::find_theme_config($parent, $this->settings
)) {
560 // this is not good - better exclude faulty parents
563 $libfile = $parent_config->dir
.'/lib.php';
564 if (is_readable($libfile)) {
565 // theme may store various function here
566 include_once($libfile);
568 $renderersfile = $parent_config->dir
.'/renderers.php';
569 if (is_readable($renderersfile)) {
570 // may contain core and plugin renderers and renderer factory
571 include_once($renderersfile);
573 $this->parent_configs
[$parent] = $parent_config;
575 $libfile = $this->dir
.'/lib.php';
576 if (is_readable($libfile)) {
577 // theme may store various function here
578 include_once($libfile);
580 $rendererfile = $this->dir
.'/renderers.php';
581 if (is_readable($rendererfile)) {
582 // may contain core and plugin renderers and renderer factory
583 include_once($rendererfile);
585 // check if renderers.php file is missnamed renderer.php
586 if (is_readable($this->dir
.'/renderer.php')) {
587 debugging('Developer hint: '.$this->dir
.'/renderer.php should be renamed to ' . $this->dir
."/renderers.php.
588 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER
);
592 // cascade all layouts properly
593 foreach ($baseconfig->layouts
as $layout=>$value) {
594 if (!isset($this->layouts
[$layout])) {
595 foreach ($this->parent_configs
as $parent_config) {
596 if (isset($parent_config->layouts
[$layout])) {
597 $this->layouts
[$layout] = $parent_config->layouts
[$layout];
601 $this->layouts
[$layout] = $value;
605 //fix arrows if needed
606 $this->check_theme_arrows();
610 * Let the theme initialise the page object (usually $PAGE).
612 * This may be used for example to request jQuery in add-ons.
614 * @param moodle_page $page
616 public function init_page(moodle_page
$page) {
617 $themeinitfunction = 'theme_'.$this->name
.'_page_init';
618 if (function_exists($themeinitfunction)) {
619 $themeinitfunction($page);
624 * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow, $THEME->darrow have been set (theme/-/config.php).
625 * If not it applies sensible defaults.
627 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
628 * search forum block, etc. Important: these are 'silent' in a screen-reader
629 * (unlike > »), and must be accompanied by text.
631 private function check_theme_arrows() {
632 if (!isset($this->rarrow
) and !isset($this->larrow
)) {
633 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
634 // Also OK in Win 9x/2K/IE 5.x
635 $this->rarrow
= '►';
636 $this->larrow
= '◄';
637 $this->uarrow
= '▲';
638 $this->darrow
= '▼';
639 if (empty($_SERVER['HTTP_USER_AGENT'])) {
642 $uagent = $_SERVER['HTTP_USER_AGENT'];
644 if (false !== strpos($uagent, 'Opera')
645 ||
false !== strpos($uagent, 'Mac')) {
646 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
647 // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
648 $this->rarrow
= '▶︎';
649 $this->larrow
= '◀︎';
651 elseif ((false !== strpos($uagent, 'Konqueror'))
652 ||
(false !== strpos($uagent, 'Android'))) {
653 // The fonts on Android don't include the characters required for this to work as expected.
654 // So we use the same ones Konqueror uses.
655 $this->rarrow
= '→';
656 $this->larrow
= '←';
657 $this->uarrow
= '↑';
658 $this->darrow
= '↓';
660 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
661 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
662 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
663 // To be safe, non-Unicode browsers!
664 $this->rarrow
= '>';
665 $this->larrow
= '<';
670 // RTL support - in RTL languages, swap r and l arrows
671 if (right_to_left()) {
673 $this->rarrow
= $this->larrow
;
680 * Returns output renderer prefixes, these are used when looking
681 * for the overridden renderers in themes.
685 public function renderer_prefixes() {
686 global $CFG; // just in case the included files need it
688 $prefixes = array('theme_'.$this->name
);
690 foreach ($this->parent_configs
as $parent) {
691 $prefixes[] = 'theme_'.$parent->name
;
698 * Returns the stylesheet URL of this editor content
700 * @param bool $encoded false means use & and true use & in URLs
703 public function editor_css_url($encoded=true) {
705 $rev = theme_get_revision();
707 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
708 if (!empty($CFG->slasharguments
)) {
709 $url->set_slashargument('/'.$this->name
.'/'.$rev.'/editor', 'noparam', true);
711 $url->params(array('theme'=>$this->name
,'rev'=>$rev, 'type'=>'editor'));
714 $params = array('theme'=>$this->name
, 'type'=>'editor');
715 $url = new moodle_url($CFG->httpswwwroot
.'/theme/styles_debug.php', $params);
721 * Returns the content of the CSS to be used in editor content
725 public function editor_css_files() {
728 // First editor plugins.
729 $plugins = core_component
::get_plugin_list('editor');
730 foreach ($plugins as $plugin=>$fulldir) {
731 $sheetfile = "$fulldir/editor_styles.css";
732 if (is_readable($sheetfile)) {
733 $files['plugin_'.$plugin] = $sheetfile;
736 // Then parent themes - base first, the immediate parent last.
737 foreach (array_reverse($this->parent_configs
) as $parent_config) {
738 if (empty($parent_config->editor_sheets
)) {
741 foreach ($parent_config->editor_sheets
as $sheet) {
742 $sheetfile = "$parent_config->dir/style/$sheet.css";
743 if (is_readable($sheetfile)) {
744 $files['parent_'.$parent_config->name
.'_'.$sheet] = $sheetfile;
748 // Finally this theme.
749 if (!empty($this->editor_sheets
)) {
750 foreach ($this->editor_sheets
as $sheet) {
751 $sheetfile = "$this->dir/style/$sheet.css";
752 if (is_readable($sheetfile)) {
753 $files['theme_'.$sheet] = $sheetfile;
762 * Get the stylesheet URL of this theme.
764 * @param moodle_page $page Not used... deprecated?
765 * @return moodle_url[]
767 public function css_urls(moodle_page
$page) {
770 $rev = theme_get_revision();
774 $svg = $this->use_svg_icons();
775 $separate = (core_useragent
::is_ie() && !core_useragent
::check_ie_version('10'));
778 $filename = right_to_left() ?
'all-rtl' : 'all';
779 $url = new moodle_url("$CFG->httpswwwroot/theme/styles.php");
780 if (!empty($CFG->slasharguments
)) {
783 // We add a simple /_s to the start of the path.
784 // The underscore is used to ensure that it isn't a valid theme name.
785 $slashargs .= '/_s'.$slashargs;
787 $slashargs .= '/'.$this->name
.'/'.$rev.'/'.$filename;
789 $slashargs .= '/chunk0';
791 $url->set_slashargument($slashargs, 'noparam', true);
793 $params = array('theme' => $this->name
, 'rev' => $rev, 'type' => $filename);
795 // We add an SVG param so that we know not to serve SVG images.
796 // We do this because all modern browsers support SVG and this param will one day be removed.
797 $params['svg'] = '0';
800 $params['chunk'] = '0';
802 $url->params($params);
807 $baseurl = new moodle_url($CFG->httpswwwroot
.'/theme/styles_debug.php');
809 $css = $this->get_css_files(true);
811 // We add an SVG param so that we know not to serve SVG images.
812 // We do this because all modern browsers support SVG and this param will one day be removed.
813 $baseurl->param('svg', '0');
815 if (right_to_left()) {
816 $baseurl->param('rtl', 1);
819 // We might need to chunk long files.
820 $baseurl->param('chunk', '0');
822 if (core_useragent
::is_ie()) {
823 // Lalala, IE does not allow more than 31 linked CSS files from main document.
824 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
, 'type'=>'ie', 'subtype'=>'plugins'));
825 foreach ($css['parents'] as $parent=>$sheets) {
826 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
827 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
829 if ($this->get_scss_property()) {
830 // No need to define the type as IE here.
831 $urls[] = new moodle_url($baseurl, array('theme' => $this->name
, 'type' => 'scss'));
832 } else if (!empty($this->lessfile
)) {
833 // No need to define the type as IE here.
834 $urls[] = new moodle_url($baseurl, array('theme' => $this->name
, 'type' => 'less'));
836 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
, 'type'=>'ie', 'subtype'=>'theme'));
839 foreach ($css['plugins'] as $plugin=>$unused) {
840 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
,'type'=>'plugin', 'subtype'=>$plugin));
842 foreach ($css['parents'] as $parent=>$sheets) {
843 foreach ($sheets as $sheet=>$unused2) {
844 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name
,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
847 foreach ($css['theme'] as $sheet => $filename) {
848 if ($sheet === self
::SCSS_KEY
) {
849 // This is the theme SCSS file.
850 $urls[] = new moodle_url($baseurl, array('theme' => $this->name
, 'type' => 'scss'));
851 } else if ($sheet === $this->lessfile
) {
852 // This is the theme LESS file.
853 $urls[] = new moodle_url($baseurl, array('theme' => $this->name
, 'type' => 'less'));
855 // Sheet first in order to make long urls easier to read.
856 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name
, 'type'=>'theme'));
866 * Get the whole css stylesheet for production mode.
868 * NOTE: this method is not expected to be used from any addons.
870 * @return string CSS markup compressed
872 public function get_css_content() {
875 foreach ($this->get_css_files(false) as $type => $value) {
876 foreach ($value as $identifier => $val) {
877 if (is_array($val)) {
878 foreach ($val as $v) {
879 $csscontent .= file_get_contents($v) . "\n";
882 if ($type === 'theme' && $identifier === self
::SCSS_KEY
) {
883 // We need the content from SCSS because this is the SCSS file from the theme.
884 $csscontent .= $this->get_css_content_from_scss(false);
885 } else if ($type === 'theme' && $identifier === $this->lessfile
) {
886 // We need the content from LESS because this is the LESS file from the theme.
887 $csscontent .= $this->get_css_content_from_less(false);
889 $csscontent .= file_get_contents($val) . "\n";
894 $csscontent = $this->post_process($csscontent);
895 $csscontent = core_minify
::css($csscontent);
901 * Get the theme designer css markup,
902 * the parameters are coming from css_urls().
904 * NOTE: this method is not expected to be used from any addons.
906 * @param string $type
907 * @param string $subtype
908 * @param string $sheet
909 * @return string CSS markup
911 public function get_css_content_debug($type, $subtype, $sheet) {
913 if ($type === 'scss') {
914 // The SCSS file of the theme is requested.
915 $csscontent = $this->get_css_content_from_scss(true);
916 if ($csscontent !== false) {
917 return $this->post_process($csscontent);
920 } else if ($type === 'less') {
921 // The LESS file of the theme is requested.
922 $csscontent = $this->get_css_content_from_less(true);
923 if ($csscontent !== false) {
924 return $this->post_process($csscontent);
930 $css = $this->get_css_files(true);
932 if ($type === 'ie') {
933 // IE is a sloppy browser with weird limits, sorry.
934 if ($subtype === 'plugins') {
935 $cssfiles = $css['plugins'];
937 } else if ($subtype === 'parents') {
939 // Do not bother with the empty parent here.
941 // Build up the CSS for that parent so we can serve it as one file.
942 foreach ($css[$subtype][$sheet] as $parent => $css) {
946 } else if ($subtype === 'theme') {
947 $cssfiles = $css['theme'];
948 foreach ($cssfiles as $key => $value) {
949 if (in_array($key, [$this->lessfile
, self
::SCSS_KEY
])) {
950 // Remove the LESS/SCSS file from the theme CSS files.
951 // The LESS/SCSS files use the type 'less' or 'scss', not 'ie'.
952 unset($cssfiles[$key]);
957 } else if ($type === 'plugin') {
958 if (isset($css['plugins'][$subtype])) {
959 $cssfiles[] = $css['plugins'][$subtype];
962 } else if ($type === 'parent') {
963 if (isset($css['parents'][$subtype][$sheet])) {
964 $cssfiles[] = $css['parents'][$subtype][$sheet];
967 } else if ($type === 'theme') {
968 if (isset($css['theme'][$sheet])) {
969 $cssfiles[] = $css['theme'][$sheet];
974 foreach ($cssfiles as $file) {
975 $contents = file_get_contents($file);
976 $contents = $this->post_process($contents);
977 $comment = "/** Path: $type $subtype $sheet.' **/\n";
979 $csscontent .= $comment.$stats.$contents."\n\n";
986 * Get the whole css stylesheet for editor iframe.
988 * NOTE: this method is not expected to be used from any addons.
990 * @return string CSS markup
992 public function get_css_content_editor() {
993 // Do not bother to optimise anything here, just very basic stuff.
994 $cssfiles = $this->editor_css_files();
996 foreach ($cssfiles as $file) {
997 $css .= file_get_contents($file)."\n";
999 return $this->post_process($css);
1003 * Returns an array of organised CSS files required for this output.
1005 * @param bool $themedesigner
1006 * @return array nested array of file paths
1008 protected function get_css_files($themedesigner) {
1012 $cachekey = 'cssfiles';
1013 if ($themedesigner) {
1014 require_once($CFG->dirroot
.'/lib/csslib.php');
1015 // We need some kind of caching here because otherwise the page navigation becomes
1016 // way too slow in theme designer mode. Feel free to create full cache definition later...
1017 $cache = cache
::make_from_params(cache_store
::MODE_APPLICATION
, 'core', 'themedesigner', array('theme' => $this->name
));
1018 if ($files = $cache->get($cachekey)) {
1019 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME
) {
1020 unset($files['created']);
1026 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
1028 // Get all plugin sheets.
1029 $excludes = $this->resolve_excludes('plugins_exclude_sheets');
1030 if ($excludes !== true) {
1031 foreach (core_component
::get_plugin_types() as $type=>$unused) {
1032 if ($type === 'theme' ||
(!empty($excludes[$type]) and $excludes[$type] === true)) {
1035 $plugins = core_component
::get_plugin_list($type);
1036 foreach ($plugins as $plugin=>$fulldir) {
1037 if (!empty($excludes[$type]) and is_array($excludes[$type])
1038 and in_array($plugin, $excludes[$type])) {
1042 // Get the CSS from the plugin.
1043 $sheetfile = "$fulldir/styles.css";
1044 if (is_readable($sheetfile)) {
1045 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
1048 // Create a list of candidate sheets from parents (direct parent last) and current theme.
1049 $candidates = array();
1050 foreach (array_reverse($this->parent_configs
) as $parent_config) {
1051 $candidates[] = $parent_config->name
;
1053 $candidates[] = $this->name
;
1055 // Add the sheets found.
1056 foreach ($candidates as $candidate) {
1057 $sheetthemefile = "$fulldir/styles_{$candidate}.css";
1058 if (is_readable($sheetthemefile)) {
1059 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile;
1066 // Find out wanted parent sheets.
1067 $excludes = $this->resolve_excludes('parents_exclude_sheets');
1068 if ($excludes !== true) {
1069 foreach (array_reverse($this->parent_configs
) as $parent_config) { // Base first, the immediate parent last.
1070 $parent = $parent_config->name
;
1071 if (empty($parent_config->sheets
) ||
(!empty($excludes[$parent]) and $excludes[$parent] === true)) {
1074 foreach ($parent_config->sheets
as $sheet) {
1075 if (!empty($excludes[$parent]) && is_array($excludes[$parent])
1076 && in_array($sheet, $excludes[$parent])) {
1080 // We never refer to the parent LESS files.
1081 $sheetfile = "$parent_config->dir/style/$sheet.css";
1082 if (is_readable($sheetfile)) {
1083 $cssfiles['parents'][$parent][$sheet] = $sheetfile;
1090 // Current theme sheets and less file.
1091 // We first add the SCSS, or LESS file because we want the CSS ones to
1092 // be included after the SCSS/LESS code. However, if both the LESS file
1093 // and a CSS file share the same name, the CSS file is ignored.
1094 if ($this->get_scss_property()) {
1095 $cssfiles['theme'][self
::SCSS_KEY
] = true;
1096 } else if (!empty($this->lessfile
)) {
1097 $sheetfile = "{$this->dir}/less/{$this->lessfile}.less";
1098 if (is_readable($sheetfile)) {
1099 $cssfiles['theme'][$this->lessfile
] = $sheetfile;
1102 if (is_array($this->sheets
)) {
1103 foreach ($this->sheets
as $sheet) {
1104 $sheetfile = "$this->dir/style/$sheet.css";
1105 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) {
1106 $cssfiles['theme'][$sheet] = $sheetfile;
1113 $files['created'] = time();
1114 $cache->set($cachekey, $files);
1120 * Return the CSS content generated from LESS the file.
1122 * @param bool $themedesigner True if theme designer is enabled.
1123 * @return bool|string Return false when the compilation failed. Else the compiled string.
1125 protected function get_css_content_from_less($themedesigner) {
1128 $lessfile = $this->lessfile
;
1129 if (!$lessfile ||
!is_readable($this->dir
. '/less/' . $lessfile . '.less')) {
1130 throw new coding_exception('The theme did not define a LESS file, or it is not readable.');
1133 // We might need more memory/time to do this, so let's play safe.
1134 raise_memory_limit(MEMORY_EXTRA
);
1135 core_php_time_limit
::raise(300);
1138 $files = $this->get_css_files($themedesigner);
1140 // Get the LESS file path.
1141 $themelessfile = $files['theme'][$lessfile];
1143 // Setup compiler options.
1145 // We need to set the import directory to where $lessfile is.
1146 'import_dirs' => array(dirname($themelessfile) => '/'),
1147 // Always disable default caching.
1148 'cache_method' => false,
1149 // Disable the relative URLs, we have post_process() to handle that.
1150 'relativeUrls' => false,
1153 if ($themedesigner) {
1154 // Add the sourceMap inline to ensure that it is atomically generated.
1155 $options['sourceMap'] = true;
1156 $options['sourceMapBasepath'] = $CFG->dirroot
;
1157 $options['sourceMapRootpath'] = $CFG->wwwroot
;
1160 // Instantiate the compiler.
1161 $compiler = new core_lessc($options);
1164 $compiler->parse_file_content($themelessfile);
1166 // Get the callbacks.
1167 $compiler->parse($this->get_extra_less_code());
1168 $compiler->ModifyVars($this->get_less_variables());
1171 $compiled = $compiler->getCss();
1173 } catch (Less_Exception_Parser
$e) {
1175 debugging('Error while compiling LESS ' . $lessfile . ' file: ' . $e->getMessage(), DEBUG_DEVELOPER
);
1178 // Try to save memory.
1186 * Return the CSS content generated from the SCSS file.
1188 * @param bool $themedesigner True if theme designer is enabled.
1189 * @return bool|string Return false when the compilation failed. Else the compiled string.
1191 protected function get_css_content_from_scss($themedesigner) {
1194 list($paths, $scss) = $this->get_scss_property();
1196 throw new coding_exception('The theme did not define a SCSS file, or it is not readable.');
1199 // We might need more memory/time to do this, so let's play safe.
1200 raise_memory_limit(MEMORY_EXTRA
);
1201 core_php_time_limit
::raise(300);
1203 // Set-up the compiler.
1204 $compiler = new core_scss();
1205 $compiler->prepend_raw_scss($this->get_pre_scss_code());
1206 if (is_string($scss)) {
1207 $compiler->set_file($scss);
1209 $compiler->append_raw_scss($scss($this));
1210 $compiler->setImportPaths($paths);
1212 $compiler->append_raw_scss($this->get_extra_scss_code());
1216 $compiled = $compiler->to_css();
1218 } catch (\Leafo\ScssPhp\Exception
$e) {
1220 debugging('Error while compiling SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER
);
1223 // Try to save memory.
1231 * Return extra LESS variables to use when compiling.
1233 * @return array Where keys are the variable names (omitting the @), and the values are the value.
1235 protected function get_less_variables() {
1236 $variables = array();
1238 // Getting all the candidate functions.
1239 $candidates = array();
1240 foreach ($this->parent_configs
as $parent_config) {
1241 if (!isset($parent_config->lessvariablescallback
)) {
1244 $candidates[] = $parent_config->lessvariablescallback
;
1246 $candidates[] = $this->lessvariablescallback
;
1248 // Calling the functions.
1249 foreach ($candidates as $function) {
1250 if (function_exists($function)) {
1251 $vars = $function($this);
1252 if (!is_array($vars)) {
1253 debugging('Callback ' . $function . ' did not return an array() as expected', DEBUG_DEVELOPER
);
1256 $variables = array_merge($variables, $vars);
1264 * Return extra LESS code to add when compiling.
1266 * This is intended to be used by themes to inject some LESS code
1267 * before it gets compiled. If you want to inject variables you
1268 * should use {@link self::get_less_variables()}.
1270 * @return string The LESS code to inject.
1272 protected function get_extra_less_code() {
1275 // Getting all the candidate functions.
1276 $candidates = array();
1277 foreach ($this->parent_configs
as $parent_config) {
1278 if (!isset($parent_config->extralesscallback
)) {
1281 $candidates[] = $parent_config->extralesscallback
;
1283 $candidates[] = $this->extralesscallback
;
1285 // Calling the functions.
1286 foreach ($candidates as $function) {
1287 if (function_exists($function)) {
1288 $content .= "\n/** Extra LESS from $function **/\n" . $function($this) . "\n";
1296 * Return extra SCSS code to add when compiling.
1298 * This is intended to be used by themes to inject some SCSS code
1299 * before it gets compiled. If you want to inject variables you
1300 * should use {@link self::get_scss_variables()}.
1302 * @return string The SCSS code to inject.
1304 protected function get_extra_scss_code() {
1307 // Getting all the candidate functions.
1308 $candidates = array();
1309 foreach ($this->parent_configs
as $parent_config) {
1310 if (!isset($parent_config->extrascsscallback
)) {
1313 $candidates[] = $parent_config->extrascsscallback
;
1315 $candidates[] = $this->extrascsscallback
;
1317 // Calling the functions.
1318 foreach ($candidates as $function) {
1319 if (function_exists($function)) {
1320 $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n";
1328 * SCSS code to prepend when compiling.
1330 * This is intended to be used by themes to inject SCSS code before it gets compiled.
1332 * @return string The SCSS code to inject.
1334 protected function get_pre_scss_code() {
1337 // Getting all the candidate functions.
1338 $candidates = array();
1339 foreach ($this->parent_configs
as $parent_config) {
1340 if (!isset($parent_config->prescsscallback
)) {
1343 $candidates[] = $parent_config->prescsscallback
;
1345 $candidates[] = $this->prescsscallback
;
1347 // Calling the functions.
1348 foreach ($candidates as $function) {
1349 if (function_exists($function)) {
1350 $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n";
1358 * Get the SCSS property.
1360 * This resolves whether a SCSS file (or content) has to be used when generating
1361 * the stylesheet for the theme. It will look at parents themes and check the
1362 * SCSS properties there.
1364 * @return False when SCSS is not used.
1365 * An array with the import paths, and the path to the SCSS file or Closure as second.
1367 public function get_scss_property() {
1368 if ($this->scsscache
=== null) {
1369 $configs = [$this] +
$this->parent_configs
;
1372 foreach ($configs as $config) {
1373 $path = "{$config->dir}/scss";
1375 // We collect the SCSS property until we've found one.
1376 if (empty($scss) && !empty($config->scss
)) {
1377 $candidate = is_string($config->scss
) ?
"{$path}/{$config->scss}.scss" : $config->scss
;
1378 if ($candidate instanceof Closure
) {
1380 } else if (is_string($candidate) && is_readable($candidate)) {
1385 // We collect the import paths once we've found a SCSS property.
1386 if ($scss && is_dir($path)) {
1392 $this->scsscache
= $scss !== null ?
[$paths, $scss] : false;
1395 return $this->scsscache
;
1399 * Generate a URL to the file that serves theme JavaScript files.
1401 * If we determine that the theme has no relevant files, then we return
1402 * early with a null value.
1404 * @param bool $inhead true means head url, false means footer
1405 * @return moodle_url|null
1407 public function javascript_url($inhead) {
1410 $rev = theme_get_revision();
1411 $params = array('theme'=>$this->name
,'rev'=>$rev);
1412 $params['type'] = $inhead ?
'head' : 'footer';
1414 // Return early if there are no files to serve
1415 if (count($this->javascript_files($params['type'])) === 0) {
1419 if (!empty($CFG->slasharguments
) and $rev > 0) {
1420 $url = new moodle_url("$CFG->httpswwwroot/theme/javascript.php");
1421 $url->set_slashargument('/'.$this->name
.'/'.$rev.'/'.$params['type'], 'noparam', true);
1424 return new moodle_url($CFG->httpswwwroot
.'/theme/javascript.php', $params);
1429 * Get the URL's for the JavaScript files used by this theme.
1430 * They won't be served directly, instead they'll be mediated through
1431 * theme/javascript.php.
1433 * @param string $type Either javascripts_footer, or javascripts
1436 public function javascript_files($type) {
1437 if ($type === 'footer') {
1438 $type = 'javascripts_footer';
1440 $type = 'javascripts';
1444 // find out wanted parent javascripts
1445 $excludes = $this->resolve_excludes('parents_exclude_javascripts');
1446 if ($excludes !== true) {
1447 foreach (array_reverse($this->parent_configs
) as $parent_config) { // base first, the immediate parent last
1448 $parent = $parent_config->name
;
1449 if (empty($parent_config->$type)) {
1452 if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
1455 foreach ($parent_config->$type as $javascript) {
1456 if (!empty($excludes[$parent]) and is_array($excludes[$parent])
1457 and in_array($javascript, $excludes[$parent])) {
1460 $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
1461 if (is_readable($javascriptfile)) {
1462 $js[] = $javascriptfile;
1468 // current theme javascripts
1469 if (is_array($this->$type)) {
1470 foreach ($this->$type as $javascript) {
1471 $javascriptfile = "$this->dir/javascript/$javascript.js";
1472 if (is_readable($javascriptfile)) {
1473 $js[] = $javascriptfile;
1481 * Resolves an exclude setting to the themes setting is applicable or the
1482 * setting of its closest parent.
1484 * @param string $variable The name of the setting the exclude setting to resolve
1485 * @param string $default
1488 protected function resolve_excludes($variable, $default = null) {
1489 $setting = $default;
1490 if (is_array($this->{$variable}) or $this->{$variable} === true) {
1491 $setting = $this->{$variable};
1493 foreach ($this->parent_configs
as $parent_config) { // the immediate parent first, base last
1494 if (!isset($parent_config->{$variable})) {
1497 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
1498 $setting = $parent_config->{$variable};
1507 * Returns the content of the one huge javascript file merged from all theme javascript files.
1512 public function javascript_content($type) {
1513 $jsfiles = $this->javascript_files($type);
1515 foreach ($jsfiles as $jsfile) {
1516 $js .= file_get_contents($jsfile)."\n";
1522 * Post processes CSS.
1524 * This method post processes all of the CSS before it is served for this theme.
1525 * This is done so that things such as image URL's can be swapped in and to
1526 * run any specific CSS post process method the theme has requested.
1527 * This allows themes to use CSS settings.
1529 * @param string $css The CSS to process.
1530 * @return string The processed CSS.
1532 public function post_process($css) {
1533 // now resolve all image locations
1534 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER
)) {
1535 $replaced = array();
1536 foreach ($matches as $match) {
1537 if (isset($replaced[$match[0]])) {
1540 $replaced[$match[0]] = true;
1541 $imagename = $match[2];
1542 $component = rtrim($match[1], '|');
1543 $imageurl = $this->pix_url($imagename, $component)->out(false);
1544 // we do not need full url because the image.php is always in the same dir
1545 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl);
1546 $css = str_replace($match[0], $imageurl, $css);
1550 // Now resolve all font locations.
1551 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER
)) {
1552 $replaced = array();
1553 foreach ($matches as $match) {
1554 if (isset($replaced[$match[0]])) {
1557 $replaced[$match[0]] = true;
1558 $fontname = $match[2];
1559 $component = rtrim($match[1], '|');
1560 $fonturl = $this->font_url($fontname, $component)->out(false);
1561 // We do not need full url because the font.php is always in the same dir.
1562 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl);
1563 $css = str_replace($match[0], $fonturl, $css);
1567 // Now resolve all theme settings or do any other postprocessing.
1568 // This needs to be done before calling core parser, since the parser strips [[settings]] tags.
1569 $csspostprocess = $this->csspostprocess
;
1570 if (function_exists($csspostprocess)) {
1571 $css = $csspostprocess($css, $this);
1574 // Post processing using an object representation of CSS.
1575 $treeprocessor = $this->get_css_tree_post_processor();
1576 $needsparsing = !empty($treeprocessor) ||
!empty($this->rtlmode
);
1577 if ($needsparsing) {
1579 // We might need more memory/time to do this, so let's play safe.
1580 raise_memory_limit(MEMORY_EXTRA
);
1581 core_php_time_limit
::raise(300);
1583 $parser = new core_cssparser($css);
1584 $csstree = $parser->parse();
1587 if ($this->rtlmode
) {
1588 $this->rtlize($csstree);
1591 if ($treeprocessor) {
1592 $treeprocessor($csstree, $this);
1595 $css = $csstree->render();
1603 * Flip a stylesheet to RTL.
1605 * @param Object $csstree The parsed CSS tree structure to flip.
1608 protected function rtlize($csstree) {
1609 $rtlcss = new core_rtlcss($csstree);
1614 * Return the URL for an image
1616 * @param string $imagename the name of the icon.
1617 * @param string $component specification of one plugin like in get_string()
1618 * @return moodle_url
1620 public function pix_url($imagename, $component) {
1623 $params = array('theme'=>$this->name
);
1624 $svg = $this->use_svg_icons();
1626 if (empty($component) or $component === 'moodle' or $component === 'core') {
1627 $params['component'] = 'core';
1629 $params['component'] = $component;
1632 $rev = theme_get_revision();
1634 $params['rev'] = $rev;
1637 $params['image'] = $imagename;
1639 $url = new moodle_url("$CFG->httpswwwroot/theme/image.php");
1640 if (!empty($CFG->slasharguments
) and $rev > 0) {
1641 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image'];
1643 // We add a simple /_s to the start of the path.
1644 // The underscore is used to ensure that it isn't a valid theme name.
1645 $path = '/_s'.$path;
1647 $url->set_slashargument($path, 'noparam', true);
1650 // We add an SVG param so that we know not to serve SVG images.
1651 // We do this because all modern browsers support SVG and this param will one day be removed.
1652 $params['svg'] = '0';
1654 $url->params($params);
1661 * Return the URL for a font
1663 * @param string $font the name of the font (including extension).
1664 * @param string $component specification of one plugin like in get_string()
1665 * @return moodle_url
1667 public function font_url($font, $component) {
1670 $params = array('theme'=>$this->name
);
1672 if (empty($component) or $component === 'moodle' or $component === 'core') {
1673 $params['component'] = 'core';
1675 $params['component'] = $component;
1678 $rev = theme_get_revision();
1680 $params['rev'] = $rev;
1683 $params['font'] = $font;
1685 $url = new moodle_url("$CFG->httpswwwroot/theme/font.php");
1686 if (!empty($CFG->slasharguments
) and $rev > 0) {
1687 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font'];
1688 $url->set_slashargument($path, 'noparam', true);
1690 $url->params($params);
1697 * Returns URL to the stored file via pluginfile.php.
1699 * Note the theme must also implement pluginfile.php handler,
1700 * theme revision is used instead of the itemid.
1702 * @param string $setting
1703 * @param string $filearea
1704 * @return string protocol relative URL or null if not present
1706 public function setting_file_url($setting, $filearea) {
1709 if (empty($this->settings
->$setting)) {
1713 $component = 'theme_'.$this->name
;
1714 $itemid = theme_get_revision();
1715 $filepath = $this->settings
->$setting;
1716 $syscontext = context_system
::instance();
1718 $url = moodle_url
::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath);
1720 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
1721 // Note: unfortunately moodle_url does not support //urls yet.
1723 $url = preg_replace('|^https?://|i', '//', $url->out(false));
1729 * Serve the theme setting file.
1731 * @param string $filearea
1732 * @param array $args
1733 * @param bool $forcedownload
1734 * @param array $options
1735 * @return bool may terminate if file not found or donotdie not specified
1737 public function setting_file_serve($filearea, $args, $forcedownload, $options) {
1739 require_once("$CFG->libdir/filelib.php");
1741 $syscontext = context_system
::instance();
1742 $component = 'theme_'.$this->name
;
1744 $revision = array_shift($args);
1745 if ($revision < 0) {
1748 $lifetime = 60*60*24*60;
1749 // By default, theme files must be cache-able by both browsers and proxies.
1750 if (!array_key_exists('cacheability', $options)) {
1751 $options['cacheability'] = 'public';
1755 $fs = get_file_storage();
1756 $relativepath = implode('/', $args);
1758 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}";
1759 $fullpath = rtrim($fullpath, '/');
1760 if ($file = $fs->get_file_by_hash(sha1($fullpath))) {
1761 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
1764 send_file_not_found();
1769 * Resolves the real image location.
1771 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG
1772 * and we need a way in which to turn it off.
1773 * By default SVG won't be used unless asked for. This is done for two reasons:
1774 * 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
1775 * browser supports SVG.
1776 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded
1777 * by the user due to security concerns.
1779 * @param string $image name of image, may contain relative path
1780 * @param string $component
1781 * @param bool $svg If set to true SVG images will also be looked for.
1782 * @return string full file path
1784 public function resolve_image_location($image, $component, $svg = false) {
1787 if (!is_bool($svg)) {
1788 // If $svg isn't a bool then we need to decide for ourselves.
1789 $svg = $this->use_svg_icons();
1792 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1793 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) {
1796 foreach (array_reverse($this->parent_configs
) as $parent_config) { // base first, the immediate parent last
1797 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) {
1801 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) {
1804 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) {
1809 } else if ($component === 'theme') { //exception
1810 if ($image === 'favicon') {
1811 return "$this->dir/pix/favicon.ico";
1813 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) {
1816 foreach (array_reverse($this->parent_configs
) as $parent_config) { // base first, the immediate parent last
1817 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) {
1824 if (strpos($component, '_') === false) {
1825 $component = 'mod_'.$component;
1827 list($type, $plugin) = explode('_', $component, 2);
1829 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1832 foreach (array_reverse($this->parent_configs
) as $parent_config) { // base first, the immediate parent last
1833 if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image", $svg)) {
1837 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) {
1840 $dir = core_component
::get_plugin_directory($type, $plugin);
1841 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) {
1849 * Resolves the real font location.
1851 * @param string $font name of font file
1852 * @param string $component
1853 * @return string full file path
1855 public function resolve_font_location($font, $component) {
1858 if ($component === 'moodle' or $component === 'core' or empty($component)) {
1859 if (file_exists("$this->dir/fonts_core/$font")) {
1860 return "$this->dir/fonts_core/$font";
1862 foreach (array_reverse($this->parent_configs
) as $parent_config) { // Base first, the immediate parent last.
1863 if (file_exists("$parent_config->dir/fonts_core/$font")) {
1864 return "$parent_config->dir/fonts_core/$font";
1867 if (file_exists("$CFG->dataroot/fonts/$font")) {
1868 return "$CFG->dataroot/fonts/$font";
1870 if (file_exists("$CFG->dirroot/lib/fonts/$font")) {
1871 return "$CFG->dirroot/lib/fonts/$font";
1875 } else if ($component === 'theme') { // Exception.
1876 if (file_exists("$this->dir/fonts/$font")) {
1877 return "$this->dir/fonts/$font";
1879 foreach (array_reverse($this->parent_configs
) as $parent_config) { // Base first, the immediate parent last.
1880 if (file_exists("$parent_config->dir/fonts/$font")) {
1881 return "$parent_config->dir/fonts/$font";
1887 if (strpos($component, '_') === false) {
1888 $component = 'mod_'.$component;
1890 list($type, $plugin) = explode('_', $component, 2);
1892 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) {
1893 return "$this->dir/fonts_plugins/$type/$plugin/$font";
1895 foreach (array_reverse($this->parent_configs
) as $parent_config) { // Base first, the immediate parent last.
1896 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) {
1897 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font";
1900 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) {
1901 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font";
1903 $dir = core_component
::get_plugin_directory($type, $plugin);
1904 if (file_exists("$dir/fonts/$font")) {
1905 return "$dir/fonts/$font";
1912 * Return true if we should look for SVG images as well.
1916 public function use_svg_icons() {
1918 if ($this->usesvg
=== null) {
1920 if (!isset($CFG->svgicons
)) {
1921 $this->usesvg
= core_useragent
::supports_svg();
1923 // Force them on/off depending upon the setting.
1924 $this->usesvg
= (bool)$CFG->svgicons
;
1927 return $this->usesvg
;
1931 * Forces the usesvg setting to either true or false, avoiding any decision making.
1933 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred.
1934 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;)
1936 * @param bool $setting True to force the use of svg when available, null otherwise.
1938 public function force_svg_use($setting) {
1939 $this->usesvg
= (bool)$setting;
1943 * Set to be in RTL mode.
1945 * This will likely be used when post processing the CSS before serving it.
1947 * @param bool $inrtl True when in RTL mode.
1949 public function set_rtl_mode($inrtl = true) {
1950 $this->rtlmode
= $inrtl;
1954 * Checks if file with any image extension exists.
1956 * The order to these images was adjusted prior to the release of 2.4
1957 * At that point the were the following image counts in Moodle core:
1959 * - png = 667 in pix dirs (1499 total)
1960 * - gif = 385 in pix dirs (606 total)
1961 * - jpg = 62 in pix dirs (74 total)
1962 * - jpeg = 0 in pix dirs (1 total)
1964 * There is work in progress to move towards SVG presently hence that has been prioritiesed.
1966 * @param string $filepath
1967 * @param bool $svg If set to true SVG images will also be looked for.
1968 * @return string image name with extension
1970 private static function image_exists($filepath, $svg = false) {
1971 if ($svg && file_exists("$filepath.svg")) {
1972 return "$filepath.svg";
1973 } else if (file_exists("$filepath.png")) {
1974 return "$filepath.png";
1975 } else if (file_exists("$filepath.gif")) {
1976 return "$filepath.gif";
1977 } else if (file_exists("$filepath.jpg")) {
1978 return "$filepath.jpg";
1979 } else if (file_exists("$filepath.jpeg")) {
1980 return "$filepath.jpeg";
1987 * Loads the theme config from config.php file.
1989 * @param string $themename
1990 * @param stdClass $settings from config_plugins table
1991 * @param boolean $parentscheck true to also check the parents. .
1992 * @return stdClass The theme configuration
1994 private static function find_theme_config($themename, $settings, $parentscheck = true) {
1995 // We have to use the variable name $THEME (upper case) because that
1996 // is what is used in theme config.php files.
1998 if (!$dir = theme_config
::find_theme_location($themename)) {
2002 $THEME = new stdClass();
2003 $THEME->name
= $themename;
2005 $THEME->settings
= $settings;
2007 global $CFG; // just in case somebody tries to use $CFG in theme config
2008 include("$THEME->dir/config.php");
2010 // verify the theme configuration is OK
2011 if (!is_array($THEME->parents
)) {
2012 // parents option is mandatory now
2015 // We use $parentscheck to only check the direct parents (avoid infinite loop).
2016 if ($parentscheck) {
2017 // Find all parent theme configs.
2018 foreach ($THEME->parents
as $parent) {
2019 $parentconfig = theme_config
::find_theme_config($parent, $settings, false);
2020 if (empty($parentconfig)) {
2031 * Finds the theme location and verifies the theme has all needed files
2032 * and is not obsoleted.
2034 * @param string $themename
2035 * @return string full dir path or null if not found
2037 private static function find_theme_location($themename) {
2040 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2041 $dir = "$CFG->dirroot/theme/$themename";
2043 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$themename/config.php")) {
2044 $dir = "$CFG->themedir/$themename";
2050 if (file_exists("$dir/styles.php")) {
2051 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
2059 * Get the renderer for a part of Moodle for this theme.
2061 * @param moodle_page $page the page we are rendering
2062 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
2063 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
2064 * @param string $target one of rendering target constants
2065 * @return renderer_base the requested renderer.
2067 public function get_renderer(moodle_page
$page, $component, $subtype = null, $target = null) {
2068 if (is_null($this->rf
)) {
2069 $classname = $this->rendererfactory
;
2070 $this->rf
= new $classname($this);
2073 return $this->rf
->get_renderer($page, $component, $subtype, $target);
2077 * Get the information from {@link $layouts} for this type of page.
2079 * @param string $pagelayout the the page layout name.
2080 * @return array the appropriate part of {@link $layouts}.
2082 protected function layout_info_for_page($pagelayout) {
2083 if (array_key_exists($pagelayout, $this->layouts
)) {
2084 return $this->layouts
[$pagelayout];
2086 debugging('Invalid page layout specified: ' . $pagelayout);
2087 return $this->layouts
['standard'];
2092 * Given the settings of this theme, and the page pagelayout, return the
2093 * full path of the page layout file to use.
2095 * Used by {@link core_renderer::header()}.
2097 * @param string $pagelayout the the page layout name.
2098 * @return string Full path to the lyout file to use
2100 public function layout_file($pagelayout) {
2103 $layoutinfo = $this->layout_info_for_page($pagelayout);
2104 $layoutfile = $layoutinfo['file'];
2106 if (array_key_exists('theme', $layoutinfo)) {
2107 $themes = array($layoutinfo['theme']);
2109 $themes = array_merge(array($this->name
),$this->parents
);
2112 foreach ($themes as $theme) {
2113 if ($dir = $this->find_theme_location($theme)) {
2114 $path = "$dir/layout/$layoutfile";
2116 // Check the template exists, return general base theme template if not.
2117 if (is_readable($path)) {
2123 debugging('Can not find layout file for: ' . $pagelayout);
2124 // fallback to standard normal layout
2125 return "$CFG->dirroot/theme/base/layout/general.php";
2129 * Returns auxiliary page layout options specified in layout configuration array.
2131 * @param string $pagelayout
2134 public function pagelayout_options($pagelayout) {
2135 $info = $this->layout_info_for_page($pagelayout);
2136 if (!empty($info['options'])) {
2137 return $info['options'];
2143 * Inform a block_manager about the block regions this theme wants on this
2146 * @param string $pagelayout the general type of the page.
2147 * @param block_manager $blockmanager the block_manger to set up.
2149 public function setup_blocks($pagelayout, $blockmanager) {
2150 $layoutinfo = $this->layout_info_for_page($pagelayout);
2151 if (!empty($layoutinfo['regions'])) {
2152 $blockmanager->add_regions($layoutinfo['regions'], false);
2153 $blockmanager->set_default_region($layoutinfo['defaultregion']);
2158 * Gets the visible name for the requested block region.
2160 * @param string $region The region name to get
2161 * @param string $theme The theme the region belongs to (may come from the parent theme)
2164 protected function get_region_name($region, $theme) {
2165 $regionstring = get_string('region-' . $region, 'theme_' . $theme);
2166 // A name exists in this theme, so use it
2167 if (substr($regionstring, 0, 1) != '[') {
2168 return $regionstring;
2171 // Otherwise, try to find one elsewhere
2172 // Check parents, if any
2173 foreach ($this->parents
as $parentthemename) {
2174 $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
2175 if (substr($regionstring, 0, 1) != '[') {
2176 return $regionstring;
2180 // Last resort, try the bootstrapbase theme for names
2181 return get_string('region-' . $region, 'theme_bootstrapbase');
2185 * Get the list of all block regions known to this theme in all templates.
2187 * @return array internal region name => human readable name.
2189 public function get_all_block_regions() {
2191 foreach ($this->layouts
as $layoutinfo) {
2192 foreach ($layoutinfo['regions'] as $region) {
2193 $regions[$region] = $this->get_region_name($region, $this->name
);
2200 * Returns the human readable name of the theme
2204 public function get_theme_name() {
2205 return get_string('pluginname', 'theme_'.$this->name
);
2209 * Returns the block render method.
2211 * It is set by the theme via:
2212 * $THEME->blockrendermethod = '...';
2214 * It can be one of two values, blocks or blocks_for_region.
2215 * It should be set to the method being used by the theme layouts.
2219 public function get_block_render_method() {
2220 if ($this->blockrendermethod
) {
2221 // Return the specified block render method.
2222 return $this->blockrendermethod
;
2224 // Its not explicitly set, check the parent theme configs.
2225 foreach ($this->parent_configs
as $config) {
2226 if (isset($config->blockrendermethod
)) {
2227 return $config->blockrendermethod
;
2230 // Default it to blocks.
2235 * Get the callable for CSS tree post processing.
2237 * @return string|null
2239 public function get_css_tree_post_processor() {
2240 $configs = [$this] +
$this->parent_configs
;
2241 foreach ($configs as $config) {
2242 if (!empty($config->csstreepostprocessor
) && is_callable($config->csstreepostprocessor
)) {
2243 return $config->csstreepostprocessor
;
2251 * This class keeps track of which HTML tags are currently open.
2253 * This makes it much easier to always generate well formed XHTML output, even
2254 * if execution terminates abruptly. Any time you output some opening HTML
2255 * without the matching closing HTML, you should push the necessary close tags
2258 * @copyright 2009 Tim Hunt
2259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2264 class xhtml_container_stack
{
2267 * @var array Stores the list of open containers.
2269 protected $opencontainers = array();
2272 * @var array In developer debug mode, stores a stack trace of all opens and
2273 * closes, so we can output helpful error messages when there is a mismatch.
2275 protected $log = array();
2278 * @var boolean Store whether we are developer debug mode. We need this in
2279 * several places including in the destructor where we may not have access to $CFG.
2281 protected $isdebugging;
2286 public function __construct() {
2288 $this->isdebugging
= $CFG->debugdeveloper
;
2292 * Push the close HTML for a recently opened container onto the stack.
2294 * @param string $type The type of container. This is checked when {@link pop()}
2295 * is called and must match, otherwise a developer debug warning is output.
2296 * @param string $closehtml The HTML required to close the container.
2298 public function push($type, $closehtml) {
2299 $container = new stdClass
;
2300 $container->type
= $type;
2301 $container->closehtml
= $closehtml;
2302 if ($this->isdebugging
) {
2303 $this->log('Open', $type);
2305 array_push($this->opencontainers
, $container);
2309 * Pop the HTML for the next closing container from the stack. The $type
2310 * must match the type passed when the container was opened, otherwise a
2311 * warning will be output.
2313 * @param string $type The type of container.
2314 * @return string the HTML required to close the container.
2316 public function pop($type) {
2317 if (empty($this->opencontainers
)) {
2318 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
2319 $this->output_log(), DEBUG_DEVELOPER
);
2323 $container = array_pop($this->opencontainers
);
2324 if ($container->type
!= $type) {
2325 debugging('<p>The type of container to be closed (' . $container->type
.
2326 ') does not match the type of the next open container (' . $type .
2327 '). This suggests there is a nesting problem.</p>' .
2328 $this->output_log(), DEBUG_DEVELOPER
);
2330 if ($this->isdebugging
) {
2331 $this->log('Close', $type);
2333 return $container->closehtml
;
2337 * Close all but the last open container. This is useful in places like error
2338 * handling, where you want to close all the open containers (apart from <body>)
2339 * before outputting the error message.
2341 * @param bool $shouldbenone assert that the stack should be empty now - causes a
2342 * developer debug warning if it isn't.
2343 * @return string the HTML required to close any open containers inside <body>.
2345 public function pop_all_but_last($shouldbenone = false) {
2346 if ($shouldbenone && count($this->opencontainers
) != 1) {
2347 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
2348 $this->output_log(), DEBUG_DEVELOPER
);
2351 while (count($this->opencontainers
) > 1) {
2352 $container = array_pop($this->opencontainers
);
2353 $output .= $container->closehtml
;
2359 * You can call this function if you want to throw away an instance of this
2360 * class without properly emptying the stack (for example, in a unit test).
2361 * Calling this method stops the destruct method from outputting a developer
2362 * debug warning. After calling this method, the instance can no longer be used.
2364 public function discard() {
2365 $this->opencontainers
= null;
2369 * Adds an entry to the log.
2371 * @param string $action The name of the action
2372 * @param string $type The type of action
2374 protected function log($action, $type) {
2375 $this->log
[] = '<li>' . $action . ' ' . $type . ' at:' .
2376 format_backtrace(debug_backtrace()) . '</li>';
2380 * Outputs the log's contents as a HTML list.
2382 * @return string HTML list of the log
2384 protected function output_log() {
2385 return '<ul>' . implode("\n", $this->log
) . '</ul>';