MediaWiki  master
ResourceLoaderModule.php
Go to the documentation of this file.
1 <?php
25 use Psr\Log\LoggerAwareInterface;
26 use Psr\Log\LoggerInterface;
27 use Psr\Log\NullLogger;
28 
32 abstract class ResourceLoaderModule implements LoggerAwareInterface {
33  # Type of resource
34  const TYPE_SCRIPTS = 'scripts';
35  const TYPE_STYLES = 'styles';
36  const TYPE_COMBINED = 'combined';
37 
38  # Desired load type
39  // Module only has styles (loaded via <style> or <link rel=stylesheet>)
40  const LOAD_STYLES = 'styles';
41  // Module may have other resources (loaded via mw.loader from a script)
42  const LOAD_GENERAL = 'general';
43 
44  # sitewide core module like a skin file or jQuery component
46 
47  # per-user module generated by the software
49 
50  # sitewide module generated from user-editable files, like MediaWiki:Common.js, or
51  # modules accessible to multiple users, such as those generated by the Gadgets extension.
53 
54  # per-user module generated from user-editable files, like User:Me/vector.js
56 
57  # an access constant; make sure this is kept as the largest number in this group
58  const ORIGIN_ALL = 10;
59 
60  # script and style modules form a hierarchy of trustworthiness, with core modules like
61  # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
62  # limit the types of scripts and styles we allow to load on, say, sensitive special
63  # pages like Special:UserLogin and Special:Preferences
64  protected $origin = self::ORIGIN_CORE_SITEWIDE;
65 
66  /* Protected Members */
67 
68  protected $name = null;
69  protected $targets = [ 'desktop' ];
70 
71  // In-object cache for file dependencies
72  protected $fileDeps = [];
73  // In-object cache for message blob (keyed by language)
74  protected $msgBlobs = [];
75  // In-object cache for version hash
76  protected $versionHash = [];
77  // In-object cache for module content
78  protected $contents = [];
79 
83  protected $config;
84 
88  protected $logger;
89 
90  /* Methods */
91 
98  public function getName() {
99  return $this->name;
100  }
101 
108  public function setName( $name ) {
109  $this->name = $name;
110  }
111 
119  public function getOrigin() {
120  return $this->origin;
121  }
122 
127  public function getFlip( $context ) {
129 
130  return $wgContLang->getDir() !== $context->getDirection();
131  }
132 
141  // Stub, override expected
142  return '';
143  }
144 
150  public function getTemplates() {
151  // Stub, override expected.
152  return [];
153  }
154 
159  public function getConfig() {
160  if ( $this->config === null ) {
161  // Ugh, fall back to default
162  $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
163  }
164 
165  return $this->config;
166  }
167 
172  public function setConfig( Config $config ) {
173  $this->config = $config;
174  }
175 
181  public function setLogger( LoggerInterface $logger ) {
182  $this->logger = $logger;
183  }
184 
189  protected function getLogger() {
190  if ( !$this->logger ) {
191  $this->logger = new NullLogger();
192  }
193  return $this->logger;
194  }
195 
211  $resourceLoader = $context->getResourceLoader();
212  $derivative = new DerivativeResourceLoaderContext( $context );
213  $derivative->setModules( [ $this->getName() ] );
214  $derivative->setOnly( 'scripts' );
215  $derivative->setDebug( true );
216 
217  $url = $resourceLoader->createLoaderURL(
218  $this->getSource(),
219  $derivative
220  );
221 
222  return [ $url ];
223  }
224 
231  public function supportsURLLoading() {
232  return true;
233  }
234 
244  // Stub, override expected
245  return [];
246  }
247 
258  $resourceLoader = $context->getResourceLoader();
259  $derivative = new DerivativeResourceLoaderContext( $context );
260  $derivative->setModules( [ $this->getName() ] );
261  $derivative->setOnly( 'styles' );
262  $derivative->setDebug( true );
263 
264  $url = $resourceLoader->createLoaderURL(
265  $this->getSource(),
266  $derivative
267  );
268 
269  return [ 'all' => [ $url ] ];
270  }
271 
279  public function getMessages() {
280  // Stub, override expected
281  return [];
282  }
283 
289  public function getGroup() {
290  // Stub, override expected
291  return null;
292  }
293 
299  public function getSource() {
300  // Stub, override expected
301  return 'local';
302  }
303 
311  public function getPosition() {
312  return 'bottom';
313  }
314 
322  public function isRaw() {
323  return false;
324  }
325 
338  public function getDependencies( ResourceLoaderContext $context = null ) {
339  // Stub, override expected
340  return [];
341  }
342 
348  public function getTargets() {
349  return $this->targets;
350  }
351 
358  public function getType() {
359  return self::LOAD_GENERAL;
360  }
361 
376  public function getSkipFunction() {
377  return null;
378  }
379 
389  $vary = $context->getSkin() . '|' . $context->getLanguage();
390 
391  // Try in-object cache first
392  if ( !isset( $this->fileDeps[$vary] ) ) {
393  $dbr = wfGetDB( DB_SLAVE );
394  $deps = $dbr->selectField( 'module_deps',
395  'md_deps',
396  [
397  'md_module' => $this->getName(),
398  'md_skin' => $vary,
399  ],
400  __METHOD__
401  );
402 
403  if ( !is_null( $deps ) ) {
404  $this->fileDeps[$vary] = self::expandRelativePaths(
405  (array)FormatJson::decode( $deps, true )
406  );
407  } else {
408  $this->fileDeps[$vary] = [];
409  }
410  }
411  return $this->fileDeps[$vary];
412  }
413 
424  $vary = $context->getSkin() . '|' . $context->getLanguage();
425  $this->fileDeps[$vary] = $files;
426  }
427 
435  protected function saveFileDependencies( ResourceLoaderContext $context, $localFileRefs ) {
436  // Normalise array
437  $localFileRefs = array_values( array_unique( $localFileRefs ) );
438  sort( $localFileRefs );
439 
440  try {
441  // If the list has been modified since last time we cached it, update the cache
442  if ( $localFileRefs !== $this->getFileDependencies( $context ) ) {
444  $key = $cache->makeKey( __METHOD__, $this->getName() );
445  $scopeLock = $cache->getScopedLock( $key, 0 );
446  if ( !$scopeLock ) {
447  return; // T124649; avoid write slams
448  }
449 
450  $vary = $context->getSkin() . '|' . $context->getLanguage();
451  $dbw = wfGetDB( DB_MASTER );
452  $dbw->replace( 'module_deps',
453  [ [ 'md_module', 'md_skin' ] ],
454  [
455  'md_module' => $this->getName(),
456  'md_skin' => $vary,
457  // Use relative paths to avoid ghost entries when $IP changes (T111481)
458  'md_deps' => FormatJson::encode( self::getRelativePaths( $localFileRefs ) ),
459  ]
460  );
461 
462  $dbw->onTransactionResolution( function () use ( &$scopeLock ) {
463  ScopedCallback::consume( $scopeLock ); // release after commit
464  } );
465  }
466  } catch ( Exception $e ) {
467  wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
468  }
469  }
470 
481  public static function getRelativePaths( array $filePaths ) {
482  global $IP;
483  return array_map( function ( $path ) use ( $IP ) {
484  return RelPath\getRelativePath( $path, $IP );
485  }, $filePaths );
486  }
487 
495  public static function expandRelativePaths( array $filePaths ) {
496  global $IP;
497  return array_map( function ( $path ) use ( $IP ) {
498  return RelPath\joinPath( $IP, $path );
499  }, $filePaths );
500  }
501 
510  if ( !$this->getMessages() ) {
511  // Don't bother consulting MessageBlobStore
512  return null;
513  }
514  // Message blobs may only vary language, not by context keys
515  $lang = $context->getLanguage();
516  if ( !isset( $this->msgBlobs[$lang] ) ) {
517  $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', [
518  'module' => $this->getName(),
519  ] );
520  $store = $context->getResourceLoader()->getMessageBlobStore();
521  $this->msgBlobs[$lang] = $store->getBlob( $this, $lang );
522  }
523  return $this->msgBlobs[$lang];
524  }
525 
535  public function setMessageBlob( $blob, $lang ) {
536  $this->msgBlobs[$lang] = $blob;
537  }
538 
547  return [];
548  }
549 
558  $contextHash = $context->getHash();
559  // Cache this expensive operation. This calls builds the scripts, styles, and messages
560  // content which typically involves filesystem and/or database access.
561  if ( !array_key_exists( $contextHash, $this->contents ) ) {
562  $this->contents[$contextHash] = $this->buildContent( $context );
563  }
564  return $this->contents[$contextHash];
565  }
566 
574  final protected function buildContent( ResourceLoaderContext $context ) {
575  $rl = $context->getResourceLoader();
576  $stats = RequestContext::getMain()->getStats();
577  $statStart = microtime( true );
578 
579  // Only include properties that are relevant to this context (e.g. only=scripts)
580  // and that are non-empty (e.g. don't include "templates" for modules without
581  // templates). This helps prevent invalidating cache for all modules when new
582  // optional properties are introduced.
583  $content = [];
584 
585  // Scripts
586  if ( $context->shouldIncludeScripts() ) {
587  // If we are in debug mode, we'll want to return an array of URLs if possible
588  // However, we can't do this if the module doesn't support it
589  // We also can't do this if there is an only= parameter, because we have to give
590  // the module a way to return a load.php URL without causing an infinite loop
591  if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
592  $scripts = $this->getScriptURLsForDebug( $context );
593  } else {
594  $scripts = $this->getScript( $context );
595  // rtrim() because there are usually a few line breaks
596  // after the last ';'. A new line at EOF, a new line
597  // added by ResourceLoaderFileModule::readScriptFiles, etc.
598  if ( is_string( $scripts )
599  && strlen( $scripts )
600  && substr( rtrim( $scripts ), -1 ) !== ';'
601  ) {
602  // Append semicolon to prevent weird bugs caused by files not
603  // terminating their statements right (bug 27054)
604  $scripts .= ";\n";
605  }
606  }
607  $content['scripts'] = $scripts;
608  }
609 
610  // Styles
611  if ( $context->shouldIncludeStyles() ) {
612  $styles = [];
613  // Don't create empty stylesheets like array( '' => '' ) for modules
614  // that don't *have* any stylesheets (bug 38024).
615  $stylePairs = $this->getStyles( $context );
616  if ( count( $stylePairs ) ) {
617  // If we are in debug mode without &only= set, we'll want to return an array of URLs
618  // See comment near shouldIncludeScripts() for more details
619  if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
620  $styles = [
621  'url' => $this->getStyleURLsForDebug( $context )
622  ];
623  } else {
624  // Minify CSS before embedding in mw.loader.implement call
625  // (unless in debug mode)
626  if ( !$context->getDebug() ) {
627  foreach ( $stylePairs as $media => $style ) {
628  // Can be either a string or an array of strings.
629  if ( is_array( $style ) ) {
630  $stylePairs[$media] = [];
631  foreach ( $style as $cssText ) {
632  if ( is_string( $cssText ) ) {
633  $stylePairs[$media][] =
634  ResourceLoader::filter( 'minify-css', $cssText );
635  }
636  }
637  } elseif ( is_string( $style ) ) {
638  $stylePairs[$media] = ResourceLoader::filter( 'minify-css', $style );
639  }
640  }
641  }
642  // Wrap styles into @media groups as needed and flatten into a numerical array
643  $styles = [
644  'css' => $rl->makeCombinedStyles( $stylePairs )
645  ];
646  }
647  }
648  $content['styles'] = $styles;
649  }
650 
651  // Messages
652  $blob = $this->getMessageBlob( $context );
653  if ( $blob ) {
654  $content['messagesBlob'] = $blob;
655  }
656 
657  $templates = $this->getTemplates();
658  if ( $templates ) {
659  $content['templates'] = $templates;
660  }
661 
662  $statTiming = microtime( true ) - $statStart;
663  $statName = strtr( $this->getName(), '.', '_' );
664  $stats->timing( "resourceloader_build.all", 1000 * $statTiming );
665  $stats->timing( "resourceloader_build.$statName", 1000 * $statTiming );
666 
667  return $content;
668  }
669 
693  // The startup module produces a manifest with versions representing the entire module.
694  // Typically, the request for the startup module itself has only=scripts. That must apply
695  // only to the startup module content, and not to the module version computed here.
696  $context = new DerivativeResourceLoaderContext( $context );
697  $context->setModules( [] );
698  // Version hash must cover all resources, regardless of startup request itself.
699  $context->setOnly( null );
700  // Compute version hash based on content, not debug urls.
701  $context->setDebug( false );
702 
703  // Cache this somewhat expensive operation. Especially because some classes
704  // (e.g. startup module) iterate more than once over all modules to get versions.
705  $contextHash = $context->getHash();
706  if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
707 
708  if ( $this->enableModuleContentVersion() ) {
709  // Detect changes directly
710  $str = json_encode( $this->getModuleContent( $context ) );
711  } else {
712  // Infer changes based on definition and other metrics
713  $summary = $this->getDefinitionSummary( $context );
714  if ( !isset( $summary['_cacheEpoch'] ) ) {
715  throw new LogicException( 'getDefinitionSummary must call parent method' );
716  }
717  $str = json_encode( $summary );
718 
719  $mtime = $this->getModifiedTime( $context );
720  if ( $mtime !== null ) {
721  // Support: MediaWiki 1.25 and earlier
722  $str .= strval( $mtime );
723  }
724 
725  $mhash = $this->getModifiedHash( $context );
726  if ( $mhash !== null ) {
727  // Support: MediaWiki 1.25 and earlier
728  $str .= strval( $mhash );
729  }
730  }
731 
732  $this->versionHash[$contextHash] = ResourceLoader::makeHash( $str );
733  }
734  return $this->versionHash[$contextHash];
735  }
736 
746  public function enableModuleContentVersion() {
747  return false;
748  }
749 
794  return [
795  '_class' => get_class( $this ),
796  '_cacheEpoch' => $this->getConfig()->get( 'CacheEpoch' ),
797  ];
798  }
799 
808  return null;
809  }
810 
819  return null;
820  }
821 
834  if ( !is_string( $this->getModifiedHash( $context ) ) ) {
835  return 1;
836  }
837  // Dummy that is > 1
838  return 2;
839  }
840 
850  if ( $this->getDefinitionSummary( $context ) === null ) {
851  return 1;
852  }
853  // Dummy that is > 1
854  return 2;
855  }
856 
867  return false;
868  }
869 
871  private static $jsParser;
872  private static $parseCacheVersion = 1;
873 
882  protected function validateScriptFile( $fileName, $contents ) {
883  if ( $this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
884  // Try for cache hit
886  $key = $cache->makeKey(
887  'resourceloader',
888  'jsparse',
889  self::$parseCacheVersion,
890  md5( $contents )
891  );
892  $cacheEntry = $cache->get( $key );
893  if ( is_string( $cacheEntry ) ) {
894  return $cacheEntry;
895  }
896 
897  $parser = self::javaScriptParser();
898  try {
899  $parser->parse( $contents, $fileName, 1 );
900  $result = $contents;
901  } catch ( Exception $e ) {
902  // We'll save this to cache to avoid having to validate broken JS over and over...
903  $err = $e->getMessage();
904  $result = "mw.log.error(" .
905  Xml::encodeJsVar( "JavaScript parse error: $err" ) . ");";
906  }
907 
908  $cache->set( $key, $result );
909  return $result;
910  } else {
911  return $contents;
912  }
913  }
914 
918  protected static function javaScriptParser() {
919  if ( !self::$jsParser ) {
920  self::$jsParser = new JSParser();
921  }
922  return self::$jsParser;
923  }
924 
932  protected static function safeFilemtime( $filePath ) {
933  MediaWiki\suppressWarnings();
934  $mtime = filemtime( $filePath ) ?: 1;
935  MediaWiki\restoreWarnings();
936  return $mtime;
937  }
938 
947  protected static function safeFileHash( $filePath ) {
948  return FileContentsHasher::getFileContentsHash( $filePath );
949  }
950 }
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.
getMessages()
Get the messages needed for this module.
$context
Definition: load.php:43
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
$IP
Definition: WebStart.php:58
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
Definition: hooks.txt:2458
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
Definition: hooks.txt:1980
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
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.
$files
static getLocalClusterInstance()
Get the main cluster-local cache object.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
magic word & $parser
Definition: hooks.txt:2372
static safeFilemtime($filePath)
Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist...
static makeHash($value)
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':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:1814
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.
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.
Interface for configuration instances.
Definition: Config.php:28
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.
$summary
getPosition()
Where on the HTML page should this module's JS be loaded?
static encode($value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:127
$cache
Definition: mcc.php:33
const DB_SLAVE
Definition: Defines.php:46
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
Definition: distributors.txt:9
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().
getType()
Get the module's load type.
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
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 encodeJsVar($value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition: Xml.php:664
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
Definition: hooks.txt:1020
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
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
Definition: design.txt:56
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.
const DB_MASTER
Definition: Defines.php:47
getHash()
All factors that uniquely identify this request, except 'modules'.
getDependencies(ResourceLoaderContext $context=null)
Get a list of modules this module depends on.
setMessageBlob($blob, $lang)
Set in-object cache for message blobs.
static decode($value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:187
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...