MediaWiki  master
ResourceLoader Class Reference

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

Inheritance diagram for ResourceLoader:
Collaboration diagram for ResourceLoader:

Public Member Functions

 __construct (Config $config=null, LoggerInterface $logger=null)
 Register core modules and runs registration hooks. More...
 
 addSource ( $id, $loadUrl=null)
 Add a foreign source of modules. More...
 
 createLoaderURL ( $source, ResourceLoaderContext $context, array $extraQuery=[])
 Build a load.php URL. More...
 
 getCombinedVersion (ResourceLoaderContext $context, array $moduleNames)
 Helper method to get and combine versions of multiple modules. More...
 
 getConfig ()
 
 getLessCompiler ( $vars=[])
 Returns LESS compiler set up for use with MediaWiki. More...
 
 getLoadScript ( $source)
 Get the URL to the load.php endpoint for the given ResourceLoader source. More...
 
 getLogger ()
 
 getMessageBlobStore ()
 
 getModule ( $name)
 Get the ResourceLoaderModule object for a given module name. More...
 
 getModuleNames ()
 Get a list of module names. More...
 
 getModulesByMessage ( $messageKey)
 Get names of modules that use a certain message. More...
 
 getSources ()
 Get the list of sources. More...
 
 getTestSuiteModuleNames ()
 Get a list of module names with QUnit test suites. More...
 
 isModuleRegistered ( $name)
 Check whether a ResourceLoader module is registered. More...
 
 makeModuleResponse (ResourceLoaderContext $context, array $modules, array $missing=[])
 Generate code for a response. More...
 
 makeVersionQuery (ResourceLoaderContext $context, array $modules=null)
 Get the expected value of the 'version' query parameter. More...
 
 outputErrorAndLog (Exception $e, $msg, array $context=[])
 Add an error to the 'errors' array and log it. More...
 
 preloadModuleInfo (array $moduleNames, ResourceLoaderContext $context)
 Load information stored in the database about modules. More...
 
 register ( $name, $info=null)
 Register a module with the ResourceLoader system. More...
 
 registerTestModules ()
 
 respond (ResourceLoaderContext $context)
 Output a response to a load request, including the content-type header. More...
 
 setLogger (LoggerInterface $logger)
 
 setMessageBlobStore (MessageBlobStore $blobStore)
 

Static Public Member Functions

static clearCache ()
 Reset static members used for caching. More...
 
static encodeJsonForScript ( $data)
 Wrapper around json_encode that avoids needless escapes, and pretty-prints in debug mode. More...
 
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' ]`. More...
 
static filter ( $filter, $data, array $options=[])
 Run JavaScript or CSS data through a filter, caching the filtered result for future calls. More...
 
static formatException ( $e)
 Handle exception display. More...
 
static inDebugMode ()
 Determine whether debug mode was requested Order of priority is 1) request param, 2) cookie, 3) $wg setting. More...
 
static isValidModuleName ( $moduleName)
 Check a module name for validity. More...
 
static makeCombinedStyles (array $stylePairs)
 Combines an associative array mapping media type to CSS into a single stylesheet with "@media" blocks. More...
 
static makeComment ( $text)
 Generate a CSS or JS comment block. More...
 
static makeConfigSetScript (array $configuration)
 Returns JS code which will set the MediaWiki configuration array to the given value. More...
 
static makeHash ( $value)
 Create a hash for module versioning purposes. More...
 
static makeInlineCodeWithModule ( $modules, $script)
 Wraps JavaScript code to run after a required module. More...
 
static makeInlineScript ( $script, $nonce=null)
 Returns an HTML script tag that runs given JS code after startup and base modules. More...
 
static makeLoaderConditionalScript ( $script)
 Wraps JavaScript code to run after the startup module. More...
 
static makeLoaderQuery (array $modules, $lang, $skin, $user=null, $version=null, $debug=false, $only=null, $printable=false, $handheld=false, array $extraQuery=[])
 Build a query array (array representation of query string) for load.php. More...
 
