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');
288 * Ensure that the specified JavaScript file is linked to from this page.
290 * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
291 * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
293 * By default the link is put at the end of the page, since this gives best page-load performance.
295 * Even if a particular script is requested more than once, it will only be linked
298 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
299 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
300 * @param bool $inhead initialise in head
302 public function js($url, $inhead = false) {
303 $url = $this->js_fix_url($url);
304 $where = $inhead ? 'head' : 'footer';
305 $this->jsincludes[$where][$url->out()] = $url;
309 * This method was used to load YUI2 libraries into global scope,
310 * use YUI 2in3 instead. Every YUI2 module is represented as a yui2-*
311 * sandboxed module in YUI3 code via Y.YUI2. property.
313 * {@see http://tracker.moodle.org/browse/MDL-34741}
315 * @param string|array $libname
316 * @deprecated since 2.4
318 public function yui2_lib($libname) {
319 throw new coding_exception('PAGE->yui2_lib() is not available any more, use YUI 2in3 instead, see MDL-34741 for more information.');
323 * Returns the actual url through which a script is served.
325 * @param moodle_url|string $url full moodle url, or shortened path to script
328 protected function js_fix_url($url) {
331 if ($url instanceof moodle_url) {
333 } else if (strpos($url, '/') === 0) {
334 // Fix the admin links if needed.
335 if ($CFG->admin !== 'admin') {
336 if (strpos($url, "/admin/") === 0) {
337 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
341 // Check file existence only when in debug mode.
342 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
343 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
346 if (!empty($CFG->cachejs) and !empty($CFG->jsrev) and $CFG->jsrev > 0 and substr($url, -3) === '.js') {
347 if (empty($CFG->slasharguments)) {
348 return new moodle_url($CFG->httpswwwroot.'/lib/javascript.php', array('rev'=>$CFG->jsrev, 'jsfile'=>$url));
350 $returnurl = new moodle_url($CFG->httpswwwroot.'/lib/javascript.php');
351 $returnurl->set_slashargument('/'.$CFG->jsrev.$url);
355 return new moodle_url($CFG->httpswwwroot.$url);
358 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
363 * Find out if JS module present and return details.
365 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
366 * @return array description of module or null if not found
368 protected function find_module($component) {
373 if (strpos($component, 'core_') === 0) {
374 // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
375 // so that we do nto have to repeat the definition of these modules over and over again.
377 case 'core_filepicker':
378 $module = array('name' => 'core_filepicker',
379 'fullpath' => '/repository/filepicker.js',
380 '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'),
381 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
382 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
383 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
384 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
385 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
386 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
387 array('referencesexist', 'repository')
391 $module = array('name' => 'core_comment',
392 'fullpath' => '/comment/comment.js',
393 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
394 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
398 $module = array('name' => 'core_role',
399 'fullpath' => '/admin/roles/module.js',
400 'requires' => array('node', 'cookie'));
402 case 'core_completion':
403 $module = array('name' => 'core_completion',
404 'fullpath' => '/course/completion.js');
407 $module = array('name' => 'core_dock',
408 'fullpath' => '/blocks/dock.js',
409 'requires' => array('base', 'node', 'event-custom', 'event-mouseenter', 'event-resize'),
410 'strings' => array(array('addtodock', 'block'),array('undockitem', 'block'),array('undockall', 'block'),array('thisdirectionvertical', 'langconfig')));
413 $module = array('name' => 'core_message',
414 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
415 'fullpath' => '/message/module.js');
418 $module = array('name' => 'core_group',
419 'fullpath' => '/group/module.js',
420 'requires' => array('node', 'overlay', 'event-mouseenter'));
422 case 'core_question_engine':
423 $module = array('name' => 'core_question_engine',
424 'fullpath' => '/question/qengine.js',
425 'requires' => array('node', 'event'));
428 $module = array('name' => 'core_rating',
429 'fullpath' => '/rating/module.js',
430 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
432 case 'core_dndupload':
433 $module = array('name' => 'core_dndupload',
434 'fullpath' => '/lib/form/dndupload.js',
435 'requires' => array('node', 'event', 'json', 'core_filepicker'),
436 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'), array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle')));
441 if ($dir = get_component_directory($component)) {
442 if (file_exists("$dir/module.js")) {
443 if (strpos($dir, $CFG->dirroot.'/') === 0) {
444 $dir = substr($dir, strlen($CFG->dirroot));
445 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
455 * Append YUI3 module to default YUI3 JS loader.
456 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
458 * @param string|array $module name of module (details are autodetected), or full module specification as array
461 public function js_module($module) {
464 if (empty($module)) {
465 throw new coding_exception('Missing YUI3 module name or full description.');
468 if (is_string($module)) {
469 $module = $this->find_module($module);
472 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
473 throw new coding_exception('Missing YUI3 module details.');
476 // Don't load this module if we already have, no need to!
477 if ($this->js_module_loaded($module['name'])) {
478 if (debugging('', DEBUG_DEVELOPER)) {
479 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
484 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
485 // Add all needed strings.
486 if (!empty($module['strings'])) {
487 foreach ($module['strings'] as $string) {
488 $identifier = $string[0];
489 $component = isset($string[1]) ? $string[1] : 'moodle';
490 $a = isset($string[2]) ? $string[2] : null;
491 $this->string_for_js($identifier, $component, $a);
494 unset($module['strings']);
496 // Process module requirements and attempt to load each. This allows
497 // moodle modules to require each other.
498 if (!empty($module['requires'])){
499 foreach ($module['requires'] as $requirement) {
500 $rmodule = $this->find_module($requirement);
501 if (is_array($rmodule)) {
502 $this->js_module($rmodule);
507 if ($this->headdone) {
508 $this->extramodules[$module['name']] = $module;
510 $this->YUI_config->modules[$module['name']] = $module;
512 if (debugging('', DEBUG_DEVELOPER)) {
513 if (!array_key_exists($module['name'], $this->debug_moduleloadstacktraces)) {
514 $this->debug_moduleloadstacktraces[$module['name']] = array();
516 $this->debug_moduleloadstacktraces[$module['name']][] = format_backtrace(debug_backtrace());
521 * Returns true if the module has already been loaded.
523 * @param string|array $module
524 * @return bool True if the module has already been loaded
526 protected function js_module_loaded($module) {
527 if (is_string($module)) {
528 $modulename = $module;
530 $modulename = $module['name'];
532 return array_key_exists($modulename, $this->YUI_config->modules) ||
533 array_key_exists($modulename, $this->extramodules);
537 * Returns the stacktraces from loading js modules.
540 public function get_loaded_modules() {
541 return $this->debug_moduleloadstacktraces;
545 * Ensure that the specified CSS file is linked to from this page.
547 * Because stylesheet links must go in the <head> part of the HTML, you must call
548 * this function before {@link get_head_code()} is called. That normally means before
549 * the call to print_header. If you call it when it is too late, an exception
552 * Even if a particular style sheet is requested more than once, it will only
555 * Please note use of this feature is strongly discouraged,
556 * it is suitable only for places where CSS is submitted directly by teachers.
557 * (Students must not be allowed to submit any external CSS because it may
558 * contain embedded javascript!). Example of correct use is mod/data.
560 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
562 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
564 public function css($stylesheet) {
567 if ($this->headdone) {
568 throw new coding_exception('Cannot require a CSS file after <head> has been printed.', $stylesheet);
571 if ($stylesheet instanceof moodle_url) {
573 } else if (strpos($stylesheet, '/') === 0) {
574 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
576 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
579 $this->cssurls[$stylesheet->out()] = $stylesheet;
583 * Add theme stylesheet to page - do not use from plugin code,
584 * this should be called only from the core renderer!
586 * @param moodle_url $stylesheet
589 public function css_theme(moodle_url $stylesheet) {
590 $this->cssthemeurls[] = $stylesheet;
594 * Ensure that a skip link to a given target is printed at the top of the <body>.
596 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
597 * will be thrown). That normally means you must call this before the call to print_header.
599 * If you ask for a particular skip link to be printed, it is then your responsibility
600 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
601 * page, so that the skip link goes somewhere.
603 * Even if a particular skip link is requested more than once, only one copy of it will be output.
605 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
606 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
608 public function skip_link_to($target, $linktext) {
609 if ($this->topofbodydone) {
610 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
613 $this->skiplinks[$target] = $linktext;
617 * !!!DEPRECATED!!! please use js_init_call() if possible
618 * Ensure that the specified JavaScript function is called from an inline script
619 * somewhere on this page.
621 * By default the call will be put in a script tag at the
622 * end of the page after initialising Y instance, since this gives best page-load
623 * performance and allows you to use YUI3 library.
625 * If you request that a particular function is called several times, then
626 * that is what will happen (unlike linking to a CSS or JS file, where only
627 * one link will be output).
629 * The main benefit of the method is the automatic encoding of all function parameters.
633 * @param string $function the name of the JavaScritp function to call. Can
634 * be a compound name like 'Y.Event.purgeElement'. Can also be
635 * used to create and object by using a 'function name' like 'new user_selector'.
636 * @param array $arguments and array of arguments to be passed to the function.
637 * When generating the function call, this will be escaped using json_encode,
638 * so passing objects and arrays should work.
639 * @param bool $ondomready If tru the function is only called when the dom is
640 * ready for manipulation.
641 * @param int $delay The delay before the function is called.
643 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
644 $where = $ondomready ? 'ondomready' : 'normal';
645 $this->jscalls[$where][] = array($function, $arguments, $delay);
649 * Adds a call to make use of a YUI gallery module. DEPRECATED DO NOT USE!!!
651 * @deprecated DO NOT USE
653 * @param string|array $modules One or more gallery modules to require
654 * @param string $version
655 * @param string $function
656 * @param array $arguments
657 * @param bool $ondomready
659 public function js_gallery_module($modules, $version, $function, array $arguments = null, $ondomready = false) {
661 debugging('This function will be removed before 2.0 is released please change it from js_gallery_module to yui_module', DEBUG_DEVELOPER);
662 $this->yui_module($modules, $function, $arguments, $version, $ondomready);
666 * Creates a JavaScript function call that requires one or more modules to be loaded.
668 * This function can be used to include all of the standard YUI module types within JavaScript:
669 * - YUI3 modules [node, event, io]
670 * - YUI2 modules [yui2-*]
671 * - Moodle modules [moodle-*]
672 * - Gallery modules [gallery-*]
674 * @param array|string $modules One or more modules
675 * @param string $function The function to call once modules have been loaded
676 * @param array $arguments An array of arguments to pass to the function
677 * @param string $galleryversion The gallery version to use
678 * @param bool $ondomready
680 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
683 if (!$galleryversion) {
684 $galleryversion = '2010.04.08-12-35';
687 if (!is_array($modules)) {
688 $modules = array($modules);
690 if (empty($CFG->useexternalyui)) {
691 // We need to set the M.yui.galleryversion to the correct version
692 $jscode = 'M.yui.galleryversion='.json_encode($galleryversion).';';
694 // Set Y's config.gallery to the version
695 $jscode = 'Y.config.gallery='.json_encode($galleryversion).';';
697 $jscode .= 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
699 $jscode = "Y.on('domready', function() { $jscode });";
701 $this->jsinitcode[] = $jscode;
705 * Ensure that the specified JavaScript function is called from an inline script
708 * @param string $function the name of the JavaScritp function to with init code,
709 * usually something like 'M.mod_mymodule.init'
710 * @param array $extraarguments and array of arguments to be passed to the function.
711 * The first argument is always the YUI3 Y instance with all required dependencies
713 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
714 * @param array $module JS module specification array
716 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
717 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
719 // Detect module automatically.
720 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
721 $module = $this->find_module($matches[1]);
725 $this->js_init_code($jscode, $ondomready, $module);
729 * Add short static javascript code fragment to page footer.
730 * This is intended primarily for loading of js modules and initialising page layout.
731 * Ideally the JS code fragment should be stored in plugin renderer so that themes
734 * @param string $jscode
735 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
736 * @param array $module JS module specification array
738 public function js_init_code($jscode, $ondomready = false, array $module = null) {
739 $jscode = trim($jscode, " ;\n"). ';';
742 $this->js_module($module);
743 $modulename = $module['name'];
744 $jscode = "Y.use('$modulename', function(Y) { $jscode });";
748 $jscode = "Y.on('domready', function() { $jscode });";
751 $this->jsinitcode[] = $jscode;
755 * Make a language string available to JavaScript.
757 * All the strings will be available in a M.str object in the global namespace.
758 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
759 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
760 * equivalent in the current language.
762 * The arguments to this function are just like the arguments to get_string
763 * except that $component is not optional, and there are some aspects to consider
764 * when the string contains {$a} placeholder.
766 * If the string does not contain any {$a} placeholder, you can simply use
767 * M.str.component.identifier to obtain it. If you prefer, you can call
768 * M.util.get_string(identifier, component) to get the same result.
770 * If you need to use {$a} placeholders, there are two options. Either the
771 * placeholder should be substituted in PHP on server side or it should
772 * be substituted in Javascript at client side.
774 * To substitute the placeholder at server side, just provide the required
775 * value for the placeholder when you require the string. Because each string
776 * is only stored once in the JavaScript (based on $identifier and $module)
777 * you cannot get the same string with two different values of $a. If you try,
778 * an exception will be thrown. Once the placeholder is substituted, you can
779 * use M.str or M.util.get_string() as shown above:
781 * // Require the string in PHP and replace the placeholder.
782 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
783 * // Use the result of the substitution in Javascript.
784 * alert(M.str.moodle.fullnamedisplay);
786 * To substitute the placeholder at client side, use M.util.get_string()
787 * function. It implements the same logic as {@link get_string()}:
789 * // Require the string in PHP but keep {$a} as it is.
790 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
791 * // Provide the values on the fly in Javascript.
792 * user = { firstname : 'Harry', lastname : 'Potter' }
793 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
795 * If you do need the same string expanded with different $a values in PHP
796 * on server side, then the solution is to put them in your own data structure
797 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
799 * @param string $identifier the desired string.
800 * @param string $component the language file to look in.
801 * @param mixed $a any extra data to add into the string (optional).
803 public function string_for_js($identifier, $component, $a = null) {
805 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
807 if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
808 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
809 "from lang file '$component' with different \$a parameter?");
811 if (!isset($this->stringsforjs[$component][$identifier])) {
812 $this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
813 $this->stringsforjs_as[$component][$identifier] = $a;
818 * Make an array of language strings available for JS.
820 * This function calls the above function {@link string_for_js()} for each requested
821 * string in the $identifiers array that is passed to the argument for a single module
825 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
827 * // The above is identical to calling:
829 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
830 * $PAGE->requires->string_for_js('two', 'mymod');
831 * $PAGE->requires->string_for_js('three', 'mymod', 3);
834 * @param array $identifiers An array of desired strings
835 * @param string $component The module to load for
836 * @param mixed $a This can either be a single variable that gets passed as extra
837 * information for every string or it can be an array of mixed data where the
838 * key for the data matches that of the identifier it is meant for.
841 public function strings_for_js($identifiers, $component, $a = null) {
842 foreach ($identifiers as $key => $identifier) {
843 if (is_array($a) && array_key_exists($key, $a)) {
848 $this->string_for_js($identifier, $component, $extra);
853 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
855 * Make some data from PHP available to JavaScript code.
857 * For example, if you call
859 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
861 * then in JavsScript mydata.name will be 'Moodle'.
864 * @param string $variable the the name of the JavaScript variable to assign the data to.
865 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
866 * should be considered an experimental feature.
867 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
868 * so passing objects and arrays should work.
869 * @param bool $inhead initialise in head
872 public function data_for_js($variable, $data, $inhead=false) {
873 $where = $inhead ? 'head' : 'footer';
874 $this->jsinitvariables[$where][] = array($variable, $data);
878 * Creates a YUI event handler.
880 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
881 * @param string $event A valid DOM event (click, mousedown, change etc.)
882 * @param string $function The name of the function to call
883 * @param array $arguments An optional array of argument parameters to pass to the function
885 public function event_handler($selector, $event, $function, array $arguments = null) {
886 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
890 * Returns code needed for registering of event handlers.
891 * @return string JS code
893 protected function get_event_handler_code() {
895 foreach ($this->eventhandlers as $h) {
896 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
902 * Get the inline JavaScript code that need to appear in a particular place.
903 * @param bool $ondomready
906 protected function get_javascript_code($ondomready) {
907 $where = $ondomready ? 'ondomready' : 'normal';
909 if ($this->jscalls[$where]) {
910 foreach ($this->jscalls[$where] as $data) {
911 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
913 if (!empty($ondomready)) {
914 $output = " Y.on('domready', function() {\n$output\n });";
921 * Returns js code to be executed when Y is available.
924 protected function get_javascript_init_code() {
925 if (count($this->jsinitcode)) {
926 return implode("\n", $this->jsinitcode) . "\n";
932 * Returns basic YUI3 JS loading code.
933 * YUI3 is using autoloading of both CSS and JS code.
935 * Major benefit of this compared to standard js/csss loader is much improved
936 * caching, better browser cache utilisation, much fewer http requests.
940 protected function get_yui3lib_headcode() {
945 if ($this->yui3loader->combine) {
946 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase
947 .$CFG->yui3version.'/build/cssreset/reset-min.css&'
948 .$CFG->yui3version.'/build/cssfonts/fonts-min.css&'
949 .$CFG->yui3version.'/build/cssgrids/grids-min.css&'
950 .$CFG->yui3version.'/build/cssbase/base-min.css" />';
951 $code .= '<script type="text/javascript" src="'.$this->yui3loader->comboBase
952 .$CFG->yui3version.'/build/simpleyui/simpleyui-min.js&'
953 .$CFG->yui3version.'/build/loader/loader-min.js"></script>';
955 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssreset/reset-min.css" />';
956 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssfonts/fonts-min.css" />';
957 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssgrids/grids-min.css" />';
958 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.'cssbase/base-min.css" />';
959 $code .= '<script type="text/javascript" src="'.$this->yui3loader->base.'simpleyui/simpleyui-min.js"></script>';
960 $code .= '<script type="text/javascript" src="'.$this->yui3loader->base.'loader/loader-min.js"></script>';
964 if ($this->yui3loader->filter === 'RAW') {
965 $code = str_replace('-min.css', '.css', $code);
966 $code = str_replace('-min.js', '.js', $code);
967 } else if ($this->yui3loader->filter === 'DEBUG') {
968 $code = str_replace('-min.css', '.css', $code);
969 $code = str_replace('-min.js', '-debug.js', $code);
976 * Returns html tags needed for inclusion of theme CSS.
980 protected function get_css_code() {
981 // First of all the theme CSS, then any custom CSS
982 // Please note custom CSS is strongly discouraged,
983 // because it can not be overridden by themes!
984 // It is suitable only for things like mod/data which accepts CSS from teachers.
985 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
987 // This line of code may look funny but it is currently required in order
988 // to avoid MASSIVE display issues in Internet Explorer.
989 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
990 // ignored whenever another resource is added until such time as a redraw
991 // is forced, usually by moving the mouse over the affected element.
992 $code = html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
994 $urls = $this->cssthemeurls + $this->cssurls;
995 foreach ($urls as $url) {
996 $attributes['href'] = $url;
997 $code .= html_writer::empty_tag('link', $attributes) . "\n";
998 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
999 unset($attributes['id']);
1006 * Adds extra modules specified after printing of page header.
1010 protected function get_extra_modules_code() {
1011 if (empty($this->extramodules)) {
1014 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1018 * Generate any HTML that needs to go inside the <head> tag.
1020 * Normally, this method is called automatically by the code that prints the
1021 * <head> tag. You should not normally need to call it in your own code.
1023 * @param moodle_page $page
1024 * @param core_renderer $renderer
1025 * @return string the HTML code to to inside the <head> tag.
1027 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1030 // Note: the $page and $output are not stored here because it would
1031 // create circular references in memory which prevents garbage collection.
1032 $this->init_requirements_data($page, $renderer);
1034 // YUI3 JS and CSS is always loaded first - it is cached in browser.
1035 $output = $this->get_yui3lib_headcode();
1037 // Now theme CSS + custom CSS in this specific order.
1038 $output .= $this->get_css_code();
1040 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1041 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1042 // this needs to be done before including any other script.
1043 $js = "var M = {}; M.yui = {};
1044 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;};
1045 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('/');};
1046 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";
1047 $js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n";
1048 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1049 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1050 $js = str_replace('"@GALLERYCONFIGFN@"', 'galleryConfigFn', $js);
1051 $js = str_replace('"@MOODLECONFIGFN@"', 'moodleConfigFn', $js);
1052 $js = str_replace('"@2IN3CONFIGFN@"', 'yui2in3ConfigFn', $js);
1054 $output .= html_writer::script($js);
1056 // Link our main JS file, all core stuff should be there.
1057 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1060 if ($this->jsinitvariables['head']) {
1062 foreach ($this->jsinitvariables['head'] as $data) {
1063 list($var, $value) = $data;
1064 $js .= js_writer::set_variable($var, $value, true);
1066 $output .= html_writer::script($js);
1069 // All the other linked things from HEAD - there should be as few as possible.
1070 if ($this->jsincludes['head']) {
1071 foreach ($this->jsincludes['head'] as $url) {
1072 $output .= html_writer::script('', $url);
1076 // Mark head sending done, it is not possible to anything there.
1077 $this->headdone = true;
1083 * Generate any HTML that needs to go at the start of the <body> tag.
1085 * Normally, this method is called automatically by the code that prints the
1086 * <head> tag. You should not normally need to call it in your own code.
1088 * @return string the HTML code to go at the start of the <body> tag.
1090 public function get_top_of_body_code() {
1091 // First the skip links.
1093 $attributes = array('class'=>'skip');
1094 foreach ($this->skiplinks as $url => $text) {
1095 $attributes['href'] = '#' . $url;
1096 $links .= html_writer::tag('a', $text, $attributes);
1098 $output = html_writer::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1100 // Then the clever trick for hiding of things not needed when JS works.
1101 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1102 $this->topofbodydone = true;
1107 * Generate any HTML that needs to go at the end of the page.
1109 * Normally, this method is called automatically by the code that prints the
1110 * page footer. You should not normally need to call it in your own code.
1112 * @return string the HTML code to to at the end of the page.
1114 public function get_end_code() {
1117 // Add other requested modules.
1118 $output = $this->get_extra_modules_code();
1120 // All the other linked scripts - there should be as few as possible.
1121 if ($this->jsincludes['footer']) {
1122 foreach ($this->jsincludes['footer'] as $url) {
1123 $output .= html_writer::script('', $url);
1127 // Add all needed strings.
1128 if (!empty($this->stringsforjs)) {
1130 foreach ($this->stringsforjs as $component=>$v) {
1131 foreach($v as $indentifier => $langstring) {
1132 $strings[$component][$indentifier] = $langstring->out();
1135 $output .= html_writer::script(js_writer::set_variable('M.str', $strings));
1139 if ($this->jsinitvariables['footer']) {
1141 foreach ($this->jsinitvariables['footer'] as $data) {
1142 list($var, $value) = $data;
1143 $js .= js_writer::set_variable($var, $value, true);
1145 $output .= html_writer::script($js);
1148 $inyuijs = $this->get_javascript_code(false);
1149 $ondomreadyjs = $this->get_javascript_code(true);
1150 $jsinit = $this->get_javascript_init_code();
1151 $handlersjs = $this->get_event_handler_code();
1153 // There is no global Y, make sure it is available in your scope.
1154 $js = "YUI().use('node', function(Y) {\n{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}\n});";
1156 $output .= html_writer::script($js);
1162 * Have we already output the code in the <head> tag?
1166 public function is_head_done() {
1167 return $this->headdone;
1171 * Have we already output the code at the start of the <body> tag?
1175 public function is_top_of_body_done() {
1176 return $this->topofbodydone;
1181 * Invalidate all server and client side JS caches.
1183 function js_reset_all_caches() {
1185 require_once("$CFG->libdir/filelib.php");
1188 if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
1189 // This resolves problems when reset is requested repeatedly within 1s,
1190 // the < 1h condition prevents accidental switching to future dates
1191 // because we might not recover from it.
1192 $next = $CFG->jsrev+1;
1195 set_config('jsrev', $next);
1196 fulldelete("$CFG->cachedir/js");