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