2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library functions to facilitate the use of JavaScript in Moodle.
20 * Note: you can find history of this file in lib/ajax/ajaxlib.php
22 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
31 * This class tracks all the things that are needed by the current page.
33 * Normally, the only instance of this class you will need to work with is the
34 * one accessible via $PAGE->requires.
36 * Typical usage would be
38 * $PAGE->requires->js_init_call('M.mod_forum.init_view');
41 * It also supports obsoleted coding style withouth YUI3 modules.
43 * $PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overridable via themes!
44 * $PAGE->requires->js('/mod/mymod/script.js');
45 * $PAGE->requires->js('/mod/mymod/small_but_urgent.js', true);
46 * $PAGE->requires->js_function_call('init_mymod', array($data), true);
49 * There are some natural restrictions on some methods. For example, {@link css()}
50 * can only be called before the <head> tag is output. See the comments on the
51 * individual methods for details.
53 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
54 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
59 class page_requirements_manager {
62 * @var array List of string available from JS
64 protected $stringsforjs = array();
67 * @var array List of get_string $a parameters - used for validation only.
69 protected $stringsforjs_as = array();
72 * @var array List of JS variables to be initialised
74 protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
77 * @var array Included JS scripts
79 protected $jsincludes = array('head'=>array(), 'footer'=>array());
82 * @var array List of needed function calls
84 protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
87 * @var array List of skip links, those are needed for accessibility reasons
89 protected $skiplinks = array();
92 * @var array Javascript code used for initialisation of page, it should
95 protected $jsinitcode = array();
98 * @var array of moodle_url Theme sheets, initialised only from core_renderer
100 protected $cssthemeurls = array();
103 * @var array of moodle_url List of custom theme sheets, these are strongly discouraged!
104 * Useful mostly only for CSS submitted by teachers that is not part of the theme.
106 protected $cssurls = array();
109 * @var array List of requested event handlers
111 protected $eventhandlers = array();
114 * @var array Extra modules
116 protected $extramodules = array();
119 * @var bool Flag indicated head stuff already printed
121 protected $headdone = false;
124 * @var bool Flag indicating top of body already printed
126 protected $topofbodydone = false;
129 * @var stdClass YUI PHPLoader instance responsible for YUI3 loading from PHP only
131 protected $yui3loader;
134 * @var stdClass default YUI loader configuration
136 protected $YUI_config;
139 * @var array Some config vars exposed in JS, please no secret stuff there
144 * @var array Stores debug backtraces from when JS modules were included in the page
146 protected $debug_moduleloadstacktraces = array();
149 * Page requirements constructor.
151 public function __construct() {
154 // You may need to set up URL rewrite rule because oversized URLs might not be allowed by web server.
155 $sep = empty($CFG->yuislasharguments) ? '?' : '/';
157 $this->yui3loader = new stdClass();
159 // Set up some loader options.
160 if (debugging('', DEBUG_DEVELOPER)) {
161 $this->yui3loader->filter = 'RAW'; // For more detailed logging info use 'DEBUG' here.
163 $this->yui3loader->filter = null;
165 if (!empty($CFG->useexternalyui) and strpos($CFG->httpswwwroot, 'https:') !== 0) {
166 $this->yui3loader->base = 'http://yui.yahooapis.com/' . $CFG->yui3version . '/build/';
167 $this->yui3loader->comboBase = 'http://yui.yahooapis.com/combo?';
169 $this->yui3loader->base = $CFG->httpswwwroot . '/lib/yuilib/'. $CFG->yui3version . '/build/';
170 $this->yui3loader->comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep;
173 // Enable combo loader? This significantly helps with caching and performance!
174 $this->yui3loader->combine = !empty($CFG->yuicomboloading);
176 if (empty($CFG->cachejs)) {
178 } else if (empty($CFG->jsrev)) {
181 $jsrev = $CFG->jsrev;
184 // Set up JS YUI loader helper object.
185 $this->YUI_config = new stdClass();
186 $this->YUI_config->base = $this->yui3loader->base;
187 $this->YUI_config->comboBase = $this->yui3loader->comboBase;
188 $this->YUI_config->combine = $this->yui3loader->combine;
189 $this->YUI_config->filter = (string)$this->yui3loader->filter;
190 $this->YUI_config->insertBefore = 'firstthemesheet';
191 $this->YUI_config->modules = array();
192 $this->YUI_config->groups = array(
193 // Loader for our YUI modules stored in /yui/ subdirectories of our plugins and subsystems.
196 'base' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep.'moodle/'.$jsrev.'/',
197 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
198 'combine' => $this->yui3loader->combine,
201 'root' => 'moodle/'.$jsrev.'/', // Add the rev to the root path so that we can control caching.
205 'configFn' => '@MOODLECONFIGFN@'
209 // Gallery modules are not supported much, sorry.
212 'base' => $CFG->httpswwwroot . '/lib/yui/gallery/',
213 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
214 'combine' => $this->yui3loader->combine,
215 'filter' => $this->YUI_config->filter,
217 'root' => 'gallery/',
220 'group' => 'gallery',
221 'configFn' => '@GALLERYCONFIGFN@',
225 // Loader configuration for our 2in3, for now ignores $CFG->useexternalyui.
227 'base' => $CFG->httpswwwroot . '/lib/yuilib/2in3/' . $CFG->yui2version . '/build/',
228 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
229 'combine' => $this->yui3loader->combine,
231 'root' => '2in3/' . $CFG->yui2version .'/build/',
235 'configFn' => '@2IN3CONFIGFN@'
241 // Every page should include definition of following modules.
242 $this->js_module($this->find_module('core_filepicker'));
243 $this->js_module($this->find_module('core_dock'));
247 * Initialise with the bits of JavaScript that every Moodle page should have.
249 * @param moodle_page $page
250 * @param core_renderer $renderer
252 protected function init_requirements_data(moodle_page $page, core_renderer $renderer) {
255 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
256 // Otherwise, in some situations, users will get warnings about insecure content
257 // on secure pages from their web browser.
259 $this->M_cfg = array(
260 'wwwroot' => $CFG->httpswwwroot, // Yes, really. See above.
261 'sesskey' => sesskey(),
262 'loadingicon' => $renderer->pix_url('i/loading_small', 'moodle')->out(false),
263 'themerev' => theme_get_revision(),
264 'slasharguments' => (int)(!empty($CFG->slasharguments)),
265 'theme' => $page->theme->name,
266 'jsrev' => ((empty($CFG->cachejs) or empty($CFG->jsrev)) ? -1 : $CFG->jsrev),
267 'svgicons' => $page->theme->use_svg_icons()
269 if (debugging('', DEBUG_DEVELOPER)) {
270 $this->M_cfg['developerdebug'] = true;
273 // Accessibility stuff.
274 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
276 // Add strings used on many pages.
277 $this->string_for_js('confirmation', 'admin');
278 $this->string_for_js('cancel', 'moodle');
279 $this->string_for_js('yes', 'moodle');
281 // Alter links in top frame to break out of frames.
282 if ($page->pagelayout === 'frametop') {
283 $this->js_init_call('M.util.init_frametop');
286 // Include block drag/drop if editing is on
287 if ($page->user_is_editing()) {
289 'courseid' => $page->course->id,
290 'pagetype' => $page->pagetype,
291 'pagelayout' => $page->pagelayout,
292 'subpage' => $page->subpage,
293 'regions' => $page->blocks->get_regions(),
294 'contextid' => $page->context->id,
296 if (!empty($page->cm->id)) {
297 $params['cmid'] = $page->cm->id;
299 $page->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
304 * Ensure that the specified JavaScript file is linked to from this page.
306 * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
307 * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
309 * By default the link is put at the end of the page, since this gives best page-load performance.
311 * Even if a particular script is requested more than once, it will only be linked
314 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
315 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
316 * @param bool $inhead initialise in head
318 public function js($url, $inhead = false) {
319 $url = $this->js_fix_url($url);
320 $where = $inhead ? 'head' : 'footer';
321 $this->jsincludes[$where][$url->out()] = $url;
325 * This method was used to load YUI2 libraries into global scope,
326 * use YUI 2in3 instead. Every YUI2 module is represented as a yui2-*
327 * sandboxed module in YUI3 code via Y.YUI2. property.
329 * {@see http://tracker.moodle.org/browse/MDL-34741}
331 * @param string|array $libname
332 * @deprecated since 2.4
334 public function yui2_lib($libname) {
335 throw new coding_exception('PAGE->yui2_lib() is not available any more, use YUI 2in3 instead, see MDL-34741 for more information.');
339 * Returns the actual url through which a script is served.
341 * @param moodle_url|string $url full moodle url, or shortened path to script
344 protected function js_fix_url($url) {
347 if ($url instanceof moodle_url) {
349 } else if (strpos($url, '/') === 0) {
350 // Fix the admin links if needed.
351 if ($CFG->admin !== 'admin') {
352 if (strpos($url, "/admin/") === 0) {
353 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
357 // Check file existence only when in debug mode.
358 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
359 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
362 if (!empty($CFG->cachejs) and !empty($CFG->jsrev) and $CFG->jsrev > 0 and substr($url, -3) === '.js') {
363 if (empty($CFG->slasharguments)) {
364 return new moodle_url($CFG->httpswwwroot.'/lib/javascript.php', array('rev'=>$CFG->jsrev, 'jsfile'=>$url));
366 $returnurl = new moodle_url($CFG->httpswwwroot.'/lib/javascript.php');
367 $returnurl->set_slashargument('/'.$CFG->jsrev.$url);
371 return new moodle_url($CFG->httpswwwroot.$url);
374 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
379 * Find out if JS module present and return details.
381 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
382 * @return array description of module or null if not found
384 protected function find_module($component) {
389 if (strpos($component, 'core_') === 0) {
390 // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
391 // so that we do nto have to repeat the definition of these modules over and over again.
393 case 'core_filepicker':
394 $module = array('name' => 'core_filepicker',
395 'fullpath' => '/repository/filepicker.js',
396 'requires' => array('base', 'node', 'node-event-simulate', 'json', 'async-queue', 'io-base', 'io-upload-iframe', 'io-form', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort', 'resize-plugin', 'dd-plugin', 'moodle-core_filepicker'),
397 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
398 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
399 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
400 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
401 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
402 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
403 array('referencesexist', 'repository')
407 $module = array('name' => 'core_comment',
408 'fullpath' => '/comment/comment.js',
409 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
410 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
414 $module = array('name' => 'core_role',
415 'fullpath' => '/admin/roles/module.js',
416 'requires' => array('node', 'cookie'));
418 case 'core_completion':
419 $module = array('name' => 'core_completion',
420 'fullpath' => '/course/completion.js');
423 $module = array('name' => 'core_dock',
424 'fullpath' => '/blocks/dock.js',
425 'requires' => array('base', 'node', 'event-custom', 'event-mouseenter', 'event-resize'),
426 'strings' => array(array('addtodock', 'block'),array('undockitem', 'block'),array('undockall', 'block'),array('thisdirectionvertical', 'langconfig'),array('hidedockpanel', 'block'),array('hidepanel', 'block')));
429 $module = array('name' => 'core_message',
430 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
431 'fullpath' => '/message/module.js');
434 $module = array('name' => 'core_group',
435 'fullpath' => '/group/module.js',
436 'requires' => array('node', 'overlay', 'event-mouseenter'));
438 case 'core_question_engine':
439 $module = array('name' => 'core_question_engine',
440 'fullpath' => '/question/qengine.js',
441 'requires' => array('node', 'event'));
444 $module = array('name' => 'core_rating',
445 'fullpath' => '/rating/module.js',
446 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
448 case 'core_dndupload':
449 $module = array('name' => 'core_dndupload',
450 'fullpath' => '/lib/form/dndupload.js',
451 'requires' => array('node', 'event', 'json', 'core_filepicker'),
452 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
453 array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesforfile', 'moodle'),
454 array('maxareabytesreached', 'moodle')
460 if ($dir = get_component_directory($component)) {
461 if (file_exists("$dir/module.js")) {
462 if (strpos($dir, $CFG->dirroot.'/') === 0) {
463 $dir = substr($dir, strlen($CFG->dirroot));
464 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
474 * Append YUI3 module to default YUI3 JS loader.
475 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
477 * @param string|array $module name of module (details are autodetected), or full module specification as array
480 public function js_module($module) {
483 if (empty($module)) {
484 throw new coding_exception('Missing YUI3 module name or full description.');
487 if (is_string($module)) {
488 $module = $this->find_module($module);
491 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
492 throw new coding_exception('Missing YUI3 module details.');
495 // Don't load this module if we already have, no need to!
496 if ($this->js_module_loaded($module['name'])) {
497 if (debugging('', DEBUG_DEVELOPER)) {
498 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
503 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
504 // Add all needed strings.
505 if (!empty($module['strings'])) {
506 foreach ($module['strings'] as $string) {
507 $identifier = $string[0];
508 $component = isset($string[1]) ? $string[1] : 'moodle';
509 $a = isset($string[2]) ? $string[2] : null;
510 $this->string_for_js($identifier, $component, $a);
513 unset($module['strings']);
515 // Process module requirements and attempt to load each. This allows
516 // moodle modules to require each other.
517 if (!empty($module['requires'])){
518 foreach ($module['requires'] as $requirement) {
519 $rmodule = $this->find_module($requirement);
520 if (is_array($rmodule)) {
521 $this->js_module($rmodule);
526 if ($this->headdone) {
527 $this->extramodules[$module['name']] = $module;
529 $this->YUI_config->modules[$module['name']] = $module;
531 if (debugging('', DEBUG_DEVELOPER)) {
532 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces)) {
533 $this->debug_moduleloadstacktraces[$module['name']] = array();
535 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
540 * Returns true if the module has already been loaded.
542 * @param string|array $module
543 * @return bool True if the module has already been loaded
545 protected function js_module_loaded($module) {
546 if (is_string($module)) {
547 $modulename = $module;
549 $modulename = $module['name'];
551 return array_key_exists($modulename, $this->YUI_config->modules) ||
552 array_key_exists($modulename, $this->extramodules);
556 * Returns the stacktraces from loading js modules.
559 public function get_loaded_modules() {
560 return $this->debug_moduleloadstacktraces;
564 * Ensure that the specified CSS file is linked to from this page.
566 * Because stylesheet links must go in the <head> part of the HTML, you must call
567 * this function before {@link get_head_code()} is called. That normally means before
568 * the call to print_header. If you call it when it is too late, an exception
571 * Even if a particular style sheet is requested more than once, it will only
574 * Please note use of this feature is strongly discouraged,
575 * it is suitable only for places where CSS is submitted directly by teachers.
576 * (Students must not be allowed to submit any external CSS because it may
577 * contain embedded javascript!). Example of correct use is mod/data.
579 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
581 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
583 public function css($stylesheet) {
586 if ($this->headdone) {
587 throw new coding_exception('Cannot require a CSS file after <head> has been printed.', $stylesheet);
590 if ($stylesheet instanceof moodle_url) {
592 } else if (strpos($stylesheet, '/') === 0) {
593 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
595 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
598 $this->cssurls[$stylesheet->out()] = $stylesheet;
602 * Add theme stylesheet to page - do not use from plugin code,
603 * this should be called only from the core renderer!
605 * @param moodle_url $stylesheet
608 public function css_theme(moodle_url $stylesheet) {
609 $this->cssthemeurls[] = $stylesheet;
613 * Ensure that a skip link to a given target is printed at the top of the <body>.
615 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
616 * will be thrown). That normally means you must call this before the call to print_header.
618 * If you ask for a particular skip link to be printed, it is then your responsibility
619 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
620 * page, so that the skip link goes somewhere.
622 * Even if a particular skip link is requested more than once, only one copy of it will be output.
624 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
625 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
627 public function skip_link_to($target, $linktext) {
628 if ($this->topofbodydone) {
629 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
632 $this->skiplinks[$target] = $linktext;
636 * !!!DEPRECATED!!! please use js_init_call() if possible
637 * Ensure that the specified JavaScript function is called from an inline script
638 * somewhere on this page.
640 * By default the call will be put in a script tag at the
641 * end of the page after initialising Y instance, since this gives best page-load
642 * performance and allows you to use YUI3 library.
644 * If you request that a particular function is called several times, then
645 * that is what will happen (unlike linking to a CSS or JS file, where only
646 * one link will be output).
648 * The main benefit of the method is the automatic encoding of all function parameters.
652 * @param string $function the name of the JavaScritp function to call. Can
653 * be a compound name like 'Y.Event.purgeElement'. Can also be
654 * used to create and object by using a 'function name' like 'new user_selector'.
655 * @param array $arguments and array of arguments to be passed to the function.
656 * When generating the function call, this will be escaped using json_encode,
657 * so passing objects and arrays should work.
658 * @param bool $ondomready If tru the function is only called when the dom is
659 * ready for manipulation.
660 * @param int $delay The delay before the function is called.
662 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
663 $where = $ondomready ? 'ondomready' : 'normal';
664 $this->jscalls[$where][] = array($function, $arguments, $delay);
668 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
670 * @deprecated DO NOT USE
672 * @param string|array $modules One or more gallery modules to require
673 * @param string $version
674 * @param string $function
675 * @param array $arguments
676 * @param bool $ondomready
678 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
680 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER);
681 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
685 * Creates a JavaScript function call that requires one or more modules to be loaded.
687 * This function can be used to include all of the standard YUI module types within JavaScript:
688 * - YUI3 modules [node, event, io]
689 * - YUI2 modules [yui2-*]
690 * - Moodle modules [moodle-*]
691 * - Gallery modules [gallery-*]
693 * @param array|string $modules One or more modules
694 * @param string $function The function to call once modules have been loaded
695 * @param array $arguments An array of arguments to pass to the function
696 * @param string $galleryversion The gallery version to use
697 * @param bool $ondomready
699 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
702 if (!$galleryversion) {
703 $galleryversion = '2010.04.08-12-35';
706 if (!is_array($modules)) {
707 $modules = array($modules);
709 if (empty($CFG->useexternalyui)) {
710 // We need to set the M.yui.galleryversion to the correct version
711 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
713 // Set Y's config.gallery to the version
714 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
716 $jscode .= 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
718 $jscode = "Y.on('domready', function() { $jscode });";
720 $this->jsinitcode[] = $jscode;
724 * Ensure that the specified JavaScript function is called from an inline script
727 * @param string $function the name of the JavaScritp function to with init code,
728 * usually something like 'M.mod_mymodule.init'
729 * @param array $extraarguments and array of arguments to be passed to the function.
730 * The first argument is always the YUI3 Y instance with all required dependencies
732 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
733 * @param array $module JS module specification array
735 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
736 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
738 // Detect module automatically.
739 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
740 $module = $this->find_module($matches[1]);
744 $this->js_init_code($jscode, $ondomready, $module);
748 * Add short static javascript code fragment to page footer.
749 * This is intended primarily for loading of js modules and initialising page layout.
750 * Ideally the JS code fragment should be stored in plugin renderer so that themes
753 * @param string $jscode
754 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
755 * @param array $module JS module specification array
757 public function js_init_code($jscode, $ondomready = false, array $module = null) {
758 $jscode = trim($jscode, " ;\n"). ';';
761 $this->js_module($module);
762 $modulename = $module['name'];
763 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
767 $jscode = "Y.on('domready', function() { $jscode });";
770 $this->jsinitcode[] = $jscode;
774 * Make a language string available to JavaScript.
776 * All the strings will be available in a M.str object in the global namespace.
777 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
778 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
779 * equivalent in the current language.
781 * The arguments to this function are just like the arguments to get_string
782 * except that $component is not optional, and there are some aspects to consider
783 * when the string contains {$a} placeholder.
785 * If the string does not contain any {$a} placeholder, you can simply use
786 * M.str.component.identifier to obtain it. If you prefer, you can call
787 * M.util.get_string(identifier, component) to get the same result.
789 * If you need to use {$a} placeholders, there are two options. Either the
790 * placeholder should be substituted in PHP on server side or it should
791 * be substituted in Javascript at client side.
793 * To substitute the placeholder at server side, just provide the required
794 * value for the placeholder when you require the string. Because each string
795 * is only stored once in the JavaScript (based on $identifier and $module)
796 * you cannot get the same string with two different values of $a. If you try,
797 * an exception will be thrown. Once the placeholder is substituted, you can
798 * use M.str or M.util.get_string() as shown above:
800 * // Require the string in PHP and replace the placeholder.
801 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
802 * // Use the result of the substitution in Javascript.
803 * alert(M.str.moodle.fullnamedisplay);
805 * To substitute the placeholder at client side, use M.util.get_string()
806 * function. It implements the same logic as {@link get_string()}:
808 * // Require the string in PHP but keep {$a} as it is.
809 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
810 * // Provide the values on the fly in Javascript.
811 * user = { firstname : 'Harry', lastname : 'Potter' }
812 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
814 * If you do need the same string expanded with different $a values in PHP
815 * on server side, then the solution is to put them in your own data structure
816 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
818 * @param string $identifier the desired string.
819 * @param string $component the language file to look in.
820 * @param mixed $a any extra data to add into the string (optional).
822 public function string_for_js($identifier, $component, $a = null) {
824 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
826 if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
827 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
828 "from lang file '$component' with different \$a parameter?");
830 if (!isset($this->stringsforjs[$component][$identifier])) {
831 $this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
832 $this->stringsforjs_as[$component][$identifier] = $a;
837 * Make an array of language strings available for JS.
839 * This function calls the above function {@link string_for_js()} for each requested
840 * string in the $identifiers array that is passed to the argument for a single module
844 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
846 * // The above is identical to calling:
848 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
849 * $PAGE->requires->string_for_js('two', 'mymod');
850 * $PAGE->requires->string_for_js('three', 'mymod', 3);
853 * @param array $identifiers An array of desired strings
854 * @param string $component The module to load for
855 * @param mixed $a This can either be a single variable that gets passed as extra
856 * information for every string or it can be an array of mixed data where the
857 * key for the data matches that of the identifier it is meant for.
860 public function strings_for_js($identifiers, $component, $a = null) {
861 foreach ($identifiers as $key => $identifier) {
862 if (is_array($a) && array_key_exists($key, $a)) {
867 $this->string_for_js($identifier, $component, $extra);
872 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
874 * Make some data from PHP available to JavaScript code.
876 * For example, if you call
878 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
880 * then in JavsScript mydata.name will be 'Moodle'.
883 * @param string $variable the the name of the JavaScript variable to assign the data to.
884 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
885 * should be considered an experimental feature.
886 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
887 * so passing objects and arrays should work.
888 * @param bool $inhead initialise in head
891 public function data_for_js($variable, $data, $inhead=false) {
892 $where = $inhead ? 'head' : 'footer';
893 $this->jsinitvariables[$where][] = array($variable, $data);
897 * Creates a YUI event handler.
899 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
900 * @param string $event A valid DOM event (click, mousedown, change etc.)
901 * @param string $function The name of the function to call
902 * @param array $arguments An optional array of argument parameters to pass to the function
904 public function event_handler($selector, $event, $function, array $arguments = null) {
905 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
909 * Returns code needed for registering of event handlers.
910 * @return string JS code
912 protected function get_event_handler_code() {
914 foreach ($this->eventhandlers as $h) {
915 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
921 * Get the inline JavaScript code that need to appear in a particular place.
922 * @param bool $ondomready
925 protected function get_javascript_code($ondomready) {
926 $where = $ondomready ? 'ondomready' : 'normal';
928 if ($this->jscalls[$where]) {
929 foreach ($this->jscalls[$where] as $data) {
930 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
932 if (!empty($ondomready)) {
933 $output = " Y.on('domready', function() {\n$output\n });";
940 * Returns js code to be executed when Y is available.
943 protected function get_javascript_init_code() {
944 if (count($this->jsinitcode)) {
945 return implode("\n", $this->jsinitcode) . "\n";
951 * Returns basic YUI3 JS loading code.
952 * YUI3 is using autoloading of both CSS and JS code.
954 * Major benefit of this compared to standard js/csss loader is much improved
955 * caching, better browser cache utilisation, much fewer http requests.
959 protected function get_yui3lib_headcode() {
964 if ($this->yui3loader->combine) {
965 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase
966 .$CFG->yui3version.'/build/cssreset/reset-min.css&'
967 .$CFG->yui3version.'/build/cssfonts/fonts-min.css&'
968 .$CFG->yui3version.'/build/cssgrids/grids-min.css&'
969 .$CFG->yui3version.'/build/cssbase/base-min.css" />';
970 $code .= '<script type="text/javascript" src="'.$this->yui3loader->comboBase
971 .$CFG->yui3version.'/build/simpleyui/simpleyui-min.js&'
972 .$CFG->yui3version.'/build/loader/loader-min.js"></script>';
974 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssreset/reset-min.css" />';
975 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssfonts/fonts-min.css" />';
976 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssgrids/grids-min.css" />';
977 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssbase/base-min.css" />';
978 $code .= '<script type="text/javascript" src="'.$this->yui3loader->base.'simpleyui/simpleyui-min.js"></script>';
979 $code .= '<script type="text/javascript" src="'.$this->yui3loader->base.'loader/loader-min.js"></script>';
983 if ($this->yui3loader->filter === 'RAW') {
984 $code = str_replace('-min.css', '.css', $code);
985 $code = str_replace('-min.js', '.js', $code);
986 } else if ($this->yui3loader->filter === 'DEBUG') {
987 $code = str_replace('-min.css', '.css', $code);
988 $code = str_replace('-min.js', '-debug.js', $code);
995 * Returns html tags needed for inclusion of theme CSS.
999 protected function get_css_code() {
1000 // First of all the theme CSS, then any custom CSS
1001 // Please note custom CSS is strongly discouraged,
1002 // because it can not be overridden by themes!
1003 // It is suitable only for things like mod/data which accepts CSS from teachers.
1004 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1006 // This line of code may look funny but it is currently required in order
1007 // to avoid MASSIVE display issues in Internet Explorer.
1008 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1009 // ignored whenever another resource is added until such time as a redraw
1010 // is forced, usually by moving the mouse over the affected element.
1011 $code = html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1013 $urls = $this->cssthemeurls + $this->cssurls;
1014 foreach ($urls as $url) {
1015 $attributes['href'] = $url;
1016 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1017 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1018 unset($attributes['id']);
1025 * Adds extra modules specified after printing of page header.
1029 protected function get_extra_modules_code() {
1030 if (empty($this->extramodules)) {
1033 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1037 * Generate any HTML that needs to go inside the <head> tag.
1039 * Normally, this method is called automatically by the code that prints the
1040 * <head> tag. You should not normally need to call it in your own code.
1042 * @param moodle_page $page
1043 * @param core_renderer $renderer
1044 * @return string the HTML code to to inside the <head> tag.
1046 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1049 // Note: the $page and $output are not stored here because it would
1050 // create circular references in memory which prevents garbage collection.
1051 $this->init_requirements_data($page, $renderer);
1053 // YUI3 JS and CSS is always loaded first - it is cached in browser.
1054 $output = $this->get_yui3lib_headcode();
1056 // Now theme CSS + custom CSS in this specific order.
1057 $output .= $this->get_css_code();
1059 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1060 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1061 // this needs to be done before including any other script.
1062 $js = "var M = {}; M.yui = {};
1063 var moodleConfigFn = function(me) {var p = me.path, b = me.name.replace(/^moodle-/,'').split('-', 3), n = b.pop();if (/(skin|core)/.test(n)) {n = b.pop();me.type = 'css';};me.path = b.join('-')+'/'+n+'/'+n+'.'+me.type;};
1064 var galleryConfigFn = function(me) {var p = me.path,v=M.yui.galleryversion,f;if(/-(skin|core)/.test(me.name)) {me.type = 'css';p = p.replace(/-(skin|core)/, '').replace(/\.js/, '.css').split('/'), f = p.pop().replace(/(\-(min|debug))/, '');if (/-skin/.test(me.name)) {p.splice(p.length,0,v,'assets','skins','sam', f);} else {p.splice(p.length,0,v,'assets', f);};} else {p = p.split('/'), f = p.pop();p.splice(p.length,0,v, f);};me.path = p.join('/');};
1065 var yui2in3ConfigFn = function(me) {if(/-skin|reset|fonts|grids|base/.test(me.name)){me.type='css';me.path=me.path.replace(/\.js/,'.css');me.path=me.path.replace(/\/yui2-skin/,'/assets/skins/sam/yui2-skin');}};\n";
1066 $js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n";
1067 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1068 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1069 $js = str_replace('"@GALLERYCONFIGFN@"', 'galleryConfigFn', $js);
1070 $js = str_replace('"@MOODLECONFIGFN@"', 'moodleConfigFn', $js);
1071 $js = str_replace('"@2IN3CONFIGFN@"', 'yui2in3ConfigFn', $js);
1073 $output .= html_writer::script($js);
1075 // Link our main JS file, all core stuff should be there.
1076 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1079 if ($this->jsinitvariables['head']) {
1081 foreach ($this->jsinitvariables['head'] as $data) {
1082 list($var, $value) = $data;
1083 $js .= js_writer::set_variable($var, $value, true);
1085 $output .= html_writer::script($js);
1088 // All the other linked things from HEAD - there should be as few as possible.
1089 if ($this->jsincludes['head']) {
1090 foreach ($this->jsincludes['head'] as $url) {
1091 $output .= html_writer::script('', $url);
1095 // Mark head sending done, it is not possible to anything there.
1096 $this->headdone = true;
1102 * Generate any HTML that needs to go at the start of the <body> tag.
1104 * Normally, this method is called automatically by the code that prints the
1105 * <head> tag. You should not normally need to call it in your own code.
1107 * @return string the HTML code to go at the start of the <body> tag.
1109 public function get_top_of_body_code() {
1110 // First the skip links.
1112 $attributes = array('class'=>'skip');
1113 foreach ($this->skiplinks as $url => $text) {
1114 $attributes['href'] = '#' . $url;
1115 $links .= html_writer::tag('a', $text, $attributes);
1117 $output = html_writer::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1119 // Then the clever trick for hiding of things not needed when JS works.
1120 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1121 $this->topofbodydone = true;
1126 * Generate any HTML that needs to go at the end of the page.
1128 * Normally, this method is called automatically by the code that prints the
1129 * page footer. You should not normally need to call it in your own code.
1131 * @return string the HTML code to to at the end of the page.
1133 public function get_end_code() {
1136 // Add other requested modules.
1137 $output = $this->get_extra_modules_code();
1139 // All the other linked scripts - there should be as few as possible.
1140 if ($this->jsincludes['footer']) {
1141 foreach ($this->jsincludes['footer'] as $url) {
1142 $output .= html_writer::script('', $url);
1146 // Add all needed strings.
1147 if (!empty($this->stringsforjs)) {
1149 foreach ($this->stringsforjs as $component=>$v) {
1150 foreach($v as $indentifier => $langstring) {
1151 $strings[$component][$indentifier] = $langstring->out();
1154 $output .= html_writer::script(js_writer::set_variable('M.str', $strings));
1158 if ($this->jsinitvariables['footer']) {
1160 foreach ($this->jsinitvariables['footer'] as $data) {
1161 list($var, $value) = $data;
1162 $js .= js_writer::set_variable($var, $value, true);
1164 $output .= html_writer::script($js);
1167 $inyuijs = $this->get_javascript_code(false);
1168 $ondomreadyjs = $this->get_javascript_code(true);
1169 $jsinit = $this->get_javascript_init_code();
1170 $handlersjs = $this->get_event_handler_code();
1172 // There is no global Y, make sure it is available in your scope.
1173 $js = "YUI().use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1175 $output .= html_writer::script($js);
1181 * Have we already output the code in the <head> tag?
1185 public function is_head_done() {
1186 return $this->headdone;
1190 * Have we already output the code at the start of the <body> tag?
1194 public function is_top_of_body_done() {
1195 return $this->topofbodydone;
1200 * Invalidate all server and client side JS caches.
1202 function js_reset_all_caches() {
1204 require_once("$CFG->libdir/filelib.php");
1207 if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
1208 // This resolves problems when reset is requested repeatedly within 1s,
1209 // the < 1h condition prevents accidental switching to future dates
1210 // because we might not recover from it.
1211 $next = $CFG->jsrev+1;
1214 set_config('jsrev', $next);
1215 fulldelete("$CFG->cachedir/js");