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.

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   * Library functions to facilitate the use of JavaScript in Moodle.
  19   *
  20   * Note: you can find history of this file in lib/ajax/ajaxlib.php
  21   *
  22   * @copyright 2009 Tim Hunt, 2010 Petr Skoda
  23   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   * @package core
  25   * @category output
  26   */
  27  
  28  defined('MOODLE_INTERNAL') || die();
  29  
  30  /**
  31   * This class tracks all the things that are needed by the current page.
  32   *
  33   * Normally, the only instance of this  class you will need to work with is the
  34   * one accessible via $PAGE->requires.
  35   *
  36   * Typical usage would be
  37   * <pre>
  38   *     $PAGE->requires->js_call_amd('mod_forum/view', 'init');
  39   * </pre>
  40   *
  41   * It also supports obsoleted coding style with/without YUI3 modules.
  42   * <pre>
  43   *     $PAGE->requires->js_init_call('M.mod_forum.init_view');
  44   *     $PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overridable via themes!
  45   *     $PAGE->requires->js('/mod/mymod/script.js');
  46   *     $PAGE->requires->js('/mod/mymod/small_but_urgent.js', true);
  47   *     $PAGE->requires->js_function_call('init_mymod', array($data), true);
  48   * </pre>
  49   *
  50   * There are some natural restrictions on some methods. For example, {@link css()}
  51   * can only be called before the <head> tag is output. See the comments on the
  52   * individual methods for details.
  53   *
  54   * @copyright 2009 Tim Hunt, 2010 Petr Skoda
  55   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  56   * @since Moodle 2.0
  57   * @package core
  58   * @category output
  59   */
  60  class page_requirements_manager {
  61  
  62      /**
  63       * @var array List of string available from JS
  64       */
  65      protected $stringsforjs = array();
  66  
  67      /**
  68       * @var array List of get_string $a parameters - used for validation only.
  69       */
  70      protected $stringsforjs_as = array();
  71  
  72      /**
  73       * @var array List of JS variables to be initialised
  74       */
  75      protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
  76  
  77      /**
  78       * @var array Included JS scripts
  79       */
  80      protected $jsincludes = array('head'=>array(), 'footer'=>array());
  81  
  82      /**
  83       * @var array Inline scripts using RequireJS module loading.
  84       */
  85      protected $amdjscode = array('');
  86  
  87      /**
  88       * @var array List of needed function calls
  89       */
  90      protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
  91  
  92      /**
  93       * @var array List of skip links, those are needed for accessibility reasons
  94       */
  95      protected $skiplinks = array();
  96  
  97      /**
  98       * @var array Javascript code used for initialisation of page, it should
  99       * be relatively small
 100       */
 101      protected $jsinitcode = array();
 102  
 103      /**
 104       * @var array of moodle_url Theme sheets, initialised only from core_renderer
 105       */
 106      protected $cssthemeurls = array();
 107  
 108      /**
 109       * @var array of moodle_url List of custom theme sheets, these are strongly discouraged!
 110       * Useful mostly only for CSS submitted by teachers that is not part of the theme.
 111       */
 112      protected $cssurls = array();
 113  
 114      /**
 115       * @var array List of requested event handlers
 116       */
 117      protected $eventhandlers = array();
 118  
 119      /**
 120       * @var array Extra modules
 121       */
 122      protected $extramodules = array();
 123  
 124      /**
 125       * @var array trackes the names of bits of HTML that are only required once
 126       * per page. See {@link has_one_time_item_been_created()},
 127       * {@link set_one_time_item_created()} and {@link should_create_one_time_item_now()}.
 128       */
 129      protected $onetimeitemsoutput = array();
 130  
 131      /**
 132       * @var bool Flag indicated head stuff already printed
 133       */
 134      protected $headdone = false;
 135  
 136      /**
 137       * @var bool Flag indicating top of body already printed
 138       */
 139      protected $topofbodydone = false;
 140  
 141      /**
 142       * @var stdClass YUI PHPLoader instance responsible for YUI3 loading from PHP only
 143       */
 144      protected $yui3loader;
 145  
 146      /**
 147       * @var YUI_config default YUI loader configuration
 148       */
 149      protected $YUI_config;
 150  
 151      /**
 152       * @var array $yuicssmodules
 153       */
 154      protected $yuicssmodules = array();
 155  
 156      /**
 157       * @var array Some config vars exposed in JS, please no secret stuff there
 158       */
 159      protected $M_cfg;
 160  
 161      /**
 162       * @var array list of requested jQuery plugins
 163       */
 164      protected $jqueryplugins = array();
 165  
 166      /**
 167       * @var array list of jQuery plugin overrides
 168       */
 169      protected $jquerypluginoverrides = array();
 170  
 171      /**
 172       * Page requirements constructor.
 173       */
 174      public function __construct() {
 175          global $CFG;
 176  
 177          // You may need to set up URL rewrite rule because oversized URLs might not be allowed by web server.
 178          $sep = empty($CFG->yuislasharguments) ? '?' : '/';
 179  
 180          $this->yui3loader = new stdClass();
 181          $this->YUI_config = new YUI_config();
 182  
 183          if (is_https() && !empty($CFG->useexternalyui)) {
 184              // On HTTPS sites all JS must be loaded from https sites,
 185              // YUI CDN does not support https yet, sorry.
 186              $CFG->useexternalyui = 0;
 187          }
 188  
 189          // Set up some loader options.
 190          $this->yui3loader->local_base = $CFG->wwwroot . '/lib/yuilib/'. $CFG->yui3version . '/';
 191          $this->yui3loader->local_comboBase = $CFG->wwwroot . '/theme/yui_combo.php'.$sep;
 192  
 193          if (!empty($CFG->useexternalyui)) {
 194              $this->yui3loader->base = 'http://yui.yahooapis.com/' . $CFG->yui3version . '/';
 195              $this->yui3loader->comboBase = 'http://yui.yahooapis.com/combo?';
 196          } else {
 197              $this->yui3loader->base = $this->yui3loader->local_base;
 198              $this->yui3loader->comboBase = $this->yui3loader->local_comboBase;
 199          }
 200  
 201          // Enable combo loader? This significantly helps with caching and performance!
 202          $this->yui3loader->combine = !empty($CFG->yuicomboloading);
 203  
 204          $jsrev = $this->get_jsrev();
 205  
 206          // Set up JS YUI loader helper object.
 207          $this->YUI_config->base         = $this->yui3loader->base;
 208          $this->YUI_config->comboBase    = $this->yui3loader->comboBase;
 209          $this->YUI_config->combine      = $this->yui3loader->combine;
 210  
 211          // If we've had to patch any YUI modules between releases, we must override the YUI configuration to include them.
 212          if (!empty($CFG->yuipatchedmodules) && !empty($CFG->yuipatchlevel)) {
 213              $this->YUI_config->define_patched_core_modules($this->yui3loader->local_comboBase,
 214                      $CFG->yui3version,
 215                      $CFG->yuipatchlevel,
 216                      $CFG->yuipatchedmodules);
 217          }
 218  
 219          $configname = $this->YUI_config->set_config_source('lib/yui/config/yui2.js');
 220          $this->YUI_config->add_group('yui2', array(
 221              // Loader configuration for our 2in3, for now ignores $CFG->useexternalyui.
 222              'base' => $CFG->wwwroot . '/lib/yuilib/2in3/' . $CFG->yui2version . '/build/',
 223              'comboBase' => $CFG->wwwroot . '/theme/yui_combo.php'.$sep,
 224              'combine' => $this->yui3loader->combine,
 225              'ext' => false,
 226              'root' => '2in3/' . $CFG->yui2version .'/build/',
 227              'patterns' => array(
 228                  'yui2-' => array(
 229                      'group' => 'yui2',
 230                      'configFn' => $configname,
 231                  )
 232              )
 233          ));
 234          $configname = $this->YUI_config->set_config_source('lib/yui/config/moodle.js');
 235          $this->YUI_config->add_group('moodle', array(
 236              'name' => 'moodle',
 237              'base' => $CFG->wwwroot . '/theme/yui_combo.php' . $sep . 'm/' . $jsrev . '/',
 238              'combine' => $this->yui3loader->combine,
 239              'comboBase' => $CFG->wwwroot . '/theme/yui_combo.php'.$sep,
 240              'ext' => false,
 241              'root' => 'm/'.$jsrev.'/', // Add the rev to the root path so that we can control caching.
 242              'patterns' => array(
 243                  'moodle-' => array(
 244                      'group' => 'moodle',
 245                      'configFn' => $configname,
 246                  )
 247              )
 248          ));
 249  
 250          $this->YUI_config->add_group('gallery', array(
 251              'name' => 'gallery',
 252              'base' => $CFG->wwwroot . '/lib/yuilib/gallery/',
 253              'combine' => $this->yui3loader->combine,
 254              'comboBase' => $CFG->wwwroot . '/theme/yui_combo.php' . $sep,
 255              'ext' => false,
 256              'root' => 'gallery/' . $jsrev . '/',
 257              'patterns' => array(
 258                  'gallery-' => array(
 259                      'group' => 'gallery',
 260                  )
 261              )
 262          ));
 263  
 264          // Set some more loader options applying to groups too.
 265          if ($CFG->debugdeveloper) {
 266              // When debugging is enabled, we want to load the non-minified (RAW) versions of YUI library modules rather
 267              // than the DEBUG versions as these generally generate too much logging for our purposes.
 268              // However we do want the DEBUG versions of our Moodle-specific modules.
 269              // To debug a YUI-specific issue, change the yui3loader->filter value to DEBUG.
 270              $this->YUI_config->filter = 'RAW';
 271              $this->YUI_config->groups['moodle']['filter'] = 'DEBUG';
 272  
 273              // We use the yui3loader->filter setting when writing the YUI3 seed scripts into the header.
 274              $this->yui3loader->filter = $this->YUI_config->filter;
 275              $this->YUI_config->debug = true;
 276          } else {
 277              $this->yui3loader->filter = null;
 278              $this->YUI_config->groups['moodle']['filter'] = null;
 279              $this->YUI_config->debug = false;
 280          }
 281  
 282          // Include the YUI config log filters.
 283          if (!empty($CFG->yuilogexclude) && is_array($CFG->yuilogexclude)) {
 284              $this->YUI_config->logExclude = $CFG->yuilogexclude;
 285          }
 286          if (!empty($CFG->yuiloginclude) && is_array($CFG->yuiloginclude)) {
 287              $this->YUI_config->logInclude = $CFG->yuiloginclude;
 288          }
 289          if (!empty($CFG->yuiloglevel)) {
 290              $this->YUI_config->logLevel = $CFG->yuiloglevel;
 291          }
 292  
 293          // Add the moodle group's module data.
 294          $this->YUI_config->add_moodle_metadata();
 295  
 296          // Every page should include definition of following modules.
 297          $this->js_module($this->find_module('core_filepicker'));
 298          $this->js_module($this->find_module('core_comment'));
 299      }
 300  
 301      /**
 302       * Return the safe config values that get set for javascript in "M.cfg".
 303       *
 304       * @since 2.9
 305       * @return array List of safe config values that are available to javascript.
 306       */
 307      public function get_config_for_javascript(moodle_page $page, renderer_base $renderer) {
 308          global $CFG;
 309  
 310          if (empty($this->M_cfg)) {
 311  
 312              $iconsystem = \core\output\icon_system::instance();
 313  
 314              // It is possible that the $page->context is null, so we can't use $page->context->id.
 315              $contextid = null;
 316              $contextinstanceid = null;
 317              if (!is_null($page->context)) {
 318                  $contextid = $page->context->id;
 319                  $contextinstanceid = $page->context->instanceid;
 320                  $courseid = $page->course->id;
 321                  $coursecontext = context_course::instance($courseid);
 322              }
 323  
 324              $this->M_cfg = array(
 325                  'wwwroot'               => $CFG->wwwroot,
 326                  'homeurl'               => $page->navigation->action,
 327                  'sesskey'               => sesskey(),
 328                  'sessiontimeout'        => $CFG->sessiontimeout,
 329                  'sessiontimeoutwarning' => $CFG->sessiontimeoutwarning,
 330                  'themerev'              => theme_get_revision(),
 331                  'slasharguments'        => (int)(!empty($CFG->slasharguments)),
 332                  'theme'                 => $page->theme->name,
 333                  'iconsystemmodule'      => $iconsystem->get_amd_name(),
 334                  'jsrev'                 => $this->get_jsrev(),
 335                  'admin'                 => $CFG->admin,
 336                  'svgicons'              => $page->theme->use_svg_icons(),
 337                  'usertimezone'          => usertimezone(),
 338                  'courseId'              => isset($courseid) ? (int) $courseid : 0,
 339                  'courseContextId'       => isset($coursecontext) ? $coursecontext->id : 0,
 340                  'contextid'             => $contextid,
 341                  'contextInstanceId'     => (int) $contextinstanceid,
 342                  'langrev'               => get_string_manager()->get_revision(),
 343                  'templaterev'           => $this->get_templaterev()
 344              );
 345              if ($CFG->debugdeveloper) {
 346                  $this->M_cfg['developerdebug'] = true;
 347              }
 348              if (defined('BEHAT_SITE_RUNNING')) {
 349                  $this->M_cfg['behatsiterunning'] = true;
 350              }
 351  
 352          }
 353          return $this->M_cfg;
 354      }
 355  
 356      /**
 357       * Initialise with the bits of JavaScript that every Moodle page should have.
 358       *
 359       * @param moodle_page $page
 360       * @param core_renderer $renderer
 361       */
 362      protected function init_requirements_data(moodle_page $page, core_renderer $renderer) {
 363          global $CFG;
 364  
 365          // Init the js config.
 366          $this->get_config_for_javascript($page, $renderer);
 367  
 368          // Accessibility stuff.
 369          $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
 370  
 371          // Add strings used on many pages.
 372          $this->string_for_js('confirmation', 'admin');
 373          $this->string_for_js('cancel', 'moodle');
 374          $this->string_for_js('yes', 'moodle');
 375  
 376          // Alter links in top frame to break out of frames.
 377          if ($page->pagelayout === 'frametop') {
 378              $this->js_init_call('M.util.init_frametop');
 379          }
 380  
 381          // Include block drag/drop if editing is on
 382          if ($page->user_is_editing()) {
 383              $params = array(
 384                  'courseid' => $page->course->id,
 385                  'pagetype' => $page->pagetype,
 386                  'pagelayout' => $page->pagelayout,
 387                  'subpage' => $page->subpage,
 388                  'regions' => $page->blocks->get_regions(),
 389                  'contextid' => $page->context->id,
 390              );
 391              if (!empty($page->cm->id)) {
 392                  $params['cmid'] = $page->cm->id;
 393              }
 394              // Strings for drag and drop.
 395              $this->strings_for_js(array('movecontent',
 396                                          'tocontent',
 397                                          'emptydragdropregion'),
 398                                    'moodle');
 399              $page->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
 400          }
 401  
 402          // Include the YUI CSS Modules.
 403          $page->requires->set_yuicssmodules($page->theme->yuicssmodules);
 404      }
 405  
 406      /**
 407       * Determine the correct JS Revision to use for this load.
 408       *
 409       * @return int the jsrev to use.
 410       */
 411      public function get_jsrev() {
 412          global $CFG;
 413  
 414          if (empty($CFG->cachejs)) {
 415              $jsrev = -1;
 416          } else if (empty($CFG->jsrev)) {
 417              $jsrev = 1;
 418          } else {
 419              $jsrev = $CFG->jsrev;
 420          }
 421  
 422          return $jsrev;
 423      }
 424  
 425      /**
 426       * Determine the correct Template revision to use for this load.
 427       *
 428       * @return int the templaterev to use.
 429       */
 430      protected function get_templaterev() {
 431          global $CFG;
 432  
 433          if (empty($CFG->cachetemplates)) {
 434              $templaterev = -1;
 435          } else if (empty($CFG->templaterev)) {
 436              $templaterev = 1;
 437          } else {
 438              $templaterev = $CFG->templaterev;
 439          }
 440  
 441          return $templaterev;
 442      }
 443  
 444      /**
 445       * Ensure that the specified JavaScript file is linked to from this page.
 446       *
 447       * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
 448       * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
 449       *
 450       * By default the link is put at the end of the page, since this gives best page-load performance.
 451       *
 452       * Even if a particular script is requested more than once, it will only be linked
 453       * to once.
 454       *
 455       * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
 456       *      For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
 457       * @param bool $inhead initialise in head
 458       */
 459      public function js($url, $inhead = false) {
 460          $url = $this->js_fix_url($url);
 461          $where = $inhead ? 'head' : 'footer';
 462          $this->jsincludes[$where][$url->out()] = $url;
 463      }
 464  
 465      /**
 466       * Request inclusion of jQuery library in the page.
 467       *
 468       * NOTE: this should not be used in official Moodle distribution!
 469       *
 470       * {@link https://moodledev.io/docs/guides/javascript/jquery}
 471       */
 472      public function jquery() {
 473          $this->jquery_plugin('jquery');
 474      }
 475  
 476      /**
 477       * Request inclusion of jQuery plugin.
 478       *
 479       * NOTE: this should not be used in official Moodle distribution!
 480       *
 481       * jQuery plugins are located in plugin/jquery/* subdirectory,
 482       * plugin/jquery/plugins.php lists all available plugins.
 483       *
 484       * Included core plugins:
 485       *   - jQuery UI
 486       *
 487       * Add-ons may include extra jQuery plugins in jquery/ directory,
 488       * plugins.php file defines the mapping between plugin names and
 489       * necessary page includes.
 490       *
 491       * Examples:
 492       * <code>
 493       *   // file: mod/xxx/view.php
 494       *   $PAGE->requires->jquery();
 495       *   $PAGE->requires->jquery_plugin('ui');
 496       *   $PAGE->requires->jquery_plugin('ui-css');
 497       * </code>
 498       *
 499       * <code>
 500       *   // file: theme/yyy/lib.php
 501       *   function theme_yyy_page_init(moodle_page $page) {
 502       *       $page->requires->jquery();
 503       *       $page->requires->jquery_plugin('ui');
 504       *       $page->requires->jquery_plugin('ui-css');
 505       *   }
 506       * </code>
 507       *
 508       * <code>
 509       *   // file: blocks/zzz/block_zzz.php
 510       *   public function get_required_javascript() {
 511       *       parent::get_required_javascript();
 512       *       $this->page->requires->jquery();
 513       *       $page->requires->jquery_plugin('ui');
 514       *       $page->requires->jquery_plugin('ui-css');
 515       *   }
 516       * </code>
 517       *
 518       * {@link https://moodledev.io/docs/guides/javascript/jquery}
 519       *
 520       * @param string $plugin name of the jQuery plugin as defined in jquery/plugins.php
 521       * @param string $component name of the component
 522       * @return bool success
 523       */
 524      public function jquery_plugin($plugin, $component = 'core') {
 525          global $CFG;
 526  
 527          if ($this->headdone) {
 528              debugging('Can not add jQuery plugins after starting page output!');
 529              return false;
 530          }
 531  
 532          if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css'))) {
 533              debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER);
 534              $component = 'core';
 535          } else if ($component !== 'core' and strpos($component, '_') === false) {
 536              // Let's normalise the legacy activity names, Frankenstyle rulez!
 537              $component = 'mod_' . $component;
 538          }
 539  
 540          if (empty($this->jqueryplugins) and ($component !== 'core' or $plugin !== 'jquery')) {
 541              // Make sure the jQuery itself is always loaded first,
 542              // the order of all other plugins depends on order of $PAGE_>requires->.
 543              $this->jquery_plugin('jquery', 'core');
 544          }
 545  
 546          if (isset($this->jqueryplugins[$plugin])) {
 547              // No problem, we already have something, first Moodle plugin to register the jQuery plugin wins.
 548              return true;
 549          }
 550  
 551          $componentdir = core_component::get_component_directory($component);
 552          if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
 553              debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER);
 554              return false;
 555          }
 556  
 557          $plugins = array();
 558          require("$componentdir/jquery/plugins.php");
 559  
 560          if (!isset($plugins[$plugin])) {
 561              debugging("jQuery plugin '$plugin' can not be found in component '$component'.", DEBUG_DEVELOPER);
 562              return false;
 563          }
 564  
 565          $this->jqueryplugins[$plugin] = new stdClass();
 566          $this->jqueryplugins[$plugin]->plugin    = $plugin;
 567          $this->jqueryplugins[$plugin]->component = $component;
 568          $this->jqueryplugins[$plugin]->urls      = array();
 569  
 570          foreach ($plugins[$plugin]['files'] as $file) {
 571              if ($CFG->debugdeveloper) {
 572                  if (!file_exists("$componentdir/jquery/$file")) {
 573                      debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
 574                      continue;
 575                  }
 576                  $file = str_replace('.min.css', '.css', $file);
 577                  $file = str_replace('.min.js', '.js', $file);
 578              }
 579              if (!file_exists("$componentdir/jquery/$file")) {
 580                  debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
 581                  continue;
 582              }
 583              if (!empty($CFG->slasharguments)) {
 584                  $url = new moodle_url("/theme/jquery.php");
 585                  $url->set_slashargument("/$component/$file");
 586  
 587              } else {
 588                  // This is not really good, we need slasharguments for relative links, this means no caching...
 589                  $path = realpath("$componentdir/jquery/$file");
 590                  if (strpos($path, $CFG->dirroot) === 0) {
 591                      $url = $CFG->wwwroot.preg_replace('/^'.preg_quote($CFG->dirroot, '/').'/', '', $path);
 592                      // Replace all occurences of backslashes characters in url to forward slashes.
 593                      $url = str_replace('\\', '/', $url);
 594                      $url = new moodle_url($url);
 595                  } else {
 596                      // Bad luck, fix your server!
 597                      debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
 598                      continue;
 599                  }
 600              }
 601              $this->jqueryplugins[$plugin]->urls[] = $url;
 602          }
 603  
 604          return true;
 605      }
 606  
 607      /**
 608       * Request replacement of one jQuery plugin by another.
 609       *
 610       * This is useful when themes want to replace the jQuery UI theme,
 611       * the problem is that theme can not prevent others from including the core ui-css plugin.
 612       *
 613       * Example:
 614       *  1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
 615       *  2/ write theme/yourtheme/jquery/plugins.php
 616       *  3/ init jQuery from theme
 617       *
 618       * <code>
 619       *   // file theme/yourtheme/lib.php
 620       *   function theme_yourtheme_page_init($page) {
 621       *       $page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
 622       *       $page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
 623       *   }
 624       * </code>
 625       *
 626       * This code prevents loading of standard 'ui-css' which my be requested by other plugins,
 627       * the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
 628       *
 629       * {@link https://moodledev.io/docs/guides/javascript/jquery}
 630       *
 631       * @param string $oldplugin original plugin
 632       * @param string $newplugin the replacement
 633       */
 634      public function jquery_override_plugin($oldplugin, $newplugin) {
 635          if ($this->headdone) {
 636              debugging('Can not override jQuery plugins after starting page output!');
 637              return;
 638          }
 639          $this->jquerypluginoverrides[$oldplugin] = $newplugin;
 640      }
 641  
 642      /**
 643       * Return jQuery related markup for page start.
 644       * @return string
 645       */
 646      protected function get_jquery_headcode() {
 647          if (empty($this->jqueryplugins['jquery'])) {
 648              // If nobody requested jQuery then do not bother to load anything.
 649              // This may be useful for themes that want to override 'ui-css' only if requested by something else.
 650              return '';
 651          }
 652  
 653          $included = array();
 654          $urls = array();
 655  
 656          foreach ($this->jqueryplugins as $name => $unused) {
 657              if (isset($included[$name])) {
 658                  continue;
 659              }
 660              if (array_key_exists($name, $this->jquerypluginoverrides)) {
 661                  // The following loop tries to resolve the replacements,
 662                  // use max 100 iterations to prevent infinite loop resulting
 663                  // in blank page.
 664                  $cyclic = true;
 665                  $oldname = $name;
 666                  for ($i=0; $i<100; $i++) {
 667                      $name = $this->jquerypluginoverrides[$name];
 668                      if (!array_key_exists($name, $this->jquerypluginoverrides)) {
 669                          $cyclic = false;
 670                          break;
 671                      }
 672                  }
 673                  if ($cyclic) {
 674                      // We can not do much with cyclic references here, let's use the old plugin.
 675                      $name = $oldname;
 676                      debugging("Cyclic overrides detected for jQuery plugin '$name'");
 677  
 678                  } else if (empty($name)) {
 679                      // Developer requested removal of the plugin.
 680                      continue;
 681  
 682                  } else if (!isset($this->jqueryplugins[$name])) {
 683                      debugging("Unknown jQuery override plugin '$name' detected");
 684                      $name = $oldname;
 685  
 686                  } else if (isset($included[$name])) {
 687                      // The plugin was already included, easy.
 688                      continue;
 689                  }
 690              }
 691  
 692              $plugin = $this->jqueryplugins[$name];
 693              $urls = array_merge($urls, $plugin->urls);
 694              $included[$name] = true;
 695          }
 696  
 697          $output = '';
 698          $attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
 699          foreach ($urls as $url) {
 700              if (preg_match('/\.js$/', $url)) {
 701                  $output .= html_writer::script('', $url);
 702              } else if (preg_match('/\.css$/', $url)) {
 703                  $attributes['href'] = $url;
 704                  $output .= html_writer::empty_tag('link', $attributes) . "\n";
 705              }
 706          }
 707  
 708          return $output;
 709      }
 710  
 711      /**
 712       * Returns the actual url through which a script is served.
 713       *
 714       * @param moodle_url|string $url full moodle url, or shortened path to script
 715       * @return moodle_url
 716       */
 717      protected function js_fix_url($url) {
 718          global $CFG;
 719  
 720          if ($url instanceof moodle_url) {
 721              return $url;
 722          } else if (null !== $url && strpos($url, '/') === 0) {
 723              // Fix the admin links if needed.
 724              if ($CFG->admin !== 'admin') {
 725                  if (strpos($url, "/admin/") === 0) {
 726                      $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
 727                  }
 728              }
 729              if (debugging()) {
 730                  // Check file existence only when in debug mode.
 731                  if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
 732                      throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
 733                  }
 734              }
 735              if (substr($url, -3) === '.js') {
 736                  $jsrev = $this->get_jsrev();
 737                  if (empty($CFG->slasharguments)) {
 738                      return new moodle_url('/lib/javascript.php', array('rev'=>$jsrev, 'jsfile'=>$url));
 739                  } else {
 740                      $returnurl = new moodle_url('/lib/javascript.php');
 741                      $returnurl->set_slashargument('/'.$jsrev.$url);
 742                      return $returnurl;
 743                  }
 744              } else {
 745                  return new moodle_url($url);
 746              }
 747          } else {
 748              throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
 749          }
 750      }
 751  
 752      /**
 753       * Find out if JS module present and return details.
 754       *
 755       * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
 756       * @return array description of module or null if not found
 757       */
 758      protected function find_module($component) {
 759          global $CFG, $PAGE;
 760  
 761          $module = null;
 762  
 763          if (strpos($component, 'core_') === 0) {
 764              // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
 765              // so that we do nto have to repeat the definition of these modules over and over again.
 766              switch($component) {
 767                  case 'core_filepicker':
 768                      $module = array('name'     => 'core_filepicker',
 769                                      'fullpath' => '/repository/filepicker.js',
 770                                      'requires' => array(
 771                                          'base', 'node', 'node-event-simulate', 'json', 'async-queue', 'io-base', 'io-upload-iframe', 'io-form',
 772                                          'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort', 'resize-plugin', 'dd-plugin',
 773                                          'escape', 'moodle-core_filepicker', 'moodle-core-notification-dialogue'
 774                                      ),
 775                                      'strings'  => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
 776                                                          array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
 777                                                          array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
 778                                                          array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
 779                                                          array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
 780                                                          array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
 781                                                          array('referencesexist', 'repository'), array('select', 'repository')
 782                                                      ));
 783                      break;
 784                  case 'core_comment':
 785                      $module = array('name'     => 'core_comment',
 786                                      'fullpath' => '/comment/comment.js',
 787                                      'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay', 'escape'),
 788                                      'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
 789                                  );
 790                      break;
 791                  case 'core_role':
 792                      $module = array('name'     => 'core_role',
 793                                      'fullpath' => '/admin/roles/module.js',
 794                                      'requires' => array('node', 'cookie'));
 795                      break;
 796                  case 'core_completion':
 797                      break;
 798                  case 'core_message':
 799                      $module = array('name'     => 'core_message',
 800                                      'requires' => array('base', 'node', 'event', 'node-event-simulate'),
 801                                      'fullpath' => '/message/module.js');
 802                      break;
 803                  case 'core_group':
 804                      $module = array('name'     => 'core_group',
 805                                      'fullpath' => '/group/module.js',
 806                                      'requires' => array('node', 'overlay', 'event-mouseenter'));
 807                      break;
 808                  case 'core_question_engine':
 809                      $module = array('name'     => 'core_question_engine',
 810                                      'fullpath' => '/question/qengine.js',
 811                                      'requires' => array('node', 'event'));
 812                      break;
 813                  case 'core_rating':
 814                      $module = array('name'     => 'core_rating',
 815                                      'fullpath' => '/rating/module.js',
 816                                      'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
 817                      break;
 818                  case 'core_dndupload':
 819                      $module = array('name'     => 'core_dndupload',
 820                                      'fullpath' => '/lib/form/dndupload.js',
 821                                      'requires' => array('node', 'event', 'json', 'core_filepicker'),
 822                                      'strings'  => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
 823                                                          array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesfile', 'error'),
 824                                                          array('sizegb', 'moodle'), array('sizemb', 'moodle'), array('sizekb', 'moodle'), array('sizeb', 'moodle'),
 825                                                          array('maxareabytesreached', 'moodle'), array('serverconnection', 'error'),
 826                                                          array('changesmadereallygoaway', 'moodle'), array('complete', 'moodle')
 827                                                      ));
 828                      break;
 829              }
 830  
 831          } else {
 832              if ($dir = core_component::get_component_directory($component)) {
 833                  if (file_exists("$dir/module.js")) {
 834                      if (strpos($dir, $CFG->dirroot.'/') === 0) {
 835                          $dir = substr($dir, strlen($CFG->dirroot));
 836                          $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
 837                      }
 838                  }
 839              }
 840          }
 841  
 842          return $module;
 843      }
 844  
 845      /**
 846       * Append YUI3 module to default YUI3 JS loader.
 847       * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
 848       *
 849       * @param string|array $module name of module (details are autodetected), or full module specification as array
 850       * @return void
 851       */
 852      public function js_module($module) {
 853          global $CFG;
 854  
 855          if (empty($module)) {
 856              throw new coding_exception('Missing YUI3 module name or full description.');
 857          }
 858  
 859          if (is_string($module)) {
 860              $module = $this->find_module($module);
 861          }
 862  
 863          if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
 864              throw new coding_exception('Missing YUI3 module details.');
 865          }
 866  
 867          $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
 868          // Add all needed strings.
 869          if (!empty($module['strings'])) {
 870              foreach ($module['strings'] as $string) {
 871                  $identifier = $string[0];
 872                  $component = isset($string[1]) ? $string[1] : 'moodle';
 873                  $a = isset($string[2]) ? $string[2] : null;
 874                  $this->string_for_js($identifier, $component, $a);
 875              }
 876          }
 877          unset($module['strings']);
 878  
 879          // Process module requirements and attempt to load each. This allows
 880          // moodle modules to require each other.
 881          if (!empty($module['requires'])){
 882              foreach ($module['requires'] as $requirement) {
 883                  $rmodule = $this->find_module($requirement);
 884                  if (is_array($rmodule)) {
 885                      $this->js_module($rmodule);
 886                  }
 887              }
 888          }
 889  
 890          if ($this->headdone) {
 891              $this->extramodules[$module['name']] = $module;
 892          } else {
 893              $this->YUI_config->add_module_config($module['name'], $module);
 894          }
 895      }
 896  
 897      /**
 898       * Returns true if the module has already been loaded.
 899       *
 900       * @param string|array $module
 901       * @return bool True if the module has already been loaded
 902       */
 903      protected function js_module_loaded($module) {
 904          if (is_string($module)) {
 905              $modulename = $module;
 906          } else {
 907              $modulename = $module['name'];
 908          }
 909          return array_key_exists($modulename, $this->YUI_config->modules) ||
 910                 array_key_exists($modulename, $this->extramodules);
 911      }
 912  
 913      /**
 914       * Ensure that the specified CSS file is linked to from this page.
 915       *
 916       * Because stylesheet links must go in the <head> part of the HTML, you must call
 917       * this function before {@link get_head_code()} is called. That normally means before
 918       * the call to print_header. If you call it when it is too late, an exception
 919       * will be thrown.
 920       *
 921       * Even if a particular style sheet is requested more than once, it will only
 922       * be linked to once.
 923       *
 924       * Please note use of this feature is strongly discouraged,
 925       * it is suitable only for places where CSS is submitted directly by teachers.
 926       * (Students must not be allowed to submit any external CSS because it may
 927       * contain embedded javascript!). Example of correct use is mod/data.
 928       *
 929       * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
 930       *   For example:
 931       *      $PAGE->requires->css('mod/data/css.php?d='.$data->id);
 932       */
 933      public function css($stylesheet) {
 934          global $CFG;
 935  
 936          if ($this->headdone) {
 937              throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
 938          }
 939  
 940          if ($stylesheet instanceof moodle_url) {
 941              // ok
 942          } else if (strpos($stylesheet, '/') === 0) {
 943              $stylesheet = new moodle_url($stylesheet);
 944          } else {
 945              throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
 946          }
 947  
 948          $this->cssurls[$stylesheet->out()] = $stylesheet;
 949      }
 950  
 951      /**
 952       * Add theme stylesheet to page - do not use from plugin code,
 953       * this should be called only from the core renderer!
 954       *
 955       * @param moodle_url $stylesheet
 956       * @return void
 957       */
 958      public function css_theme(moodle_url $stylesheet) {
 959          $this->cssthemeurls[] = $stylesheet;
 960      }
 961  
 962      /**
 963       * Ensure that a skip link to a given target is printed at the top of the <body>.
 964       *
 965       * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
 966       * will be thrown). That normally means you must call this before the call to print_header.
 967       *
 968       * If you ask for a particular skip link to be printed, it is then your responsibility
 969       * to ensure that the appropriate <a name="..."> tag is printed in the body of the
 970       * page, so that the skip link goes somewhere.
 971       *
 972       * Even if a particular skip link is requested more than once, only one copy of it will be output.
 973       *
 974       * @param string $target the name of anchor this link should go to. For example 'maincontent'.
 975       * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
 976       */
 977      public function skip_link_to($target, $linktext) {
 978          if ($this->topofbodydone) {
 979              debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
 980              return;
 981          }
 982          $this->skiplinks[$target] = $linktext;
 983      }
 984  
 985      /**
 986       * !!!DEPRECATED!!! please use js_init_call() if possible
 987       * Ensure that the specified JavaScript function is called from an inline script
 988       * somewhere on this page.
 989       *
 990       * By default the call will be put in a script tag at the
 991       * end of the page after initialising Y instance, since this gives best page-load
 992       * performance and allows you to use YUI3 library.
 993       *
 994       * If you request that a particular function is called several times, then
 995       * that is what will happen (unlike linking to a CSS or JS file, where only
 996       * one link will be output).
 997       *
 998       * The main benefit of the method is the automatic encoding of all function parameters.
 999       *
1000       * @deprecated
1001       *
1002       * @param string $function the name of the JavaScritp function to call. Can
1003       *      be a compound name like 'Y.Event.purgeElement'. Can also be
1004       *      used to create and object by using a 'function name' like 'new user_selector'.
1005       * @param array $arguments and array of arguments to be passed to the function.
1006       *      When generating the function call, this will be escaped using json_encode,
1007       *      so passing objects and arrays should work.
1008       * @param bool $ondomready If tru the function is only called when the dom is
1009       *      ready for manipulation.
1010       * @param int $delay The delay before the function is called.
1011       */
1012      public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
1013          $where = $ondomready ? 'ondomready' : 'normal';
1014          $this->jscalls[$where][] = array($function, $arguments, $delay);
1015      }
1016  
1017      /**
1018       * This function appends a block of code to the AMD specific javascript block executed
1019       * in the page footer, just after loading the requirejs library.
1020       *
1021       * The code passed here can rely on AMD module loading, e.g. require('jquery', function($) {...});
1022       *
1023       * @param string $code The JS code to append.
1024       */
1025      public function js_amd_inline($code) {
1026          $this->amdjscode[] = $code;
1027      }
1028  
1029      /**
1030       * Load an AMD module and eventually call its method.
1031       *
1032       * This function creates a minimal inline JS snippet that requires an AMD module and eventually calls a single
1033       * function from the module with given arguments. If it is called multiple times, it will be create multiple
1034       * snippets.
1035       *
1036       * @param string $fullmodule The name of the AMD module to load, formatted as <component name>/<module name>.
1037       * @param string $func Optional function from the module to call, defaults to just loading the AMD module.
1038       * @param array $params The params to pass to the function (will be serialized into JSON).
1039       */
1040      public function js_call_amd($fullmodule, $func = null, $params = array()) {
1041          global $CFG;
1042  
1043          $modulepath = explode('/', $fullmodule);
1044  
1045          $modname = clean_param(array_shift($modulepath), PARAM_COMPONENT);
1046          foreach ($modulepath as $module) {
1047              $modname .= '/' . clean_param($module, PARAM_ALPHANUMEXT);
1048          }
1049  
1050          $functioncode = [];
1051          if ($func !== null) {
1052              $func = clean_param($func, PARAM_ALPHANUMEXT);
1053  
1054              $jsonparams = array();
1055              foreach ($params as $param) {
1056                  $jsonparams[] = json_encode($param);
1057              }
1058              $strparams = implode(', ', $jsonparams);
1059              if ($CFG->debugdeveloper) {
1060                  $toomanyparamslimit = 1024;
1061                  if (strlen($strparams) > $toomanyparamslimit) {
1062                      debugging('Too much data passed as arguments to js_call_amd("' . $fullmodule . '", "' . $func .
1063                          '"). Generally there are better ways to pass lots of data from PHP to JavaScript, for example via Ajax, ' .
1064                          'data attributes, ... . This warning is triggered if the argument string becomes longer than ' .
1065                          $toomanyparamslimit . ' characters.', DEBUG_DEVELOPER);
1066                  }
1067              }
1068  
1069              $functioncode[] = "amd.{$func}({$strparams});";
1070          }
1071  
1072          $functioncode[] = "M.util.js_complete('{$modname}');";
1073  
1074          $initcode = implode(' ', $functioncode);
1075          $js = "M.util.js_pending('{$modname}'); require(['{$modname}'], function(amd) {{$initcode}});";
1076  
1077          $this->js_amd_inline($js);
1078      }
1079  
1080      /**
1081       * Creates a JavaScript function call that requires one or more modules to be loaded.
1082       *
1083       * This function can be used to include all of the standard YUI module types within JavaScript:
1084       *     - YUI3 modules    [node, event, io]
1085       *     - YUI2 modules    [yui2-*]
1086       *     - Moodle modules  [moodle-*]
1087       *     - Gallery modules [gallery-*]
1088       *
1089       * Before writing new code that makes extensive use of YUI, you should consider it's replacement AMD/JQuery.
1090       * @see js_call_amd()
1091       *
1092       * @param array|string $modules One or more modules
1093       * @param string $function The function to call once modules have been loaded
1094       * @param array $arguments An array of arguments to pass to the function
1095       * @param string $galleryversion Deprecated: The gallery version to use
1096       * @param bool $ondomready
1097       */
1098      public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1099          if (!is_array($modules)) {
1100              $modules = array($modules);
1101          }
1102  
1103          if ($galleryversion != null) {
1104              debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.');
1105          }
1106  
1107          $jscode = 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
1108          if ($ondomready) {
1109              $jscode = "Y.on('domready', function() { $jscode });";
1110          }
1111          $this->jsinitcode[] = $jscode;
1112      }
1113  
1114      /**
1115       * Set the CSS Modules to be included from YUI.
1116       *
1117       * @param array $modules The list of YUI CSS Modules to include.
1118       */
1119      public function set_yuicssmodules(array $modules = array()) {
1120          $this->yuicssmodules = $modules;
1121      }
1122  
1123      /**
1124       * Ensure that the specified JavaScript function is called from an inline script
1125       * from page footer.
1126       *
1127       * @param string $function the name of the JavaScritp function to with init code,
1128       *      usually something like 'M.mod_mymodule.init'
1129       * @param array $extraarguments and array of arguments to be passed to the function.
1130       *      The first argument is always the YUI3 Y instance with all required dependencies
1131       *      already loaded.
1132       * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1133       * @param array $module JS module specification array
1134       */
1135      public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1136          $jscode = js_writer::function_call_with_Y($function, $extraarguments);
1137          if (!$module) {
1138              // Detect module automatically.
1139              if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
1140                  $module = $this->find_module($matches[1]);
1141              }
1142          }
1143  
1144          $this->js_init_code($jscode, $ondomready, $module);
1145      }
1146  
1147      /**
1148       * Add short static javascript code fragment to page footer.
1149       * This is intended primarily for loading of js modules and initialising page layout.
1150       * Ideally the JS code fragment should be stored in plugin renderer so that themes
1151       * may override it.
1152       *
1153       * @param string $jscode
1154       * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1155       * @param array $module JS module specification array
1156       */
1157      public function js_init_code($jscode, $ondomready = false, array $module = null) {
1158          $jscode = trim($jscode, " ;\n"). ';';
1159  
1160          $uniqid = html_writer::random_id();
1161          $startjs = " M.util.js_pending('" . $uniqid . "');";
1162          $endjs = " M.util.js_complete('" . $uniqid . "');";
1163  
1164          if ($module) {
1165              $this->js_module($module);
1166              $modulename = $module['name'];
1167              $jscode = "$startjs Y.use('$modulename', function(Y) { $jscode $endjs });";
1168          }
1169  
1170          if ($ondomready) {
1171              $jscode = "$startjs Y.on('domready', function() { $jscode $endjs });";
1172          }
1173  
1174          $this->jsinitcode[] = $jscode;
1175      }
1176  
1177      /**
1178       * Make a language string available to JavaScript.
1179       *
1180       * All the strings will be available in a M.str object in the global namespace.
1181       * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
1182       * then the JavaScript variable M.str.moodle.course will be 'Course', or the
1183       * equivalent in the current language.
1184       *
1185       * The arguments to this function are just like the arguments to get_string
1186       * except that $component is not optional, and there are some aspects to consider
1187       * when the string contains {$a} placeholder.
1188       *
1189       * If the string does not contain any {$a} placeholder, you can simply use
1190       * M.str.component.identifier to obtain it. If you prefer, you can call
1191       * M.util.get_string(identifier, component) to get the same result.
1192       *
1193       * If you need to use {$a} placeholders, there are two options. Either the
1194       * placeholder should be substituted in PHP on server side or it should
1195       * be substituted in Javascript at client side.
1196       *
1197       * To substitute the placeholder at server side, just provide the required
1198       * value for the placeholder when you require the string. Because each string
1199       * is only stored once in the JavaScript (based on $identifier and $module)
1200       * you cannot get the same string with two different values of $a. If you try,
1201       * an exception will be thrown. Once the placeholder is substituted, you can
1202       * use M.str or M.util.get_string() as shown above:
1203       *
1204       *     // Require the string in PHP and replace the placeholder.
1205       *     $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
1206       *     // Use the result of the substitution in Javascript.
1207       *     alert(M.str.moodle.fullnamedisplay);
1208       *
1209       * To substitute the placeholder at client side, use M.util.get_string()
1210       * function. It implements the same logic as {@link get_string()}:
1211       *
1212       *     // Require the string in PHP but keep {$a} as it is.
1213       *     $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
1214       *     // Provide the values on the fly in Javascript.
1215       *     user = { firstname : 'Harry', lastname : 'Potter' }
1216       *     alert(M.util.get_string('fullnamedisplay', 'moodle', user);
1217       *
1218       * If you do need the same string expanded with different $a values in PHP
1219       * on server side, then the solution is to put them in your own data structure
1220       * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
1221       *
1222       * @param string $identifier the desired string.
1223       * @param string $component the language file to look in.
1224       * @param mixed $a any extra data to add into the string (optional).
1225       */
1226      public function string_for_js($identifier, $component, $a = null) {
1227          if (!$component) {
1228              throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
1229          }
1230          if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
1231              throw new coding_exception("Attempt to re-define already required string '$identifier' " .
1232                      "from lang file '$component' with different \$a parameter?");
1233          }
1234          if (!isset($this->stringsforjs[$component][$identifier])) {
1235              $this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
1236              $this->stringsforjs_as[$component][$identifier] = $a;
1237          }
1238      }
1239  
1240      /**
1241       * Make an array of language strings available for JS.
1242       *
1243       * This function calls the above function {@link string_for_js()} for each requested
1244       * string in the $identifiers array that is passed to the argument for a single module
1245       * passed in $module.
1246       *
1247       * <code>
1248       * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
1249       *
1250       * // The above is identical to calling:
1251       *
1252       * $PAGE->requires->string_for_js('one', 'mymod', 'a');
1253       * $PAGE->requires->string_for_js('two', 'mymod');
1254       * $PAGE->requires->string_for_js('three', 'mymod', 3);
1255       * </code>
1256       *
1257       * @param array $identifiers An array of desired strings
1258       * @param string $component The module to load for
1259       * @param mixed $a This can either be a single variable that gets passed as extra
1260       *         information for every string or it can be an array of mixed data where the
1261       *         key for the data matches that of the identifier it is meant for.
1262       *
1263       */
1264      public function strings_for_js($identifiers, $component, $a = null) {
1265          foreach ($identifiers as $key => $identifier) {
1266              if (is_array($a) && array_key_exists($key, $a)) {
1267                  $extra = $a[$key];
1268              } else {
1269                  $extra = $a;
1270              }
1271              $this->string_for_js($identifier, $component, $extra);
1272          }
1273      }
1274  
1275      /**
1276       * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
1277       *
1278       * Make some data from PHP available to JavaScript code.
1279       *
1280       * For example, if you call
1281       * <pre>
1282       *      $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
1283       * </pre>
1284       * then in JavsScript mydata.name will be 'Moodle'.
1285       *
1286       * @deprecated
1287       * @param string $variable the the name of the JavaScript variable to assign the data to.
1288       *      Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1289       *      should be considered an experimental feature.
1290       * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1291       *      so passing objects and arrays should work.
1292       * @param bool $inhead initialise in head
1293       * @return void
1294       */
1295      public function data_for_js($variable, $data, $inhead=false) {
1296          $where = $inhead ? 'head' : 'footer';
1297          $this->jsinitvariables[$where][] = array($variable, $data);
1298      }
1299  
1300      /**
1301       * Creates a YUI event handler.
1302       *
1303       * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1304       * @param string $event A valid DOM event (click, mousedown, change etc.)
1305       * @param string $function The name of the function to call
1306       * @param array  $arguments An optional array of argument parameters to pass to the function
1307       */
1308      public function event_handler($selector, $event, $function, array $arguments = null) {
1309          $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
1310      }
1311  
1312      /**
1313       * Returns code needed for registering of event handlers.
1314       * @return string JS code
1315       */
1316      protected function get_event_handler_code() {
1317          $output = '';
1318          foreach ($this->eventhandlers as $h) {
1319              $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
1320          }
1321          return $output;
1322      }
1323  
1324      /**
1325       * Get the inline JavaScript code that need to appear in a particular place.
1326       * @param bool $ondomready
1327       * @return string
1328       */
1329      protected function get_javascript_code($ondomready) {
1330          $where = $ondomready ? 'ondomready' : 'normal';
1331          $output = '';
1332          if ($this->jscalls[$where]) {
1333              foreach ($this->jscalls[$where] as $data) {
1334                  $output .= js_writer::function_call($data[0], $data[1], $data[2]);
1335              }
1336              if (!empty($ondomready)) {
1337                  $output = "    Y.on('domready', function() {\n$output\n});";
1338              }
1339          }
1340          return $output;
1341      }
1342  
1343      /**
1344       * Returns js code to be executed when Y is available.
1345       * @return string
1346       */
1347      protected function get_javascript_init_code() {
1348          if (count($this->jsinitcode)) {
1349              return implode("\n", $this->jsinitcode) . "\n";
1350          }
1351          return '';
1352      }
1353  
1354      /**
1355       * Returns js code to load amd module loader, then insert inline script tags
1356       * that contain require() calls using RequireJS.
1357       * @return string
1358       */
1359      protected function get_amd_footercode() {
1360          global $CFG;
1361          $output = '';
1362  
1363          // We will cache JS if cachejs is not set, or it is true.
1364          $cachejs = !isset($CFG->cachejs) || $CFG->cachejs;
1365          $jsrev = $this->get_jsrev();
1366  
1367          $jsloader = new moodle_url('/lib/javascript.php');
1368          $jsloader->set_slashargument('/' . $jsrev . '/');
1369          $requirejsloader = new moodle_url('/lib/requirejs.php');
1370          $requirejsloader->set_slashargument('/' . $jsrev . '/');
1371  
1372          $requirejsconfig = file_get_contents($CFG->dirroot . '/lib/requirejs/moodle-config.js');
1373  
1374          // No extension required unless slash args is disabled.
1375          $jsextension = '.js';
1376          if (!empty($CFG->slasharguments)) {
1377              $jsextension = '';
1378          }
1379  
1380          $minextension = '.min';
1381          if (!$cachejs) {
1382              $minextension = '';
1383          }
1384  
1385          $requirejsconfig = str_replace('[BASEURL]', $requirejsloader, $requirejsconfig);
1386          $requirejsconfig = str_replace('[JSURL]', $jsloader, $requirejsconfig);
1387          $requirejsconfig = str_replace('[JSMIN]', $minextension, $requirejsconfig);
1388          $requirejsconfig = str_replace('[JSEXT]', $jsextension, $requirejsconfig);
1389  
1390          $output .= html_writer::script($requirejsconfig);
1391          if ($cachejs) {
1392              $output .= html_writer::script('', $this->js_fix_url('/lib/requirejs/require.min.js'));
1393          } else {
1394              $output .= html_writer::script('', $this->js_fix_url('/lib/requirejs/require.js'));
1395          }
1396  
1397          // First include must be to a module with no dependencies, this prevents multiple requests.
1398          $prefix = <<<EOF
1399  M.util.js_pending("core/first");
1400  require(['core/first'], function() {
1401  
1402  EOF;
1403  
1404          if (during_initial_install()) {
1405              // Do not run a prefetch during initial install as the DB is not available to service WS calls.
1406              $prefetch = '';
1407          } else {
1408              $prefetch = "require(['core/prefetch'])\n";
1409          }
1410  
1411          $suffix = <<<EOF
1412  
1413      M.util.js_complete("core/first");
1414  });
1415  EOF;
1416  
1417          $output .= html_writer::script($prefix . $prefetch . implode(";\n", $this->amdjscode) . $suffix);
1418          return $output;
1419      }
1420  
1421      /**
1422       * Returns basic YUI3 CSS code.
1423       *
1424       * @return string
1425       */
1426      protected function get_yui3lib_headcss() {
1427          global $CFG;
1428  
1429          $yuiformat = '-min';
1430          if ($this->yui3loader->filter === 'RAW') {
1431              $yuiformat = '';
1432          }
1433  
1434          $code = '';
1435          if ($this->yui3loader->combine) {
1436              if (!empty($this->yuicssmodules)) {
1437                  $modules = array();
1438                  foreach ($this->yuicssmodules as $module) {
1439                      $modules[] = "$CFG->yui3version/$module/$module-min.css";
1440                  }
1441                  $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase.implode('&amp;', $modules).'" />';
1442              }
1443              $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
1444  
1445          } else {
1446              if (!empty($this->yuicssmodules)) {
1447                  foreach ($this->yuicssmodules as $module) {
1448                      $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.$module.'/'.$module.'-min.css" />';
1449                  }
1450              }
1451              $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
1452          }
1453  
1454          if ($this->yui3loader->filter === 'RAW') {
1455              $code = str_replace('-min.css', '.css', $code);
1456          } else if ($this->yui3loader->filter === 'DEBUG') {
1457              $code = str_replace('-min.css', '.css', $code);
1458          }
1459          return $code;
1460      }
1461  
1462      /**
1463       * Returns basic YUI3 JS loading code.
1464       *
1465       * @return string
1466       */
1467      protected function get_yui3lib_headcode() {
1468          global $CFG;
1469  
1470          $jsrev = $this->get_jsrev();
1471  
1472          $yuiformat = '-min';
1473          if ($this->yui3loader->filter === 'RAW') {
1474              $yuiformat = '';
1475          }
1476  
1477          $format = '-min';
1478          if ($this->YUI_config->groups['moodle']['filter'] === 'DEBUG') {
1479              $format = '-debug';
1480          }
1481  
1482          $rollupversion = $CFG->yui3version;
1483          if (!empty($CFG->yuipatchlevel)) {
1484              $rollupversion .= '_' . $CFG->yuipatchlevel;
1485          }
1486  
1487          $baserollups = array(
1488              'rollup/' . $rollupversion . "/yui-moodlesimple{$yuiformat}.js",
1489          );
1490  
1491          if ($this->yui3loader->combine) {
1492              return '<script src="' .
1493                      $this->yui3loader->local_comboBase .
1494                      implode('&amp;', $baserollups) .
1495                      '"></script>';
1496          } else {
1497              $code = '';
1498              foreach ($baserollups as $rollup) {
1499                  $code .= '<script src="'.$this->yui3loader->local_comboBase.$rollup.'"></script>';
1500              }
1501              return $code;
1502          }
1503  
1504      }
1505  
1506      /**
1507       * Returns html tags needed for inclusion of theme CSS.
1508       *
1509       * @return string
1510       */
1511      protected function get_css_code() {
1512          // First of all the theme CSS, then any custom CSS
1513          // Please note custom CSS is strongly discouraged,
1514          // because it can not be overridden by themes!
1515          // It is suitable only for things like mod/data which accepts CSS from teachers.
1516          $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1517  
1518          // Add the YUI code first. We want this to be overridden by any Moodle CSS.
1519          $code = $this->get_yui3lib_headcss();
1520  
1521          // This line of code may look funny but it is currently required in order
1522          // to avoid MASSIVE display issues in Internet Explorer.
1523          // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1524          // ignored whenever another resource is added until such time as a redraw
1525          // is forced, usually by moving the mouse over the affected element.
1526          $code .= html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1527  
1528          $urls = $this->cssthemeurls + $this->cssurls;
1529          foreach ($urls as $url) {
1530              $attributes['href'] = $url;
1531              $code .= html_writer::empty_tag('link', $attributes) . "\n";
1532              // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1533              unset($attributes['id']);
1534          }
1535  
1536          return $code;
1537      }
1538  
1539      /**
1540       * Adds extra modules specified after printing of page header.
1541       *
1542       * @return string
1543       */
1544      protected function get_extra_modules_code() {
1545          if (empty($this->extramodules)) {
1546              return '';
1547          }
1548          return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1549      }
1550  
1551      /**
1552       * Generate any HTML that needs to go inside the <head> tag.
1553       *
1554       * Normally, this method is called automatically by the code that prints the
1555       * <head> tag. You should not normally need to call it in your own code.
1556       *
1557       * @param moodle_page $page
1558       * @param core_renderer $renderer
1559       * @return string the HTML code to to inside the <head> tag.
1560       */
1561      public function get_head_code(moodle_page $page, core_renderer $renderer) {
1562          global $CFG;
1563  
1564          // Note: the $page and $output are not stored here because it would
1565          // create circular references in memory which prevents garbage collection.
1566          $this->init_requirements_data($page, $renderer);
1567  
1568          $output = '';
1569  
1570          // Add all standard CSS for this page.
1571          $output .= $this->get_css_code();
1572  
1573          // Set up the M namespace.
1574          $js = "var M = {}; M.yui = {};\n";
1575  
1576          // Capture the time now ASAP during page load. This minimises the lag when
1577          // we try to relate times on the server to times in the browser.
1578          // An example of where this is used is the quiz countdown timer.
1579          $js .= "M.pageloadstarttime = new Date();\n";
1580  
1581          // Add a subset of Moodle configuration to the M namespace.
1582          $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1583  
1584          // Set up global YUI3 loader object - this should contain all code needed by plugins.
1585          // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1586          //       this needs to be done before including any other script.
1587          $js .= $this->YUI_config->get_config_functions();
1588          $js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n";
1589          $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1590          $js = $this->YUI_config->update_header_js($js);
1591  
1592          $output .= html_writer::script($js);
1593  
1594          // Add variables.
1595          if ($this->jsinitvariables['head']) {
1596              $js = '';
1597              foreach ($this->jsinitvariables['head'] as $data) {
1598                  list($var, $value) = $data;
1599                  $js .= js_writer::set_variable($var, $value, true);
1600              }
1601              $output .= html_writer::script($js);
1602          }
1603  
1604          // Mark head sending done, it is not possible to anything there.
1605          $this->headdone = true;
1606  
1607          return $output;
1608      }
1609  
1610      /**
1611       * Generate any HTML that needs to go at the start of the <body> tag.
1612       *
1613       * Normally, this method is called automatically by the code that prints the
1614       * <head> tag. You should not normally need to call it in your own code.
1615       *
1616       * @param renderer_base $renderer
1617       * @return string the HTML code to go at the start of the <body> tag.
1618       */
1619      public function get_top_of_body_code(renderer_base $renderer) {
1620          global $CFG;
1621  
1622          // First the skip links.
1623          $output = $renderer->render_skip_links($this->skiplinks);
1624  
1625          // Include the Polyfills.
1626          $output .= html_writer::script('', $this->js_fix_url('/lib/polyfills/polyfill.js'));
1627  
1628          // YUI3 JS needs to be loaded early in the body. It should be cached well by the browser.
1629          $output .= $this->get_yui3lib_headcode();
1630  
1631          // Add hacked jQuery support, it is not intended for standard Moodle distribution!
1632          $output .= $this->get_jquery_headcode();
1633  
1634          // Link our main JS file, all core stuff should be there.
1635          $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1636  
1637          // All the other linked things from HEAD - there should be as few as possible.
1638          if ($this->jsincludes['head']) {
1639              foreach ($this->jsincludes['head'] as $url) {
1640                  $output .= html_writer::script('', $url);
1641              }
1642          }
1643  
1644          // Then the clever trick for hiding of things not needed when JS works.
1645          $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1646          $this->topofbodydone = true;
1647          return $output;
1648      }
1649  
1650      /**
1651       * Generate any HTML that needs to go at the end of the page.
1652       *
1653       * Normally, this method is called automatically by the code that prints the
1654       * page footer. You should not normally need to call it in your own code.
1655       *
1656       * @return string the HTML code to to at the end of the page.
1657       */
1658      public function get_end_code() {
1659          global $CFG;
1660          $output = '';
1661  
1662          // Set the log level for the JS logging.
1663          $logconfig = new stdClass();
1664          $logconfig->level = 'warn';
1665          if ($CFG->debugdeveloper) {
1666              $logconfig->level = 'trace';
1667          }
1668          $this->js_call_amd('core/log', 'setConfig', array($logconfig));
1669          // Add any global JS that needs to run on all pages.
1670          $this->js_call_amd('core/page_global', 'init');
1671          $this->js_call_amd('core/utility');
1672  
1673          // Call amd init functions.
1674          $output .= $this->get_amd_footercode();
1675  
1676          // Add other requested modules.
1677          $output .= $this->get_extra_modules_code();
1678  
1679          $this->js_init_code('M.util.js_complete("init");', true);
1680  
1681          // All the other linked scripts - there should be as few as possible.
1682          if ($this->jsincludes['footer']) {
1683              foreach ($this->jsincludes['footer'] as $url) {
1684                  $output .= html_writer::script('', $url);
1685              }
1686          }
1687  
1688          // Add all needed strings.
1689          // First add core strings required for some dialogues.
1690          $this->strings_for_js(array(
1691              'confirm',
1692              'yes',
1693              'no',
1694              'areyousure',
1695              'closebuttontitle',
1696              'unknownerror',
1697              'error',
1698              'file',
1699              'url',
1700              // TODO MDL-70830 shortforms should preload the collapseall/expandall strings properly.
1701              'collapseall',
1702              'expandall',
1703          ), 'moodle');
1704          $this->strings_for_js(array(
1705              'debuginfo',
1706              'line',
1707              'stacktrace',
1708          ), 'debug');
1709          $this->string_for_js('labelsep', 'langconfig');
1710          if (!empty($this->stringsforjs)) {
1711              $strings = array();
1712              foreach ($this->stringsforjs as $component=>$v) {
1713                  foreach($v as $indentifier => $langstring) {
1714                      $strings[$component][$indentifier] = $langstring->out();
1715                  }
1716              }
1717              $output .= html_writer::script(js_writer::set_variable('M.str', $strings));
1718          }
1719  
1720          // Add variables.
1721          if ($this->jsinitvariables['footer']) {
1722              $js = '';
1723              foreach ($this->jsinitvariables['footer'] as $data) {
1724                  list($var, $value) = $data;
1725                  $js .= js_writer::set_variable($var, $value, true);
1726              }
1727              $output .= html_writer::script($js);
1728          }
1729  
1730          $inyuijs = $this->get_javascript_code(false);
1731          $ondomreadyjs = $this->get_javascript_code(true);
1732          $jsinit = $this->get_javascript_init_code();
1733          $handlersjs = $this->get_event_handler_code();
1734  
1735          // There is a global Y, make sure it is available in your scope.
1736          $js = "(function() {{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}})();";
1737  
1738          $output .= html_writer::script($js);
1739  
1740          return $output;
1741      }
1742  
1743      /**
1744       * Have we already output the code in the <head> tag?
1745       *
1746       * @return bool
1747       */
1748      public function is_head_done() {
1749          return $this->headdone;
1750      }
1751  
1752      /**
1753       * Have we already output the code at the start of the <body> tag?
1754       *
1755       * @return bool
1756       */
1757      public function is_top_of_body_done() {
1758          return $this->topofbodydone;
1759      }
1760  
1761      /**
1762       * Should we generate a bit of content HTML that is only required once  on
1763       * this page (e.g. the contents of the modchooser), now? Basically, we call
1764       * {@link has_one_time_item_been_created()}, and if the thing has not already
1765       * been output, we return true to tell the caller to generate it, and also
1766       * call {@link set_one_time_item_created()} to record the fact that it is
1767       * about to be generated.
1768       *
1769       * That is, a typical usage pattern (in a renderer method) is:
1770       * <pre>
1771       * if (!$this->page->requires->should_create_one_time_item_now($thing)) {
1772       *     return '';
1773       * }
1774       * // Else generate it.
1775       * </pre>
1776       *
1777       * @param string $thing identifier for the bit of content. Should be of the form
1778       *      frankenstyle_things, e.g. core_course_modchooser.
1779       * @return bool if true, the caller should generate that bit of output now, otherwise don't.
1780       */
1781      public function should_create_one_time_item_now($thing) {
1782          if ($this->has_one_time_item_been_created($thing)) {
1783              return false;
1784          }
1785  
1786          $this->set_one_time_item_created($thing);
1787          return true;
1788      }
1789  
1790      /**
1791       * Has a particular bit of HTML that is only required once  on this page
1792       * (e.g. the contents of the modchooser) already been generated?
1793       *
1794       * Normally, you can use the {@link should_create_one_time_item_now()} helper
1795       * method rather than calling this method directly.
1796       *
1797       * @param string $thing identifier for the bit of content. Should be of the form
1798       *      frankenstyle_things, e.g. core_course_modchooser.
1799       * @return bool whether that bit of output has been created.
1800       */
1801      public function has_one_time_item_been_created($thing) {
1802          return isset($this->onetimeitemsoutput[$thing]);
1803      }
1804  
1805      /**
1806       * Indicate that a particular bit of HTML that is only required once on this
1807       * page (e.g. the contents of the modchooser) has been generated (or is about to be)?
1808       *
1809       * Normally, you can use the {@link should_create_one_time_item_now()} helper
1810       * method rather than calling this method directly.
1811       *
1812       * @param string $thing identifier for the bit of content. Should be of the form
1813       *      frankenstyle_things, e.g. core_course_modchooser.
1814       */
1815      public function set_one_time_item_created($thing) {
1816          if ($this->has_one_time_item_been_created($thing)) {
1817              throw new coding_exception($thing . ' is only supposed to be ouput ' .
1818                      'once per page, but it seems to be being output again.');
1819          }
1820          return $this->onetimeitemsoutput[$thing] = true;
1821      }
1822  }
1823  
1824  /**
1825   * This class represents the YUI configuration.
1826   *
1827   * @copyright 2013 Andrew Nicols
1828   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1829   * @since Moodle 2.5
1830   * @package core
1831   * @category output
1832   */
1833  class YUI_config {
1834      /**
1835       * These settings must be public so that when the object is converted to json they are exposed.
1836       * Note: Some of these are camelCase because YUI uses camelCase variable names.
1837       *
1838       * The settings are described and documented in the YUI API at:
1839       * - http://yuilibrary.com/yui/docs/api/classes/config.html
1840       * - http://yuilibrary.com/yui/docs/api/classes/Loader.html
1841       */
1842      public $debug = false;
1843      public $base;
1844      public $comboBase;
1845      public $combine;
1846      public $filter = null;
1847      public $insertBefore = 'firstthemesheet';
1848      public $groups = array();
1849      public $modules = array();
1850  
1851      /**
1852       * @var array List of functions used by the YUI Loader group pattern recognition.
1853       */
1854      protected $jsconfigfunctions = array();
1855  
1856      /**
1857       * Create a new group within the YUI_config system.
1858       *
1859       * @param String $name The name of the group. This must be unique and
1860       * not previously used.
1861       * @param Array $config The configuration for this group.
1862       * @return void
1863       */
1864      public function add_group($name, $config) {
1865          if (isset($this->groups[$name])) {
1866              throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
1867          }
1868          $this->groups[$name] = $config;
1869      }
1870  
1871      /**
1872       * Update an existing group configuration
1873       *
1874       * Note, any existing configuration for that group will be wiped out.
1875       * This includes module configuration.
1876       *
1877       * @param String $name The name of the group. This must be unique and
1878       * not previously used.
1879       * @param Array $config The configuration for this group.
1880       * @return void
1881       */
1882      public function update_group($name, $config) {
1883          if (!isset($this->groups[$name])) {
1884              throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.');
1885          }
1886          $this->groups[$name] = $config;
1887      }
1888  
1889      /**
1890       * Set the value of a configuration function used by the YUI Loader's pattern testing.
1891       *
1892       * Only the body of the function should be passed, and not the whole function wrapper.
1893       *
1894       * The JS function your write will be passed a single argument 'name' containing the
1895       * name of the module being loaded.
1896       *
1897       * @param $function String the body of the JavaScript function. This should be used i
1898       * @return String the name of the function to use in the group pattern configuration.
1899       */
1900      public function set_config_function($function) {
1901          $configname = 'yui' . (count($this->jsconfigfunctions) + 1) . 'ConfigFn';
1902          if (isset($this->jsconfigfunctions[$configname])) {
1903              throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
1904          }
1905          $this->jsconfigfunctions[$configname] = $function;
1906          return '@' . $configname . '@';
1907      }
1908  
1909      /**
1910       * Allow setting of the config function described in {@see set_config_function} from a file.
1911       * The contents of this file are then passed to set_config_function.
1912       *
1913       * When jsrev is positive, the function is minified and stored in a MUC cache for subsequent uses.
1914       *
1915       * @param $file The path to the JavaScript function used for YUI configuration.
1916       * @return String the name of the function to use in the group pattern configuration.
1917       */
1918      public function set_config_source($file) {
1919          global $CFG;
1920          $cache = cache::make('core', 'yuimodules');
1921  
1922          // Attempt to get the metadata from the cache.
1923          $keyname = 'configfn_' . $file;
1924          $fullpath = $CFG->dirroot . '/' . $file;
1925          if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
1926              $cache->delete($keyname);
1927              $configfn = file_get_contents($fullpath);
1928          } else {
1929              $configfn = $cache->get($keyname);
1930              if ($configfn === false) {
1931                  require_once($CFG->libdir . '/jslib.php');
1932                  $configfn = core_minify::js_files(array($fullpath));
1933                  $cache->set($keyname, $configfn);
1934              }
1935          }
1936          return $this->set_config_function($configfn);
1937      }
1938  
1939      /**
1940       * Retrieve the list of JavaScript functions for YUI_config groups.
1941       *
1942       * @return String The complete set of config functions
1943       */
1944      public function get_config_functions() {
1945          $configfunctions = '';
1946          foreach ($this->jsconfigfunctions as $functionname => $function) {
1947              $configfunctions .= "var {$functionname} = function(me) {";
1948              $configfunctions .= $function;
1949              $configfunctions .= "};\n";
1950          }
1951          return $configfunctions;
1952      }
1953  
1954      /**
1955       * Update the header JavaScript with any required modification for the YUI Loader.
1956       *
1957       * @param $js String The JavaScript to manipulate.
1958       * @return String the modified JS string.
1959       */
1960      public function update_header_js($js) {
1961          // Update the names of the the configFn variables.
1962          // The PHP json_encode function cannot handle literal names so we have to wrap
1963          // them in @ and then replace them with literals of the same function name.
1964          foreach ($this->jsconfigfunctions as $functionname => $function) {
1965              $js = str_replace('"@' . $functionname . '@"', $functionname, $js);
1966          }
1967          return $js;
1968      }
1969  
1970      /**
1971       * Add configuration for a specific module.
1972       *
1973       * @param String $name The name of the module to add configuration for.
1974       * @param Array $config The configuration for the specified module.
1975       * @param String $group The name of the group to add configuration for.
1976       * If not specified, then this module is added to the global
1977       * configuration.
1978       * @return void
1979       */
1980      public function add_module_config($name, $config, $group = null) {
1981          if ($group) {
1982              if (!isset($this->groups[$name])) {
1983                  throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.');
1984              }
1985              if (!isset($this->groups[$group]['modules'])) {
1986                  $this->groups[$group]['modules'] = array();
1987              }
1988              $modules = &$this->groups[$group]['modules'];
1989          } else {
1990              $modules = &$this->modules;
1991          }
1992          $modules[$name] = $config;
1993      }
1994  
1995      /**
1996       * Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
1997       *
1998       * If js caching is disabled, metadata will not be served causing YUI to calculate
1999       * module dependencies as each module is loaded.
2000       *
2001       * If metadata does not exist it will be created and stored in a MUC entry.
2002       *
2003       * @return void
2004       */
2005      public function add_moodle_metadata() {
2006          global $CFG;
2007          if (!isset($this->groups['moodle'])) {
2008              throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.');
2009          }
2010  
2011          if (!isset($this->groups['moodle']['modules'])) {
2012              $this->groups['moodle']['modules'] = array();
2013          }
2014  
2015          $cache = cache::make('core', 'yuimodules');
2016          if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
2017              $metadata = array();
2018              $metadata = $this->get_moodle_metadata();
2019              $cache->delete('metadata');
2020          } else {
2021              // Attempt to get the metadata from the cache.
2022              if (!$metadata = $cache->get('metadata')) {
2023                  $metadata = $this->get_moodle_metadata();
2024                  $cache->set('metadata', $metadata);
2025              }
2026          }
2027  
2028          // Merge with any metadata added specific to this page which was added manually.
2029          $this->groups['moodle']['modules'] = array_merge($this->groups['moodle']['modules'],
2030                  $metadata);
2031      }
2032  
2033      /**
2034       * Determine the module metadata for all moodle YUI modules.
2035       *
2036       * This works through all modules capable of serving YUI modules, and attempts to get
2037       * metadata for each of those modules.
2038       *
2039       * @return Array of module metadata
2040       */
2041      private function get_moodle_metadata() {
2042          $moodlemodules = array();
2043          // Core isn't a plugin type or subsystem - handle it seperately.
2044          if ($module = $this->get_moodle_path_metadata(core_component::get_component_directory('core'))) {
2045              $moodlemodules = array_merge($moodlemodules, $module);
2046          }
2047  
2048          // Handle other core subsystems.
2049          $subsystems = core_component::get_core_subsystems();
2050          foreach ($subsystems as $subsystem => $path) {
2051              if (is_null($path)) {
2052                  continue;
2053              }
2054              if ($module = $this->get_moodle_path_metadata($path)) {
2055                  $moodlemodules = array_merge($moodlemodules, $module);
2056              }
2057          }
2058  
2059          // And finally the plugins.
2060          $plugintypes = core_component::get_plugin_types();
2061          foreach ($plugintypes as $plugintype => $pathroot) {
2062              $pluginlist = core_component::get_plugin_list($plugintype);
2063              foreach ($pluginlist as $plugin => $path) {
2064                  if ($module = $this->get_moodle_path_metadata($path)) {
2065                      $moodlemodules = array_merge($moodlemodules, $module);
2066                  }
2067              }
2068          }
2069  
2070          return $moodlemodules;
2071      }
2072  
2073      /**
2074       * Helper function process and return the YUI metadata for all of the modules under the specified path.
2075       *
2076       * @param String $path the UNC path to the YUI src directory.
2077       * @return Array the complete array for frankenstyle directory.
2078       */
2079      private function get_moodle_path_metadata($path) {
2080          // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
2081          $baseyui = $path . '/yui/src';
2082          $modules = array();
2083          if (is_dir($baseyui)) {
2084              $items = new DirectoryIterator($baseyui);
2085              foreach ($items as $item) {
2086                  if ($item->isDot() or !$item->isDir()) {
2087                      continue;
2088                  }
2089                  $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
2090                  if (!is_readable($metafile)) {
2091                      continue;
2092                  }
2093                  $metadata = file_get_contents($metafile);
2094                  $modules = array_merge($modules, (array) json_decode($metadata));
2095              }
2096          }
2097          return $modules;
2098      }
2099  
2100      /**
2101       * Define YUI modules which we have been required to patch between releases.
2102       *
2103       * We must do this because we aggressively cache content on the browser, and we must also override use of the
2104       * external CDN which will serve the true authoritative copy of the code without our patches.
2105       *
2106       * @param String combobase The local combobase
2107       * @param String yuiversion The current YUI version
2108       * @param Int patchlevel The patch level we're working to for YUI
2109       * @param Array patchedmodules An array containing the names of the patched modules
2110       * @return void
2111       */
2112      public function define_patched_core_modules($combobase, $yuiversion, $patchlevel, $patchedmodules) {
2113          // The version we use is suffixed with a patchlevel so that we can get additional revisions between YUI releases.
2114          $subversion = $yuiversion . '_' . $patchlevel;
2115  
2116          if ($this->comboBase == $combobase) {
2117              // If we are using the local combobase in the loader, we can add a group and still make use of the combo
2118              // loader. We just need to specify a different root which includes a slightly different YUI version number
2119              // to include our patchlevel.
2120              $patterns = array();
2121              $modules = array();
2122              foreach ($patchedmodules as $modulename) {
2123                  // We must define the pattern and module here so that the loader uses our group configuration instead of
2124                  // the standard module definition. We may lose some metadata provided by upstream but this will be
2125                  // loaded when the module is loaded anyway.
2126                  $patterns[$modulename] = array(
2127                      'group' => 'yui-patched',
2128                  );
2129                  $modules[$modulename] = array();
2130              }
2131  
2132              // Actually add the patch group here.
2133              $this->add_group('yui-patched', array(
2134                  'combine' => true,
2135                  'root' => $subversion . '/',
2136                  'patterns' => $patterns,
2137                  'modules' => $modules,
2138              ));
2139  
2140          } else {
2141              // The CDN is in use - we need to instead use the local combobase for this module and override the modules
2142              // definition. We cannot use the local base - we must use the combobase because we cannot invalidate the
2143              // local base in browser caches.
2144              $fullpathbase = $combobase . $subversion . '/';
2145              foreach ($patchedmodules as $modulename) {
2146                  $this->modules[$modulename] = array(
2147                      'fullpath' => $fullpathbase . $modulename . '/' . $modulename . '-min.js'
2148                  );
2149              }
2150          }
2151      }
2152  }
2153  
2154  /**
2155   * Invalidate all server and client side template caches.
2156   */
2157  function template_reset_all_caches() {
2158      global $CFG;
2159  
2160      $next = time();
2161      if (isset($CFG->templaterev) and $next <= $CFG->templaterev and $CFG->templaterev - $next < 60 * 60) {
2162          // This resolves problems when reset is requested repeatedly within 1s,
2163          // the < 1h condition prevents accidental switching to future dates
2164          // because we might not recover from it.
2165          $next = $CFG->templaterev + 1;
2166      }
2167  
2168      set_config('templaterev', $next);
2169  }
2170  
2171  /**
2172   * Invalidate all server and client side JS caches.
2173   */
2174  function js_reset_all_caches() {
2175      global $CFG;
2176  
2177      $next = time();
2178      if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
2179          // This resolves problems when reset is requested repeatedly within 1s,
2180          // the < 1h condition prevents accidental switching to future dates
2181          // because we might not recover from it.
2182          $next = $CFG->jsrev+1;
2183      }
2184  
2185      set_config('jsrev', $next);
2186  }