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 stdClass 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 // 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?';
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
)) {
184 } else if (empty($CFG->jsrev
)) {
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
,
202 'root' => '2in3/' . $CFG->yui2version
.'/build/',
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(
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,
217 'root' => 'moodle/'.$jsrev.'/', // Add the rev to the root path so that we can control caching.
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;
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) {
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()) {
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
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:
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.
362 * // file: mod/xxx/view.php
363 * $PAGE->requires->jquery();
364 * $PAGE->requires->jquery_plugin('ui');
365 * $PAGE->requires->jquery_plugin('ui-css');
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');
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');
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') {
396 if ($this->headdone
) {
397 debugging('Can not add jQuery plugins after starting page output!');
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
);
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.
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
);
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
);
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'");
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'");
452 if (!empty($CFG->slasharguments
)) {
453 $url = new moodle_url("$CFG->httpswwwroot/theme/jquery.php");
454 $url->set_slashargument("/$component/$file");
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);
463 // Bad luck, fix your server!
464 debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
468 $this->jqueryplugins
[$plugin]->urls
[] = $url;
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.
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
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');
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!');
506 $this->jquerypluginoverrides
[$oldplugin] = $newplugin;
510 * Return jQuery related markup for page start.
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.
523 foreach ($this->jqueryplugins
as $name => $unused) {
524 if (isset($included[$name])) {
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
533 for ($i=0; $i<100; $i++
) {
534 $name = $this->jquerypluginoverrides
[$name];
535 if (!array_key_exists($name, $this->jquerypluginoverrides
)) {
541 // We can not do much with cyclic references here, let's use the old plugin.
543 debugging("Cyclic overrides detected for jQuery plugin '$name'");
545 } else if (empty($name)) {
546 // Developer requested removal of the plugin.
549 } else if (!isset($this->jqueryplugins
[$name])) {
550 debugging("Unknown jQuery override plugin '$name' detected");
553 } else if (isset($included[$name])) {
554 // The plugin was already included, easy.
559 $plugin = $this->jqueryplugins
[$name];
560 $urls = array_merge($urls, $plugin->urls
);
561 $included[$name] = true;
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";
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
598 protected function js_fix_url($url) {
601 if ($url instanceof moodle_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);
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));
620 $returnurl = new moodle_url($CFG->httpswwwroot
.'/lib/javascript.php');
621 $returnurl->set_slashargument('/'.$CFG->jsrev
.$url);
625 return new moodle_url($CFG->httpswwwroot
.$url);
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) {
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.
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')
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'))
668 $module = array('name' => 'core_role',
669 'fullpath' => '/admin/roles/module.js',
670 'requires' => array('node', 'cookie'));
672 case 'core_completion':
673 $module = array('name' => 'core_completion',
674 'fullpath' => '/course/completion.js');
677 $module = array('name' => 'core_dock',
678 'fullpath' => '/blocks/dock.js',
679 'requires' => array('base', 'node', 'event-custom', 'event-mouseenter', 'event-resize'),
680 'strings' => array(array('addtodock', 'block'),array('undockitem', 'block'),array('undockblock', 'block'),array('undockall', 'block'),array('thisdirectionvertical', 'langconfig'),array('hidedockpanel', 'block'),array('hidepanel', 'block')));
683 $module = array('name' => 'core_message',
684 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
685 'fullpath' => '/message/module.js');
688 $module = array('name' => 'core_group',
689 'fullpath' => '/group/module.js',
690 'requires' => array('node', 'overlay', 'event-mouseenter'));
692 case 'core_question_engine':
693 $module = array('name' => 'core_question_engine',
694 'fullpath' => '/question/qengine.js',
695 'requires' => array('node', 'event'));
698 $module = array('name' => 'core_rating',
699 'fullpath' => '/rating/module.js',
700 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
702 case 'core_dndupload':
703 $module = array('name' => 'core_dndupload',
704 'fullpath' => '/lib/form/dndupload.js',
705 'requires' => array('node', 'event', 'json', 'core_filepicker'),
706 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
707 array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesforfile', 'moodle'),
708 array('maxareabytesreached', 'moodle')
714 if ($dir = get_component_directory($component)) {
715 if (file_exists("$dir/module.js")) {
716 if (strpos($dir, $CFG->dirroot
.'/') === 0) {
717 $dir = substr($dir, strlen($CFG->dirroot
));
718 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
728 * Append YUI3 module to default YUI3 JS loader.
729 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
731 * @param string|array $module name of module (details are autodetected), or full module specification as array
734 public function js_module($module) {
737 if (empty($module)) {
738 throw new coding_exception('Missing YUI3 module name or full description.');
741 if (is_string($module)) {
742 $module = $this->find_module($module);
745 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
746 throw new coding_exception('Missing YUI3 module details.');
749 // Don't load this module if we already have, no need to!
750 if ($this->js_module_loaded($module['name'])) {
751 if (debugging('', DEBUG_DEVELOPER
)) {
752 $this->debug_moduleloadstacktraces
[$module['name']][] = format_backtrace(debug_backtrace());
757 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
758 // Add all needed strings.
759 if (!empty($module['strings'])) {
760 foreach ($module['strings'] as $string) {
761 $identifier = $string[0];
762 $component = isset($string[1]) ?
$string[1] : 'moodle';
763 $a = isset($string[2]) ?
$string[2] : null;
764 $this->string_for_js($identifier, $component, $a);
767 unset($module['strings']);
769 // Process module requirements and attempt to load each. This allows
770 // moodle modules to require each other.
771 if (!empty($module['requires'])){
772 foreach ($module['requires'] as $requirement) {
773 $rmodule = $this->find_module($requirement);
774 if (is_array($rmodule)) {
775 $this->js_module($rmodule);
780 if ($this->headdone
) {
781 $this->extramodules
[$module['name']] = $module;
783 $this->YUI_config
->add_module_config($module['name'], $module);
785 if (debugging('', DEBUG_DEVELOPER
)) {
786 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces
)) {
787 $this->debug_moduleloadstacktraces
[$module['name']] = array();
789 $this->debug_moduleloadstacktraces
[$module['name']][] = format_backtrace(debug_backtrace());
794 * Returns true if the module has already been loaded.
796 * @param string|array $module
797 * @return bool True if the module has already been loaded
799 protected function js_module_loaded($module) {
800 if (is_string($module)) {
801 $modulename = $module;
803 $modulename = $module['name'];
805 return array_key_exists($modulename, $this->YUI_config
->modules
) ||
806 array_key_exists($modulename, $this->extramodules
);
810 * Returns the stacktraces from loading js modules.
813 public function get_loaded_modules() {
814 return $this->debug_moduleloadstacktraces
;
818 * Ensure that the specified CSS file is linked to from this page.
820 * Because stylesheet links must go in the <head> part of the HTML, you must call
821 * this function before {@link get_head_code()} is called. That normally means before
822 * the call to print_header. If you call it when it is too late, an exception
825 * Even if a particular style sheet is requested more than once, it will only
828 * Please note use of this feature is strongly discouraged,
829 * it is suitable only for places where CSS is submitted directly by teachers.
830 * (Students must not be allowed to submit any external CSS because it may
831 * contain embedded javascript!). Example of correct use is mod/data.
833 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
835 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
837 public function css($stylesheet) {
840 if ($this->headdone
) {
841 throw new coding_exception('Cannot require a CSS file after <head> has been printed.', $stylesheet);
844 if ($stylesheet instanceof moodle_url
) {
846 } else if (strpos($stylesheet, '/') === 0) {
847 $stylesheet = new moodle_url($CFG->httpswwwroot
.$stylesheet);
849 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
852 $this->cssurls
[$stylesheet->out()] = $stylesheet;
856 * Add theme stylesheet to page - do not use from plugin code,
857 * this should be called only from the core renderer!
859 * @param moodle_url $stylesheet
862 public function css_theme(moodle_url
$stylesheet) {
863 $this->cssthemeurls
[] = $stylesheet;
867 * Ensure that a skip link to a given target is printed at the top of the <body>.
869 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
870 * will be thrown). That normally means you must call this before the call to print_header.
872 * If you ask for a particular skip link to be printed, it is then your responsibility
873 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
874 * page, so that the skip link goes somewhere.
876 * Even if a particular skip link is requested more than once, only one copy of it will be output.
878 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
879 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
881 public function skip_link_to($target, $linktext) {
882 if ($this->topofbodydone
) {
883 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
886 $this->skiplinks
[$target] = $linktext;
890 * !!!DEPRECATED!!! please use js_init_call() if possible
891 * Ensure that the specified JavaScript function is called from an inline script
892 * somewhere on this page.
894 * By default the call will be put in a script tag at the
895 * end of the page after initialising Y instance, since this gives best page-load
896 * performance and allows you to use YUI3 library.
898 * If you request that a particular function is called several times, then
899 * that is what will happen (unlike linking to a CSS or JS file, where only
900 * one link will be output).
902 * The main benefit of the method is the automatic encoding of all function parameters.
906 * @param string $function the name of the JavaScritp function to call. Can
907 * be a compound name like 'Y.Event.purgeElement'. Can also be
908 * used to create and object by using a 'function name' like 'new user_selector'.
909 * @param array $arguments and array of arguments to be passed to the function.
910 * When generating the function call, this will be escaped using json_encode,
911 * so passing objects and arrays should work.
912 * @param bool $ondomready If tru the function is only called when the dom is
913 * ready for manipulation.
914 * @param int $delay The delay before the function is called.
916 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
917 $where = $ondomready ?
'ondomready' : 'normal';
918 $this->jscalls
[$where][] = array($function, $arguments, $delay);
922 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
924 * @deprecated DO NOT USE
926 * @param string|array $modules One or more gallery modules to require
927 * @param string $version
928 * @param string $function
929 * @param array $arguments
930 * @param bool $ondomready
932 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
934 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER
);
935 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
939 * Creates a JavaScript function call that requires one or more modules to be loaded.
941 * This function can be used to include all of the standard YUI module types within JavaScript:
942 * - YUI3 modules [node, event, io]
943 * - YUI2 modules [yui2-*]
944 * - Moodle modules [moodle-*]
945 * - Gallery modules [gallery-*]
947 * @param array|string $modules One or more modules
948 * @param string $function The function to call once modules have been loaded
949 * @param array $arguments An array of arguments to pass to the function
950 * @param string $galleryversion The gallery version to use
951 * @param bool $ondomready
953 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
956 if (!$galleryversion) {
957 $galleryversion = '2010.04.08-12-35';
960 if (!is_array($modules)) {
961 $modules = array($modules);
963 if (empty($CFG->useexternalyui
)) {
964 // We need to set the M.yui.galleryversion to the correct version
965 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
967 // Set Y's config.gallery to the version
968 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
970 $jscode .= 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer
::function_call($function, $arguments).'});';
972 $jscode = "Y.on('domready', function() { $jscode });";
974 $this->jsinitcode
[] = $jscode;
978 * Ensure that the specified JavaScript function is called from an inline script
981 * @param string $function the name of the JavaScritp function to with init code,
982 * usually something like 'M.mod_mymodule.init'
983 * @param array $extraarguments and array of arguments to be passed to the function.
984 * The first argument is always the YUI3 Y instance with all required dependencies
986 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
987 * @param array $module JS module specification array
989 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
990 $jscode = js_writer
::function_call_with_Y($function, $extraarguments);
992 // Detect module automatically.
993 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
994 $module = $this->find_module($matches[1]);
998 $this->js_init_code($jscode, $ondomready, $module);
1002 * Add short static javascript code fragment to page footer.
1003 * This is intended primarily for loading of js modules and initialising page layout.
1004 * Ideally the JS code fragment should be stored in plugin renderer so that themes
1007 * @param string $jscode
1008 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1009 * @param array $module JS module specification array
1011 public function js_init_code($jscode, $ondomready = false, array $module = null) {
1012 $jscode = trim($jscode, " ;\n"). ';';
1015 $this->js_module($module);
1016 $modulename = $module['name'];
1017 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
1021 $jscode = "Y.on('domready', function() { $jscode });";
1024 $this->jsinitcode
[] = $jscode;
1028 * Make a language string available to JavaScript.
1030 * All the strings will be available in a M.str object in the global namespace.
1031 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
1032 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
1033 * equivalent in the current language.
1035 * The arguments to this function are just like the arguments to get_string
1036 * except that $component is not optional, and there are some aspects to consider
1037 * when the string contains {$a} placeholder.
1039 * If the string does not contain any {$a} placeholder, you can simply use
1040 * M.str.component.identifier to obtain it. If you prefer, you can call
1041 * M.util.get_string(identifier, component) to get the same result.
1043 * If you need to use {$a} placeholders, there are two options. Either the
1044 * placeholder should be substituted in PHP on server side or it should
1045 * be substituted in Javascript at client side.
1047 * To substitute the placeholder at server side, just provide the required
1048 * value for the placeholder when you require the string. Because each string
1049 * is only stored once in the JavaScript (based on $identifier and $module)
1050 * you cannot get the same string with two different values of $a. If you try,
1051 * an exception will be thrown. Once the placeholder is substituted, you can
1052 * use M.str or M.util.get_string() as shown above:
1054 * // Require the string in PHP and replace the placeholder.
1055 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
1056 * // Use the result of the substitution in Javascript.
1057 * alert(M.str.moodle.fullnamedisplay);
1059 * To substitute the placeholder at client side, use M.util.get_string()
1060 * function. It implements the same logic as {@link get_string()}:
1062 * // Require the string in PHP but keep {$a} as it is.
1063 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
1064 * // Provide the values on the fly in Javascript.
1065 * user = { firstname : 'Harry', lastname : 'Potter' }
1066 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
1068 * If you do need the same string expanded with different $a values in PHP
1069 * on server side, then the solution is to put them in your own data structure
1070 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
1072 * @param string $identifier the desired string.
1073 * @param string $component the language file to look in.
1074 * @param mixed $a any extra data to add into the string (optional).
1076 public function string_for_js($identifier, $component, $a = null) {
1078 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
1080 if (isset($this->stringsforjs_as
[$component][$identifier]) and $this->stringsforjs_as
[$component][$identifier] !== $a) {
1081 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
1082 "from lang file '$component' with different \$a parameter?");
1084 if (!isset($this->stringsforjs
[$component][$identifier])) {
1085 $this->stringsforjs
[$component][$identifier] = new lang_string($identifier, $component, $a);
1086 $this->stringsforjs_as
[$component][$identifier] = $a;
1091 * Make an array of language strings available for JS.
1093 * This function calls the above function {@link string_for_js()} for each requested
1094 * string in the $identifiers array that is passed to the argument for a single module
1095 * passed in $module.
1098 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
1100 * // The above is identical to calling:
1102 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
1103 * $PAGE->requires->string_for_js('two', 'mymod');
1104 * $PAGE->requires->string_for_js('three', 'mymod', 3);
1107 * @param array $identifiers An array of desired strings
1108 * @param string $component The module to load for
1109 * @param mixed $a This can either be a single variable that gets passed as extra
1110 * information for every string or it can be an array of mixed data where the
1111 * key for the data matches that of the identifier it is meant for.
1114 public function strings_for_js($identifiers, $component, $a = null) {
1115 foreach ($identifiers as $key => $identifier) {
1116 if (is_array($a) && array_key_exists($key, $a)) {
1121 $this->string_for_js($identifier, $component, $extra);
1126 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
1128 * Make some data from PHP available to JavaScript code.
1130 * For example, if you call
1132 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
1134 * then in JavsScript mydata.name will be 'Moodle'.
1137 * @param string $variable the the name of the JavaScript variable to assign the data to.
1138 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1139 * should be considered an experimental feature.
1140 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1141 * so passing objects and arrays should work.
1142 * @param bool $inhead initialise in head
1145 public function data_for_js($variable, $data, $inhead=false) {
1146 $where = $inhead ?
'head' : 'footer';
1147 $this->jsinitvariables
[$where][] = array($variable, $data);
1151 * Creates a YUI event handler.
1153 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1154 * @param string $event A valid DOM event (click, mousedown, change etc.)
1155 * @param string $function The name of the function to call
1156 * @param array $arguments An optional array of argument parameters to pass to the function
1158 public function event_handler($selector, $event, $function, array $arguments = null) {
1159 $this->eventhandlers
[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
1163 * Returns code needed for registering of event handlers.
1164 * @return string JS code
1166 protected function get_event_handler_code() {
1168 foreach ($this->eventhandlers
as $h) {
1169 $output .= js_writer
::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
1175 * Get the inline JavaScript code that need to appear in a particular place.
1176 * @param bool $ondomready
1179 protected function get_javascript_code($ondomready) {
1180 $where = $ondomready ?
'ondomready' : 'normal';
1182 if ($this->jscalls
[$where]) {
1183 foreach ($this->jscalls
[$where] as $data) {
1184 $output .= js_writer
::function_call($data[0], $data[1], $data[2]);
1186 if (!empty($ondomready)) {
1187 $output = " Y.on('domready', function() {\n$output\n });";
1194 * Returns js code to be executed when Y is available.
1197 protected function get_javascript_init_code() {
1198 if (count($this->jsinitcode
)) {
1199 return implode("\n", $this->jsinitcode
) . "\n";
1205 * Returns basic YUI3 JS loading code.
1206 * YUI3 is using autoloading of both CSS and JS code.
1208 * Major benefit of this compared to standard js/csss loader is much improved
1209 * caching, better browser cache utilisation, much fewer http requests.
1211 * @param moodle_page $page
1214 protected function get_yui3lib_headcode($page) {
1219 if ($this->yui3loader
->combine
) {
1220 if (!empty($page->theme
->yuicssmodules
)) {
1222 foreach ($page->theme
->yuicssmodules
as $module) {
1223 $modules[] = "$CFG->yui3version/build/$module/$module-min.css";
1225 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->comboBase
.implode('&', $modules).'" />';
1227 $code .= '<script type="text/javascript" src="'.$this->yui3loader
->comboBase
1228 .$CFG->yui3version
.'/build/simpleyui/simpleyui-min.js&'
1229 .$CFG->yui3version
.'/build/loader/loader-min.js"></script>';
1231 if (!empty($page->theme
->yuicssmodules
)) {
1232 foreach ($page->theme
->yuicssmodules
as $module) {
1233 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->base
.$module.'/'.$module.'-min.css" />';
1236 $code .= '<script type="text/javascript" src="'.$this->yui3loader
->base
.'simpleyui/simpleyui-min.js"></script>';
1237 $code .= '<script type="text/javascript" src="'.$this->yui3loader
->base
.'loader/loader-min.js"></script>';
1241 if ($this->yui3loader
->filter
=== 'RAW') {
1242 $code = str_replace('-min.css', '.css', $code);
1243 $code = str_replace('-min.js', '.js', $code);
1244 } else if ($this->yui3loader
->filter
=== 'DEBUG') {
1245 $code = str_replace('-min.css', '.css', $code);
1246 $code = str_replace('-min.js', '-debug.js', $code);
1253 * Returns html tags needed for inclusion of theme CSS.
1257 protected function get_css_code() {
1258 // First of all the theme CSS, then any custom CSS
1259 // Please note custom CSS is strongly discouraged,
1260 // because it can not be overridden by themes!
1261 // It is suitable only for things like mod/data which accepts CSS from teachers.
1262 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1264 // This line of code may look funny but it is currently required in order
1265 // to avoid MASSIVE display issues in Internet Explorer.
1266 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1267 // ignored whenever another resource is added until such time as a redraw
1268 // is forced, usually by moving the mouse over the affected element.
1269 $code = html_writer
::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1271 $urls = $this->cssthemeurls +
$this->cssurls
;
1272 foreach ($urls as $url) {
1273 $attributes['href'] = $url;
1274 $code .= html_writer
::empty_tag('link', $attributes) . "\n";
1275 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1276 unset($attributes['id']);
1283 * Adds extra modules specified after printing of page header.
1287 protected function get_extra_modules_code() {
1288 if (empty($this->extramodules
)) {
1291 return html_writer
::script(js_writer
::function_call('M.yui.add_module', array($this->extramodules
)));
1295 * Generate any HTML that needs to go inside the <head> tag.
1297 * Normally, this method is called automatically by the code that prints the
1298 * <head> tag. You should not normally need to call it in your own code.
1300 * @param moodle_page $page
1301 * @param core_renderer $renderer
1302 * @return string the HTML code to to inside the <head> tag.
1304 public function get_head_code(moodle_page
$page, core_renderer
$renderer) {
1307 // Note: the $page and $output are not stored here because it would
1308 // create circular references in memory which prevents garbage collection.
1309 $this->init_requirements_data($page, $renderer);
1313 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1314 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1315 // this needs to be done before including any other script.
1316 $js = "var M = {}; M.yui = {};\n";
1317 $js .= $this->YUI_config
->get_config_functions();
1318 $js .= js_writer
::set_variable('YUI_config', $this->YUI_config
, false) . "\n";
1319 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1320 $js .= js_writer
::set_variable('M.cfg', $this->M_cfg
, false);
1322 $js = $this->YUI_config
->update_header_js($js);
1323 $output .= html_writer
::script($js);
1325 // YUI3 JS and CSS need to be loaded in the header but after the YUI_config has been created.
1326 // They should be cached well by the browser.
1327 $output .= $this->get_yui3lib_headcode($page);
1329 // Add hacked jQuery support, it is not intended for standard Moodle distribution!
1330 $output .= $this->get_jquery_headcode();
1332 // Now theme CSS + custom CSS in this specific order.
1333 $output .= $this->get_css_code();
1335 // Link our main JS file, all core stuff should be there.
1336 $output .= html_writer
::script('', $this->js_fix_url('/lib/javascript-static.js'));
1339 if ($this->jsinitvariables
['head']) {
1341 foreach ($this->jsinitvariables
['head'] as $data) {
1342 list($var, $value) = $data;
1343 $js .= js_writer
::set_variable($var, $value, true);
1345 $output .= html_writer
::script($js);
1348 // All the other linked things from HEAD - there should be as few as possible.
1349 if ($this->jsincludes
['head']) {
1350 foreach ($this->jsincludes
['head'] as $url) {
1351 $output .= html_writer
::script('', $url);
1355 // Mark head sending done, it is not possible to anything there.
1356 $this->headdone
= true;
1362 * Generate any HTML that needs to go at the start of the <body> tag.
1364 * Normally, this method is called automatically by the code that prints the
1365 * <head> tag. You should not normally need to call it in your own code.
1367 * @return string the HTML code to go at the start of the <body> tag.
1369 public function get_top_of_body_code() {
1370 // First the skip links.
1372 $attributes = array('class'=>'skip');
1373 foreach ($this->skiplinks
as $url => $text) {
1374 $attributes['href'] = '#' . $url;
1375 $links .= html_writer
::tag('a', $text, $attributes);
1377 $output = html_writer
::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1379 // Then the clever trick for hiding of things not needed when JS works.
1380 $output .= html_writer
::script("document.body.className += ' jsenabled';") . "\n";
1381 $this->topofbodydone
= true;
1386 * Generate any HTML that needs to go at the end of the page.
1388 * Normally, this method is called automatically by the code that prints the
1389 * page footer. You should not normally need to call it in your own code.
1391 * @return string the HTML code to to at the end of the page.
1393 public function get_end_code() {
1396 // Add other requested modules.
1397 $output = $this->get_extra_modules_code();
1399 // All the other linked scripts - there should be as few as possible.
1400 if ($this->jsincludes
['footer']) {
1401 foreach ($this->jsincludes
['footer'] as $url) {
1402 $output .= html_writer
::script('', $url);
1406 // Add all needed strings.
1407 if (!empty($this->stringsforjs
)) {
1409 foreach ($this->stringsforjs
as $component=>$v) {
1410 foreach($v as $indentifier => $langstring) {
1411 $strings[$component][$indentifier] = $langstring->out();
1414 $output .= html_writer
::script(js_writer
::set_variable('M.str', $strings));
1418 if ($this->jsinitvariables
['footer']) {
1420 foreach ($this->jsinitvariables
['footer'] as $data) {
1421 list($var, $value) = $data;
1422 $js .= js_writer
::set_variable($var, $value, true);
1424 $output .= html_writer
::script($js);
1427 $inyuijs = $this->get_javascript_code(false);
1428 $ondomreadyjs = $this->get_javascript_code(true);
1429 $jsinit = $this->get_javascript_init_code();
1430 $handlersjs = $this->get_event_handler_code();
1432 // There is no global Y, make sure it is available in your scope.
1433 $js = "YUI().use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1435 $output .= html_writer
::script($js);
1441 * Have we already output the code in the <head> tag?
1445 public function is_head_done() {
1446 return $this->headdone
;
1450 * Have we already output the code at the start of the <body> tag?
1454 public function is_top_of_body_done() {
1455 return $this->topofbodydone
;
1460 * This class represents the YUI configuration.
1462 * @copyright 2013 Andrew Nicols
1463 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1470 * These settings must be public so that when the object is converted to json they are exposed.
1471 * Note: Some of these are camelCase because YUI uses camelCase variable names.
1473 * The settings are described and documented in the YUI API at:
1474 * - http://yuilibrary.com/yui/docs/api/classes/config.html
1475 * - http://yuilibrary.com/yui/docs/api/classes/Loader.html
1477 public $debug = false;
1481 public $filter = null;
1482 public $insertBefore = 'firstthemesheet';
1483 public $groups = array();
1484 public $modules = array();
1487 * @var array List of functions used by the YUI Loader group pattern recognition.
1489 protected $jsconfigfunctions = array();
1492 * Create a new group within the YUI_config system.
1494 * @param String $name The name of the group. This must be unique and
1495 * not previously used.
1496 * @param Array $config The configuration for this group.
1499 public function add_group($name, $config) {
1500 if (isset($this->groups
[$name])) {
1501 throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
1503 $this->groups
[$name] = $config;
1507 * Update an existing group configuration
1509 * Note, any existing configuration for that group will be wiped out.
1510 * This includes module configuration.
1512 * @param String $name The name of the group. This must be unique and
1513 * not previously used.
1514 * @param Array $config The configuration for this group.
1517 public function update_group($name, $config) {
1518 if (!isset($this->groups
[$name])) {
1519 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.');
1521 $this->groups
[$name] = $config;
1525 * Set the value of a configuration function used by the YUI Loader's pattern testing.
1527 * Only the body of the function should be passed, and not the whole function wrapper.
1529 * The JS function your write will be passed a single argument 'name' containing the
1530 * name of the module being loaded.
1532 * @param $function String the body of the JavaScript function. This should be used i
1533 * @return String the name of the function to use in the group pattern configuration.
1535 public function set_config_function($function) {
1536 $configname = 'yui' . (count($this->jsconfigfunctions
) +
1) . 'ConfigFn';
1537 if (isset($this->jsconfigfunctions
[$configname])) {
1538 throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
1540 $this->jsconfigfunctions
[$configname] = $function;
1541 return '@' . $configname . '@';
1545 * Retrieve the list of JavaScript functions for YUI_config groups.
1547 * @return String The complete set of config functions
1549 public function get_config_functions() {
1550 $configfunctions = '';
1551 foreach ($this->jsconfigfunctions
as $functionname => $function) {
1552 $configfunctions .= "var {$functionname} = function(me) {";
1553 $configfunctions .= $function;
1554 $configfunctions .= "};\n";
1556 return $configfunctions;
1560 * Update the header JavaScript with any required modification for the YUI Loader.
1562 * @param $js String The JavaScript to manipulate.
1563 * @return String the modified JS string.
1565 public function update_header_js($js) {
1566 // Update the names of the the configFn variables.
1567 // The PHP json_encode function cannot handle literal names so we have to wrap
1568 // them in @ and then replace them with literals of the same function name.
1569 foreach ($this->jsconfigfunctions
as $functionname => $function) {
1570 $js = str_replace('"@' . $functionname . '@"', $functionname, $js);
1576 * Add configuration for a specific module.
1578 * @param String $name The name of the module to add configuration for.
1579 * @param Array $config The configuration for the specified module.
1580 * @param String $group The name of the group to add configuration for.
1581 * If not specified, then this module is added to the global
1585 public function add_module_config($name, $config, $group = null) {
1587 if (!isset($this->groups
[$name])) {
1588 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.');
1590 if (!isset($this->groups
[$group]['modules'])) {
1591 $this->groups
[$group]['modules'] = array();
1593 $modules = &$this->groups
[$group]['modules'];
1595 $modules = &$this->modules
;
1597 $modules[$name] = $config;
1601 * Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
1603 * If js caching is disabled, metadata will not be served causing YUI to calculate
1604 * module dependencies as each module is loaded.
1606 * If metadata does not exist it will be created and stored in a MUC entry.
1610 public function add_moodle_metadata() {
1612 if (!isset($this->groups
['moodle'])) {
1613 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.');
1616 if (!isset($this->groups
['moodle']['modules'])) {
1617 $this->groups
['moodle']['modules'] = array();
1620 $cache = cache
::make('core', 'yuimodules');
1621 if (!isset($CFG->jsrev
) ||
$CFG->jsrev
== -1) {
1622 $metadata = array();
1623 $cache->delete('metadata');
1625 // Attempt to get the metadata from the cache.
1626 if (!$metadata = $cache->get('metadata')) {
1627 $metadata = $this->get_moodle_metadata();
1628 $cache->set('metadata', $metadata);
1632 // Merge with any metadata added specific to this page which was added manually.
1633 $this->groups
['moodle']['modules'] = array_merge($this->groups
['moodle']['modules'],
1638 * Determine the module metadata for all moodle YUI modules.
1640 * This works through all modules capable of serving YUI modules, and attempts to get
1641 * metadata for each of those modules.
1643 * @return Array of module metadata
1645 private function get_moodle_metadata() {
1646 $moodlemodules = array();
1647 // Core isn't a plugin type or subsystem - handle it seperately.
1648 if ($module = $this->get_moodle_path_metadata(get_component_directory('core'))) {
1649 $moodlemodules = array_merge($moodlemodules, $module);
1652 // Handle other core subsystems.
1653 $subsystems = get_core_subsystems();
1654 foreach ($subsystems as $subsystem => $path) {
1655 if (is_null($path)) {
1658 $path = get_component_directory($subsystem);
1659 if ($module = $this->get_moodle_path_metadata($path)) {
1660 $moodlemodules = array_merge($moodlemodules, $module);
1664 // And finally the plugins.
1665 $plugintypes = get_plugin_types();
1666 foreach ($plugintypes as $plugintype => $pathroot) {
1667 $pluginlist = get_plugin_list($plugintype);
1668 foreach ($pluginlist as $plugin => $path) {
1669 if ($module = $this->get_moodle_path_metadata($path)) {
1670 $moodlemodules = array_merge($moodlemodules, $module);
1675 return $moodlemodules;
1679 * Helper function process and return the YUI metadata for all of the modules under the specified path.
1681 * @param String $path the UNC path to the YUI src directory.
1682 * @return Array the complete array for frankenstyle directory.
1684 private function get_moodle_path_metadata($path) {
1685 // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
1686 $baseyui = $path . '/yui/src';
1688 if (is_dir($baseyui)) {
1689 $items = new DirectoryIterator($baseyui);
1690 foreach ($items as $item) {
1691 if ($item->isDot() or !$item->isDir()) {
1694 $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
1695 if (!is_readable($metafile)) {
1698 $metadata = file_get_contents($metafile);
1699 $modules = array_merge($modules, (array) json_decode($metadata));
1707 * Invalidate all server and client side JS caches.
1709 function js_reset_all_caches() {
1711 require_once("$CFG->libdir/filelib.php");
1714 if (isset($CFG->jsrev
) and $next <= $CFG->jsrev
and $CFG->jsrev
- $next < 60*60) {
1715 // This resolves problems when reset is requested repeatedly within 1s,
1716 // the < 1h condition prevents accidental switching to future dates
1717 // because we might not recover from it.
1718 $next = $CFG->jsrev+
1;
1721 set_config('jsrev', $next);
1722 fulldelete("$CFG->cachedir/js");