Debian Codegraph @

includes/registration/ExtensionRegistry.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Registration;
4
5 use AutoLoader;
6 use Composer\Semver\Semver;
7 use InvalidArgumentException;
8 use LogicException;
9 use MediaWiki\Settings\SettingsBuilder;
10 use MediaWiki\Shell\Shell;
11 use MediaWiki\ShellDisabledError;
12 use MediaWiki\WikiMap\WikiMap;
13 use ObjectCacheFactory;
14 use RuntimeException;
15 use UnexpectedValueException;
16 use Wikimedia\ObjectCache\BagOStuff;
17 use Wikimedia\ScopedCallback;
18
19 /**
20 * @defgroup ExtensionRegistry ExtensionRegistry
21 *
22 * For higher level documentation, see <https://www.mediawiki.org/wiki/Manual:Extension_registration/Architecture>.
23 */
24
25 /**
26 * Load JSON files, and uses a Processor to extract information.
27 *
28 * This also adds the extension's classes to the AutoLoader.
29 *
30 * @ingroup ExtensionRegistry
31 * @since 1.25
32 */
33 class ExtensionRegistry {
34
35 /**
36 * "requires" key that applies to MediaWiki core
37 */
38 public const MEDIAWIKI_CORE = 'MediaWiki';
39
40 /**
41 * Version of the highest supported manifest version
42 * Note: Update MANIFEST_VERSION_MW_VERSION when changing this
43 */
44 public const MANIFEST_VERSION = 2;
45
46 /**
47 * MediaWiki version constraint representing what the current
48 * highest MANIFEST_VERSION is supported in
49 */
50 public const MANIFEST_VERSION_MW_VERSION = '>= 1.29.0';
51
52 /**
53 * Version of the oldest supported manifest version
54 */
55 public const OLDEST_MANIFEST_VERSION = 1;
56
57 /**
58 * Bump whenever the registration cache needs resetting
59 */
60 private const CACHE_VERSION = 8;
61
62 private const CACHE_EXPIRY = 60 * 60 * 24;
63
64 /**
65 * Special key that defines the merge strategy
66 *
67 * @since 1.26
68 */
69 public const MERGE_STRATEGY = '_merge_strategy';
70
71 /**
72 * Attributes that should be lazy-loaded
73 */
74 private const LAZY_LOADED_ATTRIBUTES = [
75 'TrackingCategories',
76 'QUnitTestModules',
77 'SkinLessImportPaths',
78 ];
79
80 /**
81 * Array of loaded things, keyed by name, values are credits information.
82 *
83 * The keys that the credit info arrays may have is defined
84 * by ExtensionProcessor::CREDIT_ATTRIBS (plus a 'path' key that
85 * points to the skin or extension JSON file).
86 *
87 * This info may be accessed via ExtensionRegistry::getAllThings.
88 *
89 * @var array[]
90 */
91 private $loaded = [];
92
93 /**
94 * List of paths that should be loaded
95 *
96 * @var int[]
97 */
98 protected $queued = [];
99
100 /**
101 * Whether we are done loading things
102 *
103 * @var bool
104 */
105 private $finished = false;
106
107 /**
108 * Items in the JSON file that aren't being
109 * set as globals
110 *
111 * @var array
112 */
113 protected $attributes = [];
114
115 /**
116 * Attributes for testing
117 *
118 * @var array
119 */
120 protected $testAttributes = [];
121
122 /**
123 * Lazy-loaded attributes
124 *
125 * @var array
126 */
127 protected $lazyAttributes = [];
128
129 /**
130 * The hash of cache-varying options, lazy-initialised
131 *
132 * @var string|null
133 */
134 private $varyHash;
135
136 /**
137 * Whether to check dev-requires
138 *
139 * @var bool
140 */
141 protected $checkDev = false;
142
143 /**
144 * Whether test classes and namespaces should be added to the auto loader
145 *
146 * @var bool
147 */
148 protected $loadTestClassesAndNamespaces = false;
149
150 /**
151 * @var ExtensionRegistry
152 */
153 private static $instance;
154
155 /**
156 * @var ?BagOStuff
157 */
158 private $cache = null;
159
160 /**
161 * @var ?SettingsBuilder
162 */
163 private ?SettingsBuilder $settingsBuilder = null;
164
165 private static bool $accessDisabledForUnitTests = false;
166
167 /**
168 * @codeCoverageIgnore
169 * @return ExtensionRegistry
170 */
171 public static function getInstance() {
172 if ( self::$accessDisabledForUnitTests ) {
173 throw new RuntimeException( 'Access is disabled in unit tests' );
174 }
175 if ( self::$instance === null ) {
176 self::$instance = new self();
177 }
178
179 return self::$instance;
180 }
181
182 /**
183 * @internal
184 */
185 public static function disableForTest(): void {
186 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
187 throw new RuntimeException( 'Can only be called in tests' );
188 }
189 self::$accessDisabledForUnitTests = true;
190 }
191
192 /**
193 * @internal
194 */
195 public static function enableForTest(): void {
196 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
197 throw new RuntimeException( 'Can only be called in tests' );
198 }
199 self::$accessDisabledForUnitTests = false;
200 }
201
202 /**
203 * Set the cache to use for extension info.
204 * Intended for use during testing.
205 *
206 * @internal
207 *
208 * @param BagOStuff $cache
209 */
210 public function setCache( BagOStuff $cache ): void {
211 $this->cache = $cache;
212 }
213
214 /**
215 * @since 1.34
216 *
217 * @param bool $check
218 */
219 public function setCheckDevRequires( $check ) {
220 $this->checkDev = $check;
221 $this->invalidateProcessCache();
222 }
223
224 /**
225 * Controls if classes and namespaces defined under the keys TestAutoloadClasses and
226 * TestAutoloadNamespaces should be added to the autoloader.
227 *
228 * @since 1.35
229 *
230 * @param bool $load
231 */
232 public function setLoadTestClassesAndNamespaces( $load ) {
233 $this->loadTestClassesAndNamespaces = $load;
234 }
235
236 /**
237 * @param string $path Absolute path to the JSON file
238 */
239 public function queue( $path ) {
240 global $wgExtensionInfoMTime;
241
242 $mtime = $wgExtensionInfoMTime;
243 if ( $mtime === false ) {
244 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
245 $mtime = @filemtime( $path );
246 // @codeCoverageIgnoreStart
247 if ( $mtime === false ) {
248 $err = error_get_last();
249 throw new MissingExtensionException( $path, $err['message'] );
250 // @codeCoverageIgnoreEnd
251 }
252 }
253 $this->queued[$path] = $mtime;
254 $this->invalidateProcessCache();
255 }
256
257 private function getCache(): BagOStuff {
258 if ( !$this->cache ) {
259 // NOTE: Copy of ObjectCacheFactory::getDefaultKeyspace
260 //
261 // Can't call MediaWikiServices here, as we must not cause services
262 // to be instantiated before extensions have loaded.
263 global $wgCachePrefix;
264 $keyspace = ( is_string( $wgCachePrefix ) && $wgCachePrefix !== '' )
265 ? $wgCachePrefix
266 : WikiMap::getCurrentWikiDbDomain()->getId();
267
268 return ObjectCacheFactory::makeLocalServerCache( $keyspace );
269 }
270
271 return $this->cache;
272 }
273
274 private function makeCacheKey( BagOStuff $cache, $component, ...$extra ) {
275 // Allow reusing cached ExtensionRegistry metadata between wikis (T274648)
276 return $cache->makeGlobalKey(
277 "registration-$component",
278 $this->getVaryHash(),
279 ...$extra
280 );
281 }
282
283 /**
284 * Get the cache varying hash
285 *
286 * @return string
287 */
288 private function getVaryHash() {
289 if ( $this->varyHash === null ) {
290 // We vary the cache on the current queue (what will be or already was loaded)
291 // plus various versions of stuff for VersionChecker
292 $vary = [
293 'registration' => self::CACHE_VERSION,
294 'mediawiki' => MW_VERSION,
295 'abilities' => $this->getAbilities(),
296 'checkDev' => $this->checkDev,
297 'queue' => $this->queued,
298 ];
299 $this->varyHash = md5( json_encode( $vary ) );
300 }
301
302 return $this->varyHash;
303 }
304
305 /**
306 * Invalidate the cache of the vary hash and the lazy options.
307 */
308 private function invalidateProcessCache() {
309 $this->varyHash = null;
310 $this->lazyAttributes = [];
311 }
312
313 public function loadFromQueue() {
314 if ( !$this->queued ) {
315 return;
316 }
317
318 if ( $this->finished ) {
319 throw new LogicException(
320 "The following paths tried to load late: "
321 . implode( ', ', array_keys( $this->queued ) )
322 );
323 }
324
325 $cache = $this->getCache();
326 // See if this queue is in APC
327 $key = $this->makeCacheKey( $cache, 'main' );
328 $data = $cache->get( $key );
329 if ( !$data ) {
330 $data = $this->readFromQueue( $this->queued );
331 $this->saveToCache( $cache, $data );
332 }
333 $this->exportExtractedData( $data );
334 }
335
336 /**
337 * Save data in the cache
338 *
339 * @param BagOStuff $cache
340 * @param array $data
341 */
342 protected function saveToCache( BagOStuff $cache, array $data ) {
343 global $wgDevelopmentWarnings;
344 if ( $data['warnings'] && $wgDevelopmentWarnings ) {
345 // If warnings were shown, don't cache it
346 return;
347 }
348 $lazy = [];
349 // Cache lazy-loaded attributes separately
350 foreach ( self::LAZY_LOADED_ATTRIBUTES as $attrib ) {
351 if ( isset( $data['attributes'][$attrib] ) ) {
352 $lazy[$attrib] = $data['attributes'][$attrib];
353 unset( $data['attributes'][$attrib] );
354 }
355 }
356 $mainKey = $this->makeCacheKey( $cache, 'main' );
357 $cache->set( $mainKey, $data, self::CACHE_EXPIRY );
358 foreach ( $lazy as $attrib => $value ) {
359 $cache->set(
360 $this->makeCacheKey( $cache, 'lazy-attrib', $attrib ),
361 $value,
362 self::CACHE_EXPIRY
363 );
364 }
365 }
366
367 /**
368 * Get the current load queue. Not intended to be used
369 * outside of the installer.
370 *
371 * @return int[] Map of extension.json files' modification timestamps keyed by absolute path
372 */
373 public function getQueue() {
374 return $this->queued;
375 }
376
377 /**
378 * Clear the current load queue. Not intended to be used
379 * outside of the installer.
380 */
381 public function clearQueue() {
382 $this->queued = [];
383 $this->invalidateProcessCache();
384 }
385
386 /**
387 * After this is called, no more extensions can be loaded
388 *
389 * @since 1.29
390 */
391 public function finish() {
392 $this->finished = true;
393 }
394
395 /**
396 * Get the list of abilities and their values
397 *
398 * @return bool[]
399 */
400 private function getAbilities() {
401 return [
402 'shell' => !Shell::isDisabled(),
403 ];
404 }
405
406 /**
407 * Queries information about the software environment and constructs an appropriate version checker
408 *
409 * @return VersionChecker
410 */
411 private function buildVersionChecker() {
412 // array to optionally specify more verbose error messages for
413 // missing abilities
414 $abilityErrors = [
415 'shell' => ( new ShellDisabledError() )->getMessage(),
416 ];
417
418 return new VersionChecker(
419 MW_VERSION,
420 PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION,
421 get_loaded_extensions(),
422 $this->getAbilities(),
423 $abilityErrors
424 );
425 }
426
427 /**
428 * Process a queue of extensions and return their extracted data
429 *
430 * @internal since 1.39. Extensions should use ExtensionProcessor instead.
431 *
432 * @param int[] $queue keys are filenames, values are ignored
433 *
434 * @return array extracted info
435 * @throws InvalidArgumentException
436 * @throws ExtensionDependencyError
437 */
438 public function readFromQueue( array $queue ) {
439 $processor = new ExtensionProcessor();
440 $versionChecker = $this->buildVersionChecker();
441 $extDependencies = [];
442 $warnings = false;
443 foreach ( $queue as $path => $mtime ) {
444 $json = file_get_contents( $path );
445 if ( $json === false ) {
446 throw new InvalidArgumentException( "Unable to read $path, does it exist?" );
447 }
448 $info = json_decode( $json, /* $assoc = */ true );
449 if ( !is_array( $info ) ) {
450 throw new InvalidArgumentException( "$path is not a valid JSON file." );
451 }
452
453 $version = $info['manifest_version'];
454 if ( $version < self::OLDEST_MANIFEST_VERSION || $version > self::MANIFEST_VERSION ) {
455 throw new InvalidArgumentException( "$path: unsupported manifest_version: {$version}" );
456 }
457
458 // get all requirements/dependencies for this extension
459 $requires = $processor->getRequirements( $info, $this->checkDev );
460
461 // validate the information needed and add the requirements
462 if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
463 $extDependencies[$info['name']] = $requires;
464 }
465
466 // Compatible, read and extract info
467 $processor->extractInfo( $path, $info, $version );
468 }
469 $data = $processor->getExtractedInfo( $this->loadTestClassesAndNamespaces );
470 $data['warnings'] = $warnings;
471
472 // check for incompatible extensions
473 $incompatible = $versionChecker
474 ->setLoadedExtensionsAndSkins( $data['credits'] )
475 ->checkArray( $extDependencies );
476
477 if ( $incompatible ) {
478 throw new ExtensionDependencyError( $incompatible );
479 }
480
481 return $data;
482 }
483
484 protected function exportExtractedData( array $info ) {
485 if ( $info['globals'] ) {
486 // Create a copy of the keys to allow fast access via isset also for null values
487 // Since php8.1 always a read-only copy is created when the whole object is passed on function calls
488 // (like for array_key_exists). See T366547 - https://wiki.php.net/rfc/restrict_globals_usage
489 $knownGlobals = array_fill_keys( array_keys( $GLOBALS ), true );
490
491 foreach ( $info['globals'] as $key => $val ) {
492 // If a merge strategy is set, read it and remove it from the value
493 // so it doesn't accidentally end up getting set.
494 if ( is_array( $val ) && isset( $val[self::MERGE_STRATEGY] ) ) {
495 $mergeStrategy = $val[self::MERGE_STRATEGY];
496 unset( $val[self::MERGE_STRATEGY] );
497 } else {
498 $mergeStrategy = 'array_merge';
499 }
500
501 if ( $mergeStrategy === 'provide_default' ) {
502 if ( !isset( $knownGlobals[$key] ) ) {
503 $GLOBALS[$key] = $val;
504 $knownGlobals[$key] = true;
505 }
506 continue;
507 }
508
509 // Performance optimization: When the global doesn't exist (not even with null), just set it
510 if ( !isset( $knownGlobals[$key] ) ) {
511 $GLOBALS[$key] = $val;
512 $knownGlobals[$key] = true;
513 continue;
514 } elseif ( !is_array( $val ) || !is_array( $GLOBALS[$key] ) ) {
515 // When at least one of the global value and the default is not an array, the merge
516 // strategy is ignored and the global value will simply override the default.
517 continue;
518 } elseif ( !$GLOBALS[$key] ) {
519 // Performance optimization: When the target is an empty array, just set it
520 $GLOBALS[$key] = $val;
521 continue;
522 }
523
524 switch ( $mergeStrategy ) {
525 case 'array_merge_recursive':
526 $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
527 break;
528 case 'array_replace_recursive':
529 $GLOBALS[$key] = array_replace_recursive( $val, $GLOBALS[$key] );
530 break;
531 case 'array_plus_2d':
532 $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
533 break;
534 case 'array_plus':
535 $GLOBALS[$key] += $val;
536 break;
537 case 'array_merge':
538 $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
539 break;
540 default:
541 throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
542 }
543 }
544 }
545
546 if ( isset( $info['autoloaderNS'] ) ) {
547 AutoLoader::registerNamespaces( $info['autoloaderNS'] );
548 }
549
550 if ( isset( $info['autoloaderClasses'] ) ) {
551 AutoLoader::registerClasses( $info['autoloaderClasses'] );
552 }
553
554 foreach ( $info['defines'] as $name => $val ) {
555 if ( !defined( $name ) ) {
556 define( $name, $val );
557 } elseif ( constant( $name ) !== $val ) {
558 throw new UnexpectedValueException(
559 "$name cannot be re-defined with $val it has already been set with " . constant( $name )
560 );
561 }
562 }
563
564 if ( isset( $info['autoloaderPaths'] ) ) {
565 AutoLoader::loadFiles( $info['autoloaderPaths'] );
566 }
567
568 $this->loaded += $info['credits'];
569 if ( $info['attributes'] ) {
570 if ( !$this->attributes ) {
571 $this->attributes = $info['attributes'];
572 } else {
573 $this->attributes = array_merge_recursive( $this->attributes, $info['attributes'] );
574 }
575 }
576
577 // XXX: SettingsBuilder should really be a parameter to this method.
578 $settings = $this->getSettingsBuilder();
579
580 foreach ( $info['callbacks'] as $name => $cb ) {
581 if ( !is_callable( $cb ) ) {
582 if ( is_array( $cb ) ) {
583 $cb = '[ ' . implode( ', ', $cb ) . ' ]';
584 }
585 throw new UnexpectedValueException( "callback '$cb' is not callable" );
586 }
587 $cb( $info['credits'][$name], $settings );
588 }
589 }
590
591 /**
592 * Whether a thing has been loaded
593 *
594 * @param string $name
595 * @param string $constraint The required version constraint for this dependency
596 * @return bool
597 */
598 public function isLoaded( $name, $constraint = '*' ) {
599 $isLoaded = isset( $this->loaded[$name] );
600 if ( $constraint === '*' || !$isLoaded ) {
601 return $isLoaded;
602 }
603 // if a specific constraint is requested, but no version is set, throw an exception
604 if ( !isset( $this->loaded[$name]['version'] ) ) {
605 $msg = "{$name} does not expose its version, but an extension or a skin"
606 . " requires: {$constraint}.";
607 throw new LogicException( $msg );
608 }
609
610 return Semver::satisfies( $this->loaded[$name]['version'], $constraint );
611 }
612
613 /**
614 * @param string $name
615 *
616 * @return array
617 */
618 public function getAttribute( $name ) {
619 if ( isset( $this->testAttributes[$name] ) ) {
620 return $this->testAttributes[$name];
621 }
622
623 if ( in_array( $name, self::LAZY_LOADED_ATTRIBUTES, true ) ) {
624 return $this->getLazyLoadedAttribute( $name );
625 }
626
627 return $this->attributes[$name] ?? [];
628 }
629
630 /**
631 * Get an attribute value that isn't cached by reading each
632 * extension.json file again
633 *
634 * @param string $name
635 *
636 * @return array
637 */
638 protected function getLazyLoadedAttribute( $name ) {
639 if ( isset( $this->testAttributes[$name] ) ) {
640 return $this->testAttributes[$name];
641 }
642 if ( isset( $this->lazyAttributes[$name] ) ) {
643 return $this->lazyAttributes[$name];
644 }
645
646 // See if it's in the cache
647 $cache = $this->getCache();
648 $key = $this->makeCacheKey( $cache, 'lazy-attrib', $name );
649 $data = $cache->get( $key );
650 if ( $data !== false ) {
651 $this->lazyAttributes[$name] = $data;
652
653 return $data;
654 }
655
656 $paths = [];
657 foreach ( $this->loaded as $info ) {
658 // mtime (array value) doesn't matter here since
659 // we're skipping cache, so use a dummy time
660 $paths[$info['path']] = 1;
661 }
662
663 $result = $this->readFromQueue( $paths );
664 $data = $result['attributes'][$name] ?? [];
665 $this->saveToCache( $cache, $result );
666 $this->lazyAttributes[$name] = $data;
667
668 return $data;
669 }
670
671 /**
672 * Force override the value of an attribute during tests
673 *
674 * @param string $name Name of attribute to override
675 * @param array $value Value to set
676 *
677 * @return ScopedCallback to reset
678 * @since 1.33
679 */
680 public function setAttributeForTest( $name, array $value ) {
681 // @codeCoverageIgnoreStart
682 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
683 throw new LogicException( __METHOD__ . ' can only be used in tests' );
684 }
685 // @codeCoverageIgnoreEnd
686 if ( isset( $this->testAttributes[$name] ) ) {
687 throw new InvalidArgumentException( "The attribute '$name' has already been overridden" );
688 }
689 $this->testAttributes[$name] = $value;
690
691 return new ScopedCallback( function () use ( $name ) {
692 unset( $this->testAttributes[$name] );
693 } );
694 }
695
696 /**
697 * Get credits information about all installed extensions and skins.
698 *
699 * @return array[] Keyed by component name.
700 */
701 public function getAllThings() {
702 return $this->loaded;
703 }
704
705 /**
706 * Fully expand autoloader paths
707 *
708 * @param string $dir
709 * @param string[] $files
710 *
711 * @return array
712 */
713 protected static function processAutoLoader( $dir, array $files ) {
714 // Make paths absolute, relative to the JSON file
715 foreach ( $files as &$file ) {
716 $file = "$dir/$file";
717 }
718
719 return $files;
720 }
721
722 /**
723 * @internal for use by Setup. Hopefully in the future, we find a better way.
724 *
725 * @param SettingsBuilder $settingsBuilder
726 */
727 public function setSettingsBuilder( SettingsBuilder $settingsBuilder ) {
728 $this->settingsBuilder = $settingsBuilder;
729 }
730
731 private function getSettingsBuilder(): SettingsBuilder {
732 if ( $this->settingsBuilder === null ) {
733 $this->settingsBuilder = SettingsBuilder::getInstance();
734 }
735
736 return $this->settingsBuilder;
737 }
738 }
739
740 /** @deprecated class alias since 1.43 */
741 class_alias( ExtensionRegistry::class, 'ExtensionRegistry' );