static makeLoaderRegisterScript (ResourceLoaderContext $context, array $modules)
 Returns JS code which calls mw.loader.register with the given parameter. More...
 
static makeLoaderSourcesScript (ResourceLoaderContext $context, array $sources)
 Returns JS code which calls mw.loader.addSource() with the given parameters. More...
 
static makeLoaderStateScript (ResourceLoaderContext $context, array $states)
 Returns a JS call to mw.loader.state, which sets the state of modules to a given value: More...
 
static makeMessageSetScript ( $messages)
 Returns JS code which, when called, will register a given list of messages. More...
 
static makePackedModulesString (array $modules)
 Convert an array of module names to a packed query string. More...
 

Public Attributes

const HASH_LENGTH = 5
 

Protected Member Functions

 isFileModule ( $name)
 Whether the module is a ResourceLoaderFileModule (including subclasses). More...
 
 measureResponseTime (Timing $timing)
 
 sendResponseHeaders (ResourceLoaderContext $context, $etag, $errors, array $extra=[])
 Send main response headers to the client. More...
 
 tryRespondFromFileCache (ResourceFileCache $fileCache, ResourceLoaderContext $context, $etag)
 Send out code for a response from file cache if possible. More...
 
 tryRespondNotModified (ResourceLoaderContext $context, $etag)
 Respond with HTTP 304 Not Modified if appropiate. More...
 

Static Protected Member Functions

static createLoaderQuery (ResourceLoaderContext $context, array $extraQuery=[])
 Helper for createLoaderURL() More...
 
static formatExceptionNoComment ( $e)
 Handle exception display. More...
 

Protected Attributes

MessageBlobStore $blobStore
 
Config $config
 
array $errors = []
 Errors accumulated during current respond() call. More...
 
string [] $extraHeaders = []
 Extra HTTP response headers from modules loaded in makeModuleResponse() More...
 
array [] $moduleInfos = []
 Map of (module name => associative info array) More...
 
ResourceLoaderModule [] $modules = []
 Map of (module name => ResourceLoaderModule) More...
 
array $sources = []
 Map of (source => path); E.g. More...
 
