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