2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
28 defined('MOODLE_INTERNAL') ||
die();
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
38 * $PAGE->requires->js_call_amd('mod_forum/view', 'init');
41 * It also supports obsoleted coding style with/without YUI3 modules.
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);
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
60 class page_requirements_manager
{
63 * @var array List of string available from JS
65 protected $stringsforjs = array();
68 * @var array List of get_string $a parameters - used for validation only.
70 protected $stringsforjs_as = array();
73 * @var array List of JS variables to be initialised
75 protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
78 * @var array Included JS scripts
80 protected $jsincludes = array('head'=>array(), 'footer'=>array());
83 * @var array Inline scripts using RequireJS module loading.
85 protected $amdjscode = array('');
88 * @var array List of needed function calls
90 protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
93 * @var array List of skip links, those are needed for accessibility reasons
95 protected $skiplinks = array();
98 * @var array Javascript code used for initialisation of page, it should
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 Some config vars exposed in JS, please no secret stuff there
157 * @var array list of requested jQuery plugins
159 protected $jqueryplugins = array();
162 * @var array list of jQuery plugin overrides
164 protected $jquerypluginoverrides = array();
167 * Page requirements constructor.
169 public function __construct() {
172 // You may need to set up URL rewrite rule because oversized URLs might not be allowed by web server.
173 $sep = empty($CFG->yuislasharguments
) ?
'?' : '/';
175 $this->yui3loader
= new stdClass();
176 $this->YUI_config
= new YUI_config();
179 // On HTTPS sites all JS must be loaded from https sites,
180 // YUI CDN does not support https yet, sorry.
181 $CFG->useexternalyui
= 0;
184 // Set up some loader options.
185 $this->yui3loader
->local_base
= $CFG->httpswwwroot
. '/lib/yuilib/'. $CFG->yui3version
. '/';
186 $this->yui3loader
->local_comboBase
= $CFG->httpswwwroot
. '/theme/yui_combo.php'.$sep;
188 if (!empty($CFG->useexternalyui
)) {
189 $this->yui3loader
->base
= 'http://yui.yahooapis.com/' . $CFG->yui3version
. '/';
190 $this->yui3loader
->comboBase
= 'http://yui.yahooapis.com/combo?';
192 $this->yui3loader
->base
= $this->yui3loader
->local_base
;
193 $this->yui3loader
->comboBase
= $this->yui3loader
->local_comboBase
;
196 // Enable combo loader? This significantly helps with caching and performance!
197 $this->yui3loader
->combine
= !empty($CFG->yuicomboloading
);
199 $jsrev = $this->get_jsrev();
201 // Set up JS YUI loader helper object.
202 $this->YUI_config
->base
= $this->yui3loader
->base
;
203 $this->YUI_config
->comboBase
= $this->yui3loader
->comboBase
;
204 $this->YUI_config
->combine
= $this->yui3loader
->combine
;
206 // If we've had to patch any YUI modules between releases, we must override the YUI configuration to include them.
207 // For important information on patching YUI modules, please see http://docs.moodle.org/dev/YUI/Patching.
208 if (!empty($CFG->yuipatchedmodules
) && !empty($CFG->yuipatchlevel
)) {
209 $this->YUI_config
->define_patched_core_modules($this->yui3loader
->local_comboBase
,
212 $CFG->yuipatchedmodules
);
215 $configname = $this->YUI_config
->set_config_source('lib/yui/config/yui2.js');
216 $this->YUI_config
->add_group('yui2', array(
217 // Loader configuration for our 2in3, for now ignores $CFG->useexternalyui.
218 'base' => $CFG->httpswwwroot
. '/lib/yuilib/2in3/' . $CFG->yui2version
. '/build/',
219 'comboBase' => $CFG->httpswwwroot
. '/theme/yui_combo.php'.$sep,
220 'combine' => $this->yui3loader
->combine
,
222 'root' => '2in3/' . $CFG->yui2version
.'/build/',
226 'configFn' => $configname,
230 $configname = $this->YUI_config
->set_config_source('lib/yui/config/moodle.js');
231 $this->YUI_config
->add_group('moodle', array(
233 'base' => $CFG->httpswwwroot
. '/theme/yui_combo.php' . $sep . 'm/' . $jsrev . '/',
234 'combine' => $this->yui3loader
->combine
,
235 'comboBase' => $CFG->httpswwwroot
. '/theme/yui_combo.php'.$sep,
237 'root' => 'm/'.$jsrev.'/', // Add the rev to the root path so that we can control caching.
241 'configFn' => $configname,
246 $this->YUI_config
->add_group('gallery', array(
248 'base' => $CFG->httpswwwroot
. '/lib/yuilib/gallery/',
249 'combine' => $this->yui3loader
->combine
,
250 'comboBase' => $CFG->httpswwwroot
. '/theme/yui_combo.php' . $sep,
252 'root' => 'gallery/' . $jsrev . '/',
255 'group' => 'gallery',
260 // Set some more loader options applying to groups too.
261 if ($CFG->debugdeveloper
) {
262 // When debugging is enabled, we want to load the non-minified (RAW) versions of YUI library modules rather
263 // than the DEBUG versions as these generally generate too much logging for our purposes.
264 // However we do want the DEBUG versions of our Moodle-specific modules.
265 // To debug a YUI-specific issue, change the yui3loader->filter value to DEBUG.
266 $this->YUI_config
->filter
= 'RAW';
267 $this->YUI_config
->groups
['moodle']['filter'] = 'DEBUG';
269 // We use the yui3loader->filter setting when writing the YUI3 seed scripts into the header.
270 $this->yui3loader
->filter
= $this->YUI_config
->filter
;
271 $this->YUI_config
->debug
= true;
273 $this->yui3loader
->filter
= null;
274 $this->YUI_config
->groups
['moodle']['filter'] = null;
275 $this->YUI_config
->debug
= false;
278 // Include the YUI config log filters.
279 if (!empty($CFG->yuilogexclude
) && is_array($CFG->yuilogexclude
)) {
280 $this->YUI_config
->logExclude
= $CFG->yuilogexclude
;
282 if (!empty($CFG->yuiloginclude
) && is_array($CFG->yuiloginclude
)) {
283 $this->YUI_config
->logInclude
= $CFG->yuiloginclude
;
285 if (!empty($CFG->yuiloglevel
)) {
286 $this->YUI_config
->logLevel
= $CFG->yuiloglevel
;
289 // Add the moodle group's module data.
290 $this->YUI_config
->add_moodle_metadata();
292 // Every page should include definition of following modules.
293 $this->js_module($this->find_module('core_filepicker'));
297 * Return the safe config values that get set for javascript in "M.cfg".
300 * @return array List of safe config values that are available to javascript.
302 public function get_config_for_javascript(moodle_page
$page, renderer_base
$renderer) {
305 if (empty($this->M_cfg
)) {
306 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
307 // Otherwise, in some situations, users will get warnings about insecure content
308 // on secure pages from their web browser.
310 $this->M_cfg
= array(
311 'wwwroot' => $CFG->httpswwwroot
, // Yes, really. See above.
312 'sesskey' => sesskey(),
313 'loadingicon' => $renderer->pix_url('i/loading_small', 'moodle')->out(false),
314 'themerev' => theme_get_revision(),
315 'slasharguments' => (int)(!empty($CFG->slasharguments
)),
316 'theme' => $page->theme
->name
,
317 'jsrev' => $this->get_jsrev(),
318 'admin' => $CFG->admin
,
319 'svgicons' => $page->theme
->use_svg_icons()
321 if ($CFG->debugdeveloper
) {
322 $this->M_cfg
['developerdebug'] = true;
324 if (defined('BEHAT_SITE_RUNNING')) {
325 $this->M_cfg
['behatsiterunning'] = true;
333 * Initialise with the bits of JavaScript that every Moodle page should have.
335 * @param moodle_page $page
336 * @param core_renderer $renderer
338 protected function init_requirements_data(moodle_page
$page, core_renderer
$renderer) {
341 // Init the js config.
342 $this->get_config_for_javascript($page, $renderer);
344 // Accessibility stuff.
345 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
347 // Add strings used on many pages.
348 $this->string_for_js('confirmation', 'admin');
349 $this->string_for_js('cancel', 'moodle');
350 $this->string_for_js('yes', 'moodle');
352 // Alter links in top frame to break out of frames.
353 if ($page->pagelayout
=== 'frametop') {
354 $this->js_init_call('M.util.init_frametop');
357 // Include block drag/drop if editing is on
358 if ($page->user_is_editing()) {
360 'courseid' => $page->course
->id
,
361 'pagetype' => $page->pagetype
,
362 'pagelayout' => $page->pagelayout
,
363 'subpage' => $page->subpage
,
364 'regions' => $page->blocks
->get_regions(),
365 'contextid' => $page->context
->id
,
367 if (!empty($page->cm
->id
)) {
368 $params['cmid'] = $page->cm
->id
;
370 // Strings for drag and drop.
371 $this->strings_for_js(array('movecontent',
373 'emptydragdropregion'),
375 $page->requires
->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
380 * Determine the correct JS Revision to use for this load.
382 * @return int the jsrev to use.
384 protected function get_jsrev() {
387 if (empty($CFG->cachejs
)) {
389 } else if (empty($CFG->jsrev
)) {
392 $jsrev = $CFG->jsrev
;
399 * Ensure that the specified JavaScript file is linked to from this page.
401 * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
402 * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
404 * By default the link is put at the end of the page, since this gives best page-load performance.
406 * Even if a particular script is requested more than once, it will only be linked
409 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
410 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
411 * @param bool $inhead initialise in head
413 public function js($url, $inhead = false) {
414 $url = $this->js_fix_url($url);
415 $where = $inhead ?
'head' : 'footer';
416 $this->jsincludes
[$where][$url->out()] = $url;
420 * Request inclusion of jQuery library in the page.
422 * NOTE: this should not be used in official Moodle distribution!
424 * We are going to bundle jQuery 1.9.x until we drop support
425 * all support for IE 6-8. Use $PAGE->requires->jquery_plugin('migrate')
426 * for code written for earlier jQuery versions.
428 * {@see http://docs.moodle.org/dev/jQuery}
430 public function jquery() {
431 $this->jquery_plugin('jquery');
435 * Request inclusion of jQuery plugin.
437 * NOTE: this should not be used in official Moodle distribution!
439 * jQuery plugins are located in plugin/jquery/* subdirectory,
440 * plugin/jquery/plugins.php lists all available plugins.
442 * Included core plugins:
444 * - jQuery Migrate (useful for code written for previous UI version)
446 * Add-ons may include extra jQuery plugins in jquery/ directory,
447 * plugins.php file defines the mapping between plugin names and
448 * necessary page includes.
452 * // file: mod/xxx/view.php
453 * $PAGE->requires->jquery();
454 * $PAGE->requires->jquery_plugin('ui');
455 * $PAGE->requires->jquery_plugin('ui-css');
459 * // file: theme/yyy/lib.php
460 * function theme_yyy_page_init(moodle_page $page) {
461 * $page->requires->jquery();
462 * $page->requires->jquery_plugin('ui');
463 * $page->requires->jquery_plugin('ui-css');
468 * // file: blocks/zzz/block_zzz.php
469 * public function get_required_javascript() {
470 * parent::get_required_javascript();
471 * $this->page->requires->jquery();
472 * $page->requires->jquery_plugin('ui');
473 * $page->requires->jquery_plugin('ui-css');
477 * {@see http://docs.moodle.org/dev/jQuery}
479 * @param string $plugin name of the jQuery plugin as defined in jquery/plugins.php
480 * @param string $component name of the component
481 * @return bool success
483 public function jquery_plugin($plugin, $component = 'core') {
486 if ($this->headdone
) {
487 debugging('Can not add jQuery plugins after starting page output!');
491 if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css', 'migrate'))) {
492 debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER
);
494 } else if ($component !== 'core' and strpos($component, '_') === false) {
495 // Let's normalise the legacy activity names, Frankenstyle rulez!
496 $component = 'mod_' . $component;
499 if (empty($this->jqueryplugins
) and ($component !== 'core' or $plugin !== 'jquery')) {
500 // Make sure the jQuery itself is always loaded first,
501 // the order of all other plugins depends on order of $PAGE_>requires->.
502 $this->jquery_plugin('jquery', 'core');
505 if (isset($this->jqueryplugins
[$plugin])) {
506 // No problem, we already have something, first Moodle plugin to register the jQuery plugin wins.
510 $componentdir = core_component
::get_component_directory($component);
511 if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
512 debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER
);
517 require("$componentdir/jquery/plugins.php");
519 if (!isset($plugins[$plugin])) {
520 debugging("jQuery plugin '$plugin' can not be found in component '$component'.", DEBUG_DEVELOPER
);
524 $this->jqueryplugins
[$plugin] = new stdClass();
525 $this->jqueryplugins
[$plugin]->plugin
= $plugin;
526 $this->jqueryplugins
[$plugin]->component
= $component;
527 $this->jqueryplugins
[$plugin]->urls
= array();
529 foreach ($plugins[$plugin]['files'] as $file) {
530 if ($CFG->debugdeveloper
) {
531 if (!file_exists("$componentdir/jquery/$file")) {
532 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
535 $file = str_replace('.min.css', '.css', $file);
536 $file = str_replace('.min.js', '.js', $file);
538 if (!file_exists("$componentdir/jquery/$file")) {
539 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
542 if (!empty($CFG->slasharguments
)) {
543 $url = new moodle_url("$CFG->httpswwwroot/theme/jquery.php");
544 $url->set_slashargument("/$component/$file");
547 // This is not really good, we need slasharguments for relative links, this means no caching...
548 $path = realpath("$componentdir/jquery/$file");
549 if (strpos($path, $CFG->dirroot
) === 0) {
550 $url = $CFG->httpswwwroot
.preg_replace('/^'.preg_quote($CFG->dirroot
, '/').'/', '', $path);
551 // Replace all occurences of backslashes characters in url to forward slashes.
552 $url = str_replace('\\', '/', $url);
553 $url = new moodle_url($url);
555 // Bad luck, fix your server!
556 debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
560 $this->jqueryplugins
[$plugin]->urls
[] = $url;
567 * Request replacement of one jQuery plugin by another.
569 * This is useful when themes want to replace the jQuery UI theme,
570 * the problem is that theme can not prevent others from including the core ui-css plugin.
573 * 1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
574 * 2/ write theme/yourtheme/jquery/plugins.php
575 * 3/ init jQuery from theme
578 * // file theme/yourtheme/lib.php
579 * function theme_yourtheme_page_init($page) {
580 * $page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
581 * $page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
585 * This code prevents loading of standard 'ui-css' which my be requested by other plugins,
586 * the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
588 * {@see http://docs.moodle.org/dev/jQuery}
590 * @param string $oldplugin original plugin
591 * @param string $newplugin the replacement
593 public function jquery_override_plugin($oldplugin, $newplugin) {
594 if ($this->headdone
) {
595 debugging('Can not override jQuery plugins after starting page output!');
598 $this->jquerypluginoverrides
[$oldplugin] = $newplugin;
602 * Return jQuery related markup for page start.
605 protected function get_jquery_headcode() {
606 if (empty($this->jqueryplugins
['jquery'])) {
607 // If nobody requested jQuery then do not bother to load anything.
608 // This may be useful for themes that want to override 'ui-css' only if requested by something else.
615 foreach ($this->jqueryplugins
as $name => $unused) {
616 if (isset($included[$name])) {
619 if (array_key_exists($name, $this->jquerypluginoverrides
)) {
620 // The following loop tries to resolve the replacements,
621 // use max 100 iterations to prevent infinite loop resulting
625 for ($i=0; $i<100; $i++
) {
626 $name = $this->jquerypluginoverrides
[$name];
627 if (!array_key_exists($name, $this->jquerypluginoverrides
)) {
633 // We can not do much with cyclic references here, let's use the old plugin.
635 debugging("Cyclic overrides detected for jQuery plugin '$name'");
637 } else if (empty($name)) {
638 // Developer requested removal of the plugin.
641 } else if (!isset($this->jqueryplugins
[$name])) {
642 debugging("Unknown jQuery override plugin '$name' detected");
645 } else if (isset($included[$name])) {
646 // The plugin was already included, easy.
651 $plugin = $this->jqueryplugins
[$name];
652 $urls = array_merge($urls, $plugin->urls
);
653 $included[$name] = true;
657 $attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
658 foreach ($urls as $url) {
659 if (preg_match('/\.js$/', $url)) {
660 $output .= html_writer
::script('', $url);
661 } else if (preg_match('/\.css$/', $url)) {
662 $attributes['href'] = $url;
663 $output .= html_writer
::empty_tag('link', $attributes) . "\n";
671 * Returns the actual url through which a script is served.
673 * @param moodle_url|string $url full moodle url, or shortened path to script
676 protected function js_fix_url($url) {
679 if ($url instanceof moodle_url
) {
681 } else if (strpos($url, '/') === 0) {
682 // Fix the admin links if needed.
683 if ($CFG->admin
!== 'admin') {
684 if (strpos($url, "/admin/") === 0) {
685 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
689 // Check file existence only when in debug mode.
690 if (!file_exists($CFG->dirroot
. strtok($url, '?'))) {
691 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
694 if (substr($url, -3) === '.js') {
695 $jsrev = $this->get_jsrev();
696 if (empty($CFG->slasharguments
)) {
697 return new moodle_url($CFG->httpswwwroot
.'/lib/javascript.php', array('rev'=>$jsrev, 'jsfile'=>$url));
699 $returnurl = new moodle_url($CFG->httpswwwroot
.'/lib/javascript.php');
700 $returnurl->set_slashargument('/'.$jsrev.$url);
704 return new moodle_url($CFG->httpswwwroot
.$url);
707 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
712 * Find out if JS module present and return details.
714 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
715 * @return array description of module or null if not found
717 protected function find_module($component) {
722 if (strpos($component, 'core_') === 0) {
723 // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
724 // so that we do nto have to repeat the definition of these modules over and over again.
726 case 'core_filepicker':
727 $module = array('name' => 'core_filepicker',
728 'fullpath' => '/repository/filepicker.js',
729 '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'),
730 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
731 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
732 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
733 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
734 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
735 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
736 array('referencesexist', 'repository'), array('select', 'repository')
740 $module = array('name' => 'core_comment',
741 'fullpath' => '/comment/comment.js',
742 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
743 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
747 $module = array('name' => 'core_role',
748 'fullpath' => '/admin/roles/module.js',
749 'requires' => array('node', 'cookie'));
751 case 'core_completion':
752 $module = array('name' => 'core_completion',
753 'fullpath' => '/course/completion.js');
756 $module = array('name' => 'core_message',
757 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
758 'fullpath' => '/message/module.js');
761 $module = array('name' => 'core_group',
762 'fullpath' => '/group/module.js',
763 'requires' => array('node', 'overlay', 'event-mouseenter'));
765 case 'core_question_engine':
766 $module = array('name' => 'core_question_engine',
767 'fullpath' => '/question/qengine.js',
768 'requires' => array('node', 'event'));
771 $module = array('name' => 'core_rating',
772 'fullpath' => '/rating/module.js',
773 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
775 case 'core_dndupload':
776 $module = array('name' => 'core_dndupload',
777 'fullpath' => '/lib/form/dndupload.js',
778 'requires' => array('node', 'event', 'json', 'core_filepicker'),
779 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
780 array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesforfile', 'moodle'),
781 array('maxareabytesreached', 'moodle'), array('serverconnection', 'error'),
787 if ($dir = core_component
::get_component_directory($component)) {
788 if (file_exists("$dir/module.js")) {
789 if (strpos($dir, $CFG->dirroot
.'/') === 0) {
790 $dir = substr($dir, strlen($CFG->dirroot
));
791 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
801 * Append YUI3 module to default YUI3 JS loader.
802 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
804 * @param string|array $module name of module (details are autodetected), or full module specification as array
807 public function js_module($module) {
810 if (empty($module)) {
811 throw new coding_exception('Missing YUI3 module name or full description.');
814 if (is_string($module)) {
815 $module = $this->find_module($module);
818 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
819 throw new coding_exception('Missing YUI3 module details.');
822 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
823 // Add all needed strings.
824 if (!empty($module['strings'])) {
825 foreach ($module['strings'] as $string) {
826 $identifier = $string[0];
827 $component = isset($string[1]) ?
$string[1] : 'moodle';
828 $a = isset($string[2]) ?
$string[2] : null;
829 $this->string_for_js($identifier, $component, $a);
832 unset($module['strings']);
834 // Process module requirements and attempt to load each. This allows
835 // moodle modules to require each other.
836 if (!empty($module['requires'])){
837 foreach ($module['requires'] as $requirement) {
838 $rmodule = $this->find_module($requirement);
839 if (is_array($rmodule)) {
840 $this->js_module($rmodule);
845 if ($this->headdone
) {
846 $this->extramodules
[$module['name']] = $module;
848 $this->YUI_config
->add_module_config($module['name'], $module);
853 * Returns true if the module has already been loaded.
855 * @param string|array $module
856 * @return bool True if the module has already been loaded
858 protected function js_module_loaded($module) {
859 if (is_string($module)) {
860 $modulename = $module;
862 $modulename = $module['name'];
864 return array_key_exists($modulename, $this->YUI_config
->modules
) ||
865 array_key_exists($modulename, $this->extramodules
);
869 * Ensure that the specified CSS file is linked to from this page.
871 * Because stylesheet links must go in the <head> part of the HTML, you must call
872 * this function before {@link get_head_code()} is called. That normally means before
873 * the call to print_header. If you call it when it is too late, an exception
876 * Even if a particular style sheet is requested more than once, it will only
879 * Please note use of this feature is strongly discouraged,
880 * it is suitable only for places where CSS is submitted directly by teachers.
881 * (Students must not be allowed to submit any external CSS because it may
882 * contain embedded javascript!). Example of correct use is mod/data.
884 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
886 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
888 public function css($stylesheet) {
891 if ($this->headdone
) {
892 throw new coding_exception('Cannot require a CSS file after <head> has been printed.', $stylesheet);
895 if ($stylesheet instanceof moodle_url
) {
897 } else if (strpos($stylesheet, '/') === 0) {
898 $stylesheet = new moodle_url($CFG->httpswwwroot
.$stylesheet);
900 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
903 $this->cssurls
[$stylesheet->out()] = $stylesheet;
907 * Add theme stylesheet to page - do not use from plugin code,
908 * this should be called only from the core renderer!
910 * @param moodle_url $stylesheet
913 public function css_theme(moodle_url
$stylesheet) {
914 $this->cssthemeurls
[] = $stylesheet;
918 * Ensure that a skip link to a given target is printed at the top of the <body>.
920 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
921 * will be thrown). That normally means you must call this before the call to print_header.
923 * If you ask for a particular skip link to be printed, it is then your responsibility
924 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
925 * page, so that the skip link goes somewhere.
927 * Even if a particular skip link is requested more than once, only one copy of it will be output.
929 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
930 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
932 public function skip_link_to($target, $linktext) {
933 if ($this->topofbodydone
) {
934 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
937 $this->skiplinks
[$target] = $linktext;
941 * !!!DEPRECATED!!! please use js_init_call() if possible
942 * Ensure that the specified JavaScript function is called from an inline script
943 * somewhere on this page.
945 * By default the call will be put in a script tag at the
946 * end of the page after initialising Y instance, since this gives best page-load
947 * performance and allows you to use YUI3 library.
949 * If you request that a particular function is called several times, then
950 * that is what will happen (unlike linking to a CSS or JS file, where only
951 * one link will be output).
953 * The main benefit of the method is the automatic encoding of all function parameters.
957 * @param string $function the name of the JavaScritp function to call. Can
958 * be a compound name like 'Y.Event.purgeElement'. Can also be
959 * used to create and object by using a 'function name' like 'new user_selector'.
960 * @param array $arguments and array of arguments to be passed to the function.
961 * When generating the function call, this will be escaped using json_encode,
962 * so passing objects and arrays should work.
963 * @param bool $ondomready If tru the function is only called when the dom is
964 * ready for manipulation.
965 * @param int $delay The delay before the function is called.
967 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
968 $where = $ondomready ?
'ondomready' : 'normal';
969 $this->jscalls
[$where][] = array($function, $arguments, $delay);
973 * This function appends a block of code to the AMD specific javascript block executed
974 * in the page footer, just after loading the requirejs library.
976 * The code passed here can rely on AMD module loading, e.g. require('jquery', function($) {...});
978 * @param string $code The JS code to append.
980 public function js_amd_inline($code) {
981 $this->amdjscode
[] = $code;
985 * This function creates a minimal JS script that requires and calls a single function from an AMD module with arguments.
986 * If it is called multiple times, it will be executed multiple times.
988 * @param string $fullmodule The format for module names is <component name>/<module name>.
989 * @param string $func The function from the module to call
990 * @param array $params The params to pass to the function. They will be json encoded, so no nasty classes/types please.
992 public function js_call_amd($fullmodule, $func, $params = array()) {
995 list($component, $module) = explode('/', $fullmodule, 2);
997 $component = clean_param($component, PARAM_COMPONENT
);
998 $module = clean_param($module, PARAM_ALPHANUMEXT
);
999 $func = clean_param($func, PARAM_ALPHANUMEXT
);
1001 $jsonparams = array();
1002 foreach ($params as $param) {
1003 $jsonparams[] = json_encode($param);
1005 $strparams = implode(', ', $jsonparams);
1006 if ($CFG->debugdeveloper
) {
1007 $toomanyparamslimit = 1024;
1008 if (strlen($strparams) > $toomanyparamslimit) {
1009 debugging('Too many params passed to js_call_amd("' . $fullmodule . '", "' . $func . '")', DEBUG_DEVELOPER
);
1013 $js = 'require(["' . $component . '/' . $module . '"], function(amd) { amd.' . $func . '(' . $strparams . '); });';
1015 $this->js_amd_inline($js);
1019 * Creates a JavaScript function call that requires one or more modules to be loaded.
1021 * This function can be used to include all of the standard YUI module types within JavaScript:
1022 * - YUI3 modules [node, event, io]
1023 * - YUI2 modules [yui2-*]
1024 * - Moodle modules [moodle-*]
1025 * - Gallery modules [gallery-*]
1027 * Before writing new code that makes extensive use of YUI, you should consider it's replacement AMD/JQuery.
1028 * @see js_call_amd()
1030 * @param array|string $modules One or more modules
1031 * @param string $function The function to call once modules have been loaded
1032 * @param array $arguments An array of arguments to pass to the function
1033 * @param string $galleryversion Deprecated: The gallery version to use
1034 * @param bool $ondomready
1036 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1037 if (!is_array($modules)) {
1038 $modules = array($modules);
1041 if ($galleryversion != null) {
1042 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.');
1045 $jscode = 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer
::function_call($function, $arguments).'});';
1047 $jscode = "Y.on('domready', function() { $jscode });";
1049 $this->jsinitcode
[] = $jscode;
1053 * Ensure that the specified JavaScript function is called from an inline script
1056 * @param string $function the name of the JavaScritp function to with init code,
1057 * usually something like 'M.mod_mymodule.init'
1058 * @param array $extraarguments and array of arguments to be passed to the function.
1059 * The first argument is always the YUI3 Y instance with all required dependencies
1061 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1062 * @param array $module JS module specification array
1064 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1065 $jscode = js_writer
::function_call_with_Y($function, $extraarguments);
1067 // Detect module automatically.
1068 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
1069 $module = $this->find_module($matches[1]);
1073 $this->js_init_code($jscode, $ondomready, $module);
1077 * Add short static javascript code fragment to page footer.
1078 * This is intended primarily for loading of js modules and initialising page layout.
1079 * Ideally the JS code fragment should be stored in plugin renderer so that themes
1082 * @param string $jscode
1083 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1084 * @param array $module JS module specification array
1086 public function js_init_code($jscode, $ondomready = false, array $module = null) {
1087 $jscode = trim($jscode, " ;\n"). ';';
1089 $uniqid = html_writer
::random_id();
1090 $startjs = " M.util.js_pending('" . $uniqid . "');";
1091 $endjs = " M.util.js_complete('" . $uniqid . "');";
1094 $this->js_module($module);
1095 $modulename = $module['name'];
1096 $jscode = "$startjs Y.use('$modulename', function(Y) { $jscode $endjs });";
1100 $jscode = "$startjs Y.on('domready', function() { $jscode $endjs });";
1103 $this->jsinitcode
[] = $jscode;
1107 * Make a language string available to JavaScript.
1109 * All the strings will be available in a M.str object in the global namespace.
1110 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
1111 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
1112 * equivalent in the current language.
1114 * The arguments to this function are just like the arguments to get_string
1115 * except that $component is not optional, and there are some aspects to consider
1116 * when the string contains {$a} placeholder.
1118 * If the string does not contain any {$a} placeholder, you can simply use
1119 * M.str.component.identifier to obtain it. If you prefer, you can call
1120 * M.util.get_string(identifier, component) to get the same result.
1122 * If you need to use {$a} placeholders, there are two options. Either the
1123 * placeholder should be substituted in PHP on server side or it should
1124 * be substituted in Javascript at client side.
1126 * To substitute the placeholder at server side, just provide the required
1127 * value for the placeholder when you require the string. Because each string
1128 * is only stored once in the JavaScript (based on $identifier and $module)
1129 * you cannot get the same string with two different values of $a. If you try,
1130 * an exception will be thrown. Once the placeholder is substituted, you can
1131 * use M.str or M.util.get_string() as shown above:
1133 * // Require the string in PHP and replace the placeholder.
1134 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
1135 * // Use the result of the substitution in Javascript.
1136 * alert(M.str.moodle.fullnamedisplay);
1138 * To substitute the placeholder at client side, use M.util.get_string()
1139 * function. It implements the same logic as {@link get_string()}:
1141 * // Require the string in PHP but keep {$a} as it is.
1142 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
1143 * // Provide the values on the fly in Javascript.
1144 * user = { firstname : 'Harry', lastname : 'Potter' }
1145 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
1147 * If you do need the same string expanded with different $a values in PHP
1148 * on server side, then the solution is to put them in your own data structure
1149 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
1151 * @param string $identifier the desired string.
1152 * @param string $component the language file to look in.
1153 * @param mixed $a any extra data to add into the string (optional).
1155 public function string_for_js($identifier, $component, $a = null) {
1157 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
1159 if (isset($this->stringsforjs_as
[$component][$identifier]) and $this->stringsforjs_as
[$component][$identifier] !== $a) {
1160 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
1161 "from lang file '$component' with different \$a parameter?");
1163 if (!isset($this->stringsforjs
[$component][$identifier])) {
1164 $this->stringsforjs
[$component][$identifier] = new lang_string($identifier, $component, $a);
1165 $this->stringsforjs_as
[$component][$identifier] = $a;
1170 * Make an array of language strings available for JS.
1172 * This function calls the above function {@link string_for_js()} for each requested
1173 * string in the $identifiers array that is passed to the argument for a single module
1174 * passed in $module.
1177 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
1179 * // The above is identical to calling:
1181 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
1182 * $PAGE->requires->string_for_js('two', 'mymod');
1183 * $PAGE->requires->string_for_js('three', 'mymod', 3);
1186 * @param array $identifiers An array of desired strings
1187 * @param string $component The module to load for
1188 * @param mixed $a This can either be a single variable that gets passed as extra
1189 * information for every string or it can be an array of mixed data where the
1190 * key for the data matches that of the identifier it is meant for.
1193 public function strings_for_js($identifiers, $component, $a = null) {
1194 foreach ($identifiers as $key => $identifier) {
1195 if (is_array($a) && array_key_exists($key, $a)) {
1200 $this->string_for_js($identifier, $component, $extra);
1205 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
1207 * Make some data from PHP available to JavaScript code.
1209 * For example, if you call
1211 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
1213 * then in JavsScript mydata.name will be 'Moodle'.
1216 * @param string $variable the the name of the JavaScript variable to assign the data to.
1217 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1218 * should be considered an experimental feature.
1219 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1220 * so passing objects and arrays should work.
1221 * @param bool $inhead initialise in head
1224 public function data_for_js($variable, $data, $inhead=false) {
1225 $where = $inhead ?
'head' : 'footer';
1226 $this->jsinitvariables
[$where][] = array($variable, $data);
1230 * Creates a YUI event handler.
1232 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1233 * @param string $event A valid DOM event (click, mousedown, change etc.)
1234 * @param string $function The name of the function to call
1235 * @param array $arguments An optional array of argument parameters to pass to the function
1237 public function event_handler($selector, $event, $function, array $arguments = null) {
1238 $this->eventhandlers
[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
1242 * Returns code needed for registering of event handlers.
1243 * @return string JS code
1245 protected function get_event_handler_code() {
1247 foreach ($this->eventhandlers
as $h) {
1248 $output .= js_writer
::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
1254 * Get the inline JavaScript code that need to appear in a particular place.
1255 * @param bool $ondomready
1258 protected function get_javascript_code($ondomready) {
1259 $where = $ondomready ?
'ondomready' : 'normal';
1261 if ($this->jscalls
[$where]) {
1262 foreach ($this->jscalls
[$where] as $data) {
1263 $output .= js_writer
::function_call($data[0], $data[1], $data[2]);
1265 if (!empty($ondomready)) {
1266 $output = " Y.on('domready', function() {\n$output\n});";
1273 * Returns js code to be executed when Y is available.
1276 protected function get_javascript_init_code() {
1277 if (count($this->jsinitcode
)) {
1278 return implode("\n", $this->jsinitcode
) . "\n";
1284 * Returns js code to load amd module loader, then insert inline script tags
1285 * that contain require() calls using RequireJS.
1288 protected function get_amd_footercode() {
1291 $jsrev = $this->get_jsrev();
1293 $jsloader = new moodle_url($CFG->httpswwwroot
. '/lib/javascript.php');
1294 $jsloader->set_slashargument('/' . $jsrev . '/');
1295 $requirejsloader = new moodle_url($CFG->httpswwwroot
. '/lib/requirejs.php');
1296 $requirejsloader->set_slashargument('/' . $jsrev . '/');
1298 $requirejsconfig = file_get_contents($CFG->dirroot
. '/lib/requirejs/moodle-config.js');
1300 // No extension required unless slash args is disabled.
1301 $jsextension = '.js';
1302 if (!empty($CFG->slasharguments
)) {
1306 $requirejsconfig = str_replace('[BASEURL]', $requirejsloader, $requirejsconfig);
1307 $requirejsconfig = str_replace('[JSURL]', $jsloader, $requirejsconfig);
1308 $requirejsconfig = str_replace('[JSEXT]', $jsextension, $requirejsconfig);
1310 $output .= html_writer
::script($requirejsconfig);
1311 if ($CFG->debugdeveloper
) {
1312 $output .= html_writer
::script('', $this->js_fix_url('/lib/requirejs/require.js'));
1314 $output .= html_writer
::script('', $this->js_fix_url('/lib/requirejs/require.min.js'));
1317 // First include must be to a module with no dependencies, this prevents multiple requests.
1318 $prefix = "require(['core/first'], function() {\n";
1320 $output .= html_writer
::script($prefix . implode(";\n", $this->amdjscode
) . $suffix);
1325 * Returns basic YUI3 JS loading code.
1326 * YUI3 is using autoloading of both CSS and JS code.
1328 * Major benefit of this compared to standard js/csss loader is much improved
1329 * caching, better browser cache utilisation, much fewer http requests.
1331 * @param moodle_page $page
1334 protected function get_yui3lib_headcode($page) {
1339 $jsrev = $this->get_jsrev();
1341 $yuiformat = '-min';
1342 if ($this->yui3loader
->filter
=== 'RAW') {
1347 if ($this->YUI_config
->groups
['moodle']['filter'] === 'DEBUG') {
1351 $rollupversion = $CFG->yui3version
;
1352 if (!empty($CFG->yuipatchlevel
)) {
1353 $rollupversion .= '_' . $CFG->yuipatchlevel
;
1356 $baserollups = array(
1357 'rollup/' . $rollupversion . "/yui-moodlesimple{$yuiformat}.js",
1358 'rollup/' . $jsrev . "/mcore{$format}.js",
1361 if ($this->yui3loader
->combine
) {
1362 if (!empty($page->theme
->yuicssmodules
)) {
1364 foreach ($page->theme
->yuicssmodules
as $module) {
1365 $modules[] = "$CFG->yui3version/$module/$module-min.css";
1367 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->comboBase
.implode('&', $modules).'" />';
1369 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->local_comboBase
.'rollup/'.$CFG->yui3version
.'/yui-moodlesimple' . $yuiformat . '.css" />';
1370 $code .= '<script type="text/javascript" src="'.$this->yui3loader
->local_comboBase
1371 . implode('&', $baserollups) . '"></script>';
1374 if (!empty($page->theme
->yuicssmodules
)) {
1375 foreach ($page->theme
->yuicssmodules
as $module) {
1376 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->base
.$module.'/'.$module.'-min.css" />';
1379 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->local_comboBase
.'rollup/'.$CFG->yui3version
.'/yui-moodlesimple' . $yuiformat . '.css" />';
1380 foreach ($baserollups as $rollup) {
1381 $code .= '<script type="text/javascript" src="'.$this->yui3loader
->local_comboBase
.$rollup.'"></script>';
1385 if ($this->yui3loader
->filter
=== 'RAW') {
1386 $code = str_replace('-min.css', '.css', $code);
1387 } else if ($this->yui3loader
->filter
=== 'DEBUG') {
1388 $code = str_replace('-min.css', '.css', $code);
1394 * Returns html tags needed for inclusion of theme CSS.
1398 protected function get_css_code() {
1399 // First of all the theme CSS, then any custom CSS
1400 // Please note custom CSS is strongly discouraged,
1401 // because it can not be overridden by themes!
1402 // It is suitable only for things like mod/data which accepts CSS from teachers.
1403 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1405 // This line of code may look funny but it is currently required in order
1406 // to avoid MASSIVE display issues in Internet Explorer.
1407 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1408 // ignored whenever another resource is added until such time as a redraw
1409 // is forced, usually by moving the mouse over the affected element.
1410 $code = html_writer
::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1412 $urls = $this->cssthemeurls +
$this->cssurls
;
1413 foreach ($urls as $url) {
1414 $attributes['href'] = $url;
1415 $code .= html_writer
::empty_tag('link', $attributes) . "\n";
1416 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1417 unset($attributes['id']);
1424 * Adds extra modules specified after printing of page header.
1428 protected function get_extra_modules_code() {
1429 if (empty($this->extramodules
)) {
1432 return html_writer
::script(js_writer
::function_call('M.yui.add_module', array($this->extramodules
)));
1436 * Generate any HTML that needs to go inside the <head> tag.
1438 * Normally, this method is called automatically by the code that prints the
1439 * <head> tag. You should not normally need to call it in your own code.
1441 * @param moodle_page $page
1442 * @param core_renderer $renderer
1443 * @return string the HTML code to to inside the <head> tag.
1445 public function get_head_code(moodle_page
$page, core_renderer
$renderer) {
1448 // Note: the $page and $output are not stored here because it would
1449 // create circular references in memory which prevents garbage collection.
1450 $this->init_requirements_data($page, $renderer);
1454 // Set up the M namespace.
1455 $js = "var M = {}; M.yui = {};\n";
1457 // Capture the time now ASAP during page load. This minimises the lag when
1458 // we try to relate times on the server to times in the browser.
1459 // An example of where this is used is the quiz countdown timer.
1460 $js .= "M.pageloadstarttime = new Date();\n";
1462 // Add a subset of Moodle configuration to the M namespace.
1463 $js .= js_writer
::set_variable('M.cfg', $this->M_cfg
, false);
1465 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1466 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1467 // this needs to be done before including any other script.
1468 $js .= $this->YUI_config
->get_config_functions();
1469 $js .= js_writer
::set_variable('YUI_config', $this->YUI_config
, false) . "\n";
1470 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1471 $js = $this->YUI_config
->update_header_js($js);
1473 $output .= html_writer
::script($js);
1475 // YUI3 JS and CSS need to be loaded in the header but after the YUI_config has been created.
1476 // They should be cached well by the browser.
1477 $output .= $this->get_yui3lib_headcode($page);
1479 // Add hacked jQuery support, it is not intended for standard Moodle distribution!
1480 $output .= $this->get_jquery_headcode();
1482 // Now theme CSS + custom CSS in this specific order.
1483 $output .= $this->get_css_code();
1485 // Link our main JS file, all core stuff should be there.
1486 $output .= html_writer
::script('', $this->js_fix_url('/lib/javascript-static.js'));
1489 if ($this->jsinitvariables
['head']) {
1491 foreach ($this->jsinitvariables
['head'] as $data) {
1492 list($var, $value) = $data;
1493 $js .= js_writer
::set_variable($var, $value, true);
1495 $output .= html_writer
::script($js);
1498 // All the other linked things from HEAD - there should be as few as possible.
1499 if ($this->jsincludes
['head']) {
1500 foreach ($this->jsincludes
['head'] as $url) {
1501 $output .= html_writer
::script('', $url);
1505 // Mark head sending done, it is not possible to anything there.
1506 $this->headdone
= true;
1512 * Generate any HTML that needs to go at the start of the <body> tag.
1514 * Normally, this method is called automatically by the code that prints the
1515 * <head> tag. You should not normally need to call it in your own code.
1517 * @return string the HTML code to go at the start of the <body> tag.
1519 public function get_top_of_body_code() {
1520 // First the skip links.
1522 $attributes = array('class'=>'skip');
1523 foreach ($this->skiplinks
as $url => $text) {
1524 $attributes['href'] = '#' . $url;
1525 $links .= html_writer
::tag('a', $text, $attributes);
1527 $output = html_writer
::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1529 // Then the clever trick for hiding of things not needed when JS works.
1530 $output .= html_writer
::script("document.body.className += ' jsenabled';") . "\n";
1531 $this->topofbodydone
= true;
1536 * Generate any HTML that needs to go at the end of the page.
1538 * Normally, this method is called automatically by the code that prints the
1539 * page footer. You should not normally need to call it in your own code.
1541 * @return string the HTML code to to at the end of the page.
1543 public function get_end_code() {
1547 // Set the log level for the JS logging.
1548 $logconfig = new stdClass();
1549 $logconfig->level
= 'warn';
1550 if ($CFG->debugdeveloper
) {
1551 $logconfig->level
= 'trace';
1553 $this->js_call_amd('core/log', 'setConfig', array($logconfig));
1555 // Call amd init functions.
1556 $output .= $this->get_amd_footercode();
1558 // Add other requested modules.
1559 $output .= $this->get_extra_modules_code();
1561 $this->js_init_code('M.util.js_complete("init");', true);
1563 // All the other linked scripts - there should be as few as possible.
1564 if ($this->jsincludes
['footer']) {
1565 foreach ($this->jsincludes
['footer'] as $url) {
1566 $output .= html_writer
::script('', $url);
1570 // Add all needed strings.
1571 // First add core strings required for some dialogues.
1572 $this->strings_for_js(array(
1580 if (!empty($this->stringsforjs
)) {
1582 foreach ($this->stringsforjs
as $component=>$v) {
1583 foreach($v as $indentifier => $langstring) {
1584 $strings[$component][$indentifier] = $langstring->out();
1587 $output .= html_writer
::script(js_writer
::set_variable('M.str', $strings));
1591 if ($this->jsinitvariables
['footer']) {
1593 foreach ($this->jsinitvariables
['footer'] as $data) {
1594 list($var, $value) = $data;
1595 $js .= js_writer
::set_variable($var, $value, true);
1597 $output .= html_writer
::script($js);
1600 $inyuijs = $this->get_javascript_code(false);
1601 $ondomreadyjs = $this->get_javascript_code(true);
1602 $jsinit = $this->get_javascript_init_code();
1603 $handlersjs = $this->get_event_handler_code();
1605 // There is no global Y, make sure it is available in your scope.
1606 $js = "YUI().use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1608 $output .= html_writer
::script($js);
1614 * Have we already output the code in the <head> tag?
1618 public function is_head_done() {
1619 return $this->headdone
;
1623 * Have we already output the code at the start of the <body> tag?
1627 public function is_top_of_body_done() {
1628 return $this->topofbodydone
;
1632 * Should we generate a bit of content HTML that is only required once on
1633 * this page (e.g. the contents of the modchooser), now? Basically, we call
1634 * {@link has_one_time_item_been_created()}, and if the thing has not already
1635 * been output, we return true to tell the caller to generate it, and also
1636 * call {@link set_one_time_item_created()} to record the fact that it is
1637 * about to be generated.
1639 * That is, a typical usage pattern (in a renderer method) is:
1641 * if (!$this->page->requires->should_create_one_time_item_now($thing)) {
1644 * // Else generate it.
1647 * @param string $thing identifier for the bit of content. Should be of the form
1648 * frankenstyle_things, e.g. core_course_modchooser.
1649 * @return bool if true, the caller should generate that bit of output now, otherwise don't.
1651 public function should_create_one_time_item_now($thing) {
1652 if ($this->has_one_time_item_been_created($thing)) {
1656 $this->set_one_time_item_created($thing);
1661 * Has a particular bit of HTML that is only required once on this page
1662 * (e.g. the contents of the modchooser) already been generated?
1664 * Normally, you can use the {@link should_create_one_time_item_now()} helper
1665 * method rather than calling this method directly.
1667 * @param string $thing identifier for the bit of content. Should be of the form
1668 * frankenstyle_things, e.g. core_course_modchooser.
1669 * @return bool whether that bit of output has been created.
1671 public function has_one_time_item_been_created($thing) {
1672 return isset($this->onetimeitemsoutput
[$thing]);
1676 * Indicate that a particular bit of HTML that is only required once on this
1677 * page (e.g. the contents of the modchooser) has been generated (or is about to be)?
1679 * Normally, you can use the {@link should_create_one_time_item_now()} helper
1680 * method rather than calling this method directly.
1682 * @param string $thing identifier for the bit of content. Should be of the form
1683 * frankenstyle_things, e.g. core_course_modchooser.
1685 public function set_one_time_item_created($thing) {
1686 if ($this->has_one_time_item_been_created($thing)) {
1687 throw new coding_exception($thing . ' is only supposed to be ouput ' .
1688 'once per page, but it seems to be being output again.');
1690 return $this->onetimeitemsoutput
[$thing] = true;
1695 * This class represents the YUI configuration.
1697 * @copyright 2013 Andrew Nicols
1698 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1705 * These settings must be public so that when the object is converted to json they are exposed.
1706 * Note: Some of these are camelCase because YUI uses camelCase variable names.
1708 * The settings are described and documented in the YUI API at:
1709 * - http://yuilibrary.com/yui/docs/api/classes/config.html
1710 * - http://yuilibrary.com/yui/docs/api/classes/Loader.html
1712 public $debug = false;
1716 public $filter = null;
1717 public $insertBefore = 'firstthemesheet';
1718 public $groups = array();
1719 public $modules = array();
1722 * @var array List of functions used by the YUI Loader group pattern recognition.
1724 protected $jsconfigfunctions = array();
1727 * Create a new group within the YUI_config system.
1729 * @param String $name The name of the group. This must be unique and
1730 * not previously used.
1731 * @param Array $config The configuration for this group.
1734 public function add_group($name, $config) {
1735 if (isset($this->groups
[$name])) {
1736 throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
1738 $this->groups
[$name] = $config;
1742 * Update an existing group configuration
1744 * Note, any existing configuration for that group will be wiped out.
1745 * This includes module configuration.
1747 * @param String $name The name of the group. This must be unique and
1748 * not previously used.
1749 * @param Array $config The configuration for this group.
1752 public function update_group($name, $config) {
1753 if (!isset($this->groups
[$name])) {
1754 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.');
1756 $this->groups
[$name] = $config;
1760 * Set the value of a configuration function used by the YUI Loader's pattern testing.
1762 * Only the body of the function should be passed, and not the whole function wrapper.
1764 * The JS function your write will be passed a single argument 'name' containing the
1765 * name of the module being loaded.
1767 * @param $function String the body of the JavaScript function. This should be used i
1768 * @return String the name of the function to use in the group pattern configuration.
1770 public function set_config_function($function) {
1771 $configname = 'yui' . (count($this->jsconfigfunctions
) +
1) . 'ConfigFn';
1772 if (isset($this->jsconfigfunctions
[$configname])) {
1773 throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
1775 $this->jsconfigfunctions
[$configname] = $function;
1776 return '@' . $configname . '@';
1780 * Allow setting of the config function described in {@see set_config_function} from a file.
1781 * The contents of this file are then passed to set_config_function.
1783 * When jsrev is positive, the function is minified and stored in a MUC cache for subsequent uses.
1785 * @param $file The path to the JavaScript function used for YUI configuration.
1786 * @return String the name of the function to use in the group pattern configuration.
1788 public function set_config_source($file) {
1790 $cache = cache
::make('core', 'yuimodules');
1792 // Attempt to get the metadata from the cache.
1793 $keyname = 'configfn_' . $file;
1794 $fullpath = $CFG->dirroot
. '/' . $file;
1795 if (!isset($CFG->jsrev
) ||
$CFG->jsrev
== -1) {
1796 $cache->delete($keyname);
1797 $configfn = file_get_contents($fullpath);
1799 $configfn = $cache->get($keyname);
1800 if ($configfn === false) {
1801 require_once($CFG->libdir
. '/jslib.php');
1802 $configfn = core_minify
::js_files(array($fullpath));
1803 $cache->set($keyname, $configfn);
1806 return $this->set_config_function($configfn);
1810 * Retrieve the list of JavaScript functions for YUI_config groups.
1812 * @return String The complete set of config functions
1814 public function get_config_functions() {
1815 $configfunctions = '';
1816 foreach ($this->jsconfigfunctions
as $functionname => $function) {
1817 $configfunctions .= "var {$functionname} = function(me) {";
1818 $configfunctions .= $function;
1819 $configfunctions .= "};\n";
1821 return $configfunctions;
1825 * Update the header JavaScript with any required modification for the YUI Loader.
1827 * @param $js String The JavaScript to manipulate.
1828 * @return String the modified JS string.
1830 public function update_header_js($js) {
1831 // Update the names of the the configFn variables.
1832 // The PHP json_encode function cannot handle literal names so we have to wrap
1833 // them in @ and then replace them with literals of the same function name.
1834 foreach ($this->jsconfigfunctions
as $functionname => $function) {
1835 $js = str_replace('"@' . $functionname . '@"', $functionname, $js);
1841 * Add configuration for a specific module.
1843 * @param String $name The name of the module to add configuration for.
1844 * @param Array $config The configuration for the specified module.
1845 * @param String $group The name of the group to add configuration for.
1846 * If not specified, then this module is added to the global
1850 public function add_module_config($name, $config, $group = null) {
1852 if (!isset($this->groups
[$name])) {
1853 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.');
1855 if (!isset($this->groups
[$group]['modules'])) {
1856 $this->groups
[$group]['modules'] = array();
1858 $modules = &$this->groups
[$group]['modules'];
1860 $modules = &$this->modules
;
1862 $modules[$name] = $config;
1866 * Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
1868 * If js caching is disabled, metadata will not be served causing YUI to calculate
1869 * module dependencies as each module is loaded.
1871 * If metadata does not exist it will be created and stored in a MUC entry.
1875 public function add_moodle_metadata() {
1877 if (!isset($this->groups
['moodle'])) {
1878 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.');
1881 if (!isset($this->groups
['moodle']['modules'])) {
1882 $this->groups
['moodle']['modules'] = array();
1885 $cache = cache
::make('core', 'yuimodules');
1886 if (!isset($CFG->jsrev
) ||
$CFG->jsrev
== -1) {
1887 $metadata = array();
1888 $metadata = $this->get_moodle_metadata();
1889 $cache->delete('metadata');
1891 // Attempt to get the metadata from the cache.
1892 if (!$metadata = $cache->get('metadata')) {
1893 $metadata = $this->get_moodle_metadata();
1894 $cache->set('metadata', $metadata);
1898 // Merge with any metadata added specific to this page which was added manually.
1899 $this->groups
['moodle']['modules'] = array_merge($this->groups
['moodle']['modules'],
1904 * Determine the module metadata for all moodle YUI modules.
1906 * This works through all modules capable of serving YUI modules, and attempts to get
1907 * metadata for each of those modules.
1909 * @return Array of module metadata
1911 private function get_moodle_metadata() {
1912 $moodlemodules = array();
1913 // Core isn't a plugin type or subsystem - handle it seperately.
1914 if ($module = $this->get_moodle_path_metadata(core_component
::get_component_directory('core'))) {
1915 $moodlemodules = array_merge($moodlemodules, $module);
1918 // Handle other core subsystems.
1919 $subsystems = core_component
::get_core_subsystems();
1920 foreach ($subsystems as $subsystem => $path) {
1921 if (is_null($path)) {
1924 if ($module = $this->get_moodle_path_metadata($path)) {
1925 $moodlemodules = array_merge($moodlemodules, $module);
1929 // And finally the plugins.
1930 $plugintypes = core_component
::get_plugin_types();
1931 foreach ($plugintypes as $plugintype => $pathroot) {
1932 $pluginlist = core_component
::get_plugin_list($plugintype);
1933 foreach ($pluginlist as $plugin => $path) {
1934 if ($module = $this->get_moodle_path_metadata($path)) {
1935 $moodlemodules = array_merge($moodlemodules, $module);
1940 return $moodlemodules;
1944 * Helper function process and return the YUI metadata for all of the modules under the specified path.
1946 * @param String $path the UNC path to the YUI src directory.
1947 * @return Array the complete array for frankenstyle directory.
1949 private function get_moodle_path_metadata($path) {
1950 // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
1951 $baseyui = $path . '/yui/src';
1953 if (is_dir($baseyui)) {
1954 $items = new DirectoryIterator($baseyui);
1955 foreach ($items as $item) {
1956 if ($item->isDot() or !$item->isDir()) {
1959 $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
1960 if (!is_readable($metafile)) {
1963 $metadata = file_get_contents($metafile);
1964 $modules = array_merge($modules, (array) json_decode($metadata));
1971 * Define YUI modules which we have been required to patch between releases.
1973 * We must do this because we aggressively cache content on the browser, and we must also override use of the
1974 * external CDN which will serve the true authoritative copy of the code without our patches.
1976 * @param String combobase The local combobase
1977 * @param String yuiversion The current YUI version
1978 * @param Int patchlevel The patch level we're working to for YUI
1979 * @param Array patchedmodules An array containing the names of the patched modules
1982 public function define_patched_core_modules($combobase, $yuiversion, $patchlevel, $patchedmodules) {
1983 // The version we use is suffixed with a patchlevel so that we can get additional revisions between YUI releases.
1984 $subversion = $yuiversion . '_' . $patchlevel;
1986 if ($this->comboBase
== $combobase) {
1987 // If we are using the local combobase in the loader, we can add a group and still make use of the combo
1988 // loader. We just need to specify a different root which includes a slightly different YUI version number
1989 // to include our patchlevel.
1990 $patterns = array();
1992 foreach ($patchedmodules as $modulename) {
1993 // We must define the pattern and module here so that the loader uses our group configuration instead of
1994 // the standard module definition. We may lose some metadata provided by upstream but this will be
1995 // loaded when the module is loaded anyway.
1996 $patterns[$modulename] = array(
1997 'group' => 'yui-patched',
1999 $modules[$modulename] = array();
2002 // Actually add the patch group here.
2003 $this->add_group('yui-patched', array(
2005 'root' => $subversion . '/',
2006 'patterns' => $patterns,
2007 'modules' => $modules,
2011 // The CDN is in use - we need to instead use the local combobase for this module and override the modules
2012 // definition. We cannot use the local base - we must use the combobase because we cannot invalidate the
2013 // local base in browser caches.
2014 $fullpathbase = $combobase . $subversion . '/';
2015 foreach ($patchedmodules as $modulename) {
2016 $this->modules
[$modulename] = array(
2017 'fullpath' => $fullpathbase . $modulename . '/' . $modulename . '-min.js'
2025 * Invalidate all server and client side JS caches.
2027 function js_reset_all_caches() {
2031 if (isset($CFG->jsrev
) and $next <= $CFG->jsrev
and $CFG->jsrev
- $next < 60*60) {
2032 // This resolves problems when reset is requested repeatedly within 1s,
2033 // the < 1h condition prevents accidental switching to future dates
2034 // because we might not recover from it.
2035 $next = $CFG->jsrev+
1;
2038 set_config('jsrev', $next);