38 # sitewide core module like a skin file or jQuery component
41 # per-user module generated by the software
44 # sitewide module generated from user-editable files, like MediaWiki:Common.js, or
45 # modules accessible to multiple users, such as those generated by the Gadgets extension.
48 # per-user module generated from user-editable files, like User:Me/vector.js
51 # an access constant; make sure this is kept as the largest number in this group
54 # script and style modules form a hierarchy of trustworthiness, with core modules like
55 # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
56 # limit the types of scripts and styles we allow to load on, say, sensitive special
57 # pages like Special:UserLogin and Special:Preferences
58 protected $origin = self::ORIGIN_CORE_SITEWIDE;
134 return $wgContLang->getDir() !==
$context->getDirection();
164 if ( $this->config === null ) {
194 if ( !$this->logger ) {
195 $this->logger =
new NullLogger();
217 $derivative->setModules( [ $this->
getName() ] );
218 $derivative->setOnly(
'scripts' );
219 $derivative->setDebug(
true );
264 $derivative->setModules( [ $this->
getName() ] );
265 $derivative->setOnly(
'styles' );
266 $derivative->setDebug(
true );
273 return [
'all' => [ $url ] ];
386 if ( !isset( $this->fileDeps[$vary] ) ) {
388 $deps =
$dbr->selectField(
'module_deps',
391 'md_module' => $this->
getName(),
397 if ( !is_null( $deps ) ) {
398 $this->fileDeps[$vary] = self::expandRelativePaths(
402 $this->fileDeps[$vary] = [];
405 return $this->fileDeps[$vary];
419 $this->fileDeps[$vary] =
$files;
431 $localFileRefs = array_values( array_unique( $localFileRefs ) );
432 sort( $localFileRefs );
439 $scopeLock =
$cache->getScopedLock(
$key, 0 );
446 $dbw->replace(
'module_deps',
447 [ [
'md_module',
'md_skin' ] ],
449 'md_module' => $this->
getName(),
456 $dbw->onTransactionIdle(
function ()
use ( &$scopeLock ) {
461 wfDebugLog(
'resourceloader', __METHOD__ .
": failed to update DB: $e" );
477 return array_map(
function (
$path )
use ( $IP ) {
478 return RelPath\getRelativePath(
$path, $IP );
491 return array_map(
function (
$path )
use ( $IP ) {
492 return RelPath\joinPath( $IP,
$path );
510 if ( !isset( $this->msgBlobs[
$lang] ) ) {
511 $this->
getLogger()->warning(
'Message blob for {module} should have been preloaded', [
515 $this->msgBlobs[
$lang] = $store->getBlob( $this, $lang );
517 return $this->msgBlobs[
$lang];
552 $contextHash = $context->
getHash();
555 if ( !array_key_exists( $contextHash, $this->
contents ) ) {
558 return $this->
contents[$contextHash];
571 $statStart = microtime(
true );
592 if ( is_string( $scripts )
593 && strlen( $scripts )
594 && substr( rtrim( $scripts ), -1 ) !==
';'
609 $stylePairs = $this->
getStyles( $context );
610 if ( count( $stylePairs ) ) {
621 foreach ( $stylePairs
as $media => $style ) {
623 if ( is_array( $style ) ) {
624 $stylePairs[$media] = [];
625 foreach ( $style
as $cssText ) {
626 if ( is_string( $cssText ) ) {
627 $stylePairs[$media][] =
631 } elseif ( is_string( $style ) ) {
638 'css' => $rl->makeCombinedStyles( $stylePairs )
656 $statTiming = microtime(
true ) - $statStart;
657 $statName = strtr( $this->
getName(),
'.',
'_' );
658 $stats->timing(
"resourceloader_build.all", 1000 * $statTiming );
659 $stats->timing(
"resourceloader_build.$statName", 1000 * $statTiming );
691 $context->setModules( [] );
693 $context->setOnly( null );
695 $context->setDebug(
false );
699 $contextHash = $context->
getHash();
700 if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
708 if ( !isset(
$summary[
'_cacheEpoch'] ) ) {
709 throw new LogicException(
'getDefinitionSummary must call parent method' );
714 if ( $mtime !== null ) {
716 $str .= strval( $mtime );
720 if ( $mhash !== null ) {
722 $str .= strval( $mhash );
728 return $this->versionHash[$contextHash];
789 '_class' => get_class( $this ),
790 '_cacheEpoch' => $this->
getConfig()->get(
'CacheEpoch' ),
877 if ( $this->
getConfig()->
get(
'ResourceLoaderValidateJS' ) ) {
883 self::$parseCacheVersion,
887 if ( is_string( $cacheEntry ) ) {
891 $parser = self::javaScriptParser();
897 $err = $e->getMessage();
913 if ( !self::$jsParser ) {
916 return self::$jsParser;
927 MediaWiki\suppressWarnings();
928 $mtime = filemtime( $filePath ) ?: 1;
929 MediaWiki\restoreWarnings();
isRaw()
Whether this module's JS expects to work without the client-side ResourceLoader module.
static getMainWANInstance()
Get the main WAN cache object.
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
the array() calling protocol came about after MediaWiki 1.4rc1.
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
getMessages()
Get the messages needed for this module.
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
error also a ContextSource you ll probably need to make sure the header is varied on such as when responding to a resource loader request or generating HTML output & $resourceLoader
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
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
getModifiedHash(ResourceLoaderContext $context)
Helper method for providing a version hash to getVersionHash().
if(!isset($args[0])) $lang
buildContent(ResourceLoaderContext $context)
Bundle all resources attached to this module into an array.
getMessageBlob(ResourceLoaderContext $context)
Get the hash of the message blob.
getHashMtime(ResourceLoaderContext $context)
Back-compat dummy for old subclass implementations of getModifiedTime().
getStyleURLsForDebug(ResourceLoaderContext $context)
Get the URL or URLs to load for this module's CSS in debug mode.
setFileDependencies(ResourceLoaderContext $context, $files)
Set in-object cache for file dependencies.
static getLocalClusterInstance()
Get the main cluster-local cache object.
setConfig(Config $config)
when a variable name is used in a it is silently declared as a new local masking the global
const ORIGIN_CORE_INDIVIDUAL
static safeFilemtime($filePath)
Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist...
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. '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 '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!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:Associative array mapping language codes to prefixed links of the form"language:title".&$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':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) $result
static getFileContentsHash($filePaths, $algo= 'md4')
Get a hash of the combined contents of one or more files, either by retrieving a previously-computed ...
Allows changing specific properties of a context object, without changing the main one...
getLessVars(ResourceLoaderContext $context)
Get module-specific LESS variables, if any.
static expandRelativePaths(array $filePaths)
Expand directories relative to $IP.
const ORIGIN_USER_INDIVIDUAL
wfDebugLog($logGroup, $text, $dest= 'all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
static getMain()
Static methods.
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.
getSkipFunction()
Get the skip function.
validateScriptFile($fileName, $contents)
Validate a given script file; if valid returns the original source.
getSource()
Get the origin of this module.
getTemplates()
Takes named templates by the module and returns an array mapping.
enableModuleContentVersion()
Whether to generate version hash based on module content.
getPosition()
Where on the HTML page should this module's JS be loaded?
const ORIGIN_USER_SITEWIDE
static $parseCacheVersion
static getRelativePaths(array $filePaths)
Make file paths relative to MediaWiki directory.
setName($name)
Set this module's name.
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
getTargets()
Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile'].
getModifiedTime(ResourceLoaderContext $context)
Get this module's last modification timestamp for a given context.
static getDefaultInstance()
static JSParser $jsParser
Lazy-initialized; use self::javaScriptParser()
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
getDefinitionMtime(ResourceLoaderContext $context)
Back-compat dummy for old subclass implementations of getModifiedTime().
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
static safeFileHash($filePath)
Compute a non-cryptographic string hash of a file's contents.
isKnownEmpty(ResourceLoaderContext $context)
Check whether this module is known to be empty.
static filter($filter, $data, array $options=[])
Run JavaScript or CSS data through a filter, caching the filtered result for future calls...
getScript(ResourceLoaderContext $context)
Get all JS for this module for a given language and skin.
static javaScriptParser()
static encodeJsVar($value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at name
setOrigin($origin)
Set this module's origin.
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
getGroup()
Get the group this module is in.
static consume(ScopedCallback &$sc=null)
Trigger a scoped callback and destroy it.
getStyles(ResourceLoaderContext $context)
Get all CSS for this module for a given skin.
getHash()
All factors that uniquely identify this request, except 'modules'.
const ORIGIN_CORE_SITEWIDE
getDependencies(ResourceLoaderContext $context=null)
Get a list of modules this module depends on.
setMessageBlob($blob, $lang)
Set in-object cache for message blobs.
setLogger(LoggerInterface $logger)
saveFileDependencies(ResourceLoaderContext $context, $localFileRefs)
Set the files this module depends on indirectly for a given skin.
supportsURLLoading()
Whether this module supports URL loading.
getOrigin()
Get this module's origin.
getScriptURLsForDebug(ResourceLoaderContext $context)
Get the URL or URLs to load for this module's JS in debug mode.
getModuleContent(ResourceLoaderContext $context)
Get an array of this module's resources.
getName()
Get this module's name.
Object passed around to modules which contains information about the state of a specific loader reque...