MediaWiki  1.33.0
ExtensionRegistry.php
Go to the documentation of this file.
1 <?php
2 
3 use Composer\Semver\Semver;
4 use Wikimedia\ScopedCallback;
7 
18 
22  const MEDIAWIKI_CORE = 'MediaWiki';
23 
28  const MANIFEST_VERSION = 2;
29 
34  const MANIFEST_VERSION_MW_VERSION = '>= 1.29.0';
35 
40 
44  const CACHE_VERSION = 7;
45 
51  const MERGE_STRATEGY = '_merge_strategy';
52 
58  private $loaded = [];
59 
65  protected $queued = [];
66 
72  private $finished = false;
73 
80  protected $attributes = [];
81 
87  protected $testAttributes = [];
88 
92  private static $instance;
93 
98  public static function getInstance() {
99  if ( self::$instance === null ) {
100  self::$instance = new self();
101  }
102 
103  return self::$instance;
104  }
105 
109  public function queue( $path ) {
110  global $wgExtensionInfoMTime;
111 
112  $mtime = $wgExtensionInfoMTime;
113  if ( $mtime === false ) {
114  if ( file_exists( $path ) ) {
115  $mtime = filemtime( $path );
116  } else {
117  throw new Exception( "$path does not exist!" );
118  }
119  // @codeCoverageIgnoreStart
120  if ( $mtime === false ) {
121  $err = error_get_last();
122  throw new Exception( "Couldn't stat $path: {$err['message']}" );
123  // @codeCoverageIgnoreEnd
124  }
125  }
126  $this->queued[$path] = $mtime;
127  }
128 
133  public function loadFromQueue() {
135  if ( !$this->queued ) {
136  return;
137  }
138 
139  if ( $this->finished ) {
140  throw new MWException(
141  "The following paths tried to load late: "
142  . implode( ', ', array_keys( $this->queued ) )
143  );
144  }
145 
146  // A few more things to vary the cache on
147  $versions = [
148  'registration' => self::CACHE_VERSION,
149  'mediawiki' => $wgVersion,
150  'abilities' => $this->getAbilities(),
151  ];
152 
153  // We use a try/catch because we don't want to fail here
154  // if $wgObjectCaches is not configured properly for APC setup
155  try {
156  // Don't use MediaWikiServices here to prevent instantiating it before extensions have
157  // been loaded
159  $cache = ObjectCache::newFromId( $cacheId );
160  } catch ( InvalidArgumentException $e ) {
161  $cache = new EmptyBagOStuff();
162  }
163  // See if this queue is in APC
164  $key = $cache->makeKey(
165  'registration',
166  md5( json_encode( $this->queued + $versions ) )
167  );
168  $data = $cache->get( $key );
169  if ( $data ) {
170  $this->exportExtractedData( $data );
171  } else {
172  $data = $this->readFromQueue( $this->queued );
173  $this->exportExtractedData( $data );
174  // Do this late since we don't want to extract it since we already
175  // did that, but it should be cached
176  $data['globals']['wgAutoloadClasses'] += $data['autoload'];
177  unset( $data['autoload'] );
178  if ( !( $data['warnings'] && $wgDevelopmentWarnings ) ) {
179  // If there were no warnings that were shown, cache it
180  $cache->set( $key, $data, 60 * 60 * 24 );
181  }
182  }
183  $this->queued = [];
184  }
185 
192  public function getQueue() {
193  return $this->queued;
194  }
195 
200  public function clearQueue() {
201  $this->queued = [];
202  }
203 
209  public function finish() {
210  $this->finished = true;
211  }
212 
217  private function getAbilities() {
218  return [
219  'shell' => !Shell::isDisabled(),
220  ];
221  }
222 
228  private function buildVersionChecker() {
229  global $wgVersion;
230  // array to optionally specify more verbose error messages for
231  // missing abilities
232  $abilityErrors = [
233  'shell' => ( new ShellDisabledError() )->getMessage(),
234  ];
235 
236  return new VersionChecker(
237  $wgVersion,
238  PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION,
239  get_loaded_extensions(),
240  $this->getAbilities(),
241  $abilityErrors
242  );
243  }
244 
253  public function readFromQueue( array $queue ) {
254  $autoloadClasses = [];
255  $autoloadNamespaces = [];
256  $autoloaderPaths = [];
257  $processor = new ExtensionProcessor();
258  $versionChecker = $this->buildVersionChecker();
259  $extDependencies = [];
260  $incompatible = [];
261  $warnings = false;
262  foreach ( $queue as $path => $mtime ) {
263  $json = file_get_contents( $path );
264  if ( $json === false ) {
265  throw new Exception( "Unable to read $path, does it exist?" );
266  }
267  $info = json_decode( $json, /* $assoc = */ true );
268  if ( !is_array( $info ) ) {
269  throw new Exception( "$path is not a valid JSON file." );
270  }
271 
272  if ( !isset( $info['manifest_version'] ) ) {
273  wfDeprecated(
274  "{$info['name']}'s extension.json or skin.json does not have manifest_version",
275  '1.29'
276  );
277  $warnings = true;
278  // For backwards-compatability, assume a version of 1
279  $info['manifest_version'] = 1;
280  }
281  $version = $info['manifest_version'];
282  if ( $version < self::OLDEST_MANIFEST_VERSION || $version > self::MANIFEST_VERSION ) {
283  $incompatible[] = "$path: unsupported manifest_version: {$version}";
284  }
285 
286  $dir = dirname( $path );
287  if ( isset( $info['AutoloadClasses'] ) ) {
288  $autoload = $this->processAutoLoader( $dir, $info['AutoloadClasses'] );
289  $GLOBALS['wgAutoloadClasses'] += $autoload;
290  $autoloadClasses += $autoload;
291  }
292  if ( isset( $info['AutoloadNamespaces'] ) ) {
293  $autoloadNamespaces += $this->processAutoLoader( $dir, $info['AutoloadNamespaces'] );
294  AutoLoader::$psr4Namespaces += $autoloadNamespaces;
295  }
296 
297  // get all requirements/dependencies for this extension
298  $requires = $processor->getRequirements( $info );
299 
300  // validate the information needed and add the requirements
301  if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
302  $extDependencies[$info['name']] = $requires;
303  }
304 
305  // Get extra paths for later inclusion
306  $autoloaderPaths = array_merge( $autoloaderPaths,
307  $processor->getExtraAutoloaderPaths( $dir, $info ) );
308  // Compatible, read and extract info
309  $processor->extractInfo( $path, $info, $version );
310  }
311  $data = $processor->getExtractedInfo();
312  $data['warnings'] = $warnings;
313 
314  // check for incompatible extensions
315  $incompatible = array_merge(
316  $incompatible,
317  $versionChecker
318  ->setLoadedExtensionsAndSkins( $data['credits'] )
319  ->checkArray( $extDependencies )
320  );
321 
322  if ( $incompatible ) {
323  throw new ExtensionDependencyError( $incompatible );
324  }
325 
326  // Need to set this so we can += to it later
327  $data['globals']['wgAutoloadClasses'] = [];
328  $data['autoload'] = $autoloadClasses;
329  $data['autoloaderPaths'] = $autoloaderPaths;
330  $data['autoloaderNS'] = $autoloadNamespaces;
331  return $data;
332  }
333 
334  protected function exportExtractedData( array $info ) {
335  foreach ( $info['globals'] as $key => $val ) {
336  // If a merge strategy is set, read it and remove it from the value
337  // so it doesn't accidentally end up getting set.
338  if ( is_array( $val ) && isset( $val[self::MERGE_STRATEGY] ) ) {
339  $mergeStrategy = $val[self::MERGE_STRATEGY];
340  unset( $val[self::MERGE_STRATEGY] );
341  } else {
342  $mergeStrategy = 'array_merge';
343  }
344 
345  // Optimistic: If the global is not set, or is an empty array, replace it entirely.
346  // Will be O(1) performance.
347  if ( !array_key_exists( $key, $GLOBALS ) || ( is_array( $GLOBALS[$key] ) && !$GLOBALS[$key] ) ) {
348  $GLOBALS[$key] = $val;
349  continue;
350  }
351 
352  if ( !is_array( $GLOBALS[$key] ) || !is_array( $val ) ) {
353  // config setting that has already been overridden, don't set it
354  continue;
355  }
356 
357  switch ( $mergeStrategy ) {
358  case 'array_merge_recursive':
359  $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
360  break;
361  case 'array_replace_recursive':
362  $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
363  break;
364  case 'array_plus_2d':
365  $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
366  break;
367  case 'array_plus':
368  $GLOBALS[$key] += $val;
369  break;
370  case 'array_merge':
371  $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
372  break;
373  default:
374  throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
375  }
376  }
377 
378  if ( isset( $info['autoloaderNS'] ) ) {
379  AutoLoader::$psr4Namespaces += $info['autoloaderNS'];
380  }
381 
382  foreach ( $info['defines'] as $name => $val ) {
383  define( $name, $val );
384  }
385  foreach ( $info['autoloaderPaths'] as $path ) {
386  if ( file_exists( $path ) ) {
387  require_once $path;
388  }
389  }
390 
391  $this->loaded += $info['credits'];
392  if ( $info['attributes'] ) {
393  if ( !$this->attributes ) {
394  $this->attributes = $info['attributes'];
395  } else {
396  $this->attributes = array_merge_recursive( $this->attributes, $info['attributes'] );
397  }
398  }
399 
400  foreach ( $info['callbacks'] as $name => $cb ) {
401  if ( !is_callable( $cb ) ) {
402  if ( is_array( $cb ) ) {
403  $cb = '[ ' . implode( ', ', $cb ) . ' ]';
404  }
405  throw new UnexpectedValueException( "callback '$cb' is not callable" );
406  }
407  $cb( $info['credits'][$name] );
408  }
409  }
410 
419  public function load( $path ) {
420  $this->loadFromQueue(); // First clear the queue
421  $this->queue( $path );
422  $this->loadFromQueue();
423  }
424 
433  public function isLoaded( $name, $constraint = '*' ) {
434  $isLoaded = isset( $this->loaded[$name] );
435  if ( $constraint === '*' || !$isLoaded ) {
436  return $isLoaded;
437  }
438  // if a specific constraint is requested, but no version is set, throw an exception
439  if ( !isset( $this->loaded[$name]['version'] ) ) {
440  $msg = "{$name} does not expose its version, but an extension or a skin"
441  . " requires: {$constraint}.";
442  throw new LogicException( $msg );
443  }
444 
445  return SemVer::satisfies( $this->loaded[$name]['version'], $constraint );
446  }
447 
452  public function getAttribute( $name ) {
453  return $this->testAttributes[$name] ??
454  $this->attributes[$name] ?? [];
455  }
456 
465  public function setAttributeForTest( $name, array $value ) {
466  // @codeCoverageIgnoreStart
467  if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
468  throw new RuntimeException( __METHOD__ . ' can only be used in tests' );
469  }
470  // @codeCoverageIgnoreEnd
471  if ( isset( $this->testAttributes[$name] ) ) {
472  throw new Exception( "The attribute '$name' has already been overridden" );
473  }
474  $this->testAttributes[$name] = $value;
475  return new ScopedCallback( function () use ( $name ) {
476  unset( $this->testAttributes[$name] );
477  } );
478  }
479 
485  public function getAllThings() {
486  return $this->loaded;
487  }
488 
496  protected function processAutoLoader( $dir, array $files ) {
497  // Make paths absolute, relative to the JSON file
498  foreach ( $files as &$file ) {
499  $file = "$dir/$file";
500  }
501  return $files;
502  }
503 }
ObjectCache\newFromId
static newFromId( $id)
Create a new cache object of the specified type.
Definition: ObjectCache.php:122
ExtensionRegistry\isLoaded
isLoaded( $name, $constraint=' *')
Whether a thing has been loaded.
Definition: ExtensionRegistry.php:433
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:44
ExtensionRegistry\getQueue
getQueue()
Get the current load queue.
Definition: ExtensionRegistry.php:192
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
ExtensionRegistry\$finished
bool $finished
Whether we are done loading things.
Definition: ExtensionRegistry.php:72
ExtensionRegistry\MANIFEST_VERSION
const MANIFEST_VERSION
Version of the highest supported manifest version Note: Update MANIFEST_VERSION_MW_VERSION when chang...
Definition: ExtensionRegistry.php:28
ExtensionRegistry\queue
queue( $path)
Definition: ExtensionRegistry.php:109
EmptyBagOStuff
A BagOStuff object with no objects in it.
Definition: EmptyBagOStuff.php:29
wfArrayPlus2d
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
Definition: GlobalFunctions.php:3225
ExtensionDependencyError
Copyright (C) 2018 Kunal Mehta legoktm@member.fsf.org
Definition: ExtensionDependencyError.php:24
ObjectCache\detectLocalServerCache
static detectLocalServerCache()
Detects which local server cache library is present and returns a configuration for it.
Definition: ObjectCache.php:410
ExtensionRegistry\exportExtractedData
exportExtractedData(array $info)
Definition: ExtensionRegistry.php:334
ExtensionRegistry
ExtensionRegistry class.
Definition: ExtensionRegistry.php:17
$wgVersion
$wgVersion
MediaWiki version number.
Definition: DefaultSettings.php:75
ExtensionRegistry\getAllThings
getAllThings()
Get information about all things.
Definition: ExtensionRegistry.php:485
ExtensionRegistry\$loaded
array $loaded
Array of loaded things, keyed by name, values are credits information.
Definition: ExtensionRegistry.php:58
ExtensionRegistry\getAbilities
getAbilities()
Get the list of abilities and their values.
Definition: ExtensionRegistry.php:217
ExtensionRegistry\processAutoLoader
processAutoLoader( $dir, array $files)
Fully expand autoloader paths.
Definition: ExtensionRegistry.php:496
ExtensionRegistry\setAttributeForTest
setAttributeForTest( $name, array $value)
Force override the value of an attribute during tests.
Definition: ExtensionRegistry.php:465
ExtensionRegistry\clearQueue
clearQueue()
Clear the current load queue.
Definition: ExtensionRegistry.php:200
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
ExtensionRegistry\MERGE_STRATEGY
const MERGE_STRATEGY
Special key that defines the merge strategy.
Definition: ExtensionRegistry.php:51
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:98
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
ExtensionProcessor
Definition: ExtensionProcessor.php:3
ExtensionRegistry\CACHE_VERSION
const CACHE_VERSION
Bump whenever the registration cache needs resetting.
Definition: ExtensionRegistry.php:44
MWException
MediaWiki exception.
Definition: MWException.php:26
ExtensionRegistry\$attributes
array $attributes
Items in the JSON file that aren't being set as globals.
Definition: ExtensionRegistry.php:80
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1078
ExtensionRegistry\load
load( $path)
Loads and processes the given JSON file without delay.
Definition: ExtensionRegistry.php:419
$queue
$queue
Definition: mergeMessageFileList.php:159
ExtensionRegistry\MANIFEST_VERSION_MW_VERSION
const MANIFEST_VERSION_MW_VERSION
MediaWiki version constraint representing what the current highest MANIFEST_VERSION is supported in.
Definition: ExtensionRegistry.php:34
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
AutoLoader\$psr4Namespaces
static string[] $psr4Namespaces
Definition: AutoLoader.php:37
ExtensionRegistry\finish
finish()
After this is called, no more extensions can be loaded.
Definition: ExtensionRegistry.php:209
ExtensionRegistry\loadFromQueue
loadFromQueue()
Definition: ExtensionRegistry.php:133
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))
ExtensionRegistry\OLDEST_MANIFEST_VERSION
const OLDEST_MANIFEST_VERSION
Version of the oldest supported manifest version.
Definition: ExtensionRegistry.php:39
ExtensionRegistry\MEDIAWIKI_CORE
const MEDIAWIKI_CORE
"requires" key that applies to MediaWiki core/$wgVersion
Definition: ExtensionRegistry.php:22
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2162
ExtensionRegistry\readFromQueue
readFromQueue(array $queue)
Process a queue of extensions and return their extracted data.
Definition: ExtensionRegistry.php:253
$value
$value
Definition: styleTest.css.php:49
ExtensionRegistry\$queued
array $queued
List of paths that should be loaded.
Definition: ExtensionRegistry.php:65
ExtensionRegistry\$testAttributes
array $testAttributes
Attributes for testing.
Definition: ExtensionRegistry.php:87
$wgDevelopmentWarnings
$wgDevelopmentWarnings
If set to true MediaWiki will throw notices for some possible error conditions and for deprecated fun...
Definition: DefaultSettings.php:6329
MediaWiki\ShellDisabledError
Definition: ShellDisabledError.php:28
VersionChecker
Provides functions to check a set of extensions with dependencies against a set of loaded extensions ...
Definition: VersionChecker.php:32
$cache
$cache
Definition: mcc.php:33
ExtensionRegistry\buildVersionChecker
buildVersionChecker()
Queries information about the software environment and constructs an appropiate version checker.
Definition: ExtensionRegistry.php:228
$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
$wgExtensionInfoMTime
int bool $wgExtensionInfoMTime
When loading extensions through the extension registration system, this can be used to invalidate the...
Definition: DefaultSettings.php:2687
ExtensionRegistry\getAttribute
getAttribute( $name)
Definition: ExtensionRegistry.php:452
ExtensionRegistry\$instance
static ExtensionRegistry $instance
Definition: ExtensionRegistry.php:92
$GLOBALS
$GLOBALS['IP']
Definition: ComposerHookHandler.php:6