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