Merge branch 'MDL-78263-master' of https://github.com/jleyva/moodle
[moodle.git] / lib / outputrequirementslib.php
blob071eed348392553c2f0e3ad0f7df78b77ceffd98
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.
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/>.
17 /**
18 * Library functions to facilitate the use of JavaScript in Moodle.
20 * Note: you can find history of this file in lib/ajax/ajaxlib.php
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
28 defined('MOODLE_INTERNAL') || die();
30 /**
31 * This class tracks all the things that are needed by the current page.
33 * Normally, the only instance of this class you will need to work with is the
34 * one accessible via $PAGE->requires.
36 * Typical usage would be
37 * <pre>
38 * $PAGE->requires->js_call_amd('mod_forum/view', 'init');
39 * </pre>
41 * It also supports obsoleted coding style with/without YUI3 modules.
42 * <pre>
43 * $PAGE->requires->js_init_call('M.mod_forum.init_view');
44 * $PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overridable via themes!
45 * $PAGE->requires->js('/mod/mymod/script.js');
46 * $PAGE->requires->js('/mod/mymod/small_but_urgent.js', true);
47 * $PAGE->requires->js_function_call('init_mymod', array($data), true);
48 * </pre>
50 * There are some natural restrictions on some methods. For example, {@link css()}
51 * can only be called before the <head> tag is output. See the comments on the
52 * individual methods for details.
54 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
55 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
56 * @since Moodle 2.0
57 * @package core
58 * @category output
60 class page_requirements_manager {
62 /**
63 * @var array List of string available from JS
65 protected $stringsforjs = array();
67 /**
68 * @var array List of get_string $a parameters - used for validation only.
70 protected $stringsforjs_as = array();
72 /**
73 * @var array List of JS variables to be initialised
75 protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
77 /**
78 * @var array Included JS scripts
80 protected $jsincludes = array('head'=>array(), 'footer'=>array());
82 /**
83 * @var array Inline scripts using RequireJS module loading.
85 protected $amdjscode = array('');
87 /**
88 * @var array List of needed function calls
90 protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
92 /**
93 * @var array List of skip links, those are needed for accessibility reasons
95 protected $skiplinks = array();
97 /**
98 * @var array Javascript code used for initialisation of page, it should
99 * be relatively small
101 protected $jsinitcode = array();
104 * @var array of moodle_url Theme sheets, initialised only from core_renderer
106 protected $cssthemeurls = array();
109 * @var array of moodle_url List of custom theme sheets, these are strongly discouraged!
110 * Useful mostly only for CSS submitted by teachers that is not part of the theme.
112 protected $cssurls = array();
115 * @var array List of requested event handlers
117 protected $eventhandlers = array();
120 * @var array Extra modules
122 protected $extramodules = array();
125 * @var array trackes the names of bits of HTML that are only required once
126 * per page. See {@link has_one_time_item_been_created()},
127 * {@link set_one_time_item_created()} and {@link should_create_one_time_item_now()}.
129 protected $onetimeitemsoutput = array();
132 * @var bool Flag indicated head stuff already printed
134 protected $headdone = false;
137 * @var bool Flag indicating top of body already printed
139 protected $topofbodydone = false;
142 * @var stdClass YUI PHPLoader instance responsible for YUI3 loading from PHP only
144 protected $yui3loader;
147 * @var YUI_config default YUI loader configuration
149 protected $YUI_config;
152 * @var array $yuicssmodules
154 protected $yuicssmodules = array();
157 * @var array Some config vars exposed in JS, please no secret stuff there
159 protected $M_cfg;
162 * @var array list of requested jQuery plugins
164 protected $jqueryplugins = array();
167 * @var array list of jQuery plugin overrides
169 protected $jquerypluginoverrides = array();
172 * Page requirements constructor.
174 public function __construct() {
175 global $CFG;
177 // You may need to set up URL rewrite rule because oversized URLs might not be allowed by web server.
178 $sep = empty($CFG->yuislasharguments) ? '?' : '/';
180 $this->yui3loader = new stdClass();
181 $this->YUI_config = new YUI_config();
183 // Set up some loader options.
184 $this->yui3loader->local_base = $CFG->wwwroot . '/lib/yuilib/'. $CFG->yui3version . '/';
185 $this->yui3loader->local_comboBase = $CFG->wwwroot . '/theme/yui_combo.php'.$sep;
187 $this->yui3loader->base = $this->yui3loader->local_base;
188 $this->yui3loader->comboBase = $this->yui3loader->local_comboBase;
190 // Enable combo loader? This significantly helps with caching and performance!
191 $this->yui3loader->combine = !empty($CFG->yuicomboloading);
193 $jsrev = $this->get_jsrev();
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;
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);
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.
212 'base' => $CFG->wwwroot . '/lib/yuilib/2in3/' . $CFG->yui2version . '/build/',
213 'comboBase' => $CFG->wwwroot . '/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,
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->wwwroot . '/theme/yui_combo.php' . $sep . 'm/' . $jsrev . '/',
228 'combine' => $this->yui3loader->combine,
229 'comboBase' => $CFG->wwwroot . '/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,
240 $this->YUI_config->add_group('gallery', array(
241 'name' => 'gallery',
242 'base' => $CFG->wwwroot . '/lib/yuilib/gallery/',
243 'combine' => $this->yui3loader->combine,
244 'comboBase' => $CFG->wwwroot . '/theme/yui_combo.php' . $sep,
245 'ext' => false,
246 'root' => 'gallery/' . $jsrev . '/',
247 'patterns' => array(
248 'gallery-' => array(
249 'group' => 'gallery',
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';
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;
272 // Include the YUI config log filters.
273 if (!empty($CFG->yuilogexclude) && is_array($CFG->yuilogexclude)) {
274 $this->YUI_config->logExclude = $CFG->yuilogexclude;
276 if (!empty($CFG->yuiloginclude) && is_array($CFG->yuiloginclude)) {
277 $this->YUI_config->logInclude = $CFG->yuiloginclude;
279 if (!empty($CFG->yuiloglevel)) {
280 $this->YUI_config->logLevel = $CFG->yuiloglevel;
283 // Add the moodle group's module data.
284 $this->YUI_config->add_moodle_metadata();
286 // Every page should include definition of following modules.
287 $this->js_module($this->find_module('core_filepicker'));
288 $this->js_module($this->find_module('core_comment'));
292 * Return the safe config values that get set for javascript in "M.cfg".
294 * @since 2.9
295 * @return array List of safe config values that are available to javascript.
297 public function get_config_for_javascript(moodle_page $page, renderer_base $renderer) {
298 global $CFG;
300 if (empty($this->M_cfg)) {
302 $iconsystem = \core\output\icon_system::instance();
304 // It is possible that the $page->context is null, so we can't use $page->context->id.
305 $contextid = null;
306 $contextinstanceid = null;
307 if (!is_null($page->context)) {
308 $contextid = $page->context->id;
309 $contextinstanceid = $page->context->instanceid;
310 $courseid = $page->course->id;
311 $coursecontext = context_course::instance($courseid);
314 $this->M_cfg = array(
315 'wwwroot' => $CFG->wwwroot,
316 'homeurl' => $page->navigation->action,
317 'sesskey' => sesskey(),
318 'sessiontimeout' => $CFG->sessiontimeout,
319 'sessiontimeoutwarning' => $CFG->sessiontimeoutwarning,
320 'themerev' => theme_get_revision(),
321 'slasharguments' => (int)(!empty($CFG->slasharguments)),
322 'theme' => $page->theme->name,
323 'iconsystemmodule' => $iconsystem->get_amd_name(),
324 'jsrev' => $this->get_jsrev(),
325 'admin' => $CFG->admin,
326 'svgicons' => $page->theme->use_svg_icons(),
327 'usertimezone' => usertimezone(),
328 'courseId' => isset($courseid) ? (int) $courseid : 0,
329 'courseContextId' => isset($coursecontext) ? $coursecontext->id : 0,
330 'contextid' => $contextid,
331 'contextInstanceId' => (int) $contextinstanceid,
332 'langrev' => get_string_manager()->get_revision(),
333 'templaterev' => $this->get_templaterev()
335 if ($CFG->debugdeveloper) {
336 $this->M_cfg['developerdebug'] = true;
338 if (defined('BEHAT_SITE_RUNNING')) {
339 $this->M_cfg['behatsiterunning'] = true;
343 return $this->M_cfg;
347 * Initialise with the bits of JavaScript that every Moodle page should have.
349 * @param moodle_page $page
350 * @param core_renderer $renderer
352 protected function init_requirements_data(moodle_page $page, core_renderer $renderer) {
353 global $CFG;
355 // Init the js config.
356 $this->get_config_for_javascript($page, $renderer);
358 // Accessibility stuff.
359 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
361 // Add strings used on many pages.
362 $this->string_for_js('confirmation', 'admin');
363 $this->string_for_js('cancel', 'moodle');
364 $this->string_for_js('yes', 'moodle');
366 // Alter links in top frame to break out of frames.
367 if ($page->pagelayout === 'frametop') {
368 $this->js_init_call('M.util.init_frametop');
371 // Include block drag/drop if editing is on
372 if ($page->user_is_editing()) {
373 $params = array(
374 'regions' => $page->blocks->get_regions(),
375 'pagehash' => $page->get_edited_page_hash(),
377 if (!empty($page->cm->id)) {
378 $params['cmid'] = $page->cm->id;
380 // Strings for drag and drop.
381 $this->strings_for_js(array('movecontent',
382 'tocontent',
383 'emptydragdropregion'),
384 'moodle');
385 $page->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
386 $page->requires->js_call_amd('core_block/edit', 'init', ['pagehash' => $page->get_edited_page_hash()]);
389 // Include the YUI CSS Modules.
390 $page->requires->set_yuicssmodules($page->theme->yuicssmodules);
394 * Determine the correct JS Revision to use for this load.
396 * @return int the jsrev to use.
398 public function get_jsrev() {
399 global $CFG;
401 if (empty($CFG->cachejs)) {
402 $jsrev = -1;
403 } else if (empty($CFG->jsrev)) {
404 $jsrev = 1;
405 } else {
406 $jsrev = $CFG->jsrev;
409 return $jsrev;
413 * Determine the correct Template revision to use for this load.
415 * @return int the templaterev to use.
417 protected function get_templaterev() {
418 global $CFG;
420 if (empty($CFG->cachetemplates)) {
421 $templaterev = -1;
422 } else if (empty($CFG->templaterev)) {
423 $templaterev = 1;
424 } else {
425 $templaterev = $CFG->templaterev;
428 return $templaterev;
432 * Ensure that the specified JavaScript file is linked to from this page.
434 * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
435 * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
437 * By default the link is put at the end of the page, since this gives best page-load performance.
439 * Even if a particular script is requested more than once, it will only be linked
440 * to once.
442 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
443 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
444 * @param bool $inhead initialise in head
446 public function js($url, $inhead = false) {
447 if ($url == '/question/qengine.js') {
448 debugging('The question/qengine.js has been deprecated. ' .
449 'Please use core_question/question_engine', DEBUG_DEVELOPER);
451 $url = $this->js_fix_url($url);
452 $where = $inhead ? 'head' : 'footer';
453 $this->jsincludes[$where][$url->out()] = $url;
457 * Request inclusion of jQuery library in the page.
459 * NOTE: this should not be used in official Moodle distribution!
461 * {@see http://docs.moodle.org/dev/jQuery}
463 public function jquery() {
464 $this->jquery_plugin('jquery');
468 * Request inclusion of jQuery plugin.
470 * NOTE: this should not be used in official Moodle distribution!
472 * jQuery plugins are located in plugin/jquery/* subdirectory,
473 * plugin/jquery/plugins.php lists all available plugins.
475 * Included core plugins:
476 * - jQuery UI
478 * Add-ons may include extra jQuery plugins in jquery/ directory,
479 * plugins.php file defines the mapping between plugin names and
480 * necessary page includes.
482 * Examples:
483 * <code>
484 * // file: mod/xxx/view.php
485 * $PAGE->requires->jquery();
486 * $PAGE->requires->jquery_plugin('ui');
487 * $PAGE->requires->jquery_plugin('ui-css');
488 * </code>
490 * <code>
491 * // file: theme/yyy/lib.php
492 * function theme_yyy_page_init(moodle_page $page) {
493 * $page->requires->jquery();
494 * $page->requires->jquery_plugin('ui');
495 * $page->requires->jquery_plugin('ui-css');
497 * </code>
499 * <code>
500 * // file: blocks/zzz/block_zzz.php
501 * public function get_required_javascript() {
502 * parent::get_required_javascript();
503 * $this->page->requires->jquery();
504 * $page->requires->jquery_plugin('ui');
505 * $page->requires->jquery_plugin('ui-css');
507 * </code>
509 * {@see http://docs.moodle.org/dev/jQuery}
511 * @param string $plugin name of the jQuery plugin as defined in jquery/plugins.php
512 * @param string $component name of the component
513 * @return bool success
515 public function jquery_plugin($plugin, $component = 'core') {
516 global $CFG;
518 if ($this->headdone) {
519 debugging('Can not add jQuery plugins after starting page output!');
520 return false;
523 if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css'))) {
524 debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER);
525 $component = 'core';
526 } else if ($component !== 'core' and strpos($component, '_') === false) {
527 // Let's normalise the legacy activity names, Frankenstyle rulez!
528 $component = 'mod_' . $component;
531 if (empty($this->jqueryplugins) and ($component !== 'core' or $plugin !== 'jquery')) {
532 // Make sure the jQuery itself is always loaded first,
533 // the order of all other plugins depends on order of $PAGE_>requires->.
534 $this->jquery_plugin('jquery', 'core');
537 if (isset($this->jqueryplugins[$plugin])) {
538 // No problem, we already have something, first Moodle plugin to register the jQuery plugin wins.
539 return true;
542 $componentdir = core_component::get_component_directory($component);
543 if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
544 debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER);
545 return false;
548 $plugins = array();
549 require("$componentdir/jquery/plugins.php");
551 if (!isset($plugins[$plugin])) {
552 debugging("jQuery plugin '$plugin' can not be found in component '$component'.", DEBUG_DEVELOPER);
553 return false;
556 $this->jqueryplugins[$plugin] = new stdClass();
557 $this->jqueryplugins[$plugin]->plugin = $plugin;
558 $this->jqueryplugins[$plugin]->component = $component;
559 $this->jqueryplugins[$plugin]->urls = array();
561 foreach ($plugins[$plugin]['files'] as $file) {
562 if ($CFG->debugdeveloper) {
563 if (!file_exists("$componentdir/jquery/$file")) {
564 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
565 continue;
567 $file = str_replace('.min.css', '.css', $file);
568 $file = str_replace('.min.js', '.js', $file);
570 if (!file_exists("$componentdir/jquery/$file")) {
571 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
572 continue;
574 if (!empty($CFG->slasharguments)) {
575 $url = new moodle_url("/theme/jquery.php");
576 $url->set_slashargument("/$component/$file");
578 } else {
579 // This is not really good, we need slasharguments for relative links, this means no caching...
580 $path = realpath("$componentdir/jquery/$file");
581 if (strpos($path, $CFG->dirroot) === 0) {
582 $url = $CFG->wwwroot.preg_replace('/^'.preg_quote($CFG->dirroot, '/').'/', '', $path);
583 // Replace all occurences of backslashes characters in url to forward slashes.
584 $url = str_replace('\\', '/', $url);
585 $url = new moodle_url($url);
586 } else {
587 // Bad luck, fix your server!
588 debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
589 continue;
592 $this->jqueryplugins[$plugin]->urls[] = $url;
595 return true;
599 * Request replacement of one jQuery plugin by another.
601 * This is useful when themes want to replace the jQuery UI theme,
602 * the problem is that theme can not prevent others from including the core ui-css plugin.
604 * Example:
605 * 1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
606 * 2/ write theme/yourtheme/jquery/plugins.php
607 * 3/ init jQuery from theme
609 * <code>
610 * // file theme/yourtheme/lib.php
611 * function theme_yourtheme_page_init($page) {
612 * $page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
613 * $page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
615 * </code>
617 * This code prevents loading of standard 'ui-css' which my be requested by other plugins,
618 * the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
620 * {@see http://docs.moodle.org/dev/jQuery}
622 * @param string $oldplugin original plugin
623 * @param string $newplugin the replacement
625 public function jquery_override_plugin($oldplugin, $newplugin) {
626 if ($this->headdone) {
627 debugging('Can not override jQuery plugins after starting page output!');
628 return;
630 $this->jquerypluginoverrides[$oldplugin] = $newplugin;
634 * Return jQuery related markup for page start.
635 * @return string
637 protected function get_jquery_headcode() {
638 if (empty($this->jqueryplugins['jquery'])) {
639 // If nobody requested jQuery then do not bother to load anything.
640 // This may be useful for themes that want to override 'ui-css' only if requested by something else.
641 return '';
644 $included = array();
645 $urls = array();
647 foreach ($this->jqueryplugins as $name => $unused) {
648 if (isset($included[$name])) {
649 continue;
651 if (array_key_exists($name, $this->jquerypluginoverrides)) {
652 // The following loop tries to resolve the replacements,
653 // use max 100 iterations to prevent infinite loop resulting
654 // in blank page.
655 $cyclic = true;
656 $oldname = $name;
657 for ($i=0; $i<100; $i++) {
658 $name = $this->jquerypluginoverrides[$name];
659 if (!array_key_exists($name, $this->jquerypluginoverrides)) {
660 $cyclic = false;
661 break;
664 if ($cyclic) {
665 // We can not do much with cyclic references here, let's use the old plugin.
666 $name = $oldname;
667 debugging("Cyclic overrides detected for jQuery plugin '$name'");
669 } else if (empty($name)) {
670 // Developer requested removal of the plugin.
671 continue;
673 } else if (!isset($this->jqueryplugins[$name])) {
674 debugging("Unknown jQuery override plugin '$name' detected");
675 $name = $oldname;
677 } else if (isset($included[$name])) {
678 // The plugin was already included, easy.
679 continue;
683 $plugin = $this->jqueryplugins[$name];
684 $urls = array_merge($urls, $plugin->urls);
685 $included[$name] = true;
688 $output = '';
689 $attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
690 foreach ($urls as $url) {
691 if (preg_match('/\.js$/', $url)) {
692 $output .= html_writer::script('', $url);
693 } else if (preg_match('/\.css$/', $url)) {
694 $attributes['href'] = $url;
695 $output .= html_writer::empty_tag('link', $attributes) . "\n";
699 return $output;
703 * Returns the actual url through which a JavaScript file is served.
705 * @param moodle_url|string $url full moodle url, or shortened path to script.
706 * @throws coding_exception if the given $url isn't a shortened url starting with / or a moodle_url instance.
707 * @return moodle_url
709 protected function js_fix_url($url) {
710 global $CFG;
712 if ($url instanceof moodle_url) {
713 // If the URL is external to Moodle, it won't be handled by Moodle (!).
714 if ($url->is_local_url()) {
715 $localurl = $url->out_as_local_url();
716 // Check if the URL points to a Moodle PHP resource.
717 if (strpos($localurl, '.php') !== false) {
718 // It's a Moodle PHP resource e.g. a resource already served by the proper Moodle Handler.
719 return $url;
721 // It's a local resource: we need to further examine it.
722 return $this->js_fix_url($url->out_as_local_url(false));
724 // The URL is not a Moodle resource.
725 return $url;
726 } else if (null !== $url && strpos($url, '/') === 0) {
727 // Fix the admin links if needed.
728 if ($CFG->admin !== 'admin') {
729 if (strpos($url, "/admin/") === 0) {
730 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
733 if (debugging()) {
734 // Check file existence only when in debug mode.
735 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
736 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
739 if (substr($url, -3) === '.js') {
740 $jsrev = $this->get_jsrev();
741 if (empty($CFG->slasharguments)) {
742 return new moodle_url('/lib/javascript.php', ['rev' => $jsrev, 'jsfile' => $url]);
743 } else {
744 $returnurl = new moodle_url('/lib/javascript.php');
745 $returnurl->set_slashargument('/'.$jsrev.$url);
746 return $returnurl;
748 } else {
749 return new moodle_url($url);
751 } else {
752 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
757 * Find out if JS module present and return details.
759 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
760 * @return array description of module or null if not found
762 protected function find_module($component) {
763 global $CFG, $PAGE;
765 $module = null;
767 if (strpos($component, 'core_') === 0) {
768 // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
769 // so that we do nto have to repeat the definition of these modules over and over again.
770 switch($component) {
771 case 'core_filepicker':
772 $module = array('name' => 'core_filepicker',
773 'fullpath' => '/repository/filepicker.js',
774 'requires' => array(
775 'base', 'node', 'node-event-simulate', 'json', 'async-queue', 'io-base', 'io-upload-iframe', 'io-form',
776 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort', 'resize-plugin', 'dd-plugin',
777 'escape', 'moodle-core_filepicker', 'moodle-core-notification-dialogue'
779 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
780 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
781 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
782 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
783 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
784 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
785 array('referencesexist', 'repository'), array('select', 'repository')
787 break;
788 case 'core_comment':
789 $module = array('name' => 'core_comment',
790 'fullpath' => '/comment/comment.js',
791 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay', 'escape'),
792 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
794 break;
795 case 'core_role':
796 $module = array('name' => 'core_role',
797 'fullpath' => '/admin/roles/module.js',
798 'requires' => array('node', 'cookie'));
799 break;
800 case 'core_completion':
801 break;
802 case 'core_message':
803 $module = array('name' => 'core_message',
804 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
805 'fullpath' => '/message/module.js');
806 break;
807 case 'core_group':
808 $module = array('name' => 'core_group',
809 'fullpath' => '/group/module.js',
810 'requires' => array('node', 'overlay', 'event-mouseenter'));
811 break;
812 case 'core_question_engine':
813 $module = array('name' => 'core_question_engine',
814 'fullpath' => '/question/qengine.js',
815 'requires' => array('node', 'event'));
816 break;
817 case 'core_rating':
818 $module = array('name' => 'core_rating',
819 'fullpath' => '/rating/module.js',
820 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
821 break;
822 case 'core_dndupload':
823 $module = array('name' => 'core_dndupload',
824 'fullpath' => '/lib/form/dndupload.js',
825 'requires' => array('node', 'event', 'json', 'core_filepicker'),
826 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
827 array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesfile', 'error'),
828 array('sizegb', 'moodle'), array('sizemb', 'moodle'), array('sizekb', 'moodle'), array('sizeb', 'moodle'),
829 array('maxareabytesreached', 'moodle'), array('serverconnection', 'error'),
830 array('changesmadereallygoaway', 'moodle'), array('complete', 'moodle')
832 break;
835 } else {
836 if ($dir = core_component::get_component_directory($component)) {
837 if (file_exists("$dir/module.js")) {
838 if (strpos($dir, $CFG->dirroot.'/') === 0) {
839 $dir = substr($dir, strlen($CFG->dirroot));
840 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
846 return $module;
850 * Append YUI3 module to default YUI3 JS loader.
851 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
853 * @param string|array $module name of module (details are autodetected), or full module specification as array
854 * @return void
856 public function js_module($module) {
857 global $CFG;
859 if (empty($module)) {
860 throw new coding_exception('Missing YUI3 module name or full description.');
863 if (is_string($module)) {
864 $module = $this->find_module($module);
867 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
868 throw new coding_exception('Missing YUI3 module details.');
871 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
872 // Add all needed strings.
873 if (!empty($module['strings'])) {
874 foreach ($module['strings'] as $string) {
875 $identifier = $string[0];
876 $component = isset($string[1]) ? $string[1] : 'moodle';
877 $a = isset($string[2]) ? $string[2] : null;
878 $this->string_for_js($identifier, $component, $a);
881 unset($module['strings']);
883 // Process module requirements and attempt to load each. This allows
884 // moodle modules to require each other.
885 if (!empty($module['requires'])){
886 foreach ($module['requires'] as $requirement) {
887 $rmodule = $this->find_module($requirement);
888 if (is_array($rmodule)) {
889 $this->js_module($rmodule);
894 if ($this->headdone) {
895 $this->extramodules[$module['name']] = $module;
896 } else {
897 $this->YUI_config->add_module_config($module['name'], $module);
902 * Returns true if the module has already been loaded.
904 * @param string|array $module
905 * @return bool True if the module has already been loaded
907 protected function js_module_loaded($module) {
908 if (is_string($module)) {
909 $modulename = $module;
910 } else {
911 $modulename = $module['name'];
913 return array_key_exists($modulename, $this->YUI_config->modules) ||
914 array_key_exists($modulename, $this->extramodules);
918 * Ensure that the specified CSS file is linked to from this page.
920 * Because stylesheet links must go in the <head> part of the HTML, you must call
921 * this function before {@link get_head_code()} is called. That normally means before
922 * the call to print_header. If you call it when it is too late, an exception
923 * will be thrown.
925 * Even if a particular style sheet is requested more than once, it will only
926 * be linked to once.
928 * Please note use of this feature is strongly discouraged,
929 * it is suitable only for places where CSS is submitted directly by teachers.
930 * (Students must not be allowed to submit any external CSS because it may
931 * contain embedded javascript!). Example of correct use is mod/data.
933 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
934 * For example:
935 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
937 public function css($stylesheet) {
938 global $CFG;
940 if ($this->headdone) {
941 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
944 if ($stylesheet instanceof moodle_url) {
945 // ok
946 } else if (strpos($stylesheet, '/') === 0) {
947 $stylesheet = new moodle_url($stylesheet);
948 } else {
949 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
952 $this->cssurls[$stylesheet->out()] = $stylesheet;
956 * Add theme stylesheet to page - do not use from plugin code,
957 * this should be called only from the core renderer!
959 * @param moodle_url $stylesheet
960 * @return void
962 public function css_theme(moodle_url $stylesheet) {
963 $this->cssthemeurls[] = $stylesheet;
967 * Ensure that a skip link to a given target is printed at the top of the <body>.
969 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
970 * will be thrown). That normally means you must call this before the call to print_header.
972 * If you ask for a particular skip link to be printed, it is then your responsibility
973 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
974 * page, so that the skip link goes somewhere.
976 * Even if a particular skip link is requested more than once, only one copy of it will be output.
978 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
979 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
981 public function skip_link_to($target, $linktext) {
982 if ($this->topofbodydone) {
983 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
984 return;
986 $this->skiplinks[$target] = $linktext;
990 * !!!DEPRECATED!!! please use js_init_call() if possible
991 * Ensure that the specified JavaScript function is called from an inline script
992 * somewhere on this page.
994 * By default the call will be put in a script tag at the
995 * end of the page after initialising Y instance, since this gives best page-load
996 * performance and allows you to use YUI3 library.
998 * If you request that a particular function is called several times, then
999 * that is what will happen (unlike linking to a CSS or JS file, where only
1000 * one link will be output).
1002 * The main benefit of the method is the automatic encoding of all function parameters.
1004 * @deprecated
1006 * @param string $function the name of the JavaScritp function to call. Can
1007 * be a compound name like 'Y.Event.purgeElement'. Can also be
1008 * used to create and object by using a 'function name' like 'new user_selector'.
1009 * @param array $arguments and array of arguments to be passed to the function.
1010 * When generating the function call, this will be escaped using json_encode,
1011 * so passing objects and arrays should work.
1012 * @param bool $ondomready If tru the function is only called when the dom is
1013 * ready for manipulation.
1014 * @param int $delay The delay before the function is called.
1016 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
1017 $where = $ondomready ? 'ondomready' : 'normal';
1018 $this->jscalls[$where][] = array($function, $arguments, $delay);
1022 * This function appends a block of code to the AMD specific javascript block executed
1023 * in the page footer, just after loading the requirejs library.
1025 * The code passed here can rely on AMD module loading, e.g. require('jquery', function($) {...});
1027 * @param string $code The JS code to append.
1029 public function js_amd_inline($code) {
1030 $this->amdjscode[] = $code;
1034 * Load an AMD module and eventually call its method.
1036 * This function creates a minimal inline JS snippet that requires an AMD module and eventually calls a single
1037 * function from the module with given arguments. If it is called multiple times, it will be create multiple
1038 * snippets.
1040 * @param string $fullmodule The name of the AMD module to load, formatted as <component name>/<module name>.
1041 * @param string $func Optional function from the module to call, defaults to just loading the AMD module.
1042 * @param array $params The params to pass to the function (will be serialized into JSON).
1044 public function js_call_amd($fullmodule, $func = null, $params = array()) {
1045 global $CFG;
1047 $modulepath = explode('/', $fullmodule);
1049 $modname = clean_param(array_shift($modulepath), PARAM_COMPONENT);
1050 foreach ($modulepath as $module) {
1051 $modname .= '/' . clean_param($module, PARAM_ALPHANUMEXT);
1054 $functioncode = [];
1055 if ($func !== null) {
1056 $func = clean_param($func, PARAM_ALPHANUMEXT);
1058 $jsonparams = array();
1059 foreach ($params as $param) {
1060 $jsonparams[] = json_encode($param);
1062 $strparams = implode(', ', $jsonparams);
1063 if ($CFG->debugdeveloper) {
1064 $toomanyparamslimit = 1024;
1065 if (strlen($strparams) > $toomanyparamslimit) {
1066 debugging('Too much data passed as arguments to js_call_amd("' . $fullmodule . '", "' . $func .
1067 '"). Generally there are better ways to pass lots of data from PHP to JavaScript, for example via Ajax, ' .
1068 'data attributes, ... . This warning is triggered if the argument string becomes longer than ' .
1069 $toomanyparamslimit . ' characters.', DEBUG_DEVELOPER);
1073 $functioncode[] = "amd.{$func}({$strparams});";
1076 $functioncode[] = "M.util.js_complete('{$modname}');";
1078 $initcode = implode(' ', $functioncode);
1079 $js = "M.util.js_pending('{$modname}'); require(['{$modname}'], function(amd) {{$initcode}});";
1081 $this->js_amd_inline($js);
1085 * Creates a JavaScript function call that requires one or more modules to be loaded.
1087 * This function can be used to include all of the standard YUI module types within JavaScript:
1088 * - YUI3 modules [node, event, io]
1089 * - YUI2 modules [yui2-*]
1090 * - Moodle modules [moodle-*]
1091 * - Gallery modules [gallery-*]
1093 * Before writing new code that makes extensive use of YUI, you should consider it's replacement AMD/JQuery.
1094 * @see js_call_amd()
1096 * @param array|string $modules One or more modules
1097 * @param string $function The function to call once modules have been loaded
1098 * @param array $arguments An array of arguments to pass to the function
1099 * @param string $galleryversion Deprecated: The gallery version to use
1100 * @param bool $ondomready
1102 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1103 if (!is_array($modules)) {
1104 $modules = array($modules);
1107 if ($galleryversion != null) {
1108 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.');
1111 $jscode = 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
1112 if ($ondomready) {
1113 $jscode = "Y.on('domready', function() { $jscode });";
1115 $this->jsinitcode[] = $jscode;
1119 * Set the CSS Modules to be included from YUI.
1121 * @param array $modules The list of YUI CSS Modules to include.
1123 public function set_yuicssmodules(array $modules = array()) {
1124 $this->yuicssmodules = $modules;
1128 * Ensure that the specified JavaScript function is called from an inline script
1129 * from page footer.
1131 * @param string $function the name of the JavaScritp function to with init code,
1132 * usually something like 'M.mod_mymodule.init'
1133 * @param array $extraarguments and array of arguments to be passed to the function.
1134 * The first argument is always the YUI3 Y instance with all required dependencies
1135 * already loaded.
1136 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1137 * @param array $module JS module specification array
1139 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1140 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
1141 if (!$module) {
1142 // Detect module automatically.
1143 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
1144 $module = $this->find_module($matches[1]);
1148 $this->js_init_code($jscode, $ondomready, $module);
1152 * Add short static javascript code fragment to page footer.
1153 * This is intended primarily for loading of js modules and initialising page layout.
1154 * Ideally the JS code fragment should be stored in plugin renderer so that themes
1155 * may override it.
1157 * @param string $jscode
1158 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1159 * @param array $module JS module specification array
1161 public function js_init_code($jscode, $ondomready = false, array $module = null) {
1162 $jscode = trim($jscode, " ;\n"). ';';
1164 $uniqid = html_writer::random_id();
1165 $startjs = " M.util.js_pending('" . $uniqid . "');";
1166 $endjs = " M.util.js_complete('" . $uniqid . "');";
1168 if ($module) {
1169 $this->js_module($module);
1170 $modulename = $module['name'];
1171 $jscode = "$startjs Y.use('$modulename', function(Y) { $jscode $endjs });";
1174 if ($ondomready) {
1175 $jscode = "$startjs Y.on('domready', function() { $jscode $endjs });";
1178 $this->jsinitcode[] = $jscode;
1182 * Make a language string available to JavaScript.
1184 * All the strings will be available in a M.str object in the global namespace.
1185 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
1186 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
1187 * equivalent in the current language.
1189 * The arguments to this function are just like the arguments to get_string
1190 * except that $component is not optional, and there are some aspects to consider
1191 * when the string contains {$a} placeholder.
1193 * If the string does not contain any {$a} placeholder, you can simply use
1194 * M.str.component.identifier to obtain it. If you prefer, you can call
1195 * M.util.get_string(identifier, component) to get the same result.
1197 * If you need to use {$a} placeholders, there are two options. Either the
1198 * placeholder should be substituted in PHP on server side or it should
1199 * be substituted in Javascript at client side.
1201 * To substitute the placeholder at server side, just provide the required
1202 * value for the placeholder when you require the string. Because each string
1203 * is only stored once in the JavaScript (based on $identifier and $module)
1204 * you cannot get the same string with two different values of $a. If you try,
1205 * an exception will be thrown. Once the placeholder is substituted, you can
1206 * use M.str or M.util.get_string() as shown above:
1208 * // Require the string in PHP and replace the placeholder.
1209 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
1210 * // Use the result of the substitution in Javascript.
1211 * alert(M.str.moodle.fullnamedisplay);
1213 * To substitute the placeholder at client side, use M.util.get_string()
1214 * function. It implements the same logic as {@link get_string()}:
1216 * // Require the string in PHP but keep {$a} as it is.
1217 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
1218 * // Provide the values on the fly in Javascript.
1219 * user = { firstname : 'Harry', lastname : 'Potter' }
1220 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
1222 * If you do need the same string expanded with different $a values in PHP
1223 * on server side, then the solution is to put them in your own data structure
1224 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
1226 * @param string $identifier the desired string.
1227 * @param string $component the language file to look in.
1228 * @param mixed $a any extra data to add into the string (optional).
1230 public function string_for_js($identifier, $component, $a = null) {
1231 if (!$component) {
1232 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
1234 if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
1235 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
1236 "from lang file '$component' with different \$a parameter?");
1238 if (!isset($this->stringsforjs[$component][$identifier])) {
1239 $this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
1240 $this->stringsforjs_as[$component][$identifier] = $a;
1245 * Make an array of language strings available for JS.
1247 * This function calls the above function {@link string_for_js()} for each requested
1248 * string in the $identifiers array that is passed to the argument for a single module
1249 * passed in $module.
1251 * <code>
1252 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
1254 * // The above is identical to calling:
1256 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
1257 * $PAGE->requires->string_for_js('two', 'mymod');
1258 * $PAGE->requires->string_for_js('three', 'mymod', 3);
1259 * </code>
1261 * @param array $identifiers An array of desired strings
1262 * @param string $component The module to load for
1263 * @param mixed $a This can either be a single variable that gets passed as extra
1264 * information for every string or it can be an array of mixed data where the
1265 * key for the data matches that of the identifier it is meant for.
1268 public function strings_for_js($identifiers, $component, $a = null) {
1269 foreach ($identifiers as $key => $identifier) {
1270 if (is_array($a) && array_key_exists($key, $a)) {
1271 $extra = $a[$key];
1272 } else {
1273 $extra = $a;
1275 $this->string_for_js($identifier, $component, $extra);
1280 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
1282 * Make some data from PHP available to JavaScript code.
1284 * For example, if you call
1285 * <pre>
1286 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
1287 * </pre>
1288 * then in JavsScript mydata.name will be 'Moodle'.
1290 * @deprecated
1291 * @param string $variable the the name of the JavaScript variable to assign the data to.
1292 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1293 * should be considered an experimental feature.
1294 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1295 * so passing objects and arrays should work.
1296 * @param bool $inhead initialise in head
1297 * @return void
1299 public function data_for_js($variable, $data, $inhead=false) {
1300 $where = $inhead ? 'head' : 'footer';
1301 $this->jsinitvariables[$where][] = array($variable, $data);
1305 * Creates a YUI event handler.
1307 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1308 * @param string $event A valid DOM event (click, mousedown, change etc.)
1309 * @param string $function The name of the function to call
1310 * @param array $arguments An optional array of argument parameters to pass to the function
1312 public function event_handler($selector, $event, $function, array $arguments = null) {
1313 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
1317 * Returns code needed for registering of event handlers.
1318 * @return string JS code
1320 protected function get_event_handler_code() {
1321 $output = '';
1322 foreach ($this->eventhandlers as $h) {
1323 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
1325 return $output;
1329 * Get the inline JavaScript code that need to appear in a particular place.
1330 * @param bool $ondomready
1331 * @return string
1333 protected function get_javascript_code($ondomready) {
1334 $where = $ondomready ? 'ondomready' : 'normal';
1335 $output = '';
1336 if ($this->jscalls[$where]) {
1337 foreach ($this->jscalls[$where] as $data) {
1338 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
1340 if (!empty($ondomready)) {
1341 $output = " Y.on('domready', function() {\n$output\n});";
1344 return $output;
1348 * Returns js code to be executed when Y is available.
1349 * @return string
1351 protected function get_javascript_init_code() {
1352 if (count($this->jsinitcode)) {
1353 return implode("\n", $this->jsinitcode) . "\n";
1355 return '';
1359 * Returns js code to load amd module loader, then insert inline script tags
1360 * that contain require() calls using RequireJS.
1361 * @return string
1363 protected function get_amd_footercode() {
1364 global $CFG;
1365 $output = '';
1367 // We will cache JS if cachejs is not set, or it is true.
1368 $cachejs = !isset($CFG->cachejs) || $CFG->cachejs;
1369 $jsrev = $this->get_jsrev();
1371 $jsloader = new moodle_url('/lib/javascript.php');
1372 $jsloader->set_slashargument('/' . $jsrev . '/');
1373 $requirejsloader = new moodle_url('/lib/requirejs.php');
1374 $requirejsloader->set_slashargument('/' . $jsrev . '/');
1376 $requirejsconfig = file_get_contents($CFG->dirroot . '/lib/requirejs/moodle-config.js');
1378 // No extension required unless slash args is disabled.
1379 $jsextension = '.js';
1380 if (!empty($CFG->slasharguments)) {
1381 $jsextension = '';
1384 $minextension = '.min';
1385 if (!$cachejs) {
1386 $minextension = '';
1389 $requirejsconfig = str_replace('[BASEURL]', $requirejsloader, $requirejsconfig);
1390 $requirejsconfig = str_replace('[JSURL]', $jsloader, $requirejsconfig);
1391 $requirejsconfig = str_replace('[JSMIN]', $minextension, $requirejsconfig);
1392 $requirejsconfig = str_replace('[JSEXT]', $jsextension, $requirejsconfig);
1394 $output .= html_writer::script($requirejsconfig);
1395 if ($cachejs) {
1396 $output .= html_writer::script('', $this->js_fix_url('/lib/requirejs/require.min.js'));
1397 } else {
1398 $output .= html_writer::script('', $this->js_fix_url('/lib/requirejs/require.js'));
1401 // First include must be to a module with no dependencies, this prevents multiple requests.
1402 $prefix = <<<EOF
1403 M.util.js_pending("core/first");
1404 require(['core/first'], function() {
1406 EOF;
1408 if (during_initial_install()) {
1409 // Do not run a prefetch during initial install as the DB is not available to service WS calls.
1410 $prefetch = '';
1411 } else {
1412 $prefetch = "require(['core/prefetch'])\n";
1415 $suffix = <<<EOF
1417 M.util.js_complete("core/first");
1419 EOF;
1421 $output .= html_writer::script($prefix . $prefetch . implode(";\n", $this->amdjscode) . $suffix);
1422 return $output;
1426 * Returns basic YUI3 CSS code.
1428 * @return string
1430 protected function get_yui3lib_headcss() {
1431 global $CFG;
1433 $yuiformat = '-min';
1434 if ($this->yui3loader->filter === 'RAW') {
1435 $yuiformat = '';
1438 $code = '';
1439 if ($this->yui3loader->combine) {
1440 if (!empty($this->yuicssmodules)) {
1441 $modules = array();
1442 foreach ($this->yuicssmodules as $module) {
1443 $modules[] = "$CFG->yui3version/$module/$module-min.css";
1445 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase.implode('&amp;', $modules).'" />';
1447 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
1449 } else {
1450 if (!empty($this->yuicssmodules)) {
1451 foreach ($this->yuicssmodules as $module) {
1452 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.$module.'/'.$module.'-min.css" />';
1455 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
1458 if ($this->yui3loader->filter === 'RAW') {
1459 $code = str_replace('-min.css', '.css', $code);
1460 } else if ($this->yui3loader->filter === 'DEBUG') {
1461 $code = str_replace('-min.css', '.css', $code);
1463 return $code;
1467 * Returns basic YUI3 JS loading code.
1469 * @return string
1471 protected function get_yui3lib_headcode() {
1472 global $CFG;
1474 $jsrev = $this->get_jsrev();
1476 $yuiformat = '-min';
1477 if ($this->yui3loader->filter === 'RAW') {
1478 $yuiformat = '';
1481 $format = '-min';
1482 if ($this->YUI_config->groups['moodle']['filter'] === 'DEBUG') {
1483 $format = '-debug';
1486 $rollupversion = $CFG->yui3version;
1487 if (!empty($CFG->yuipatchlevel)) {
1488 $rollupversion .= '_' . $CFG->yuipatchlevel;
1491 $baserollups = array(
1492 'rollup/' . $rollupversion . "/yui-moodlesimple{$yuiformat}.js",
1495 if ($this->yui3loader->combine) {
1496 return '<script src="' .
1497 $this->yui3loader->local_comboBase .
1498 implode('&amp;', $baserollups) .
1499 '"></script>';
1500 } else {
1501 $code = '';
1502 foreach ($baserollups as $rollup) {
1503 $code .= '<script src="'.$this->yui3loader->local_comboBase.$rollup.'"></script>';
1505 return $code;
1511 * Returns html tags needed for inclusion of theme CSS.
1513 * @return string
1515 protected function get_css_code() {
1516 // First of all the theme CSS, then any custom CSS
1517 // Please note custom CSS is strongly discouraged,
1518 // because it can not be overridden by themes!
1519 // It is suitable only for things like mod/data which accepts CSS from teachers.
1520 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1522 // Add the YUI code first. We want this to be overridden by any Moodle CSS.
1523 $code = $this->get_yui3lib_headcss();
1525 // This line of code may look funny but it is currently required in order
1526 // to avoid MASSIVE display issues in Internet Explorer.
1527 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1528 // ignored whenever another resource is added until such time as a redraw
1529 // is forced, usually by moving the mouse over the affected element.
1530 $code .= html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1532 $urls = $this->cssthemeurls + $this->cssurls;
1533 foreach ($urls as $url) {
1534 $attributes['href'] = $url;
1535 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1536 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1537 unset($attributes['id']);
1540 return $code;
1544 * Adds extra modules specified after printing of page header.
1546 * @return string
1548 protected function get_extra_modules_code() {
1549 if (empty($this->extramodules)) {
1550 return '';
1552 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1556 * Generate any HTML that needs to go inside the <head> tag.
1558 * Normally, this method is called automatically by the code that prints the
1559 * <head> tag. You should not normally need to call it in your own code.
1561 * @param moodle_page $page
1562 * @param core_renderer $renderer
1563 * @return string the HTML code to to inside the <head> tag.
1565 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1566 global $CFG;
1568 // Note: the $page and $output are not stored here because it would
1569 // create circular references in memory which prevents garbage collection.
1570 $this->init_requirements_data($page, $renderer);
1572 $output = '';
1574 // Add all standard CSS for this page.
1575 $output .= $this->get_css_code();
1577 // Set up the M namespace.
1578 $js = "var M = {}; M.yui = {};\n";
1580 // Capture the time now ASAP during page load. This minimises the lag when
1581 // we try to relate times on the server to times in the browser.
1582 // An example of where this is used is the quiz countdown timer.
1583 $js .= "M.pageloadstarttime = new Date();\n";
1585 // Add a subset of Moodle configuration to the M namespace.
1586 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1588 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1589 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1590 // this needs to be done before including any other script.
1591 $js .= $this->YUI_config->get_config_functions();
1592 $js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n";
1593 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1594 $js = $this->YUI_config->update_header_js($js);
1596 $output .= html_writer::script($js);
1598 // Add variables.
1599 if ($this->jsinitvariables['head']) {
1600 $js = '';
1601 foreach ($this->jsinitvariables['head'] as $data) {
1602 list($var, $value) = $data;
1603 $js .= js_writer::set_variable($var, $value, true);
1605 $output .= html_writer::script($js);
1608 // Mark head sending done, it is not possible to anything there.
1609 $this->headdone = true;
1611 return $output;
1615 * Generate any HTML that needs to go at the start of the <body> tag.
1617 * Normally, this method is called automatically by the code that prints the
1618 * <head> tag. You should not normally need to call it in your own code.
1620 * @param renderer_base $renderer
1621 * @return string the HTML code to go at the start of the <body> tag.
1623 public function get_top_of_body_code(renderer_base $renderer) {
1624 global $CFG;
1626 // First the skip links.
1627 $output = $renderer->render_skip_links($this->skiplinks);
1629 // Include the Polyfills.
1630 $output .= html_writer::script('', $this->js_fix_url('/lib/polyfills/polyfill.js'));
1632 // YUI3 JS needs to be loaded early in the body. It should be cached well by the browser.
1633 $output .= $this->get_yui3lib_headcode();
1635 // Add hacked jQuery support, it is not intended for standard Moodle distribution!
1636 $output .= $this->get_jquery_headcode();
1638 // Link our main JS file, all core stuff should be there.
1639 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1641 // All the other linked things from HEAD - there should be as few as possible.
1642 if ($this->jsincludes['head']) {
1643 foreach ($this->jsincludes['head'] as $url) {
1644 $output .= html_writer::script('', $url);
1648 // Then the clever trick for hiding of things not needed when JS works.
1649 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1650 $this->topofbodydone = true;
1651 return $output;
1655 * Generate any HTML that needs to go at the end of the page.
1657 * Normally, this method is called automatically by the code that prints the
1658 * page footer. You should not normally need to call it in your own code.
1660 * @return string the HTML code to to at the end of the page.
1662 public function get_end_code() {
1663 global $CFG;
1664 $output = '';
1666 // Set the log level for the JS logging.
1667 $logconfig = new stdClass();
1668 $logconfig->level = 'warn';
1669 if ($CFG->debugdeveloper) {
1670 $logconfig->level = 'trace';
1672 $this->js_call_amd('core/log', 'setConfig', array($logconfig));
1673 // Add any global JS that needs to run on all pages.
1674 $this->js_call_amd('core/page_global', 'init');
1675 $this->js_call_amd('core/utility');
1677 // Call amd init functions.
1678 $output .= $this->get_amd_footercode();
1680 // Add other requested modules.
1681 $output .= $this->get_extra_modules_code();
1683 $this->js_init_code('M.util.js_complete("init");', true);
1685 // All the other linked scripts - there should be as few as possible.
1686 if ($this->jsincludes['footer']) {
1687 foreach ($this->jsincludes['footer'] as $url) {
1688 $output .= html_writer::script('', $url);
1692 // Add all needed strings.
1693 // First add core strings required for some dialogues.
1694 $this->strings_for_js(array(
1695 'confirm',
1696 'yes',
1697 'no',
1698 'areyousure',
1699 'closebuttontitle',
1700 'unknownerror',
1701 'error',
1702 'file',
1703 'url',
1704 // TODO MDL-70830 shortforms should preload the collapseall/expandall strings properly.
1705 'collapseall',
1706 'expandall',
1707 ), 'moodle');
1708 $this->strings_for_js(array(
1709 'debuginfo',
1710 'line',
1711 'stacktrace',
1712 ), 'debug');
1713 $this->string_for_js('labelsep', 'langconfig');
1714 if (!empty($this->stringsforjs)) {
1715 $strings = array();
1716 foreach ($this->stringsforjs as $component=>$v) {
1717 foreach($v as $indentifier => $langstring) {
1718 $strings[$component][$indentifier] = $langstring->out();
1721 $output .= html_writer::script(js_writer::set_variable('M.str', $strings));
1724 // Add variables.
1725 if ($this->jsinitvariables['footer']) {
1726 $js = '';
1727 foreach ($this->jsinitvariables['footer'] as $data) {
1728 list($var, $value) = $data;
1729 $js .= js_writer::set_variable($var, $value, true);
1731 $output .= html_writer::script($js);
1734 $inyuijs = $this->get_javascript_code(false);
1735 $ondomreadyjs = $this->get_javascript_code(true);
1736 $jsinit = $this->get_javascript_init_code();
1737 $handlersjs = $this->get_event_handler_code();
1739 // There is a global Y, make sure it is available in your scope.
1740 $js = "(function() {{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}})();";
1742 $output .= html_writer::script($js);
1744 return $output;
1748 * Have we already output the code in the <head> tag?
1750 * @return bool
1752 public function is_head_done() {
1753 return $this->headdone;
1757 * Have we already output the code at the start of the <body> tag?
1759 * @return bool
1761 public function is_top_of_body_done() {
1762 return $this->topofbodydone;
1766 * Should we generate a bit of content HTML that is only required once on
1767 * this page (e.g. the contents of the modchooser), now? Basically, we call
1768 * {@link has_one_time_item_been_created()}, and if the thing has not already
1769 * been output, we return true to tell the caller to generate it, and also
1770 * call {@link set_one_time_item_created()} to record the fact that it is
1771 * about to be generated.
1773 * That is, a typical usage pattern (in a renderer method) is:
1774 * <pre>
1775 * if (!$this->page->requires->should_create_one_time_item_now($thing)) {
1776 * return '';
1778 * // Else generate it.
1779 * </pre>
1781 * @param string $thing identifier for the bit of content. Should be of the form
1782 * frankenstyle_things, e.g. core_course_modchooser.
1783 * @return bool if true, the caller should generate that bit of output now, otherwise don't.
1785 public function should_create_one_time_item_now($thing) {
1786 if ($this->has_one_time_item_been_created($thing)) {
1787 return false;
1790 $this->set_one_time_item_created($thing);
1791 return true;
1795 * Has a particular bit of HTML that is only required once on this page
1796 * (e.g. the contents of the modchooser) already been generated?
1798 * Normally, you can use the {@link should_create_one_time_item_now()} helper
1799 * method rather than calling this method directly.
1801 * @param string $thing identifier for the bit of content. Should be of the form
1802 * frankenstyle_things, e.g. core_course_modchooser.
1803 * @return bool whether that bit of output has been created.
1805 public function has_one_time_item_been_created($thing) {
1806 return isset($this->onetimeitemsoutput[$thing]);
1810 * Indicate that a particular bit of HTML that is only required once on this
1811 * page (e.g. the contents of the modchooser) has been generated (or is about to be)?
1813 * Normally, you can use the {@link should_create_one_time_item_now()} helper
1814 * method rather than calling this method directly.
1816 * @param string $thing identifier for the bit of content. Should be of the form
1817 * frankenstyle_things, e.g. core_course_modchooser.
1819 public function set_one_time_item_created($thing) {
1820 if ($this->has_one_time_item_been_created($thing)) {
1821 throw new coding_exception($thing . ' is only supposed to be ouput ' .
1822 'once per page, but it seems to be being output again.');
1824 return $this->onetimeitemsoutput[$thing] = true;
1829 * This class represents the YUI configuration.
1831 * @copyright 2013 Andrew Nicols
1832 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1833 * @since Moodle 2.5
1834 * @package core
1835 * @category output
1837 class YUI_config {
1839 * These settings must be public so that when the object is converted to json they are exposed.
1840 * Note: Some of these are camelCase because YUI uses camelCase variable names.
1842 * The settings are described and documented in the YUI API at:
1843 * - http://yuilibrary.com/yui/docs/api/classes/config.html
1844 * - http://yuilibrary.com/yui/docs/api/classes/Loader.html
1846 public $debug = false;
1847 public $base;
1848 public $comboBase;
1849 public $combine;
1850 public $filter = null;
1851 public $insertBefore = 'firstthemesheet';
1852 public $groups = array();
1853 public $modules = array();
1854 /** @var array The log sources that should be not be logged. */
1855 public $logInclude = [];
1856 /** @var array Tog sources that should be logged. */
1857 public $logExclude = [];
1858 /** @var string The minimum log level for YUI logging statements. */
1859 public $logLevel;
1862 * @var array List of functions used by the YUI Loader group pattern recognition.
1864 protected $jsconfigfunctions = array();
1867 * Create a new group within the YUI_config system.
1869 * @param String $name The name of the group. This must be unique and
1870 * not previously used.
1871 * @param Array $config The configuration for this group.
1872 * @return void
1874 public function add_group($name, $config) {
1875 if (isset($this->groups[$name])) {
1876 throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
1878 $this->groups[$name] = $config;
1882 * Update an existing group configuration
1884 * Note, any existing configuration for that group will be wiped out.
1885 * This includes module configuration.
1887 * @param String $name The name of the group. This must be unique and
1888 * not previously used.
1889 * @param Array $config The configuration for this group.
1890 * @return void
1892 public function update_group($name, $config) {
1893 if (!isset($this->groups[$name])) {
1894 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.');
1896 $this->groups[$name] = $config;
1900 * Set the value of a configuration function used by the YUI Loader's pattern testing.
1902 * Only the body of the function should be passed, and not the whole function wrapper.
1904 * The JS function your write will be passed a single argument 'name' containing the
1905 * name of the module being loaded.
1907 * @param $function String the body of the JavaScript function. This should be used i
1908 * @return String the name of the function to use in the group pattern configuration.
1910 public function set_config_function($function) {
1911 $configname = 'yui' . (count($this->jsconfigfunctions) + 1) . 'ConfigFn';
1912 if (isset($this->jsconfigfunctions[$configname])) {
1913 throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
1915 $this->jsconfigfunctions[$configname] = $function;
1916 return '@' . $configname . '@';
1920 * Allow setting of the config function described in {@see set_config_function} from a file.
1921 * The contents of this file are then passed to set_config_function.
1923 * When jsrev is positive, the function is minified and stored in a MUC cache for subsequent uses.
1925 * @param $file The path to the JavaScript function used for YUI configuration.
1926 * @return String the name of the function to use in the group pattern configuration.
1928 public function set_config_source($file) {
1929 global $CFG;
1930 $cache = cache::make('core', 'yuimodules');
1932 // Attempt to get the metadata from the cache.
1933 $keyname = 'configfn_' . $file;
1934 $fullpath = $CFG->dirroot . '/' . $file;
1935 if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
1936 $cache->delete($keyname);
1937 $configfn = file_get_contents($fullpath);
1938 } else {
1939 $configfn = $cache->get($keyname);
1940 if ($configfn === false) {
1941 require_once($CFG->libdir . '/jslib.php');
1942 $configfn = core_minify::js_files(array($fullpath));
1943 $cache->set($keyname, $configfn);
1946 return $this->set_config_function($configfn);
1950 * Retrieve the list of JavaScript functions for YUI_config groups.
1952 * @return String The complete set of config functions
1954 public function get_config_functions() {
1955 $configfunctions = '';
1956 foreach ($this->jsconfigfunctions as $functionname => $function) {
1957 $configfunctions .= "var {$functionname} = function(me) {";
1958 $configfunctions .= $function;
1959 $configfunctions .= "};\n";
1961 return $configfunctions;
1965 * Update the header JavaScript with any required modification for the YUI Loader.
1967 * @param $js String The JavaScript to manipulate.
1968 * @return String the modified JS string.
1970 public function update_header_js($js) {
1971 // Update the names of the the configFn variables.
1972 // The PHP json_encode function cannot handle literal names so we have to wrap
1973 // them in @ and then replace them with literals of the same function name.
1974 foreach ($this->jsconfigfunctions as $functionname => $function) {
1975 $js = str_replace('"@' . $functionname . '@"', $functionname, $js);
1977 return $js;
1981 * Add configuration for a specific module.
1983 * @param String $name The name of the module to add configuration for.
1984 * @param Array $config The configuration for the specified module.
1985 * @param String $group The name of the group to add configuration for.
1986 * If not specified, then this module is added to the global
1987 * configuration.
1988 * @return void
1990 public function add_module_config($name, $config, $group = null) {
1991 if ($group) {
1992 if (!isset($this->groups[$name])) {
1993 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.');
1995 if (!isset($this->groups[$group]['modules'])) {
1996 $this->groups[$group]['modules'] = array();
1998 $modules = &$this->groups[$group]['modules'];
1999 } else {
2000 $modules = &$this->modules;
2002 $modules[$name] = $config;
2006 * Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
2008 * If js caching is disabled, metadata will not be served causing YUI to calculate
2009 * module dependencies as each module is loaded.
2011 * If metadata does not exist it will be created and stored in a MUC entry.
2013 * @return void
2015 public function add_moodle_metadata() {
2016 global $CFG;
2017 if (!isset($this->groups['moodle'])) {
2018 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.');
2021 if (!isset($this->groups['moodle']['modules'])) {
2022 $this->groups['moodle']['modules'] = array();
2025 $cache = cache::make('core', 'yuimodules');
2026 if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
2027 $metadata = array();
2028 $metadata = $this->get_moodle_metadata();
2029 $cache->delete('metadata');
2030 } else {
2031 // Attempt to get the metadata from the cache.
2032 if (!$metadata = $cache->get('metadata')) {
2033 $metadata = $this->get_moodle_metadata();
2034 $cache->set('metadata', $metadata);
2038 // Merge with any metadata added specific to this page which was added manually.
2039 $this->groups['moodle']['modules'] = array_merge($this->groups['moodle']['modules'],
2040 $metadata);
2044 * Determine the module metadata for all moodle YUI modules.
2046 * This works through all modules capable of serving YUI modules, and attempts to get
2047 * metadata for each of those modules.
2049 * @return Array of module metadata
2051 private function get_moodle_metadata() {
2052 $moodlemodules = array();
2053 // Core isn't a plugin type or subsystem - handle it seperately.
2054 if ($module = $this->get_moodle_path_metadata(core_component::get_component_directory('core'))) {
2055 $moodlemodules = array_merge($moodlemodules, $module);
2058 // Handle other core subsystems.
2059 $subsystems = core_component::get_core_subsystems();
2060 foreach ($subsystems as $subsystem => $path) {
2061 if (is_null($path)) {
2062 continue;
2064 if ($module = $this->get_moodle_path_metadata($path)) {
2065 $moodlemodules = array_merge($moodlemodules, $module);
2069 // And finally the plugins.
2070 $plugintypes = core_component::get_plugin_types();
2071 foreach ($plugintypes as $plugintype => $pathroot) {
2072 $pluginlist = core_component::get_plugin_list($plugintype);
2073 foreach ($pluginlist as $plugin => $path) {
2074 if ($module = $this->get_moodle_path_metadata($path)) {
2075 $moodlemodules = array_merge($moodlemodules, $module);
2080 return $moodlemodules;
2084 * Helper function process and return the YUI metadata for all of the modules under the specified path.
2086 * @param String $path the UNC path to the YUI src directory.
2087 * @return Array the complete array for frankenstyle directory.
2089 private function get_moodle_path_metadata($path) {
2090 // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
2091 $baseyui = $path . '/yui/src';
2092 $modules = array();
2093 if (is_dir($baseyui)) {
2094 $items = new DirectoryIterator($baseyui);
2095 foreach ($items as $item) {
2096 if ($item->isDot() or !$item->isDir()) {
2097 continue;
2099 $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
2100 if (!is_readable($metafile)) {
2101 continue;
2103 $metadata = file_get_contents($metafile);
2104 $modules = array_merge($modules, (array) json_decode($metadata));
2107 return $modules;
2111 * Define YUI modules which we have been required to patch between releases.
2113 * We must do this because we aggressively cache content on the browser, and we must also override use of the
2114 * external CDN which will serve the true authoritative copy of the code without our patches.
2116 * @param String combobase The local combobase
2117 * @param String yuiversion The current YUI version
2118 * @param Int patchlevel The patch level we're working to for YUI
2119 * @param Array patchedmodules An array containing the names of the patched modules
2120 * @return void
2122 public function define_patched_core_modules($combobase, $yuiversion, $patchlevel, $patchedmodules) {
2123 // The version we use is suffixed with a patchlevel so that we can get additional revisions between YUI releases.
2124 $subversion = $yuiversion . '_' . $patchlevel;
2126 if ($this->comboBase == $combobase) {
2127 // If we are using the local combobase in the loader, we can add a group and still make use of the combo
2128 // loader. We just need to specify a different root which includes a slightly different YUI version number
2129 // to include our patchlevel.
2130 $patterns = array();
2131 $modules = array();
2132 foreach ($patchedmodules as $modulename) {
2133 // We must define the pattern and module here so that the loader uses our group configuration instead of
2134 // the standard module definition. We may lose some metadata provided by upstream but this will be
2135 // loaded when the module is loaded anyway.
2136 $patterns[$modulename] = array(
2137 'group' => 'yui-patched',
2139 $modules[$modulename] = array();
2142 // Actually add the patch group here.
2143 $this->add_group('yui-patched', array(
2144 'combine' => true,
2145 'root' => $subversion . '/',
2146 'patterns' => $patterns,
2147 'modules' => $modules,
2150 } else {
2151 // The CDN is in use - we need to instead use the local combobase for this module and override the modules
2152 // definition. We cannot use the local base - we must use the combobase because we cannot invalidate the
2153 // local base in browser caches.
2154 $fullpathbase = $combobase . $subversion . '/';
2155 foreach ($patchedmodules as $modulename) {
2156 $this->modules[$modulename] = array(
2157 'fullpath' => $fullpathbase . $modulename . '/' . $modulename . '-min.js'
2165 * Invalidate all server and client side template caches.
2167 function template_reset_all_caches() {
2168 global $CFG;
2170 $next = time();
2171 if (isset($CFG->templaterev) and $next <= $CFG->templaterev and $CFG->templaterev - $next < 60 * 60) {
2172 // This resolves problems when reset is requested repeatedly within 1s,
2173 // the < 1h condition prevents accidental switching to future dates
2174 // because we might not recover from it.
2175 $next = $CFG->templaterev + 1;
2178 set_config('templaterev', $next);
2182 * Invalidate all server and client side JS caches.
2184 function js_reset_all_caches() {
2185 global $CFG;
2187 $next = time();
2188 if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
2189 // This resolves problems when reset is requested repeatedly within 1s,
2190 // the < 1h condition prevents accidental switching to future dates
2191 // because we might not recover from it.
2192 $next = $CFG->jsrev+1;
2195 set_config('jsrev', $next);