Merge "mw.widgets.UsersMultiselectWidget: Compat with mw.special.preferences.confirmC...
[lhc/web/wiklou.git] / includes / registration / ExtensionRegistry.php
1 <?php
2
3 use MediaWiki\MediaWikiServices;
4
5 /**
6 * ExtensionRegistry class
7 *
8 * The Registry loads JSON files, and uses a Processor
9 * to extract information from them. It also registers
10 * classes with the autoloader.
11 *
12 * @since 1.25
13 */
14 class ExtensionRegistry {
15
16 /**
17 * "requires" key that applies to MediaWiki core/$wgVersion
18 */
19 const MEDIAWIKI_CORE = 'MediaWiki';
20
21 /**
22 * Version of the highest supported manifest version
23 * Note: Update MANIFEST_VERSION_MW_VERSION when changing this
24 */
25 const MANIFEST_VERSION = 2;
26
27 /**
28 * MediaWiki version constraint representing what the current
29 * highest MANIFEST_VERSION is supported in
30 */
31 const MANIFEST_VERSION_MW_VERSION = '>= 1.29.0';
32
33 /**
34 * Version of the oldest supported manifest version
35 */
36 const OLDEST_MANIFEST_VERSION = 1;
37
38 /**
39 * Bump whenever the registration cache needs resetting
40 */
41 const CACHE_VERSION = 6;
42
43 /**
44 * Special key that defines the merge strategy
45 *
46 * @since 1.26
47 */
48 const MERGE_STRATEGY = '_merge_strategy';
49
50 /**
51 * Array of loaded things, keyed by name, values are credits information
52 *
53 * @var array
54 */
55 private $loaded = [];
56
57 /**
58 * List of paths that should be loaded
59 *
60 * @var array
61 */
62 protected $queued = [];
63
64 /**
65 * Whether we are done loading things
66 *
67 * @var bool
68 */
69 private $finished = false;
70
71 /**
72 * Items in the JSON file that aren't being
73 * set as globals
74 *
75 * @var array
76 */
77 protected $attributes = [];
78
79 /**
80 * @var ExtensionRegistry
81 */
82 private static $instance;
83
84 /**
85 * @codeCoverageIgnore
86 * @return ExtensionRegistry
87 */
88 public static function getInstance() {
89 if ( self::$instance === null ) {
90 self::$instance = new self();
91 }
92
93 return self::$instance;
94 }
95
96 /**
97 * @param string $path Absolute path to the JSON file
98 */
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 ) {
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
119 /**
120 * @throws MWException If the queue is already marked as finished (no further things should
121 * be loaded then).
122 */
123 public function loadFromQueue() {
124 global $wgVersion, $wgDevelopmentWarnings;
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
172 /**
173 * Get the current load queue. Not intended to be used
174 * outside of the installer.
175 *
176 * @return array
177 */
178 public function getQueue() {
179 return $this->queued;
180 }
181
182 /**
183 * Clear the current load queue. Not intended to be used
184 * outside of the installer.
185 */
186 public function clearQueue() {
187 $this->queued = [];
188 }
189
190 /**
191 * After this is called, no more extensions can be loaded
192 *
193 * @since 1.29
194 */
195 public function finish() {
196 $this->finished = true;
197 }
198
199 /**
200 * Process a queue of extensions and return their extracted data
201 *
202 * @param array $queue keys are filenames, values are ignored
203 * @return array extracted info
204 * @throws Exception
205 * @throws ExtensionDependencyError
206 */
207 public function readFromQueue( array $queue ) {
208 global $wgVersion;
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 }
250
251 // get all requirements/dependencies for this extension
252 $requires = $processor->getRequirements( $info );
253
254 // validate the information needed and add the requirements
255 if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
256 $extDependencies[$info['name']] = $requires;
257 }
258
259 // Get extra paths for later inclusion
260 $autoloaderPaths = array_merge( $autoloaderPaths,
261 $processor->getExtraAutoloaderPaths( $dir, $info ) );
262 // Compatible, read and extract info
263 $processor->extractInfo( $path, $info, $version );
264 }
265 $data = $processor->getExtractedInfo();
266 $data['warnings'] = $warnings;
267
268 // check for incompatible extensions
269 $incompatible = array_merge(
270 $incompatible,
271 $versionChecker
272 ->setLoadedExtensionsAndSkins( $data['credits'] )
273 ->checkArray( $extDependencies )
274 );
275
276 if ( $incompatible ) {
277 throw new ExtensionDependencyError( $incompatible );
278 }
279
280 // Need to set this so we can += to it later
281 $data['globals']['wgAutoloadClasses'] = [];
282 $data['autoload'] = $autoloadClasses;
283 $data['autoloaderPaths'] = $autoloaderPaths;
284 $data['autoloaderNS'] = $autoloadNamespaces;
285 return $data;
286 }
287
288 protected function exportExtractedData( array $info ) {
289 foreach ( $info['globals'] as $key => $val ) {
290 // If a merge strategy is set, read it and remove it from the value
291 // so it doesn't accidentally end up getting set.
292 if ( is_array( $val ) && isset( $val[self::MERGE_STRATEGY] ) ) {
293 $mergeStrategy = $val[self::MERGE_STRATEGY];
294 unset( $val[self::MERGE_STRATEGY] );
295 } else {
296 $mergeStrategy = 'array_merge';
297 }
298
299 // Optimistic: If the global is not set, or is an empty array, replace it entirely.
300 // Will be O(1) performance.
301 if ( !array_key_exists( $key, $GLOBALS ) || ( is_array( $GLOBALS[$key] ) && !$GLOBALS[$key] ) ) {
302 $GLOBALS[$key] = $val;
303 continue;
304 }
305
306 if ( !is_array( $GLOBALS[$key] ) || !is_array( $val ) ) {
307 // config setting that has already been overridden, don't set it
308 continue;
309 }
310
311 switch ( $mergeStrategy ) {
312 case 'array_merge_recursive':
313 $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
314 break;
315 case 'array_replace_recursive':
316 $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
317 break;
318 case 'array_plus_2d':
319 $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
320 break;
321 case 'array_plus':
322 $GLOBALS[$key] += $val;
323 break;
324 case 'array_merge':
325 $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
326 break;
327 default:
328 throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
329 }
330 }
331
332 if ( isset( $info['autoloaderNS'] ) ) {
333 AutoLoader::$psr4Namespaces += $info['autoloaderNS'];
334 }
335
336 foreach ( $info['defines'] as $name => $val ) {
337 define( $name, $val );
338 }
339 foreach ( $info['autoloaderPaths'] as $path ) {
340 if ( file_exists( $path ) ) {
341 require_once $path;
342 }
343 }
344
345 $this->loaded += $info['credits'];
346 if ( $info['attributes'] ) {
347 if ( !$this->attributes ) {
348 $this->attributes = $info['attributes'];
349 } else {
350 $this->attributes = array_merge_recursive( $this->attributes, $info['attributes'] );
351 }
352 }
353
354 foreach ( $info['callbacks'] as $name => $cb ) {
355 if ( !is_callable( $cb ) ) {
356 if ( is_array( $cb ) ) {
357 $cb = '[ ' . implode( ', ', $cb ) . ' ]';
358 }
359 throw new UnexpectedValueException( "callback '$cb' is not callable" );
360 }
361 call_user_func( $cb, $info['credits'][$name] );
362 }
363 }
364
365 /**
366 * Loads and processes the given JSON file without delay
367 *
368 * If some extensions are already queued, this will load
369 * those as well.
370 *
371 * @param string $path Absolute path to the JSON file
372 */
373 public function load( $path ) {
374 $this->loadFromQueue(); // First clear the queue
375 $this->queue( $path );
376 $this->loadFromQueue();
377 }
378
379 /**
380 * Whether a thing has been loaded
381 * @param string $name
382 * @return bool
383 */
384 public function isLoaded( $name ) {
385 return isset( $this->loaded[$name] );
386 }
387
388 /**
389 * @param string $name
390 * @return array
391 */
392 public function getAttribute( $name ) {
393 if ( isset( $this->attributes[$name] ) ) {
394 return $this->attributes[$name];
395 } else {
396 return [];
397 }
398 }
399
400 /**
401 * Get information about all things
402 *
403 * @return array
404 */
405 public function getAllThings() {
406 return $this->loaded;
407 }
408
409 /**
410 * Fully expand autoloader paths
411 *
412 * @param string $dir
413 * @param array $files
414 * @return array
415 */
416 protected function processAutoLoader( $dir, array $files ) {
417 // Make paths absolute, relative to the JSON file
418 foreach ( $files as &$file ) {
419 $file = "$dir/$file";
420 }
421 return $files;
422 }
423 }