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