Merge branch 'MDL-33987_M23' of git://github.com/lazydaisy/moodle into MOODLE_23_STABLE
[moodle.git] / lib / outputrequirementslib.php
bloba50fcd254f4efd80be15909b83da7111277256ab
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library functions to facilitate the use of JavaScript in Moodle.
20 * Note: you can find history of this file in lib/ajax/ajaxlib.php
22 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @package core
25 * @category output
28 defined('MOODLE_INTERNAL') || die();
30 /**
31 * This class tracks all the things that are needed by the current page.
33 * Normally, the only instance of this class you will need to work with is the
34 * one accessible via $PAGE->requires.
36 * Typical usage would be
37 * <pre>
38 * $PAGE->requires->js_init_call('M.mod_forum.init_view');
39 * </pre>
41 * It also supports obsoleted coding style withouth YUI3 modules.
42 * <pre>
43 * $PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overridable via themes!
44 * $PAGE->requires->js('/mod/mymod/script.js');
45 * $PAGE->requires->js('/mod/mymod/small_but_urgent.js', true);
46 * $PAGE->requires->js_function_call('init_mymod', array($data), true);
47 * </pre>
49 * There are some natural restrictions on some methods. For example, {@link css()}
50 * can only be called before the <head> tag is output. See the comments on the
51 * individual methods for details.
53 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
54 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
55 * @since Moodle 2.0
56 * @package core
57 * @category output
59 class page_requirements_manager {
61 /**
62 * @var array List of string available from JS
64 protected $stringsforjs = array();
66 /**
67 * @var array List of JS variables to be initialised
69 protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
71 /**
72 * @var array Included JS scripts
74 protected $jsincludes = array('head'=>array(), 'footer'=>array());
76 /**
77 * @var array List of needed function calls
79 protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
81 /**
82 * @var array List of skip links, those are needed for accessibility reasons
84 protected $skiplinks = array();
86 /**
87 * @var array Javascript code used for initialisation of page, it should
88 * be relatively small
90 protected $jsinitcode = array();
92 /**
93 * @var array of moodle_url Theme sheets, initialised only from core_renderer
95 protected $cssthemeurls = array();
97 /**
98 * @var array of moodle_url List of custom theme sheets, these are strongly discouraged!
99 * Useful mostly only for CSS submitted by teachers that is not part of the theme.
101 protected $cssurls = array();
104 * @var array List of requested event handlers
106 protected $eventhandlers = array();
109 * @var array Extra modules
111 protected $extramodules = array();
114 * @var bool Flag indicated head stuff already printed
116 protected $headdone = false;
119 * @var bool Flag indicating top of body already printed
121 protected $topofbodydone = false;
124 * @var YAHOO_util_Loader YUI PHPLoader instance responsible for YUI2 loading
125 * from PHP only
127 protected $yui2loader;
130 * @var stdClass YUI PHPLoader instance responsible for YUI3 loading from PHP only
132 protected $yui3loader;
135 * @var stdClass YUI loader information for YUI3 loading from javascript
137 protected $M_yui_loader;
140 * @var array Some config vars exposed in JS, please no secret stuff there
142 protected $M_cfg;
145 * @var array Stores debug backtraces from when JS modules were included in the page
147 protected $debug_moduleloadstacktraces = array();
150 * Page requirements constructor.
152 public function __construct() {
153 global $CFG;
155 // You may need to set up URL rewrite rule because oversized URLs might not be allowed by web server.
156 $sep = empty($CFG->yuislasharguments) ? '?' : '/';
158 require_once("$CFG->libdir/yui/phploader/phploader/loader.php");
160 $this->yui3loader = new stdClass();
161 $this->yui2loader = new YAHOO_util_Loader($CFG->yui2version);
163 // set up some loader options
164 if (debugging('', DEBUG_DEVELOPER)) {
165 $this->yui3loader->filter = YUI_RAW; // for more detailed logging info use YUI_DEBUG here
166 $this->yui2loader->filter = YUI_RAW; // for more detailed logging info use YUI_DEBUG here
167 $this->yui2loader->allowRollups = false;
168 } else {
169 $this->yui3loader->filter = null;
170 $this->yui2loader->filter = null;
172 if (!empty($CFG->useexternalyui) and strpos($CFG->httpswwwroot, 'https:') !== 0) {
173 $this->yui3loader->base = 'http://yui.yahooapis.com/' . $CFG->yui3version . '/build/';
174 $this->yui2loader->base = 'http://yui.yahooapis.com/' . $CFG->yui2version . '/build/';
175 $this->yui3loader->comboBase = 'http://yui.yahooapis.com/combo?';
176 $this->yui2loader->comboBase = 'http://yui.yahooapis.com/combo?';
177 } else {
178 $this->yui3loader->base = $CFG->httpswwwroot . '/lib/yui/'. $CFG->yui3version . '/build/';
179 $this->yui2loader->base = $CFG->httpswwwroot . '/lib/yui/'. $CFG->yui2version . '/build/';
180 $this->yui3loader->comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep;
181 $this->yui2loader->comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep;
184 // enable combo loader? this significantly helps with caching and performance!
185 $this->yui3loader->combine = !empty($CFG->yuicomboloading);
186 $this->yui2loader->combine = !empty($CFG->yuicomboloading);
188 if (empty($CFG->cachejs)) {
189 $jsrev = -1;
190 } else if (empty($CFG->jsrev)) {
191 $jsrev = 1;
192 } else {
193 $jsrev = $CFG->jsrev;
196 // set up JS YUI loader helper object
197 $this->M_yui_loader = new stdClass();
198 $this->M_yui_loader->base = $this->yui3loader->base;
199 $this->M_yui_loader->comboBase = $this->yui3loader->comboBase;
200 $this->M_yui_loader->combine = $this->yui3loader->combine;
201 $this->M_yui_loader->filter = (string)$this->yui3loader->filter;
202 $this->M_yui_loader->insertBefore = 'firstthemesheet';
203 $this->M_yui_loader->modules = array();
204 $this->M_yui_loader->groups = array(
205 'moodle' => array(
206 'name' => 'moodle',
207 'base' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep.'moodle/'.$jsrev.'/',
208 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
209 'combine' => $this->yui3loader->combine,
210 'filter' => '',
211 'ext' => false,
212 'root' => 'moodle/'.$jsrev.'/', // Add the rev to the root path so that we can control caching
213 'patterns' => array(
214 'moodle-' => array(
215 'group' => 'moodle',
216 'configFn' => '@MOODLECONFIGFN@'
218 'root' => 'moodle'
221 'local' => array(
222 'name' => 'gallery',
223 'base' => $CFG->wwwroot.'/lib/yui/gallery/',
224 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
225 'combine' => $this->yui3loader->combine,
226 'filter' => $this->M_yui_loader->filter,
227 'ext' => false,
228 'root' => 'gallery/',
229 'patterns' => array(
230 'gallery-' => array(
231 'group' => 'gallery',
232 'configFn' => '@GALLERYCONFIGFN@',
234 'root' => 'gallery'
238 $this->add_yui2_modules(); // adds loading info for all YUI2 modules
239 $this->js_module($this->find_module('core_filepicker'));
240 $this->js_module($this->find_module('core_dock'));
245 * This method adds yui2 modules into the yui3 JS loader so that they can
246 * be easily included for use in JavaScript.
248 protected function add_yui2_modules() {
249 //note: this function is definitely not perfect, because
250 // it adds tons of markup into each page, but it can be
251 // abstracted into separate JS file with proper headers
252 global $CFG;
254 $GLOBALS['yui_current'] = array();
255 require($CFG->libdir.'/yui/phploader/lib/meta/config_'.$CFG->yui2version.'.php');
256 $info = $GLOBALS['yui_current'];
257 unset($GLOBALS['yui_current']);
259 if (empty($CFG->yuicomboloading)) {
260 $urlbase = $this->yui2loader->base;
261 } else {
262 $urlbase = $this->yui2loader->comboBase.$CFG->yui2version.'/build/';
265 $modules = array();
266 $ignored = array(); // list of CSS modules that are not needed
267 foreach ($info['moduleInfo'] as $name => $module) {
268 if ($module['type'] === 'css') {
269 $ignored[$name] = true;
270 } else {
271 $modules['yui2-'.$name] = $module;
274 foreach ($modules as $name=>$module) {
275 $module['fullpath'] = $urlbase.$module['path']; // fix path to point to correct location
276 $module['async'] = false;
277 unset($module['path']);
278 unset($module['skinnable']); // we load all YUI2 css automatically, this prevents weird missing css loader problems
279 foreach(array('requires', 'optional', 'supersedes') as $fixme) {
280 if (!empty($module[$fixme])) {
281 $fixed = false;
282 foreach ($module[$fixme] as $key=>$dep) {
283 if (isset($ignored[$dep])) {
284 unset($module[$fixme][$key]);
285 $fixed = true;
286 } else {
287 $module[$fixme][$key] = 'yui2-'.$dep;
290 if ($fixed) {
291 $module[$fixme] = array_merge($module[$fixme]); // fix keys
295 $this->M_yui_loader->modules[$name] = $module;
296 if (debugging('', DEBUG_DEVELOPER)) {
297 if (!array_key_exists($name, $this->debug_moduleloadstacktraces)) {
298 $this->debug_moduleloadstacktraces[$name] = array();
300 $this->debug_moduleloadstacktraces[$name][] = format_backtrace(debug_backtrace());
306 * Initialise with the bits of JavaScript that every Moodle page should have.
308 * @param moodle_page $page
309 * @param core_renderer $renderer
311 protected function init_requirements_data(moodle_page $page, core_renderer $renderer) {
312 global $CFG;
314 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
315 // Otherwise, in some situations, users will get warnings about insecure content
316 // on secure pages from their web browser.
318 $this->M_cfg = array(
319 'wwwroot' => $CFG->httpswwwroot, // Yes, really. See above.
320 'sesskey' => sesskey(),
321 'loadingicon' => $renderer->pix_url('i/loading_small', 'moodle')->out(false),
322 'themerev' => theme_get_revision(),
323 'slasharguments' => (int)(!empty($CFG->slasharguments)),
324 'theme' => $page->theme->name,
325 'jsrev' => ((empty($CFG->cachejs) or empty($CFG->jsrev)) ? -1 : $CFG->jsrev),
327 if (debugging('', DEBUG_DEVELOPER)) {
328 $this->M_cfg['developerdebug'] = true;
331 // accessibility stuff
332 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
334 // to be removed soon
335 $this->yui2_lib('dom'); // at least javascript-static.js needs to be migrated to YUI3
337 $this->string_for_js('confirmation', 'admin');
338 $this->string_for_js('cancel', 'moodle');
339 $this->string_for_js('yes', 'moodle');
341 if ($page->pagelayout === 'frametop') {
342 $this->js_init_call('M.util.init_frametop');
347 * Ensure that the specified JavaScript file is linked to from this page.
349 * NOTE: This function is to be used in rare cases only, please store your JS in module.js file
350 * and use $PAGE->requires->js_init_call() instead.
352 * By default the link is put at the end of the page, since this gives best page-load performance.
354 * Even if a particular script is requested more than once, it will only be linked
355 * to once.
357 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
358 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
359 * @param bool $inhead initialise in head
361 public function js($url, $inhead = false) {
362 $url = $this->js_fix_url($url);
363 $where = $inhead ? 'head' : 'footer';
364 $this->jsincludes[$where][$url->out()] = $url;
368 * Ensure that the specified YUI2 library file, and all its required dependencies,
369 * are linked to from this page.
371 * By default the link is put at the end of the page, since this gives best page-load
372 * performance. Optional dependencies are not loaded automatically - if you want
373 * them you will need to load them first with other calls to this method.
375 * Even if a particular library is requested more than once (perhaps as a dependency
376 * of other libraries) it will only be linked to once.
378 * The library is leaded as soon as possible, if $OUTPUT->header() not used yet it
379 * is put into the page header, otherwise it is loaded in the page footer.
381 * @param string|array $libname the name of the YUI2 library you require. For example 'autocomplete'.
383 public function yui2_lib($libname) {
384 $libnames = (array)$libname;
385 foreach ($libnames as $lib) {
386 $this->yui2loader->load($lib);
391 * Returns the actual url through which a script is served.
393 * @param moodle_url|string $url full moodle url, or shortened path to script
394 * @return moodle_url
396 protected function js_fix_url($url) {
397 global $CFG;
399 if ($url instanceof moodle_url) {
400 return $url;
401 } else if (strpos($url, '/') === 0) {
402 if (debugging()) {
403 // check file existence only when in debug mode
404 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
405 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
408 if (!empty($CFG->cachejs) and !empty($CFG->jsrev) and $CFG->jsrev > 0 and strpos($url, '/lib/editor/') !== 0 and substr($url, -3) === '.js') {
409 if (empty($CFG->slasharguments)) {
410 return new moodle_url($CFG->httpswwwroot.'/lib/javascript.php', array('rev'=>$CFG->jsrev, 'jsfile'=>$url));
411 } else {
412 $returnurl = new moodle_url($CFG->httpswwwroot.'/lib/javascript.php');
413 $returnurl->set_slashargument('/'.$CFG->jsrev.$url);
414 return $returnurl;
416 } else {
417 return new moodle_url($CFG->httpswwwroot.$url);
419 } else {
420 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
425 * Find out if JS module present and return details.
427 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
428 * @return array description of module or null if not found
430 protected function find_module($component) {
431 global $CFG, $PAGE;
433 $module = null;
435 if (strpos($component, 'core_') === 0) {
436 // must be some core stuff - list here is not complete, this is just the stuff used from multiple places
437 // so that we do nto have to repeat the definition of these modules over and over again
438 switch($component) {
439 case 'core_filepicker':
440 $module = array('name' => 'core_filepicker',
441 'fullpath' => '/repository/filepicker.js',
442 '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', 'moodle-core_filepicker'),
443 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
444 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
445 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
446 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
447 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
448 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
449 array('referencesexist', 'repository')
451 break;
452 case 'core_comment':
453 $module = array('name' => 'core_comment',
454 'fullpath' => '/comment/comment.js',
455 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
456 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
458 break;
459 case 'core_role':
460 $module = array('name' => 'core_role',
461 'fullpath' => '/admin/roles/module.js',
462 'requires' => array('node', 'cookie'));
463 break;
464 case 'core_completion':
465 $module = array('name' => 'core_completion',
466 'fullpath' => '/course/completion.js');
467 break;
468 case 'core_dock':
469 $module = array('name' => 'core_dock',
470 'fullpath' => '/blocks/dock.js',
471 'requires' => array('base', 'node', 'event-custom', 'event-mouseenter', 'event-resize'),
472 'strings' => array(array('addtodock', 'block'),array('undockitem', 'block'),array('undockall', 'block'),array('thisdirectionvertical', 'langconfig')));
473 break;
474 case 'core_message':
475 $module = array('name' => 'core_message',
476 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
477 'fullpath' => '/message/module.js');
478 break;
479 case 'core_group':
480 $module = array('name' => 'core_group',
481 'fullpath' => '/group/module.js',
482 'requires' => array('node', 'overlay', 'event-mouseenter'));
483 break;
484 case 'core_question_engine':
485 $module = array('name' => 'core_question_engine',
486 'fullpath' => '/question/qengine.js',
487 'requires' => array('node', 'event'));
488 break;
489 case 'core_rating':
490 $module = array('name' => 'core_rating',
491 'fullpath' => '/rating/module.js',
492 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
493 break;
494 case 'core_filetree':
495 $module = array('name' => 'core_filetree',
496 'fullpath' => '/files/module.js',
497 'requires' => array('node', 'event', 'overlay', 'io-base', 'json', 'yui2-treeview'));
498 break;
499 case 'core_dndupload':
500 $module = array('name' => 'core_dndupload',
501 'fullpath' => '/lib/form/dndupload.js',
502 'requires' => array('node', 'event', 'json', 'core_filepicker'),
503 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'), array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle')));
504 break;
507 } else {
508 if ($dir = get_component_directory($component)) {
509 if (file_exists("$dir/module.js")) {
510 if (strpos($dir, $CFG->dirroot.'/') === 0) {
511 $dir = substr($dir, strlen($CFG->dirroot));
512 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
518 return $module;
522 * Append YUI3 module to default YUI3 JS loader.
523 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
525 * @param string|array $module name of module (details are autodetected), or full module specification as array
526 * @return void
528 public function js_module($module) {
529 global $CFG;
531 if (empty($module)) {
532 throw new coding_exception('Missing YUI3 module name or full description.');
535 if (is_string($module)) {
536 $module = $this->find_module($module);
539 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
540 throw new coding_exception('Missing YUI3 module details.');
543 // Don't load this module if we already have, no need to!
544 if ($this->js_module_loaded($module['name'])) {
545 if (debugging('', DEBUG_DEVELOPER)) {
546 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
548 return;
551 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
552 // add all needed strings
553 if (!empty($module['strings'])) {
554 foreach ($module['strings'] as $string) {
555 $identifier = $string[0];
556 $component = isset($string[1]) ? $string[1] : 'moodle';
557 $a = isset($string[2]) ? $string[2] : null;
558 $this->string_for_js($identifier, $component, $a);
561 unset($module['strings']);
563 // Process module requirements and attempt to load each. This allows
564 // moodle modules to require each other.
565 if (!empty($module['requires'])){
566 foreach ($module['requires'] as $requirement) {
567 $rmodule = $this->find_module($requirement);
568 if (is_array($rmodule)) {
569 $this->js_module($rmodule);
574 if ($this->headdone) {
575 $this->extramodules[$module['name']] = $module;
576 } else {
577 $this->M_yui_loader->modules[$module['name']] = $module;
579 if (debugging('', DEBUG_DEVELOPER)) {
580 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces)) {
581 $this->debug_moduleloadstacktraces[$module['name']] = array();
583 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
588 * Returns true if the module has already been loaded.
590 * @param string|array $module
591 * @return bool True if the module has already been loaded
593 protected function js_module_loaded($module) {
594 if (is_string($module)) {
595 $modulename = $module;
596 } else {
597 $modulename = $module['name'];
599 return array_key_exists($modulename, $this->M_yui_loader->modules) ||
600 array_key_exists($modulename, $this->extramodules);
604 * Returns the stacktraces from loading js modules.
605 * @return array
607 public function get_loaded_modules() {
608 return $this->debug_moduleloadstacktraces;
612 * Ensure that the specified CSS file is linked to from this page.
614 * Because stylesheet links must go in the <head> part of the HTML, you must call
615 * this function before {@link get_head_code()} is called. That normally means before
616 * the call to print_header. If you call it when it is too late, an exception
617 * will be thrown.
619 * Even if a particular style sheet is requested more than once, it will only
620 * be linked to once.
622 * Please note use of this feature is strongly discouraged,
623 * it is suitable only for places where CSS is submitted directly by teachers.
624 * (Students must not be allowed to submit any external CSS because it may
625 * contain embedded javascript!). Example of correct use is mod/data.
627 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
628 * For example:
629 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
631 public function css($stylesheet) {
632 global $CFG;
634 if ($this->headdone) {
635 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
638 if ($stylesheet instanceof moodle_url) {
639 // ok
640 } else if (strpos($stylesheet, '/') === 0) {
641 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
642 } else {
643 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
646 $this->cssurls[$stylesheet->out()] = $stylesheet; // overrides
650 * Add theme stylkesheet to page - do not use from plugin code,
651 * this should be called only from the core renderer!
653 * @param moodle_url $stylesheet
654 * @return void
656 public function css_theme(moodle_url $stylesheet) {
657 $this->cssthemeurls[] = $stylesheet;
661 * Ensure that a skip link to a given target is printed at the top of the <body>.
663 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
664 * will be thrown). That normally means you must call this before the call to print_header.
666 * If you ask for a particular skip link to be printed, it is then your responsibility
667 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
668 * page, so that the skip link goes somewhere.
670 * Even if a particular skip link is requested more than once, only one copy of it will be output.
672 * @param $target the name of anchor this link should go to. For example 'maincontent'.
673 * @param $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
675 public function skip_link_to($target, $linktext) {
676 if ($this->topofbodydone) {
677 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
678 return;
680 $this->skiplinks[$target] = $linktext;
684 * !!!DEPRECATED!!! please use js_init_call() if possible
685 * Ensure that the specified JavaScript function is called from an inline script
686 * somewhere on this page.
688 * By default the call will be put in a script tag at the
689 * end of the page after initialising Y instance, since this gives best page-load
690 * performance and allows you to use YUI3 library.
692 * If you request that a particular function is called several times, then
693 * that is what will happen (unlike linking to a CSS or JS file, where only
694 * one link will be output).
696 * The main benefit of the method is the automatic encoding of all function parameters.
698 * @param string $function the name of the JavaScritp function to call. Can
699 * be a compound name like 'Y.Event.purgeElement'. Can also be
700 * used to create and object by using a 'function name' like 'new user_selector'.
701 * @param array $arguments and array of arguments to be passed to the function.
702 * When generating the function call, this will be escaped using json_encode,
703 * so passing objects and arrays should work.
704 * @param bool $ondomready If tru the function is only called when the dom is
705 * ready for manipulation.
706 * @param int $delay The delay before the function is called.
708 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
709 $where = $ondomready ? 'ondomready' : 'normal';
710 $this->jscalls[$where][] = array($function, $arguments, $delay);
714 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
716 * @deprecated DO NOT USE
718 * @param string|array $modules One or more gallery modules to require
719 * @param string $version
720 * @param string $function
721 * @param array $arguments
722 * @param bool $ondomready
724 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
725 global $CFG;
726 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER);
727 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
731 * Creates a JavaScript function call that requires one or more modules to be loaded
733 * This function can be used to include all of the standard YUI module types within JavaScript:
734 * - YUI3 modules [node, event, io]
735 * - YUI2 modules [yui2-*]
736 * - Moodle modules [moodle-*]
737 * - Gallery modules [gallery-*]
739 * @param array|string $modules One or more modules
740 * @param string $function The function to call once modules have been loaded
741 * @param array $arguments An array of arguments to pass to the function
742 * @param string $galleryversion The gallery version to use
743 * @param bool $ondomready
745 public function yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
746 global $CFG;
748 if (!is_array($modules)) {
749 $modules = array($modules);
751 if (empty($CFG->useexternalyui)) {
752 // We need to set the M.yui.galleryversion to the correct version
753 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
754 } else {
755 // Set Y's config.gallery to the version
756 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
758 $jscode .= 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
759 if ($ondomready) {
760 $jscode = "Y.on('domready', function() { $jscode });";
762 $this->jsinitcode[] = $jscode;
766 * Ensure that the specified JavaScript function is called from an inline script
767 * from page footer.
769 * @param string $function the name of the JavaScritp function to with init code,
770 * usually something like 'M.mod_mymodule.init'
771 * @param array $extraarguments and array of arguments to be passed to the function.
772 * The first argument is always the YUI3 Y instance with all required dependencies
773 * already loaded.
774 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
775 * @param array $module JS module specification array
777 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
778 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
779 if (!$module) {
780 // detect module automatically
781 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
782 $module = $this->find_module($matches[1]);
786 $this->js_init_code($jscode, $ondomready, $module);
790 * Add short static javascript code fragment to page footer.
791 * This is intended primarily for loading of js modules and initialising page layout.
792 * Ideally the JS code fragment should be stored in plugin renderer so that themes
793 * may override it.
794 * @param string $jscode
795 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
796 * @param array $module JS module specification array
798 public function js_init_code($jscode, $ondomready = false, array $module = null) {
799 $jscode = trim($jscode, " ;\n"). ';';
801 if ($module) {
802 $this->js_module($module);
803 $modulename = $module['name'];
804 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
807 if ($ondomready) {
808 $jscode = "Y.on('domready', function() { $jscode });";
811 $this->jsinitcode[] = $jscode;
815 * Make a language string available to JavaScript.
817 * All the strings will be available in a M.str object in the global namespace.
818 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
819 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
820 * equivalent in the current language.
822 * The arguments to this function are just like the arguments to get_string
823 * except that $component is not optional, and there are some aspects to consider
824 * when the string contains {$a} placeholder.
826 * If the string does not contain any {$a} placeholder, you can simply use
827 * M.str.component.identifier to obtain it. If you prefer, you can call
828 * M.util.get_string(identifier, component) to get the same result.
830 * If you need to use {$a} placeholders, there are two options. Either the
831 * placeholder should be substituted in PHP on server side or it should
832 * be substituted in Javascript at client side.
834 * To substitute the placeholder at server side, just provide the required
835 * value for the placeholder when you require the string. Because each string
836 * is only stored once in the JavaScript (based on $identifier and $module)
837 * you cannot get the same string with two different values of $a. If you try,
838 * an exception will be thrown. Once the placeholder is substituted, you can
839 * use M.str or M.util.get_string() as shown above:
841 * // require the string in PHP and replace the placeholder
842 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
843 * // use the result of the substitution in Javascript
844 * alert(M.str.moodle.fullnamedisplay);
846 * To substitute the placeholder at client side, use M.util.get_string()
847 * function. It implements the same logic as {@link get_string()}:
849 * // require the string in PHP but keep {$a} as it is
850 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
851 * // provide the values on the fly in Javascript
852 * user = { firstname : 'Harry', lastname : 'Potter' }
853 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
855 * If you do need the same string expanded with different $a values in PHP
856 * on server side, then the solution is to put them in your own data structure
857 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
859 * @param string $identifier the desired string.
860 * @param string $component the language file to look in.
861 * @param mixed $a any extra data to add into the string (optional).
863 public function string_for_js($identifier, $component, $a = NULL) {
864 $string = get_string($identifier, $component, $a);
865 if (!$component) {
866 throw new coding_exception('The $module parameter is required for page_requirements_manager::string_for_js.');
868 if (isset($this->stringsforjs[$component][$identifier]) && $this->stringsforjs[$component][$identifier] !== $string) {
869 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
870 "from lang file '$component'. Did you already ask for it with a different \$a? {$this->stringsforjs[$component][$identifier]} !== $string");
872 $this->stringsforjs[$component][$identifier] = $string;
876 * Make an array of language strings available for JS
878 * This function calls the above function {@link string_for_js()} for each requested
879 * string in the $identifiers array that is passed to the argument for a single module
880 * passed in $module.
882 * <code>
883 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
885 * // The above is identitical to calling
887 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
888 * $PAGE->requires->string_for_js('two', 'mymod');
889 * $PAGE->requires->string_for_js('three', 'mymod', 3);
890 * </code>
892 * @param array $identifiers An array of desired strings
893 * @param string $component The module to load for
894 * @param mixed $a This can either be a single variable that gets passed as extra
895 * information for every string or it can be an array of mixed data where the
896 * key for the data matches that of the identifier it is meant for.
899 public function strings_for_js($identifiers, $component, $a=NULL) {
900 foreach ($identifiers as $key => $identifier) {
901 if (is_array($a) && array_key_exists($key, $a)) {
902 $extra = $a[$key];
903 } else {
904 $extra = $a;
906 $this->string_for_js($identifier, $component, $extra);
911 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
913 * Make some data from PHP available to JavaScript code.
915 * For example, if you call
916 * <pre>
917 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
918 * </pre>
919 * then in JavsScript mydata.name will be 'Moodle'.
920 * @param string $variable the the name of the JavaScript variable to assign the data to.
921 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
922 * should be considered an experimental feature.
923 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
924 * so passing objects and arrays should work.
925 * @param bool $inhead initialise in head
926 * @return void
928 public function data_for_js($variable, $data, $inhead=false) {
929 $where = $inhead ? 'head' : 'footer';
930 $this->jsinitvariables[$where][] = array($variable, $data);
934 * Creates a YUI event handler.
936 * @param mixed $selector standard YUI selector for elemnts, may be array or string, element id is in the form "#idvalue"
937 * @param string $event A valid DOM event (click, mousedown, change etc.)
938 * @param string $function The name of the function to call
939 * @param array $arguments An optional array of argument parameters to pass to the function
941 public function event_handler($selector, $event, $function, array $arguments = null) {
942 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
946 * Returns code needed for registering of event handlers.
947 * @return string JS code
949 protected function get_event_handler_code() {
950 $output = '';
951 foreach ($this->eventhandlers as $h) {
952 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
954 return $output;
958 * Get the inline JavaScript code that need to appear in a particular place.
959 * @param bool $ondomready
960 * @return string
962 protected function get_javascript_code($ondomready) {
963 $where = $ondomready ? 'ondomready' : 'normal';
964 $output = '';
965 if ($this->jscalls[$where]) {
966 foreach ($this->jscalls[$where] as $data) {
967 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
969 if (!empty($ondomready)) {
970 $output = " Y.on('domready', function() {\n$output\n });";
973 return $output;
977 * Returns js code to be executed when Y is available.
978 * @return string
980 protected function get_javascript_init_code() {
981 if (count($this->jsinitcode)) {
982 return implode("\n", $this->jsinitcode) . "\n";
984 return '';
988 * Returns basic YUI3 JS loading code.
989 * YUI3 is using autoloading of both CSS and JS code.
991 * Major benefit of this compared to standard js/csss loader is much improved
992 * caching, better browser cache utilisation, much fewer http requests.
994 * @return string
996 protected function get_yui3lib_headcode() {
997 global $CFG;
999 $code = '';
1001 if ($this->yui3loader->combine) {
1002 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase
1003 .$CFG->yui3version.'/build/cssreset/reset-min.css&amp;'
1004 .$CFG->yui3version.'/build/cssfonts/fonts-min.css&amp;'
1005 .$CFG->yui3version.'/build/cssgrids/grids-min.css&amp;'
1006 .$CFG->yui3version.'/build/cssbase/base-min.css" />';
1007 $code .= '<script type="text/javascript" src="'.$this->yui3loader->comboBase.$CFG->yui3version.'/build/yui/yui-min.js"></script>';
1008 } else {
1009 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssreset/reset-min.css" />';
1010 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssfonts/fonts-min.css" />';
1011 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssgrids/grids-min.css" />';
1012 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssbase/base-min.css" />';
1013 $code .= '<script type="text/javascript" src="'.$this->yui3loader->base.'yui/yui-min.js"></script>';
1017 if ($this->yui3loader->filter === YUI_RAW) {
1018 $code = str_replace('-min.css', '.css', $code);
1019 $code = str_replace('-min.js', '.js', $code);
1020 } else if ($this->yui3loader->filter === YUI_DEBUG) {
1021 $code = str_replace('-min.css', '.css', $code);
1022 $code = str_replace('-min.js', '-debug.js', $code);
1025 return $code;
1029 * Returns basic YUI2 JS loading code.
1030 * It can be called manually at any time.
1031 * If called manually the result needs to be output using echo().
1033 * Major benefit of this compared to standard js loader is much improved
1034 * caching, better browser cache utilisation, much fewer http requests.
1036 * All YUI2 CSS is loaded automatically.
1038 * @return string JS embedding code
1040 public function get_yui2lib_code() {
1041 global $CFG;
1043 if ($this->headdone) {
1044 $code = $this->yui2loader->script();
1045 } else {
1046 $code = $this->yui2loader->script();
1047 if ($this->yui2loader->combine) {
1048 $skinurl = $this->yui2loader->comboBase . $CFG->yui2version . '/build/assets/skins/sam/skin.css';
1049 } else {
1050 $skinurl = $this->yui2loader->base . 'assets/skins/sam/skin.css';
1052 // please note this is a temporary hack until we fully migrate to later YUI3 that has all the widgets
1053 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css', 'href'=>$skinurl);
1054 $code .= "\n" . html_writer::empty_tag('link', $attributes) . "\n";
1056 $code = str_replace('&amp;', '&', $code);
1057 $code = str_replace('&', '&amp;', $code);
1058 return $code;
1062 * Returns html tags needed for inclusion of theme CSS
1064 * @return string
1066 protected function get_css_code() {
1067 // First of all the theme CSS, then any custom CSS
1068 // Please note custom CSS is strongly discouraged,
1069 // because it can not be overridden by themes!
1070 // It is suitable only for things like mod/data which accepts CSS from teachers.
1071 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1073 // This line of code may look funny but it is currently required in order
1074 // to avoid MASSIVE display issues in Internet Explorer.
1075 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1076 // ignored whenever another resource is added until such time as a redraw
1077 // is forced, usually by moving the mouse over the affected element.
1078 $code = html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1080 $urls = $this->cssthemeurls + $this->cssurls;
1081 foreach ($urls as $url) {
1082 $attributes['href'] = $url;
1083 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1084 // this id is needed in first sheet only so that theme may override YUI sheets laoded on the fly
1085 unset($attributes['id']);
1088 return $code;
1092 * Adds extra modules specified after printing of page header
1094 * @return string
1096 protected function get_extra_modules_code() {
1097 if (empty($this->extramodules)) {
1098 return '';
1100 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1104 * Generate any HTML that needs to go inside the <head> tag.
1106 * Normally, this method is called automatically by the code that prints the
1107 * <head> tag. You should not normally need to call it in your own code.
1109 * @param moodle_page $page
1110 * @param core_renderer $renderer
1111 * @return string the HTML code to to inside the <head> tag.
1113 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1114 global $CFG;
1116 // note: the $page and $output are not stored here because it would
1117 // create circular references in memory which prevents garbage collection
1118 $this->init_requirements_data($page, $renderer);
1120 // yui3 JS and CSS is always loaded first - it is cached in browser
1121 $output = $this->get_yui3lib_headcode();
1123 // BC: load basic YUI2 for now, all yui2 things should be loaded via Y.use('yui2-oldmodulename')
1124 $output .= $this->get_yui2lib_code();
1126 // now theme CSS + custom CSS in this specific order
1127 $output .= $this->get_css_code();
1129 // set up global YUI3 loader object - this should contain all code needed by plugins
1130 // note: in JavaScript just use "YUI(M.yui.loader).use('overlay', function(Y) { .... });"
1131 // this needs to be done before including any other script
1132 $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";
1133 $js .= js_writer::set_variable('M.yui.loader', $this->M_yui_loader, false) . "\n";
1134 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1135 $js = str_replace('"@GALLERYCONFIGFN@"', 'galleryConfigFn', $js);
1136 $js = str_replace('"@MOODLECONFIGFN@"', 'moodleConfigFn', $js);
1138 $output .= html_writer::script($js);
1140 // link our main JS file, all core stuff should be there
1141 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1143 // add variables
1144 if ($this->jsinitvariables['head']) {
1145 $js = '';
1146 foreach ($this->jsinitvariables['head'] as $data) {
1147 list($var, $value) = $data;
1148 $js .= js_writer::set_variable($var, $value, true);
1150 $output .= html_writer::script($js);
1153 // all the other linked things from HEAD - there should be as few as possible
1154 if ($this->jsincludes['head']) {
1155 foreach ($this->jsincludes['head'] as $url) {
1156 $output .= html_writer::script('', $url);
1160 // mark head sending done, it is not possible to anything there
1161 $this->headdone = true;
1163 return $output;
1167 * Generate any HTML that needs to go at the start of the <body> tag.
1169 * Normally, this method is called automatically by the code that prints the
1170 * <head> tag. You should not normally need to call it in your own code.
1172 * @return string the HTML code to go at the start of the <body> tag.
1174 public function get_top_of_body_code() {
1175 // first the skip links
1176 $links = '';
1177 $attributes = array('class'=>'skip');
1178 foreach ($this->skiplinks as $url => $text) {
1179 $attributes['href'] = '#' . $url;
1180 $links .= html_writer::tag('a', $text, $attributes);
1182 $output = html_writer::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1184 // then the clever trick for hiding of things not needed when JS works
1185 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1186 $this->topofbodydone = true;
1187 return $output;
1191 * Generate any HTML that needs to go at the end of the page.
1193 * Normally, this method is called automatically by the code that prints the
1194 * page footer. You should not normally need to call it in your own code.
1196 * @return string the HTML code to to at the end of the page.
1198 public function get_end_code() {
1199 global $CFG;
1200 // add other requested modules
1201 $output = $this->get_extra_modules_code();
1203 // add missing YUI2 YUI - to be removed once we convert everything to YUI3!
1204 $output .= $this->get_yui2lib_code();
1206 // all the other linked scripts - there should be as few as possible
1207 if ($this->jsincludes['footer']) {
1208 foreach ($this->jsincludes['footer'] as $url) {
1209 $output .= html_writer::script('', $url);
1213 // add all needed strings
1214 if (!empty($this->stringsforjs)) {
1215 $output .= html_writer::script(js_writer::set_variable('M.str', $this->stringsforjs));
1218 // add variables
1219 if ($this->jsinitvariables['footer']) {
1220 $js = '';
1221 foreach ($this->jsinitvariables['footer'] as $data) {
1222 list($var, $value) = $data;
1223 $js .= js_writer::set_variable($var, $value, true);
1225 $output .= html_writer::script($js);
1228 $inyuijs = $this->get_javascript_code(false);
1229 $ondomreadyjs = $this->get_javascript_code(true);
1230 $jsinit = $this->get_javascript_init_code();
1231 $handlersjs = $this->get_event_handler_code();
1233 // there is no global Y, make sure it is available in your scope
1234 $js = "YUI(M.yui.loader).use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1236 $output .= html_writer::script($js);
1238 return $output;
1242 * Have we already output the code in the <head> tag?
1244 * @return bool
1246 public function is_head_done() {
1247 return $this->headdone;
1251 * Have we already output the code at the start of the <body> tag?
1253 * @return bool
1255 public function is_top_of_body_done() {
1256 return $this->topofbodydone;
1261 * Invalidate all server and client side JS caches.
1263 function js_reset_all_caches() {
1264 global $CFG;
1265 require_once("$CFG->libdir/filelib.php");
1267 $next = time();
1268 if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
1269 // This resolves problems when reset is requested repeatedly within 1s,
1270 // the < 1h condition prevents accidental switching to future dates
1271 // because we might not recover from it.
1272 $next = $CFG->jsrev+1;
1275 set_config('jsrev', $next);
1276 fulldelete("$CFG->cachedir/js");