Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.
/lib/ -> outputlib.php (source)

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

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