Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.

Differences Between: [Versions 310 and 403] [Versions 311 and 403] [Versions 39 and 403] [Versions 400 and 403] [Versions 401 and 403]

Library functions to facilitate the use of JavaScript in Moodle. Note: you can find history of this file in lib/ajax/ajaxlib.php

Copyright: 2009 Tim Hunt, 2010 Petr Skoda
License: http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
File Size: 2195 lines (89 kb)
Included or required:0 times
Referenced: 0 times
Includes or requires: 0 files

Defines 2 classes


Class: page_requirements_manager  - X-Ref

This class tracks all the things that are needed by the current page.

Normally, the only instance of this  class you will need to work with is the
one accessible via $PAGE->requires.

Typical usage would be
<pre>
$PAGE->requires->js_call_amd('mod_forum/view', 'init');
</pre>

It also supports obsoleted coding style with/without YUI3 modules.
<pre>
$PAGE->requires->js_init_call('M.mod_forum.init_view');
$PAGE->requires->css('/mod/mymod/userstyles.php?id='.$id); // not overridable via themes!
$PAGE->requires->js('/mod/mymod/script.js');
$PAGE->requires->js('/mod/mymod/small_but_urgent.js', true);
$PAGE->requires->js_function_call('init_mymod', array($data), true);
</pre>

There are some natural restrictions on some methods. For example, {@link css()}
can only be called before the <head> tag is output. See the comments on the
individual methods for details.

__construct()   X-Ref
Page requirements constructor.


get_config_for_javascript(moodle_page $page, renderer_base $renderer)   X-Ref
Return the safe config values that get set for javascript in "M.cfg".

return: array List of safe config values that are available to javascript.

init_requirements_data(moodle_page $page, core_renderer $renderer)   X-Ref
Initialise with the bits of JavaScript that every Moodle page should have.

param: moodle_page $page
param: core_renderer $renderer

get_jsrev()   X-Ref
Determine the correct JS Revision to use for this load.

return: int the jsrev to use.

get_templaterev()   X-Ref
Determine the correct Template revision to use for this load.

return: int the templaterev to use.

js($url, $inhead = false)   X-Ref
Ensure that the specified JavaScript file is linked to from this page.

NOTE: This function is to be used in RARE CASES ONLY, please store your JS in module.js file
and use $PAGE->requires->js_init_call() instead or use /yui/ subdirectories for YUI modules.

By default the link is put at the end of the page, since this gives best page-load performance.

Even if a particular script is requested more than once, it will only be linked
to once.

param: string|moodle_url $url The path to the .js file, relative to $CFG->dirroot / $CFG->wwwroot.
param: bool $inhead initialise in head

jquery()   X-Ref
Request inclusion of jQuery library in the page.

NOTE: this should not be used in official Moodle distribution!

{@link https://moodledev.io/docs/guides/javascript/jquery}

jquery_plugin($plugin, $component = 'core')   X-Ref
Request inclusion of jQuery plugin.

NOTE: this should not be used in official Moodle distribution!

jQuery plugins are located in plugin/jquery/* subdirectory,
plugin/jquery/plugins.php lists all available plugins.

Included core plugins:
- jQuery UI

Add-ons may include extra jQuery plugins in jquery/ directory,
plugins.php file defines the mapping between plugin names and
necessary page includes.

Examples:
<code>
// file: mod/xxx/view.php
$PAGE->requires->jquery();
$PAGE->requires->jquery_plugin('ui');
$PAGE->requires->jquery_plugin('ui-css');
</code>

<code>
// file: theme/yyy/lib.php
function theme_yyy_page_init(moodle_page $page) {
$page->requires->jquery();
$page->requires->jquery_plugin('ui');
$page->requires->jquery_plugin('ui-css');
}
</code>

<code>
// file: blocks/zzz/block_zzz.php
public function get_required_javascript() {
parent::get_required_javascript();
$this->page->requires->jquery();
$page->requires->jquery_plugin('ui');
$page->requires->jquery_plugin('ui-css');
}
</code>

{@link https://moodledev.io/docs/guides/javascript/jquery}

param: string $plugin name of the jQuery plugin as defined in jquery/plugins.php
param: string $component name of the component
return: bool success

jquery_override_plugin($oldplugin, $newplugin)   X-Ref
Request replacement of one jQuery plugin by another.

This is useful when themes want to replace the jQuery UI theme,
the problem is that theme can not prevent others from including the core ui-css plugin.

Example:
1/ generate new jQuery UI theme and place it into theme/yourtheme/jquery/
2/ write theme/yourtheme/jquery/plugins.php
3/ init jQuery from theme

<code>
// file theme/yourtheme/lib.php
function theme_yourtheme_page_init($page) {
$page->requires->jquery_plugin('yourtheme-ui-css', 'theme_yourtheme');
$page->requires->jquery_override_plugin('ui-css', 'yourtheme-ui-css');
}
</code>

This code prevents loading of standard 'ui-css' which my be requested by other plugins,
the 'yourtheme-ui-css' gets loaded only if some other code requires jquery.

{@link https://moodledev.io/docs/guides/javascript/jquery}

param: string $oldplugin original plugin
param: string $newplugin the replacement

get_jquery_headcode()   X-Ref
Return jQuery related markup for page start.

return: string

js_fix_url($url)   X-Ref
Returns the actual url through which a JavaScript file is served.

param: moodle_url|string $url full moodle url, or shortened path to script.
return: moodle_url

find_module($component)   X-Ref
Find out if JS module present and return details.

param: string $component name of component in frankenstyle, ex: core_group, mod_forum
return: array description of module or null if not found

js_module($module)   X-Ref
Append YUI3 module to default YUI3 JS loader.
The structure of module array is described at {@link http://developer.yahoo.com/yui/3/yui/}

param: string|array $module name of module (details are autodetected), or full module specification as array
return: void

js_module_loaded($module)   X-Ref
Returns true if the module has already been loaded.

param: string|array $module
return: bool True if the module has already been loaded

css($stylesheet)   X-Ref
Ensure that the specified CSS file is linked to from this page.

Because stylesheet links must go in the <head> part of the HTML, you must call
this function before {@link get_head_code()} is called. That normally means before
the call to print_header. If you call it when it is too late, an exception
will be thrown.

Even if a particular style sheet is requested more than once, it will only
be linked to once.

Please note use of this feature is strongly discouraged,
it is suitable only for places where CSS is submitted directly by teachers.
(Students must not be allowed to submit any external CSS because it may
contain embedded javascript!). Example of correct use is mod/data.

param: string $stylesheet The path to the .css file, relative to $CFG->wwwroot.

css_theme(moodle_url $stylesheet)   X-Ref
Add theme stylesheet to page - do not use from plugin code,
this should be called only from the core renderer!

param: moodle_url $stylesheet
return: void

skip_link_to($target, $linktext)   X-Ref
Ensure that a skip link to a given target is printed at the top of the <body>.

You must call this function before {@link get_top_of_body_code()}, (if not, an exception
will be thrown). That normally means you must call this before the call to print_header.

If you ask for a particular skip link to be printed, it is then your responsibility
to ensure that the appropriate <a name="..."> tag is printed in the body of the
page, so that the skip link goes somewhere.

Even if a particular skip link is requested more than once, only one copy of it will be output.

param: string $target the name of anchor this link should go to. For example 'maincontent'.
param: string $linktext The text to use for the skip link. Normally get_string('skipto', 'access', ...);

js_function_call($function, array $arguments = null, $ondomready = false, $delay = 0)   X-Ref
!!!DEPRECATED!!! please use js_init_call() if possible
Ensure that the specified JavaScript function is called from an inline script
somewhere on this page.

By default the call will be put in a script tag at the
end of the page after initialising Y instance, since this gives best page-load
performance and allows you to use YUI3 library.

If you request that a particular function is called several times, then
that is what will happen (unlike linking to a CSS or JS file, where only
one link will be output).

The main benefit of the method is the automatic encoding of all function parameters.

param: string $function the name of the JavaScritp function to call. Can
param: array $arguments and array of arguments to be passed to the function.
param: bool $ondomready If tru the function is only called when the dom is
param: int $delay The delay before the function is called.

js_amd_inline($code)   X-Ref
This function appends a block of code to the AMD specific javascript block executed
in the page footer, just after loading the requirejs library.

The code passed here can rely on AMD module loading, e.g. require('jquery', function($) {...});

param: string $code The JS code to append.

js_call_amd($fullmodule, $func = null, $params = array()   X-Ref
Load an AMD module and eventually call its method.

This function creates a minimal inline JS snippet that requires an AMD module and eventually calls a single
function from the module with given arguments. If it is called multiple times, it will be create multiple
snippets.

param: string $fullmodule The name of the AMD module to load, formatted as <component name>/<module name>.
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).

yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false)   X-Ref
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.
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

set_yuicssmodules(array $modules = array()   X-Ref
Set the CSS Modules to be included from YUI.

param: array $modules The list of YUI CSS Modules to include.

js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null)   X-Ref
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,
param: array $extraarguments and array of arguments to be passed to the function.
param: bool $ondomready wait for dom ready (helps with some IE problems when modifying DOM)
param: array $module JS module specification array

js_init_code($jscode, $ondomready = false, array $module = null)   X-Ref
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

string_for_js($identifier, $component, $a = null)   X-Ref
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).

strings_for_js($identifiers, $component, $a = null)   X-Ref
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.

<code>
$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);
</code>

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

data_for_js($variable, $data, $inhead=false)   X-Ref
!!!!!!DEPRECATED!!!!!! please use js_init_call() for everything now.

Make some data from PHP available to JavaScript code.

For example, if you call
<pre>
$PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
</pre>
then in JavsScript mydata.name will be 'Moodle'.

param: string $variable the the name of the JavaScript variable to assign the data to.
param: mixed $data The data to pass to JavaScript. This will be escaped using json_encode,
param: bool $inhead initialise in head
return: void

event_handler($selector, $event, $function, array $arguments = null)   X-Ref
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

get_event_handler_code()   X-Ref
Returns code needed for registering of event handlers.

return: string JS code

get_javascript_code($ondomready)   X-Ref
Get the inline JavaScript code that need to appear in a particular place.

param: bool $ondomready
return: string

get_javascript_init_code()   X-Ref
Returns js code to be executed when Y is available.

return: string

get_amd_footercode()   X-Ref
Returns js code to load amd module loader, then insert inline script tags
that contain require() calls using RequireJS.

return: string

get_yui3lib_headcss()   X-Ref
Returns basic YUI3 CSS code.

return: string

get_yui3lib_headcode()   X-Ref
Returns basic YUI3 JS loading code.

return: string

get_css_code()   X-Ref
Returns html tags needed for inclusion of theme CSS.

return: string

get_extra_modules_code()   X-Ref
Adds extra modules specified after printing of page header.

return: string

get_head_code(moodle_page $page, core_renderer $renderer)   X-Ref
Generate any HTML that needs to go inside the <head> tag.

Normally, this method is called automatically by the code that prints the
<head> 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 <head> tag.

get_top_of_body_code(renderer_base $renderer)   X-Ref
Generate any HTML that needs to go at the start of the <body> tag.

Normally, this method is called automatically by the code that prints the
<head> 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 <body> tag.

get_end_code()   X-Ref
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.

is_head_done()   X-Ref
Have we already output the code in the <head> tag?

return: bool

is_top_of_body_done()   X-Ref
Have we already output the code at the start of the <body> tag?

return: bool

should_create_one_time_item_now($thing)   X-Ref
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:
<pre>
if (!$this->page->requires->should_create_one_time_item_now($thing)) {
return '';
}
// Else generate it.
</pre>

param: string $thing identifier for the bit of content. Should be of the form
return: bool if true, the caller should generate that bit of output now, otherwise don't.

has_one_time_item_been_created($thing)   X-Ref
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
return: bool whether that bit of output has been created.

set_one_time_item_created($thing)   X-Ref
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

Class: YUI_config  - X-Ref

This class represents the YUI configuration.

add_group($name, $config)   X-Ref
Create a new group within the YUI_config system.

param: String $name The name of the group. This must be unique and
param: Array $config The configuration for this group.
return: void

update_group($name, $config)   X-Ref
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
param: Array $config The configuration for this group.
return: void

set_config_function($function)   X-Ref
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.

set_config_source($file)   X-Ref
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.

get_config_functions()   X-Ref
Retrieve the list of JavaScript functions for YUI_config groups.

return: String The complete set of config functions

update_header_js($js)   X-Ref
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.

add_module_config($name, $config, $group = null)   X-Ref
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.
return: void

add_moodle_metadata()   X-Ref
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

get_moodle_metadata()   X-Ref
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

get_moodle_path_metadata($path)   X-Ref
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.

define_patched_core_modules($combobase, $yuiversion, $patchlevel, $patchedmodules)   X-Ref
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

template_reset_all_caches()   X-Ref
Invalidate all server and client side template caches.


js_reset_all_caches()   X-Ref
Invalidate all server and client side JS caches.