MediaWiki master
|
ResourceLoader is a loading system for JavaScript and CSS resources. More...
Inherits LoggerAwareInterface.
Public Member Functions | |
__construct (Config $config, ?LoggerInterface $logger=null, ?DependencyStore $tracker=null, array $params=[]) | |
addSource ( $sources, $loadUrl=null) | |
Add a foreign source of modules. | |
createLoaderURL ( $source, Context $context, array $extraQuery=[]) | |
Build a load.php URL. | |
expandUrl (string $base, string $url) | |
Resolve a possibly relative URL against a base URL. | |
getCombinedVersion (Context $context, array $moduleNames) | |
Helper method to get and combine versions of multiple modules. | |
getConfig () | |
getDependencyStore () | |
getErrors () | |
getLessCompiler (array $vars=[], array $importDirs=[]) | |
Return a LESS compiler that is set up for use with MediaWiki. | |
getLoadScript ( $source) | |
Get the URL to the load.php endpoint for the given ResourceLoader source. | |
getLogger () | |
getMessageBlobStore () | |
getModule ( $name) | |
Get the Module object for a given module name. | |
getModuleNames () | |
getModulesByMessage ( $messageKey) | |
Get names of modules that use a certain message. | |
getSources () | |
Get the list of sources. | |
getTestSuiteModuleNames () | |
Get a list of modules with QUnit tests. | |
isModuleRegistered ( $name) | |
Check whether a ResourceLoader module is registered. | |
makeModuleResponse (Context $context, array $modules, array $missing=[]) | |
Generate code for a response. | |
makeVersionQuery (Context $context, array $modules) | |
Get the expected value of the 'version' query parameter. | |
outputErrorAndLog (Exception $e, $msg, array $context=[]) | |
Add an error to the 'errors' array and log it. | |
preloadModuleInfo (array $moduleNames, Context $context) | |
Load information stored in the database and dependency tracking store about modules. | |
register ( $name, ?array $info=null) | |
Register a module with the ResourceLoader system. | |
registerTestModules () | |
respond (Context $context) | |
Output a response to a load request, including the content-type header. | |
setDependencyStore (DependencyStore $tracker) | |
setLogger (LoggerInterface $logger) | |
setMessageBlobStore (MessageBlobStore $blobStore) | |
setModuleSkinStyles (array $moduleSkinStyles) | |
Static Public Member Functions | |
static | clearCache () |
Reset static members used for caching. | |
static | ensureNewline ( $str) |
Ensure the string is either empty or ends in a line break. | |
static | expandModuleNames ( $modules) |
Expand a string of the form jquery.foo,bar|jquery.ui.baz,quux to an array of module names like ‘[ 'jquery.foo’, 'jquery.bar', 'jquery.ui.baz', 'jquery.ui.quux' ]`. | |
static | filter ( $filter, $data, array $options=[]) |
Run JavaScript or CSS data through a filter, caching the filtered result for future calls. | |
static | getSiteConfigSettings (Context $context, Config $conf) |
Get site configuration settings to expose to JavaScript on all pages via mw.config . | |
static | getUserDefaults (Context $context, HookContainer $hookContainer, UserOptionsLookup $userOptionsLookup) |
Get user default options to expose to JavaScript on all pages via mw.user.options . | |
static | inDebugMode () |
Determine whether debug mode is on. | |
static | isValidModuleName ( $moduleName) |
Check a module name for validity. | |
static | makeCombinedStyles (array $stylePairs) |
Combines an associative array mapping media type to CSS into a single stylesheet with "@media" blocks. | |
static | makeComment ( $text) |
Generate a CSS or JS comment block. | |
static | makeConfigSetScript (array $configuration) |
Return JS code which will set the MediaWiki configuration array to the given value. | |
static | makeHash ( $value) |
Create a hash for module versioning purposes. | |
static | makeInlineCodeWithModule ( $modules, $script) |
Wrap JavaScript code to run after a required module. | |
static | makeInlineScript ( $script, $nonce=null) |
Make an HTML script that runs given JS code after startup and base modules. | |
static | makeLoaderConditionalScript ( $script) |
Wrap JavaScript code to run after the startup module. | |
static | makeLoaderQuery (array $modules, $lang, $skin, $user=null, $version=null, $debug=Context::DEBUG_OFF, $only=null, $printable=false, $handheld=null, array $extraQuery=[]) |
Build a query array (array representation of query string) for load.php. | |
static | makeLoaderRegisterScript (Context $context, array $modules) |
Format JS code which calls mw.loader.register() with the given parameters. | |
static | makeLoaderSourcesScript (Context $context, array $sources) |
Format JS code which calls mw.loader.addSource() with the given parameters. | |
static | makeLoaderStateScript (Context $context, array $states) |
Format a JS call to mw.loader.state() | |
static | makePackedModulesString (array $modules) |
Convert an array of module names to a packed query string. | |
Public Attributes | |
const | HASH_LENGTH = 5 |
Protected Member Functions | |
measureResponseTime () | |
Send stats about the time used to build the response. | |
sendResponseHeaders (Context $context, $etag, $errors, array $extra=[]) | |
Send main response headers to the client. | |
tryRespondNotModified (Context $context, $etag) | |
Respond with HTTP 304 Not Modified if appropriate. | |
Static Protected Member Functions | |
static | createLoaderQuery (Context $context, array $extraQuery=[]) |
Helper for createLoaderURL() | |
static | formatExceptionNoComment (Throwable $e) |
Handle exception display. | |
Protected Attributes | |
array | $errors = [] |
Errors accumulated during a respond() call. | |
string[] | $extraHeaders = [] |
Buffer for extra response headers during a makeModuleResponse() call. | |
Static Protected Attributes | |
static int null | $debugMode = null |
ResourceLoader is a loading system for JavaScript and CSS resources.
For higher level documentation, see https://www.mediawiki.org/wiki/ResourceLoader/Architecture.
Definition at line 93 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::__construct | ( | Config | $config, |
?LoggerInterface | $logger = null, | ||
?DependencyStore | $tracker = null, | ||
array | $params = [] ) |
Config | $config | Generic pass-through for use by extension callbacks and other MediaWiki-specific module classes. |
LoggerInterface | null | $logger | [optional] |
DependencyStore | null | $tracker | [optional] |
array | $params | [optional]
|
Definition at line 165 of file ResourceLoader.php.
References $params, MediaWiki\ResourceLoader\ResourceLoader\addSource(), MediaWiki\MediaWikiServices\getInstance(), MediaWiki\ResourceLoader\ResourceLoader\setDependencyStore(), and MediaWiki\ResourceLoader\ResourceLoader\setMessageBlobStore().
MediaWiki\ResourceLoader\ResourceLoader::addSource | ( | $sources, | |
$loadUrl = null ) |
Add a foreign source of modules.
Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
array | string | $sources | Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ] |
string | array | null | $loadUrl | load.php url (string), or array with loadUrl key for backwards-compatibility. |
InvalidArgumentException | If array-form $loadUrl lacks a 'loadUrl' key. |
Definition at line 341 of file ResourceLoader.php.
References $source.
Referenced by MediaWiki\ResourceLoader\ResourceLoader\__construct().
|
static |
Reset static members used for caching.
Global state and $wgRequest are evil, but we're using it right now and sometimes we need to be able to force ResourceLoader to re-evaluate the context because it has changed (e.g. in the test suite).
Definition at line 1853 of file ResourceLoader.php.
|
staticprotected |
Helper for createLoaderURL()
Context | $context | |
array | $extraQuery |
Definition at line 1884 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::createLoaderURL | ( | $source, | |
Context | $context, | ||
array | $extraQuery = [] ) |
Build a load.php URL.
string | $source | Name of the ResourceLoader source |
Context | $context | |
array | $extraQuery |
Definition at line 1866 of file ResourceLoader.php.
|
static |
Ensure the string is either empty or ends in a line break.
string | $str |
Definition at line 1280 of file ResourceLoader.php.
|
static |
Expand a string of the form jquery.foo,bar|jquery.ui.baz,quux
to an array of module names like ‘[ 'jquery.foo’, 'jquery.bar', 'jquery.ui.baz', 'jquery.ui.quux' ]`.
This process is reversed by ResourceLoader::makePackedModulesString().
string | $modules | Packed module name list |
Definition at line 1793 of file ResourceLoader.php.
Referenced by MediaWiki\ResourceLoader\Context\__construct().
MediaWiki\ResourceLoader\ResourceLoader::expandUrl | ( | string | $base, |
string | $url ) |
Resolve a possibly relative URL against a base URL.
The base URL must have a server and should have a protocol. A protocol-relative base expands to HTTPS.
This is a standalone version of MediaWiki's UrlUtils::expand (T32956).
string | $base | |
string | $url |
Definition at line 2067 of file ResourceLoader.php.
|
static |
Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
Available filters are:
If $data is empty, only contains whitespace or the filter was unknown, $data is returned unmodified.
string | $filter | Name of filter to run |
string | $data | Text to filter, such as JavaScript or CSS text |
array<string,bool> | $options Keys:
|
Definition at line 2099 of file ResourceLoader.php.
|
staticprotected |
Handle exception display.
Throwable | $e | Exception to be shown to the user |
Definition at line 969 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::getCombinedVersion | ( | Context | $context, |
array | $moduleNames ) |
Helper method to get and combine versions of multiple modules.
Context | $context | |
string[] | $moduleNames | List of known module names |
Definition at line 604 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::getConfig | ( | ) |
Definition at line 200 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::getDependencyStore | ( | ) |
Definition at line 249 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::getErrors | ( | ) |
MediaWiki\ResourceLoader\ResourceLoader::getLessCompiler | ( | array | $vars = [], |
array | $importDirs = [] ) |
Return a LESS compiler that is set up for use with MediaWiki.
array | $vars | Associative array of variables that should be used for compilation. Since 1.32, this method no longer automatically includes global LESS vars from ResourceLoader::getLessVars (T191937). |
array | $importDirs | Additional directories to look in for @import (since 1.36) |
Definition at line 1982 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::getLoadScript | ( | $source | ) |
Get the URL to the load.php endpoint for the given ResourceLoader source.
string | $source | Source ID |
UnexpectedValueException | If the source ID was not registered |
Definition at line 493 of file ResourceLoader.php.
References $source.
MediaWiki\ResourceLoader\ResourceLoader::getLogger | ( | ) |
Definition at line 216 of file ResourceLoader.php.
Referenced by MediaWiki\ResourceLoader\Context\__construct().
MediaWiki\ResourceLoader\ResourceLoader::getMessageBlobStore | ( | ) |
MediaWiki\ResourceLoader\ResourceLoader::getModule | ( | $name | ) |
Get the Module object for a given module name.
If an array of module parameters exists but a Module object has not yet been instantiated, this method will instantiate and cache that object such that subsequent calls simply return the same object.
string | $name | Module name |
Definition at line 403 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::getModuleNames | ( | ) |
Definition at line 366 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::getModulesByMessage | ( | $messageKey | ) |
Get names of modules that use a certain message.
string | $messageKey |
Definition at line 1294 of file ResourceLoader.php.
|
static |
Get site configuration settings to expose to JavaScript on all pages via mw.config
.
Context | $context | |
Config | $conf |
Definition at line 2196 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::getSources | ( | ) |
Get the list of sources.
Definition at line 481 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::getTestSuiteModuleNames | ( | ) |
Get a list of modules with QUnit tests.
Definition at line 377 of file ResourceLoader.php.
|
static |
Get user default options to expose to JavaScript on all pages via mw.user.options
.
Context | $context | |
HookContainer | $hookContainer | |
UserOptionsLookup | $userOptionsLookup |
Definition at line 2173 of file ResourceLoader.php.
|
static |
Determine whether debug mode is on.
Order of priority is:
Definition at line 1830 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::isModuleRegistered | ( | $name | ) |
Check whether a ResourceLoader module is registered.
string | $name |
Definition at line 388 of file ResourceLoader.php.
|
static |
Check a module name for validity.
Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be at most 255 bytes.
string | $moduleName | Module name to check |
Definition at line 1967 of file ResourceLoader.php.
|
static |
Combines an associative array mapping media type to CSS into a single stylesheet with "@media" blocks.
array<string,string|string[]> | $stylePairs Map from media type to CSS string(s) |
Definition at line 1502 of file ResourceLoader.php.
|
static |
Generate a CSS or JS comment block.
Only use this for public data, not error message details.
string | $text |
Definition at line 957 of file ResourceLoader.php.
Referenced by MediaWiki\ResourceLoader\WikiModule\getScript().
|
static |
Return JS code which will set the MediaWiki configuration array to the given value.
array | $configuration | List of configuration values keyed by variable name |
LogicException |
Definition at line 1739 of file ResourceLoader.php.
|
static |
Create a hash for module versioning purposes.
This hash is used in three ways:
To differentiate between the current version and a past version of a module by the same name.
In the cache key of localStorage in the browser (mw.loader.store). This store keeps only one version of any given module. As long as the next version the client encounters has a different hash from the last version it saw, it will correctly discard it in favour of a network fetch.
A browser may evict a site's storage container for any reason (e.g. when the user hasn't visited a site for some time, and/or when the device is low on storage space). Anecdotally it seems devices rarely keep unused storage beyond 2 weeks on mobile devices and 4 weeks on desktop. But, there is no hard limit or expiration on localStorage. ResourceLoader's Client also clears localStorage when the user changes their language preference or when they (temporarily) use Debug Mode.
The only hard factors that reduce the range of possible versions are 1) the name and existence of a given module, and 2) the TTL for mw.loader.store, and 3) the $wgResourceLoaderStorageVersion
configuration variable.
To identify a batch response of modules from load.php in an HTTP cache.
When fetching modules in a batch from load.php, a combined hash is created by the JS code, and appended as query parameter.
In cache proxies (e.g. Varnish, Nginx) and in the browser's HTTP cache, these urls are used to identify other previously cached responses. The range of possible versions a given version has to be unique amongst is determined by the maximum duration each response is stored for, which is controlled by ‘$wgResourceLoaderMaxage['versioned’]`.
To detect race conditions between multiple web servers in a MediaWiki deployment of which some have the newer version and some still the older version.
An HTTP request from a browser for the Startup manifest may be responded to by a server with the newer version. The browser may then use that to request a given module, which may then be responded to by a server with the older version. To avoid caching this for too long (which would pollute all other users without repairing itself), the combined hash that the JS client adds to the url is verified by the server (in ::sendResponseHeaders). If they don't match, we instruct cache proxies and clients to not cache this response as long as they normally would. This is also the reason that the algorithm used here in PHP must match the one used in JS.
The fnv132 digest creates a 32-bit integer, which goes upto 4 Giga and needs up to 7 chars in base 36. Within 7 characters, base 36 can count up to 78,364,164,096 (78 Giga), (but with fnv132 we'd use very little of this range, mostly padding). Within 6 characters, base 36 can count up to 2,176,782,336 (2 Giga). Within 5 characters, base 36 can count up to 60,466,176 (60 Mega).
string | $value |
Definition at line 567 of file ResourceLoader.php.
|
static |
Wrap JavaScript code to run after a required module.
string | string[] | $modules | Module name(s) |
string | $script | JavaScript code |
Definition at line 1704 of file ResourceLoader.php.
|
static |
Make an HTML script that runs given JS code after startup and base modules.
The code will be wrapped in a closure, and it will be executed by ResourceLoader's startup module if the client has adequate support for MediaWiki JavaScript code.
string | $script | JavaScript code |
string | null | $nonce | Unused |
Definition at line 1722 of file ResourceLoader.php.
Referenced by MediaWiki\Debug\MWDebug\getDebugHTML().
|
static |
Wrap JavaScript code to run after the startup module.
string | $script | JavaScript code |
Definition at line 1690 of file ResourceLoader.php.
|
static |
Build a query array (array representation of query string) for load.php.
Helper function for createLoaderURL().
string[] | $modules | |
string | $lang | |
string | $skin | |
string | null | $user | |
string | null | $version | |
int | $debug | |
string | null | $only | |
bool | $printable | |
bool | null | $handheld | Unused as of MW 1.38 |
array | $extraQuery |
Definition at line 1917 of file ResourceLoader.php.
|
static |
Format JS code which calls mw.loader.register()
with the given parameters.
Context | $context | |
array[] | $modules | Array of module registration arrays, each containing
|
Definition at line 1635 of file ResourceLoader.php.
|
static |
Format JS code which calls mw.loader.addSource()
with the given parameters.
Context | $context | |
array<string,string> | $sources |
Definition at line 1676 of file ResourceLoader.php.
|
static |
Format a JS call to mw.loader.state()
Context | $context | |
array<string,string> | $states |
Definition at line 1564 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::makeModuleResponse | ( | Context | $context, |
array | $modules, | ||
array | $missing = [] ) |
Generate code for a response.
Calling this method also populates the errors
and headers
members, later used by respond().
Context | $context | Context in which to generate a response |
Module[] | $modules | List of module objects keyed by module name |
string[] | $missing | List of requested module names that are unregistered (optional) |
Definition at line 998 of file ResourceLoader.php.
References MediaWiki\ResourceLoader\Context\encodeJson(), MediaWiki\ResourceLoader\Context\getDebug(), MediaWiki\ResourceLoader\Context\getImageObj(), MediaWiki\ResourceLoader\Context\getOnly(), MediaWiki\ResourceLoader\Context\getRaw(), MediaWiki\ResourceLoader\Context\isSourceMap(), and MediaWiki\ResourceLoader\Context\shouldIncludeScripts().
|
static |
Convert an array of module names to a packed query string.
For example, ‘[ 'foo.bar’, 'foo.baz', 'bar.baz', 'bar.quux' ] becomes
'foo.bar,baz|bar.baz,quux'`.
This process is reversed by ResourceLoader::expandModuleNames(). See also mw.loader::buildModulesString() which is a port of this, used on the client-side.
string[] | $modules | List of module names (strings) |
Definition at line 1765 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::makeVersionQuery | ( | Context | $context, |
array | $modules ) |
Get the expected value of the 'version' query parameter.
This is used by respond() to set a short Cache-Control header for requests with information newer than the current server has. This avoids pollution of edge caches. Typically during deployment. (T117587)
This MUST match return value of mw.loader#getCombinedVersion()
client-side.
Context | $context | |
string[] | $modules |
Definition at line 644 of file ResourceLoader.php.
|
protected |
Send stats about the time used to build the response.
Definition at line 792 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::outputErrorAndLog | ( | Exception | $e, |
$msg, | |||
array | $context = [] ) |
Add an error to the 'errors' array and log it.
Exception | $e | |
string | $msg | |
array | $context |
Definition at line 587 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::preloadModuleInfo | ( | array | $moduleNames, |
Context | $context ) |
Load information stored in the database and dependency tracking store about modules.
string[] | $moduleNames | |
Context | $context | ResourceLoader-specific context of the request |
Definition at line 436 of file ResourceLoader.php.
References MediaWiki\ResourceLoader\Context\getLanguage().
MediaWiki\ResourceLoader\ResourceLoader::register | ( | $name, | |
?array | $info = null ) |
Register a module with the ResourceLoader system.
string | array[] | $name | Module name as a string or, array of module info arrays keyed by name. |
array | null | $info | Module info array. When using the first parameter to register multiple modules at once, this parameter is optional. |
InvalidArgumentException | If a module name contains illegal characters (pipes or commas) |
InvalidArgumentException | If the module info is not an array |
Definition at line 272 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::registerTestModules | ( | ) |
Definition at line 305 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::respond | ( | Context | $context | ) |
Output a response to a load request, including the content-type header.
Context | $context | Context in which a response should be formed |
Definition at line 667 of file ResourceLoader.php.
References MediaWiki\ResourceLoader\Context\encodeJson(), MediaWiki\ResourceLoader\Context\getDebug(), MediaWiki\ResourceLoader\Context\getImage(), MediaWiki\ResourceLoader\Context\getImageObj(), MediaWiki\ResourceLoader\Context\getModules(), MediaWiki\ResourceLoader\Context\getOnly(), MediaWiki\ResourceLoader\Context\getVersion(), MediaWiki\ResourceLoader\Context\isSourceMap(), MW_ENTRY_POINT, and MediaWiki\ResourceLoader\Context\shouldIncludeScripts().
|
protected |
Send main response headers to the client.
Deals with Content-Type, CORS (for stylesheets), and caching.
Context | $context | |
string | $etag | ETag header value |
bool | $errors | Whether there are errors in the response |
string[] | $extra | Array of extra HTTP response headers |
Definition at line 813 of file ResourceLoader.php.
MediaWiki\ResourceLoader\ResourceLoader::setDependencyStore | ( | DependencyStore | $tracker | ) |
DependencyStore | $tracker |
Definition at line 240 of file ResourceLoader.php.
Referenced by MediaWiki\ResourceLoader\ResourceLoader\__construct().
MediaWiki\ResourceLoader\ResourceLoader::setLogger | ( | LoggerInterface | $logger | ) |
MediaWiki\ResourceLoader\ResourceLoader::setMessageBlobStore | ( | MessageBlobStore | $blobStore | ) |
MessageBlobStore | $blobStore |
Definition at line 232 of file ResourceLoader.php.
Referenced by MediaWiki\ResourceLoader\ResourceLoader\__construct().
MediaWiki\ResourceLoader\ResourceLoader::setModuleSkinStyles | ( | array | $moduleSkinStyles | ) |
array | $moduleSkinStyles |
Definition at line 257 of file ResourceLoader.php.
|
protected |
Respond with HTTP 304 Not Modified if appropriate.
If there's an If-None-Match header, respond with a 304 appropriately and clear out the output buffer. If the client cache is too old then do nothing.
Context | $context | |
string | $etag | ETag header value |
Definition at line 886 of file ResourceLoader.php.
References MediaWiki\ResourceLoader\Context\getDebug(), MediaWiki\ResourceLoader\Context\getRequest(), and wfResetOutputBuffers().
|
staticprotected |
Definition at line 103 of file ResourceLoader.php.
|
protected |
Errors accumulated during a respond() call.
Exposed for testing.
Definition at line 133 of file ResourceLoader.php.
|
protected |
Buffer for extra response headers during a makeModuleResponse() call.
Exposed for testing.
Definition at line 138 of file ResourceLoader.php.
const MediaWiki\ResourceLoader\ResourceLoader::HASH_LENGTH = 5 |
Definition at line 503 of file ResourceLoader.php.