MDL-27541 course reports - allow teachers to view individual reports
[moodle.git] / lib / outputrequirementslib.php
blob70f05e40df58be16b349013967c25bb66a01cf63
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 'fullpath' => '/message/module.js');
449 break;
450 case 'core_flashdetect':
451 $module = array('name' => 'core_flashdetect',
452 'fullpath' => '/lib/flashdetect/flashdetect.js',
453 'requires' => array('io'));
454 break;
455 case 'core_group':
456 $module = array('name' => 'core_group',
457 'fullpath' => '/group/module.js',
458 'requires' => array('node', 'overlay', 'event-mouseenter'));
459 break;
460 case 'core_question_engine':
461 $module = array('name' => 'core_question_engine',
462 'fullpath' => '/question/qengine.js',
463 'requires' => array('node', 'event'));
464 break;
465 case 'core_rating':
466 $module = array('name' => 'core_rating',
467 'fullpath' => '/rating/module.js',
468 'requires' => array('node', 'event', 'overlay', 'io', 'json'));
469 break;
470 case 'core_filetree':
471 $module = array('name' => 'core_filetree',
472 'fullpath' => '/files/module.js',
473 'requires' => array('node', 'event', 'overlay', 'io', 'json', 'yui2-treeview'));
474 break;
477 } else {
478 if ($dir = get_component_directory($component)) {
479 if (file_exists("$dir/module.js")) {
480 if (strpos($dir, $CFG->dirroot.'/') === 0) {
481 $dir = substr($dir, strlen($CFG->dirroot));
482 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
488 return $module;
492 * Append YUI3 module to default YUI3 JS loader.
493 * The structure of module array is described at http://developer.yahoo.com/yui/3/yui/:
494 * @param string|array $module name of module (details are autodetected), or full module specification as array
495 * @return void
497 public function js_module($module) {
498 global $CFG;
500 if (empty($module)) {
501 throw new coding_exception('Missing YUI3 module name or full description.');
504 if (is_string($module)) {
505 $module = $this->find_module($module);
508 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
509 throw new coding_exception('Missing YUI3 module details.');
512 // Don't load this module if we already have, no need to!
513 if ($this->js_module_loaded($module['name'])) {
514 if (debugging('', DEBUG_DEVELOPER)) {
515 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
517 return;
520 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
521 // add all needed strings
522 if (!empty($module['strings'])) {
523 foreach ($module['strings'] as $string) {
524 $identifier = $string[0];
525 $component = isset($string[1]) ? $string[1] : 'moodle';
526 $a = isset($string[2]) ? $string[2] : null;
527 $this->string_for_js($identifier, $component, $a);
530 unset($module['strings']);
532 // Process module requirements and attempt to load each. This allows
533 // moodle modules to require each other.
534 if (!empty($module['requires'])){
535 foreach ($module['requires'] as $requirement) {
536 $rmodule = $this->find_module($requirement);
537 if (is_array($rmodule)) {
538 $this->js_module($rmodule);
543 if ($this->headdone) {
544 $this->extramodules[$module['name']] = $module;
545 } else {
546 $this->M_yui_loader->modules[$module['name']] = $module;
548 if (debugging('', DEBUG_DEVELOPER)) {
549 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces)) {
550 $this->debug_moduleloadstacktraces[$module['name']] = array();
552 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
557 * Returns true if the module has already been loaded.
559 * @param string|array $modulename
560 * @return bool True if the module has already been loaded
562 protected function js_module_loaded($module) {
563 if (is_string($module)) {
564 $modulename = $module;
565 } else {
566 $modulename = $module['name'];
568 return array_key_exists($modulename, $this->M_yui_loader->modules) ||
569 array_key_exists($modulename, $this->extramodules);
573 * Returns the stacktraces from loading js modules.
574 * @return array
576 public function get_loaded_modules() {
577 return $this->debug_moduleloadstacktraces;
581 * Ensure that the specified CSS file is linked to from this page.
583 * Because stylesheet links must go in the <head> part of the HTML, you must call
584 * this function before {@link get_head_code()} is called. That normally means before
585 * the call to print_header. If you call it when it is too late, an exception
586 * will be thrown.
588 * Even if a particular style sheet is requested more than once, it will only
589 * be linked to once.
591 * Please note use of this feature is strongly discouraged,
592 * it is suitable only for places where CSS is submitted directly by teachers.
593 * (Students must not be allowed to submit any external CSS because it may
594 * contain embedded javascript!). Example of correct use is mod/data.
596 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
597 * For example:
598 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
600 public function css($stylesheet) {
601 global $CFG;
603 if ($this->headdone) {
604 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
607 if ($stylesheet instanceof moodle_url) {
608 // ok
609 } else if (strpos($stylesheet, '/') === 0) {
610 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
611 } else {
612 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
615 $this->cssurls[$stylesheet->out()] = $stylesheet; // overrides
619 * Add theme stylkesheet to page - do not use from plugin code,
620 * this should be called only from the core renderer!
621 * @param moodle_url $stylesheet
622 * @return void
624 public function css_theme(moodle_url $stylesheet) {
625 $this->cssthemeurls[] = $stylesheet;
629 * Ensure that a skip link to a given target is printed at the top of the <body>.
631 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
632 * will be thrown). That normally means you must call this before the call to print_header.
634 * If you ask for a particular skip link to be printed, it is then your responsibility
635 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
636 * page, so that the skip link goes somewhere.
638 * Even if a particular skip link is requested more than once, only one copy of it will be output.
640 * @param $target the name of anchor this link should go to. For example 'maincontent'.
641 * @param $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
643 public function skip_link_to($target, $linktext) {
644 if ($this->topofbodydone) {
645 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
646 return;
648 $this->skiplinks[$target] = $linktext;
652 * !!!DEPRECATED!!! please use js_init_call() if possible
653 * Ensure that the specified JavaScript function is called from an inline script
654 * somewhere on this page.
656 * By default the call will be put in a script tag at the
657 * end of the page after initialising Y instance, since this gives best page-load
658 * performance and allows you to use YUI3 library.
660 * If you request that a particular function is called several times, then
661 * that is what will happen (unlike linking to a CSS or JS file, where only
662 * one link will be output).
664 * The main benefit of the method is the automatic encoding of all function parameters.
666 * @param string $function the name of the JavaScritp function to call. Can
667 * be a compound name like 'Y.Event.purgeElement'. Can also be
668 * used to create and object by using a 'function name' like 'new user_selector'.
669 * @param array $arguments and array of arguments to be passed to the function.
670 * When generating the function call, this will be escaped using json_encode,
671 * so passing objects and arrays should work.
672 * @param bool $ondomready
673 * @param int $delay
674 * @return void
676 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
677 $where = $ondomready ? 'ondomready' : 'normal';
678 $this->jscalls[$where][] = array($function, $arguments, $delay);
682 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
684 * @deprecated DO NOT USE
686 * @param string|array $modules One or more gallery modules to require
687 * @param string $version
688 * @param string $function
689 * @param array $arguments
690 * @param bool $ondomready
692 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
693 global $CFG;
694 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER);
695 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
699 * Creates a JavaScript function call that requires one or more modules to be loaded
701 * This function can be used to include all of the standard YUI module types within JavaScript:
702 * - YUI3 modules [node, event, io]
703 * - YUI2 modules [yui2-*]
704 * - Moodle modules [moodle-*]
705 * - Gallery modules [gallery-*]
707 * @param array|string $modules One or more modules
708 * @param string $function The function to call once modules have been loaded
709 * @param array $arguments An array of arguments to pass to the function
710 * @param string $galleryversion The gallery version to use
711 * @param bool $ondomready
713 public function yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
714 global $CFG;
716 if (!is_array($modules)) {
717 $modules = array($modules);
719 if (empty($CFG->useexternalyui) || true) {
720 // We need to set the M.yui.galleryversion to the correct version
721 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
722 } else {
723 // Set Y's config.gallery to the version
724 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
726 $jscode .= 'Y.use('.join(',', array_map('json_encode', $modules)).',function() {'.js_writer::function_call($function, $arguments).'})';
727 if ($ondomready) {
728 $jscode = "Y.on('domready', function() { $jscode });";
730 $this->jsinitcode[] = $jscode;
734 * Ensure that the specified JavaScript function is called from an inline script
735 * from page footer.
737 * @param string $function the name of the JavaScritp function to with init code,
738 * usually something like 'M.mod_mymodule.init'
739 * @param array $extraarguments and array of arguments to be passed to the function.
740 * The first argument is always the YUI3 Y instance with all required dependencies
741 * already loaded.
742 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
743 * @param array $module JS module specification array
744 * @return void
746 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
747 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
748 if (!$module) {
749 // detect module automatically
750 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
751 $module = $this->find_module($matches[1]);
755 $this->js_init_code($jscode, $ondomready, $module);
759 * Add short static javascript code fragment to page footer.
760 * This is intended primarily for loading of js modules and initialising page layout.
761 * Ideally the JS code fragment should be stored in plugin renderer so that themes
762 * may override it.
763 * @param string $jscode
764 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
765 * @param array $module JS module specification array
766 * @return void
768 public function js_init_code($jscode, $ondomready = false, array $module = null) {
769 $jscode = trim($jscode, " ;\n"). ';';
771 if ($module) {
772 $this->js_module($module);
773 $modulename = $module['name'];
774 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
777 if ($ondomready) {
778 $jscode = "Y.on('domready', function() { $jscode });";
781 $this->jsinitcode[] = $jscode;
785 * Make a language string available to JavaScript.
787 * All the strings will be available in a M.str object in the global namespace.
788 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
789 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
790 * equivalent in the current language.
792 * The arguments to this function are just like the arguments to get_string
793 * except that $component is not optional, and there are some aspects to consider
794 * when the string contains {$a} placeholder.
796 * If the string does not contain any {$a} placeholder, you can simply use
797 * M.str.component.identifier to obtain it. If you prefer, you can call
798 * M.util.get_string(identifier, component) to get the same result.
800 * If you need to use {$a} placeholders, there are two options. Either the
801 * placeholder should be substituted in PHP on server side or it should
802 * be substituted in Javascript at client side.
804 * To substitute the placeholder at server side, just provide the required
805 * value for the placeholder when you require the string. Because each string
806 * is only stored once in the JavaScript (based on $identifier and $module)
807 * you cannot get the same string with two different values of $a. If you try,
808 * an exception will be thrown. Once the placeholder is substituted, you can
809 * use M.str or M.util.get_string() as shown above:
811 * // require the string in PHP and replace the placeholder
812 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
813 * // use the result of the substitution in Javascript
814 * alert(M.str.moodle.fullnamedisplay);
816 * To substitute the placeholder at client side, use M.util.get_string()
817 * function. It implements the same logic as {@see get_string()}:
819 * // require the string in PHP but keep {$a} as it is
820 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
821 * // provide the values on the fly in Javascript
822 * user = { firstname : 'Harry', lastname : 'Potter' }
823 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
825 * If you do need the same string expanded with different $a values in PHP
826 * on server side, then the solution is to put them in your own data structure
827 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
829 * @param string $identifier the desired string.
830 * @param string $module the language file to look in.
831 * @param mixed $a any extra data to add into the string (optional).
833 public function string_for_js($identifier, $component, $a = NULL) {
834 $string = get_string($identifier, $component, $a);
835 if (!$component) {
836 throw new coding_exception('The $module parameter is required for page_requirements_manager::string_for_js.');
838 if (isset($this->stringsforjs[$component][$identifier]) && $this->stringsforjs[$component][$identifier] !== $string) {
839 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
840 "from lang file '$component'. Did you already ask for it with a different \$a? {$this->stringsforjs[$component][$identifier]} !== $string");
842 $this->stringsforjs[$component][$identifier] = $string;
846 * Make an array of language strings available for JS
848 * This function calls the above function {@link string_for_js()} for each requested
849 * string in the $identifiers array that is passed to the argument for a single module
850 * passed in $module.
852 * <code>
853 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
855 * // The above is identitical to calling
857 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
858 * $PAGE->requires->string_for_js('two', 'mymod');
859 * $PAGE->requires->string_for_js('three', 'mymod', 3);
860 * </code>
862 * @param array $identifiers An array of desired strings
863 * @param string $component The module to load for
864 * @param mixed $a This can either be a single variable that gets passed as extra
865 * information for every string or it can be an array of mixed data where the
866 * key for the data matches that of the identifier it is meant for.
869 public function strings_for_js($identifiers, $component, $a=NULL) {
870 foreach ($identifiers as $key => $identifier) {
871 if (is_array($a) && array_key_exists($key, $a)) {
872 $extra = $a[$key];
873 } else {
874 $extra = $a;
876 $this->string_for_js($identifier, $component, $extra);
881 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
883 * Make some data from PHP available to JavaScript code.
885 * For example, if you call
886 * <pre>
887 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
888 * </pre>
889 * then in JavsScript mydata.name will be 'Moodle'.
890 * @param string $variable the the name of the JavaScript variable to assign the data to.
891 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
892 * should be considered an experimental feature.
893 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
894 * so passing objects and arrays should work.
895 * @param bool $inhead initialise in head
896 * @return void
898 public function data_for_js($variable, $data, $inhead=false) {
899 $where = $inhead ? 'head' : 'footer';
900 $this->jsinitvariables[$where][] = array($variable, $data);
904 * Creates a YUI event handler.
906 * @param mixed $selector standard YUI selector for elemnts, may be array or string, element id is in the form "#idvalue"
907 * @param string $event A valid DOM event (click, mousedown, change etc.)
908 * @param string $function The name of the function to call
909 * @param array $arguments An optional array of argument parameters to pass to the function
910 * @return void
912 public function event_handler($selector, $event, $function, array $arguments = null) {
913 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
917 * Returns code needed for registering of event handlers.
918 * @return string JS code
920 protected function get_event_handler_code() {
921 $output = '';
922 foreach ($this->eventhandlers as $h) {
923 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
925 return $output;
929 * Get the inline JavaScript code that need to appear in a particular place.
930 * @return bool $ondomready
932 protected function get_javascript_code($ondomready) {
933 $where = $ondomready ? 'ondomready' : 'normal';
934 $output = '';
935 if ($this->jscalls[$where]) {
936 foreach ($this->jscalls[$where] as $data) {
937 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
939 if (!empty($ondomready)) {
940 $output = " Y.on('domready', function() {\n$output\n });";
943 return $output;
947 * Returns js code to be executed when Y is available.
948 * @return unknown_type
950 protected function get_javascript_init_code() {
951 if (count($this->jsinitcode)) {
952 return implode("\n", $this->jsinitcode) . "\n";
954 return '';
958 * Returns basic YUI3 JS loading code.
959 * YUI3 is using autoloading of both CSS and JS code.
961 * Major benefit of this compared to standard js/csss loader is much improved
962 * caching, better browser cache utilisation, much fewer http requests.
964 * @return string
966 protected function get_yui3lib_headcode() {
967 $code = $this->yui3loader->tags();
968 // unfortunately yui loader does not produce xhtml strict code, so let's fix it for now
969 $code = str_replace('&amp;', '&', $code);
970 $code = str_replace('&', '&amp;', $code);
971 return $code;
975 * Returns basic YUI2 JS loading code.
976 * It can be called manually at any time.
977 * If called manually the result needs to be output using echo().
979 * Major benefit of this compared to standard js loader is much improved
980 * caching, better browser cache utilisation, much fewer http requests.
982 * All YUI2 CSS is loaded automatically.
984 * @return string JS embedding code
986 public function get_yui2lib_code() {
987 global $CFG;
989 if ($this->headdone) {
990 $code = $this->yui2loader->script();
991 } else {
992 $code = $this->yui2loader->script();
993 if ($this->yui2loader->combine) {
994 $skinurl = $this->yui2loader->comboBase . $CFG->yui2version . '/build/assets/skins/sam/skin.css';
995 } else {
996 $skinurl = $this->yui2loader->base . 'assets/skins/sam/skin.css';
998 // please note this is a temporary hack until we fully migrate to later YUI3 that has all the widgets
999 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css', 'href'=>$skinurl);
1000 $code .= "\n" . html_writer::empty_tag('link', $attributes) . "\n";
1002 $code = str_replace('&amp;', '&', $code);
1003 $code = str_replace('&', '&amp;', $code);
1004 return $code;
1008 * Returns html tags needed for inclusion of theme CSS
1009 * @return string
1011 protected function get_css_code() {
1012 // First of all the theme CSS, then any custom CSS
1013 // Please note custom CSS is strongly discouraged,
1014 // because it can not be overridden by themes!
1015 // It is suitable only for things like mod/data which accepts CSS from teachers.
1016 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1018 // This line of code may look funny but it is currently required in order
1019 // to avoid MASSIVE display issues in Internet Explorer.
1020 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1021 // ignored whenever another resource is added until such time as a redraw
1022 // is forced, usually by moving the mouse over the affected element.
1023 $code = html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1025 $urls = $this->cssthemeurls + $this->cssurls;
1026 foreach ($urls as $url) {
1027 $attributes['href'] = $url;
1028 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1029 // this id is needed in first sheet only so that theme may override YUI sheets laoded on the fly
1030 unset($attributes['id']);
1033 return $code;
1037 * Adds extra modules specified after printing of page header
1039 protected function get_extra_modules_code() {
1040 if (empty($this->extramodules)) {
1041 return '';
1043 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1047 * Generate any HTML that needs to go inside the <head> tag.
1049 * Normally, this method is called automatically by the code that prints the
1050 * <head> tag. You should not normally need to call it in your own code.
1052 * @return string the HTML code to to inside the <head> tag.
1054 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1055 global $CFG;
1057 // note: the $page and $output are not stored here because it would
1058 // create circular references in memory which prevents garbage collection
1059 $this->init_requirements_data($page, $renderer);
1061 // yui3 JS and CSS is always loaded first - it is cached in browser
1062 $output = $this->get_yui3lib_headcode();
1064 // BC: load basic YUI2 for now, all yui2 things should be loaded via Y.use('yui2-oldmodulename')
1065 $output .= $this->get_yui2lib_code();
1067 // now theme CSS + custom CSS in this specific order
1068 $output .= $this->get_css_code();
1070 // set up global YUI3 loader object - this should contain all code needed by plugins
1071 // note: in JavaScript just use "YUI(M.yui.loader).use('overlay', function(Y) { .... });"
1072 // this needs to be done before including any other script
1073 $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";
1074 $js .= js_writer::set_variable('M.yui.loader', $this->M_yui_loader, false) . "\n";
1075 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1076 $js = str_replace('"@GALLERYCONFIGFN@"', 'galleryConfigFn', $js);
1077 $js = str_replace('"@MOODLECONFIGFN@"', 'moodleConfigFn', $js);
1079 $output .= html_writer::script($js);
1081 // link our main JS file, all core stuff should be there
1082 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1084 // add variables
1085 if ($this->jsinitvariables['head']) {
1086 $js = '';
1087 foreach ($this->jsinitvariables['head'] as $data) {
1088 list($var, $value) = $data;
1089 $js .= js_writer::set_variable($var, $value, true);
1091 $output .= html_writer::script($js);
1094 // all the other linked things from HEAD - there should be as few as possible
1095 if ($this->jsincludes['head']) {
1096 foreach ($this->jsincludes['head'] as $url) {
1097 $output .= html_writer::script('', $url);
1101 // mark head sending done, it is not possible to anything there
1102 $this->headdone = true;
1104 return $output;
1108 * Generate any HTML that needs to go at the start of the <body> tag.
1110 * Normally, this method is called automatically by the code that prints the
1111 * <head> tag. You should not normally need to call it in your own code.
1113 * @return string the HTML code to go at the start of the <body> tag.
1115 public function get_top_of_body_code() {
1116 // first the skip links
1117 $links = '';
1118 $attributes = array('class'=>'skip');
1119 foreach ($this->skiplinks as $url => $text) {
1120 $attributes['href'] = '#' . $url;
1121 $links .= html_writer::tag('a', $text, $attributes);
1123 $output = html_writer::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1125 // then the clever trick for hiding of things not needed when JS works
1126 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1127 $this->topofbodydone = true;
1128 return $output;
1132 * Generate any HTML that needs to go at the end of the page.
1134 * Normally, this method is called automatically by the code that prints the
1135 * page footer. You should not normally need to call it in your own code.
1137 * @return string the HTML code to to at the end of the page.
1139 public function get_end_code() {
1140 global $CFG;
1141 // add other requested modules
1142 $output = $this->get_extra_modules_code();
1144 // add missing YUI2 YUI - to be removed once we convert everything to YUI3!
1145 $output .= $this->get_yui2lib_code();
1147 // all the other linked scripts - there should be as few as possible
1148 if ($this->jsincludes['footer']) {
1149 foreach ($this->jsincludes['footer'] as $url) {
1150 $output .= html_writer::script('', $url);
1154 // add all needed strings
1155 if (!empty($this->stringsforjs)) {
1156 $output .= html_writer::script(js_writer::set_variable('M.str', $this->stringsforjs));
1159 // add variables
1160 if ($this->jsinitvariables['footer']) {
1161 $js = '';
1162 foreach ($this->jsinitvariables['footer'] as $data) {
1163 list($var, $value) = $data;
1164 $js .= js_writer::set_variable($var, $value, true);
1166 $output .= html_writer::script($js);
1169 $inyuijs = $this->get_javascript_code(false);
1170 $ondomreadyjs = $this->get_javascript_code(true);
1171 $jsinit = $this->get_javascript_init_code();
1172 $handlersjs = $this->get_event_handler_code();
1174 // there is no global Y, make sure it is available in your scope
1175 $js = "YUI(M.yui.loader).use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1177 $output .= html_writer::script($js);
1179 return $output;
1183 * @return boolean Have we already output the code in the <head> tag?
1185 public function is_head_done() {
1186 return $this->headdone;
1190 * @return boolean Have we already output the code at the start of the <body> tag?
1192 public function is_top_of_body_done() {
1193 return $this->topofbodydone;
1198 * Invalidate all server and client side JS caches.
1199 * @return void
1201 function js_reset_all_caches() {
1202 global $CFG;
1203 require_once("$CFG->libdir/filelib.php");
1205 set_config('jsrev', empty($CFG->jsrev) ? 1 : $CFG->jsrev+1);
1206 fulldelete("$CFG->dataroot/cache/js");