Search moodle.org's
Developer Documentation


  • Bug fixes for general core bugs in 2.8.x ended 9 November 2015 (12 months).
  • Bug fixes for security issues in 2.8.x ended 9 May 2016 (18 months).
  • minimum PHP 5.4.4 (always use latest PHP 5.4.x or 5.5.x on Windows - http://windows.php.net/download/), PHP 7 is NOT supported
  • Differences Between: [Versions 28 and 29] [Versions 28 and 30] [Versions 28 and 31] [Versions 28 and 32] [Versions 28 and 33] [Versions 28 and 34] [Versions 28 and 35] [Versions 28 and 36] [Versions 28 and 37]

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

    Search This Site: