MediaWiki  REL1_31
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 ) {
133 
134  return $wgContLang->getDir() !== $context->getDirection();
135  }
136 
142  protected function getDeprecationInformation() {
143  $deprecationInfo = $this->deprecated;
144  if ( $deprecationInfo ) {
145  $name = $this->getName();
146  $warning = 'This page is using the deprecated ResourceLoader module "' . $name . '".';
147  if ( is_string( $deprecationInfo ) ) {
148  $warning .= "\n" . $deprecationInfo;
149  }
150  return Xml::encodeJsCall(
151  'mw.log.warn',
152  [ $warning ]
153  );
154  } else {
155  return '';
156  }
157  }
158 
167  // Stub, override expected
168  return '';
169  }
170 
176  public function getTemplates() {
177  // Stub, override expected.
178  return [];
179  }
180 
185  public function getConfig() {
186  if ( $this->config === null ) {
187  // Ugh, fall back to default
188  $this->config = MediaWikiServices::getInstance()->getMainConfig();
189  }
190 
191  return $this->config;
192  }
193 
198  public function setConfig( Config $config ) {
199  $this->config = $config;
200  }
201 
207  public function setLogger( LoggerInterface $logger ) {
208  $this->logger = $logger;
209  }
210 
215  protected function getLogger() {
216  if ( !$this->logger ) {
217  $this->logger = new NullLogger();
218  }
219  return $this->logger;
220  }
221 
237  $resourceLoader = $context->getResourceLoader();
238  $derivative = new DerivativeResourceLoaderContext( $context );
239  $derivative->setModules( [ $this->getName() ] );
240  $derivative->setOnly( 'scripts' );
241  $derivative->setDebug( true );
242 
243  $url = $resourceLoader->createLoaderURL(
244  $this->getSource(),
245  $derivative
246  );
247 
248  return [ $url ];
249  }
250 
257  public function supportsURLLoading() {
258  return true;
259  }
260 
270  // Stub, override expected
271  return [];
272  }
273 
284  $resourceLoader = $context->getResourceLoader();
285  $derivative = new DerivativeResourceLoaderContext( $context );
286  $derivative->setModules( [ $this->getName() ] );
287  $derivative->setOnly( 'styles' );
288  $derivative->setDebug( true );
289 
290  $url = $resourceLoader->createLoaderURL(
291  $this->getSource(),
292  $derivative
293  );
294 
295  return [ 'all' => [ $url ] ];
296  }
297 
305  public function getMessages() {
306  // Stub, override expected
307  return [];
308  }
309 
315  public function getGroup() {
316  // Stub, override expected
317  return null;
318  }
319 
325  public function getSource() {
326  // Stub, override expected
327  return 'local';
328  }
329 
337  public function isRaw() {
338  return false;
339  }
340 
353  public function getDependencies( ResourceLoaderContext $context = null ) {
354  // Stub, override expected
355  return [];
356  }
357 
363  public function getTargets() {
364  return $this->targets;
365  }
366 
373  public function getType() {
374  return self::LOAD_GENERAL;
375  }
376 
391  public function getSkipFunction() {
392  return null;
393  }
394 
404  $vary = $context->getSkin() . '|' . $context->getLanguage();
405 
406  // Try in-object cache first
407  if ( !isset( $this->fileDeps[$vary] ) ) {
408  $dbr = wfGetDB( DB_REPLICA );
409  $deps = $dbr->selectField( 'module_deps',
410  'md_deps',
411  [
412  'md_module' => $this->getName(),
413  'md_skin' => $vary,
414  ],
415  __METHOD__
416  );
417 
418  if ( !is_null( $deps ) ) {
419  $this->fileDeps[$vary] = self::expandRelativePaths(
420  (array)FormatJson::decode( $deps, true )
421  );
422  } else {
423  $this->fileDeps[$vary] = [];
424  }
425  }
426  return $this->fileDeps[$vary];
427  }
428 
439  $vary = $context->getSkin() . '|' . $context->getLanguage();
440  $this->fileDeps[$vary] = $files;
441  }
442 
450  protected function saveFileDependencies( ResourceLoaderContext $context, $localFileRefs ) {
451  try {
452  // Related bugs and performance considerations:
453  // 1. Don't needlessly change the database value with the same list in a
454  // different order or with duplicates.
455  // 2. Use relative paths to avoid ghost entries when $IP changes. (T111481)
456  // 3. Don't needlessly replace the database with the same value
457  // just because $IP changed (e.g. when upgrading a wiki).
458  // 4. Don't create an endless replace loop on every request for this
459  // module when '../' is used anywhere. Even though both are expanded
460  // (one expanded by getFileDependencies from the DB, the other is
461  // still raw as originally read by RL), the latter has not
462  // been normalized yet.
463 
464  // Normalise
465  $localFileRefs = array_values( array_unique( $localFileRefs ) );
466  sort( $localFileRefs );
467  $localPaths = self::getRelativePaths( $localFileRefs );
468 
469  $storedPaths = self::getRelativePaths( $this->getFileDependencies( $context ) );
470  // If the list has been modified since last time we cached it, update the cache
471  if ( $localPaths !== $storedPaths ) {
472  $vary = $context->getSkin() . '|' . $context->getLanguage();
474  $key = $cache->makeKey( __METHOD__, $this->getName(), $vary );
475  $scopeLock = $cache->getScopedLock( $key, 0 );
476  if ( !$scopeLock ) {
477  return; // T124649; avoid write slams
478  }
479 
480  $deps = FormatJson::encode( $localPaths );
481  $dbw = wfGetDB( DB_MASTER );
482  $dbw->upsert( 'module_deps',
483  [
484  'md_module' => $this->getName(),
485  'md_skin' => $vary,
486  'md_deps' => $deps,
487  ],
488  [ [ 'md_module', 'md_skin' ] ],
489  [
490  'md_deps' => $deps,
491  ]
492  );
493 
494  if ( $dbw->trxLevel() ) {
495  $dbw->onTransactionResolution(
496  function () use ( &$scopeLock ) {
497  ScopedCallback::consume( $scopeLock ); // release after commit
498  },
499  __METHOD__
500  );
501  }
502  }
503  } catch ( Exception $e ) {
504  wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
505  }
506  }
507 
518  public static function getRelativePaths( array $filePaths ) {
519  global $IP;
520  return array_map( function ( $path ) use ( $IP ) {
521  return RelPath::getRelativePath( $path, $IP );
522  }, $filePaths );
523  }
524 
532  public static function expandRelativePaths( array $filePaths ) {
533  global $IP;
534  return array_map( function ( $path ) use ( $IP ) {
535  return RelPath::joinPath( $IP, $path );
536  }, $filePaths );
537  }
538 
547  if ( !$this->getMessages() ) {
548  // Don't bother consulting MessageBlobStore
549  return null;
550  }
551  // Message blobs may only vary language, not by context keys
552  $lang = $context->getLanguage();
553  if ( !isset( $this->msgBlobs[$lang] ) ) {
554  $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', [
555  'module' => $this->getName(),
556  ] );
557  $store = $context->getResourceLoader()->getMessageBlobStore();
558  $this->msgBlobs[$lang] = $store->getBlob( $this, $lang );
559  }
560  return $this->msgBlobs[$lang];
561  }
562 
572  public function setMessageBlob( $blob, $lang ) {
573  $this->msgBlobs[$lang] = $blob;
574  }
575 
590  final public function getHeaders( ResourceLoaderContext $context ) {
591  $headers = [];
592 
593  $formattedLinks = [];
594  foreach ( $this->getPreloadLinks( $context ) as $url => $attribs ) {
595  $link = "<{$url}>;rel=preload";
596  foreach ( $attribs as $key => $val ) {
597  $link .= ";{$key}={$val}";
598  }
599  $formattedLinks[] = $link;
600  }
601  if ( $formattedLinks ) {
602  $headers[] = 'Link: ' . implode( ',', $formattedLinks );
603  }
604 
605  return $headers;
606  }
607 
648  return [];
649  }
650 
659  return [];
660  }
661 
670  $contextHash = $context->getHash();
671  // Cache this expensive operation. This calls builds the scripts, styles, and messages
672  // content which typically involves filesystem and/or database access.
673  if ( !array_key_exists( $contextHash, $this->contents ) ) {
674  $this->contents[$contextHash] = $this->buildContent( $context );
675  }
676  return $this->contents[$contextHash];
677  }
678 
686  final protected function buildContent( ResourceLoaderContext $context ) {
687  $rl = $context->getResourceLoader();
688  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
689  $statStart = microtime( true );
690 
691  // Only include properties that are relevant to this context (e.g. only=scripts)
692  // and that are non-empty (e.g. don't include "templates" for modules without
693  // templates). This helps prevent invalidating cache for all modules when new
694  // optional properties are introduced.
695  $content = [];
696 
697  // Scripts
698  if ( $context->shouldIncludeScripts() ) {
699  // If we are in debug mode, we'll want to return an array of URLs if possible
700  // However, we can't do this if the module doesn't support it
701  // We also can't do this if there is an only= parameter, because we have to give
702  // the module a way to return a load.php URL without causing an infinite loop
703  if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
704  $scripts = $this->getScriptURLsForDebug( $context );
705  } else {
706  $scripts = $this->getScript( $context );
707  // Make the script safe to concatenate by making sure there is at least one
708  // trailing new line at the end of the content. Previously, this looked for
709  // a semi-colon instead, but that breaks concatenation if the semicolon
710  // is inside a comment like "// foo();". Instead, simply use a
711  // line break as separator which matches JavaScript native logic for implicitly
712  // ending statements even if a semi-colon is missing.
713  // Bugs: T29054, T162719.
714  if ( is_string( $scripts )
715  && strlen( $scripts )
716  && substr( $scripts, -1 ) !== "\n"
717  ) {
718  $scripts .= "\n";
719  }
720  }
721  $content['scripts'] = $scripts;
722  }
723 
724  // Styles
725  if ( $context->shouldIncludeStyles() ) {
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 
765  // Messages
766  $blob = $this->getMessageBlob( $context );
767  if ( $blob ) {
768  $content['messagesBlob'] = $blob;
769  }
770 
771  $templates = $this->getTemplates();
772  if ( $templates ) {
773  $content['templates'] = $templates;
774  }
775 
776  $headers = $this->getHeaders( $context );
777  if ( $headers ) {
778  $content['headers'] = $headers;
779  }
780 
781  $statTiming = microtime( true ) - $statStart;
782  $statName = strtr( $this->getName(), '.', '_' );
783  $stats->timing( "resourceloader_build.all", 1000 * $statTiming );
784  $stats->timing( "resourceloader_build.$statName", 1000 * $statTiming );
785 
786  return $content;
787  }
788 
812  // The startup module produces a manifest with versions representing the entire module.
813  // Typically, the request for the startup module itself has only=scripts. That must apply
814  // only to the startup module content, and not to the module version computed here.
816  $context->setModules( [] );
817  // Version hash must cover all resources, regardless of startup request itself.
818  $context->setOnly( null );
819  // Compute version hash based on content, not debug urls.
820  $context->setDebug( false );
821 
822  // Cache this somewhat expensive operation. Especially because some classes
823  // (e.g. startup module) iterate more than once over all modules to get versions.
824  $contextHash = $context->getHash();
825  if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
826  if ( $this->enableModuleContentVersion() ) {
827  // Detect changes directly
828  $str = json_encode( $this->getModuleContent( $context ) );
829  } else {
830  // Infer changes based on definition and other metrics
831  $summary = $this->getDefinitionSummary( $context );
832  if ( !isset( $summary['_cacheEpoch'] ) ) {
833  throw new LogicException( 'getDefinitionSummary must call parent method' );
834  }
835  $str = json_encode( $summary );
836 
837  $mtime = $this->getModifiedTime( $context );
838  if ( $mtime !== null ) {
839  // Support: MediaWiki 1.25 and earlier
840  $str .= strval( $mtime );
841  }
842 
843  $mhash = $this->getModifiedHash( $context );
844  if ( $mhash !== null ) {
845  // Support: MediaWiki 1.25 and earlier
846  $str .= strval( $mhash );
847  }
848  }
849 
850  $this->versionHash[$contextHash] = ResourceLoader::makeHash( $str );
851  }
852  return $this->versionHash[$contextHash];
853  }
854 
864  public function enableModuleContentVersion() {
865  return false;
866  }
867 
912  return [
913  '_class' => static::class,
914  '_cacheEpoch' => $this->getConfig()->get( 'CacheEpoch' ),
915  ];
916  }
917 
926  return null;
927  }
928 
937  return null;
938  }
939 
950  return false;
951  }
952 
964  return $this->getGroup() === 'private';
965  }
966 
968  private static $jsParser;
969  private static $parseCacheVersion = 1;
970 
979  protected function validateScriptFile( $fileName, $contents ) {
980  if ( !$this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
981  return $contents;
982  }
984  return $cache->getWithSetCallback(
985  $cache->makeGlobalKey(
986  'resourceloader',
987  'jsparse',
988  self::$parseCacheVersion,
989  md5( $contents ),
990  $fileName
991  ),
992  $cache::TTL_WEEK,
993  function () use ( $contents, $fileName ) {
995  try {
996  $parser->parse( $contents, $fileName, 1 );
997  $result = $contents;
998  } catch ( Exception $e ) {
999  // We'll save this to cache to avoid having to re-validate broken JS
1000  $err = $e->getMessage();
1001  $result = "mw.log.error(" .
1002  Xml::encodeJsVar( "JavaScript parse error: $err" ) . ");";
1003  }
1004  return $result;
1005  }
1006  );
1007  }
1008 
1012  protected static function javaScriptParser() {
1013  if ( !self::$jsParser ) {
1014  self::$jsParser = new JSParser();
1015  }
1016  return self::$jsParser;
1017  }
1018 
1026  protected static function safeFilemtime( $filePath ) {
1027  Wikimedia\suppressWarnings();
1028  $mtime = filemtime( $filePath ) ?: 1;
1029  Wikimedia\restoreWarnings();
1030  return $mtime;
1031  }
1032 
1041  protected static function safeFileHash( $filePath ) {
1042  return FileContentsHasher::getFileContentsHash( $filePath );
1043  }
1044 }
ResourceLoader\filter
static filter( $filter, $data, array $options=[])
Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
Definition: ResourceLoader.php:189
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:257
ResourceLoaderModule\getStyleURLsForDebug
getStyleURLsForDebug(ResourceLoaderContext $context)
Get the URL or URLs to load for this module's CSS in debug mode.
Definition: ResourceLoaderModule.php:283
ResourceLoaderModule\setMessageBlob
setMessageBlob( $blob, $lang)
Set in-object cache for message blobs.
Definition: ResourceLoaderModule.php:572
ResourceLoaderModule\setFileDependencies
setFileDependencies(ResourceLoaderContext $context, $files)
Set in-object cache for file dependencies.
Definition: ResourceLoaderModule.php:438
ObjectCache\getLocalClusterInstance
static getLocalClusterInstance()
Get the main cluster-local cache object.
Definition: ObjectCache.php:367
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
ResourceLoaderModule\getModifiedTime
getModifiedTime(ResourceLoaderContext $context)
Get this module's last modification timestamp for a given context.
Definition: ResourceLoaderModule.php:925
ResourceLoaderModule\TYPE_COMBINED
const TYPE_COMBINED
Definition: ResourceLoaderModule.php:39
array
the array() calling protocol came about after MediaWiki 1.4rc1.
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
ResourceLoaderModule\ORIGIN_CORE_SITEWIDE
const ORIGIN_CORE_SITEWIDE
Definition: ResourceLoaderModule.php:48
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:337
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:1026
ResourceLoaderModule\setName
setName( $name)
Set this module's name.
Definition: ResourceLoaderModule.php:112
ResourceLoaderModule\setLogger
setLogger(LoggerInterface $logger)
Definition: ResourceLoaderModule.php:207
ResourceLoaderModule\saveFileDependencies
saveFileDependencies(ResourceLoaderContext $context, $localFileRefs)
Set the files this module depends on indirectly for a given skin.
Definition: ResourceLoaderModule.php:450
ResourceLoaderModule\getHeaders
getHeaders(ResourceLoaderContext $context)
Get headers to send as part of a module web response.
Definition: ResourceLoaderModule.php:590
ResourceLoaderModule\getType
getType()
Get the module's load type.
Definition: ResourceLoaderModule.php:373
ResourceLoaderModule\getTargets
getTargets()
Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile'].
Definition: ResourceLoaderModule.php:363
ResourceLoaderModule\shouldEmbedModule
shouldEmbedModule(ResourceLoaderContext $context)
Check whether this module should be embeded rather than linked.
Definition: ResourceLoaderModule.php:963
ResourceLoaderModule\$origin
$origin
Definition: ResourceLoaderModule.php:67
ResourceLoaderModule\getStyles
getStyles(ResourceLoaderContext $context)
Get all CSS for this module for a given skin.
Definition: ResourceLoaderModule.php:269
$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:2818
$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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> 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! 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! 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:1993
ResourceLoaderModule\getTemplates
getTemplates()
Takes named templates by the module and returns an array mapping.
Definition: ResourceLoaderModule.php:176
Xml\encodeJsVar
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition: Xml.php:660
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:1087
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:37
ResourceLoaderModule\buildContent
buildContent(ResourceLoaderContext $context)
Bundle all resources attached to this module into an array.
Definition: ResourceLoaderModule.php:686
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:658
$dbr
$dbr
Definition: testCompression.php:50
ResourceLoaderModule\enableModuleContentVersion
enableModuleContentVersion()
Whether to generate version hash based on module content.
Definition: ResourceLoaderModule.php:864
Xml\encodeJsCall
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition: Xml.php:678
Config
Interface for configuration instances.
Definition: Config.php:28
FormatJson\decode
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:187
FormatJson\encode
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:127
ResourceLoaderModule\getGroup
getGroup()
Get the group this module is in.
Definition: ResourceLoaderModule.php:315
ResourceLoaderModule\$jsParser
static JSParser $jsParser
Lazy-initialized; use self::javaScriptParser()
Definition: ResourceLoaderModule.php:968
ResourceLoaderModule\getLogger
getLogger()
Definition: ResourceLoaderModule.php:215
ResourceLoaderModule\getScript
getScript(ResourceLoaderContext $context)
Get all JS for this module for a given language and skin.
Definition: ResourceLoaderModule.php:166
$blob
$blob
Definition: testCompression.php:65
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2812
ResourceLoader\makeHash
static makeHash( $value)
Definition: ResourceLoader.php:627
$parser
do that in ParserLimitReportFormat instead $parser
Definition: hooks.txt:2603
ResourceLoaderModule\$contents
$contents
Definition: ResourceLoaderModule.php:79
ResourceLoaderModule\TYPE_SCRIPTS
const TYPE_SCRIPTS
Definition: ResourceLoaderModule.php:37
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:9
$link
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3021
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:95
ResourceLoaderModule\expandRelativePaths
static expandRelativePaths(array $filePaths)
Expand directories relative to $IP.
Definition: ResourceLoaderModule.php:532
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
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:546
ResourceLoaderModule\$parseCacheVersion
static $parseCacheVersion
Definition: ResourceLoaderModule.php:969
ResourceLoaderModule\isKnownEmpty
isKnownEmpty(ResourceLoaderContext $context)
Check whether this module is known to be empty.
Definition: ResourceLoaderModule.php:949
$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:2014
ResourceLoaderModule\getDeprecationInformation
getDeprecationInformation()
Get JS representing deprecation information for the current module if available.
Definition: ResourceLoaderModule.php:142
ResourceLoaderModule\safeFileHash
static safeFileHash( $filePath)
Compute a non-cryptographic string hash of a file's contents.
Definition: ResourceLoaderModule.php:1041
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:353
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:647
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:305
ResourceLoaderModule\validateScriptFile
validateScriptFile( $fileName, $contents)
Validate a given script file; if valid returns the original source.
Definition: ResourceLoaderModule.php:979
ResourceLoaderModule\getModifiedHash
getModifiedHash(ResourceLoaderContext $context)
Helper method for providing a version hash to getVersionHash().
Definition: ResourceLoaderModule.php:936
ResourceLoaderModule\getDefinitionSummary
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
Definition: ResourceLoaderModule.php:911
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:669
ResourceLoaderModule\getSkipFunction
getSkipFunction()
Get the skip function.
Definition: ResourceLoaderModule.php:391
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:198
ObjectCache\getMainWANInstance
static getMainWANInstance()
Get the main WAN cache object.
Definition: ObjectCache.php:380
ResourceLoaderModule\getScriptURLsForDebug
getScriptURLsForDebug(ResourceLoaderContext $context)
Get the URL or URLs to load for this module's JS in debug mode.
Definition: ResourceLoaderModule.php:236
$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:22
ResourceLoaderModule\getRelativePaths
static getRelativePaths(array $filePaths)
Make file paths relative to MediaWiki directory.
Definition: ResourceLoaderModule.php:518
ResourceLoaderModule\getFileDependencies
getFileDependencies(ResourceLoaderContext $context)
Get the files this module depends on indirectly for a given skin.
Definition: ResourceLoaderModule.php:403
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:811
ResourceLoaderModule\getSource
getSource()
Get the origin of this module.
Definition: ResourceLoaderModule.php:325
JSParser
Definition: jsminplus.php:675
name
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
Definition: design.txt:12
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:56
ResourceLoaderModule\javaScriptParser
static javaScriptParser()
Definition: ResourceLoaderModule.php:1012
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:25
$IP
$IP
Definition: WebStart.php:52
ResourceLoaderModule\$msgBlobs
$msgBlobs
Definition: ResourceLoaderModule.php:75
ResourceLoaderModule\getName
getName()
Get this module's name.
Definition: ResourceLoaderModule.php:102
$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:2811
ResourceLoaderModule\getConfig
getConfig()
Definition: ResourceLoaderModule.php:185
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2171
$wgContLang
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 content language as $wgContLang
Definition: design.txt:57