MediaWiki REL1_39
MediaWiki\ResourceLoader\ResourceLoader Class Reference

ResourceLoader is a loading system for JavaScript and CSS resources. More...

Inheritance diagram for MediaWiki\ResourceLoader\ResourceLoader:
Collaboration diagram for MediaWiki\ResourceLoader\ResourceLoader:

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 ()
 
 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.
 
 loadModuleDependenciesInternal ( $moduleName, $variant)
 
 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.
 
 saveModuleDependenciesInternal ( $moduleName, $variant, $paths, $priorPaths)
 
 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 encodeJsonForScript ( $data)
 Wrapper around json_encode that avoids needless escapes, and pretty-prints in debug mode.
 
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 formatException (Throwable $e)
 Handle exception display.
 
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)
 Returns a JS call to mw.loader.state, which sets the state of modules to a given value:
 
static makeMessageSetScript ( $messages)
 Returns JS code which, when called, will register a given list of messages.
 
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.
 
 tryRespondFromFileCache (ResourceFileCache $fileCache, Context $context, $etag)
 Send out code for a response from file cache if possible.
 
 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
 

Detailed Description

ResourceLoader is a loading system for JavaScript and CSS resources.

For higher level documentation, see https://www.mediawiki.org/wiki/ResourceLoader/Architecture.

Since
1.17

Definition at line 100 of file ResourceLoader.php.

Constructor & Destructor Documentation

◆ __construct()

MediaWiki\ResourceLoader\ResourceLoader::__construct ( Config $config,
LoggerInterface $logger = null,
DependencyStore $tracker = null,
array $params = [] )
Access: internal
For ServiceWiring only (TODO: Make stable as part of T32956).
Parameters
Config$configGeneric pass-through for use by extension callbacks and other MediaWiki-specific module classes.
LoggerInterface | null$logger[optional]
DependencyStore | null$tracker[optional]
array$params[optional]
  • loadScript: URL path to the load.php entrypoint. Default: ‘’/load.php'.
  • maxageVersioned: HTTP cache max-age in seconds for URLs with a "version" parameter. This applies to most load.php responses, and may have a long duration (e.g. weeks or months), because a change in the module bundle will naturally produce a different URL and thus automatically bust the CDN and web browser caches. Default: 30 days.
  • maxageUnversioned: HTTP cache max-age in seconds for URLs without a "version" parameter. This should have a short duration (e.g. minutes), and affects the startup manifest which controls how quickly changes (in the module registry, dependency tree, or module content) will propagate to clients. Default: 5 minutes.
  • useFileCache: Enable use of MediaWiki's FileCache feature. See also $wgUseFileCache and ResourceFileCache. Default:false`.

Definition at line 183 of file ResourceLoader.php.

References $tracker, MediaWiki\ResourceLoader\ResourceLoader\addSource(), MediaWiki\MediaWikiServices\getInstance(), MediaWiki\ResourceLoader\ResourceLoader\setDependencyStore(), and MediaWiki\ResourceLoader\ResourceLoader\setMessageBlobStore().

Member Function Documentation

◆ addSource()

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).

Parameters
array | string$sourcesSource ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
string | array | null$loadUrlload.php url (string), or array with loadUrl key for backwards-compatibility.
Exceptions
InvalidArgumentExceptionIf array-form $loadUrl lacks a 'loadUrl' key.

Definition at line 355 of file ResourceLoader.php.

References $source.

Referenced by MediaWiki\ResourceLoader\ResourceLoader\__construct().

◆ clearCache()

static MediaWiki\ResourceLoader\ResourceLoader::clearCache ( )
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).

Access: internal
For use by unit tests

Definition at line 1723 of file ResourceLoader.php.

◆ createLoaderQuery()

static MediaWiki\ResourceLoader\ResourceLoader::createLoaderQuery ( Context $context,
array $extraQuery = [] )
staticprotected

Helper for createLoaderURL()

Since
1.24
See also
makeLoaderQuery
Parameters
Context$context
array$extraQuery
Returns
array

Definition at line 1754 of file ResourceLoader.php.

◆ createLoaderURL()

MediaWiki\ResourceLoader\ResourceLoader::createLoaderURL ( $source,
Context $context,
array $extraQuery = [] )

Build a load.php URL.

