BlueSpice MediaWiki master
 All Classes Namespaces Files Functions Variables Groups Pages
ResourceLoader Class Reference
Inheritance diagram for ResourceLoader:
Collaboration diagram for ResourceLoader:

Public Member Functions

 preloadModuleInfo (array $moduleNames, ResourceLoaderContext $context)
 
 __construct (Config $config=null, LoggerInterface $logger=null)
 
 getConfig ()
 
 setLogger (LoggerInterface $logger)
 
 getLogger ()
 
 getMessageBlobStore ()
 
 setMessageBlobStore (MessageBlobStore $blobStore)
 
 register ($name, $info=null)
 
 registerTestModules ()
 
 addSource ($id, $loadUrl=null)
 
 getModuleNames ()
 
 getTestModuleNames ($framework= 'all')
 
 isModuleRegistered ($name)
 
 getSources ()
 
 getLoadScript ($source)
 
 getCombinedVersion (ResourceLoaderContext $context, array $moduleNames)
 
 makeVersionQuery (ResourceLoaderContext $context)
 
 respond (ResourceLoaderContext $context)
 
 makeModuleResponse (ResourceLoaderContext $context, array $modules, array $missing=[])
 
 getModulesByMessage ($messageKey)
 
 createLoaderURL ($source, ResourceLoaderContext $context, $extraQuery=[])
 
 getLessCompiler ($extraVars=[])
 
 getLessVars ()
 

Static Public Member Functions

static filter ($filter, $data, array $options=[])
 
static makeHash ($value)
 
static makeComment ($text)
 
static formatException ($e)
 
static makeMessageSetScript ($messages)
 
static makeCombinedStyles (array $stylePairs)
 
static makeLoaderStateScript ($name, $state=null)
 
static makeCustomLoaderScript ($name, $version, $dependencies, $group, $source, $script)
 
static makeLoaderRegisterScript ($name, $version=null, $dependencies=null, $group=null, $source=null, $skip=null)
 
static makeLoaderSourcesScript ($id, $loadUrl=null)
 
static makeLoaderConditionalScript ($script)
 
static makeInlineScript ($script)
 
static makeConfigSetScript (array $configuration)
 
static makePackedModulesString ($modules)
 
static inDebugMode ()
 
static clearCache ()
 
static makeLoaderQuery ($modules, $lang, $skin, $user=null, $version=null, $debug=false, $only=null, $printable=false, $handheld=false, $extraQuery=[])
 
static isValidModuleName ($moduleName)
 

Public Attributes

const FILTER_NOMIN = '/*@nomin*/'
 

Protected Member Functions

 isFileModule ($name)
 
 outputErrorAndLog (Exception $e, $msg, array $context=[])
 
 measureResponseTime (Timing $timing)
 
 sendResponseHeaders (ResourceLoaderContext $context, $etag, $errors, array $extra=[])
 
 tryRespondNotModified (ResourceLoaderContext $context, $etag)
 
 tryRespondFromFileCache (ResourceFileCache $fileCache, ResourceLoaderContext $context, $etag)
 

Static Protected Member Functions

static formatExceptionNoComment ($e)
 
static makeLoaderImplementScript ($name, $scripts, $styles, $messages, $templates)
 
static createLoaderQuery (ResourceLoaderContext $context, $extraQuery=[])
 

Protected Attributes

 $modules = []
 
 $moduleInfos = []
 
 $config
 
 $testModuleNames = []
 
 $sources = []
 
 $errors = []
 
 $extraHeaders = []
 
 $blobStore
 

Static Protected Attributes

static $filterCacheVersion = 7
 
static $debugMode = null
 

Detailed Description

Dynamic JavaScript and CSS resource loading system.

Most of the documentation is on the MediaWiki documentation wiki starting at: https://www.mediawiki.org/wiki/ResourceLoader

Constructor & Destructor Documentation

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

Register core modules and runs registration hooks.

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

Member Function Documentation

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$loadUrlload.php url (string), or array with loadUrl key for backwards-compatibility.
Exceptions
MWException
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).

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

Helper for createLoaderURL()

