.
* @param string $func Optional function from the module to call, defaults to just loading the AMD module.
* @param array $params The params to pass to the function (will be serialized into JSON).
*/
public function js_call_amd($fullmodule, $func = null, $params = array()) {
global $CFG;
list($component, $module) = explode('/', $fullmodule, 2);
$component = clean_param($component, PARAM_COMPONENT);
$module = clean_param($module, PARAM_ALPHANUMEXT);
$modname = "{$component}/{$module}";
$functioncode = [];
if ($func !== null) {
$func = clean_param($func, PARAM_ALPHANUMEXT);
$jsonparams = array();
foreach ($params as $param) {
$jsonparams[] = json_encode($param);
}
$strparams = implode(', ', $jsonparams);
if ($CFG->debugdeveloper) {
$toomanyparamslimit = 1024;
if (strlen($strparams) > $toomanyparamslimit) {
debugging('Too much data passed as arguments to js_call_amd("' . $fullmodule . '", "' . $func .
'"). Generally there are better ways to pass lots of data from PHP to JavaScript, for example via Ajax, ' .
'data attributes, ... . This warning is triggered if the argument string becomes longer than ' .
$toomanyparamslimit . ' characters.', DEBUG_DEVELOPER);
}
}
$functioncode[] = "amd.{$func}({$strparams});";
}
$functioncode[] = "M.util.js_complete('{$modname}');";
$initcode = implode(' ', $functioncode);
$js = "M.util.js_pending('{$modname}'); require(['{$modname}'], function(amd) {{$initcode}});";
$this->js_amd_inline($js);
}
/**
* Creates a JavaScript function call that requires one or more modules to be loaded.
*
* This function can be used to include all of the standard YUI module types within JavaScript:
* - YUI3 modules [node, event, io]
* - YUI2 modules [yui2-*]
* - Moodle modules [moodle-*]
* - Gallery modules [gallery-*]
*
* Before writing new code that makes extensive use of YUI, you should consider it's replacement AMD/JQuery.
* @see js_call_amd()
*
* @param array|string $modules One or more modules
* @param string $function The function to call once modules have been loaded
* @param array $arguments An array of arguments to pass to the function
* @param string $galleryversion Deprecated: The gallery version to use
* @param bool $ondomready
*/
public function yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
if (!is_array($modules)) {
$modules = array($modules);
}
if ($galleryversion != null) {
debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.');
}
$jscode = 'Y.use('.join(',', array_map('json_encode', convert_to_array($modules))).',function() {'.js_writer::function_call($function, $arguments).'});';
if ($ondomready) {
$jscode = "Y.on('domready', function() { $jscode });";
}
$this->jsinitcode[] = $jscode;
}
/**
* Set the CSS Modules to be included from YUI.
*
* @param array $modules The list of YUI CSS Modules to include.
*/
public function set_yuicssmodules(array $modules = array()) {
$this->yuicssmodules = $modules;
}
/**
* Ensure that the specified JavaScript function is called from an inline script
* from page footer.
*
* @param string $function the name of the JavaScritp function to with init code,
* usually something like 'M.mod_mymodule.init'
* @param array $extraarguments and array of arguments to be passed to the function.
* The first argument is always the YUI3 Y instance with all required dependencies
* already loaded.
* @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
* @param array $module JS module specification array
*/
public function js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
$jscode = js_writer::function_call_with_Y($function, $extraarguments);
if (!$module) {
// Detect module automatically.
if (preg_match('/M\.([a-z0-9]+_[^\.]+)/', $function, $matches)) {
$module = $this->find_module($matches[1]);
}
}
$this->js_init_code($jscode, $ondomready, $module);
}
/**
* Add short static javascript code fragment to page footer.
* This is intended primarily for loading of js modules and initialising page layout.
* Ideally the JS code fragment should be stored in plugin renderer so that themes
* may override it.
*
* @param string $jscode
* @param bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
* @param array $module JS module specification array
*/
public function js_init_code($jscode, $ondomready = false, array $module = null) {
$jscode = trim($jscode, " ;\n"). ';';
$uniqid = html_writer::random_id();
$startjs = " M.util.js_pending('" . $uniqid . "');";
$endjs = " M.util.js_complete('" . $uniqid . "');";
if ($module) {
$this->js_module($module);
$modulename = $module['name'];
$jscode = "$startjs Y.use('$modulename', function(Y) { $jscode $endjs });";
}
if ($ondomready) {
$jscode = "$startjs Y.on('domready', function() { $jscode $endjs });";
}
$this->jsinitcode[] = $jscode;
}
/**
* Make a language string available to JavaScript.
*
* All the strings will be available in a M.str object in the global namespace.
* So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
* then the JavaScript variable M.str.moodle.course will be 'Course', or the
* equivalent in the current language.
*
* The arguments to this function are just like the arguments to get_string
* except that $component is not optional, and there are some aspects to consider
* when the string contains {$a} placeholder.
*
* If the string does not contain any {$a} placeholder, you can simply use
* M.str.component.identifier to obtain it. If you prefer, you can call
* M.util.get_string(identifier, component) to get the same result.
*
* If you need to use {$a} placeholders, there are two options. Either the
* placeholder should be substituted in PHP on server side or it should
* be substituted in Javascript at client side.
*
* To substitute the placeholder at server side, just provide the required
* value for the placeholder when you require the string. Because each string
* is only stored once in the JavaScript (based on $identifier and $module)
* you cannot get the same string with two different values of $a. If you try,
* an exception will be thrown. Once the placeholder is substituted, you can
* use M.str or M.util.get_string() as shown above:
*
* // Require the string in PHP and replace the placeholder.
* $PAGE->requires->string_for_js('fullnamedisplay', 'moodle', $USER);
* // Use the result of the substitution in Javascript.
* alert(M.str.moodle.fullnamedisplay);
*
* To substitute the placeholder at client side, use M.util.get_string()
* function. It implements the same logic as {@link get_string()}:
*
* // Require the string in PHP but keep {$a} as it is.
* $PAGE->requires->string_for_js('fullnamedisplay', 'moodle');
* // Provide the values on the fly in Javascript.
* user = { firstname : 'Harry', lastname : 'Potter' }
* alert(M.util.get_string('fullnamedisplay', 'moodle', user);
*
* If you do need the same string expanded with different $a values in PHP
* on server side, then the solution is to put them in your own data structure
* (e.g. and array) that you pass to JavaScript with {@link data_for_js()}.
*
* @param string $identifier the desired string.
* @param string $component the language file to look in.
* @param mixed $a any extra data to add into the string (optional).
*/
public function string_for_js($identifier, $component, $a = null) {
if (!$component) {
throw new coding_exception('The $component parameter is required for page_requirements_manager::string_for_js().');
}
if (isset($this->stringsforjs_as[$component][$identifier]) and $this->stringsforjs_as[$component][$identifier] !== $a) {
throw new coding_exception("Attempt to re-define already required string '$identifier' " .
"from lang file '$component' with different \$a parameter?");
}
if (!isset($this->stringsforjs[$component][$identifier])) {
$this->stringsforjs[$component][$identifier] = new lang_string($identifier, $component, $a);
$this->stringsforjs_as[$component][$identifier] = $a;
}
}
/**
* Make an array of language strings available for JS.
*
* This function calls the above function {@link string_for_js()} for each requested
* string in the $identifiers array that is passed to the argument for a single module
* passed in $module.
*
*
* $PAGE->requires->strings_for_js(array('one', 'two', 'three'), 'mymod', array('a', null, 3));
*
* // The above is identical to calling:
*
* $PAGE->requires->string_for_js('one', 'mymod', 'a');
* $PAGE->requires->string_for_js('two', 'mymod');
* $PAGE->requires->string_for_js('three', 'mymod', 3);
*
*
* @param array $identifiers An array of desired strings
* @param string $component The module to load for
* @param mixed $a This can either be a single variable that gets passed as extra
* information for every string or it can be an array of mixed data where the
* key for the data matches that of the identifier it is meant for.
*
*/
public function strings_for_js($identifiers, $component, $a = null) {
foreach ($identifiers as $key => $identifier) {
if (is_array($a) && array_key_exists($key, $a)) {
$extra = $a[$key];
} else {
$extra = $a;
}
$this->string_for_js($identifier, $component, $extra);
}
}
/**
* !!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.
*
* Make some data from PHP available to JavaScript code.
*
* For example, if you call
*
* $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
*
* then in JavsScript mydata.name will be 'Moodle'.
*
* @deprecated
* @param string $variable the the name of the JavaScript variable to assign the data to.
* Will probably work if you use a compound name like 'mybuttons.button[1]', but this
* should be considered an experimental feature.
* @param mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
* so passing objects and arrays should work.
* @param bool $inhead initialise in head
* @return void
*/
public function data_for_js($variable, $data, $inhead=false) {
$where = $inhead ? 'head' : 'footer';
$this->jsinitvariables[$where][] = array($variable, $data);
}
/**
* Creates a YUI event handler.
*
* @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
* @param string $event A valid DOM event (click, mousedown, change etc.)
* @param string $function The name of the function to call
* @param array $arguments An optional array of argument parameters to pass to the function
*/
public function event_handler($selector, $event, $function, array $arguments = null) {
$this->eventhandlers[] = array('selector'=>$selector, 'event'=>$event, 'function'=>$function, 'arguments'=>$arguments);
}
/**
* Returns code needed for registering of event handlers.
* @return string JS code
*/
protected function get_event_handler_code() {
$output = '';
foreach ($this->eventhandlers as $h) {
$output .= js_writer::event_handler($h['selector'], $h['event'], $h['function'], $h['arguments']);
}
return $output;
}
/**
* Get the inline JavaScript code that need to appear in a particular place.
* @param bool $ondomready
* @return string
*/
protected function get_javascript_code($ondomready) {
$where = $ondomready ? 'ondomready' : 'normal';
$output = '';
if ($this->jscalls[$where]) {
foreach ($this->jscalls[$where] as $data) {
$output .= js_writer::function_call($data[0], $data[1], $data[2]);
}
if (!empty($ondomready)) {
$output = " Y.on('domready', function() {\n$output\n});";
}
}
return $output;
}
/**
* Returns js code to be executed when Y is available.
* @return string
*/
protected function get_javascript_init_code() {
if (count($this->jsinitcode)) {
return implode("\n", $this->jsinitcode) . "\n";
}
return '';
}
/**
* Returns js code to load amd module loader, then insert inline script tags
* that contain require() calls using RequireJS.
* @return string
*/
protected function get_amd_footercode() {
global $CFG;
$output = '';
// We will cache JS if cachejs is not set, or it is true.
$cachejs = !isset($CFG->cachejs) || $CFG->cachejs;
$jsrev = $this->get_jsrev();
$jsloader = new moodle_url('/lib/javascript.php');
$jsloader->set_slashargument('/' . $jsrev . '/');
$requirejsloader = new moodle_url('/lib/requirejs.php');
$requirejsloader->set_slashargument('/' . $jsrev . '/');
$requirejsconfig = file_get_contents($CFG->dirroot . '/lib/requirejs/moodle-config.js');
// No extension required unless slash args is disabled.
$jsextension = '.js';
if (!empty($CFG->slasharguments)) {
$jsextension = '';
}
$minextension = '.min';
if (!$cachejs) {
$minextension = '';
}
$requirejsconfig = str_replace('[BASEURL]', $requirejsloader, $requirejsconfig);
$requirejsconfig = str_replace('[JSURL]', $jsloader, $requirejsconfig);
$requirejsconfig = str_replace('[JSMIN]', $minextension, $requirejsconfig);
$requirejsconfig = str_replace('[JSEXT]', $jsextension, $requirejsconfig);
$output .= html_writer::script($requirejsconfig);
if ($cachejs) {
$output .= html_writer::script('', $this->js_fix_url('/lib/requirejs/require.min.js'));
} else {
$output .= html_writer::script('', $this->js_fix_url('/lib/requirejs/require.js'));
}
// First include must be to a module with no dependencies, this prevents multiple requests.
$prefix = 'M.util.js_pending("core/first");';
$prefix .= "require(['core/first'], function() {\n";
$suffix = 'M.util.js_complete("core/first");';
$suffix .= "\n});";
$output .= html_writer::script($prefix . implode(";\n", $this->amdjscode) . $suffix);
return $output;
}
/**
* Returns basic YUI3 CSS code.
*
* @return string
*/
protected function get_yui3lib_headcss() {
global $CFG;
$yuiformat = '-min';
if ($this->yui3loader->filter === 'RAW') {
$yuiformat = '';
}
$code = '';
if ($this->yui3loader->combine) {
if (!empty($this->yuicssmodules)) {
$modules = array();
foreach ($this->yuicssmodules as $module) {
$modules[] = "$CFG->yui3version/$module/$module-min.css";
}
$code .= '';
}
$code .= '';
} else {
if (!empty($this->yuicssmodules)) {
foreach ($this->yuicssmodules as $module) {
$code .= '';
}
}
$code .= '';
}
if ($this->yui3loader->filter === 'RAW') {
$code = str_replace('-min.css', '.css', $code);
} else if ($this->yui3loader->filter === 'DEBUG') {
$code = str_replace('-min.css', '.css', $code);
}
return $code;
}
/**
* Returns basic YUI3 JS loading code.
*
* @return string
*/
protected function get_yui3lib_headcode() {
global $CFG;
$jsrev = $this->get_jsrev();
$yuiformat = '-min';
if ($this->yui3loader->filter === 'RAW') {
$yuiformat = '';
}
$format = '-min';
if ($this->YUI_config->groups['moodle']['filter'] === 'DEBUG') {
$format = '-debug';
}
$rollupversion = $CFG->yui3version;
if (!empty($CFG->yuipatchlevel)) {
$rollupversion .= '_' . $CFG->yuipatchlevel;
}
$baserollups = array(
'rollup/' . $rollupversion . "/yui-moodlesimple{$yuiformat}.js",
);
if ($this->yui3loader->combine) {
return '';
} else {
$code = '';
foreach ($baserollups as $rollup) {
$code .= '';
}
return $code;
}
}
/**
* Returns html tags needed for inclusion of theme CSS.
*
* @return string
*/
protected function get_css_code() {
// First of all the theme CSS, then any custom CSS
// Please note custom CSS is strongly discouraged,
// because it can not be overridden by themes!
// It is suitable only for things like mod/data which accepts CSS from teachers.
$attributes = array('rel'=>'stylesheet', 'type'=>'text/css');
// Add the YUI code first. We want this to be overridden by any Moodle CSS.
$code = $this->get_yui3lib_headcss();
// This line of code may look funny but it is currently required in order
// to avoid MASSIVE display issues in Internet Explorer.
// As of IE8 + YUI3.1.1 the reference stylesheet (firstthemesheet) gets
// ignored whenever another resource is added until such time as a redraw
// is forced, usually by moving the mouse over the affected element.
$code .= html_writer::tag('script', '/** Required in order to fix style inclusion problems in IE with YUI **/', array('id'=>'firstthemesheet', 'type'=>'text/css'));
$urls = $this->cssthemeurls + $this->cssurls;
foreach ($urls as $url) {
$attributes['href'] = $url;
$code .= html_writer::empty_tag('link', $attributes) . "\n";
// This id is needed in first sheet only so that theme may override YUI sheets loaded on the fly.
unset($attributes['id']);
}
return $code;
}
/**
* Adds extra modules specified after printing of page header.
*
* @return string
*/
protected function get_extra_modules_code() {
if (empty($this->extramodules)) {
return '';
}
return html_writer::script(js_writer::function_call('M.yui.add_module', array($this->extramodules)));
}
/**
* Generate any HTML that needs to go inside the tag.
*
* Normally, this method is called automatically by the code that prints the
* tag. You should not normally need to call it in your own code.
*
* @param moodle_page $page
* @param core_renderer $renderer
* @return string the HTML code to to inside the tag.
*/
public function get_head_code(moodle_page $page, core_renderer $renderer) {
global $CFG;
// Note: the $page and $output are not stored here because it would
// create circular references in memory which prevents garbage collection.
$this->init_requirements_data($page, $renderer);
$output = '';
// Add all standard CSS for this page.
$output .= $this->get_css_code();
// Set up the M namespace.
$js = "var M = {}; M.yui = {};\n";
// Capture the time now ASAP during page load. This minimises the lag when
// we try to relate times on the server to times in the browser.
// An example of where this is used is the quiz countdown timer.
$js .= "M.pageloadstarttime = new Date();\n";
// Add a subset of Moodle configuration to the M namespace.
$js .= js_writer::set_variable('M.cfg', $this->M_cfg, false);
// Set up global YUI3 loader object - this should contain all code needed by plugins.
// Note: in JavaScript just use "YUI().use('overlay', function(Y) { .... });",
// this needs to be done before including any other script.
$js .= $this->YUI_config->get_config_functions();
$js .= js_writer::set_variable('YUI_config', $this->YUI_config, false) . "\n";
$js .= "M.yui.loader = {modules: {}};\n"; // Backwards compatibility only, not used any more.
$js = $this->YUI_config->update_header_js($js);
$output .= html_writer::script($js);
// Add variables.
if ($this->jsinitvariables['head']) {
$js = '';
foreach ($this->jsinitvariables['head'] as $data) {
list($var, $value) = $data;
$js .= js_writer::set_variable($var, $value, true);
}
$output .= html_writer::script($js);
}
// Mark head sending done, it is not possible to anything there.
$this->headdone = true;
return $output;
}
/**
* Generate any HTML that needs to go at the start of the tag.
*
* Normally, this method is called automatically by the code that prints the
* tag. You should not normally need to call it in your own code.
*
* @param renderer_base $renderer
* @return string the HTML code to go at the start of the tag.
*/
public function get_top_of_body_code(renderer_base $renderer) {
// First the skip links.
$output = $renderer->render_skip_links($this->skiplinks);
// Include the MDN Polyfill.
$output .= html_writer::script('', $this->js_fix_url('/lib/mdn-polyfills/polyfill.js'));
// YUI3 JS needs to be loaded early in the body. It should be cached well by the browser.
$output .= $this->get_yui3lib_headcode();
// Add hacked jQuery support, it is not intended for standard Moodle distribution!
$output .= $this->get_jquery_headcode();
// Link our main JS file, all core stuff should be there.
$output .= html_writer::script('', $this->js_fix_url('/lib/javascript-static.js'));
// All the other linked things from HEAD - there should be as few as possible.
if ($this->jsincludes['head']) {
foreach ($this->jsincludes['head'] as $url) {
$output .= html_writer::script('', $url);
}
}
// Then the clever trick for hiding of things not needed when JS works.
$output .= html_writer::script("document.body.className += ' jsenabled';") . "\n";
$this->topofbodydone = true;
return $output;
}
/**
* Generate any HTML that needs to go at the end of the page.
*
* Normally, this method is called automatically by the code that prints the
* page footer. You should not normally need to call it in your own code.
*
* @return string the HTML code to to at the end of the page.
*/
public function get_end_code() {
global $CFG;
$output = '';
// Set the log level for the JS logging.
$logconfig = new stdClass();
$logconfig->level = 'warn';
if ($CFG->debugdeveloper) {
$logconfig->level = 'trace';
}
$this->js_call_amd('core/log', 'setConfig', array($logconfig));
// Add any global JS that needs to run on all pages.
$this->js_call_amd('core/page_global', 'init');
// Call amd init functions.
$output .= $this->get_amd_footercode();
// Add other requested modules.
$output .= $this->get_extra_modules_code();
$this->js_init_code('M.util.js_complete("init");', true);
// All the other linked scripts - there should be as few as possible.
if ($this->jsincludes['footer']) {
foreach ($this->jsincludes['footer'] as $url) {
$output .= html_writer::script('', $url);
}
}
// Add all needed strings.
// First add core strings required for some dialogues.
$this->strings_for_js(array(
'confirm',
'yes',
'no',
'areyousure',
'closebuttontitle',
'unknownerror',
), 'moodle');
if (!empty($this->stringsforjs)) {
$strings = array();
foreach ($this->stringsforjs as $component=>$v) {
foreach($v as $indentifier => $langstring) {
$strings[$component][$indentifier] = $langstring->out();
}
}
$output .= html_writer::script(js_writer::set_variable('M.str', $strings));
}
// Add variables.
if ($this->jsinitvariables['footer']) {
$js = '';
foreach ($this->jsinitvariables['footer'] as $data) {
list($var, $value) = $data;
$js .= js_writer::set_variable($var, $value, true);
}
$output .= html_writer::script($js);
}
$inyuijs = $this->get_javascript_code(false);
$ondomreadyjs = $this->get_javascript_code(true);
$jsinit = $this->get_javascript_init_code();
$handlersjs = $this->get_event_handler_code();
// There is a global Y, make sure it is available in your scope.
$js = "(function() {{$inyuijs}{$ondomreadyjs}{$jsinit}{$handlersjs}})();";
$output .= html_writer::script($js);
return $output;
}
/**
* Have we already output the code in the tag?
*
* @return bool
*/
public function is_head_done() {
return $this->headdone;
}
/**
* Have we already output the code at the start of the tag?
*
* @return bool
*/
public function is_top_of_body_done() {
return $this->topofbodydone;
}
/**
* Should we generate a bit of content HTML that is only required once on
* this page (e.g. the contents of the modchooser), now? Basically, we call
* {@link has_one_time_item_been_created()}, and if the thing has not already
* been output, we return true to tell the caller to generate it, and also
* call {@link set_one_time_item_created()} to record the fact that it is
* about to be generated.
*
* That is, a typical usage pattern (in a renderer method) is:
*
* if (!$this->page->requires->should_create_one_time_item_now($thing)) {
* return '';
* }
* // Else generate it.
*
*
* @param string $thing identifier for the bit of content. Should be of the form
* frankenstyle_things, e.g. core_course_modchooser.
* @return bool if true, the caller should generate that bit of output now, otherwise don't.
*/
public function should_create_one_time_item_now($thing) {
if ($this->has_one_time_item_been_created($thing)) {
return false;
}
$this->set_one_time_item_created($thing);
return true;
}
/**
* Has a particular bit of HTML that is only required once on this page
* (e.g. the contents of the modchooser) already been generated?
*
* Normally, you can use the {@link should_create_one_time_item_now()} helper
* method rather than calling this method directly.
*
* @param string $thing identifier for the bit of content. Should be of the form
* frankenstyle_things, e.g. core_course_modchooser.
* @return bool whether that bit of output has been created.
*/
public function has_one_time_item_been_created($thing) {
return isset($this->onetimeitemsoutput[$thing]);
}
/**
* Indicate that a particular bit of HTML that is only required once on this
* page (e.g. the contents of the modchooser) has been generated (or is about to be)?
*
* Normally, you can use the {@link should_create_one_time_item_now()} helper
* method rather than calling this method directly.
*
* @param string $thing identifier for the bit of content. Should be of the form
* frankenstyle_things, e.g. core_course_modchooser.
*/
public function set_one_time_item_created($thing) {
if ($this->has_one_time_item_been_created($thing)) {
throw new coding_exception($thing . ' is only supposed to be ouput ' .
'once per page, but it seems to be being output again.');
}
return $this->onetimeitemsoutput[$thing] = true;
}
}
/**
* This class represents the YUI configuration.
*
* @copyright 2013 Andrew Nicols
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.5
* @package core
* @category output
*/
class YUI_config {
/**
* These settings must be public so that when the object is converted to json they are exposed.
* Note: Some of these are camelCase because YUI uses camelCase variable names.
*
* The settings are described and documented in the YUI API at:
* - http://yuilibrary.com/yui/docs/api/classes/config.html
* - http://yuilibrary.com/yui/docs/api/classes/Loader.html
*/
public $debug = false;
public $base;
public $comboBase;
public $combine;
public $filter = null;
public $insertBefore = 'firstthemesheet';
public $groups = array();
public $modules = array();
/**
* @var array List of functions used by the YUI Loader group pattern recognition.
*/
protected $jsconfigfunctions = array();
/**
* Create a new group within the YUI_config system.
*
* @param String $name The name of the group. This must be unique and
* not previously used.
* @param Array $config The configuration for this group.
* @return void
*/
public function add_group($name, $config) {
if (isset($this->groups[$name])) {
throw new coding_exception("A YUI configuration group for '{$name}' already exists. To make changes to this group use YUI_config->update_group().");
}
$this->groups[$name] = $config;
}
/**
* Update an existing group configuration
*
* Note, any existing configuration for that group will be wiped out.
* This includes module configuration.
*
* @param String $name The name of the group. This must be unique and
* not previously used.
* @param Array $config The configuration for this group.
* @return void
*/
public function update_group($name, $config) {
if (!isset($this->groups[$name])) {
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.');
}
$this->groups[$name] = $config;
}
/**
* Set the value of a configuration function used by the YUI Loader's pattern testing.
*
* Only the body of the function should be passed, and not the whole function wrapper.
*
* The JS function your write will be passed a single argument 'name' containing the
* name of the module being loaded.
*
* @param $function String the body of the JavaScript function. This should be used i
* @return String the name of the function to use in the group pattern configuration.
*/
public function set_config_function($function) {
$configname = 'yui' . (count($this->jsconfigfunctions) + 1) . 'ConfigFn';
if (isset($this->jsconfigfunctions[$configname])) {
throw new coding_exception("A YUI config function with this name already exists. Config function names must be unique.");
}
$this->jsconfigfunctions[$configname] = $function;
return '@' . $configname . '@';
}
/**
* Allow setting of the config function described in {@see set_config_function} from a file.
* The contents of this file are then passed to set_config_function.
*
* When jsrev is positive, the function is minified and stored in a MUC cache for subsequent uses.
*
* @param $file The path to the JavaScript function used for YUI configuration.
* @return String the name of the function to use in the group pattern configuration.
*/
public function set_config_source($file) {
global $CFG;
$cache = cache::make('core', 'yuimodules');
// Attempt to get the metadata from the cache.
$keyname = 'configfn_' . $file;
$fullpath = $CFG->dirroot . '/' . $file;
if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
$cache->delete($keyname);
$configfn = file_get_contents($fullpath);
} else {
$configfn = $cache->get($keyname);
if ($configfn === false) {
require_once($CFG->libdir . '/jslib.php');
$configfn = core_minify::js_files(array($fullpath));
$cache->set($keyname, $configfn);
}
}
return $this->set_config_function($configfn);
}
/**
* Retrieve the list of JavaScript functions for YUI_config groups.
*
* @return String The complete set of config functions
*/
public function get_config_functions() {
$configfunctions = '';
foreach ($this->jsconfigfunctions as $functionname => $function) {
$configfunctions .= "var {$functionname} = function(me) {";
$configfunctions .= $function;
$configfunctions .= "};\n";
}
return $configfunctions;
}
/**
* Update the header JavaScript with any required modification for the YUI Loader.
*
* @param $js String The JavaScript to manipulate.
* @return String the modified JS string.
*/
public function update_header_js($js) {
// Update the names of the the configFn variables.
// The PHP json_encode function cannot handle literal names so we have to wrap
// them in @ and then replace them with literals of the same function name.
foreach ($this->jsconfigfunctions as $functionname => $function) {
$js = str_replace('"@' . $functionname . '@"', $functionname, $js);
}
return $js;
}
/**
* Add configuration for a specific module.
*
* @param String $name The name of the module to add configuration for.
* @param Array $config The configuration for the specified module.
* @param String $group The name of the group to add configuration for.
* If not specified, then this module is added to the global
* configuration.
* @return void
*/
public function add_module_config($name, $config, $group = null) {
if ($group) {
if (!isset($this->groups[$name])) {
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.');
}
if (!isset($this->groups[$group]['modules'])) {
$this->groups[$group]['modules'] = array();
}
$modules = &$this->groups[$group]['modules'];
} else {
$modules = &$this->modules;
}
$modules[$name] = $config;
}
/**
* Add the moodle YUI module metadata for the moodle group to the YUI_config instance.
*
* If js caching is disabled, metadata will not be served causing YUI to calculate
* module dependencies as each module is loaded.
*
* If metadata does not exist it will be created and stored in a MUC entry.
*
* @return void
*/
public function add_moodle_metadata() {
global $CFG;
if (!isset($this->groups['moodle'])) {
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.');
}
if (!isset($this->groups['moodle']['modules'])) {
$this->groups['moodle']['modules'] = array();
}
$cache = cache::make('core', 'yuimodules');
if (!isset($CFG->jsrev) || $CFG->jsrev == -1) {
$metadata = array();
$metadata = $this->get_moodle_metadata();
$cache->delete('metadata');
} else {
// Attempt to get the metadata from the cache.
if (!$metadata = $cache->get('metadata')) {
$metadata = $this->get_moodle_metadata();
$cache->set('metadata', $metadata);
}
}
// Merge with any metadata added specific to this page which was added manually.
$this->groups['moodle']['modules'] = array_merge($this->groups['moodle']['modules'],
$metadata);
}
/**
* Determine the module metadata for all moodle YUI modules.
*
* This works through all modules capable of serving YUI modules, and attempts to get
* metadata for each of those modules.
*
* @return Array of module metadata
*/
private function get_moodle_metadata() {
$moodlemodules = array();
// Core isn't a plugin type or subsystem - handle it seperately.
if ($module = $this->get_moodle_path_metadata(core_component::get_component_directory('core'))) {
$moodlemodules = array_merge($moodlemodules, $module);
}
// Handle other core subsystems.
$subsystems = core_component::get_core_subsystems();
foreach ($subsystems as $subsystem => $path) {
if (is_null($path)) {
continue;
}
if ($module = $this->get_moodle_path_metadata($path)) {
$moodlemodules = array_merge($moodlemodules, $module);
}
}
// And finally the plugins.
$plugintypes = core_component::get_plugin_types();
foreach ($plugintypes as $plugintype => $pathroot) {
$pluginlist = core_component::get_plugin_list($plugintype);
foreach ($pluginlist as $plugin => $path) {
if ($module = $this->get_moodle_path_metadata($path)) {
$moodlemodules = array_merge($moodlemodules, $module);
}
}
}
return $moodlemodules;
}
/**
* Helper function process and return the YUI metadata for all of the modules under the specified path.
*
* @param String $path the UNC path to the YUI src directory.
* @return Array the complete array for frankenstyle directory.
*/
private function get_moodle_path_metadata($path) {
// Add module metadata is stored in frankenstyle_modname/yui/src/yui_modname/meta/yui_modname.json.
$baseyui = $path . '/yui/src';
$modules = array();
if (is_dir($baseyui)) {
$items = new DirectoryIterator($baseyui);
foreach ($items as $item) {
if ($item->isDot() or !$item->isDir()) {
continue;
}
$metafile = realpath($baseyui . '/' . $item . '/meta/' . $item . '.json');
if (!is_readable($metafile)) {
continue;
}
$metadata = file_get_contents($metafile);
$modules = array_merge($modules, (array) json_decode($metadata));
}
}
return $modules;
}
/**
* Define YUI modules which we have been required to patch between releases.
*
* We must do this because we aggressively cache content on the browser, and we must also override use of the
* external CDN which will serve the true authoritative copy of the code without our patches.
*
* @param String combobase The local combobase
* @param String yuiversion The current YUI version
* @param Int patchlevel The patch level we're working to for YUI
* @param Array patchedmodules An array containing the names of the patched modules
* @return void
*/
public function define_patched_core_modules($combobase, $yuiversion, $patchlevel, $patchedmodules) {
// The version we use is suffixed with a patchlevel so that we can get additional revisions between YUI releases.
$subversion = $yuiversion . '_' . $patchlevel;
if ($this->comboBase == $combobase) {
// If we are using the local combobase in the loader, we can add a group and still make use of the combo
// loader. We just need to specify a different root which includes a slightly different YUI version number
// to include our patchlevel.
$patterns = array();
$modules = array();
foreach ($patchedmodules as $modulename) {
// We must define the pattern and module here so that the loader uses our group configuration instead of
// the standard module definition. We may lose some metadata provided by upstream but this will be
// loaded when the module is loaded anyway.
$patterns[$modulename] = array(
'group' => 'yui-patched',
);
$modules[$modulename] = array();
}
// Actually add the patch group here.
$this->add_group('yui-patched', array(
'combine' => true,
'root' => $subversion . '/',
'patterns' => $patterns,
'modules' => $modules,
));
} else {
// The CDN is in use - we need to instead use the local combobase for this module and override the modules
// definition. We cannot use the local base - we must use the combobase because we cannot invalidate the
// local base in browser caches.
$fullpathbase = $combobase . $subversion . '/';
foreach ($patchedmodules as $modulename) {
$this->modules[$modulename] = array(
'fullpath' => $fullpathbase . $modulename . '/' . $modulename . '-min.js'
);
}
}
}
}
/**
* Invalidate all server and client side JS caches.
*/
function js_reset_all_caches() {
global $CFG;
$next = time();
if (isset($CFG->jsrev) and $next <= $CFG->jsrev and $CFG->jsrev - $next < 60*60) {
// This resolves problems when reset is requested repeatedly within 1s,
// the < 1h condition prevents accidental switching to future dates
// because we might not recover from it.
$next = $CFG->jsrev+1;
}
set_config('jsrev', $next);
}