Since
1.24
Parameters
string$sourceName of the ResourceLoader source
Context$context
array$extraQuery
Returns
string URL to load.php. May be protocol-relative if $wgLoadScript is, too.

Definition at line 1736 of file ResourceLoader.php.

◆ encodeJsonForScript()

static MediaWiki\ResourceLoader\ResourceLoader::encodeJsonForScript ( $data)
static

Wrapper around json_encode that avoids needless escapes, and pretty-prints in debug mode.

Access: internal
For use within ResourceLoader classes only
Since
1.32
Parameters
mixed$data
Returns
string|false JSON string, false on error

Definition at line 1393 of file ResourceLoader.php.

◆ ensureNewline()

static MediaWiki\ResourceLoader\ResourceLoader::ensureNewline ( $str)
static

Ensure the string is either empty or ends in a line break.

Access: internal
Parameters
string$str
Returns
string

Definition at line 1245 of file ResourceLoader.php.

◆ expandModuleNames()

static MediaWiki\ResourceLoader\ResourceLoader::expandModuleNames ( $modules)
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().

Since
1.33
Parameters
string$modulesPacked module name list
Returns
string[] Array of module names

Definition at line 1663 of file ResourceLoader.php.

Referenced by MediaWiki\ResourceLoader\Context\__construct().

◆ expandUrl()

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 wfExpandUrl (T32956).

Access: internal
For use by core ResourceLoader classes only
Parameters
string$base
string$url
Returns
string URL

Definition at line 1884 of file ResourceLoader.php.

◆ filter()

static MediaWiki\ResourceLoader\ResourceLoader::filter ( $filter,
$data,
array $options = [] )
static

Run JavaScript or CSS data through a filter, caching the filtered result for future calls.

Available filters are:

  • minify-js
  • minify-css

If $data is empty, only contains whitespace or the filter was unknown, $data is returned unmodified.

Parameters
string$filterName of filter to run
string$dataText to filter, such as JavaScript or CSS text
array<string,bool>$options Keys:
  • (bool) cache: Whether to allow caching this data. Default: true.
Returns
string Filtered data or unfiltered data

Definition at line 1916 of file ResourceLoader.php.

◆ formatException()

static MediaWiki\ResourceLoader\ResourceLoader::formatException ( Throwable $e)
static

Handle exception display.

Parameters
Throwable$eException to be shown to the user
Returns
string Sanitized text in a CSS/JS comment that can be returned to the user

Definition at line 1059 of file ResourceLoader.php.

◆ formatExceptionNoComment()

static MediaWiki\ResourceLoader\ResourceLoader::formatExceptionNoComment ( Throwable $e)
staticprotected

Handle exception display.

Since
1.25
Parameters
Throwable$eException to be shown to the user
Returns
string Sanitized text that can be returned to the user

Definition at line 1070 of file ResourceLoader.php.

◆ getCombinedVersion()

MediaWiki\ResourceLoader\ResourceLoader::getCombinedVersion ( Context $context,
array $moduleNames )

Helper method to get and combine versions of multiple modules.

Since
1.26
Parameters
Context$context
string[]$moduleNamesList of known module names
Returns
string Hash

Definition at line 695 of file ResourceLoader.php.

References $hashes.

◆ getConfig()

MediaWiki\ResourceLoader\ResourceLoader::getConfig ( )
Returns
Config

Definition at line 218 of file ResourceLoader.php.

◆ getLessCompiler()

MediaWiki\ResourceLoader\ResourceLoader::getLessCompiler ( array $vars = [],
array $importDirs = [] )

Return a LESS compiler that is set up for use with MediaWiki.

Since
1.27
Parameters
array$varsAssociative 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$importDirsAdditional directories to look in for @import (since 1.36)
Exceptions
MWException
Returns
Less_Parser

Definition at line 1851 of file ResourceLoader.php.

◆ getLoadScript()

MediaWiki\ResourceLoader\ResourceLoader::getLoadScript ( $source)

Get the URL to the load.php endpoint for the given ResourceLoader source.

Since
1.24
Parameters
string$sourceSource ID
Returns
string
Exceptions
UnexpectedValueExceptionIf the source ID was not registered

Definition at line 584 of file ResourceLoader.php.

References $source.

◆ getLogger()

MediaWiki\ResourceLoader\ResourceLoader::getLogger ( )
Since
1.27
Returns
LoggerInterface

