MediaWiki  master
ExtensionRegistry.php
Go to the documentation of this file.
1 <?php
2 
7 
18 
22  const MEDIAWIKI_CORE = 'MediaWiki';
23 
28  const MANIFEST_VERSION = 2;
29 
34  const MANIFEST_VERSION_MW_VERSION = '>= 1.29.0';
35 
40 
44  const CACHE_VERSION = 7;
45 
51  const MERGE_STRATEGY = '_merge_strategy';
52 
58  private $loaded = [];
59 
65  protected $queued = [];
66 
72  private $finished = false;
73 
80  protected $attributes = [];
81 
87  protected $testAttributes = [];
88 
94  protected $checkDev = false;
95 
99  private static $instance;
100 
105  public static function getInstance() {
106  if ( self::$instance === null ) {
107  self::$instance = new self();
108  }
109 
110  return self::$instance;
111  }
112 
117  public function setCheckDevRequires( $check ) {
118  $this->checkDev = $check;
119  }
120 
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 
148  public function loadFromQueue() {
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
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 
208  public function getQueue() {
209  return $this->queued;
210  }
211 
216  public function clearQueue() {
217  $this->queued = [];
218  }
219 
225  public function finish() {
226  $this->finished = true;
227  }
228 
233  private function getAbilities() {
234  return [
235  'shell' => !Shell::isDisabled(),
236  ];
237  }
238 
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 
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  if ( isset( $info['AutoloadClasses'] ) ) {
304  $autoload = $this->processAutoLoader( $dir, $info['AutoloadClasses'] );
305  $GLOBALS['wgAutoloadClasses'] += $autoload;
306  $autoloadClasses += $autoload;
307  }
308  if ( isset( $info['AutoloadNamespaces'] ) ) {
309  $autoloadNamespaces += $this->processAutoLoader( $dir, $info['AutoloadNamespaces'] );
310  AutoLoader::$psr4Namespaces += $autoloadNamespaces;
311  }
312 
313  // get all requirements/dependencies for this extension
314  $requires = $processor->getRequirements( $info, $this->checkDev );
315 
316  // validate the information needed and add the requirements
317  if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
318  $extDependencies[$info['name']] = $requires;
319  }
320 
321  // Get extra paths for later inclusion
322  $autoloaderPaths = array_merge( $autoloaderPaths,
323  $processor->getExtraAutoloaderPaths( $dir, $info ) );
324  // Compatible, read and extract info
325  $processor->extractInfo( $path, $info, $version );
326  }
327  $data = $processor->getExtractedInfo();
328  $data['warnings'] = $warnings;
329 
330  // check for incompatible extensions
331  $incompatible = array_merge(
332  $incompatible,
333  $versionChecker
334  ->setLoadedExtensionsAndSkins( $data['credits'] )
335  ->checkArray( $extDependencies )
336  );
337 
338  if ( $incompatible ) {
339  throw new ExtensionDependencyError( $incompatible );
340  }
341 
342  // Need to set this so we can += to it later
343  $data['globals']['wgAutoloadClasses'] = [];
344  $data['autoload'] = $autoloadClasses;
345  $data['autoloaderPaths'] = $autoloaderPaths;
346  $data['autoloaderNS'] = $autoloadNamespaces;
347  return $data;
348  }
349 
350  protected function exportExtractedData( array $info ) {
351  foreach ( $info['globals'] as $key => $val ) {
352  // If a merge strategy is set, read it and remove it from the value
353  // so it doesn't accidentally end up getting set.
354  if ( is_array( $val ) && isset( $val[self::MERGE_STRATEGY] ) ) {
355  $mergeStrategy = $val[self::MERGE_STRATEGY];
356  unset( $val[self::MERGE_STRATEGY] );
357  } else {
358  $mergeStrategy = 'array_merge';
359  }
360 
361  // Optimistic: If the global is not set, or is an empty array, replace it entirely.
362  // Will be O(1) performance.
363  if ( !array_key_exists( $key, $GLOBALS ) || ( is_array( $GLOBALS[$key] ) && !$GLOBALS[$key] ) ) {
364  $GLOBALS[$key] = $val;
365  continue;
366  }
367 
368  if ( !is_array( $GLOBALS[$key] ) || !is_array( $val ) ) {
369  // config setting that has already been overridden, don't set it
370  continue;
371  }
372 
373  switch ( $mergeStrategy ) {
374  case 'array_merge_recursive':
375  $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
376  break;
377  case 'array_replace_recursive':
378  $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
379  break;
380  case 'array_plus_2d':
381  $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
382  break;
383  case 'array_plus':
384  $GLOBALS[$key] += $val;
385  break;
386  case 'array_merge':
387  $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
388  break;
389  default:
390  throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
391  }
392  }
393 
394  if ( isset( $info['autoloaderNS'] ) ) {
395  AutoLoader::$psr4Namespaces += $info['autoloaderNS'];
396  }
397 
398  foreach ( $info['defines'] as $name => $val ) {
399  define( $name, $val );
400  }
401  foreach ( $info['autoloaderPaths'] as $path ) {
402  if ( file_exists( $path ) ) {
403  require_once $path;
404  }
405  }
406 
407  $this->loaded += $info['credits'];
408  if ( $info['attributes'] ) {
409  if ( !$this->attributes ) {
410  $this->attributes = $info['attributes'];
411  } else {
412  $this->attributes = array_merge_recursive( $this->attributes, $info['attributes'] );
413  }
414  }
415 
416  foreach ( $info['callbacks'] as $name => $cb ) {
417  if ( !is_callable( $cb ) ) {
418  if ( is_array( $cb ) ) {
419  $cb = '[ ' . implode( ', ', $cb ) . ' ]';
420  }
421  throw new UnexpectedValueException( "callback '$cb' is not callable" );
422  }
423  $cb( $info['credits'][$name] );
424  }
425  }
426 
436  public function load( $path ) {
437  wfDeprecated( __METHOD__, '1.34' );
438  $this->loadFromQueue(); // First clear the queue
439  $this->queue( $path );
440  $this->loadFromQueue();
441  }
442 
451  public function isLoaded( $name, $constraint = '*' ) {
452  $isLoaded = isset( $this->loaded[$name] );
453  if ( $constraint === '*' || !$isLoaded ) {
454  return $isLoaded;
455  }
456  // if a specific constraint is requested, but no version is set, throw an exception
457  if ( !isset( $this->loaded[$name]['version'] ) ) {
458  $msg = "{$name} does not expose its version, but an extension or a skin"
459  . " requires: {$constraint}.";
460  throw new LogicException( $msg );
461  }
462 
463  return SemVer::satisfies( $this->loaded[$name]['version'], $constraint );
464  }
465 
470  public function getAttribute( $name ) {
471  return $this->testAttributes[$name] ??
472  $this->attributes[$name] ?? [];
473  }
474 
483  public function setAttributeForTest( $name, array $value ) {
484  // @codeCoverageIgnoreStart
485  if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
486  throw new RuntimeException( __METHOD__ . ' can only be used in tests' );
487  }
488  // @codeCoverageIgnoreEnd
489  if ( isset( $this->testAttributes[$name] ) ) {
490  throw new Exception( "The attribute '$name' has already been overridden" );
491  }
492  $this->testAttributes[$name] = $value;
493  return new ScopedCallback( function () use ( $name ) {
494  unset( $this->testAttributes[$name] );
495  } );
496  }
497 
503  public function getAllThings() {
504  return $this->loaded;
505  }
506 
514  protected function processAutoLoader( $dir, array $files ) {
515  // Make paths absolute, relative to the JSON file
516  foreach ( $files as &$file ) {
517  $file = "$dir/$file";
518  }
519  return $files;
520  }
521 }
static ExtensionRegistry $instance
const MANIFEST_VERSION
Version of the highest supported manifest version Note: Update MANIFEST_VERSION_MW_VERSION when chang...
$wgVersion
MediaWiki version number.
bool $finished
Whether we are done loading things.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Copyright (C) 2018 Kunal Mehta legoktm@member.fsf.org
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
Provides functions to check a set of extensions with dependencies against a set of loaded extensions ...
exportExtractedData(array $info)
$value
processAutoLoader( $dir, array $files)
Fully expand autoloader paths.
setAttributeForTest( $name, array $value)
Force override the value of an attribute during tests.
getAllThings()
Get information about all things.
array $loaded
Array of loaded things, keyed by name, values are credits information.
const MERGE_STRATEGY
Special key that defines the merge strategy.
getAbilities()
Get the list of abilities and their values.
clearQueue()
Clear the current load queue.
const MANIFEST_VERSION_MW_VERSION
MediaWiki version constraint representing what the current highest MANIFEST_VERSION is supported in...
const CACHE_VERSION
Bump whenever the registration cache needs resetting.
array $attributes
Items in the JSON file that aren&#39;t being set as globals.
load( $path)
Loads and processes the given JSON file without delay.
int bool $wgExtensionInfoMTime
When loading extensions through the extension registration system, this can be used to invalidate the...
$cache
Definition: mcc.php:33
const MEDIAWIKI_CORE
"requires" key that applies to MediaWiki core/$wgVersion
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
finish()
After this is called, no more extensions can be loaded.
$GLOBALS['IP']
const OLDEST_MANIFEST_VERSION
Version of the oldest supported manifest version.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
readFromQueue(array $queue)
Process a queue of extensions and return their extracted data.
array $queued
List of paths that should be loaded.
array $testAttributes
Attributes for testing.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
buildVersionChecker()
Queries information about the software environment and constructs an appropiate version checker...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
static newFromId( $id)
Create a new cache object of the specified type.
bool $checkDev
Whether to check dev-requires.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
static detectLocalServerCache()
Detects which local server cache library is present and returns a configuration for it...
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
static string [] $psr4Namespaces
Definition: AutoLoader.php:37
$wgDevelopmentWarnings
If set to true MediaWiki will throw notices for some possible error conditions and for deprecated fun...
isLoaded( $name, $constraint=' *')
Whether a thing has been loaded.
getQueue()
Get the current load queue.