Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[lhc/web/wiklou.git] / includes / registration / ExtensionRegistry.php
1 <?php
2
3 use Composer\Semver\Semver;
4 use Wikimedia\ScopedCallback;
5
6 /**
7 * ExtensionRegistry class
8 *
9 * The Registry loads JSON files, and uses a Processor
10 * to extract information from them. It also registers
11 * classes with the autoloader.
12 *
13 * @since 1.25
14 */
15 class ExtensionRegistry {
16
17 /**
18 * "requires" key that applies to MediaWiki core/$wgVersion
19 */
20 const MEDIAWIKI_CORE = 'MediaWiki';
21
22 /**
23 * Version of the highest supported manifest version
24 * Note: Update MANIFEST_VERSION_MW_VERSION when changing this
25 */
26 const MANIFEST_VERSION = 2;
27
28 /**
29 * MediaWiki version constraint representing what the current
30 * highest MANIFEST_VERSION is supported in
31 */
32 const MANIFEST_VERSION_MW_VERSION = '>= 1.29.0';
33
34 /**
35 * Version of the oldest supported manifest version
36 */
37 const OLDEST_MANIFEST_VERSION = 1;
38
39 /**
40 * Bump whenever the registration cache needs resetting
41 */
42 const CACHE_VERSION = 7;
43
44 /**
45 * Special key that defines the merge strategy
46 *
47 * @since 1.26
48 */
49 const MERGE_STRATEGY = '_merge_strategy';
50
51 /**
52 * Array of loaded things, keyed by name, values are credits information
53 *
54 * @var array
55 */
56 private $loaded = [];
57
58 /**
59 * List of paths that should be loaded
60 *
61 * @var array
62 */
63 protected $queued = [];
64
65 /**
66 * Whether we are done loading things
67 *
68 * @var bool
69 */
70 private $finished = false;
71
72 /**
73 * Items in the JSON file that aren't being
74 * set as globals
75 *
76 * @var array
77 */
78 protected $attributes = [];
79
80 /**
81 * Attributes for testing
82 *
83 * @var array
84 */
85 protected $testAttributes = [];
86
87 /**
88 * @var ExtensionRegistry
89 */
90 private static $instance;
91
92 /**
93 * @codeCoverageIgnore
94 * @return ExtensionRegistry
95 */
96 public static function getInstance() {
97 if ( self::$instance === null ) {
98 self::$instance = new self();
99 }
100
101 return self::$instance;
102 }
103
104 /**
105 * @param string $path Absolute path to the JSON file
106 */
107 public function queue( $path ) {
108 global $wgExtensionInfoMTime;
109
110 $mtime = $wgExtensionInfoMTime;
111 if ( $mtime === false ) {
112 if ( file_exists( $path ) ) {
113 $mtime = filemtime( $path );
114 } else {
115 throw new Exception( "$path does not exist!" );
116 }
117 // @codeCoverageIgnoreStart
118 if ( $mtime === false ) {
119 $err = error_get_last();
120 throw new Exception( "Couldn't stat $path: {$err['message']}" );
121 // @codeCoverageIgnoreEnd
122 }
123 }
124 $this->queued[$path] = $mtime;
125 }
126
127 /**
128 * @throws MWException If the queue is already marked as finished (no further things should
129 * be loaded then).
130 */
131 public function loadFromQueue() {
132 global $wgVersion, $wgDevelopmentWarnings;
133 if ( !$this->queued ) {
134 return;
135 }
136
137 if ( $this->finished ) {
138 throw new MWException(
139 "The following paths tried to load late: "
140 . implode( ', ', array_keys( $this->queued ) )
141 );
142 }
143
144 // A few more things to vary the cache on
145 $versions = [
146 'registration' => self::CACHE_VERSION,
147 'mediawiki' => $wgVersion
148 ];
149
150 // We use a try/catch because we don't want to fail here
151 // if $wgObjectCaches is not configured properly for APC setup
152 try {
153 // Don't use MediaWikiServices here to prevent instantiating it before extensions have
154 // been loaded
155 $cacheId = ObjectCache::detectLocalServerCache();
156 $cache = ObjectCache::newFromId( $cacheId );
157 } catch ( InvalidArgumentException $e ) {
158 $cache = new EmptyBagOStuff();
159 }
160 // See if this queue is in APC
161 $key = $cache->makeKey(
162 'registration',
163 md5( json_encode( $this->queued + $versions ) )
164 );
165 $data = $cache->get( $key );
166 if ( $data ) {
167 $this->exportExtractedData( $data );
168 } else {
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 );
178 }
179 }
180 $this->queued = [];
181 }
182
183 /**
184 * Get the current load queue. Not intended to be used
185 * outside of the installer.
186 *
187 * @return array
188 */
189 public function getQueue() {
190 return $this->queued;
191 }
192
193 /**
194 * Clear the current load queue. Not intended to be used
195 * outside of the installer.
196 */
197 public function clearQueue() {
198 $this->queued = [];
199 }
200
201 /**
202 * After this is called, no more extensions can be loaded
203 *
204 * @since 1.29
205 */
206 public function finish() {
207 $this->finished = true;
208 }
209
210 /**
211 * Process a queue of extensions and return their extracted data
212 *
213 * @param array $queue keys are filenames, values are ignored
214 * @return array extracted info
215 * @throws Exception
216 * @throws ExtensionDependencyError
217 */
218 public function readFromQueue( array $queue ) {
219 global $wgVersion;
220 $autoloadClasses = [];
221 $autoloadNamespaces = [];
222 $autoloaderPaths = [];
223 $processor = new ExtensionProcessor();
224 $versionChecker = new VersionChecker(
225 $wgVersion,
226 PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION,
227 get_loaded_extensions()
228 );
229 $extDependencies = [];
230 $incompatible = [];
231 $warnings = false;
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?" );
236 }
237 $info = json_decode( $json, /* $assoc = */ true );
238 if ( !is_array( $info ) ) {
239 throw new Exception( "$path is not a valid JSON file." );
240 }
241
242 if ( !isset( $info['manifest_version'] ) ) {
243 wfDeprecated(
244 "{$info['name']}'s extension.json or skin.json does not have manifest_version",
245 '1.29'
246 );
247 $warnings = true;
248 // For backwards-compatability, assume a version of 1
249 $info['manifest_version'] = 1;
250 }
251 $version = $info['manifest_version'];
252 if ( $version < self::OLDEST_MANIFEST_VERSION || $version > self::MANIFEST_VERSION ) {
253 $incompatible[] = "$path: unsupported manifest_version: {$version}";
254 }
255
256 $dir = dirname( $path );
257 if ( isset( $info['AutoloadClasses'] ) ) {
258 $autoload = $this->processAutoLoader( $dir, $info['AutoloadClasses'] );
259 $GLOBALS['wgAutoloadClasses'] += $autoload;
260 $autoloadClasses += $autoload;
261 }
262 if ( isset( $info['AutoloadNamespaces'] ) ) {
263 $autoloadNamespaces += $this->processAutoLoader( $dir, $info['AutoloadNamespaces'] );
264 AutoLoader::$psr4Namespaces += $autoloadNamespaces;
265 }
266
267 // get all requirements/dependencies for this extension
268 $requires = $processor->getRequirements( $info );
269
270 // validate the information needed and add the requirements
271 if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
272 $extDependencies[$info['name']] = $requires;
273 }
274
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 );
280 }
281 $data = $processor->getExtractedInfo();
282 $data['warnings'] = $warnings;
283
284 // check for incompatible extensions
285 $incompatible = array_merge(
286 $incompatible,
287 $versionChecker
288 ->setLoadedExtensionsAndSkins( $data['credits'] )
289 ->checkArray( $extDependencies )
290 );
291
292 if ( $incompatible ) {
293 throw new ExtensionDependencyError( $incompatible );
294 }
295
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;
301 return $data;
302 }
303
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] );
311 } else {
312 $mergeStrategy = 'array_merge';
313 }
314
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;
319 continue;
320 }
321
322 if ( !is_array( $GLOBALS[$key] ) || !is_array( $val ) ) {
323 // config setting that has already been overridden, don't set it
324 continue;
325 }
326
327 switch ( $mergeStrategy ) {
328 case 'array_merge_recursive':
329 $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
330 break;
331 case 'array_replace_recursive':
332 $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
333 break;
334 case 'array_plus_2d':
335 $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
336 break;
337 case 'array_plus':
338 $GLOBALS[$key] += $val;
339 break;
340 case 'array_merge':
341 $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
342 break;
343 default:
344 throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
345 }
346 }
347
348 if ( isset( $info['autoloaderNS'] ) ) {
349 AutoLoader::$psr4Namespaces += $info['autoloaderNS'];
350 }
351
352 foreach ( $info['defines'] as $name => $val ) {
353 define( $name, $val );
354 }
355 foreach ( $info['autoloaderPaths'] as $path ) {
356 if ( file_exists( $path ) ) {
357 require_once $path;
358 }
359 }
360
361 $this->loaded += $info['credits'];
362 if ( $info['attributes'] ) {
363 if ( !$this->attributes ) {
364 $this->attributes = $info['attributes'];
365 } else {
366 $this->attributes = array_merge_recursive( $this->attributes, $info['attributes'] );
367 }
368 }
369
370 foreach ( $info['callbacks'] as $name => $cb ) {
371 if ( !is_callable( $cb ) ) {
372 if ( is_array( $cb ) ) {
373 $cb = '[ ' . implode( ', ', $cb ) . ' ]';
374 }
375 throw new UnexpectedValueException( "callback '$cb' is not callable" );
376 }
377 $cb( $info['credits'][$name] );
378 }
379 }
380
381 /**
382 * Loads and processes the given JSON file without delay
383 *
384 * If some extensions are already queued, this will load
385 * those as well.
386 *
387 * @param string $path Absolute path to the JSON file
388 */
389 public function load( $path ) {
390 $this->loadFromQueue(); // First clear the queue
391 $this->queue( $path );
392 $this->loadFromQueue();
393 }
394
395 /**
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
401 * @return bool
402 */
403 public function isLoaded( $name, $constraint = '*' ) {
404 $isLoaded = isset( $this->loaded[$name] );
405 if ( $constraint === '*' || !$isLoaded ) {
406 return $isLoaded;
407 }
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 );
413 }
414
415 return SemVer::satisfies( $this->loaded[$name]['version'], $constraint );
416 }
417
418 /**
419 * @param string $name
420 * @return array
421 */
422 public function getAttribute( $name ) {
423 return $this->testAttributes[$name] ??
424 $this->attributes[$name] ?? [];
425 }
426
427 /**
428 * Force override the value of an attribute during tests
429 *
430 * @param string $name Name of attribute to override
431 * @param array $value Value to set
432 * @return ScopedCallback to reset
433 * @since 1.33
434 */
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' );
439 }
440 // @codeCoverageIgnoreEnd
441 if ( isset( $this->testAttributes[$name] ) ) {
442 throw new Exception( "The attribute '$name' has already been overridden" );
443 }
444 $this->testAttributes[$name] = $value;
445 return new ScopedCallback( function () use ( $name ) {
446 unset( $this->testAttributes[$name] );
447 } );
448 }
449
450 /**
451 * Get information about all things
452 *
453 * @return array
454 */
455 public function getAllThings() {
456 return $this->loaded;
457 }
458
459 /**
460 * Fully expand autoloader paths
461 *
462 * @param string $dir
463 * @param array $files
464 * @return array
465 */
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";
470 }
471 return $files;
472 }
473 }