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 
92  private static $instance;
93 
98  public static function getInstance() {
99  if ( self::$instance === null ) {
100  self::$instance = new self();
101  }
102 
103  return self::$instance;
104  }
105 
109  public function queue( $path ) {
110  global $wgExtensionInfoMTime;
111 
112  $mtime = $wgExtensionInfoMTime;
113  if ( $mtime === false ) {
114  if ( file_exists( $path ) ) {
115  $mtime = filemtime( $path );
116  } else {
117  throw new Exception( "$path does not exist!" );
118  }
119  // @codeCoverageIgnoreStart
120  if ( $mtime === false ) {
121  $err = error_get_last();
122  throw new Exception( "Couldn't stat $path: {$err['message']}" );
123  // @codeCoverageIgnoreEnd
124  }
125  }
126  $this->queued[$path] = $mtime;
127  }
128 
133  public function loadFromQueue() {
135  if ( !$this->queued ) {
136  return;
137  }
138 
139  if ( $this->finished ) {
140  throw new MWException(
141  "The following paths tried to load late: "
142  . implode( ', ', array_keys( $this->queued ) )
143  );
144  }
145 
146  // A few more things to vary the cache on
147  $versions = [
148  'registration' => self::CACHE_VERSION,
149  'mediawiki' => $wgVersion,
150  'abilities' => $this->getAbilities(),
151  ];
152 
153  // We use a try/catch because we don't want to fail here
154  // if $wgObjectCaches is not configured properly for APC setup
155  try {
156  // Don't use MediaWikiServices here to prevent instantiating it before extensions have
157  // been loaded
159  $cache = ObjectCache::newFromId( $cacheId );
160  } catch ( InvalidArgumentException $e ) {
161  $cache = new EmptyBagOStuff();
162  }
163  // See if this queue is in APC
164  $key = $cache->makeKey(
165  'registration',
166  md5( json_encode( $this->queued + $versions ) )
167  );
168  $data = $cache->get( $key );
169  if ( $data ) {
170  $this->exportExtractedData( $data );
171  } else {
172  $data = $this->readFromQueue( $this->queued );
173  $this->exportExtractedData( $data );
174  // Do this late since we don't want to extract it since we already
175  // did that, but it should be cached
176  $data['globals']['wgAutoloadClasses'] += $data['autoload'];
177  unset( $data['autoload'] );
178  if ( !( $data['warnings'] && $wgDevelopmentWarnings ) ) {
179  // If there were no warnings that were shown, cache it
180  $cache->set( $key, $data, 60 * 60 * 24 );
181  }
182  }
183  $this->queued = [];
184  }
185 
192  public function getQueue() {
193  return $this->queued;
194  }
195 
200  public function clearQueue() {
201  $this->queued = [];
202  }
203 
209  public function finish() {
210  $this->finished = true;
211  }
212 
217  private function getAbilities() {
218  return [
219  'shell' => !Shell::isDisabled(),
220  ];
221  }
222 
228  private function buildVersionChecker() {
229  global $wgVersion;
230  // array to optionally specify more verbose error messages for
231  // missing abilities
232  $abilityErrors = [
233  'shell' => ( new ShellDisabledError() )->getMessage(),
234  ];
235 
236  return new VersionChecker(
237  $wgVersion,
238  PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION,
239  get_loaded_extensions(),
240  $this->getAbilities(),
241  $abilityErrors
242  );
243  }
244 
253  public function readFromQueue( array $queue ) {
254  $autoloadClasses = [];
255  $autoloadNamespaces = [];
256  $autoloaderPaths = [];
257  $processor = new ExtensionProcessor();
258  $versionChecker = $this->buildVersionChecker();
259  $extDependencies = [];
260  $incompatible = [];
261  $warnings = false;
262  foreach ( $queue as $path => $mtime ) {
263  $json = file_get_contents( $path );
264  if ( $json === false ) {
265  throw new Exception( "Unable to read $path, does it exist?" );
266  }
267  $info = json_decode( $json, /* $assoc = */ true );
268  if ( !is_array( $info ) ) {
269  throw new Exception( "$path is not a valid JSON file." );
270  }
271 
272  if ( !isset( $info['manifest_version'] ) ) {
273  wfDeprecated(
274  "{$info['name']}'s extension.json or skin.json does not have manifest_version",
275  '1.29'
276  );
277  $warnings = true;
278  // For backwards-compatability, assume a version of 1
279  $info['manifest_version'] = 1;
280  }
281  $version = $info['manifest_version'];
282  if ( $version < self::OLDEST_MANIFEST_VERSION || $version > self::MANIFEST_VERSION ) {
283  $incompatible[] = "$path: unsupported manifest_version: {$version}";
284  }
285 
286  $dir = dirname( $path );
287  if ( isset( $info['AutoloadClasses'] ) ) {
288  $autoload = $this->processAutoLoader( $dir, $info['AutoloadClasses'] );
289  $GLOBALS['wgAutoloadClasses'] += $autoload;
290  $autoloadClasses += $autoload;
291  }
292  if ( isset( $info['AutoloadNamespaces'] ) ) {
293  $autoloadNamespaces += $this->processAutoLoader( $dir, $info['AutoloadNamespaces'] );
294  AutoLoader::$psr4Namespaces += $autoloadNamespaces;
295  }
296 
297  // get all requirements/dependencies for this extension
298  $requires = $processor->getRequirements( $info );
299 
300  // validate the information needed and add the requirements
301  if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
302  $extDependencies[$info['name']] = $requires;
303  }
304 
305  // Get extra paths for later inclusion
306  $autoloaderPaths = array_merge( $autoloaderPaths,
307  $processor->getExtraAutoloaderPaths( $dir, $info ) );
308  // Compatible, read and extract info
309  $processor->extractInfo( $path, $info, $version );
310  }
311  $data = $processor->getExtractedInfo();
312  $data['warnings'] = $warnings;
313 
314  // check for incompatible extensions
315  $incompatible = array_merge(
316  $incompatible,
317  $versionChecker
318  ->setLoadedExtensionsAndSkins( $data['credits'] )
319  ->checkArray( $extDependencies )
320  );
321 
322  if ( $incompatible ) {
323  throw new ExtensionDependencyError( $incompatible );
324  }
325 
326  // Need to set this so we can += to it later
327  $data['globals']['wgAutoloadClasses'] = [];
328  $data['autoload'] = $autoloadClasses;
329  $data['autoloaderPaths'] = $autoloaderPaths;
330  $data['autoloaderNS'] = $autoloadNamespaces;
331  return $data;
332  }
333 
334  protected function exportExtractedData( array $info ) {
335  foreach ( $info['globals'] as $key => $val ) {
336  // If a merge strategy is set, read it and remove it from the value
337  // so it doesn't accidentally end up getting set.
338  if ( is_array( $val ) && isset( $val[self::MERGE_STRATEGY] ) ) {
339  $mergeStrategy = $val[self::MERGE_STRATEGY];
340  unset( $val[self::MERGE_STRATEGY] );
341  } else {
342  $mergeStrategy = 'array_merge';
343  }
344 
345  // Optimistic: If the global is not set, or is an empty array, replace it entirely.
346  // Will be O(1) performance.
347  if ( !array_key_exists( $key, $GLOBALS ) || ( is_array( $GLOBALS[$key] ) && !$GLOBALS[$key] ) ) {
348  $GLOBALS[$key] = $val;
349  continue;
350  }
351 
352  if ( !is_array( $GLOBALS[$key] ) || !is_array( $val ) ) {
353  // config setting that has already been overridden, don't set it
354  continue;
355  }
356 
357  switch ( $mergeStrategy ) {
358  case 'array_merge_recursive':
359  $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
360  break;
361  case 'array_replace_recursive':
362  $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
363  break;
364  case 'array_plus_2d':
365  $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
366  break;
367  case 'array_plus':
368  $GLOBALS[$key] += $val;
369  break;
370  case 'array_merge':
371  $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
372  break;
373  default:
374  throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
375  }
376  }
377 
378  if ( isset( $info['autoloaderNS'] ) ) {
379  AutoLoader::$psr4Namespaces += $info['autoloaderNS'];
380  }
381 
382  foreach ( $info['defines'] as $name => $val ) {
383  define( $name, $val );
384  }
385  foreach ( $info['autoloaderPaths'] as $path ) {
386  if ( file_exists( $path ) ) {
387  require_once $path;
388  }
389  }
390 
391  $this->loaded += $info['credits'];
392  if ( $info['attributes'] ) {
393  if ( !$this->attributes ) {
394  $this->attributes = $info['attributes'];
395  } else {
396  $this->attributes = array_merge_recursive( $this->attributes, $info['attributes'] );
397  }
398  }
399 
400  foreach ( $info['callbacks'] as $name => $cb ) {
401  if ( !is_callable( $cb ) ) {
402  if ( is_array( $cb ) ) {
403  $cb = '[ ' . implode( ', ', $cb ) . ' ]';
404  }
405  throw new UnexpectedValueException( "callback '$cb' is not callable" );
406  }
407  $cb( $info['credits'][$name] );
408  }
409  }
410 
420  public function load( $path ) {
421  wfDeprecated( __METHOD__, '1.34' );
422  $this->loadFromQueue(); // First clear the queue
423  $this->queue( $path );
424  $this->loadFromQueue();
425  }
426 
435  public function isLoaded( $name, $constraint = '*' ) {
436  $isLoaded = isset( $this->loaded[$name] );
437  if ( $constraint === '*' || !$isLoaded ) {
438  return $isLoaded;
439  }
440  // if a specific constraint is requested, but no version is set, throw an exception
441  if ( !isset( $this->loaded[$name]['version'] ) ) {
442  $msg = "{$name} does not expose its version, but an extension or a skin"
443  . " requires: {$constraint}.";
444  throw new LogicException( $msg );
445  }
446 
447  return SemVer::satisfies( $this->loaded[$name]['version'], $constraint );
448  }
449 
454  public function getAttribute( $name ) {
455  return $this->testAttributes[$name] ??
456  $this->attributes[$name] ?? [];
457  }
458 
467  public function setAttributeForTest( $name, array $value ) {
468  // @codeCoverageIgnoreStart
469  if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
470  throw new RuntimeException( __METHOD__ . ' can only be used in tests' );
471  }
472  // @codeCoverageIgnoreEnd
473  if ( isset( $this->testAttributes[$name] ) ) {
474  throw new Exception( "The attribute '$name' has already been overridden" );
475  }
476  $this->testAttributes[$name] = $value;
477  return new ScopedCallback( function () use ( $name ) {
478  unset( $this->testAttributes[$name] );
479  } );
480  }
481 
487  public function getAllThings() {
488  return $this->loaded;
489  }
490 
498  protected function processAutoLoader( $dir, array $files ) {
499  // Make paths absolute, relative to the JSON file
500  foreach ( $files as &$file ) {
501  $file = "$dir/$file";
502  }
503  return $files;
504  }
505 }
static ExtensionRegistry $instance
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
const MANIFEST_VERSION
Version of the highest supported manifest version Note: Update MANIFEST_VERSION_MW_VERSION when chang...
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
$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
ExtensionRegistry class.
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.
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.