MediaWiki  master
ExtensionRegistry.php
Go to the documentation of this file.
1 <?php
2 
8 
19 
23  const MEDIAWIKI_CORE = 'MediaWiki';
24 
29  const MANIFEST_VERSION = 2;
30 
35  const MANIFEST_VERSION_MW_VERSION = '>= 1.29.0';
36 
41 
45  const CACHE_VERSION = 7;
46 
52  const MERGE_STRATEGY = '_merge_strategy';
53 
59  private $loaded = [];
60 
66  protected $queued = [];
67 
73  private $finished = false;
74 
81  protected $attributes = [];
82 
88  protected $testAttributes = [];
89 
95  protected $checkDev = false;
96 
100  private static $instance;
101 
106  public static function getInstance() {
107  if ( self::$instance === null ) {
108  self::$instance = new self();
109  }
110 
111  return self::$instance;
112  }
113 
118  public function setCheckDevRequires( $check ) {
119  $this->checkDev = $check;
120  }
121 
125  public function queue( $path ) {
126  global $wgExtensionInfoMTime;
127 
128  $mtime = $wgExtensionInfoMTime;
129  if ( $mtime === false ) {
130  AtEase::suppressWarnings();
131  $mtime = filemtime( $path );
132  AtEase::restoreWarnings();
133  // @codeCoverageIgnoreStart
134  if ( $mtime === false ) {
135  $err = error_get_last();
136  throw new Exception( "Unable to open file $path: {$err['message']}" );
137  // @codeCoverageIgnoreEnd
138  }
139  }
140  $this->queued[$path] = $mtime;
141  }
142 
147  public function loadFromQueue() {
149  if ( !$this->queued ) {
150  return;
151  }
152 
153  if ( $this->finished ) {
154  throw new MWException(
155  "The following paths tried to load late: "
156  . implode( ', ', array_keys( $this->queued ) )
157  );
158  }
159 
160  // A few more things to vary the cache on
161  $versions = [
162  'registration' => self::CACHE_VERSION,
163  'mediawiki' => $wgVersion,
164  'abilities' => $this->getAbilities(),
165  'checkDev' => $this->checkDev,
166  ];
167 
168  // We use a try/catch because we don't want to fail here
169  // if $wgObjectCaches is not configured properly for APC setup
170  try {
171  // Avoid MediaWikiServices to prevent instantiating it before extensions have loaded
173  $cache = ObjectCache::newFromParams( $wgObjectCaches[$cacheId] );
174  } catch ( InvalidArgumentException $e ) {
175  $cache = new EmptyBagOStuff();
176  }
177  // See if this queue is in APC
178  $key = $cache->makeKey(
179  'registration',
180  md5( json_encode( $this->queued + $versions ) )
181  );
182  $data = $cache->get( $key );
183  if ( $data ) {
184  $this->exportExtractedData( $data );
185  } else {
186  $data = $this->readFromQueue( $this->queued );
187  $this->exportExtractedData( $data );
188  // Do this late since we don't want to extract it since we already
189  // did that, but it should be cached
190  $data['globals']['wgAutoloadClasses'] += $data['autoload'];
191  unset( $data['autoload'] );
192  if ( !( $data['warnings'] && $wgDevelopmentWarnings ) ) {
193  // If there were no warnings that were shown, cache it
194  $cache->set( $key, $data, 60 * 60 * 24 );
195  }
196  }
197  $this->queued = [];
198  }
199 
206  public function getQueue() {
207  return $this->queued;
208  }
209 
214  public function clearQueue() {
215  $this->queued = [];
216  }
217 
223  public function finish() {
224  $this->finished = true;
225  }
226 
231  private function getAbilities() {
232  return [
233  'shell' => !Shell::isDisabled(),
234  ];
235  }
236 
242  private function buildVersionChecker() {
243  global $wgVersion;
244  // array to optionally specify more verbose error messages for
245  // missing abilities
246  $abilityErrors = [
247  'shell' => ( new ShellDisabledError() )->getMessage(),
248  ];
249 
250  return new VersionChecker(
251  $wgVersion,
252  PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION,
253  get_loaded_extensions(),
254  $this->getAbilities(),
255  $abilityErrors
256  );
257  }
258 
267  public function readFromQueue( array $queue ) {
268  $autoloadClasses = [];
269  $autoloadNamespaces = [];
270  $autoloaderPaths = [];
271  $processor = new ExtensionProcessor();
272  $versionChecker = $this->buildVersionChecker();
273  $extDependencies = [];
274  $warnings = false;
275  foreach ( $queue as $path => $mtime ) {
276  $json = file_get_contents( $path );
277  if ( $json === false ) {
278  throw new Exception( "Unable to read $path, does it exist?" );
279  }
280  $info = json_decode( $json, /* $assoc = */ true );
281  if ( !is_array( $info ) ) {
282  throw new Exception( "$path is not a valid JSON file." );
283  }
284 
285  if ( !isset( $info['manifest_version'] ) ) {
286  wfDeprecated(
287  "{$info['name']}'s extension.json or skin.json does not have manifest_version",
288  '1.29'
289  );
290  $warnings = true;
291  // For backwards-compatability, assume a version of 1
292  $info['manifest_version'] = 1;
293  }
294  $version = $info['manifest_version'];
295  if ( $version < self::OLDEST_MANIFEST_VERSION || $version > self::MANIFEST_VERSION ) {
296  throw new Exception( "$path: unsupported manifest_version: {$version}" );
297  }
298 
299  $dir = dirname( $path );
300  self::exportAutoloadClassesAndNamespaces(
301  $dir,
302  $info,
303  $autoloadClasses,
304  $autoloadNamespaces
305  );
306 
307  // get all requirements/dependencies for this extension
308  $requires = $processor->getRequirements( $info, $this->checkDev );
309 
310  // validate the information needed and add the requirements
311  if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
312  $extDependencies[$info['name']] = $requires;
313  }
314 
315  // Get extra paths for later inclusion
316  $autoloaderPaths = array_merge( $autoloaderPaths,
317  $processor->getExtraAutoloaderPaths( $dir, $info ) );
318  // Compatible, read and extract info
319  $processor->extractInfo( $path, $info, $version );
320  }
321  $data = $processor->getExtractedInfo();
322  $data['warnings'] = $warnings;
323 
324  // check for incompatible extensions
325  $incompatible = $versionChecker
326  ->setLoadedExtensionsAndSkins( $data['credits'] )
327  ->checkArray( $extDependencies );
328 
329  if ( $incompatible ) {
330  throw new ExtensionDependencyError( $incompatible );
331  }
332 
333  // Need to set this so we can += to it later
334  $data['globals']['wgAutoloadClasses'] = [];
335  $data['autoload'] = $autoloadClasses;
336  $data['autoloaderPaths'] = $autoloaderPaths;
337  $data['autoloaderNS'] = $autoloadNamespaces;
338  return $data;
339  }
340 
349  public static function exportAutoloadClassesAndNamespaces(
350  $dir, $info, &$autoloadClasses = [], &$autoloadNamespaces = []
351  ) {
352  if ( isset( $info['AutoloadClasses'] ) ) {
353  $autoload = self::processAutoLoader( $dir, $info['AutoloadClasses'] );
354  $GLOBALS['wgAutoloadClasses'] += $autoload;
355  $autoloadClasses += $autoload;
356  }
357  if ( isset( $info['AutoloadNamespaces'] ) ) {
358  $autoloadNamespaces += self::processAutoLoader( $dir, $info['AutoloadNamespaces'] );
359  AutoLoader::$psr4Namespaces += $autoloadNamespaces;
360  }
361  }
362 
363  protected function exportExtractedData( array $info ) {
364  foreach ( $info['globals'] as $key => $val ) {
365  // If a merge strategy is set, read it and remove it from the value
366  // so it doesn't accidentally end up getting set.
367  if ( is_array( $val ) && isset( $val[self::MERGE_STRATEGY] ) ) {
368  $mergeStrategy = $val[self::MERGE_STRATEGY];
369  unset( $val[self::MERGE_STRATEGY] );
370  } else {
371  $mergeStrategy = 'array_merge';
372  }
373 
374  // Optimistic: If the global is not set, or is an empty array, replace it entirely.
375  // Will be O(1) performance.
376  if ( !array_key_exists( $key, $GLOBALS ) || ( is_array( $GLOBALS[$key] ) && !$GLOBALS[$key] ) ) {
377  $GLOBALS[$key] = $val;
378  continue;
379  }
380 
381  if ( !is_array( $GLOBALS[$key] ) || !is_array( $val ) ) {
382  // config setting that has already been overridden, don't set it
383  continue;
384  }
385 
386  switch ( $mergeStrategy ) {
387  case 'array_merge_recursive':
388  $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
389  break;
390  case 'array_replace_recursive':
391  $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
392  break;
393  case 'array_plus_2d':
394  $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
395  break;
396  case 'array_plus':
397  $GLOBALS[$key] += $val;
398  break;
399  case 'array_merge':
400  $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
401  break;
402  default:
403  throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
404  }
405  }
406 
407  if ( isset( $info['autoloaderNS'] ) ) {
408  AutoLoader::$psr4Namespaces += $info['autoloaderNS'];
409  }
410 
411  foreach ( $info['defines'] as $name => $val ) {
412  define( $name, $val );
413  }
414  foreach ( $info['autoloaderPaths'] as $path ) {
415  if ( file_exists( $path ) ) {
416  require_once $path;
417  }
418  }
419 
420  $this->loaded += $info['credits'];
421  if ( $info['attributes'] ) {
422  if ( !$this->attributes ) {
423  $this->attributes = $info['attributes'];
424  } else {
425  $this->attributes = array_merge_recursive( $this->attributes, $info['attributes'] );
426  }
427  }
428 
429  foreach ( $info['callbacks'] as $name => $cb ) {
430  if ( !is_callable( $cb ) ) {
431  if ( is_array( $cb ) ) {
432  $cb = '[ ' . implode( ', ', $cb ) . ' ]';
433  }
434  throw new UnexpectedValueException( "callback '$cb' is not callable" );
435  }
436  $cb( $info['credits'][$name] );
437  }
438  }
439 
449  public function load( $path ) {
450  wfDeprecated( __METHOD__, '1.34' );
451  $this->loadFromQueue(); // First clear the queue
452  $this->queue( $path );
453  $this->loadFromQueue();
454  }
455 
464  public function isLoaded( $name, $constraint = '*' ) {
465  $isLoaded = isset( $this->loaded[$name] );
466  if ( $constraint === '*' || !$isLoaded ) {
467  return $isLoaded;
468  }
469  // if a specific constraint is requested, but no version is set, throw an exception
470  if ( !isset( $this->loaded[$name]['version'] ) ) {
471  $msg = "{$name} does not expose its version, but an extension or a skin"
472  . " requires: {$constraint}.";
473  throw new LogicException( $msg );
474  }
475 
476  return SemVer::satisfies( $this->loaded[$name]['version'], $constraint );
477  }
478 
483  public function getAttribute( $name ) {
484  return $this->testAttributes[$name] ??
485  $this->attributes[$name] ?? [];
486  }
487 
496  public function setAttributeForTest( $name, array $value ) {
497  // @codeCoverageIgnoreStart
498  if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
499  throw new RuntimeException( __METHOD__ . ' can only be used in tests' );
500  }
501  // @codeCoverageIgnoreEnd
502  if ( isset( $this->testAttributes[$name] ) ) {
503  throw new Exception( "The attribute '$name' has already been overridden" );
504  }
505  $this->testAttributes[$name] = $value;
506  return new ScopedCallback( function () use ( $name ) {
507  unset( $this->testAttributes[$name] );
508  } );
509  }
510 
516  public function getAllThings() {
517  return $this->loaded;
518  }
519 
527  protected static function processAutoLoader( $dir, array $files ) {
528  // Make paths absolute, relative to the JSON file
529  foreach ( $files as &$file ) {
530  $file = "$dir/$file";
531  }
532  return $files;
533  }
534 }
static ExtensionRegistry $instance
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
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.
Copyright (C) 2018 Kunal Mehta legoktm@member.fsf.org
static exportAutoloadClassesAndNamespaces( $dir, $info, &$autoloadClasses=[], &$autoloadNamespaces=[])
Export autoload classes and namespaces for a given directory and parsed JSON info file...
Provides functions to check a set of extensions with dependencies against a set of loaded extensions ...
exportExtractedData(array $info)
setAttributeForTest( $name, array $value)
Force override the value of an attribute during tests.
getAllThings()
Get information about all things.
const MERGE_STRATEGY
Special key that defines the merge strategy.
getAbilities()
Get the list of abilities and their values.
static processAutoLoader( $dir, array $files)
Fully expand autoloader paths.
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
finish()
After this is called, no more extensions can be loaded.
$GLOBALS['IP']
const OLDEST_MANIFEST_VERSION
Version of the oldest supported manifest version.
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.
static newFromParams( $params)
Create a new cache object from parameters.
buildVersionChecker()
Queries information about the software environment and constructs an appropiate version checker...
array [] $loaded
Array of loaded things, keyed by name, values are credits information.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
bool $checkDev
Whether to check dev-requires.
$wgObjectCaches
Advanced object cache configuration.
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.