Definition at line 234 of file ResourceLoader.php.

Referenced by MediaWiki\ResourceLoader\Context\__construct().

◆ getMessageBlobStore()

MediaWiki\ResourceLoader\ResourceLoader::getMessageBlobStore ( )
Since
1.26
Returns
MessageBlobStore

Definition at line 242 of file ResourceLoader.php.

◆ getModule()

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.

Parameters
string$nameModule name
Returns
Module|null If module has been registered, return a Module instance. Otherwise, return null.

Definition at line 417 of file ResourceLoader.php.

◆ getModuleNames()

MediaWiki\ResourceLoader\ResourceLoader::getModuleNames ( )
Returns
string[]

Definition at line 380 of file ResourceLoader.php.

◆ getModulesByMessage()

MediaWiki\ResourceLoader\ResourceLoader::getModulesByMessage ( $messageKey)

Get names of modules that use a certain message.

Parameters
string$messageKey
Returns
string[] List of module names

Definition at line 1259 of file ResourceLoader.php.

◆ getSiteConfigSettings()

static MediaWiki\ResourceLoader\ResourceLoader::getSiteConfigSettings ( Context $context,
Config $conf )
static

Get site configuration settings to expose to JavaScript on all pages via mw.config.

Access: internal
Exposed for use from Resources.php
Parameters
Context$context
Config$conf
Returns
array

Definition at line 2009 of file ResourceLoader.php.

◆ getSources()

MediaWiki\ResourceLoader\ResourceLoader::getSources ( )

Get the list of sources.

Returns
array Like [ id => load.php url, ... ]

Definition at line 572 of file ResourceLoader.php.

◆ getTestSuiteModuleNames()

MediaWiki\ResourceLoader\ResourceLoader::getTestSuiteModuleNames ( )

Get a list of modules with QUnit tests.

Access: internal
For use by SpecialJavaScriptTest only
Returns
string[]

Definition at line 391 of file ResourceLoader.php.

◆ getUserDefaults()

static MediaWiki\ResourceLoader\ResourceLoader::getUserDefaults ( Context $context,
HookContainer $hookContainer,
UserOptionsLookup $userOptionsLookup )
static

Get user default options to expose to JavaScript on all pages via mw.user.options.

Access: internal
Exposed for use from Resources.php
Parameters
Context$context
HookContainer$hookContainer
UserOptionsLookup$userOptionsLookup
Returns
array

Definition at line 1986 of file ResourceLoader.php.

◆ inDebugMode()

static MediaWiki\ResourceLoader\ResourceLoader::inDebugMode ( )
static

Determine whether debug mode is on.

Order of priority is:

  • 1) Request parameter,
  • 2) Cookie,
  • 3) Site configuration.
Returns
int

Definition at line 1700 of file ResourceLoader.php.

◆ isModuleRegistered()

MediaWiki\ResourceLoader\ResourceLoader::isModuleRegistered ( $name)

Check whether a ResourceLoader module is registered.

Since
1.25
Parameters
string$name
Returns
bool

Definition at line 402 of file ResourceLoader.php.

◆ isValidModuleName()

static MediaWiki\ResourceLoader\ResourceLoader::isValidModuleName ( $moduleName)
static

Check a module name for validity.

Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be at most 255 bytes.

Parameters
string$moduleNameModule name to check
Returns
bool Whether $moduleName is a valid module name

Definition at line 1835 of file ResourceLoader.php.

◆ loadModuleDependenciesInternal()

MediaWiki\ResourceLoader\ResourceLoader::loadModuleDependenciesInternal ( $moduleName,
$variant )
Access: internal
Exposed for letting getModule() pass the callable to DependencyStore
Parameters
string$moduleName
string$variantLanguage/skin variant
Returns
string[] List of absolute file paths

Definition at line 503 of file ResourceLoader.php.

References MediaWiki\ResourceLoader\Module\expandRelativePaths().

◆ makeCombinedStyles()

static MediaWiki\ResourceLoader\ResourceLoader::makeCombinedStyles ( array $stylePairs)
static

Combines an associative array mapping media type to CSS into a single stylesheet with "@media" blocks.

Parameters
array<string,string|string[]>$stylePairs Map from media type to CSS string(s)
Returns
string[] CSS strings