array $testModuleNames = []
 Associative array mapping framework ids to a list of names of test suite modules like [ 'qunit' => [ 'mediawiki.tests.qunit.suites', 'ext.foo.tests', ... More...
 
string [] $testSuiteModuleNames = []
 List of module names that contain QUnit test suites. More...
 

Static Protected Attributes

static bool $debugMode = null
 

Private Member Functions

 ensureNewline ( $str)
 Ensure the string is either empty or ends in a line break. More...
 

Static Private Member Functions

static applyFilter ( $filter, $data)
 
static isEmptyObject (stdClass $obj)
 
static makeLoaderImplementScript (ResourceLoaderContext $context, $name, $scripts, $styles, $messages, $templates)
 Return JS code that calls mw.loader.implement with given module properties. More...
 
static trimArray (array &$array)
 Remove empty values from the end of an array. More...
 

Private Attributes

LoggerInterface $logger
 

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 44 of file ResourceLoader.php.

Constructor & Destructor Documentation

◆ __construct()

ResourceLoader::__construct ( Config  $config = null,
LoggerInterface  $logger = null 
)

Register core modules and runs registration hooks.

Parameters
Config | null$config
LoggerInterface | null$logger[optional]

Definition at line 221 of file ResourceLoader.php.

References $config, addSource(), Config\get(), setMessageBlobStore(), and wfDeprecated().

Member Function Documentation

◆ addSource()

ResourceLoader::addSource (   $id,
  $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$idSource ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
string | array | null$loadUrlload.php url (string), or array with loadUrl key for backwards-compatibility.
Exceptions
MWException

Definition at line 412 of file ResourceLoader.php.

Referenced by __construct().

◆ applyFilter()

static ResourceLoader::applyFilter (   $filter,
  $data 
)
staticprivate

◆ clearCache()

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

Definition at line 1668 of file ResourceLoader.php.

Referenced by isEmptyObject().

◆ createLoaderQuery()

static ResourceLoader::createLoaderQuery ( ResourceLoaderContext  $context,
array  $extraQuery = [] 
)
staticprotected

Helper for createLoaderURL()

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

Definition at line 1699 of file ResourceLoader.php.

Referenced by isEmptyObject().

◆ createLoaderURL()

ResourceLoader::createLoaderURL (   $source,
ResourceLoaderContext  $context,
array  $extraQuery = [] 
)

Build a load.php URL.

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

Definition at line 1681 of file ResourceLoader.php.

Referenced by isEmptyObject().

◆ encodeJsonForScript()

static ResourceLoader::encodeJsonForScript (   $data)
static

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

Definition at line 1343 of file ResourceLoader.php.

Referenced by makeModuleResponse().

◆ ensureNewline()

ResourceLoader::ensureNewline (   $str)
private

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

Parameters
string$str
Returns
string

Definition at line 1195 of file ResourceLoader.php.

Referenced by makeModuleResponse().

◆ expandModuleNames()

static 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
array Array of module names

Definition at line 1616 of file ResourceLoader.php.

Referenced by ResourceLoaderContext\__construct(), and isEmptyObject().

◆ filter()

static 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:

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$optionsKeys:
  • (bool) cache: Whether to allow caching this data. Default: true.
Returns
string Filtered data, or a comment containing an error message

Definition at line 166 of file ResourceLoader.php.

References $cache, $filter, CACHE_ANYTHING, and ObjectCache\getLocalServerInstance().

Referenced by ResourceLoaderModule\buildContent(), ResourceLoaderClientHtml\getHeadHtml(), and ResourceLoaderStartUpModule\getModuleRegistrations().

◆ formatException()

static ResourceLoader::formatException (   $e)
static

Handle exception display.

Parameters
Exception$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 1015 of file ResourceLoader.php.

◆ formatExceptionNoComment()

static ResourceLoader::formatExceptionNoComment (   $e)
staticprotected

Handle exception display.

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

Definition at line 1026 of file ResourceLoader.php.

References $wgShowExceptionDetails, MWExceptionHandler\getLogMessage(), MWExceptionHandler\getPublicLogMessage(), and MWExceptionHandler\getRedactedTraceAsString().

◆ getCombinedVersion()

ResourceLoader::getCombinedVersion ( ResourceLoaderContext  $context,
array  $moduleNames 
)

Helper method to get and combine versions of multiple modules.

Since
1.26
Parameters
ResourceLoaderContext$context
string[]$moduleNames List of known module names
Returns
string Hash

Definition at line 659 of file ResourceLoader.php.

References $hashes, getModule(), and outputErrorAndLog().

Referenced by makeVersionQuery(), and respond().

◆ getConfig()

ResourceLoader::getConfig ( )
Returns
Config

Definition at line 242 of file ResourceLoader.php.

References $config.

Referenced by getModule().

◆ getLessCompiler()

ResourceLoader::getLessCompiler (   $vars = [])

Returns LESS compiler 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).
Exceptions
MWException
Returns
Less_Parser

Definition at line 1797 of file ResourceLoader.php.

Referenced by isEmptyObject().

◆ getLoadScript()

ResourceLoader::getLoadScript (   $source)

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

Since
1.24
Parameters
string$source
Exceptions
MWExceptionOn an invalid $source name
Returns
string

Definition at line 548 of file ResourceLoader.php.

References $source.

Referenced by isEmptyObject().

◆ getLogger()

ResourceLoader::getLogger ( )
Since
1.27
Returns
LoggerInterface

Definition at line 258 of file ResourceLoader.php.

References $logger.

Referenced by ResourceLoaderContext\__construct().

◆ getMessageBlobStore()

ResourceLoader::getMessageBlobStore ( )
Since
1.26
Returns
MessageBlobStore

Definition at line 266 of file ResourceLoader.php.

References $blobStore.

Referenced by preloadModuleInfo().

◆ getModule()

ResourceLoader::getModule (   $name)

Get the ResourceLoaderModule object for a given module name.

If an array of module parameters exists but a ResourceLoaderModule 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
ResourceLoaderModule|null If module has been registered, return a ResourceLoaderModule instance. Otherwise, return null.

Definition at line 485 of file ResourceLoader.php.

References getConfig().

Referenced by getCombinedVersion(), ResourceLoaderClientHtml\getData(), makeModuleResponse(), makeVersionQuery(), preloadModuleInfo(), and respond().

◆ getModuleNames()

ResourceLoader::getModuleNames ( )

Get a list of module names.

Returns
array List of module names

Definition at line 448 of file ResourceLoader.php.

Referenced by makeModuleResponse().

◆ getModulesByMessage()

ResourceLoader::getModulesByMessage (   $messageKey)

Get names of modules that use a certain message.

Parameters
string$messageKey
Returns
array List of module names

Definition at line 1209 of file ResourceLoader.php.

Referenced by makeModuleResponse().

◆ getSources()

ResourceLoader::getSources ( )

Get the list of sources.

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

Definition at line 535 of file ResourceLoader.php.

References $sources.

◆ getTestSuiteModuleNames()

ResourceLoader::getTestSuiteModuleNames ( )

Get a list of module names with QUnit test suites.

Definition at line 459 of file ResourceLoader.php.

References $testSuiteModuleNames.

◆ inDebugMode()

static ResourceLoader::inDebugMode ( )
static

Determine whether debug mode was requested Order of priority is 1) request param, 2) cookie, 3) $wg setting.

