Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[lhc/web/wiklou.git] / includes / registration / ExtensionRegistry.php
1 <?php
2
3 use Composer\Semver\Semver;
4 use Wikimedia\ScopedCallback;
5 use MediaWiki\Shell\Shell;
6 use MediaWiki\ShellDisabledError;
7
8 /**
9 * ExtensionRegistry class
10 *
11 * The Registry loads JSON files, and uses a Processor
12 * to extract information from them. It also registers
13 * classes with the autoloader.
14 *
15 * @since 1.25
16 */
17 class ExtensionRegistry {
18
19 /**
20 * "requires" key that applies to MediaWiki core/$wgVersion
21 */
22 const MEDIAWIKI_CORE = 'MediaWiki';
23
24 /**
25 * Version of the highest supported manifest version
26 * Note: Update MANIFEST_VERSION_MW_VERSION when changing this
27 */
28 const MANIFEST_VERSION = 2;
29
30 /**
31 * MediaWiki version constraint representing what the current
32 * highest MANIFEST_VERSION is supported in
33 */
34 const MANIFEST_VERSION_MW_VERSION = '>= 1.29.0';
35
36 /**
37 * Version of the oldest supported manifest version
38 */
39 const OLDEST_MANIFEST_VERSION = 1;
40
41 /**
42 * Bump whenever the registration cache needs resetting
43 */
44 const CACHE_VERSION = 7;
45
46 /**
47 * Special key that defines the merge strategy
48 *
49 * @since 1.26
50 */
51 const MERGE_STRATEGY = '_merge_strategy';
52
53 /**
54 * Array of loaded things, keyed by name, values are credits information
55 *
56 * @var array
57 */
58 private $loaded = [];
59
60 /**
61 * List of paths that should be loaded
62 *
63 * @var array
64 */
65 protected $queued = [];
66
67 /**
68 * Whether we are done loading things
69 *
70 * @var bool
71 */
72 private $finished = false;
73
74 /**
75 * Items in the JSON file that aren't being
76 * set as globals
77 *
78 * @var array
79 */
80 protected $attributes = [];
81
82 /**
83 * Attributes for testing
84 *
85 * @var array
86 */
87 protected $testAttributes = [];
88
89 /**
90 * Whether to check dev-requires
91 *
92 * @var bool
93 */
94 protected $checkDev = false;
95
96 /**
97 * @var ExtensionRegistry
98 */
99 private static $instance;
100
101 /**
102 * @codeCoverageIgnore
103 * @return ExtensionRegistry
104 */
105 public static function getInstance() {
106 if ( self::$instance === null ) {
107 self::$instance = new self();
108 }
109
110 return self::$instance;
111 }
112
113 /**
114 * @since 1.34
115 * @param bool $check
116 */
117 public function setCheckDevRequires( $check ) {
118 $this->checkDev = $check;
119 }
120
121 /**
122 * @param string $path Absolute path to the JSON file
123 */
124 public function queue( $path ) {
125 global $wgExtensionInfoMTime;
126
127 $mtime = $wgExtensionInfoMTime;
128 if ( $mtime === false ) {
129 if ( file_exists( $path ) ) {
130 $mtime = filemtime( $path );
131 } else {
132 throw new Exception( "$path does not exist!" );
133 }
134 // @codeCoverageIgnoreStart
135 if ( $mtime === false ) {
136 $err = error_get_last();
137 throw new Exception( "Couldn't stat $path: {$err['message']}" );
138 // @codeCoverageIgnoreEnd
139 }
140 }
141 $this->queued[$path] = $mtime;
142 }
143
144 /**
145 * @throws MWException If the queue is already marked as finished (no further things should
146 * be loaded then).
147 */
148 public function loadFromQueue() {
149 global $wgVersion, $wgDevelopmentWarnings;
150 if ( !$this->queued ) {
151 return;
152 }
153
154 if ( $this->finished ) {
155 throw new MWException(
156 "The following paths tried to load late: "
157 . implode( ', ', array_keys( $this->queued ) )
158 );
159 }
160
161 // A few more things to vary the cache on
162 $versions = [
163 'registration' => self::CACHE_VERSION,
164 'mediawiki' => $wgVersion,
165 'abilities' => $this->getAbilities(),
166 'checkDev' => $this->checkDev,
167 ];
168
169 // We use a try/catch because we don't want to fail here
170 // if $wgObjectCaches is not configured properly for APC setup
171 try {
172 // Don't use MediaWikiServices here to prevent instantiating it before extensions have
173 // been loaded
174 $cacheId = ObjectCache::detectLocalServerCache();
175 $cache = ObjectCache::newFromId( $cacheId );
176 } catch ( InvalidArgumentException $e ) {
177 $cache = new EmptyBagOStuff();
178 }
179 // See if this queue is in APC
180 $key = $cache->makeKey(
181 'registration',
182 md5( json_encode( $this->queued + $versions ) )
183 );
184 $data = $cache->get( $key );
185 if ( $data ) {
186 $this->exportExtractedData( $data );
187 } else {
188 $data = $this->readFromQueue( $this->queued );
189 $this->exportExtractedData( $data );
190 // Do this late since we don't want to extract it since we already
191 // did that, but it should be cached
192 $data['globals']['wgAutoloadClasses'] += $data['autoload'];
193 unset( $data['autoload'] );
194 if ( !( $data['warnings'] && $wgDevelopmentWarnings ) ) {
195 // If there were no warnings that were shown, cache it
196 $cache->set( $key, $data, 60 * 60 * 24 );
197 }
198 }
199 $this->queued = [];
200 }
201
202 /**
203 * Get the current load queue. Not intended to be used
204 * outside of the installer.
205 *
206 * @return array
207 */
208 public function getQueue() {
209 return $this->queued;
210 }
211
212 /**
213 * Clear the current load queue. Not intended to be used
214 * outside of the installer.
215 */
216 public function clearQueue() {
217 $this->queued = [];
218 }
219
220 /**
221 * After this is called, no more extensions can be loaded
222 *
223 * @since 1.29
224 */
225 public function finish() {
226 $this->finished = true;
227 }
228
229 /**
230 * Get the list of abilities and their values
231 * @return bool[]
232 */
233 private function getAbilities() {
234 return [
235 'shell' => !Shell::isDisabled(),
236 ];
237 }
238
239 /**
240 * Queries information about the software environment and constructs an appropiate version checker
241 *
242 * @return VersionChecker
243 */
244 private function buildVersionChecker() {
245 global $wgVersion;
246 // array to optionally specify more verbose error messages for
247 // missing abilities
248 $abilityErrors = [
249 'shell' => ( new ShellDisabledError() )->getMessage(),
250 ];
251
252 return new VersionChecker(
253 $wgVersion,
254 PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION,
255 get_loaded_extensions(),
256 $this->getAbilities(),
257 $abilityErrors
258 );
259 }
260
261 /**
262 * Process a queue of extensions and return their extracted data
263 *
264 * @param array $queue keys are filenames, values are ignored
265 * @return array extracted info
266 * @throws Exception
267 * @throws ExtensionDependencyError
268 */
269 public function readFromQueue( array $queue ) {
270 $autoloadClasses = [];
271 $autoloadNamespaces = [];
272 $autoloaderPaths = [];
273 $processor = new ExtensionProcessor();
274 $versionChecker = $this->buildVersionChecker();
275 $extDependencies = [];
276 $incompatible = [];
277 $warnings = false;
278 foreach ( $queue as $path => $mtime ) {
279 $json = file_get_contents( $path );
280 if ( $json === false ) {
281 throw new Exception( "Unable to read $path, does it exist?" );
282 }
283 $info = json_decode( $json, /* $assoc = */ true );
284 if ( !is_array( $info ) ) {
285 throw new Exception( "$path is not a valid JSON file." );
286 }
287
288 if ( !isset( $info['manifest_version'] ) ) {
289 wfDeprecated(
290 "{$info['name']}'s extension.json or skin.json does not have manifest_version",
291 '1.29'
292 );
293 $warnings = true;
294 // For backwards-compatability, assume a version of 1
295 $info['manifest_version'] = 1;
296 }
297 $version = $info['manifest_version'];
298 if ( $version < self::OLDEST_MANIFEST_VERSION || $version > self::MANIFEST_VERSION ) {
299 $incompatible[] = "$path: unsupported manifest_version: {$version}";
300 }
301
302 $dir = dirname( $path );
303 self::exportAutoloadClassesAndNamespaces(
304 $dir,
305 $info,
306 $autoloadClasses,
307 $autoloadNamespaces
308 );
309
310 if ( isset( $info['AutoloadClasses'] ) ) {
311 $autoload = $this->processAutoLoader( $dir, $info['AutoloadClasses'] );
312 $GLOBALS['wgAutoloadClasses'] += $autoload;
313 $autoloadClasses += $autoload;
314 }
315 if ( isset( $info['AutoloadNamespaces'] ) ) {
316 $autoloadNamespaces += $this->processAutoLoader( $dir, $info['AutoloadNamespaces'] );
317 AutoLoader::$psr4Namespaces += $autoloadNamespaces;
318 }
319
320 // get all requirements/dependencies for this extension
321 $requires = $processor->getRequirements( $info, $this->checkDev );
322
323 // validate the information needed and add the requirements
324 if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
325 $extDependencies[$info['name']] = $requires;
326 }
327
328 // Get extra paths for later inclusion
329 $autoloaderPaths = array_merge( $autoloaderPaths,
330 $processor->getExtraAutoloaderPaths( $dir, $info ) );
331 // Compatible, read and extract info
332 $processor->extractInfo( $path, $info, $version );
333 }
334 $data = $processor->getExtractedInfo();
335 $data['warnings'] = $warnings;
336
337 // check for incompatible extensions
338 $incompatible = array_merge(
339 $incompatible,
340 $versionChecker
341 ->setLoadedExtensionsAndSkins( $data['credits'] )
342 ->checkArray( $extDependencies )
343 );
344
345 if ( $incompatible ) {
346 throw new ExtensionDependencyError( $incompatible );
347 }
348
349 // Need to set this so we can += to it later
350 $data['globals']['wgAutoloadClasses'] = [];
351 $data['autoload'] = $autoloadClasses;
352 $data['autoloaderPaths'] = $autoloaderPaths;
353 $data['autoloaderNS'] = $autoloadNamespaces;
354 return $data;
355 }
356
357 /**
358 * Export autoload classes and namespaces for a given directory and parsed JSON info file.
359 *
360 * @param string $dir
361 * @param array $info
362 * @param array &$autoloadClasses
363 * @param array &$autoloadNamespaces
364 */
365 public static function exportAutoloadClassesAndNamespaces(
366 $dir, $info, &$autoloadClasses = [], &$autoloadNamespaces = []
367 ) {
368 if ( isset( $info['AutoloadClasses'] ) ) {
369 $autoload = self::processAutoLoader( $dir, $info['AutoloadClasses'] );
370 $GLOBALS['wgAutoloadClasses'] += $autoload;
371 $autoloadClasses += $autoload;
372 }
373 if ( isset( $info['AutoloadNamespaces'] ) ) {
374 $autoloadNamespaces += self::processAutoLoader( $dir, $info['AutoloadNamespaces'] );
375 AutoLoader::$psr4Namespaces += $autoloadNamespaces;
376 }
377 }
378
379 protected function exportExtractedData( array $info ) {
380 foreach ( $info['globals'] as $key => $val ) {
381 // If a merge strategy is set, read it and remove it from the value
382 // so it doesn't accidentally end up getting set.
383 if ( is_array( $val ) && isset( $val[self::MERGE_STRATEGY] ) ) {
384 $mergeStrategy = $val[self::MERGE_STRATEGY];
385 unset( $val[self::MERGE_STRATEGY] );
386 } else {
387 $mergeStrategy = 'array_merge';
388 }
389
390 // Optimistic: If the global is not set, or is an empty array, replace it entirely.
391 // Will be O(1) performance.
392 if ( !array_key_exists( $key, $GLOBALS ) || ( is_array( $GLOBALS[$key] ) && !$GLOBALS[$key] ) ) {
393 $GLOBALS[$key] = $val;
394 continue;
395 }
396
397 if ( !is_array( $GLOBALS[$key] ) || !is_array( $val ) ) {
398 // config setting that has already been overridden, don't set it
399 continue;
400 }
401
402 switch ( $mergeStrategy ) {
403 case 'array_merge_recursive':
404 $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
405 break;
406 case 'array_replace_recursive':
407 $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
408 break;
409 case 'array_plus_2d':
410 $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
411 break;
412 case 'array_plus':
413 $GLOBALS[$key] += $val;
414 break;
415 case 'array_merge':
416 $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
417 break;
418 default:
419 throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
420 }
421 }
422
423 if ( isset( $info['autoloaderNS'] ) ) {
424 AutoLoader::$psr4Namespaces += $info['autoloaderNS'];
425 }
426
427 foreach ( $info['defines'] as $name => $val ) {
428 define( $name, $val );
429 }
430 foreach ( $info['autoloaderPaths'] as $path ) {
431 if ( file_exists( $path ) ) {
432 require_once $path;
433 }
434 }
435
436 $this->loaded += $info['credits'];
437 if ( $info['attributes'] ) {
438 if ( !$this->attributes ) {
439 $this->attributes = $info['attributes'];
440 } else {
441 $this->attributes = array_merge_recursive( $this->attributes, $info['attributes'] );
442 }
443 }
444
445 foreach ( $info['callbacks'] as $name => $cb ) {
446 if ( !is_callable( $cb ) ) {
447 if ( is_array( $cb ) ) {
448 $cb = '[ ' . implode( ', ', $cb ) . ' ]';
449 }
450 throw new UnexpectedValueException( "callback '$cb' is not callable" );
451 }
452 $cb( $info['credits'][$name] );
453 }
454 }
455
456 /**
457 * Loads and processes the given JSON file without delay
458 *
459 * If some extensions are already queued, this will load
460 * those as well.
461 * TODO: Remove in MediaWiki 1.35
462 * @deprecated since 1.34, use ExtensionRegistry->queue() instead
463 * @param string $path Absolute path to the JSON file
464 */
465 public function load( $path ) {
466 wfDeprecated( __METHOD__, '1.34' );
467 $this->loadFromQueue(); // First clear the queue
468 $this->queue( $path );
469 $this->loadFromQueue();
470 }
471
472 /**
473 * Whether a thing has been loaded
474 * @param string $name
475 * @param string $constraint The required version constraint for this dependency
476 * @throws LogicException if a specific contraint is asked for,
477 * but the extension isn't versioned
478 * @return bool
479 */
480 public function isLoaded( $name, $constraint = '*' ) {
481 $isLoaded = isset( $this->loaded[$name] );
482 if ( $constraint === '*' || !$isLoaded ) {
483 return $isLoaded;
484 }
485 // if a specific constraint is requested, but no version is set, throw an exception
486 if ( !isset( $this->loaded[$name]['version'] ) ) {
487 $msg = "{$name} does not expose its version, but an extension or a skin"
488 . " requires: {$constraint}.";
489 throw new LogicException( $msg );
490 }
491
492 return SemVer::satisfies( $this->loaded[$name]['version'], $constraint );
493 }
494
495 /**
496 * @param string $name
497 * @return array
498 */
499 public function getAttribute( $name ) {
500 return $this->testAttributes[$name] ??
501 $this->attributes[$name] ?? [];
502 }
503
504 /**
505 * Force override the value of an attribute during tests
506 *
507 * @param string $name Name of attribute to override
508 * @param array $value Value to set
509 * @return ScopedCallback to reset
510 * @since 1.33
511 */
512 public function setAttributeForTest( $name, array $value ) {
513 // @codeCoverageIgnoreStart
514 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
515 throw new RuntimeException( __METHOD__ . ' can only be used in tests' );
516 }
517 // @codeCoverageIgnoreEnd
518 if ( isset( $this->testAttributes[$name] ) ) {
519 throw new Exception( "The attribute '$name' has already been overridden" );
520 }
521 $this->testAttributes[$name] = $value;
522 return new ScopedCallback( function () use ( $name ) {
523 unset( $this->testAttributes[$name] );
524 } );
525 }
526
527 /**
528 * Get information about all things
529 *
530 * @return array
531 */
532 public function getAllThings() {
533 return $this->loaded;
534 }
535
536 /**
537 * Fully expand autoloader paths
538 *
539 * @param string $dir
540 * @param array $files
541 * @return array
542 */
543 protected static function processAutoLoader( $dir, array $files ) {
544 // Make paths absolute, relative to the JSON file
545 foreach ( $files as &$file ) {
546 $file = "$dir/$file";
547 }
548 return $files;
549 }
550 }