3 use Composer\Semver\Semver
;
6 * ExtensionRegistry class
8 * The Registry loads JSON files, and uses a Processor
9 * to extract information from them. It also registers
10 * classes with the autoloader.
14 class ExtensionRegistry
{
17 * "requires" key that applies to MediaWiki core/$wgVersion
19 const MEDIAWIKI_CORE
= 'MediaWiki';
22 * Version of the highest supported manifest version
23 * Note: Update MANIFEST_VERSION_MW_VERSION when changing this
25 const MANIFEST_VERSION
= 2;
28 * MediaWiki version constraint representing what the current
29 * highest MANIFEST_VERSION is supported in
31 const MANIFEST_VERSION_MW_VERSION
= '>= 1.29.0';
34 * Version of the oldest supported manifest version
36 const OLDEST_MANIFEST_VERSION
= 1;
39 * Bump whenever the registration cache needs resetting
41 const CACHE_VERSION
= 7;
44 * Special key that defines the merge strategy
48 const MERGE_STRATEGY
= '_merge_strategy';
51 * Array of loaded things, keyed by name, values are credits information
58 * List of paths that should be loaded
62 protected $queued = [];
65 * Whether we are done loading things
69 private $finished = false;
72 * Items in the JSON file that aren't being
77 protected $attributes = [];
80 * @var ExtensionRegistry
82 private static $instance;
86 * @return ExtensionRegistry
88 public static function getInstance() {
89 if ( self
::$instance === null ) {
90 self
::$instance = new self();
93 return self
::$instance;
97 * @param string $path Absolute path to the JSON file
99 public function queue( $path ) {
100 global $wgExtensionInfoMTime;
102 $mtime = $wgExtensionInfoMTime;
103 if ( $mtime === false ) {
104 if ( file_exists( $path ) ) {
105 $mtime = filemtime( $path );
107 throw new Exception( "$path does not exist!" );
109 // @codeCoverageIgnoreStart
110 if ( $mtime === false ) {
111 $err = error_get_last();
112 throw new Exception( "Couldn't stat $path: {$err['message']}" );
113 // @codeCoverageIgnoreEnd
116 $this->queued
[$path] = $mtime;
120 * @throws MWException If the queue is already marked as finished (no further things should
123 public function loadFromQueue() {
124 global $wgVersion, $wgDevelopmentWarnings;
125 if ( !$this->queued
) {
129 if ( $this->finished
) {
130 throw new MWException(
131 "The following paths tried to load late: "
132 . implode( ', ', array_keys( $this->queued
) )
136 // A few more things to vary the cache on
138 'registration' => self
::CACHE_VERSION
,
139 'mediawiki' => $wgVersion
142 // We use a try/catch because we don't want to fail here
143 // if $wgObjectCaches is not configured properly for APC setup
145 // Don't use MediaWikiServices here to prevent instantiating it before extensions have
147 $cacheId = ObjectCache
::detectLocalServerCache();
148 $cache = ObjectCache
::newFromId( $cacheId );
149 } catch ( InvalidArgumentException
$e ) {
150 $cache = new EmptyBagOStuff();
152 // See if this queue is in APC
153 $key = $cache->makeKey(
155 md5( json_encode( $this->queued +
$versions ) )
157 $data = $cache->get( $key );
159 $this->exportExtractedData( $data );
161 $data = $this->readFromQueue( $this->queued
);
162 $this->exportExtractedData( $data );
163 // Do this late since we don't want to extract it since we already
164 // did that, but it should be cached
165 $data['globals']['wgAutoloadClasses'] +
= $data['autoload'];
166 unset( $data['autoload'] );
167 if ( !( $data['warnings'] && $wgDevelopmentWarnings ) ) {
168 // If there were no warnings that were shown, cache it
169 $cache->set( $key, $data, 60 * 60 * 24 );
176 * Get the current load queue. Not intended to be used
177 * outside of the installer.
181 public function getQueue() {
182 return $this->queued
;
186 * Clear the current load queue. Not intended to be used
187 * outside of the installer.
189 public function clearQueue() {
194 * After this is called, no more extensions can be loaded
198 public function finish() {
199 $this->finished
= true;
203 * Process a queue of extensions and return their extracted data
205 * @param array $queue keys are filenames, values are ignored
206 * @return array extracted info
208 * @throws ExtensionDependencyError
210 public function readFromQueue( array $queue ) {
212 $autoloadClasses = [];
213 $autoloadNamespaces = [];
214 $autoloaderPaths = [];
215 $processor = new ExtensionProcessor();
216 $versionChecker = new VersionChecker( $wgVersion );
217 $extDependencies = [];
220 foreach ( $queue as $path => $mtime ) {
221 $json = file_get_contents( $path );
222 if ( $json === false ) {
223 throw new Exception( "Unable to read $path, does it exist?" );
225 $info = json_decode( $json, /* $assoc = */ true );
226 if ( !is_array( $info ) ) {
227 throw new Exception( "$path is not a valid JSON file." );
230 if ( !isset( $info['manifest_version'] ) ) {
232 "{$info['name']}'s extension.json or skin.json does not have manifest_version",
236 // For backwards-compatability, assume a version of 1
237 $info['manifest_version'] = 1;
239 $version = $info['manifest_version'];
240 if ( $version < self
::OLDEST_MANIFEST_VERSION ||
$version > self
::MANIFEST_VERSION
) {
241 $incompatible[] = "$path: unsupported manifest_version: {$version}";
244 $dir = dirname( $path );
245 if ( isset( $info['AutoloadClasses'] ) ) {
246 $autoload = $this->processAutoLoader( $dir, $info['AutoloadClasses'] );
247 $GLOBALS['wgAutoloadClasses'] +
= $autoload;
248 $autoloadClasses +
= $autoload;
250 if ( isset( $info['AutoloadNamespaces'] ) ) {
251 $autoloadNamespaces +
= $this->processAutoLoader( $dir, $info['AutoloadNamespaces'] );
252 AutoLoader
::$psr4Namespaces +
= $autoloadNamespaces;
255 // get all requirements/dependencies for this extension
256 $requires = $processor->getRequirements( $info );
258 // validate the information needed and add the requirements
259 if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
260 $extDependencies[$info['name']] = $requires;
263 // Get extra paths for later inclusion
264 $autoloaderPaths = array_merge( $autoloaderPaths,
265 $processor->getExtraAutoloaderPaths( $dir, $info ) );
266 // Compatible, read and extract info
267 $processor->extractInfo( $path, $info, $version );
269 $data = $processor->getExtractedInfo();
270 $data['warnings'] = $warnings;
272 // check for incompatible extensions
273 $incompatible = array_merge(
276 ->setLoadedExtensionsAndSkins( $data['credits'] )
277 ->checkArray( $extDependencies )
280 if ( $incompatible ) {
281 throw new ExtensionDependencyError( $incompatible );
284 // Need to set this so we can += to it later
285 $data['globals']['wgAutoloadClasses'] = [];
286 $data['autoload'] = $autoloadClasses;
287 $data['autoloaderPaths'] = $autoloaderPaths;
288 $data['autoloaderNS'] = $autoloadNamespaces;
292 protected function exportExtractedData( array $info ) {
293 foreach ( $info['globals'] as $key => $val ) {
294 // If a merge strategy is set, read it and remove it from the value
295 // so it doesn't accidentally end up getting set.
296 if ( is_array( $val ) && isset( $val[self
::MERGE_STRATEGY
] ) ) {
297 $mergeStrategy = $val[self
::MERGE_STRATEGY
];
298 unset( $val[self
::MERGE_STRATEGY
] );
300 $mergeStrategy = 'array_merge';
303 // Optimistic: If the global is not set, or is an empty array, replace it entirely.
304 // Will be O(1) performance.
305 if ( !array_key_exists( $key, $GLOBALS ) ||
( is_array( $GLOBALS[$key] ) && !$GLOBALS[$key] ) ) {
306 $GLOBALS[$key] = $val;
310 if ( !is_array( $GLOBALS[$key] ) ||
!is_array( $val ) ) {
311 // config setting that has already been overridden, don't set it
315 switch ( $mergeStrategy ) {
316 case 'array_merge_recursive':
317 $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
319 case 'array_replace_recursive':
320 $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
322 case 'array_plus_2d':
323 $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
326 $GLOBALS[$key] +
= $val;
329 $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
332 throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
336 if ( isset( $info['autoloaderNS'] ) ) {
337 AutoLoader
::$psr4Namespaces +
= $info['autoloaderNS'];
340 foreach ( $info['defines'] as $name => $val ) {
341 define( $name, $val );
343 foreach ( $info['autoloaderPaths'] as $path ) {
344 if ( file_exists( $path ) ) {
349 $this->loaded +
= $info['credits'];
350 if ( $info['attributes'] ) {
351 if ( !$this->attributes
) {
352 $this->attributes
= $info['attributes'];
354 $this->attributes
= array_merge_recursive( $this->attributes
, $info['attributes'] );
358 foreach ( $info['callbacks'] as $name => $cb ) {
359 if ( !is_callable( $cb ) ) {
360 if ( is_array( $cb ) ) {
361 $cb = '[ ' . implode( ', ', $cb ) . ' ]';
363 throw new UnexpectedValueException( "callback '$cb' is not callable" );
365 call_user_func( $cb, $info['credits'][$name] );
370 * Loads and processes the given JSON file without delay
372 * If some extensions are already queued, this will load
375 * @param string $path Absolute path to the JSON file
377 public function load( $path ) {
378 $this->loadFromQueue(); // First clear the queue
379 $this->queue( $path );
380 $this->loadFromQueue();
384 * Whether a thing has been loaded
385 * @param string $name
386 * @param string $constraint The required version constraint for this dependency
387 * @throws LogicException if a specific contraint is asked for,
388 * but the extension isn't versioned
391 public function isLoaded( $name, $constraint = '*' ) {
392 $isLoaded = isset( $this->loaded
[$name] );
393 if ( $constraint === '*' ||
!$isLoaded ) {
396 // if a specific constraint is requested, but no version is set, throw an exception
397 if ( !isset( $this->loaded
[$name]['version'] ) ) {
398 $msg = "{$name} does not expose its version, but an extension or a skin"
399 . " requires: {$constraint}.";
400 throw new LogicException( $msg );
403 return SemVer
::satisfies( $this->loaded
[$name]['version'], $constraint );
407 * @param string $name
410 public function getAttribute( $name ) {
411 if ( isset( $this->attributes
[$name] ) ) {
412 return $this->attributes
[$name];
419 * Get information about all things
423 public function getAllThings() {
424 return $this->loaded
;
428 * Fully expand autoloader paths
431 * @param array $files
434 protected function processAutoLoader( $dir, array $files ) {
435 // Make paths absolute, relative to the JSON file
436 foreach ( $files as &$file ) {
437 $file = "$dir/$file";