MDL-33741 file_info: check capability when serving file in coursecat description
[moodle.git] / lib / outputrequirementslib.php
blobe79308d7168cc7181a6ef1247659608ab52e9420
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
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
24 * @package core
25 * @category output
28 defined('MOODLE_INTERNAL') || die();
30 /**
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
37 * <pre>
38 * $PAGE->requires->js_call_amd('mod_forum/view', 'init');
39 * </pre>
41 * It also supports obsoleted coding style with/without YUI3 modules.
42 * <pre>
43 * $PAGE->requires->js_init_call('M.mod_forum.init_view');
44 * $PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overridable via themes!
45 * $PAGE->requires->js('/mod/mymod/script.js');
46 * $PAGE->requires->js('/mod/mymod/small_but_urgent.js', true);
47 * $PAGE->requires->js_function_call('init_mymod', array($data), true);
48 * </pre>
50 * There are some natural restrictions on some methods. For example, {@link css()}
51 * can only be called before the <head> tag is output. See the comments on the
52 * individual methods for details.
54 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
55 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
56 * @since Moodle 2.0
57 * @package core
58 * @category output
60 class page_requirements_manager {
62 /**
63 * @var array List of string available from JS
65 protected $stringsforjs = array();
67 /**
68 * @var array List of get_string $a parameters - used for validation only.
70 protected $stringsforjs_as = array();
72 /**
73 * @var array List of JS variables to be initialised
75 protected $jsinitvariables = array('head'=>array(), 'footer'=>array());
77 /**
78 * @var array Included JS scripts
80 protected $jsincludes = array('head'=>array(), 'footer'=>array());
82 /**
83 * @var array Inline scripts using RequireJS module loading.
85 protected $amdjscode = array('');
87 /**
88 * @var array List of needed function calls
90 protected $jscalls = array('normal'=>array(), 'ondomready'=>array());
92 /**
93 * @var array List of skip links, those are needed for accessibility reasons
95 protected $skiplinks = array();
97 /**
98 * @var array Javascript code used for initialisation of page, it should
99 * be relatively small
101 protected $jsinitcode = array();
104 * @var array of moodle_url Theme sheets, initialised only from core_renderer
106 protected $cssthemeurls = array();
109 * @var array of moodle_url List of custom theme sheets, these are strongly discouraged!
110 * Useful mostly only for CSS submitted by teachers that is not part of the theme.
112 protected $cssurls = array();
115 * @var array List of requested event handlers
117 protected $eventhandlers = array();
120 * @var array Extra modules
122 protected $extramodules = array();
125 * @var array trackes the names of bits of HTML that are only required once
126 * per page. See {@link has_one_time_item_been_created()},
127 * {@link set_one_time_item_created()} and {@link should_create_one_time_item_now()}.
129 protected $onetimeitemsoutput = array();
132 * @var bool Flag indicated head stuff already printed
134 protected $headdone = false;
137 * @var bool Flag indicating top of body already printed
139 protected $topofbodydone = false;
142 * @var stdClass YUI PHPLoader instance responsible for YUI3 loading from PHP only
144 protected $yui3loader;
147 * @var YUI_config default YUI loader configuration
149 protected $YUI_config;
152 * @var array $yuicssmodules
154 protected $yuicssmodules = array();
157 * @var array Some config vars exposed in JS, please no secret stuff there
159 protected $M_cfg;
162 * @var array list of requested jQuery plugins
164 protected $jqueryplugins = array();
167 * @var array list of jQuery plugin overrides
169 protected $jquerypluginoverrides = array();
172 * Page requirements constructor.
174 public function __construct() {
175 global $CFG;
177 // You may need to set up URL rewrite rule because oversized URLs might not be allowed by web server.
178 $sep = empty($CFG->yuislasharguments) ? '?' : '/';
180 $this->yui3loader = new stdClass();
181 $this->YUI_config = new YUI_config();
183 if (is_https()) {
184 // On HTTPS sites all JS must be loaded from https sites,
185 // YUI CDN does not support https yet, sorry.
186 $CFG->useexternalyui = 0;
189 // Set up some loader options.
190 $this->yui3loader->local_base = $CFG->httpswwwroot . '/lib/yuilib/'. $CFG->yui3version . '/';
191 $this->yui3loader->local_comboBase = $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep;
193 if (!empty($CFG->useexternalyui)) {
194 $this->yui3loader->base = 'http://yui.yahooapis.com/' . $CFG->yui3version . '/';
195 $this->yui3loader->comboBase = 'http://yui.yahooapis.com/combo?';
196 } else {
197 $this->yui3loader->base = $this->yui3loader->local_base;
198 $this->yui3loader->comboBase = $this->yui3loader->local_comboBase;
201 // Enable combo loader? This significantly helps with caching and performance!
202 $this->yui3loader->combine = !empty($CFG->yuicomboloading);
204 $jsrev = $this->get_jsrev();
206 // Set up JS YUI loader helper object.
207 $this->YUI_config->base = $this->yui3loader->base;
208 $this->YUI_config->comboBase = $this->yui3loader->comboBase;
209 $this->YUI_config->combine = $this->yui3loader->combine;
211 // If we've had to patch any YUI modules between releases, we must override the YUI configuration to include them.
212 // For important information on patching YUI modules, please see http://docs.moodle.org/dev/YUI/Patching.
213 if (!empty($CFG->yuipatchedmodules) && !empty($CFG->yuipatchlevel)) {
214 $this->YUI_config->define_patched_core_modules($this->yui3loader->local_comboBase,
215 $CFG->yui3version,
216 $CFG->yuipatchlevel,
217 $CFG->yuipatchedmodules);
220 $configname = $this->YUI_config->set_config_source('lib/yui/config/yui2.js');
221 $this->YUI_config->add_group('yui2', array(
222 // Loader configuration for our 2in3, for now ignores $CFG->useexternalyui.
223 'base' => $CFG->httpswwwroot . '/lib/yuilib/2in3/' . $CFG->yui2version . '/build/',
224 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
225 'combine' => $this->yui3loader->combine,
226 'ext' => false,
227 'root' => '2in3/' . $CFG->yui2version .'/build/',
228 'patterns' => array(
229 'yui2-' => array(
230 'group' => 'yui2',
231 'configFn' => $configname,
235 $configname = $this->YUI_config->set_config_source('lib/yui/config/moodle.js');
236 $this->YUI_config->add_group('moodle', array(
237 'name' => 'moodle',
238 'base' => $CFG->httpswwwroot . '/theme/yui_combo.php' . $sep . 'm/' . $jsrev . '/',
239 'combine' => $this->yui3loader->combine,
240 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php'.$sep,
241 'ext' => false,
242 'root' => 'm/'.$jsrev.'/', // Add the rev to the root path so that we can control caching.
243 'patterns' => array(
244 'moodle-' => array(
245 'group' => 'moodle',
246 'configFn' => $configname,
251 $this->YUI_config->add_group('gallery', array(
252 'name' => 'gallery',
253 'base' => $CFG->httpswwwroot . '/lib/yuilib/gallery/',
254 'combine' => $this->yui3loader->combine,
255 'comboBase' => $CFG->httpswwwroot . '/theme/yui_combo.php' . $sep,
256 'ext' => false,
257 'root' => 'gallery/' . $jsrev . '/',
258 'patterns' => array(
259 'gallery-' => array(
260 'group' => 'gallery',
265 // Set some more loader options applying to groups too.
266 if ($CFG->debugdeveloper) {
267 // When debugging is enabled, we want to load the non-minified (RAW) versions of YUI library modules rather
268 // than the DEBUG versions as these generally generate too much logging for our purposes.
269 // However we do want the DEBUG versions of our Moodle-specific modules.
270 // To debug a YUI-specific issue, change the yui3loader->filter value to DEBUG.
271 $this->YUI_config->filter = 'RAW';
272 $this->YUI_config->groups['moodle']['filter'] = 'DEBUG';
274 // We use the yui3loader->filter setting when writing the YUI3 seed scripts into the header.
275 $this->yui3loader->filter = $this->YUI_config->filter;
276 $this->YUI_config->debug = true;
277 } else {
278 $this->yui3loader->filter = null;
279 $this->YUI_config->groups['moodle']['filter'] = null;
280 $this->YUI_config->debug = false;
283 // Include the YUI config log filters.
284 if (!empty($CFG->yuilogexclude) && is_array($CFG->yuilogexclude)) {
285 $this->YUI_config->logExclude = $CFG->yuilogexclude;
287 if (!empty($CFG->yuiloginclude) && is_array($CFG->yuiloginclude)) {
288 $this->YUI_config->logInclude = $CFG->yuiloginclude;
290 if (!empty($CFG->yuiloglevel)) {
291 $this->YUI_config->logLevel = $CFG->yuiloglevel;
294 // Add the moodle group's module data.
295 $this->YUI_config->add_moodle_metadata();
297 // Every page should include definition of following modules.
298 $this->js_module($this->find_module('core_filepicker'));
302 * Return the safe config values that get set for javascript in "M.cfg".
304 * @since 2.9
305 * @return array List of safe config values that are available to javascript.
307 public function get_config_for_javascript(moodle_page $page, renderer_base $renderer) {
308 global $CFG;
310 if (empty($this->M_cfg)) {
311 // JavaScript should always work with $CFG->httpswwwroot rather than $CFG->wwwroot.
312 // Otherwise, in some situations, users will get warnings about insecure content
313 // on secure pages from their web browser.
315 $this->M_cfg = array(
316 'wwwroot' => $CFG->httpswwwroot, // Yes, really. See above.
317 'sesskey' => sesskey(),
318 'loadingicon' => $renderer->pix_url('i/loading_small', 'moodle')->out(false),
319 'themerev' => theme_get_revision(),
320 'slasharguments' => (int)(!empty($CFG->slasharguments)),
321 'theme' => $page->theme->name,
322 'jsrev' => $this->get_jsrev(),
323 'admin' => $CFG->admin,
324 'svgicons' => $page->theme->use_svg_icons()
326 if ($CFG->debugdeveloper) {
327 $this->M_cfg['developerdebug'] = true;
329 if (defined('BEHAT_SITE_RUNNING')) {
330 $this->M_cfg['behatsiterunning'] = true;
334 return $this->M_cfg;
338 * Initialise with the bits of JavaScript that every Moodle page should have.
340 * @param moodle_page $page
341 * @param core_renderer $renderer
343 protected function init_requirements_data(moodle_page $page, core_renderer $renderer) {
344 global $CFG;
346 // Init the js config.
347 $this->get_config_for_javascript($page, $renderer);
349 // Accessibility stuff.
350 $this->skip_link_to('maincontent', get_string('tocontent', 'access'));
352 // Add strings used on many pages.
353 $this->string_for_js('confirmation', 'admin');
354 $this->string_for_js('cancel', 'moodle');
355 $this->string_for_js('yes', 'moodle');
357 // Alter links in top frame to break out of frames.
358 if ($page->pagelayout === 'frametop') {
359 $this->js_init_call('M.util.init_frametop');
362 // Include block drag/drop if editing is on
363 if ($page->user_is_editing()) {
364 $params = array(
365 'courseid' => $page->course->id,
366 'pagetype' => $page->pagetype,
367 'pagelayout' => $page->pagelayout,
368 'subpage' => $page->subpage,
369 'regions' => $page->blocks->get_regions(),
370 'contextid' => $page->context->id,
372 if (!empty($page->cm->id)) {
373 $params['cmid'] = $page->cm->id;
375 // Strings for drag and drop.
376 $this->strings_for_js(array('movecontent',
377 'tocontent',
378 'emptydragdropregion'),
379 'moodle');
380 $page->requires->yui_module('moodle-core-blocks', 'M.core_blocks.init_dragdrop', array($params), null, true);
383 // Include the YUI CSS Modules.
384 $page->requires->set_yuicssmodules($page->theme->yuicssmodules);
388 * Determine the correct JS Revision to use for this load.
390 * @return int the jsrev to use.
392 protected function get_jsrev() {
393 global $CFG;
395 if (empty($CFG->cachejs)) {
396 $jsrev = -1;
397 } else if (empty($CFG->jsrev)) {
398 $jsrev = 1;
399 } else {
400 $jsrev = $CFG->jsrev;
403 return $jsrev;
407 * Ensure that the specified JavaScript file is linked to from this page.
409 * NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
410 * and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.
412 * By default the link is put at the end of the page, since this gives best page-load performance.
414 * Even if a particular script is requested more than once, it will only be linked
415 * to once.
417 * @param string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
418 * For example '/mod/mymod/customscripts.js'; use moodle_url for external scripts
419 * @param bool $inhead initialise in head
421 public function js($url, $inhead = false) {
422 $url = $this->js_fix_url($url);
423 $where = $inhead ? 'head' : 'footer';
424 $this->jsincludes[$where][$url->out()] = $url;
428 * Request inclusion of jQuery library in the page.
430 * NOTE: this should not be used in official Moodle distribution!
432 * We are going to bundle jQuery 1.9.x until we drop support
433 * all support for IE 6-8. Use $PAGE->requires->jquery_plugin('migrate')
434 * for code written for earlier jQuery versions.
436 * {@see http://docs.moodle.org/dev/jQuery}
438 public function jquery() {
439 $this->jquery_plugin('jquery');
443 * Request inclusion of jQuery plugin.
445 * NOTE: this should not be used in official Moodle distribution!
447 * jQuery plugins are located in plugin/jquery/* subdirectory,
448 * plugin/jquery/plugins.php lists all available plugins.
450 * Included core plugins:
451 * - jQuery UI
452 * - jQuery Migrate (useful for code written for previous UI version)
454 * Add-ons may include extra jQuery plugins in jquery/ directory,
455 * plugins.php file defines the mapping between plugin names and
456 * necessary page includes.
458 * Examples:
459 * <code>
460 * // file: mod/xxx/view.php
461 * $PAGE->requires->jquery();
462 * $PAGE->requires->jquery_plugin('ui');
463 * $PAGE->requires->jquery_plugin('ui-css');
464 * </code>
466 * <code>
467 * // file: theme/yyy/lib.php
468 * function theme_yyy_page_init(moodle_page $page) {
469 * $page->requires->jquery();
470 * $page->requires->jquery_plugin('ui');
471 * $page->requires->jquery_plugin('ui-css');
473 * </code>
475 * <code>
476 * // file: blocks/zzz/block_zzz.php
477 * public function get_required_javascript() {
478 * parent::get_required_javascript();
479 * $this->page->requires->jquery();
480 * $page->requires->jquery_plugin('ui');
481 * $page->requires->jquery_plugin('ui-css');
483 * </code>
485 * {@see http://docs.moodle.org/dev/jQuery}
487 * @param string $plugin name of the jQuery plugin as defined in jquery/plugins.php
488 * @param string $component name of the component
489 * @return bool success
491 public function jquery_plugin($plugin, $component = 'core') {
492 global $CFG;
494 if ($this->headdone) {
495 debugging('Can not add jQuery plugins after starting page output!');
496 return false;
499 if ($component !== 'core' and in_array($plugin, array('jquery', 'ui', 'ui-css', 'migrate'))) {
500 debugging("jQuery plugin '$plugin' is included in Moodle core, other components can not use the same name.", DEBUG_DEVELOPER);
501 $component = 'core';
502 } else if ($component !== 'core' and strpos($component, '_') === false) {
503 // Let's normalise the legacy activity names, Frankenstyle rulez!
504 $component = 'mod_' . $component;
507 if (empty($this->jqueryplugins) and ($component !== 'core' or $plugin !== 'jquery')) {
508 // Make sure the jQuery itself is always loaded first,
509 // the order of all other plugins depends on order of $PAGE_>requires->.
510 $this->jquery_plugin('jquery', 'core');
513 if (isset($this->jqueryplugins[$plugin])) {
514 // No problem, we already have something, first Moodle plugin to register the jQuery plugin wins.
515 return true;
518 $componentdir = core_component::get_component_directory($component);
519 if (!file_exists($componentdir) or !file_exists("$componentdir/jquery/plugins.php")) {
520 debugging("Can not load jQuery plugin '$plugin', missing plugins.php in component '$component'.", DEBUG_DEVELOPER);
521 return false;
524 $plugins = array();
525 require("$componentdir/jquery/plugins.php");
527 if (!isset($plugins[$plugin])) {
528 debugging("jQuery plugin '$plugin' can not be found in component '$component'.", DEBUG_DEVELOPER);
529 return false;
532 $this->jqueryplugins[$plugin] = new stdClass();
533 $this->jqueryplugins[$plugin]->plugin = $plugin;
534 $this->jqueryplugins[$plugin]->component = $component;
535 $this->jqueryplugins[$plugin]->urls = array();
537 foreach ($plugins[$plugin]['files'] as $file) {
538 if ($CFG->debugdeveloper) {
539 if (!file_exists("$componentdir/jquery/$file")) {
540 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
541 continue;
543 $file = str_replace('.min.css', '.css', $file);
544 $file = str_replace('.min.js', '.js', $file);
546 if (!file_exists("$componentdir/jquery/$file")) {
547 debugging("Invalid file '$file' specified in jQuery plugin '$plugin' in component '$component'");
548 continue;
550 if (!empty($CFG->slasharguments)) {
551 $url = new moodle_url("$CFG->httpswwwroot/theme/jquery.php");
552 $url->set_slashargument("/$component/$file");
554 } else {
555 // This is not really good, we need slasharguments for relative links, this means no caching...
556 $path = realpath("$componentdir/jquery/$file");
557 if (strpos($path, $CFG->dirroot) === 0) {
558 $url = $CFG->httpswwwroot.preg_replace('/^'.preg_quote($CFG->dirroot, '/').'/', '', $path);
559 // Replace all occurences of backslashes characters in url to forward slashes.
560 $url = str_replace('\\', '/', $url);
561 $url = new moodle_url($url);
562 } else {
563 // Bad luck, fix your server!
564 debugging("Moodle jQuery integration requires 'slasharguments' setting to be enabled.");
565 continue;
568 $this->jqueryplugins[$plugin]->urls[] = $url;
571 return true;
575 * Request replacement of one jQuery plugin by another.
577 * This is useful when themes want to replace the jQuery UI theme,
578 * the problem is that theme can not prevent others from including the core ui-css plugin.
580 * Example:
581 * 1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
582 * 2/ write theme/yourtheme/jquery/plugins.php
583 * 3/ init jQuery from theme
585 * <code>
586 * // file theme/yourtheme/lib.php
587 * function theme_yourtheme_page_init($page) {
588 * $page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
589 * $page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
591 * </code>
593 * This code prevents loading of standard 'ui-css' which my be requested by other plugins,
594 * the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.
596 * {@see http://docs.moodle.org/dev/jQuery}
598 * @param string $oldplugin original plugin
599 * @param string $newplugin the replacement
601 public function jquery_override_plugin($oldplugin, $newplugin) {
602 if ($this->headdone) {
603 debugging('Can not override jQuery plugins after starting page output!');
604 return;
606 $this->jquerypluginoverrides[$oldplugin] = $newplugin;
610 * Return jQuery related markup for page start.
611 * @return string
613 protected function get_jquery_headcode() {
614 if (empty($this->jqueryplugins['jquery'])) {
615 // If nobody requested jQuery then do not bother to load anything.
616 // This may be useful for themes that want to override 'ui-css' only if requested by something else.
617 return '';
620 $included = array();
621 $urls = array();
623 foreach ($this->jqueryplugins as $name => $unused) {
624 if (isset($included[$name])) {
625 continue;
627 if (array_key_exists($name, $this->jquerypluginoverrides)) {
628 // The following loop tries to resolve the replacements,
629 // use max 100 iterations to prevent infinite loop resulting
630 // in blank page.
631 $cyclic = true;
632 $oldname = $name;
633 for ($i=0; $i<100; $i++) {
634 $name = $this->jquerypluginoverrides[$name];
635 if (!array_key_exists($name, $this->jquerypluginoverrides)) {
636 $cyclic = false;
637 break;
640 if ($cyclic) {
641 // We can not do much with cyclic references here, let's use the old plugin.
642 $name = $oldname;
643 debugging("Cyclic overrides detected for jQuery plugin '$name'");
645 } else if (empty($name)) {
646 // Developer requested removal of the plugin.
647 continue;
649 } else if (!isset($this->jqueryplugins[$name])) {
650 debugging("Unknown jQuery override plugin '$name' detected");
651 $name = $oldname;
653 } else if (isset($included[$name])) {
654 // The plugin was already included, easy.
655 continue;
659 $plugin = $this->jqueryplugins[$name];
660 $urls = array_merge($urls, $plugin->urls);
661 $included[$name] = true;
664 $output = '';
665 $attributes = array('rel' => 'stylesheet', 'type' => 'text/css');
666 foreach ($urls as $url) {
667 if (preg_match('/\.js$/', $url)) {
668 $output .= html_writer::script('', $url);
669 } else if (preg_match('/\.css$/', $url)) {
670 $attributes['href'] = $url;
671 $output .= html_writer::empty_tag('link', $attributes) . "\n";
675 return $output;
679 * Returns the actual url through which a script is served.
681 * @param moodle_url|string $url full moodle url, or shortened path to script
682 * @return moodle_url
684 protected function js_fix_url($url) {
685 global $CFG;
687 if ($url instanceof moodle_url) {
688 return $url;
689 } else if (strpos($url, '/') === 0) {
690 // Fix the admin links if needed.
691 if ($CFG->admin !== 'admin') {
692 if (strpos($url, "/admin/") === 0) {
693 $url = preg_replace("|^/admin/|", "/$CFG->admin/", $url);
696 if (debugging()) {
697 // Check file existence only when in debug mode.
698 if (!file_exists($CFG->dirroot . strtok($url, '?'))) {
699 throw new coding_exception('Attempt to require a JavaScript file that does not exist.', $url);
702 if (substr($url, -3) === '.js') {
703 $jsrev = $this->get_jsrev();
704 if (empty($CFG->slasharguments)) {
705 return new moodle_url($CFG->httpswwwroot.'/lib/javascript.php', array('rev'=>$jsrev, 'jsfile'=>$url));
706 } else {
707 $returnurl = new moodle_url($CFG->httpswwwroot.'/lib/javascript.php');
708 $returnurl->set_slashargument('/'.$jsrev.$url);
709 return $returnurl;
711 } else {
712 return new moodle_url($CFG->httpswwwroot.$url);
714 } else {
715 throw new coding_exception('Invalid JS url, it has to be shortened url starting with / or moodle_url instance.', $url);
720 * Find out if JS module present and return details.
722 * @param string $component name of component in frankenstyle, ex: core_group, mod_forum
723 * @return array description of module or null if not found
725 protected function find_module($component) {
726 global $CFG, $PAGE;
728 $module = null;
730 if (strpos($component, 'core_') === 0) {
731 // Must be some core stuff - list here is not complete, this is just the stuff used from multiple places
732 // so that we do nto have to repeat the definition of these modules over and over again.
733 switch($component) {
734 case 'core_filepicker':
735 $module = array('name' => 'core_filepicker',
736 'fullpath' => '/repository/filepicker.js',
737 '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', 'escape', 'moodle-core_filepicker'),
738 'strings' => array(array('lastmodified', 'moodle'), array('name', 'moodle'), array('type', 'repository'), array('size', 'repository'),
739 array('invalidjson', 'repository'), array('error', 'moodle'), array('info', 'moodle'),
740 array('nofilesattached', 'repository'), array('filepicker', 'repository'), array('logout', 'repository'),
741 array('nofilesavailable', 'repository'), array('norepositoriesavailable', 'repository'),
742 array('fileexistsdialogheader', 'repository'), array('fileexistsdialog_editor', 'repository'),
743 array('fileexistsdialog_filemanager', 'repository'), array('renameto', 'repository'),
744 array('referencesexist', 'repository'), array('select', 'repository')
746 break;
747 case 'core_comment':
748 $module = array('name' => 'core_comment',
749 'fullpath' => '/comment/comment.js',
750 'requires' => array('base', 'io-base', 'node', 'json', 'yui2-animation', 'overlay'),
751 'strings' => array(array('confirmdeletecomments', 'admin'), array('yes', 'moodle'), array('no', 'moodle'))
753 break;
754 case 'core_role':
755 $module = array('name' => 'core_role',
756 'fullpath' => '/admin/roles/module.js',
757 'requires' => array('node', 'cookie'));
758 break;
759 case 'core_completion':
760 $module = array('name' => 'core_completion',
761 'fullpath' => '/course/completion.js');
762 break;
763 case 'core_message':
764 $module = array('name' => 'core_message',
765 'requires' => array('base', 'node', 'event', 'node-event-simulate'),
766 'fullpath' => '/message/module.js');
767 break;
768 case 'core_group':
769 $module = array('name' => 'core_group',
770 'fullpath' => '/group/module.js',
771 'requires' => array('node', 'overlay', 'event-mouseenter'));
772 break;
773 case 'core_question_engine':
774 $module = array('name' => 'core_question_engine',
775 'fullpath' => '/question/qengine.js',
776 'requires' => array('node', 'event'));
777 break;
778 case 'core_rating':
779 $module = array('name' => 'core_rating',
780 'fullpath' => '/rating/module.js',
781 'requires' => array('node', 'event', 'overlay', 'io-base', 'json'));
782 break;
783 case 'core_dndupload':
784 $module = array('name' => 'core_dndupload',
785 'fullpath' => '/lib/form/dndupload.js',
786 'requires' => array('node', 'event', 'json', 'core_filepicker'),
787 'strings' => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'),
788 array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle'), array('maxbytesforfile', 'moodle'),
789 array('maxareabytesreached', 'moodle'), array('serverconnection', 'error'),
791 break;
794 } else {
795 if ($dir = core_component::get_component_directory($component)) {
796 if (file_exists("$dir/module.js")) {
797 if (strpos($dir, $CFG->dirroot.'/') === 0) {
798 $dir = substr($dir, strlen($CFG->dirroot));
799 $module = array('name'=>$component, 'fullpath'=>"$dir/module.js", 'requires' => array());
805 return $module;
809 * Append YUI3 module to default YUI3 JS loader.
810 * The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}
812 * @param string|array $module name of module (details are autodetected), or full module specification as array
813 * @return void
815 public function js_module($module) {
816 global $CFG;
818 if (empty($module)) {
819 throw new coding_exception('Missing YUI3 module name or full description.');
822 if (is_string($module)) {
823 $module = $this->find_module($module);
826 if (empty($module) or empty($module['name']) or empty($module['fullpath'])) {
827 throw new coding_exception('Missing YUI3 module details.');
830 $module['fullpath'] = $this->js_fix_url($module['fullpath'])->out(false);
831 // Add all needed strings.
832 if (!empty($module['strings'])) {
833 foreach ($module['strings'] as $string) {
834 $identifier = $string[0];
835 $component = isset($string[1]) ? $string[1] : 'moodle';
836 $a = isset($string[2]) ? $string[2] : null;
837 $this->string_for_js($identifier, $component, $a);
840 unset($module['strings']);
842 // Process module requirements and attempt to load each. This allows
843 // moodle modules to require each other.
844 if (!empty($module['requires'])){
845 foreach ($module['requires'] as $requirement) {
846 $rmodule = $this->find_module($requirement);
847 if (is_array($rmodule)) {
848 $this->js_module($rmodule);
853 if ($this->headdone) {
854 $this->extramodules[$module['name']] = $module;
855 } else {
856 $this->YUI_config->add_module_config($module['name'], $module);
861 * Returns true if the module has already been loaded.
863 * @param string|array $module
864 * @return bool True if the module has already been loaded
866 protected function js_module_loaded($module) {
867 if (is_string($module)) {
868 $modulename = $module;
869 } else {
870 $modulename = $module['name'];
872 return array_key_exists($modulename, $this->YUI_config->modules) ||
873 array_key_exists($modulename, $this->extramodules);
877 * Ensure that the specified CSS file is linked to from this page.
879 * Because stylesheet links must go in the <head> part of the HTML, you must call
880 * this function before {@link get_head_code()} is called. That normally means before
881 * the call to print_header. If you call it when it is too late, an exception
882 * will be thrown.
884 * Even if a particular style sheet is requested more than once, it will only
885 * be linked to once.
887 * Please note use of this feature is strongly discouraged,
888 * it is suitable only for places where CSS is submitted directly by teachers.
889 * (Students must not be allowed to submit any external CSS because it may
890 * contain embedded javascript!). Example of correct use is mod/data.
892 * @param string $stylesheet The path to the .css file, relative to $CFG->wwwroot.
893 * For example:
894 * $PAGE->requires->css('mod/data/css.php?d='.$data->id);
896 public function css($stylesheet) {
897 global $CFG;
899 if ($this->headdone) {
900 throw new coding_exception('Cannot require a CSS file after &lt;head> has been printed.', $stylesheet);
903 if ($stylesheet instanceof moodle_url) {
904 // ok
905 } else if (strpos($stylesheet, '/') === 0) {
906 $stylesheet = new moodle_url($CFG->httpswwwroot.$stylesheet);
907 } else {
908 throw new coding_exception('Invalid stylesheet parameter.', $stylesheet);
911 $this->cssurls[$stylesheet->out()] = $stylesheet;
915 * Add theme stylesheet to page - do not use from plugin code,
916 * this should be called only from the core renderer!
918 * @param moodle_url $stylesheet
919 * @return void
921 public function css_theme(moodle_url $stylesheet) {
922 $this->cssthemeurls[] = $stylesheet;
926 * Ensure that a skip link to a given target is printed at the top of the <body>.
928 * You must call this function before {@link get_top_of_body_code()}, (if not, an exception
929 * will be thrown). That normally means you must call this before the call to print_header.
931 * If you ask for a particular skip link to be printed, it is then your responsibility
932 * to ensure that the appropriate <a name="..."> tag is printed in the body of the
933 * page, so that the skip link goes somewhere.
935 * Even if a particular skip link is requested more than once, only one copy of it will be output.
937 * @param string $target the name of anchor this link should go to. For example 'maincontent'.
938 * @param string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);
940 public function skip_link_to($target, $linktext) {
941 if ($this->topofbodydone) {
942 debugging('Page header already printed, can not add skip links any more, code needs to be fixed.');
943 return;
945 $this->skiplinks[$target] = $linktext;
949 * !!!DEPRECATED!!! please use js_init_call() if possible
950 * Ensure that the specified JavaScript function is called from an inline script
951 * somewhere on this page.
953 * By default the call will be put in a script tag at the
954 * end of the page after initialising Y instance, since this gives best page-load
955 * performance and allows you to use YUI3 library.
957 * If you request that a particular function is called several times, then
958 * that is what will happen (unlike linking to a CSS or JS file, where only
959 * one link will be output).
961 * The main benefit of the method is the automatic encoding of all function parameters.
963 * @deprecated
965 * @param string $function the name of the JavaScritp function to call. Can
966 * be a compound name like 'Y.Event.purgeElement'. Can also be
967 * used to create and object by using a 'function name' like 'new user_selector'.
968 * @param array $arguments and array of arguments to be passed to the function.
969 * When generating the function call, this will be escaped using json_encode,
970 * so passing objects and arrays should work.
971 * @param bool $ondomready If tru the function is only called when the dom is
972 * ready for manipulation.
973 * @param int $delay The delay before the function is called.
975 public function js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0) {
976 $where = $ondomready ? 'ondomready' : 'normal';
977 $this->jscalls[$where][] = array($function, $arguments, $delay);
981 * This function appends a block of code to the AMD specific javascript block executed
982 * in the page footer, just after loading the requirejs library.
984 * The code passed here can rely on AMD module loading, e.g. require('jquery', function($) {...});
986 * @param string $code The JS code to append.
988 public function js_amd_inline($code) {
989 $this->amdjscode[] = $code;
993 * This function creates a minimal JS script that requires and calls a single function from an AMD module with arguments.
994 * If it is called multiple times, it will be executed multiple times.
996 * @param string $fullmodule The format for module names is <component name>/<module name>.
997 * @param string $func The function from the module to call
998 * @param array $params The params to pass to the function. They will be json encoded, so no nasty classes/types please.
1000 public function js_call_amd($fullmodule, $func, $params = array()) {
1001 global $CFG;
1003 list($component, $module) = explode('/', $fullmodule, 2);
1005 $component = clean_param($component, PARAM_COMPONENT);
1006 $module = clean_param($module, PARAM_ALPHANUMEXT);
1007 $func = clean_param($func, PARAM_ALPHANUMEXT);
1009 $jsonparams = array();
1010 foreach ($params as $param) {
1011 $jsonparams[] = json_encode($param);
1013 $strparams = implode(', ', $jsonparams);
1014 if ($CFG->debugdeveloper) {
1015 $toomanyparamslimit = 1024;
1016 if (strlen($strparams) > $toomanyparamslimit) {
1017 debugging('Too many params passed to js_call_amd("' . $fullmodule . '", "' . $func . '")', DEBUG_DEVELOPER);
1021 $js = 'require(["' . $component . '/' . $module . '"], function(amd) { amd.' . $func . '(' . $strparams . '); });';
1023 $this->js_amd_inline($js);
1027 * Creates a JavaScript function call that requires one or more modules to be loaded.
1029 * This function can be used to include all of the standard YUI module types within JavaScript:
1030 * - YUI3 modules [node, event, io]
1031 * - YUI2 modules [yui2-*]
1032 * - Moodle modules [moodle-*]
1033 * - Gallery modules [gallery-*]
1035 * Before writing new code that makes extensive use of YUI, you should consider it's replacement AMD/JQuery.
1036 * @see js_call_amd()
1038 * @param array|string $modules One or more modules
1039 * @param string $function The function to call once modules have been loaded
1040 * @param array $arguments An array of arguments to pass to the function
1041 * @param string $galleryversion Deprecated: The gallery version to use
1042 * @param bool $ondomready
1044 public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1045 if (!is_array($modules)) {
1046 $modules = array($modules);
1049 if ($galleryversion != null) {
1050 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.');
1053 $jscode = 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
1054 if ($ondomready) {
1055 $jscode = "Y.on('domready', function() { $jscode });";
1057 $this->jsinitcode[] = $jscode;
1061 * Set the CSS Modules to be included from YUI.
1063 * @param array $modules The list of YUI CSS Modules to include.
1065 public function set_yuicssmodules(array $modules = array()) {
1066 $this->yuicssmodules = $modules;
1070 * Ensure that the specified JavaScript function is called from an inline script
1071 * from page footer.
1073 * @param string $function the name of the JavaScritp function to with init code,
1074 * usually something like 'M.mod_mymodule.init'
1075 * @param array $extraarguments and array of arguments to be passed to the function.
1076 * The first argument is always the YUI3 Y instance with all required dependencies
1077 * already loaded.
1078 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1079 * @param array $module JS module specification array
1081 public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1082 $jscode = js_writer::function_call_with_Y($function, $extraarguments);
1083 if (!$module) {
1084 // Detect module automatically.
1085 if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
1086 $module = $this->find_module($matches[1]);
1090 $this->js_init_code($jscode, $ondomready, $module);
1094 * Add short static javascript code fragment to page footer.
1095 * This is intended primarily for loading of js modules and initialising page layout.
1096 * Ideally the JS code fragment should be stored in plugin renderer so that themes
1097 * may override it.
1099 * @param string $jscode
1100 * @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
1101 * @param array $module JS module specification array
1103 public function js_init_code($jscode, $ondomready = false, array $module = null) {
1104 $jscode = trim($jscode, " ;\n"). ';';
1106 $uniqid = html_writer::random_id();
1107 $startjs = " M.util.js_pending('" . $uniqid . "');";
1108 $endjs = " M.util.js_complete('" . $uniqid . "');";
1110 if ($module) {
1111 $this->js_module($module);
1112 $modulename = $module['name'];
1113 $jscode = "$startjs Y.use('$modulename', function(Y) { $jscode $endjs });";
1116 if ($ondomready) {
1117 $jscode = "$startjs Y.on('domready', function() { $jscode $endjs });";
1120 $this->jsinitcode[] = $jscode;
1124 * Make a language string available to JavaScript.
1126 * All the strings will be available in a M.str object in the global namespace.
1127 * So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
1128 * then the JavaScript variable M.str.moodle.course will be 'Course', or the
1129 * equivalent in the current language.
1131 * The arguments to this function are just like the arguments to get_string
1132 * except that $component is not optional, and there are some aspects to consider
1133 * when the string contains {$a} placeholder.
1135 * If the string does not contain any {$a} placeholder, you can simply use
1136 * M.str.component.identifier to obtain it. If you prefer, you can call
1137 * M.util.get_string(identifier, component) to get the same result.
1139 * If you need to use {$a} placeholders, there are two options. Either the
1140 * placeholder should be substituted in PHP on server side or it should
1141 * be substituted in Javascript at client side.
1143 * To substitute the placeholder at server side, just provide the required
1144 * value for the placeholder when you require the string. Because each string
1145 * is only stored once in the JavaScript (based on $identifier and $module)
1146 * you cannot get the same string with two different values of $a. If you try,
1147 * an exception will be thrown. Once the placeholder is substituted, you can
1148 * use M.str or M.util.get_string() as shown above:
1150 * // Require the string in PHP and replace the placeholder.
1151 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
1152 * // Use the result of the substitution in Javascript.
1153 * alert(M.str.moodle.fullnamedisplay);
1155 * To substitute the placeholder at client side, use M.util.get_string()
1156 * function. It implements the same logic as {@link get_string()}:
1158 * // Require the string in PHP but keep {$a} as it is.
1159 * $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
1160 * // Provide the values on the fly in Javascript.
1161 * user = { firstname : 'Harry', lastname : 'Potter' }
1162 * alert(M.util.get_string('fullnamedisplay', 'moodle', user);
1164 * If you do need the same string expanded with different $a values in PHP
1165 * on server side, then the solution is to put them in your own data structure
1166 * (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
1168 * @param string $identifier the desired string.
1169 * @param string $component the language file to look in.
1170 * @param mixed $a any extra data to add into the string (optional).
1172 public function string_for_js($identifier, $component, $a = null) {
1173 if (!$component) {
1174 throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
1176 if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
1177 throw new coding_exception("Attempt to re-define already required string '$identifier' " .
1178 "from lang file '$component' with different \$a parameter?");
1180 if (!isset($this->stringsforjs[$component][$identifier])) {
1181 $this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
1182 $this->stringsforjs_as[$component][$identifier] = $a;
1187 * Make an array of language strings available for JS.
1189 * This function calls the above function {@link string_for_js()} for each requested
1190 * string in the $identifiers array that is passed to the argument for a single module
1191 * passed in $module.
1193 * <code>
1194 * $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
1196 * // The above is identical to calling:
1198 * $PAGE->requires->string_for_js('one', 'mymod', 'a');
1199 * $PAGE->requires->string_for_js('two', 'mymod');
1200 * $PAGE->requires->string_for_js('three', 'mymod', 3);
1201 * </code>
1203 * @param array $identifiers An array of desired strings
1204 * @param string $component The module to load for
1205 * @param mixed $a This can either be a single variable that gets passed as extra
1206 * information for every string or it can be an array of mixed data where the
1207 * key for the data matches that of the identifier it is meant for.
1210 public function strings_for_js($identifiers, $component, $a = null) {
1211 foreach ($identifiers as $key => $identifier) {
1212 if (is_array($a) && array_key_exists($key, $a)) {
1213 $extra = $a[$key];
1214 } else {
1215 $extra = $a;
1217 $this->string_for_js($identifier, $component, $extra);
1222 * !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
1224 * Make some data from PHP available to JavaScript code.
1226 * For example, if you call
1227 * <pre>
1228 * $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
1229 * </pre>
1230 * then in JavsScript mydata.name will be 'Moodle'.
1232 * @deprecated
1233 * @param string $variable the the name of the JavaScript variable to assign the data to.
1234 * Will probably work if you use a compound name like 'mybuttons.button[1]', but this
1235 * should be considered an experimental feature.
1236 * @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
1237 * so passing objects and arrays should work.
1238 * @param bool $inhead initialise in head
1239 * @return void
1241 public function data_for_js($variable, $data, $inhead=false) {
1242 $where = $inhead ? 'head' : 'footer';
1243 $this->jsinitvariables[$where][] = array($variable, $data);
1247 * Creates a YUI event handler.
1249 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1250 * @param string $event A valid DOM event (click, mousedown, change etc.)
1251 * @param string $function The name of the function to call
1252 * @param array $arguments An optional array of argument parameters to pass to the function
1254 public function event_handler($selector, $event, $function, array $arguments = null) {
1255 $this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
1259 * Returns code needed for registering of event handlers.
1260 * @return string JS code
1262 protected function get_event_handler_code() {
1263 $output = '';
1264 foreach ($this->eventhandlers as $h) {
1265 $output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
1267 return $output;
1271 * Get the inline JavaScript code that need to appear in a particular place.
1272 * @param bool $ondomready
1273 * @return string
1275 protected function get_javascript_code($ondomready) {
1276 $where = $ondomready ? 'ondomready' : 'normal';
1277 $output = '';
1278 if ($this->jscalls[$where]) {
1279 foreach ($this->jscalls[$where] as $data) {
1280 $output .= js_writer::function_call($data[0], $data[1], $data[2]);
1282 if (!empty($ondomready)) {
1283 $output = " Y.on('domready', function() {\n$output\n});";
1286 return $output;
1290 * Returns js code to be executed when Y is available.
1291 * @return string
1293 protected function get_javascript_init_code() {
1294 if (count($this->jsinitcode)) {
1295 return implode("\n", $this->jsinitcode) . "\n";
1297 return '';
1301 * Returns js code to load amd module loader, then insert inline script tags
1302 * that contain require() calls using RequireJS.
1303 * @return string
1305 protected function get_amd_footercode() {
1306 global $CFG;
1307 $output = '';
1308 $jsrev = $this->get_jsrev();
1310 $jsloader = new moodle_url($CFG->httpswwwroot . '/lib/javascript.php');
1311 $jsloader->set_slashargument('/' . $jsrev . '/');
1312 $requirejsloader = new moodle_url($CFG->httpswwwroot . '/lib/requirejs.php');
1313 $requirejsloader->set_slashargument('/' . $jsrev . '/');
1315 $requirejsconfig = file_get_contents($CFG->dirroot . '/lib/requirejs/moodle-config.js');
1317 // No extension required unless slash args is disabled.
1318 $jsextension = '.js';
1319 if (!empty($CFG->slasharguments)) {
1320 $jsextension = '';
1323 $requirejsconfig = str_replace('[BASEURL]', $requirejsloader, $requirejsconfig);
1324 $requirejsconfig = str_replace('[JSURL]', $jsloader, $requirejsconfig);
1325 $requirejsconfig = str_replace('[JSEXT]', $jsextension, $requirejsconfig);
1327 $output .= html_writer::script($requirejsconfig);
1328 if ($CFG->debugdeveloper) {
1329 $output .= html_writer::script('', $this->js_fix_url('/lib/requirejs/require.js'));
1330 } else {
1331 $output .= html_writer::script('', $this->js_fix_url('/lib/requirejs/require.min.js'));
1334 // First include must be to a module with no dependencies, this prevents multiple requests.
1335 $prefix = "require(['core/first'], function() {\n";
1336 $suffix = "\n});";
1337 $output .= html_writer::script($prefix . implode(";\n", $this->amdjscode) . $suffix);
1338 return $output;
1342 * Returns basic YUI3 CSS code.
1344 * @return string
1346 protected function get_yui3lib_headcss() {
1347 global $CFG;
1349 $yuiformat = '-min';
1350 if ($this->yui3loader->filter === 'RAW') {
1351 $yuiformat = '';
1354 $code = '';
1355 if ($this->yui3loader->combine) {
1356 if (!empty($this->yuicssmodules)) {
1357 $modules = array();
1358 foreach ($this->yuicssmodules as $module) {
1359 $modules[] = "$CFG->yui3version/$module/$module-min.css";
1361 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->comboBase.implode('&amp;', $modules).'" />';
1363 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
1365 } else {
1366 if (!empty($this->yuicssmodules)) {
1367 foreach ($this->yuicssmodules as $module) {
1368 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->base.$module.'/'.$module.'-min.css" />';
1371 $code .= '<link rel="stylesheet" type="text/css" href="'.$this->yui3loader->local_comboBase.'rollup/'.$CFG->yui3version.'/yui-moodlesimple' . $yuiformat . '.css" />';
1374 if ($this->yui3loader->filter === 'RAW') {
1375 $code = str_replace('-min.css', '.css', $code);
1376 } else if ($this->yui3loader->filter === 'DEBUG') {
1377 $code = str_replace('-min.css', '.css', $code);
1379 return $code;
1383 * Returns basic YUI3 JS loading code.
1385 * @return string
1387 protected function get_yui3lib_headcode() {
1388 global $CFG;
1390 $jsrev = $this->get_jsrev();
1392 $yuiformat = '-min';
1393 if ($this->yui3loader->filter === 'RAW') {
1394 $yuiformat = '';
1397 $format = '-min';
1398 if ($this->YUI_config->groups['moodle']['filter'] === 'DEBUG') {
1399 $format = '-debug';
1402 $rollupversion = $CFG->yui3version;
1403 if (!empty($CFG->yuipatchlevel)) {
1404 $rollupversion .= '_' . $CFG->yuipatchlevel;
1407 $baserollups = array(
1408 'rollup/' . $rollupversion . "/yui-moodlesimple{$yuiformat}.js",
1409 'rollup/' . $jsrev . "/mcore{$format}.js",
1412 if ($this->yui3loader->combine) {
1413 return '<script type="text/javascript" src="' .
1414 $this->yui3loader->local_comboBase .
1415 implode('&amp;', $baserollups) .
1416 '"></script>';
1417 } else {
1418 $code = '';
1419 foreach ($baserollups as $rollup) {
1420 $code .= '<script type="text/javascript" src="'.$this->yui3loader->local_comboBase.$rollup.'"></script>';
1422 return $code;
1428 * Returns html tags needed for inclusion of theme CSS.
1430 * @return string
1432 protected function get_css_code() {
1433 // First of all the theme CSS, then any custom CSS
1434 // Please note custom CSS is strongly discouraged,
1435 // because it can not be overridden by themes!
1436 // It is suitable only for things like mod/data which accepts CSS from teachers.
1437 $attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
1439 // Add the YUI code first. We want this to be overridden by any Moodle CSS.
1440 $code = $this->get_yui3lib_headcss();
1442 // This line of code may look funny but it is currently required in order
1443 // to avoid MASSIVE display issues in Internet Explorer.
1444 // As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
1445 // ignored whenever another resource is added until such time as a redraw
1446 // is forced, usually by moving the mouse over the affected element.
1447 $code .= html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
1449 $urls = $this->cssthemeurls + $this->cssurls;
1450 foreach ($urls as $url) {
1451 $attributes['href'] = $url;
1452 $code .= html_writer::empty_tag('link', $attributes) . "\n";
1453 // This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
1454 unset($attributes['id']);
1457 return $code;
1461 * Adds extra modules specified after printing of page header.
1463 * @return string
1465 protected function get_extra_modules_code() {
1466 if (empty($this->extramodules)) {
1467 return '';
1469 return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
1473 * Generate any HTML that needs to go inside the <head> tag.
1475 * Normally, this method is called automatically by the code that prints the
1476 * <head> tag. You should not normally need to call it in your own code.
1478 * @param moodle_page $page
1479 * @param core_renderer $renderer
1480 * @return string the HTML code to to inside the <head> tag.
1482 public function get_head_code(moodle_page $page, core_renderer $renderer) {
1483 global $CFG;
1485 // Note: the $page and $output are not stored here because it would
1486 // create circular references in memory which prevents garbage collection.
1487 $this->init_requirements_data($page, $renderer);
1489 $output = '';
1491 // Add all standard CSS for this page.
1492 $output .= $this->get_css_code();
1494 // Set up the M namespace.
1495 $js = "var M = {}; M.yui = {};\n";
1497 // Capture the time now ASAP during page load. This minimises the lag when
1498 // we try to relate times on the server to times in the browser.
1499 // An example of where this is used is the quiz countdown timer.
1500 $js .= "M.pageloadstarttime = new Date();\n";
1502 // Add a subset of Moodle configuration to the M namespace.
1503 $js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
1505 // Set up global YUI3 loader object - this should contain all code needed by plugins.
1506 // Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
1507 // this needs to be done before including any other script.
1508 $js .= $this->YUI_config->get_config_functions();
1509 $js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n";
1510 $js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
1511 $js = $this->YUI_config->update_header_js($js);
1513 $output .= html_writer::script($js);
1515 // Add variables.
1516 if ($this->jsinitvariables['head']) {
1517 $js = '';
1518 foreach ($this->jsinitvariables['head'] as $data) {
1519 list($var, $value) = $data;
1520 $js .= js_writer::set_variable($var, $value, true);
1522 $output .= html_writer::script($js);
1525 // Mark head sending done, it is not possible to anything there.
1526 $this->headdone = true;
1528 return $output;
1532 * Generate any HTML that needs to go at the start of the <body> tag.
1534 * Normally, this method is called automatically by the code that prints the
1535 * <head> tag. You should not normally need to call it in your own code.
1537 * @return string the HTML code to go at the start of the <body> tag.
1539 public function get_top_of_body_code() {
1540 // First the skip links.
1541 $links = '';
1542 $attributes = array('class' => 'skip');
1543 foreach ($this->skiplinks as $url => $text) {
1544 $links .= html_writer::link('#'.$url, $text, $attributes);
1546 $output = html_writer::tag('div', $links, array('class'=>'skiplinks')) . "\n";
1547 $this->js_init_call('M.util.init_skiplink');
1549 // YUI3 JS needs to be loaded early in the body. It should be cached well by the browser.
1550 $output .= $this->get_yui3lib_headcode();
1552 // Add hacked jQuery support, it is not intended for standard Moodle distribution!
1553 $output .= $this->get_jquery_headcode();
1555 // Link our main JS file, all core stuff should be there.
1556 $output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
1558 // All the other linked things from HEAD - there should be as few as possible.
1559 if ($this->jsincludes['head']) {
1560 foreach ($this->jsincludes['head'] as $url) {
1561 $output .= html_writer::script('', $url);
1565 // Then the clever trick for hiding of things not needed when JS works.
1566 $output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
1567 $this->topofbodydone = true;
1568 return $output;
1572 * Generate any HTML that needs to go at the end of the page.
1574 * Normally, this method is called automatically by the code that prints the
1575 * page footer. You should not normally need to call it in your own code.
1577 * @return string the HTML code to to at the end of the page.
1579 public function get_end_code() {
1580 global $CFG;
1581 $output = '';
1583 // Set the log level for the JS logging.
1584 $logconfig = new stdClass();
1585 $logconfig->level = 'warn';
1586 if ($CFG->debugdeveloper) {
1587 $logconfig->level = 'trace';
1589 $this->js_call_amd('core/log', 'setConfig', array($logconfig));
1591 // Call amd init functions.
1592 $output .= $this->get_amd_footercode();
1594 // Add other requested modules.
1595 $output .= $this->get_extra_modules_code();
1597 $this->js_init_code('M.util.js_complete("init");', true);
1599 // All the other linked scripts - there should be as few as possible.
1600 if ($this->jsincludes['footer']) {
1601 foreach ($this->jsincludes['footer'] as $url) {
1602 $output .= html_writer::script('', $url);
1606 // Add all needed strings.
1607 // First add core strings required for some dialogues.
1608 $this->strings_for_js(array(
1609 'confirm',
1610 'yes',
1611 'no',
1612 'areyousure',
1613 'closebuttontitle',
1614 'unknownerror',
1615 ), 'moodle');
1616 if (!empty($this->stringsforjs)) {
1617 $strings = array();
1618 foreach ($this->stringsforjs as $component=>$v) {
1619 foreach($v as $indentifier => $langstring) {
1620 $strings[$component][$indentifier] = $langstring->out();
1623 $output .= html_writer::script(js_writer::set_variable('M.str', $strings));
1626 // Add variables.
1627 if ($this->jsinitvariables['footer']) {
1628 $js = '';
1629 foreach ($this->jsinitvariables['footer'] as $data) {
1630 list($var, $value) = $data;
1631 $js .= js_writer::set_variable($var, $value, true);
1633 $output .= html_writer::script($js);
1636 $inyuijs = $this->get_javascript_code(false);
1637 $ondomreadyjs = $this->get_javascript_code(true);
1638 $jsinit = $this->get_javascript_init_code();
1639 $handlersjs = $this->get_event_handler_code();
1641 // There is a global Y, make sure it is available in your scope.
1642 $js = "(function() {{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}})();";
1644 $output .= html_writer::script($js);
1646 return $output;
1650 * Have we already output the code in the <head> tag?
1652 * @return bool
1654 public function is_head_done() {
1655 return $this->headdone;
1659 * Have we already output the code at the start of the <body> tag?
1661 * @return bool
1663 public function is_top_of_body_done() {
1664 return $this->topofbodydone;
1668 * Should we generate a bit of content HTML that is only required once on
1669 * this page (e.g. the contents of the modchooser), now? Basically, we call
1670 * {@link has_one_time_item_been_created()}, and if the thing has not already
1671 * been output, we return true to tell the caller to generate it, and also
1672 * call {@link set_one_time_item_created()} to record the fact that it is
1673 * about to be generated.
1675 * That is, a typical usage pattern (in a renderer method) is:
1676 * <pre>
1677 * if (!$this->page->requires->should_create_one_time_item_now($thing)) {
1678 * return '';
1680 * // Else generate it.
1681 * </pre>
1683 * @param string $thing identifier for the bit of content. Should be of the form
1684 * frankenstyle_things, e.g. core_course_modchooser.
1685 * @return bool if true, the caller should generate that bit of output now, otherwise don't.
1687 public function should_create_one_time_item_now($thing) {
1688 if ($this->has_one_time_item_been_created($thing)) {
1689 return false;
1692 $this->set_one_time_item_created($thing);
1693 return true;
1697 * Has a particular bit of HTML that is only required once on this page
1698 * (e.g. the contents of the modchooser) already been generated?
1700 * Normally, you can use the {@link should_create_one_time_item_now()} helper
1701 * method rather than calling this method directly.
1703 * @param string $thing identifier for the bit of content. Should be of the form
1704 * frankenstyle_things, e.g. core_course_modchooser.
1705 * @return bool whether that bit of output has been created.
1707 public function has_one_time_item_been_created($thing) {
1708 return isset($this->onetimeitemsoutput[$thing]);
1712 * Indicate that a particular bit of HTML that is only required once on this
1713 * page (e.g. the contents of the modchooser) has been generated (or is about to be)?
1715 * Normally, you can use the {@link should_create_one_time_item_now()} helper
1716 * method rather than calling this method directly.
1718 * @param string $thing identifier for the bit of content. Should be of the form
1719 * frankenstyle_things, e.g. core_course_modchooser.
1721 public function set_one_time_item_created($thing) {
1722 if ($this->has_one_time_item_been_created($thing)) {
1723 throw new coding_exception($thing . ' is only supposed to be ouput ' .
1724 'once per page, but it seems to be being output again.');
1726 return $this->onetimeitemsoutput[$thing] = true;
1731 * This class represents the YUI configuration.
1733 * @copyright 2013 Andrew Nicols
1734 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1735 * @since Moodle 2.5
1736 * @package core
1737 * @category output
1739 class YUI_config {
1741 * These settings must be public so that when the object is converted to json they are exposed.
1742 * Note: Some of these are camelCase because YUI uses camelCase variable names.
1744 * The settings are described and documented in the YUI API at:
1745 * - http://yuilibrary.com/yui/docs/api/classes/config.html
1746 * - http://yuilibrary.com/yui/docs/api/classes/Loader.html
1748 public $debug = false;
1749 public $base;
1750 public $comboBase;
1751 public $combine;
1752 public $filter = null;
1753 public $insertBefore = 'firstthemesheet';
1754 public $groups = array();
1755 public $modules = array();
1758 * @var array List of functions used by the YUI Loader group pattern recognition.
1760 protected $jsconfigfunctions = array();
1763 * Create a new group within the YUI_config system.
1765 * @param String $name The name of the group. This must be unique and
1766 * not previously used.
1767 * @param Array $config The configuration for this group.
1768 * @return void
1770 public function add_group($name, $config) {
1771 if (isset($this->groups[$name])) {
1772 throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
1774 $this->groups[$name] = $config;
1778 * Update an existing group configuration
1780 * Note, any existing configuration for that group will be wiped out.
1781 * This includes module configuration.
1783 * @param String $name The name of the group. This must be unique and
1784 * not previously used.
1785 * @param Array $config The configuration for this group.
1786 * @return void
1788 public function update_group($name, $config) {
1789 if (!isset($this->groups[$name])) {
1790 throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.');
1792 $this->groups[$name] = $config;
1796 * Set the value of a configuration function used by the YUI Loader's pattern testing.
1798 * Only the body of the function should be passed, and not the whole function wrapper.
1800 * The JS function your write will be passed a single argument 'name' containing the
1801 * name of the module being loaded.
1803 * @param $function String the body of the JavaScript function. This should be used i
1804 * @return String the name of the function to use in the group pattern configuration.
1806 public function set_config_function($function) {
1807 $configname = 'yui' . (count($this->jsconfigfunctions) + 1) . 'ConfigFn';
1808 if (isset($this->jsconfigfunctions[$configname])) {
1809 throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
1811 $this->jsconfigfunctions[$configname] = $function;
1812 return '@' . $configname . '@';
1816 * Allow setting of the config function described in {@see set_config_function} from a file.
1817 * The contents of this file are then passed to set_config_function.
1819 * When jsrev is positive, the function is minified and stored in a MUC cache for subsequent uses.
1821 * @param $file The path to the JavaScript function used for YUI configuration.
1822 * @return String the name of the function to use in the group pattern configuration.
1824 public function set_config_source($file) {
1825 global $CFG;
1826 $cache = cache::make('core', 'yuimodules');
1828 // Attempt to get the metadata from the cache.
1829 $keyname = 'configfn_' . $file;
1830 $fullpath = $CFG->dirroot . '/' . $file;
1831 if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
1832 $cache->delete($keyname);
1833 $configfn = file_get_contents($fullpath);
1834 } else {
1835 $configfn = $cache->get($keyname);
1836 if ($configfn === false) {
1837 require_once($CFG->libdir . '/jslib.php');
1838 $configfn = core_minify::js_files(array($fullpath));
1839 $cache->set($keyname, $configfn);
1842 return $this->set_config_function($configfn);
1846 * Retrieve the list of JavaScript functions for YUI_config groups.
1848 * @return String The complete set of config functions
1850 public function get_config_functions() {
1851 $configfunctions = '';
1852 foreach ($this->jsconfigfunctions as $functionname => $function) {
1853 $configfunctions .= "var {$functionname} = function(me) {";
1854 $configfunctions .= $function;
1855 $configfunctions .= "};\n";
1857 return $configfunctions;
1861 * Update the header JavaScript with any required modification for the YUI Loader.
1863 * @param $js String The JavaScript to manipulate.
1864 * @return String the modified JS string.
1866 public function update_header_js($js) {
1867 // Update the names of the the configFn variables.
1868 // The PHP json_encode function cannot handle literal names so we have to wrap
1869 // them in @ and then replace them with literals of the same function name.
1870 foreach ($this->jsconfigfunctions as $functionname => $function) {
1871 $js = str_replace('"@' . $functionname . '@"', $functionname, $js);
1873 return $js;
1877 * Add configuration for a specific module.
1879 * @param String $name The name of the module to add configuration for.
1880 * @param Array $config The configuration for the specified module.
1881 * @param String $group The name of the group to add configuration for.
1882 * If not specified, then this module is added to the global
1883 * configuration.
1884 * @return void
1886 public function add_module_config($name, $config, $group = null) {
1887 if ($group) {
1888 if (!isset($this->groups[$name])) {
1889 throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.');
1891 if (!isset($this->groups[$group]['modules'])) {
1892 $this->groups[$group]['modules'] = array();
1894 $modules = &$this->groups[$group]['modules'];
1895 } else {
1896 $modules = &$this->modules;
1898 $modules[$name] = $config;
1902 * Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
1904 * If js caching is disabled, metadata will not be served causing YUI to calculate
1905 * module dependencies as each module is loaded.
1907 * If metadata does not exist it will be created and stored in a MUC entry.
1909 * @return void
1911 public function add_moodle_metadata() {
1912 global $CFG;
1913 if (!isset($this->groups['moodle'])) {
1914 throw new coding_exception('The Moodle YUI module does not exist. You must define the moodle module config using YUI_config->add_module_config first.');
1917 if (!isset($this->groups['moodle']['modules'])) {
1918 $this->groups['moodle']['modules'] = array();
1921 $cache = cache::make('core', 'yuimodules');
1922 if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
1923 $metadata = array();
1924 $metadata = $this->get_moodle_metadata();
1925 $cache->delete('metadata');
1926 } else {
1927 // Attempt to get the metadata from the cache.
1928 if (!$metadata = $cache->get('metadata')) {
1929 $metadata = $this->get_moodle_metadata();
1930 $cache->set('metadata', $metadata);
1934 // Merge with any metadata added specific to this page which was added manually.
1935 $this->groups['moodle']['modules'] = array_merge($this->groups['moodle']['modules'],
1936 $metadata);
1940 * Determine the module metadata for all moodle YUI modules.
1942 * This works through all modules capable of serving YUI modules, and attempts to get
1943 * metadata for each of those modules.
1945 * @return Array of module metadata
1947 private function get_moodle_metadata() {
1948 $moodlemodules = array();
1949 // Core isn't a plugin type or subsystem - handle it seperately.
1950 if ($module = $this->get_moodle_path_metadata(core_component::get_component_directory('core'))) {
1951 $moodlemodules = array_merge($moodlemodules, $module);
1954 // Handle other core subsystems.
1955 $subsystems = core_component::get_core_subsystems();
1956 foreach ($subsystems as $subsystem => $path) {
1957 if (is_null($path)) {
1958 continue;
1960 if ($module = $this->get_moodle_path_metadata($path)) {
1961 $moodlemodules = array_merge($moodlemodules, $module);
1965 // And finally the plugins.
1966 $plugintypes = core_component::get_plugin_types();
1967 foreach ($plugintypes as $plugintype => $pathroot) {
1968 $pluginlist = core_component::get_plugin_list($plugintype);
1969 foreach ($pluginlist as $plugin => $path) {
1970 if ($module = $this->get_moodle_path_metadata($path)) {
1971 $moodlemodules = array_merge($moodlemodules, $module);
1976 return $moodlemodules;
1980 * Helper function process and return the YUI metadata for all of the modules under the specified path.
1982 * @param String $path the UNC path to the YUI src directory.
1983 * @return Array the complete array for frankenstyle directory.
1985 private function get_moodle_path_metadata($path) {
1986 // Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
1987 $baseyui = $path . '/yui/src';
1988 $modules = array();
1989 if (is_dir($baseyui)) {
1990 $items = new DirectoryIterator($baseyui);
1991 foreach ($items as $item) {
1992 if ($item->isDot() or !$item->isDir()) {
1993 continue;
1995 $metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
1996 if (!is_readable($metafile)) {
1997 continue;
1999 $metadata = file_get_contents($metafile);
2000 $modules = array_merge($modules, (array) json_decode($metadata));
2003 return $modules;
2007 * Define YUI modules which we have been required to patch between releases.
2009 * We must do this because we aggressively cache content on the browser, and we must also override use of the
2010 * external CDN which will serve the true authoritative copy of the code without our patches.
2012 * @param String combobase The local combobase
2013 * @param String yuiversion The current YUI version
2014 * @param Int patchlevel The patch level we're working to for YUI
2015 * @param Array patchedmodules An array containing the names of the patched modules
2016 * @return void
2018 public function define_patched_core_modules($combobase, $yuiversion, $patchlevel, $patchedmodules) {
2019 // The version we use is suffixed with a patchlevel so that we can get additional revisions between YUI releases.
2020 $subversion = $yuiversion . '_' . $patchlevel;
2022 if ($this->comboBase == $combobase) {
2023 // If we are using the local combobase in the loader, we can add a group and still make use of the combo
2024 // loader. We just need to specify a different root which includes a slightly different YUI version number
2025 // to include our patchlevel.
2026 $patterns = array();
2027 $modules = array();
2028 foreach ($patchedmodules as $modulename) {
2029 // We must define the pattern and module here so that the loader uses our group configuration instead of
2030 // the standard module definition. We may lose some metadata provided by upstream but this will be
2031 // loaded when the module is loaded anyway.
2032 $patterns[$modulename] = array(
2033 'group' => 'yui-patched',
2035 $modules[$modulename] = array();
2038 // Actually add the patch group here.
2039 $this->add_group('yui-patched', array(
2040 'combine' => true,
2041 'root' => $subversion . '/',
2042 'patterns' => $patterns,
2043 'modules' => $modules,
2046 } else {
2047 // The CDN is in use - we need to instead use the local combobase for this module and override the modules
2048 // definition. We cannot use the local base - we must use the combobase because we cannot invalidate the
2049 // local base in browser caches.
2050 $fullpathbase = $combobase . $subversion . '/';
2051 foreach ($patchedmodules as $modulename) {
2052 $this->modules[$modulename] = array(
2053 'fullpath' => $fullpathbase . $modulename . '/' . $modulename . '-min.js'
2061 * Invalidate all server and client side JS caches.
2063 function js_reset_all_caches() {
2064 global $CFG;
2066 $next = time();
2067 if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
2068 // This resolves problems when reset is requested repeatedly within 1s,
2069 // the < 1h condition prevents accidental switching to future dates
2070 // because we might not recover from it.
2071 $next = $CFG->jsrev+1;
2074 set_config('jsrev', $next);