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