MDL-27639 restore of attempt data from 2.0 - first attempt.
[moodle.git] / lib / outputrequirementslib.php
blob336f36e6a81069af842ae81eca7ff3745ce242af
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 /**
20 * Library functions to facilitate the use of JavaScript in Moodle.
22 * @package core
23 * @subpackage lib
24 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 // note: you can find history of this file in lib/ajax/ajaxlib.php
32 /**
33 * This class tracks all the things that are needed by the current page.
35 * Normally, the only instance of this class you will need to work with is the
36 * one accessible via $PAGE->requires.
38 * Typical usage would be
39 * <pre>
40 * $PAGE->requires->js_init_call('M.mod_forum.init_view');
41 * </pre>
43 * It also supports obsoleted coding style withouth YUI3 modules.
44 * <pre>
45 * $PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overridable via themes!
46 * $PAGE->requires->js('/mod/mymod/script.js');
47 * $PAGE->requires->js('/mod/mymod/small_but_urgent.js', true);
48 * $PAGE->requires->js_function_call('init_mymod', array($data), true);
49 * </pre>
51 * There are some natural restrictions on some methods. For example, {@link css()}
52 * can only be called before the <head> tag is output. See the comments on the
53 * individual methods for details.
55 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
57 * @since Moodle 2.0
59 class page_requirements_manager {
60 /** List of string available from JS */
61 protected $stringsforjs = array();
62 /** List of JS variables to be initialised */
63 protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
64 /** Included JS scripts */
65 protected $jsincludes = array('head'=>array(), 'footer'=>array());
66 /** List of needed function calls */
67 protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
68 /**
69 * List of skip links, those are needed for accessibility reasons
70 * @var array
72 protected $skiplinks = array();
73 /**
74 * Javascript code used for initialisation of page, it should be relatively small
75 * @var array
77 protected $jsinitcode = array();
78 /**
79 * Theme sheets, initialised only from core_renderer
80 * @var array of moodle_url
82 protected $cssthemeurls = array();
83 /**
84 * List of custom theme sheets, these are strongly discouraged!
85 * Useful mostly only for CSS submitted by teachers that is not part of the theme.
86 * @var array of moodle_url
88 protected $cssurls = array();
89 /**
90 * List of requested event handlers
91 * @var array
93 protected $eventhandlers = array();
94 /**
95 * Extra modules
96 * @var array
98 protected $extramodules = array();
99 /** Flag indicated head stuff already printed */
100 protected $headdone = false;
101 /** Flag indicating top of body already printed */
102 protected $topofbodydone = false;
104 /** YUI PHPLoader instance responsible for YUI2 loading from PHP only */
105 protected $yui2loader;
106 /** YUI PHPLoader instance responsible for YUI3 loading from PHP only */
107 protected $yui3loader;
108 /** YUI PHPLoader instance responsible for YUI3 loading from javascript */
109 protected $M_yui_loader;
110 /** some config vars exposed in JS, please no secret stuff there */
111 protected $M_cfg;
112 /** stores debug backtraces from when JS modules were included in the page */
113 protected $debug_moduleloadstacktraces = array();
116 * Page requirements constructor.
118 public function __construct() {
119 global $CFG;
121 require_once("$CFG->libdir/yui/phploader/phploader/loader.php");
123 $this->yui3loader = new YAHOO_util_Loader($CFG->yui3version);
124 $this->yui2loader = new YAHOO_util_Loader($CFG->yui2version);
126 // set up some loader options
127 if (debugging('', DEBUG_DEVELOPER)) {
128 $this->yui3loader->filter = YUI_DEBUG; // alternatively we could use just YUI_RAW here
129 $this->yui2loader->filter = YUI_DEBUG; // alternatively we could use just YUI_RAW here
130 } else {
131 $this->yui3loader->filter = null;
132 $this->yui2loader->filter = null;
134 if (!empty($CFG->useexternalyui)) {
135 $this->yui3loader->base = 'http://yui.yahooapis.com/' . $CFG->yui3version . '/build/';
136 $this->yui2loader->base = 'http://yui.yahooapis.com/' . $CFG->yui2version . '/build/';
137 $this->yui3loader->comboBase = 'http://yui.yahooapis.com/combo?';
138 $this->yui2loader->comboBase = 'http://yui.yahooapis.com/combo?';
139 } else {
140 $this->yui3loader->base = $CFG->httpswwwroot . '/lib/yui/'. $CFG->yui3version . '/build/';
141 $this->yui2loader->base = $CFG->httpswwwroot . '/lib/yui/'. $CFG->yui2version . '/build/';
142 $this->yui3loader->comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php?';
143 $this->yui2loader->comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php?';
146 // enable combo loader? this significantly helps with caching and performance!
147 $this->yui3loader->combine = !empty($CFG->yuicomboloading);
148 $this->yui2loader->combine = !empty($CFG->yuicomboloading);
150 if (empty($CFG->cachejs)) {
151 $jsrev = -1;
152 } else if (empty($CFG->jsrev)) {
153 $jsrev = 1;
154 } else {
155 $jsrev = $CFG->jsrev;
158 // set up JS YUI loader helper object
159 $this->M_yui_loader = new stdClass();
160 $this->M_yui_loader->base = $this->yui3loader->base;
161 $this->M_yui_loader->comboBase = $this->yui3loader->comboBase;
162 $this->M_yui_loader->combine = $this->yui3loader->combine;
163 $this->M_yui_loader->filter = ($this->yui3loader->filter == YUI_DEBUG) ? 'debug' : '';
164 $this->M_yui_loader->insertBefore = 'firstthemesheet';
165 $this->M_yui_loader->modules = array();
166 $this->M_yui_loader->groups = array(
167 'moodle' => array(
168 'name' => 'moodle',
169 'base' => $CFG->httpswwwroot . '/theme/yui_combo.php?moodle/'.$jsrev.'/',
170 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php?',
171 'combine' => $this->yui3loader->combine,
172 'filter' => '',
173 'ext' => false,
174 'root' => 'moodle/'.$jsrev.'/', // Add the rev to the root path so that we can control caching
175 'patterns' => array(
176 'moodle-' => array(
177 'group' => 'moodle',
178 'configFn' => '@MOODLECONFIGFN@'
180 'root' => 'moodle'
183 'local' => array(
184 'name' => 'gallery',
185 'base' => $CFG->wwwroot.'/lib/yui/gallery/',
186 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php?',
187 'combine' => $this->yui3loader->combine,
188 'filter' => $this->M_yui_loader->filter,
189 'ext' => false,
190 'root' => 'gallery/',
191 'patterns' => array(
192 'gallery-' => array(
193 'group' => 'gallery',
194 'configFn' => '@GALLERYCONFIGFN@',
196 'root' => 'gallery'
200 $this->add_yui2_modules(); // adds loading info for all YUI2 modules
201 $this->js_module($this->find_module('core_filepicker'));
202 $this->js_module($this->find_module('core_dock'));
204 // YUI3 init code
205 $libs = array('cssreset', 'cssbase', 'cssfonts', 'cssgrids', 'node', 'loader'); // full CSS reset + basic libs
206 foreach ($libs as $lib) {
207 $this->yui3loader->load($lib);
212 * This method adds yui2 modules into the yui3 JS loader-
213 * @return void
215 protected function add_yui2_modules() {
216 //note: this function is definitely not perfect, because
217 // it adds tons of markup into each page, but it can be
218 // abstracted into separate JS file with proper headers
219 global $CFG;
221 $GLOBALS['yui_current'] = array();
222 require($CFG->libdir.'/yui/phploader/lib/meta/config_'.$CFG->yui2version.'.php');
223 $info = $GLOBALS['yui_current'];
224 unset($GLOBALS['yui_current']);
226 if (empty($CFG->yuicomboloading)) {
227 $urlbase = $this->yui2loader->base;
228 } else {
229 $urlbase = $this->yui2loader->comboBase.$CFG->yui2version.'/build/';
232 $modules = array();
233 $ignored = array(); // list of CSS modules that are not needed
234 foreach ($info['moduleInfo'] as $name => $module) {
235 if ($module['type'] === 'css') {
236 $ignored[$name] = true;
237 } else {
238 $modules['yui2-'.$name] = $module;
241 foreach ($modules as $name=>$module) {
242 $module['fullpath'] = $urlbase.$module['path']; // fix path to point to correct location
243 unset($module['path']);
244 unset($module['skinnable']); // we load all YUI2 css automatically, this prevents weird missing css loader problems
245 foreach(array('requires', 'optional', 'supersedes') as $fixme) {
246 if (!empty($module[$fixme])) {
247 $fixed = false;
248 foreach ($module[$fixme] as $key=>$dep) {
249 if (isset($ignored[$dep])) {
250 unset($module[$fixme][$key]);
251 $fixed = true;
252 } else {
253 $module[$fixme][$key] = 'yui2-'.$dep;
256 if ($fixed) {
257 $module[$fixme] = array_merge($module[$fixme]); // fix keys
261 $this->M_yui_loader->modules[$name] = $module;
262 if (debugging('', DEBUG_DEVELOPER)) {
263 if (!array_key_exists($name, $this->debug_moduleloadstacktraces)) {
264 $this->debug_moduleloadstacktraces[$name] = array();
266 $this->debug_moduleloadstacktraces[$name][] = format_backtrace(debug_backtrace());
272 * Initialise with the bits of JavaScript that every Moodle page should have.
274 * @param moodle_page $page
275 * @param core_renderer $output
277 protected function init_requirements_data(moodle_page $page, core_renderer $renderer) {
278 global $CFG;
280 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
281 // Otherwise, in some situations, users will get warnings about insecure content
282 // on secure pages from their web browser.
284 $this->M_cfg = array(
285 'wwwroot' => $CFG->httpswwwroot, // Yes, really. See above.
286 'sesskey' => sesskey(),
287 'loadingicon' => $renderer->pix_url('i/loading_small', 'moodle')->out(false),
288 'themerev' => theme_get_revision(),
289 'theme' => $page->theme->name,
290 'jsrev' => ((empty($CFG->cachejs) or empty($CFG->jsrev)) ? -1 : $CFG->jsrev),
292 if (debugging('', DEBUG_DEVELOPER)) {
293 $this->M_cfg['developerdebug'] = true;
294 $this->yui2_lib('logger');
297 // accessibility stuff
298 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
300 // to be removed soon
301 $this->yui2_lib('dom'); // at least javascript-static.js needs to be migrated to YUI3
303 $this->string_for_js('confirmation', 'admin');
304 $this->string_for_js('cancel', 'moodle');
305 $this->string_for_js('yes', 'moodle');
307 if ($page->pagelayout === 'frametop') {
308 $this->js_init_call('M.util.init_frametop');
313 * Ensure that the specified JavaScript file is linked to from this page.
315 * NOTE: This function is to be used in rare cases only, please store your JS in module.js file
316 * and use $PAGE->requires->js_init_call() instead.
318 * By default the link is put at the end of the page, since this gives best page-load performance.
320 * Even if a particular script is requested more than once, it will only be linked
321 * to once.
323 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
324 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
325 * @param bool $inhead initialise in head
326 * @return void
328 public function js($url, $inhead=false) {
329 $url = $this->js_fix_url($url);
330 $where = $inhead ? 'head' : 'footer';
331 $this->jsincludes[$where][$url->out()] = $url;
335 * Ensure that the specified YUI2 library file, and all its required dependencies,
336 * are linked to from this page.
338 * By default the link is put at the end of the page, since this gives best page-load
339 * performance. Optional dependencies are not loaded automatically - if you want
340 * them you will need to load them first with other calls to this method.
342 * Even if a particular library is requested more than once (perhaps as a dependency
343 * of other libraries) it will only be linked to once.
345 * The library is leaded as soon as possible, if $OUTPUT->header() not used yet it
346 * is put into the page header, otherwise it is loaded in the page footer.
348 * @param string|array $libname the name of the YUI2 library you require. For example 'autocomplete'.
349 * @return void
351 public function yui2_lib($libname) {
352 $libnames = (array)$libname;
353 foreach ($libnames as $lib) {
354 $this->yui2loader->load($lib);
359 * Returns the actual url through which a script is served.
360 * @param moodle_url|string $url full moodle url, or shortened path to script
361 * @return moodle_url
363 protected function js_fix_url($url) {
364 global $CFG;
366 if ($url instanceof moodle_url) {
367 return $url;
368 } else if (strpos($url, '/') === 0) {
369 if (debugging()) {
370 // check file existence only when in debug mode
371 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
372 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
375 if (!empty($CFG->cachejs) and !empty($CFG->jsrev) and strpos($url, '/lib/editor/') !== 0 and substr($url, -3) === '.js') {
376 return new moodle_url($CFG->httpswwwroot.'/lib/javascript.php', array('file'=>$url, 'rev'=>$CFG->jsrev));
377 } else {
378 return new moodle_url($CFG->httpswwwroot.$url);
380 } else {
381 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
386 * Find out if JS module present and return details.
387 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
388 * @return array description of module or null if not found
390 protected function find_module($component) {
391 global $CFG;
393 $module = null;
396 if (strpos($component, 'core_') === 0) {
397 // must be some core stuff - list here is not complete, this is just the stuff used from multiple places
398 // so that we do nto have to repeat the definition of these modules over and over again
399 switch($component) {
400 case 'core_filepicker':
401 $module = array('name' => 'core_filepicker',
402 'fullpath' => '/repository/filepicker.js',
403 'requires' => array('base', 'node', 'node-event-simulate', 'json', 'async-queue', 'io', 'yui2-button', 'yui2-container', 'yui2-layout', 'yui2-menu', 'yui2-treeview', 'yui2-dragdrop', 'yui2-cookie'),
404 'strings' => array(array('add', 'repository'), array('back', 'repository'), array('cancel', 'moodle'), array('close', 'repository'),
405 array('cleancache', 'repository'), array('copying', 'repository'), array('date', 'repository'), array('downloadsucc', 'repository'),
406 array('emptylist', 'repository'), array('error', 'repository'), array('federatedsearch', 'repository'),
407 array('filenotnull', 'repository'), array('getfile', 'repository'), array('help', 'moodle'), array('iconview', 'repository'),
408 array('invalidjson', 'repository'), array('linkexternal', 'repository'), array('listview', 'repository'),
409 array('loading', 'repository'), array('login', 'repository'), array('logout', 'repository'), array('noenter', 'repository'),
410 array('noresult', 'repository'), array('manageurl', 'repository'), array('popup', 'repository'), array('preview', 'repository'),
411 array('refresh', 'repository'), array('save', 'repository'), array('saveas', 'repository'), array('saved', 'repository'),
412 array('saving', 'repository'), array('search', 'repository'), array('searching', 'repository'), array('size', 'repository'),
413 array('submit', 'repository'), array('sync', 'repository'), array('title', 'repository'), array('upload', 'repository'),
414 array('uploading', 'repository'), array('xhtmlerror', 'repository'),
415 array('cancel'), array('chooselicense', 'repository'), array('author', 'repository'),
416 array('ok', 'moodle'), array('error', 'moodle'), array('info', 'moodle'), array('norepositoriesavailable', 'repository'), array('norepositoriesexternalavailable', 'repository'),
417 array('nofilesattached', 'repository'), array('filepicker', 'repository'),
418 array('nofilesavailable', 'repository'), array('overwrite', 'repository'),
419 array('renameto', 'repository'), array('fileexists', 'repository'),
420 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
421 array('fileexistsdialog_filemanager', 'repository')
423 break;
424 case 'core_comment':
425 $module = array('name' => 'core_comment',
426 'fullpath' => '/comment/comment.js',
427 'requires' => array('base', 'io', 'node', 'json', 'yui2-animation', 'overlay'),
428 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
430 break;
431 case 'core_role':
432 $module = array('name' => 'core_role',
433 'fullpath' => '/admin/roles/module.js',
434 'requires' => array('node', 'cookie'));
435 break;
436 case 'core_completion':
437 $module = array('name' => 'core_completion',
438 'fullpath' => '/course/completion.js');
439 break;
440 case 'core_dock':
441 $module = array('name' => 'core_dock',
442 'fullpath' => '/blocks/dock.js',
443 'requires' => array('base', 'node', 'event-custom', 'event-mouseenter', 'event-resize'),
444 'strings' => array(array('addtodock', 'block'),array('undockitem', 'block'),array('undockall', 'block'),array('thisdirectionvertical', 'langconfig')));
445 break;
446 case 'core_message':
447 $module = array('name' => 'core_message',
448 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
449 'fullpath' => '/message/module.js');
450 break;
451 case 'core_flashdetect':
452 $module = array('name' => 'core_flashdetect',
453 'fullpath' => '/lib/flashdetect/flashdetect.js',
454 'requires' => array('io'));
455 break;
456 case 'core_group':
457 $module = array('name' => 'core_group',
458 'fullpath' => '/group/module.js',
459 'requires' => array('node', 'overlay', 'event-mouseenter'));
460 break;
461 case 'core_question_engine':
462 $module = array('name' => 'core_question_engine',
463 'fullpath' => '/question/qengine.js',
464 'requires' => array('node', 'event'));
465 break;
466 case 'core_rating':
467 $module = array('name' => 'core_rating',
468 'fullpath' => '/rating/module.js',
469 'requires' => array('node', 'event', 'overlay', 'io', 'json'));
470 break;
471 case 'core_filetree':
472 $module = array('name' => 'core_filetree',
473 'fullpath' => '/files/module.js',
474 'requires' => array('node', 'event', 'overlay', 'io', 'json', 'yui2-treeview'));
475 break;
478 } else {
479 if ($dir = get_component_directory($component)) {
480 if (file_exists("$dir/module.js")) {
481 if (strpos($dir, $CFG->dirroot.'/') === 0) {
482 $dir = substr($dir, strlen($CFG->dirroot));
483 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
489 return $module;
493 * Append YUI3 module to default YUI3 JS loader.
494 * The structure of module array is described at http://developer.yahoo.com/yui/3/yui/:
495 * @param string|array $module name of module (details are autodetected), or full module specification as array
496 * @return void
498 public function js_module($module) {
499 global $CFG;
501 if (empty($module)) {
502 throw new coding_exception('Missing YUI3 module name or full description.');
505 if (is_string($module)) {
506 $module = $this->find_module($module);
509 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
510 throw new coding_exception('Missing YUI3 module details.');
513 // Don't load this module if we already have, no need to!
514 if ($this->js_module_loaded($module['name'])) {
515 if (debugging('', DEBUG_DEVELOPER)) {
516 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
518 return;
521 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
522 // add all needed strings
523 if (!empty($module['strings'])) {
524 foreach ($module['strings'] as $string) {
525 $identifier = $string[0];
526 $component = isset($string[1]) ? $string[1] : 'moodle';
527 $a = isset($string[2]) ? $string[2] : null;
528 $this->string_for_js($identifier, $component, $a);
531 unset($module['strings']);
533 // Process module requirements and attempt to load each. This allows
534 // moodle modules to require each other.
535 if (!empty($module['requires'])){
536 foreach ($module['requires'] as $requirement) {
537 $rmodule = $this->find_module($requirement);
538 if (is_array($rmodule)) {
539 $this->js_module($rmodule);
544 if ($this->headdone) {
545 $this->extramodules[$module['name']] = $module;
546 } else {
547 $this->M_yui_loader->modules[$module['name']] = $module;
549 if (debugging('', DEBUG_DEVELOPER)) {
550 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces)) {
551 $this->debug_moduleloadstacktraces[$module['name']] = array();
553 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
558 * Returns true if the module has already been loaded.
560 * @param string|array $modulename
561 * @return bool True if the module has already been loaded
563 protected function js_module_loaded($module) {
564 if (is_string($module)) {
565 $modulename = $module;
566 } else {
567 $modulename = $module['name'];
569 return array_key_exists($modulename, $this->M_yui_loader->modules) ||
570 array_key_exists($modulename, $this->extramodules);
574 * Returns the stacktraces from loading js modules.
575 * @return array
577 public function get_loaded_modules() {
578 return $this->debug_moduleloadstacktraces;
582 * Ensure that the specified CSS file is linked to from this page.
584 * Because stylesheet links must go in the <head> part of the HTML, you must call
585 * this function before {@link get_head_code()} is called. That normally means before
586 * the call to print_header. If you call it when it is too late, an exception
587 * will be thrown.
589 * Even if a particular style sheet is requested more than once, it will only
590 * be linked to once.
592 * Please note use of this feature is strongly discouraged,
593 * it is suitable only for places where CSS is submitted directly by teachers.
594 * (Students must not be allowed to submit any external CSS because it may
595 * contain embedded javascript!). Example of correct use is mod/data.
597 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
598 * For example:
599 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
601 public function css($stylesheet) {
602 global $CFG;
604 if ($this->headdone) {
605 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
608 if ($stylesheet instanceof moodle_url) {
609 // ok
610 } else if (strpos($stylesheet, '/') === 0) {
611 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
612 } else {
613 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
616 $this->cssurls[$stylesheet->out()] = $stylesheet; // overrides
620 * Add theme stylkesheet to page - do not use from plugin code,
621 * this should be called only from the core renderer!
622 * @param moodle_url $stylesheet
623 * @return void
625 public function css_theme(moodle_url $stylesheet) {
626 $this->cssthemeurls[] = $stylesheet;
630 * Ensure that a skip link to a given target is printed at the top of the <body>.
632 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
633 * will be thrown). That normally means you must call this before the call to print_header.
635 * If you ask for a particular skip link to be printed, it is then your responsibility
636 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
637 * page, so that the skip link goes somewhere.
639 * Even if a particular skip link is requested more than once, only one copy of it will be output.
641 * @param $target the name of anchor this link should go to. For example 'maincontent'.
642 * @param $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
644 public function skip_link_to($target, $linktext) {
645 if ($this->topofbodydone) {
646 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
647 return;
649 $this->skiplinks[$target] = $linktext;
653 * !!!DEPRECATED!!! please use js_init_call() if possible
654 * Ensure that the specified JavaScript function is called from an inline script
655 * somewhere on this page.
657 * By default the call will be put in a script tag at the
658 * end of the page after initialising Y instance, since this gives best page-load
659 * performance and allows you to use YUI3 library.
661 * If you request that a particular function is called several times, then
662 * that is what will happen (unlike linking to a CSS or JS file, where only
663 * one link will be output).
665 * The main benefit of the method is the automatic encoding of all function parameters.
667 * @param string $function the name of the JavaScritp function to call. Can
668 * be a compound name like 'Y.Event.purgeElement'. Can also be
669 * used to create and object by using a 'function name' like 'new user_selector'.
670 * @param array $arguments and array of arguments to be passed to the function.
671 * When generating the function call, this will be escaped using json_encode,
672 * so passing objects and arrays should work.
673 * @param bool $ondomready
674 * @param int $delay
675 * @return void
677 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
678 $where = $ondomready ? 'ondomready' : 'normal';
679 $this->jscalls[$where][] = array($function, $arguments, $delay);
683 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
685 * @deprecated DO NOT USE
687 * @param string|array $modules One or more gallery modules to require
688 * @param string $version
689 * @param string $function
690 * @param array $arguments
691 * @param bool $ondomready
693 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
694 global $CFG;
695 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER);
696 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
700 * Creates a JavaScript function call that requires one or more modules to be loaded
702 * This function can be used to include all of the standard YUI module types within JavaScript:
703 * - YUI3 modules [node, event, io]
704 * - YUI2 modules [yui2-*]
705 * - Moodle modules [moodle-*]
706 * - Gallery modules [gallery-*]
708 * @param array|string $modules One or more modules
709 * @param string $function The function to call once modules have been loaded
710 * @param array $arguments An array of arguments to pass to the function
711 * @param string $galleryversion The gallery version to use
712 * @param bool $ondomready
714 public function yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
715 global $CFG;
717 if (!is_array($modules)) {
718 $modules = array($modules);
720 if (empty($CFG->useexternalyui) || true) {
721 // We need to set the M.yui.galleryversion to the correct version
722 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
723 } else {
724 // Set Y's config.gallery to the version
725 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
727 $jscode .= 'Y.use('.join(',', array_map('json_encode', $modules)).',function() {'.js_writer::function_call($function, $arguments).'})';
728 if ($ondomready) {
729 $jscode = "Y.on('domready', function() { $jscode });";
731 $this->jsinitcode[] = $jscode;
735 * Ensure that the specified JavaScript function is called from an inline script
736 * from page footer.
738 * @param string $function the name of the JavaScritp function to with init code,
739 * usually something like 'M.mod_mymodule.init'
740 * @param array $extraarguments and array of arguments to be passed to the function.
741 * The first argument is always the YUI3 Y instance with all required dependencies
742 * already loaded.
743 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
744 * @param array $module JS module specification array
745 * @return void
747 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
748 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
749 if (!$module) {
750 // detect module automatically
751 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
752 $module = $this->find_module($matches[1]);
756 $this->js_init_code($jscode, $ondomready, $module);
760 * Add short static javascript code fragment to page footer.
761 * This is intended primarily for loading of js modules and initialising page layout.
762 * Ideally the JS code fragment should be stored in plugin renderer so that themes
763 * may override it.
764 * @param string $jscode
765 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
766 * @param array $module JS module specification array
767 * @return void
769 public function js_init_code($jscode, $ondomready = false, array $module = null) {
770 $jscode = trim($jscode, " ;\n"). ';';
772 if ($module) {
773 $this->js_module($module);
774 $modulename = $module['name'];
775 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
778 if ($ondomready) {
779 $jscode = "Y.on('domready', function() { $jscode });";
782 $this->jsinitcode[] = $jscode;
786 * Make a language string available to JavaScript.
788 * All the strings will be available in a M.str object in the global namespace.
789 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
790 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
791 * equivalent in the current language.
793 * The arguments to this function are just like the arguments to get_string
794 * except that $component is not optional, and there are some aspects to consider
795 * when the string contains {$a} placeholder.
797 * If the string does not contain any {$a} placeholder, you can simply use
798 * M.str.component.identifier to obtain it. If you prefer, you can call
799 * M.util.get_string(identifier, component) to get the same result.
801 * If you need to use {$a} placeholders, there are two options. Either the
802 * placeholder should be substituted in PHP on server side or it should
803 * be substituted in Javascript at client side.
805 * To substitute the placeholder at server side, just provide the required
806 * value for the placeholder when you require the string. Because each string
807 * is only stored once in the JavaScript (based on $identifier and $module)
808 * you cannot get the same string with two different values of $a. If you try,
809 * an exception will be thrown. Once the placeholder is substituted, you can
810 * use M.str or M.util.get_string() as shown above:
812 * // require the string in PHP and replace the placeholder
813 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
814 * // use the result of the substitution in Javascript
815 * alert(M.str.moodle.fullnamedisplay);
817 * To substitute the placeholder at client side, use M.util.get_string()
818 * function. It implements the same logic as {@see get_string()}:
820 * // require the string in PHP but keep {$a} as it is
821 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
822 * // provide the values on the fly in Javascript
823 * user = { firstname : 'Harry', lastname : 'Potter' }
824 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
826 * If you do need the same string expanded with different $a values in PHP
827 * on server side, then the solution is to put them in your own data structure
828 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
830 * @param string $identifier the desired string.
831 * @param string $module the language file to look in.
832 * @param mixed $a any extra data to add into the string (optional).
834 public function string_for_js($identifier, $component, $a = NULL) {
835 $string = get_string($identifier, $component, $a);
836 if (!$component) {
837 throw new coding_exception('The $module parameter is required for page_requirements_manager::string_for_js.');
839 if (isset($this->stringsforjs[$component][$identifier]) && $this->stringsforjs[$component][$identifier] !== $string) {
840 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
841 "from lang file '$component'. Did you already ask for it with a different \$a? {$this->stringsforjs[$component][$identifier]} !== $string");
843 $this->stringsforjs[$component][$identifier] = $string;
847 * Make an array of language strings available for JS
849 * This function calls the above function {@link string_for_js()} for each requested
850 * string in the $identifiers array that is passed to the argument for a single module
851 * passed in $module.
853 * <code>
854 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
856 * // The above is identitical to calling
858 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
859 * $PAGE->requires->string_for_js('two', 'mymod');
860 * $PAGE->requires->string_for_js('three', 'mymod', 3);
861 * </code>
863 * @param array $identifiers An array of desired strings
864 * @param string $component The module to load for
865 * @param mixed $a This can either be a single variable that gets passed as extra
866 * information for every string or it can be an array of mixed data where the
867 * key for the data matches that of the identifier it is meant for.
870 public function strings_for_js($identifiers, $component, $a=NULL) {
871 foreach ($identifiers as $key => $identifier) {
872 if (is_array($a) && array_key_exists($key, $a)) {
873 $extra = $a[$key];
874 } else {
875 $extra = $a;
877 $this->string_for_js($identifier, $component, $extra);
882 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
884 * Make some data from PHP available to JavaScript code.
886 * For example, if you call
887 * <pre>
888 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
889 * </pre>
890 * then in JavsScript mydata.name will be 'Moodle'.
891 * @param string $variable the the name of the JavaScript variable to assign the data to.
892 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
893 * should be considered an experimental feature.
894 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
895 * so passing objects and arrays should work.
896 * @param bool $inhead initialise in head
897 * @return void
899 public function data_for_js($variable, $data, $inhead=false) {
900 $where = $inhead ? 'head' : 'footer';
901 $this->jsinitvariables[$where][] = array($variable, $data);
905 * Creates a YUI event handler.
907 * @param mixed $selector standard YUI selector for elemnts, may be array or string, element id is in the form "#idvalue"
908 * @param string $event A valid DOM event (click, mousedown, change etc.)
909 * @param string $function The name of the function to call
910 * @param array $arguments An optional array of argument parameters to pass to the function
911 * @return void
913 public function event_handler($selector, $event, $function, array $arguments = null) {
914 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
918 * Returns code needed for registering of event handlers.
919 * @return string JS code
921 protected function get_event_handler_code() {
922 $output = '';
923 foreach ($this->eventhandlers as $h) {
924 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
926 return $output;
930 * Get the inline JavaScript code that need to appear in a particular place.
931 * @return bool $ondomready
933 protected function get_javascript_code($ondomready) {
934 $where = $ondomready ? 'ondomready' : 'normal';
935 $output = '';
936 if ($this->jscalls[$where]) {
937 foreach ($this->jscalls[$where] as $data) {
938 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
940 if (!empty($ondomready)) {
941 $output = " Y.on('domready', function() {\n$output\n });";
944 return $output;
948 * Returns js code to be executed when Y is available.
949 * @return unknown_type
951 protected function get_javascript_init_code() {
952 if (count($this->jsinitcode)) {
953 return implode("\n", $this->jsinitcode) . "\n";
955 return '';
959 * Returns basic YUI3 JS loading code.
960 * YUI3 is using autoloading of both CSS and JS code.
962 * Major benefit of this compared to standard js/csss loader is much improved
963 * caching, better browser cache utilisation, much fewer http requests.
965 * @return string
967 protected function get_yui3lib_headcode() {
968 $code = $this->yui3loader->tags();
969 // unfortunately yui loader does not produce xhtml strict code, so let's fix it for now
970 $code = str_replace('&amp;', '&', $code);
971 $code = str_replace('&', '&amp;', $code);
972 return $code;
976 * Returns basic YUI2 JS loading code.
977 * It can be called manually at any time.
978 * If called manually the result needs to be output using echo().
980 * Major benefit of this compared to standard js loader is much improved
981 * caching, better browser cache utilisation, much fewer http requests.
983 * All YUI2 CSS is loaded automatically.
985 * @return string JS embedding code
987 public function get_yui2lib_code() {
988 global $CFG;
990 if ($this->headdone) {
991 $code = $this->yui2loader->script();
992 } else {
993 $code = $this->yui2loader->script();
994 if ($this->yui2loader->combine) {
995 $skinurl = $this->yui2loader->comboBase . $CFG->yui2version . '/build/assets/skins/sam/skin.css';
996 } else {
997 $skinurl = $this->yui2loader->base . 'assets/skins/sam/skin.css';
999 // please note this is a temporary hack until we fully migrate to later YUI3 that has all the widgets
1000 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css', 'href'=>$skinurl);
1001 $code .= "\n" . html_writer::empty_tag('link', $attributes) . "\n";
1003 $code = str_replace('&amp;', '&', $code);
1004 $code = str_replace('&', '&amp;', $code);
1005 return $code;
1009 * Returns html tags needed for inclusion of theme CSS
1010 * @return string
1012 protected function get_css_code() {
1013 // First of all the theme CSS, then any custom CSS
1014 // Please note custom CSS is strongly discouraged,
1015 // because it can not be overridden by themes!
1016 // It is suitable only for things like mod/data which accepts CSS from teachers.
1017 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1019 // This line of code may look funny but it is currently required in order
1020 // to avoid MASSIVE display issues in Internet Explorer.
1021 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1022 // ignored whenever another resource is added until such time as a redraw
1023 // is forced, usually by moving the mouse over the affected element.
1024 $code = html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1026 $urls = $this->cssthemeurls + $this->cssurls;
1027 foreach ($urls as $url) {
1028 $attributes['href'] = $url;
1029 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1030 // this id is needed in first sheet only so that theme may override YUI sheets laoded on the fly
1031 unset($attributes['id']);
1034 return $code;
1038 * Adds extra modules specified after printing of page header
1040 protected function get_extra_modules_code() {
1041 if (empty($this->extramodules)) {
1042 return '';
1044 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1048 * Generate any HTML that needs to go inside the <head> tag.
1050 * Normally, this method is called automatically by the code that prints the
1051 * <head> tag. You should not normally need to call it in your own code.
1053 * @return string the HTML code to to inside the <head> tag.
1055 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1056 global $CFG;
1058 // note: the $page and $output are not stored here because it would
1059 // create circular references in memory which prevents garbage collection
1060 $this->init_requirements_data($page, $renderer);
1062 // yui3 JS and CSS is always loaded first - it is cached in browser
1063 $output = $this->get_yui3lib_headcode();
1065 // BC: load basic YUI2 for now, all yui2 things should be loaded via Y.use('yui2-oldmodulename')
1066 $output .= $this->get_yui2lib_code();
1068 // now theme CSS + custom CSS in this specific order
1069 $output .= $this->get_css_code();
1071 // set up global YUI3 loader object - this should contain all code needed by plugins
1072 // note: in JavaScript just use "YUI(M.yui.loader).use('overlay', function(Y) { .... });"
1073 // this needs to be done before including any other script
1074 $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";
1075 $js .= js_writer::set_variable('M.yui.loader', $this->M_yui_loader, false) . "\n";
1076 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1077 $js = str_replace('"@GALLERYCONFIGFN@"', 'galleryConfigFn', $js);
1078 $js = str_replace('"@MOODLECONFIGFN@"', 'moodleConfigFn', $js);
1080 $output .= html_writer::script($js);
1082 // link our main JS file, all core stuff should be there
1083 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1085 // add variables
1086 if ($this->jsinitvariables['head']) {
1087 $js = '';
1088 foreach ($this->jsinitvariables['head'] as $data) {
1089 list($var, $value) = $data;
1090 $js .= js_writer::set_variable($var, $value, true);
1092 $output .= html_writer::script($js);
1095 // all the other linked things from HEAD - there should be as few as possible
1096 if ($this->jsincludes['head']) {
1097 foreach ($this->jsincludes['head'] as $url) {
1098 $output .= html_writer::script('', $url);
1102 // mark head sending done, it is not possible to anything there
1103 $this->headdone = true;
1105 return $output;
1109 * Generate any HTML that needs to go at the start of the <body> tag.
1111 * Normally, this method is called automatically by the code that prints the
1112 * <head> tag. You should not normally need to call it in your own code.
1114 * @return string the HTML code to go at the start of the <body> tag.
1116 public function get_top_of_body_code() {
1117 // first the skip links
1118 $links = '';
1119 $attributes = array('class'=>'skip');
1120 foreach ($this->skiplinks as $url => $text) {
1121 $attributes['href'] = '#' . $url;
1122 $links .= html_writer::tag('a', $text, $attributes);
1124 $output = html_writer::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1126 // then the clever trick for hiding of things not needed when JS works
1127 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1128 $this->topofbodydone = true;
1129 return $output;
1133 * Generate any HTML that needs to go at the end of the page.
1135 * Normally, this method is called automatically by the code that prints the
1136 * page footer. You should not normally need to call it in your own code.
1138 * @return string the HTML code to to at the end of the page.
1140 public function get_end_code() {
1141 global $CFG;
1142 // add other requested modules
1143 $output = $this->get_extra_modules_code();
1145 // add missing YUI2 YUI - to be removed once we convert everything to YUI3!
1146 $output .= $this->get_yui2lib_code();
1148 // all the other linked scripts - there should be as few as possible
1149 if ($this->jsincludes['footer']) {
1150 foreach ($this->jsincludes['footer'] as $url) {
1151 $output .= html_writer::script('', $url);
1155 // add all needed strings
1156 if (!empty($this->stringsforjs)) {
1157 $output .= html_writer::script(js_writer::set_variable('M.str', $this->stringsforjs));
1160 // add variables
1161 if ($this->jsinitvariables['footer']) {
1162 $js = '';
1163 foreach ($this->jsinitvariables['footer'] as $data) {
1164 list($var, $value) = $data;
1165 $js .= js_writer::set_variable($var, $value, true);
1167 $output .= html_writer::script($js);
1170 $inyuijs = $this->get_javascript_code(false);
1171 $ondomreadyjs = $this->get_javascript_code(true);
1172 $jsinit = $this->get_javascript_init_code();
1173 $handlersjs = $this->get_event_handler_code();
1175 // there is no global Y, make sure it is available in your scope
1176 $js = "YUI(M.yui.loader).use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1178 $output .= html_writer::script($js);
1180 return $output;
1184 * @return boolean Have we already output the code in the <head> tag?
1186 public function is_head_done() {
1187 return $this->headdone;
1191 * @return boolean Have we already output the code at the start of the <body> tag?
1193 public function is_top_of_body_done() {
1194 return $this->topofbodydone;
1199 * Invalidate all server and client side JS caches.
1200 * @return void
1202 function js_reset_all_caches() {
1203 global $CFG;
1204 require_once("$CFG->libdir/filelib.php");
1206 set_config('jsrev', empty($CFG->jsrev) ? 1 : $CFG->jsrev+1);
1207 fulldelete("$CFG->dataroot/cache/js");