3 use Composer\Semver\Semver
;
4 use Wikimedia\ScopedCallback
;
5 use MediaWiki\Shell\Shell
;
6 use MediaWiki\ShellDisabledError
;
9 * ExtensionRegistry class
11 * The Registry loads JSON files, and uses a Processor
12 * to extract information from them. It also registers
13 * classes with the autoloader.
17 class ExtensionRegistry
{
20 * "requires" key that applies to MediaWiki core/$wgVersion
22 const MEDIAWIKI_CORE
= 'MediaWiki';
25 * Version of the highest supported manifest version
26 * Note: Update MANIFEST_VERSION_MW_VERSION when changing this
28 const MANIFEST_VERSION
= 2;
31 * MediaWiki version constraint representing what the current
32 * highest MANIFEST_VERSION is supported in
34 const MANIFEST_VERSION_MW_VERSION
= '>= 1.29.0';
37 * Version of the oldest supported manifest version
39 const OLDEST_MANIFEST_VERSION
= 1;
42 * Bump whenever the registration cache needs resetting
44 const CACHE_VERSION
= 7;
47 * Special key that defines the merge strategy
51 const MERGE_STRATEGY
= '_merge_strategy';
54 * Array of loaded things, keyed by name, values are credits information
61 * List of paths that should be loaded
65 protected $queued = [];
68 * Whether we are done loading things
72 private $finished = false;
75 * Items in the JSON file that aren't being
80 protected $attributes = [];
83 * Attributes for testing
87 protected $testAttributes = [];
90 * @var ExtensionRegistry
92 private static $instance;
96 * @return ExtensionRegistry
98 public static function getInstance() {
99 if ( self
::$instance === null ) {
100 self
::$instance = new self();
103 return self
::$instance;
107 * @param string $path Absolute path to the JSON file
109 public function queue( $path ) {
110 global $wgExtensionInfoMTime;
112 $mtime = $wgExtensionInfoMTime;
113 if ( $mtime === false ) {
114 if ( file_exists( $path ) ) {
115 $mtime = filemtime( $path );
117 throw new Exception( "$path does not exist!" );
119 // @codeCoverageIgnoreStart
120 if ( $mtime === false ) {
121 $err = error_get_last();
122 throw new Exception( "Couldn't stat $path: {$err['message']}" );
123 // @codeCoverageIgnoreEnd
126 $this->queued
[$path] = $mtime;
130 * @throws MWException If the queue is already marked as finished (no further things should
133 public function loadFromQueue() {
134 global $wgVersion, $wgDevelopmentWarnings;
135 if ( !$this->queued
) {
139 if ( $this->finished
) {
140 throw new MWException(
141 "The following paths tried to load late: "
142 . implode( ', ', array_keys( $this->queued
) )
146 // A few more things to vary the cache on
148 'registration' => self
::CACHE_VERSION
,
149 'mediawiki' => $wgVersion,
150 'abilities' => $this->getAbilities(),
153 // We use a try/catch because we don't want to fail here
154 // if $wgObjectCaches is not configured properly for APC setup
156 // Don't use MediaWikiServices here to prevent instantiating it before extensions have
158 $cacheId = ObjectCache
::detectLocalServerCache();
159 $cache = ObjectCache
::newFromId( $cacheId );
160 } catch ( InvalidArgumentException
$e ) {
161 $cache = new EmptyBagOStuff();
163 // See if this queue is in APC
164 $key = $cache->makeKey(
166 md5( json_encode( $this->queued +
$versions ) )
168 $data = $cache->get( $key );
170 $this->exportExtractedData( $data );
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 );
187 * Get the current load queue. Not intended to be used
188 * outside of the installer.
192 public function getQueue() {
193 return $this->queued
;
197 * Clear the current load queue. Not intended to be used
198 * outside of the installer.
200 public function clearQueue() {
205 * After this is called, no more extensions can be loaded
209 public function finish() {
210 $this->finished
= true;
214 * Get the list of abilities and their values
217 private function getAbilities() {
219 'shell' => !Shell
::isDisabled(),
224 * Queries information about the software environment and constructs an appropiate version checker
226 * @return VersionChecker
228 private function buildVersionChecker() {
230 // array to optionally specify more verbose error messages for
233 'shell' => ( new ShellDisabledError() )->getMessage(),
236 return new VersionChecker(
238 PHP_MAJOR_VERSION
. '.' . PHP_MINOR_VERSION
. '.' . PHP_RELEASE_VERSION
,
239 get_loaded_extensions(),
240 $this->getAbilities(),
246 * Process a queue of extensions and return their extracted data
248 * @param array $queue keys are filenames, values are ignored
249 * @return array extracted info
251 * @throws ExtensionDependencyError
253 public function readFromQueue( array $queue ) {
254 $autoloadClasses = [];
255 $autoloadNamespaces = [];
256 $autoloaderPaths = [];
257 $processor = new ExtensionProcessor();
258 $versionChecker = $this->buildVersionChecker();
259 $extDependencies = [];
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?" );
267 $info = json_decode( $json, /* $assoc = */ true );
268 if ( !is_array( $info ) ) {
269 throw new Exception( "$path is not a valid JSON file." );
272 if ( !isset( $info['manifest_version'] ) ) {
274 "{$info['name']}'s extension.json or skin.json does not have manifest_version",
278 // For backwards-compatability, assume a version of 1
279 $info['manifest_version'] = 1;
281 $version = $info['manifest_version'];
282 if ( $version < self
::OLDEST_MANIFEST_VERSION ||
$version > self
::MANIFEST_VERSION
) {
283 $incompatible[] = "$path: unsupported manifest_version: {$version}";
286 $dir = dirname( $path );
287 if ( isset( $info['AutoloadClasses'] ) ) {
288 $autoload = $this->processAutoLoader( $dir, $info['AutoloadClasses'] );
289 $GLOBALS['wgAutoloadClasses'] +
= $autoload;
290 $autoloadClasses +
= $autoload;
292 if ( isset( $info['AutoloadNamespaces'] ) ) {
293 $autoloadNamespaces +
= $this->processAutoLoader( $dir, $info['AutoloadNamespaces'] );
294 AutoLoader
::$psr4Namespaces +
= $autoloadNamespaces;
297 // get all requirements/dependencies for this extension
298 $requires = $processor->getRequirements( $info );
300 // validate the information needed and add the requirements
301 if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
302 $extDependencies[$info['name']] = $requires;
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 );
311 $data = $processor->getExtractedInfo();
312 $data['warnings'] = $warnings;
314 // check for incompatible extensions
315 $incompatible = array_merge(
318 ->setLoadedExtensionsAndSkins( $data['credits'] )
319 ->checkArray( $extDependencies )
322 if ( $incompatible ) {
323 throw new ExtensionDependencyError( $incompatible );
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;
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
] );
342 $mergeStrategy = 'array_merge';
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;
352 if ( !is_array( $GLOBALS[$key] ) ||
!is_array( $val ) ) {
353 // config setting that has already been overridden, don't set it
357 switch ( $mergeStrategy ) {
358 case 'array_merge_recursive':
359 $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
361 case 'array_replace_recursive':
362 $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
364 case 'array_plus_2d':
365 $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
368 $GLOBALS[$key] +
= $val;
371 $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
374 throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
378 if ( isset( $info['autoloaderNS'] ) ) {
379 AutoLoader
::$psr4Namespaces +
= $info['autoloaderNS'];
382 foreach ( $info['defines'] as $name => $val ) {
383 define( $name, $val );
385 foreach ( $info['autoloaderPaths'] as $path ) {
386 if ( file_exists( $path ) ) {
391 $this->loaded +
= $info['credits'];
392 if ( $info['attributes'] ) {
393 if ( !$this->attributes
) {
394 $this->attributes
= $info['attributes'];
396 $this->attributes
= array_merge_recursive( $this->attributes
, $info['attributes'] );
400 foreach ( $info['callbacks'] as $name => $cb ) {
401 if ( !is_callable( $cb ) ) {
402 if ( is_array( $cb ) ) {
403 $cb = '[ ' . implode( ', ', $cb ) . ' ]';
405 throw new UnexpectedValueException( "callback '$cb' is not callable" );
407 $cb( $info['credits'][$name] );
412 * Loads and processes the given JSON file without delay
414 * If some extensions are already queued, this will load
416 * TODO: Remove in MediaWiki 1.35
417 * @deprecated since 1.34, use ExtensionRegistry->queue() instead
418 * @param string $path Absolute path to the JSON file
420 public function load( $path ) {
421 wfDeprecated( __METHOD__
, '1.34' );
422 $this->loadFromQueue(); // First clear the queue
423 $this->queue( $path );
424 $this->loadFromQueue();
428 * Whether a thing has been loaded
429 * @param string $name
430 * @param string $constraint The required version constraint for this dependency
431 * @throws LogicException if a specific contraint is asked for,
432 * but the extension isn't versioned
435 public function isLoaded( $name, $constraint = '*' ) {
436 $isLoaded = isset( $this->loaded
[$name] );
437 if ( $constraint === '*' ||
!$isLoaded ) {
440 // if a specific constraint is requested, but no version is set, throw an exception
441 if ( !isset( $this->loaded
[$name]['version'] ) ) {
442 $msg = "{$name} does not expose its version, but an extension or a skin"
443 . " requires: {$constraint}.";
444 throw new LogicException( $msg );
447 return SemVer
::satisfies( $this->loaded
[$name]['version'], $constraint );
451 * @param string $name
454 public function getAttribute( $name ) {
455 return $this->testAttributes
[$name] ??
456 $this->attributes
[$name] ??
[];
460 * Force override the value of an attribute during tests
462 * @param string $name Name of attribute to override
463 * @param array $value Value to set
464 * @return ScopedCallback to reset
467 public function setAttributeForTest( $name, array $value ) {
468 // @codeCoverageIgnoreStart
469 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
470 throw new RuntimeException( __METHOD__
. ' can only be used in tests' );
472 // @codeCoverageIgnoreEnd
473 if ( isset( $this->testAttributes
[$name] ) ) {
474 throw new Exception( "The attribute '$name' has already been overridden" );
476 $this->testAttributes
[$name] = $value;
477 return new ScopedCallback( function () use ( $name ) {
478 unset( $this->testAttributes
[$name] );
483 * Get information about all things
487 public function getAllThings() {
488 return $this->loaded
;
492 * Fully expand autoloader paths
495 * @param array $files
498 protected function processAutoLoader( $dir, array $files ) {
499 // Make paths absolute, relative to the JSON file
500 foreach ( $files as &$file ) {
501 $file = "$dir/$file";