Go to the documentation of this file.
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\LoggerInterface;
28 use Psr\Log\NullLogger;
29 use Wikimedia\RelPath;
30 use Wikimedia\ScopedCallback;
47 # sitewide core module like a skin file or jQuery component
50 # per-user module generated by the software
53 # sitewide module generated from user-editable files, like MediaWiki:Common.js, or
54 # modules accessible to multiple users, such as those generated by the Gadgets extension.
57 # per-user module generated from user-editable files, like User:Me/vector.js
60 # an access constant; make sure this is kept as the largest number in this group
63 # script and style modules form a hierarchy of trustworthiness, with core modules like
64 # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
65 # limit the types of scripts and styles we allow to load on, say, sensitive special
66 # pages like Special:UserLogin and Special:Preferences
132 return MediaWikiServices::getInstance()->getContentLanguage()->getDir() !==
143 if ( $deprecationInfo ) {
145 $warning =
'This page is using the deprecated ResourceLoader module "' .
$name .
'".';
146 if ( is_string( $deprecationInfo ) ) {
147 $warning .=
"\n" . $deprecationInfo;
197 if ( $this->config ===
null ) {
199 $this->config = MediaWikiServices::getInstance()->getMainConfig();
227 if ( !$this->logger ) {
228 $this->logger =
new NullLogger();
250 $derivative->setModules( [ $this->
getName() ] );
251 $derivative->setOnly(
'scripts' );
252 $derivative->setDebug(
true );
297 $derivative->setModules( [ $this->
getName() ] );
298 $derivative->setOnly(
'styles' );
299 $derivative->setDebug(
true );
306 return [
'all' => [ $url ] ];
418 if ( !isset( $this->fileDeps[$vary] ) ) {
420 $deps =
$dbr->selectField(
'module_deps',
423 'md_module' => $this->
getName(),
429 if ( !is_null( $deps ) ) {
431 (
array)json_decode( $deps,
true )
434 $this->fileDeps[$vary] = [];
437 return $this->fileDeps[$vary];
451 $this->fileDeps[$vary] = $files;
476 $localFileRefs = array_values( array_unique( $localFileRefs ) );
477 sort( $localFileRefs );
481 if ( $localPaths === $storedPaths ) {
489 $key =
$cache->makeKey( __METHOD__, $this->
getName(), $vary );
490 $scopeLock =
$cache->getScopedLock( $key, 0 );
499 $deps = json_encode( $localPaths, JSON_UNESCAPED_SLASHES );
501 $dbw->upsert(
'module_deps',
503 'md_module' => $this->
getName(),
507 [ [
'md_module',
'md_skin' ] ],
513 if ( $dbw->trxLevel() ) {
514 $dbw->onTransactionResolution(
515 function ()
use ( &$scopeLock ) {
516 ScopedCallback::consume( $scopeLock );
521 }
catch ( Exception
$e ) {
524 wfDebugLog(
'resourceloader', __METHOD__ .
": failed to update DB: $e" );
541 return RelPath::getRelativePath(
$path,
$IP );
555 return RelPath::joinPath(
$IP,
$path );
573 if ( !isset( $this->msgBlobs[
$lang] ) ) {
574 $this->
getLogger()->warning(
'Message blob for {module} should have been preloaded', [
577 $store =
$context->getResourceLoader()->getMessageBlobStore();
578 $this->msgBlobs[
$lang] = $store->getBlob( $this,
$lang );
580 return $this->msgBlobs[
$lang];
613 $formattedLinks = [];
615 $link =
"<{$url}>;rel=preload";
617 $link .=
";{$key}={$val}";
619 $formattedLinks[] =
$link;
621 if ( $formattedLinks ) {
622 $headers[] =
'Link: ' . implode(
',', $formattedLinks );
693 if ( !array_key_exists( $contextHash, $this->
contents ) ) {
696 return $this->
contents[$contextHash];
707 $rl =
$context->getResourceLoader();
708 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
709 $statStart = microtime(
true );
735 if ( is_string( $scripts )
736 && strlen( $scripts )
737 && substr( $scripts, -1 ) !==
"\n"
747 $stylePairs = $this->
getStyles( $context );
748 if (
count( $stylePairs ) ) {
759 foreach ( $stylePairs
as $media => $style ) {
761 if ( is_array( $style ) ) {
762 $stylePairs[$media] = [];
763 foreach ( $style
as $cssText ) {
764 if ( is_string( $cssText ) ) {
765 $stylePairs[$media][] =
766 ResourceLoader::filter(
'minify-css', $cssText );
769 } elseif ( is_string( $style ) ) {
770 $stylePairs[$media] = ResourceLoader::filter(
'minify-css', $style );
776 'css' => $rl->makeCombinedStyles( $stylePairs )
798 $statTiming = microtime(
true ) - $statStart;
799 $statName = strtr( $this->
getName(),
'.',
'_' );
800 $stats->timing(
"resourceloader_build.all", 1000 * $statTiming );
801 $stats->timing(
"resourceloader_build.$statName", 1000 * $statTiming );
827 if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
834 if ( !isset( $summary[
'_class'] ) ) {
835 throw new LogicException(
'getDefinitionSummary must call parent method' );
837 $str = json_encode( $summary );
840 $this->versionHash[$contextHash] = ResourceLoader::makeHash( $str );
842 return $this->versionHash[$contextHash];
906 '_cacheVersion' => ResourceLoader::CACHE_VERSION,
934 return $this->
getGroup() ===
'private';
950 if ( !$this->
getConfig()->
get(
'ResourceLoaderValidateJS' ) ) {
953 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
954 return $cache->getWithSetCallback(
958 self::$parseCacheVersion,
967 Wikimedia\suppressWarnings();
969 }
catch ( Exception
$e ) {
972 Wikimedia\restoreWarnings();
979 return 'mw.log.error(' .
992 if ( !self::$jsParser ) {
1006 Wikimedia\suppressWarnings();
1007 $mtime = filemtime( $filePath ) ?: 1;
1008 Wikimedia\restoreWarnings();
Object passed around to modules which contains information about the state of a specific loader reque...
supportsURLLoading()
Whether this module supports URL loading.
getStyleURLsForDebug(ResourceLoaderContext $context)
Get the URL or URLs to load for this module's CSS in debug mode.
setMessageBlob( $blob, $lang)
Set in-object cache for message blobs.
setFileDependencies(ResourceLoaderContext $context, $files)
Set in-object cache for file dependencies.
static getLocalClusterInstance()
Get the main cluster-local cache object.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
if(!isset( $args[0])) $lang
const ORIGIN_CORE_SITEWIDE
const ORIGIN_USER_SITEWIDE
isRaw()
Whether this module's JS expects to work without the client-side ResourceLoader module.
static safeFilemtime( $filePath)
Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
setName( $name)
Set this module's name.
setLogger(LoggerInterface $logger)
saveFileDependencies(ResourceLoaderContext $context, $localFileRefs)
Set the files this module depends on indirectly for a given skin.
getHeaders(ResourceLoaderContext $context)
Get headers to send as part of a module web response.
getType()
Get the module's load type.
getTargets()
Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile'].
shouldEmbedModule(ResourceLoaderContext $context)
Check whether this module should be embeded rather than linked.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext such as when responding to a resource loader request or generating HTML output & $resourceLoader
getStyles(ResourceLoaderContext $context)
Get all CSS for this module for a given skin.
getTemplates()
Takes named templates by the module and returns an array mapping.
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
buildContent(ResourceLoaderContext $context)
Bundle all resources attached to this module into an array.
static getFileContentsHash( $filePaths, $algo='md4')
Get a hash of the combined contents of one or more files, either by retrieving a previously-computed ...
getLessVars(ResourceLoaderContext $context)
Get module-specific LESS variables, if any.
enableModuleContentVersion()
Whether to generate version hash based on module content.
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
and how to run hooks for an and one after Each event has a name
Interface for configuration instances.
getGroup()
Get the group this module is in.
static JSParser $jsParser
Lazy-initialized; use self::javaScriptParser()
getScript(ResourceLoaderContext $context)
Get all JS for this module for a given language and skin.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Some information about database access in MediaWiki By Tim January Database layout For information about the MediaWiki database such as a description of the tables and their contents
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
static expandRelativePaths(array $filePaths)
Expand directories relative to $IP.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
getOrigin()
Get this module's origin.
getMessageBlob(ResourceLoaderContext $context)
Get the hash of the message blob.
static $parseCacheVersion
isKnownEmpty(ResourceLoaderContext $context)
Check whether this module is known to be empty.
getDeprecationInformation()
Get JS representing deprecation information for the current module if available.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
static safeFileHash( $filePath)
Compute a non-cryptographic string hash of a file's contents.
const ORIGIN_USER_INDIVIDUAL
getDependencies(ResourceLoaderContext $context=null)
Get a list of modules this module depends on.
getPreloadLinks(ResourceLoaderContext $context)
Get a list of resources that web browsers may preload.
Allows changing specific properties of a context object, without changing the main one.
getMessages()
Get the messages needed for this module.
validateScriptFile( $fileName, $contents)
Validate a given script file; if valid returns the original source.
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
const ORIGIN_CORE_INDIVIDUAL
getModuleContent(ResourceLoaderContext $context)
Get an array of this module's resources.
getSkipFunction()
Get the skip function.
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
setConfig(Config $config)
getScriptURLsForDebug(ResourceLoaderContext $context)
Get the URL or URLs to load for this module's JS in debug mode.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
static getRelativePaths(array $filePaths)
Make file paths relative to MediaWiki directory.
usually copyright or history_copyright This message must be in HTML not wikitext & $link
getFileDependencies(ResourceLoaderContext $context)
Get the files this module depends on indirectly for a given skin.
getVersionHash(ResourceLoaderContext $context)
Get a string identifying the current version of this module in a given context.
getSource()
Get the source of this module.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
static javaScriptParser()
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
getName()
Get this module's name.