26use Psr\Log\LoggerAwareInterface;
27use Psr\Log\LoggerInterface;
28use Psr\Log\NullLogger;
30use 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
69 protected $name =
null;
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;
149 return Xml::encodeJsCall(
185 if ( $this->config ===
null ) {
187 $this->config = MediaWikiServices::getInstance()->getMainConfig();
215 if ( !$this->logger ) {
216 $this->logger =
new NullLogger();
238 $derivative->setModules( [ $this->
getName() ] );
239 $derivative->setOnly(
'scripts' );
240 $derivative->setDebug(
true );
285 $derivative->setModules( [ $this->
getName() ] );
286 $derivative->setOnly(
'styles' );
287 $derivative->setDebug(
true );
294 return [
'all' => [ $url ] ];
406 if ( !isset( $this->fileDeps[$vary] ) ) {
408 $deps =
$dbr->selectField(
'module_deps',
411 'md_module' => $this->
getName(),
417 if ( !is_null( $deps ) ) {
419 (
array)json_decode( $deps,
true )
422 $this->fileDeps[$vary] = [];
425 return $this->fileDeps[$vary];
439 $this->fileDeps[$vary] = $files;
464 $localFileRefs = array_values( array_unique( $localFileRefs ) );
465 sort( $localFileRefs );
470 if ( $localPaths !== $storedPaths ) {
472 $cache = ObjectCache::getLocalClusterInstance();
473 $key =
$cache->makeKey( __METHOD__, $this->
getName(), $vary );
474 $scopeLock =
$cache->getScopedLock( $key, 0 );
481 $deps = json_encode( $localPaths, JSON_UNESCAPED_SLASHES );
483 $dbw->upsert(
'module_deps',
485 'md_module' => $this->
getName(),
489 [ [
'md_module',
'md_skin' ] ],
495 if ( $dbw->trxLevel() ) {
496 $dbw->onTransactionResolution(
497 function () use ( &$scopeLock ) {
498 ScopedCallback::consume( $scopeLock );
504 }
catch ( Exception
$e ) {
505 wfDebugLog(
'resourceloader', __METHOD__ .
": failed to update DB: $e" );
521 return array_map(
function ( $path ) use (
$IP ) {
522 return RelPath::getRelativePath( $path,
$IP );
535 return array_map(
function ( $path ) use (
$IP ) {
536 return RelPath::joinPath(
$IP, $path );
554 if ( !isset( $this->msgBlobs[
$lang] ) ) {
555 $this->
getLogger()->warning(
'Message blob for {module} should have been preloaded', [
558 $store =
$context->getResourceLoader()->getMessageBlobStore();
559 $this->msgBlobs[
$lang] = $store->getBlob( $this,
$lang );
561 return $this->msgBlobs[
$lang];
594 $formattedLinks = [];
596 $link =
"<{$url}>;rel=preload";
597 foreach (
$attribs as $key => $val ) {
598 $link .=
";{$key}={$val}";
600 $formattedLinks[] =
$link;
602 if ( $formattedLinks ) {
603 $headers[] =
'Link: ' . implode(
',', $formattedLinks );
674 if ( !array_key_exists( $contextHash, $this->
contents ) ) {
677 return $this->
contents[$contextHash];
688 $rl =
$context->getResourceLoader();
689 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
690 $statStart = microtime(
true );
705 if (
$context->getDebug() && !
$context->getOnly() && $this->supportsURLLoading() ) {
716 if ( is_string( $scripts )
717 && strlen( $scripts )
718 && substr( $scripts, -1 ) !==
"\n"
729 $stylePairs = $this->
getStyles( $context );
730 if ( count( $stylePairs ) ) {
733 if (
$context->getDebug() && !
$context->getOnly() && $this->supportsURLLoading() ) {
741 foreach ( $stylePairs as $media => $style ) {
743 if ( is_array( $style ) ) {
744 $stylePairs[$media] = [];
745 foreach ( $style as $cssText ) {
746 if ( is_string( $cssText ) ) {
747 $stylePairs[$media][] =
751 } elseif ( is_string( $style ) ) {
758 'css' => $rl->makeCombinedStyles( $stylePairs )
780 $statTiming = microtime(
true ) - $statStart;
781 $statName = strtr( $this->
getName(),
'.',
'_' );
782 $stats->timing(
"resourceloader_build.all", 1000 * $statTiming );
783 $stats->timing(
"resourceloader_build.$statName", 1000 * $statTiming );
809 if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
816 if ( !isset( $summary[
'_class'] ) ) {
817 throw new LogicException(
'getDefinitionSummary must call parent method' );
819 $str = json_encode( $summary );
824 return $this->versionHash[$contextHash];
885 '_class' => static::class,
888 '_cacheVersion' => ResourceLoader::CACHE_VERSION,
916 return $this->
getGroup() ===
'private';
932 if ( !$this->
getConfig()->
get(
'ResourceLoaderValidateJS' ) ) {
935 $cache = ObjectCache::getMainWANInstance();
936 return $cache->getWithSetCallback(
940 self::$parseCacheVersion,
945 function () use (
$contents, $fileName ) {
950 }
catch ( Exception
$e ) {
952 $err =
$e->getMessage();
953 $result =
"mw.log.error(" .
954 Xml::encodeJsVar(
"JavaScript parse error: $err" ) .
");";
965 if ( !self::$jsParser ) {
979 Wikimedia\suppressWarnings();
980 $mtime = filemtime( $filePath ) ?: 1;
981 Wikimedia\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.
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.
enableModuleContentVersion()
Whether to generate version hash based on module content.
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.
getModuleContent(ResourceLoaderContext $context)
Get an array of this module's resources.
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
getStyles(ResourceLoaderContext $context)
Get all CSS for this module for a given skin.
getLessVars(ResourceLoaderContext $context)
Get module-specific LESS variables, if any.
getScriptURLsForDebug(ResourceLoaderContext $context)
Get the URL or URLs to load for this module's JS in debug mode.
getVersionHash(ResourceLoaderContext $context)
Get a string identifying the current version of this module in a given context.
getGroup()
Get the group this module is in.
setLogger(LoggerInterface $logger)
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
static JSParser $jsParser
Lazy-initialized; use self::javaScriptParser()
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.
getPreloadLinks(ResourceLoaderContext $context)
Get a list of resources that web browsers may preload.
shouldEmbedModule(ResourceLoaderContext $context)
Check whether this module should be embeded rather than linked.
static safeFilemtime( $filePath)
Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
getSource()
Get the source of this module.
buildContent(ResourceLoaderContext $context)
Bundle all resources attached to this module into an array.
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.
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
namespace being checked & $result
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $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
> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) name
returning false will NOT prevent logging $e
Interface for configuration instances.
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))
if(!isset( $args[0])) $lang