3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * Library functions to facilitate the use of JavaScript in Moodle.
24 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') ||
die();
30 // note: you can find history of this file in lib/ajax/ajaxlib.php
33 * This class tracks all the things that are needed by the current page.
35 * Normally, the only instance of this class you will need to work with is the
36 * one accessible via $PAGE->requires.
38 * Typical usage would be
40 * $PAGE->requires->js_init_call('M.mod_forum.init_view');
43 * It also supports obsoleted coding style withouth YUI3 modules.
45 * $PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overridable via themes!
46 * $PAGE->requires->js('/mod/mymod/script.js');
47 * $PAGE->requires->js('/mod/mymod/small_but_urgent.js', true);
48 * $PAGE->requires->js_function_call('init_mymod', array($data), true);
51 * There are some natural restrictions on some methods. For example, {@link css()}
52 * can only be called before the <head> tag is output. See the comments on the
53 * individual methods for details.
55 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
59 class page_requirements_manager
{
60 /** List of string available from JS */
61 protected $stringsforjs = array();
62 /** List of JS variables to be initialised */
63 protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
64 /** Included JS scripts */
65 protected $jsincludes = array('head'=>array(), 'footer'=>array());
66 /** List of needed function calls */
67 protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
69 * List of skip links, those are needed for accessibility reasons
72 protected $skiplinks = array();
74 * Javascript code used for initialisation of page, it should be relatively small
77 protected $jsinitcode = array();
79 * Theme sheets, initialised only from core_renderer
80 * @var array of moodle_url
82 protected $cssthemeurls = array();
84 * List of custom theme sheets, these are strongly discouraged!
85 * Useful mostly only for CSS submitted by teachers that is not part of the theme.
86 * @var array of moodle_url
88 protected $cssurls = array();
90 * List of requested event handlers
93 protected $eventhandlers = array();
98 protected $extramodules = array();
99 /** Flag indicated head stuff already printed */
100 protected $headdone = false;
101 /** Flag indicating top of body already printed */
102 protected $topofbodydone = false;
104 /** YUI PHPLoader instance responsible for YUI2 loading from PHP only */
105 protected $yui2loader;
106 /** YUI PHPLoader instance responsible for YUI3 loading from PHP only */
107 protected $yui3loader;
108 /** YUI loader information for YUI3 loading from javascript */
109 protected $M_yui_loader;
110 /** some config vars exposed in JS, please no secret stuff there */
112 /** stores debug backtraces from when JS modules were included in the page */
113 protected $debug_moduleloadstacktraces = array();
116 * Page requirements constructor.
118 public function __construct() {
121 require_once("$CFG->libdir/yui/phploader/phploader/loader.php");
123 $this->yui3loader
= new stdClass();
124 $this->yui2loader
= new YAHOO_util_Loader($CFG->yui2version
);
126 // set up some loader options
127 if (debugging('', DEBUG_DEVELOPER
)) {
128 $this->yui3loader
->filter
= YUI_RAW
; // for more detailed logging info use YUI_DEBUG here
129 $this->yui2loader
->filter
= YUI_RAW
; // for more detailed logging info use YUI_DEBUG here
130 $this->yui2loader
->allowRollups
= false;
132 $this->yui3loader
->filter
= null;
133 $this->yui2loader
->filter
= null;
135 if (!empty($CFG->useexternalyui
) and strpos($CFG->httpswwwroot
, 'https:') !== 0) {
136 $this->yui3loader
->base
= 'http://yui.yahooapis.com/' . $CFG->yui3version
. '/build/';
137 $this->yui2loader
->base
= 'http://yui.yahooapis.com/' . $CFG->yui2version
. '/build/';
138 $this->yui3loader
->comboBase
= 'http://yui.yahooapis.com/combo?';
139 $this->yui2loader
->comboBase
= 'http://yui.yahooapis.com/combo?';
141 $this->yui3loader
->base
= $CFG->httpswwwroot
. '/lib/yui/'. $CFG->yui3version
. '/build/';
142 $this->yui2loader
->base
= $CFG->httpswwwroot
. '/lib/yui/'. $CFG->yui2version
. '/build/';
143 $this->yui3loader
->comboBase
= $CFG->httpswwwroot
. '/theme/yui_combo.php?';
144 $this->yui2loader
->comboBase
= $CFG->httpswwwroot
. '/theme/yui_combo.php?';
147 // enable combo loader? this significantly helps with caching and performance!
148 $this->yui3loader
->combine
= !empty($CFG->yuicomboloading
);
149 $this->yui2loader
->combine
= !empty($CFG->yuicomboloading
);
151 if (empty($CFG->cachejs
)) {
153 } else if (empty($CFG->jsrev
)) {
156 $jsrev = $CFG->jsrev
;
159 // set up JS YUI loader helper object
160 $this->M_yui_loader
= new stdClass();
161 $this->M_yui_loader
->base
= $this->yui3loader
->base
;
162 $this->M_yui_loader
->comboBase
= $this->yui3loader
->comboBase
;
163 $this->M_yui_loader
->combine
= $this->yui3loader
->combine
;
164 $this->M_yui_loader
->filter
= (string)$this->yui3loader
->filter
;
165 $this->M_yui_loader
->insertBefore
= 'firstthemesheet';
166 $this->M_yui_loader
->modules
= array();
167 $this->M_yui_loader
->groups
= array(
170 'base' => $CFG->httpswwwroot
. '/theme/yui_combo.php?moodle/'.$jsrev.'/',
171 'comboBase' => $CFG->httpswwwroot
. '/theme/yui_combo.php?',
172 'combine' => $this->yui3loader
->combine
,
175 'root' => 'moodle/'.$jsrev.'/', // Add the rev to the root path so that we can control caching
179 'configFn' => '@MOODLECONFIGFN@'
186 'base' => $CFG->wwwroot
.'/lib/yui/gallery/',
187 'comboBase' => $CFG->httpswwwroot
. '/theme/yui_combo.php?',
188 'combine' => $this->yui3loader
->combine
,
189 'filter' => $this->M_yui_loader
->filter
,
191 'root' => 'gallery/',
194 'group' => 'gallery',
195 'configFn' => '@GALLERYCONFIGFN@',
201 $this->add_yui2_modules(); // adds loading info for all YUI2 modules
202 $this->js_module($this->find_module('core_filepicker'));
203 $this->js_module($this->find_module('core_dock'));
208 * This method adds yui2 modules into the yui3 JS loader-
211 protected function add_yui2_modules() {
212 //note: this function is definitely not perfect, because
213 // it adds tons of markup into each page, but it can be
214 // abstracted into separate JS file with proper headers
217 $GLOBALS['yui_current'] = array();
218 require($CFG->libdir
.'/yui/phploader/lib/meta/config_'.$CFG->yui2version
.'.php');
219 $info = $GLOBALS['yui_current'];
220 unset($GLOBALS['yui_current']);
222 if (empty($CFG->yuicomboloading
)) {
223 $urlbase = $this->yui2loader
->base
;
225 $urlbase = $this->yui2loader
->comboBase
.$CFG->yui2version
.'/build/';
229 $ignored = array(); // list of CSS modules that are not needed
230 foreach ($info['moduleInfo'] as $name => $module) {
231 if ($module['type'] === 'css') {
232 $ignored[$name] = true;
234 $modules['yui2-'.$name] = $module;
237 foreach ($modules as $name=>$module) {
238 $module['fullpath'] = $urlbase.$module['path']; // fix path to point to correct location
239 unset($module['path']);
240 unset($module['skinnable']); // we load all YUI2 css automatically, this prevents weird missing css loader problems
241 foreach(array('requires', 'optional', 'supersedes') as $fixme) {
242 if (!empty($module[$fixme])) {
244 foreach ($module[$fixme] as $key=>$dep) {
245 if (isset($ignored[$dep])) {
246 unset($module[$fixme][$key]);
249 $module[$fixme][$key] = 'yui2-'.$dep;
253 $module[$fixme] = array_merge($module[$fixme]); // fix keys
257 $this->M_yui_loader
->modules
[$name] = $module;
258 if (debugging('', DEBUG_DEVELOPER
)) {
259 if (!array_key_exists($name, $this->debug_moduleloadstacktraces
)) {
260 $this->debug_moduleloadstacktraces
[$name] = array();
262 $this->debug_moduleloadstacktraces
[$name][] = format_backtrace(debug_backtrace());
268 * Initialise with the bits of JavaScript that every Moodle page should have.
270 * @param moodle_page $page
271 * @param core_renderer $renderer
273 protected function init_requirements_data(moodle_page
$page, core_renderer
$renderer) {
276 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
277 // Otherwise, in some situations, users will get warnings about insecure content
278 // on secure pages from their web browser.
280 $this->M_cfg
= array(
281 'wwwroot' => $CFG->httpswwwroot
, // Yes, really. See above.
282 'sesskey' => sesskey(),
283 'loadingicon' => $renderer->pix_url('i/loading_small', 'moodle')->out(false),
284 'themerev' => theme_get_revision(),
285 'theme' => $page->theme
->name
,
286 'jsrev' => ((empty($CFG->cachejs
) or empty($CFG->jsrev
)) ?
-1 : $CFG->jsrev
),
288 if (debugging('', DEBUG_DEVELOPER
)) {
289 $this->M_cfg
['developerdebug'] = true;
290 $this->yui2_lib('logger');
293 // accessibility stuff
294 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
296 // to be removed soon
297 $this->yui2_lib('dom'); // at least javascript-static.js needs to be migrated to YUI3
299 $this->string_for_js('confirmation', 'admin');
300 $this->string_for_js('cancel', 'moodle');
301 $this->string_for_js('yes', 'moodle');
303 if ($page->pagelayout
=== 'frametop') {
304 $this->js_init_call('M.util.init_frametop');
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.
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
324 public function js($url, $inhead=false) {
325 $url = $this->js_fix_url($url);
326 $where = $inhead ?
'head' : 'footer';
327 $this->jsincludes
[$where][$url->out()] = $url;
331 * Ensure that the specified YUI2 library file, and all its required dependencies,
332 * are linked to from this page.
334 * By default the link is put at the end of the page, since this gives best page-load
335 * performance. Optional dependencies are not loaded automatically - if you want
336 * them you will need to load them first with other calls to this method.
338 * Even if a particular library is requested more than once (perhaps as a dependency
339 * of other libraries) it will only be linked to once.
341 * The library is leaded as soon as possible, if $OUTPUT->header() not used yet it
342 * is put into the page header, otherwise it is loaded in the page footer.
344 * @param string|array $libname the name of the YUI2 library you require. For example 'autocomplete'.
347 public function yui2_lib($libname) {
348 $libnames = (array)$libname;
349 foreach ($libnames as $lib) {
350 $this->yui2loader
->load($lib);
355 * Returns the actual url through which a script is served.
356 * @param moodle_url|string $url full moodle url, or shortened path to script
359 protected function js_fix_url($url) {
362 if ($url instanceof moodle_url
) {
364 } else if (strpos($url, '/') === 0) {
366 // check file existence only when in debug mode
367 if (!file_exists($CFG->dirroot
. strtok($url, '?'))) {
368 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
371 if (!empty($CFG->cachejs
) and !empty($CFG->jsrev
) and strpos($url, '/lib/editor/') !== 0 and substr($url, -3) === '.js') {
372 return new moodle_url($CFG->httpswwwroot
.'/lib/javascript.php', array('file'=>$url, 'rev'=>$CFG->jsrev
));
374 return new moodle_url($CFG->httpswwwroot
.$url);
377 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
382 * Find out if JS module present and return details.
383 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
384 * @return array description of module or null if not found
386 protected function find_module($component) {
392 if (strpos($component, 'core_') === 0) {
393 // must be some core stuff - list here is not complete, this is just the stuff used from multiple places
394 // so that we do nto have to repeat the definition of these modules over and over again
396 case 'core_filepicker':
397 $module = array('name' => 'core_filepicker',
398 'fullpath' => '/repository/filepicker.js',
399 'requires' => array('base', 'node', 'node-event-simulate', 'json', 'async-queue', 'io-base', 'io-upload-iframe', 'io-form', 'yui2-button', 'yui2-container', 'yui2-layout', 'yui2-menu', 'yui2-treeview', 'yui2-dragdrop', 'yui2-cookie'),
400 'strings' => array(array('add', 'repository'), array('back', 'repository'), array('cancel', 'moodle'), array('close', 'repository'),
401 array('cleancache', 'repository'), array('copying', 'repository'), array('date', 'repository'), array('downloadsucc', 'repository'),
402 array('emptylist', 'repository'), array('error', 'repository'), array('federatedsearch', 'repository'),
403 array('filenotnull', 'repository'), array('getfile', 'repository'), array('help', 'moodle'), array('iconview', 'repository'),
404 array('invalidjson', 'repository'), array('linkexternal', 'repository'), array('listview', 'repository'),
405 array('loading', 'repository'), array('login', 'repository'), array('logout', 'repository'), array('noenter', 'repository'),
406 array('noresult', 'repository'), array('manageurl', 'repository'), array('popup', 'repository'), array('preview', 'repository'),
407 array('refresh', 'repository'), array('save', 'repository'), array('saveas', 'repository'), array('saved', 'repository'),
408 array('saving', 'repository'), array('search', 'repository'), array('searching', 'repository'), array('size', 'repository'),
409 array('submit', 'repository'), array('sync', 'repository'), array('title', 'repository'), array('upload', 'repository'),
410 array('uploading', 'repository'), array('xhtmlerror', 'repository'),
411 array('cancel'), array('chooselicense', 'repository'), array('author', 'repository'),
412 array('ok', 'moodle'), array('error', 'moodle'), array('info', 'moodle'), array('norepositoriesavailable', 'repository'), array('norepositoriesexternalavailable', 'repository'),
413 array('nofilesattached', 'repository'), array('filepicker', 'repository'),
414 array('nofilesavailable', 'repository'), array('overwrite', 'repository'),
415 array('renameto', 'repository'), array('fileexists', 'repository'),
416 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
417 array('fileexistsdialog_filemanager', 'repository')
421 $module = array('name' => 'core_comment',
422 'fullpath' => '/comment/comment.js',
423 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
424 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
428 $module = array('name' => 'core_role',
429 'fullpath' => '/admin/roles/module.js',
430 'requires' => array('node', 'cookie'));
432 case 'core_completion':
433 $module = array('name' => 'core_completion',
434 'fullpath' => '/course/completion.js');
437 $module = array('name' => 'core_dock',
438 'fullpath' => '/blocks/dock.js',
439 'requires' => array('base', 'node', 'event-custom', 'event-mouseenter', 'event-resize'),
440 'strings' => array(array('addtodock', 'block'),array('undockitem', 'block'),array('undockall', 'block'),array('thisdirectionvertical', 'langconfig')));
443 $module = array('name' => 'core_message',
444 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
445 'fullpath' => '/message/module.js');
448 $module = array('name' => 'core_group',
449 'fullpath' => '/group/module.js',
450 'requires' => array('node', 'overlay', 'event-mouseenter'));
452 case 'core_question_engine':
453 $module = array('name' => 'core_question_engine',
454 'fullpath' => '/question/qengine.js',
455 'requires' => array('node', 'event'));
458 $module = array('name' => 'core_rating',
459 'fullpath' => '/rating/module.js',
460 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
462 case 'core_filetree':
463 $module = array('name' => 'core_filetree',
464 'fullpath' => '/files/module.js',
465 'requires' => array('node', 'event', 'overlay', 'io-base', 'json', 'yui2-treeview'));
470 if ($dir = get_component_directory($component)) {
471 if (file_exists("$dir/module.js")) {
472 if (strpos($dir, $CFG->dirroot
.'/') === 0) {
473 $dir = substr($dir, strlen($CFG->dirroot
));
474 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
484 * Append YUI3 module to default YUI3 JS loader.
485 * The structure of module array is described at http://developer.yahoo.com/yui/3/yui/:
486 * @param string|array $module name of module (details are autodetected), or full module specification as array
489 public function js_module($module) {
492 if (empty($module)) {
493 throw new coding_exception('Missing YUI3 module name or full description.');
496 if (is_string($module)) {
497 $module = $this->find_module($module);
500 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
501 throw new coding_exception('Missing YUI3 module details.');
504 // Don't load this module if we already have, no need to!
505 if ($this->js_module_loaded($module['name'])) {
506 if (debugging('', DEBUG_DEVELOPER
)) {
507 $this->debug_moduleloadstacktraces
[$module['name']][] = format_backtrace(debug_backtrace());
512 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
513 // add all needed strings
514 if (!empty($module['strings'])) {
515 foreach ($module['strings'] as $string) {
516 $identifier = $string[0];
517 $component = isset($string[1]) ?
$string[1] : 'moodle';
518 $a = isset($string[2]) ?
$string[2] : null;
519 $this->string_for_js($identifier, $component, $a);
522 unset($module['strings']);
524 // Process module requirements and attempt to load each. This allows
525 // moodle modules to require each other.
526 if (!empty($module['requires'])){
527 foreach ($module['requires'] as $requirement) {
528 $rmodule = $this->find_module($requirement);
529 if (is_array($rmodule)) {
530 $this->js_module($rmodule);
535 if ($this->headdone
) {
536 $this->extramodules
[$module['name']] = $module;
538 $this->M_yui_loader
->modules
[$module['name']] = $module;
540 if (debugging('', DEBUG_DEVELOPER
)) {
541 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces
)) {
542 $this->debug_moduleloadstacktraces
[$module['name']] = array();
544 $this->debug_moduleloadstacktraces
[$module['name']][] = format_backtrace(debug_backtrace());
549 * Returns true if the module has already been loaded.
551 * @param string|array $module
552 * @return bool True if the module has already been loaded
554 protected function js_module_loaded($module) {
555 if (is_string($module)) {
556 $modulename = $module;
558 $modulename = $module['name'];
560 return array_key_exists($modulename, $this->M_yui_loader
->modules
) ||
561 array_key_exists($modulename, $this->extramodules
);
565 * Returns the stacktraces from loading js modules.
568 public function get_loaded_modules() {
569 return $this->debug_moduleloadstacktraces
;
573 * Ensure that the specified CSS file is linked to from this page.
575 * Because stylesheet links must go in the <head> part of the HTML, you must call
576 * this function before {@link get_head_code()} is called. That normally means before
577 * the call to print_header. If you call it when it is too late, an exception
580 * Even if a particular style sheet is requested more than once, it will only
583 * Please note use of this feature is strongly discouraged,
584 * it is suitable only for places where CSS is submitted directly by teachers.
585 * (Students must not be allowed to submit any external CSS because it may
586 * contain embedded javascript!). Example of correct use is mod/data.
588 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
590 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
592 public function css($stylesheet) {
595 if ($this->headdone
) {
596 throw new coding_exception('Cannot require a CSS file after <head> has been printed.', $stylesheet);
599 if ($stylesheet instanceof moodle_url
) {
601 } else if (strpos($stylesheet, '/') === 0) {
602 $stylesheet = new moodle_url($CFG->httpswwwroot
.$stylesheet);
604 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
607 $this->cssurls
[$stylesheet->out()] = $stylesheet; // overrides
611 * Add theme stylkesheet to page - do not use from plugin code,
612 * this should be called only from the core renderer!
613 * @param moodle_url $stylesheet
616 public function css_theme(moodle_url
$stylesheet) {
617 $this->cssthemeurls
[] = $stylesheet;
621 * Ensure that a skip link to a given target is printed at the top of the <body>.
623 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
624 * will be thrown). That normally means you must call this before the call to print_header.
626 * If you ask for a particular skip link to be printed, it is then your responsibility
627 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
628 * page, so that the skip link goes somewhere.
630 * Even if a particular skip link is requested more than once, only one copy of it will be output.
632 * @param $target the name of anchor this link should go to. For example 'maincontent'.
633 * @param $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
635 public function skip_link_to($target, $linktext) {
636 if ($this->topofbodydone
) {
637 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
640 $this->skiplinks
[$target] = $linktext;
644 * !!!DEPRECATED!!! please use js_init_call() if possible
645 * Ensure that the specified JavaScript function is called from an inline script
646 * somewhere on this page.
648 * By default the call will be put in a script tag at the
649 * end of the page after initialising Y instance, since this gives best page-load
650 * performance and allows you to use YUI3 library.
652 * If you request that a particular function is called several times, then
653 * that is what will happen (unlike linking to a CSS or JS file, where only
654 * one link will be output).
656 * The main benefit of the method is the automatic encoding of all function parameters.
658 * @param string $function the name of the JavaScritp function to call. Can
659 * be a compound name like 'Y.Event.purgeElement'. Can also be
660 * used to create and object by using a 'function name' like 'new user_selector'.
661 * @param array $arguments and array of arguments to be passed to the function.
662 * When generating the function call, this will be escaped using json_encode,
663 * so passing objects and arrays should work.
664 * @param bool $ondomready
668 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
669 $where = $ondomready ?
'ondomready' : 'normal';
670 $this->jscalls
[$where][] = array($function, $arguments, $delay);
674 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
676 * @deprecated DO NOT USE
678 * @param string|array $modules One or more gallery modules to require
679 * @param string $version
680 * @param string $function
681 * @param array $arguments
682 * @param bool $ondomready
684 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
686 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER
);
687 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
691 * Creates a JavaScript function call that requires one or more modules to be loaded
693 * This function can be used to include all of the standard YUI module types within JavaScript:
694 * - YUI3 modules [node, event, io]
695 * - YUI2 modules [yui2-*]
696 * - Moodle modules [moodle-*]
697 * - Gallery modules [gallery-*]
699 * @param array|string $modules One or more modules
700 * @param string $function The function to call once modules have been loaded
701 * @param array $arguments An array of arguments to pass to the function
702 * @param string $galleryversion The gallery version to use
703 * @param bool $ondomready
705 public function yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
708 if (!is_array($modules)) {
709 $modules = array($modules);
711 if (empty($CFG->useexternalyui
) ||
true) {
712 // We need to set the M.yui.galleryversion to the correct version
713 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
715 // Set Y's config.gallery to the version
716 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
718 $jscode .= 'Y.use('.join(',', array_map('json_encode', $modules)).',function() {'.js_writer
::function_call($function, $arguments).'});';
720 $jscode = "Y.on('domready', function() { $jscode });";
722 $this->jsinitcode
[] = $jscode;
726 * Ensure that the specified JavaScript function is called from an inline script
729 * @param string $function the name of the JavaScritp function to with init code,
730 * usually something like 'M.mod_mymodule.init'
731 * @param array $extraarguments and array of arguments to be passed to the function.
732 * The first argument is always the YUI3 Y instance with all required dependencies
734 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
735 * @param array $module JS module specification array
738 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
739 $jscode = js_writer
::function_call_with_Y($function, $extraarguments);
741 // detect module automatically
742 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
743 $module = $this->find_module($matches[1]);
747 $this->js_init_code($jscode, $ondomready, $module);
751 * Add short static javascript code fragment to page footer.
752 * This is intended primarily for loading of js modules and initialising page layout.
753 * Ideally the JS code fragment should be stored in plugin renderer so that themes
755 * @param string $jscode
756 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
757 * @param array $module JS module specification array
760 public function js_init_code($jscode, $ondomready = false, array $module = null) {
761 $jscode = trim($jscode, " ;\n"). ';';
764 $this->js_module($module);
765 $modulename = $module['name'];
766 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
770 $jscode = "Y.on('domready', function() { $jscode });";
773 $this->jsinitcode
[] = $jscode;
777 * Make a language string available to JavaScript.
779 * All the strings will be available in a M.str object in the global namespace.
780 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
781 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
782 * equivalent in the current language.
784 * The arguments to this function are just like the arguments to get_string
785 * except that $component is not optional, and there are some aspects to consider
786 * when the string contains {$a} placeholder.
788 * If the string does not contain any {$a} placeholder, you can simply use
789 * M.str.component.identifier to obtain it. If you prefer, you can call
790 * M.util.get_string(identifier, component) to get the same result.
792 * If you need to use {$a} placeholders, there are two options. Either the
793 * placeholder should be substituted in PHP on server side or it should
794 * be substituted in Javascript at client side.
796 * To substitute the placeholder at server side, just provide the required
797 * value for the placeholder when you require the string. Because each string
798 * is only stored once in the JavaScript (based on $identifier and $module)
799 * you cannot get the same string with two different values of $a. If you try,
800 * an exception will be thrown. Once the placeholder is substituted, you can
801 * use M.str or M.util.get_string() as shown above:
803 * // require the string in PHP and replace the placeholder
804 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
805 * // use the result of the substitution in Javascript
806 * alert(M.str.moodle.fullnamedisplay);
808 * To substitute the placeholder at client side, use M.util.get_string()
809 * function. It implements the same logic as {@see get_string()}:
811 * // require the string in PHP but keep {$a} as it is
812 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
813 * // provide the values on the fly in Javascript
814 * user = { firstname : 'Harry', lastname : 'Potter' }
815 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
817 * If you do need the same string expanded with different $a values in PHP
818 * on server side, then the solution is to put them in your own data structure
819 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
821 * @param string $identifier the desired string.
822 * @param string $component the language file to look in.
823 * @param mixed $a any extra data to add into the string (optional).
825 public function string_for_js($identifier, $component, $a = NULL) {
826 $string = get_string($identifier, $component, $a);
828 throw new coding_exception('The $module parameter is required for page_requirements_manager::string_for_js.');
830 if (isset($this->stringsforjs
[$component][$identifier]) && $this->stringsforjs
[$component][$identifier] !== $string) {
831 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
832 "from lang file '$component'. Did you already ask for it with a different \$a? {$this->stringsforjs[$component][$identifier]} !== $string");
834 $this->stringsforjs
[$component][$identifier] = $string;
838 * Make an array of language strings available for JS
840 * This function calls the above function {@link string_for_js()} for each requested
841 * string in the $identifiers array that is passed to the argument for a single module
845 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
847 * // The above is identitical to calling
849 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
850 * $PAGE->requires->string_for_js('two', 'mymod');
851 * $PAGE->requires->string_for_js('three', 'mymod', 3);
854 * @param array $identifiers An array of desired strings
855 * @param string $component The module to load for
856 * @param mixed $a This can either be a single variable that gets passed as extra
857 * information for every string or it can be an array of mixed data where the
858 * key for the data matches that of the identifier it is meant for.
861 public function strings_for_js($identifiers, $component, $a=NULL) {
862 foreach ($identifiers as $key => $identifier) {
863 if (is_array($a) && array_key_exists($key, $a)) {
868 $this->string_for_js($identifier, $component, $extra);
873 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
875 * Make some data from PHP available to JavaScript code.
877 * For example, if you call
879 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
881 * then in JavsScript mydata.name will be 'Moodle'.
882 * @param string $variable the the name of the JavaScript variable to assign the data to.
883 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
884 * should be considered an experimental feature.
885 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
886 * so passing objects and arrays should work.
887 * @param bool $inhead initialise in head
890 public function data_for_js($variable, $data, $inhead=false) {
891 $where = $inhead ?
'head' : 'footer';
892 $this->jsinitvariables
[$where][] = array($variable, $data);
896 * Creates a YUI event handler.
898 * @param mixed $selector standard YUI selector for elemnts, may be array or string, element id is in the form "#idvalue"
899 * @param string $event A valid DOM event (click, mousedown, change etc.)
900 * @param string $function The name of the function to call
901 * @param array $arguments An optional array of argument parameters to pass to the function
904 public function event_handler($selector, $event, $function, array $arguments = null) {
905 $this->eventhandlers
[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
909 * Returns code needed for registering of event handlers.
910 * @return string JS code
912 protected function get_event_handler_code() {
914 foreach ($this->eventhandlers
as $h) {
915 $output .= js_writer
::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
921 * Get the inline JavaScript code that need to appear in a particular place.
922 * @param bool $ondomready
925 protected function get_javascript_code($ondomready) {
926 $where = $ondomready ?
'ondomready' : 'normal';
928 if ($this->jscalls
[$where]) {
929 foreach ($this->jscalls
[$where] as $data) {
930 $output .= js_writer
::function_call($data[0], $data[1], $data[2]);
932 if (!empty($ondomready)) {
933 $output = " Y.on('domready', function() {\n$output\n });";
940 * Returns js code to be executed when Y is available.
941 * @return unknown_type
943 protected function get_javascript_init_code() {
944 if (count($this->jsinitcode
)) {
945 return implode("\n", $this->jsinitcode
) . "\n";
951 * Returns basic YUI3 JS loading code.
952 * YUI3 is using autoloading of both CSS and JS code.
954 * Major benefit of this compared to standard js/csss loader is much improved
955 * caching, better browser cache utilisation, much fewer http requests.
959 protected function get_yui3lib_headcode() {
964 if ($this->yui3loader
->combine
) {
965 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->comboBase
966 .$CFG->yui3version
.'/build/cssreset/reset-min.css&'
967 .$CFG->yui3version
.'/build/cssfonts/fonts-min.css&'
968 .$CFG->yui3version
.'/build/cssgrids/grids-min.css&'
969 .$CFG->yui3version
.'/build/cssbase/base-min.css" />';
971 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->base
.'cssreset/reset-min.css" />';
972 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->base
.'cssfonts/fonts-min.css" />';
973 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->base
.'cssgrids/grids-min.css" />';
974 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader
->base
.'cssbase/base-min.css" />';
977 $code .= '<script type="text/javascript" src="'.$this->yui3loader
->base
.'yui/yui-min.js"></script>';
979 if ($this->yui3loader
->filter
=== YUI_RAW
) {
980 $code = str_replace('-min.css', '.css', $code);
981 $code = str_replace('-min.js', '.js', $code);
982 } else if ($this->yui3loader
->filter
=== YUI_DEBUG
) {
983 $code = str_replace('-min.css', '.css', $code);
984 $code = str_replace('-min.js', '-debug.js', $code);
991 * Returns basic YUI2 JS loading code.
992 * It can be called manually at any time.
993 * If called manually the result needs to be output using echo().
995 * Major benefit of this compared to standard js loader is much improved
996 * caching, better browser cache utilisation, much fewer http requests.
998 * All YUI2 CSS is loaded automatically.
1000 * @return string JS embedding code
1002 public function get_yui2lib_code() {
1005 if ($this->headdone
) {
1006 $code = $this->yui2loader
->script();
1008 $code = $this->yui2loader
->script();
1009 if ($this->yui2loader
->combine
) {
1010 $skinurl = $this->yui2loader
->comboBase
. $CFG->yui2version
. '/build/assets/skins/sam/skin.css';
1012 $skinurl = $this->yui2loader
->base
. 'assets/skins/sam/skin.css';
1014 // please note this is a temporary hack until we fully migrate to later YUI3 that has all the widgets
1015 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css', 'href'=>$skinurl);
1016 $code .= "\n" . html_writer
::empty_tag('link', $attributes) . "\n";
1018 $code = str_replace('&', '&', $code);
1019 $code = str_replace('&', '&', $code);
1024 * Returns html tags needed for inclusion of theme CSS
1027 protected function get_css_code() {
1028 // First of all the theme CSS, then any custom CSS
1029 // Please note custom CSS is strongly discouraged,
1030 // because it can not be overridden by themes!
1031 // It is suitable only for things like mod/data which accepts CSS from teachers.
1032 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1034 // This line of code may look funny but it is currently required in order
1035 // to avoid MASSIVE display issues in Internet Explorer.
1036 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1037 // ignored whenever another resource is added until such time as a redraw
1038 // is forced, usually by moving the mouse over the affected element.
1039 $code = html_writer
::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1041 $urls = $this->cssthemeurls +
$this->cssurls
;
1042 foreach ($urls as $url) {
1043 $attributes['href'] = $url;
1044 $code .= html_writer
::empty_tag('link', $attributes) . "\n";
1045 // this id is needed in first sheet only so that theme may override YUI sheets laoded on the fly
1046 unset($attributes['id']);
1053 * Adds extra modules specified after printing of page header
1056 protected function get_extra_modules_code() {
1057 if (empty($this->extramodules
)) {
1060 return html_writer
::script(js_writer
::function_call('M.yui.add_module', array($this->extramodules
)));
1064 * Generate any HTML that needs to go inside the <head> tag.
1066 * Normally, this method is called automatically by the code that prints the
1067 * <head> tag. You should not normally need to call it in your own code.
1069 * @param moodle_page $page
1070 * @param core_renderer $renderer
1071 * @return string the HTML code to to inside the <head> tag.
1073 public function get_head_code(moodle_page
$page, core_renderer
$renderer) {
1076 // note: the $page and $output are not stored here because it would
1077 // create circular references in memory which prevents garbage collection
1078 $this->init_requirements_data($page, $renderer);
1080 // yui3 JS and CSS is always loaded first - it is cached in browser
1081 $output = $this->get_yui3lib_headcode();
1083 // BC: load basic YUI2 for now, all yui2 things should be loaded via Y.use('yui2-oldmodulename')
1084 $output .= $this->get_yui2lib_code();
1086 // now theme CSS + custom CSS in this specific order
1087 $output .= $this->get_css_code();
1089 // set up global YUI3 loader object - this should contain all code needed by plugins
1090 // note: in JavaScript just use "YUI(M.yui.loader).use('overlay', function(Y) { .... });"
1091 // this needs to be done before including any other script
1092 $js = "var M = {}; M.yui = {}; var moodleConfigFn = function(me) {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+'.'+me.type;}; var galleryConfigFn = function(me) {var p = me.path,v=M.yui.galleryversion,f;if(/-(skin|core)/.test(me.name)) {me.type = 'css';p = p.replace(/-(skin|core)/, '').replace(/\.js/, '.css').split('/'), f = p.pop().replace(/(\-(min|debug))/, '');if (/-skin/.test(me.name)) {p.splice(p.length,0,v,'assets','skins','sam', f);} else {p.splice(p.length,0,v,'assets', f);};} else {p = p.split('/'), f = p.pop();p.splice(p.length,0,v, f);};me.path = p.join('/');};\n";
1093 $js .= js_writer
::set_variable('M.yui.loader', $this->M_yui_loader
, false) . "\n";
1094 $js .= js_writer
::set_variable('M.cfg', $this->M_cfg
, false);
1095 $js = str_replace('"@GALLERYCONFIGFN@"', 'galleryConfigFn', $js);
1096 $js = str_replace('"@MOODLECONFIGFN@"', 'moodleConfigFn', $js);
1098 $output .= html_writer
::script($js);
1100 // link our main JS file, all core stuff should be there
1101 $output .= html_writer
::script('', $this->js_fix_url('/lib/javascript-static.js'));
1104 if ($this->jsinitvariables
['head']) {
1106 foreach ($this->jsinitvariables
['head'] as $data) {
1107 list($var, $value) = $data;
1108 $js .= js_writer
::set_variable($var, $value, true);
1110 $output .= html_writer
::script($js);
1113 // all the other linked things from HEAD - there should be as few as possible
1114 if ($this->jsincludes
['head']) {
1115 foreach ($this->jsincludes
['head'] as $url) {
1116 $output .= html_writer
::script('', $url);
1120 // mark head sending done, it is not possible to anything there
1121 $this->headdone
= true;
1127 * Generate any HTML that needs to go at the start of the <body> tag.
1129 * Normally, this method is called automatically by the code that prints the
1130 * <head> tag. You should not normally need to call it in your own code.
1132 * @return string the HTML code to go at the start of the <body> tag.
1134 public function get_top_of_body_code() {
1135 // first the skip links
1137 $attributes = array('class'=>'skip');
1138 foreach ($this->skiplinks
as $url => $text) {
1139 $attributes['href'] = '#' . $url;
1140 $links .= html_writer
::tag('a', $text, $attributes);
1142 $output = html_writer
::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1144 // then the clever trick for hiding of things not needed when JS works
1145 $output .= html_writer
::script("document.body.className += ' jsenabled';") . "\n";
1146 $this->topofbodydone
= true;
1151 * Generate any HTML that needs to go at the end of the page.
1153 * Normally, this method is called automatically by the code that prints the
1154 * page footer. You should not normally need to call it in your own code.
1156 * @return string the HTML code to to at the end of the page.
1158 public function get_end_code() {
1160 // add other requested modules
1161 $output = $this->get_extra_modules_code();
1163 // add missing YUI2 YUI - to be removed once we convert everything to YUI3!
1164 $output .= $this->get_yui2lib_code();
1166 // all the other linked scripts - there should be as few as possible
1167 if ($this->jsincludes
['footer']) {
1168 foreach ($this->jsincludes
['footer'] as $url) {
1169 $output .= html_writer
::script('', $url);
1173 // add all needed strings
1174 if (!empty($this->stringsforjs
)) {
1175 $output .= html_writer
::script(js_writer
::set_variable('M.str', $this->stringsforjs
));
1179 if ($this->jsinitvariables
['footer']) {
1181 foreach ($this->jsinitvariables
['footer'] as $data) {
1182 list($var, $value) = $data;
1183 $js .= js_writer
::set_variable($var, $value, true);
1185 $output .= html_writer
::script($js);
1188 $inyuijs = $this->get_javascript_code(false);
1189 $ondomreadyjs = $this->get_javascript_code(true);
1190 $jsinit = $this->get_javascript_init_code();
1191 $handlersjs = $this->get_event_handler_code();
1193 // there is no global Y, make sure it is available in your scope
1194 $js = "YUI(M.yui.loader).use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1196 $output .= html_writer
::script($js);
1202 * @return boolean Have we already output the code in the <head> tag?
1204 public function is_head_done() {
1205 return $this->headdone
;
1209 * @return boolean Have we already output the code at the start of the <body> tag?
1211 public function is_top_of_body_done() {
1212 return $this->topofbodydone
;
1217 * Invalidate all server and client side JS caches.
1220 function js_reset_all_caches() {
1222 require_once("$CFG->libdir/filelib.php");
1224 set_config('jsrev', empty($CFG->jsrev
) ?
1 : $CFG->jsrev+
1);
1225 fulldelete("$CFG->cachedir/js");