Merge branch 'wip_MDL-49327_2.7_guide_getinstance' of https://github.com/nixorv/moodl...
[moodle.git] / lib / outputrequirementslib.php
blob01700af29a1135447ca60a5ade2a8c1a5ecd3e9b
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library functions to facilitate the use of JavaScript in Moodle.
20 * Note: you can find history of this file in lib/ajax/ajaxlib.php
22 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @package core
25 * @category output
28 defined('MOODLE_INTERNAL') || die();
30 /**
31 * This class tracks all the things that are needed by the current page.
33 * Normally, the only instance of this class you will need to work with is the
34 * one accessible via $PAGE->requires.
36 * Typical usage would be
37 * <pre>
38 * $PAGE->requires->js_init_call('M.mod_forum.init_view');
39 * </pre>
41 * It also supports obsoleted coding style withouth YUI3 modules.
42 * <pre>
43 * $PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overridable via themes!
44 * $PAGE->requires->js('/mod/mymod/script.js');
45 * $PAGE->requires->js('/mod/mymod/small_but_urgent.js', true);
46 * $PAGE->requires->js_function_call('init_mymod', array($data), true);
47 * </pre>
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.
53 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
54 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
55 * @since Moodle 2.0
56 * @package core
57 * @category output
59 class page_requirements_manager {
61 /**
62 * @var array List of string available from JS
64 protected $stringsforjs = array();
66 /**
67 * @var array List of get_string $a parameters - used for validation only.
69 protected $stringsforjs_as = array();
71 /**
72 * @var array List of JS variables to be initialised
74 protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
76 /**
77 * @var array Included JS scripts
79 protected $jsincludes = array('head'=>array(), 'footer'=>array());
81 /**
82 * @var array List of needed function calls
84 protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
86 /**
87 * @var array List of skip links, those are needed for accessibility reasons
89 protected $skiplinks = array();
91 /**
92 * @var array Javascript code used for initialisation of page, it should
93 * be relatively small
95 protected $jsinitcode = array();
97 /**
98 * @var array of moodle_url Theme sheets, initialised only from core_renderer
100 protected $cssthemeurls = array();
103 * @var array of moodle_url List of custom theme sheets, these are strongly discouraged!
104 * Useful mostly only for CSS submitted by teachers that is not part of the theme.
106 protected $cssurls = array();
109 * @var array List of requested event handlers
111 protected $eventhandlers = array();
114 * @var array Extra modules
116 protected $extramodules = array();
119 * @var bool Flag indicated head stuff already printed
121 protected $headdone = false;
124 * @var bool Flag indicating top of body already printed
126 protected $topofbodydone = false;
129 * @var stdClass YUI PHPLoader instance responsible for YUI3 loading from PHP only
131 protected $yui3loader;
134 * @var YUI_config default YUI loader configuration
136 protected $YUI_config;
139 * @var array Some config vars exposed in JS, please no secret stuff there
141 protected $M_cfg;
144 * @var array list of requested jQuery plugins
146 protected $jqueryplugins = array();
149 * @var array list of jQuery plugin overrides
151 protected $jquerypluginoverrides = array();
154 * Page requirements constructor.
156 public function __construct() {
157 global $CFG;
159 // You may need to set up URL rewrite rule because oversized URLs might not be allowed by web server.
160 $sep = empty($CFG->yuislasharguments) ? '?' : '/';
162 $this->yui3loader = new stdClass();
163 $this->YUI_config = new YUI_config();
165 if (strpos($CFG->httpswwwroot, 'https:') === 0) {
166 // On HTTPS sites all JS must be loaded from https sites,
167 // YUI CDN does not support https yet, sorry.
168 $CFG->useexternalyui = 0;
171 // Set up some loader options.
172 $this->yui3loader->local_base = $CFG->httpswwwroot . '/lib/yuilib/'. $CFG->yui3version . '/';
173 $this->yui3loader->local_comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep;
175 if (!empty($CFG->useexternalyui)) {
176 $this->yui3loader->base = 'http://yui.yahooapis.com/' . $CFG->yui3version . '/';
177 $this->yui3loader->comboBase = 'http://yui.yahooapis.com/combo?';
178 } else {
179 $this->yui3loader->base = $this->yui3loader->local_base;
180 $this->yui3loader->comboBase = $this->yui3loader->local_comboBase;
183 // Enable combo loader? This significantly helps with caching and performance!
184 $this->yui3loader->combine = !empty($CFG->yuicomboloading);
186 $jsrev = $this->get_jsrev();
188 // Set up JS YUI loader helper object.
189 $this->YUI_config->base = $this->yui3loader->base;
190 $this->YUI_config->comboBase = $this->yui3loader->comboBase;
191 $this->YUI_config->combine = $this->yui3loader->combine;
193 // If we've had to patch any YUI modules between releases, we must override the YUI configuration to include them.
194 // For important information on patching YUI modules, please see http://docs.moodle.org/dev/YUI/Patching.
195 if (!empty($CFG->yuipatchedmodules) && !empty($CFG->yuipatchlevel)) {
196 $this->YUI_config->define_patched_core_modules($this->yui3loader->local_comboBase,
197 $CFG->yui3version,
198 $CFG->yuipatchlevel,
199 $CFG->yuipatchedmodules);
202 $configname = $this->YUI_config->set_config_source('lib/yui/config/yui2.js');
203 $this->YUI_config->add_group('yui2', array(
204 // Loader configuration for our 2in3, for now ignores $CFG->useexternalyui.
205 'base' => $CFG->httpswwwroot . '/lib/yuilib/2in3/' . $CFG->yui2version . '/build/',
206 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
207 'combine' => $this->yui3loader->combine,
208 'ext' => false,
209 'root' => '2in3/' . $CFG->yui2version .'/build/',
210 'patterns' => array(
211 'yui2-' => array(
212 'group' => 'yui2',
213 'configFn' => $configname,
217 $configname = $this->YUI_config->set_config_source('lib/yui/config/moodle.js');
218 $this->YUI_config->add_group('moodle', array(
219 'name' => 'moodle',
220 'base' => $CFG->httpswwwroot . '/theme/yui_combo.php' . $sep . 'm/' . $jsrev . '/',
221 'combine' => $this->yui3loader->combine,
222 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
223 'ext' => false,
224 'root' => 'm/'.$jsrev.'/', // Add the rev to the root path so that we can control caching.
225 'patterns' => array(
226 'moodle-' => array(
227 'group' => 'moodle',
228 'configFn' => $configname,
233 $this->YUI_config->add_group('gallery', array(
234 'name' => 'gallery',
235 'base' => $CFG->httpswwwroot . '/lib/yuilib/gallery/',
236 'combine' => $this->yui3loader->combine,
237 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php' . $sep,
238 'ext' => false,
239 'root' => 'gallery/' . $jsrev . '/',
240 'patterns' => array(
241 'gallery-' => array(
242 'group' => 'gallery',
247 // Set some more loader options applying to groups too.
248 if ($CFG->debugdeveloper) {
249 // When debugging is enabled, we want to load the non-minified (RAW) versions of YUI library modules rather
250 // than the DEBUG versions as these generally generate too much logging for our purposes.
251 // However we do want the DEBUG versions of our Moodle-specific modules.
252 // To debug a YUI-specific issue, change the yui3loader->filter value to DEBUG.
253 $this->YUI_config->filter = 'RAW';
254 $this->YUI_config->groups['moodle']['filter'] = 'DEBUG';
256 // We use the yui3loader->filter setting when writing the YUI3 seed scripts into the header.
257 $this->yui3loader->filter = $this->YUI_config->filter;
258 $this->YUI_config->debug = true;
259 } else {
260 $this->yui3loader->filter = null;
261 $this->YUI_config->groups['moodle']['filter'] = null;
262 $this->YUI_config->debug = false;
265 // Include the YUI config log filters.
266 if (!empty($CFG->yuilogexclude) && is_array($CFG->yuilogexclude)) {
267 $this->YUI_config->logExclude = $CFG->yuilogexclude;
269 if (!empty($CFG->yuiloginclude) && is_array($CFG->yuiloginclude)) {
270 $this->YUI_config->logInclude = $CFG->yuiloginclude;
272 if (!empty($CFG->yuiloglevel)) {
273 $this->YUI_config->logLevel = $CFG->yuiloglevel;
276 // Add the moodle group's module data.
277 $this->YUI_config->add_moodle_metadata();
279 // Every page should include definition of following modules.
280 $this->js_module($this->find_module('core_filepicker'));
284 * Initialise with the bits of JavaScript that every Moodle page should have.
286 * @param moodle_page $page
287 * @param core_renderer $renderer
289 protected function init_requirements_data(moodle_page $page, core_renderer $renderer) {
290 global $CFG;
292 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
293 // Otherwise, in some situations, users will get warnings about insecure content
294 // on secure pages from their web browser.
296 $this->M_cfg = array(
297 'wwwroot' => $CFG->httpswwwroot, // Yes, really. See above.
298 'sesskey' => sesskey(),
299 'loadingicon' => $renderer->pix_url('i/loading_small', 'moodle')->out(false),
300 'themerev' => theme_get_revision(),
301 'slasharguments' => (int)(!empty($CFG->slasharguments)),
302 'theme' => $page->theme->name,
303 'jsrev' => $this->get_jsrev(),
304 'svgicons' => $page->theme->use_svg_icons()
306 if ($CFG->debugdeveloper) {
307 $this->M_cfg['developerdebug'] = true;
309 if (defined('BEHAT_SITE_RUNNING')) {
310 $this->M_cfg['behatsiterunning'] = true;
313 // Accessibility stuff.
314 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
316 // Add strings used on many pages.
317 $this->string_for_js('confirmation', 'admin');
318 $this->string_for_js('cancel', 'moodle');
319 $this->string_for_js('yes', 'moodle');
321 // Alter links in top frame to break out of frames.
322 if ($page->pagelayout === 'frametop') {
323 $this->js_init_call('M.util.init_frametop');
326 // Include block drag/drop if editing is on
327 if ($page->user_is_editing()) {
328 $params = array(
329 'courseid' => $page->course->id,
330 'pagetype' => $page->pagetype,
331 'pagelayout' => $page->pagelayout,
332 'subpage' => $page->subpage,
333 'regions' => $page->blocks->get_regions(),
334 'contextid' => $page->context->id,
336 if (!empty($page->cm->id)) {
337 $params['cmid'] = $page->cm->id;
339 // Strings for drag and drop.
340 $this->strings_for_js(array('movecontent',
341 'tocontent',
342 'emptydragdropregion'),
343 'moodle');
344 $page->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
349 * Determine the correct JS Revision to use for this load.
351 * @return int the jsrev to use.
353 protected function get_jsrev() {
354 global $CFG;
356 if (empty($CFG->cachejs)) {
357 $jsrev = -1;
358 } else if (empty($CFG->jsrev)) {
359 $jsrev = 1;
360 } else {
361 $jsrev = $CFG->jsrev;
364 return $jsrev;
368 * Ensure that the specified JavaScript file is linked to from this page.
370 * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
371 * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
373 * By default the link is put at the end of the page, since this gives best page-load performance.
375 * Even if a particular script is requested more than once, it will only be linked
376 * to once.
378 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
379 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
380 * @param bool $inhead initialise in head
382 public function js($url, $inhead = false) {
383 $url = $this->js_fix_url($url);
384 $where = $inhead ? 'head' : 'footer';
385 $this->jsincludes[$where][$url->out()] = $url;
389 * Request inclusion of jQuery library in the page.
391 * NOTE: this should not be used in official Moodle distribution!
393 * We are going to bundle jQuery 1.9.x until we drop support
394 * all support for IE 6-8. Use $PAGE->requires->jquery_plugin('migrate')
395 * for code written for earlier jQuery versions.
397 * {@see http://docs.moodle.org/dev/jQuery}
399 public function jquery() {
400 $this->jquery_plugin('jquery');
404 * Request inclusion of jQuery plugin.
406 * NOTE: this should not be used in official Moodle distribution!
408 * jQuery plugins are located in plugin/jquery/* subdirectory,
409 * plugin/jquery/plugins.php lists all available plugins.
411 * Included core plugins:
412 * - jQuery UI
413 * - jQuery Migrate (useful for code written for previous UI version)
415 * Add-ons may include extra jQuery plugins in jquery/ directory,
416 * plugins.php file defines the mapping between plugin names and
417 * necessary page includes.
419 * Examples:
420 * <code>
421 * // file: mod/xxx/view.php
422 * $PAGE->requires->jquery();
423 * $PAGE->requires->jquery_plugin('ui');
424 * $PAGE->requires->jquery_plugin('ui-css');
425 * </code>
427 * <code>
428 * // file: theme/yyy/lib.php
429 * function theme_yyy_page_init(moodle_page $page) {
430 * $page->requires->jquery();
431 * $page->requires->jquery_plugin('ui');
432 * $page->requires->jquery_plugin('ui-css');
434 * </code>
436 * <code>
437 * // file: blocks/zzz/block_zzz.php
438 * public function get_required_javascript() {
439 * parent::get_required_javascript();
440 * $this->page->requires->jquery();
441 * $page->requires->jquery_plugin('ui');
442 * $page->requires->jquery_plugin('ui-css');
444 * </code>
446 * {@see http://docs.moodle.org/dev/jQuery}
448 * @param string $plugin name of the jQuery plugin as defined in jquery/plugins.php
449 * @param string $component name of the component
450 * @return bool success
452 public function jquery_plugin($plugin, $component = 'core') {
453 global $CFG;
455 if ($this->headdone) {
456 debugging('Can not add jQuery plugins after starting page output!');
457 return false;
460 if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css', 'migrate'))) {
461 debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER);
462 $component = 'core';
463 } else if ($component !== 'core' and strpos($component, '_') === false) {
464 // Let's normalise the legacy activity names, Frankenstyle rulez!
465 $component = 'mod_' . $component;
468 if (empty($this->jqueryplugins) and ($component !== 'core' or $plugin !== 'jquery')) {
469 // Make sure the jQuery itself is always loaded first,
470 // the order of all other plugins depends on order of $PAGE_>requires->.
471 $this->jquery_plugin('jquery', 'core');
474 if (isset($this->jqueryplugins[$plugin])) {
475 // No problem, we already have something, first Moodle plugin to register the jQuery plugin wins.
476 return true;
479 $componentdir = core_component::get_component_directory($component);
480 if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
481 debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER);
482 return false;
485 $plugins = array();
486 require("$componentdir/jquery/plugins.php");
488 if (!isset($plugins[$plugin])) {
489 debugging("jQuery plugin '$plugin' can not be found in component '$component'.", DEBUG_DEVELOPER);
490 return false;
493 $this->jqueryplugins[$plugin] = new stdClass();
494 $this->jqueryplugins[$plugin]->plugin = $plugin;
495 $this->jqueryplugins[$plugin]->component = $component;
496 $this->jqueryplugins[$plugin]->urls = array();
498 foreach ($plugins[$plugin]['files'] as $file) {
499 if ($CFG->debugdeveloper) {
500 if (!file_exists("$componentdir/jquery/$file")) {
501 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
502 continue;
504 $file = str_replace('.min.css', '.css', $file);
505 $file = str_replace('.min.js', '.js', $file);
507 if (!file_exists("$componentdir/jquery/$file")) {
508 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
509 continue;
511 if (!empty($CFG->slasharguments)) {
512 $url = new moodle_url("$CFG->httpswwwroot/theme/jquery.php");
513 $url->set_slashargument("/$component/$file");
515 } else {
516 // This is not really good, we need slasharguments for relative links, this means no caching...
517 $path = realpath("$componentdir/jquery/$file");
518 if (strpos($path, $CFG->dirroot) === 0) {
519 $url = $CFG->httpswwwroot.preg_replace('/^'.preg_quote($CFG->dirroot, '/').'/', '', $path);
520 $url = new moodle_url($url);
521 } else {
522 // Bad luck, fix your server!
523 debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
524 continue;
527 $this->jqueryplugins[$plugin]->urls[] = $url;
530 return true;
534 * Request replacement of one jQuery plugin by another.
536 * This is useful when themes want to replace the jQuery UI theme,
537 * the problem is that theme can not prevent others from including the core ui-css plugin.
539 * Example:
540 * 1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
541 * 2/ write theme/yourtheme/jquery/plugins.php
542 * 3/ init jQuery from theme
544 * <code>
545 * // file theme/yourtheme/lib.php
546 * function theme_yourtheme_page_init($page) {
547 * $page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
548 * $page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
550 * </code>
552 * This code prevents loading of standard 'ui-css' which my be requested by other plugins,
553 * the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
555 * {@see http://docs.moodle.org/dev/jQuery}
557 * @param string $oldplugin original plugin
558 * @param string $newplugin the replacement
560 public function jquery_override_plugin($oldplugin, $newplugin) {
561 if ($this->headdone) {
562 debugging('Can not override jQuery plugins after starting page output!');
563 return;
565 $this->jquerypluginoverrides[$oldplugin] = $newplugin;
569 * Return jQuery related markup for page start.
570 * @return string
572 protected function get_jquery_headcode() {
573 if (empty($this->jqueryplugins['jquery'])) {
574 // If nobody requested jQuery then do not bother to load anything.
575 // This may be useful for themes that want to override 'ui-css' only if requested by something else.
576 return '';
579 $included = array();
580 $urls = array();
582 foreach ($this->jqueryplugins as $name => $unused) {
583 if (isset($included[$name])) {
584 continue;
586 if (array_key_exists($name, $this->jquerypluginoverrides)) {
587 // The following loop tries to resolve the replacements,
588 // use max 100 iterations to prevent infinite loop resulting
589 // in blank page.
590 $cyclic = true;
591 $oldname = $name;
592 for ($i=0; $i<100; $i++) {
593 $name = $this->jquerypluginoverrides[$name];
594 if (!array_key_exists($name, $this->jquerypluginoverrides)) {
595 $cyclic = false;
596 break;
599 if ($cyclic) {
600 // We can not do much with cyclic references here, let's use the old plugin.
601 $name = $oldname;
602 debugging("Cyclic overrides detected for jQuery plugin '$name'");
604 } else if (empty($name)) {
605 // Developer requested removal of the plugin.
606 continue;
608 } else if (!isset($this->jqueryplugins[$name])) {
609 debugging("Unknown jQuery override plugin '$name' detected");
610 $name = $oldname;
612 } else if (isset($included[$name])) {
613 // The plugin was already included, easy.
614 continue;
618 $plugin = $this->jqueryplugins[$name];
619 $urls = array_merge($urls, $plugin->urls);
620 $included[$name] = true;
623 $output = '';
624 $attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
625 foreach ($urls as $url) {
626 if (preg_match('/\.js$/', $url)) {
627 $output .= html_writer::script('', $url);
628 } else if (preg_match('/\.css$/', $url)) {
629 $attributes['href'] = $url;
630 $output .= html_writer::empty_tag('link', $attributes) . "\n";
634 return $output;
638 * Returns the actual url through which a script is served.
640 * @param moodle_url|string $url full moodle url, or shortened path to script
641 * @return moodle_url
643 protected function js_fix_url($url) {
644 global $CFG;
646 if ($url instanceof moodle_url) {
647 return $url;
648 } else if (strpos($url, '/') === 0) {
649 // Fix the admin links if needed.
650 if ($CFG->admin !== 'admin') {
651 if (strpos($url, "/admin/") === 0) {
652 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
655 if (debugging()) {
656 // Check file existence only when in debug mode.
657 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
658 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
661 if (substr($url, -3) === '.js') {
662 $jsrev = $this->get_jsrev();
663 if (empty($CFG->slasharguments)) {
664 return new moodle_url($CFG->httpswwwroot.'/lib/javascript.php', array('rev'=>$jsrev, 'jsfile'=>$url));
665 } else {
666 $returnurl = new moodle_url($CFG->httpswwwroot.'/lib/javascript.php');
667 $returnurl->set_slashargument('/'.$jsrev.$url);
668 return $returnurl;
670 } else {
671 return new moodle_url($CFG->httpswwwroot.$url);
673 } else {
674 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
679 * Find out if JS module present and return details.
681 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
682 * @return array description of module or null if not found
684 protected function find_module($component) {
685 global $CFG, $PAGE;
687 $module = null;
689 if (strpos($component, 'core_') === 0) {
690 // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
691 // so that we do nto have to repeat the definition of these modules over and over again.
692 switch($component) {
693 case 'core_filepicker':
694 $module = array('name' => 'core_filepicker',
695 'fullpath' => '/repository/filepicker.js',
696 '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'),
697 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
698 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
699 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
700 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
701 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
702 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
703 array('referencesexist', 'repository'), array('select', 'repository')
705 break;
706 case 'core_comment':
707 $module = array('name' => 'core_comment',
708 'fullpath' => '/comment/comment.js',
709 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
710 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
712 break;
713 case 'core_role':
714 $module = array('name' => 'core_role',
715 'fullpath' => '/admin/roles/module.js',
716 'requires' => array('node', 'cookie'));
717 break;
718 case 'core_completion':
719 $module = array('name' => 'core_completion',
720 'fullpath' => '/course/completion.js');
721 break;
722 case 'core_message':
723 $module = array('name' => 'core_message',
724 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
725 'fullpath' => '/message/module.js');
726 break;
727 case 'core_group':
728 $module = array('name' => 'core_group',
729 'fullpath' => '/group/module.js',
730 'requires' => array('node', 'overlay', 'event-mouseenter'));
731 break;
732 case 'core_question_engine':
733 $module = array('name' => 'core_question_engine',
734 'fullpath' => '/question/qengine.js',
735 'requires' => array('node', 'event'));
736 break;
737 case 'core_rating':
738 $module = array('name' => 'core_rating',
739 'fullpath' => '/rating/module.js',
740 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
741 break;
742 case 'core_dndupload':
743 $module = array('name' => 'core_dndupload',
744 'fullpath' => '/lib/form/dndupload.js',
745 'requires' => array('node', 'event', 'json', 'core_filepicker'),
746 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
747 array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesforfile', 'moodle'),
748 array('maxareabytesreached', 'moodle'), array('serverconnection', 'error'),
750 break;
753 } else {
754 if ($dir = core_component::get_component_directory($component)) {
755 if (file_exists("$dir/module.js")) {
756 if (strpos($dir, $CFG->dirroot.'/') === 0) {
757 $dir = substr($dir, strlen($CFG->dirroot));
758 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
764 return $module;
768 * Append YUI3 module to default YUI3 JS loader.
769 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
771 * @param string|array $module name of module (details are autodetected), or full module specification as array
772 * @return void
774 public function js_module($module) {
775 global $CFG;
777 if (empty($module)) {
778 throw new coding_exception('Missing YUI3 module name or full description.');
781 if (is_string($module)) {
782 $module = $this->find_module($module);
785 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
786 throw new coding_exception('Missing YUI3 module details.');
789 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
790 // Add all needed strings.
791 if (!empty($module['strings'])) {
792 foreach ($module['strings'] as $string) {
793 $identifier = $string[0];
794 $component = isset($string[1]) ? $string[1] : 'moodle';
795 $a = isset($string[2]) ? $string[2] : null;
796 $this->string_for_js($identifier, $component, $a);
799 unset($module['strings']);
801 // Process module requirements and attempt to load each. This allows
802 // moodle modules to require each other.
803 if (!empty($module['requires'])){
804 foreach ($module['requires'] as $requirement) {
805 $rmodule = $this->find_module($requirement);
806 if (is_array($rmodule)) {
807 $this->js_module($rmodule);
812 if ($this->headdone) {
813 $this->extramodules[$module['name']] = $module;
814 } else {
815 $this->YUI_config->add_module_config($module['name'], $module);
820 * Returns true if the module has already been loaded.
822 * @param string|array $module
823 * @return bool True if the module has already been loaded
825 protected function js_module_loaded($module) {
826 if (is_string($module)) {
827 $modulename = $module;
828 } else {
829 $modulename = $module['name'];
831 return array_key_exists($modulename, $this->YUI_config->modules) ||
832 array_key_exists($modulename, $this->extramodules);
836 * Ensure that the specified CSS file is linked to from this page.
838 * Because stylesheet links must go in the <head> part of the HTML, you must call
839 * this function before {@link get_head_code()} is called. That normally means before
840 * the call to print_header. If you call it when it is too late, an exception
841 * will be thrown.
843 * Even if a particular style sheet is requested more than once, it will only
844 * be linked to once.
846 * Please note use of this feature is strongly discouraged,
847 * it is suitable only for places where CSS is submitted directly by teachers.
848 * (Students must not be allowed to submit any external CSS because it may
849 * contain embedded javascript!). Example of correct use is mod/data.
851 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
852 * For example:
853 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
855 public function css($stylesheet) {
856 global $CFG;
858 if ($this->headdone) {
859 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
862 if ($stylesheet instanceof moodle_url) {
863 // ok
864 } else if (strpos($stylesheet, '/') === 0) {
865 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
866 } else {
867 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
870 $this->cssurls[$stylesheet->out()] = $stylesheet;
874 * Add theme stylesheet to page - do not use from plugin code,
875 * this should be called only from the core renderer!
877 * @param moodle_url $stylesheet
878 * @return void
880 public function css_theme(moodle_url $stylesheet) {
881 $this->cssthemeurls[] = $stylesheet;
885 * Ensure that a skip link to a given target is printed at the top of the <body>.
887 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
888 * will be thrown). That normally means you must call this before the call to print_header.
890 * If you ask for a particular skip link to be printed, it is then your responsibility
891 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
892 * page, so that the skip link goes somewhere.
894 * Even if a particular skip link is requested more than once, only one copy of it will be output.
896 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
897 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
899 public function skip_link_to($target, $linktext) {
900 if ($this->topofbodydone) {
901 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
902 return;
904 $this->skiplinks[$target] = $linktext;
908 * !!!DEPRECATED!!! please use js_init_call() if possible
909 * Ensure that the specified JavaScript function is called from an inline script
910 * somewhere on this page.
912 * By default the call will be put in a script tag at the
913 * end of the page after initialising Y instance, since this gives best page-load
914 * performance and allows you to use YUI3 library.
916 * If you request that a particular function is called several times, then
917 * that is what will happen (unlike linking to a CSS or JS file, where only
918 * one link will be output).
920 * The main benefit of the method is the automatic encoding of all function parameters.
922 * @deprecated
924 * @param string $function the name of the JavaScritp function to call. Can
925 * be a compound name like 'Y.Event.purgeElement'. Can also be
926 * used to create and object by using a 'function name' like 'new user_selector'.
927 * @param array $arguments and array of arguments to be passed to the function.
928 * When generating the function call, this will be escaped using json_encode,
929 * so passing objects and arrays should work.
930 * @param bool $ondomready If tru the function is only called when the dom is
931 * ready for manipulation.
932 * @param int $delay The delay before the function is called.
934 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
935 $where = $ondomready ? 'ondomready' : 'normal';
936 $this->jscalls[$where][] = array($function, $arguments, $delay);
940 * Creates a JavaScript function call that requires one or more modules to be loaded.
942 * This function can be used to include all of the standard YUI module types within JavaScript:
943 * - YUI3 modules [node, event, io]
944 * - YUI2 modules [yui2-*]
945 * - Moodle modules [moodle-*]
946 * - Gallery modules [gallery-*]
948 * @param array|string $modules One or more modules
949 * @param string $function The function to call once modules have been loaded
950 * @param array $arguments An array of arguments to pass to the function
951 * @param string $galleryversion Deprecated: The gallery version to use
952 * @param bool $ondomready
954 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
955 if (!is_array($modules)) {
956 $modules = array($modules);
959 if ($galleryversion != null) {
960 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.');
963 $jscode = 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
964 if ($ondomready) {
965 $jscode = "Y.on('domready', function() { $jscode });";
967 $this->jsinitcode[] = $jscode;
971 * Ensure that the specified JavaScript function is called from an inline script
972 * from page footer.
974 * @param string $function the name of the JavaScritp function to with init code,
975 * usually something like 'M.mod_mymodule.init'
976 * @param array $extraarguments and array of arguments to be passed to the function.
977 * The first argument is always the YUI3 Y instance with all required dependencies
978 * already loaded.
979 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
980 * @param array $module JS module specification array
982 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
983 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
984 if (!$module) {
985 // Detect module automatically.
986 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
987 $module = $this->find_module($matches[1]);
991 $this->js_init_code($jscode, $ondomready, $module);
995 * Add short static javascript code fragment to page footer.
996 * This is intended primarily for loading of js modules and initialising page layout.
997 * Ideally the JS code fragment should be stored in plugin renderer so that themes
998 * may override it.
1000 * @param string $jscode
1001 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1002 * @param array $module JS module specification array
1004 public function js_init_code($jscode, $ondomready = false, array $module = null) {
1005 $jscode = trim($jscode, " ;\n"). ';';
1007 $uniqid = html_writer::random_id();
1008 $startjs = " M.util.js_pending('" . $uniqid . "');";
1009 $endjs = " M.util.js_complete('" . $uniqid . "');";
1011 if ($module) {
1012 $this->js_module($module);
1013 $modulename = $module['name'];
1014 $jscode = "$startjs Y.use('$modulename', function(Y) { $jscode $endjs });";
1017 if ($ondomready) {
1018 $jscode = "$startjs Y.on('domready', function() { $jscode $endjs });";
1021 $this->jsinitcode[] = $jscode;
1025 * Make a language string available to JavaScript.
1027 * All the strings will be available in a M.str object in the global namespace.
1028 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
1029 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
1030 * equivalent in the current language.
1032 * The arguments to this function are just like the arguments to get_string
1033 * except that $component is not optional, and there are some aspects to consider
1034 * when the string contains {$a} placeholder.
1036 * If the string does not contain any {$a} placeholder, you can simply use
1037 * M.str.component.identifier to obtain it. If you prefer, you can call
1038 * M.util.get_string(identifier, component) to get the same result.
1040 * If you need to use {$a} placeholders, there are two options. Either the
1041 * placeholder should be substituted in PHP on server side or it should
1042 * be substituted in Javascript at client side.
1044 * To substitute the placeholder at server side, just provide the required
1045 * value for the placeholder when you require the string. Because each string
1046 * is only stored once in the JavaScript (based on $identifier and $module)
1047 * you cannot get the same string with two different values of $a. If you try,
1048 * an exception will be thrown. Once the placeholder is substituted, you can
1049 * use M.str or M.util.get_string() as shown above:
1051 * // Require the string in PHP and replace the placeholder.
1052 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
1053 * // Use the result of the substitution in Javascript.
1054 * alert(M.str.moodle.fullnamedisplay);
1056 * To substitute the placeholder at client side, use M.util.get_string()
1057 * function. It implements the same logic as {@link get_string()}:
1059 * // Require the string in PHP but keep {$a} as it is.
1060 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
1061 * // Provide the values on the fly in Javascript.
1062 * user = { firstname : 'Harry', lastname : 'Potter' }
1063 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
1065 * If you do need the same string expanded with different $a values in PHP
1066 * on server side, then the solution is to put them in your own data structure
1067 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
1069 * @param string $identifier the desired string.
1070 * @param string $component the language file to look in.
1071 * @param mixed $a any extra data to add into the string (optional).
1073 public function string_for_js($identifier, $component, $a = null) {
1074 if (!$component) {
1075 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
1077 if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
1078 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
1079 "from lang file '$component' with different \$a parameter?");
1081 if (!isset($this->stringsforjs[$component][$identifier])) {
1082 $this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
1083 $this->stringsforjs_as[$component][$identifier] = $a;
1088 * Make an array of language strings available for JS.
1090 * This function calls the above function {@link string_for_js()} for each requested
1091 * string in the $identifiers array that is passed to the argument for a single module
1092 * passed in $module.
1094 * <code>
1095 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
1097 * // The above is identical to calling:
1099 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
1100 * $PAGE->requires->string_for_js('two', 'mymod');
1101 * $PAGE->requires->string_for_js('three', 'mymod', 3);
1102 * </code>
1104 * @param array $identifiers An array of desired strings
1105 * @param string $component The module to load for
1106 * @param mixed $a This can either be a single variable that gets passed as extra
1107 * information for every string or it can be an array of mixed data where the
1108 * key for the data matches that of the identifier it is meant for.
1111 public function strings_for_js($identifiers, $component, $a = null) {
1112 foreach ($identifiers as $key => $identifier) {
1113 if (is_array($a) && array_key_exists($key, $a)) {
1114 $extra = $a[$key];
1115 } else {
1116 $extra = $a;
1118 $this->string_for_js($identifier, $component, $extra);
1123 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
1125 * Make some data from PHP available to JavaScript code.
1127 * For example, if you call
1128 * <pre>
1129 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
1130 * </pre>
1131 * then in JavsScript mydata.name will be 'Moodle'.
1133 * @deprecated
1134 * @param string $variable the the name of the JavaScript variable to assign the data to.
1135 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1136 * should be considered an experimental feature.
1137 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1138 * so passing objects and arrays should work.
1139 * @param bool $inhead initialise in head
1140 * @return void
1142 public function data_for_js($variable, $data, $inhead=false) {
1143 $where = $inhead ? 'head' : 'footer';
1144 $this->jsinitvariables[$where][] = array($variable, $data);
1148 * Creates a YUI event handler.
1150 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1151 * @param string $event A valid DOM event (click, mousedown, change etc.)
1152 * @param string $function The name of the function to call
1153 * @param array $arguments An optional array of argument parameters to pass to the function
1155 public function event_handler($selector, $event, $function, array $arguments = null) {
1156 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
1160 * Returns code needed for registering of event handlers.
1161 * @return string JS code
1163 protected function get_event_handler_code() {
1164 $output = '';
1165 foreach ($this->eventhandlers as $h) {
1166 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
1168 return $output;
1172 * Get the inline JavaScript code that need to appear in a particular place.
1173 * @param bool $ondomready
1174 * @return string
1176 protected function get_javascript_code($ondomready) {
1177 $where = $ondomready ? 'ondomready' : 'normal';
1178 $output = '';
1179 if ($this->jscalls[$where]) {
1180 foreach ($this->jscalls[$where] as $data) {
1181 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
1183 if (!empty($ondomready)) {
1184 $output = " Y.on('domready', function() {\n$output\n});";
1187 return $output;
1191 * Returns js code to be executed when Y is available.
1192 * @return string
1194 protected function get_javascript_init_code() {
1195 if (count($this->jsinitcode)) {
1196 return implode("\n", $this->jsinitcode) . "\n";
1198 return '';
1202 * Returns basic YUI3 JS loading code.
1203 * YUI3 is using autoloading of both CSS and JS code.
1205 * Major benefit of this compared to standard js/csss loader is much improved
1206 * caching, better browser cache utilisation, much fewer http requests.
1208 * @param moodle_page $page
1209 * @return string
1211 protected function get_yui3lib_headcode($page) {
1212 global $CFG;
1214 $code = '';
1216 $jsrev = $this->get_jsrev();
1218 $yuiformat = '-min';
1219 if ($this->yui3loader->filter === 'RAW') {
1220 $yuiformat = '';
1223 $format = '-min';
1224 if ($this->YUI_config->groups['moodle']['filter'] === 'DEBUG') {
1225 $format = '-debug';
1228 $rollupversion = $CFG->yui3version;
1229 if (!empty($CFG->yuipatchlevel)) {
1230 $rollupversion .= '_' . $CFG->yuipatchlevel;
1233 $baserollups = array(
1234 'rollup/' . $rollupversion . "/yui-moodlesimple{$yuiformat}.js",
1235 'rollup/' . $jsrev . "/mcore{$format}.js",
1238 if ($this->yui3loader->combine) {
1239 if (!empty($page->theme->yuicssmodules)) {
1240 $modules = array();
1241 foreach ($page->theme->yuicssmodules as $module) {
1242 $modules[] = "$CFG->yui3version/$module/$module-min.css";
1244 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase.implode('&amp;', $modules).'" />';
1246 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
1247 $code .= '<script type="text/javascript" src="'.$this->yui3loader->local_comboBase
1248 . implode('&amp;', $baserollups) . '"></script>';
1250 } else {
1251 if (!empty($page->theme->yuicssmodules)) {
1252 foreach ($page->theme->yuicssmodules as $module) {
1253 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.$module.'/'.$module.'-min.css" />';
1256 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
1257 foreach ($baserollups as $rollup) {
1258 $code .= '<script type="text/javascript" src="'.$this->yui3loader->local_comboBase.$rollup.'"></script>';
1262 if ($this->yui3loader->filter === 'RAW') {
1263 $code = str_replace('-min.css', '.css', $code);
1264 } else if ($this->yui3loader->filter === 'DEBUG') {
1265 $code = str_replace('-min.css', '.css', $code);
1267 return $code;
1271 * Returns html tags needed for inclusion of theme CSS.
1273 * @return string
1275 protected function get_css_code() {
1276 // First of all the theme CSS, then any custom CSS
1277 // Please note custom CSS is strongly discouraged,
1278 // because it can not be overridden by themes!
1279 // It is suitable only for things like mod/data which accepts CSS from teachers.
1280 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1282 // This line of code may look funny but it is currently required in order
1283 // to avoid MASSIVE display issues in Internet Explorer.
1284 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1285 // ignored whenever another resource is added until such time as a redraw
1286 // is forced, usually by moving the mouse over the affected element.
1287 $code = html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1289 $urls = $this->cssthemeurls + $this->cssurls;
1290 foreach ($urls as $url) {
1291 $attributes['href'] = $url;
1292 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1293 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1294 unset($attributes['id']);
1297 return $code;
1301 * Adds extra modules specified after printing of page header.
1303 * @return string
1305 protected function get_extra_modules_code() {
1306 if (empty($this->extramodules)) {
1307 return '';
1309 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1313 * Generate any HTML that needs to go inside the <head> tag.
1315 * Normally, this method is called automatically by the code that prints the
1316 * <head> tag. You should not normally need to call it in your own code.
1318 * @param moodle_page $page
1319 * @param core_renderer $renderer
1320 * @return string the HTML code to to inside the <head> tag.
1322 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1323 global $CFG;
1325 // Note: the $page and $output are not stored here because it would
1326 // create circular references in memory which prevents garbage collection.
1327 $this->init_requirements_data($page, $renderer);
1329 $output = '';
1331 // Set up the M namespace.
1332 $js = "var M = {}; M.yui = {};\n";
1334 // Capture the time now ASAP during page load. This minimises the lag when
1335 // we try to relate times on the server to times in the browser.
1336 // An example of where this is used is the quiz countdown timer.
1337 $js .= "M.pageloadstarttime = new Date();\n";
1339 // Add a subset of Moodle configuration to the M namespace.
1340 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1342 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1343 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1344 // this needs to be done before including any other script.
1345 $js .= $this->YUI_config->get_config_functions();
1346 $js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n";
1347 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1348 $js = $this->YUI_config->update_header_js($js);
1350 $output .= html_writer::script($js);
1352 // YUI3 JS and CSS need to be loaded in the header but after the YUI_config has been created.
1353 // They should be cached well by the browser.
1354 $output .= $this->get_yui3lib_headcode($page);
1356 // Add hacked jQuery support, it is not intended for standard Moodle distribution!
1357 $output .= $this->get_jquery_headcode();
1359 // Now theme CSS + custom CSS in this specific order.
1360 $output .= $this->get_css_code();
1362 // Link our main JS file, all core stuff should be there.
1363 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1365 // Add variables.
1366 if ($this->jsinitvariables['head']) {
1367 $js = '';
1368 foreach ($this->jsinitvariables['head'] as $data) {
1369 list($var, $value) = $data;
1370 $js .= js_writer::set_variable($var, $value, true);
1372 $output .= html_writer::script($js);
1375 // All the other linked things from HEAD - there should be as few as possible.
1376 if ($this->jsincludes['head']) {
1377 foreach ($this->jsincludes['head'] as $url) {
1378 $output .= html_writer::script('', $url);
1382 // Mark head sending done, it is not possible to anything there.
1383 $this->headdone = true;
1385 return $output;
1389 * Generate any HTML that needs to go at the start of the <body> tag.
1391 * Normally, this method is called automatically by the code that prints the
1392 * <head> tag. You should not normally need to call it in your own code.
1394 * @return string the HTML code to go at the start of the <body> tag.
1396 public function get_top_of_body_code() {
1397 // First the skip links.
1398 $links = '';
1399 $attributes = array('class'=>'skip');
1400 foreach ($this->skiplinks as $url => $text) {
1401 $attributes['href'] = '#' . $url;
1402 $links .= html_writer::tag('a', $text, $attributes);
1404 $output = html_writer::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1406 // Then the clever trick for hiding of things not needed when JS works.
1407 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1408 $this->topofbodydone = true;
1409 return $output;
1413 * Generate any HTML that needs to go at the end of the page.
1415 * Normally, this method is called automatically by the code that prints the
1416 * page footer. You should not normally need to call it in your own code.
1418 * @return string the HTML code to to at the end of the page.
1420 public function get_end_code() {
1421 global $CFG;
1423 // Add other requested modules.
1424 $output = $this->get_extra_modules_code();
1426 $this->js_init_code('M.util.js_complete("init");', true);
1428 // All the other linked scripts - there should be as few as possible.
1429 if ($this->jsincludes['footer']) {
1430 foreach ($this->jsincludes['footer'] as $url) {
1431 $output .= html_writer::script('', $url);
1435 // Add all needed strings.
1436 // First add core strings required for some dialogues.
1437 $this->strings_for_js(array(
1438 'confirm',
1439 'yes',
1440 'no',
1441 'areyousure',
1442 'closebuttontitle',
1443 'unknownerror',
1444 ), 'moodle');
1445 if (!empty($this->stringsforjs)) {
1446 $strings = array();
1447 foreach ($this->stringsforjs as $component=>$v) {
1448 foreach($v as $indentifier => $langstring) {
1449 $strings[$component][$indentifier] = $langstring->out();
1452 $output .= html_writer::script(js_writer::set_variable('M.str', $strings));
1455 // Add variables.
1456 if ($this->jsinitvariables['footer']) {
1457 $js = '';
1458 foreach ($this->jsinitvariables['footer'] as $data) {
1459 list($var, $value) = $data;
1460 $js .= js_writer::set_variable($var, $value, true);
1462 $output .= html_writer::script($js);
1465 $inyuijs = $this->get_javascript_code(false);
1466 $ondomreadyjs = $this->get_javascript_code(true);
1467 $jsinit = $this->get_javascript_init_code();
1468 $handlersjs = $this->get_event_handler_code();
1470 // There is no global Y, make sure it is available in your scope.
1471 $js = "YUI().use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1473 $output .= html_writer::script($js);
1475 return $output;
1479 * Have we already output the code in the <head> tag?
1481 * @return bool
1483 public function is_head_done() {
1484 return $this->headdone;
1488 * Have we already output the code at the start of the <body> tag?
1490 * @return bool
1492 public function is_top_of_body_done() {
1493 return $this->topofbodydone;
1498 * This class represents the YUI configuration.
1500 * @copyright 2013 Andrew Nicols
1501 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1502 * @since Moodle 2.5
1503 * @package core
1504 * @category output
1506 class YUI_config {
1508 * These settings must be public so that when the object is converted to json they are exposed.
1509 * Note: Some of these are camelCase because YUI uses camelCase variable names.
1511 * The settings are described and documented in the YUI API at:
1512 * - http://yuilibrary.com/yui/docs/api/classes/config.html
1513 * - http://yuilibrary.com/yui/docs/api/classes/Loader.html
1515 public $debug = false;
1516 public $base;
1517 public $comboBase;
1518 public $combine;
1519 public $filter = null;
1520 public $insertBefore = 'firstthemesheet';
1521 public $groups = array();
1522 public $modules = array();
1525 * @var array List of functions used by the YUI Loader group pattern recognition.
1527 protected $jsconfigfunctions = array();
1530 * Create a new group within the YUI_config system.
1532 * @param String $name The name of the group. This must be unique and
1533 * not previously used.
1534 * @param Array $config The configuration for this group.
1535 * @return void
1537 public function add_group($name, $config) {
1538 if (isset($this->groups[$name])) {
1539 throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
1541 $this->groups[$name] = $config;
1545 * Update an existing group configuration
1547 * Note, any existing configuration for that group will be wiped out.
1548 * This includes module configuration.
1550 * @param String $name The name of the group. This must be unique and
1551 * not previously used.
1552 * @param Array $config The configuration for this group.
1553 * @return void
1555 public function update_group($name, $config) {
1556 if (!isset($this->groups[$name])) {
1557 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.');
1559 $this->groups[$name] = $config;
1563 * Set the value of a configuration function used by the YUI Loader's pattern testing.
1565 * Only the body of the function should be passed, and not the whole function wrapper.
1567 * The JS function your write will be passed a single argument 'name' containing the
1568 * name of the module being loaded.
1570 * @param $function String the body of the JavaScript function. This should be used i
1571 * @return String the name of the function to use in the group pattern configuration.
1573 public function set_config_function($function) {
1574 $configname = 'yui' . (count($this->jsconfigfunctions) + 1) . 'ConfigFn';
1575 if (isset($this->jsconfigfunctions[$configname])) {
1576 throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
1578 $this->jsconfigfunctions[$configname] = $function;
1579 return '@' . $configname . '@';
1583 * Allow setting of the config function described in {@see set_config_function} from a file.
1584 * The contents of this file are then passed to set_config_function.
1586 * When jsrev is positive, the function is minified and stored in a MUC cache for subsequent uses.
1588 * @param $file The path to the JavaScript function used for YUI configuration.
1589 * @return String the name of the function to use in the group pattern configuration.
1591 public function set_config_source($file) {
1592 global $CFG;
1593 $cache = cache::make('core', 'yuimodules');
1595 // Attempt to get the metadata from the cache.
1596 $keyname = 'configfn_' . $file;
1597 $fullpath = $CFG->dirroot . '/' . $file;
1598 if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
1599 $cache->delete($keyname);
1600 $configfn = file_get_contents($fullpath);
1601 } else {
1602 $configfn = $cache->get($keyname);
1603 if ($configfn === false) {
1604 require_once($CFG->libdir . '/jslib.php');
1605 $configfn = core_minify::js_files(array($fullpath));
1606 $cache->set($keyname, $configfn);
1609 return $this->set_config_function($configfn);
1613 * Retrieve the list of JavaScript functions for YUI_config groups.
1615 * @return String The complete set of config functions
1617 public function get_config_functions() {
1618 $configfunctions = '';
1619 foreach ($this->jsconfigfunctions as $functionname => $function) {
1620 $configfunctions .= "var {$functionname} = function(me) {";
1621 $configfunctions .= $function;
1622 $configfunctions .= "};\n";
1624 return $configfunctions;
1628 * Update the header JavaScript with any required modification for the YUI Loader.
1630 * @param $js String The JavaScript to manipulate.
1631 * @return String the modified JS string.
1633 public function update_header_js($js) {
1634 // Update the names of the the configFn variables.
1635 // The PHP json_encode function cannot handle literal names so we have to wrap
1636 // them in @ and then replace them with literals of the same function name.
1637 foreach ($this->jsconfigfunctions as $functionname => $function) {
1638 $js = str_replace('"@' . $functionname . '@"', $functionname, $js);
1640 return $js;
1644 * Add configuration for a specific module.
1646 * @param String $name The name of the module to add configuration for.
1647 * @param Array $config The configuration for the specified module.
1648 * @param String $group The name of the group to add configuration for.
1649 * If not specified, then this module is added to the global
1650 * configuration.
1651 * @return void
1653 public function add_module_config($name, $config, $group = null) {
1654 if ($group) {
1655 if (!isset($this->groups[$name])) {
1656 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.');
1658 if (!isset($this->groups[$group]['modules'])) {
1659 $this->groups[$group]['modules'] = array();
1661 $modules = &$this->groups[$group]['modules'];
1662 } else {
1663 $modules = &$this->modules;
1665 $modules[$name] = $config;
1669 * Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
1671 * If js caching is disabled, metadata will not be served causing YUI to calculate
1672 * module dependencies as each module is loaded.
1674 * If metadata does not exist it will be created and stored in a MUC entry.
1676 * @return void
1678 public function add_moodle_metadata() {
1679 global $CFG;
1680 if (!isset($this->groups['moodle'])) {
1681 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.');
1684 if (!isset($this->groups['moodle']['modules'])) {
1685 $this->groups['moodle']['modules'] = array();
1688 $cache = cache::make('core', 'yuimodules');
1689 if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
1690 $metadata = array();
1691 $metadata = $this->get_moodle_metadata();
1692 $cache->delete('metadata');
1693 } else {
1694 // Attempt to get the metadata from the cache.
1695 if (!$metadata = $cache->get('metadata')) {
1696 $metadata = $this->get_moodle_metadata();
1697 $cache->set('metadata', $metadata);
1701 // Merge with any metadata added specific to this page which was added manually.
1702 $this->groups['moodle']['modules'] = array_merge($this->groups['moodle']['modules'],
1703 $metadata);
1707 * Determine the module metadata for all moodle YUI modules.
1709 * This works through all modules capable of serving YUI modules, and attempts to get
1710 * metadata for each of those modules.
1712 * @return Array of module metadata
1714 private function get_moodle_metadata() {
1715 $moodlemodules = array();
1716 // Core isn't a plugin type or subsystem - handle it seperately.
1717 if ($module = $this->get_moodle_path_metadata(core_component::get_component_directory('core'))) {
1718 $moodlemodules = array_merge($moodlemodules, $module);
1721 // Handle other core subsystems.
1722 $subsystems = core_component::get_core_subsystems();
1723 foreach ($subsystems as $subsystem => $path) {
1724 if (is_null($path)) {
1725 continue;
1727 if ($module = $this->get_moodle_path_metadata($path)) {
1728 $moodlemodules = array_merge($moodlemodules, $module);
1732 // And finally the plugins.
1733 $plugintypes = core_component::get_plugin_types();
1734 foreach ($plugintypes as $plugintype => $pathroot) {
1735 $pluginlist = core_component::get_plugin_list($plugintype);
1736 foreach ($pluginlist as $plugin => $path) {
1737 if ($module = $this->get_moodle_path_metadata($path)) {
1738 $moodlemodules = array_merge($moodlemodules, $module);
1743 return $moodlemodules;
1747 * Helper function process and return the YUI metadata for all of the modules under the specified path.
1749 * @param String $path the UNC path to the YUI src directory.
1750 * @return Array the complete array for frankenstyle directory.
1752 private function get_moodle_path_metadata($path) {
1753 // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
1754 $baseyui = $path . '/yui/src';
1755 $modules = array();
1756 if (is_dir($baseyui)) {
1757 $items = new DirectoryIterator($baseyui);
1758 foreach ($items as $item) {
1759 if ($item->isDot() or !$item->isDir()) {
1760 continue;
1762 $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
1763 if (!is_readable($metafile)) {
1764 continue;
1766 $metadata = file_get_contents($metafile);
1767 $modules = array_merge($modules, (array) json_decode($metadata));
1770 return $modules;
1774 * Define YUI modules which we have been required to patch between releases.
1776 * We must do this because we aggressively cache content on the browser, and we must also override use of the
1777 * external CDN which will serve the true authoritative copy of the code without our patches.
1779 * @param String combobase The local combobase
1780 * @param String yuiversion The current YUI version
1781 * @param Int patchlevel The patch level we're working to for YUI
1782 * @param Array patchedmodules An array containing the names of the patched modules
1783 * @return void
1785 public function define_patched_core_modules($combobase, $yuiversion, $patchlevel, $patchedmodules) {
1786 // The version we use is suffixed with a patchlevel so that we can get additional revisions between YUI releases.
1787 $subversion = $yuiversion . '_' . $patchlevel;
1789 if ($this->comboBase == $combobase) {
1790 // If we are using the local combobase in the loader, we can add a group and still make use of the combo
1791 // loader. We just need to specify a different root which includes a slightly different YUI version number
1792 // to include our patchlevel.
1793 $patterns = array();
1794 $modules = array();
1795 foreach ($patchedmodules as $modulename) {
1796 // We must define the pattern and module here so that the loader uses our group configuration instead of
1797 // the standard module definition. We may lose some metadata provided by upstream but this will be
1798 // loaded when the module is loaded anyway.
1799 $patterns[$modulename] = array(
1800 'group' => 'yui-patched',
1802 $modules[$modulename] = array();
1805 // Actually add the patch group here.
1806 $this->add_group('yui-patched', array(
1807 'combine' => true,
1808 'root' => $subversion . '/',
1809 'patterns' => $patterns,
1810 'modules' => $modules,
1813 } else {
1814 // The CDN is in use - we need to instead use the local combobase for this module and override the modules
1815 // definition. We cannot use the local base - we must use the combobase because we cannot invalidate the
1816 // local base in browser caches.
1817 $fullpathbase = $combobase . $subversion . '/';
1818 foreach ($patchedmodules as $modulename) {
1819 $this->modules[$modulename] = array(
1820 'fullpath' => $fullpathbase . $modulename . '/' . $modulename . '-min.js'
1828 * Invalidate all server and client side JS caches.
1830 function js_reset_all_caches() {
1831 global $CFG;
1833 $next = time();
1834 if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
1835 // This resolves problems when reset is requested repeatedly within 1s,
1836 // the < 1h condition prevents accidental switching to future dates
1837 // because we might not recover from it.
1838 $next = $CFG->jsrev+1;
1841 set_config('jsrev', $next);