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