Since
1.24
See Also
makeLoaderQuery
Parameters
ResourceLoaderContext$context
array$extraQuery
Returns
array
ResourceLoader::createLoaderURL (   $source,
ResourceLoaderContext  $context,
  $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.
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:

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
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
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
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
ResourceLoader::getConfig ( )
Returns
Config
ResourceLoader::getLessCompiler (   $extraVars = [])

Returns LESS compiler set up for use with MediaWiki

Since
1.27
Parameters
array$extraVarsAssociative array of extra (i.e., other than the globally-configured ones) that should be used for compilation.
Exceptions
MWException
Returns
Less_Parser
ResourceLoader::getLessVars ( )

Get global LESS variables.

Since
1.27
Returns
array Map of variable names to string CSS values.
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
ResourceLoader::getLogger ( )
Since
1.27
Returns
LoggerInterface
ResourceLoader::getMessageBlobStore ( )
Since
1.26
Returns
MessageBlobStore
ResourceLoader::getModuleNames ( )

Get a list of module names.

Returns
array List of module names
ResourceLoader::getModulesByMessage (   $messageKey)

Get names of modules that use a certain message.

Parameters
string$messageKey
Returns
array List of module names
ResourceLoader::getSources ( )

Get the list of sources.

Returns
array Like [ id => load.php url, ... ]
ResourceLoader::getTestModuleNames (   $framework = 'all')

Get a list of test module names for one (or all) frameworks.

If the given framework id is unknkown, or if the in-object variable is not an array, then it will return an empty array.

Parameters
string$frameworkGet only the test module names for one particular framework (optional)
Returns
array
Todo:
api siteinfo prop testmodulenames modulenames
static ResourceLoader::inDebugMode ( )
static

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

Returns
bool
ResourceLoader::isFileModule (   $name)
protected

Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule or one of its subclasses.

Parameters
string$nameModule name
Returns
bool
ResourceLoader::isModuleRegistered (   $name)

Check whether a ResourceLoader module is registered

Since
1.25
Parameters
string$name
Returns
bool
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
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
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
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
static ResourceLoader::makeCustomLoaderScript (   $name,
  $version,
  $dependencies,
  $group,
  $source,
  $script 
)
static

Returns JS code which calls the script given by $script. The script will be called with local variables name, version, dependencies and group, which will have values corresponding to $name, $version, $dependencies and $group as supplied.

Parameters
string$nameModule name
string$versionModule version hash
array$dependenciesList of module names on which this module depends
string$groupGroup which the module is in.
string$sourceSource of the module, or 'local' if not foreign.
string$scriptJavaScript code
Returns
string JavaScript code
static ResourceLoader::makeHash (   $value)
static
Since
1.26
Parameters
string$value
Returns
string Hash
static ResourceLoader::makeInlineScript (   $script)
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
Returns
WrappedString HTML
static ResourceLoader::makeLoaderConditionalScript (   $script)
static

Wraps JavaScript code to run after startup and base modules.

Parameters
string$scriptJavaScript code
Returns
string JavaScript code
static ResourceLoader::makeLoaderImplementScript (   $name,
  $scripts,
  $styles,
  $messages,
  $templates 
)
staticprotected

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

Parameters
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, or a string of JavaScript for $.globalEval.
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
static ResourceLoader::makeLoaderQuery (   $modules,
  $lang,
  $skin,
  $user = null,
  $version = null,
  $debug = false,
  $only = null,
  $printable = false,
  $handheld = false,
  $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$user
string$version
bool$debug
string$only
bool$printable
bool$handheld
array$extraQuery
Returns
array
static ResourceLoader::makeLoaderRegisterScript (   $name,
  $version = null,
  $dependencies = null,
  $group = null,
  $source = null,
  $skip = null 
)
static

Returns JS code which calls mw.loader.register with the given parameters. Has three calling conventions:

Parameters
string$nameModule name
string$versionModule version hash
array$dependenciesList of module names on which this module depends
string$groupGroup which the module is in
string$sourceSource of the module, or 'local' if not foreign
string$skipScript body of the skip function
Returns
string JavaScript code
static ResourceLoader::makeLoaderSourcesScript (   $id,
  $loadUrl = null 
)
static

Returns JS code which calls mw.loader.addSource() with the given parameters. Has two calling conventions:

Parameters
string$idSource ID
string$loadUrlload.php url
Returns
string JavaScript code
static ResourceLoader::makeLoaderStateScript (   $name,
  $state = null 
)
static

Returns a JS call to mw.loader.state, which sets the state of a module or modules to a given value. Has two calling conventions:

Parameters
string$name
string$state
Returns
string JavaScript code
static ResourceLoader::makeMessageSetScript (   $messages)
static

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

Parameters
mixed$messagesEither an associative array mapping message key to value, or a JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
Returns
string JavaScript code
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
static ResourceLoader::makePackedModulesString (   $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 ResourceLoaderContext::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
ResourceLoader::makeVersionQuery ( ResourceLoaderContext  $context)

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
Returns
string Hash
ResourceLoader::outputErrorAndLog ( Exception  $e,
  $msg,
array  $context = [] 
)
protected

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

Should only be called from within respond().

Since
1.29
Parameters
Exception$e
string$msg
array$context
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
ResourceLoader::register (   $name,
  $info = null 
)

Register a module with the ResourceLoader system.

Parameters
mixed$nameName of module as a string or List of name/object pairs as an array
array$infoModule info array. For backwards compatibility with 1.17alpha, this may also be a ResourceLoaderModule object. Optional when using multiple-registration calling style.
Exceptions
MWExceptionIf a duplicate module registration is attempted
MWExceptionIf a module name contains illegal characters (pipes or commas)
MWExceptionIf something other than a ResourceLoaderModule is being registered
Returns
bool False if there were any errors, in which case one or more modules were not registered
ResourceLoader::respond ( ResourceLoaderContext  $context)

Output a response to a load request, including the content-type header.

Parameters
ResourceLoaderContext$contextContext in which a response should be formed
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
ResourceLoader::setLogger ( LoggerInterface  $logger)
Since
1.26
Parameters
LoggerInterface$logger

Implements Psr\Log\LoggerAwareInterface.

ResourceLoader::setMessageBlobStore ( MessageBlobStore  $blobStore)
Since
1.25
Parameters
MessageBlobStore$blobStore
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
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

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