Definition at line 1357 of file ResourceLoader.php.

◆ makeComment()

static MediaWiki\ResourceLoader\ResourceLoader::makeComment ( $text)
static

Generate a CSS or JS comment block.

Only use this for public data, not error message details.

Parameters
string$text
Returns
string

Definition at line 1048 of file ResourceLoader.php.

Referenced by MediaWiki\ResourceLoader\WikiModule\getScript().

◆ makeConfigSetScript()

static MediaWiki\ResourceLoader\ResourceLoader::makeConfigSetScript ( array $configuration)
static

Return JS code which will set the MediaWiki configuration array to the given value.

Parameters
array$configurationList of configuration values keyed by variable name
Returns
string JavaScript code
Exceptions
Exception

Definition at line 1609 of file ResourceLoader.php.

◆ makeHash()

static MediaWiki\ResourceLoader\ResourceLoader::makeHash ( $value)
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).

Since
1.26
Parameters
string$value
Returns
string Hash

Definition at line 658 of file ResourceLoader.php.

◆ makeInlineCodeWithModule()

static MediaWiki\ResourceLoader\ResourceLoader::makeInlineCodeWithModule ( $modules,
$script )
static

Wrap JavaScript code to run after a required module.

Since
1.32
Parameters
string | string[]$modulesModule name(s)
string$scriptJavaScript code
Returns
string JavaScript code

Definition at line 1563 of file ResourceLoader.php.

◆ makeInlineScript()

static MediaWiki\ResourceLoader\ResourceLoader::makeInlineScript ( $script,
$nonce = null )
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.

Parameters
string$scriptJavaScript code
string | null$nonceContent-Security-Policy nonce (from OutputPage->getCSP()->getNonce())
Returns
string|WrappedString HTML

Definition at line 1582 of file ResourceLoader.php.

◆ makeLoaderConditionalScript()

static MediaWiki\ResourceLoader\ResourceLoader::makeLoaderConditionalScript ( $script)
static

Wrap JavaScript code to run after the startup module.

Parameters
string$scriptJavaScript code
Returns
string JavaScript code

Definition at line 1549 of file ResourceLoader.php.

◆ makeLoaderQuery()

static MediaWiki\ResourceLoader\ResourceLoader::makeLoaderQuery ( array $modules,
$lang,
$skin,
$user = null,
$version = null,
$debug = Context::DEBUG_OFF,
$only = null,
$printable = false,
$handheld = null,
array $extraQuery = [] )
static

Build a query array (array representation of query string) for load.php.

Helper function for createLoaderURL().

Parameters
string[]$modules
string$lang
string$skin
string | null$user
string | null$version
int$debug
string | null$only
bool$printable
bool | null$handheldUnused as of MW 1.38
array$extraQuery
Returns
array

Definition at line 1787 of file ResourceLoader.php.

◆ makeLoaderRegisterScript()

static MediaWiki\ResourceLoader\ResourceLoader::makeLoaderRegisterScript ( Context $context,
array $modules )
static

Format JS code which calls mw.loader.register() with the given parameters.