Returns
bool

Definition at line 1648 of file ResourceLoader.php.

Referenced by SpecialJavaScriptTest\exportQUnit(), OutputPage\getRlClientContext(), isEmptyObject(), and SpecialJavaScriptTest\plainQUnit().

◆ isEmptyObject()

◆ isFileModule()

ResourceLoader::isFileModule (   $name)
protected

Whether the module is a ResourceLoaderFileModule (including subclasses).

Parameters
string$nameModule name
Returns
bool

Definition at line 516 of file ResourceLoader.php.

Referenced by register().

◆ isModuleRegistered()

ResourceLoader::isModuleRegistered (   $name)

Check whether a ResourceLoader module is registered.

Since
1.25
Parameters
string$name
Returns
bool

Definition at line 470 of file ResourceLoader.php.

◆ isValidModuleName()

static 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 1783 of file ResourceLoader.php.

Referenced by isEmptyObject().

◆ makeCombinedStyles()

static ResourceLoader::makeCombinedStyles ( array  $stylePairs)
static

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

Parameters
array$stylePairsArray keyed by media type containing (arrays of) CSS strings
Returns
array

Definition at line 1307 of file ResourceLoader.php.

Referenced by ResourceLoaderModule\buildContent(), WebInstallerOutput\getCSS(), and makeModuleResponse().

◆ makeComment()

static 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 1004 of file ResourceLoader.php.

Referenced by ResourceLoaderWikiModule\getScript(), and ResourceLoaderWikiModule\getStyles().

◆ makeConfigSetScript()

static ResourceLoader::makeConfigSetScript ( array  $configuration)
static

Returns 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 1562 of file ResourceLoader.php.

Referenced by SpecialJavaScriptTest\exportQUnit(), OutputPage\getBottomScripts(), MWDebug\getDebugHTML(), isEmptyObject(), and Skin\makeVariablesScript().

◆ makeHash()

static 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 622 of file ResourceLoader.php.

Referenced by ResourceLoaderStartUpModule\getModuleRegistrations(), and ResourceLoaderModule\getVersionHash().

◆ makeInlineCodeWithModule()

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

Wraps JavaScript code to run after a required module.

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

Definition at line 1516 of file ResourceLoader.php.

Referenced by SpecialJavaScriptTest\exportQUnit(), and isEmptyObject().

◆ makeInlineScript()

static ResourceLoader::makeInlineScript (   $script,
  $nonce = null 
)
static

Returns an HTML script tag 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$nonce[optional] Content-Security-Policy nonce (from OutputPage::getCSPNonce)
Returns
string|WrappedString HTML

