MediaWiki  1.32.5
ExtensionRegistry.php
Go to the documentation of this file.
1 <?php
2 
3 use Composer\Semver\Semver;
4 
15 
19  const MEDIAWIKI_CORE = 'MediaWiki';
20 
25  const MANIFEST_VERSION = 2;
26 
31  const MANIFEST_VERSION_MW_VERSION = '>= 1.29.0';
32 
37 
41  const CACHE_VERSION = 7;
42 
48  const MERGE_STRATEGY = '_merge_strategy';
49 
55  private $loaded = [];
56 
62  protected $queued = [];
63 
69  private $finished = false;
70 
77  protected $attributes = [];
78 
82  private static $instance;
83 
88  public static function getInstance() {
89  if ( self::$instance === null ) {
90  self::$instance = new self();
91  }
92 
93  return self::$instance;
94  }
95 
99  public function queue( $path ) {
100  global $wgExtensionInfoMTime;
101 
102  $mtime = $wgExtensionInfoMTime;
103  if ( $mtime === false ) {
104  if ( file_exists( $path ) ) {
105  $mtime = filemtime( $path );
106  } else {
107  throw new Exception( "$path does not exist!" );
108  }
109  // @codeCoverageIgnoreStart
110  if ( $mtime === false ) {
111  $err = error_get_last();
112  throw new Exception( "Couldn't stat $path: {$err['message']}" );
113  // @codeCoverageIgnoreEnd
114  }
115  }
116  $this->queued[$path] = $mtime;
117  }
118 
123  public function loadFromQueue() {
125  if ( !$this->queued ) {
126  return;
127  }
128 
129  if ( $this->finished ) {
130  throw new MWException(
131  "The following paths tried to load late: "
132  . implode( ', ', array_keys( $this->queued ) )
133  );
134  }
135 
136  // A few more things to vary the cache on
137  $versions = [
138  'registration' => self::CACHE_VERSION,
139  'mediawiki' => $wgVersion
140  ];
141 
142  // We use a try/catch because we don't want to fail here
143  // if $wgObjectCaches is not configured properly for APC setup
144  try {
145  // Don't use MediaWikiServices here to prevent instantiating it before extensions have
146  // been loaded
148  $cache = ObjectCache::newFromId( $cacheId );
149  } catch ( InvalidArgumentException $e ) {
150  $cache = new EmptyBagOStuff();
151  }
152  // See if this queue is in APC
153  $key = $cache->makeKey(
154  'registration',
155  md5( json_encode( $this->queued + $versions ) )
156  );
157  $data = $cache->get( $key );
158  if ( $data ) {
159  $this->exportExtractedData( $data );
160  } else {
161  $data = $this->readFromQueue( $this->queued );
162  $this->exportExtractedData( $data );
163  // Do this late since we don't want to extract it since we already
164  // did that, but it should be cached
165  $data['globals']['wgAutoloadClasses'] += $data['autoload'];
166  unset( $data['autoload'] );
167  if ( !( $data['warnings'] && $wgDevelopmentWarnings ) ) {
168  // If there were no warnings that were shown, cache it
169  $cache->set( $key, $data, 60 * 60 * 24 );
170  }
171  }
172  $this->queued = [];
173  }
174 
181  public function getQueue() {
182  return $this->queued;
183  }
184 
189  public function clearQueue() {
190  $this->queued = [];
191  }
192 
198  public function finish() {
199  $this->finished = true;
200  }
201 
210  public function readFromQueue( array $queue ) {
211  global $wgVersion;
212  $autoloadClasses = [];
213  $autoloadNamespaces = [];
214  $autoloaderPaths = [];
215  $processor = new ExtensionProcessor();
216  $versionChecker = new VersionChecker(
217  $wgVersion,
218  PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION,
219  get_loaded_extensions()
220  );
221  $extDependencies = [];
222  $incompatible = [];
223  $warnings = false;
224  foreach ( $queue as $path => $mtime ) {
225  $json = file_get_contents( $path );
226  if ( $json === false ) {
227  throw new Exception( "Unable to read $path, does it exist?" );
228  }
229  $info = json_decode( $json, /* $assoc = */ true );
230  if ( !is_array( $info ) ) {
231  throw new Exception( "$path is not a valid JSON file." );
232  }
233 
234  if ( !isset( $info['manifest_version'] ) ) {
235  wfDeprecated(
236  "{$info['name']}'s extension.json or skin.json does not have manifest_version",
237  '1.29'
238  );
239  $warnings = true;
240  // For backwards-compatability, assume a version of 1
241  $info['manifest_version'] = 1;
242  }
243  $version = $info['manifest_version'];
244  if ( $version < self::OLDEST_MANIFEST_VERSION || $version > self::MANIFEST_VERSION ) {
245  $incompatible[] = "$path: unsupported manifest_version: {$version}";
246  }
247 
248  $dir = dirname( $path );
249  if ( isset( $info['AutoloadClasses'] ) ) {
250  $autoload = $this->processAutoLoader( $dir, $info['AutoloadClasses'] );
251  $GLOBALS['wgAutoloadClasses'] += $autoload;
252  $autoloadClasses += $autoload;
253  }
254  if ( isset( $info['AutoloadNamespaces'] ) ) {
255  $autoloadNamespaces += $this->processAutoLoader( $dir, $info['AutoloadNamespaces'] );
256  AutoLoader::$psr4Namespaces += $autoloadNamespaces;
257  }
258 
259  // get all requirements/dependencies for this extension
260  $requires = $processor->getRequirements( $info );
261 
262  // validate the information needed and add the requirements
263  if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
264  $extDependencies[$info['name']] = $requires;
265  }
266 
267  // Get extra paths for later inclusion
268  $autoloaderPaths = array_merge( $autoloaderPaths,
269  $processor->getExtraAutoloaderPaths( $dir, $info ) );
270  // Compatible, read and extract info
271  $processor->extractInfo( $path, $info, $version );
272  }
273  $data = $processor->getExtractedInfo();
274  $data['warnings'] = $warnings;
275 
276  // check for incompatible extensions
277  $incompatible = array_merge(
278  $incompatible,
279  $versionChecker
280  ->setLoadedExtensionsAndSkins( $data['credits'] )
281  ->checkArray( $extDependencies )
282  );
283 
284  if ( $incompatible ) {
285  throw new ExtensionDependencyError( $incompatible );
286  }
287 
288  // Need to set this so we can += to it later
289  $data['globals']['wgAutoloadClasses'] = [];
290  $data['autoload'] = $autoloadClasses;
291  $data['autoloaderPaths'] = $autoloaderPaths;
292  $data['autoloaderNS'] = $autoloadNamespaces;
293  return $data;
294  }
295 
296  protected function exportExtractedData( array $info ) {
297  foreach ( $info['globals'] as $key => $val ) {
298  // If a merge strategy is set, read it and remove it from the value
299  // so it doesn't accidentally end up getting set.
300  if ( is_array( $val ) && isset( $val[self::MERGE_STRATEGY] ) ) {
301  $mergeStrategy = $val[self::MERGE_STRATEGY];
302  unset( $val[self::MERGE_STRATEGY] );
303  } else {
304  $mergeStrategy = 'array_merge';
305  }
306 
307  // Optimistic: If the global is not set, or is an empty array, replace it entirely.
308  // Will be O(1) performance.
309  if ( !array_key_exists( $key, $GLOBALS ) || ( is_array( $GLOBALS[$key] ) && !$GLOBALS[$key] ) ) {
310  $GLOBALS[$key] = $val;
311  continue;
312  }
313 
314  if ( !is_array( $GLOBALS[$key] ) || !is_array( $val ) ) {
315  // config setting that has already been overridden, don't set it
316  continue;
317  }
318 
319  switch ( $mergeStrategy ) {
320  case 'array_merge_recursive':
321  $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
322  break;
323  case 'array_replace_recursive':
324  $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
325  break;
326  case 'array_plus_2d':
327  $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
328  break;
329  case 'array_plus':
330  $GLOBALS[$key] += $val;
331  break;
332  case 'array_merge':
333  $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
334  break;
335  default:
336  throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
337  }
338  }
339 
340  if ( isset( $info['autoloaderNS'] ) ) {
341  AutoLoader::$psr4Namespaces += $info['autoloaderNS'];
342  }
343 
344  foreach ( $info['defines'] as $name => $val ) {
345  define( $name, $val );
346  }
347  foreach ( $info['autoloaderPaths'] as $path ) {
348  if ( file_exists( $path ) ) {
349  require_once $path;
350  }
351  }
352 
353  $this->loaded += $info['credits'];
354  if ( $info['attributes'] ) {
355  if ( !$this->attributes ) {
356  $this->attributes = $info['attributes'];
357  } else {
358  $this->attributes = array_merge_recursive( $this->attributes, $info['attributes'] );
359  }
360  }
361 
362  foreach ( $info['callbacks'] as $name => $cb ) {
363  if ( !is_callable( $cb ) ) {
364  if ( is_array( $cb ) ) {
365  $cb = '[ ' . implode( ', ', $cb ) . ' ]';
366  }
367  throw new UnexpectedValueException( "callback '$cb' is not callable" );
368  }
369  call_user_func( $cb, $info['credits'][$name] );
370  }
371  }
372 
381  public function load( $path ) {
382  $this->loadFromQueue(); // First clear the queue
383  $this->queue( $path );
384  $this->loadFromQueue();
385  }
386 
395  public function isLoaded( $name, $constraint = '*' ) {
396  $isLoaded = isset( $this->loaded[$name] );
397  if ( $constraint === '*' || !$isLoaded ) {
398  return $isLoaded;
399  }
400  // if a specific constraint is requested, but no version is set, throw an exception
401  if ( !isset( $this->loaded[$name]['version'] ) ) {
402  $msg = "{$name} does not expose its version, but an extension or a skin"
403  . " requires: {$constraint}.";
404  throw new LogicException( $msg );
405  }
406 
407  return SemVer::satisfies( $this->loaded[$name]['version'], $constraint );
408  }
409 
414  public function getAttribute( $name ) {
415  return $this->attributes[$name] ?? [];
416  }
417 
423  public function getAllThings() {
424  return $this->loaded;
425  }
426 
434  protected function processAutoLoader( $dir, array $files ) {
435  // Make paths absolute, relative to the JSON file
436  foreach ( $files as &$file ) {
437  $file = "$dir/$file";
438  }
439  return $files;
440  }
441 }
ObjectCache\newFromId
static newFromId( $id)
Create a new cache object of the specified type.
Definition: ObjectCache.php:122
ExtensionRegistry\isLoaded
isLoaded( $name, $constraint=' *')
Whether a thing has been loaded.
Definition: ExtensionRegistry.php:395
ExtensionRegistry\getQueue
getQueue()
Get the current load queue.
Definition: ExtensionRegistry.php:181
ExtensionRegistry\$finished
bool $finished
Whether we are done loading things.
Definition: ExtensionRegistry.php:69
ExtensionRegistry\MANIFEST_VERSION
const MANIFEST_VERSION
Version of the highest supported manifest version Note: Update MANIFEST_VERSION_MW_VERSION when chang...
Definition: ExtensionRegistry.php:25
ExtensionRegistry\queue
queue( $path)
Definition: ExtensionRegistry.php:99
EmptyBagOStuff
A BagOStuff object with no objects in it.
Definition: EmptyBagOStuff.php:29
wfArrayPlus2d
wfArrayPlus2d(array $baseArray, array $newValues)
Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
Definition: GlobalFunctions.php:3282
ExtensionDependencyError
Copyright (C) 2018 Kunal Mehta legoktm@member.fsf.org
Definition: ExtensionDependencyError.php:24
ObjectCache\detectLocalServerCache
static detectLocalServerCache()
Detects which local server cache library is present and returns a configuration for it.
Definition: ObjectCache.php:419
ExtensionRegistry\exportExtractedData
exportExtractedData(array $info)
Definition: ExtensionRegistry.php:296
ExtensionRegistry
ExtensionRegistry class.
Definition: ExtensionRegistry.php:14
$wgVersion
$wgVersion
MediaWiki version number.
Definition: DefaultSettings.php:74
ExtensionRegistry\getAllThings
getAllThings()
Get information about all things.
Definition: ExtensionRegistry.php:423
ExtensionRegistry\$loaded
array $loaded
Array of loaded things, keyed by name, values are credits information.
Definition: ExtensionRegistry.php:55
ExtensionRegistry\processAutoLoader
processAutoLoader( $dir, array $files)
Fully expand autoloader paths.
Definition: ExtensionRegistry.php:434
ExtensionRegistry\clearQueue
clearQueue()
Clear the current load queue.
Definition: ExtensionRegistry.php:189
php
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
ExtensionRegistry\MERGE_STRATEGY
const MERGE_STRATEGY
Special key that defines the merge strategy.
Definition: ExtensionRegistry.php:48
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:88
ExtensionProcessor
Definition: ExtensionProcessor.php:3
ExtensionRegistry\CACHE_VERSION
const CACHE_VERSION
Bump whenever the registration cache needs resetting.
Definition: ExtensionRegistry.php:41
MWException
MediaWiki exception.
Definition: MWException.php:26
ExtensionRegistry\$attributes
array $attributes
Items in the JSON file that aren't being set as globals.
Definition: ExtensionRegistry.php:77
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1118
ExtensionRegistry\load
load( $path)
Loads and processes the given JSON file without delay.
Definition: ExtensionRegistry.php:381
$queue
$queue
Definition: mergeMessageFileList.php:160
ExtensionRegistry\MANIFEST_VERSION_MW_VERSION
const MANIFEST_VERSION_MW_VERSION
MediaWiki version constraint representing what the current highest MANIFEST_VERSION is supported in.
Definition: ExtensionRegistry.php:31
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
AutoLoader\$psr4Namespaces
static string[] $psr4Namespaces
Definition: AutoLoader.php:37
ExtensionRegistry\finish
finish()
After this is called, no more extensions can be loaded.
Definition: ExtensionRegistry.php:198
ExtensionRegistry\loadFromQueue
loadFromQueue()
Definition: ExtensionRegistry.php:123
array
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))
ExtensionRegistry\OLDEST_MANIFEST_VERSION
const OLDEST_MANIFEST_VERSION
Version of the oldest supported manifest version.
Definition: ExtensionRegistry.php:36
ExtensionRegistry\MEDIAWIKI_CORE
const MEDIAWIKI_CORE
"requires" key that applies to MediaWiki core/$wgVersion
Definition: ExtensionRegistry.php:19
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2221
ExtensionRegistry\readFromQueue
readFromQueue(array $queue)
Process a queue of extensions and return their extracted data.
Definition: ExtensionRegistry.php:210
ExtensionRegistry\$queued
array $queued
List of paths that should be loaded.
Definition: ExtensionRegistry.php:62
$wgDevelopmentWarnings
$wgDevelopmentWarnings
If set to true MediaWiki will throw notices for some possible error conditions and for deprecated fun...
Definition: DefaultSettings.php:6356
VersionChecker
Provides functions to check a set of extensions with dependencies against a set of loaded extensions ...
Definition: VersionChecker.php:32
$cache
$cache
Definition: mcc.php:33
$path
$path
Definition: NoLocalSettings.php:25
as
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
$wgExtensionInfoMTime
int bool $wgExtensionInfoMTime
When loading extensions through the extension registration system, this can be used to invalidate the...
Definition: DefaultSettings.php:2714
ExtensionRegistry\getAttribute
getAttribute( $name)
Definition: ExtensionRegistry.php:414
ExtensionRegistry\$instance
static ExtensionRegistry $instance
Definition: ExtensionRegistry.php:82
$GLOBALS
$GLOBALS['IP']
Definition: ComposerHookHandler.php:6