MDL-21370 restore - avoid adding slashes twice to user info. Merged from 19_STABLE
[moodle.git] / lib / ajax / ajaxlib.php
CommitLineData
f72f94a2 1<?php
b2330db6 2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18
19/**
20 * Library functions to facilitate the use of JavaScript in Moodle.
21 *
22 * @package moodlecore
23 * @copyright 2009 Tim Hunt
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27
b2330db6 28/**
29 * This class tracks all the things that are needed by the current page.
30 *
31 * Normally, the only instance of this class you will need to work with is the
32 * one accessible via $PAGE->requires.
33 *
34 * Typical useage would be
9ca13950 35 * <pre>
78946b9b 36 * $PAGE->requires->css('mod/mymod/userstyles.php?id='.$id); // not overriddable via themes!
b2330db6 37 * $PAGE->requires->js('mod/mymod/script.js');
38 * $PAGE->requires->js('mod/mymod/small_but_urgent.js')->in_head();
39 * $PAGE->requires->js_function_call('init_mymod', array($data))->on_dom_ready();
9ca13950 40 * </pre>
b2330db6 41 *
2c144fc3 42 * There are some natural restrictions on some methods. For example, {@link css()}
43 * can only be called before the <head> tag is output. See the comments on the
44 * individual methods for details.
45 *
b2330db6 46 * @copyright 2009 Tim Hunt
47 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5c5418fe 48 * @since Moodle 2.0
b2330db6 49 */
50class page_requirements_manager {
51 const WHEN_IN_HEAD = 0;
52 const WHEN_TOP_OF_BODY = 10;
53 const WHEN_AT_END = 20;
54 const WHEN_ON_DOM_READY = 30;
55
9e43d2b3 56 protected $linkedrequirements = array();
b2330db6 57 protected $stringsforjs = array();
58 protected $requiredjscode = array();
59
2212eb7a
PS
60 protected $themestylesheets = array();
61
b2330db6 62 protected $variablesinitialised = array('mstr' => 1); // 'mstr' is special. See string_for_js.
63
64 protected $headdone = false;
65 protected $topofbodydone = false;
66
945f19f7 67 /** YUI PHPLoader instance responsible for YUI2 loading from PHP only */
985d1d1d 68 protected $yui2loader;
945f19f7
PS
69 /** YUI PHPLoader instance responsible for YUI3 loading from PHP only */
70 protected $yui3loader;
71 /** YUI PHPLoader instance responsible for YUI3 loading from javascript */
72 protected $json_yui3loader;
4c907141
PS
73
74 /**
75 * Page requirements constructor.
76 */
77 public function __construct() {
78 global $CFG;
945f19f7 79
4c907141
PS
80 require_once("$CFG->libdir/yui/phploader/phploader/loader.php");
81
82 $this->yui3loader = new YAHOO_util_Loader($CFG->yui3version);
985d1d1d 83 $this->yui2loader = new YAHOO_util_Loader($CFG->yui2version);
4c907141
PS
84
85 // set up some loader options
4c907141
PS
86 if (debugging('', DEBUG_DEVELOPER)) {
87 $this->yui3loader->filter = YUI_DEBUG; // alternatively we could use just YUI_RAW here
985d1d1d 88 $this->yui2loader->filter = YUI_DEBUG; // alternatively we could use just YUI_RAW here
4c907141
PS
89 } else {
90 $this->yui3loader->filter = null;
985d1d1d 91 $this->yui2loader->filter = null;
95fbe49b 92 }
4c907141
PS
93 if (!empty($CFG->useexternalyui)) {
94 $this->yui3loader->base = 'http://yui.yahooapis.com/' . $CFG->yui3version . '/build/';
985d1d1d 95 $this->yui2loader->base = 'http://yui.yahooapis.com/' . $CFG->yui2version . '/build/';
945f19f7
PS
96 $this->yui3loader->comboBase = 'http://yui.yahooapis.com/combo?';
97 $this->yui2loader->comboBase = 'http://yui.yahooapis.com/combo?';
4c907141 98 } else {
aa42314d
PS
99 $this->yui3loader->base = $CFG->httpswwwroot . '/lib/yui/'. $CFG->yui3version . '/build/';
100 $this->yui2loader->base = $CFG->httpswwwroot . '/lib/yui/'. $CFG->yui2version . '/build/';
945f19f7
PS
101 $this->yui3loader->comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php?';
102 $this->yui2loader->comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php?';
4c907141
PS
103 }
104
945f19f7 105 // enable combo loader? this significantly helps with caching and performance!
aa42314d
PS
106 $this->yui3loader->combine = !empty($CFG->yuicomboloading);
107 $this->yui2loader->combine = !empty($CFG->yuicomboloading);
945f19f7 108
2212eb7a 109 // set up JS YUI loader helper object
945f19f7 110 $this->json_yui3loader = new stdClass();
2212eb7a
PS
111 $this->json_yui3loader->base = $this->yui3loader->base;
112 $this->json_yui3loader->comboBase = $this->yui3loader->comboBase;
113 $this->json_yui3loader->combine = $this->yui3loader->combine;
114 $this->json_yui3loader->filter = ($this->yui3loader->filter == YUI_DEBUG) ? 'debug' : '';
115 $this->json_yui3loader->insertBefore = 'firstthemesheet';
116 $this->json_yui3loader->modules = array();
c8870e68
PS
117 $this->add_yui2_modules(); // adds loading info for YUI2
118 }
119
120 /**
121 * This method adds yui2 modules into the yui3 JS loader-
122 * @return void
123 */
124 protected function add_yui2_modules() {
125 //note: this function is definitely not perfect, because
126 // it adds tons of markup into each page, but it can be
127 // abstracted into separate JS file with proper headers
128 global $CFG;
129
130 $GLOBALS['yui_current'] = array();
131 require($CFG->libdir.'/yui/phploader/lib/meta/config_'.$CFG->yui2version.'.php');
132 $info = $GLOBALS['yui_current'];
133 unset($GLOBALS['yui_current']);
134
135 if (empty($CFG->yuicomboloading)) {
136 $urlbase = $this->yui2loader->base;
137 } else {
138 $urlbase = $this->yui2loader->comboBase.$CFG->yui2version.'/build/';
139 }
140
141 $modules = array();
142 $ignored = array(); // list of CSS modules that are not needed
143 foreach ($info['moduleInfo'] as $name => $module) {
144 if ($module['type'] === 'css') {
145 $ignored[$name] = true;
146 } else {
147 $modules['yui2-'.$name] = $module;
148 }
149 }
150 foreach ($modules as $name=>$module) {
151 $module['fullpath'] = $urlbase.$module['path']; // fix path to point to correct location
152 unset($module['path']);
153 foreach(array('requires', 'optional', 'supersedes') as $fixme) {
154 if (!empty($module[$fixme])) {
155 $fixed = false;
156 foreach ($module[$fixme] as $key=>$dep) {
157 if (isset($ignored[$dep])) {
158 unset($module[$fixme][$key]);
159 $fixed = true;
160 } else {
161 $module[$fixme][$key] = 'yui2-'.$dep;
162 }
163 }
164 if ($fixed) {
165 $module[$fixme] = array_merge($module[$fixme]); // fix keys
166 }
167 }
168 }
169 $this->json_yui3loader->modules[$name] = $module;
170 }
945f19f7
PS
171 }
172
173 /**
174 * Initialise with the bits of JavaScript that every Moodle page should have.
175 *
176 * @param moodle_page $page
177 * @param core_renderer $output
178 */
c724f835 179 protected function setup_core_javascript(moodle_page $page, core_renderer $output) {
945f19f7
PS
180 global $CFG;
181
182 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
183 // Otherwise, in some situations, users will get warnings about insecure content
184 // on sercure pages from their web browser.
185
186 //TODO: problem here is we may need this in some included JS - move this somehow to the very beginning
187 // right after the YUI loading
188 $config = array(
189 'wwwroot' => $CFG->httpswwwroot, // Yes, really. See above.
190 'sesskey' => sesskey(),
b9bc2019 191 'loadingicon' => $output->pix_url('i/loading_small', 'moodle')->out(false),
945f19f7
PS
192 'themerev' => theme_get_revision(),
193 'theme' => $page->theme->name,
194 'yui2loaderBase' => $this->yui2loader->base,
195 'yui3loaderBase' => $this->yui3loader->base,
196 'yui2loaderComboBase' => $this->yui2loader->comboBase,
197 'yui3loaderComboBase' => $this->yui3loader->comboBase,
198 'yuicombine' => (int)$this->yui3loader->combine,
199 'yuifilter' => debugging('', DEBUG_DEVELOPER) ? 'debug' : '',
200
201 );
202 if (debugging('', DEBUG_DEVELOPER)) {
203 $config['developerdebug'] = true;
204 }
205 $this->data_for_js('moodle_cfg', $config)->in_head();
206
945f19f7
PS
207 if (debugging('', DEBUG_DEVELOPER)) {
208 $this->yui2_lib('logger');
209 }
210
211 // YUI3 init code
212 $this->yui3_lib(array('cssreset', 'cssbase', 'cssfonts', 'cssgrids')); // full CSS reset
213 $this->yui3_lib(array('yui', 'loader')); // allows autoloading of everything else
214
215
216 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
217
218 // Note that, as a short-cut, the code
219 // $js = "document.body.className += ' jsenabled';\n";
220 // is hard-coded in {@link page_requirements_manager::get_top_of_body_code)
2574fae6
PS
221 $this->yui2_lib('dom'); // needs to be migrated to YUI3 before we release 2.0
222 $this->yui2_lib('container'); // needs to be migrated to YUI3 before we release 2.0
223 $this->yui2_lib('connection'); // needs to be migrated to YUI3 before we release 2.0
99eaca9d
DC
224 // File Picker use this module loading YUI2 widgets
225 $this->yui2_lib('yuiloader'); // needs to be migrated to YUI3 before we release 2.0
c8870e68 226 $this->js_module('filepicker'); // should be migrated elsewhere before 2.0
2574fae6 227
945f19f7
PS
228 $this->string_for_js('confirmation', 'admin');
229 $this->string_for_js('cancel', 'moodle');
230 $this->string_for_js('yes', 'moodle');
231 $this->js_function_call('init_help_icons');
4c907141
PS
232 }
233
b2330db6 234 /**
2c144fc3 235 * Ensure that the specified JavaScript file is linked to from this page.
236 *
237 * By default the link is put at the end of the page, since this gives best page-load performance.
b2330db6 238 *
239 * Even if a particular script is requested more than once, it will only be linked
240 * to once.
241 *
242 * @param $jsfile The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
02fd1ad7 243 * No leading slash. For example '/mod/mymod/customscripts.js';
b2330db6 244 * @param boolean $fullurl This parameter is intended for internal use only.
cf615522 245 * However, in exceptional circumstances you may wish to use it to link
246 * to JavaScript on another server. For example, lib/recaptchalib.php has to
247 * do this. This really should only be done in exceptional circumstances. This
248 * may change in the future without warning.
b2330db6 249 * (If true, $jsfile is treaded as a full URL, not relative $CFG->wwwroot.)
2c144fc3 250 * @return required_js The required_js object. This allows you to control when the
251 * link to the script is output by calling methods like {@link required_js::asap()} or
252 * {@link required_js::in_head()}.
b2330db6 253 */
254 public function js($jsfile, $fullurl = false) {
255 global $CFG;
256 if (!$fullurl) {
02fd1ad7 257 $jsfile = ltrim($jsfile, '/'); // for now until we change all js urls to start with '/' like the rest of urls
d76b8a20 258 // strtok is used to trim off any GET string arguments before looking for the file
259 if (!file_exists($CFG->dirroot . '/' . strtok($jsfile, '?'))) {
b2330db6 260 throw new coding_exception('Attept to require a JavaScript file that does not exist.', $jsfile);
261 }
262 $url = $CFG->httpswwwroot . '/' . $jsfile;
263 } else {
264 $url = $jsfile;
265 }
9e43d2b3 266 if (!isset($this->linkedrequirements[$url])) {
267 $this->linkedrequirements[$url] = new required_js($this, $url);
b2330db6 268 }
9e43d2b3 269 return $this->linkedrequirements[$url];
b2330db6 270 }
271
272 /**
4c907141 273 * Ensure that the specified YUI2 library file, and all its required dependancies,
2c144fc3 274 * are linked to from this page.
275 *
276 * By default the link is put at the end of the page, since this gives best page-load
277 * performance. Optional dependencies are not loaded automatically - if you want
278 * them you will need to load them first with other calls to this method.
b2330db6 279 *
b2330db6 280 * Even if a particular library is requested more than once (perhaps as a dependancy
281 * of other libraries) it will only be linked to once.
282 *
985d1d1d 283 * The library is leaded as soon as possible, if $OUTPUT->header() not used yet it
945f19f7 284 * is put into the page header, otherwise it is loaded in the page footer.
985d1d1d
PS
285 *
286 * @param string|array $libname the name of the YUI2 library you require. For example 'autocomplete'.
287 * @return void
b2330db6 288 */
f44b10ed 289 public function yui2_lib($libname) {
985d1d1d
PS
290 $libnames = (array)$libname;
291 foreach ($libnames as $lib) {
292 $this->yui2loader->load($lib);
b2330db6 293 }
b2330db6 294 }
295
4c907141
PS
296 /**
297 * Ensure that the specified YUI3 library file, and all its required dependancies,
298 * are laoded automatically on this page.
985d1d1d 299 *
4c907141
PS
300 * @param string|array $libname the name of the YUI3 library you require. For example 'overlay'.
301 * @return void
302 */
303 public function yui3_lib($libname) {
304 if ($this->headdone) {
9d897331 305 throw new coding_exception('YUI3 libraries can be preloaded by PHP only from HEAD, please use YUI autoloading instead: ', $libname);
4c907141
PS
306 }
307 $libnames = (array)$libname;
308 foreach ($libnames as $lib) {
309 $this->yui3loader->load($lib);
310 }
311 }
312
c8870e68
PS
313 /**
314 * Append YUI3 module to default YUI3 JS loader.
315 * The structure of module array is described at http://developer.yahoo.com/yui/3/yui/:
316 * @param string $name unique module name based of full plugin name
317 * @param array $module usually the module details may be detected from the $name
318 * @return void
319 */
320 public function js_module($name, array $module = null) {
321 global $CFG;
322
323 if (strpos($name, 'core_') === 0) {
324 // must be some core stuff
325 } else {
326 if ($name === 'filepicker') { // TODO: rename to 'core_filepicker' and move above
327 $pathtofilepicker = $CFG->httpswwwroot.'/repository/filepicker.js';
328 $module = array('fullpath'=>$pathtofilepicker, 'requires' => array('base', 'node', 'json', 'async-queue', 'io'));
329 }
330 //TODO: look for plugin info?
331 }
332
333 if ($module === null) {
334 throw new coding_exception('Missing YUI3 module details.');
335 }
336
337 $this->json_yui3loader->modules[$name] = $module;
338 }
339
b2330db6 340 /**
2c144fc3 341 * Ensure that the specified CSS file is linked to from this page.
342 *
343 * Because stylesheet links must go in the <head> part of the HTML, you must call
344 * this function before {@link get_head_code()} is called. That normally means before
b2330db6 345 * the call to print_header. If you call it when it is too late, an exception
346 * will be thrown.
347 *
348 * Even if a particular style sheet is requested more than once, it will only
349 * be linked to once.
350 *
9ca13950 351 * @param string $stylesheet The path to the .css file, relative to
b2330db6 352 * $CFG->dirroot / $CFG->wwwroot. No leading slash. For example
353 * 'mod/mymod/styles.css';
354 * @param boolean $fullurl This parameter is intended for internal use only.
355 * (If true, $stylesheet is treaded as a full URL, not relative $CFG->wwwroot.)
356 */
357 public function css($stylesheet, $fullurl = false) {
358 global $CFG;
9f509643
DC
359 if (!$fullurl) {
360 if (!file_exists($CFG->dirroot . '/' . strtok($stylesheet, '?'))) {
361 throw new coding_exception('Attempt to require a CSS file that does not exist.', $stylesheet);
362 }
363 $url = $CFG->httpswwwroot . '/' . $stylesheet;
364 } else {
365 $url = $stylesheet;
366 }
b2330db6 367
70f83b58 368 if (isset($this->linkedrequirements[$url])) {
9f509643 369 // already required, ignore it
70f83b58 370 return;
b2330db6 371 } else {
70f83b58
DC
372 if ($this->headdone) {
373 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
374 }
9e43d2b3 375 $this->linkedrequirements[$url] = new required_css($this, $url);
b2330db6 376 }
377 }
378
2212eb7a
PS
379 /**
380 * Add theme stylkesheet to page - do not use from plugin code,
381 * this shoudl be called only from the core renderer!
382 * @param moodle_url $stylesheet
383 * @return void
384 */
385 public function themecss(moodle_url $stylesheet) {
386 $this->themestylesheets[] = $stylesheet;
387 }
388
b2330db6 389 /**
2c144fc3 390 * Ensure that a skip link to a given target is printed at the top of the <body>.
391 *
392 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
b2330db6 393 * will be thrown). That normally means you must call this before the call to print_header.
394 *
395 * If you ask for a particular skip link to be printed, it is then your responsibility
2c144fc3 396 * to ensure that the appropraite <a name="..."> tag is printed in the body of the
b2330db6 397 * page, so that the skip link goes somewhere.
398 *
399 * Even if a particular skip link is requested more than once, only one copy of it will be output.
400 *
401 * @param $target the name of anchor this link should go to. For example 'maincontent'.
402 * @param $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
403 */
404 public function skip_link_to($target, $linktext) {
9e43d2b3 405 if (!isset($this->linkedrequirements[$target])) {
406 $this->linkedrequirements[$target] = new required_skip_link($this, $target, $linktext);
b2330db6 407 }
408 }
409
410 /**
411 * Ensure that the specified JavaScript function is called from an inline script
2c144fc3 412 * somewhere on this page.
413 *
414 * By default the call will be put in a script tag at the
b2330db6 415 * end of the page, since this gives best page-load performance.
416 *
417 * If you request that a particular function is called several times, then
418 * that is what will happen (unlike linking to a CSS or JS file, where only
419 * one link will be output).
420 *
421 * @param string $function the name of the JavaScritp function to call. Can
cf615522 422 * be a compound name like 'YAHOO.util.Event.addListener'. Can also be
423 * used to create and object by using a 'function name' like 'new user_selector'.
b2330db6 424 * @param array $arguments and array of arguments to be passed to the function.
425 * When generating the function call, this will be escaped using json_encode,
426 * so passing objects and arrays should work.
2c144fc3 427 * @return required_js_function_call The required_js_function_call object.
b2330db6 428 * This allows you to control when the link to the script is output by
2c144fc3 429 * calling methods like {@link required_js_function_call::in_head()},
430 * {@link required_js_function_call::at_top_of_body()},
431 * {@link required_js_function_call::on_dom_ready()} or
432 * {@link required_js_function_call::after_delay()} methods.
b2330db6 433 */
434 public function js_function_call($function, $arguments = array()) {
435 $requirement = new required_js_function_call($this, $function, $arguments);
436 $this->requiredjscode[] = $requirement;
437 return $requirement;
438 }
439
440 /**
2c144fc3 441 * Make a language string available to JavaScript.
117bd748 442 *
2c144fc3 443 * All the strings will be available in a mstr object in the global namespace.
444 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
b2330db6 445 * then the JavaScript variable mstr.moodle.course will be 'Course', or the
446 * equivalent in the current language.
447 *
448 * The arguments to this function are just like the arguments to get_string
449 * except that $module is not optional, and there are limitations on how you
450 * use $a. Because each string is only stored once in the JavaScript (based
451 * on $identifier and $module) you cannot get the same string with two different
452 * values of $a. If you try, an exception will be thrown.
453 *
454 * If you do need the same string expanded with different $a values, then
455 * the solution is to put them in your own data structure (e.g. and array)
2c144fc3 456 * that you pass to JavaScript with {@link data_for_js()}.
b2330db6 457 *
458 * @param string $identifier the desired string.
459 * @param string $module the language file to look in.
460 * @param mixed $a any extra data to add into the string (optional).
461 */
462 public function string_for_js($identifier, $module, $a = NULL) {
463 $string = get_string($identifier, $module, $a);
464 if (!$module) {
2c144fc3 465 throw new coding_exception('The $module parameter is required for page_requirements_manager::string_for_js.');
b2330db6 466 }
467 if (isset($this->stringsforjs[$module][$identifier]) && $this->stringsforjs[$module][$identifier] != $string) {
468 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
469 "from lang file '$module'. Did you already ask for it with a different \$a?");
470 }
471 $this->stringsforjs[$module][$identifier] = $string;
472 }
473
747b85cb 474 /**
475 * Make an array of language strings available for JS
476 *
477 * This function calls the above function {@link string_for_js()} for each requested
478 * string in the $identifiers array that is passed to the argument for a single module
479 * passed in $module.
480 *
481 * <code>
482 * $PAGE->strings_for_js(Array('one', 'two', 'three'), 'mymod', Array('a', null, 3));
483 *
484 * // The above is identifical to calling
485 *
486 * $PAGE->string_for_js('one', 'mymod', 'a');
487 * $PAGE->string_for_js('two', 'mymod');
488 * $PAGE->string_for_js('three', 'mymod', 3);
489 * </code>
490 *
491 * @param array $identifiers An array of desired strings
492 * @param string $module The module to load for
493 * @param mixed $a This can either be a single variable that gets passed as extra
494 * information for every string or it can be an array of mixed data where the
495 * key for the data matches that of the identifier it is meant for.
496 *
497 */
498 public function strings_for_js($identifiers, $module, $a=NULL) {
499 foreach ($identifiers as $key => $identifier) {
500 if (is_array($a) && array_key_exists($key, $a)) {
501 $extra = $a[$key];
502 } else {
503 $extra = $a;
504 }
505 $this->string_for_js($identifier, $module, $extra);
506 }
507 }
508
b2330db6 509 /**
2c144fc3 510 * Make some data from PHP available to JavaScript code.
117bd748 511 *
2c144fc3 512 * For example, if you call
513 * <pre>
b2330db6 514 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
2c144fc3 515 * </pre>
b2330db6 516 * then in JavsScript mydata.name will be 'Moodle'.
517 *
518 * You cannot call this function more than once with the same variable name
519 * (if you try, it will throw an exception). Your code should prepare all the
520 * date you want, and then pass it to this method. There is no way to change
521 * the value associated with a particular variable later.
522 *
523 * @param string $variable the the name of the JavaScript variable to assign the data to.
524 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
525 * should be considered an experimental feature.
526 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
527 * so passing objects and arrays should work.
2c144fc3 528 * @return required_data_for_js The required_data_for_js object.
b2330db6 529 * This allows you to control when the link to the script is output by
2c144fc3 530 * calling methods like {@link required_data_for_js::asap()},
531 * {@link required_data_for_js::in_head()} or
8a0cb3a1 532 * {@link required_data_for_js::at_top_of_body()} methods.
b2330db6 533 */
534 public function data_for_js($variable, $data) {
535 if (isset($this->variablesinitialised[$variable])) {
536 throw new coding_exception("A variable called '" . $variable .
537 "' has already been passed ot JavaScript. You cannot overwrite it.");
538 }
539 $requirement = new required_data_for_js($this, $variable, $data);
540 $this->requiredjscode[] = $requirement;
541 $this->variablesinitialised[$variable] = 1;
542 return $requirement;
543 }
117bd748 544
647df7e3 545 /**
546 * Creates a YUI event handler.
547 *
548 * @param string $id The id of the DOM element that will be listening for the event
549 * @param string $event A valid DOM event (click, mousedown, change etc.)
550 * @param string $function The name of the function to call
551 * @param array $arguments An optional array of argument parameters to pass to the function
552 * @return required_event_handler The event_handler object
553 */
554 public function event_handler($id, $event, $function, $arguments=array()) {
f8065dd2 555 $requirement = new required_event_handler($this, $id, $event, $function, $arguments);
647df7e3 556 $this->requiredjscode[] = $requirement;
985d1d1d 557 $this->yui2_lib('event');
647df7e3 558 return $requirement;
559 }
b2330db6 560
561 /**
562 * Get the code for the linked resources that need to appear in a particular place.
563 * @param $when one of the WHEN_... constants.
564 * @return string the HTML that should be output in that place.
565 */
566 protected function get_linked_resources_code($when) {
567 $output = '';
9e43d2b3 568 foreach ($this->linkedrequirements as $requirement) {
b2330db6 569 if (!$requirement->is_done() && $requirement->get_when() == $when) {
570 $output .= $requirement->get_html();
571 $requirement->mark_done();
572 }
573 }
574 return $output;
575 }
576
577 /**
2c144fc3 578 * Get the inline JavaScript code that need to appear in a particular place.
b2330db6 579 * @param $when one of the WHEN_... constants.
580 * @return string the javascript that should be output in that place.
581 */
582 protected function get_javascript_code($when, $indent = '') {
583 $output = '';
584 foreach ($this->requiredjscode as $requirement) {
585 if (!$requirement->is_done() && $requirement->get_when() == $when) {
586 $output .= $indent . $requirement->get_js_code();
587 $requirement->mark_done();
588 }
589 }
590 return $output;
591 }
592
4c907141
PS
593 /**
594 * Returns basic YUI3 JS loading code.
985d1d1d 595 * YUI3 is using autoloading of both CSS and JS code.
4c907141 596 *
c724f835
PS
597 * Major benefit of this compared to standard js/csss loader is much improved
598 * caching, better browser cache utilisation, much fewer http requests.
599 *
4c907141
PS
600 * @return string
601 */
985d1d1d 602 protected function get_yui3lib_headcode() {
636365f8
PS
603 $code = $this->yui3loader->css() . $this->yui3loader->script();
604 // unfortunately yui loader does not produce xhtml strict code, so let's fix it for now
605 $code = str_replace('&amp;', '&', $code);
606 $code = str_replace('&', '&amp;', $code);
607 return $code;
985d1d1d
PS
608 }
609
610 /**
611 * Returns basic YUI2 JS loading code.
612 * It can be called manually at any time.
c724f835
PS
613 * If called manually the result needs to be output using echo().
614 *
615 * Major benefit of this compared to standard js loader is much improved
616 * caching, better browser cache utilisation, much fewer http requests.
617 *
618 * All YUI2 CSS is loaded automatically.
985d1d1d
PS
619 *
620 * @return string JS embedding code
621 */
622 public function get_yui2lib_code() {
c724f835
PS
623 global $CFG;
624
985d1d1d 625 if ($this->headdone) {
636365f8 626 $code = $this->yui2loader->script_embed();
985d1d1d 627 } else {
636365f8 628 $code = $this->yui2loader->script();
c724f835
PS
629 if ($this->yui2loader->combine) {
630 $skinurl = $this->yui2loader->comboBase . $CFG->yui2version . '/build/assets/skins/sam/skin.css';
631 } else {
632 $skinurl = $this->yui2loader->base . 'assets/skins/sam/skin.css';
633 }
634 // please note this is a temporary hack until we fully migrate to later YUI3 that has all the widgets
635 // we can not use moodle_url because the url fomrat for combo loader is "a bit" non-standard
636 $code .= "\n".'<link rel="stylesheet" type="text/css" href="'.$skinurl.'" />'."\n";
985d1d1d 637 }
636365f8
PS
638 $code = str_replace('&amp;', '&', $code);
639 $code = str_replace('&', '&amp;', $code);
640 return $code;
4c907141
PS
641 }
642
2212eb7a
PS
643 /**
644 * Returns html tags needed for inclusion of theme CSS
645 * @return string
646 */
647 protected function themecss_code() {
648 $code = '';
649 $firstthemelink = true;
650 foreach ($this->themestylesheets as $sheet) {
651 // this id is needed for YUI3 loader so that we may override
652 // YUI CSS in our themes
653 $id = $firstthemelink ? 'id="firstthemesheet"' : '';
654 $code .= '<link rel="stylesheet" type="text/css" href="' . $sheet . '" '.$id.'/>' . "\n";;
655 }
656 return $code;
657 }
658
b2330db6 659 /**
2c144fc3 660 * Generate any HTML that needs to go inside the <head> tag.
661 *
662 * Normally, this method is called automatically by the code that prints the
663 * <head> tag. You should not normally need to call it in your own code.
b2330db6 664 *
2c144fc3 665 * @return string the HTML code to to inside the <head> tag.
b2330db6 666 */
a6855934 667 public function get_head_code(moodle_page $page, core_renderer $output) {
945f19f7
PS
668 // note: the $page and $output are not stored here because it would
669 // create circular references in memory which prevents garbage collection
670 $this->setup_core_javascript($page, $output);
2212eb7a 671 // yui3 JS and CSS is always laoded first - it is cached in browser
985d1d1d 672 $output = $this->get_yui3lib_headcode();
c8870e68 673 // BC: load basic YUI2 for now, yui2 things should be laoded as yui3 modules
985d1d1d 674 $output .= $this->get_yui2lib_code();
c8870e68 675 // now theme CSS, it must be loaded before the
2212eb7a 676 $output .= $this->themecss_code();
4c907141 677 $output .= $this->get_linked_resources_code(self::WHEN_IN_HEAD);
b2330db6 678 $js = $this->get_javascript_code(self::WHEN_IN_HEAD);
679 $output .= ajax_generate_script_tag($js);
680 $this->headdone = true;
681 return $output;
682 }
683
684 /**
2c144fc3 685 * Generate any HTML that needs to go at the start of the <body> tag.
686 *
687 * Normally, this method is called automatically by the code that prints the
688 * <head> tag. You should not normally need to call it in your own code.
b2330db6 689 *
2c144fc3 690 * @return string the HTML code to go at the start of the <body> tag.
b2330db6 691 */
692 public function get_top_of_body_code() {
ac63efae 693 $output = '<div class="skiplinks">' . $this->get_linked_resources_code(self::WHEN_TOP_OF_BODY) . '</div>';
b2330db6 694 $js = "document.body.className += ' jsenabled';\n";
695 $js .= $this->get_javascript_code(self::WHEN_TOP_OF_BODY);
696 $output .= ajax_generate_script_tag($js);
697 $this->topofbodydone = true;
698 return $output;
699 }
700
701 /**
702 * Generate any HTML that needs to go at the end of the page.
703 *
2c144fc3 704 * Normally, this method is called automatically by the code that prints the
705 * page footer. You should not normally need to call it in your own code.
706 *
b2330db6 707 * @return string the HTML code to to at the end of the page.
708 */
709 public function get_end_code() {
9d897331 710 global $CFG;
c8870e68 711 // add missing YUI2 YUI - to be removed once we convert everything to YUI3!
985d1d1d 712 $output = $this->get_yui2lib_code();
c8870e68
PS
713
714 // set up global YUI3 loader object - this should contain all code needed by plugins
715 // note: in JavaScript just use "YUI(yui3loader).use('overlay', function(Y) { .... });"
716 $output .= $this->data_for_js('yui3loader', $this->json_yui3loader)->now();
717
718 // now print all the stuff that was added through ->requires
985d1d1d 719 $output .= $this->get_linked_resources_code(self::WHEN_AT_END);
b2330db6 720
cf615522 721 if (!empty($this->stringsforjs)) {
722 array_unshift($this->requiredjscode, new required_data_for_js($this, 'mstr', $this->stringsforjs));
723 }
724
b2330db6 725 $js = $this->get_javascript_code(self::WHEN_AT_END);
726
727 $ondomreadyjs = $this->get_javascript_code(self::WHEN_ON_DOM_READY, ' ');
9d897331 728
c8870e68
PS
729//TODO: do we really need the global "Y" defined in javasecript-static.js?
730// The problem is that we can not rely on it to be fully initialised
9d897331 731 $js .= <<<EOD
c8870e68
PS
732
733 Y = YUI(yui3loader).use('node-base', function(Y) {
99eaca9d 734 Y.on('domready', function() {
c8870e68 735 $ondomreadyjs
99eaca9d 736 });
c8870e68 737 // TODO: call user js functions from here so that they have the proper Y
9d897331 738 });
9d897331 739EOD;
b2330db6 740
741 $output .= ajax_generate_script_tag($js);
742
743 return $output;
744 }
745
746 /**
2c144fc3 747 * @return boolean Have we already output the code in the <head> tag?
b2330db6 748 */
749 public function is_head_done() {
750 return $this->headdone;
751 }
752
753 /**
2c144fc3 754 * @return boolean Have we already output the code at the start of the <body> tag?
b2330db6 755 */
756 public function is_top_of_body_done() {
757 return $this->topofbodydone;
758 }
759}
760
761
762/**
763 * This is the base class for all sorts of requirements. just to factor out some
764 * common code.
765 *
766 * @copyright 2009 Tim Hunt
767 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5c5418fe 768 * @since Moodle 2.0
b2330db6 769 */
770abstract class requirement_base {
771 protected $manager;
772 protected $when;
773 protected $done = false;
774
775 /**
776 * Constructor. Normally the class and its subclasses should not be created
777 * directly. Client code should create them via a page_requirements_manager
778 * method like ->js(...).
779 *
780 * @param page_requirements_manager $manager the page_requirements_manager we are associated with.
781 */
782 protected function __construct(page_requirements_manager $manager) {
783 $this->manager = $manager;
784 }
785
786 /**
787 * Mark that this requirement has been satisfied (that is, that the HTML
2c144fc3 788 * returned by {@link get_html()} has been output.
b2330db6 789 * @return boolean has this requirement been satisfied yet? That is, has
2c144fc3 790 * that the HTML returned by {@link get_html()} has been output already.
b2330db6 791 */
792 public function is_done() {
793 return $this->done;
794 }
795
796 /**
797 * Mark that this requirement has been satisfied (that is, that the HTML
2c144fc3 798 * returned by {@link get_html()} has been output.
b2330db6 799 */
800 public function mark_done() {
801 $this->done = true;
802 }
803
804 /**
805 * Where on the page the HTML this requirement is meant to go.
2c144fc3 806 * @return integer One of the {@link page_requirements_manager}::WHEN_... constants.
b2330db6 807 */
808 public function get_when() {
809 return $this->when;
810 }
811}
812
813/**
814 * This class represents something that must be output somewhere in the HTML.
815 *
816 * Examples include links to JavaScript or CSS files. However, it should not
817 * necessarily be output immediately, we may have to wait for an appropriate time.
818 *
819 * @copyright 2009 Tim Hunt
820 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5c5418fe 821 * @since Moodle 2.0
b2330db6 822 */
823abstract class linked_requirement extends requirement_base {
824 protected $url;
825
826 /**
827 * Constructor. Normally the class and its subclasses should not be created
828 * directly. Client code should create them via a page_requirements_manager
829 * method like ->js(...).
830 *
831 * @param page_requirements_manager $manager the page_requirements_manager we are associated with.
832 * @param string $url The URL of the thing we are linking to.
833 */
834 protected function __construct(page_requirements_manager $manager, $url) {
835 parent::__construct($manager);
836 $this->url = $url;
837 }
838
839 /**
840 * @return string the HTML needed to satisfy this requirement.
841 */
842 abstract public function get_html();
843}
844
845
846/**
2c144fc3 847 * A subclass of {@link linked_requirement} to represent a requried JavaScript file.
b2330db6 848 *
849 * You should not create instances of this class directly. Instead you should
2c144fc3 850 * work with a {@link page_requirements_manager} - and probably the only
b2330db6 851 * page_requirements_manager you will ever need is the one at $PAGE->requires.
852 *
2c144fc3 853 * The methods {@link asap()}, {@link in_head()} and {@link at_top_of_body()}
854 * are indented to be used as a fluid API, so you can say things like
b2330db6 855 * $PAGE->requires->js('mod/mymod/script.js')->in_head();
856 *
857 * However, by default JavaScript files are included at the end of the HTML.
858 * This is recommended practice because it means that the web browser will only
859 * start loading the javascript files after the rest of the page is loaded, and
860 * that gives the best performance for users.
861 *
862 * @copyright 2009 Tim Hunt
863 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5c5418fe 864 * @since Moodle 2.0
b2330db6 865 */
866class required_js extends linked_requirement {
867 /**
868 * Constructor. Normally instances of this class should not be created
869 * directly. Client code should create them via the page_requirements_manager
2c144fc3 870 * method {@link page_requirements_manager::js()}.
b2330db6 871 *
872 * @param page_requirements_manager $manager the page_requirements_manager we are associated with.
873 * @param string $url The URL of the JavaScript file we are linking to.
874 */
875 public function __construct(page_requirements_manager $manager, $url) {
876 parent::__construct($manager, $url);
877 $this->when = page_requirements_manager::WHEN_AT_END;
878 }
879
880 public function get_html() {
cf615522 881 return ajax_get_link_to_script($this->url);
b2330db6 882 }
883
884 /**
885 * Indicate that the link to this JavaScript file should be output as soon as
886 * possible. That is, if this requirement has already been output, this method
2c144fc3 887 * does nothing. Otherwise, if the <head> tag has not yet been printed, the link
888 * to this script will be put in <head>. Otherwise, this method returns a
b2330db6 889 * fragment of HTML that the caller is responsible for outputting as soon as
890 * possible. In fact, it is recommended that you only call this function from
891 * an echo statement, like:
2c144fc3 892 * <pre>
b2330db6 893 * echo $PAGE->requires->js(...)->asap();
2c144fc3 894 * </pre>
b2330db6 895 *
896 * @return string The HTML required to include this JavaScript file. The caller
897 * is responsible for outputting this HTML promptly.
898 */
899 public function asap() {
b2330db6 900 if (!$this->manager->is_head_done()) {
901 $this->in_head();
902 return '';
4262a2f8 903 } else {
904 return $this->now();
905 }
906 }
907
908 /**
909 * Return the required JavaScript immediately, so it can be included in some
910 * HTML that is being built.
911 *
912 * This is not really recommeneded. But is necessary in some legacy code that
913 * includes a .js files that does document.write.
914 *
915 * @return string The HTML for the script tag. The caller
916 * is responsible for making sure it is output.
917 */
918 public function now() {
919 if ($this->is_done()) {
920 return '';
b2330db6 921 }
bfbbfdeb 922 $output = $this->get_html();
b2330db6 923 $this->mark_done();
bfbbfdeb 924 return $output;
b2330db6 925 }
926
927 /**
928 * Indicate that the link to this JavaScript file should be output in the
2c144fc3 929 * <head> section of the HTML. If it too late for this request to be
b2330db6 930 * satisfied, an exception is thrown.
931 */
932 public function in_head() {
933 if ($this->is_done() || $this->when <= page_requirements_manager::WHEN_IN_HEAD) {
934 return;
935 }
936 if ($this->manager->is_head_done()) {
937 throw new coding_exception('Too late to ask for a JavaScript file to be linked to from &lt;head>.');
938 }
939 $this->when = page_requirements_manager::WHEN_IN_HEAD;
940 }
941
942 /**
943 * Indicate that the link to this JavaScript file should be output at the top
2c144fc3 944 * of the <body> section of the HTML. If it too late for this request to be
b2330db6 945 * satisfied, an exception is thrown.
946 */
947 public function at_top_of_body() {
948 if ($this->is_done() || $this->when <= page_requirements_manager::WHEN_TOP_OF_BODY) {
949 return;
950 }
951 if ($this->manager->is_top_of_body_done()) {
952 throw new coding_exception('Too late to ask for a JavaScript file to be linked to from the top of &lt;body>.');
953 }
954 $this->when = page_requirements_manager::WHEN_TOP_OF_BODY;
955 }
956}
957
b2330db6 958
959/**
2c144fc3 960 * A subclass of {@link linked_requirement} to represent a required CSS file.
961 * Of course, all links to CSS files must go in the <head> section of the HTML.
b2330db6 962 *
963 * @copyright 2009 Tim Hunt
964 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5c5418fe 965 * @since Moodle 2.0
b2330db6 966 */
967class required_css extends linked_requirement {
968 /**
2c144fc3 969 * Constructor. Normally instances of this class should not be created directly.
970 * Client code should create them via the page_requirements_manager
971 * method {@link page_requirements_manager::css()}
b2330db6 972 *
973 * @param page_requirements_manager $manager the page_requirements_manager we are associated with.
974 * @param string $url The URL of the CSS file we are linking to.
975 */
976 public function __construct(page_requirements_manager $manager, $url) {
977 parent::__construct($manager, $url);
978 $this->when = page_requirements_manager::WHEN_IN_HEAD;
979 }
980
981 public function get_html() {
982 return '<link rel="stylesheet" type="text/css" href="' . $this->url . '" />' . "\n";;
983 }
984}
985
986
987/**
2c144fc3 988 * A subclass of {@link linked_requirement} to represent a skip link.
b2330db6 989 * A skip link is a concept from accessibility. You have some links like
990 * 'Skip to main content' linking to an #maincontent anchor, at the start of the
2c144fc3 991 * <body> tag, so that users using assistive technologies like screen readers
b2330db6 992 * can easily get to the main content without having to work their way through
993 * any navigation, blocks, etc. that comes before it in the HTML.
994 *
995 * @copyright 2009 Tim Hunt
996 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5c5418fe 997 * @since Moodle 2.0
b2330db6 998 */
999class required_skip_link extends linked_requirement {
1000 protected $linktext;
1001
1002 /**
2c144fc3 1003 * Constructor. Normally instances of this class should not be created directly.
1004 * Client code should create them via the page_requirements_manager
f44b10ed 1005 * method {@link page_requirements_manager::yui2_lib()}.
b2330db6 1006 *
1007 * @param page_requirements_manager $manager the page_requirements_manager we are associated with.
1008 * @param string $target the name of the anchor in the page we are linking to.
1009 * @param string $linktext the test to use for the link.
1010 */
1011 public function __construct(page_requirements_manager $manager, $target, $linktext) {
1012 parent::__construct($manager, $target);
1013 $this->when = page_requirements_manager::WHEN_TOP_OF_BODY;
1014 $this->linktext = $linktext;
1015 }
1016
1017 public function get_html() {
ac63efae 1018 return '<a class="skip" href="#' . $this->url . '">' . $this->linktext . "</a>\n";
b2330db6 1019 }
1020}
1021
1022
1023/**
1024 * This is the base class for requirements that are JavaScript code.
1025 *
1026 * @copyright 2009 Tim Hunt
1027 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5c5418fe 1028 * @since Moodle 2.0
b2330db6 1029 */
1030abstract class required_js_code extends requirement_base {
1031
1032 /**
2c144fc3 1033 * Constructor.
b2330db6 1034 * @param page_requirements_manager $manager the page_requirements_manager we are associated with.
1035 */
1036 protected function __construct(page_requirements_manager $manager) {
1037 parent::__construct($manager);
1038 $this->when = page_requirements_manager::WHEN_AT_END;
1039 }
1040
1041 /**
1042 * @return string the JavaScript code needed to satisfy this requirement.
1043 */
1044 abstract public function get_js_code();
1045
1046 /**
1047 * Indicate that the link to this JavaScript file should be output as soon as
1048 * possible. That is, if this requirement has already been output, this method
2c144fc3 1049 * does nothing. Otherwise, if the <head> tag has not yet been printed, the link
1050 * to this script will be put in <head>. Otherwise, this method returns a
b2330db6 1051 * fragment of HTML that the caller is responsible for outputting as soon as
1052 * possible. In fact, it is recommended that you only call this function from
1053 * an echo statement, like:
2c144fc3 1054 * <pre>
b2330db6 1055 * echo $PAGE->requires->js(...)->asap();
2c144fc3 1056 * </pre>
b2330db6 1057 *
c966c8a2 1058 * @return string The HTML for the script tag. The caller
b2330db6 1059 * is responsible for outputting this HTML promptly.
1060 */
1061 public function asap() {
c966c8a2 1062 if ($this->manager->is_head_done()) {
1063 return $this->now();
1064 } else {
b2330db6 1065 $this->in_head();
1066 return '';
1067 }
c966c8a2 1068 }
1069
1070 /**
1071 * Return the required JavaScript immediately, so it can be included in some
1072 * HTML that is being built.
1073 * @return string The HTML for the script tag. The caller
1074 * is responsible for making sure it is output.
1075 */
1076 public function now() {
1077 if ($this->is_done()) {
1078 return '';
1079 }
b2330db6 1080 $js = $this->get_js_code();
1081 $output = ajax_generate_script_tag($js);
1082 $this->mark_done();
1083 return $output;
1084 }
1085
1086 /**
1087 * Indicate that the link to this JavaScript file should be output in the
2c144fc3 1088 * <head> section of the HTML. If it too late for this request to be
b2330db6 1089 * satisfied, an exception is thrown.
1090 */
1091 public function in_head() {
1092 if ($this->is_done() || $this->when <= page_requirements_manager::WHEN_IN_HEAD) {
1093 return;
1094 }
1095 if ($this->manager->is_head_done()) {
1096 throw new coding_exception('Too late to ask for some JavaScript code to be output in &lt;head>.');
1097 }
1098 $this->when = page_requirements_manager::WHEN_IN_HEAD;
1099 }
1100
1101 /**
1102 * Indicate that the link to this JavaScript file should be output at the top
2c144fc3 1103 * of the <body> section of the HTML. If it too late for this request to be
b2330db6 1104 * satisfied, an exception is thrown.
1105 */
1106 public function at_top_of_body() {
1107 if ($this->is_done() || $this->when <= page_requirements_manager::WHEN_TOP_OF_BODY) {
1108 return;
1109 }
1110 if ($this->manager->is_top_of_body_done()) {
1111 throw new coding_exception('Too late to ask for some JavaScript code to be output at the top of &lt;body>.');
1112 }
1113 $this->when = page_requirements_manager::WHEN_TOP_OF_BODY;
1114 }
1115}
1116
1117
1118/**
1119 * This class represents a JavaScript function that must be called from the HTML
1120 * page. By default the call will be made at the end of the page, but you can
2c144fc3 1121 * chage that using the {@link asap()}, {@link in_head()}, etc. methods.
b2330db6 1122 *
1123 * @copyright 2009 Tim Hunt
1124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5c5418fe 1125 * @since Moodle 2.0
b2330db6 1126 */
1127class required_js_function_call extends required_js_code {
1128 protected $function;
1129 protected $arguments;
cf615522 1130 protected $delay = 0;
b2330db6 1131
1132 /**
2c144fc3 1133 * Constructor. Normally instances of this class should not be created directly.
1134 * Client code should create them via the page_requirements_manager
1135 * method {@link page_requirements_manager::js_function_call()}.
b2330db6 1136 *
1137 * @param page_requirements_manager $manager the page_requirements_manager we are associated with.
1138 * @param string $function the name of the JavaScritp function to call.
1139 * Can be a compound name like 'YAHOO.util.Event.addListener'.
1140 * @param array $arguments and array of arguments to be passed to the function.
1141 * When generating the function call, this will be escaped using json_encode,
1142 * so passing objects and arrays should work.
1143 */
1144 public function __construct(page_requirements_manager $manager, $function, $arguments) {
1145 parent::__construct($manager);
1146 $this->function = $function;
1147 $this->arguments = $arguments;
1148 }
1149
1150 public function get_js_code() {
1151 $quotedargs = array();
1152 foreach ($this->arguments as $arg) {
1153 $quotedargs[] = json_encode($arg);
1154 }
cf615522 1155 $js = $this->function . '(' . implode(', ', $quotedargs) . ');';
1156 if ($this->delay) {
1157 $js = 'setTimeout(function() { ' . $js . ' }, ' . ($this->delay * 1000) . ');';
1158 }
1159 return $js . "\n";
b2330db6 1160 }
1161
1162 /**
1163 * Indicate that this function should be called in YUI's onDomReady event.
1164 *
1165 * Not that this is probably not necessary most of the time. Just having the
1166 * function call at the end of the HTML should normally be sufficient.
1167 */
1168 public function on_dom_ready() {
1169 if ($this->is_done() || $this->when < page_requirements_manager::WHEN_AT_END) {
1170 return;
1171 }
f44b10ed 1172 $this->manager->yui2_lib('event');
b2330db6 1173 $this->when = page_requirements_manager::WHEN_ON_DOM_READY;
1174 }
cf615522 1175
1176 /**
1177 * Indicate that this function should be called a certain number of seconds
1178 * after the page has finished loading. (More exactly, a number of seconds
1179 * after the onDomReady event fires.)
1180 *
1181 * @param integer $seconds the number of seconds delay.
1182 */
1183 public function after_delay($seconds) {
1184 if ($seconds) {
1185 $this->on_dom_ready();
1186 }
1187 $this->delay = $seconds;
1188 }
b2330db6 1189}
1190
1191
1192/**
1193 * This class represents some data from PHP that needs to be made available in a
1194 * global JavaScript variable. By default the data will be output at the end of
2c144fc3 1195 * the page, but you can chage that using the {@link asap()}, {@link in_head()}, etc. methods.
b2330db6 1196 *
1197 * @copyright 2009 Tim Hunt
1198 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5c5418fe 1199 * @since Moodle 2.0
b2330db6 1200 */
1201class required_data_for_js extends required_js_code {
1202 protected $variable;
1203 protected $data;
1204
1205 /**
2c144fc3 1206 * Constructor. Normally the class and its subclasses should not be created directly.
1207 * Client code should create them via the page_requirements_manager
1208 * method {@link page_requirements_manager::data_for_js()}.
b2330db6 1209 *
1210 * @param page_requirements_manager $manager the page_requirements_manager we are associated with.
1211 * @param string $variable the the name of the JavaScript variable to assign the data to.
1212 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1213 * should be considered an experimental feature.
1214 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1215 * so passing objects and arrays should work.
1216 */
1217 public function __construct(page_requirements_manager $manager, $variable, $data) {
1218 parent::__construct($manager);
1219 $this->variable = $variable;
1220 $this->data = json_encode($data);
1221 // json_encode immediately, so that if $data is an object (and therefore was
1222 // passed in by reference) we get the data at the time the call was made, and
1223 // not whatever the data happened to be when this is output.
1224 }
1225
1226 public function get_js_code() {
1227 $prefix = 'var ';
1228 if (strpos($this->variable, '.') || strpos($this->variable, '[')) {
1229 $prefix = '';
1230 }
1231 return $prefix . $this->variable . ' = ' . $this->data . ";\n";
1232 }
1233}
1234
647df7e3 1235/**
117bd748 1236 * This class represents a Javascript event handler, listening for a
647df7e3 1237 * specific Event to occur on a DOM element identified by a given id.
117bd748 1238 * By default the data will be output at the end of the page, but you
647df7e3 1239 * can change that using the {@link asap()}, {@link in_head()}, etc. methods.
1240 *
1241 * @copyright 2009 Nicolas Connault
1242 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1243 * @since Moodle 2.0
1244 */
1245class required_event_handler extends required_js_code {
1246 protected $id;
1247 protected $event;
1248 protected $function;
1249 protected $args = array();
1250
1251 /**
1252 * Constructor. Normally the class and its subclasses should not be created directly.
1253 * Client code should create them via the page_requirements_manager
1254 * method {@link page_requirements_manager::data_for_js()}.
1255 *
1256 * @param page_requirements_manager $manager the page_requirements_manager we are associated with.
1257 * @param string $id The id of the DOM element that will be listening for the event
1258 * @param string $event A valid DOM event (click, mousedown, change etc.)
1259 * @param string $function The name of the function to call
1260 * @param array $arguments An optional array of argument parameters to pass to the function
1261 */
1262 public function __construct(page_requirements_manager $manager, $id, $event, $function, $args=array()) {
1263 parent::__construct($manager);
1264 $this->id = $id;
1265 $this->event = $event;
1266 $this->function = $function;
1267 $this->args = $args;
1268 }
1269
1270 public function get_js_code() {
f8065dd2 1271 $output = "YAHOO.util.Event.addListener('$this->id', '$this->event', $this->function";
647df7e3 1272 if (!empty($this->args)) {
1273 $output .= ', ' . json_encode($this->args);
1274 }
1275 return $output . ");\n";
1276 }
1277}
b2330db6 1278
1279/**
1280 * Generate a script tag containing the the specified code.
1281 *
1282 * @param string $js the JavaScript code
1283 * @return string HTML, the code wrapped in <script> tags.
1284 */
1285function ajax_generate_script_tag($js) {
cf615522 1286 if ($js) {
1287 return '<script type="text/javascript">' . "\n//<![CDATA[\n" .
1288 $js . "//]]>\n</script>\n";
1289 } else {
1290 return '';
1291 }
b2330db6 1292}
1293
1294
f72f94a2 1295/**
cf615522 1296 * Return the HTML required to link to a JavaScript file.
1297 * @param $url the URL of a JavaScript file.
1298 * @return string the required HTML.
f72f94a2 1299 */
cf615522 1300function ajax_get_link_to_script($url) {
1301 return '<script type="text/javascript" src="' . $url . '"></script>' . "\n";
9bb74178 1302}
88c5092a 1303
1304
1305/**
1306 * Returns whether ajax is enabled/allowed or not.
1307 */
c2a9fc91 1308function ajaxenabled($browsers = array()) {
88c5092a 1309
1310 global $CFG, $USER;
483f3067 1311
c2a9fc91 1312 if (!empty($browsers)) {
1313 $valid = false;
1314 foreach ($browsers as $brand => $version) {
1315 if (check_browser_version($brand, $version)) {
1316 $valid = true;
483f3067 1317 }
c2a9fc91 1318 }
483f3067 1319
c2a9fc91 1320 if (!$valid) {
1321 return false;
1322 }
1323 }
483f3067 1324
d499142e 1325 $ie = check_browser_version('MSIE', 6.0);
1326 $ff = check_browser_version('Gecko', 20051106);
1327 $op = check_browser_version('Opera', 9.0);
1328 $sa = check_browser_version('Safari', 412);
1329
1330 if (!$ie && !$ff && !$op && !$sa) {
1331 /** @see http://en.wikipedia.org/wiki/User_agent */
483f3067 1332 // Gecko build 20051107 is what is in Firefox 1.5.
88c5092a 1333 // We still have issues with AJAX in other browsers.
1334 return false;
1335 }
1336
2f11bfc0 1337 if (!empty($CFG->enableajax) && (!empty($USER->ajax) || !isloggedin())) {
88c5092a 1338 return true;
1339 } else {
1340 return false;
1341 }
1342}
9bb74178 1343
35b974da 1344
1345/**
2469f7ea 1346 * Used to create view of document to be passed to JavaScript on pageload.
1347 * We use this class to pass data from PHP to JavaScript.
35b974da 1348 */
4fc45e1d 1349class jsportal {
9bb74178 1350
0a0bb380 1351 var $currentblocksection = null;
9bb74178 1352 var $blocks = array();
0a0bb380 1353
9bb74178 1354
35b974da 1355 /**
1356 * Takes id of block and adds it
1357 */
2469f7ea 1358 function block_add($id, $hidden=false){
0a0bb380 1359 $hidden_binary = 0;
9bb74178 1360
1361 if ($hidden) {
1362 $hidden_binary = 1;
1363 }
35b974da 1364 $this->blocks[count($this->blocks)] = array($this->currentblocksection, $id, $hidden_binary);
0a0bb380 1365 }
9bb74178 1366
1367
2469f7ea 1368 /**
1369 * Prints the JavaScript code needed to set up AJAX for the course.
1370 */
1371 function print_javascript($courseid, $return=false) {
ddc66060 1372 global $CFG, $USER, $OUTPUT, $COURSE;
9bb74178 1373
d4df8fdc 1374 $blocksoutput = $output = '';
35b974da 1375 for ($i=0; $i<count($this->blocks); $i++) {
2469f7ea 1376 $blocksoutput .= "['".$this->blocks[$i][0]."',
1377 '".$this->blocks[$i][1]."',
1378 '".$this->blocks[$i][2]."']";
1379
1380 if ($i != (count($this->blocks) - 1)) {
35b974da 1381 $blocksoutput .= ',';
9bb74178 1382 }
1383 }
32f0b38a 1384 $output .= "<script type=\"text/javascript\">\n";
72d28452 1385 $output .= " main.portal.id = ".$courseid.";\n";
2469f7ea 1386 $output .= " main.portal.blocks = new Array(".$blocksoutput.");\n";
ddc66060 1387 $output .= " main.portal.strings['courseformat']='".$COURSE->format."';\n";
2469f7ea 1388 $output .= " main.portal.strings['wwwroot']='".$CFG->wwwroot."';\n";
f8eaeffa 1389 $output .= " main.portal.strings['marker']='".get_string('markthistopic', '', '_var_')."';\n";
1390 $output .= " main.portal.strings['marked']='".get_string('markedthistopic', '', '_var_')."';\n";
b1b4c2d7 1391 $output .= " main.portal.numsections = ".$COURSE->numsections.";\n";
f8eaeffa 1392 $output .= " main.portal.strings['hide']='".get_string('hide')."';\n";
1393 $output .= " main.portal.strings['hidesection']='".get_string('hidesection', '', '_var_')."';\n";
1394 $output .= " main.portal.strings['show']='".get_string('show')."';\n";
1395 $output .= " main.portal.strings['delete']='".get_string('delete')."';\n";
d2a11d46 1396 $output .= " main.portal.strings['move']='".get_string('move')."';\n";
f8eaeffa 1397 $output .= " main.portal.strings['movesection']='".get_string('movesection', '', '_var_')."';\n";
d2a11d46 1398 $output .= " main.portal.strings['moveleft']='".get_string('moveleft')."';\n";
1399 $output .= " main.portal.strings['moveright']='".get_string('moveright')."';\n";
4fc45e1d 1400 $output .= " main.portal.strings['update']='".get_string('update')."';\n";
d2a11d46 1401 $output .= " main.portal.strings['groupsnone']='".get_string('groupsnone')."';\n";
1402 $output .= " main.portal.strings['groupsseparate']='".get_string('groupsseparate')."';\n";
1403 $output .= " main.portal.strings['groupsvisible']='".get_string('groupsvisible')."';\n";
1404 $output .= " main.portal.strings['clicktochange']='".get_string('clicktochange')."';\n";
2469f7ea 1405 $output .= " main.portal.strings['deletecheck']='".get_string('deletecheck','','_var_')."';\n";
1406 $output .= " main.portal.strings['resource']='".get_string('resource')."';\n";
1407 $output .= " main.portal.strings['activity']='".get_string('activity')."';\n";
d4a1fcaf 1408 $output .= " main.portal.strings['sesskey']='".sesskey()."';\n";
b5d0cafc
PS
1409 $output .= " main.portal.icons['spacerimg']='".$OUTPUT->pix_url('spaces')."';\n";
1410 $output .= " main.portal.icons['marker']='".$OUTPUT->pix_url('i/marker')."';\n";
1411 $output .= " main.portal.icons['ihide']='".$OUTPUT->pix_url('i/hide')."';\n";
1412 $output .= " main.portal.icons['move_2d']='".$OUTPUT->pix_url('i/move_2d')."';\n";
1413 $output .= " main.portal.icons['show']='".$OUTPUT->pix_url('t/show')."';\n";
1414 $output .= " main.portal.icons['hide']='".$OUTPUT->pix_url('t/hide')."';\n";
1415 $output .= " main.portal.icons['delete']='".$OUTPUT->pix_url('t/delete')."';\n";
1416 $output .= " main.portal.icons['groupn']='".$OUTPUT->pix_url('t/groupn')."';\n";
1417 $output .= " main.portal.icons['groups']='".$OUTPUT->pix_url('t/groups')."';\n";
1418 $output .= " main.portal.icons['groupv']='".$OUTPUT->pix_url('t/groupv')."';\n";
ddedf979 1419 if (right_to_left()) {
b5d0cafc
PS
1420 $output .= " main.portal.icons['backwards']='".$OUTPUT->pix_url('t/right')."';\n";
1421 $output .= " main.portal.icons['forwards']='".$OUTPUT->pix_url('t/left')."';\n";
ddedf979 1422 } else {
b5d0cafc
PS
1423 $output .= " main.portal.icons['backwards']='".$OUTPUT->pix_url('t/left')."';\n";
1424 $output .= " main.portal.icons['forwards']='".$OUTPUT->pix_url('t/right')."';\n";
ddedf979 1425 }
1426
2469f7ea 1427 $output .= " onloadobj.load();\n";
4fc45e1d 1428 $output .= " main.process_blocks();\n";
35b974da 1429 $output .= "</script>";
2469f7ea 1430 if ($return) {
1431 return $output;
1432 } else {
1433 echo $output;
1434 }
0a0bb380 1435 }
9bb74178 1436
2469f7ea 1437}