Example
ResourceLoader::makeLoaderRegisterScript( $context, [
[ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
[ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
...
] ):
Access: internal
For use by StartUpModule only
Parameters
Context$context
array[]$modulesArray of module registration arrays, each containing
  • string: module name
  • string: module version
  • array|null: List of dependencies (optional)
  • string|null: Module group (optional)
  • string|null: Name of foreign module source, or 'local' (optional)
  • string|null: Script body of a skip function (optional)
Returns
string JavaScript code

Definition at line 1493 of file ResourceLoader.php.

◆ makeLoaderSourcesScript()

static MediaWiki\ResourceLoader\ResourceLoader::makeLoaderSourcesScript ( Context $context,
array $sources )
static

Format JS code which calls mw.loader.addSource() with the given parameters.

  • ResourceLoader::makeLoaderSourcesScript( $context, [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] ); Register sources with the given IDs and properties.
Access: internal
For use by StartUpModule only
Parameters
Context$context
array<string,string>$sources
Returns
string JavaScript code

Definition at line 1535 of file ResourceLoader.php.

◆ makeLoaderStateScript()

static MediaWiki\ResourceLoader\ResourceLoader::makeLoaderStateScript ( Context $context,
array $states )
static

Returns a JS call to mw.loader.state, which sets the state of modules to a given value:

  • ResourceLoader::makeLoaderStateScript( $context, [ $name => $state, ... ] ): Set the state of modules with the given names to the given states
Access: internal
For use by StartUpModule
Parameters
Context$context
array<string,string>$states
Returns
string JavaScript code

Definition at line 1425 of file ResourceLoader.php.

◆ makeMessageSetScript()

static MediaWiki\ResourceLoader\ResourceLoader::makeMessageSetScript ( $messages)
static

Returns JS code which, when called, will register a given list of messages.

Parameters
mixed$messagesAssociative array mapping message key to value.
Returns
string JavaScript code

Definition at line 1344 of file ResourceLoader.php.

◆ makeModuleResponse()

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().

Parameters
Context$contextContext in which to generate a response
Module[]$modulesList of module objects keyed by module name
string[]$missingList of requested module names that are unregistered (optional)
Returns
string Response data

Definition at line 1091 of file ResourceLoader.php.

References $content, $debug, $modules, MediaWiki\ResourceLoader\Context\encodeJson(), MediaWiki\ResourceLoader\Context\getDebug(), MediaWiki\ResourceLoader\Context\getImageObj(), MediaWiki\ResourceLoader\Context\getOnly(), MediaWiki\ResourceLoader\Context\getRaw(), and MediaWiki\ResourceLoader\Context\shouldIncludeScripts().

◆ makePackedModulesString()

static MediaWiki\ResourceLoader\ResourceLoader::makePackedModulesString ( array $modules)
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.

Parameters
string[]$modulesList of module names (strings)
Returns
string Packed query string

Definition at line 1635 of file ResourceLoader.php.

◆ makeVersionQuery()

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.

Since
1.28
Parameters
Context$context
string[]$modules
Returns
string Hash

Definition at line 733 of file ResourceLoader.php.

References $modules.

◆ measureResponseTime()

MediaWiki\ResourceLoader\ResourceLoader::measureResponseTime ( )
protected

Send stats about the time used to build the response.

Returns
ScopedCallback

Definition at line 872 of file ResourceLoader.php.

References MediaWiki\MediaWikiServices\getInstance().

◆ outputErrorAndLog()

MediaWiki\ResourceLoader\ResourceLoader::outputErrorAndLog ( Exception $e,
$msg,
array $context = [] )

Add an error to the 'errors' array and log it.

Access: internal
For use by StartUpModule.
Since
1.29
Parameters
Exception$e
string$msg
array$context

Definition at line 678 of file ResourceLoader.php.

◆ preloadModuleInfo()

MediaWiki\ResourceLoader\ResourceLoader::preloadModuleInfo ( array $moduleNames,
Context $context )

Load information stored in the database and dependency tracking store about modules.

Parameters
string[]$moduleNames
Context$contextResourceLoader-specific context of the request

Definition at line 454 of file ResourceLoader.php.

References $blob, $dbr, $lang, DB_REPLICA, MediaWiki\ResourceLoader\Module\expandRelativePaths(), MediaWiki\ResourceLoader\Context\getLanguage(), MediaWiki\ResourceLoader\Module\getVary(), MediaWiki\ResourceLoader\WikiModule\preloadTitleInfo(), and wfGetDB().

◆ register()

MediaWiki\ResourceLoader\ResourceLoader::register ( $name,
array $info = null )

Register a module with the ResourceLoader system.

See also
$wgResourceModules for the available options.
Parameters
string | array[]$nameModule name as a string or, array of module info arrays keyed by name.
array | null$infoModule info array. When using the first parameter to register multiple modules at once, this parameter is optional.
Exceptions
InvalidArgumentExceptionIf a module name contains illegal characters (pipes or commas)
InvalidArgumentExceptionIf the module info is not an array

Definition at line 281 of file ResourceLoader.php.

◆ registerTestModules()

MediaWiki\ResourceLoader\ResourceLoader::registerTestModules ( )
Access: internal
For use by ServiceWiring only

Definition at line 314 of file ResourceLoader.php.

◆ respond()

MediaWiki\ResourceLoader\ResourceLoader::respond ( Context $context)

◆ saveModuleDependenciesInternal()

MediaWiki\ResourceLoader\ResourceLoader::saveModuleDependenciesInternal ( $moduleName,
$variant,
$paths,
$priorPaths )
Access: internal
Exposed for letting getModule() pass the callable to DependencyStore
Parameters
string$moduleName
string$variantLanguage/skin variant
string[]$pathsList of relative paths referenced during computation
string[]$priorPathsList of relative paths tracked in the dependency store

Definition at line 516 of file ResourceLoader.php.

References $cache, and ObjectCache\getLocalClusterInstance().

◆ sendResponseHeaders()

MediaWiki\ResourceLoader\ResourceLoader::sendResponseHeaders ( Context $context,
$etag,
$errors,
array $extra = [] )
protected

Send main response headers to the client.

Deals with Content-Type, CORS (for stylesheets), and caching.

Parameters
Context$context
string$etagETag header value
bool$errorsWhether there are errors in the response
string[]$extraArray of extra HTTP response headers

Definition at line 891 of file ResourceLoader.php.

◆ setDependencyStore()

MediaWiki\ResourceLoader\ResourceLoader::setDependencyStore ( DependencyStore $tracker)
Since
1.35
Parameters
DependencyStore$tracker

Definition at line 258 of file ResourceLoader.php.

References $tracker.

Referenced by MediaWiki\ResourceLoader\ResourceLoader\__construct().

◆ setLogger()

MediaWiki\ResourceLoader\ResourceLoader::setLogger ( LoggerInterface $logger)
Since
1.26
Parameters
LoggerInterface$logger

Definition at line 226 of file ResourceLoader.php.

◆ setMessageBlobStore()

MediaWiki\ResourceLoader\ResourceLoader::setMessageBlobStore ( MessageBlobStore $blobStore)
Since
1.25
Parameters
MessageBlobStore$blobStore

Definition at line 250 of file ResourceLoader.php.

Referenced by MediaWiki\ResourceLoader\ResourceLoader\__construct().

◆ setModuleSkinStyles()

MediaWiki\ResourceLoader\ResourceLoader::setModuleSkinStyles ( array $moduleSkinStyles)
Access: internal
For use by ServiceWiring.php
Parameters
array$moduleSkinStyles

Definition at line 266 of file ResourceLoader.php.

◆ tryRespondFromFileCache()

MediaWiki\ResourceLoader\ResourceLoader::tryRespondFromFileCache ( ResourceFileCache $fileCache,
Context $context,
$etag )
protected

Send out code for a response from file cache if possible.

Parameters
ResourceFileCache$fileCacheCache object for this request URL
Context$contextContext in which to generate a response
string$etagETag header value
Returns
bool If this found a cache file and handled the response

Definition at line 995 of file ResourceLoader.php.

References FileCacheBase\cacheTimestamp(), DB_REPLICA, FileCacheBase\fetchText(), MediaWiki\ResourceLoader\Context\getDebug(), MediaWiki\ResourceLoader\Context\getVersion(), FileCacheBase\isCacheGood(), and wfGetDB().

◆ tryRespondNotModified()

MediaWiki\ResourceLoader\ResourceLoader::tryRespondNotModified ( Context $context,
$etag )
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.

Parameters
Context$context
string$etagETag header value
Returns
bool True if HTTP 304 was sent and output handled

Definition at line 962 of file ResourceLoader.php.

References MediaWiki\ResourceLoader\Context\getDebug(), MediaWiki\ResourceLoader\Context\getRequest(), and wfResetOutputBuffers().

Member Data Documentation

◆ $debugMode

int null MediaWiki\ResourceLoader\ResourceLoader::$debugMode = null
staticprotected

Definition at line 114 of file ResourceLoader.php.

◆ $errors

array MediaWiki\ResourceLoader\ResourceLoader::$errors = []
protected

Errors accumulated during a respond() call.

Exposed for testing.

Definition at line 146 of file ResourceLoader.php.

◆ $extraHeaders

string [] MediaWiki\ResourceLoader\ResourceLoader::$extraHeaders = []
protected

Buffer for extra response headers during a makeModuleResponse() call.

Exposed for testing.

Definition at line 151 of file ResourceLoader.php.

◆ HASH_LENGTH

const MediaWiki\ResourceLoader\ResourceLoader::HASH_LENGTH = 5
Access: internal
For use by StartUpModule only.

Definition at line 594 of file ResourceLoader.php.


The documentation for this class was generated from the following file: