MediaWiki  REL1_31
ExtensionRegistry.php
Go to the documentation of this file.
1 <?php
2 
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 = 6;
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 ) {
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  $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
146  } catch ( MWException $e ) {
147  $cache = new EmptyBagOStuff();
148  }
149  // See if this queue is in APC
150  $key = $cache->makeKey(
151  'registration',
152  md5( json_encode( $this->queued + $versions ) )
153  );
154  $data = $cache->get( $key );
155  if ( $data ) {
156  $this->exportExtractedData( $data );
157  } else {
158  $data = $this->readFromQueue( $this->queued );
159  $this->exportExtractedData( $data );
160  // Do this late since we don't want to extract it since we already
161  // did that, but it should be cached
162  $data['globals']['wgAutoloadClasses'] += $data['autoload'];
163  unset( $data['autoload'] );
164  if ( !( $data['warnings'] && $wgDevelopmentWarnings ) ) {
165  // If there were no warnings that were shown, cache it
166  $cache->set( $key, $data, 60 * 60 * 24 );
167  }
168  }
169  $this->queued = [];
170  }
171 
178  public function getQueue() {
179  return $this->queued;
180  }
181 
186  public function clearQueue() {
187  $this->queued = [];
188  }
189 
195  public function finish() {
196  $this->finished = true;
197  }
198 
207  public function readFromQueue( array $queue ) {
209  $autoloadClasses = [];
210  $autoloadNamespaces = [];
211  $autoloaderPaths = [];
212  $processor = new ExtensionProcessor();
213  $versionChecker = new VersionChecker( $wgVersion );
214  $extDependencies = [];
215  $incompatible = [];
216  $warnings = false;
217  foreach ( $queue as $path => $mtime ) {
218  $json = file_get_contents( $path );
219  if ( $json === false ) {
220  throw new Exception( "Unable to read $path, does it exist?" );
221  }
222  $info = json_decode( $json, /* $assoc = */ true );
223  if ( !is_array( $info ) ) {
224  throw new Exception( "$path is not a valid JSON file." );
225  }
226 
227  if ( !isset( $info['manifest_version'] ) ) {
228  wfDeprecated(
229  "{$info['name']}'s extension.json or skin.json does not have manifest_version",
230  '1.29'
231  );
232  $warnings = true;
233  // For backwards-compatability, assume a version of 1
234  $info['manifest_version'] = 1;
235  }
236  $version = $info['manifest_version'];
237  if ( $version < self::OLDEST_MANIFEST_VERSION || $version > self::MANIFEST_VERSION ) {
238  $incompatible[] = "$path: unsupported manifest_version: {$version}";
239  }
240 
241  $dir = dirname( $path );
242  if ( isset( $info['AutoloadClasses'] ) ) {
243  $autoload = $this->processAutoLoader( $dir, $info['AutoloadClasses'] );
244  $GLOBALS['wgAutoloadClasses'] += $autoload;
245  $autoloadClasses += $autoload;
246  }
247  if ( isset( $info['AutoloadNamespaces'] ) ) {
248  $autoloadNamespaces += $this->processAutoLoader( $dir, $info['AutoloadNamespaces'] );
249  AutoLoader::$psr4Namespaces += $autoloadNamespaces;
250  }
251 
252  // get all requirements/dependencies for this extension
253  $requires = $processor->getRequirements( $info );
254 
255  // validate the information needed and add the requirements
256  if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
257  $extDependencies[$info['name']] = $requires;
258  }
259 
260  // Get extra paths for later inclusion
261  $autoloaderPaths = array_merge( $autoloaderPaths,
262  $processor->getExtraAutoloaderPaths( $dir, $info ) );
263  // Compatible, read and extract info
264  $processor->extractInfo( $path, $info, $version );
265  }
266  $data = $processor->getExtractedInfo();
267  $data['warnings'] = $warnings;
268 
269  // check for incompatible extensions
270  $incompatible = array_merge(
271  $incompatible,
272  $versionChecker
273  ->setLoadedExtensionsAndSkins( $data['credits'] )
274  ->checkArray( $extDependencies )
275  );
276 
277  if ( $incompatible ) {
278  throw new ExtensionDependencyError( $incompatible );
279  }
280 
281  // Need to set this so we can += to it later
282  $data['globals']['wgAutoloadClasses'] = [];
283  $data['autoload'] = $autoloadClasses;
284  $data['autoloaderPaths'] = $autoloaderPaths;
285  $data['autoloaderNS'] = $autoloadNamespaces;
286  return $data;
287  }
288 
289  protected function exportExtractedData( array $info ) {
290  foreach ( $info['globals'] as $key => $val ) {
291  // If a merge strategy is set, read it and remove it from the value
292  // so it doesn't accidentally end up getting set.
293  if ( is_array( $val ) && isset( $val[self::MERGE_STRATEGY] ) ) {
294  $mergeStrategy = $val[self::MERGE_STRATEGY];
295  unset( $val[self::MERGE_STRATEGY] );
296  } else {
297  $mergeStrategy = 'array_merge';
298  }
299 
300  // Optimistic: If the global is not set, or is an empty array, replace it entirely.
301  // Will be O(1) performance.
302  if ( !array_key_exists( $key, $GLOBALS ) || ( is_array( $GLOBALS[$key] ) && !$GLOBALS[$key] ) ) {
303  $GLOBALS[$key] = $val;
304  continue;
305  }
306 
307  if ( !is_array( $GLOBALS[$key] ) || !is_array( $val ) ) {
308  // config setting that has already been overridden, don't set it
309  continue;
310  }
311 
312  switch ( $mergeStrategy ) {
313  case 'array_merge_recursive':
314  $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
315  break;
316  case 'array_replace_recursive':
317  $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
318  break;
319  case 'array_plus_2d':
320  $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
321  break;
322  case 'array_plus':
323  $GLOBALS[$key] += $val;
324  break;
325  case 'array_merge':
326  $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
327  break;
328  default:
329  throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
330  }
331  }
332 
333  if ( isset( $info['autoloaderNS'] ) ) {
334  AutoLoader::$psr4Namespaces += $info['autoloaderNS'];
335  }
336 
337  foreach ( $info['defines'] as $name => $val ) {
338  define( $name, $val );
339  }
340  foreach ( $info['autoloaderPaths'] as $path ) {
341  if ( file_exists( $path ) ) {
342  require_once $path;
343  }
344  }
345 
346  $this->loaded += $info['credits'];
347  if ( $info['attributes'] ) {
348  if ( !$this->attributes ) {
349  $this->attributes = $info['attributes'];
350  } else {
351  $this->attributes = array_merge_recursive( $this->attributes, $info['attributes'] );
352  }
353  }
354 
355  foreach ( $info['callbacks'] as $name => $cb ) {
356  if ( !is_callable( $cb ) ) {
357  if ( is_array( $cb ) ) {
358  $cb = '[ ' . implode( ', ', $cb ) . ' ]';
359  }
360  throw new UnexpectedValueException( "callback '$cb' is not callable" );
361  }
362  call_user_func( $cb, $info['credits'][$name] );
363  }
364  }
365 
374  public function load( $path ) {
375  $this->loadFromQueue(); // First clear the queue
376  $this->queue( $path );
377  $this->loadFromQueue();
378  }
379 
385  public function isLoaded( $name ) {
386  return isset( $this->loaded[$name] );
387  }
388 
393  public function getAttribute( $name ) {
394  if ( isset( $this->attributes[$name] ) ) {
395  return $this->attributes[$name];
396  } else {
397  return [];
398  }
399  }
400 
406  public function getAllThings() {
407  return $this->loaded;
408  }
409 
417  protected function processAutoLoader( $dir, array $files ) {
418  // Make paths absolute, relative to the JSON file
419  foreach ( $files as &$file ) {
420  $file = "$dir/$file";
421  }
422  return $files;
423  }
424 }
ExtensionRegistry\getQueue
getQueue()
Get the current load queue.
Definition: ExtensionRegistry.php:178
ExtensionRegistry\$finished
bool $finished
Whether we are done loading things.
Definition: ExtensionRegistry.php:69
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
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:3427
ExtensionDependencyError
Copyright (C) 2018 Kunal Mehta legoktm@member.fsf.org
Definition: ExtensionDependencyError.php:24
array
the array() calling protocol came about after MediaWiki 1.4rc1.
ExtensionRegistry\exportExtractedData
exportExtractedData(array $info)
Definition: ExtensionRegistry.php:289
ExtensionRegistry
ExtensionRegistry class.
Definition: ExtensionRegistry.php:14
$wgVersion
$wgVersion
MediaWiki version number.
Definition: DefaultSettings.php:75
ExtensionRegistry\getAllThings
getAllThings()
Get information about all things.
Definition: ExtensionRegistry.php:406
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:417
ExtensionRegistry\clearQueue
clearQueue()
Clear the current load queue.
Definition: ExtensionRegistry.php:186
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:37
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\isLoaded
isLoaded( $name)
Whether a thing has been loaded.
Definition: ExtensionRegistry.php:385
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:1123
ExtensionRegistry\load
load( $path)
Loads and processes the given JSON file without delay.
Definition: ExtensionRegistry.php:374
$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
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:195
ExtensionRegistry\loadFromQueue
loadFromQueue()
Definition: ExtensionRegistry.php:123
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:95
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
ExtensionRegistry\readFromQueue
readFromQueue(array $queue)
Process a queue of extensions and return their extracted data.
Definition: ExtensionRegistry.php:207
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:6343
VersionChecker
Provides functions to check a set of extensions with dependencies against a set of loaded extensions ...
Definition: VersionChecker.php:32
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
$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:22
$wgExtensionInfoMTime
int bool $wgExtensionInfoMTime
When loading extensions through the extension registration system, this can be used to invalidate the...
Definition: DefaultSettings.php:2660
ExtensionRegistry\getAttribute
getAttribute( $name)
Definition: ExtensionRegistry.php:393
MediaWikiServices
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 MediaWikiServices
Definition: injection.txt:25
ExtensionRegistry\$instance
static ExtensionRegistry $instance
Definition: ExtensionRegistry.php:82
$GLOBALS
$GLOBALS['IP']
Definition: ComposerHookHandler.php:6
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2171