/lib/outputlib.php
PHP | 2683 lines | 1433 code | 290 blank | 960 comment | 278 complexity | 2bb13ab4038a63c421e7ff25dcaa9425 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, GPL-3.0, Apache-2.0, LGPL-2.1
Large files files are truncated, but you can click here to view the full file
- <?php
- // This file is part of Moodle - http://moodle.org/
- //
- // Moodle is free software: you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // Moodle is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License
- // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
- /**
- * Functions for generating the HTML that Moodle should output.
- *
- * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
- * for an overview.
- *
- * @copyright 2009 Tim Hunt
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- * @package core
- * @category output
- */
- defined('MOODLE_INTERNAL') || die();
- require_once($CFG->libdir.'/outputcomponents.php');
- require_once($CFG->libdir.'/outputactions.php');
- require_once($CFG->libdir.'/outputfactories.php');
- require_once($CFG->libdir.'/outputrenderers.php');
- require_once($CFG->libdir.'/outputrequirementslib.php');
- /**
- * Returns current theme revision number.
- *
- * @return int
- */
- function theme_get_revision() {
- global $CFG;
- if (empty($CFG->themedesignermode)) {
- if (empty($CFG->themerev)) {
- // This only happens during install. It doesn't matter what themerev we use as long as it's positive.
- return 1;
- } else {
- return $CFG->themerev;
- }
- } else {
- return -1;
- }
- }
- /**
- * Returns current theme sub revision number. This is the revision for
- * this theme exclusively, not the global theme revision.
- *
- * @param string $themename The non-frankenstyle name of the theme
- * @return int
- */
- function theme_get_sub_revision_for_theme($themename) {
- global $CFG;
- if (empty($CFG->themedesignermode)) {
- $pluginname = "theme_{$themename}";
- $revision = during_initial_install() ? null : get_config($pluginname, 'themerev');
- if (empty($revision)) {
- // This only happens during install. It doesn't matter what themerev we use as long as it's positive.
- return 1;
- } else {
- return $revision;
- }
- } else {
- return -1;
- }
- }
- /**
- * Calculates and returns the next theme revision number.
- *
- * @return int
- */
- function theme_get_next_revision() {
- global $CFG;
- $next = time();
- if (isset($CFG->themerev) and $next <= $CFG->themerev and $CFG->themerev - $next < 60*60) {
- // This resolves problems when reset is requested repeatedly within 1s,
- // the < 1h condition prevents accidental switching to future dates
- // because we might not recover from it.
- $next = $CFG->themerev+1;
- }
- return $next;
- }
- /**
- * Calculates and returns the next theme revision number.
- *
- * @param string $themename The non-frankenstyle name of the theme
- * @return int
- */
- function theme_get_next_sub_revision_for_theme($themename) {
- global $CFG;
- $next = time();
- $current = theme_get_sub_revision_for_theme($themename);
- if ($next <= $current and $current - $next < 60 * 60) {
- // This resolves problems when reset is requested repeatedly within 1s,
- // the < 1h condition prevents accidental switching to future dates
- // because we might not recover from it.
- $next = $current + 1;
- }
- return $next;
- }
- /**
- * Sets the current theme revision number.
- *
- * @param int $revision The new theme revision number
- */
- function theme_set_revision($revision) {
- set_config('themerev', $revision);
- }
- /**
- * Sets the current theme revision number for a specific theme.
- * This does not affect the global themerev value.
- *
- * @param string $themename The non-frankenstyle name of the theme
- * @param int $revision The new theme revision number
- */
- function theme_set_sub_revision_for_theme($themename, $revision) {
- set_config('themerev', $revision, "theme_{$themename}");
- }
- /**
- * Get the path to a theme config.php file.
- *
- * @param string $themename The non-frankenstyle name of the theme to check
- */
- function theme_get_config_file_path($themename) {
- global $CFG;
- if (file_exists("{$CFG->dirroot}/theme/{$themename}/config.php")) {
- return "{$CFG->dirroot}/theme/{$themename}/config.php";
- } else if (!empty($CFG->themedir) and file_exists("{$CFG->themedir}/{$themename}/config.php")) {
- return "{$CFG->themedir}/{$themename}/config.php";
- } else {
- return null;
- }
- }
- /**
- * Get the path to the local cached CSS file.
- *
- * @param string $themename The non-frankenstyle theme name.
- * @param int $globalrevision The global theme revision.
- * @param int $themerevision The theme specific revision.
- * @param string $direction Either 'ltr' or 'rtl' (case sensitive).
- */
- function theme_get_css_filename($themename, $globalrevision, $themerevision, $direction) {
- global $CFG;
- $path = "{$CFG->localcachedir}/theme/{$globalrevision}/{$themename}/css";
- $filename = $direction == 'rtl' ? "all-rtl_{$themerevision}" : "all_{$themerevision}";
- return "{$path}/{$filename}.css";
- }
- /**
- * Generates and saves the CSS files for the given theme configs.
- *
- * @param theme_config[] $themeconfigs An array of theme_config instances.
- * @param array $directions Must be a subset of ['rtl', 'ltr'].
- * @param bool $cache Should the generated files be stored in local cache.
- * @return array The built theme content in a multi-dimensional array of name => direction => content
- */
- function theme_build_css_for_themes($themeconfigs = [], $directions = ['rtl', 'ltr'],
- $cache = true, $mtraceprogress = false): array {
- global $CFG;
- if (empty($themeconfigs)) {
- return [];
- }
- require_once("{$CFG->libdir}/csslib.php");
- $themescss = [];
- $themerev = theme_get_revision();
- // Make sure the local cache directory exists.
- make_localcache_directory('theme');
- foreach ($themeconfigs as $themeconfig) {
- $themecss = [];
- $oldrevision = theme_get_sub_revision_for_theme($themeconfig->name);
- $newrevision = theme_get_next_sub_revision_for_theme($themeconfig->name);
- // First generate all the new css.
- foreach ($directions as $direction) {
- if ($mtraceprogress) {
- $timestart = microtime(true);
- mtrace('Building theme CSS for ' . $themeconfig->name . ' [' .
- $direction . '] ...', '');
- }
- // Lock it on. Technically we should build all themes for SVG and no SVG - but ie9 is out of support.
- $themeconfig->force_svg_use(true);
- $themeconfig->set_rtl_mode(($direction === 'rtl'));
- $themecss[$direction] = $themeconfig->get_css_content();
- if ($cache) {
- $themeconfig->set_css_content_cache($themecss[$direction]);
- $filename = theme_get_css_filename($themeconfig->name, $themerev, $newrevision, $direction);
- css_store_css($themeconfig, $filename, $themecss[$direction]);
- }
- if ($mtraceprogress) {
- mtrace(' done in ' . round(microtime(true) - $timestart, 2) . ' seconds.');
- }
- }
- $themescss[$themeconfig->name] = $themecss;
- if ($cache) {
- // Only update the theme revision after we've successfully created the
- // new CSS cache.
- theme_set_sub_revision_for_theme($themeconfig->name, $newrevision);
- // Now purge old files. We must purge all old files in the local cache
- // because we've incremented the theme sub revision. This will leave any
- // files with the old revision inaccessbile so we might as well removed
- // them from disk.
- foreach (['ltr', 'rtl'] as $direction) {
- $oldcss = theme_get_css_filename($themeconfig->name, $themerev, $oldrevision, $direction);
- if (file_exists($oldcss)) {
- unlink($oldcss);
- }
- }
- }
- }
- return $themescss;
- }
- /**
- * Invalidate all server and client side caches.
- *
- * This method deletes the physical directory that is used to cache the theme
- * files used for serving.
- * Because it deletes the main theme cache directory all themes are reset by
- * this function.
- */
- function theme_reset_all_caches() {
- global $CFG, $PAGE;
- require_once("{$CFG->libdir}/filelib.php");
- $next = theme_get_next_revision();
- theme_set_revision($next);
- if (!empty($CFG->themedesignermode)) {
- $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner');
- $cache->purge();
- }
- // Purge compiled post processed css.
- cache::make('core', 'postprocessedcss')->purge();
- // Delete all old theme localcaches.
- $themecachedirs = glob("{$CFG->localcachedir}/theme/*", GLOB_ONLYDIR);
- foreach ($themecachedirs as $localcachedir) {
- fulldelete($localcachedir);
- }
- if ($PAGE) {
- $PAGE->reload_theme();
- }
- }
- /**
- * Reset static caches.
- *
- * This method indicates that all running cron processes should exit at the
- * next opportunity.
- */
- function theme_reset_static_caches() {
- \core\task\manager::clear_static_caches();
- }
- /**
- * Enable or disable theme designer mode.
- *
- * @param bool $state
- */
- function theme_set_designer_mod($state) {
- set_config('themedesignermode', (int)!empty($state));
- // Reset caches after switching mode so that any designer mode caches get purged too.
- theme_reset_all_caches();
- }
- /**
- * Checks if the given device has a theme defined in config.php.
- *
- * @return bool
- */
- function theme_is_device_locked($device) {
- global $CFG;
- $themeconfigname = core_useragent::get_device_type_cfg_var_name($device);
- return isset($CFG->config_php_settings[$themeconfigname]);
- }
- /**
- * Returns the theme named defined in config.php for the given device.
- *
- * @return string or null
- */
- function theme_get_locked_theme_for_device($device) {
- global $CFG;
- if (!theme_is_device_locked($device)) {
- return null;
- }
- $themeconfigname = core_useragent::get_device_type_cfg_var_name($device);
- return $CFG->config_php_settings[$themeconfigname];
- }
- /**
- * This class represents the configuration variables of a Moodle theme.
- *
- * All the variables with access: public below (with a few exceptions that are marked)
- * are the properties you can set in your themes config.php file.
- *
- * There are also some methods and protected variables that are part of the inner
- * workings of Moodle's themes system. If you are just editing a themes config.php
- * file, you can just ignore those, and the following information for developers.
- *
- * Normally, to create an instance of this class, you should use the
- * {@link theme_config::load()} factory method to load a themes config.php file.
- * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
- * will create one for you, accessible as $PAGE->theme.
- *
- * @copyright 2009 Tim Hunt
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- * @since Moodle 2.0
- * @package core
- * @category output
- */
- class theme_config {
- /**
- * @var string Default theme, used when requested theme not found.
- */
- const DEFAULT_THEME = 'boost';
- /** The key under which the SCSS file is stored amongst the CSS files. */
- const SCSS_KEY = '__SCSS__';
- /**
- * @var array You can base your theme on other themes by linking to the other theme as
- * parents. This lets you use the CSS and layouts from the other themes
- * (see {@link theme_config::$layouts}).
- * That makes it easy to create a new theme that is similar to another one
- * but with a few changes. In this themes CSS you only need to override
- * those rules you want to change.
- */
- public $parents;
- /**
- * @var array The names of all the stylesheets from this theme that you would
- * like included, in order. Give the names of the files without .css.
- */
- public $sheets = array();
- /**
- * @var array The names of all the stylesheets from parents that should be excluded.
- * true value may be used to specify all parents or all themes from one parent.
- * If no value specified value from parent theme used.
- */
- public $parents_exclude_sheets = null;
- /**
- * @var array List of plugin sheets to be excluded.
- * If no value specified value from parent theme used.
- */
- public $plugins_exclude_sheets = null;
- /**
- * @var array List of style sheets that are included in the text editor bodies.
- * Sheets from parent themes are used automatically and can not be excluded.
- */
- public $editor_sheets = array();
- /**
- * @var bool Whether a fallback version of the stylesheet will be used
- * whilst the final version is generated.
- */
- public $usefallback = false;
- /**
- * @var array The names of all the javascript files this theme that you would
- * like included from head, in order. Give the names of the files without .js.
- */
- public $javascripts = array();
- /**
- * @var array The names of all the javascript files this theme that you would
- * like included from footer, in order. Give the names of the files without .js.
- */
- public $javascripts_footer = array();
- /**
- * @var array The names of all the javascript files from parents that should
- * be excluded. true value may be used to specify all parents or all themes
- * from one parent.
- * If no value specified value from parent theme used.
- */
- public $parents_exclude_javascripts = null;
- /**
- * @var array Which file to use for each page layout.
- *
- * This is an array of arrays. The keys of the outer array are the different layouts.
- * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
- * 'popup', 'form', .... The most reliable way to get a complete list is to look at
- * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
- * That file also has a good example of how to set this setting.
- *
- * For each layout, the value in the outer array is an array that describes
- * how you want that type of page to look. For example
- * <pre>
- * $THEME->layouts = array(
- * // Most pages - if we encounter an unknown or a missing page type, this one is used.
- * 'standard' => array(
- * 'theme' = 'mytheme',
- * 'file' => 'normal.php',
- * 'regions' => array('side-pre', 'side-post'),
- * 'defaultregion' => 'side-post'
- * ),
- * // The site home page.
- * 'home' => array(
- * 'theme' = 'mytheme',
- * 'file' => 'home.php',
- * 'regions' => array('side-pre', 'side-post'),
- * 'defaultregion' => 'side-post'
- * ),
- * // ...
- * );
- * </pre>
- *
- * 'theme' name of the theme where is the layout located
- * 'file' is the layout file to use for this type of page.
- * layout files are stored in layout subfolder
- * 'regions' This lists the regions on the page where blocks may appear. For
- * each region you list here, your layout file must include a call to
- * <pre>
- * echo $OUTPUT->blocks_for_region($regionname);
- * </pre>
- * or equivalent so that the blocks are actually visible.
- *
- * 'defaultregion' If the list of regions is non-empty, then you must pick
- * one of the one of them as 'default'. This has two meanings. First, this is
- * where new blocks are added. Second, if there are any blocks associated with
- * the page, but in non-existent regions, they appear here. (Imaging, for example,
- * that someone added blocks using a different theme that used different region
- * names, and then switched to this theme.)
- */
- public $layouts = array();
- /**
- * @var string Name of the renderer factory class to use. Must implement the
- * {@link renderer_factory} interface.
- *
- * This is an advanced feature. Moodle output is generated by 'renderers',
- * you can customise the HTML that is output by writing custom renderers,
- * and then you need to specify 'renderer factory' so that Moodle can find
- * your renderers.
- *
- * There are some renderer factories supplied with Moodle. Please follow these
- * links to see what they do.
- * <ul>
- * <li>{@link standard_renderer_factory} - the default.</li>
- * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
- * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
- * </ul>
- */
- public $rendererfactory = 'standard_renderer_factory';
- /**
- * @var string Function to do custom CSS post-processing.
- *
- * This is an advanced feature. If you want to do custom post-processing on the
- * CSS before it is output (for example, to replace certain variable names
- * with particular values) you can give the name of a function here.
- */
- public $csspostprocess = null;
- /**
- * @var string Function to do custom CSS post-processing on a parsed CSS tree.
- *
- * This is an advanced feature. If you want to do custom post-processing on the
- * CSS before it is output, you can provide the name of the function here. The
- * function will receive a CSS tree document as first parameter, and the theme_config
- * object as second parameter. A return value is not required, the tree can
- * be edited in place.
- */
- public $csstreepostprocessor = null;
- /**
- * @var string Accessibility: Right arrow-like character is
- * used in the breadcrumb trail, course navigation menu
- * (previous/next activity), calendar, and search forum block.
- * If the theme does not set characters, appropriate defaults
- * are set automatically. Please DO NOT
- * use < > » - these are confusing for blind users.
- */
- public $rarrow = null;
- /**
- * @var string Accessibility: Left arrow-like character is
- * used in the breadcrumb trail, course navigation menu
- * (previous/next activity), calendar, and search forum block.
- * If the theme does not set characters, appropriate defaults
- * are set automatically. Please DO NOT
- * use < > » - these are confusing for blind users.
- */
- public $larrow = null;
- /**
- * @var string Accessibility: Up arrow-like character is used in
- * the book heirarchical navigation.
- * If the theme does not set characters, appropriate defaults
- * are set automatically. Please DO NOT
- * use ^ - this is confusing for blind users.
- */
- public $uarrow = null;
- /**
- * @var string Accessibility: Down arrow-like character.
- * If the theme does not set characters, appropriate defaults
- * are set automatically.
- */
- public $darrow = null;
- /**
- * @var bool Some themes may want to disable ajax course editing.
- */
- public $enablecourseajax = true;
- /**
- * @var string Determines served document types
- * - 'html5' the only officially supported doctype in Moodle
- * - 'xhtml5' may be used in development for validation (not intended for production servers!)
- * - 'xhtml' XHTML 1.0 Strict for legacy themes only
- */
- public $doctype = 'html5';
- /**
- * @var string requiredblocks If set to a string, will list the block types that cannot be deleted. Defaults to
- * navigation and settings.
- */
- public $requiredblocks = false;
- //==Following properties are not configurable from theme config.php==
- /**
- * @var string The name of this theme. Set automatically when this theme is
- * loaded. This can not be set in theme config.php
- */
- public $name;
- /**
- * @var string The folder where this themes files are stored. This is set
- * automatically. This can not be set in theme config.php
- */
- public $dir;
- /**
- * @var stdClass Theme settings stored in config_plugins table.
- * This can not be set in theme config.php
- */
- public $settings = null;
- /**
- * @var bool If set to true and the theme enables the dock then blocks will be able
- * to be moved to the special dock
- */
- public $enable_dock = false;
- /**
- * @var bool If set to true then this theme will not be shown in the theme selector unless
- * theme designer mode is turned on.
- */
- public $hidefromselector = false;
- /**
- * @var array list of YUI CSS modules to be included on each page. This may be used
- * to remove cssreset and use cssnormalise module instead.
- */
- public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase');
- /**
- * An associative array of block manipulations that should be made if the user is using an rtl language.
- * The key is the original block region, and the value is the block region to change to.
- * This is used when displaying blocks for regions only.
- * @var array
- */
- public $blockrtlmanipulations = array();
- /**
- * @var renderer_factory Instance of the renderer_factory implementation
- * we are using. Implementation detail.
- */
- protected $rf = null;
- /**
- * @var array List of parent config objects.
- **/
- protected $parent_configs = array();
- /**
- * Used to determine whether we can serve SVG images or not.
- * @var bool
- */
- private $usesvg = null;
- /**
- * Whether in RTL mode or not.
- * @var bool
- */
- protected $rtlmode = false;
- /**
- * The SCSS file to compile (without .scss), located in the scss/ folder of the theme.
- * Or a Closure, which receives the theme_config as argument and must
- * return the SCSS content.
- * @var string|Closure
- */
- public $scss = false;
- /**
- * Local cache of the SCSS property.
- * @var false|array
- */
- protected $scsscache = null;
- /**
- * The name of the function to call to get the SCSS code to inject.
- * @var string
- */
- public $extrascsscallback = null;
- /**
- * The name of the function to call to get SCSS to prepend.
- * @var string
- */
- public $prescsscallback = null;
- /**
- * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php
- * Defaults to {@link core_renderer::blocks_for_region()}
- * @var string
- */
- public $blockrendermethod = null;
- /**
- * Remember the results of icon remapping for the current page.
- * @var array
- */
- public $remapiconcache = [];
- /**
- * The name of the function to call to get precompiled CSS.
- * @var string
- */
- public $precompiledcsscallback = null;
- /**
- * Whether the theme uses course index.
- * @var bool
- */
- public $usescourseindex = false;
- /**
- * Load the config.php file for a particular theme, and return an instance
- * of this class. (That is, this is a factory method.)
- *
- * @param string $themename the name of the theme.
- * @return theme_config an instance of this class.
- */
- public static function load($themename) {
- global $CFG;
- // load theme settings from db
- try {
- $settings = get_config('theme_'.$themename);
- } catch (dml_exception $e) {
- // most probably moodle tables not created yet
- $settings = new stdClass();
- }
- if ($config = theme_config::find_theme_config($themename, $settings)) {
- return new theme_config($config);
- } else if ($themename == theme_config::DEFAULT_THEME) {
- throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
- } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) {
- debugging('This page should be using theme ' . $themename .
- ' which cannot be initialised. Falling back to the site theme ' . $CFG->theme, DEBUG_NORMAL);
- return new theme_config($config);
- } else {
- // bad luck, the requested theme has some problems - admin see details in theme config
- debugging('This page should be using theme ' . $themename .
- ' which cannot be initialised. Nor can the site theme ' . $CFG->theme .
- '. Falling back to ' . theme_config::DEFAULT_THEME, DEBUG_NORMAL);
- return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
- }
- }
- /**
- * Theme diagnostic code. It is very problematic to send debug output
- * to the actual CSS file, instead this functions is supposed to
- * diagnose given theme and highlights all potential problems.
- * This information should be available from the theme selection page
- * or some other debug page for theme designers.
- *
- * @param string $themename
- * @return array description of problems
- */
- public static function diagnose($themename) {
- //TODO: MDL-21108
- return array();
- }
- /**
- * Private constructor, can be called only from the factory method.
- * @param stdClass $config
- */
- private function __construct($config) {
- global $CFG; //needed for included lib.php files
- $this->settings = $config->settings;
- $this->name = $config->name;
- $this->dir = $config->dir;
- if ($this->name != self::DEFAULT_THEME) {
- $baseconfig = self::find_theme_config(self::DEFAULT_THEME, $this->settings);
- } else {
- $baseconfig = $config;
- }
- $configurable = array(
- 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'usefallback',
- 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts',
- 'layouts', 'enablecourseajax', 'requiredblocks',
- 'rendererfactory', 'csspostprocess', 'editor_sheets', 'editor_scss', 'rarrow', 'larrow', 'uarrow', 'darrow',
- 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations', 'blockrendermethod',
- 'scss', 'extrascsscallback', 'prescsscallback', 'csstreepostprocessor', 'addblockposition',
- 'iconsystem', 'precompiledcsscallback', 'haseditswitch', 'usescourseindex');
- foreach ($config as $key=>$value) {
- if (in_array($key, $configurable)) {
- $this->$key = $value;
- }
- }
- // verify all parents and load configs and renderers
- foreach ($this->parents as $parent) {
- if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
- // this is not good - better exclude faulty parents
- continue;
- }
- $libfile = $parent_config->dir.'/lib.php';
- if (is_readable($libfile)) {
- // theme may store various function here
- include_once($libfile);
- }
- $renderersfile = $parent_config->dir.'/renderers.php';
- if (is_readable($renderersfile)) {
- // may contain core and plugin renderers and renderer factory
- include_once($renderersfile);
- }
- $this->parent_configs[$parent] = $parent_config;
- }
- $libfile = $this->dir.'/lib.php';
- if (is_readable($libfile)) {
- // theme may store various function here
- include_once($libfile);
- }
- $rendererfile = $this->dir.'/renderers.php';
- if (is_readable($rendererfile)) {
- // may contain core and plugin renderers and renderer factory
- include_once($rendererfile);
- } else {
- // check if renderers.php file is missnamed renderer.php
- if (is_readable($this->dir.'/renderer.php')) {
- debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php.
- See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER);
- }
- }
- // cascade all layouts properly
- foreach ($baseconfig->layouts as $layout=>$value) {
- if (!isset($this->layouts[$layout])) {
- foreach ($this->parent_configs as $parent_config) {
- if (isset($parent_config->layouts[$layout])) {
- $this->layouts[$layout] = $parent_config->layouts[$layout];
- continue 2;
- }
- }
- $this->layouts[$layout] = $value;
- }
- }
- //fix arrows if needed
- $this->check_theme_arrows();
- }
- /**
- * Let the theme initialise the page object (usually $PAGE).
- *
- * This may be used for example to request jQuery in add-ons.
- *
- * @param moodle_page $page
- */
- public function init_page(moodle_page $page) {
- $themeinitfunction = 'theme_'.$this->name.'_page_init';
- if (function_exists($themeinitfunction)) {
- $themeinitfunction($page);
- }
- }
- /**
- * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow, $THEME->darrow have been set (theme/-/config.php).
- * If not it applies sensible defaults.
- *
- * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
- * search forum block, etc. Important: these are 'silent' in a screen-reader
- * (unlike > »), and must be accompanied by text.
- */
- private function check_theme_arrows() {
- if (!isset($this->rarrow) and !isset($this->larrow)) {
- // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
- // Also OK in Win 9x/2K/IE 5.x
- $this->rarrow = '►';
- $this->larrow = '◄';
- $this->uarrow = '▲';
- $this->darrow = '▼';
- if (empty($_SERVER['HTTP_USER_AGENT'])) {
- $uagent = '';
- } else {
- $uagent = $_SERVER['HTTP_USER_AGENT'];
- }
- if (false !== strpos($uagent, 'Opera')
- || false !== strpos($uagent, 'Mac')) {
- // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
- // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
- $this->rarrow = '▶︎';
- $this->larrow = '◀︎';
- }
- elseif ((false !== strpos($uagent, 'Konqueror'))
- || (false !== strpos($uagent, 'Android'))) {
- // The fonts on Android don't include the characters required for this to work as expected.
- // So we use the same ones Konqueror uses.
- $this->rarrow = '→';
- $this->larrow = '←';
- $this->uarrow = '↑';
- $this->darrow = '↓';
- }
- elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
- && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
- // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
- // To be safe, non-Unicode browsers!
- $this->rarrow = '>';
- $this->larrow = '<';
- $this->uarrow = '^';
- $this->darrow = 'v';
- }
- // RTL support - in RTL languages, swap r and l arrows
- if (right_to_left()) {
- $t = $this->rarrow;
- $this->rarrow = $this->larrow;
- $this->larrow = $t;
- }
- }
- }
- /**
- * Returns output renderer prefixes, these are used when looking
- * for the overridden renderers in themes.
- *
- * @return array
- */
- public function renderer_prefixes() {
- global $CFG; // just in case the included files need it
- $prefixes = array('theme_'.$this->name);
- foreach ($this->parent_configs as $parent) {
- $prefixes[] = 'theme_'.$parent->name;
- }
- return $prefixes;
- }
- /**
- * Returns the stylesheet URL of this editor content
- *
- * @param bool $encoded false means use & and true use & in URLs
- * @return moodle_url
- */
- public function editor_css_url($encoded=true) {
- global $CFG;
- $rev = theme_get_revision();
- if ($rev > -1) {
- $themesubrevision = theme_get_sub_revision_for_theme($this->name);
- // Provide the sub revision to allow us to invalidate cached theme CSS
- // on a per theme basis, rather than globally.
- if ($themesubrevision && $themesubrevision > 0) {
- $rev .= "_{$themesubrevision}";
- }
- $url = new moodle_url("/theme/styles.php");
- if (!empty($CFG->slasharguments)) {
- $url->set_slashargument('/'.$this->name.'/'.$rev.'/editor', 'noparam', true);
- } else {
- $url->params(array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor'));
- }
- } else {
- $params = array('theme'=>$this->name, 'type'=>'editor');
- $url = new moodle_url('/theme/styles_debug.php', $params);
- }
- return $url;
- }
- /**
- * Returns the content of the CSS to be used in editor content
- *
- * @return array
- */
- public function editor_css_files() {
- $files = array();
- // First editor plugins.
- $plugins = core_component::get_plugin_list('editor');
- foreach ($plugins as $plugin=>$fulldir) {
- $sheetfile = "$fulldir/editor_styles.css";
- if (is_readable($sheetfile)) {
- $files['plugin_'.$plugin] = $sheetfile;
- }
- }
- // Then parent themes - base first, the immediate parent last.
- foreach (array_reverse($this->parent_configs) as $parent_config) {
- if (empty($parent_config->editor_sheets)) {
- continue;
- }
- foreach ($parent_config->editor_sheets as $sheet) {
- $sheetfile = "$parent_config->dir/style/$sheet.css";
- if (is_readable($sheetfile)) {
- $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
- }
- }
- }
- // Finally this theme.
- if (!empty($this->editor_sheets)) {
- foreach ($this->editor_sheets as $sheet) {
- $sheetfile = "$this->dir/style/$sheet.css";
- if (is_readable($sheetfile)) {
- $files['theme_'.$sheet] = $sheetfile;
- }
- }
- }
- return $files;
- }
- /**
- * Compiles and returns the content of the SCSS to be used in editor content
- *
- * @return string Compiled CSS from the editor SCSS
- */
- public function editor_scss_to_css() {
- $css = '';
- $dir = $this->dir;
- $filenames = [];
- // Use editor_scss file(s) provided by this theme if set.
- if (!empty($this->editor_scss)) {
- $filenames = $this->editor_scss;
- } else {
- // If no editor_scss set, move up theme hierarchy until one is found (if at all).
- // This is so child themes only need to set editor_scss if an override is required.
- foreach (array_reverse($this->parent_configs) as $parentconfig) {
- if (!empty($parentconfig->editor_scss)) {
- $dir = $parentconfig->dir;
- $filenames = $parentconfig->editor_scss;
- // Config found, stop looking.
- break;
- }
- }
- }
- if (!empty($filenames)) {
- $compiler = new core_scss();
- foreach ($filenames as $filename) {
- $compiler->set_file("{$dir}/scss/{$filename}.scss");
- try {
- $css .= $compiler->to_css();
- } catch (\Exception $e) {
- debugging('Error while compiling editor SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER);
- }
- }
- }
- return $css;
- }
- /**
- * Get the stylesheet URL of this theme.
- *
- * @param moodle_page $page Not used... deprecated?
- * @return moodle_url[]
- */
- public function css_urls(moodle_page $page) {
- global $CFG;
- $rev = theme_get_revision();
- $urls = array();
- $svg = $this->use_svg_icons();
- $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10'));
- if ($rev > -1) {
- $filename = right_to_left() ? 'all-rtl' : 'all';
- $url = new moodle_url("/theme/styles.php");
- $themesubrevision = theme_get_sub_revision_for_theme($this->name);
- // Provide the sub revision to allow us to invalidate cached theme CSS
- // on a per theme basis, rather than globally.
- if ($themesubrevision && $themesubrevision > 0) {
- $rev .= "_{$themesubrevision}";
- }
- if (!empty($CFG->slasharguments)) {
- $slashargs = '';
- if (!$svg) {
- // We add a simple /_s to the start of the path.
- // The underscore is used to ensure that it isn't a valid theme name.
- $slashargs .= '/_s'.$slashargs;
- }
- $slashargs .= '/'.$this->name.'/'.$rev.'/'.$filename;
- if ($separate) {
- $slashargs .= '/chunk0';
- }
- $url->set_slashargument($slashargs, 'noparam', true);
- } else {
- $params = array('theme' => $this->name, 'rev' => $rev, 'type' => $filename);
- if (!$svg) {
- // We add an SVG param so that we know not to serve SVG images.
- // We do this because all modern browsers support SVG and this param will one day be removed.
- $params['svg'] = '0';
- }
- if ($separate) {
- $params['chunk'] = '0';
- }
- $url->params($params);
- }
- $urls[] = $url;
- } else {
- $baseurl = new moodle_url('/theme/styles_debug.php');
- $css = $this->get_css_files(true);
- if (!$svg) {
- // We add an SVG param so that we know not to serve SVG images.
- // We do this because all modern browsers support SVG and this param will one day be removed.
- $baseurl->param('svg', '0');
- }
- if (right_to_left()) {
- $baseurl->param('rtl', 1);
- }
- if ($separate) {
- // We might need to chunk long files.
- $baseurl->param('chunk', '0');
- }
- if (core_useragent::is_ie()) {
- // Lalala, IE does not allow more than 31 linked CSS files from main document.
- $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
- foreach ($css['parents'] as $parent=>$sheets) {
- // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096).
- $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
- }
- if ($this->get_scss_property()) {
- // No need to define the type as IE here.
- $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
- }
- $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
- } else {
- foreach ($css['plugins'] as $plugin=>$unused) {
- $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
- }
- foreach ($css['parents'] as $parent=>$sheets) {
- foreach ($sheets as $sheet=>$unused2) {
- $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
- }
- }
- foreach ($css['theme'] as $sheet => $filename) {
- if ($sheet === self::SCSS_KEY) {
- // This is the theme SCSS file.
- $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss'));
- } else {
- // Sheet first in order to make long urls easier to read.
- $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme'));
- }
- }
- }
- }
- // Allow themes to change the css url to something like theme/mytheme/mycss.php.
- component_callback('theme_' . $this->name, 'alter_css_urls', [&$urls]);
- return $urls;
- }
- /**
- * Get the whole css stylesheet for production mode.
- *
- * NOTE: this method is not expected to be used from any addons.
- *
- * @return string CSS markup compressed
- */
- public function get_css_content() {
- $csscontent = '';
- foreach ($this->get_css_files(false) as $type => $value) {
- foreach ($value as $identifier => $val) {
- if (is_array($val)) {
- foreach ($val as $v) {
- $csscontent .= file_get_contents($v) . "\n";
- }
- } else {
- if ($type === 'theme' && $identifier === self::SCSS_KEY) {
- // We need the content from SCSS because this is the SCSS file from the theme.
- if ($compiled = $this->get_css_content_from_scss(false)) {
- $csscontent .= $compiled;
- } else {
- // The compiler failed so default back to any precompiled css that might
- // exist.
- $csscontent .= $this->get_precompiled_css_content();
- }
- } else {
- $csscontent .= file_get_contents($val) . "\n";
- }
- }
- }
- }
- $csscontent = $this->post_process($csscontent);
- $csscontent = core_minify::css($csscontent);
- return $csscontent;
- }
- /**
- * Set post processed CSS content cache.
- *
- * @param string $csscontent The post processed CSS content.
- * @return bool True if the content was successfully cached.
- */
- public function set_css_content_cache($csscontent) {
- $cache = cache::make('core', 'postprocessedcss');
- $key = $this->get_css_cache_key();
- return $cache->set($key, $csscontent);
- }
- /**
- * Return whether the post processed CSS content has been cached.
- *
- * @return bool Whether the post-processed CSS is available in the cache.
- */
- public function has_css_cached_content() {
- $key = $this->get_css_cache_key();
- $cache = cache::make('core', 'postprocessedcss');
- return $cache->has($key);
- }
- /**
- * Return cached post processed CSS content.
- *
- * @return bool|string The cached css content or false if not found.
- */
- public function get_css_cached_content() {
- $key = $this->get_css_cache_key();
- $cache = cache::make('core', 'postprocessedcss');
- return $cache->get($key);
- }
- /**
- * Generate the css content cache key.
- *
- * @return string The post processed css cache key.
- */
- public function get_css_cache_key() {
- $nosvg = (!$this->use_svg_icons()) ? 'nosvg_' : '';
- $rtlmode = ($this->rtlmode == true) ? 'rtl' : 'ltr';
- return $nosvg . $this->name . '_' . $rtlmode;
- }
- /**
- * Get the theme designer css markup,
- * the parameters are coming from css_urls().
- *
- * NOTE: this method is not expected to be used from any addons.
- *
- * @param string $type
- * @param string $subtype
- * @param string $sheet
- * @return string CSS markup
- */
- public function get_css_content_debug($type, $subtype, $sheet) {
- if ($type === 'scss') {
- // The SCSS file of the theme is requested.
- $csscontent = $this->get_css_content_from_scss(true);
- if ($csscontent !== false) {
- return $this->post_process($csscontent);
- }
- return '';
- }
- $cssfiles = array();
- $css = $this->get_css_files(true);
- if ($type === 'ie') {
- // IE is a sloppy browser with weird limits, sorry.
- if ($subtype === 'plugins') {
- $cssfiles = $css['plugins'];
- } else if ($subtype === 'parents') {
- if (empty($sheet)) {
- // Do not bother with the empty parent here.
- } else {
- // Build up the CSS for that parent so we can serve it as one file.
- foreach ($css[$subtype][$sheet] as $parent => $css) {
- $cssfiles[] = $css;
- }
- }
- } else if ($subtype === 'theme') {
- $cssfiles = $css['theme'];
- foreach ($cssfiles as $key => $value) {
- if (in_array($key, [self::SCSS_KEY])) {
- // Remove the SCSS file from the theme CSS files.
- // The SCSS files use the type 'scss', not 'ie'.
- unset($cssfiles[$key]);
- }
- }
- }
- } else if ($type === 'plugin') {
- if (isset($css['plugins'][$subtype])) {
- $cssfiles[] = $css['plugins'][$subtype];
- }
- } else if ($type === 'parent') {
- if (isset($css['parents'][$subtype][$sheet])) {
- $cssfiles[] = $css['parents'][$subtype][$sheet];
- }
- } else if ($type === 'theme') {
- if (isset($css['theme'][$sheet])) {
- $cssfiles[] = $css['theme'][$sheet];
- }
- }
- $csscontent = '';
- foreach ($cssfiles as $file) {
- $contents = file_get_contents($file);
- $contents = $this->post_process($contents);
- $comment = "/** Path: $type $subtype $sheet.' **/\n";
- $stats = '';
- $csscontent .= $comment.$stats.$contents."\n\n";
- }
- return $csscontent;
- }
- /**
- * Get the whole css stylesheet for editor iframe.
- *
- * NOTE: this method is not expected to be used from any addons.
- *
- * @return string CSS markup
- */
- public function get_css_content_editor() {
- $css = '';
- $cssfiles = $this->editor_css_files();
- // If editor has static CSS, include it.
- foreach ($cssfiles as $file) {
- $css .= file_get_contents($file)."\n";
- }
- // If editor has SCSS, compile and include it.
- if (($convertedscss = $this->editor_scss_to_css())) {
- $css .= $convertedscss;
- }
- $output = $this->post_process($css);
- return $output;
- }
- /**
- * Returns an array of organised CSS files required for this output.
- *
- * @param bool $themedesigner
- * @return array nested array of file paths
- */
- protected function get_css_files($themedesigner) {
- global $CFG;
- $cache = null;
- $cachekey = 'cssfiles';
- if ($themedesigner) {
- require_once($CFG->dirroot.'/lib/csslib.php');
- // We need some kind of caching here because otherwise the page navigation becomes
- // way too slow in theme designer mode. Feel free to create full cache definition later...
- $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name));
- if ($files = $cache->get($cachekey)) {
- if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) {
- unset($files['created']);
- return $files;
- }
- }
- }
- $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
- // Get all plugin sheets.
- $excludes = $this->resolve_excludes('plugins_exclude_sheets');
- if ($excludes !== true) {
- foreach (core_component::get_plugin_types() as $type=>$unused) {
- if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
- continue;
- }
- $plugins = core_component::get_plugin_list($type);
- foreach ($plugins as $plugin=>$fulldir) {
- if (!empty($excludes[$type]) and is_array($excludes[$type])
- and in_array($plugin, $excludes[$type])) {
- continue;
- }
- // Get the CSS from the plugin.
- …
Large files files are truncated, but you can click here to view the full file