weekly release 3.3dev
[moodle.git] / lib / outputrequirementslib.php
blob532314f9494c1b6f1dc45103a326aa9bb2136b2b
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library functions to facilitate the use of JavaScript in Moodle.
20 * Note: you can find history of this file in lib/ajax/ajaxlib.php
22 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @package core
25 * @category output
28 defined('MOODLE_INTERNAL') || die();
30 /**
31 * This class tracks all the things that are needed by the current page.
33 * Normally, the only instance of this class you will need to work with is the
34 * one accessible via $PAGE->requires.
36 * Typical usage would be
37 * <pre>
38 * $PAGE->requires->js_call_amd('mod_forum/view', 'init');
39 * </pre>
41 * It also supports obsoleted coding style with/without YUI3 modules.
42 * <pre>
43 * $PAGE->requires->js_init_call('M.mod_forum.init_view');
44 * $PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overridable via themes!
45 * $PAGE->requires->js('/mod/mymod/script.js');
46 * $PAGE->requires->js('/mod/mymod/small_but_urgent.js', true);
47 * $PAGE->requires->js_function_call('init_mymod', array($data), true);
48 * </pre>
50 * There are some natural restrictions on some methods. For example, {@link css()}
51 * can only be called before the <head> tag is output. See the comments on the
52 * individual methods for details.
54 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
55 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
56 * @since Moodle 2.0
57 * @package core
58 * @category output
60 class page_requirements_manager {
62 /**
63 * @var array List of string available from JS
65 protected $stringsforjs = array();
67 /**
68 * @var array List of get_string $a parameters - used for validation only.
70 protected $stringsforjs_as = array();
72 /**
73 * @var array List of JS variables to be initialised
75 protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
77 /**
78 * @var array Included JS scripts
80 protected $jsincludes = array('head'=>array(), 'footer'=>array());
82 /**
83 * @var array Inline scripts using RequireJS module loading.
85 protected $amdjscode = array('');
87 /**
88 * @var array List of needed function calls
90 protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
92 /**
93 * @var array List of skip links, those are needed for accessibility reasons
95 protected $skiplinks = array();
97 /**
98 * @var array Javascript code used for initialisation of page, it should
99 * be relatively small
101 protected $jsinitcode = array();
104 * @var array of moodle_url Theme sheets, initialised only from core_renderer
106 protected $cssthemeurls = array();
109 * @var array of moodle_url List of custom theme sheets, these are strongly discouraged!
110 * Useful mostly only for CSS submitted by teachers that is not part of the theme.
112 protected $cssurls = array();
115 * @var array List of requested event handlers
117 protected $eventhandlers = array();
120 * @var array Extra modules
122 protected $extramodules = array();
125 * @var array trackes the names of bits of HTML that are only required once
126 * per page. See {@link has_one_time_item_been_created()},
127 * {@link set_one_time_item_created()} and {@link should_create_one_time_item_now()}.
129 protected $onetimeitemsoutput = array();
132 * @var bool Flag indicated head stuff already printed
134 protected $headdone = false;
137 * @var bool Flag indicating top of body already printed
139 protected $topofbodydone = false;
142 * @var stdClass YUI PHPLoader instance responsible for YUI3 loading from PHP only
144 protected $yui3loader;
147 * @var YUI_config default YUI loader configuration
149 protected $YUI_config;
152 * @var array $yuicssmodules
154 protected $yuicssmodules = array();
157 * @var array Some config vars exposed in JS, please no secret stuff there
159 protected $M_cfg;
162 * @var array list of requested jQuery plugins
164 protected $jqueryplugins = array();
167 * @var array list of jQuery plugin overrides
169 protected $jquerypluginoverrides = array();
172 * Page requirements constructor.
174 public function __construct() {
175 global $CFG;
177 // You may need to set up URL rewrite rule because oversized URLs might not be allowed by web server.
178 $sep = empty($CFG->yuislasharguments) ? '?' : '/';
180 $this->yui3loader = new stdClass();
181 $this->YUI_config = new YUI_config();
183 if (is_https()) {
184 // On HTTPS sites all JS must be loaded from https sites,
185 // YUI CDN does not support https yet, sorry.
186 $CFG->useexternalyui = 0;
189 // Set up some loader options.
190 $this->yui3loader->local_base = $CFG->httpswwwroot . '/lib/yuilib/'. $CFG->yui3version . '/';
191 $this->yui3loader->local_comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep;
193 if (!empty($CFG->useexternalyui)) {
194 $this->yui3loader->base = 'http://yui.yahooapis.com/' . $CFG->yui3version . '/';
195 $this->yui3loader->comboBase = 'http://yui.yahooapis.com/combo?';
196 } else {
197 $this->yui3loader->base = $this->yui3loader->local_base;
198 $this->yui3loader->comboBase = $this->yui3loader->local_comboBase;
201 // Enable combo loader? This significantly helps with caching and performance!
202 $this->yui3loader->combine = !empty($CFG->yuicomboloading);
204 $jsrev = $this->get_jsrev();
206 // Set up JS YUI loader helper object.
207 $this->YUI_config->base = $this->yui3loader->base;
208 $this->YUI_config->comboBase = $this->yui3loader->comboBase;
209 $this->YUI_config->combine = $this->yui3loader->combine;
211 // If we've had to patch any YUI modules between releases, we must override the YUI configuration to include them.
212 // For important information on patching YUI modules, please see http://docs.moodle.org/dev/YUI/Patching.
213 if (!empty($CFG->yuipatchedmodules) && !empty($CFG->yuipatchlevel)) {
214 $this->YUI_config->define_patched_core_modules($this->yui3loader->local_comboBase,
215 $CFG->yui3version,
216 $CFG->yuipatchlevel,
217 $CFG->yuipatchedmodules);
220 $configname = $this->YUI_config->set_config_source('lib/yui/config/yui2.js');
221 $this->YUI_config->add_group('yui2', array(
222 // Loader configuration for our 2in3, for now ignores $CFG->useexternalyui.
223 'base' => $CFG->httpswwwroot . '/lib/yuilib/2in3/' . $CFG->yui2version . '/build/',
224 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
225 'combine' => $this->yui3loader->combine,
226 'ext' => false,
227 'root' => '2in3/' . $CFG->yui2version .'/build/',
228 'patterns' => array(
229 'yui2-' => array(
230 'group' => 'yui2',
231 'configFn' => $configname,
235 $configname = $this->YUI_config->set_config_source('lib/yui/config/moodle.js');
236 $this->YUI_config->add_group('moodle', array(
237 'name' => 'moodle',
238 'base' => $CFG->httpswwwroot . '/theme/yui_combo.php' . $sep . 'm/' . $jsrev . '/',
239 'combine' => $this->yui3loader->combine,
240 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
241 'ext' => false,
242 'root' => 'm/'.$jsrev.'/', // Add the rev to the root path so that we can control caching.
243 'patterns' => array(
244 'moodle-' => array(
245 'group' => 'moodle',
246 'configFn' => $configname,
251 $this->YUI_config->add_group('gallery', array(
252 'name' => 'gallery',
253 'base' => $CFG->httpswwwroot . '/lib/yuilib/gallery/',
254 'combine' => $this->yui3loader->combine,
255 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php' . $sep,
256 'ext' => false,
257 'root' => 'gallery/' . $jsrev . '/',
258 'patterns' => array(
259 'gallery-' => array(
260 'group' => 'gallery',
265 // Set some more loader options applying to groups too.
266 if ($CFG->debugdeveloper) {
267 // When debugging is enabled, we want to load the non-minified (RAW) versions of YUI library modules rather
268 // than the DEBUG versions as these generally generate too much logging for our purposes.
269 // However we do want the DEBUG versions of our Moodle-specific modules.
270 // To debug a YUI-specific issue, change the yui3loader->filter value to DEBUG.
271 $this->YUI_config->filter = 'RAW';
272 $this->YUI_config->groups['moodle']['filter'] = 'DEBUG';
274 // We use the yui3loader->filter setting when writing the YUI3 seed scripts into the header.
275 $this->yui3loader->filter = $this->YUI_config->filter;
276 $this->YUI_config->debug = true;
277 } else {
278 $this->yui3loader->filter = null;
279 $this->YUI_config->groups['moodle']['filter'] = null;
280 $this->YUI_config->debug = false;
283 // Include the YUI config log filters.
284 if (!empty($CFG->yuilogexclude) && is_array($CFG->yuilogexclude)) {
285 $this->YUI_config->logExclude = $CFG->yuilogexclude;
287 if (!empty($CFG->yuiloginclude) && is_array($CFG->yuiloginclude)) {
288 $this->YUI_config->logInclude = $CFG->yuiloginclude;
290 if (!empty($CFG->yuiloglevel)) {
291 $this->YUI_config->logLevel = $CFG->yuiloglevel;
294 // Add the moodle group's module data.
295 $this->YUI_config->add_moodle_metadata();
297 // Every page should include definition of following modules.
298 $this->js_module($this->find_module('core_filepicker'));
299 $this->js_module($this->find_module('core_comment'));
303 * Return the safe config values that get set for javascript in "M.cfg".
305 * @since 2.9
306 * @return array List of safe config values that are available to javascript.
308 public function get_config_for_javascript(moodle_page $page, renderer_base $renderer) {
309 global $CFG;
311 if (empty($this->M_cfg)) {
312 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
313 // Otherwise, in some situations, users will get warnings about insecure content
314 // on secure pages from their web browser.
316 $this->M_cfg = array(
317 'wwwroot' => $CFG->httpswwwroot, // Yes, really. See above.
318 'sesskey' => sesskey(),
319 'loadingicon' => $renderer->pix_url('i/loading_small', 'moodle')->out(false),
320 'themerev' => theme_get_revision(),
321 'slasharguments' => (int)(!empty($CFG->slasharguments)),
322 'theme' => $page->theme->name,
323 'jsrev' => $this->get_jsrev(),
324 'admin' => $CFG->admin,
325 'svgicons' => $page->theme->use_svg_icons()
327 if ($CFG->debugdeveloper) {
328 $this->M_cfg['developerdebug'] = true;
330 if (defined('BEHAT_SITE_RUNNING')) {
331 $this->M_cfg['behatsiterunning'] = true;
335 return $this->M_cfg;
339 * Initialise with the bits of JavaScript that every Moodle page should have.
341 * @param moodle_page $page
342 * @param core_renderer $renderer
344 protected function init_requirements_data(moodle_page $page, core_renderer $renderer) {
345 global $CFG;
347 // Init the js config.
348 $this->get_config_for_javascript($page, $renderer);
350 // Accessibility stuff.
351 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
353 // Add strings used on many pages.
354 $this->string_for_js('confirmation', 'admin');
355 $this->string_for_js('cancel', 'moodle');
356 $this->string_for_js('yes', 'moodle');
358 // Alter links in top frame to break out of frames.
359 if ($page->pagelayout === 'frametop') {
360 $this->js_init_call('M.util.init_frametop');
363 // Include block drag/drop if editing is on
364 if ($page->user_is_editing()) {
365 $params = array(
366 'courseid' => $page->course->id,
367 'pagetype' => $page->pagetype,
368 'pagelayout' => $page->pagelayout,
369 'subpage' => $page->subpage,
370 'regions' => $page->blocks->get_regions(),
371 'contextid' => $page->context->id,
373 if (!empty($page->cm->id)) {
374 $params['cmid'] = $page->cm->id;
376 // Strings for drag and drop.
377 $this->strings_for_js(array('movecontent',
378 'tocontent',
379 'emptydragdropregion'),
380 'moodle');
381 $page->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
384 // Include the YUI CSS Modules.
385 $page->requires->set_yuicssmodules($page->theme->yuicssmodules);
389 * Determine the correct JS Revision to use for this load.
391 * @return int the jsrev to use.
393 protected function get_jsrev() {
394 global $CFG;
396 if (empty($CFG->cachejs)) {
397 $jsrev = -1;
398 } else if (empty($CFG->jsrev)) {
399 $jsrev = 1;
400 } else {
401 $jsrev = $CFG->jsrev;
404 return $jsrev;
408 * Ensure that the specified JavaScript file is linked to from this page.
410 * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
411 * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
413 * By default the link is put at the end of the page, since this gives best page-load performance.
415 * Even if a particular script is requested more than once, it will only be linked
416 * to once.
418 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
419 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
420 * @param bool $inhead initialise in head
422 public function js($url, $inhead = false) {
423 $url = $this->js_fix_url($url);
424 $where = $inhead ? 'head' : 'footer';
425 $this->jsincludes[$where][$url->out()] = $url;
429 * Request inclusion of jQuery library in the page.
431 * NOTE: this should not be used in official Moodle distribution!
433 * {@see http://docs.moodle.org/dev/jQuery}
435 public function jquery() {
436 $this->jquery_plugin('jquery');
440 * Request inclusion of jQuery plugin.
442 * NOTE: this should not be used in official Moodle distribution!
444 * jQuery plugins are located in plugin/jquery/* subdirectory,
445 * plugin/jquery/plugins.php lists all available plugins.
447 * Included core plugins:
448 * - jQuery UI
450 * Add-ons may include extra jQuery plugins in jquery/ directory,
451 * plugins.php file defines the mapping between plugin names and
452 * necessary page includes.
454 * Examples:
455 * <code>
456 * // file: mod/xxx/view.php
457 * $PAGE->requires->jquery();
458 * $PAGE->requires->jquery_plugin('ui');
459 * $PAGE->requires->jquery_plugin('ui-css');
460 * </code>
462 * <code>
463 * // file: theme/yyy/lib.php
464 * function theme_yyy_page_init(moodle_page $page) {
465 * $page->requires->jquery();
466 * $page->requires->jquery_plugin('ui');
467 * $page->requires->jquery_plugin('ui-css');
469 * </code>
471 * <code>
472 * // file: blocks/zzz/block_zzz.php
473 * public function get_required_javascript() {
474 * parent::get_required_javascript();
475 * $this->page->requires->jquery();
476 * $page->requires->jquery_plugin('ui');
477 * $page->requires->jquery_plugin('ui-css');
479 * </code>
481 * {@see http://docs.moodle.org/dev/jQuery}
483 * @param string $plugin name of the jQuery plugin as defined in jquery/plugins.php
484 * @param string $component name of the component
485 * @return bool success
487 public function jquery_plugin($plugin, $component = 'core') {
488 global $CFG;
490 if ($this->headdone) {
491 debugging('Can not add jQuery plugins after starting page output!');
492 return false;
495 if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css'))) {
496 debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER);
497 $component = 'core';
498 } else if ($component !== 'core' and strpos($component, '_') === false) {
499 // Let's normalise the legacy activity names, Frankenstyle rulez!
500 $component = 'mod_' . $component;
503 if (empty($this->jqueryplugins) and ($component !== 'core' or $plugin !== 'jquery')) {
504 // Make sure the jQuery itself is always loaded first,
505 // the order of all other plugins depends on order of $PAGE_>requires->.
506 $this->jquery_plugin('jquery', 'core');
509 if (isset($this->jqueryplugins[$plugin])) {
510 // No problem, we already have something, first Moodle plugin to register the jQuery plugin wins.
511 return true;
514 $componentdir = core_component::get_component_directory($component);
515 if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
516 debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER);
517 return false;
520 $plugins = array();
521 require("$componentdir/jquery/plugins.php");
523 if (!isset($plugins[$plugin])) {
524 debugging("jQuery plugin '$plugin' can not be found in component '$component'.", DEBUG_DEVELOPER);
525 return false;
528 $this->jqueryplugins[$plugin] = new stdClass();
529 $this->jqueryplugins[$plugin]->plugin = $plugin;
530 $this->jqueryplugins[$plugin]->component = $component;
531 $this->jqueryplugins[$plugin]->urls = array();
533 foreach ($plugins[$plugin]['files'] as $file) {
534 if ($CFG->debugdeveloper) {
535 if (!file_exists("$componentdir/jquery/$file")) {
536 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
537 continue;
539 $file = str_replace('.min.css', '.css', $file);
540 $file = str_replace('.min.js', '.js', $file);
542 if (!file_exists("$componentdir/jquery/$file")) {
543 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
544 continue;
546 if (!empty($CFG->slasharguments)) {
547 $url = new moodle_url("$CFG->httpswwwroot/theme/jquery.php");
548 $url->set_slashargument("/$component/$file");
550 } else {
551 // This is not really good, we need slasharguments for relative links, this means no caching...
552 $path = realpath("$componentdir/jquery/$file");
553 if (strpos($path, $CFG->dirroot) === 0) {
554 $url = $CFG->httpswwwroot.preg_replace('/^'.preg_quote($CFG->dirroot, '/').'/', '', $path);
555 // Replace all occurences of backslashes characters in url to forward slashes.
556 $url = str_replace('\\', '/', $url);
557 $url = new moodle_url($url);
558 } else {
559 // Bad luck, fix your server!
560 debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
561 continue;
564 $this->jqueryplugins[$plugin]->urls[] = $url;
567 return true;
571 * Request replacement of one jQuery plugin by another.
573 * This is useful when themes want to replace the jQuery UI theme,
574 * the problem is that theme can not prevent others from including the core ui-css plugin.
576 * Example:
577 * 1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
578 * 2/ write theme/yourtheme/jquery/plugins.php
579 * 3/ init jQuery from theme
581 * <code>
582 * // file theme/yourtheme/lib.php
583 * function theme_yourtheme_page_init($page) {
584 * $page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
585 * $page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
587 * </code>
589 * This code prevents loading of standard 'ui-css' which my be requested by other plugins,
590 * the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
592 * {@see http://docs.moodle.org/dev/jQuery}
594 * @param string $oldplugin original plugin
595 * @param string $newplugin the replacement
597 public function jquery_override_plugin($oldplugin, $newplugin) {
598 if ($this->headdone) {
599 debugging('Can not override jQuery plugins after starting page output!');
600 return;
602 $this->jquerypluginoverrides[$oldplugin] = $newplugin;
606 * Return jQuery related markup for page start.
607 * @return string
609 protected function get_jquery_headcode() {
610 if (empty($this->jqueryplugins['jquery'])) {
611 // If nobody requested jQuery then do not bother to load anything.
612 // This may be useful for themes that want to override 'ui-css' only if requested by something else.
613 return '';
616 $included = array();
617 $urls = array();
619 foreach ($this->jqueryplugins as $name => $unused) {
620 if (isset($included[$name])) {
621 continue;
623 if (array_key_exists($name, $this->jquerypluginoverrides)) {
624 // The following loop tries to resolve the replacements,
625 // use max 100 iterations to prevent infinite loop resulting
626 // in blank page.
627 $cyclic = true;
628 $oldname = $name;
629 for ($i=0; $i<100; $i++) {
630 $name = $this->jquerypluginoverrides[$name];
631 if (!array_key_exists($name, $this->jquerypluginoverrides)) {
632 $cyclic = false;
633 break;
636 if ($cyclic) {
637 // We can not do much with cyclic references here, let's use the old plugin.
638 $name = $oldname;
639 debugging("Cyclic overrides detected for jQuery plugin '$name'");
641 } else if (empty($name)) {
642 // Developer requested removal of the plugin.
643 continue;
645 } else if (!isset($this->jqueryplugins[$name])) {
646 debugging("Unknown jQuery override plugin '$name' detected");
647 $name = $oldname;
649 } else if (isset($included[$name])) {
650 // The plugin was already included, easy.
651 continue;
655 $plugin = $this->jqueryplugins[$name];
656 $urls = array_merge($urls, $plugin->urls);
657 $included[$name] = true;
660 $output = '';
661 $attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
662 foreach ($urls as $url) {
663 if (preg_match('/\.js$/', $url)) {
664 $output .= html_writer::script('', $url);
665 } else if (preg_match('/\.css$/', $url)) {
666 $attributes['href'] = $url;
667 $output .= html_writer::empty_tag('link', $attributes) . "\n";
671 return $output;
675 * Returns the actual url through which a script is served.
677 * @param moodle_url|string $url full moodle url, or shortened path to script
678 * @return moodle_url
680 protected function js_fix_url($url) {
681 global $CFG;
683 if ($url instanceof moodle_url) {
684 return $url;
685 } else if (strpos($url, '/') === 0) {
686 // Fix the admin links if needed.
687 if ($CFG->admin !== 'admin') {
688 if (strpos($url, "/admin/") === 0) {
689 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
692 if (debugging()) {
693 // Check file existence only when in debug mode.
694 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
695 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
698 if (substr($url, -3) === '.js') {
699 $jsrev = $this->get_jsrev();
700 if (empty($CFG->slasharguments)) {
701 return new moodle_url($CFG->httpswwwroot.'/lib/javascript.php', array('rev'=>$jsrev, 'jsfile'=>$url));
702 } else {
703 $returnurl = new moodle_url($CFG->httpswwwroot.'/lib/javascript.php');
704 $returnurl->set_slashargument('/'.$jsrev.$url);
705 return $returnurl;
707 } else {
708 return new moodle_url($CFG->httpswwwroot.$url);
710 } else {
711 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
716 * Find out if JS module present and return details.
718 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
719 * @return array description of module or null if not found
721 protected function find_module($component) {
722 global $CFG, $PAGE;
724 $module = null;
726 if (strpos($component, 'core_') === 0) {
727 // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
728 // so that we do nto have to repeat the definition of these modules over and over again.
729 switch($component) {
730 case 'core_filepicker':
731 $module = array('name' => 'core_filepicker',
732 'fullpath' => '/repository/filepicker.js',
733 'requires' => array(
734 'base', 'node', 'node-event-simulate', 'json', 'async-queue', 'io-base', 'io-upload-iframe', 'io-form',
735 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort', 'resize-plugin', 'dd-plugin',
736 'escape', 'moodle-core_filepicker', 'moodle-core-notification-dialogue'
738 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
739 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
740 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
741 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
742 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
743 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
744 array('referencesexist', 'repository'), array('select', 'repository')
746 break;
747 case 'core_comment':
748 $module = array('name' => 'core_comment',
749 'fullpath' => '/comment/comment.js',
750 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
751 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
753 break;
754 case 'core_role':
755 $module = array('name' => 'core_role',
756 'fullpath' => '/admin/roles/module.js',
757 'requires' => array('node', 'cookie'));
758 break;
759 case 'core_completion':
760 $module = array('name' => 'core_completion',
761 'fullpath' => '/course/completion.js');
762 break;
763 case 'core_message':
764 $module = array('name' => 'core_message',
765 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
766 'fullpath' => '/message/module.js');
767 break;
768 case 'core_group':
769 $module = array('name' => 'core_group',
770 'fullpath' => '/group/module.js',
771 'requires' => array('node', 'overlay', 'event-mouseenter'));
772 break;
773 case 'core_question_engine':
774 $module = array('name' => 'core_question_engine',
775 'fullpath' => '/question/qengine.js',
776 'requires' => array('node', 'event'));
777 break;
778 case 'core_rating':
779 $module = array('name' => 'core_rating',
780 'fullpath' => '/rating/module.js',
781 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
782 break;
783 case 'core_dndupload':
784 $module = array('name' => 'core_dndupload',
785 'fullpath' => '/lib/form/dndupload.js',
786 'requires' => array('node', 'event', 'json', 'core_filepicker'),
787 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
788 array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesfile', 'error'),
789 array('sizegb', 'moodle'), array('sizemb', 'moodle'), array('sizekb', 'moodle'), array('sizeb', 'moodle'),
790 array('maxareabytesreached', 'moodle'), array('serverconnection', 'error'),
792 break;
795 } else {
796 if ($dir = core_component::get_component_directory($component)) {
797 if (file_exists("$dir/module.js")) {
798 if (strpos($dir, $CFG->dirroot.'/') === 0) {
799 $dir = substr($dir, strlen($CFG->dirroot));
800 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
806 return $module;
810 * Append YUI3 module to default YUI3 JS loader.
811 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
813 * @param string|array $module name of module (details are autodetected), or full module specification as array
814 * @return void
816 public function js_module($module) {
817 global $CFG;
819 if (empty($module)) {
820 throw new coding_exception('Missing YUI3 module name or full description.');
823 if (is_string($module)) {
824 $module = $this->find_module($module);
827 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
828 throw new coding_exception('Missing YUI3 module details.');
831 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
832 // Add all needed strings.
833 if (!empty($module['strings'])) {
834 foreach ($module['strings'] as $string) {
835 $identifier = $string[0];
836 $component = isset($string[1]) ? $string[1] : 'moodle';
837 $a = isset($string[2]) ? $string[2] : null;
838 $this->string_for_js($identifier, $component, $a);
841 unset($module['strings']);
843 // Process module requirements and attempt to load each. This allows
844 // moodle modules to require each other.
845 if (!empty($module['requires'])){
846 foreach ($module['requires'] as $requirement) {
847 $rmodule = $this->find_module($requirement);
848 if (is_array($rmodule)) {
849 $this->js_module($rmodule);
854 if ($this->headdone) {
855 $this->extramodules[$module['name']] = $module;
856 } else {
857 $this->YUI_config->add_module_config($module['name'], $module);
862 * Returns true if the module has already been loaded.
864 * @param string|array $module
865 * @return bool True if the module has already been loaded
867 protected function js_module_loaded($module) {
868 if (is_string($module)) {
869 $modulename = $module;
870 } else {
871 $modulename = $module['name'];
873 return array_key_exists($modulename, $this->YUI_config->modules) ||
874 array_key_exists($modulename, $this->extramodules);
878 * Ensure that the specified CSS file is linked to from this page.
880 * Because stylesheet links must go in the <head> part of the HTML, you must call
881 * this function before {@link get_head_code()} is called. That normally means before
882 * the call to print_header. If you call it when it is too late, an exception
883 * will be thrown.
885 * Even if a particular style sheet is requested more than once, it will only
886 * be linked to once.
888 * Please note use of this feature is strongly discouraged,
889 * it is suitable only for places where CSS is submitted directly by teachers.
890 * (Students must not be allowed to submit any external CSS because it may
891 * contain embedded javascript!). Example of correct use is mod/data.
893 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
894 * For example:
895 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
897 public function css($stylesheet) {
898 global $CFG;
900 if ($this->headdone) {
901 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
904 if ($stylesheet instanceof moodle_url) {
905 // ok
906 } else if (strpos($stylesheet, '/') === 0) {
907 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
908 } else {
909 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
912 $this->cssurls[$stylesheet->out()] = $stylesheet;
916 * Add theme stylesheet to page - do not use from plugin code,
917 * this should be called only from the core renderer!
919 * @param moodle_url $stylesheet
920 * @return void
922 public function css_theme(moodle_url $stylesheet) {
923 $this->cssthemeurls[] = $stylesheet;
927 * Ensure that a skip link to a given target is printed at the top of the <body>.
929 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
930 * will be thrown). That normally means you must call this before the call to print_header.
932 * If you ask for a particular skip link to be printed, it is then your responsibility
933 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
934 * page, so that the skip link goes somewhere.
936 * Even if a particular skip link is requested more than once, only one copy of it will be output.
938 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
939 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
941 public function skip_link_to($target, $linktext) {
942 if ($this->topofbodydone) {
943 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
944 return;
946 $this->skiplinks[$target] = $linktext;
950 * !!!DEPRECATED!!! please use js_init_call() if possible
951 * Ensure that the specified JavaScript function is called from an inline script
952 * somewhere on this page.
954 * By default the call will be put in a script tag at the
955 * end of the page after initialising Y instance, since this gives best page-load
956 * performance and allows you to use YUI3 library.
958 * If you request that a particular function is called several times, then
959 * that is what will happen (unlike linking to a CSS or JS file, where only
960 * one link will be output).
962 * The main benefit of the method is the automatic encoding of all function parameters.
964 * @deprecated
966 * @param string $function the name of the JavaScritp function to call. Can
967 * be a compound name like 'Y.Event.purgeElement'. Can also be
968 * used to create and object by using a 'function name' like 'new user_selector'.
969 * @param array $arguments and array of arguments to be passed to the function.
970 * When generating the function call, this will be escaped using json_encode,
971 * so passing objects and arrays should work.
972 * @param bool $ondomready If tru the function is only called when the dom is
973 * ready for manipulation.
974 * @param int $delay The delay before the function is called.
976 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
977 $where = $ondomready ? 'ondomready' : 'normal';
978 $this->jscalls[$where][] = array($function, $arguments, $delay);
982 * This function appends a block of code to the AMD specific javascript block executed
983 * in the page footer, just after loading the requirejs library.
985 * The code passed here can rely on AMD module loading, e.g. require('jquery', function($) {...});
987 * @param string $code The JS code to append.
989 public function js_amd_inline($code) {
990 $this->amdjscode[] = $code;
994 * This function creates a minimal JS script that requires and calls a single function from an AMD module with arguments.
995 * If it is called multiple times, it will be executed multiple times.
997 * @param string $fullmodule The format for module names is <component name>/<module name>.
998 * @param string $func The function from the module to call
999 * @param array $params The params to pass to the function. They will be json encoded, so no nasty classes/types please.
1001 public function js_call_amd($fullmodule, $func, $params = array()) {
1002 global $CFG;
1004 list($component, $module) = explode('/', $fullmodule, 2);
1006 $component = clean_param($component, PARAM_COMPONENT);
1007 $module = clean_param($module, PARAM_ALPHANUMEXT);
1008 $func = clean_param($func, PARAM_ALPHANUMEXT);
1010 $jsonparams = array();
1011 foreach ($params as $param) {
1012 $jsonparams[] = json_encode($param);
1014 $strparams = implode(', ', $jsonparams);
1015 if ($CFG->debugdeveloper) {
1016 $toomanyparamslimit = 1024;
1017 if (strlen($strparams) > $toomanyparamslimit) {
1018 debugging('Too many params passed to js_call_amd("' . $fullmodule . '", "' . $func . '")', DEBUG_DEVELOPER);
1022 $js = 'require(["' . $component . '/' . $module . '"], function(amd) { amd.' . $func . '(' . $strparams . '); });';
1024 $this->js_amd_inline($js);
1028 * Creates a JavaScript function call that requires one or more modules to be loaded.
1030 * This function can be used to include all of the standard YUI module types within JavaScript:
1031 * - YUI3 modules [node, event, io]
1032 * - YUI2 modules [yui2-*]
1033 * - Moodle modules [moodle-*]
1034 * - Gallery modules [gallery-*]
1036 * Before writing new code that makes extensive use of YUI, you should consider it's replacement AMD/JQuery.
1037 * @see js_call_amd()
1039 * @param array|string $modules One or more modules
1040 * @param string $function The function to call once modules have been loaded
1041 * @param array $arguments An array of arguments to pass to the function
1042 * @param string $galleryversion Deprecated: The gallery version to use
1043 * @param bool $ondomready
1045 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1046 if (!is_array($modules)) {
1047 $modules = array($modules);
1050 if ($galleryversion != null) {
1051 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.');
1054 $jscode = 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
1055 if ($ondomready) {
1056 $jscode = "Y.on('domready', function() { $jscode });";
1058 $this->jsinitcode[] = $jscode;
1062 * Set the CSS Modules to be included from YUI.
1064 * @param array $modules The list of YUI CSS Modules to include.
1066 public function set_yuicssmodules(array $modules = array()) {
1067 $this->yuicssmodules = $modules;
1071 * Ensure that the specified JavaScript function is called from an inline script
1072 * from page footer.
1074 * @param string $function the name of the JavaScritp function to with init code,
1075 * usually something like 'M.mod_mymodule.init'
1076 * @param array $extraarguments and array of arguments to be passed to the function.
1077 * The first argument is always the YUI3 Y instance with all required dependencies
1078 * already loaded.
1079 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1080 * @param array $module JS module specification array
1082 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1083 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
1084 if (!$module) {
1085 // Detect module automatically.
1086 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
1087 $module = $this->find_module($matches[1]);
1091 $this->js_init_code($jscode, $ondomready, $module);
1095 * Add short static javascript code fragment to page footer.
1096 * This is intended primarily for loading of js modules and initialising page layout.
1097 * Ideally the JS code fragment should be stored in plugin renderer so that themes
1098 * may override it.
1100 * @param string $jscode
1101 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1102 * @param array $module JS module specification array
1104 public function js_init_code($jscode, $ondomready = false, array $module = null) {
1105 $jscode = trim($jscode, " ;\n"). ';';
1107 $uniqid = html_writer::random_id();
1108 $startjs = " M.util.js_pending('" . $uniqid . "');";
1109 $endjs = " M.util.js_complete('" . $uniqid . "');";
1111 if ($module) {
1112 $this->js_module($module);
1113 $modulename = $module['name'];
1114 $jscode = "$startjs Y.use('$modulename', function(Y) { $jscode $endjs });";
1117 if ($ondomready) {
1118 $jscode = "$startjs Y.on('domready', function() { $jscode $endjs });";
1121 $this->jsinitcode[] = $jscode;
1125 * Make a language string available to JavaScript.
1127 * All the strings will be available in a M.str object in the global namespace.
1128 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
1129 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
1130 * equivalent in the current language.
1132 * The arguments to this function are just like the arguments to get_string
1133 * except that $component is not optional, and there are some aspects to consider
1134 * when the string contains {$a} placeholder.
1136 * If the string does not contain any {$a} placeholder, you can simply use
1137 * M.str.component.identifier to obtain it. If you prefer, you can call
1138 * M.util.get_string(identifier, component) to get the same result.
1140 * If you need to use {$a} placeholders, there are two options. Either the
1141 * placeholder should be substituted in PHP on server side or it should
1142 * be substituted in Javascript at client side.
1144 * To substitute the placeholder at server side, just provide the required
1145 * value for the placeholder when you require the string. Because each string
1146 * is only stored once in the JavaScript (based on $identifier and $module)
1147 * you cannot get the same string with two different values of $a. If you try,
1148 * an exception will be thrown. Once the placeholder is substituted, you can
1149 * use M.str or M.util.get_string() as shown above:
1151 * // Require the string in PHP and replace the placeholder.
1152 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
1153 * // Use the result of the substitution in Javascript.
1154 * alert(M.str.moodle.fullnamedisplay);
1156 * To substitute the placeholder at client side, use M.util.get_string()
1157 * function. It implements the same logic as {@link get_string()}:
1159 * // Require the string in PHP but keep {$a} as it is.
1160 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
1161 * // Provide the values on the fly in Javascript.
1162 * user = { firstname : 'Harry', lastname : 'Potter' }
1163 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
1165 * If you do need the same string expanded with different $a values in PHP
1166 * on server side, then the solution is to put them in your own data structure
1167 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
1169 * @param string $identifier the desired string.
1170 * @param string $component the language file to look in.
1171 * @param mixed $a any extra data to add into the string (optional).
1173 public function string_for_js($identifier, $component, $a = null) {
1174 if (!$component) {
1175 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
1177 if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
1178 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
1179 "from lang file '$component' with different \$a parameter?");
1181 if (!isset($this->stringsforjs[$component][$identifier])) {
1182 $this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
1183 $this->stringsforjs_as[$component][$identifier] = $a;
1188 * Make an array of language strings available for JS.
1190 * This function calls the above function {@link string_for_js()} for each requested
1191 * string in the $identifiers array that is passed to the argument for a single module
1192 * passed in $module.
1194 * <code>
1195 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
1197 * // The above is identical to calling:
1199 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
1200 * $PAGE->requires->string_for_js('two', 'mymod');
1201 * $PAGE->requires->string_for_js('three', 'mymod', 3);
1202 * </code>
1204 * @param array $identifiers An array of desired strings
1205 * @param string $component The module to load for
1206 * @param mixed $a This can either be a single variable that gets passed as extra
1207 * information for every string or it can be an array of mixed data where the
1208 * key for the data matches that of the identifier it is meant for.
1211 public function strings_for_js($identifiers, $component, $a = null) {
1212 foreach ($identifiers as $key => $identifier) {
1213 if (is_array($a) && array_key_exists($key, $a)) {
1214 $extra = $a[$key];
1215 } else {
1216 $extra = $a;
1218 $this->string_for_js($identifier, $component, $extra);
1223 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
1225 * Make some data from PHP available to JavaScript code.
1227 * For example, if you call
1228 * <pre>
1229 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
1230 * </pre>
1231 * then in JavsScript mydata.name will be 'Moodle'.
1233 * @deprecated
1234 * @param string $variable the the name of the JavaScript variable to assign the data to.
1235 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1236 * should be considered an experimental feature.
1237 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1238 * so passing objects and arrays should work.
1239 * @param bool $inhead initialise in head
1240 * @return void
1242 public function data_for_js($variable, $data, $inhead=false) {
1243 $where = $inhead ? 'head' : 'footer';
1244 $this->jsinitvariables[$where][] = array($variable, $data);
1248 * Creates a YUI event handler.
1250 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1251 * @param string $event A valid DOM event (click, mousedown, change etc.)
1252 * @param string $function The name of the function to call
1253 * @param array $arguments An optional array of argument parameters to pass to the function
1255 public function event_handler($selector, $event, $function, array $arguments = null) {
1256 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
1260 * Returns code needed for registering of event handlers.
1261 * @return string JS code
1263 protected function get_event_handler_code() {
1264 $output = '';
1265 foreach ($this->eventhandlers as $h) {
1266 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
1268 return $output;
1272 * Get the inline JavaScript code that need to appear in a particular place.
1273 * @param bool $ondomready
1274 * @return string
1276 protected function get_javascript_code($ondomready) {
1277 $where = $ondomready ? 'ondomready' : 'normal';
1278 $output = '';
1279 if ($this->jscalls[$where]) {
1280 foreach ($this->jscalls[$where] as $data) {
1281 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
1283 if (!empty($ondomready)) {
1284 $output = " Y.on('domready', function() {\n$output\n});";
1287 return $output;
1291 * Returns js code to be executed when Y is available.
1292 * @return string
1294 protected function get_javascript_init_code() {
1295 if (count($this->jsinitcode)) {
1296 return implode("\n", $this->jsinitcode) . "\n";
1298 return '';
1302 * Returns js code to load amd module loader, then insert inline script tags
1303 * that contain require() calls using RequireJS.
1304 * @return string
1306 protected function get_amd_footercode() {
1307 global $CFG;
1308 $output = '';
1309 $jsrev = $this->get_jsrev();
1311 $jsloader = new moodle_url($CFG->httpswwwroot . '/lib/javascript.php');
1312 $jsloader->set_slashargument('/' . $jsrev . '/');
1313 $requirejsloader = new moodle_url($CFG->httpswwwroot . '/lib/requirejs.php');
1314 $requirejsloader->set_slashargument('/' . $jsrev . '/');
1316 $requirejsconfig = file_get_contents($CFG->dirroot . '/lib/requirejs/moodle-config.js');
1318 // No extension required unless slash args is disabled.
1319 $jsextension = '.js';
1320 if (!empty($CFG->slasharguments)) {
1321 $jsextension = '';
1324 $requirejsconfig = str_replace('[BASEURL]', $requirejsloader, $requirejsconfig);
1325 $requirejsconfig = str_replace('[JSURL]', $jsloader, $requirejsconfig);
1326 $requirejsconfig = str_replace('[JSEXT]', $jsextension, $requirejsconfig);
1328 $output .= html_writer::script($requirejsconfig);
1329 if ($CFG->debugdeveloper) {
1330 $output .= html_writer::script('', $this->js_fix_url('/lib/requirejs/require.js'));
1331 } else {
1332 $output .= html_writer::script('', $this->js_fix_url('/lib/requirejs/require.min.js'));
1335 // First include must be to a module with no dependencies, this prevents multiple requests.
1336 $prefix = "require(['core/first'], function() {\n";
1337 $suffix = "\n});";
1338 $output .= html_writer::script($prefix . implode(";\n", $this->amdjscode) . $suffix);
1339 return $output;
1343 * Returns basic YUI3 CSS code.
1345 * @return string
1347 protected function get_yui3lib_headcss() {
1348 global $CFG;
1350 $yuiformat = '-min';
1351 if ($this->yui3loader->filter === 'RAW') {
1352 $yuiformat = '';
1355 $code = '';
1356 if ($this->yui3loader->combine) {
1357 if (!empty($this->yuicssmodules)) {
1358 $modules = array();
1359 foreach ($this->yuicssmodules as $module) {
1360 $modules[] = "$CFG->yui3version/$module/$module-min.css";
1362 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase.implode('&amp;', $modules).'" />';
1364 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
1366 } else {
1367 if (!empty($this->yuicssmodules)) {
1368 foreach ($this->yuicssmodules as $module) {
1369 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.$module.'/'.$module.'-min.css" />';
1372 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
1375 if ($this->yui3loader->filter === 'RAW') {
1376 $code = str_replace('-min.css', '.css', $code);
1377 } else if ($this->yui3loader->filter === 'DEBUG') {
1378 $code = str_replace('-min.css', '.css', $code);
1380 return $code;
1384 * Returns basic YUI3 JS loading code.
1386 * @return string
1388 protected function get_yui3lib_headcode() {
1389 global $CFG;
1391 $jsrev = $this->get_jsrev();
1393 $yuiformat = '-min';
1394 if ($this->yui3loader->filter === 'RAW') {
1395 $yuiformat = '';
1398 $format = '-min';
1399 if ($this->YUI_config->groups['moodle']['filter'] === 'DEBUG') {
1400 $format = '-debug';
1403 $rollupversion = $CFG->yui3version;
1404 if (!empty($CFG->yuipatchlevel)) {
1405 $rollupversion .= '_' . $CFG->yuipatchlevel;
1408 $baserollups = array(
1409 'rollup/' . $rollupversion . "/yui-moodlesimple{$yuiformat}.js",
1412 if ($this->yui3loader->combine) {
1413 return '<script type="text/javascript" src="' .
1414 $this->yui3loader->local_comboBase .
1415 implode('&amp;', $baserollups) .
1416 '"></script>';
1417 } else {
1418 $code = '';
1419 foreach ($baserollups as $rollup) {
1420 $code .= '<script type="text/javascript" src="'.$this->yui3loader->local_comboBase.$rollup.'"></script>';
1422 return $code;
1428 * Returns html tags needed for inclusion of theme CSS.
1430 * @return string
1432 protected function get_css_code() {
1433 // First of all the theme CSS, then any custom CSS
1434 // Please note custom CSS is strongly discouraged,
1435 // because it can not be overridden by themes!
1436 // It is suitable only for things like mod/data which accepts CSS from teachers.
1437 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1439 // Add the YUI code first. We want this to be overridden by any Moodle CSS.
1440 $code = $this->get_yui3lib_headcss();
1442 // This line of code may look funny but it is currently required in order
1443 // to avoid MASSIVE display issues in Internet Explorer.
1444 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1445 // ignored whenever another resource is added until such time as a redraw
1446 // is forced, usually by moving the mouse over the affected element.
1447 $code .= html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1449 $urls = $this->cssthemeurls + $this->cssurls;
1450 foreach ($urls as $url) {
1451 $attributes['href'] = $url;
1452 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1453 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1454 unset($attributes['id']);
1457 return $code;
1461 * Adds extra modules specified after printing of page header.
1463 * @return string
1465 protected function get_extra_modules_code() {
1466 if (empty($this->extramodules)) {
1467 return '';
1469 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1473 * Generate any HTML that needs to go inside the <head> tag.
1475 * Normally, this method is called automatically by the code that prints the
1476 * <head> tag. You should not normally need to call it in your own code.
1478 * @param moodle_page $page
1479 * @param core_renderer $renderer
1480 * @return string the HTML code to to inside the <head> tag.
1482 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1483 global $CFG;
1485 // Note: the $page and $output are not stored here because it would
1486 // create circular references in memory which prevents garbage collection.
1487 $this->init_requirements_data($page, $renderer);
1489 $output = '';
1491 // Add all standard CSS for this page.
1492 $output .= $this->get_css_code();
1494 // Set up the M namespace.
1495 $js = "var M = {}; M.yui = {};\n";
1497 // Capture the time now ASAP during page load. This minimises the lag when
1498 // we try to relate times on the server to times in the browser.
1499 // An example of where this is used is the quiz countdown timer.
1500 $js .= "M.pageloadstarttime = new Date();\n";
1502 // Add a subset of Moodle configuration to the M namespace.
1503 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1505 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1506 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1507 // this needs to be done before including any other script.
1508 $js .= $this->YUI_config->get_config_functions();
1509 $js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n";
1510 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1511 $js = $this->YUI_config->update_header_js($js);
1513 $output .= html_writer::script($js);
1515 // Add variables.
1516 if ($this->jsinitvariables['head']) {
1517 $js = '';
1518 foreach ($this->jsinitvariables['head'] as $data) {
1519 list($var, $value) = $data;
1520 $js .= js_writer::set_variable($var, $value, true);
1522 $output .= html_writer::script($js);
1525 // Mark head sending done, it is not possible to anything there.
1526 $this->headdone = true;
1528 return $output;
1532 * Generate any HTML that needs to go at the start of the <body> tag.
1534 * Normally, this method is called automatically by the code that prints the
1535 * <head> tag. You should not normally need to call it in your own code.
1537 * @param renderer_base $renderer
1538 * @return string the HTML code to go at the start of the <body> tag.
1540 public function get_top_of_body_code(renderer_base $renderer) {
1541 // First the skip links.
1542 $output = $renderer->render_skip_links($this->skiplinks);
1544 // YUI3 JS needs to be loaded early in the body. It should be cached well by the browser.
1545 $output .= $this->get_yui3lib_headcode();
1547 // Add hacked jQuery support, it is not intended for standard Moodle distribution!
1548 $output .= $this->get_jquery_headcode();
1550 // Link our main JS file, all core stuff should be there.
1551 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1553 // All the other linked things from HEAD - there should be as few as possible.
1554 if ($this->jsincludes['head']) {
1555 foreach ($this->jsincludes['head'] as $url) {
1556 $output .= html_writer::script('', $url);
1560 // Then the clever trick for hiding of things not needed when JS works.
1561 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1562 $this->topofbodydone = true;
1563 return $output;
1567 * Generate any HTML that needs to go at the end of the page.
1569 * Normally, this method is called automatically by the code that prints the
1570 * page footer. You should not normally need to call it in your own code.
1572 * @return string the HTML code to to at the end of the page.
1574 public function get_end_code() {
1575 global $CFG;
1576 $output = '';
1578 // Set the log level for the JS logging.
1579 $logconfig = new stdClass();
1580 $logconfig->level = 'warn';
1581 if ($CFG->debugdeveloper) {
1582 $logconfig->level = 'trace';
1584 $this->js_call_amd('core/log', 'setConfig', array($logconfig));
1586 // Call amd init functions.
1587 $output .= $this->get_amd_footercode();
1589 // Add other requested modules.
1590 $output .= $this->get_extra_modules_code();
1592 $this->js_init_code('M.util.js_complete("init");', true);
1594 // All the other linked scripts - there should be as few as possible.
1595 if ($this->jsincludes['footer']) {
1596 foreach ($this->jsincludes['footer'] as $url) {
1597 $output .= html_writer::script('', $url);
1601 // Add all needed strings.
1602 // First add core strings required for some dialogues.
1603 $this->strings_for_js(array(
1604 'confirm',
1605 'yes',
1606 'no',
1607 'areyousure',
1608 'closebuttontitle',
1609 'unknownerror',
1610 ), 'moodle');
1611 if (!empty($this->stringsforjs)) {
1612 $strings = array();
1613 foreach ($this->stringsforjs as $component=>$v) {
1614 foreach($v as $indentifier => $langstring) {
1615 $strings[$component][$indentifier] = $langstring->out();
1618 $output .= html_writer::script(js_writer::set_variable('M.str', $strings));
1621 // Add variables.
1622 if ($this->jsinitvariables['footer']) {
1623 $js = '';
1624 foreach ($this->jsinitvariables['footer'] as $data) {
1625 list($var, $value) = $data;
1626 $js .= js_writer::set_variable($var, $value, true);
1628 $output .= html_writer::script($js);
1631 $inyuijs = $this->get_javascript_code(false);
1632 $ondomreadyjs = $this->get_javascript_code(true);
1633 $jsinit = $this->get_javascript_init_code();
1634 $handlersjs = $this->get_event_handler_code();
1636 // There is a global Y, make sure it is available in your scope.
1637 $js = "(function() {{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}})();";
1639 $output .= html_writer::script($js);
1641 return $output;
1645 * Have we already output the code in the <head> tag?
1647 * @return bool
1649 public function is_head_done() {
1650 return $this->headdone;
1654 * Have we already output the code at the start of the <body> tag?
1656 * @return bool
1658 public function is_top_of_body_done() {
1659 return $this->topofbodydone;
1663 * Should we generate a bit of content HTML that is only required once on
1664 * this page (e.g. the contents of the modchooser), now? Basically, we call
1665 * {@link has_one_time_item_been_created()}, and if the thing has not already
1666 * been output, we return true to tell the caller to generate it, and also
1667 * call {@link set_one_time_item_created()} to record the fact that it is
1668 * about to be generated.
1670 * That is, a typical usage pattern (in a renderer method) is:
1671 * <pre>
1672 * if (!$this->page->requires->should_create_one_time_item_now($thing)) {
1673 * return '';
1675 * // Else generate it.
1676 * </pre>
1678 * @param string $thing identifier for the bit of content. Should be of the form
1679 * frankenstyle_things, e.g. core_course_modchooser.
1680 * @return bool if true, the caller should generate that bit of output now, otherwise don't.
1682 public function should_create_one_time_item_now($thing) {
1683 if ($this->has_one_time_item_been_created($thing)) {
1684 return false;
1687 $this->set_one_time_item_created($thing);
1688 return true;
1692 * Has a particular bit of HTML that is only required once on this page
1693 * (e.g. the contents of the modchooser) already been generated?
1695 * Normally, you can use the {@link should_create_one_time_item_now()} helper
1696 * method rather than calling this method directly.
1698 * @param string $thing identifier for the bit of content. Should be of the form
1699 * frankenstyle_things, e.g. core_course_modchooser.
1700 * @return bool whether that bit of output has been created.
1702 public function has_one_time_item_been_created($thing) {
1703 return isset($this->onetimeitemsoutput[$thing]);
1707 * Indicate that a particular bit of HTML that is only required once on this
1708 * page (e.g. the contents of the modchooser) has been generated (or is about to be)?
1710 * Normally, you can use the {@link should_create_one_time_item_now()} helper
1711 * method rather than calling this method directly.
1713 * @param string $thing identifier for the bit of content. Should be of the form
1714 * frankenstyle_things, e.g. core_course_modchooser.
1716 public function set_one_time_item_created($thing) {
1717 if ($this->has_one_time_item_been_created($thing)) {
1718 throw new coding_exception($thing . ' is only supposed to be ouput ' .
1719 'once per page, but it seems to be being output again.');
1721 return $this->onetimeitemsoutput[$thing] = true;
1726 * This class represents the YUI configuration.
1728 * @copyright 2013 Andrew Nicols
1729 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1730 * @since Moodle 2.5
1731 * @package core
1732 * @category output
1734 class YUI_config {
1736 * These settings must be public so that when the object is converted to json they are exposed.
1737 * Note: Some of these are camelCase because YUI uses camelCase variable names.
1739 * The settings are described and documented in the YUI API at:
1740 * - http://yuilibrary.com/yui/docs/api/classes/config.html
1741 * - http://yuilibrary.com/yui/docs/api/classes/Loader.html
1743 public $debug = false;
1744 public $base;
1745 public $comboBase;
1746 public $combine;
1747 public $filter = null;
1748 public $insertBefore = 'firstthemesheet';
1749 public $groups = array();
1750 public $modules = array();
1753 * @var array List of functions used by the YUI Loader group pattern recognition.
1755 protected $jsconfigfunctions = array();
1758 * Create a new group within the YUI_config system.
1760 * @param String $name The name of the group. This must be unique and
1761 * not previously used.
1762 * @param Array $config The configuration for this group.
1763 * @return void
1765 public function add_group($name, $config) {
1766 if (isset($this->groups[$name])) {
1767 throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
1769 $this->groups[$name] = $config;
1773 * Update an existing group configuration
1775 * Note, any existing configuration for that group will be wiped out.
1776 * This includes module configuration.
1778 * @param String $name The name of the group. This must be unique and
1779 * not previously used.
1780 * @param Array $config The configuration for this group.
1781 * @return void
1783 public function update_group($name, $config) {
1784 if (!isset($this->groups[$name])) {
1785 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.');
1787 $this->groups[$name] = $config;
1791 * Set the value of a configuration function used by the YUI Loader's pattern testing.
1793 * Only the body of the function should be passed, and not the whole function wrapper.
1795 * The JS function your write will be passed a single argument 'name' containing the
1796 * name of the module being loaded.
1798 * @param $function String the body of the JavaScript function. This should be used i
1799 * @return String the name of the function to use in the group pattern configuration.
1801 public function set_config_function($function) {
1802 $configname = 'yui' . (count($this->jsconfigfunctions) + 1) . 'ConfigFn';
1803 if (isset($this->jsconfigfunctions[$configname])) {
1804 throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
1806 $this->jsconfigfunctions[$configname] = $function;
1807 return '@' . $configname . '@';
1811 * Allow setting of the config function described in {@see set_config_function} from a file.
1812 * The contents of this file are then passed to set_config_function.
1814 * When jsrev is positive, the function is minified and stored in a MUC cache for subsequent uses.
1816 * @param $file The path to the JavaScript function used for YUI configuration.
1817 * @return String the name of the function to use in the group pattern configuration.
1819 public function set_config_source($file) {
1820 global $CFG;
1821 $cache = cache::make('core', 'yuimodules');
1823 // Attempt to get the metadata from the cache.
1824 $keyname = 'configfn_' . $file;
1825 $fullpath = $CFG->dirroot . '/' . $file;
1826 if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
1827 $cache->delete($keyname);
1828 $configfn = file_get_contents($fullpath);
1829 } else {
1830 $configfn = $cache->get($keyname);
1831 if ($configfn === false) {
1832 require_once($CFG->libdir . '/jslib.php');
1833 $configfn = core_minify::js_files(array($fullpath));
1834 $cache->set($keyname, $configfn);
1837 return $this->set_config_function($configfn);
1841 * Retrieve the list of JavaScript functions for YUI_config groups.
1843 * @return String The complete set of config functions
1845 public function get_config_functions() {
1846 $configfunctions = '';
1847 foreach ($this->jsconfigfunctions as $functionname => $function) {
1848 $configfunctions .= "var {$functionname} = function(me) {";
1849 $configfunctions .= $function;
1850 $configfunctions .= "};\n";
1852 return $configfunctions;
1856 * Update the header JavaScript with any required modification for the YUI Loader.
1858 * @param $js String The JavaScript to manipulate.
1859 * @return String the modified JS string.
1861 public function update_header_js($js) {
1862 // Update the names of the the configFn variables.
1863 // The PHP json_encode function cannot handle literal names so we have to wrap
1864 // them in @ and then replace them with literals of the same function name.
1865 foreach ($this->jsconfigfunctions as $functionname => $function) {
1866 $js = str_replace('"@' . $functionname . '@"', $functionname, $js);
1868 return $js;
1872 * Add configuration for a specific module.
1874 * @param String $name The name of the module to add configuration for.
1875 * @param Array $config The configuration for the specified module.
1876 * @param String $group The name of the group to add configuration for.
1877 * If not specified, then this module is added to the global
1878 * configuration.
1879 * @return void
1881 public function add_module_config($name, $config, $group = null) {
1882 if ($group) {
1883 if (!isset($this->groups[$name])) {
1884 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.');
1886 if (!isset($this->groups[$group]['modules'])) {
1887 $this->groups[$group]['modules'] = array();
1889 $modules = &$this->groups[$group]['modules'];
1890 } else {
1891 $modules = &$this->modules;
1893 $modules[$name] = $config;
1897 * Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
1899 * If js caching is disabled, metadata will not be served causing YUI to calculate
1900 * module dependencies as each module is loaded.
1902 * If metadata does not exist it will be created and stored in a MUC entry.
1904 * @return void
1906 public function add_moodle_metadata() {
1907 global $CFG;
1908 if (!isset($this->groups['moodle'])) {
1909 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.');
1912 if (!isset($this->groups['moodle']['modules'])) {
1913 $this->groups['moodle']['modules'] = array();
1916 $cache = cache::make('core', 'yuimodules');
1917 if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
1918 $metadata = array();
1919 $metadata = $this->get_moodle_metadata();
1920 $cache->delete('metadata');
1921 } else {
1922 // Attempt to get the metadata from the cache.
1923 if (!$metadata = $cache->get('metadata')) {
1924 $metadata = $this->get_moodle_metadata();
1925 $cache->set('metadata', $metadata);
1929 // Merge with any metadata added specific to this page which was added manually.
1930 $this->groups['moodle']['modules'] = array_merge($this->groups['moodle']['modules'],
1931 $metadata);
1935 * Determine the module metadata for all moodle YUI modules.
1937 * This works through all modules capable of serving YUI modules, and attempts to get
1938 * metadata for each of those modules.
1940 * @return Array of module metadata
1942 private function get_moodle_metadata() {
1943 $moodlemodules = array();
1944 // Core isn't a plugin type or subsystem - handle it seperately.
1945 if ($module = $this->get_moodle_path_metadata(core_component::get_component_directory('core'))) {
1946 $moodlemodules = array_merge($moodlemodules, $module);
1949 // Handle other core subsystems.
1950 $subsystems = core_component::get_core_subsystems();
1951 foreach ($subsystems as $subsystem => $path) {
1952 if (is_null($path)) {
1953 continue;
1955 if ($module = $this->get_moodle_path_metadata($path)) {
1956 $moodlemodules = array_merge($moodlemodules, $module);
1960 // And finally the plugins.
1961 $plugintypes = core_component::get_plugin_types();
1962 foreach ($plugintypes as $plugintype => $pathroot) {
1963 $pluginlist = core_component::get_plugin_list($plugintype);
1964 foreach ($pluginlist as $plugin => $path) {
1965 if ($module = $this->get_moodle_path_metadata($path)) {
1966 $moodlemodules = array_merge($moodlemodules, $module);
1971 return $moodlemodules;
1975 * Helper function process and return the YUI metadata for all of the modules under the specified path.
1977 * @param String $path the UNC path to the YUI src directory.
1978 * @return Array the complete array for frankenstyle directory.
1980 private function get_moodle_path_metadata($path) {
1981 // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
1982 $baseyui = $path . '/yui/src';
1983 $modules = array();
1984 if (is_dir($baseyui)) {
1985 $items = new DirectoryIterator($baseyui);
1986 foreach ($items as $item) {
1987 if ($item->isDot() or !$item->isDir()) {
1988 continue;
1990 $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
1991 if (!is_readable($metafile)) {
1992 continue;
1994 $metadata = file_get_contents($metafile);
1995 $modules = array_merge($modules, (array) json_decode($metadata));
1998 return $modules;
2002 * Define YUI modules which we have been required to patch between releases.
2004 * We must do this because we aggressively cache content on the browser, and we must also override use of the
2005 * external CDN which will serve the true authoritative copy of the code without our patches.
2007 * @param String combobase The local combobase
2008 * @param String yuiversion The current YUI version
2009 * @param Int patchlevel The patch level we're working to for YUI
2010 * @param Array patchedmodules An array containing the names of the patched modules
2011 * @return void
2013 public function define_patched_core_modules($combobase, $yuiversion, $patchlevel, $patchedmodules) {
2014 // The version we use is suffixed with a patchlevel so that we can get additional revisions between YUI releases.
2015 $subversion = $yuiversion . '_' . $patchlevel;
2017 if ($this->comboBase == $combobase) {
2018 // If we are using the local combobase in the loader, we can add a group and still make use of the combo
2019 // loader. We just need to specify a different root which includes a slightly different YUI version number
2020 // to include our patchlevel.
2021 $patterns = array();
2022 $modules = array();
2023 foreach ($patchedmodules as $modulename) {
2024 // We must define the pattern and module here so that the loader uses our group configuration instead of
2025 // the standard module definition. We may lose some metadata provided by upstream but this will be
2026 // loaded when the module is loaded anyway.
2027 $patterns[$modulename] = array(
2028 'group' => 'yui-patched',
2030 $modules[$modulename] = array();
2033 // Actually add the patch group here.
2034 $this->add_group('yui-patched', array(
2035 'combine' => true,
2036 'root' => $subversion . '/',
2037 'patterns' => $patterns,
2038 'modules' => $modules,
2041 } else {
2042 // The CDN is in use - we need to instead use the local combobase for this module and override the modules
2043 // definition. We cannot use the local base - we must use the combobase because we cannot invalidate the
2044 // local base in browser caches.
2045 $fullpathbase = $combobase . $subversion . '/';
2046 foreach ($patchedmodules as $modulename) {
2047 $this->modules[$modulename] = array(
2048 'fullpath' => $fullpathbase . $modulename . '/' . $modulename . '-min.js'
2056 * Invalidate all server and client side JS caches.
2058 function js_reset_all_caches() {
2059 global $CFG;
2061 $next = time();
2062 if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
2063 // This resolves problems when reset is requested repeatedly within 1s,
2064 // the < 1h condition prevents accidental switching to future dates
2065 // because we might not recover from it.
2066 $next = $CFG->jsrev+1;
2069 set_config('jsrev', $next);