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 // 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_source('lib/yui/config/yui2.js');
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_source('lib/yui/config/moodle.js');
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'));
251 * Initialise with the bits of JavaScript that every Moodle page should have.
253 * @param moodle_page $page
254 * @param core_renderer $renderer
256 protected function init_requirements_data(moodle_page
$page, core_renderer
$renderer) {
259 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
260 // Otherwise, in some situations, users will get warnings about insecure content
261 // on secure pages from their web browser.
263 $this->M_cfg
= array(
264 'wwwroot' => $CFG->httpswwwroot
, // Yes, really. See above.
265 'sesskey' => sesskey(),
266 'loadingicon' => $renderer->pix_url('i/loading_small', 'moodle')->out(false),
267 'themerev' => theme_get_revision(),
268 'slasharguments' => (int)(!empty($CFG->slasharguments
)),
269 'theme' => $page->theme
->name
,
270 'jsrev' => ((empty($CFG->cachejs
) or empty($CFG->jsrev
)) ?
-1 : $CFG->jsrev
),
271 'svgicons' => $page->theme
->use_svg_icons()
273 if (debugging('', DEBUG_DEVELOPER
)) {
274 $this->M_cfg
['developerdebug'] = true;
277 // Accessibility stuff.
278 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
280 // Add strings used on many pages.
281 $this->string_for_js('confirmation', 'admin');
282 $this->string_for_js('cancel', 'moodle');
283 $this->string_for_js('yes', 'moodle');
285 // Alter links in top frame to break out of frames.
286 if ($page->pagelayout
=== 'frametop') {
287 $this->js_init_call('M.util.init_frametop');
290 // Include block drag/drop if editing is on
291 if ($page->user_is_editing()) {
293 'courseid' => $page->course
->id
,
294 'pagetype' => $page->pagetype
,
295 'pagelayout' => $page->pagelayout
,
296 'subpage' => $page->subpage
,
297 'regions' => $page->blocks
->get_regions(),
298 'contextid' => $page->context
->id
,
300 if (!empty($page->cm
->id
)) {
301 $params['cmid'] = $page->cm
->id
;
303 $page->requires
->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
308 * Ensure that the specified JavaScript file is linked to from this page.
310 * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
311 * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
313 * By default the link is put at the end of the page, since this gives best page-load performance.
315 * Even if a particular script is requested more than once, it will only be linked
318 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
319 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
320 * @param bool $inhead initialise in head
322 public function js($url, $inhead = false) {
323 $url = $this->js_fix_url($url);
324 $where = $inhead ?
'head' : 'footer';
325 $this->jsincludes
[$where][$url->out()] = $url;
329 * Request inclusion of jQuery library in the page.
331 * NOTE: this should not be used in official Moodle distribution!
333 * We are going to bundle jQuery 1.9.x until we drop support
334 * all support for IE 6-8. Use $PAGE->requires->jquery_plugin('migrate')
335 * for code written for earlier jQuery versions.
337 * {@see http://docs.moodle.org/dev/jQuery}
339 public function jquery() {
340 $this->jquery_plugin('jquery');
344 * Request inclusion of jQuery plugin.
346 * NOTE: this should not be used in official Moodle distribution!
348 * jQuery plugins are located in plugin/jquery/* subdirectory,
349 * plugin/jquery/plugins.php lists all available plugins.
351 * Included core plugins:
353 * - jQuery Migrate (useful for code written for previous UI version)
355 * Add-ons may include extra jQuery plugins in jquery/ directory,
356 * plugins.php file defines the mapping between plugin names and
357 * necessary page includes.
361 * // file: mod/xxx/view.php
362 * $PAGE->requires->jquery();
363 * $PAGE->requires->jquery_plugin('ui');
364 * $PAGE->requires->jquery_plugin('ui-css');
368 * // file: theme/yyy/lib.php
369 * function theme_yyy_page_init(moodle_page $page) {
370 * $page->requires->jquery();
371 * $page->requires->jquery_plugin('ui');
372 * $page->requires->jquery_plugin('ui-css');
377 * // file: blocks/zzz/block_zzz.php
378 * public function get_required_javascript() {
379 * parent::get_required_javascript();
380 * $this->page->requires->jquery();
381 * $page->requires->jquery_plugin('ui');
382 * $page->requires->jquery_plugin('ui-css');
386 * {@see http://docs.moodle.org/dev/jQuery}
388 * @param string $plugin name of the jQuery plugin as defined in jquery/plugins.php
389 * @param string $component name of the component
390 * @return bool success
392 public function jquery_plugin($plugin, $component = 'core') {
395 if ($this->headdone
) {
396 debugging('Can not add jQuery plugins after starting page output!');
400 if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css', 'migrate'))) {
401 debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER
);
403 } else if ($component !== 'core' and strpos($component, '_') === false) {
404 // Let's normalise the legacy activity names, Frankenstyle rulez!
405 $component = 'mod_' . $component;
408 if (empty($this->jqueryplugins
) and ($component !== 'core' or $plugin !== 'jquery')) {
409 // Make sure the jQuery itself is always loaded first,
410 // the order of all other plugins depends on order of $PAGE_>requires->.
411 $this->jquery_plugin('jquery', 'core');
414 if (isset($this->jqueryplugins
[$plugin])) {
415 // No problem, we already have something, first Moodle plugin to register the jQuery plugin wins.
419 $componentdir = core_component
::get_component_directory($component);
420 if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
421 debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER
);
426 require("$componentdir/jquery/plugins.php");
428 if (!isset($plugins[$plugin])) {
429 debugging("jQuery plugin '$plugin' can not be found in component '$component'.", DEBUG_DEVELOPER
);
433 $this->jqueryplugins
[$plugin] = new stdClass();
434 $this->jqueryplugins
[$plugin]->plugin
= $plugin;
435 $this->jqueryplugins
[$plugin]->component
= $component;
436 $this->jqueryplugins
[$plugin]->urls
= array();
438 foreach ($plugins[$plugin]['files'] as $file) {
439 if (debugging('', DEBUG_DEVELOPER
)) {
440 if (!file_exists("$componentdir/jquery/$file")) {
441 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
444 $file = str_replace('.min.css', '.css', $file);
445 $file = str_replace('.min.js', '.js', $file);
447 if (!file_exists("$componentdir/jquery/$file")) {
448 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
451 if (!empty($CFG->slasharguments
)) {
452 $url = new moodle_url("$CFG->httpswwwroot/theme/jquery.php");
453 $url->set_slashargument("/$component/$file");
456 // This is not really good, we need slasharguments for relative links, this means no caching...
457 $path = realpath("$componentdir/jquery/$file");
458 if (strpos($path, $CFG->dirroot
) === 0) {
459 $url = $CFG->httpswwwroot
.preg_replace('/^'.preg_quote($CFG->dirroot
, '/').'/', '', $path);
460 $url = new moodle_url($url);
462 // Bad luck, fix your server!
463 debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
467 $this->jqueryplugins
[$plugin]->urls
[] = $url;
474 * Request replacement of one jQuery plugin by another.
476 * This is useful when themes want to replace the jQuery UI theme,
477 * the problem is that theme can not prevent others from including the core ui-css plugin.
480 * 1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
481 * 2/ write theme/yourtheme/jquery/plugins.php
482 * 3/ init jQuery from theme
485 * // file theme/yourtheme/lib.php
486 * function theme_yourtheme_page_init($page) {
487 * $page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
488 * $page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
492 * This code prevents loading of standard 'ui-css' which my be requested by other plugins,
493 * the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
495 * {@see http://docs.moodle.org/dev/jQuery}
497 * @param string $oldplugin original plugin
498 * @param string $newplugin the replacement
500 public function jquery_override_plugin($oldplugin, $newplugin) {
501 if ($this->headdone
) {
502 debugging('Can not override jQuery plugins after starting page output!');
505 $this->jquerypluginoverrides
[$oldplugin] = $newplugin;
509 * Return jQuery related markup for page start.
512 protected function get_jquery_headcode() {
513 if (empty($this->jqueryplugins
['jquery'])) {
514 // If nobody requested jQuery then do not bother to load anything.
515 // This may be useful for themes that want to override 'ui-css' only if requested by something else.
522 foreach ($this->jqueryplugins
as $name => $unused) {
523 if (isset($included[$name])) {
526 if (array_key_exists($name, $this->jquerypluginoverrides
)) {
527 // The following loop tries to resolve the replacements,
528 // use max 100 iterations to prevent infinite loop resulting
532 for ($i=0; $i<100; $i++
) {
533 $name = $this->jquerypluginoverrides
[$name];
534 if (!array_key_exists($name, $this->jquerypluginoverrides
)) {
540 // We can not do much with cyclic references here, let's use the old plugin.
542 debugging("Cyclic overrides detected for jQuery plugin '$name'");
544 } else if (empty($name)) {
545 // Developer requested removal of the plugin.
548 } else if (!isset($this->jqueryplugins
[$name])) {
549 debugging("Unknown jQuery override plugin '$name' detected");
552 } else if (isset($included[$name])) {
553 // The plugin was already included, easy.
558 $plugin = $this->jqueryplugins
[$name];
559 $urls = array_merge($urls, $plugin->urls
);
560 $included[$name] = true;
564 $attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
565 foreach ($urls as $url) {
566 if (preg_match('/\.js$/', $url)) {
567 $output .= html_writer
::script('', $url);
568 } else if (preg_match('/\.css$/', $url)) {
569 $attributes['href'] = $url;
570 $output .= html_writer
::empty_tag('link', $attributes) . "\n";
578 * This method was used to load YUI2 libraries into global scope,
579 * use YUI 2in3 instead. Every YUI2 module is represented as a yui2-*
580 * sandboxed module in YUI3 code via Y.YUI2. property.
582 * {@see http://tracker.moodle.org/browse/MDL-34741}
584 * @param string|array $libname
585 * @deprecated since 2.4
587 public function yui2_lib($libname) {
588 throw new coding_exception('PAGE->yui2_lib() is not available any more, use YUI 2in3 instead, see MDL-34741 for more information.');
592 * Returns the actual url through which a script is served.
594 * @param moodle_url|string $url full moodle url, or shortened path to script
597 protected function js_fix_url($url) {
600 if ($url instanceof moodle_url
) {
602 } else if (strpos($url, '/') === 0) {
603 // Fix the admin links if needed.
604 if ($CFG->admin
!== 'admin') {
605 if (strpos($url, "/admin/") === 0) {
606 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
610 // Check file existence only when in debug mode.
611 if (!file_exists($CFG->dirroot
. strtok($url, '?'))) {
612 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
615 if (substr($url, -3) === '.js') {
616 if (empty($CFG->cachejs
) or !isset($CFG->jsrev
)) {
619 $jsrev = (int)$CFG->jsrev
;
621 if (empty($CFG->slasharguments
)) {
622 return new moodle_url($CFG->httpswwwroot
.'/lib/javascript.php', array('rev'=>$jsrev, 'jsfile'=>$url));
624 $returnurl = new moodle_url($CFG->httpswwwroot
.'/lib/javascript.php');
625 $returnurl->set_slashargument('/'.$jsrev.$url);
629 return new moodle_url($CFG->httpswwwroot
.$url);
632 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
637 * Find out if JS module present and return details.
639 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
640 * @return array description of module or null if not found
642 protected function find_module($component) {
647 if (strpos($component, 'core_') === 0) {
648 // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
649 // so that we do nto have to repeat the definition of these modules over and over again.
651 case 'core_filepicker':
652 $module = array('name' => 'core_filepicker',
653 'fullpath' => '/repository/filepicker.js',
654 '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'),
655 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
656 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
657 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
658 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
659 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
660 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
661 array('referencesexist', 'repository')
665 $module = array('name' => 'core_comment',
666 'fullpath' => '/comment/comment.js',
667 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
668 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
672 $module = array('name' => 'core_role',
673 'fullpath' => '/admin/roles/module.js',
674 'requires' => array('node', 'cookie'));
676 case 'core_completion':
677 $module = array('name' => 'core_completion',
678 'fullpath' => '/course/completion.js');
681 $module = array('name' => 'core_message',
682 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
683 'fullpath' => '/message/module.js');
686 $module = array('name' => 'core_group',
687 'fullpath' => '/group/module.js',
688 'requires' => array('node', 'overlay', 'event-mouseenter'));
690 case 'core_question_engine':
691 $module = array('name' => 'core_question_engine',
692 'fullpath' => '/question/qengine.js',
693 'requires' => array('node', 'event'));
696 $module = array('name' => 'core_rating',
697 'fullpath' => '/rating/module.js',
698 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
700 case 'core_dndupload':
701 $module = array('name' => 'core_dndupload',
702 'fullpath' => '/lib/form/dndupload.js',
703 'requires' => array('node', 'event', 'json', 'core_filepicker'),
704 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
705 array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesforfile', 'moodle'),
706 array('maxareabytesreached', 'moodle')
712 if ($dir = core_component
::get_component_directory($component)) {
713 if (file_exists("$dir/module.js")) {
714 if (strpos($dir, $CFG->dirroot
.'/') === 0) {
715 $dir = substr($dir, strlen($CFG->dirroot
));
716 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
726 * Append YUI3 module to default YUI3 JS loader.
727 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
729 * @param string|array $module name of module (details are autodetected), or full module specification as array
732 public function js_module($module) {
735 if (empty($module)) {
736 throw new coding_exception('Missing YUI3 module name or full description.');
739 if (is_string($module)) {
740 $module = $this->find_module($module);
743 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
744 throw new coding_exception('Missing YUI3 module details.');
747 // Don't load this module if we already have, no need to!
748 if ($this->js_module_loaded($module['name'])) {
749 if (debugging('', DEBUG_DEVELOPER
)) {
750 $this->debug_moduleloadstacktraces
[$module['name']][] = format_backtrace(debug_backtrace());
755 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
756 // Add all needed strings.
757 if (!empty($module['strings'])) {
758 foreach ($module['strings'] as $string) {
759 $identifier = $string[0];
760 $component = isset($string[1]) ?
$string[1] : 'moodle';
761 $a = isset($string[2]) ?
$string[2] : null;
762 $this->string_for_js($identifier, $component, $a);
765 unset($module['strings']);
767 // Process module requirements and attempt to load each. This allows
768 // moodle modules to require each other.
769 if (!empty($module['requires'])){
770 foreach ($module['requires'] as $requirement) {
771 $rmodule = $this->find_module($requirement);
772 if (is_array($rmodule)) {
773 $this->js_module($rmodule);
778 if ($this->headdone
) {
779 $this->extramodules
[$module['name']] = $module;
781 $this->YUI_config
->add_module_config($module['name'], $module);
783 if (debugging('', DEBUG_DEVELOPER
)) {
784 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces
)) {
785 $this->debug_moduleloadstacktraces
[$module['name']] = array();
787 $this->debug_moduleloadstacktraces
[$module['name']][] = format_backtrace(debug_backtrace());
792 * Returns true if the module has already been loaded.
794 * @param string|array $module
795 * @return bool True if the module has already been loaded
797 protected function js_module_loaded($module) {
798 if (is_string($module)) {
799 $modulename = $module;
801 $modulename = $module['name'];
803 return array_key_exists($modulename, $this->YUI_config
->modules
) ||
804 array_key_exists($modulename, $this->extramodules
);
808 * Returns the stacktraces from loading js modules.
811 public function get_loaded_modules() {
812 return $this->debug_moduleloadstacktraces
;
816 * Ensure that the specified CSS file is linked to from this page.
818 * Because stylesheet links must go in the <head> part of the HTML, you must call
819 * this function before {@link get_head_code()} is called. That normally means before
820 * the call to print_header. If you call it when it is too late, an exception
823 * Even if a particular style sheet is requested more than once, it will only
826 * Please note use of this feature is strongly discouraged,
827 * it is suitable only for places where CSS is submitted directly by teachers.
828 * (Students must not be allowed to submit any external CSS because it may
829 * contain embedded javascript!). Example of correct use is mod/data.
831 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
833 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
835 public function css($stylesheet) {
838 if ($this->headdone
) {
839 throw new coding_exception('Cannot require a CSS file after <head> has been printed.', $stylesheet);
842 if ($stylesheet instanceof moodle_url
) {
844 } else if (strpos($stylesheet, '/') === 0) {
845 $stylesheet = new moodle_url($CFG->httpswwwroot
.$stylesheet);
847 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
850 $this->cssurls
[$stylesheet->out()] = $stylesheet;
854 * Add theme stylesheet to page - do not use from plugin code,
855 * this should be called only from the core renderer!
857 * @param moodle_url $stylesheet
860 public function css_theme(moodle_url
$stylesheet) {
861 $this->cssthemeurls
[] = $stylesheet;
865 * Ensure that a skip link to a given target is printed at the top of the <body>.
867 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
868 * will be thrown). That normally means you must call this before the call to print_header.
870 * If you ask for a particular skip link to be printed, it is then your responsibility
871 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
872 * page, so that the skip link goes somewhere.
874 * Even if a particular skip link is requested more than once, only one copy of it will be output.
876 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
877 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
879 public function skip_link_to($target, $linktext) {
880 if ($this->topofbodydone
) {
881 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
884 $this->skiplinks
[$target] = $linktext;
888 * !!!DEPRECATED!!! please use js_init_call() if possible
889 * Ensure that the specified JavaScript function is called from an inline script
890 * somewhere on this page.
892 * By default the call will be put in a script tag at the
893 * end of the page after initialising Y instance, since this gives best page-load
894 * performance and allows you to use YUI3 library.
896 * If you request that a particular function is called several times, then
897 * that is what will happen (unlike linking to a CSS or JS file, where only
898 * one link will be output).
900 * The main benefit of the method is the automatic encoding of all function parameters.
904 * @param string $function the name of the JavaScritp function to call. Can
905 * be a compound name like 'Y.Event.purgeElement'. Can also be
906 * used to create and object by using a 'function name' like 'new user_selector'.
907 * @param array $arguments and array of arguments to be passed to the function.
908 * When generating the function call, this will be escaped using json_encode,
909 * so passing objects and arrays should work.
910 * @param bool $ondomready If tru the function is only called when the dom is
911 * ready for manipulation.
912 * @param int $delay The delay before the function is called.
914 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
915 $where = $ondomready ?
'ondomready' : 'normal';
916 $this->jscalls
[$where][] = array($function, $arguments, $delay);
920 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
922 * @deprecated DO NOT USE
924 * @param string|array $modules One or more gallery modules to require
925 * @param string $version
926 * @param string $function
927 * @param array $arguments
928 * @param bool $ondomready
930 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
932 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER
);
933 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
937 * Creates a JavaScript function call that requires one or more modules to be loaded.
939 * This function can be used to include all of the standard YUI module types within JavaScript:
940 * - YUI3 modules [node, event, io]
941 * - YUI2 modules [yui2-*]
942 * - Moodle modules [moodle-*]
943 * - Gallery modules [gallery-*]
945 * @param array|string $modules One or more modules
946 * @param string $function The function to call once modules have been loaded
947 * @param array $arguments An array of arguments to pass to the function
948 * @param string $galleryversion The gallery version to use
949 * @param bool $ondomready
951 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
954 if (!$galleryversion) {
955 $galleryversion = '2010.04.08-12-35';
958 if (!is_array($modules)) {
959 $modules = array($modules);
961 if (empty($CFG->useexternalyui
)) {
962 // We need to set the M.yui.galleryversion to the correct version
963 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
965 // Set Y's config.gallery to the version
966 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
968 $jscode .= 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer
::function_call($function, $arguments).'});';
970 $jscode = "Y.on('domready', function() { $jscode });";
972 $this->jsinitcode
[] = $jscode;
976 * Ensure that the specified JavaScript function is called from an inline script
979 * @param string $function the name of the JavaScritp function to with init code,
980 * usually something like 'M.mod_mymodule.init'
981 * @param array $extraarguments and array of arguments to be passed to the function.
982 * The first argument is always the YUI3 Y instance with all required dependencies
984 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
985 * @param array $module JS module specification array
987 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
988 $jscode = js_writer
::function_call_with_Y($function, $extraarguments);
990 // Detect module automatically.
991 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
992 $module = $this->find_module($matches[1]);
996 $this->js_init_code($jscode, $ondomready, $module);
1000 * Add short static javascript code fragment to page footer.
1001 * This is intended primarily for loading of js modules and initialising page layout.
1002 * Ideally the JS code fragment should be stored in plugin renderer so that themes
1005 * @param string $jscode
1006 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1007 * @param array $module JS module specification array
1009 public function js_init_code($jscode, $ondomready = false, array $module = null) {
1010 $jscode = trim($jscode, " ;\n"). ';';
1013 $this->js_module($module);
1014 $modulename = $module['name'];
1015 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
1019 $jscode = "Y.on('domready', function() { $jscode });";
1022 $this->jsinitcode
[] = $jscode;
1026 * Make a language string available to JavaScript.
1028 * All the strings will be available in a M.str object in the global namespace.
1029 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
1030 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
1031 * equivalent in the current language.
1033 * The arguments to this function are just like the arguments to get_string
1034 * except that $component is not optional, and there are some aspects to consider
1035 * when the string contains {$a} placeholder.
1037 * If the string does not contain any {$a} placeholder, you can simply use
1038 * M.str.component.identifier to obtain it. If you prefer, you can call
1039 * M.util.get_string(identifier, component) to get the same result.
1041 * If you need to use {$a} placeholders, there are two options. Either the
1042 * placeholder should be substituted in PHP on server side or it should
1043 * be substituted in Javascript at client side.
1045 * To substitute the placeholder at server side, just provide the required
1046 * value for the placeholder when you require the string. Because each string
1047 * is only stored once in the JavaScript (based on $identifier and $module)
1048 * you cannot get the same string with two different values of $a. If you try,
1049 * an exception will be thrown. Once the placeholder is substituted, you can
1050 * use M.str or M.util.get_string() as shown above:
1052 * // Require the string in PHP and replace the placeholder.
1053 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
1054 * // Use the result of the substitution in Javascript.
1055 * alert(M.str.moodle.fullnamedisplay);
1057 * To substitute the placeholder at client side, use M.util.get_string()
1058 * function. It implements the same logic as {@link get_string()}:
1060 * // Require the string in PHP but keep {$a} as it is.
1061 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
1062 * // Provide the values on the fly in Javascript.
1063 * user = { firstname : 'Harry', lastname : 'Potter' }
1064 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
1066 * If you do need the same string expanded with different $a values in PHP
1067 * on server side, then the solution is to put them in your own data structure
1068 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
1070 * @param string $identifier the desired string.
1071 * @param string $component the language file to look in.
1072 * @param mixed $a any extra data to add into the string (optional).
1074 public function string_for_js($identifier, $component, $a = null) {
1076 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
1078 if (isset($this->stringsforjs_as
[$component][$identifier]) and $this->stringsforjs_as
[$component][$identifier] !== $a) {
1079 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
1080 "from lang file '$component' with different \$a parameter?");
1082 if (!isset($this->stringsforjs
[$component][$identifier])) {
1083 $this->stringsforjs
[$component][$identifier] = new lang_string($identifier, $component, $a);
1084 $this->stringsforjs_as
[$component][$identifier] = $a;
1089 * Make an array of language strings available for JS.
1091 * This function calls the above function {@link string_for_js()} for each requested
1092 * string in the $identifiers array that is passed to the argument for a single module
1093 * passed in $module.
1096 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
1098 * // The above is identical to calling:
1100 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
1101 * $PAGE->requires->string_for_js('two', 'mymod');
1102 * $PAGE->requires->string_for_js('three', 'mymod', 3);
1105 * @param array $identifiers An array of desired strings
1106 * @param string $component The module to load for
1107 * @param mixed $a This can either be a single variable that gets passed as extra
1108 * information for every string or it can be an array of mixed data where the
1109 * key for the data matches that of the identifier it is meant for.
1112 public function strings_for_js($identifiers, $component, $a = null) {
1113 foreach ($identifiers as $key => $identifier) {
1114 if (is_array($a) && array_key_exists($key, $a)) {
1119 $this->string_for_js($identifier, $component, $extra);
1124 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
1126 * Make some data from PHP available to JavaScript code.
1128 * For example, if you call
1130 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
1132 * then in JavsScript mydata.name will be 'Moodle'.
1135 * @param string $variable the the name of the JavaScript variable to assign the data to.
1136 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1137 * should be considered an experimental feature.
1138 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1139 * so passing objects and arrays should work.
1140 * @param bool $inhead initialise in head
1143 public function data_for_js($variable, $data, $inhead=false) {
1144 $where = $inhead ?
'head' : 'footer';
1145 $this->jsinitvariables
[$where][] = array($variable, $data);
1149 * Creates a YUI event handler.
1151 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1152 * @param string $event A valid DOM event (click, mousedown, change etc.)
1153 * @param string $function The name of the function to call
1154 * @param array $arguments An optional array of argument parameters to pass to the function
1156 public function event_handler($selector, $event, $function, array $arguments = null) {
1157 $this->eventhandlers
[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
1161 * Returns code needed for registering of event handlers.
1162 * @return string JS code
1164 protected function get_event_handler_code() {
1166 foreach ($this->eventhandlers
as $h) {
1167 $output .= js_writer
::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
1173 * Get the inline JavaScript code that need to appear in a particular place.
1174 * @param bool $ondomready
1177 protected function get_javascript_code($ondomready) {
1178 $where = $ondomready ?
'ondomready' : 'normal';
1180 if ($this->jscalls
[$where]) {
1181 foreach ($this->jscalls
[$where] as $data) {
1182 $output .= js_writer
::function_call($data[0], $data[1], $data[2]);
1184 if (!empty($ondomready)) {
1185 $output = " Y.on('domready', function() {\n$output\n });";
1192 * Returns js code to be executed when Y is available.
1195 protected function get_javascript_init_code() {
1196 if (count($this->jsinitcode
)) {
1197 return implode("\n", $this->jsinitcode
) . "\n";
1203 * Returns basic YUI3 JS loading code.
1204 * YUI3 is using autoloading of both CSS and JS code.
1206 * Major benefit of this compared to standard js/csss loader is much improved
1207 * caching, better browser cache utilisation, much fewer http requests.
1209 * @param moodle_page $page
1212 protected function get_yui3lib_headcode($page) {
1217 if ($this->yui3loader
->combine
) {
1218 if (!empty($page->theme
->yuicssmodules
)) {
1220 foreach ($page->theme
->yuicssmodules
as $module) {
1221 $modules[] = "$CFG->yui3version/build/$module/$module-min.css";
1223 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->comboBase
.implode('&', $modules).'" />';
1225 $code .= '<script type="text/javascript" src="'.$this->yui3loader
->comboBase
1226 .$CFG->yui3version
.'/build/simpleyui/simpleyui-min.js&'
1227 .$CFG->yui3version
.'/build/loader/loader-min.js"></script>';
1229 if (!empty($page->theme
->yuicssmodules
)) {
1230 foreach ($page->theme
->yuicssmodules
as $module) {
1231 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->base
.$module.'/'.$module.'-min.css" />';
1234 $code .= '<script type="text/javascript" src="'.$this->yui3loader
->base
.'simpleyui/simpleyui-min.js"></script>';
1235 $code .= '<script type="text/javascript" src="'.$this->yui3loader
->base
.'loader/loader-min.js"></script>';
1239 if ($this->yui3loader
->filter
=== 'RAW') {
1240 $code = str_replace('-min.css', '.css', $code);
1241 $code = str_replace('-min.js', '.js', $code);
1242 } else if ($this->yui3loader
->filter
=== 'DEBUG') {
1243 $code = str_replace('-min.css', '.css', $code);
1244 $code = str_replace('-min.js', '-debug.js', $code);
1251 * Returns html tags needed for inclusion of theme CSS.
1255 protected function get_css_code() {
1256 // First of all the theme CSS, then any custom CSS
1257 // Please note custom CSS is strongly discouraged,
1258 // because it can not be overridden by themes!
1259 // It is suitable only for things like mod/data which accepts CSS from teachers.
1260 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1262 // This line of code may look funny but it is currently required in order
1263 // to avoid MASSIVE display issues in Internet Explorer.
1264 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1265 // ignored whenever another resource is added until such time as a redraw
1266 // is forced, usually by moving the mouse over the affected element.
1267 $code = html_writer
::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1269 $urls = $this->cssthemeurls +
$this->cssurls
;
1270 foreach ($urls as $url) {
1271 $attributes['href'] = $url;
1272 $code .= html_writer
::empty_tag('link', $attributes) . "\n";
1273 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1274 unset($attributes['id']);
1281 * Adds extra modules specified after printing of page header.
1285 protected function get_extra_modules_code() {
1286 if (empty($this->extramodules
)) {
1289 return html_writer
::script(js_writer
::function_call('M.yui.add_module', array($this->extramodules
)));
1293 * Generate any HTML that needs to go inside the <head> tag.
1295 * Normally, this method is called automatically by the code that prints the
1296 * <head> tag. You should not normally need to call it in your own code.
1298 * @param moodle_page $page
1299 * @param core_renderer $renderer
1300 * @return string the HTML code to to inside the <head> tag.
1302 public function get_head_code(moodle_page
$page, core_renderer
$renderer) {
1305 // Note: the $page and $output are not stored here because it would
1306 // create circular references in memory which prevents garbage collection.
1307 $this->init_requirements_data($page, $renderer);
1311 // Set up the M namespace.
1312 $js = "var M = {}; M.yui = {};\n";
1314 // Capture the time now ASAP during page load. This minimises the lag when
1315 // we try to relate times on the server to times in the browser.
1316 // An example of where this is used is the quiz countdown timer.
1317 $js .= "M.pageloadstarttime = new Date();\n";
1319 // Add a subset of Moodle configuration to the M namespace.
1320 $js .= js_writer
::set_variable('M.cfg', $this->M_cfg
, false);
1322 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1323 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1324 // this needs to be done before including any other script.
1325 $js .= $this->YUI_config
->get_config_functions();
1326 $js .= js_writer
::set_variable('YUI_config', $this->YUI_config
, false) . "\n";
1327 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1328 $js = $this->YUI_config
->update_header_js($js);
1330 $output .= html_writer
::script($js);
1332 // YUI3 JS and CSS need to be loaded in the header but after the YUI_config has been created.
1333 // They should be cached well by the browser.
1334 $output .= $this->get_yui3lib_headcode($page);
1336 // Add hacked jQuery support, it is not intended for standard Moodle distribution!
1337 $output .= $this->get_jquery_headcode();
1339 // Now theme CSS + custom CSS in this specific order.
1340 $output .= $this->get_css_code();
1342 // Link our main JS file, all core stuff should be there.
1343 $output .= html_writer
::script('', $this->js_fix_url('/lib/javascript-static.js'));
1346 if ($this->jsinitvariables
['head']) {
1348 foreach ($this->jsinitvariables
['head'] as $data) {
1349 list($var, $value) = $data;
1350 $js .= js_writer
::set_variable($var, $value, true);
1352 $output .= html_writer
::script($js);
1355 // All the other linked things from HEAD - there should be as few as possible.
1356 if ($this->jsincludes
['head']) {
1357 foreach ($this->jsincludes
['head'] as $url) {
1358 $output .= html_writer
::script('', $url);
1362 // Mark head sending done, it is not possible to anything there.
1363 $this->headdone
= true;
1369 * Generate any HTML that needs to go at the start of the <body> tag.
1371 * Normally, this method is called automatically by the code that prints the
1372 * <head> tag. You should not normally need to call it in your own code.
1374 * @return string the HTML code to go at the start of the <body> tag.
1376 public function get_top_of_body_code() {
1377 // First the skip links.
1379 $attributes = array('class'=>'skip');
1380 foreach ($this->skiplinks
as $url => $text) {
1381 $attributes['href'] = '#' . $url;
1382 $links .= html_writer
::tag('a', $text, $attributes);
1384 $output = html_writer
::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1386 // Then the clever trick for hiding of things not needed when JS works.
1387 $output .= html_writer
::script("document.body.className += ' jsenabled';") . "\n";
1388 $this->topofbodydone
= true;
1393 * Generate any HTML that needs to go at the end of the page.
1395 * Normally, this method is called automatically by the code that prints the
1396 * page footer. You should not normally need to call it in your own code.
1398 * @return string the HTML code to to at the end of the page.
1400 public function get_end_code() {
1403 // Add other requested modules.
1404 $output = $this->get_extra_modules_code();
1406 // All the other linked scripts - there should be as few as possible.
1407 if ($this->jsincludes
['footer']) {
1408 foreach ($this->jsincludes
['footer'] as $url) {
1409 $output .= html_writer
::script('', $url);
1413 // Add all needed strings.
1414 if (!empty($this->stringsforjs
)) {
1416 foreach ($this->stringsforjs
as $component=>$v) {
1417 foreach($v as $indentifier => $langstring) {
1418 $strings[$component][$indentifier] = $langstring->out();
1421 $output .= html_writer
::script(js_writer
::set_variable('M.str', $strings));
1425 if ($this->jsinitvariables
['footer']) {
1427 foreach ($this->jsinitvariables
['footer'] as $data) {
1428 list($var, $value) = $data;
1429 $js .= js_writer
::set_variable($var, $value, true);
1431 $output .= html_writer
::script($js);
1434 $inyuijs = $this->get_javascript_code(false);
1435 $ondomreadyjs = $this->get_javascript_code(true);
1436 $jsinit = $this->get_javascript_init_code();
1437 $handlersjs = $this->get_event_handler_code();
1439 // There is no global Y, make sure it is available in your scope.
1440 $js = "YUI().use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1442 $output .= html_writer
::script($js);
1448 * Have we already output the code in the <head> tag?
1452 public function is_head_done() {
1453 return $this->headdone
;
1457 * Have we already output the code at the start of the <body> tag?
1461 public function is_top_of_body_done() {
1462 return $this->topofbodydone
;
1467 * This class represents the YUI configuration.
1469 * @copyright 2013 Andrew Nicols
1470 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1477 * These settings must be public so that when the object is converted to json they are exposed.
1478 * Note: Some of these are camelCase because YUI uses camelCase variable names.
1480 * The settings are described and documented in the YUI API at:
1481 * - http://yuilibrary.com/yui/docs/api/classes/config.html
1482 * - http://yuilibrary.com/yui/docs/api/classes/Loader.html
1484 public $debug = false;
1488 public $filter = null;
1489 public $insertBefore = 'firstthemesheet';
1490 public $groups = array();
1491 public $modules = array();
1494 * @var array List of functions used by the YUI Loader group pattern recognition.
1496 protected $jsconfigfunctions = array();
1499 * Create a new group within the YUI_config system.
1501 * @param String $name The name of the group. This must be unique and
1502 * not previously used.
1503 * @param Array $config The configuration for this group.
1506 public function add_group($name, $config) {
1507 if (isset($this->groups
[$name])) {
1508 throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
1510 $this->groups
[$name] = $config;
1514 * Update an existing group configuration
1516 * Note, any existing configuration for that group will be wiped out.
1517 * This includes module configuration.
1519 * @param String $name The name of the group. This must be unique and
1520 * not previously used.
1521 * @param Array $config The configuration for this group.
1524 public function update_group($name, $config) {
1525 if (!isset($this->groups
[$name])) {
1526 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.');
1528 $this->groups
[$name] = $config;
1532 * Set the value of a configuration function used by the YUI Loader's pattern testing.
1534 * Only the body of the function should be passed, and not the whole function wrapper.
1536 * The JS function your write will be passed a single argument 'name' containing the
1537 * name of the module being loaded.
1539 * @param $function String the body of the JavaScript function. This should be used i
1540 * @return String the name of the function to use in the group pattern configuration.
1542 public function set_config_function($function) {
1543 $configname = 'yui' . (count($this->jsconfigfunctions
) +
1) . 'ConfigFn';
1544 if (isset($this->jsconfigfunctions
[$configname])) {
1545 throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
1547 $this->jsconfigfunctions
[$configname] = $function;
1548 return '@' . $configname . '@';
1552 * Allow setting of the config function described in {@see set_config_function} from a file.
1553 * The contents of this file are then passed to set_config_function.
1555 * When jsrev is positive, the function is minified and stored in a MUC cache for subsequent uses.
1557 * @param $file The path to the JavaScript function used for YUI configuration.
1558 * @return String the name of the function to use in the group pattern configuration.
1560 public function set_config_source($file) {
1562 $cache = cache
::make('core', 'yuimodules');
1564 // Attempt to get the metadata from the cache.
1565 $keyname = 'configfn_' . $file;
1566 $fullpath = $CFG->dirroot
. '/' . $file;
1567 if (!isset($CFG->jsrev
) ||
$CFG->jsrev
== -1) {
1568 $cache->delete($keyname);
1569 $configfn = file_get_contents($fullpath);
1571 $configfn = $cache->get($keyname);
1572 if ($configfn === false) {
1573 require_once($CFG->libdir
. '/jslib.php');
1574 $configfn = js_minify($fullpath);
1575 $cache->set($keyname, $configfn);
1578 return $this->set_config_function($configfn);
1582 * Retrieve the list of JavaScript functions for YUI_config groups.
1584 * @return String The complete set of config functions
1586 public function get_config_functions() {
1587 $configfunctions = '';
1588 foreach ($this->jsconfigfunctions
as $functionname => $function) {
1589 $configfunctions .= "var {$functionname} = function(me) {";
1590 $configfunctions .= $function;
1591 $configfunctions .= "};\n";
1593 return $configfunctions;
1597 * Update the header JavaScript with any required modification for the YUI Loader.
1599 * @param $js String The JavaScript to manipulate.
1600 * @return String the modified JS string.
1602 public function update_header_js($js) {
1603 // Update the names of the the configFn variables.
1604 // The PHP json_encode function cannot handle literal names so we have to wrap
1605 // them in @ and then replace them with literals of the same function name.
1606 foreach ($this->jsconfigfunctions
as $functionname => $function) {
1607 $js = str_replace('"@' . $functionname . '@"', $functionname, $js);
1613 * Add configuration for a specific module.
1615 * @param String $name The name of the module to add configuration for.
1616 * @param Array $config The configuration for the specified module.
1617 * @param String $group The name of the group to add configuration for.
1618 * If not specified, then this module is added to the global
1622 public function add_module_config($name, $config, $group = null) {
1624 if (!isset($this->groups
[$name])) {
1625 throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.');
1627 if (!isset($this->groups
[$group]['modules'])) {
1628 $this->groups
[$group]['modules'] = array();
1630 $modules = &$this->groups
[$group]['modules'];
1632 $modules = &$this->modules
;
1634 $modules[$name] = $config;
1638 * Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
1640 * If js caching is disabled, metadata will not be served causing YUI to calculate
1641 * module dependencies as each module is loaded.
1643 * If metadata does not exist it will be created and stored in a MUC entry.
1647 public function add_moodle_metadata() {
1649 if (!isset($this->groups
['moodle'])) {
1650 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.');
1653 if (!isset($this->groups
['moodle']['modules'])) {
1654 $this->groups
['moodle']['modules'] = array();
1657 $cache = cache
::make('core', 'yuimodules');
1658 if (!isset($CFG->jsrev
) ||
$CFG->jsrev
== -1) {
1659 $metadata = array();
1660 $cache->delete('metadata');
1662 // Attempt to get the metadata from the cache.
1663 if (!$metadata = $cache->get('metadata')) {
1664 $metadata = $this->get_moodle_metadata();
1665 $cache->set('metadata', $metadata);
1669 // Merge with any metadata added specific to this page which was added manually.
1670 $this->groups
['moodle']['modules'] = array_merge($this->groups
['moodle']['modules'],
1675 * Determine the module metadata for all moodle YUI modules.
1677 * This works through all modules capable of serving YUI modules, and attempts to get
1678 * metadata for each of those modules.
1680 * @return Array of module metadata
1682 private function get_moodle_metadata() {
1683 $moodlemodules = array();
1684 // Core isn't a plugin type or subsystem - handle it seperately.
1685 if ($module = $this->get_moodle_path_metadata(core_component
::get_component_directory('core'))) {
1686 $moodlemodules = array_merge($moodlemodules, $module);
1689 // Handle other core subsystems.
1690 $subsystems = core_component
::get_core_subsystems();
1691 foreach ($subsystems as $subsystem => $path) {
1692 if (is_null($path)) {
1695 if ($module = $this->get_moodle_path_metadata($path)) {
1696 $moodlemodules = array_merge($moodlemodules, $module);
1700 // And finally the plugins.
1701 $plugintypes = core_component
::get_plugin_types();
1702 foreach ($plugintypes as $plugintype => $pathroot) {
1703 $pluginlist = core_component
::get_plugin_list($plugintype);
1704 foreach ($pluginlist as $plugin => $path) {
1705 if ($module = $this->get_moodle_path_metadata($path)) {
1706 $moodlemodules = array_merge($moodlemodules, $module);
1711 return $moodlemodules;
1715 * Helper function process and return the YUI metadata for all of the modules under the specified path.
1717 * @param String $path the UNC path to the YUI src directory.
1718 * @return Array the complete array for frankenstyle directory.
1720 private function get_moodle_path_metadata($path) {
1721 // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
1722 $baseyui = $path . '/yui/src';
1724 if (is_dir($baseyui)) {
1725 $items = new DirectoryIterator($baseyui);
1726 foreach ($items as $item) {
1727 if ($item->isDot() or !$item->isDir()) {
1730 $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
1731 if (!is_readable($metafile)) {
1734 $metadata = file_get_contents($metafile);
1735 $modules = array_merge($modules, (array) json_decode($metadata));
1743 * Invalidate all server and client side JS caches.
1745 function js_reset_all_caches() {
1749 if (isset($CFG->jsrev
) and $next <= $CFG->jsrev
and $CFG->jsrev
- $next < 60*60) {
1750 // This resolves problems when reset is requested repeatedly within 1s,
1751 // the < 1h condition prevents accidental switching to future dates
1752 // because we might not recover from it.
1753 $next = $CFG->jsrev+
1;
1756 set_config('jsrev', $next);