Merge branch 'MDL-40255_M25' of git://github.com/lazydaisy/moodle into MOODLE_25_STABLE
[moodle.git] / lib / outputrequirementslib.php
blob5994d37061fda784bc333738ec25e1c482701e29
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;
278 // Accessibility stuff.
279 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
281 // Add strings used on many pages.
282 $this->string_for_js('confirmation', 'admin');
283 $this->string_for_js('cancel', 'moodle');
284 $this->string_for_js('yes', 'moodle');
286 // Alter links in top frame to break out of frames.
287 if ($page->pagelayout === 'frametop') {
288 $this->js_init_call('M.util.init_frametop');
291 // Include block drag/drop if editing is on
292 if ($page->user_is_editing()) {
293 $params = array(
294 'courseid' => $page->course->id,
295 'pagetype' => $page->pagetype,
296 'pagelayout' => $page->pagelayout,
297 'subpage' => $page->subpage,
298 'regions' => $page->blocks->get_regions(),
299 'contextid' => $page->context->id,
301 if (!empty($page->cm->id)) {
302 $params['cmid'] = $page->cm->id;
304 $page->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
309 * Ensure that the specified JavaScript file is linked to from this page.
311 * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
312 * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
314 * By default the link is put at the end of the page, since this gives best page-load performance.
316 * Even if a particular script is requested more than once, it will only be linked
317 * to once.
319 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
320 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
321 * @param bool $inhead initialise in head
323 public function js($url, $inhead = false) {
324 $url = $this->js_fix_url($url);
325 $where = $inhead ? 'head' : 'footer';
326 $this->jsincludes[$where][$url->out()] = $url;
330 * Request inclusion of jQuery library in the page.
332 * NOTE: this should not be used in official Moodle distribution!
334 * We are going to bundle jQuery 1.9.x until we drop support
335 * all support for IE 6-8. Use $PAGE->requires->jquery_plugin('migrate')
336 * for code written for earlier jQuery versions.
338 * {@see http://docs.moodle.org/dev/jQuery}
340 public function jquery() {
341 $this->jquery_plugin('jquery');
345 * Request inclusion of jQuery plugin.
347 * NOTE: this should not be used in official Moodle distribution!
349 * jQuery plugins are located in plugin/jquery/* subdirectory,
350 * plugin/jquery/plugins.php lists all available plugins.
352 * Included core plugins:
353 * - jQuery UI
354 * - jQuery Migrate (useful for code written for previous UI version)
356 * Add-ons may include extra jQuery plugins in jquery/ directory,
357 * plugins.php file defines the mapping between plugin names and
358 * necessary page includes.
360 * Examples:
361 * <code>
362 * // file: mod/xxx/view.php
363 * $PAGE->requires->jquery();
364 * $PAGE->requires->jquery_plugin('ui');
365 * $PAGE->requires->jquery_plugin('ui-css');
366 * </code>
368 * <code>
369 * // file: theme/yyy/lib.php
370 * function theme_yyy_page_init(moodle_page $page) {
371 * $page->requires->jquery();
372 * $page->requires->jquery_plugin('ui');
373 * $page->requires->jquery_plugin('ui-css');
375 * </code>
377 * <code>
378 * // file: blocks/zzz/block_zzz.php
379 * public function get_required_javascript() {
380 * parent::get_required_javascript();
381 * $this->page->requires->jquery();
382 * $page->requires->jquery_plugin('ui');
383 * $page->requires->jquery_plugin('ui-css');
385 * </code>
387 * {@see http://docs.moodle.org/dev/jQuery}
389 * @param string $plugin name of the jQuery plugin as defined in jquery/plugins.php
390 * @param string $component name of the component
391 * @return bool success
393 public function jquery_plugin($plugin, $component = 'core') {
394 global $CFG;
396 if ($this->headdone) {
397 debugging('Can not add jQuery plugins after starting page output!');
398 return false;
401 if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css', 'migrate'))) {
402 debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER);
403 $component = 'core';
404 } else if ($component !== 'core' and strpos($component, '_') === false) {
405 // Let's normalise the legacy activity names, Frankenstyle rulez!
406 $component = 'mod_' . $component;
409 if (empty($this->jqueryplugins) and ($component !== 'core' or $plugin !== 'jquery')) {
410 // Make sure the jQuery itself is always loaded first,
411 // the order of all other plugins depends on order of $PAGE_>requires->.
412 $this->jquery_plugin('jquery', 'core');
415 if (isset($this->jqueryplugins[$plugin])) {
416 // No problem, we already have something, first Moodle plugin to register the jQuery plugin wins.
417 return true;
420 $componentdir = get_component_directory($component);
421 if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
422 debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER);
423 return false;
426 $plugins = array();
427 require("$componentdir/jquery/plugins.php");
429 if (!isset($plugins[$plugin])) {
430 debugging("jQuery plugin '$plugin' can not be found in component '$component'.", DEBUG_DEVELOPER);
431 return false;
434 $this->jqueryplugins[$plugin] = new stdClass();
435 $this->jqueryplugins[$plugin]->plugin = $plugin;
436 $this->jqueryplugins[$plugin]->component = $component;
437 $this->jqueryplugins[$plugin]->urls = array();
439 foreach ($plugins[$plugin]['files'] as $file) {
440 if (debugging('', DEBUG_DEVELOPER)) {
441 if (!file_exists("$componentdir/jquery/$file")) {
442 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
443 continue;
445 $file = str_replace('.min.css', '.css', $file);
446 $file = str_replace('.min.js', '.js', $file);
448 if (!file_exists("$componentdir/jquery/$file")) {
449 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
450 continue;
452 if (!empty($CFG->slasharguments)) {
453 $url = new moodle_url("$CFG->httpswwwroot/theme/jquery.php");
454 $url->set_slashargument("/$component/$file");
456 } else {
457 // This is not really good, we need slasharguments for relative links, this means no caching...
458 $path = realpath("$componentdir/jquery/$file");
459 if (strpos($path, $CFG->dirroot) === 0) {
460 $url = $CFG->httpswwwroot.preg_replace('/^'.preg_quote($CFG->dirroot, '/').'/', '', $path);
461 $url = new moodle_url($url);
462 } else {
463 // Bad luck, fix your server!
464 debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
465 continue;
468 $this->jqueryplugins[$plugin]->urls[] = $url;
471 return true;
475 * Request replacement of one jQuery plugin by another.
477 * This is useful when themes want to replace the jQuery UI theme,
478 * the problem is that theme can not prevent others from including the core ui-css plugin.
480 * Example:
481 * 1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
482 * 2/ write theme/yourtheme/jquery/plugins.php
483 * 3/ init jQuery from theme
485 * <code>
486 * // file theme/yourtheme/lib.php
487 * function theme_yourtheme_page_init($page) {
488 * $page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
489 * $page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
491 * </code>
493 * This code prevents loading of standard 'ui-css' which my be requested by other plugins,
494 * the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
496 * {@see http://docs.moodle.org/dev/jQuery}
498 * @param string $oldplugin original plugin
499 * @param string $newplugin the replacement
501 public function jquery_override_plugin($oldplugin, $newplugin) {
502 if ($this->headdone) {
503 debugging('Can not override jQuery plugins after starting page output!');
504 return;
506 $this->jquerypluginoverrides[$oldplugin] = $newplugin;
510 * Return jQuery related markup for page start.
511 * @return string
513 protected function get_jquery_headcode() {
514 if (empty($this->jqueryplugins['jquery'])) {
515 // If nobody requested jQuery then do not bother to load anything.
516 // This may be useful for themes that want to override 'ui-css' only if requested by something else.
517 return '';
520 $included = array();
521 $urls = array();
523 foreach ($this->jqueryplugins as $name => $unused) {
524 if (isset($included[$name])) {
525 continue;
527 if (array_key_exists($name, $this->jquerypluginoverrides)) {
528 // The following loop tries to resolve the replacements,
529 // use max 100 iterations to prevent infinite loop resulting
530 // in blank page.
531 $cyclic = true;
532 $oldname = $name;
533 for ($i=0; $i<100; $i++) {
534 $name = $this->jquerypluginoverrides[$name];
535 if (!array_key_exists($name, $this->jquerypluginoverrides)) {
536 $cyclic = false;
537 break;
540 if ($cyclic) {
541 // We can not do much with cyclic references here, let's use the old plugin.
542 $name = $oldname;
543 debugging("Cyclic overrides detected for jQuery plugin '$name'");
545 } else if (empty($name)) {
546 // Developer requested removal of the plugin.
547 continue;
549 } else if (!isset($this->jqueryplugins[$name])) {
550 debugging("Unknown jQuery override plugin '$name' detected");
551 $name = $oldname;
553 } else if (isset($included[$name])) {
554 // The plugin was already included, easy.
555 continue;
559 $plugin = $this->jqueryplugins[$name];
560 $urls = array_merge($urls, $plugin->urls);
561 $included[$name] = true;
564 $output = '';
565 $attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
566 foreach ($urls as $url) {
567 if (preg_match('/\.js$/', $url)) {
568 $output .= html_writer::script('', $url);
569 } else if (preg_match('/\.css$/', $url)) {
570 $attributes['href'] = $url;
571 $output .= html_writer::empty_tag('link', $attributes) . "\n";
575 return $output;
579 * This method was used to load YUI2 libraries into global scope,
580 * use YUI 2in3 instead. Every YUI2 module is represented as a yui2-*
581 * sandboxed module in YUI3 code via Y.YUI2. property.
583 * {@see http://tracker.moodle.org/browse/MDL-34741}
585 * @param string|array $libname
586 * @deprecated since 2.4
588 public function yui2_lib($libname) {
589 throw new coding_exception('PAGE->yui2_lib() is not available any more, use YUI 2in3 instead, see MDL-34741 for more information.');
593 * Returns the actual url through which a script is served.
595 * @param moodle_url|string $url full moodle url, or shortened path to script
596 * @return moodle_url
598 protected function js_fix_url($url) {
599 global $CFG;
601 if ($url instanceof moodle_url) {
602 return $url;
603 } else if (strpos($url, '/') === 0) {
604 // Fix the admin links if needed.
605 if ($CFG->admin !== 'admin') {
606 if (strpos($url, "/admin/") === 0) {
607 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
610 if (debugging()) {
611 // Check file existence only when in debug mode.
612 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
613 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
616 if (!empty($CFG->cachejs) and !empty($CFG->jsrev) and $CFG->jsrev > 0 and substr($url, -3) === '.js') {
617 if (empty($CFG->slasharguments)) {
618 return new moodle_url($CFG->httpswwwroot.'/lib/javascript.php', array('rev'=>$CFG->jsrev, 'jsfile'=>$url));
619 } else {
620 $returnurl = new moodle_url($CFG->httpswwwroot.'/lib/javascript.php');
621 $returnurl->set_slashargument('/'.$CFG->jsrev.$url);
622 return $returnurl;
624 } else {
625 return new moodle_url($CFG->httpswwwroot.$url);
627 } else {
628 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
633 * Find out if JS module present and return details.
635 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
636 * @return array description of module or null if not found
638 protected function find_module($component) {
639 global $CFG, $PAGE;
641 $module = null;
643 if (strpos($component, 'core_') === 0) {
644 // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
645 // so that we do nto have to repeat the definition of these modules over and over again.
646 switch($component) {
647 case 'core_filepicker':
648 $module = array('name' => 'core_filepicker',
649 'fullpath' => '/repository/filepicker.js',
650 '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'),
651 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
652 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
653 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
654 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
655 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
656 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
657 array('referencesexist', 'repository')
659 break;
660 case 'core_comment':
661 $module = array('name' => 'core_comment',
662 'fullpath' => '/comment/comment.js',
663 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
664 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
666 break;
667 case 'core_role':
668 $module = array('name' => 'core_role',
669 'fullpath' => '/admin/roles/module.js',
670 'requires' => array('node', 'cookie'));
671 break;
672 case 'core_completion':
673 $module = array('name' => 'core_completion',
674 'fullpath' => '/course/completion.js');
675 break;
676 case 'core_dock':
677 $module = array('name' => 'core_dock',
678 'fullpath' => '/blocks/dock.js',
679 'requires' => array('base', 'node', 'event-custom', 'event-mouseenter', 'event-resize', 'escape'),
680 'strings' => array(array('addtodock', 'block'),array('undockitem', 'block'),array('dockblock', 'block'),
681 array('undockblock', 'block'),array('undockall', 'block'),array('thisdirectionvertical', 'langconfig'),
682 array('hidedockpanel', 'block'),array('hidepanel', 'block')
684 break;
685 case 'core_message':
686 $module = array('name' => 'core_message',
687 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
688 'fullpath' => '/message/module.js');
689 break;
690 case 'core_group':
691 $module = array('name' => 'core_group',
692 'fullpath' => '/group/module.js',
693 'requires' => array('node', 'overlay', 'event-mouseenter'));
694 break;
695 case 'core_question_engine':
696 $module = array('name' => 'core_question_engine',
697 'fullpath' => '/question/qengine.js',
698 'requires' => array('node', 'event'));
699 break;
700 case 'core_rating':
701 $module = array('name' => 'core_rating',
702 'fullpath' => '/rating/module.js',
703 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
704 break;
705 case 'core_dndupload':
706 $module = array('name' => 'core_dndupload',
707 'fullpath' => '/lib/form/dndupload.js',
708 'requires' => array('node', 'event', 'json', 'core_filepicker'),
709 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
710 array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesforfile', 'moodle'),
711 array('maxareabytesreached', 'moodle')
713 break;
716 } else {
717 if ($dir = get_component_directory($component)) {
718 if (file_exists("$dir/module.js")) {
719 if (strpos($dir, $CFG->dirroot.'/') === 0) {
720 $dir = substr($dir, strlen($CFG->dirroot));
721 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
727 return $module;
731 * Append YUI3 module to default YUI3 JS loader.
732 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
734 * @param string|array $module name of module (details are autodetected), or full module specification as array
735 * @return void
737 public function js_module($module) {
738 global $CFG;
740 if (empty($module)) {
741 throw new coding_exception('Missing YUI3 module name or full description.');
744 if (is_string($module)) {
745 $module = $this->find_module($module);
748 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
749 throw new coding_exception('Missing YUI3 module details.');
752 // Don't load this module if we already have, no need to!
753 if ($this->js_module_loaded($module['name'])) {
754 if (debugging('', DEBUG_DEVELOPER)) {
755 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
757 return;
760 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
761 // Add all needed strings.
762 if (!empty($module['strings'])) {
763 foreach ($module['strings'] as $string) {
764 $identifier = $string[0];
765 $component = isset($string[1]) ? $string[1] : 'moodle';
766 $a = isset($string[2]) ? $string[2] : null;
767 $this->string_for_js($identifier, $component, $a);
770 unset($module['strings']);
772 // Process module requirements and attempt to load each. This allows
773 // moodle modules to require each other.
774 if (!empty($module['requires'])){
775 foreach ($module['requires'] as $requirement) {
776 $rmodule = $this->find_module($requirement);
777 if (is_array($rmodule)) {
778 $this->js_module($rmodule);
783 if ($this->headdone) {
784 $this->extramodules[$module['name']] = $module;
785 } else {
786 $this->YUI_config->add_module_config($module['name'], $module);
788 if (debugging('', DEBUG_DEVELOPER)) {
789 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces)) {
790 $this->debug_moduleloadstacktraces[$module['name']] = array();
792 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
797 * Returns true if the module has already been loaded.
799 * @param string|array $module
800 * @return bool True if the module has already been loaded
802 protected function js_module_loaded($module) {
803 if (is_string($module)) {
804 $modulename = $module;
805 } else {
806 $modulename = $module['name'];
808 return array_key_exists($modulename, $this->YUI_config->modules) ||
809 array_key_exists($modulename, $this->extramodules);
813 * Returns the stacktraces from loading js modules.
814 * @return array
816 public function get_loaded_modules() {
817 return $this->debug_moduleloadstacktraces;
821 * Ensure that the specified CSS file is linked to from this page.
823 * Because stylesheet links must go in the <head> part of the HTML, you must call
824 * this function before {@link get_head_code()} is called. That normally means before
825 * the call to print_header. If you call it when it is too late, an exception
826 * will be thrown.
828 * Even if a particular style sheet is requested more than once, it will only
829 * be linked to once.
831 * Please note use of this feature is strongly discouraged,
832 * it is suitable only for places where CSS is submitted directly by teachers.
833 * (Students must not be allowed to submit any external CSS because it may
834 * contain embedded javascript!). Example of correct use is mod/data.
836 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
837 * For example:
838 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
840 public function css($stylesheet) {
841 global $CFG;
843 if ($this->headdone) {
844 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
847 if ($stylesheet instanceof moodle_url) {
848 // ok
849 } else if (strpos($stylesheet, '/') === 0) {
850 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
851 } else {
852 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
855 $this->cssurls[$stylesheet->out()] = $stylesheet;
859 * Add theme stylesheet to page - do not use from plugin code,
860 * this should be called only from the core renderer!
862 * @param moodle_url $stylesheet
863 * @return void
865 public function css_theme(moodle_url $stylesheet) {
866 $this->cssthemeurls[] = $stylesheet;
870 * Ensure that a skip link to a given target is printed at the top of the <body>.
872 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
873 * will be thrown). That normally means you must call this before the call to print_header.
875 * If you ask for a particular skip link to be printed, it is then your responsibility
876 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
877 * page, so that the skip link goes somewhere.
879 * Even if a particular skip link is requested more than once, only one copy of it will be output.
881 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
882 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
884 public function skip_link_to($target, $linktext) {
885 if ($this->topofbodydone) {
886 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
887 return;
889 $this->skiplinks[$target] = $linktext;
893 * !!!DEPRECATED!!! please use js_init_call() if possible
894 * Ensure that the specified JavaScript function is called from an inline script
895 * somewhere on this page.
897 * By default the call will be put in a script tag at the
898 * end of the page after initialising Y instance, since this gives best page-load
899 * performance and allows you to use YUI3 library.
901 * If you request that a particular function is called several times, then
902 * that is what will happen (unlike linking to a CSS or JS file, where only
903 * one link will be output).
905 * The main benefit of the method is the automatic encoding of all function parameters.
907 * @deprecated
909 * @param string $function the name of the JavaScritp function to call. Can
910 * be a compound name like 'Y.Event.purgeElement'. Can also be
911 * used to create and object by using a 'function name' like 'new user_selector'.
912 * @param array $arguments and array of arguments to be passed to the function.
913 * When generating the function call, this will be escaped using json_encode,
914 * so passing objects and arrays should work.
915 * @param bool $ondomready If tru the function is only called when the dom is
916 * ready for manipulation.
917 * @param int $delay The delay before the function is called.
919 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
920 $where = $ondomready ? 'ondomready' : 'normal';
921 $this->jscalls[$where][] = array($function, $arguments, $delay);
925 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
927 * @deprecated DO NOT USE
929 * @param string|array $modules One or more gallery modules to require
930 * @param string $version
931 * @param string $function
932 * @param array $arguments
933 * @param bool $ondomready
935 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
936 global $CFG;
937 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER);
938 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
942 * Creates a JavaScript function call that requires one or more modules to be loaded.
944 * This function can be used to include all of the standard YUI module types within JavaScript:
945 * - YUI3 modules [node, event, io]
946 * - YUI2 modules [yui2-*]
947 * - Moodle modules [moodle-*]
948 * - Gallery modules [gallery-*]
950 * @param array|string $modules One or more modules
951 * @param string $function The function to call once modules have been loaded
952 * @param array $arguments An array of arguments to pass to the function
953 * @param string $galleryversion The gallery version to use
954 * @param bool $ondomready
956 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
957 global $CFG;
959 if (!$galleryversion) {
960 $galleryversion = '2010.04.08-12-35';
963 if (!is_array($modules)) {
964 $modules = array($modules);
966 if (empty($CFG->useexternalyui)) {
967 // We need to set the M.yui.galleryversion to the correct version
968 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
969 } else {
970 // Set Y's config.gallery to the version
971 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
973 $jscode .= 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
974 if ($ondomready) {
975 $jscode = "Y.on('domready', function() { $jscode });";
977 $this->jsinitcode[] = $jscode;
981 * Ensure that the specified JavaScript function is called from an inline script
982 * from page footer.
984 * @param string $function the name of the JavaScritp function to with init code,
985 * usually something like 'M.mod_mymodule.init'
986 * @param array $extraarguments and array of arguments to be passed to the function.
987 * The first argument is always the YUI3 Y instance with all required dependencies
988 * already loaded.
989 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
990 * @param array $module JS module specification array
992 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
993 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
994 if (!$module) {
995 // Detect module automatically.
996 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
997 $module = $this->find_module($matches[1]);
1001 $this->js_init_code($jscode, $ondomready, $module);
1005 * Add short static javascript code fragment to page footer.
1006 * This is intended primarily for loading of js modules and initialising page layout.
1007 * Ideally the JS code fragment should be stored in plugin renderer so that themes
1008 * may override it.
1010 * @param string $jscode
1011 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1012 * @param array $module JS module specification array
1014 public function js_init_code($jscode, $ondomready = false, array $module = null) {
1015 $jscode = trim($jscode, " ;\n"). ';';
1017 if ($module) {
1018 $this->js_module($module);
1019 $modulename = $module['name'];
1020 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
1023 if ($ondomready) {
1024 $jscode = "Y.on('domready', function() { $jscode });";
1027 $this->jsinitcode[] = $jscode;
1031 * Make a language string available to JavaScript.
1033 * All the strings will be available in a M.str object in the global namespace.
1034 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
1035 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
1036 * equivalent in the current language.
1038 * The arguments to this function are just like the arguments to get_string
1039 * except that $component is not optional, and there are some aspects to consider
1040 * when the string contains {$a} placeholder.
1042 * If the string does not contain any {$a} placeholder, you can simply use
1043 * M.str.component.identifier to obtain it. If you prefer, you can call
1044 * M.util.get_string(identifier, component) to get the same result.
1046 * If you need to use {$a} placeholders, there are two options. Either the
1047 * placeholder should be substituted in PHP on server side or it should
1048 * be substituted in Javascript at client side.
1050 * To substitute the placeholder at server side, just provide the required
1051 * value for the placeholder when you require the string. Because each string
1052 * is only stored once in the JavaScript (based on $identifier and $module)
1053 * you cannot get the same string with two different values of $a. If you try,
1054 * an exception will be thrown. Once the placeholder is substituted, you can
1055 * use M.str or M.util.get_string() as shown above:
1057 * // Require the string in PHP and replace the placeholder.
1058 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
1059 * // Use the result of the substitution in Javascript.
1060 * alert(M.str.moodle.fullnamedisplay);
1062 * To substitute the placeholder at client side, use M.util.get_string()
1063 * function. It implements the same logic as {@link get_string()}:
1065 * // Require the string in PHP but keep {$a} as it is.
1066 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
1067 * // Provide the values on the fly in Javascript.
1068 * user = { firstname : 'Harry', lastname : 'Potter' }
1069 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
1071 * If you do need the same string expanded with different $a values in PHP
1072 * on server side, then the solution is to put them in your own data structure
1073 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
1075 * @param string $identifier the desired string.
1076 * @param string $component the language file to look in.
1077 * @param mixed $a any extra data to add into the string (optional).
1079 public function string_for_js($identifier, $component, $a = null) {
1080 if (!$component) {
1081 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
1083 if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
1084 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
1085 "from lang file '$component' with different \$a parameter?");
1087 if (!isset($this->stringsforjs[$component][$identifier])) {
1088 $this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
1089 $this->stringsforjs_as[$component][$identifier] = $a;
1094 * Make an array of language strings available for JS.
1096 * This function calls the above function {@link string_for_js()} for each requested
1097 * string in the $identifiers array that is passed to the argument for a single module
1098 * passed in $module.
1100 * <code>
1101 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
1103 * // The above is identical to calling:
1105 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
1106 * $PAGE->requires->string_for_js('two', 'mymod');
1107 * $PAGE->requires->string_for_js('three', 'mymod', 3);
1108 * </code>
1110 * @param array $identifiers An array of desired strings
1111 * @param string $component The module to load for
1112 * @param mixed $a This can either be a single variable that gets passed as extra
1113 * information for every string or it can be an array of mixed data where the
1114 * key for the data matches that of the identifier it is meant for.
1117 public function strings_for_js($identifiers, $component, $a = null) {
1118 foreach ($identifiers as $key => $identifier) {
1119 if (is_array($a) && array_key_exists($key, $a)) {
1120 $extra = $a[$key];
1121 } else {
1122 $extra = $a;
1124 $this->string_for_js($identifier, $component, $extra);
1129 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
1131 * Make some data from PHP available to JavaScript code.
1133 * For example, if you call
1134 * <pre>
1135 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
1136 * </pre>
1137 * then in JavsScript mydata.name will be 'Moodle'.
1139 * @deprecated
1140 * @param string $variable the the name of the JavaScript variable to assign the data to.
1141 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1142 * should be considered an experimental feature.
1143 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1144 * so passing objects and arrays should work.
1145 * @param bool $inhead initialise in head
1146 * @return void
1148 public function data_for_js($variable, $data, $inhead=false) {
1149 $where = $inhead ? 'head' : 'footer';
1150 $this->jsinitvariables[$where][] = array($variable, $data);
1154 * Creates a YUI event handler.
1156 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1157 * @param string $event A valid DOM event (click, mousedown, change etc.)
1158 * @param string $function The name of the function to call
1159 * @param array $arguments An optional array of argument parameters to pass to the function
1161 public function event_handler($selector, $event, $function, array $arguments = null) {
1162 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
1166 * Returns code needed for registering of event handlers.
1167 * @return string JS code
1169 protected function get_event_handler_code() {
1170 $output = '';
1171 foreach ($this->eventhandlers as $h) {
1172 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
1174 return $output;
1178 * Get the inline JavaScript code that need to appear in a particular place.
1179 * @param bool $ondomready
1180 * @return string
1182 protected function get_javascript_code($ondomready) {
1183 $where = $ondomready ? 'ondomready' : 'normal';
1184 $output = '';
1185 if ($this->jscalls[$where]) {
1186 foreach ($this->jscalls[$where] as $data) {
1187 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
1189 if (!empty($ondomready)) {
1190 $output = " Y.on('domready', function() {\n$output\n });";
1193 return $output;
1197 * Returns js code to be executed when Y is available.
1198 * @return string
1200 protected function get_javascript_init_code() {
1201 if (count($this->jsinitcode)) {
1202 return implode("\n", $this->jsinitcode) . "\n";
1204 return '';
1208 * Returns basic YUI3 JS loading code.
1209 * YUI3 is using autoloading of both CSS and JS code.
1211 * Major benefit of this compared to standard js/csss loader is much improved
1212 * caching, better browser cache utilisation, much fewer http requests.
1214 * @param moodle_page $page
1215 * @return string
1217 protected function get_yui3lib_headcode($page) {
1218 global $CFG;
1220 $code = '';
1222 if ($this->yui3loader->combine) {
1223 if (!empty($page->theme->yuicssmodules)) {
1224 $modules = array();
1225 foreach ($page->theme->yuicssmodules as $module) {
1226 $modules[] = "$CFG->yui3version/build/$module/$module-min.css";
1228 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase.implode('&amp;', $modules).'" />';
1230 $code .= '<script type="text/javascript" src="'.$this->yui3loader->comboBase
1231 .$CFG->yui3version.'/build/simpleyui/simpleyui-min.js&amp;'
1232 .$CFG->yui3version.'/build/loader/loader-min.js"></script>';
1233 } else {
1234 if (!empty($page->theme->yuicssmodules)) {
1235 foreach ($page->theme->yuicssmodules as $module) {
1236 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.$module.'/'.$module.'-min.css" />';
1239 $code .= '<script type="text/javascript" src="'.$this->yui3loader->base.'simpleyui/simpleyui-min.js"></script>';
1240 $code .= '<script type="text/javascript" src="'.$this->yui3loader->base.'loader/loader-min.js"></script>';
1244 if ($this->yui3loader->filter === 'RAW') {
1245 $code = str_replace('-min.css', '.css', $code);
1246 $code = str_replace('-min.js', '.js', $code);
1247 } else if ($this->yui3loader->filter === 'DEBUG') {
1248 $code = str_replace('-min.css', '.css', $code);
1249 $code = str_replace('-min.js', '-debug.js', $code);
1252 return $code;
1256 * Returns html tags needed for inclusion of theme CSS.
1258 * @return string
1260 protected function get_css_code() {
1261 // First of all the theme CSS, then any custom CSS
1262 // Please note custom CSS is strongly discouraged,
1263 // because it can not be overridden by themes!
1264 // It is suitable only for things like mod/data which accepts CSS from teachers.
1265 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1267 // This line of code may look funny but it is currently required in order
1268 // to avoid MASSIVE display issues in Internet Explorer.
1269 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1270 // ignored whenever another resource is added until such time as a redraw
1271 // is forced, usually by moving the mouse over the affected element.
1272 $code = html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1274 $urls = $this->cssthemeurls + $this->cssurls;
1275 foreach ($urls as $url) {
1276 $attributes['href'] = $url;
1277 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1278 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1279 unset($attributes['id']);
1282 return $code;
1286 * Adds extra modules specified after printing of page header.
1288 * @return string
1290 protected function get_extra_modules_code() {
1291 if (empty($this->extramodules)) {
1292 return '';
1294 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1298 * Generate any HTML that needs to go inside the <head> tag.
1300 * Normally, this method is called automatically by the code that prints the
1301 * <head> tag. You should not normally need to call it in your own code.
1303 * @param moodle_page $page
1304 * @param core_renderer $renderer
1305 * @return string the HTML code to to inside the <head> tag.
1307 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1308 global $CFG;
1310 // Note: the $page and $output are not stored here because it would
1311 // create circular references in memory which prevents garbage collection.
1312 $this->init_requirements_data($page, $renderer);
1314 $output = '';
1316 // Set up the M namespace.
1317 $js = "var M = {}; M.yui = {};\n";
1319 // Capture the time now ASAP during page load. This minimises the lag when
1320 // we try to relate times on the server to times in the browser.
1321 // An example of where this is used is the quiz countdown timer.
1322 $js .= "M.pageloadstarttime = new Date();\n";
1324 // Add a subset of Moodle configuration to the M namespace.
1325 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1327 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1328 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1329 // this needs to be done before including any other script.
1330 $js .= $this->YUI_config->get_config_functions();
1331 $js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n";
1332 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1333 $js = $this->YUI_config->update_header_js($js);
1335 $output .= html_writer::script($js);
1337 // YUI3 JS and CSS need to be loaded in the header but after the YUI_config has been created.
1338 // They should be cached well by the browser.
1339 $output .= $this->get_yui3lib_headcode($page);
1341 // Add hacked jQuery support, it is not intended for standard Moodle distribution!
1342 $output .= $this->get_jquery_headcode();
1344 // Now theme CSS + custom CSS in this specific order.
1345 $output .= $this->get_css_code();
1347 // Link our main JS file, all core stuff should be there.
1348 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1350 // Add variables.
1351 if ($this->jsinitvariables['head']) {
1352 $js = '';
1353 foreach ($this->jsinitvariables['head'] as $data) {
1354 list($var, $value) = $data;
1355 $js .= js_writer::set_variable($var, $value, true);
1357 $output .= html_writer::script($js);
1360 // All the other linked things from HEAD - there should be as few as possible.
1361 if ($this->jsincludes['head']) {
1362 foreach ($this->jsincludes['head'] as $url) {
1363 $output .= html_writer::script('', $url);
1367 // Mark head sending done, it is not possible to anything there.
1368 $this->headdone = true;
1370 return $output;
1374 * Generate any HTML that needs to go at the start of the <body> tag.
1376 * Normally, this method is called automatically by the code that prints the
1377 * <head> tag. You should not normally need to call it in your own code.
1379 * @return string the HTML code to go at the start of the <body> tag.
1381 public function get_top_of_body_code() {
1382 // First the skip links.
1383 $links = '';
1384 $attributes = array('class'=>'skip');
1385 foreach ($this->skiplinks as $url => $text) {
1386 $attributes['href'] = '#' . $url;
1387 $links .= html_writer::tag('a', $text, $attributes);
1389 $output = html_writer::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1391 // Then the clever trick for hiding of things not needed when JS works.
1392 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1393 $this->topofbodydone = true;
1394 return $output;
1398 * Generate any HTML that needs to go at the end of the page.
1400 * Normally, this method is called automatically by the code that prints the
1401 * page footer. You should not normally need to call it in your own code.
1403 * @return string the HTML code to to at the end of the page.
1405 public function get_end_code() {
1406 global $CFG;
1408 // Add other requested modules.
1409 $output = $this->get_extra_modules_code();
1411 // All the other linked scripts - there should be as few as possible.
1412 if ($this->jsincludes['footer']) {
1413 foreach ($this->jsincludes['footer'] as $url) {
1414 $output .= html_writer::script('', $url);
1418 // Add all needed strings.
1419 if (!empty($this->stringsforjs)) {
1420 $strings = array();
1421 foreach ($this->stringsforjs as $component=>$v) {
1422 foreach($v as $indentifier => $langstring) {
1423 $strings[$component][$indentifier] = $langstring->out();
1426 $output .= html_writer::script(js_writer::set_variable('M.str', $strings));
1429 // Add variables.
1430 if ($this->jsinitvariables['footer']) {
1431 $js = '';
1432 foreach ($this->jsinitvariables['footer'] as $data) {
1433 list($var, $value) = $data;
1434 $js .= js_writer::set_variable($var, $value, true);
1436 $output .= html_writer::script($js);
1439 $inyuijs = $this->get_javascript_code(false);
1440 $ondomreadyjs = $this->get_javascript_code(true);
1441 $jsinit = $this->get_javascript_init_code();
1442 $handlersjs = $this->get_event_handler_code();
1444 // There is no global Y, make sure it is available in your scope.
1445 $js = "YUI().use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1447 $output .= html_writer::script($js);
1449 return $output;
1453 * Have we already output the code in the <head> tag?
1455 * @return bool
1457 public function is_head_done() {
1458 return $this->headdone;
1462 * Have we already output the code at the start of the <body> tag?
1464 * @return bool
1466 public function is_top_of_body_done() {
1467 return $this->topofbodydone;
1472 * This class represents the YUI configuration.
1474 * @copyright 2013 Andrew Nicols
1475 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1476 * @since Moodle 2.5
1477 * @package core
1478 * @category output
1480 class YUI_config {
1482 * These settings must be public so that when the object is converted to json they are exposed.
1483 * Note: Some of these are camelCase because YUI uses camelCase variable names.
1485 * The settings are described and documented in the YUI API at:
1486 * - http://yuilibrary.com/yui/docs/api/classes/config.html
1487 * - http://yuilibrary.com/yui/docs/api/classes/Loader.html
1489 public $debug = false;
1490 public $base;
1491 public $comboBase;
1492 public $combine;
1493 public $filter = null;
1494 public $insertBefore = 'firstthemesheet';
1495 public $groups = array();
1496 public $modules = array();
1499 * @var array List of functions used by the YUI Loader group pattern recognition.
1501 protected $jsconfigfunctions = array();
1504 * Create a new group within the YUI_config system.
1506 * @param String $name The name of the group. This must be unique and
1507 * not previously used.
1508 * @param Array $config The configuration for this group.
1509 * @return void
1511 public function add_group($name, $config) {
1512 if (isset($this->groups[$name])) {
1513 throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
1515 $this->groups[$name] = $config;
1519 * Update an existing group configuration
1521 * Note, any existing configuration for that group will be wiped out.
1522 * This includes module configuration.
1524 * @param String $name The name of the group. This must be unique and
1525 * not previously used.
1526 * @param Array $config The configuration for this group.
1527 * @return void
1529 public function update_group($name, $config) {
1530 if (!isset($this->groups[$name])) {
1531 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.');
1533 $this->groups[$name] = $config;
1537 * Set the value of a configuration function used by the YUI Loader's pattern testing.
1539 * Only the body of the function should be passed, and not the whole function wrapper.
1541 * The JS function your write will be passed a single argument 'name' containing the
1542 * name of the module being loaded.
1544 * @param $function String the body of the JavaScript function. This should be used i
1545 * @return String the name of the function to use in the group pattern configuration.
1547 public function set_config_function($function) {
1548 $configname = 'yui' . (count($this->jsconfigfunctions) + 1) . 'ConfigFn';
1549 if (isset($this->jsconfigfunctions[$configname])) {
1550 throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
1552 $this->jsconfigfunctions[$configname] = $function;
1553 return '@' . $configname . '@';
1557 * Retrieve the list of JavaScript functions for YUI_config groups.
1559 * @return String The complete set of config functions
1561 public function get_config_functions() {
1562 $configfunctions = '';
1563 foreach ($this->jsconfigfunctions as $functionname => $function) {
1564 $configfunctions .= "var {$functionname} = function(me) {";
1565 $configfunctions .= $function;
1566 $configfunctions .= "};\n";
1568 return $configfunctions;
1572 * Update the header JavaScript with any required modification for the YUI Loader.
1574 * @param $js String The JavaScript to manipulate.
1575 * @return String the modified JS string.
1577 public function update_header_js($js) {
1578 // Update the names of the the configFn variables.
1579 // The PHP json_encode function cannot handle literal names so we have to wrap
1580 // them in @ and then replace them with literals of the same function name.
1581 foreach ($this->jsconfigfunctions as $functionname => $function) {
1582 $js = str_replace('"@' . $functionname . '@"', $functionname, $js);
1584 return $js;
1588 * Add configuration for a specific module.
1590 * @param String $name The name of the module to add configuration for.
1591 * @param Array $config The configuration for the specified module.
1592 * @param String $group The name of the group to add configuration for.
1593 * If not specified, then this module is added to the global
1594 * configuration.
1595 * @return void
1597 public function add_module_config($name, $config, $group = null) {
1598 if ($group) {
1599 if (!isset($this->groups[$name])) {
1600 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.');
1602 if (!isset($this->groups[$group]['modules'])) {
1603 $this->groups[$group]['modules'] = array();
1605 $modules = &$this->groups[$group]['modules'];
1606 } else {
1607 $modules = &$this->modules;
1609 $modules[$name] = $config;
1613 * Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
1615 * If js caching is disabled, metadata will not be served causing YUI to calculate
1616 * module dependencies as each module is loaded.
1618 * If metadata does not exist it will be created and stored in a MUC entry.
1620 * @return void
1622 public function add_moodle_metadata() {
1623 global $CFG;
1624 if (!isset($this->groups['moodle'])) {
1625 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.');
1628 if (!isset($this->groups['moodle']['modules'])) {
1629 $this->groups['moodle']['modules'] = array();
1632 $cache = cache::make('core', 'yuimodules');
1633 if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
1634 $metadata = array();
1635 $cache->delete('metadata');
1636 } else {
1637 // Attempt to get the metadata from the cache.
1638 if (!$metadata = $cache->get('metadata')) {
1639 $metadata = $this->get_moodle_metadata();
1640 $cache->set('metadata', $metadata);
1644 // Merge with any metadata added specific to this page which was added manually.
1645 $this->groups['moodle']['modules'] = array_merge($this->groups['moodle']['modules'],
1646 $metadata);
1650 * Determine the module metadata for all moodle YUI modules.
1652 * This works through all modules capable of serving YUI modules, and attempts to get
1653 * metadata for each of those modules.
1655 * @return Array of module metadata
1657 private function get_moodle_metadata() {
1658 $moodlemodules = array();
1659 // Core isn't a plugin type or subsystem - handle it seperately.
1660 if ($module = $this->get_moodle_path_metadata(get_component_directory('core'))) {
1661 $moodlemodules = array_merge($moodlemodules, $module);
1664 // Handle other core subsystems.
1665 $subsystems = get_core_subsystems();
1666 foreach ($subsystems as $subsystem => $path) {
1667 if (is_null($path)) {
1668 continue;
1670 $path = get_component_directory($subsystem);
1671 if ($module = $this->get_moodle_path_metadata($path)) {
1672 $moodlemodules = array_merge($moodlemodules, $module);
1676 // And finally the plugins.
1677 $plugintypes = get_plugin_types();
1678 foreach ($plugintypes as $plugintype => $pathroot) {
1679 $pluginlist = get_plugin_list($plugintype);
1680 foreach ($pluginlist as $plugin => $path) {
1681 if ($module = $this->get_moodle_path_metadata($path)) {
1682 $moodlemodules = array_merge($moodlemodules, $module);
1687 return $moodlemodules;
1691 * Helper function process and return the YUI metadata for all of the modules under the specified path.
1693 * @param String $path the UNC path to the YUI src directory.
1694 * @return Array the complete array for frankenstyle directory.
1696 private function get_moodle_path_metadata($path) {
1697 // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
1698 $baseyui = $path . '/yui/src';
1699 $modules = array();
1700 if (is_dir($baseyui)) {
1701 $items = new DirectoryIterator($baseyui);
1702 foreach ($items as $item) {
1703 if ($item->isDot() or !$item->isDir()) {
1704 continue;
1706 $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
1707 if (!is_readable($metafile)) {
1708 continue;
1710 $metadata = file_get_contents($metafile);
1711 $modules = array_merge($modules, (array) json_decode($metadata));
1714 return $modules;
1719 * Invalidate all server and client side JS caches.
1721 function js_reset_all_caches() {
1722 global $CFG;
1723 require_once("$CFG->libdir/filelib.php");
1725 $next = time();
1726 if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
1727 // This resolves problems when reset is requested repeatedly within 1s,
1728 // the < 1h condition prevents accidental switching to future dates
1729 // because we might not recover from it.
1730 $next = $CFG->jsrev+1;
1733 set_config('jsrev', $next);
1734 fulldelete("$CFG->cachedir/js");