Definition at line 1535 of file ResourceLoader.php.

Referenced by ResourceLoaderClientHtml\getBodyHtml(), OutputPage\getBottomScripts(), MWDebug\getDebugHTML(), isEmptyObject(), ResourceLoaderClientHtml\makeLoad(), and Skin\makeVariablesScript().

◆ makeLoaderConditionalScript()

static ResourceLoader::makeLoaderConditionalScript (   $script)
static

Wraps JavaScript code to run after the startup module.

Parameters
string$scriptJavaScript code
Returns
string JavaScript code

Definition at line 1502 of file ResourceLoader.php.

Referenced by SpecialJavaScriptTest\exportQUnit(), and isEmptyObject().

◆ makeLoaderImplementScript()

static ResourceLoader::makeLoaderImplementScript ( ResourceLoaderContext  $context,
  $name,
  $scripts,
  $styles,
  $messages,
  $templates 
)
staticprivate

Return JS code that calls mw.loader.implement with given module properties.

Parameters
ResourceLoaderContext$context
string$nameModule name or implement key (format "`[name]@[version]`")
XmlJsCode | array | string$scriptsCode as XmlJsCode (to be wrapped in a closure), list of URLs to JavaScript files, string of JavaScript for $.globalEval, or array with 'files' and 'main' properties (see ResourceLoaderModule::getScript())
mixed$stylesArray of CSS strings keyed by media type, or an array of lists of URLs to CSS files keyed by media type
mixed$messagesList of messages associated with this module. May either be an associative array mapping message key to value, or a JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
array$templatesKeys are name of templates and values are the source of the template.
Exceptions
MWException
Returns
string JavaScript code

Definition at line 1238 of file ResourceLoader.php.

Referenced by makeModuleResponse().

◆ makeLoaderQuery()

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

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

Helper function for createLoaderURL().

Parameters
array$modules
string$lang
string$skin
string | null$user
string | null$version
bool$debug
string | null$only
bool$printable
bool$handheld
array$extraQuery
Returns
array

Definition at line 1732 of file ResourceLoader.php.

Referenced by OutputPage\getRlClientContext(), and isEmptyObject().

◆ makeLoaderRegisterScript()

static ResourceLoader::makeLoaderRegisterScript ( ResourceLoaderContext  $context,
array  $modules 
)
static

Returns JS code which calls mw.loader.register with the given parameter.

Example
[ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
[ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
...
] ):

Definition at line 1445 of file ResourceLoader.php.

Referenced by ResourceLoaderStartUpModule\getModuleRegistrations(), and isEmptyObject().

◆ makeLoaderSourcesScript()

static ResourceLoader::makeLoaderSourcesScript ( ResourceLoaderContext  $context,
array  $sources 
)
static

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

Definition at line 1488 of file ResourceLoader.php.

Referenced by ResourceLoaderStartUpModule\getModuleRegistrations(), and isEmptyObject().

◆ makeLoaderStateScript()

static ResourceLoader::makeLoaderStateScript ( ResourceLoaderContext  $context,
array  $states 
)
static

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

Definition at line 1375 of file ResourceLoader.php.

Referenced by ResourceLoaderStartUpModule\getModuleRegistrations(), and makeModuleResponse().

◆ makeMessageSetScript()

static 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 1294 of file ResourceLoader.php.

Referenced by makeModuleResponse().

◆ makeModuleResponse()

