3 use Composer\Semver\Semver
;
4 use Wikimedia\ScopedCallback
;
7 * ExtensionRegistry class
9 * The Registry loads JSON files, and uses a Processor
10 * to extract information from them. It also registers
11 * classes with the autoloader.
15 class ExtensionRegistry
{
18 * "requires" key that applies to MediaWiki core/$wgVersion
20 const MEDIAWIKI_CORE
= 'MediaWiki';
23 * Version of the highest supported manifest version
24 * Note: Update MANIFEST_VERSION_MW_VERSION when changing this
26 const MANIFEST_VERSION
= 2;
29 * MediaWiki version constraint representing what the current
30 * highest MANIFEST_VERSION is supported in
32 const MANIFEST_VERSION_MW_VERSION
= '>= 1.29.0';
35 * Version of the oldest supported manifest version
37 const OLDEST_MANIFEST_VERSION
= 1;
40 * Bump whenever the registration cache needs resetting
42 const CACHE_VERSION
= 7;
45 * Special key that defines the merge strategy
49 const MERGE_STRATEGY
= '_merge_strategy';
52 * Array of loaded things, keyed by name, values are credits information
59 * List of paths that should be loaded
63 protected $queued = [];
66 * Whether we are done loading things
70 private $finished = false;
73 * Items in the JSON file that aren't being
78 protected $attributes = [];
81 * Attributes for testing
85 protected $testAttributes = [];
88 * @var ExtensionRegistry
90 private static $instance;
94 * @return ExtensionRegistry
96 public static function getInstance() {
97 if ( self
::$instance === null ) {
98 self
::$instance = new self();
101 return self
::$instance;
105 * @param string $path Absolute path to the JSON file
107 public function queue( $path ) {
108 global $wgExtensionInfoMTime;
110 $mtime = $wgExtensionInfoMTime;
111 if ( $mtime === false ) {
112 if ( file_exists( $path ) ) {
113 $mtime = filemtime( $path );
115 throw new Exception( "$path does not exist!" );
117 // @codeCoverageIgnoreStart
118 if ( $mtime === false ) {
119 $err = error_get_last();
120 throw new Exception( "Couldn't stat $path: {$err['message']}" );
121 // @codeCoverageIgnoreEnd
124 $this->queued
[$path] = $mtime;
128 * @throws MWException If the queue is already marked as finished (no further things should
131 public function loadFromQueue() {
132 global $wgVersion, $wgDevelopmentWarnings;
133 if ( !$this->queued
) {
137 if ( $this->finished
) {
138 throw new MWException(
139 "The following paths tried to load late: "
140 . implode( ', ', array_keys( $this->queued
) )
144 // A few more things to vary the cache on
146 'registration' => self
::CACHE_VERSION
,
147 'mediawiki' => $wgVersion
150 // We use a try/catch because we don't want to fail here
151 // if $wgObjectCaches is not configured properly for APC setup
153 // Don't use MediaWikiServices here to prevent instantiating it before extensions have
155 $cacheId = ObjectCache
::detectLocalServerCache();
156 $cache = ObjectCache
::newFromId( $cacheId );
157 } catch ( InvalidArgumentException
$e ) {
158 $cache = new EmptyBagOStuff();
160 // See if this queue is in APC
161 $key = $cache->makeKey(
163 md5( json_encode( $this->queued +
$versions ) )
165 $data = $cache->get( $key );
167 $this->exportExtractedData( $data );
169 $data = $this->readFromQueue( $this->queued
);
170 $this->exportExtractedData( $data );
171 // Do this late since we don't want to extract it since we already
172 // did that, but it should be cached
173 $data['globals']['wgAutoloadClasses'] +
= $data['autoload'];
174 unset( $data['autoload'] );
175 if ( !( $data['warnings'] && $wgDevelopmentWarnings ) ) {
176 // If there were no warnings that were shown, cache it
177 $cache->set( $key, $data, 60 * 60 * 24 );
184 * Get the current load queue. Not intended to be used
185 * outside of the installer.
189 public function getQueue() {
190 return $this->queued
;
194 * Clear the current load queue. Not intended to be used
195 * outside of the installer.
197 public function clearQueue() {
202 * After this is called, no more extensions can be loaded
206 public function finish() {
207 $this->finished
= true;
211 * Process a queue of extensions and return their extracted data
213 * @param array $queue keys are filenames, values are ignored
214 * @return array extracted info
216 * @throws ExtensionDependencyError
218 public function readFromQueue( array $queue ) {
220 $autoloadClasses = [];
221 $autoloadNamespaces = [];
222 $autoloaderPaths = [];
223 $processor = new ExtensionProcessor();
224 $versionChecker = new VersionChecker(
226 PHP_MAJOR_VERSION
. '.' . PHP_MINOR_VERSION
. '.' . PHP_RELEASE_VERSION
,
227 get_loaded_extensions()
229 $extDependencies = [];
232 foreach ( $queue as $path => $mtime ) {
233 $json = file_get_contents( $path );
234 if ( $json === false ) {
235 throw new Exception( "Unable to read $path, does it exist?" );
237 $info = json_decode( $json, /* $assoc = */ true );
238 if ( !is_array( $info ) ) {
239 throw new Exception( "$path is not a valid JSON file." );
242 if ( !isset( $info['manifest_version'] ) ) {
244 "{$info['name']}'s extension.json or skin.json does not have manifest_version",
248 // For backwards-compatability, assume a version of 1
249 $info['manifest_version'] = 1;
251 $version = $info['manifest_version'];
252 if ( $version < self
::OLDEST_MANIFEST_VERSION ||
$version > self
::MANIFEST_VERSION
) {
253 $incompatible[] = "$path: unsupported manifest_version: {$version}";
256 $dir = dirname( $path );
257 if ( isset( $info['AutoloadClasses'] ) ) {
258 $autoload = $this->processAutoLoader( $dir, $info['AutoloadClasses'] );
259 $GLOBALS['wgAutoloadClasses'] +
= $autoload;
260 $autoloadClasses +
= $autoload;
262 if ( isset( $info['AutoloadNamespaces'] ) ) {
263 $autoloadNamespaces +
= $this->processAutoLoader( $dir, $info['AutoloadNamespaces'] );
264 AutoLoader
::$psr4Namespaces +
= $autoloadNamespaces;
267 // get all requirements/dependencies for this extension
268 $requires = $processor->getRequirements( $info );
270 // validate the information needed and add the requirements
271 if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
272 $extDependencies[$info['name']] = $requires;
275 // Get extra paths for later inclusion
276 $autoloaderPaths = array_merge( $autoloaderPaths,
277 $processor->getExtraAutoloaderPaths( $dir, $info ) );
278 // Compatible, read and extract info
279 $processor->extractInfo( $path, $info, $version );
281 $data = $processor->getExtractedInfo();
282 $data['warnings'] = $warnings;
284 // check for incompatible extensions
285 $incompatible = array_merge(
288 ->setLoadedExtensionsAndSkins( $data['credits'] )
289 ->checkArray( $extDependencies )
292 if ( $incompatible ) {
293 throw new ExtensionDependencyError( $incompatible );
296 // Need to set this so we can += to it later
297 $data['globals']['wgAutoloadClasses'] = [];
298 $data['autoload'] = $autoloadClasses;
299 $data['autoloaderPaths'] = $autoloaderPaths;
300 $data['autoloaderNS'] = $autoloadNamespaces;
304 protected function exportExtractedData( array $info ) {
305 foreach ( $info['globals'] as $key => $val ) {
306 // If a merge strategy is set, read it and remove it from the value
307 // so it doesn't accidentally end up getting set.
308 if ( is_array( $val ) && isset( $val[self
::MERGE_STRATEGY
] ) ) {
309 $mergeStrategy = $val[self
::MERGE_STRATEGY
];
310 unset( $val[self
::MERGE_STRATEGY
] );
312 $mergeStrategy = 'array_merge';
315 // Optimistic: If the global is not set, or is an empty array, replace it entirely.
316 // Will be O(1) performance.
317 if ( !array_key_exists( $key, $GLOBALS ) ||
( is_array( $GLOBALS[$key] ) && !$GLOBALS[$key] ) ) {
318 $GLOBALS[$key] = $val;
322 if ( !is_array( $GLOBALS[$key] ) ||
!is_array( $val ) ) {
323 // config setting that has already been overridden, don't set it
327 switch ( $mergeStrategy ) {
328 case 'array_merge_recursive':
329 $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
331 case 'array_replace_recursive':
332 $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
334 case 'array_plus_2d':
335 $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
338 $GLOBALS[$key] +
= $val;
341 $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
344 throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
348 if ( isset( $info['autoloaderNS'] ) ) {
349 AutoLoader
::$psr4Namespaces +
= $info['autoloaderNS'];
352 foreach ( $info['defines'] as $name => $val ) {
353 define( $name, $val );
355 foreach ( $info['autoloaderPaths'] as $path ) {
356 if ( file_exists( $path ) ) {
361 $this->loaded +
= $info['credits'];
362 if ( $info['attributes'] ) {
363 if ( !$this->attributes
) {
364 $this->attributes
= $info['attributes'];
366 $this->attributes
= array_merge_recursive( $this->attributes
, $info['attributes'] );
370 foreach ( $info['callbacks'] as $name => $cb ) {
371 if ( !is_callable( $cb ) ) {
372 if ( is_array( $cb ) ) {
373 $cb = '[ ' . implode( ', ', $cb ) . ' ]';
375 throw new UnexpectedValueException( "callback '$cb' is not callable" );
377 $cb( $info['credits'][$name] );
382 * Loads and processes the given JSON file without delay
384 * If some extensions are already queued, this will load
387 * @param string $path Absolute path to the JSON file
389 public function load( $path ) {
390 $this->loadFromQueue(); // First clear the queue
391 $this->queue( $path );
392 $this->loadFromQueue();
396 * Whether a thing has been loaded
397 * @param string $name
398 * @param string $constraint The required version constraint for this dependency
399 * @throws LogicException if a specific contraint is asked for,
400 * but the extension isn't versioned
403 public function isLoaded( $name, $constraint = '*' ) {
404 $isLoaded = isset( $this->loaded
[$name] );
405 if ( $constraint === '*' ||
!$isLoaded ) {
408 // if a specific constraint is requested, but no version is set, throw an exception
409 if ( !isset( $this->loaded
[$name]['version'] ) ) {
410 $msg = "{$name} does not expose its version, but an extension or a skin"
411 . " requires: {$constraint}.";
412 throw new LogicException( $msg );
415 return SemVer
::satisfies( $this->loaded
[$name]['version'], $constraint );
419 * @param string $name
422 public function getAttribute( $name ) {
423 return $this->testAttributes
[$name] ??
424 $this->attributes
[$name] ??
[];
428 * Force override the value of an attribute during tests
430 * @param string $name Name of attribute to override
431 * @param array $value Value to set
432 * @return ScopedCallback to reset
435 public function setAttributeForTest( $name, array $value ) {
436 // @codeCoverageIgnoreStart
437 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
438 throw new RuntimeException( __METHOD__
. ' can only be used in tests' );
440 // @codeCoverageIgnoreEnd
441 if ( isset( $this->testAttributes
[$name] ) ) {
442 throw new Exception( "The attribute '$name' has already been overridden" );
444 $this->testAttributes
[$name] = $value;
445 return new ScopedCallback( function () use ( $name ) {
446 unset( $this->testAttributes
[$name] );
451 * Get information about all things
455 public function getAllThings() {
456 return $this->loaded
;
460 * Fully expand autoloader paths
463 * @param array $files
466 protected function processAutoLoader( $dir, array $files ) {
467 // Make paths absolute, relative to the JSON file
468 foreach ( $files as &$file ) {
469 $file = "$dir/$file";