Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

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

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