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