MDL-25474 do not try to use caching for dynamic JS - it can not work
[moodle.git] / lib / outputrequirementslib.php
CommitLineData
0bb38e8c
PS
1<?php
2
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.
14//
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/>.
17
18
19/**
20 * Library functions to facilitate the use of JavaScript in Moodle.
21 *
78bfb562
PS
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
0bb38e8c
PS
26 */
27
78bfb562
PS
28defined('MOODLE_INTERNAL') || die();
29
0bb38e8c
PS
30// note: you can find history of this file in lib/ajax/ajaxlib.php
31
32/**
33 * This class tracks all the things that are needed by the current page.
34 *
35 * Normally, the only instance of this class you will need to work with is the
36 * one accessible via $PAGE->requires.
37 *
173ba4f1 38 * Typical usage would be
0bb38e8c
PS
39 * <pre>
40 * $PAGE->requires->init_js_call('M.mod_forum.init_view');
41 * </pre>
42 *
43 * It also supports obsoleted coding style withouth YUI3 modules.
44 * <pre>
173ba4f1 45 * $PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overridable via themes!
0bb38e8c
PS
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>
50 *
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.
54 *
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
58 */
59class 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
71 */
72 protected $skiplinks = array();
73 /**
173ba4f1 74 * Javascript code used for initialisation of page, it should be relatively small
0bb38e8c
PS
75 * @var array
76 */
77 protected $jsinitcode = array();
78 /**
79 * Theme sheets, initialised only from core_renderer
80 * @var array of moodle_url
81 */
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
87 */
88 protected $cssurls = array();
89 /**
90 * List of requested event handlers
91 * @var array
92 */
93 protected $eventhandlers = array();
94 /**
95 * Extra modules
96 * @var array
97 */
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;
103
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;
d067fc47
SH
112 /** stores debug backtraces from when JS modules were included in the page */
113 protected $debug_moduleloadstacktraces = array();
0bb38e8c
PS
114
115 /**
116 * Page requirements constructor.
117 */
118 public function __construct() {
119 global $CFG;
120
121 require_once("$CFG->libdir/yui/phploader/phploader/loader.php");
122
123 $this->yui3loader = new YAHOO_util_Loader($CFG->yui3version);
124 $this->yui2loader = new YAHOO_util_Loader($CFG->yui2version);
125
126 // set up some loader options
127 if (debugging('', DEBUG_DEVELOPER)) {
573e7e33
DC
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
0bb38e8c
PS
130 } else {
131 $this->yui3loader->filter = null;
132 $this->yui2loader->filter = null;
133 }
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?';
144 }
145
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);
149
77387297
SH
150 if (empty($CFG->cachejs)) {
151 $jsrev = -1;
152 } else if (empty($CFG->jsrev)) {
153 $jsrev = 1;
154 } else {
155 $jsrev = $CFG->jsrev;
156 }
f312e878 157
0bb38e8c
PS
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();
2b722f87
SH
166 $this->M_yui_loader->groups = array(
167 'moodle' => array(
168 'name' => 'moodle',
77387297 169 'base' => $CFG->httpswwwroot . '/theme/yui_combo.php?moodle/'.$jsrev.'/',
2b722f87
SH
170 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php?',
171 'combine' => $this->yui3loader->combine,
172 'filter' => '',
173 'ext' => false,
77387297 174 'root' => 'moodle/'.$jsrev.'/', // Add the rev to the root path so that we can control caching
2b722f87
SH
175 'patterns' => array(
176 'moodle-' => array(
177 'group' => 'moodle',
178 'configFn' => '@MOODLECONFIGFN@'
2a102b90 179 ),
2b722f87 180 'root' => 'moodle'
2a102b90 181 )
2b722f87
SH
182 ),
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@',
195 ),
196 'root' => 'gallery'
197 )
198 )
199 );
0bb38e8c
PS
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'));
203
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);
208 }
209 }
210
211 /**
212 * This method adds yui2 modules into the yui3 JS loader-
213 * @return void
214 */
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;
220
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']);
225
226 if (empty($CFG->yuicomboloading)) {
227 $urlbase = $this->yui2loader->base;
228 } else {
229 $urlbase = $this->yui2loader->comboBase.$CFG->yui2version.'/build/';
230 }
231
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;
239 }
240 }
241 foreach ($modules as $name=>$module) {
242 $module['fullpath'] = $urlbase.$module['path']; // fix path to point to correct location
243 unset($module['path']);
0139ec3f 244 unset($module['skinnable']); // we load all YUI2 css automatically, this prevents weird missing css loader problems
0bb38e8c
PS
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;
254 }
255 }
256 if ($fixed) {
257 $module[$fixme] = array_merge($module[$fixme]); // fix keys
258 }
259 }
260 }
261 $this->M_yui_loader->modules[$name] = $module;
d067fc47
SH
262 if (debugging('', DEBUG_DEVELOPER)) {
263 if (!array_key_exists($name, $this->debug_moduleloadstacktraces)) {
264 $this->debug_moduleloadstacktraces[$name] = array();
265 }
266 $this->debug_moduleloadstacktraces[$name][] = format_backtrace(debug_backtrace());
267 }
0bb38e8c
PS
268 }
269 }
270
271 /**
272 * Initialise with the bits of JavaScript that every Moodle page should have.
273 *
274 * @param moodle_page $page
275 * @param core_renderer $output
276 */
277 protected function init_requirements_data(moodle_page $page, core_renderer $renderer) {
278 global $CFG;
279
280 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
281 // Otherwise, in some situations, users will get warnings about insecure content
4aea3cc7 282 // on secure pages from their web browser.
0bb38e8c
PS
283
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 );
291 if (debugging('', DEBUG_DEVELOPER)) {
292 $this->M_cfg['developerdebug'] = true;
293 $this->yui2_lib('logger');
294 }
295
296 // accessibility stuff
2cf81209 297 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
0bb38e8c
PS
298
299 // to be removed soon
300 $this->yui2_lib('dom'); // at least javascript-static.js needs to be migrated to YUI3
301
302 $this->string_for_js('confirmation', 'admin');
303 $this->string_for_js('cancel', 'moodle');
304 $this->string_for_js('yes', 'moodle');
879b4f9a 305
4aea3cc7
PS
306 if ($page->pagelayout === 'frametop') {
307 $this->js_init_call('M.util.init_frametop');
308 }
0bb38e8c
PS
309 }
310
311 /**
312 * Ensure that the specified JavaScript file is linked to from this page.
313 *
314 * NOTE: This function is to be used in rare cases only, please store your JS in module.js file
315 * and use $PAGE->requires->js_init_call() instead.
316 *
317 * By default the link is put at the end of the page, since this gives best page-load performance.
318 *
319 * Even if a particular script is requested more than once, it will only be linked
320 * to once.
321 *
322 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
323 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
324 * @param bool $inhead initialise in head
325 * @return void
326 */
327 public function js($url, $inhead=false) {
328 $url = $this->js_fix_url($url);
329 $where = $inhead ? 'head' : 'footer';
330 $this->jsincludes[$where][$url->out()] = $url;
331 }
332
333 /**
173ba4f1 334 * Ensure that the specified YUI2 library file, and all its required dependencies,
0bb38e8c
PS
335 * are linked to from this page.
336 *
337 * By default the link is put at the end of the page, since this gives best page-load
338 * performance. Optional dependencies are not loaded automatically - if you want
339 * them you will need to load them first with other calls to this method.
340 *
173ba4f1 341 * Even if a particular library is requested more than once (perhaps as a dependency
0bb38e8c
PS
342 * of other libraries) it will only be linked to once.
343 *
344 * The library is leaded as soon as possible, if $OUTPUT->header() not used yet it
345 * is put into the page header, otherwise it is loaded in the page footer.
346 *
347 * @param string|array $libname the name of the YUI2 library you require. For example 'autocomplete'.
348 * @return void
349 */
350 public function yui2_lib($libname) {
351 $libnames = (array)$libname;
352 foreach ($libnames as $lib) {
353 $this->yui2loader->load($lib);
354 }
355 }
356
357 /**
358 * Returns the actual url through which a script is served.
359 * @param moodle_url|string $url full moodle url, or shortened path to script
360 * @return moodle_url
361 */
362 protected function js_fix_url($url) {
363 global $CFG;
364
365 if ($url instanceof moodle_url) {
366 return $url;
367 } else if (strpos($url, '/') === 0) {
368 if (debugging()) {
369 // check file existence only when in debug mode
370 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
44fab7fa 371 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
0bb38e8c
PS
372 }
373 }
621df74e 374 if (!empty($CFG->cachejs) and !empty($CFG->jsrev) and strpos($url, '/lib/editor/') !== 0 and substr($url, -3) === '.js') {
0139ec3f
PS
375 return new moodle_url($CFG->httpswwwroot.'/lib/javascript.php', array('file'=>$url, 'rev'=>$CFG->jsrev));
376 } else {
377 return new moodle_url($CFG->httpswwwroot.$url);
378 }
0bb38e8c
PS
379 } else {
380 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
381 }
382 }
383
384 /**
173ba4f1 385 * Find out if JS module present and return details.
88623be1 386 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
0bb38e8c
PS
387 * @return array description of module or null if not found
388 */
88623be1 389 protected function find_module($component) {
0bb38e8c
PS
390 global $CFG;
391
392 $module = null;
393
879b4f9a 394
88623be1 395 if (strpos($component, 'core_') === 0) {
0bb38e8c
PS
396 // must be some core stuff - list here is not complete, this is just the stuff used from multiple places
397 // so that we do nto have to repeat the definition of these modules over and over again
88623be1 398 switch($component) {
0bb38e8c
PS
399 case 'core_filepicker':
400 $module = array('name' => 'core_filepicker',
401 'fullpath' => '/repository/filepicker.js',
0e77c304 402 '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'),
87ad1edc
PS
403 'strings' => array(array('add', 'repository'), array('back', 'repository'), array('cancel', 'moodle'), array('close', 'repository'),
404 array('cleancache', 'repository'), array('copying', 'repository'), array('date', 'repository'), array('downloadsucc', 'repository'),
405 array('emptylist', 'repository'), array('error', 'repository'), array('federatedsearch', 'repository'),
406 array('filenotnull', 'repository'), array('getfile', 'repository'), array('help', 'moodle'), array('iconview', 'repository'),
407 array('invalidjson', 'repository'), array('linkexternal', 'repository'), array('listview', 'repository'),
408 array('loading', 'repository'), array('login', 'repository'), array('logout', 'repository'), array('noenter', 'repository'),
409 array('noresult', 'repository'), array('manageurl', 'repository'), array('popup', 'repository'), array('preview', 'repository'),
410 array('refresh', 'repository'), array('save', 'repository'), array('saveas', 'repository'), array('saved', 'repository'),
411 array('saving', 'repository'), array('search', 'repository'), array('searching', 'repository'), array('size', 'repository'),
412 array('submit', 'repository'), array('sync', 'repository'), array('title', 'repository'), array('upload', 'repository'),
413 array('uploading', 'repository'), array('xhtmlerror', 'repository'),
f00340e2 414 array('xhtml', 'quiz'), array('cancel'), array('chooselicense', 'repository'), array('author', 'repository'),
ed5f6c0f 415 array('ok', 'moodle'), array('error', 'moodle'), array('info', 'moodle'), array('norepositoriesavailable', 'repository'), array('norepositoriesexternalavailable', 'repository'),
f312e878
DC
416 array('nofilesattached', 'repository'), array('filepicker', 'repository'),
417 array('nofilesavailable', 'repository')
879b4f9a 418 ));
0bb38e8c
PS
419 break;
420 case 'core_comment':
421 $module = array('name' => 'core_comment',
422 'fullpath' => '/comment/comment.js',
4b201bc6 423 'requires' => array('base', 'io', 'node', 'json', 'yui2-animation', 'overlay'),
535b4a51 424 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
34e20eb4 425 );
0bb38e8c
PS
426 break;
427 case 'core_role':
428 $module = array('name' => 'core_role',
87b4981b
SH
429 'fullpath' => '/admin/roles/module.js',
430 'requires' => array('node', 'cookie'));
0bb38e8c
PS
431 break;
432 case 'core_completion':
433 $module = array('name' => 'core_completion',
434 'fullpath' => '/course/completion.js');
435 break;
436 case 'core_dock':
437 $module = array('name' => 'core_dock',
438 'fullpath' => '/blocks/dock.js',
7e4617f7 439 'requires' => array('base', 'node', 'event-custom', 'event-mouseenter', 'event-resize'),
b496e634 440 'strings' => array(array('addtodock', 'block'),array('undockitem', 'block'),array('undockall', 'block'),array('thisdirectionvertical', 'langconfig')));
0bb38e8c 441 break;
0bb38e8c
PS
442 case 'core_message':
443 $module = array('name' => 'core_message',
444 'fullpath' => '/message/module.js');
445 break;
446 case 'core_flashdetect':
447 $module = array('name' => 'core_flashdetect',
448 'fullpath' => '/lib/flashdetect/flashdetect.js',
449 'requires' => array('io'));
450 break;
c2489597
SH
451 case 'core_group':
452 $module = array('name' => 'core_group',
453 'fullpath' => '/group/module.js',
454 'requires' => array('node', 'overlay', 'event-mouseenter'));
455 break;
157434a5
TH
456 case 'core_question_engine':
457 $module = array('name' => 'core_question_engine',
458 'fullpath' => '/question/qengine.js',
459 'requires' => array('node', 'event'));
460 break;
3dcdf440
PS
461 case 'core_rating':
462 $module = array('name' => 'core_rating',
a09aeee4
AD
463 'fullpath' => '/rating/module.js',
464 'requires' => array('node', 'event', 'overlay', 'io', 'json'));
465 break;
fb2fb46e
DC
466 case 'core_filetree':
467 $module = array('name' => 'core_filetree',
468 'fullpath' => '/files/module.js',
469 'requires' => array('node', 'event', 'overlay', 'io', 'json', 'yui2-treeview'));
470 break;
0bb38e8c
PS
471 }
472
473 } else {
ae586328
PS
474 if ($dir = get_component_directory($component)) {
475 if (file_exists("$dir/module.js")) {
476 if (strpos($dir, $CFG->dirroot.'/') === 0) {
477 $dir = substr($dir, strlen($CFG->dirroot));
478 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
479 }
0bb38e8c
PS
480 }
481 }
482 }
483
484 return $module;
485 }
486
487 /**
488 * Append YUI3 module to default YUI3 JS loader.
489 * The structure of module array is described at http://developer.yahoo.com/yui/3/yui/:
490 * @param string|array $module name of module (details are autodetected), or full module specification as array
491 * @return void
492 */
493 public function js_module($module) {
494 global $CFG;
495
496 if (empty($module)) {
497 throw new coding_exception('Missing YUI3 module name or full description.');
498 }
499
500 if (is_string($module)) {
501 $module = $this->find_module($module);
502 }
503
504 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
505 throw new coding_exception('Missing YUI3 module details.');
506 }
507
d067fc47
SH
508 // Don't load this module if we already have, no need to!
509 if ($this->js_module_loaded($module['name'])) {
510 if (debugging('', DEBUG_DEVELOPER)) {
511 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
512 }
513 return;
514 }
515
0bb38e8c 516 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
87ad1edc
PS
517 // add all needed strings
518 if (!empty($module['strings'])) {
519 foreach ($module['strings'] as $string) {
520 $identifier = $string[0];
521 $component = isset($string[1]) ? $string[1] : 'moodle';
522 $a = isset($string[2]) ? $string[2] : null;
523 $this->string_for_js($identifier, $component, $a);
524 }
525 }
526 unset($module['strings']);
527
d067fc47
SH
528 // Process module requirements and attempt to load each. This allows
529 // moodle modules to require each other.
530 if (!empty($module['requires'])){
531 foreach ($module['requires'] as $requirement) {
532 $rmodule = $this->find_module($requirement);
533 if (is_array($rmodule)) {
534 $this->js_module($rmodule);
535 }
536 }
537 }
621df74e 538
0bb38e8c
PS
539 if ($this->headdone) {
540 $this->extramodules[$module['name']] = $module;
541 } else {
542 $this->M_yui_loader->modules[$module['name']] = $module;
543 }
d067fc47
SH
544 if (debugging('', DEBUG_DEVELOPER)) {
545 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces)) {
546 $this->debug_moduleloadstacktraces[$module['name']] = array();
547 }
548 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
549 }
550 }
551
552 /**
553 * Returns true if the module has already been loaded.
554 *
555 * @param string|array $modulename
556 * @return bool True if the module has already been loaded
557 */
558 protected function js_module_loaded($module) {
559 if (is_string($module)) {
560 $modulename = $module;
561 } else {
562 $modulename = $module['name'];
563 }
564 return array_key_exists($modulename, $this->M_yui_loader->modules) ||
565 array_key_exists($modulename, $this->extramodules);
566 }
567
568 /**
569 * Returns the stacktraces from loading js modules.
570 * @return array
571 */
572 public function get_loaded_modules() {
573 return $this->debug_moduleloadstacktraces;
0bb38e8c
PS
574 }
575
576 /**
577 * Ensure that the specified CSS file is linked to from this page.
578 *
579 * Because stylesheet links must go in the <head> part of the HTML, you must call
580 * this function before {@link get_head_code()} is called. That normally means before
581 * the call to print_header. If you call it when it is too late, an exception
582 * will be thrown.
583 *
584 * Even if a particular style sheet is requested more than once, it will only
585 * be linked to once.
586 *
86c2da17 587 * Please note use of this feature is strongly discouraged,
0bb38e8c
PS
588 * it is suitable only for places where CSS is submitted directly by teachers.
589 * (Students must not be allowed to submit any external CSS because it may
590 * contain embedded javascript!). Example of correct use is mod/data.
591 *
592 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
593 * For example:
594 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
595 */
596 public function css($stylesheet) {
597 global $CFG;
598
599 if ($this->headdone) {
600 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
601 }
602
603 if ($stylesheet instanceof moodle_url) {
604 // ok
605 } else if (strpos($stylesheet, '/') === 0) {
606 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
607 } else {
608 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
609 }
610
611 $this->cssurls[$stylesheet->out()] = $stylesheet; // overrides
612 }
613
614 /**
615 * Add theme stylkesheet to page - do not use from plugin code,
616 * this should be called only from the core renderer!
617 * @param moodle_url $stylesheet
618 * @return void
619 */
620 public function css_theme(moodle_url $stylesheet) {
621 $this->cssthemeurls[] = $stylesheet;
622 }
623
624 /**
625 * Ensure that a skip link to a given target is printed at the top of the <body>.
626 *
627 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
628 * will be thrown). That normally means you must call this before the call to print_header.
629 *
630 * If you ask for a particular skip link to be printed, it is then your responsibility
173ba4f1 631 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
0bb38e8c
PS
632 * page, so that the skip link goes somewhere.
633 *
634 * Even if a particular skip link is requested more than once, only one copy of it will be output.
635 *
636 * @param $target the name of anchor this link should go to. For example 'maincontent'.
637 * @param $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
638 */
639 public function skip_link_to($target, $linktext) {
640 if ($this->topofbodydone) {
641 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
642 return;
643 }
644 $this->skiplinks[$target] = $linktext;
645 }
646
647 /**
648 * !!!DEPRECATED!!! please use js_init_call() if possible
649 * Ensure that the specified JavaScript function is called from an inline script
650 * somewhere on this page.
651 *
652 * By default the call will be put in a script tag at the
653 * end of the page after initialising Y instance, since this gives best page-load
654 * performance and allows you to use YUI3 library.
655 *
656 * If you request that a particular function is called several times, then
657 * that is what will happen (unlike linking to a CSS or JS file, where only
658 * one link will be output).
659 *
173ba4f1 660 * The main benefit of the method is the automatic encoding of all function parameters.
0bb38e8c
PS
661 *
662 * @param string $function the name of the JavaScritp function to call. Can
663 * be a compound name like 'Y.Event.purgeElement'. Can also be
664 * used to create and object by using a 'function name' like 'new user_selector'.
665 * @param array $arguments and array of arguments to be passed to the function.
666 * When generating the function call, this will be escaped using json_encode,
667 * so passing objects and arrays should work.
668 * @param bool $ondomready
669 * @param int $delay
670 * @return void
671 */
672 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
673 $where = $ondomready ? 'ondomready' : 'normal';
674 $this->jscalls[$where][] = array($function, $arguments, $delay);
675 }
676
2a102b90 677 /**
2b722f87 678 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
2a102b90 679 *
2b722f87 680 * @deprecated DO NOT USE
2a102b90
SH
681 *
682 * @param string|array $modules One or more gallery modules to require
683 * @param string $version
684 * @param string $function
685 * @param array $arguments
686 * @param bool $ondomready
687 */
688 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
689 global $CFG;
2b722f87
SH
690 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER);
691 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
692 }
693
694 /**
695 * Creates a JavaScript function call that requires one or more modules to be loaded
696 *
697 * This function can be used to include all of the standard YUI module types within JavaScript:
698 * - YUI3 modules [node, event, io]
699 * - YUI2 modules [yui2-*]
700 * - Moodle modules [moodle-*]
701 * - Gallery modules [gallery-*]
702 *
703 * @param array|string $modules One or more modules
704 * @param string $function The function to call once modules have been loaded
705 * @param array $arguments An array of arguments to pass to the function
706 * @param string $galleryversion The gallery version to use
707 * @param bool $ondomready
708 */
709 public function yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
6e6e3881
PS
710 global $CFG;
711
2a102b90
SH
712 if (!is_array($modules)) {
713 $modules = array($modules);
714 }
715 if (empty($CFG->useexternalyui) || true) {
716 // We need to set the M.yui.galleryversion to the correct version
2b722f87 717 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
2a102b90
SH
718 } else {
719 // Set Y's config.gallery to the version
2b722f87 720 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
2a102b90
SH
721 }
722 $jscode .= 'Y.use('.join(',', array_map('json_encode', $modules)).',function() {'.js_writer::function_call($function, $arguments).'})';
723 if ($ondomready) {
724 $jscode = "Y.on('domready', function() { $jscode });";
725 }
726 $this->jsinitcode[] = $jscode;
727 }
728
0bb38e8c
PS
729 /**
730 * Ensure that the specified JavaScript function is called from an inline script
731 * from page footer.
732 *
733 * @param string $function the name of the JavaScritp function to with init code,
734 * usually something like 'M.mod_mymodule.init'
735 * @param array $extraarguments and array of arguments to be passed to the function.
736 * The first argument is always the YUI3 Y instance with all required dependencies
737 * already loaded.
738 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
739 * @param array $module JS module specification array
740 * @return void
741 */
742 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
743 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
744 if (!$module) {
745 // detect module automatically
746 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
747 $module = $this->find_module($matches[1]);
748 }
749 }
750
751 $this->js_init_code($jscode, $ondomready, $module);
752 }
753
754 /**
755 * Add short static javascript code fragment to page footer.
756 * This is intended primarily for loading of js modules and initialising page layout.
757 * Ideally the JS code fragment should be stored in plugin renderer so that themes
758 * may override it.
759 * @param string $jscode
760 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
761 * @param array $module JS module specification array
762 * @return void
763 */
764 public function js_init_code($jscode, $ondomready = false, array $module = null) {
765 $jscode = trim($jscode, " ;\n"). ';';
766
767 if ($module) {
768 $this->js_module($module);
769 $modulename = $module['name'];
770 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
771 }
772
773 if ($ondomready) {
774 $jscode = "Y.on('domready', function() { $jscode });";
775 }
776
777 $this->jsinitcode[] = $jscode;
778 }
779
780 /**
781 * Make a language string available to JavaScript.
782 *
2b728cb5 783 * All the strings will be available in a M.str object in the global namespace.
0bb38e8c 784 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
2b728cb5 785 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
0bb38e8c
PS
786 * equivalent in the current language.
787 *
788 * The arguments to this function are just like the arguments to get_string
7f91ba53
DM
789 * except that $component is not optional, and there are some aspects to consider
790 * when the string contains {$a} placeholder.
791 *
792 * If the string does not contain any {$a} placeholder, you can simply use
793 * M.str.component.identifier to obtain it. If you prefer, you can call
794 * M.util.get_string(identifier, component) to get the same result.
795 *
796 * If you need to use {$a} placeholders, there are two options. Either the
797 * placeholder should be substituted in PHP on server side or it should
798 * be substituted in Javascript at client side.
799 *
800 * To substitute the placeholder at server side, just provide the required
801 * value for the placeholder when you require the string. Because each string
802 * is only stored once in the JavaScript (based on $identifier and $module)
803 * you cannot get the same string with two different values of $a. If you try,
804 * an exception will be thrown. Once the placeholder is substituted, you can
805 * use M.str or M.util.get_string() as shown above:
806 *
807 * // require the string in PHP and replace the placeholder
808 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
809 * // use the result of the substitution in Javascript
810 * alert(M.str.moodle.fullnamedisplay);
811 *
812 * To substitute the placeholder at client side, use M.util.get_string()
813 * function. It implements the same logic as {@see get_string()}:
814 *
815 * // require the string in PHP but keep {$a} as it is
816 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
817 * // provide the values on the fly in Javascript
818 * user = { firstname : 'Harry', lastname : 'Potter' }
819 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
820 *
821 * If you do need the same string expanded with different $a values in PHP
822 * on server side, then the solution is to put them in your own data structure
823 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
0bb38e8c
PS
824 *
825 * @param string $identifier the desired string.
826 * @param string $module the language file to look in.
827 * @param mixed $a any extra data to add into the string (optional).
828 */
829 public function string_for_js($identifier, $component, $a = NULL) {
830 $string = get_string($identifier, $component, $a);
831 if (!$component) {
832 throw new coding_exception('The $module parameter is required for page_requirements_manager::string_for_js.');
833 }
df997f84 834 if (isset($this->stringsforjs[$component][$identifier]) && $this->stringsforjs[$component][$identifier] !== $string) {
0bb38e8c 835 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
df997f84 836 "from lang file '$component'. Did you already ask for it with a different \$a? {$this->stringsforjs[$component][$identifier]} !== $string");
0bb38e8c
PS
837 }
838 $this->stringsforjs[$component][$identifier] = $string;
839 }
840
841 /**
842 * Make an array of language strings available for JS
843 *
844 * This function calls the above function {@link string_for_js()} for each requested
845 * string in the $identifiers array that is passed to the argument for a single module
846 * passed in $module.
847 *
848 * <code>
849 * $PAGE->strings_for_js(Array('one', 'two', 'three'), 'mymod', Array('a', null, 3));
850 *
173ba4f1 851 * // The above is identitical to calling
0bb38e8c
PS
852 *
853 * $PAGE->string_for_js('one', 'mymod', 'a');
854 * $PAGE->string_for_js('two', 'mymod');
855 * $PAGE->string_for_js('three', 'mymod', 3);
856 * </code>
857 *
858 * @param array $identifiers An array of desired strings
859 * @param string $component The module to load for
860 * @param mixed $a This can either be a single variable that gets passed as extra
861 * information for every string or it can be an array of mixed data where the
862 * key for the data matches that of the identifier it is meant for.
863 *
864 */
865 public function strings_for_js($identifiers, $component, $a=NULL) {
866 foreach ($identifiers as $key => $identifier) {
867 if (is_array($a) && array_key_exists($key, $a)) {
868 $extra = $a[$key];
869 } else {
870 $extra = $a;
871 }
872 $this->string_for_js($identifier, $component, $extra);
873 }
874 }
875
876 /**
877 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
878 *
879 * Make some data from PHP available to JavaScript code.
880 *
881 * For example, if you call
882 * <pre>
883 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
884 * </pre>
885 * then in JavsScript mydata.name will be 'Moodle'.
886 * @param string $variable the the name of the JavaScript variable to assign the data to.
887 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
888 * should be considered an experimental feature.
889 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
890 * so passing objects and arrays should work.
891 * @param bool $inhead initialise in head
892 * @return void
893 */
894 public function data_for_js($variable, $data, $inhead=false) {
895 $where = $inhead ? 'head' : 'footer';
896 $this->jsinitvariables[$where][] = array($variable, $data);
897 }
898
899 /**
900 * Creates a YUI event handler.
901 *
902 * @param mixed $selector standard YUI selector for elemnts, may be array or string, element id is in the form "#idvalue"
903 * @param string $event A valid DOM event (click, mousedown, change etc.)
904 * @param string $function The name of the function to call
905 * @param array $arguments An optional array of argument parameters to pass to the function
906 * @return void
879b4f9a
DC
907 */
908 public function event_handler($selector, $event, $function, array $arguments = null) {
0bb38e8c
PS
909 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
910 }
911
912 /**
913 * Returns code needed for registering of event handlers.
914 * @return string JS code
915 */
916 protected function get_event_handler_code() {
917 $output = '';
918 foreach ($this->eventhandlers as $h) {
919 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
920 }
921 return $output;
922 }
923
924 /**
925 * Get the inline JavaScript code that need to appear in a particular place.
926 * @return bool $ondomready
927 */
928 protected function get_javascript_code($ondomready) {
929 $where = $ondomready ? 'ondomready' : 'normal';
930 $output = '';
931 if ($this->jscalls[$where]) {
932 foreach ($this->jscalls[$where] as $data) {
e6a3ea28 933 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
0bb38e8c
PS
934 }
935 if (!empty($ondomready)) {
936 $output = " Y.on('domready', function() {\n$output\n });";
937 }
938 }
939 return $output;
940 }
941
942 /**
943 * Returns js code to be executed when Y is available.
944 * @return unknown_type
945 */
946 protected function get_javascript_init_code() {
947 if (count($this->jsinitcode)) {
948 return implode("\n", $this->jsinitcode) . "\n";
949 }
950 return '';
951 }
952
953 /**
954 * Returns basic YUI3 JS loading code.
955 * YUI3 is using autoloading of both CSS and JS code.
956 *
957 * Major benefit of this compared to standard js/csss loader is much improved
958 * caching, better browser cache utilisation, much fewer http requests.
959 *
960 * @return string
961 */
962 protected function get_yui3lib_headcode() {
a6338a13 963 $code = $this->yui3loader->tags();
0bb38e8c
PS
964 // unfortunately yui loader does not produce xhtml strict code, so let's fix it for now
965 $code = str_replace('&amp;', '&', $code);
966 $code = str_replace('&', '&amp;', $code);
967 return $code;
968 }
969
970 /**
971 * Returns basic YUI2 JS loading code.
972 * It can be called manually at any time.
973 * If called manually the result needs to be output using echo().
974 *
975 * Major benefit of this compared to standard js loader is much improved
976 * caching, better browser cache utilisation, much fewer http requests.
977 *
978 * All YUI2 CSS is loaded automatically.
979 *
980 * @return string JS embedding code
981 */
982 public function get_yui2lib_code() {
983 global $CFG;
984
985 if ($this->headdone) {
986 $code = $this->yui2loader->script();
987 } else {
988 $code = $this->yui2loader->script();
989 if ($this->yui2loader->combine) {
990 $skinurl = $this->yui2loader->comboBase . $CFG->yui2version . '/build/assets/skins/sam/skin.css';
991 } else {
992 $skinurl = $this->yui2loader->base . 'assets/skins/sam/skin.css';
993 }
994 // please note this is a temporary hack until we fully migrate to later YUI3 that has all the widgets
995 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css', 'href'=>$skinurl);
996 $code .= "\n" . html_writer::empty_tag('link', $attributes) . "\n";
997 }
998 $code = str_replace('&amp;', '&', $code);
999 $code = str_replace('&', '&amp;', $code);
1000 return $code;
1001 }
1002
1003 /**
1004 * Returns html tags needed for inclusion of theme CSS
1005 * @return string
1006 */
1007 protected function get_css_code() {
1008 // First of all the theme CSS, then any custom CSS
1009 // Please note custom CSS is strongly discouraged,
1010 // because it can not be overridden by themes!
1011 // It is suitable only for things like mod/data which accepts CSS from teachers.
692e9fa5 1012 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
0bb38e8c 1013
692e9fa5
SH
1014 // This line of code may look funny but it is currently required in order
1015 // to avoid MASSIVE display issues in Internet Explorer.
1016 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1017 // ignored whenever another resource is added until such time as a redraw
1018 // is forced, usually by moving the mouse over the affected element.
f4136193 1019 $code = html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
0bb38e8c
PS
1020
1021 $urls = $this->cssthemeurls + $this->cssurls;
0bb38e8c
PS
1022 foreach ($urls as $url) {
1023 $attributes['href'] = $url;
1024 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1025 // this id is needed in first sheet only so that theme may override YUI sheets laoded on the fly
1026 unset($attributes['id']);
1027 }
1028
1029 return $code;
1030 }
1031
1032 /**
1033 * Adds extra modules specified after printing of page header
1034 */
1035 protected function get_extra_modules_code() {
1036 if (empty($this->extramodules)) {
1037 return '';
1038 }
1039 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1040 }
1041
1042 /**
1043 * Generate any HTML that needs to go inside the <head> tag.
1044 *
1045 * Normally, this method is called automatically by the code that prints the
1046 * <head> tag. You should not normally need to call it in your own code.
1047 *
1048 * @return string the HTML code to to inside the <head> tag.
1049 */
1050 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1051 global $CFG;
1052
1053 // note: the $page and $output are not stored here because it would
1054 // create circular references in memory which prevents garbage collection
1055 $this->init_requirements_data($page, $renderer);
1056
1057 // yui3 JS and CSS is always loaded first - it is cached in browser
1058 $output = $this->get_yui3lib_headcode();
1059
1060 // BC: load basic YUI2 for now, all yui2 things should be loaded via Y.use('yui2-oldmodulename')
1061 $output .= $this->get_yui2lib_code();
1062
1063 // now theme CSS + custom CSS in this specific order
1064 $output .= $this->get_css_code();
1065
1066 // set up global YUI3 loader object - this should contain all code needed by plugins
1067 // note: in JavaScript just use "YUI(M.yui.loader).use('overlay', function(Y) { .... });"
1068 // this needs to be done before including any other script
2b722f87
SH
1069 $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";
1070 $js .= js_writer::set_variable('M.yui.loader', $this->M_yui_loader, false) . "\n";
0bb38e8c 1071 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
2b722f87
SH
1072 $js = str_replace('"@GALLERYCONFIGFN@"', 'galleryConfigFn', $js);
1073 $js = str_replace('"@MOODLECONFIGFN@"', 'moodleConfigFn', $js);
1074
0bb38e8c
PS
1075 $output .= html_writer::script($js);
1076
1077 // link our main JS file, all core stuff should be there
0139ec3f 1078 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
0bb38e8c
PS
1079
1080 // add variables
1081 if ($this->jsinitvariables['head']) {
1082 $js = '';
1083 foreach ($this->jsinitvariables['head'] as $data) {
1084 list($var, $value) = $data;
1085 $js .= js_writer::set_variable($var, $value, true);
1086 }
1087 $output .= html_writer::script($js);
1088 }
1089
1090 // all the other linked things from HEAD - there should be as few as possible
1091 if ($this->jsincludes['head']) {
1092 foreach ($this->jsincludes['head'] as $url) {
1093 $output .= html_writer::script('', $url);
1094 }
1095 }
1096
1097 // mark head sending done, it is not possible to anything there
1098 $this->headdone = true;
1099
1100 return $output;
1101 }
1102
1103 /**
1104 * Generate any HTML that needs to go at the start of the <body> tag.
1105 *
1106 * Normally, this method is called automatically by the code that prints the
1107 * <head> tag. You should not normally need to call it in your own code.
1108 *
1109 * @return string the HTML code to go at the start of the <body> tag.
1110 */
1111 public function get_top_of_body_code() {
1112 // first the skip links
1113 $links = '';
1114 $attributes = array('class'=>'skip');
1115 foreach ($this->skiplinks as $url => $text) {
1116 $attributes['href'] = '#' . $url;
26acc814 1117 $links .= html_writer::tag('a', $text, $attributes);
0bb38e8c 1118 }
26acc814 1119 $output = html_writer::tag('div', $links, array('class'=>'skiplinks')) . "\n";
0bb38e8c
PS
1120
1121 // then the clever trick for hiding of things not needed when JS works
1122 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1123 $this->topofbodydone = true;
1124 return $output;
1125 }
1126
1127 /**
1128 * Generate any HTML that needs to go at the end of the page.
1129 *
1130 * Normally, this method is called automatically by the code that prints the
1131 * page footer. You should not normally need to call it in your own code.
1132 *
1133 * @return string the HTML code to to at the end of the page.
1134 */
1135 public function get_end_code() {
2cf81209 1136 global $CFG;
0bb38e8c
PS
1137 // add other requested modules
1138 $output = $this->get_extra_modules_code();
1139
1140 // add missing YUI2 YUI - to be removed once we convert everything to YUI3!
1141 $output .= $this->get_yui2lib_code();
2cf81209 1142
0bb38e8c
PS
1143 // all the other linked scripts - there should be as few as possible
1144 if ($this->jsincludes['footer']) {
1145 foreach ($this->jsincludes['footer'] as $url) {
1146 $output .= html_writer::script('', $url);
1147 }
1148 }
1149
1150 // add all needed strings
1151 if (!empty($this->stringsforjs)) {
2b728cb5 1152 $output .= html_writer::script(js_writer::set_variable('M.str', $this->stringsforjs));
0bb38e8c
PS
1153 }
1154
1155 // add variables
1156 if ($this->jsinitvariables['footer']) {
1157 $js = '';
1158 foreach ($this->jsinitvariables['footer'] as $data) {
1159 list($var, $value) = $data;
1160 $js .= js_writer::set_variable($var, $value, true);
1161 }
1162 $output .= html_writer::script($js);
1163 }
1164
1165 $inyuijs = $this->get_javascript_code(false);
1166 $ondomreadyjs = $this->get_javascript_code(true);
1167 $jsinit = $this->get_javascript_init_code();
1168 $handlersjs = $this->get_event_handler_code();
1169
0139ec3f 1170 // there is no global Y, make sure it is available in your scope
0bb38e8c
PS
1171 $js = "YUI(M.yui.loader).use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1172
1173 $output .= html_writer::script($js);
1174
1175 return $output;
1176 }
1177
1178 /**
1179 * @return boolean Have we already output the code in the <head> tag?
1180 */
1181 public function is_head_done() {
1182 return $this->headdone;
1183 }
1184
1185 /**
1186 * @return boolean Have we already output the code at the start of the <body> tag?
1187 */
1188 public function is_top_of_body_done() {
1189 return $this->topofbodydone;
1190 }
1191}
0139ec3f
PS
1192
1193/**
1194 * Invalidate all server and client side JS caches.
1195 * @return void
1196 */
1197function js_reset_all_caches() {
1198 global $CFG;
1199 require_once("$CFG->libdir/filelib.php");
1200
1201 set_config('jsrev', empty($CFG->jsrev) ? 1 : $CFG->jsrev+1);
09c48cea 1202 fulldelete("$CFG->dataroot/cache/js");
0139ec3f
PS
1203}
1204