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 $yuicssmodules
154 protected $yuicssmodules = array();
157 * @var array Some config vars exposed in JS, please no secret stuff there
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() {
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() && !empty($CFG->useexternalyui
)) {
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->wwwroot
. '/lib/yuilib/'. $CFG->yui3version
. '/';
191 $this->yui3loader
->local_comboBase
= $CFG->wwwroot
. '/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?';
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
,
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->wwwroot
. '/lib/yuilib/2in3/' . $CFG->yui2version
. '/build/',
224 'comboBase' => $CFG->wwwroot
. '/theme/yui_combo.php'.$sep,
225 'combine' => $this->yui3loader
->combine
,
227 'root' => '2in3/' . $CFG->yui2version
.'/build/',
231 'configFn' => $configname,
235 $configname = $this->YUI_config
->set_config_source('lib/yui/config/moodle.js');
236 $this->YUI_config
->add_group('moodle', array(
238 'base' => $CFG->wwwroot
. '/theme/yui_combo.php' . $sep . 'm/' . $jsrev . '/',
239 'combine' => $this->yui3loader
->combine
,
240 'comboBase' => $CFG->wwwroot
. '/theme/yui_combo.php'.$sep,
242 'root' => 'm/'.$jsrev.'/', // Add the rev to the root path so that we can control caching.
246 'configFn' => $configname,
251 $this->YUI_config
->add_group('gallery', array(
253 'base' => $CFG->wwwroot
. '/lib/yuilib/gallery/',
254 'combine' => $this->yui3loader
->combine
,
255 'comboBase' => $CFG->wwwroot
. '/theme/yui_combo.php' . $sep,
257 'root' => 'gallery/' . $jsrev . '/',
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;
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".
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) {
311 if (empty($this->M_cfg
)) {
313 $iconsystem = \core\output\icon_system
::instance();
315 // It is possible that the $page->context is null, so we can't use $page->context->id.
317 if (!is_null($page->context
)) {
318 $contextid = $page->context
->id
;
321 $this->M_cfg
= array(
322 'wwwroot' => $CFG->wwwroot
,
323 'sesskey' => sesskey(),
324 'themerev' => theme_get_revision(),
325 'slasharguments' => (int)(!empty($CFG->slasharguments
)),
326 'theme' => $page->theme
->name
,
327 'iconsystemmodule' => $iconsystem->get_amd_name(),
328 'jsrev' => $this->get_jsrev(),
329 'admin' => $CFG->admin
,
330 'svgicons' => $page->theme
->use_svg_icons(),
331 'usertimezone' => usertimezone(),
332 'contextid' => $contextid,
334 if ($CFG->debugdeveloper
) {
335 $this->M_cfg
['developerdebug'] = true;
337 if (defined('BEHAT_SITE_RUNNING')) {
338 $this->M_cfg
['behatsiterunning'] = true;
346 * Initialise with the bits of JavaScript that every Moodle page should have.
348 * @param moodle_page $page
349 * @param core_renderer $renderer
351 protected function init_requirements_data(moodle_page
$page, core_renderer
$renderer) {
354 // Init the js config.
355 $this->get_config_for_javascript($page, $renderer);
357 // Accessibility stuff.
358 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
360 // Add strings used on many pages.
361 $this->string_for_js('confirmation', 'admin');
362 $this->string_for_js('cancel', 'moodle');
363 $this->string_for_js('yes', 'moodle');
365 // Alter links in top frame to break out of frames.
366 if ($page->pagelayout
=== 'frametop') {
367 $this->js_init_call('M.util.init_frametop');
370 // Include block drag/drop if editing is on
371 if ($page->user_is_editing()) {
373 'courseid' => $page->course
->id
,
374 'pagetype' => $page->pagetype
,
375 'pagelayout' => $page->pagelayout
,
376 'subpage' => $page->subpage
,
377 'regions' => $page->blocks
->get_regions(),
378 'contextid' => $page->context
->id
,
380 if (!empty($page->cm
->id
)) {
381 $params['cmid'] = $page->cm
->id
;
383 // Strings for drag and drop.
384 $this->strings_for_js(array('movecontent',
386 'emptydragdropregion'),
388 $page->requires
->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
391 // Include the YUI CSS Modules.
392 $page->requires
->set_yuicssmodules($page->theme
->yuicssmodules
);
396 * Determine the correct JS Revision to use for this load.
398 * @return int the jsrev to use.
400 protected function get_jsrev() {
403 if (empty($CFG->cachejs
)) {
405 } else if (empty($CFG->jsrev
)) {
408 $jsrev = $CFG->jsrev
;
415 * Ensure that the specified JavaScript file is linked to from this page.
417 * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
418 * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
420 * By default the link is put at the end of the page, since this gives best page-load performance.
422 * Even if a particular script is requested more than once, it will only be linked
425 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
426 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
427 * @param bool $inhead initialise in head
429 public function js($url, $inhead = false) {
430 $url = $this->js_fix_url($url);
431 $where = $inhead ?
'head' : 'footer';
432 $this->jsincludes
[$where][$url->out()] = $url;
436 * Request inclusion of jQuery library in the page.
438 * NOTE: this should not be used in official Moodle distribution!
440 * {@see http://docs.moodle.org/dev/jQuery}
442 public function jquery() {
443 $this->jquery_plugin('jquery');
447 * Request inclusion of jQuery plugin.
449 * NOTE: this should not be used in official Moodle distribution!
451 * jQuery plugins are located in plugin/jquery/* subdirectory,
452 * plugin/jquery/plugins.php lists all available plugins.
454 * Included core plugins:
457 * Add-ons may include extra jQuery plugins in jquery/ directory,
458 * plugins.php file defines the mapping between plugin names and
459 * necessary page includes.
463 * // file: mod/xxx/view.php
464 * $PAGE->requires->jquery();
465 * $PAGE->requires->jquery_plugin('ui');
466 * $PAGE->requires->jquery_plugin('ui-css');
470 * // file: theme/yyy/lib.php
471 * function theme_yyy_page_init(moodle_page $page) {
472 * $page->requires->jquery();
473 * $page->requires->jquery_plugin('ui');
474 * $page->requires->jquery_plugin('ui-css');
479 * // file: blocks/zzz/block_zzz.php
480 * public function get_required_javascript() {
481 * parent::get_required_javascript();
482 * $this->page->requires->jquery();
483 * $page->requires->jquery_plugin('ui');
484 * $page->requires->jquery_plugin('ui-css');
488 * {@see http://docs.moodle.org/dev/jQuery}
490 * @param string $plugin name of the jQuery plugin as defined in jquery/plugins.php
491 * @param string $component name of the component
492 * @return bool success
494 public function jquery_plugin($plugin, $component = 'core') {
497 if ($this->headdone
) {
498 debugging('Can not add jQuery plugins after starting page output!');
502 if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css'))) {
503 debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER
);
505 } else if ($component !== 'core' and strpos($component, '_') === false) {
506 // Let's normalise the legacy activity names, Frankenstyle rulez!
507 $component = 'mod_' . $component;
510 if (empty($this->jqueryplugins
) and ($component !== 'core' or $plugin !== 'jquery')) {
511 // Make sure the jQuery itself is always loaded first,
512 // the order of all other plugins depends on order of $PAGE_>requires->.
513 $this->jquery_plugin('jquery', 'core');
516 if (isset($this->jqueryplugins
[$plugin])) {
517 // No problem, we already have something, first Moodle plugin to register the jQuery plugin wins.
521 $componentdir = core_component
::get_component_directory($component);
522 if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
523 debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER
);
528 require("$componentdir/jquery/plugins.php");
530 if (!isset($plugins[$plugin])) {
531 debugging("jQuery plugin '$plugin' can not be found in component '$component'.", DEBUG_DEVELOPER
);
535 $this->jqueryplugins
[$plugin] = new stdClass();
536 $this->jqueryplugins
[$plugin]->plugin
= $plugin;
537 $this->jqueryplugins
[$plugin]->component
= $component;
538 $this->jqueryplugins
[$plugin]->urls
= array();
540 foreach ($plugins[$plugin]['files'] as $file) {
541 if ($CFG->debugdeveloper
) {
542 if (!file_exists("$componentdir/jquery/$file")) {
543 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
546 $file = str_replace('.min.css', '.css', $file);
547 $file = str_replace('.min.js', '.js', $file);
549 if (!file_exists("$componentdir/jquery/$file")) {
550 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
553 if (!empty($CFG->slasharguments
)) {
554 $url = new moodle_url("/theme/jquery.php");
555 $url->set_slashargument("/$component/$file");
558 // This is not really good, we need slasharguments for relative links, this means no caching...
559 $path = realpath("$componentdir/jquery/$file");
560 if (strpos($path, $CFG->dirroot
) === 0) {
561 $url = $CFG->wwwroot
.preg_replace('/^'.preg_quote($CFG->dirroot
, '/').'/', '', $path);
562 // Replace all occurences of backslashes characters in url to forward slashes.
563 $url = str_replace('\\', '/', $url);
564 $url = new moodle_url($url);
566 // Bad luck, fix your server!
567 debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
571 $this->jqueryplugins
[$plugin]->urls
[] = $url;
578 * Request replacement of one jQuery plugin by another.
580 * This is useful when themes want to replace the jQuery UI theme,
581 * the problem is that theme can not prevent others from including the core ui-css plugin.
584 * 1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
585 * 2/ write theme/yourtheme/jquery/plugins.php
586 * 3/ init jQuery from theme
589 * // file theme/yourtheme/lib.php
590 * function theme_yourtheme_page_init($page) {
591 * $page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
592 * $page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
596 * This code prevents loading of standard 'ui-css' which my be requested by other plugins,
597 * the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
599 * {@see http://docs.moodle.org/dev/jQuery}
601 * @param string $oldplugin original plugin
602 * @param string $newplugin the replacement
604 public function jquery_override_plugin($oldplugin, $newplugin) {
605 if ($this->headdone
) {
606 debugging('Can not override jQuery plugins after starting page output!');
609 $this->jquerypluginoverrides
[$oldplugin] = $newplugin;
613 * Return jQuery related markup for page start.
616 protected function get_jquery_headcode() {
617 if (empty($this->jqueryplugins
['jquery'])) {
618 // If nobody requested jQuery then do not bother to load anything.
619 // This may be useful for themes that want to override 'ui-css' only if requested by something else.
626 foreach ($this->jqueryplugins
as $name => $unused) {
627 if (isset($included[$name])) {
630 if (array_key_exists($name, $this->jquerypluginoverrides
)) {
631 // The following loop tries to resolve the replacements,
632 // use max 100 iterations to prevent infinite loop resulting
636 for ($i=0; $i<100; $i++
) {
637 $name = $this->jquerypluginoverrides
[$name];
638 if (!array_key_exists($name, $this->jquerypluginoverrides
)) {
644 // We can not do much with cyclic references here, let's use the old plugin.
646 debugging("Cyclic overrides detected for jQuery plugin '$name'");
648 } else if (empty($name)) {
649 // Developer requested removal of the plugin.
652 } else if (!isset($this->jqueryplugins
[$name])) {
653 debugging("Unknown jQuery override plugin '$name' detected");
656 } else if (isset($included[$name])) {
657 // The plugin was already included, easy.
662 $plugin = $this->jqueryplugins
[$name];
663 $urls = array_merge($urls, $plugin->urls
);
664 $included[$name] = true;
668 $attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
669 foreach ($urls as $url) {
670 if (preg_match('/\.js$/', $url)) {
671 $output .= html_writer
::script('', $url);
672 } else if (preg_match('/\.css$/', $url)) {
673 $attributes['href'] = $url;
674 $output .= html_writer
::empty_tag('link', $attributes) . "\n";
682 * Returns the actual url through which a script is served.
684 * @param moodle_url|string $url full moodle url, or shortened path to script
687 protected function js_fix_url($url) {
690 if ($url instanceof moodle_url
) {
692 } else if (strpos($url, '/') === 0) {
693 // Fix the admin links if needed.
694 if ($CFG->admin
!== 'admin') {
695 if (strpos($url, "/admin/") === 0) {
696 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
700 // Check file existence only when in debug mode.
701 if (!file_exists($CFG->dirroot
. strtok($url, '?'))) {
702 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
705 if (substr($url, -3) === '.js') {
706 $jsrev = $this->get_jsrev();
707 if (empty($CFG->slasharguments
)) {
708 return new moodle_url('/lib/javascript.php', array('rev'=>$jsrev, 'jsfile'=>$url));
710 $returnurl = new moodle_url('/lib/javascript.php');
711 $returnurl->set_slashargument('/'.$jsrev.$url);
715 return new moodle_url($url);
718 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
723 * Find out if JS module present and return details.
725 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
726 * @return array description of module or null if not found
728 protected function find_module($component) {
733 if (strpos($component, 'core_') === 0) {
734 // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
735 // so that we do nto have to repeat the definition of these modules over and over again.
737 case 'core_filepicker':
738 $module = array('name' => 'core_filepicker',
739 'fullpath' => '/repository/filepicker.js',
741 'base', 'node', 'node-event-simulate', 'json', 'async-queue', 'io-base', 'io-upload-iframe', 'io-form',
742 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort', 'resize-plugin', 'dd-plugin',
743 'escape', 'moodle-core_filepicker', 'moodle-core-notification-dialogue'
745 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
746 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
747 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
748 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
749 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
750 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
751 array('referencesexist', 'repository'), array('select', 'repository')
755 $module = array('name' => 'core_comment',
756 'fullpath' => '/comment/comment.js',
757 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay', 'escape'),
758 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
762 $module = array('name' => 'core_role',
763 'fullpath' => '/admin/roles/module.js',
764 'requires' => array('node', 'cookie'));
766 case 'core_completion':
767 $module = array('name' => 'core_completion',
768 'fullpath' => '/course/completion.js');
771 $module = array('name' => 'core_message',
772 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
773 'fullpath' => '/message/module.js');
776 $module = array('name' => 'core_group',
777 'fullpath' => '/group/module.js',
778 'requires' => array('node', 'overlay', 'event-mouseenter'));
780 case 'core_question_engine':
781 $module = array('name' => 'core_question_engine',
782 'fullpath' => '/question/qengine.js',
783 'requires' => array('node', 'event'));
786 $module = array('name' => 'core_rating',
787 'fullpath' => '/rating/module.js',
788 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
790 case 'core_dndupload':
791 $module = array('name' => 'core_dndupload',
792 'fullpath' => '/lib/form/dndupload.js',
793 'requires' => array('node', 'event', 'json', 'core_filepicker'),
794 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
795 array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesfile', 'error'),
796 array('sizegb', 'moodle'), array('sizemb', 'moodle'), array('sizekb', 'moodle'), array('sizeb', 'moodle'),
797 array('maxareabytesreached', 'moodle'), array('serverconnection', 'error'),
798 array('changesmadereallygoaway', 'moodle')
804 if ($dir = core_component
::get_component_directory($component)) {
805 if (file_exists("$dir/module.js")) {
806 if (strpos($dir, $CFG->dirroot
.'/') === 0) {
807 $dir = substr($dir, strlen($CFG->dirroot
));
808 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
818 * Append YUI3 module to default YUI3 JS loader.
819 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
821 * @param string|array $module name of module (details are autodetected), or full module specification as array
824 public function js_module($module) {
827 if (empty($module)) {
828 throw new coding_exception('Missing YUI3 module name or full description.');
831 if (is_string($module)) {
832 $module = $this->find_module($module);
835 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
836 throw new coding_exception('Missing YUI3 module details.');
839 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
840 // Add all needed strings.
841 if (!empty($module['strings'])) {
842 foreach ($module['strings'] as $string) {
843 $identifier = $string[0];
844 $component = isset($string[1]) ?
$string[1] : 'moodle';
845 $a = isset($string[2]) ?
$string[2] : null;
846 $this->string_for_js($identifier, $component, $a);
849 unset($module['strings']);
851 // Process module requirements and attempt to load each. This allows
852 // moodle modules to require each other.
853 if (!empty($module['requires'])){
854 foreach ($module['requires'] as $requirement) {
855 $rmodule = $this->find_module($requirement);
856 if (is_array($rmodule)) {
857 $this->js_module($rmodule);
862 if ($this->headdone
) {
863 $this->extramodules
[$module['name']] = $module;
865 $this->YUI_config
->add_module_config($module['name'], $module);
870 * Returns true if the module has already been loaded.
872 * @param string|array $module
873 * @return bool True if the module has already been loaded
875 protected function js_module_loaded($module) {
876 if (is_string($module)) {
877 $modulename = $module;
879 $modulename = $module['name'];
881 return array_key_exists($modulename, $this->YUI_config
->modules
) ||
882 array_key_exists($modulename, $this->extramodules
);
886 * Ensure that the specified CSS file is linked to from this page.
888 * Because stylesheet links must go in the <head> part of the HTML, you must call
889 * this function before {@link get_head_code()} is called. That normally means before
890 * the call to print_header. If you call it when it is too late, an exception
893 * Even if a particular style sheet is requested more than once, it will only
896 * Please note use of this feature is strongly discouraged,
897 * it is suitable only for places where CSS is submitted directly by teachers.
898 * (Students must not be allowed to submit any external CSS because it may
899 * contain embedded javascript!). Example of correct use is mod/data.
901 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
903 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
905 public function css($stylesheet) {
908 if ($this->headdone
) {
909 throw new coding_exception('Cannot require a CSS file after <head> has been printed.', $stylesheet);
912 if ($stylesheet instanceof moodle_url
) {
914 } else if (strpos($stylesheet, '/') === 0) {
915 $stylesheet = new moodle_url($stylesheet);
917 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
920 $this->cssurls
[$stylesheet->out()] = $stylesheet;
924 * Add theme stylesheet to page - do not use from plugin code,
925 * this should be called only from the core renderer!
927 * @param moodle_url $stylesheet
930 public function css_theme(moodle_url
$stylesheet) {
931 $this->cssthemeurls
[] = $stylesheet;
935 * Ensure that a skip link to a given target is printed at the top of the <body>.
937 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
938 * will be thrown). That normally means you must call this before the call to print_header.
940 * If you ask for a particular skip link to be printed, it is then your responsibility
941 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
942 * page, so that the skip link goes somewhere.
944 * Even if a particular skip link is requested more than once, only one copy of it will be output.
946 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
947 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
949 public function skip_link_to($target, $linktext) {
950 if ($this->topofbodydone
) {
951 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
954 $this->skiplinks
[$target] = $linktext;
958 * !!!DEPRECATED!!! please use js_init_call() if possible
959 * Ensure that the specified JavaScript function is called from an inline script
960 * somewhere on this page.
962 * By default the call will be put in a script tag at the
963 * end of the page after initialising Y instance, since this gives best page-load
964 * performance and allows you to use YUI3 library.
966 * If you request that a particular function is called several times, then
967 * that is what will happen (unlike linking to a CSS or JS file, where only
968 * one link will be output).
970 * The main benefit of the method is the automatic encoding of all function parameters.
974 * @param string $function the name of the JavaScritp function to call. Can
975 * be a compound name like 'Y.Event.purgeElement'. Can also be
976 * used to create and object by using a 'function name' like 'new user_selector'.
977 * @param array $arguments and array of arguments to be passed to the function.
978 * When generating the function call, this will be escaped using json_encode,
979 * so passing objects and arrays should work.
980 * @param bool $ondomready If tru the function is only called when the dom is
981 * ready for manipulation.
982 * @param int $delay The delay before the function is called.
984 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
985 $where = $ondomready ?
'ondomready' : 'normal';
986 $this->jscalls
[$where][] = array($function, $arguments, $delay);
990 * This function appends a block of code to the AMD specific javascript block executed
991 * in the page footer, just after loading the requirejs library.
993 * The code passed here can rely on AMD module loading, e.g. require('jquery', function($) {...});
995 * @param string $code The JS code to append.
997 public function js_amd_inline($code) {
998 $this->amdjscode
[] = $code;
1002 * Load an AMD module and eventually call its method.
1004 * This function creates a minimal inline JS snippet that requires an AMD module and eventually calls a single
1005 * function from the module with given arguments. If it is called multiple times, it will be create multiple
1008 * @param string $fullmodule The name of the AMD module to load, formatted as <component name>/<module name>.
1009 * @param string $func Optional function from the module to call, defaults to just loading the AMD module.
1010 * @param array $params The params to pass to the function (will be serialized into JSON).
1012 public function js_call_amd($fullmodule, $func = null, $params = array()) {
1015 list($component, $module) = explode('/', $fullmodule, 2);
1017 $component = clean_param($component, PARAM_COMPONENT
);
1018 $module = clean_param($module, PARAM_ALPHANUMEXT
);
1020 if ($func !== null) {
1021 $func = clean_param($func, PARAM_ALPHANUMEXT
);
1023 $jsonparams = array();
1024 foreach ($params as $param) {
1025 $jsonparams[] = json_encode($param);
1027 $strparams = implode(', ', $jsonparams);
1028 if ($CFG->debugdeveloper
) {
1029 $toomanyparamslimit = 1024;
1030 if (strlen($strparams) > $toomanyparamslimit) {
1031 debugging('Too much data passed as arguments to js_call_amd("' . $fullmodule . '", "' . $func .
1032 '"). Generally there are better ways to pass lots of data from PHP to JavaScript, for example via Ajax, ' .
1033 'data attributes, ... . This warning is triggered if the argument string becomes longer than ' .
1034 $toomanyparamslimit . ' characters.', DEBUG_DEVELOPER
);
1038 $js = 'require(["' . $component . '/' . $module . '"], function(amd) { amd.' . $func . '(' . $strparams . '); });';
1041 $js = 'require(["' . $component . '/' . $module . '"]);';
1044 $this->js_amd_inline($js);
1048 * Creates a JavaScript function call that requires one or more modules to be loaded.
1050 * This function can be used to include all of the standard YUI module types within JavaScript:
1051 * - YUI3 modules [node, event, io]
1052 * - YUI2 modules [yui2-*]
1053 * - Moodle modules [moodle-*]
1054 * - Gallery modules [gallery-*]
1056 * Before writing new code that makes extensive use of YUI, you should consider it's replacement AMD/JQuery.
1057 * @see js_call_amd()
1059 * @param array|string $modules One or more modules
1060 * @param string $function The function to call once modules have been loaded
1061 * @param array $arguments An array of arguments to pass to the function
1062 * @param string $galleryversion Deprecated: The gallery version to use
1063 * @param bool $ondomready
1065 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1066 if (!is_array($modules)) {
1067 $modules = array($modules);
1070 if ($galleryversion != null) {
1071 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.');
1074 $jscode = 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer
::function_call($function, $arguments).'});';
1076 $jscode = "Y.on('domready', function() { $jscode });";
1078 $this->jsinitcode
[] = $jscode;
1082 * Set the CSS Modules to be included from YUI.
1084 * @param array $modules The list of YUI CSS Modules to include.
1086 public function set_yuicssmodules(array $modules = array()) {
1087 $this->yuicssmodules
= $modules;
1091 * Ensure that the specified JavaScript function is called from an inline script
1094 * @param string $function the name of the JavaScritp function to with init code,
1095 * usually something like 'M.mod_mymodule.init'
1096 * @param array $extraarguments and array of arguments to be passed to the function.
1097 * The first argument is always the YUI3 Y instance with all required dependencies
1099 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1100 * @param array $module JS module specification array
1102 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1103 $jscode = js_writer
::function_call_with_Y($function, $extraarguments);
1105 // Detect module automatically.
1106 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
1107 $module = $this->find_module($matches[1]);
1111 $this->js_init_code($jscode, $ondomready, $module);
1115 * Add short static javascript code fragment to page footer.
1116 * This is intended primarily for loading of js modules and initialising page layout.
1117 * Ideally the JS code fragment should be stored in plugin renderer so that themes
1120 * @param string $jscode
1121 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1122 * @param array $module JS module specification array
1124 public function js_init_code($jscode, $ondomready = false, array $module = null) {
1125 $jscode = trim($jscode, " ;\n"). ';';
1127 $uniqid = html_writer
::random_id();
1128 $startjs = " M.util.js_pending('" . $uniqid . "');";
1129 $endjs = " M.util.js_complete('" . $uniqid . "');";
1132 $this->js_module($module);
1133 $modulename = $module['name'];
1134 $jscode = "$startjs Y.use('$modulename', function(Y) { $jscode $endjs });";
1138 $jscode = "$startjs Y.on('domready', function() { $jscode $endjs });";
1141 $this->jsinitcode
[] = $jscode;
1145 * Make a language string available to JavaScript.
1147 * All the strings will be available in a M.str object in the global namespace.
1148 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
1149 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
1150 * equivalent in the current language.
1152 * The arguments to this function are just like the arguments to get_string
1153 * except that $component is not optional, and there are some aspects to consider
1154 * when the string contains {$a} placeholder.
1156 * If the string does not contain any {$a} placeholder, you can simply use
1157 * M.str.component.identifier to obtain it. If you prefer, you can call
1158 * M.util.get_string(identifier, component) to get the same result.
1160 * If you need to use {$a} placeholders, there are two options. Either the
1161 * placeholder should be substituted in PHP on server side or it should
1162 * be substituted in Javascript at client side.
1164 * To substitute the placeholder at server side, just provide the required
1165 * value for the placeholder when you require the string. Because each string
1166 * is only stored once in the JavaScript (based on $identifier and $module)
1167 * you cannot get the same string with two different values of $a. If you try,
1168 * an exception will be thrown. Once the placeholder is substituted, you can
1169 * use M.str or M.util.get_string() as shown above:
1171 * // Require the string in PHP and replace the placeholder.
1172 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
1173 * // Use the result of the substitution in Javascript.
1174 * alert(M.str.moodle.fullnamedisplay);
1176 * To substitute the placeholder at client side, use M.util.get_string()
1177 * function. It implements the same logic as {@link get_string()}:
1179 * // Require the string in PHP but keep {$a} as it is.
1180 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
1181 * // Provide the values on the fly in Javascript.
1182 * user = { firstname : 'Harry', lastname : 'Potter' }
1183 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
1185 * If you do need the same string expanded with different $a values in PHP
1186 * on server side, then the solution is to put them in your own data structure
1187 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
1189 * @param string $identifier the desired string.
1190 * @param string $component the language file to look in.
1191 * @param mixed $a any extra data to add into the string (optional).
1193 public function string_for_js($identifier, $component, $a = null) {
1195 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
1197 if (isset($this->stringsforjs_as
[$component][$identifier]) and $this->stringsforjs_as
[$component][$identifier] !== $a) {
1198 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
1199 "from lang file '$component' with different \$a parameter?");
1201 if (!isset($this->stringsforjs
[$component][$identifier])) {
1202 $this->stringsforjs
[$component][$identifier] = new lang_string($identifier, $component, $a);
1203 $this->stringsforjs_as
[$component][$identifier] = $a;
1208 * Make an array of language strings available for JS.
1210 * This function calls the above function {@link string_for_js()} for each requested
1211 * string in the $identifiers array that is passed to the argument for a single module
1212 * passed in $module.
1215 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
1217 * // The above is identical to calling:
1219 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
1220 * $PAGE->requires->string_for_js('two', 'mymod');
1221 * $PAGE->requires->string_for_js('three', 'mymod', 3);
1224 * @param array $identifiers An array of desired strings
1225 * @param string $component The module to load for
1226 * @param mixed $a This can either be a single variable that gets passed as extra
1227 * information for every string or it can be an array of mixed data where the
1228 * key for the data matches that of the identifier it is meant for.
1231 public function strings_for_js($identifiers, $component, $a = null) {
1232 foreach ($identifiers as $key => $identifier) {
1233 if (is_array($a) && array_key_exists($key, $a)) {
1238 $this->string_for_js($identifier, $component, $extra);
1243 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
1245 * Make some data from PHP available to JavaScript code.
1247 * For example, if you call
1249 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
1251 * then in JavsScript mydata.name will be 'Moodle'.
1254 * @param string $variable the the name of the JavaScript variable to assign the data to.
1255 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1256 * should be considered an experimental feature.
1257 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1258 * so passing objects and arrays should work.
1259 * @param bool $inhead initialise in head
1262 public function data_for_js($variable, $data, $inhead=false) {
1263 $where = $inhead ?
'head' : 'footer';
1264 $this->jsinitvariables
[$where][] = array($variable, $data);
1268 * Creates a YUI event handler.
1270 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1271 * @param string $event A valid DOM event (click, mousedown, change etc.)
1272 * @param string $function The name of the function to call
1273 * @param array $arguments An optional array of argument parameters to pass to the function
1275 public function event_handler($selector, $event, $function, array $arguments = null) {
1276 $this->eventhandlers
[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
1280 * Returns code needed for registering of event handlers.
1281 * @return string JS code
1283 protected function get_event_handler_code() {
1285 foreach ($this->eventhandlers
as $h) {
1286 $output .= js_writer
::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
1292 * Get the inline JavaScript code that need to appear in a particular place.
1293 * @param bool $ondomready
1296 protected function get_javascript_code($ondomready) {
1297 $where = $ondomready ?
'ondomready' : 'normal';
1299 if ($this->jscalls
[$where]) {
1300 foreach ($this->jscalls
[$where] as $data) {
1301 $output .= js_writer
::function_call($data[0], $data[1], $data[2]);
1303 if (!empty($ondomready)) {
1304 $output = " Y.on('domready', function() {\n$output\n});";
1311 * Returns js code to be executed when Y is available.
1314 protected function get_javascript_init_code() {
1315 if (count($this->jsinitcode
)) {
1316 return implode("\n", $this->jsinitcode
) . "\n";
1322 * Returns js code to load amd module loader, then insert inline script tags
1323 * that contain require() calls using RequireJS.
1326 protected function get_amd_footercode() {
1330 // We will cache JS if cachejs is not set, or it is true.
1331 $cachejs = !isset($CFG->cachejs
) ||
$CFG->cachejs
;
1332 $jsrev = $this->get_jsrev();
1334 $jsloader = new moodle_url('/lib/javascript.php');
1335 $jsloader->set_slashargument('/' . $jsrev . '/');
1336 $requirejsloader = new moodle_url('/lib/requirejs.php');
1337 $requirejsloader->set_slashargument('/' . $jsrev . '/');
1339 $requirejsconfig = file_get_contents($CFG->dirroot
. '/lib/requirejs/moodle-config.js');
1341 // No extension required unless slash args is disabled.
1342 $jsextension = '.js';
1343 if (!empty($CFG->slasharguments
)) {
1347 $minextension = '.min';
1352 $requirejsconfig = str_replace('[BASEURL]', $requirejsloader, $requirejsconfig);
1353 $requirejsconfig = str_replace('[JSURL]', $jsloader, $requirejsconfig);
1354 $requirejsconfig = str_replace('[JSMIN]', $minextension, $requirejsconfig);
1355 $requirejsconfig = str_replace('[JSEXT]', $jsextension, $requirejsconfig);
1357 $output .= html_writer
::script($requirejsconfig);
1359 $output .= html_writer
::script('', $this->js_fix_url('/lib/requirejs/require.min.js'));
1361 $output .= html_writer
::script('', $this->js_fix_url('/lib/requirejs/require.js'));
1364 // First include must be to a module with no dependencies, this prevents multiple requests.
1365 $prefix = "require(['core/first'], function() {\n";
1367 $output .= html_writer
::script($prefix . implode(";\n", $this->amdjscode
) . $suffix);
1372 * Returns basic YUI3 CSS code.
1376 protected function get_yui3lib_headcss() {
1379 $yuiformat = '-min';
1380 if ($this->yui3loader
->filter
=== 'RAW') {
1385 if ($this->yui3loader
->combine
) {
1386 if (!empty($this->yuicssmodules
)) {
1388 foreach ($this->yuicssmodules
as $module) {
1389 $modules[] = "$CFG->yui3version/$module/$module-min.css";
1391 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->comboBase
.implode('&', $modules).'" />';
1393 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->local_comboBase
.'rollup/'.$CFG->yui3version
.'/yui-moodlesimple' . $yuiformat . '.css" />';
1396 if (!empty($this->yuicssmodules
)) {
1397 foreach ($this->yuicssmodules
as $module) {
1398 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->base
.$module.'/'.$module.'-min.css" />';
1401 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->local_comboBase
.'rollup/'.$CFG->yui3version
.'/yui-moodlesimple' . $yuiformat . '.css" />';
1404 if ($this->yui3loader
->filter
=== 'RAW') {
1405 $code = str_replace('-min.css', '.css', $code);
1406 } else if ($this->yui3loader
->filter
=== 'DEBUG') {
1407 $code = str_replace('-min.css', '.css', $code);
1413 * Returns basic YUI3 JS loading code.
1417 protected function get_yui3lib_headcode() {
1420 $jsrev = $this->get_jsrev();
1422 $yuiformat = '-min';
1423 if ($this->yui3loader
->filter
=== 'RAW') {
1428 if ($this->YUI_config
->groups
['moodle']['filter'] === 'DEBUG') {
1432 $rollupversion = $CFG->yui3version
;
1433 if (!empty($CFG->yuipatchlevel
)) {
1434 $rollupversion .= '_' . $CFG->yuipatchlevel
;
1437 $baserollups = array(
1438 'rollup/' . $rollupversion . "/yui-moodlesimple{$yuiformat}.js",
1441 if ($this->yui3loader
->combine
) {
1442 return '<script type="text/javascript" src="' .
1443 $this->yui3loader
->local_comboBase
.
1444 implode('&', $baserollups) .
1448 foreach ($baserollups as $rollup) {
1449 $code .= '<script type="text/javascript" src="'.$this->yui3loader
->local_comboBase
.$rollup.'"></script>';
1457 * Returns html tags needed for inclusion of theme CSS.
1461 protected function get_css_code() {
1462 // First of all the theme CSS, then any custom CSS
1463 // Please note custom CSS is strongly discouraged,
1464 // because it can not be overridden by themes!
1465 // It is suitable only for things like mod/data which accepts CSS from teachers.
1466 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1468 // Add the YUI code first. We want this to be overridden by any Moodle CSS.
1469 $code = $this->get_yui3lib_headcss();
1471 // This line of code may look funny but it is currently required in order
1472 // to avoid MASSIVE display issues in Internet Explorer.
1473 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1474 // ignored whenever another resource is added until such time as a redraw
1475 // is forced, usually by moving the mouse over the affected element.
1476 $code .= html_writer
::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1478 $urls = $this->cssthemeurls +
$this->cssurls
;
1479 foreach ($urls as $url) {
1480 $attributes['href'] = $url;
1481 $code .= html_writer
::empty_tag('link', $attributes) . "\n";
1482 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1483 unset($attributes['id']);
1490 * Adds extra modules specified after printing of page header.
1494 protected function get_extra_modules_code() {
1495 if (empty($this->extramodules
)) {
1498 return html_writer
::script(js_writer
::function_call('M.yui.add_module', array($this->extramodules
)));
1502 * Generate any HTML that needs to go inside the <head> tag.
1504 * Normally, this method is called automatically by the code that prints the
1505 * <head> tag. You should not normally need to call it in your own code.
1507 * @param moodle_page $page
1508 * @param core_renderer $renderer
1509 * @return string the HTML code to to inside the <head> tag.
1511 public function get_head_code(moodle_page
$page, core_renderer
$renderer) {
1514 // Note: the $page and $output are not stored here because it would
1515 // create circular references in memory which prevents garbage collection.
1516 $this->init_requirements_data($page, $renderer);
1520 // Add all standard CSS for this page.
1521 $output .= $this->get_css_code();
1523 // Set up the M namespace.
1524 $js = "var M = {}; M.yui = {};\n";
1526 // Capture the time now ASAP during page load. This minimises the lag when
1527 // we try to relate times on the server to times in the browser.
1528 // An example of where this is used is the quiz countdown timer.
1529 $js .= "M.pageloadstarttime = new Date();\n";
1531 // Add a subset of Moodle configuration to the M namespace.
1532 $js .= js_writer
::set_variable('M.cfg', $this->M_cfg
, false);
1534 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1535 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1536 // this needs to be done before including any other script.
1537 $js .= $this->YUI_config
->get_config_functions();
1538 $js .= js_writer
::set_variable('YUI_config', $this->YUI_config
, false) . "\n";
1539 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1540 $js = $this->YUI_config
->update_header_js($js);
1542 $output .= html_writer
::script($js);
1545 if ($this->jsinitvariables
['head']) {
1547 foreach ($this->jsinitvariables
['head'] as $data) {
1548 list($var, $value) = $data;
1549 $js .= js_writer
::set_variable($var, $value, true);
1551 $output .= html_writer
::script($js);
1554 // Mark head sending done, it is not possible to anything there.
1555 $this->headdone
= true;
1561 * Generate any HTML that needs to go at the start of the <body> tag.
1563 * Normally, this method is called automatically by the code that prints the
1564 * <head> tag. You should not normally need to call it in your own code.
1566 * @param renderer_base $renderer
1567 * @return string the HTML code to go at the start of the <body> tag.
1569 public function get_top_of_body_code(renderer_base
$renderer) {
1570 // First the skip links.
1571 $output = $renderer->render_skip_links($this->skiplinks
);
1573 // YUI3 JS needs to be loaded early in the body. It should be cached well by the browser.
1574 $output .= $this->get_yui3lib_headcode();
1576 // Add hacked jQuery support, it is not intended for standard Moodle distribution!
1577 $output .= $this->get_jquery_headcode();
1579 // Link our main JS file, all core stuff should be there.
1580 $output .= html_writer
::script('', $this->js_fix_url('/lib/javascript-static.js'));
1582 // All the other linked things from HEAD - there should be as few as possible.
1583 if ($this->jsincludes
['head']) {
1584 foreach ($this->jsincludes
['head'] as $url) {
1585 $output .= html_writer
::script('', $url);
1589 // Then the clever trick for hiding of things not needed when JS works.
1590 $output .= html_writer
::script("document.body.className += ' jsenabled';") . "\n";
1591 $this->topofbodydone
= true;
1596 * Generate any HTML that needs to go at the end of the page.
1598 * Normally, this method is called automatically by the code that prints the
1599 * page footer. You should not normally need to call it in your own code.
1601 * @return string the HTML code to to at the end of the page.
1603 public function get_end_code() {
1607 // Set the log level for the JS logging.
1608 $logconfig = new stdClass();
1609 $logconfig->level
= 'warn';
1610 if ($CFG->debugdeveloper
) {
1611 $logconfig->level
= 'trace';
1613 $this->js_call_amd('core/log', 'setConfig', array($logconfig));
1614 // Add any global JS that needs to run on all pages.
1615 $this->js_call_amd('core/page_global', 'init');
1617 // Call amd init functions.
1618 $output .= $this->get_amd_footercode();
1620 // Add other requested modules.
1621 $output .= $this->get_extra_modules_code();
1623 $this->js_init_code('M.util.js_complete("init");', true);
1625 // All the other linked scripts - there should be as few as possible.
1626 if ($this->jsincludes
['footer']) {
1627 foreach ($this->jsincludes
['footer'] as $url) {
1628 $output .= html_writer
::script('', $url);
1632 // Add all needed strings.
1633 // First add core strings required for some dialogues.
1634 $this->strings_for_js(array(
1642 if (!empty($this->stringsforjs
)) {
1644 foreach ($this->stringsforjs
as $component=>$v) {
1645 foreach($v as $indentifier => $langstring) {
1646 $strings[$component][$indentifier] = $langstring->out();
1649 $output .= html_writer
::script(js_writer
::set_variable('M.str', $strings));
1653 if ($this->jsinitvariables
['footer']) {
1655 foreach ($this->jsinitvariables
['footer'] as $data) {
1656 list($var, $value) = $data;
1657 $js .= js_writer
::set_variable($var, $value, true);
1659 $output .= html_writer
::script($js);
1662 $inyuijs = $this->get_javascript_code(false);
1663 $ondomreadyjs = $this->get_javascript_code(true);
1664 $jsinit = $this->get_javascript_init_code();
1665 $handlersjs = $this->get_event_handler_code();
1667 // There is a global Y, make sure it is available in your scope.
1668 $js = "(function() {{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}})();";
1670 $output .= html_writer
::script($js);
1676 * Have we already output the code in the <head> tag?
1680 public function is_head_done() {
1681 return $this->headdone
;
1685 * Have we already output the code at the start of the <body> tag?
1689 public function is_top_of_body_done() {
1690 return $this->topofbodydone
;
1694 * Should we generate a bit of content HTML that is only required once on
1695 * this page (e.g. the contents of the modchooser), now? Basically, we call
1696 * {@link has_one_time_item_been_created()}, and if the thing has not already
1697 * been output, we return true to tell the caller to generate it, and also
1698 * call {@link set_one_time_item_created()} to record the fact that it is
1699 * about to be generated.
1701 * That is, a typical usage pattern (in a renderer method) is:
1703 * if (!$this->page->requires->should_create_one_time_item_now($thing)) {
1706 * // Else generate it.
1709 * @param string $thing identifier for the bit of content. Should be of the form
1710 * frankenstyle_things, e.g. core_course_modchooser.
1711 * @return bool if true, the caller should generate that bit of output now, otherwise don't.
1713 public function should_create_one_time_item_now($thing) {
1714 if ($this->has_one_time_item_been_created($thing)) {
1718 $this->set_one_time_item_created($thing);
1723 * Has a particular bit of HTML that is only required once on this page
1724 * (e.g. the contents of the modchooser) already been generated?
1726 * Normally, you can use the {@link should_create_one_time_item_now()} helper
1727 * method rather than calling this method directly.
1729 * @param string $thing identifier for the bit of content. Should be of the form
1730 * frankenstyle_things, e.g. core_course_modchooser.
1731 * @return bool whether that bit of output has been created.
1733 public function has_one_time_item_been_created($thing) {
1734 return isset($this->onetimeitemsoutput
[$thing]);
1738 * Indicate that a particular bit of HTML that is only required once on this
1739 * page (e.g. the contents of the modchooser) has been generated (or is about to be)?
1741 * Normally, you can use the {@link should_create_one_time_item_now()} helper
1742 * method rather than calling this method directly.
1744 * @param string $thing identifier for the bit of content. Should be of the form
1745 * frankenstyle_things, e.g. core_course_modchooser.
1747 public function set_one_time_item_created($thing) {
1748 if ($this->has_one_time_item_been_created($thing)) {
1749 throw new coding_exception($thing . ' is only supposed to be ouput ' .
1750 'once per page, but it seems to be being output again.');
1752 return $this->onetimeitemsoutput
[$thing] = true;
1757 * This class represents the YUI configuration.
1759 * @copyright 2013 Andrew Nicols
1760 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1767 * These settings must be public so that when the object is converted to json they are exposed.
1768 * Note: Some of these are camelCase because YUI uses camelCase variable names.
1770 * The settings are described and documented in the YUI API at:
1771 * - http://yuilibrary.com/yui/docs/api/classes/config.html
1772 * - http://yuilibrary.com/yui/docs/api/classes/Loader.html
1774 public $debug = false;
1778 public $filter = null;
1779 public $insertBefore = 'firstthemesheet';
1780 public $groups = array();
1781 public $modules = array();
1784 * @var array List of functions used by the YUI Loader group pattern recognition.
1786 protected $jsconfigfunctions = array();
1789 * Create a new group within the YUI_config system.
1791 * @param String $name The name of the group. This must be unique and
1792 * not previously used.
1793 * @param Array $config The configuration for this group.
1796 public function add_group($name, $config) {
1797 if (isset($this->groups
[$name])) {
1798 throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
1800 $this->groups
[$name] = $config;
1804 * Update an existing group configuration
1806 * Note, any existing configuration for that group will be wiped out.
1807 * This includes module configuration.
1809 * @param String $name The name of the group. This must be unique and
1810 * not previously used.
1811 * @param Array $config The configuration for this group.
1814 public function update_group($name, $config) {
1815 if (!isset($this->groups
[$name])) {
1816 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.');
1818 $this->groups
[$name] = $config;
1822 * Set the value of a configuration function used by the YUI Loader's pattern testing.
1824 * Only the body of the function should be passed, and not the whole function wrapper.
1826 * The JS function your write will be passed a single argument 'name' containing the
1827 * name of the module being loaded.
1829 * @param $function String the body of the JavaScript function. This should be used i
1830 * @return String the name of the function to use in the group pattern configuration.
1832 public function set_config_function($function) {
1833 $configname = 'yui' . (count($this->jsconfigfunctions
) +
1) . 'ConfigFn';
1834 if (isset($this->jsconfigfunctions
[$configname])) {
1835 throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
1837 $this->jsconfigfunctions
[$configname] = $function;
1838 return '@' . $configname . '@';
1842 * Allow setting of the config function described in {@see set_config_function} from a file.
1843 * The contents of this file are then passed to set_config_function.
1845 * When jsrev is positive, the function is minified and stored in a MUC cache for subsequent uses.
1847 * @param $file The path to the JavaScript function used for YUI configuration.
1848 * @return String the name of the function to use in the group pattern configuration.
1850 public function set_config_source($file) {
1852 $cache = cache
::make('core', 'yuimodules');
1854 // Attempt to get the metadata from the cache.
1855 $keyname = 'configfn_' . $file;
1856 $fullpath = $CFG->dirroot
. '/' . $file;
1857 if (!isset($CFG->jsrev
) ||
$CFG->jsrev
== -1) {
1858 $cache->delete($keyname);
1859 $configfn = file_get_contents($fullpath);
1861 $configfn = $cache->get($keyname);
1862 if ($configfn === false) {
1863 require_once($CFG->libdir
. '/jslib.php');
1864 $configfn = core_minify
::js_files(array($fullpath));
1865 $cache->set($keyname, $configfn);
1868 return $this->set_config_function($configfn);
1872 * Retrieve the list of JavaScript functions for YUI_config groups.
1874 * @return String The complete set of config functions
1876 public function get_config_functions() {
1877 $configfunctions = '';
1878 foreach ($this->jsconfigfunctions
as $functionname => $function) {
1879 $configfunctions .= "var {$functionname} = function(me) {";
1880 $configfunctions .= $function;
1881 $configfunctions .= "};\n";
1883 return $configfunctions;
1887 * Update the header JavaScript with any required modification for the YUI Loader.
1889 * @param $js String The JavaScript to manipulate.
1890 * @return String the modified JS string.
1892 public function update_header_js($js) {
1893 // Update the names of the the configFn variables.
1894 // The PHP json_encode function cannot handle literal names so we have to wrap
1895 // them in @ and then replace them with literals of the same function name.
1896 foreach ($this->jsconfigfunctions
as $functionname => $function) {
1897 $js = str_replace('"@' . $functionname . '@"', $functionname, $js);
1903 * Add configuration for a specific module.
1905 * @param String $name The name of the module to add configuration for.
1906 * @param Array $config The configuration for the specified module.
1907 * @param String $group The name of the group to add configuration for.
1908 * If not specified, then this module is added to the global
1912 public function add_module_config($name, $config, $group = null) {
1914 if (!isset($this->groups
[$name])) {
1915 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.');
1917 if (!isset($this->groups
[$group]['modules'])) {
1918 $this->groups
[$group]['modules'] = array();
1920 $modules = &$this->groups
[$group]['modules'];
1922 $modules = &$this->modules
;
1924 $modules[$name] = $config;
1928 * Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
1930 * If js caching is disabled, metadata will not be served causing YUI to calculate
1931 * module dependencies as each module is loaded.
1933 * If metadata does not exist it will be created and stored in a MUC entry.
1937 public function add_moodle_metadata() {
1939 if (!isset($this->groups
['moodle'])) {
1940 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.');
1943 if (!isset($this->groups
['moodle']['modules'])) {
1944 $this->groups
['moodle']['modules'] = array();
1947 $cache = cache
::make('core', 'yuimodules');
1948 if (!isset($CFG->jsrev
) ||
$CFG->jsrev
== -1) {
1949 $metadata = array();
1950 $metadata = $this->get_moodle_metadata();
1951 $cache->delete('metadata');
1953 // Attempt to get the metadata from the cache.
1954 if (!$metadata = $cache->get('metadata')) {
1955 $metadata = $this->get_moodle_metadata();
1956 $cache->set('metadata', $metadata);
1960 // Merge with any metadata added specific to this page which was added manually.
1961 $this->groups
['moodle']['modules'] = array_merge($this->groups
['moodle']['modules'],
1966 * Determine the module metadata for all moodle YUI modules.
1968 * This works through all modules capable of serving YUI modules, and attempts to get
1969 * metadata for each of those modules.
1971 * @return Array of module metadata
1973 private function get_moodle_metadata() {
1974 $moodlemodules = array();
1975 // Core isn't a plugin type or subsystem - handle it seperately.
1976 if ($module = $this->get_moodle_path_metadata(core_component
::get_component_directory('core'))) {
1977 $moodlemodules = array_merge($moodlemodules, $module);
1980 // Handle other core subsystems.
1981 $subsystems = core_component
::get_core_subsystems();
1982 foreach ($subsystems as $subsystem => $path) {
1983 if (is_null($path)) {
1986 if ($module = $this->get_moodle_path_metadata($path)) {
1987 $moodlemodules = array_merge($moodlemodules, $module);
1991 // And finally the plugins.
1992 $plugintypes = core_component
::get_plugin_types();
1993 foreach ($plugintypes as $plugintype => $pathroot) {
1994 $pluginlist = core_component
::get_plugin_list($plugintype);
1995 foreach ($pluginlist as $plugin => $path) {
1996 if ($module = $this->get_moodle_path_metadata($path)) {
1997 $moodlemodules = array_merge($moodlemodules, $module);
2002 return $moodlemodules;
2006 * Helper function process and return the YUI metadata for all of the modules under the specified path.
2008 * @param String $path the UNC path to the YUI src directory.
2009 * @return Array the complete array for frankenstyle directory.
2011 private function get_moodle_path_metadata($path) {
2012 // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
2013 $baseyui = $path . '/yui/src';
2015 if (is_dir($baseyui)) {
2016 $items = new DirectoryIterator($baseyui);
2017 foreach ($items as $item) {
2018 if ($item->isDot() or !$item->isDir()) {
2021 $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
2022 if (!is_readable($metafile)) {
2025 $metadata = file_get_contents($metafile);
2026 $modules = array_merge($modules, (array) json_decode($metadata));
2033 * Define YUI modules which we have been required to patch between releases.
2035 * We must do this because we aggressively cache content on the browser, and we must also override use of the
2036 * external CDN which will serve the true authoritative copy of the code without our patches.
2038 * @param String combobase The local combobase
2039 * @param String yuiversion The current YUI version
2040 * @param Int patchlevel The patch level we're working to for YUI
2041 * @param Array patchedmodules An array containing the names of the patched modules
2044 public function define_patched_core_modules($combobase, $yuiversion, $patchlevel, $patchedmodules) {
2045 // The version we use is suffixed with a patchlevel so that we can get additional revisions between YUI releases.
2046 $subversion = $yuiversion . '_' . $patchlevel;
2048 if ($this->comboBase
== $combobase) {
2049 // If we are using the local combobase in the loader, we can add a group and still make use of the combo
2050 // loader. We just need to specify a different root which includes a slightly different YUI version number
2051 // to include our patchlevel.
2052 $patterns = array();
2054 foreach ($patchedmodules as $modulename) {
2055 // We must define the pattern and module here so that the loader uses our group configuration instead of
2056 // the standard module definition. We may lose some metadata provided by upstream but this will be
2057 // loaded when the module is loaded anyway.
2058 $patterns[$modulename] = array(
2059 'group' => 'yui-patched',
2061 $modules[$modulename] = array();
2064 // Actually add the patch group here.
2065 $this->add_group('yui-patched', array(
2067 'root' => $subversion . '/',
2068 'patterns' => $patterns,
2069 'modules' => $modules,
2073 // The CDN is in use - we need to instead use the local combobase for this module and override the modules
2074 // definition. We cannot use the local base - we must use the combobase because we cannot invalidate the
2075 // local base in browser caches.
2076 $fullpathbase = $combobase . $subversion . '/';
2077 foreach ($patchedmodules as $modulename) {
2078 $this->modules
[$modulename] = array(
2079 'fullpath' => $fullpathbase . $modulename . '/' . $modulename . '-min.js'
2087 * Invalidate all server and client side JS caches.
2089 function js_reset_all_caches() {
2093 if (isset($CFG->jsrev
) and $next <= $CFG->jsrev
and $CFG->jsrev
- $next < 60*60) {
2094 // This resolves problems when reset is requested repeatedly within 1s,
2095 // the < 1h condition prevents accidental switching to future dates
2096 // because we might not recover from it.
2097 $next = $CFG->jsrev+
1;
2100 set_config('jsrev', $next);