2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library functions to facilitate the use of JavaScript in Moodle.
20 * Note: you can find history of this file in lib/ajax/ajaxlib.php
22 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
31 * This class tracks all the things that are needed by the current page.
33 * Normally, the only instance of this class you will need to work with is the
34 * one accessible via $PAGE->requires.
36 * Typical usage would be
38 * $PAGE->requires->js_init_call('M.mod_forum.init_view');
41 * It also supports obsoleted coding style withouth YUI3 modules.
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);
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
59 class page_requirements_manager {
62 * @var array List of string available from JS
64 protected $stringsforjs = array();
67 * @var array List of get_string $a parameters - used for validation only.
69 protected $stringsforjs_as = array();
72 * @var array List of JS variables to be initialised
74 protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
77 * @var array Included JS scripts
79 protected $jsincludes = array('head'=>array(), 'footer'=>array());
82 * @var array List of needed function calls
84 protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
87 * @var array List of skip links, those are needed for accessibility reasons
89 protected $skiplinks = array();
92 * @var array Javascript code used for initialisation of page, it should
95 protected $jsinitcode = array();
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
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() {
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 if (strpos($CFG->httpswwwroot, 'https:') === 0) {
171 // On HTTPS sites all JS must be loaded from https sites,
172 // YUI CDN does not support https yet, sorry.
173 $CFG->useexternalyui = 0;
176 // Set up some loader options.
177 $this->yui3loader->local_base = $CFG->httpswwwroot . '/lib/yuilib/'. $CFG->yui3version . '/';
178 $this->yui3loader->local_comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep;
180 if (!empty($CFG->useexternalyui)) {
181 $this->yui3loader->base = 'http://yui.yahooapis.com/' . $CFG->yui3version . '/';
182 $this->yui3loader->comboBase = 'http://yui.yahooapis.com/combo?';
184 $this->yui3loader->base = $this->yui3loader->local_base;
185 $this->yui3loader->comboBase = $this->yui3loader->local_comboBase;
188 // Enable combo loader? This significantly helps with caching and performance!
189 $this->yui3loader->combine = !empty($CFG->yuicomboloading);
191 $jsrev = $this->get_jsrev();
193 // Set up JS YUI loader helper object.
194 $this->YUI_config->base = $this->yui3loader->base;
195 $this->YUI_config->comboBase = $this->yui3loader->comboBase;
196 $this->YUI_config->combine = $this->yui3loader->combine;
198 $configname = $this->YUI_config->set_config_source('lib/yui/config/yui2.js');
199 $this->YUI_config->add_group('yui2', array(
200 // Loader configuration for our 2in3, for now ignores $CFG->useexternalyui.
201 'base' => $CFG->httpswwwroot . '/lib/yuilib/2in3/' . $CFG->yui2version . '/build/',
202 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
203 'combine' => $this->yui3loader->combine,
205 'root' => '2in3/' . $CFG->yui2version .'/build/',
209 'configFn' => $configname,
213 $configname = $this->YUI_config->set_config_source('lib/yui/config/moodle.js');
214 $this->YUI_config->add_group('moodle', array(
216 'base' => $CFG->httpswwwroot . '/theme/yui_combo.php' . $sep . 'm/' . $jsrev . '/',
217 'combine' => $this->yui3loader->combine,
218 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
220 'root' => 'm/'.$jsrev.'/', // Add the rev to the root path so that we can control caching.
224 'configFn' => $configname,
229 // Set some more loader options applying to groups too.
230 if ($CFG->debugdeveloper) {
231 // When debugging is enabled, we want to load the non-minified (RAW) versions of YUI library modules rather
232 // than the DEBUG versions as these generally generate too much logging for our purposes.
233 // However we do want the DEBUG versions of our Moodle-specific modules.
234 // To debug a YUI-specific issue, change the yui3loader->filter value to DEBUG.
235 $this->YUI_config->filter = 'RAW';
236 $this->YUI_config->groups['moodle']['filter'] = 'DEBUG';
238 // We use the yui3loader->filter setting when writing the YUI3 seed scripts into the header.
239 $this->yui3loader->filter = $this->YUI_config->filter;
240 $this->YUI_config->debug = true;
242 $this->yui3loader->filter = null;
243 $this->YUI_config->debug = false;
246 // Include the YUI config log filters.
247 if (!empty($CFG->yuilogexclude) && is_array($CFG->yuilogexclude)) {
248 $this->YUI_config->logExclude = $CFG->yuilogexclude;
250 if (!empty($CFG->yuiloginclude) && is_array($CFG->yuiloginclude)) {
251 $this->YUI_config->logInclude = $CFG->yuiloginclude;
253 if (!empty($CFG->yuiloglevel)) {
254 $this->YUI_config->logLevel = $CFG->yuiloglevel;
257 // Add the moodle group's module data.
258 $this->YUI_config->add_moodle_metadata();
260 // Every page should include definition of following modules.
261 $this->js_module($this->find_module('core_filepicker'));
265 * Initialise with the bits of JavaScript that every Moodle page should have.
267 * @param moodle_page $page
268 * @param core_renderer $renderer
270 protected function init_requirements_data(moodle_page $page, core_renderer $renderer) {
273 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
274 // Otherwise, in some situations, users will get warnings about insecure content
275 // on secure pages from their web browser.
277 $this->M_cfg = array(
278 'wwwroot' => $CFG->httpswwwroot, // Yes, really. See above.
279 'sesskey' => sesskey(),
280 'loadingicon' => $renderer->pix_url('i/loading_small', 'moodle')->out(false),
281 'themerev' => theme_get_revision(),
282 'slasharguments' => (int)(!empty($CFG->slasharguments)),
283 'theme' => $page->theme->name,
284 'jsrev' => $this->get_jsrev(),
285 'svgicons' => $page->theme->use_svg_icons()
287 if ($CFG->debugdeveloper) {
288 $this->M_cfg['developerdebug'] = true;
291 // Accessibility stuff.
292 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
294 // Add strings used on many pages.
295 $this->string_for_js('confirmation', 'admin');
296 $this->string_for_js('cancel', 'moodle');
297 $this->string_for_js('yes', 'moodle');
299 // Alter links in top frame to break out of frames.
300 if ($page->pagelayout === 'frametop') {
301 $this->js_init_call('M.util.init_frametop');
304 // Include block drag/drop if editing is on
305 if ($page->user_is_editing()) {
307 'courseid' => $page->course->id,
308 'pagetype' => $page->pagetype,
309 'pagelayout' => $page->pagelayout,
310 'subpage' => $page->subpage,
311 'regions' => $page->blocks->get_regions(),
312 'contextid' => $page->context->id,
314 if (!empty($page->cm->id)) {
315 $params['cmid'] = $page->cm->id;
317 // Strings for drag and drop.
318 $this->strings_for_js(array('movecontent',
320 'emptydragdropregion'),
322 $page->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
327 * Determine the correct JS Revision to use for this load.
329 * @return int the jsrev to use.
331 protected function get_jsrev() {
334 if (empty($CFG->cachejs)) {
336 } else if (empty($CFG->jsrev)) {
339 $jsrev = $CFG->jsrev;
346 * Ensure that the specified JavaScript file is linked to from this page.
348 * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
349 * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
351 * By default the link is put at the end of the page, since this gives best page-load performance.
353 * Even if a particular script is requested more than once, it will only be linked
356 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
357 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
358 * @param bool $inhead initialise in head
360 public function js($url, $inhead = false) {
361 $url = $this->js_fix_url($url);
362 $where = $inhead ? 'head' : 'footer';
363 $this->jsincludes[$where][$url->out()] = $url;
367 * Request inclusion of jQuery library in the page.
369 * NOTE: this should not be used in official Moodle distribution!
371 * We are going to bundle jQuery 1.9.x until we drop support
372 * all support for IE 6-8. Use $PAGE->requires->jquery_plugin('migrate')
373 * for code written for earlier jQuery versions.
375 * {@see http://docs.moodle.org/dev/jQuery}
377 public function jquery() {
378 $this->jquery_plugin('jquery');
382 * Request inclusion of jQuery plugin.
384 * NOTE: this should not be used in official Moodle distribution!
386 * jQuery plugins are located in plugin/jquery/* subdirectory,
387 * plugin/jquery/plugins.php lists all available plugins.
389 * Included core plugins:
391 * - jQuery Migrate (useful for code written for previous UI version)
393 * Add-ons may include extra jQuery plugins in jquery/ directory,
394 * plugins.php file defines the mapping between plugin names and
395 * necessary page includes.
399 * // file: mod/xxx/view.php
400 * $PAGE->requires->jquery();
401 * $PAGE->requires->jquery_plugin('ui');
402 * $PAGE->requires->jquery_plugin('ui-css');
406 * // file: theme/yyy/lib.php
407 * function theme_yyy_page_init(moodle_page $page) {
408 * $page->requires->jquery();
409 * $page->requires->jquery_plugin('ui');
410 * $page->requires->jquery_plugin('ui-css');
415 * // file: blocks/zzz/block_zzz.php
416 * public function get_required_javascript() {
417 * parent::get_required_javascript();
418 * $this->page->requires->jquery();
419 * $page->requires->jquery_plugin('ui');
420 * $page->requires->jquery_plugin('ui-css');
424 * {@see http://docs.moodle.org/dev/jQuery}
426 * @param string $plugin name of the jQuery plugin as defined in jquery/plugins.php
427 * @param string $component name of the component
428 * @return bool success
430 public function jquery_plugin($plugin, $component = 'core') {
433 if ($this->headdone) {
434 debugging('Can not add jQuery plugins after starting page output!');
438 if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css', 'migrate'))) {
439 debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER);
441 } else if ($component !== 'core' and strpos($component, '_') === false) {
442 // Let's normalise the legacy activity names, Frankenstyle rulez!
443 $component = 'mod_' . $component;
446 if (empty($this->jqueryplugins) and ($component !== 'core' or $plugin !== 'jquery')) {
447 // Make sure the jQuery itself is always loaded first,
448 // the order of all other plugins depends on order of $PAGE_>requires->.
449 $this->jquery_plugin('jquery', 'core');
452 if (isset($this->jqueryplugins[$plugin])) {
453 // No problem, we already have something, first Moodle plugin to register the jQuery plugin wins.
457 $componentdir = core_component::get_component_directory($component);
458 if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
459 debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER);
464 require("$componentdir/jquery/plugins.php");
466 if (!isset($plugins[$plugin])) {
467 debugging("jQuery plugin '$plugin' can not be found in component '$component'.", DEBUG_DEVELOPER);
471 $this->jqueryplugins[$plugin] = new stdClass();
472 $this->jqueryplugins[$plugin]->plugin = $plugin;
473 $this->jqueryplugins[$plugin]->component = $component;
474 $this->jqueryplugins[$plugin]->urls = array();
476 foreach ($plugins[$plugin]['files'] as $file) {
477 if ($CFG->debugdeveloper) {
478 if (!file_exists("$componentdir/jquery/$file")) {
479 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
482 $file = str_replace('.min.css', '.css', $file);
483 $file = str_replace('.min.js', '.js', $file);
485 if (!file_exists("$componentdir/jquery/$file")) {
486 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
489 if (!empty($CFG->slasharguments)) {
490 $url = new moodle_url("$CFG->httpswwwroot/theme/jquery.php");
491 $url->set_slashargument("/$component/$file");
494 // This is not really good, we need slasharguments for relative links, this means no caching...
495 $path = realpath("$componentdir/jquery/$file");
496 if (strpos($path, $CFG->dirroot) === 0) {
497 $url = $CFG->httpswwwroot.preg_replace('/^'.preg_quote($CFG->dirroot, '/').'/', '', $path);
498 $url = new moodle_url($url);
500 // Bad luck, fix your server!
501 debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
505 $this->jqueryplugins[$plugin]->urls[] = $url;
512 * Request replacement of one jQuery plugin by another.
514 * This is useful when themes want to replace the jQuery UI theme,
515 * the problem is that theme can not prevent others from including the core ui-css plugin.
518 * 1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
519 * 2/ write theme/yourtheme/jquery/plugins.php
520 * 3/ init jQuery from theme
523 * // file theme/yourtheme/lib.php
524 * function theme_yourtheme_page_init($page) {
525 * $page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
526 * $page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
530 * This code prevents loading of standard 'ui-css' which my be requested by other plugins,
531 * the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
533 * {@see http://docs.moodle.org/dev/jQuery}
535 * @param string $oldplugin original plugin
536 * @param string $newplugin the replacement
538 public function jquery_override_plugin($oldplugin, $newplugin) {
539 if ($this->headdone) {
540 debugging('Can not override jQuery plugins after starting page output!');
543 $this->jquerypluginoverrides[$oldplugin] = $newplugin;
547 * Return jQuery related markup for page start.
550 protected function get_jquery_headcode() {
551 if (empty($this->jqueryplugins['jquery'])) {
552 // If nobody requested jQuery then do not bother to load anything.
553 // This may be useful for themes that want to override 'ui-css' only if requested by something else.
560 foreach ($this->jqueryplugins as $name => $unused) {
561 if (isset($included[$name])) {
564 if (array_key_exists($name, $this->jquerypluginoverrides)) {
565 // The following loop tries to resolve the replacements,
566 // use max 100 iterations to prevent infinite loop resulting
570 for ($i=0; $i<100; $i++) {
571 $name = $this->jquerypluginoverrides[$name];
572 if (!array_key_exists($name, $this->jquerypluginoverrides)) {
578 // We can not do much with cyclic references here, let's use the old plugin.
580 debugging("Cyclic overrides detected for jQuery plugin '$name'");
582 } else if (empty($name)) {
583 // Developer requested removal of the plugin.
586 } else if (!isset($this->jqueryplugins[$name])) {
587 debugging("Unknown jQuery override plugin '$name' detected");
590 } else if (isset($included[$name])) {
591 // The plugin was already included, easy.
596 $plugin = $this->jqueryplugins[$name];
597 $urls = array_merge($urls, $plugin->urls);
598 $included[$name] = true;
602 $attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
603 foreach ($urls as $url) {
604 if (preg_match('/\.js$/', $url)) {
605 $output .= html_writer::script('', $url);
606 } else if (preg_match('/\.css$/', $url)) {
607 $attributes['href'] = $url;
608 $output .= html_writer::empty_tag('link', $attributes) . "\n";
616 * This method was used to load YUI2 libraries into global scope,
617 * use YUI 2in3 instead. Every YUI2 module is represented as a yui2-*
618 * sandboxed module in YUI3 code via Y.YUI2. property.
620 * {@see http://tracker.moodle.org/browse/MDL-34741}
622 * @param string|array $libname
623 * @deprecated since 2.4
625 public function yui2_lib($libname) {
626 throw new coding_exception('PAGE->yui2_lib() is not available any more, use YUI 2in3 instead, see MDL-34741 for more information.');
630 * Returns the actual url through which a script is served.
632 * @param moodle_url|string $url full moodle url, or shortened path to script
635 protected function js_fix_url($url) {
638 if ($url instanceof moodle_url) {
640 } else if (strpos($url, '/') === 0) {
641 // Fix the admin links if needed.
642 if ($CFG->admin !== 'admin') {
643 if (strpos($url, "/admin/") === 0) {
644 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
648 // Check file existence only when in debug mode.
649 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
650 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
653 if (substr($url, -3) === '.js') {
654 $jsrev = $this->get_jsrev();
655 if (empty($CFG->slasharguments)) {
656 return new moodle_url($CFG->httpswwwroot.'/lib/javascript.php', array('rev'=>$jsrev, 'jsfile'=>$url));
658 $returnurl = new moodle_url($CFG->httpswwwroot.'/lib/javascript.php');
659 $returnurl->set_slashargument('/'.$jsrev.$url);
663 return new moodle_url($CFG->httpswwwroot.$url);
666 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
671 * Find out if JS module present and return details.
673 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
674 * @return array description of module or null if not found
676 protected function find_module($component) {
681 if (strpos($component, 'core_') === 0) {
682 // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
683 // so that we do nto have to repeat the definition of these modules over and over again.
685 case 'core_filepicker':
686 $module = array('name' => 'core_filepicker',
687 'fullpath' => '/repository/filepicker.js',
688 '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'),
689 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
690 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
691 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
692 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
693 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
694 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
695 array('referencesexist', 'repository'), array('select', 'repository')
699 $module = array('name' => 'core_comment',
700 'fullpath' => '/comment/comment.js',
701 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
702 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
706 $module = array('name' => 'core_role',
707 'fullpath' => '/admin/roles/module.js',
708 'requires' => array('node', 'cookie'));
710 case 'core_completion':
711 $module = array('name' => 'core_completion',
712 'fullpath' => '/course/completion.js');
715 $module = array('name' => 'core_message',
716 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
717 'fullpath' => '/message/module.js');
720 $module = array('name' => 'core_group',
721 'fullpath' => '/group/module.js',
722 'requires' => array('node', 'overlay', 'event-mouseenter'));
724 case 'core_question_engine':
725 $module = array('name' => 'core_question_engine',
726 'fullpath' => '/question/qengine.js',
727 'requires' => array('node', 'event'));
730 $module = array('name' => 'core_rating',
731 'fullpath' => '/rating/module.js',
732 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
734 case 'core_dndupload':
735 $module = array('name' => 'core_dndupload',
736 'fullpath' => '/lib/form/dndupload.js',
737 'requires' => array('node', 'event', 'json', 'core_filepicker'),
738 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
739 array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesforfile', 'moodle'),
740 array('maxareabytesreached', 'moodle')
746 if ($dir = core_component::get_component_directory($component)) {
747 if (file_exists("$dir/module.js")) {
748 if (strpos($dir, $CFG->dirroot.'/') === 0) {
749 $dir = substr($dir, strlen($CFG->dirroot));
750 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
760 * Append YUI3 module to default YUI3 JS loader.
761 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
763 * @param string|array $module name of module (details are autodetected), or full module specification as array
766 public function js_module($module) {
769 if (empty($module)) {
770 throw new coding_exception('Missing YUI3 module name or full description.');
773 if (is_string($module)) {
774 $module = $this->find_module($module);
777 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
778 throw new coding_exception('Missing YUI3 module details.');
781 // Don't load this module if we already have, no need to!
782 if ($this->js_module_loaded($module['name'])) {
783 if ($CFG->debugdeveloper) {
784 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
789 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
790 // Add all needed strings.
791 if (!empty($module['strings'])) {
792 foreach ($module['strings'] as $string) {
793 $identifier = $string[0];
794 $component = isset($string[1]) ? $string[1] : 'moodle';
795 $a = isset($string[2]) ? $string[2] : null;
796 $this->string_for_js($identifier, $component, $a);
799 unset($module['strings']);
801 // Process module requirements and attempt to load each. This allows
802 // moodle modules to require each other.
803 if (!empty($module['requires'])){
804 foreach ($module['requires'] as $requirement) {
805 $rmodule = $this->find_module($requirement);
806 if (is_array($rmodule)) {
807 $this->js_module($rmodule);
812 if ($this->headdone) {
813 $this->extramodules[$module['name']] = $module;
815 $this->YUI_config->add_module_config($module['name'], $module);
817 if ($CFG->debugdeveloper) {
818 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces)) {
819 $this->debug_moduleloadstacktraces[$module['name']] = array();
821 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
826 * Returns true if the module has already been loaded.
828 * @param string|array $module
829 * @return bool True if the module has already been loaded
831 protected function js_module_loaded($module) {
832 if (is_string($module)) {
833 $modulename = $module;
835 $modulename = $module['name'];
837 return array_key_exists($modulename, $this->YUI_config->modules) ||
838 array_key_exists($modulename, $this->extramodules);
842 * Returns the stacktraces from loading js modules.
845 public function get_loaded_modules() {
846 return $this->debug_moduleloadstacktraces;
850 * Ensure that the specified CSS file is linked to from this page.
852 * Because stylesheet links must go in the <head> part of the HTML, you must call
853 * this function before {@link get_head_code()} is called. That normally means before
854 * the call to print_header. If you call it when it is too late, an exception
857 * Even if a particular style sheet is requested more than once, it will only
860 * Please note use of this feature is strongly discouraged,
861 * it is suitable only for places where CSS is submitted directly by teachers.
862 * (Students must not be allowed to submit any external CSS because it may
863 * contain embedded javascript!). Example of correct use is mod/data.
865 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
867 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
869 public function css($stylesheet) {
872 if ($this->headdone) {
873 throw new coding_exception('Cannot require a CSS file after <head> has been printed.', $stylesheet);
876 if ($stylesheet instanceof moodle_url) {
878 } else if (strpos($stylesheet, '/') === 0) {
879 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
881 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
884 $this->cssurls[$stylesheet->out()] = $stylesheet;
888 * Add theme stylesheet to page - do not use from plugin code,
889 * this should be called only from the core renderer!
891 * @param moodle_url $stylesheet
894 public function css_theme(moodle_url $stylesheet) {
895 $this->cssthemeurls[] = $stylesheet;
899 * Ensure that a skip link to a given target is printed at the top of the <body>.
901 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
902 * will be thrown). That normally means you must call this before the call to print_header.
904 * If you ask for a particular skip link to be printed, it is then your responsibility
905 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
906 * page, so that the skip link goes somewhere.
908 * Even if a particular skip link is requested more than once, only one copy of it will be output.
910 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
911 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
913 public function skip_link_to($target, $linktext) {
914 if ($this->topofbodydone) {
915 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
918 $this->skiplinks[$target] = $linktext;
922 * !!!DEPRECATED!!! please use js_init_call() if possible
923 * Ensure that the specified JavaScript function is called from an inline script
924 * somewhere on this page.
926 * By default the call will be put in a script tag at the
927 * end of the page after initialising Y instance, since this gives best page-load
928 * performance and allows you to use YUI3 library.
930 * If you request that a particular function is called several times, then
931 * that is what will happen (unlike linking to a CSS or JS file, where only
932 * one link will be output).
934 * The main benefit of the method is the automatic encoding of all function parameters.
938 * @param string $function the name of the JavaScritp function to call. Can
939 * be a compound name like 'Y.Event.purgeElement'. Can also be
940 * used to create and object by using a 'function name' like 'new user_selector'.
941 * @param array $arguments and array of arguments to be passed to the function.
942 * When generating the function call, this will be escaped using json_encode,
943 * so passing objects and arrays should work.
944 * @param bool $ondomready If tru the function is only called when the dom is
945 * ready for manipulation.
946 * @param int $delay The delay before the function is called.
948 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
949 $where = $ondomready ? 'ondomready' : 'normal';
950 $this->jscalls[$where][] = array($function, $arguments, $delay);
954 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
956 * @deprecated DO NOT USE
958 * @param string|array $modules One or more gallery modules to require
959 * @param string $version
960 * @param string $function
961 * @param array $arguments
962 * @param bool $ondomready
964 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
966 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER);
967 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
971 * Creates a JavaScript function call that requires one or more modules to be loaded.
973 * This function can be used to include all of the standard YUI module types within JavaScript:
974 * - YUI3 modules [node, event, io]
975 * - YUI2 modules [yui2-*]
976 * - Moodle modules [moodle-*]
977 * - Gallery modules [gallery-*]
979 * @param array|string $modules One or more modules
980 * @param string $function The function to call once modules have been loaded
981 * @param array $arguments An array of arguments to pass to the function
982 * @param string $galleryversion The gallery version to use
983 * @param bool $ondomready
985 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
988 if (!$galleryversion) {
989 $galleryversion = '2010.04.08-12-35';
992 if (!is_array($modules)) {
993 $modules = array($modules);
995 if (empty($CFG->useexternalyui)) {
996 // We need to set the M.yui.galleryversion to the correct version
997 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
999 // Set Y's config.gallery to the version
1000 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
1002 $jscode .= 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
1004 $jscode = "Y.on('domready', function() { $jscode });";
1006 $this->jsinitcode[] = $jscode;
1010 * Ensure that the specified JavaScript function is called from an inline script
1013 * @param string $function the name of the JavaScritp function to with init code,
1014 * usually something like 'M.mod_mymodule.init'
1015 * @param array $extraarguments and array of arguments to be passed to the function.
1016 * The first argument is always the YUI3 Y instance with all required dependencies
1018 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1019 * @param array $module JS module specification array
1021 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1022 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
1024 // Detect module automatically.
1025 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
1026 $module = $this->find_module($matches[1]);
1030 $this->js_init_code($jscode, $ondomready, $module);
1034 * Add short static javascript code fragment to page footer.
1035 * This is intended primarily for loading of js modules and initialising page layout.
1036 * Ideally the JS code fragment should be stored in plugin renderer so that themes
1039 * @param string $jscode
1040 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1041 * @param array $module JS module specification array
1043 public function js_init_code($jscode, $ondomready = false, array $module = null) {
1044 $jscode = trim($jscode, " ;\n"). ';';
1047 $this->js_module($module);
1048 $modulename = $module['name'];
1049 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
1053 $jscode = "Y.on('domready', function() { $jscode });";
1056 $this->jsinitcode[] = $jscode;
1060 * Make a language string available to JavaScript.
1062 * All the strings will be available in a M.str object in the global namespace.
1063 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
1064 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
1065 * equivalent in the current language.
1067 * The arguments to this function are just like the arguments to get_string
1068 * except that $component is not optional, and there are some aspects to consider
1069 * when the string contains {$a} placeholder.
1071 * If the string does not contain any {$a} placeholder, you can simply use
1072 * M.str.component.identifier to obtain it. If you prefer, you can call
1073 * M.util.get_string(identifier, component) to get the same result.
1075 * If you need to use {$a} placeholders, there are two options. Either the
1076 * placeholder should be substituted in PHP on server side or it should
1077 * be substituted in Javascript at client side.
1079 * To substitute the placeholder at server side, just provide the required
1080 * value for the placeholder when you require the string. Because each string
1081 * is only stored once in the JavaScript (based on $identifier and $module)
1082 * you cannot get the same string with two different values of $a. If you try,
1083 * an exception will be thrown. Once the placeholder is substituted, you can
1084 * use M.str or M.util.get_string() as shown above:
1086 * // Require the string in PHP and replace the placeholder.
1087 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
1088 * // Use the result of the substitution in Javascript.
1089 * alert(M.str.moodle.fullnamedisplay);
1091 * To substitute the placeholder at client side, use M.util.get_string()
1092 * function. It implements the same logic as {@link get_string()}:
1094 * // Require the string in PHP but keep {$a} as it is.
1095 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
1096 * // Provide the values on the fly in Javascript.
1097 * user = { firstname : 'Harry', lastname : 'Potter' }
1098 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
1100 * If you do need the same string expanded with different $a values in PHP
1101 * on server side, then the solution is to put them in your own data structure
1102 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
1104 * @param string $identifier the desired string.
1105 * @param string $component the language file to look in.
1106 * @param mixed $a any extra data to add into the string (optional).
1108 public function string_for_js($identifier, $component, $a = null) {
1110 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
1112 if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
1113 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
1114 "from lang file '$component' with different \$a parameter?");
1116 if (!isset($this->stringsforjs[$component][$identifier])) {
1117 $this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
1118 $this->stringsforjs_as[$component][$identifier] = $a;
1123 * Make an array of language strings available for JS.
1125 * This function calls the above function {@link string_for_js()} for each requested
1126 * string in the $identifiers array that is passed to the argument for a single module
1127 * passed in $module.
1130 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
1132 * // The above is identical to calling:
1134 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
1135 * $PAGE->requires->string_for_js('two', 'mymod');
1136 * $PAGE->requires->string_for_js('three', 'mymod', 3);
1139 * @param array $identifiers An array of desired strings
1140 * @param string $component The module to load for
1141 * @param mixed $a This can either be a single variable that gets passed as extra
1142 * information for every string or it can be an array of mixed data where the
1143 * key for the data matches that of the identifier it is meant for.
1146 public function strings_for_js($identifiers, $component, $a = null) {
1147 foreach ($identifiers as $key => $identifier) {
1148 if (is_array($a) && array_key_exists($key, $a)) {
1153 $this->string_for_js($identifier, $component, $extra);
1158 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
1160 * Make some data from PHP available to JavaScript code.
1162 * For example, if you call
1164 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
1166 * then in JavsScript mydata.name will be 'Moodle'.
1169 * @param string $variable the the name of the JavaScript variable to assign the data to.
1170 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1171 * should be considered an experimental feature.
1172 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1173 * so passing objects and arrays should work.
1174 * @param bool $inhead initialise in head
1177 public function data_for_js($variable, $data, $inhead=false) {
1178 $where = $inhead ? 'head' : 'footer';
1179 $this->jsinitvariables[$where][] = array($variable, $data);
1183 * Creates a YUI event handler.
1185 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1186 * @param string $event A valid DOM event (click, mousedown, change etc.)
1187 * @param string $function The name of the function to call
1188 * @param array $arguments An optional array of argument parameters to pass to the function
1190 public function event_handler($selector, $event, $function, array $arguments = null) {
1191 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
1195 * Returns code needed for registering of event handlers.
1196 * @return string JS code
1198 protected function get_event_handler_code() {
1200 foreach ($this->eventhandlers as $h) {
1201 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
1207 * Get the inline JavaScript code that need to appear in a particular place.
1208 * @param bool $ondomready
1211 protected function get_javascript_code($ondomready) {
1212 $where = $ondomready ? 'ondomready' : 'normal';
1214 if ($this->jscalls[$where]) {
1215 foreach ($this->jscalls[$where] as $data) {
1216 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
1218 if (!empty($ondomready)) {
1219 $output = " Y.on('domready', function() {\n$output\n });";
1226 * Returns js code to be executed when Y is available.
1229 protected function get_javascript_init_code() {
1230 if (count($this->jsinitcode)) {
1231 return implode("\n", $this->jsinitcode) . "\n";
1237 * Returns basic YUI3 JS loading code.
1238 * YUI3 is using autoloading of both CSS and JS code.
1240 * Major benefit of this compared to standard js/csss loader is much improved
1241 * caching, better browser cache utilisation, much fewer http requests.
1243 * @param moodle_page $page
1246 protected function get_yui3lib_headcode($page) {
1251 $jsrev = $this->get_jsrev();
1253 $yuiformat = '-min';
1254 if ($this->yui3loader->filter === 'RAW') {
1259 if ($this->YUI_config->groups['moodle']['filter'] === 'DEBUG') {
1263 $baserollups = array(
1264 'rollup/' . $CFG->yui3version . "/yui-moodlesimple{$yuiformat}.js",
1265 'rollup/' . $jsrev . "/mcore{$format}.js",
1268 if ($this->yui3loader->combine) {
1269 if (!empty($page->theme->yuicssmodules)) {
1271 foreach ($page->theme->yuicssmodules as $module) {
1272 $modules[] = "$CFG->yui3version/$module/$module-min.css";
1274 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase.implode('&', $modules).'" />';
1276 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
1277 $code .= '<script type="text/javascript" src="'.$this->yui3loader->local_comboBase
1278 . implode('&', $baserollups) . '"></script>';
1281 if (!empty($page->theme->yuicssmodules)) {
1282 foreach ($page->theme->yuicssmodules as $module) {
1283 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.$module.'/'.$module.'-min.css" />';
1286 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
1287 foreach ($baserollups as $rollup) {
1288 $code .= '<script type="text/javascript" src="'.$this->yui3loader->local_comboBase.$rollup.'"></script>';
1292 if ($this->yui3loader->filter === 'RAW') {
1293 $code = str_replace('-min.css', '.css', $code);
1294 } else if ($this->yui3loader->filter === 'DEBUG') {
1295 $code = str_replace('-min.css', '.css', $code);
1301 * Returns html tags needed for inclusion of theme CSS.
1305 protected function get_css_code() {
1306 // First of all the theme CSS, then any custom CSS
1307 // Please note custom CSS is strongly discouraged,
1308 // because it can not be overridden by themes!
1309 // It is suitable only for things like mod/data which accepts CSS from teachers.
1310 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1312 // This line of code may look funny but it is currently required in order
1313 // to avoid MASSIVE display issues in Internet Explorer.
1314 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1315 // ignored whenever another resource is added until such time as a redraw
1316 // is forced, usually by moving the mouse over the affected element.
1317 $code = html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1319 $urls = $this->cssthemeurls + $this->cssurls;
1320 foreach ($urls as $url) {
1321 $attributes['href'] = $url;
1322 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1323 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1324 unset($attributes['id']);
1331 * Adds extra modules specified after printing of page header.
1335 protected function get_extra_modules_code() {
1336 if (empty($this->extramodules)) {
1339 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1343 * Generate any HTML that needs to go inside the <head> tag.
1345 * Normally, this method is called automatically by the code that prints the
1346 * <head> tag. You should not normally need to call it in your own code.
1348 * @param moodle_page $page
1349 * @param core_renderer $renderer
1350 * @return string the HTML code to to inside the <head> tag.
1352 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1355 // Note: the $page and $output are not stored here because it would
1356 // create circular references in memory which prevents garbage collection.
1357 $this->init_requirements_data($page, $renderer);
1361 // Set up the M namespace.
1362 $js = "var M = {}; M.yui = {};\n";
1364 // Capture the time now ASAP during page load. This minimises the lag when
1365 // we try to relate times on the server to times in the browser.
1366 // An example of where this is used is the quiz countdown timer.
1367 $js .= "M.pageloadstarttime = new Date();\n";
1369 // Add a subset of Moodle configuration to the M namespace.
1370 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1372 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1373 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1374 // this needs to be done before including any other script.
1375 $js .= $this->YUI_config->get_config_functions();
1376 $js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n";
1377 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1378 $js = $this->YUI_config->update_header_js($js);
1380 $output .= html_writer::script($js);
1382 // YUI3 JS and CSS need to be loaded in the header but after the YUI_config has been created.
1383 // They should be cached well by the browser.
1384 $output .= $this->get_yui3lib_headcode($page);
1386 // Add hacked jQuery support, it is not intended for standard Moodle distribution!
1387 $output .= $this->get_jquery_headcode();
1389 // Now theme CSS + custom CSS in this specific order.
1390 $output .= $this->get_css_code();
1392 // Link our main JS file, all core stuff should be there.
1393 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1396 if ($this->jsinitvariables['head']) {
1398 foreach ($this->jsinitvariables['head'] as $data) {
1399 list($var, $value) = $data;
1400 $js .= js_writer::set_variable($var, $value, true);
1402 $output .= html_writer::script($js);
1405 // All the other linked things from HEAD - there should be as few as possible.
1406 if ($this->jsincludes['head']) {
1407 foreach ($this->jsincludes['head'] as $url) {
1408 $output .= html_writer::script('', $url);
1412 // Mark head sending done, it is not possible to anything there.
1413 $this->headdone = true;
1419 * Generate any HTML that needs to go at the start of the <body> tag.
1421 * Normally, this method is called automatically by the code that prints the
1422 * <head> tag. You should not normally need to call it in your own code.
1424 * @return string the HTML code to go at the start of the <body> tag.
1426 public function get_top_of_body_code() {
1427 // First the skip links.
1429 $attributes = array('class'=>'skip');
1430 foreach ($this->skiplinks as $url => $text) {
1431 $attributes['href'] = '#' . $url;
1432 $links .= html_writer::tag('a', $text, $attributes);
1434 $output = html_writer::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1436 // Then the clever trick for hiding of things not needed when JS works.
1437 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1438 $this->topofbodydone = true;
1443 * Generate any HTML that needs to go at the end of the page.
1445 * Normally, this method is called automatically by the code that prints the
1446 * page footer. You should not normally need to call it in your own code.
1448 * @return string the HTML code to to at the end of the page.
1450 public function get_end_code() {
1453 // Add other requested modules.
1454 $output = $this->get_extra_modules_code();
1456 // All the other linked scripts - there should be as few as possible.
1457 if ($this->jsincludes['footer']) {
1458 foreach ($this->jsincludes['footer'] as $url) {
1459 $output .= html_writer::script('', $url);
1463 // Add all needed strings.
1464 if (!empty($this->stringsforjs)) {
1466 foreach ($this->stringsforjs as $component=>$v) {
1467 foreach($v as $indentifier => $langstring) {
1468 $strings[$component][$indentifier] = $langstring->out();
1471 $output .= html_writer::script(js_writer::set_variable('M.str', $strings));
1475 if ($this->jsinitvariables['footer']) {
1477 foreach ($this->jsinitvariables['footer'] as $data) {
1478 list($var, $value) = $data;
1479 $js .= js_writer::set_variable($var, $value, true);
1481 $output .= html_writer::script($js);
1484 $inyuijs = $this->get_javascript_code(false);
1485 $ondomreadyjs = $this->get_javascript_code(true);
1486 $jsinit = $this->get_javascript_init_code();
1487 $handlersjs = $this->get_event_handler_code();
1489 // There is no global Y, make sure it is available in your scope.
1490 $js = "YUI().use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1492 $output .= html_writer::script($js);
1498 * Have we already output the code in the <head> tag?
1502 public function is_head_done() {
1503 return $this->headdone;
1507 * Have we already output the code at the start of the <body> tag?
1511 public function is_top_of_body_done() {
1512 return $this->topofbodydone;
1517 * This class represents the YUI configuration.
1519 * @copyright 2013 Andrew Nicols
1520 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1527 * These settings must be public so that when the object is converted to json they are exposed.
1528 * Note: Some of these are camelCase because YUI uses camelCase variable names.
1530 * The settings are described and documented in the YUI API at:
1531 * - http://yuilibrary.com/yui/docs/api/classes/config.html
1532 * - http://yuilibrary.com/yui/docs/api/classes/Loader.html
1534 public $debug = false;
1538 public $filter = null;
1539 public $insertBefore = 'firstthemesheet';
1540 public $groups = array();
1541 public $modules = array();
1544 * @var array List of functions used by the YUI Loader group pattern recognition.
1546 protected $jsconfigfunctions = array();
1549 * Create a new group within the YUI_config system.
1551 * @param String $name The name of the group. This must be unique and
1552 * not previously used.
1553 * @param Array $config The configuration for this group.
1556 public function add_group($name, $config) {
1557 if (isset($this->groups[$name])) {
1558 throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
1560 $this->groups[$name] = $config;
1564 * Update an existing group configuration
1566 * Note, any existing configuration for that group will be wiped out.
1567 * This includes module configuration.
1569 * @param String $name The name of the group. This must be unique and
1570 * not previously used.
1571 * @param Array $config The configuration for this group.
1574 public function update_group($name, $config) {
1575 if (!isset($this->groups[$name])) {
1576 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.');
1578 $this->groups[$name] = $config;
1582 * Set the value of a configuration function used by the YUI Loader's pattern testing.
1584 * Only the body of the function should be passed, and not the whole function wrapper.
1586 * The JS function your write will be passed a single argument 'name' containing the
1587 * name of the module being loaded.
1589 * @param $function String the body of the JavaScript function. This should be used i
1590 * @return String the name of the function to use in the group pattern configuration.
1592 public function set_config_function($function) {
1593 $configname = 'yui' . (count($this->jsconfigfunctions) + 1) . 'ConfigFn';
1594 if (isset($this->jsconfigfunctions[$configname])) {
1595 throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
1597 $this->jsconfigfunctions[$configname] = $function;
1598 return '@' . $configname . '@';
1602 * Allow setting of the config function described in {@see set_config_function} from a file.
1603 * The contents of this file are then passed to set_config_function.
1605 * When jsrev is positive, the function is minified and stored in a MUC cache for subsequent uses.
1607 * @param $file The path to the JavaScript function used for YUI configuration.
1608 * @return String the name of the function to use in the group pattern configuration.
1610 public function set_config_source($file) {
1612 $cache = cache::make('core', 'yuimodules');
1614 // Attempt to get the metadata from the cache.
1615 $keyname = 'configfn_' . $file;
1616 $fullpath = $CFG->dirroot . '/' . $file;
1617 if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
1618 $cache->delete($keyname);
1619 $configfn = file_get_contents($fullpath);
1621 $configfn = $cache->get($keyname);
1622 if ($configfn === false) {
1623 require_once($CFG->libdir . '/jslib.php');
1624 $configfn = core_minify::js_files(array($fullpath));
1625 $cache->set($keyname, $configfn);
1628 return $this->set_config_function($configfn);
1632 * Retrieve the list of JavaScript functions for YUI_config groups.
1634 * @return String The complete set of config functions
1636 public function get_config_functions() {
1637 $configfunctions = '';
1638 foreach ($this->jsconfigfunctions as $functionname => $function) {
1639 $configfunctions .= "var {$functionname} = function(me) {";
1640 $configfunctions .= $function;
1641 $configfunctions .= "};\n";
1643 return $configfunctions;
1647 * Update the header JavaScript with any required modification for the YUI Loader.
1649 * @param $js String The JavaScript to manipulate.
1650 * @return String the modified JS string.
1652 public function update_header_js($js) {
1653 // Update the names of the the configFn variables.
1654 // The PHP json_encode function cannot handle literal names so we have to wrap
1655 // them in @ and then replace them with literals of the same function name.
1656 foreach ($this->jsconfigfunctions as $functionname => $function) {
1657 $js = str_replace('"@' . $functionname . '@"', $functionname, $js);
1663 * Add configuration for a specific module.
1665 * @param String $name The name of the module to add configuration for.
1666 * @param Array $config The configuration for the specified module.
1667 * @param String $group The name of the group to add configuration for.
1668 * If not specified, then this module is added to the global
1672 public function add_module_config($name, $config, $group = null) {
1674 if (!isset($this->groups[$name])) {
1675 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.');
1677 if (!isset($this->groups[$group]['modules'])) {
1678 $this->groups[$group]['modules'] = array();
1680 $modules = &$this->groups[$group]['modules'];
1682 $modules = &$this->modules;
1684 $modules[$name] = $config;
1688 * Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
1690 * If js caching is disabled, metadata will not be served causing YUI to calculate
1691 * module dependencies as each module is loaded.
1693 * If metadata does not exist it will be created and stored in a MUC entry.
1697 public function add_moodle_metadata() {
1699 if (!isset($this->groups['moodle'])) {
1700 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.');
1703 if (!isset($this->groups['moodle']['modules'])) {
1704 $this->groups['moodle']['modules'] = array();
1707 $cache = cache::make('core', 'yuimodules');
1708 if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
1709 $metadata = array();
1710 $metadata = $this->get_moodle_metadata();
1711 $cache->delete('metadata');
1713 // Attempt to get the metadata from the cache.
1714 if (!$metadata = $cache->get('metadata')) {
1715 $metadata = $this->get_moodle_metadata();
1716 $cache->set('metadata', $metadata);
1720 // Merge with any metadata added specific to this page which was added manually.
1721 $this->groups['moodle']['modules'] = array_merge($this->groups['moodle']['modules'],
1726 * Determine the module metadata for all moodle YUI modules.
1728 * This works through all modules capable of serving YUI modules, and attempts to get
1729 * metadata for each of those modules.
1731 * @return Array of module metadata
1733 private function get_moodle_metadata() {
1734 $moodlemodules = array();
1735 // Core isn't a plugin type or subsystem - handle it seperately.
1736 if ($module = $this->get_moodle_path_metadata(core_component::get_component_directory('core'))) {
1737 $moodlemodules = array_merge($moodlemodules, $module);
1740 // Handle other core subsystems.
1741 $subsystems = core_component::get_core_subsystems();
1742 foreach ($subsystems as $subsystem => $path) {
1743 if (is_null($path)) {
1746 if ($module = $this->get_moodle_path_metadata($path)) {
1747 $moodlemodules = array_merge($moodlemodules, $module);
1751 // And finally the plugins.
1752 $plugintypes = core_component::get_plugin_types();
1753 foreach ($plugintypes as $plugintype => $pathroot) {
1754 $pluginlist = core_component::get_plugin_list($plugintype);
1755 foreach ($pluginlist as $plugin => $path) {
1756 if ($module = $this->get_moodle_path_metadata($path)) {
1757 $moodlemodules = array_merge($moodlemodules, $module);
1762 return $moodlemodules;
1766 * Helper function process and return the YUI metadata for all of the modules under the specified path.
1768 * @param String $path the UNC path to the YUI src directory.
1769 * @return Array the complete array for frankenstyle directory.
1771 private function get_moodle_path_metadata($path) {
1772 // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
1773 $baseyui = $path . '/yui/src';
1775 if (is_dir($baseyui)) {
1776 $items = new DirectoryIterator($baseyui);
1777 foreach ($items as $item) {
1778 if ($item->isDot() or !$item->isDir()) {
1781 $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
1782 if (!is_readable($metafile)) {
1785 $metadata = file_get_contents($metafile);
1786 $modules = array_merge($modules, (array) json_decode($metadata));
1794 * Invalidate all server and client side JS caches.
1796 function js_reset_all_caches() {
1800 if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
1801 // This resolves problems when reset is requested repeatedly within 1s,
1802 // the < 1h condition prevents accidental switching to future dates
1803 // because we might not recover from it.
1804 $next = $CFG->jsrev+1;
1807 set_config('jsrev', $next);