ResourceLoader::makeModuleResponse ( ResourceLoaderContext  $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
ResourceLoaderContext$contextContext in which to generate a response
ResourceLoaderModule[]$modules List of module objects keyed by module name
string[]$missing List of requested module names that are unregistered (optional)
Returns
string Response data

Definition at line 1049 of file ResourceLoader.php.

References $content, $context, $file, $filter, $path, Xml\encodeJsCall(), ResourceLoaderContext\encodeJson(), encodeJsonForScript(), XmlJsCode\encodeObject(), ensureNewline(), ResourceLoaderContext\getDebug(), ResourceLoaderContext\getImageObj(), getModule(), getModuleNames(), getModulesByMessage(), ResourceLoaderContext\getOnly(), ResourceLoaderContext\getRaw(), makeCombinedStyles(), makeLoaderImplementScript(), makeLoaderStateScript(), makeMessageSetScript(), outputErrorAndLog(), ResourceLoaderContext\shouldIncludeScripts(), and OutputPage\transformCssMedia().

Referenced by respond().

◆ makePackedModulesString()

static 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
array$modulesList of module names (strings)
Returns
string Packed query string

Definition at line 1588 of file ResourceLoader.php.

Referenced by isEmptyObject().

◆ makeVersionQuery()

ResourceLoader::makeVersionQuery ( ResourceLoaderContext  $context,
array  $modules = null 
)

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
ResourceLoaderContext$context
string[]|null$modules
Returns
string Hash

Definition at line 695 of file ResourceLoader.php.

References getCombinedVersion(), getModule(), ResourceLoaderContext\getModules(), and wfDeprecated().

Referenced by sendResponseHeaders().

◆ measureResponseTime()

ResourceLoader::measureResponseTime ( Timing  $timing)
protected

Definition at line 839 of file ResourceLoader.php.

References DeferredUpdates\addCallableUpdate(), and Timing\measure().

Referenced by respond().

◆ outputErrorAndLog()

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

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

Access:
private For internal use by ResourceLoader and ResourceLoaderStartUpModule.
Since
1.29
Parameters
Exception$e
string$msg
array$context

Definition at line 642 of file ResourceLoader.php.

References $context, and MWExceptionHandler\logException().

Referenced by getCombinedVersion(), makeModuleResponse(), and respond().

◆ preloadModuleInfo()

ResourceLoader::preloadModuleInfo ( array  $moduleNames,
ResourceLoaderContext  $context 
)

Load information stored in the database about modules.

This method grabs modules dependencies from the database and updates modules objects.

This is not inside the module code because it is much faster to request all of the information at once than it is to have each module requests its own information. This sacrifice of modularity yields a substantial performance improvement.

Parameters
array$moduleNamesList of module names to preload information for
ResourceLoaderContext$contextContext to load the information within

Definition at line 96 of file ResourceLoader.php.

References $blob, $dbr, $lang, $res, DB_REPLICA, ResourceLoaderModule\expandRelativePaths(), ResourceLoaderContext\getLanguage(), getMessageBlobStore(), getModule(), ResourceLoaderModule\getVary(), ResourceLoaderWikiModule\preloadTitleInfo(), ResourceLoaderModule\setMessageBlob(), and wfGetDB().

Referenced by respond().

◆ register()

ResourceLoader::register (   $name,
  $info = null 
)

Register a module with the ResourceLoader system.

Parameters
string|array[]$name Module 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
MWExceptionIf a duplicate module registration is attempted
MWExceptionIf a module name contains illegal characters (pipes or commas)
InvalidArgumentExceptionIf the module info is not an array

Definition at line 289 of file ResourceLoader.php.

References $path, ResourceLoaderFileModule\extractBasePaths(), and isFileModule().

◆ registerTestModules()

ResourceLoader::registerTestModules ( )

◆ respond()

◆ sendResponseHeaders()

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

Send main response headers to the client.

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

Parameters
ResourceLoaderContext$context
string$etagETag header value
bool$errorsWhether there are errors in the response
string[]$extra Array of extra HTTP response headers
Returns
void

Definition at line 860 of file ResourceLoader.php.

References $header, ResourceLoaderContext\getDebug(), ResourceLoaderContext\getImageObj(), ResourceLoaderContext\getModules(), ResourceLoaderContext\getOnly(), ResourceLoaderContext\getVersion(), makeVersionQuery(), MediaWiki\HeaderCallback\warnIfHeadersSent(), and wfTimestamp().

Referenced by respond(), tryRespondFromFileCache(), and tryRespondNotModified().

◆ setLogger()

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

Definition at line 250 of file ResourceLoader.php.

References $logger.

◆ setMessageBlobStore()

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

Definition at line 274 of file ResourceLoader.php.

References $blobStore.

Referenced by __construct().

◆ trimArray()

static ResourceLoader::trimArray ( array &  $array)
staticprivate

Remove empty values from the end of an array.

Values considered empty:

  • null
  • []
  • new XmlJsCode( '{}' )
  • new stdClass() // (object) []
Parameters
array$array

Definition at line 1402 of file ResourceLoader.php.

Referenced by isEmptyObject().

◆ tryRespondFromFileCache()

ResourceLoader::tryRespondFromFileCache ( ResourceFileCache  $fileCache,
ResourceLoaderContext  $context,
  $etag 
)
protected

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

Parameters
ResourceFileCache$fileCacheCache object for this request URL
ResourceLoaderContext$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 951 of file ResourceLoader.php.

References $response, FileCacheBase\cacheTimestamp(), DB_REPLICA, FileCacheBase\fetchText(), ResourceLoaderContext\getDebug(), ResourceLoaderContext\getVersion(), FileCacheBase\isCacheGood(), sendResponseHeaders(), wfGetDB(), and wfTimestamp().

Referenced by respond().

◆ tryRespondNotModified()

ResourceLoader::tryRespondNotModified ( ResourceLoaderContext  $context,
  $etag 
)
protected

Respond with HTTP 304 Not Modified if appropiate.

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
ResourceLoaderContext$context
string$etagETag header value
Returns
bool True if HTTP 304 was sent and output handled

Definition at line 918 of file ResourceLoader.php.

References ResourceLoaderContext\getDebug(), WebRequest\GETHEADER_LIST, ResourceLoaderContext\getRequest(), HttpStatus\header(), sendResponseHeaders(), and wfResetOutputBuffers().

Referenced by respond().

Member Data Documentation

◆ $blobStore

MessageBlobStore ResourceLoader::$blobStore
protected

Definition at line 48 of file ResourceLoader.php.

Referenced by getMessageBlobStore(), and setMessageBlobStore().

◆ $config

Config ResourceLoader::$config
protected

Definition at line 46 of file ResourceLoader.php.

Referenced by __construct(), and getConfig().

◆ $debugMode

bool ResourceLoader::$debugMode = null
staticprotected

Definition at line 74 of file ResourceLoader.php.

◆ $errors

array ResourceLoader::$errors = []
protected

Errors accumulated during current respond() call.

Definition at line 69 of file ResourceLoader.php.

Referenced by respond().

◆ $extraHeaders

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

Extra HTTP response headers from modules loaded in makeModuleResponse()

Definition at line 71 of file ResourceLoader.php.

◆ $logger

LoggerInterface ResourceLoader::$logger
private

Definition at line 51 of file ResourceLoader.php.

Referenced by getLogger(), and setLogger().

◆ $moduleInfos

array [] ResourceLoader::$moduleInfos = []
protected

Map of (module name => associative info array)

Definition at line 56 of file ResourceLoader.php.

◆ $modules

ResourceLoaderModule [] ResourceLoader::$modules = []
protected

Map of (module name => ResourceLoaderModule)

Definition at line 54 of file ResourceLoader.php.

◆ $sources

array ResourceLoader::$sources = []
protected

Map of (source => path); E.g.

[ 'source-id' => 'http://.../load.php' ]

Definition at line 67 of file ResourceLoader.php.

Referenced by getSources().

◆ $testModuleNames

array ResourceLoader::$testModuleNames = []
protected

Associative array mapping framework ids to a list of names of test suite modules like [ 'qunit' => [ 'mediawiki.tests.qunit.suites', 'ext.foo.tests', ...

], ... ]

Definition at line 62 of file ResourceLoader.php.

◆ $testSuiteModuleNames

string [] ResourceLoader::$testSuiteModuleNames = []
protected

List of module names that contain QUnit test suites.

Definition at line 64 of file ResourceLoader.php.

Referenced by getTestSuiteModuleNames(), and registerTestModules().

◆ HASH_LENGTH

const ResourceLoader::HASH_LENGTH = 5

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