Merge branch 'MDL-39444_23' of git://github.com/timhunt/moodle into MOODLE_23_STABLE
[moodle.git] / lib / outputrequirementslib.php
blobe2f6176d819da42dbe96d83ae7ac02e57bafe1ec
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 get_string $a parameters - used for validation only.
69 protected $stringsforjs_as = array();
71 /**
72 * @var array List of JS variables to be initialised
74 protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
76 /**
77 * @var array Included JS scripts
79 protected $jsincludes = array('head'=>array(), 'footer'=>array());
81 /**
82 * @var array List of needed function calls
84 protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
86 /**
87 * @var array List of skip links, those are needed for accessibility reasons
89 protected $skiplinks = array();
91 /**
92 * @var array Javascript code used for initialisation of page, it should
93 * be relatively small
95 protected $jsinitcode = array();
97 /**
98 * @var array of moodle_url Theme sheets, initialised only from core_renderer
100 protected $cssthemeurls = array();
103 * @var array of moodle_url List of custom theme sheets, these are strongly discouraged!
104 * Useful mostly only for CSS submitted by teachers that is not part of the theme.
106 protected $cssurls = array();
109 * @var array List of requested event handlers
111 protected $eventhandlers = array();
114 * @var array Extra modules
116 protected $extramodules = array();
119 * @var bool Flag indicated head stuff already printed
121 protected $headdone = false;
124 * @var bool Flag indicating top of body already printed
126 protected $topofbodydone = false;
129 * @var YAHOO_util_Loader YUI PHPLoader instance responsible for YUI2 loading
130 * from PHP only
132 protected $yui2loader;
135 * @var stdClass YUI PHPLoader instance responsible for YUI3 loading from PHP only
137 protected $yui3loader;
140 * @var stdClass YUI loader information for YUI3 loading from javascript
142 protected $M_yui_loader;
145 * @var array Some config vars exposed in JS, please no secret stuff there
147 protected $M_cfg;
150 * @var array Stores debug backtraces from when JS modules were included in the page
152 protected $debug_moduleloadstacktraces = array();
155 * Page requirements constructor.
157 public function __construct() {
158 global $CFG;
160 // You may need to set up URL rewrite rule because oversized URLs might not be allowed by web server.
161 $sep = empty($CFG->yuislasharguments) ? '?' : '/';
163 require_once("$CFG->libdir/yui/phploader/phploader/loader.php");
165 $this->yui3loader = new stdClass();
166 $this->yui2loader = new YAHOO_util_Loader($CFG->yui2version);
168 // set up some loader options
169 if (debugging('', DEBUG_DEVELOPER)) {
170 $this->yui3loader->filter = YUI_RAW; // for more detailed logging info use YUI_DEBUG here
171 $this->yui2loader->filter = YUI_RAW; // for more detailed logging info use YUI_DEBUG here
172 $this->yui2loader->allowRollups = false;
173 } else {
174 $this->yui3loader->filter = null;
175 $this->yui2loader->filter = null;
177 if (!empty($CFG->useexternalyui) and strpos($CFG->httpswwwroot, 'https:') !== 0) {
178 $this->yui3loader->base = 'http://yui.yahooapis.com/' . $CFG->yui3version . '/build/';
179 $this->yui2loader->base = 'http://yui.yahooapis.com/' . $CFG->yui2version . '/build/';
180 $this->yui3loader->comboBase = 'http://yui.yahooapis.com/combo?';
181 $this->yui2loader->comboBase = 'http://yui.yahooapis.com/combo?';
182 } else {
183 $this->yui3loader->base = $CFG->httpswwwroot . '/lib/yui/'. $CFG->yui3version . '/build/';
184 $this->yui2loader->base = $CFG->httpswwwroot . '/lib/yui/'. $CFG->yui2version . '/build/';
185 $this->yui3loader->comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep;
186 $this->yui2loader->comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep;
189 // enable combo loader? this significantly helps with caching and performance!
190 $this->yui3loader->combine = !empty($CFG->yuicomboloading);
191 $this->yui2loader->combine = !empty($CFG->yuicomboloading);
193 if (empty($CFG->cachejs)) {
194 $jsrev = -1;
195 } else if (empty($CFG->jsrev)) {
196 $jsrev = 1;
197 } else {
198 $jsrev = $CFG->jsrev;
201 // set up JS YUI loader helper object
202 $this->M_yui_loader = new stdClass();
203 $this->M_yui_loader->base = $this->yui3loader->base;
204 $this->M_yui_loader->comboBase = $this->yui3loader->comboBase;
205 $this->M_yui_loader->combine = $this->yui3loader->combine;
206 $this->M_yui_loader->filter = (string)$this->yui3loader->filter;
207 $this->M_yui_loader->insertBefore = 'firstthemesheet';
208 $this->M_yui_loader->modules = array();
209 $this->M_yui_loader->groups = array(
210 'moodle' => array(
211 'name' => 'moodle',
212 'base' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep.'moodle/'.$jsrev.'/',
213 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
214 'combine' => $this->yui3loader->combine,
215 'filter' => '',
216 'ext' => false,
217 'root' => 'moodle/'.$jsrev.'/', // Add the rev to the root path so that we can control caching
218 'patterns' => array(
219 'moodle-' => array(
220 'group' => 'moodle',
221 'configFn' => '@MOODLECONFIGFN@'
223 'root' => 'moodle'
226 'local' => array(
227 'name' => 'gallery',
228 'base' => $CFG->wwwroot.'/lib/yui/gallery/',
229 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
230 'combine' => $this->yui3loader->combine,
231 'filter' => $this->M_yui_loader->filter,
232 'ext' => false,
233 'root' => 'gallery/',
234 'patterns' => array(
235 'gallery-' => array(
236 'group' => 'gallery',
237 'configFn' => '@GALLERYCONFIGFN@',
239 'root' => 'gallery'
243 $this->add_yui2_modules(); // adds loading info for all YUI2 modules
244 $this->js_module($this->find_module('core_filepicker'));
245 $this->js_module($this->find_module('core_dock'));
250 * This method adds yui2 modules into the yui3 JS loader so that they can
251 * be easily included for use in JavaScript.
253 protected function add_yui2_modules() {
254 //note: this function is definitely not perfect, because
255 // it adds tons of markup into each page, but it can be
256 // abstracted into separate JS file with proper headers
257 global $CFG;
259 $GLOBALS['yui_current'] = array();
260 require($CFG->libdir.'/yui/phploader/lib/meta/config_'.$CFG->yui2version.'.php');
261 $info = $GLOBALS['yui_current'];
262 unset($GLOBALS['yui_current']);
264 if (empty($CFG->yuicomboloading)) {
265 $urlbase = $this->yui2loader->base;
266 } else {
267 $urlbase = $this->yui2loader->comboBase.$CFG->yui2version.'/build/';
270 $modules = array();
271 $ignored = array(); // list of CSS modules that are not needed
272 foreach ($info['moduleInfo'] as $name => $module) {
273 if ($module['type'] === 'css') {
274 $ignored[$name] = true;
275 } else {
276 $modules['yui2-'.$name] = $module;
279 foreach ($modules as $name=>$module) {
280 $module['fullpath'] = $urlbase.$module['path']; // fix path to point to correct location
281 $module['async'] = false;
282 unset($module['path']);
283 unset($module['skinnable']); // we load all YUI2 css automatically, this prevents weird missing css loader problems
284 foreach(array('requires', 'optional', 'supersedes') as $fixme) {
285 if (!empty($module[$fixme])) {
286 $fixed = false;
287 foreach ($module[$fixme] as $key=>$dep) {
288 if (isset($ignored[$dep])) {
289 unset($module[$fixme][$key]);
290 $fixed = true;
291 } else {
292 $module[$fixme][$key] = 'yui2-'.$dep;
295 if ($fixed) {
296 $module[$fixme] = array_merge($module[$fixme]); // fix keys
300 $this->M_yui_loader->modules[$name] = $module;
301 if (debugging('', DEBUG_DEVELOPER)) {
302 if (!array_key_exists($name, $this->debug_moduleloadstacktraces)) {
303 $this->debug_moduleloadstacktraces[$name] = array();
305 $this->debug_moduleloadstacktraces[$name][] = format_backtrace(debug_backtrace());
311 * Initialise with the bits of JavaScript that every Moodle page should have.
313 * @param moodle_page $page
314 * @param core_renderer $renderer
316 protected function init_requirements_data(moodle_page $page, core_renderer $renderer) {
317 global $CFG;
319 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
320 // Otherwise, in some situations, users will get warnings about insecure content
321 // on secure pages from their web browser.
323 $this->M_cfg = array(
324 'wwwroot' => $CFG->httpswwwroot, // Yes, really. See above.
325 'sesskey' => sesskey(),
326 'loadingicon' => $renderer->pix_url('i/loading_small', 'moodle')->out(false),
327 'themerev' => theme_get_revision(),
328 'slasharguments' => (int)(!empty($CFG->slasharguments)),
329 'theme' => $page->theme->name,
330 'jsrev' => ((empty($CFG->cachejs) or empty($CFG->jsrev)) ? -1 : $CFG->jsrev),
332 if (debugging('', DEBUG_DEVELOPER)) {
333 $this->M_cfg['developerdebug'] = true;
336 // accessibility stuff
337 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
339 // to be removed soon
340 $this->yui2_lib('dom'); // at least javascript-static.js needs to be migrated to YUI3
342 $this->string_for_js('confirmation', 'admin');
343 $this->string_for_js('cancel', 'moodle');
344 $this->string_for_js('yes', 'moodle');
346 if ($page->pagelayout === 'frametop') {
347 $this->js_init_call('M.util.init_frametop');
352 * Ensure that the specified JavaScript file is linked to from this page.
354 * NOTE: This function is to be used in rare cases only, please store your JS in module.js file
355 * and use $PAGE->requires->js_init_call() instead.
357 * By default the link is put at the end of the page, since this gives best page-load performance.
359 * Even if a particular script is requested more than once, it will only be linked
360 * to once.
362 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
363 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
364 * @param bool $inhead initialise in head
366 public function js($url, $inhead = false) {
367 $url = $this->js_fix_url($url);
368 $where = $inhead ? 'head' : 'footer';
369 $this->jsincludes[$where][$url->out()] = $url;
373 * Ensure that the specified YUI2 library file, and all its required dependencies,
374 * are linked to from this page.
376 * By default the link is put at the end of the page, since this gives best page-load
377 * performance. Optional dependencies are not loaded automatically - if you want
378 * them you will need to load them first with other calls to this method.
380 * Even if a particular library is requested more than once (perhaps as a dependency
381 * of other libraries) it will only be linked to once.
383 * The library is leaded as soon as possible, if $OUTPUT->header() not used yet it
384 * is put into the page header, otherwise it is loaded in the page footer.
386 * @param string|array $libname the name of the YUI2 library you require. For example 'autocomplete'.
388 public function yui2_lib($libname) {
389 $libnames = (array)$libname;
390 foreach ($libnames as $lib) {
391 $this->yui2loader->load($lib);
396 * Returns the actual url through which a script is served.
398 * @param moodle_url|string $url full moodle url, or shortened path to script
399 * @return moodle_url
401 protected function js_fix_url($url) {
402 global $CFG;
404 if ($url instanceof moodle_url) {
405 return $url;
406 } else if (strpos($url, '/') === 0) {
407 // Fix the admin links if needed.
408 if ($CFG->admin !== 'admin') {
409 if (strpos($url, "/admin/") === 0) {
410 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
413 if (debugging()) {
414 // check file existence only when in debug mode
415 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
416 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
419 if (!empty($CFG->cachejs) and !empty($CFG->jsrev) and $CFG->jsrev > 0 and strpos($url, '/lib/editor/') !== 0 and substr($url, -3) === '.js') {
420 if (empty($CFG->slasharguments)) {
421 return new moodle_url($CFG->httpswwwroot.'/lib/javascript.php', array('rev'=>$CFG->jsrev, 'jsfile'=>$url));
422 } else {
423 $returnurl = new moodle_url($CFG->httpswwwroot.'/lib/javascript.php');
424 $returnurl->set_slashargument('/'.$CFG->jsrev.$url);
425 return $returnurl;
427 } else {
428 return new moodle_url($CFG->httpswwwroot.$url);
430 } else {
431 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
436 * Find out if JS module present and return details.
438 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
439 * @return array description of module or null if not found
441 protected function find_module($component) {
442 global $CFG, $PAGE;
444 $module = null;
446 if (strpos($component, 'core_') === 0) {
447 // must be some core stuff - list here is not complete, this is just the stuff used from multiple places
448 // so that we do nto have to repeat the definition of these modules over and over again
449 switch($component) {
450 case 'core_filepicker':
451 $module = array('name' => 'core_filepicker',
452 'fullpath' => '/repository/filepicker.js',
453 'requires' => array('base', 'node', 'node-event-simulate', 'json', 'async-queue', 'io-base', 'io-upload-iframe', 'io-form', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort', 'resize-plugin', 'dd-plugin', 'escape', 'moodle-core_filepicker'),
454 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
455 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
456 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
457 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
458 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
459 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
460 array('referencesexist', 'repository')
462 break;
463 case 'core_comment':
464 $module = array('name' => 'core_comment',
465 'fullpath' => '/comment/comment.js',
466 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
467 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
469 break;
470 case 'core_role':
471 $module = array('name' => 'core_role',
472 'fullpath' => '/admin/roles/module.js',
473 'requires' => array('node', 'cookie'));
474 break;
475 case 'core_completion':
476 $module = array('name' => 'core_completion',
477 'fullpath' => '/course/completion.js');
478 break;
479 case 'core_dock':
480 $module = array('name' => 'core_dock',
481 'fullpath' => '/blocks/dock.js',
482 'requires' => array('base', 'node', 'event-custom', 'event-mouseenter', 'event-resize'),
483 'strings' => array(array('addtodock', 'block'),array('undockitem', 'block'),array('undockall', 'block'),array('thisdirectionvertical', 'langconfig'),array('hidedockpanel', 'block'),array('hidepanel', 'block')));
484 break;
485 case 'core_message':
486 $module = array('name' => 'core_message',
487 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
488 'fullpath' => '/message/module.js');
489 break;
490 case 'core_group':
491 $module = array('name' => 'core_group',
492 'fullpath' => '/group/module.js',
493 'requires' => array('node', 'overlay', 'event-mouseenter'));
494 break;
495 case 'core_question_engine':
496 $module = array('name' => 'core_question_engine',
497 'fullpath' => '/question/qengine.js',
498 'requires' => array('node', 'event'));
499 break;
500 case 'core_rating':
501 $module = array('name' => 'core_rating',
502 'fullpath' => '/rating/module.js',
503 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
504 break;
505 case 'core_filetree':
506 $module = array('name' => 'core_filetree',
507 'fullpath' => '/files/module.js',
508 'requires' => array('node', 'event', 'overlay', 'io-base', 'json', 'yui2-treeview'));
509 break;
510 case 'core_dndupload':
511 $module = array('name' => 'core_dndupload',
512 'fullpath' => '/lib/form/dndupload.js',
513 'requires' => array('node', 'event', 'json', 'core_filepicker'),
514 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'), array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle')));
515 break;
518 } else {
519 if ($dir = get_component_directory($component)) {
520 if (file_exists("$dir/module.js")) {
521 if (strpos($dir, $CFG->dirroot.'/') === 0) {
522 $dir = substr($dir, strlen($CFG->dirroot));
523 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
529 return $module;
533 * Append YUI3 module to default YUI3 JS loader.
534 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
536 * @param string|array $module name of module (details are autodetected), or full module specification as array
537 * @return void
539 public function js_module($module) {
540 global $CFG;
542 if (empty($module)) {
543 throw new coding_exception('Missing YUI3 module name or full description.');
546 if (is_string($module)) {
547 $module = $this->find_module($module);
550 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
551 throw new coding_exception('Missing YUI3 module details.');
554 // Don't load this module if we already have, no need to!
555 if ($this->js_module_loaded($module['name'])) {
556 if (debugging('', DEBUG_DEVELOPER)) {
557 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
559 return;
562 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
563 // add all needed strings
564 if (!empty($module['strings'])) {
565 foreach ($module['strings'] as $string) {
566 $identifier = $string[0];
567 $component = isset($string[1]) ? $string[1] : 'moodle';
568 $a = isset($string[2]) ? $string[2] : null;
569 $this->string_for_js($identifier, $component, $a);
572 unset($module['strings']);
574 // Process module requirements and attempt to load each. This allows
575 // moodle modules to require each other.
576 if (!empty($module['requires'])){
577 foreach ($module['requires'] as $requirement) {
578 $rmodule = $this->find_module($requirement);
579 if (is_array($rmodule)) {
580 $this->js_module($rmodule);
585 if ($this->headdone) {
586 $this->extramodules[$module['name']] = $module;
587 } else {
588 $this->M_yui_loader->modules[$module['name']] = $module;
590 if (debugging('', DEBUG_DEVELOPER)) {
591 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces)) {
592 $this->debug_moduleloadstacktraces[$module['name']] = array();
594 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
599 * Returns true if the module has already been loaded.
601 * @param string|array $module
602 * @return bool True if the module has already been loaded
604 protected function js_module_loaded($module) {
605 if (is_string($module)) {
606 $modulename = $module;
607 } else {
608 $modulename = $module['name'];
610 return array_key_exists($modulename, $this->M_yui_loader->modules) ||
611 array_key_exists($modulename, $this->extramodules);
615 * Returns the stacktraces from loading js modules.
616 * @return array
618 public function get_loaded_modules() {
619 return $this->debug_moduleloadstacktraces;
623 * Ensure that the specified CSS file is linked to from this page.
625 * Because stylesheet links must go in the <head> part of the HTML, you must call
626 * this function before {@link get_head_code()} is called. That normally means before
627 * the call to print_header. If you call it when it is too late, an exception
628 * will be thrown.
630 * Even if a particular style sheet is requested more than once, it will only
631 * be linked to once.
633 * Please note use of this feature is strongly discouraged,
634 * it is suitable only for places where CSS is submitted directly by teachers.
635 * (Students must not be allowed to submit any external CSS because it may
636 * contain embedded javascript!). Example of correct use is mod/data.
638 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
639 * For example:
640 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
642 public function css($stylesheet) {
643 global $CFG;
645 if ($this->headdone) {
646 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
649 if ($stylesheet instanceof moodle_url) {
650 // ok
651 } else if (strpos($stylesheet, '/') === 0) {
652 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
653 } else {
654 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
657 $this->cssurls[$stylesheet->out()] = $stylesheet; // overrides
661 * Add theme stylkesheet to page - do not use from plugin code,
662 * this should be called only from the core renderer!
664 * @param moodle_url $stylesheet
665 * @return void
667 public function css_theme(moodle_url $stylesheet) {
668 $this->cssthemeurls[] = $stylesheet;
672 * Ensure that a skip link to a given target is printed at the top of the <body>.
674 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
675 * will be thrown). That normally means you must call this before the call to print_header.
677 * If you ask for a particular skip link to be printed, it is then your responsibility
678 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
679 * page, so that the skip link goes somewhere.
681 * Even if a particular skip link is requested more than once, only one copy of it will be output.
683 * @param $target the name of anchor this link should go to. For example 'maincontent'.
684 * @param $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
686 public function skip_link_to($target, $linktext) {
687 if ($this->topofbodydone) {
688 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
689 return;
691 $this->skiplinks[$target] = $linktext;
695 * !!!DEPRECATED!!! please use js_init_call() if possible
696 * Ensure that the specified JavaScript function is called from an inline script
697 * somewhere on this page.
699 * By default the call will be put in a script tag at the
700 * end of the page after initialising Y instance, since this gives best page-load
701 * performance and allows you to use YUI3 library.
703 * If you request that a particular function is called several times, then
704 * that is what will happen (unlike linking to a CSS or JS file, where only
705 * one link will be output).
707 * The main benefit of the method is the automatic encoding of all function parameters.
709 * @param string $function the name of the JavaScritp function to call. Can
710 * be a compound name like 'Y.Event.purgeElement'. Can also be
711 * used to create and object by using a 'function name' like 'new user_selector'.
712 * @param array $arguments and array of arguments to be passed to the function.
713 * When generating the function call, this will be escaped using json_encode,
714 * so passing objects and arrays should work.
715 * @param bool $ondomready If tru the function is only called when the dom is
716 * ready for manipulation.
717 * @param int $delay The delay before the function is called.
719 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
720 $where = $ondomready ? 'ondomready' : 'normal';
721 $this->jscalls[$where][] = array($function, $arguments, $delay);
725 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
727 * @deprecated DO NOT USE
729 * @param string|array $modules One or more gallery modules to require
730 * @param string $version
731 * @param string $function
732 * @param array $arguments
733 * @param bool $ondomready
735 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
736 global $CFG;
737 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER);
738 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
742 * Creates a JavaScript function call that requires one or more modules to be loaded
744 * This function can be used to include all of the standard YUI module types within JavaScript:
745 * - YUI3 modules [node, event, io]
746 * - YUI2 modules [yui2-*]
747 * - Moodle modules [moodle-*]
748 * - Gallery modules [gallery-*]
750 * @param array|string $modules One or more modules
751 * @param string $function The function to call once modules have been loaded
752 * @param array $arguments An array of arguments to pass to the function
753 * @param string $galleryversion The gallery version to use
754 * @param bool $ondomready
756 public function yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
757 global $CFG;
759 if (!is_array($modules)) {
760 $modules = array($modules);
762 if (empty($CFG->useexternalyui)) {
763 // We need to set the M.yui.galleryversion to the correct version
764 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
765 } else {
766 // Set Y's config.gallery to the version
767 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
769 $jscode .= 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
770 if ($ondomready) {
771 $jscode = "Y.on('domready', function() { $jscode });";
773 $this->jsinitcode[] = $jscode;
777 * Ensure that the specified JavaScript function is called from an inline script
778 * from page footer.
780 * @param string $function the name of the JavaScritp function to with init code,
781 * usually something like 'M.mod_mymodule.init'
782 * @param array $extraarguments and array of arguments to be passed to the function.
783 * The first argument is always the YUI3 Y instance with all required dependencies
784 * already loaded.
785 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
786 * @param array $module JS module specification array
788 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
789 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
790 if (!$module) {
791 // detect module automatically
792 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
793 $module = $this->find_module($matches[1]);
797 $this->js_init_code($jscode, $ondomready, $module);
801 * Add short static javascript code fragment to page footer.
802 * This is intended primarily for loading of js modules and initialising page layout.
803 * Ideally the JS code fragment should be stored in plugin renderer so that themes
804 * may override it.
805 * @param string $jscode
806 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
807 * @param array $module JS module specification array
809 public function js_init_code($jscode, $ondomready = false, array $module = null) {
810 $jscode = trim($jscode, " ;\n"). ';';
812 if ($module) {
813 $this->js_module($module);
814 $modulename = $module['name'];
815 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
818 if ($ondomready) {
819 $jscode = "Y.on('domready', function() { $jscode });";
822 $this->jsinitcode[] = $jscode;
826 * Make a language string available to JavaScript.
828 * All the strings will be available in a M.str object in the global namespace.
829 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
830 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
831 * equivalent in the current language.
833 * The arguments to this function are just like the arguments to get_string
834 * except that $component is not optional, and there are some aspects to consider
835 * when the string contains {$a} placeholder.
837 * If the string does not contain any {$a} placeholder, you can simply use
838 * M.str.component.identifier to obtain it. If you prefer, you can call
839 * M.util.get_string(identifier, component) to get the same result.
841 * If you need to use {$a} placeholders, there are two options. Either the
842 * placeholder should be substituted in PHP on server side or it should
843 * be substituted in Javascript at client side.
845 * To substitute the placeholder at server side, just provide the required
846 * value for the placeholder when you require the string. Because each string
847 * is only stored once in the JavaScript (based on $identifier and $module)
848 * you cannot get the same string with two different values of $a. If you try,
849 * an exception will be thrown. Once the placeholder is substituted, you can
850 * use M.str or M.util.get_string() as shown above:
852 * // require the string in PHP and replace the placeholder
853 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
854 * // use the result of the substitution in Javascript
855 * alert(M.str.moodle.fullnamedisplay);
857 * To substitute the placeholder at client side, use M.util.get_string()
858 * function. It implements the same logic as {@link get_string()}:
860 * // require the string in PHP but keep {$a} as it is
861 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
862 * // provide the values on the fly in Javascript
863 * user = { firstname : 'Harry', lastname : 'Potter' }
864 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
866 * If you do need the same string expanded with different $a values in PHP
867 * on server side, then the solution is to put them in your own data structure
868 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
870 * @param string $identifier the desired string.
871 * @param string $component the language file to look in.
872 * @param mixed $a any extra data to add into the string (optional).
874 public function string_for_js($identifier, $component, $a = NULL) {
875 if (!$component) {
876 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
878 if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
879 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
880 "from lang file '$component' with different \$a parameter?");
882 if (!isset($this->stringsforjs[$component][$identifier])) {
883 $this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
884 $this->stringsforjs_as[$component][$identifier] = $a;
889 * Make an array of language strings available for JS
891 * This function calls the above function {@link string_for_js()} for each requested
892 * string in the $identifiers array that is passed to the argument for a single module
893 * passed in $module.
895 * <code>
896 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
898 * // The above is identitical to calling
900 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
901 * $PAGE->requires->string_for_js('two', 'mymod');
902 * $PAGE->requires->string_for_js('three', 'mymod', 3);
903 * </code>
905 * @param array $identifiers An array of desired strings
906 * @param string $component The module to load for
907 * @param mixed $a This can either be a single variable that gets passed as extra
908 * information for every string or it can be an array of mixed data where the
909 * key for the data matches that of the identifier it is meant for.
912 public function strings_for_js($identifiers, $component, $a=NULL) {
913 foreach ($identifiers as $key => $identifier) {
914 if (is_array($a) && array_key_exists($key, $a)) {
915 $extra = $a[$key];
916 } else {
917 $extra = $a;
919 $this->string_for_js($identifier, $component, $extra);
924 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
926 * Make some data from PHP available to JavaScript code.
928 * For example, if you call
929 * <pre>
930 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
931 * </pre>
932 * then in JavsScript mydata.name will be 'Moodle'.
933 * @param string $variable the the name of the JavaScript variable to assign the data to.
934 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
935 * should be considered an experimental feature.
936 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
937 * so passing objects and arrays should work.
938 * @param bool $inhead initialise in head
939 * @return void
941 public function data_for_js($variable, $data, $inhead=false) {
942 $where = $inhead ? 'head' : 'footer';
943 $this->jsinitvariables[$where][] = array($variable, $data);
947 * Creates a YUI event handler.
949 * @param mixed $selector standard YUI selector for elemnts, may be array or string, element id is in the form "#idvalue"
950 * @param string $event A valid DOM event (click, mousedown, change etc.)
951 * @param string $function The name of the function to call
952 * @param array $arguments An optional array of argument parameters to pass to the function
954 public function event_handler($selector, $event, $function, array $arguments = null) {
955 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
959 * Returns code needed for registering of event handlers.
960 * @return string JS code
962 protected function get_event_handler_code() {
963 $output = '';
964 foreach ($this->eventhandlers as $h) {
965 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
967 return $output;
971 * Get the inline JavaScript code that need to appear in a particular place.
972 * @param bool $ondomready
973 * @return string
975 protected function get_javascript_code($ondomready) {
976 $where = $ondomready ? 'ondomready' : 'normal';
977 $output = '';
978 if ($this->jscalls[$where]) {
979 foreach ($this->jscalls[$where] as $data) {
980 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
982 if (!empty($ondomready)) {
983 $output = " Y.on('domready', function() {\n$output\n });";
986 return $output;
990 * Returns js code to be executed when Y is available.
991 * @return string
993 protected function get_javascript_init_code() {
994 if (count($this->jsinitcode)) {
995 return implode("\n", $this->jsinitcode) . "\n";
997 return '';
1001 * Returns basic YUI3 JS loading code.
1002 * YUI3 is using autoloading of both CSS and JS code.
1004 * Major benefit of this compared to standard js/csss loader is much improved
1005 * caching, better browser cache utilisation, much fewer http requests.
1007 * @return string
1009 protected function get_yui3lib_headcode() {
1010 global $CFG;
1012 $code = '';
1014 if ($this->yui3loader->combine) {
1015 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase
1016 .$CFG->yui3version.'/build/cssreset/reset-min.css&amp;'
1017 .$CFG->yui3version.'/build/cssfonts/fonts-min.css&amp;'
1018 .$CFG->yui3version.'/build/cssgrids/grids-min.css&amp;'
1019 .$CFG->yui3version.'/build/cssbase/base-min.css" />';
1020 $code .= '<script type="text/javascript" src="'.$this->yui3loader->comboBase.$CFG->yui3version.'/build/yui/yui-min.js"></script>';
1021 } else {
1022 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssreset/reset-min.css" />';
1023 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssfonts/fonts-min.css" />';
1024 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssgrids/grids-min.css" />';
1025 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssbase/base-min.css" />';
1026 $code .= '<script type="text/javascript" src="'.$this->yui3loader->base.'yui/yui-min.js"></script>';
1030 if ($this->yui3loader->filter === YUI_RAW) {
1031 $code = str_replace('-min.css', '.css', $code);
1032 $code = str_replace('-min.js', '.js', $code);
1033 } else if ($this->yui3loader->filter === YUI_DEBUG) {
1034 $code = str_replace('-min.css', '.css', $code);
1035 $code = str_replace('-min.js', '-debug.js', $code);
1038 return $code;
1042 * Returns basic YUI2 JS loading code.
1043 * It can be called manually at any time.
1044 * If called manually the result needs to be output using echo().
1046 * Major benefit of this compared to standard js loader is much improved
1047 * caching, better browser cache utilisation, much fewer http requests.
1049 * All YUI2 CSS is loaded automatically.
1051 * @return string JS embedding code
1053 public function get_yui2lib_code() {
1054 global $CFG;
1056 if ($this->headdone) {
1057 $code = $this->yui2loader->script();
1058 } else {
1059 $code = $this->yui2loader->script();
1060 if ($this->yui2loader->combine) {
1061 $skinurl = $this->yui2loader->comboBase . $CFG->yui2version . '/build/assets/skins/sam/skin.css';
1062 } else {
1063 $skinurl = $this->yui2loader->base . 'assets/skins/sam/skin.css';
1065 // please note this is a temporary hack until we fully migrate to later YUI3 that has all the widgets
1066 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css', 'href'=>$skinurl);
1067 $code .= "\n" . html_writer::empty_tag('link', $attributes) . "\n";
1069 $code = str_replace('&amp;', '&', $code);
1070 $code = str_replace('&', '&amp;', $code);
1071 return $code;
1075 * Returns html tags needed for inclusion of theme CSS
1077 * @return string
1079 protected function get_css_code() {
1080 // First of all the theme CSS, then any custom CSS
1081 // Please note custom CSS is strongly discouraged,
1082 // because it can not be overridden by themes!
1083 // It is suitable only for things like mod/data which accepts CSS from teachers.
1084 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1086 // This line of code may look funny but it is currently required in order
1087 // to avoid MASSIVE display issues in Internet Explorer.
1088 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1089 // ignored whenever another resource is added until such time as a redraw
1090 // is forced, usually by moving the mouse over the affected element.
1091 $code = html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1093 $urls = $this->cssthemeurls + $this->cssurls;
1094 foreach ($urls as $url) {
1095 $attributes['href'] = $url;
1096 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1097 // this id is needed in first sheet only so that theme may override YUI sheets laoded on the fly
1098 unset($attributes['id']);
1101 return $code;
1105 * Adds extra modules specified after printing of page header
1107 * @return string
1109 protected function get_extra_modules_code() {
1110 if (empty($this->extramodules)) {
1111 return '';
1113 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1117 * Generate any HTML that needs to go inside the <head> tag.
1119 * Normally, this method is called automatically by the code that prints the
1120 * <head> tag. You should not normally need to call it in your own code.
1122 * @param moodle_page $page
1123 * @param core_renderer $renderer
1124 * @return string the HTML code to to inside the <head> tag.
1126 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1127 global $CFG;
1129 // note: the $page and $output are not stored here because it would
1130 // create circular references in memory which prevents garbage collection
1131 $this->init_requirements_data($page, $renderer);
1133 // yui3 JS and CSS is always loaded first - it is cached in browser
1134 $output = $this->get_yui3lib_headcode();
1136 // BC: load basic YUI2 for now, all yui2 things should be loaded via Y.use('yui2-oldmodulename')
1137 $output .= $this->get_yui2lib_code();
1139 // now theme CSS + custom CSS in this specific order
1140 $output .= $this->get_css_code();
1142 // set up global YUI3 loader object - this should contain all code needed by plugins
1143 // note: in JavaScript just use "YUI(M.yui.loader).use('overlay', function(Y) { .... });"
1144 // this needs to be done before including any other script
1145 $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";
1146 $js .= js_writer::set_variable('M.yui.loader', $this->M_yui_loader, false) . "\n";
1147 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1148 $js = str_replace('"@GALLERYCONFIGFN@"', 'galleryConfigFn', $js);
1149 $js = str_replace('"@MOODLECONFIGFN@"', 'moodleConfigFn', $js);
1151 $output .= html_writer::script($js);
1153 // link our main JS file, all core stuff should be there
1154 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1156 // add variables
1157 if ($this->jsinitvariables['head']) {
1158 $js = '';
1159 foreach ($this->jsinitvariables['head'] as $data) {
1160 list($var, $value) = $data;
1161 $js .= js_writer::set_variable($var, $value, true);
1163 $output .= html_writer::script($js);
1166 // all the other linked things from HEAD - there should be as few as possible
1167 if ($this->jsincludes['head']) {
1168 foreach ($this->jsincludes['head'] as $url) {
1169 $output .= html_writer::script('', $url);
1173 // mark head sending done, it is not possible to anything there
1174 $this->headdone = true;
1176 return $output;
1180 * Generate any HTML that needs to go at the start of the <body> tag.
1182 * Normally, this method is called automatically by the code that prints the
1183 * <head> tag. You should not normally need to call it in your own code.
1185 * @return string the HTML code to go at the start of the <body> tag.
1187 public function get_top_of_body_code() {
1188 // first the skip links
1189 $links = '';
1190 $attributes = array('class'=>'skip');
1191 foreach ($this->skiplinks as $url => $text) {
1192 $attributes['href'] = '#' . $url;
1193 $links .= html_writer::tag('a', $text, $attributes);
1195 $output = html_writer::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1197 // then the clever trick for hiding of things not needed when JS works
1198 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1199 $this->topofbodydone = true;
1200 return $output;
1204 * Generate any HTML that needs to go at the end of the page.
1206 * Normally, this method is called automatically by the code that prints the
1207 * page footer. You should not normally need to call it in your own code.
1209 * @return string the HTML code to to at the end of the page.
1211 public function get_end_code() {
1212 global $CFG;
1213 // add other requested modules
1214 $output = $this->get_extra_modules_code();
1216 // add missing YUI2 YUI - to be removed once we convert everything to YUI3!
1217 $output .= $this->get_yui2lib_code();
1219 // all the other linked scripts - there should be as few as possible
1220 if ($this->jsincludes['footer']) {
1221 foreach ($this->jsincludes['footer'] as $url) {
1222 $output .= html_writer::script('', $url);
1226 // add all needed strings
1227 if (!empty($this->stringsforjs)) {
1228 $strings = array();
1229 foreach ($this->stringsforjs as $component=>$v) {
1230 foreach($v as $indentifier => $langstring) {
1231 $strings[$component][$indentifier] = $langstring->out();
1234 $output .= html_writer::script(js_writer::set_variable('M.str', $strings));
1237 // add variables
1238 if ($this->jsinitvariables['footer']) {
1239 $js = '';
1240 foreach ($this->jsinitvariables['footer'] as $data) {
1241 list($var, $value) = $data;
1242 $js .= js_writer::set_variable($var, $value, true);
1244 $output .= html_writer::script($js);
1247 $inyuijs = $this->get_javascript_code(false);
1248 $ondomreadyjs = $this->get_javascript_code(true);
1249 $jsinit = $this->get_javascript_init_code();
1250 $handlersjs = $this->get_event_handler_code();
1252 // there is no global Y, make sure it is available in your scope
1253 $js = "YUI(M.yui.loader).use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1255 $output .= html_writer::script($js);
1257 return $output;
1261 * Have we already output the code in the <head> tag?
1263 * @return bool
1265 public function is_head_done() {
1266 return $this->headdone;
1270 * Have we already output the code at the start of the <body> tag?
1272 * @return bool
1274 public function is_top_of_body_done() {
1275 return $this->topofbodydone;
1280 * Invalidate all server and client side JS caches.
1282 function js_reset_all_caches() {
1283 global $CFG;
1284 require_once("$CFG->libdir/filelib.php");
1286 $next = time();
1287 if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
1288 // This resolves problems when reset is requested repeatedly within 1s,
1289 // the < 1h condition prevents accidental switching to future dates
1290 // because we might not recover from it.
1291 $next = $CFG->jsrev+1;
1294 set_config('jsrev', $next);
1295 fulldelete("$CFG->cachedir/js");