MediaWiki  1.32.0
ResourceLoaderModule.php
Go to the documentation of this file.
1 <?php
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\LoggerInterface;
28 use Psr\Log\NullLogger;
29 use Wikimedia\RelPath;
30 use Wikimedia\ScopedCallback;
31 
35 abstract class ResourceLoaderModule implements LoggerAwareInterface {
36  # Type of resource
37  const TYPE_SCRIPTS = 'scripts';
38  const TYPE_STYLES = 'styles';
39  const TYPE_COMBINED = 'combined';
40 
41  # Desired load type
42  // Module only has styles (loaded via <style> or <link rel=stylesheet>)
43  const LOAD_STYLES = 'styles';
44  // Module may have other resources (loaded via mw.loader from a script)
45  const LOAD_GENERAL = 'general';
46 
47  # sitewide core module like a skin file or jQuery component
49 
50  # per-user module generated by the software
52 
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.
56 
57  # per-user module generated from user-editable files, like User:Me/vector.js
59 
60  # an access constant; make sure this is kept as the largest number in this group
61  const ORIGIN_ALL = 10;
62 
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
68 
69  protected $name = null;
70  protected $targets = [ 'desktop' ];
71 
72  // In-object cache for file dependencies
73  protected $fileDeps = [];
74  // In-object cache for message blob (keyed by language)
75  protected $msgBlobs = [];
76  // In-object cache for version hash
77  protected $versionHash = [];
78  // In-object cache for module content
79  protected $contents = [];
80 
84  protected $config;
85 
89  protected $deprecated = false;
90 
94  protected $logger;
95 
102  public function getName() {
103  return $this->name;
104  }
105 
112  public function setName( $name ) {
113  $this->name = $name;
114  }
115 
123  public function getOrigin() {
124  return $this->origin;
125  }
126 
131  public function getFlip( $context ) {
132  return MediaWikiServices::getInstance()->getContentLanguage()->getDir() !==
133  $context->getDirection();
134  }
135 
141  public function getDeprecationInformation() {
142  $deprecationInfo = $this->deprecated;
143  if ( $deprecationInfo ) {
144  $name = $this->getName();
145  $warning = 'This page is using the deprecated ResourceLoader module "' . $name . '".';
146  if ( is_string( $deprecationInfo ) ) {
147  $warning .= "\n" . $deprecationInfo;
148  }
149  return Xml::encodeJsCall(
150  'mw.log.warn',
151  [ $warning ]
152  );
153  } else {
154  return '';
155  }
156  }
157 
166  // Stub, override expected
167  return '';
168  }
169 
175  public function getTemplates() {
176  // Stub, override expected.
177  return [];
178  }
179 
184  public function getConfig() {
185  if ( $this->config === null ) {
186  // Ugh, fall back to default
187  $this->config = MediaWikiServices::getInstance()->getMainConfig();
188  }
189 
190  return $this->config;
191  }
192 
197  public function setConfig( Config $config ) {
198  $this->config = $config;
199  }
200 
206  public function setLogger( LoggerInterface $logger ) {
207  $this->logger = $logger;
208  }
209 
214  protected function getLogger() {
215  if ( !$this->logger ) {
216  $this->logger = new NullLogger();
217  }
218  return $this->logger;
219  }
220 
236  $resourceLoader = $context->getResourceLoader();
237  $derivative = new DerivativeResourceLoaderContext( $context );
238  $derivative->setModules( [ $this->getName() ] );
239  $derivative->setOnly( 'scripts' );
240  $derivative->setDebug( true );
241 
242  $url = $resourceLoader->createLoaderURL(
243  $this->getSource(),
244  $derivative
245  );
246 
247  return [ $url ];
248  }
249 
256  public function supportsURLLoading() {
257  return true;
258  }
259 
269  // Stub, override expected
270  return [];
271  }
272 
283  $resourceLoader = $context->getResourceLoader();
284  $derivative = new DerivativeResourceLoaderContext( $context );
285  $derivative->setModules( [ $this->getName() ] );
286  $derivative->setOnly( 'styles' );
287  $derivative->setDebug( true );
288 
289  $url = $resourceLoader->createLoaderURL(
290  $this->getSource(),
291  $derivative
292  );
293 
294  return [ 'all' => [ $url ] ];
295  }
296 
304  public function getMessages() {
305  // Stub, override expected
306  return [];
307  }
308 
314  public function getGroup() {
315  // Stub, override expected
316  return null;
317  }
318 
324  public function getSource() {
325  // Stub, override expected
326  return 'local';
327  }
328 
336  public function isRaw() {
337  return false;
338  }
339 
352  public function getDependencies( ResourceLoaderContext $context = null ) {
353  // Stub, override expected
354  return [];
355  }
356 
362  public function getTargets() {
363  return $this->targets;
364  }
365 
372  public function getType() {
373  return self::LOAD_GENERAL;
374  }
375 
390  public function getSkipFunction() {
391  return null;
392  }
393 
403  $vary = $context->getSkin() . '|' . $context->getLanguage();
404 
405  // Try in-object cache first
406  if ( !isset( $this->fileDeps[$vary] ) ) {
407  $dbr = wfGetDB( DB_REPLICA );
408  $deps = $dbr->selectField( 'module_deps',
409  'md_deps',
410  [
411  'md_module' => $this->getName(),
412  'md_skin' => $vary,
413  ],
414  __METHOD__
415  );
416 
417  if ( !is_null( $deps ) ) {
418  $this->fileDeps[$vary] = self::expandRelativePaths(
419  (array)json_decode( $deps, true )
420  );
421  } else {
422  $this->fileDeps[$vary] = [];
423  }
424  }
425  return $this->fileDeps[$vary];
426  }
427 
438  $vary = $context->getSkin() . '|' . $context->getLanguage();
439  $this->fileDeps[$vary] = $files;
440  }
441 
449  protected function saveFileDependencies( ResourceLoaderContext $context, $localFileRefs ) {
450  try {
451  // Related bugs and performance considerations:
452  // 1. Don't needlessly change the database value with the same list in a
453  // different order or with duplicates.
454  // 2. Use relative paths to avoid ghost entries when $IP changes. (T111481)
455  // 3. Don't needlessly replace the database with the same value
456  // just because $IP changed (e.g. when upgrading a wiki).
457  // 4. Don't create an endless replace loop on every request for this
458  // module when '../' is used anywhere. Even though both are expanded
459  // (one expanded by getFileDependencies from the DB, the other is
460  // still raw as originally read by RL), the latter has not
461  // been normalized yet.
462 
463  // Normalise
464  $localFileRefs = array_values( array_unique( $localFileRefs ) );
465  sort( $localFileRefs );
466  $localPaths = self::getRelativePaths( $localFileRefs );
467 
468  $storedPaths = self::getRelativePaths( $this->getFileDependencies( $context ) );
469  // If the list has been modified since last time we cached it, update the cache
470  if ( $localPaths !== $storedPaths ) {
471  $vary = $context->getSkin() . '|' . $context->getLanguage();
473  $key = $cache->makeKey( __METHOD__, $this->getName(), $vary );
474  $scopeLock = $cache->getScopedLock( $key, 0 );
475  if ( !$scopeLock ) {
476  return; // T124649; avoid write slams
477  }
478 
479  // No needless escaping as this isn't HTML output.
480  // Only stored in the database and parsed in PHP.
481  $deps = json_encode( $localPaths, JSON_UNESCAPED_SLASHES );
482  $dbw = wfGetDB( DB_MASTER );
483  $dbw->upsert( 'module_deps',
484  [
485  'md_module' => $this->getName(),
486  'md_skin' => $vary,
487  'md_deps' => $deps,
488  ],
489  [ 'md_module', 'md_skin' ],
490  [
491  'md_deps' => $deps,
492  ]
493  );
494 
495  if ( $dbw->trxLevel() ) {
496  $dbw->onTransactionResolution(
497  function () use ( &$scopeLock ) {
498  ScopedCallback::consume( $scopeLock ); // release after commit
499  },
500  __METHOD__
501  );
502  }
503  }
504  } catch ( Exception $e ) {
505  wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
506  }
507  }
508 
519  public static function getRelativePaths( array $filePaths ) {
520  global $IP;
521  return array_map( function ( $path ) use ( $IP ) {
522  return RelPath::getRelativePath( $path, $IP );
523  }, $filePaths );
524  }
525 
533  public static function expandRelativePaths( array $filePaths ) {
534  global $IP;
535  return array_map( function ( $path ) use ( $IP ) {
536  return RelPath::joinPath( $IP, $path );
537  }, $filePaths );
538  }
539 
548  if ( !$this->getMessages() ) {
549  // Don't bother consulting MessageBlobStore
550  return null;
551  }
552  // Message blobs may only vary language, not by context keys
553  $lang = $context->getLanguage();
554  if ( !isset( $this->msgBlobs[$lang] ) ) {
555  $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', [
556  'module' => $this->getName(),
557  ] );
558  $store = $context->getResourceLoader()->getMessageBlobStore();
559  $this->msgBlobs[$lang] = $store->getBlob( $this, $lang );
560  }
561  return $this->msgBlobs[$lang];
562  }
563 
573  public function setMessageBlob( $blob, $lang ) {
574  $this->msgBlobs[$lang] = $blob;
575  }
576 
591  final public function getHeaders( ResourceLoaderContext $context ) {
592  $headers = [];
593 
594  $formattedLinks = [];
595  foreach ( $this->getPreloadLinks( $context ) as $url => $attribs ) {
596  $link = "<{$url}>;rel=preload";
597  foreach ( $attribs as $key => $val ) {
598  $link .= ";{$key}={$val}";
599  }
600  $formattedLinks[] = $link;
601  }
602  if ( $formattedLinks ) {
603  $headers[] = 'Link: ' . implode( ',', $formattedLinks );
604  }
605 
606  return $headers;
607  }
608 
649  return [];
650  }
651 
660  return [];
661  }
662 
671  $contextHash = $context->getHash();
672  // Cache this expensive operation. This calls builds the scripts, styles, and messages
673  // content which typically involves filesystem and/or database access.
674  if ( !array_key_exists( $contextHash, $this->contents ) ) {
675  $this->contents[$contextHash] = $this->buildContent( $context );
676  }
677  return $this->contents[$contextHash];
678  }
679 
687  final protected function buildContent( ResourceLoaderContext $context ) {
688  $rl = $context->getResourceLoader();
689  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
690  $statStart = microtime( true );
691 
692  // This MUST build both scripts and styles, regardless of whether $context->getOnly()
693  // is 'scripts' or 'styles' because the result is used by getVersionHash which
694  // must be consistent regardles of the 'only' filter on the current request.
695  // Also, when introducing new module content resources (e.g. templates, headers),
696  // these should only be included in the array when they are non-empty so that
697  // existing modules not using them do not get their cache invalidated.
698  $content = [];
699 
700  // Scripts
701  // If we are in debug mode, we'll want to return an array of URLs if possible
702  // However, we can't do this if the module doesn't support it.
703  // We also can't do this if there is an only= parameter, because we have to give
704  // the module a way to return a load.php URL without causing an infinite loop
705  if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
706  $scripts = $this->getScriptURLsForDebug( $context );
707  } else {
708  $scripts = $this->getScript( $context );
709  // Make the script safe to concatenate by making sure there is at least one
710  // trailing new line at the end of the content. Previously, this looked for
711  // a semi-colon instead, but that breaks concatenation if the semicolon
712  // is inside a comment like "// foo();". Instead, simply use a
713  // line break as separator which matches JavaScript native logic for implicitly
714  // ending statements even if a semi-colon is missing.
715  // Bugs: T29054, T162719.
716  if ( is_string( $scripts )
717  && strlen( $scripts )
718  && substr( $scripts, -1 ) !== "\n"
719  ) {
720  $scripts .= "\n";
721  }
722  }
723  $content['scripts'] = $scripts;
724 
725  // Styles
726  $styles = [];
727  // Don't create empty stylesheets like [ '' => '' ] for modules
728  // that don't *have* any stylesheets (T40024).
729  $stylePairs = $this->getStyles( $context );
730  if ( count( $stylePairs ) ) {
731  // If we are in debug mode without &only= set, we'll want to return an array of URLs
732  // See comment near shouldIncludeScripts() for more details
733  if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
734  $styles = [
735  'url' => $this->getStyleURLsForDebug( $context )
736  ];
737  } else {
738  // Minify CSS before embedding in mw.loader.implement call
739  // (unless in debug mode)
740  if ( !$context->getDebug() ) {
741  foreach ( $stylePairs as $media => $style ) {
742  // Can be either a string or an array of strings.
743  if ( is_array( $style ) ) {
744  $stylePairs[$media] = [];
745  foreach ( $style as $cssText ) {
746  if ( is_string( $cssText ) ) {
747  $stylePairs[$media][] =
748  ResourceLoader::filter( 'minify-css', $cssText );
749  }
750  }
751  } elseif ( is_string( $style ) ) {
752  $stylePairs[$media] = ResourceLoader::filter( 'minify-css', $style );
753  }
754  }
755  }
756  // Wrap styles into @media groups as needed and flatten into a numerical array
757  $styles = [
758  'css' => $rl->makeCombinedStyles( $stylePairs )
759  ];
760  }
761  }
762  $content['styles'] = $styles;
763 
764  // Messages
765  $blob = $this->getMessageBlob( $context );
766  if ( $blob ) {
767  $content['messagesBlob'] = $blob;
768  }
769 
770  $templates = $this->getTemplates();
771  if ( $templates ) {
772  $content['templates'] = $templates;
773  }
774 
775  $headers = $this->getHeaders( $context );
776  if ( $headers ) {
777  $content['headers'] = $headers;
778  }
779 
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 );
784 
785  return $content;
786  }
787 
806  // Cache this somewhat expensive operation. Especially because some classes
807  // (e.g. startup module) iterate more than once over all modules to get versions.
808  $contextHash = $context->getHash();
809  if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
810  if ( $this->enableModuleContentVersion() ) {
811  // Detect changes directly by hashing the module contents.
812  $str = json_encode( $this->getModuleContent( $context ) );
813  } else {
814  // Infer changes based on definition and other metrics
815  $summary = $this->getDefinitionSummary( $context );
816  if ( !isset( $summary['_class'] ) ) {
817  throw new LogicException( 'getDefinitionSummary must call parent method' );
818  }
819  $str = json_encode( $summary );
820  }
821 
822  $this->versionHash[$contextHash] = ResourceLoader::makeHash( $str );
823  }
824  return $this->versionHash[$contextHash];
825  }
826 
836  public function enableModuleContentVersion() {
837  return false;
838  }
839 
884  return [
885  '_class' => static::class,
886  // Make sure that when filter cache for minification is invalidated,
887  // we also change the HTTP urls and mw.loader.store keys (T176884).
888  '_cacheVersion' => ResourceLoader::CACHE_VERSION,
889  ];
890  }
891 
902  return false;
903  }
904 
916  return $this->getGroup() === 'private';
917  }
918 
920  private static $jsParser;
921  private static $parseCacheVersion = 1;
922 
931  protected function validateScriptFile( $fileName, $contents ) {
932  if ( !$this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
933  return $contents;
934  }
936  return $cache->getWithSetCallback(
937  $cache->makeGlobalKey(
938  'resourceloader',
939  'jsparse',
940  self::$parseCacheVersion,
941  md5( $contents ),
942  $fileName
943  ),
944  $cache::TTL_WEEK,
945  function () use ( $contents, $fileName ) {
947  try {
948  $parser->parse( $contents, $fileName, 1 );
949  $result = $contents;
950  } catch ( Exception $e ) {
951  // We'll save this to cache to avoid having to re-validate broken JS
952  $err = $e->getMessage();
953  $result = "mw.log.error(" .
954  Xml::encodeJsVar( "JavaScript parse error: $err" ) . ");";
955  }
956  return $result;
957  }
958  );
959  }
960 
964  protected static function javaScriptParser() {
965  if ( !self::$jsParser ) {
966  self::$jsParser = new JSParser();
967  }
968  return self::$jsParser;
969  }
970 
978  protected static function safeFilemtime( $filePath ) {
979  Wikimedia\suppressWarnings();
980  $mtime = filemtime( $filePath ) ?: 1;
981  Wikimedia\restoreWarnings();
982  return $mtime;
983  }
984 
993  protected static function safeFileHash( $filePath ) {
994  return FileContentsHasher::getFileContentsHash( $filePath );
995  }
996 }
ResourceLoaderModule\LOAD_GENERAL
const LOAD_GENERAL
Definition: ResourceLoaderModule.php:45
ResourceLoaderContext
Object passed around to modules which contains information about the state of a specific loader reque...
Definition: ResourceLoaderContext.php:32
ResourceLoaderModule\getFlip
getFlip( $context)
Definition: ResourceLoaderModule.php:131
ResourceLoaderModule\supportsURLLoading
supportsURLLoading()
Whether this module supports URL loading.
Definition: ResourceLoaderModule.php:256
ResourceLoaderModule\getStyleURLsForDebug
getStyleURLsForDebug(ResourceLoaderContext $context)
Get the URL or URLs to load for this module's CSS in debug mode.
Definition: ResourceLoaderModule.php:282
ResourceLoaderModule\setMessageBlob
setMessageBlob( $blob, $lang)
Set in-object cache for message blobs.
Definition: ResourceLoaderModule.php:573
ResourceLoaderModule\setFileDependencies
setFileDependencies(ResourceLoaderContext $context, $files)
Set in-object cache for file dependencies.
Definition: ResourceLoaderModule.php:437
ObjectCache\getLocalClusterInstance
static getLocalClusterInstance()
Get the main cluster-local cache object.
Definition: ObjectCache.php:365
$context
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
Definition: hooks.txt:2675
ResourceLoaderModule\TYPE_COMBINED
const TYPE_COMBINED
Definition: ResourceLoaderModule.php:39
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
ResourceLoaderModule\ORIGIN_CORE_SITEWIDE
const ORIGIN_CORE_SITEWIDE
Definition: ResourceLoaderModule.php:48
captcha-old.count
count
Definition: captcha-old.py:249
ResourceLoaderModule\ORIGIN_USER_SITEWIDE
const ORIGIN_USER_SITEWIDE
Definition: ResourceLoaderModule.php:55
ResourceLoaderModule\isRaw
isRaw()
Whether this module's JS expects to work without the client-side ResourceLoader module.
Definition: ResourceLoaderModule.php:336
ResourceLoaderModule\$versionHash
$versionHash
Definition: ResourceLoaderModule.php:77
ResourceLoaderModule\safeFilemtime
static safeFilemtime( $filePath)
Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
Definition: ResourceLoaderModule.php:978
ResourceLoaderModule\setName
setName( $name)
Set this module's name.
Definition: ResourceLoaderModule.php:112
ResourceLoaderModule\setLogger
setLogger(LoggerInterface $logger)
Definition: ResourceLoaderModule.php:206
ResourceLoaderModule\saveFileDependencies
saveFileDependencies(ResourceLoaderContext $context, $localFileRefs)
Set the files this module depends on indirectly for a given skin.
Definition: ResourceLoaderModule.php:449
$result
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 '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) $result
Definition: hooks.txt:2034
ResourceLoaderModule\getHeaders
getHeaders(ResourceLoaderContext $context)
Get headers to send as part of a module web response.
Definition: ResourceLoaderModule.php:591
ResourceLoaderModule\getType
getType()
Get the module's load type.
Definition: ResourceLoaderModule.php:372
ResourceLoaderModule\getTargets
getTargets()
Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile'].
Definition: ResourceLoaderModule.php:362
ResourceLoaderModule\shouldEmbedModule
shouldEmbedModule(ResourceLoaderContext $context)
Check whether this module should be embeded rather than linked.
Definition: ResourceLoaderModule.php:915
ResourceLoaderModule\$origin
$origin
Definition: ResourceLoaderModule.php:67
$resourceLoader
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
Definition: hooks.txt:2675
ResourceLoaderModule\getStyles
getStyles(ResourceLoaderContext $context)
Get all CSS for this module for a given skin.
Definition: ResourceLoaderModule.php:268
ResourceLoaderModule\getTemplates
getTemplates()
Takes named templates by the module and returns an array mapping.
Definition: ResourceLoaderModule.php:175
Xml\encodeJsVar
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition: Xml.php:661
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1082
php
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
Definition: injection.txt:35
ResourceLoaderModule\buildContent
buildContent(ResourceLoaderContext $context)
Bundle all resources attached to this module into an array.
Definition: ResourceLoaderModule.php:687
FileContentsHasher\getFileContentsHash
static getFileContentsHash( $filePaths, $algo='md4')
Get a hash of the combined contents of one or more files, either by retrieving a previously-computed ...
Definition: FileContentsHasher.php:89
ResourceLoaderModule\getLessVars
getLessVars(ResourceLoaderContext $context)
Get module-specific LESS variables, if any.
Definition: ResourceLoaderModule.php:659
$dbr
$dbr
Definition: testCompression.php:50
ResourceLoaderModule\enableModuleContentVersion
enableModuleContentVersion()
Whether to generate version hash based on module content.
Definition: ResourceLoaderModule.php:836
Xml\encodeJsCall
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition: Xml.php:679
name
and how to run hooks for an and one after Each event has a name
Definition: hooks.txt:6
Config
Interface for configuration instances.
Definition: Config.php:28
ResourceLoaderModule\getGroup
getGroup()
Get the group this module is in.
Definition: ResourceLoaderModule.php:314
ResourceLoaderModule\$jsParser
static JSParser $jsParser
Lazy-initialized; use self::javaScriptParser()
Definition: ResourceLoaderModule.php:920
ResourceLoaderModule\getLogger
getLogger()
Definition: ResourceLoaderModule.php:214
ResourceLoaderModule\getScript
getScript(ResourceLoaderContext $context)
Get all JS for this module for a given language and skin.
Definition: ResourceLoaderModule.php:165
$blob
$blob
Definition: testCompression.php:65
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2693
ResourceLoaderModule\$contents
$contents
Definition: ResourceLoaderModule.php:79
$attribs
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
Definition: hooks.txt:2036
$IP
$IP
Definition: update.php:3
ResourceLoaderModule\TYPE_SCRIPTS
const TYPE_SCRIPTS
Definition: ResourceLoaderModule.php:37
use
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
Definition: MIT-LICENSE.txt:10
contents
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
Definition: database.txt:2
$parser
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition: hooks.txt:1841
ResourceLoaderModule\expandRelativePaths
static expandRelativePaths(array $filePaths)
Expand directories relative to $IP.
Definition: ResourceLoaderModule.php:533
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
ResourceLoaderContext\getLanguage
getLanguage()
Definition: ResourceLoaderContext.php:177
DB_MASTER
const DB_MASTER
Definition: defines.php:26
array
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))
ResourceLoaderModule\getOrigin
getOrigin()
Get this module's origin.
Definition: ResourceLoaderModule.php:123
ResourceLoaderModule\getMessageBlob
getMessageBlob(ResourceLoaderContext $context)
Get the hash of the message blob.
Definition: ResourceLoaderModule.php:547
ResourceLoaderModule\$parseCacheVersion
static $parseCacheVersion
Definition: ResourceLoaderModule.php:921
ResourceLoaderModule\isKnownEmpty
isKnownEmpty(ResourceLoaderContext $context)
Check whether this module is known to be empty.
Definition: ResourceLoaderModule.php:901
ResourceLoaderModule\getDeprecationInformation
getDeprecationInformation()
Get JS representing deprecation information for the current module if available.
Definition: ResourceLoaderModule.php:141
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2213
ResourceLoaderModule\safeFileHash
static safeFileHash( $filePath)
Compute a non-cryptographic string hash of a file's contents.
Definition: ResourceLoaderModule.php:993
ResourceLoaderModule\ORIGIN_USER_INDIVIDUAL
const ORIGIN_USER_INDIVIDUAL
Definition: ResourceLoaderModule.php:58
ResourceLoaderModule\$deprecated
array bool $deprecated
Definition: ResourceLoaderModule.php:89
ResourceLoaderModule\getDependencies
getDependencies(ResourceLoaderContext $context=null)
Get a list of modules this module depends on.
Definition: ResourceLoaderModule.php:352
ResourceLoaderModule\$targets
$targets
Definition: ResourceLoaderModule.php:70
ResourceLoaderModule\getPreloadLinks
getPreloadLinks(ResourceLoaderContext $context)
Get a list of resources that web browsers may preload.
Definition: ResourceLoaderModule.php:648
DerivativeResourceLoaderContext
Allows changing specific properties of a context object, without changing the main one.
Definition: DerivativeResourceLoaderContext.php:30
ResourceLoaderModule\$name
$name
Definition: ResourceLoaderModule.php:69
ResourceLoaderModule\LOAD_STYLES
const LOAD_STYLES
Definition: ResourceLoaderModule.php:43
ResourceLoaderModule\getMessages
getMessages()
Get the messages needed for this module.
Definition: ResourceLoaderModule.php:304
ResourceLoaderModule\validateScriptFile
validateScriptFile( $fileName, $contents)
Validate a given script file; if valid returns the original source.
Definition: ResourceLoaderModule.php:931
ResourceLoaderModule\getDefinitionSummary
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
Definition: ResourceLoaderModule.php:883
ResourceLoaderModule\ORIGIN_CORE_INDIVIDUAL
const ORIGIN_CORE_INDIVIDUAL
Definition: ResourceLoaderModule.php:51
ResourceLoaderModule\getModuleContent
getModuleContent(ResourceLoaderContext $context)
Get an array of this module's resources.
Definition: ResourceLoaderModule.php:670
ResourceLoaderModule\getSkipFunction
getSkipFunction()
Get the skip function.
Definition: ResourceLoaderModule.php:390
ResourceLoaderModule\ORIGIN_ALL
const ORIGIN_ALL
Definition: ResourceLoaderModule.php:61
ResourceLoaderModule
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
Definition: ResourceLoaderModule.php:35
ResourceLoaderModule\$config
Config $config
Definition: ResourceLoaderModule.php:84
ResourceLoaderModule\$logger
LoggerInterface $logger
Definition: ResourceLoaderModule.php:94
ResourceLoaderModule\$fileDeps
$fileDeps
Definition: ResourceLoaderModule.php:73
$cache
$cache
Definition: mcc.php:33
ResourceLoaderModule\setConfig
setConfig(Config $config)
Definition: ResourceLoaderModule.php:197
ObjectCache\getMainWANInstance
static getMainWANInstance()
Get the main WAN cache object.
Definition: ObjectCache.php:378
ResourceLoaderModule\getScriptURLsForDebug
getScriptURLsForDebug(ResourceLoaderContext $context)
Get the URL or URLs to load for this module's JS in debug mode.
Definition: ResourceLoaderModule.php:235
$path
$path
Definition: NoLocalSettings.php:25
as
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
Definition: distributors.txt:9
ResourceLoaderModule\getRelativePaths
static getRelativePaths(array $filePaths)
Make file paths relative to MediaWiki directory.
Definition: ResourceLoaderModule.php:519
$link
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3090
ResourceLoaderModule\getFileDependencies
getFileDependencies(ResourceLoaderContext $context)
Get the files this module depends on indirectly for a given skin.
Definition: ResourceLoaderModule.php:402
ResourceLoaderModule\TYPE_STYLES
const TYPE_STYLES
Definition: ResourceLoaderModule.php:38
ResourceLoaderModule\getVersionHash
getVersionHash(ResourceLoaderContext $context)
Get a string identifying the current version of this module in a given context.
Definition: ResourceLoaderModule.php:805
$content
$content
Definition: pageupdater.txt:72
ResourceLoaderModule\getSource
getSource()
Get the source of this module.
Definition: ResourceLoaderModule.php:324
JSParser
Definition: jsminplus.php:674
class
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
Definition: maintenance.txt:52
ResourceLoaderModule\javaScriptParser
static javaScriptParser()
Definition: ResourceLoaderModule.php:964
MediaWikiServices
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
Definition: injection.txt:23
ResourceLoaderModule\$msgBlobs
$msgBlobs
Definition: ResourceLoaderModule.php:75
ResourceLoaderModule\getName
getName()
Get this module's name.
Definition: ResourceLoaderModule.php:102
ResourceLoaderModule\getConfig
getConfig()
Definition: ResourceLoaderModule.php:184