Merge branch 'MDL-40119-25' of git://github.com/andrewnicols/moodle into MOODLE_25_STABLE
[moodle.git] / lib / outputrequirementslib.php
blob5bfc91eb0ce60cf21f752562115cc43e447ca8a3
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library functions to facilitate the use of JavaScript in Moodle.
20 * Note: you can find history of this file in lib/ajax/ajaxlib.php
22 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @package core
25 * @category output
28 defined('MOODLE_INTERNAL') || die();
30 /**
31 * This class tracks all the things that are needed by the current page.
33 * Normally, the only instance of this class you will need to work with is the
34 * one accessible via $PAGE->requires.
36 * Typical usage would be
37 * <pre>
38 * $PAGE->requires->js_init_call('M.mod_forum.init_view');
39 * </pre>
41 * It also supports obsoleted coding style withouth YUI3 modules.
42 * <pre>
43 * $PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overridable via themes!
44 * $PAGE->requires->js('/mod/mymod/script.js');
45 * $PAGE->requires->js('/mod/mymod/small_but_urgent.js', true);
46 * $PAGE->requires->js_function_call('init_mymod', array($data), true);
47 * </pre>
49 * There are some natural restrictions on some methods. For example, {@link css()}
50 * can only be called before the <head> tag is output. See the comments on the
51 * individual methods for details.
53 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
54 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
55 * @since Moodle 2.0
56 * @package core
57 * @category output
59 class page_requirements_manager {
61 /**
62 * @var array List of string available from JS
64 protected $stringsforjs = array();
66 /**
67 * @var array List of get_string $a parameters - used for validation only.
69 protected $stringsforjs_as = array();
71 /**
72 * @var array List of JS variables to be initialised
74 protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
76 /**
77 * @var array Included JS scripts
79 protected $jsincludes = array('head'=>array(), 'footer'=>array());
81 /**
82 * @var array List of needed function calls
84 protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
86 /**
87 * @var array List of skip links, those are needed for accessibility reasons
89 protected $skiplinks = array();
91 /**
92 * @var array Javascript code used for initialisation of page, it should
93 * be relatively small
95 protected $jsinitcode = array();
97 /**
98 * @var array of moodle_url Theme sheets, initialised only from core_renderer
100 protected $cssthemeurls = array();
103 * @var array of moodle_url List of custom theme sheets, these are strongly discouraged!
104 * Useful mostly only for CSS submitted by teachers that is not part of the theme.
106 protected $cssurls = array();
109 * @var array List of requested event handlers
111 protected $eventhandlers = array();
114 * @var array Extra modules
116 protected $extramodules = array();
119 * @var bool Flag indicated head stuff already printed
121 protected $headdone = false;
124 * @var bool Flag indicating top of body already printed
126 protected $topofbodydone = false;
129 * @var stdClass YUI PHPLoader instance responsible for YUI3 loading from PHP only
131 protected $yui3loader;
134 * @var YUI_config default YUI loader configuration
136 protected $YUI_config;
139 * @var array Some config vars exposed in JS, please no secret stuff there
141 protected $M_cfg;
144 * @var array Stores debug backtraces from when JS modules were included in the page
146 protected $debug_moduleloadstacktraces = array();
149 * @var array list of requested jQuery plugins
151 protected $jqueryplugins = array();
154 * @var array list of jQuery plugin overrides
156 protected $jquerypluginoverrides = array();
159 * Page requirements constructor.
161 public function __construct() {
162 global $CFG;
164 // You may need to set up URL rewrite rule because oversized URLs might not be allowed by web server.
165 $sep = empty($CFG->yuislasharguments) ? '?' : '/';
167 $this->yui3loader = new stdClass();
168 $this->YUI_config = new YUI_config();
170 // Set up some loader options.
171 if (!empty($CFG->useexternalyui) and strpos($CFG->httpswwwroot, 'https:') !== 0) {
172 $this->yui3loader->base = 'http://yui.yahooapis.com/' . $CFG->yui3version . '/build/';
173 $this->yui3loader->comboBase = 'http://yui.yahooapis.com/combo?';
174 } else {
175 $this->yui3loader->base = $CFG->httpswwwroot . '/lib/yuilib/'. $CFG->yui3version . '/build/';
176 $this->yui3loader->comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep;
179 // Enable combo loader? This significantly helps with caching and performance!
180 $this->yui3loader->combine = !empty($CFG->yuicomboloading);
182 if (empty($CFG->cachejs)) {
183 $jsrev = -1;
184 } else if (empty($CFG->jsrev)) {
185 $jsrev = 1;
186 } else {
187 $jsrev = $CFG->jsrev;
190 // Set up JS YUI loader helper object.
191 $this->YUI_config->base = $this->yui3loader->base;
192 $this->YUI_config->comboBase = $this->yui3loader->comboBase;
193 $this->YUI_config->combine = $this->yui3loader->combine;
195 $configname = $this->YUI_config->set_config_function("if(/-skin|reset|fonts|grids|base/.test(me.name)){me.type='css';me.path=me.path.replace(/\.js/,'.css');me.path=me.path.replace(/\/yui2-skin/,'/assets/skins/sam/yui2-skin');}");
196 $this->YUI_config->add_group('yui2', array(
197 // Loader configuration for our 2in3, for now ignores $CFG->useexternalyui.
198 'base' => $CFG->httpswwwroot . '/lib/yuilib/2in3/' . $CFG->yui2version . '/build/',
199 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
200 'combine' => $this->yui3loader->combine,
201 'ext' => false,
202 'root' => '2in3/' . $CFG->yui2version .'/build/',
203 'patterns' => array(
204 'yui2-' => array(
205 'group' => 'yui2',
206 'configFn' => $configname,
210 $configname = $this->YUI_config->set_config_function("var p = me.path, b = me.name.replace(/^moodle-/,'').split('-', 3), n = b.pop();if (/(skin|core)/.test(n)) {n = b.pop();me.type = 'css';};me.path = b.join('-')+'/'+n+'/'+n;if(me.type !== 'css'){me.path=me.path+'-min';};me.path=me.path+'.'+me.type;");
211 $this->YUI_config->add_group('moodle', array(
212 'name' => 'moodle',
213 'base' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep.'moodle/'.$jsrev.'/',
214 'combine' => $this->yui3loader->combine,
215 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
216 'ext' => false,
217 'root' => 'moodle/'.$jsrev.'/', // Add the rev to the root path so that we can control caching.
218 'patterns' => array(
219 'moodle-' => array(
220 'group' => 'moodle',
221 'configFn' => $configname,
226 // Set some more loader options applying to groups too.
227 if (debugging('', DEBUG_DEVELOPER)) {
228 // When debugging is enabled, we want to load the non-minified (RAW) versions of YUI library modules rather
229 // than the DEBUG versions as these generally generate too much logging for our purposes.
230 // However we do want the DEBUG versions of our Moodle-specific modules.
231 // To debug a YUI-specific issue, change the yui3loader->filter value to DEBUG.
232 $this->YUI_config->filter = 'RAW';
233 $this->YUI_config->groups['moodle']['filter'] = 'DEBUG';
235 // We use the yui3loader->filter setting when writing the YUI3 seed scripts into the header.
236 $this->yui3loader->filter = $this->YUI_config->filter;
237 $this->YUI_config->debug = true;
238 } else {
239 $this->yui3loader->filter = null;
240 $this->YUI_config->debug = false;
243 // Add the moodle group's module data.
244 $this->YUI_config->add_moodle_metadata();
246 // Every page should include definition of following modules.
247 $this->js_module($this->find_module('core_filepicker'));
248 $this->js_module($this->find_module('core_dock'));
252 * Initialise with the bits of JavaScript that every Moodle page should have.
254 * @param moodle_page $page
255 * @param core_renderer $renderer
257 protected function init_requirements_data(moodle_page $page, core_renderer $renderer) {
258 global $CFG;
260 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
261 // Otherwise, in some situations, users will get warnings about insecure content
262 // on secure pages from their web browser.
264 $this->M_cfg = array(
265 'wwwroot' => $CFG->httpswwwroot, // Yes, really. See above.
266 'sesskey' => sesskey(),
267 'loadingicon' => $renderer->pix_url('i/loading_small', 'moodle')->out(false),
268 'themerev' => theme_get_revision(),
269 'slasharguments' => (int)(!empty($CFG->slasharguments)),
270 'theme' => $page->theme->name,
271 'jsrev' => ((empty($CFG->cachejs) or empty($CFG->jsrev)) ? -1 : $CFG->jsrev),
272 'svgicons' => $page->theme->use_svg_icons()
274 if (debugging('', DEBUG_DEVELOPER)) {
275 $this->M_cfg['developerdebug'] = true;
277 if (defined('BEHAT_SITE_RUNNING')) {
278 $this->M_cfg['behatsiterunning'] = true;
281 // Accessibility stuff.
282 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
284 // Add strings used on many pages.
285 $this->string_for_js('confirmation', 'admin');
286 $this->string_for_js('cancel', 'moodle');
287 $this->string_for_js('yes', 'moodle');
289 // Alter links in top frame to break out of frames.
290 if ($page->pagelayout === 'frametop') {
291 $this->js_init_call('M.util.init_frametop');
294 // Include block drag/drop if editing is on
295 if ($page->user_is_editing()) {
296 $params = array(
297 'courseid' => $page->course->id,
298 'pagetype' => $page->pagetype,
299 'pagelayout' => $page->pagelayout,
300 'subpage' => $page->subpage,
301 'regions' => $page->blocks->get_regions(),
302 'contextid' => $page->context->id,
304 if (!empty($page->cm->id)) {
305 $params['cmid'] = $page->cm->id;
307 $page->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
312 * Ensure that the specified JavaScript file is linked to from this page.
314 * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
315 * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
317 * By default the link is put at the end of the page, since this gives best page-load performance.
319 * Even if a particular script is requested more than once, it will only be linked
320 * to once.
322 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
323 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
324 * @param bool $inhead initialise in head
326 public function js($url, $inhead = false) {
327 $url = $this->js_fix_url($url);
328 $where = $inhead ? 'head' : 'footer';
329 $this->jsincludes[$where][$url->out()] = $url;
333 * Request inclusion of jQuery library in the page.
335 * NOTE: this should not be used in official Moodle distribution!
337 * We are going to bundle jQuery 1.9.x until we drop support
338 * all support for IE 6-8. Use $PAGE->requires->jquery_plugin('migrate')
339 * for code written for earlier jQuery versions.
341 * {@see http://docs.moodle.org/dev/jQuery}
343 public function jquery() {
344 $this->jquery_plugin('jquery');
348 * Request inclusion of jQuery plugin.
350 * NOTE: this should not be used in official Moodle distribution!
352 * jQuery plugins are located in plugin/jquery/* subdirectory,
353 * plugin/jquery/plugins.php lists all available plugins.
355 * Included core plugins:
356 * - jQuery UI
357 * - jQuery Migrate (useful for code written for previous UI version)
359 * Add-ons may include extra jQuery plugins in jquery/ directory,
360 * plugins.php file defines the mapping between plugin names and
361 * necessary page includes.
363 * Examples:
364 * <code>
365 * // file: mod/xxx/view.php
366 * $PAGE->requires->jquery();
367 * $PAGE->requires->jquery_plugin('ui');
368 * $PAGE->requires->jquery_plugin('ui-css');
369 * </code>
371 * <code>
372 * // file: theme/yyy/lib.php
373 * function theme_yyy_page_init(moodle_page $page) {
374 * $page->requires->jquery();
375 * $page->requires->jquery_plugin('ui');
376 * $page->requires->jquery_plugin('ui-css');
378 * </code>
380 * <code>
381 * // file: blocks/zzz/block_zzz.php
382 * public function get_required_javascript() {
383 * parent::get_required_javascript();
384 * $this->page->requires->jquery();
385 * $page->requires->jquery_plugin('ui');
386 * $page->requires->jquery_plugin('ui-css');
388 * </code>
390 * {@see http://docs.moodle.org/dev/jQuery}
392 * @param string $plugin name of the jQuery plugin as defined in jquery/plugins.php
393 * @param string $component name of the component
394 * @return bool success
396 public function jquery_plugin($plugin, $component = 'core') {
397 global $CFG;
399 if ($this->headdone) {
400 debugging('Can not add jQuery plugins after starting page output!');
401 return false;
404 if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css', 'migrate'))) {
405 debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER);
406 $component = 'core';
407 } else if ($component !== 'core' and strpos($component, '_') === false) {
408 // Let's normalise the legacy activity names, Frankenstyle rulez!
409 $component = 'mod_' . $component;
412 if (empty($this->jqueryplugins) and ($component !== 'core' or $plugin !== 'jquery')) {
413 // Make sure the jQuery itself is always loaded first,
414 // the order of all other plugins depends on order of $PAGE_>requires->.
415 $this->jquery_plugin('jquery', 'core');
418 if (isset($this->jqueryplugins[$plugin])) {
419 // No problem, we already have something, first Moodle plugin to register the jQuery plugin wins.
420 return true;
423 $componentdir = get_component_directory($component);
424 if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
425 debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER);
426 return false;
429 $plugins = array();
430 require("$componentdir/jquery/plugins.php");
432 if (!isset($plugins[$plugin])) {
433 debugging("jQuery plugin '$plugin' can not be found in component '$component'.", DEBUG_DEVELOPER);
434 return false;
437 $this->jqueryplugins[$plugin] = new stdClass();
438 $this->jqueryplugins[$plugin]->plugin = $plugin;
439 $this->jqueryplugins[$plugin]->component = $component;
440 $this->jqueryplugins[$plugin]->urls = array();
442 foreach ($plugins[$plugin]['files'] as $file) {
443 if (debugging('', DEBUG_DEVELOPER)) {
444 if (!file_exists("$componentdir/jquery/$file")) {
445 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
446 continue;
448 $file = str_replace('.min.css', '.css', $file);
449 $file = str_replace('.min.js', '.js', $file);
451 if (!file_exists("$componentdir/jquery/$file")) {
452 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
453 continue;
455 if (!empty($CFG->slasharguments)) {
456 $url = new moodle_url("$CFG->httpswwwroot/theme/jquery.php");
457 $url->set_slashargument("/$component/$file");
459 } else {
460 // This is not really good, we need slasharguments for relative links, this means no caching...
461 $path = realpath("$componentdir/jquery/$file");
462 if (strpos($path, $CFG->dirroot) === 0) {
463 $url = $CFG->httpswwwroot.preg_replace('/^'.preg_quote($CFG->dirroot, '/').'/', '', $path);
464 $url = new moodle_url($url);
465 } else {
466 // Bad luck, fix your server!
467 debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
468 continue;
471 $this->jqueryplugins[$plugin]->urls[] = $url;
474 return true;
478 * Request replacement of one jQuery plugin by another.
480 * This is useful when themes want to replace the jQuery UI theme,
481 * the problem is that theme can not prevent others from including the core ui-css plugin.
483 * Example:
484 * 1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
485 * 2/ write theme/yourtheme/jquery/plugins.php
486 * 3/ init jQuery from theme
488 * <code>
489 * // file theme/yourtheme/lib.php
490 * function theme_yourtheme_page_init($page) {
491 * $page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
492 * $page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
494 * </code>
496 * This code prevents loading of standard 'ui-css' which my be requested by other plugins,
497 * the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
499 * {@see http://docs.moodle.org/dev/jQuery}
501 * @param string $oldplugin original plugin
502 * @param string $newplugin the replacement
504 public function jquery_override_plugin($oldplugin, $newplugin) {
505 if ($this->headdone) {
506 debugging('Can not override jQuery plugins after starting page output!');
507 return;
509 $this->jquerypluginoverrides[$oldplugin] = $newplugin;
513 * Return jQuery related markup for page start.
514 * @return string
516 protected function get_jquery_headcode() {
517 if (empty($this->jqueryplugins['jquery'])) {
518 // If nobody requested jQuery then do not bother to load anything.
519 // This may be useful for themes that want to override 'ui-css' only if requested by something else.
520 return '';
523 $included = array();
524 $urls = array();
526 foreach ($this->jqueryplugins as $name => $unused) {
527 if (isset($included[$name])) {
528 continue;
530 if (array_key_exists($name, $this->jquerypluginoverrides)) {
531 // The following loop tries to resolve the replacements,
532 // use max 100 iterations to prevent infinite loop resulting
533 // in blank page.
534 $cyclic = true;
535 $oldname = $name;
536 for ($i=0; $i<100; $i++) {
537 $name = $this->jquerypluginoverrides[$name];
538 if (!array_key_exists($name, $this->jquerypluginoverrides)) {
539 $cyclic = false;
540 break;
543 if ($cyclic) {
544 // We can not do much with cyclic references here, let's use the old plugin.
545 $name = $oldname;
546 debugging("Cyclic overrides detected for jQuery plugin '$name'");
548 } else if (empty($name)) {
549 // Developer requested removal of the plugin.
550 continue;
552 } else if (!isset($this->jqueryplugins[$name])) {
553 debugging("Unknown jQuery override plugin '$name' detected");
554 $name = $oldname;
556 } else if (isset($included[$name])) {
557 // The plugin was already included, easy.
558 continue;
562 $plugin = $this->jqueryplugins[$name];
563 $urls = array_merge($urls, $plugin->urls);
564 $included[$name] = true;
567 $output = '';
568 $attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
569 foreach ($urls as $url) {
570 if (preg_match('/\.js$/', $url)) {
571 $output .= html_writer::script('', $url);
572 } else if (preg_match('/\.css$/', $url)) {
573 $attributes['href'] = $url;
574 $output .= html_writer::empty_tag('link', $attributes) . "\n";
578 return $output;
582 * This method was used to load YUI2 libraries into global scope,
583 * use YUI 2in3 instead. Every YUI2 module is represented as a yui2-*
584 * sandboxed module in YUI3 code via Y.YUI2. property.
586 * {@see http://tracker.moodle.org/browse/MDL-34741}
588 * @param string|array $libname
589 * @deprecated since 2.4
591 public function yui2_lib($libname) {
592 throw new coding_exception('PAGE->yui2_lib() is not available any more, use YUI 2in3 instead, see MDL-34741 for more information.');
596 * Returns the actual url through which a script is served.
598 * @param moodle_url|string $url full moodle url, or shortened path to script
599 * @return moodle_url
601 protected function js_fix_url($url) {
602 global $CFG;
604 if ($url instanceof moodle_url) {
605 return $url;
606 } else if (strpos($url, '/') === 0) {
607 // Fix the admin links if needed.
608 if ($CFG->admin !== 'admin') {
609 if (strpos($url, "/admin/") === 0) {
610 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
613 if (debugging()) {
614 // Check file existence only when in debug mode.
615 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
616 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
619 if (!empty($CFG->cachejs) and !empty($CFG->jsrev) and $CFG->jsrev > 0 and substr($url, -3) === '.js') {
620 if (empty($CFG->slasharguments)) {
621 return new moodle_url($CFG->httpswwwroot.'/lib/javascript.php', array('rev'=>$CFG->jsrev, 'jsfile'=>$url));
622 } else {
623 $returnurl = new moodle_url($CFG->httpswwwroot.'/lib/javascript.php');
624 $returnurl->set_slashargument('/'.$CFG->jsrev.$url);
625 return $returnurl;
627 } else {
628 return new moodle_url($CFG->httpswwwroot.$url);
630 } else {
631 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
636 * Find out if JS module present and return details.
638 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
639 * @return array description of module or null if not found
641 protected function find_module($component) {
642 global $CFG, $PAGE;
644 $module = null;
646 if (strpos($component, 'core_') === 0) {
647 // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
648 // so that we do nto have to repeat the definition of these modules over and over again.
649 switch($component) {
650 case 'core_filepicker':
651 $module = array('name' => 'core_filepicker',
652 'fullpath' => '/repository/filepicker.js',
653 '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'),
654 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
655 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
656 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
657 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
658 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
659 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
660 array('referencesexist', 'repository'), array('select', 'repository')
662 break;
663 case 'core_comment':
664 $module = array('name' => 'core_comment',
665 'fullpath' => '/comment/comment.js',
666 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
667 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
669 break;
670 case 'core_role':
671 $module = array('name' => 'core_role',
672 'fullpath' => '/admin/roles/module.js',
673 'requires' => array('node', 'cookie'));
674 break;
675 case 'core_completion':
676 $module = array('name' => 'core_completion',
677 'fullpath' => '/course/completion.js');
678 break;
679 case 'core_dock':
680 $module = array('name' => 'core_dock',
681 'fullpath' => '/blocks/dock.js',
682 'requires' => array('base', 'node', 'event-custom', 'event-mouseenter', 'event-resize', 'escape'),
683 'strings' => array(array('addtodock', 'block'),array('undockitem', 'block'),array('dockblock', 'block'),
684 array('undockblock', 'block'),array('undockall', 'block'),array('thisdirectionvertical', 'langconfig'),
685 array('hidedockpanel', 'block'),array('hidepanel', 'block')
687 break;
688 case 'core_message':
689 $module = array('name' => 'core_message',
690 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
691 'fullpath' => '/message/module.js');
692 break;
693 case 'core_group':
694 $module = array('name' => 'core_group',
695 'fullpath' => '/group/module.js',
696 'requires' => array('node', 'overlay', 'event-mouseenter'));
697 break;
698 case 'core_question_engine':
699 $module = array('name' => 'core_question_engine',
700 'fullpath' => '/question/qengine.js',
701 'requires' => array('node', 'event'));
702 break;
703 case 'core_rating':
704 $module = array('name' => 'core_rating',
705 'fullpath' => '/rating/module.js',
706 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
707 break;
708 case 'core_dndupload':
709 $module = array('name' => 'core_dndupload',
710 'fullpath' => '/lib/form/dndupload.js',
711 'requires' => array('node', 'event', 'json', 'core_filepicker'),
712 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
713 array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesforfile', 'moodle'),
714 array('maxareabytesreached', 'moodle')
716 break;
719 } else {
720 if ($dir = get_component_directory($component)) {
721 if (file_exists("$dir/module.js")) {
722 if (strpos($dir, $CFG->dirroot.'/') === 0) {
723 $dir = substr($dir, strlen($CFG->dirroot));
724 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
730 return $module;
734 * Append YUI3 module to default YUI3 JS loader.
735 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
737 * @param string|array $module name of module (details are autodetected), or full module specification as array
738 * @return void
740 public function js_module($module) {
741 global $CFG;
743 if (empty($module)) {
744 throw new coding_exception('Missing YUI3 module name or full description.');
747 if (is_string($module)) {
748 $module = $this->find_module($module);
751 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
752 throw new coding_exception('Missing YUI3 module details.');
755 // Don't load this module if we already have, no need to!
756 if ($this->js_module_loaded($module['name'])) {
757 if (debugging('', DEBUG_DEVELOPER)) {
758 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
760 return;
763 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
764 // Add all needed strings.
765 if (!empty($module['strings'])) {
766 foreach ($module['strings'] as $string) {
767 $identifier = $string[0];
768 $component = isset($string[1]) ? $string[1] : 'moodle';
769 $a = isset($string[2]) ? $string[2] : null;
770 $this->string_for_js($identifier, $component, $a);
773 unset($module['strings']);
775 // Process module requirements and attempt to load each. This allows
776 // moodle modules to require each other.
777 if (!empty($module['requires'])){
778 foreach ($module['requires'] as $requirement) {
779 $rmodule = $this->find_module($requirement);
780 if (is_array($rmodule)) {
781 $this->js_module($rmodule);
786 if ($this->headdone) {
787 $this->extramodules[$module['name']] = $module;
788 } else {
789 $this->YUI_config->add_module_config($module['name'], $module);
791 if (debugging('', DEBUG_DEVELOPER)) {
792 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces)) {
793 $this->debug_moduleloadstacktraces[$module['name']] = array();
795 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
800 * Returns true if the module has already been loaded.
802 * @param string|array $module
803 * @return bool True if the module has already been loaded
805 protected function js_module_loaded($module) {
806 if (is_string($module)) {
807 $modulename = $module;
808 } else {
809 $modulename = $module['name'];
811 return array_key_exists($modulename, $this->YUI_config->modules) ||
812 array_key_exists($modulename, $this->extramodules);
816 * Returns the stacktraces from loading js modules.
817 * @return array
819 public function get_loaded_modules() {
820 return $this->debug_moduleloadstacktraces;
824 * Ensure that the specified CSS file is linked to from this page.
826 * Because stylesheet links must go in the <head> part of the HTML, you must call
827 * this function before {@link get_head_code()} is called. That normally means before
828 * the call to print_header. If you call it when it is too late, an exception
829 * will be thrown.
831 * Even if a particular style sheet is requested more than once, it will only
832 * be linked to once.
834 * Please note use of this feature is strongly discouraged,
835 * it is suitable only for places where CSS is submitted directly by teachers.
836 * (Students must not be allowed to submit any external CSS because it may
837 * contain embedded javascript!). Example of correct use is mod/data.
839 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
840 * For example:
841 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
843 public function css($stylesheet) {
844 global $CFG;
846 if ($this->headdone) {
847 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
850 if ($stylesheet instanceof moodle_url) {
851 // ok
852 } else if (strpos($stylesheet, '/') === 0) {
853 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
854 } else {
855 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
858 $this->cssurls[$stylesheet->out()] = $stylesheet;
862 * Add theme stylesheet to page - do not use from plugin code,
863 * this should be called only from the core renderer!
865 * @param moodle_url $stylesheet
866 * @return void
868 public function css_theme(moodle_url $stylesheet) {
869 $this->cssthemeurls[] = $stylesheet;
873 * Ensure that a skip link to a given target is printed at the top of the <body>.
875 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
876 * will be thrown). That normally means you must call this before the call to print_header.
878 * If you ask for a particular skip link to be printed, it is then your responsibility
879 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
880 * page, so that the skip link goes somewhere.
882 * Even if a particular skip link is requested more than once, only one copy of it will be output.
884 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
885 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
887 public function skip_link_to($target, $linktext) {
888 if ($this->topofbodydone) {
889 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
890 return;
892 $this->skiplinks[$target] = $linktext;
896 * !!!DEPRECATED!!! please use js_init_call() if possible
897 * Ensure that the specified JavaScript function is called from an inline script
898 * somewhere on this page.
900 * By default the call will be put in a script tag at the
901 * end of the page after initialising Y instance, since this gives best page-load
902 * performance and allows you to use YUI3 library.
904 * If you request that a particular function is called several times, then
905 * that is what will happen (unlike linking to a CSS or JS file, where only
906 * one link will be output).
908 * The main benefit of the method is the automatic encoding of all function parameters.
910 * @deprecated
912 * @param string $function the name of the JavaScritp function to call. Can
913 * be a compound name like 'Y.Event.purgeElement'. Can also be
914 * used to create and object by using a 'function name' like 'new user_selector'.
915 * @param array $arguments and array of arguments to be passed to the function.
916 * When generating the function call, this will be escaped using json_encode,
917 * so passing objects and arrays should work.
918 * @param bool $ondomready If tru the function is only called when the dom is
919 * ready for manipulation.
920 * @param int $delay The delay before the function is called.
922 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
923 $where = $ondomready ? 'ondomready' : 'normal';
924 $this->jscalls[$where][] = array($function, $arguments, $delay);
928 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
930 * @deprecated DO NOT USE
932 * @param string|array $modules One or more gallery modules to require
933 * @param string $version
934 * @param string $function
935 * @param array $arguments
936 * @param bool $ondomready
938 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
939 global $CFG;
940 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER);
941 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
945 * Creates a JavaScript function call that requires one or more modules to be loaded.
947 * This function can be used to include all of the standard YUI module types within JavaScript:
948 * - YUI3 modules [node, event, io]
949 * - YUI2 modules [yui2-*]
950 * - Moodle modules [moodle-*]
951 * - Gallery modules [gallery-*]
953 * @param array|string $modules One or more modules
954 * @param string $function The function to call once modules have been loaded
955 * @param array $arguments An array of arguments to pass to the function
956 * @param string $galleryversion The gallery version to use
957 * @param bool $ondomready
959 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
960 global $CFG;
962 if (!$galleryversion) {
963 $galleryversion = '2010.04.08-12-35';
966 if (!is_array($modules)) {
967 $modules = array($modules);
969 if (empty($CFG->useexternalyui)) {
970 // We need to set the M.yui.galleryversion to the correct version
971 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
972 } else {
973 // Set Y's config.gallery to the version
974 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
976 $jscode .= 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
977 if ($ondomready) {
978 $jscode = "Y.on('domready', function() { $jscode });";
980 $this->jsinitcode[] = $jscode;
984 * Ensure that the specified JavaScript function is called from an inline script
985 * from page footer.
987 * @param string $function the name of the JavaScritp function to with init code,
988 * usually something like 'M.mod_mymodule.init'
989 * @param array $extraarguments and array of arguments to be passed to the function.
990 * The first argument is always the YUI3 Y instance with all required dependencies
991 * already loaded.
992 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
993 * @param array $module JS module specification array
995 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
996 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
997 if (!$module) {
998 // Detect module automatically.
999 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
1000 $module = $this->find_module($matches[1]);
1004 $this->js_init_code($jscode, $ondomready, $module);
1008 * Add short static javascript code fragment to page footer.
1009 * This is intended primarily for loading of js modules and initialising page layout.
1010 * Ideally the JS code fragment should be stored in plugin renderer so that themes
1011 * may override it.
1013 * @param string $jscode
1014 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1015 * @param array $module JS module specification array
1017 public function js_init_code($jscode, $ondomready = false, array $module = null) {
1018 $jscode = trim($jscode, " ;\n"). ';';
1020 if ($module) {
1021 $this->js_module($module);
1022 $modulename = $module['name'];
1023 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
1026 if ($ondomready) {
1027 $jscode = "Y.on('domready', function() { $jscode });";
1030 $this->jsinitcode[] = $jscode;
1034 * Make a language string available to JavaScript.
1036 * All the strings will be available in a M.str object in the global namespace.
1037 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
1038 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
1039 * equivalent in the current language.
1041 * The arguments to this function are just like the arguments to get_string
1042 * except that $component is not optional, and there are some aspects to consider
1043 * when the string contains {$a} placeholder.
1045 * If the string does not contain any {$a} placeholder, you can simply use
1046 * M.str.component.identifier to obtain it. If you prefer, you can call
1047 * M.util.get_string(identifier, component) to get the same result.
1049 * If you need to use {$a} placeholders, there are two options. Either the
1050 * placeholder should be substituted in PHP on server side or it should
1051 * be substituted in Javascript at client side.
1053 * To substitute the placeholder at server side, just provide the required
1054 * value for the placeholder when you require the string. Because each string
1055 * is only stored once in the JavaScript (based on $identifier and $module)
1056 * you cannot get the same string with two different values of $a. If you try,
1057 * an exception will be thrown. Once the placeholder is substituted, you can
1058 * use M.str or M.util.get_string() as shown above:
1060 * // Require the string in PHP and replace the placeholder.
1061 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
1062 * // Use the result of the substitution in Javascript.
1063 * alert(M.str.moodle.fullnamedisplay);
1065 * To substitute the placeholder at client side, use M.util.get_string()
1066 * function. It implements the same logic as {@link get_string()}:
1068 * // Require the string in PHP but keep {$a} as it is.
1069 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
1070 * // Provide the values on the fly in Javascript.
1071 * user = { firstname : 'Harry', lastname : 'Potter' }
1072 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
1074 * If you do need the same string expanded with different $a values in PHP
1075 * on server side, then the solution is to put them in your own data structure
1076 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
1078 * @param string $identifier the desired string.
1079 * @param string $component the language file to look in.
1080 * @param mixed $a any extra data to add into the string (optional).
1082 public function string_for_js($identifier, $component, $a = null) {
1083 if (!$component) {
1084 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
1086 if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
1087 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
1088 "from lang file '$component' with different \$a parameter?");
1090 if (!isset($this->stringsforjs[$component][$identifier])) {
1091 $this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
1092 $this->stringsforjs_as[$component][$identifier] = $a;
1097 * Make an array of language strings available for JS.
1099 * This function calls the above function {@link string_for_js()} for each requested
1100 * string in the $identifiers array that is passed to the argument for a single module
1101 * passed in $module.
1103 * <code>
1104 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
1106 * // The above is identical to calling:
1108 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
1109 * $PAGE->requires->string_for_js('two', 'mymod');
1110 * $PAGE->requires->string_for_js('three', 'mymod', 3);
1111 * </code>
1113 * @param array $identifiers An array of desired strings
1114 * @param string $component The module to load for
1115 * @param mixed $a This can either be a single variable that gets passed as extra
1116 * information for every string or it can be an array of mixed data where the
1117 * key for the data matches that of the identifier it is meant for.
1120 public function strings_for_js($identifiers, $component, $a = null) {
1121 foreach ($identifiers as $key => $identifier) {
1122 if (is_array($a) && array_key_exists($key, $a)) {
1123 $extra = $a[$key];
1124 } else {
1125 $extra = $a;
1127 $this->string_for_js($identifier, $component, $extra);
1132 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
1134 * Make some data from PHP available to JavaScript code.
1136 * For example, if you call
1137 * <pre>
1138 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
1139 * </pre>
1140 * then in JavsScript mydata.name will be 'Moodle'.
1142 * @deprecated
1143 * @param string $variable the the name of the JavaScript variable to assign the data to.
1144 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1145 * should be considered an experimental feature.
1146 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1147 * so passing objects and arrays should work.
1148 * @param bool $inhead initialise in head
1149 * @return void
1151 public function data_for_js($variable, $data, $inhead=false) {
1152 $where = $inhead ? 'head' : 'footer';
1153 $this->jsinitvariables[$where][] = array($variable, $data);
1157 * Creates a YUI event handler.
1159 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1160 * @param string $event A valid DOM event (click, mousedown, change etc.)
1161 * @param string $function The name of the function to call
1162 * @param array $arguments An optional array of argument parameters to pass to the function
1164 public function event_handler($selector, $event, $function, array $arguments = null) {
1165 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
1169 * Returns code needed for registering of event handlers.
1170 * @return string JS code
1172 protected function get_event_handler_code() {
1173 $output = '';
1174 foreach ($this->eventhandlers as $h) {
1175 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
1177 return $output;
1181 * Get the inline JavaScript code that need to appear in a particular place.
1182 * @param bool $ondomready
1183 * @return string
1185 protected function get_javascript_code($ondomready) {
1186 $where = $ondomready ? 'ondomready' : 'normal';
1187 $output = '';
1188 if ($this->jscalls[$where]) {
1189 foreach ($this->jscalls[$where] as $data) {
1190 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
1192 if (!empty($ondomready)) {
1193 $output = " Y.on('domready', function() {\n$output\n });";
1196 return $output;
1200 * Returns js code to be executed when Y is available.
1201 * @return string
1203 protected function get_javascript_init_code() {
1204 if (count($this->jsinitcode)) {
1205 return implode("\n", $this->jsinitcode) . "\n";
1207 return '';
1211 * Returns basic YUI3 JS loading code.
1212 * YUI3 is using autoloading of both CSS and JS code.
1214 * Major benefit of this compared to standard js/csss loader is much improved
1215 * caching, better browser cache utilisation, much fewer http requests.
1217 * @param moodle_page $page
1218 * @return string
1220 protected function get_yui3lib_headcode($page) {
1221 global $CFG;
1223 $code = '';
1225 if ($this->yui3loader->combine) {
1226 if (!empty($page->theme->yuicssmodules)) {
1227 $modules = array();
1228 foreach ($page->theme->yuicssmodules as $module) {
1229 $modules[] = "$CFG->yui3version/build/$module/$module-min.css";
1231 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase.implode('&amp;', $modules).'" />';
1233 $code .= '<script type="text/javascript" src="'.$this->yui3loader->comboBase
1234 .$CFG->yui3version.'/build/simpleyui/simpleyui-min.js&amp;'
1235 .$CFG->yui3version.'/build/loader/loader-min.js"></script>';
1236 } else {
1237 if (!empty($page->theme->yuicssmodules)) {
1238 foreach ($page->theme->yuicssmodules as $module) {
1239 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.$module.'/'.$module.'-min.css" />';
1242 $code .= '<script type="text/javascript" src="'.$this->yui3loader->base.'simpleyui/simpleyui-min.js"></script>';
1243 $code .= '<script type="text/javascript" src="'.$this->yui3loader->base.'loader/loader-min.js"></script>';
1247 if ($this->yui3loader->filter === 'RAW') {
1248 $code = str_replace('-min.css', '.css', $code);
1249 $code = str_replace('-min.js', '.js', $code);
1250 } else if ($this->yui3loader->filter === 'DEBUG') {
1251 $code = str_replace('-min.css', '.css', $code);
1252 $code = str_replace('-min.js', '-debug.js', $code);
1255 return $code;
1259 * Returns html tags needed for inclusion of theme CSS.
1261 * @return string
1263 protected function get_css_code() {
1264 // First of all the theme CSS, then any custom CSS
1265 // Please note custom CSS is strongly discouraged,
1266 // because it can not be overridden by themes!
1267 // It is suitable only for things like mod/data which accepts CSS from teachers.
1268 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1270 // This line of code may look funny but it is currently required in order
1271 // to avoid MASSIVE display issues in Internet Explorer.
1272 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1273 // ignored whenever another resource is added until such time as a redraw
1274 // is forced, usually by moving the mouse over the affected element.
1275 $code = html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1277 $urls = $this->cssthemeurls + $this->cssurls;
1278 foreach ($urls as $url) {
1279 $attributes['href'] = $url;
1280 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1281 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1282 unset($attributes['id']);
1285 return $code;
1289 * Adds extra modules specified after printing of page header.
1291 * @return string
1293 protected function get_extra_modules_code() {
1294 if (empty($this->extramodules)) {
1295 return '';
1297 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1301 * Generate any HTML that needs to go inside the <head> tag.
1303 * Normally, this method is called automatically by the code that prints the
1304 * <head> tag. You should not normally need to call it in your own code.
1306 * @param moodle_page $page
1307 * @param core_renderer $renderer
1308 * @return string the HTML code to to inside the <head> tag.
1310 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1311 global $CFG;
1313 // Note: the $page and $output are not stored here because it would
1314 // create circular references in memory which prevents garbage collection.
1315 $this->init_requirements_data($page, $renderer);
1317 $output = '';
1319 // Set up the M namespace.
1320 $js = "var M = {}; M.yui = {};\n";
1322 // Capture the time now ASAP during page load. This minimises the lag when
1323 // we try to relate times on the server to times in the browser.
1324 // An example of where this is used is the quiz countdown timer.
1325 $js .= "M.pageloadstarttime = new Date();\n";
1327 // Add a subset of Moodle configuration to the M namespace.
1328 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1330 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1331 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1332 // this needs to be done before including any other script.
1333 $js .= $this->YUI_config->get_config_functions();
1334 $js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n";
1335 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1336 $js = $this->YUI_config->update_header_js($js);
1338 $output .= html_writer::script($js);
1340 // YUI3 JS and CSS need to be loaded in the header but after the YUI_config has been created.
1341 // They should be cached well by the browser.
1342 $output .= $this->get_yui3lib_headcode($page);
1344 // Add hacked jQuery support, it is not intended for standard Moodle distribution!
1345 $output .= $this->get_jquery_headcode();
1347 // Now theme CSS + custom CSS in this specific order.
1348 $output .= $this->get_css_code();
1350 // Link our main JS file, all core stuff should be there.
1351 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1353 // Add variables.
1354 if ($this->jsinitvariables['head']) {
1355 $js = '';
1356 foreach ($this->jsinitvariables['head'] as $data) {
1357 list($var, $value) = $data;
1358 $js .= js_writer::set_variable($var, $value, true);
1360 $output .= html_writer::script($js);
1363 // All the other linked things from HEAD - there should be as few as possible.
1364 if ($this->jsincludes['head']) {
1365 foreach ($this->jsincludes['head'] as $url) {
1366 $output .= html_writer::script('', $url);
1370 // Mark head sending done, it is not possible to anything there.
1371 $this->headdone = true;
1373 return $output;
1377 * Generate any HTML that needs to go at the start of the <body> tag.
1379 * Normally, this method is called automatically by the code that prints the
1380 * <head> tag. You should not normally need to call it in your own code.
1382 * @return string the HTML code to go at the start of the <body> tag.
1384 public function get_top_of_body_code() {
1385 // First the skip links.
1386 $links = '';
1387 $attributes = array('class'=>'skip');
1388 foreach ($this->skiplinks as $url => $text) {
1389 $attributes['href'] = '#' . $url;
1390 $links .= html_writer::tag('a', $text, $attributes);
1392 $output = html_writer::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1394 // Then the clever trick for hiding of things not needed when JS works.
1395 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1396 $this->topofbodydone = true;
1397 return $output;
1401 * Generate any HTML that needs to go at the end of the page.
1403 * Normally, this method is called automatically by the code that prints the
1404 * page footer. You should not normally need to call it in your own code.
1406 * @return string the HTML code to to at the end of the page.
1408 public function get_end_code() {
1409 global $CFG;
1411 // Add other requested modules.
1412 $output = $this->get_extra_modules_code();
1414 // All the other linked scripts - there should be as few as possible.
1415 if ($this->jsincludes['footer']) {
1416 foreach ($this->jsincludes['footer'] as $url) {
1417 $output .= html_writer::script('', $url);
1421 // Add all needed strings.
1422 if (!empty($this->stringsforjs)) {
1423 $strings = array();
1424 foreach ($this->stringsforjs as $component=>$v) {
1425 foreach($v as $indentifier => $langstring) {
1426 $strings[$component][$indentifier] = $langstring->out();
1429 $output .= html_writer::script(js_writer::set_variable('M.str', $strings));
1432 // Add variables.
1433 if ($this->jsinitvariables['footer']) {
1434 $js = '';
1435 foreach ($this->jsinitvariables['footer'] as $data) {
1436 list($var, $value) = $data;
1437 $js .= js_writer::set_variable($var, $value, true);
1439 $output .= html_writer::script($js);
1442 $inyuijs = $this->get_javascript_code(false);
1443 $ondomreadyjs = $this->get_javascript_code(true);
1444 $jsinit = $this->get_javascript_init_code();
1445 $handlersjs = $this->get_event_handler_code();
1447 // There is no global Y, make sure it is available in your scope.
1448 $js = "YUI().use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1450 $output .= html_writer::script($js);
1452 return $output;
1456 * Have we already output the code in the <head> tag?
1458 * @return bool
1460 public function is_head_done() {
1461 return $this->headdone;
1465 * Have we already output the code at the start of the <body> tag?
1467 * @return bool
1469 public function is_top_of_body_done() {
1470 return $this->topofbodydone;
1475 * This class represents the YUI configuration.
1477 * @copyright 2013 Andrew Nicols
1478 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1479 * @since Moodle 2.5
1480 * @package core
1481 * @category output
1483 class YUI_config {
1485 * These settings must be public so that when the object is converted to json they are exposed.
1486 * Note: Some of these are camelCase because YUI uses camelCase variable names.
1488 * The settings are described and documented in the YUI API at:
1489 * - http://yuilibrary.com/yui/docs/api/classes/config.html
1490 * - http://yuilibrary.com/yui/docs/api/classes/Loader.html
1492 public $debug = false;
1493 public $base;
1494 public $comboBase;
1495 public $combine;
1496 public $filter = null;
1497 public $insertBefore = 'firstthemesheet';
1498 public $groups = array();
1499 public $modules = array();
1502 * @var array List of functions used by the YUI Loader group pattern recognition.
1504 protected $jsconfigfunctions = array();
1507 * Create a new group within the YUI_config system.
1509 * @param String $name The name of the group. This must be unique and
1510 * not previously used.
1511 * @param Array $config The configuration for this group.
1512 * @return void
1514 public function add_group($name, $config) {
1515 if (isset($this->groups[$name])) {
1516 throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
1518 $this->groups[$name] = $config;
1522 * Update an existing group configuration
1524 * Note, any existing configuration for that group will be wiped out.
1525 * This includes module configuration.
1527 * @param String $name The name of the group. This must be unique and
1528 * not previously used.
1529 * @param Array $config The configuration for this group.
1530 * @return void
1532 public function update_group($name, $config) {
1533 if (!isset($this->groups[$name])) {
1534 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.');
1536 $this->groups[$name] = $config;
1540 * Set the value of a configuration function used by the YUI Loader's pattern testing.
1542 * Only the body of the function should be passed, and not the whole function wrapper.
1544 * The JS function your write will be passed a single argument 'name' containing the
1545 * name of the module being loaded.
1547 * @param $function String the body of the JavaScript function. This should be used i
1548 * @return String the name of the function to use in the group pattern configuration.
1550 public function set_config_function($function) {
1551 $configname = 'yui' . (count($this->jsconfigfunctions) + 1) . 'ConfigFn';
1552 if (isset($this->jsconfigfunctions[$configname])) {
1553 throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
1555 $this->jsconfigfunctions[$configname] = $function;
1556 return '@' . $configname . '@';
1560 * Retrieve the list of JavaScript functions for YUI_config groups.
1562 * @return String The complete set of config functions
1564 public function get_config_functions() {
1565 $configfunctions = '';
1566 foreach ($this->jsconfigfunctions as $functionname => $function) {
1567 $configfunctions .= "var {$functionname} = function(me) {";
1568 $configfunctions .= $function;
1569 $configfunctions .= "};\n";
1571 return $configfunctions;
1575 * Update the header JavaScript with any required modification for the YUI Loader.
1577 * @param $js String The JavaScript to manipulate.
1578 * @return String the modified JS string.
1580 public function update_header_js($js) {
1581 // Update the names of the the configFn variables.
1582 // The PHP json_encode function cannot handle literal names so we have to wrap
1583 // them in @ and then replace them with literals of the same function name.
1584 foreach ($this->jsconfigfunctions as $functionname => $function) {
1585 $js = str_replace('"@' . $functionname . '@"', $functionname, $js);
1587 return $js;
1591 * Add configuration for a specific module.
1593 * @param String $name The name of the module to add configuration for.
1594 * @param Array $config The configuration for the specified module.
1595 * @param String $group The name of the group to add configuration for.
1596 * If not specified, then this module is added to the global
1597 * configuration.
1598 * @return void
1600 public function add_module_config($name, $config, $group = null) {
1601 if ($group) {
1602 if (!isset($this->groups[$name])) {
1603 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.');
1605 if (!isset($this->groups[$group]['modules'])) {
1606 $this->groups[$group]['modules'] = array();
1608 $modules = &$this->groups[$group]['modules'];
1609 } else {
1610 $modules = &$this->modules;
1612 $modules[$name] = $config;
1616 * Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
1618 * If js caching is disabled, metadata will not be served causing YUI to calculate
1619 * module dependencies as each module is loaded.
1621 * If metadata does not exist it will be created and stored in a MUC entry.
1623 * @return void
1625 public function add_moodle_metadata() {
1626 global $CFG;
1627 if (!isset($this->groups['moodle'])) {
1628 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.');
1631 if (!isset($this->groups['moodle']['modules'])) {
1632 $this->groups['moodle']['modules'] = array();
1635 $cache = cache::make('core', 'yuimodules');
1636 if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
1637 $metadata = array();
1638 $cache->delete('metadata');
1639 } else {
1640 // Attempt to get the metadata from the cache.
1641 if (!$metadata = $cache->get('metadata')) {
1642 $metadata = $this->get_moodle_metadata();
1643 $cache->set('metadata', $metadata);
1647 // Merge with any metadata added specific to this page which was added manually.
1648 $this->groups['moodle']['modules'] = array_merge($this->groups['moodle']['modules'],
1649 $metadata);
1653 * Determine the module metadata for all moodle YUI modules.
1655 * This works through all modules capable of serving YUI modules, and attempts to get
1656 * metadata for each of those modules.
1658 * @return Array of module metadata
1660 private function get_moodle_metadata() {
1661 $moodlemodules = array();
1662 // Core isn't a plugin type or subsystem - handle it seperately.
1663 if ($module = $this->get_moodle_path_metadata(get_component_directory('core'))) {
1664 $moodlemodules = array_merge($moodlemodules, $module);
1667 // Handle other core subsystems.
1668 $subsystems = get_core_subsystems();
1669 foreach ($subsystems as $subsystem => $path) {
1670 if (is_null($path)) {
1671 continue;
1673 $path = get_component_directory($subsystem);
1674 if ($module = $this->get_moodle_path_metadata($path)) {
1675 $moodlemodules = array_merge($moodlemodules, $module);
1679 // And finally the plugins.
1680 $plugintypes = get_plugin_types();
1681 foreach ($plugintypes as $plugintype => $pathroot) {
1682 $pluginlist = get_plugin_list($plugintype);
1683 foreach ($pluginlist as $plugin => $path) {
1684 if ($module = $this->get_moodle_path_metadata($path)) {
1685 $moodlemodules = array_merge($moodlemodules, $module);
1690 return $moodlemodules;
1694 * Helper function process and return the YUI metadata for all of the modules under the specified path.
1696 * @param String $path the UNC path to the YUI src directory.
1697 * @return Array the complete array for frankenstyle directory.
1699 private function get_moodle_path_metadata($path) {
1700 // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
1701 $baseyui = $path . '/yui/src';
1702 $modules = array();
1703 if (is_dir($baseyui)) {
1704 $items = new DirectoryIterator($baseyui);
1705 foreach ($items as $item) {
1706 if ($item->isDot() or !$item->isDir()) {
1707 continue;
1709 $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
1710 if (!is_readable($metafile)) {
1711 continue;
1713 $metadata = file_get_contents($metafile);
1714 $modules = array_merge($modules, (array) json_decode($metadata));
1717 return $modules;
1722 * Invalidate all server and client side JS caches.
1724 function js_reset_all_caches() {
1725 global $CFG;
1726 require_once("$CFG->libdir/filelib.php");
1728 $next = time();
1729 if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
1730 // This resolves problems when reset is requested repeatedly within 1s,
1731 // the < 1h condition prevents accidental switching to future dates
1732 // because we might not recover from it.
1733 $next = $CFG->jsrev+1;
1736 set_config('jsrev', $next);
1737 fulldelete("$CFG->cachedir/js");