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