26use Psr\Log\LoggerAwareInterface;
27use Psr\Log\LoggerInterface;
28use Psr\Log\NullLogger;
29use Wikimedia\ScopedCallback;
46 # sitewide core module like a skin file or jQuery component
49 # per-user module generated by the software
52 # sitewide module generated from user-editable files, like MediaWiki:Common.js, or
53 # modules accessible to multiple users, such as those generated by the Gadgets extension.
56 # per-user module generated from user-editable files, like User:Me/vector.js
59 # an access constant; make sure this is kept as the largest number in this group
62 # script and style modules form a hierarchy of trustworthiness, with core modules like
63 # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
64 # limit the types of scripts and styles we allow to load on, say, sensitive special
65 # pages like Special:UserLogin and Special:Preferences
70 protected $name =
null;
147 if ( $deprecationInfo ) {
149 $warning =
'This page is using the deprecated ResourceLoader module "' . $name .
'".';
150 if ( is_string( $deprecationInfo ) ) {
151 $warning .=
"\n" . $deprecationInfo;
153 return Xml::encodeJsCall(
189 if ( $this->config ===
null ) {
191 $this->config = MediaWikiServices::getInstance()->getMainConfig();
219 if ( !$this->logger ) {
220 $this->logger =
new NullLogger();
242 $derivative->setModules( [ $this->
getName() ] );
243 $derivative->setOnly(
'scripts' );
244 $derivative->setDebug(
true );
289 $derivative->setModules( [ $this->
getName() ] );
290 $derivative->setOnly(
'styles' );
291 $derivative->setDebug(
true );
298 return [
'all' => [ $url ] ];
420 if ( !isset( $this->fileDeps[$vary] ) ) {
422 $deps =
$dbr->selectField(
'module_deps',
425 'md_module' => $this->
getName(),
431 if ( !is_null( $deps ) ) {
433 (array)FormatJson::decode( $deps,
true )
436 $this->fileDeps[$vary] = [];
439 return $this->fileDeps[$vary];
453 $this->fileDeps[$vary] = $files;
478 $localFileRefs = array_values( array_unique( $localFileRefs ) );
479 sort( $localFileRefs );
484 if ( $localPaths !== $storedPaths ) {
486 $cache = ObjectCache::getLocalClusterInstance();
487 $key =
$cache->makeKey( __METHOD__, $this->
getName(), $vary );
488 $scopeLock =
$cache->getScopedLock( $key, 0 );
493 $deps = FormatJson::encode( $localPaths );
495 $dbw->upsert(
'module_deps',
497 'md_module' => $this->
getName(),
501 [ [
'md_module',
'md_skin' ] ],
507 if ( $dbw->trxLevel() ) {
508 $dbw->onTransactionResolution(
509 function () use ( &$scopeLock ) {
510 ScopedCallback::consume( $scopeLock );
516 }
catch ( Exception
$e ) {
517 wfDebugLog(
'resourceloader', __METHOD__ .
": failed to update DB: $e" );
533 return array_map(
function ( $path ) use (
$IP ) {
534 return RelPath\getRelativePath( $path,
$IP );
547 return array_map(
function ( $path ) use (
$IP ) {
548 return RelPath\joinPath(
$IP, $path );
566 if ( !isset( $this->msgBlobs[
$lang] ) ) {
567 $this->
getLogger()->warning(
'Message blob for {module} should have been preloaded', [
570 $store =
$context->getResourceLoader()->getMessageBlobStore();
571 $this->msgBlobs[
$lang] = $store->getBlob( $this,
$lang );
573 return $this->msgBlobs[
$lang];
606 $formattedLinks = [];
608 $link =
"<{$url}>;rel=preload";
609 foreach (
$attribs as $key => $val ) {
610 $link .=
";{$key}={$val}";
612 $formattedLinks[] =
$link;
614 if ( $formattedLinks ) {
615 $headers[] =
'Link: ' . implode(
',', $formattedLinks );
686 if ( !array_key_exists( $contextHash, $this->
contents ) ) {
689 return $this->
contents[$contextHash];
700 $rl =
$context->getResourceLoader();
701 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
702 $statStart = microtime(
true );
711 if (
$context->shouldIncludeScripts() ) {
716 if (
$context->getDebug() && !
$context->getOnly() && $this->supportsURLLoading() ) {
727 if ( is_string( $scripts )
728 && strlen( $scripts )
729 && substr( $scripts, -1 ) !==
"\n"
734 $content[
'scripts'] = $scripts;
738 if (
$context->shouldIncludeStyles() ) {
742 $stylePairs = $this->
getStyles( $context );
743 if ( count( $stylePairs ) ) {
746 if (
$context->getDebug() && !
$context->getOnly() && $this->supportsURLLoading() ) {
754 foreach ( $stylePairs as $media => $style ) {
756 if ( is_array( $style ) ) {
757 $stylePairs[$media] = [];
758 foreach ( $style as $cssText ) {
759 if ( is_string( $cssText ) ) {
760 $stylePairs[$media][] =
764 } elseif ( is_string( $style ) ) {
771 'css' => $rl->makeCombinedStyles( $stylePairs )
775 $content[
'styles'] = $styles;
781 $content[
'messagesBlob'] =
$blob;
786 $content[
'templates'] = $templates;
791 $content[
'headers'] = $headers;
794 $statTiming = microtime(
true ) - $statStart;
795 $statName = strtr( $this->
getName(),
'.',
'_' );
796 $stats->timing(
"resourceloader_build.all", 1000 * $statTiming );
797 $stats->timing(
"resourceloader_build.$statName", 1000 * $statTiming );
838 if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
839 if ( $this->enableModuleContentVersion() ) {
841 $str = json_encode( $this->getModuleContent(
$context ) );
845 if ( !isset( $summary[
'_cacheEpoch'] ) ) {
846 throw new LogicException(
'getDefinitionSummary must call parent method' );
848 $str = json_encode( $summary );
851 if ( $mtime !==
null ) {
853 $str .= strval( $mtime );
857 if ( $mhash !==
null ) {
859 $str .= strval( $mhash );
865 return $this->versionHash[$contextHash];
877 public function enableModuleContentVersion() {
926 '_class' => static::class,
927 '_cacheEpoch' => $this->
getConfig()->get(
'CacheEpoch' ),
1012 return $this->
getGroup() ===
'private';
1028 if ( !$this->
getConfig()->
get(
'ResourceLoaderValidateJS' ) ) {
1031 $cache = ObjectCache::getMainWANInstance();
1032 return $cache->getWithSetCallback(
1036 self::$parseCacheVersion,
1041 function () use (
$contents, $fileName ) {
1046 }
catch ( Exception
$e ) {
1048 $err =
$e->getMessage();
1049 $result =
"mw.log.error(" .
1050 Xml::encodeJsVar(
"JavaScript parse error: $err" ) .
");";
1061 if ( !self::$jsParser ) {
1075 MediaWiki\suppressWarnings();
1076 $mtime = filemtime( $filePath ) ?: 1;
1077 MediaWiki\restoreWarnings();
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Allows changing specific properties of a context object, without changing the main one.
static getFileContentsHash( $filePaths, $algo='md4')
Get a hash of the combined contents of one or more files, either by retrieving a previously-computed ...
Object passed around to modules which contains information about the state of a specific loader reque...
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
isKnownEmpty(ResourceLoaderContext $context)
Check whether this module is known to be empty.
getModifiedHash(ResourceLoaderContext $context)
Helper method for providing a version hash to getVersionHash().
getScript(ResourceLoaderContext $context)
Get all JS for this module for a given language and skin.
static $parseCacheVersion
getDependencies(ResourceLoaderContext $context=null)
Get a list of modules this module depends on.
const ORIGIN_CORE_SITEWIDE
getFileDependencies(ResourceLoaderContext $context)
Get the files this module depends on indirectly for a given skin.
getSkipFunction()
Get the skip function.
validateScriptFile( $fileName, $contents)
Validate a given script file; if valid returns the original source.
getMessageBlob(ResourceLoaderContext $context)
Get the hash of the message blob.
static safeFileHash( $filePath)
Compute a non-cryptographic string hash of a file's contents.
static expandRelativePaths(array $filePaths)
Expand directories relative to $IP.
supportsURLLoading()
Whether this module supports URL loading.
getMessages()
Get the messages needed for this module.
setName( $name)
Set this module's name.
isRaw()
Whether this module's JS expects to work without the client-side ResourceLoader module.
const ORIGIN_USER_SITEWIDE
const ORIGIN_USER_INDIVIDUAL
getPosition()
From where in the page HTML should this module be loaded?
getStyles(ResourceLoaderContext $context)
Get all CSS for this module for a given skin.
getScriptURLsForDebug(ResourceLoaderContext $context)
Get the URL or URLs to load for this module's JS in debug mode.
getGroup()
Get the group this module is in.
setLogger(LoggerInterface $logger)
getDefinitionSummary(ResourceLoaderContext $context)
Get a list of resources that web browsers may preload.
static JSParser $jsParser
Lazy-initialized; use self::javaScriptParser()
getHashMtime(ResourceLoaderContext $context)
Back-compat dummy for old subclass implementations of getModifiedTime().
setConfig(Config $config)
getOrigin()
Get this module's origin.
getTargets()
Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile'].
getType()
Get the module's load type.
static javaScriptParser()
setFileDependencies(ResourceLoaderContext $context, $files)
Set in-object cache for file dependencies.
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.
shouldEmbedModule(ResourceLoaderContext $context)
Check whether this module should be embeded rather than linked.
getModifiedTime(ResourceLoaderContext $context)
Get this module's last modification timestamp for a given context.
static safeFilemtime( $filePath)
Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
getSource()
Get the origin of this module.
const ORIGIN_CORE_INDIVIDUAL
static getRelativePaths(array $filePaths)
Make file paths relative to MediaWiki directory.
getDeprecationInformation()
Get JS representing deprecation information for the current module if available.
saveFileDependencies(ResourceLoaderContext $context, $localFileRefs)
Set the files this module depends on indirectly for a given skin.
getName()
Get this module's name.
getHeaders(ResourceLoaderContext $context)
Get headers to send as part of a module web response.
getDefinitionMtime(ResourceLoaderContext $context)
Back-compat dummy for old subclass implementations of getModifiedTime().
getTemplates()
Takes named templates by the module and returns an array mapping.
static filter( $filter, $data, array $options=[])
Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
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
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
namespace being checked & $result
do that in ParserLimitReportFormat instead $parser
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
usually copyright or history_copyright This message must be in HTML not wikitext & $link
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
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
returning false will NOT prevent logging $e
if(!isset( $args[0])) $lang