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