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