MDL-21240 getting rid of one asap
[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;
d96d8f03 54 const WHEN_IN_YUI = 25;
b2330db6 55 const WHEN_ON_DOM_READY = 30;
56
9e43d2b3 57 protected $linkedrequirements = array();
b2330db6 58 protected $stringsforjs = array();
59 protected $requiredjscode = array();
60
c0467479
PS
61 /**
62 * Theme sheets, initialised only from core_renderer
63 * @var array of moodle_url
64 */
65 protected $css_theme_urls = array();
66 /**
67 * List of custom theme sheets, these are strongly discouraged!
68 * Useful mostly only for CSS submitted by teachers that is not part of the theme.
69 * @var array of moodle_url
70 */
71 protected $css_urls = array();
2212eb7a 72
b2330db6 73 protected $variablesinitialised = array('mstr' => 1); // 'mstr' is special. See string_for_js.
74
75 protected $headdone = false;
76 protected $topofbodydone = false;
77
945f19f7 78 /** YUI PHPLoader instance responsible for YUI2 loading from PHP only */
985d1d1d 79 protected $yui2loader;
945f19f7
PS
80 /** YUI PHPLoader instance responsible for YUI3 loading from PHP only */
81 protected $yui3loader;
82 /** YUI PHPLoader instance responsible for YUI3 loading from javascript */
83 protected $json_yui3loader;
4c907141
PS
84
85 /**
86 * Page requirements constructor.
87 */
88 public function __construct() {
89 global $CFG;
945f19f7 90
4c907141
PS
91 require_once("$CFG->libdir/yui/phploader/phploader/loader.php");
92
93 $this->yui3loader = new YAHOO_util_Loader($CFG->yui3version);
985d1d1d 94 $this->yui2loader = new YAHOO_util_Loader($CFG->yui2version);
4c907141
PS
95
96 // set up some loader options
4c907141
PS
97 if (debugging('', DEBUG_DEVELOPER)) {
98 $this->yui3loader->filter = YUI_DEBUG; // alternatively we could use just YUI_RAW here
985d1d1d 99 $this->yui2loader->filter = YUI_DEBUG; // alternatively we could use just YUI_RAW here
4c907141
PS
100 } else {
101 $this->yui3loader->filter = null;
985d1d1d 102 $this->yui2loader->filter = null;
95fbe49b 103 }
4c907141
PS
104 if (!empty($CFG->useexternalyui)) {
105 $this->yui3loader->base = 'http://yui.yahooapis.com/' . $CFG->yui3version . '/build/';
985d1d1d 106 $this->yui2loader->base = 'http://yui.yahooapis.com/' . $CFG->yui2version . '/build/';
945f19f7
PS
107 $this->yui3loader->comboBase = 'http://yui.yahooapis.com/combo?';
108 $this->yui2loader->comboBase = 'http://yui.yahooapis.com/combo?';
4c907141 109 } else {
aa42314d
PS
110 $this->yui3loader->base = $CFG->httpswwwroot . '/lib/yui/'. $CFG->yui3version . '/build/';
111 $this->yui2loader->base = $CFG->httpswwwroot . '/lib/yui/'. $CFG->yui2version . '/build/';
945f19f7
PS
112 $this->yui3loader->comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php?';
113 $this->yui2loader->comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php?';
4c907141
PS
114 }
115
945f19f7 116 // enable combo loader? this significantly helps with caching and performance!
aa42314d
PS
117 $this->yui3loader->combine = !empty($CFG->yuicomboloading);
118 $this->yui2loader->combine = !empty($CFG->yuicomboloading);
945f19f7 119
2212eb7a 120 // set up JS YUI loader helper object
945f19f7 121 $this->json_yui3loader = new stdClass();
2212eb7a
PS
122 $this->json_yui3loader->base = $this->yui3loader->base;
123 $this->json_yui3loader->comboBase = $this->yui3loader->comboBase;
124 $this->json_yui3loader->combine = $this->yui3loader->combine;
125 $this->json_yui3loader->filter = ($this->yui3loader->filter == YUI_DEBUG) ? 'debug' : '';
126 $this->json_yui3loader->insertBefore = 'firstthemesheet';
127 $this->json_yui3loader->modules = array();
c8870e68
PS
128 $this->add_yui2_modules(); // adds loading info for YUI2
129 }
130
131 /**
132 * This method adds yui2 modules into the yui3 JS loader-
133 * @return void
134 */
135 protected function add_yui2_modules() {
136 //note: this function is definitely not perfect, because
137 // it adds tons of markup into each page, but it can be
138 // abstracted into separate JS file with proper headers
139 global $CFG;
140
141 $GLOBALS['yui_current'] = array();
142 require($CFG->libdir.'/yui/phploader/lib/meta/config_'.$CFG->yui2version.'.php');
143 $info = $GLOBALS['yui_current'];
144 unset($GLOBALS['yui_current']);
145
146 if (empty($CFG->yuicomboloading)) {
147 $urlbase = $this->yui2loader->base;
148 } else {
149 $urlbase = $this->yui2loader->comboBase.$CFG->yui2version.'/build/';
150 }
151
152 $modules = array();
153 $ignored = array(); // list of CSS modules that are not needed
154 foreach ($info['moduleInfo'] as $name => $module) {
155 if ($module['type'] === 'css') {
156 $ignored[$name] = true;
157 } else {
158 $modules['yui2-'.$name] = $module;
159 }
160 }
161 foreach ($modules as $name=>$module) {
162 $module['fullpath'] = $urlbase.$module['path']; // fix path to point to correct location
163 unset($module['path']);
164 foreach(array('requires', 'optional', 'supersedes') as $fixme) {
165 if (!empty($module[$fixme])) {
166 $fixed = false;
167 foreach ($module[$fixme] as $key=>$dep) {
168 if (isset($ignored[$dep])) {
169 unset($module[$fixme][$key]);
170 $fixed = true;
171 } else {
172 $module[$fixme][$key] = 'yui2-'.$dep;
173 }
174 }
175 if ($fixed) {
176 $module[$fixme] = array_merge($module[$fixme]); // fix keys
177 }
178 }
179 }
180 $this->json_yui3loader->modules[$name] = $module;
181 }
945f19f7
PS
182 }
183
184 /**
185 * Initialise with the bits of JavaScript that every Moodle page should have.
186 *
187 * @param moodle_page $page
188 * @param core_renderer $output
189 */
77774f6a 190 protected function init_requirements_data(moodle_page $page, core_renderer $output) {
945f19f7
PS
191 global $CFG;
192
193 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
194 // Otherwise, in some situations, users will get warnings about insecure content
195 // on sercure pages from their web browser.
196
197 //TODO: problem here is we may need this in some included JS - move this somehow to the very beginning
198 // right after the YUI loading
199 $config = array(
200 'wwwroot' => $CFG->httpswwwroot, // Yes, really. See above.
201 'sesskey' => sesskey(),
b9bc2019 202 'loadingicon' => $output->pix_url('i/loading_small', 'moodle')->out(false),
945f19f7
PS
203 'themerev' => theme_get_revision(),
204 'theme' => $page->theme->name,
205 'yui2loaderBase' => $this->yui2loader->base,
206 'yui3loaderBase' => $this->yui3loader->base,
207 'yui2loaderComboBase' => $this->yui2loader->comboBase,
208 'yui3loaderComboBase' => $this->yui3loader->comboBase,
209 'yuicombine' => (int)$this->yui3loader->combine,
210 'yuifilter' => debugging('', DEBUG_DEVELOPER) ? 'debug' : '',
211
212 );
213 if (debugging('', DEBUG_DEVELOPER)) {
214 $config['developerdebug'] = true;
215 }
216 $this->data_for_js('moodle_cfg', $config)->in_head();
217
945f19f7
PS
218 if (debugging('', DEBUG_DEVELOPER)) {
219 $this->yui2_lib('logger');
220 }
221
222 // YUI3 init code
223 $this->yui3_lib(array('cssreset', 'cssbase', 'cssfonts', 'cssgrids')); // full CSS reset
224 $this->yui3_lib(array('yui', 'loader')); // allows autoloading of everything else
225
226
227 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
228
229 // Note that, as a short-cut, the code
230 // $js = "document.body.className += ' jsenabled';\n";
231 // is hard-coded in {@link page_requirements_manager::get_top_of_body_code)
2574fae6
PS
232 $this->yui2_lib('dom'); // needs to be migrated to YUI3 before we release 2.0
233 $this->yui2_lib('container'); // needs to be migrated to YUI3 before we release 2.0
234 $this->yui2_lib('connection'); // needs to be migrated to YUI3 before we release 2.0
99eaca9d
DC
235 // File Picker use this module loading YUI2 widgets
236 $this->yui2_lib('yuiloader'); // needs to be migrated to YUI3 before we release 2.0
c8870e68 237 $this->js_module('filepicker'); // should be migrated elsewhere before 2.0
2574fae6 238
945f19f7
PS
239 $this->string_for_js('confirmation', 'admin');
240 $this->string_for_js('cancel', 'moodle');
241 $this->string_for_js('yes', 'moodle');
242 $this->js_function_call('init_help_icons');
4c907141
PS
243 }
244
b2330db6 245 /**
2c144fc3 246 * Ensure that the specified JavaScript file is linked to from this page.
247 *
248 * By default the link is put at the end of the page, since this gives best page-load performance.
b2330db6 249 *
250 * Even if a particular script is requested more than once, it will only be linked
251 * to once.
252 *
253 * @param $jsfile The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
8f298131 254 * For example '/mod/mymod/customscripts.js';
b2330db6 255 * @param boolean $fullurl This parameter is intended for internal use only.
cf615522 256 * However, in exceptional circumstances you may wish to use it to link
257 * to JavaScript on another server. For example, lib/recaptchalib.php has to
258 * do this. This really should only be done in exceptional circumstances. This
259 * may change in the future without warning.
b2330db6 260 * (If true, $jsfile is treaded as a full URL, not relative $CFG->wwwroot.)
2c144fc3 261 * @return required_js The required_js object. This allows you to control when the
262 * link to the script is output by calling methods like {@link required_js::asap()} or
263 * {@link required_js::in_head()}.
b2330db6 264 */
265 public function js($jsfile, $fullurl = false) {
266 global $CFG;
267 if (!$fullurl) {
02fd1ad7 268 $jsfile = ltrim($jsfile, '/'); // for now until we change all js urls to start with '/' like the rest of urls
d76b8a20 269 // strtok is used to trim off any GET string arguments before looking for the file
270 if (!file_exists($CFG->dirroot . '/' . strtok($jsfile, '?'))) {
b2330db6 271 throw new coding_exception('Attept to require a JavaScript file that does not exist.', $jsfile);
272 }
273 $url = $CFG->httpswwwroot . '/' . $jsfile;
274 } else {
275 $url = $jsfile;
276 }
9e43d2b3 277 if (!isset($this->linkedrequirements[$url])) {
278 $this->linkedrequirements[$url] = new required_js($this, $url);
b2330db6 279 }
9e43d2b3 280 return $this->linkedrequirements[$url];
b2330db6 281 }
282
283 /**
4c907141 284 * Ensure that the specified YUI2 library file, and all its required dependancies,
2c144fc3 285 * are linked to from this page.
286 *
287 * By default the link is put at the end of the page, since this gives best page-load
288 * performance. Optional dependencies are not loaded automatically - if you want
289 * them you will need to load them first with other calls to this method.
b2330db6 290 *
b2330db6 291 * Even if a particular library is requested more than once (perhaps as a dependancy
292 * of other libraries) it will only be linked to once.
293 *
985d1d1d 294 * The library is leaded as soon as possible, if $OUTPUT->header() not used yet it
945f19f7 295 * is put into the page header, otherwise it is loaded in the page footer.
985d1d1d
PS
296 *
297 * @param string|array $libname the name of the YUI2 library you require. For example 'autocomplete'.
298 * @return void
b2330db6 299 */
f44b10ed 300 public function yui2_lib($libname) {
985d1d1d
PS
301 $libnames = (array)$libname;
302 foreach ($libnames as $lib) {
303 $this->yui2loader->load($lib);
b2330db6 304 }
b2330db6 305 }
306
4c907141
PS
307 /**
308 * Ensure that the specified YUI3 library file, and all its required dependancies,
c0467479 309 * are loaded automatically on this page.
985d1d1d 310 *
4c907141
PS
311 * @param string|array $libname the name of the YUI3 library you require. For example 'overlay'.
312 * @return void
313 */
314 public function yui3_lib($libname) {
315 if ($this->headdone) {
9d897331 316 throw new coding_exception('YUI3 libraries can be preloaded by PHP only from HEAD, please use YUI autoloading instead: ', $libname);
4c907141
PS
317 }
318 $libnames = (array)$libname;
319 foreach ($libnames as $lib) {
320 $this->yui3loader->load($lib);
321 }
322 }
323
c8870e68
PS
324 /**
325 * Append YUI3 module to default YUI3 JS loader.
326 * The structure of module array is described at http://developer.yahoo.com/yui/3/yui/:
327 * @param string $name unique module name based of full plugin name
328 * @param array $module usually the module details may be detected from the $name
329 * @return void
330 */
331 public function js_module($name, array $module = null) {
332 global $CFG;
333
334 if (strpos($name, 'core_') === 0) {
335 // must be some core stuff
336 } else {
337 if ($name === 'filepicker') { // TODO: rename to 'core_filepicker' and move above
338 $pathtofilepicker = $CFG->httpswwwroot.'/repository/filepicker.js';
339 $module = array('fullpath'=>$pathtofilepicker, 'requires' => array('base', 'node', 'json', 'async-queue', 'io'));
340 }
341 //TODO: look for plugin info?
342 }
343
344 if ($module === null) {
345 throw new coding_exception('Missing YUI3 module details.');
346 }
347
348 $this->json_yui3loader->modules[$name] = $module;
349 }
350
b2330db6 351 /**
2c144fc3 352 * Ensure that the specified CSS file is linked to from this page.
353 *
354 * Because stylesheet links must go in the <head> part of the HTML, you must call
355 * this function before {@link get_head_code()} is called. That normally means before
b2330db6 356 * the call to print_header. If you call it when it is too late, an exception
357 * will be thrown.
358 *
359 * Even if a particular style sheet is requested more than once, it will only
360 * be linked to once.
361 *
c0467479
PS
362 * Please note sue of this feature is strongly discouraged,
363 * it is suitable only for places where CSS is submitted directly by teachers.
364 * (Students must not be allowed to submit any external CSS because it may
365 * contain embedded javascript!). Example of correct use is mod/data.
366 *
367 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
368 * For example:
369 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
b2330db6 370 */
c0467479 371 public function css($stylesheet) {
b2330db6 372 global $CFG;
c0467479
PS
373
374 if ($this->headdone) {
375 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
9f509643 376 }
b2330db6 377
c0467479
PS
378 if ($stylesheet instanceof moodle_url) {
379 // ok
380 } else if (strpos($stylesheet, '/') === 0) {
381 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
b2330db6 382 } else {
c0467479 383 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
b2330db6 384 }
c0467479
PS
385
386 $this->css_urls[$stylesheet->out()] = $stylesheet; // overrides
b2330db6 387 }
388
2212eb7a
PS
389 /**
390 * Add theme stylkesheet to page - do not use from plugin code,
c0467479 391 * this should be called only from the core renderer!
2212eb7a
PS
392 * @param moodle_url $stylesheet
393 * @return void
394 */
c0467479
PS
395 public function css_theme(moodle_url $stylesheet) {
396 $this->css_theme_urls[] = $stylesheet;
2212eb7a
PS
397 }
398
b2330db6 399 /**
2c144fc3 400 * Ensure that a skip link to a given target is printed at the top of the <body>.
401 *
402 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
b2330db6 403 * will be thrown). That normally means you must call this before the call to print_header.
404 *
405 * If you ask for a particular skip link to be printed, it is then your responsibility
2c144fc3 406 * to ensure that the appropraite <a name="..."> tag is printed in the body of the
b2330db6 407 * page, so that the skip link goes somewhere.
408 *
409 * Even if a particular skip link is requested more than once, only one copy of it will be output.
410 *
411 * @param $target the name of anchor this link should go to. For example 'maincontent'.
412 * @param $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
413 */
414 public function skip_link_to($target, $linktext) {
9e43d2b3 415 if (!isset($this->linkedrequirements[$target])) {
416 $this->linkedrequirements[$target] = new required_skip_link($this, $target, $linktext);
b2330db6 417 }
418 }
419
420 /**
421 * Ensure that the specified JavaScript function is called from an inline script
2c144fc3 422 * somewhere on this page.
423 *
424 * By default the call will be put in a script tag at the
b2330db6 425 * end of the page, since this gives best page-load performance.
426 *
427 * If you request that a particular function is called several times, then
428 * that is what will happen (unlike linking to a CSS or JS file, where only
429 * one link will be output).
430 *
431 * @param string $function the name of the JavaScritp function to call. Can
cf615522 432 * be a compound name like 'YAHOO.util.Event.addListener'. Can also be
433 * used to create and object by using a 'function name' like 'new user_selector'.
b2330db6 434 * @param array $arguments and array of arguments to be passed to the function.
435 * When generating the function call, this will be escaped using json_encode,
436 * so passing objects and arrays should work.
2c144fc3 437 * @return required_js_function_call The required_js_function_call object.
b2330db6 438 * This allows you to control when the link to the script is output by
2c144fc3 439 * calling methods like {@link required_js_function_call::in_head()},
440 * {@link required_js_function_call::at_top_of_body()},
441 * {@link required_js_function_call::on_dom_ready()} or
442 * {@link required_js_function_call::after_delay()} methods.
b2330db6 443 */
444 public function js_function_call($function, $arguments = array()) {
445 $requirement = new required_js_function_call($this, $function, $arguments);
446 $this->requiredjscode[] = $requirement;
447 return $requirement;
448 }
449
450 /**
2c144fc3 451 * Make a language string available to JavaScript.
117bd748 452 *
2c144fc3 453 * All the strings will be available in a mstr object in the global namespace.
454 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
b2330db6 455 * then the JavaScript variable mstr.moodle.course will be 'Course', or the
456 * equivalent in the current language.
457 *
458 * The arguments to this function are just like the arguments to get_string
459 * except that $module is not optional, and there are limitations on how you
460 * use $a. Because each string is only stored once in the JavaScript (based
461 * on $identifier and $module) you cannot get the same string with two different
462 * values of $a. If you try, an exception will be thrown.
463 *
464 * If you do need the same string expanded with different $a values, then
465 * the solution is to put them in your own data structure (e.g. and array)
2c144fc3 466 * that you pass to JavaScript with {@link data_for_js()}.
b2330db6 467 *
468 * @param string $identifier the desired string.
469 * @param string $module the language file to look in.
470 * @param mixed $a any extra data to add into the string (optional).
471 */
472 public function string_for_js($identifier, $module, $a = NULL) {
473 $string = get_string($identifier, $module, $a);
474 if (!$module) {
2c144fc3 475 throw new coding_exception('The $module parameter is required for page_requirements_manager::string_for_js.');
b2330db6 476 }
477 if (isset($this->stringsforjs[$module][$identifier]) && $this->stringsforjs[$module][$identifier] != $string) {
478 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
479 "from lang file '$module'. Did you already ask for it with a different \$a?");
480 }
481 $this->stringsforjs[$module][$identifier] = $string;
482 }
483
747b85cb 484 /**
485 * Make an array of language strings available for JS
486 *
487 * This function calls the above function {@link string_for_js()} for each requested
488 * string in the $identifiers array that is passed to the argument for a single module
489 * passed in $module.
490 *
491 * <code>
492 * $PAGE->strings_for_js(Array('one', 'two', 'three'), 'mymod', Array('a', null, 3));
493 *
494 * // The above is identifical to calling
495 *
496 * $PAGE->string_for_js('one', 'mymod', 'a');
497 * $PAGE->string_for_js('two', 'mymod');
498 * $PAGE->string_for_js('three', 'mymod', 3);
499 * </code>
500 *
501 * @param array $identifiers An array of desired strings
502 * @param string $module The module to load for
503 * @param mixed $a This can either be a single variable that gets passed as extra
504 * information for every string or it can be an array of mixed data where the
505 * key for the data matches that of the identifier it is meant for.
506 *
507 */
508 public function strings_for_js($identifiers, $module, $a=NULL) {
509 foreach ($identifiers as $key => $identifier) {
510 if (is_array($a) && array_key_exists($key, $a)) {
511 $extra = $a[$key];
512 } else {
513 $extra = $a;
514 }
515 $this->string_for_js($identifier, $module, $extra);
516 }
517 }
518
b2330db6 519 /**
2c144fc3 520 * Make some data from PHP available to JavaScript code.
117bd748 521 *
2c144fc3 522 * For example, if you call
523 * <pre>
b2330db6 524 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
2c144fc3 525 * </pre>
b2330db6 526 * then in JavsScript mydata.name will be 'Moodle'.
527 *
528 * You cannot call this function more than once with the same variable name
529 * (if you try, it will throw an exception). Your code should prepare all the
530 * date you want, and then pass it to this method. There is no way to change
531 * the value associated with a particular variable later.
532 *
533 * @param string $variable the the name of the JavaScript variable to assign the data to.
534 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
535 * should be considered an experimental feature.
536 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
537 * so passing objects and arrays should work.
2c144fc3 538 * @return required_data_for_js The required_data_for_js object.
b2330db6 539 * This allows you to control when the link to the script is output by
2c144fc3 540 * calling methods like {@link required_data_for_js::asap()},
541 * {@link required_data_for_js::in_head()} or
8a0cb3a1 542 * {@link required_data_for_js::at_top_of_body()} methods.
b2330db6 543 */
544 public function data_for_js($variable, $data) {
545 if (isset($this->variablesinitialised[$variable])) {
546 throw new coding_exception("A variable called '" . $variable .
547 "' has already been passed ot JavaScript. You cannot overwrite it.");
548 }
549 $requirement = new required_data_for_js($this, $variable, $data);
550 $this->requiredjscode[] = $requirement;
551 $this->variablesinitialised[$variable] = 1;
552 return $requirement;
553 }
117bd748 554
647df7e3 555 /**
556 * Creates a YUI event handler.
557 *
d96d8f03 558 * @param mixed $selector standard YUI selector for elemnts, may be array or string, element id is in the form "#idvalue"
647df7e3 559 * @param string $event A valid DOM event (click, mousedown, change etc.)
560 * @param string $function The name of the function to call
561 * @param array $arguments An optional array of argument parameters to pass to the function
562 * @return required_event_handler The event_handler object
563 */
d96d8f03
PS
564 public function event_handler($selector, $event, $function, array $arguments = null) {
565 $requirement = new required_event_handler($this, $selector, $event, $function, $arguments);
647df7e3 566 $this->requiredjscode[] = $requirement;
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 703
d96d8f03 704 // finally all JS that should go directly into head tag - mostly global config
77774f6a
PS
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
d96d8f03
PS
756 $inyuijs = $this->get_javascript_code(self::WHEN_IN_YUI, ' ');
757 $ondomreadyjs = $this->get_javascript_code(self::WHEN_ON_DOM_READY, ' ');
9d897331 758
c8870e68
PS
759//TODO: do we really need the global "Y" defined in javasecript-static.js?
760// The problem is that we can not rely on it to be fully initialised
9d897331 761 $js .= <<<EOD
d96d8f03
PS
762Y = YUI(yui3loader).use('node-base', function(Y) {
763$inyuijs ;
764 Y.on('domready', function() {
765$ondomreadyjs
9d897331 766 });
d96d8f03 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
d96d8f03
PS
1121 * page. By default the call will be made at the end of the page when YUI initialised,
1122 * but you can 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.
d96d8f03 1140 * Can be a compound name like 'Y.on'. Do not use old YUI2 YAHOO. function names.
b2330db6 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);
d96d8f03 1147 $this->when = page_requirements_manager::WHEN_IN_YUI;
b2330db6 1148 $this->function = $function;
1149 $this->arguments = $arguments;
1150 }
1151
1152 public function get_js_code() {
1153 $quotedargs = array();
1154 foreach ($this->arguments as $arg) {
1155 $quotedargs[] = json_encode($arg);
1156 }
cf615522 1157 $js = $this->function . '(' . implode(', ', $quotedargs) . ');';
1158 if ($this->delay) {
1159 $js = 'setTimeout(function() { ' . $js . ' }, ' . ($this->delay * 1000) . ');';
1160 }
1161 return $js . "\n";
b2330db6 1162 }
1163
1164 /**
1165 * Indicate that this function should be called in YUI's onDomReady event.
1166 *
d96d8f03
PS
1167 * Thisis needed mostly for buggy IE browsers because they have problems
1168 * when JS starts modifying DOM structure before the DOM is ready.
b2330db6 1169 */
1170 public function on_dom_ready() {
d96d8f03 1171 if ($this->is_done() || $this->when < page_requirements_manager::WHEN_IN_YUI) {
b2330db6 1172 return;
1173 }
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
c845f827
PS
1238 * specific Event to occur on a DOM element identified by a given selector.
1239 * Do not use {@link in_head()}, etc.
647df7e3 1240 *
1241 * @copyright 2009 Nicolas Connault
1242 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1243 * @since Moodle 2.0
1244 */
1245class required_event_handler extends required_js_code {
d96d8f03 1246 protected $selector;
647df7e3 1247 protected $event;
1248 protected $function;
1249 protected $args = array();
1250
1251 /**
1252 * Constructor. Normally the class and its subclasses should not be created directly.
1253 * Client code should create them via the page_requirements_manager
1254 * method {@link page_requirements_manager::data_for_js()}.
1255 *
1256 * @param page_requirements_manager $manager the page_requirements_manager we are associated with.
d96d8f03 1257 * @param mixed $selector standard YUI selector for elemnts, may be array or string, element id is in the form "#idvalue"
647df7e3 1258 * @param string $event A valid DOM event (click, mousedown, change etc.)
1259 * @param string $function The name of the function to call
1260 * @param array $arguments An optional array of argument parameters to pass to the function
1261 */
d96d8f03 1262 public function __construct(page_requirements_manager $manager, $selector, $event, $function, array $args = null) {
647df7e3 1263 parent::__construct($manager);
d96d8f03
PS
1264 $this->when = page_requirements_manager::WHEN_IN_YUI;
1265 $this->selector = $selector;
647df7e3 1266 $this->event = $event;
1267 $this->function = $function;
1268 $this->args = $args;
1269 }
1270
1271 public function get_js_code() {
d96d8f03
PS
1272 $selector = json_encode($this->selector);
1273 $output = "Y.on('$this->event', $this->function, $selector, null";
647df7e3 1274 if (!empty($this->args)) {
1275 $output .= ', ' . json_encode($this->args);
1276 }
1277 return $output . ");\n";
1278 }
1279}
b2330db6 1280
88c5092a 1281
1282/**
1283 * Returns whether ajax is enabled/allowed or not.
1284 */
c2a9fc91 1285function ajaxenabled($browsers = array()) {
88c5092a 1286
1287 global $CFG, $USER;
483f3067 1288
c2a9fc91 1289 if (!empty($browsers)) {
1290 $valid = false;
1291 foreach ($browsers as $brand => $version) {
1292 if (check_browser_version($brand, $version)) {
1293 $valid = true;
483f3067 1294 }
c2a9fc91 1295 }
483f3067 1296
c2a9fc91 1297 if (!$valid) {
1298 return false;
1299 }
1300 }
483f3067 1301
d499142e 1302 $ie = check_browser_version('MSIE', 6.0);
1303 $ff = check_browser_version('Gecko', 20051106);
1304 $op = check_browser_version('Opera', 9.0);
1305 $sa = check_browser_version('Safari', 412);
1306
1307 if (!$ie && !$ff && !$op && !$sa) {
1308 /** @see http://en.wikipedia.org/wiki/User_agent */
483f3067 1309 // Gecko build 20051107 is what is in Firefox 1.5.
88c5092a 1310 // We still have issues with AJAX in other browsers.
1311 return false;
1312 }
1313
2f11bfc0 1314 if (!empty($CFG->enableajax) && (!empty($USER->ajax) || !isloggedin())) {
88c5092a 1315 return true;
1316 } else {
1317 return false;
1318 }
1319}
9bb74178 1320
35b974da 1321
1322/**
2469f7ea 1323 * Used to create view of document to be passed to JavaScript on pageload.
1324 * We use this class to pass data from PHP to JavaScript.
35b974da 1325 */
4fc45e1d 1326class jsportal {
9bb74178 1327
0a0bb380 1328 var $currentblocksection = null;
9bb74178 1329 var $blocks = array();
0a0bb380 1330
9bb74178 1331
35b974da 1332 /**
1333 * Takes id of block and adds it
1334 */
2469f7ea 1335 function block_add($id, $hidden=false){
0a0bb380 1336 $hidden_binary = 0;
9bb74178 1337
1338 if ($hidden) {
1339 $hidden_binary = 1;
1340 }
35b974da 1341 $this->blocks[count($this->blocks)] = array($this->currentblocksection, $id, $hidden_binary);
0a0bb380 1342 }
9bb74178 1343
1344
2469f7ea 1345 /**
1346 * Prints the JavaScript code needed to set up AJAX for the course.
1347 */
1348 function print_javascript($courseid, $return=false) {
ddc66060 1349 global $CFG, $USER, $OUTPUT, $COURSE;
9bb74178 1350
d4df8fdc 1351 $blocksoutput = $output = '';
35b974da 1352 for ($i=0; $i<count($this->blocks); $i++) {
2469f7ea 1353 $blocksoutput .= "['".$this->blocks[$i][0]."',
1354 '".$this->blocks[$i][1]."',
1355 '".$this->blocks[$i][2]."']";
1356
1357 if ($i != (count($this->blocks) - 1)) {
35b974da 1358 $blocksoutput .= ',';
9bb74178 1359 }
1360 }
32f0b38a 1361 $output .= "<script type=\"text/javascript\">\n";
72d28452 1362 $output .= " main.portal.id = ".$courseid.";\n";
2469f7ea 1363 $output .= " main.portal.blocks = new Array(".$blocksoutput.");\n";
ddc66060 1364 $output .= " main.portal.strings['courseformat']='".$COURSE->format."';\n";
2469f7ea 1365 $output .= " main.portal.strings['wwwroot']='".$CFG->wwwroot."';\n";
f8eaeffa 1366 $output .= " main.portal.strings['marker']='".get_string('markthistopic', '', '_var_')."';\n";
1367 $output .= " main.portal.strings['marked']='".get_string('markedthistopic', '', '_var_')."';\n";
b1b4c2d7 1368 $output .= " main.portal.numsections = ".$COURSE->numsections.";\n";
f8eaeffa 1369 $output .= " main.portal.strings['hide']='".get_string('hide')."';\n";
1370 $output .= " main.portal.strings['hidesection']='".get_string('hidesection', '', '_var_')."';\n";
1371 $output .= " main.portal.strings['show']='".get_string('show')."';\n";
1372 $output .= " main.portal.strings['delete']='".get_string('delete')."';\n";
d2a11d46 1373 $output .= " main.portal.strings['move']='".get_string('move')."';\n";
f8eaeffa 1374 $output .= " main.portal.strings['movesection']='".get_string('movesection', '', '_var_')."';\n";
d2a11d46 1375 $output .= " main.portal.strings['moveleft']='".get_string('moveleft')."';\n";
1376 $output .= " main.portal.strings['moveright']='".get_string('moveright')."';\n";
4fc45e1d 1377 $output .= " main.portal.strings['update']='".get_string('update')."';\n";
d2a11d46 1378 $output .= " main.portal.strings['groupsnone']='".get_string('groupsnone')."';\n";
1379 $output .= " main.portal.strings['groupsseparate']='".get_string('groupsseparate')."';\n";
1380 $output .= " main.portal.strings['groupsvisible']='".get_string('groupsvisible')."';\n";
1381 $output .= " main.portal.strings['clicktochange']='".get_string('clicktochange')."';\n";
2469f7ea 1382 $output .= " main.portal.strings['deletecheck']='".get_string('deletecheck','','_var_')."';\n";
1383 $output .= " main.portal.strings['resource']='".get_string('resource')."';\n";
1384 $output .= " main.portal.strings['activity']='".get_string('activity')."';\n";
d4a1fcaf 1385 $output .= " main.portal.strings['sesskey']='".sesskey()."';\n";
b5d0cafc
PS
1386 $output .= " main.portal.icons['spacerimg']='".$OUTPUT->pix_url('spaces')."';\n";
1387 $output .= " main.portal.icons['marker']='".$OUTPUT->pix_url('i/marker')."';\n";
1388 $output .= " main.portal.icons['ihide']='".$OUTPUT->pix_url('i/hide')."';\n";
1389 $output .= " main.portal.icons['move_2d']='".$OUTPUT->pix_url('i/move_2d')."';\n";
1390 $output .= " main.portal.icons['show']='".$OUTPUT->pix_url('t/show')."';\n";
1391 $output .= " main.portal.icons['hide']='".$OUTPUT->pix_url('t/hide')."';\n";
1392 $output .= " main.portal.icons['delete']='".$OUTPUT->pix_url('t/delete')."';\n";
1393 $output .= " main.portal.icons['groupn']='".$OUTPUT->pix_url('t/groupn')."';\n";
1394 $output .= " main.portal.icons['groups']='".$OUTPUT->pix_url('t/groups')."';\n";
1395 $output .= " main.portal.icons['groupv']='".$OUTPUT->pix_url('t/groupv')."';\n";
ddedf979 1396 if (right_to_left()) {
b5d0cafc
PS
1397 $output .= " main.portal.icons['backwards']='".$OUTPUT->pix_url('t/right')."';\n";
1398 $output .= " main.portal.icons['forwards']='".$OUTPUT->pix_url('t/left')."';\n";
ddedf979 1399 } else {
b5d0cafc
PS
1400 $output .= " main.portal.icons['backwards']='".$OUTPUT->pix_url('t/left')."';\n";
1401 $output .= " main.portal.icons['forwards']='".$OUTPUT->pix_url('t/right')."';\n";
ddedf979 1402 }
1403
2469f7ea 1404 $output .= " onloadobj.load();\n";
4fc45e1d 1405 $output .= " main.process_blocks();\n";
35b974da 1406 $output .= "</script>";
2469f7ea 1407 if ($return) {
1408 return $output;
1409 } else {
1410 echo $output;
1411 }
0a0bb380 1412 }
9bb74178 1413
2469f7ea 1414}