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