Merge "Add tags for undo edits"
[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 */
24 const MANIFEST_VERSION = 2;
25
26 /**
27 * Version of the oldest supported manifest version
28 */
29 const OLDEST_MANIFEST_VERSION = 1;
30
31 /**
32 * Bump whenever the registration cache needs resetting
33 */
34 const CACHE_VERSION = 6;
35
36 /**
37 * Special key that defines the merge strategy
38 *
39 * @since 1.26
40 */
41 const MERGE_STRATEGY = '_merge_strategy';
42
43 /**
44 * Array of loaded things, keyed by name, values are credits information
45 *
46 * @var array
47 */
48 private $loaded = [];
49
50 /**
51 * List of paths that should be loaded
52 *
53 * @var array
54 */
55 protected $queued = [];
56
57 /**
58 * Whether we are done loading things
59 *
60 * @var bool
61 */
62 private $finished = false;
63
64 /**
65 * Items in the JSON file that aren't being
66 * set as globals
67 *
68 * @var array
69 */
70 protected $attributes = [];
71
72 /**
73 * @var ExtensionRegistry
74 */
75 private static $instance;
76
77 /**
78 * @return ExtensionRegistry
79 */
80 public static function getInstance() {
81 if ( self::$instance === null ) {
82 self::$instance = new self();
83 }
84
85 return self::$instance;
86 }
87
88 /**
89 * @param string $path Absolute path to the JSON file
90 */
91 public function queue( $path ) {
92 global $wgExtensionInfoMTime;
93
94 $mtime = $wgExtensionInfoMTime;
95 if ( $mtime === false ) {
96 if ( file_exists( $path ) ) {
97 $mtime = filemtime( $path );
98 } else {
99 throw new Exception( "$path does not exist!" );
100 }
101 if ( !$mtime ) {
102 $err = error_get_last();
103 throw new Exception( "Couldn't stat $path: {$err['message']}" );
104 }
105 }
106 $this->queued[$path] = $mtime;
107 }
108
109 /**
110 * @throws MWException If the queue is already marked as finished (no further things should
111 * be loaded then).
112 */
113 public function loadFromQueue() {
114 global $wgVersion, $wgDevelopmentWarnings;
115 if ( !$this->queued ) {
116 return;
117 }
118
119 if ( $this->finished ) {
120 throw new MWException(
121 "The following paths tried to load late: "
122 . implode( ', ', array_keys( $this->queued ) )
123 );
124 }
125
126 // A few more things to vary the cache on
127 $versions = [
128 'registration' => self::CACHE_VERSION,
129 'mediawiki' => $wgVersion
130 ];
131
132 // We use a try/catch because we don't want to fail here
133 // if $wgObjectCaches is not configured properly for APC setup
134 try {
135 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
136 } catch ( MWException $e ) {
137 $cache = new EmptyBagOStuff();
138 }
139 // See if this queue is in APC
140 $key = $cache->makeKey(
141 'registration',
142 md5( json_encode( $this->queued + $versions ) )
143 );
144 $data = $cache->get( $key );
145 if ( $data ) {
146 $this->exportExtractedData( $data );
147 } else {
148 $data = $this->readFromQueue( $this->queued );
149 $this->exportExtractedData( $data );
150 // Do this late since we don't want to extract it since we already
151 // did that, but it should be cached
152 $data['globals']['wgAutoloadClasses'] += $data['autoload'];
153 unset( $data['autoload'] );
154 if ( !( $data['warnings'] && $wgDevelopmentWarnings ) ) {
155 // If there were no warnings that were shown, cache it
156 $cache->set( $key, $data, 60 * 60 * 24 );
157 }
158 }
159 $this->queued = [];
160 }
161
162 /**
163 * Get the current load queue. Not intended to be used
164 * outside of the installer.
165 *
166 * @return array
167 */
168 public function getQueue() {
169 return $this->queued;
170 }
171
172 /**
173 * Clear the current load queue. Not intended to be used
174 * outside of the installer.
175 */
176 public function clearQueue() {
177 $this->queued = [];
178 }
179
180 /**
181 * After this is called, no more extensions can be loaded
182 *
183 * @since 1.29
184 */
185 public function finish() {
186 $this->finished = true;
187 }
188
189 /**
190 * Process a queue of extensions and return their extracted data
191 *
192 * @param array $queue keys are filenames, values are ignored
193 * @return array extracted info
194 * @throws Exception
195 */
196 public function readFromQueue( array $queue ) {
197 global $wgVersion;
198 $autoloadClasses = [];
199 $autoloadNamespaces = [];
200 $autoloaderPaths = [];
201 $processor = new ExtensionProcessor();
202 $versionChecker = new VersionChecker( $wgVersion );
203 $extDependencies = [];
204 $incompatible = [];
205 $warnings = false;
206 foreach ( $queue as $path => $mtime ) {
207 $json = file_get_contents( $path );
208 if ( $json === false ) {
209 throw new Exception( "Unable to read $path, does it exist?" );
210 }
211 $info = json_decode( $json, /* $assoc = */ true );
212 if ( !is_array( $info ) ) {
213 throw new Exception( "$path is not a valid JSON file." );
214 }
215
216 if ( !isset( $info['manifest_version'] ) ) {
217 wfDeprecated(
218 "{$info['name']}'s extension.json or skin.json does not have manifest_version",
219 '1.29'
220 );
221 $warnings = true;
222 // For backwards-compatability, assume a version of 1
223 $info['manifest_version'] = 1;
224 }
225 $version = $info['manifest_version'];
226 if ( $version < self::OLDEST_MANIFEST_VERSION || $version > self::MANIFEST_VERSION ) {
227 $incompatible[] = "$path: unsupported manifest_version: {$version}";
228 }
229
230 $dir = dirname( $path );
231 if ( isset( $info['AutoloadClasses'] ) ) {
232 $autoload = $this->processAutoLoader( $dir, $info['AutoloadClasses'] );
233 $GLOBALS['wgAutoloadClasses'] += $autoload;
234 $autoloadClasses += $autoload;
235 }
236 if ( isset( $info['AutoloadNamespaces'] ) ) {
237 $autoloadNamespaces += $this->processAutoLoader( $dir, $info['AutoloadNamespaces'] );
238 }
239
240 // get all requirements/dependencies for this extension
241 $requires = $processor->getRequirements( $info );
242
243 // validate the information needed and add the requirements
244 if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
245 $extDependencies[$info['name']] = $requires;
246 }
247
248 // Get extra paths for later inclusion
249 $autoloaderPaths = array_merge( $autoloaderPaths,
250 $processor->getExtraAutoloaderPaths( $dir, $info ) );
251 // Compatible, read and extract info
252 $processor->extractInfo( $path, $info, $version );
253 }
254 $data = $processor->getExtractedInfo();
255 $data['warnings'] = $warnings;
256
257 // check for incompatible extensions
258 $incompatible = array_merge(
259 $incompatible,
260 $versionChecker
261 ->setLoadedExtensionsAndSkins( $data['credits'] )
262 ->checkArray( $extDependencies )
263 );
264
265 if ( $incompatible ) {
266 if ( count( $incompatible ) === 1 ) {
267 throw new Exception( $incompatible[0] );
268 } else {
269 throw new Exception( implode( "\n", $incompatible ) );
270 }
271 }
272
273 // Need to set this so we can += to it later
274 $data['globals']['wgAutoloadClasses'] = [];
275 $data['autoload'] = $autoloadClasses;
276 $data['autoloaderPaths'] = $autoloaderPaths;
277 $data['autoloaderNS'] = $autoloadNamespaces;
278 return $data;
279 }
280
281 protected function exportExtractedData( array $info ) {
282 foreach ( $info['globals'] as $key => $val ) {
283 // If a merge strategy is set, read it and remove it from the value
284 // so it doesn't accidentally end up getting set.
285 if ( is_array( $val ) && isset( $val[self::MERGE_STRATEGY] ) ) {
286 $mergeStrategy = $val[self::MERGE_STRATEGY];
287 unset( $val[self::MERGE_STRATEGY] );
288 } else {
289 $mergeStrategy = 'array_merge';
290 }
291
292 // Optimistic: If the global is not set, or is an empty array, replace it entirely.
293 // Will be O(1) performance.
294 if ( !isset( $GLOBALS[$key] ) || ( is_array( $GLOBALS[$key] ) && !$GLOBALS[$key] ) ) {
295 $GLOBALS[$key] = $val;
296 continue;
297 }
298
299 if ( !is_array( $GLOBALS[$key] ) || !is_array( $val ) ) {
300 // config setting that has already been overridden, don't set it
301 continue;
302 }
303
304 switch ( $mergeStrategy ) {
305 case 'array_merge_recursive':
306 $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
307 break;
308 case 'array_replace_recursive':
309 $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
310 break;
311 case 'array_plus_2d':
312 $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
313 break;
314 case 'array_plus':
315 $GLOBALS[$key] += $val;
316 break;
317 case 'array_merge':
318 $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
319 break;
320 default:
321 throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
322 }
323 }
324
325 if ( isset( $info['autoloaderNS'] ) ) {
326 AutoLoader::$psr4Namespaces += $info['autoloaderNS'];
327 }
328
329 foreach ( $info['defines'] as $name => $val ) {
330 define( $name, $val );
331 }
332 foreach ( $info['autoloaderPaths'] as $path ) {
333 if ( file_exists( $path ) ) {
334 require_once $path;
335 }
336 }
337
338 $this->loaded += $info['credits'];
339 if ( $info['attributes'] ) {
340 if ( !$this->attributes ) {
341 $this->attributes = $info['attributes'];
342 } else {
343 $this->attributes = array_merge_recursive( $this->attributes, $info['attributes'] );
344 }
345 }
346
347 foreach ( $info['callbacks'] as $name => $cb ) {
348 if ( !is_callable( $cb ) ) {
349 if ( is_array( $cb ) ) {
350 $cb = '[ ' . implode( ', ', $cb ) . ' ]';
351 }
352 throw new UnexpectedValueException( "callback '$cb' is not callable" );
353 }
354 call_user_func( $cb, $info['credits'][$name] );
355 }
356 }
357
358 /**
359 * Loads and processes the given JSON file without delay
360 *
361 * If some extensions are already queued, this will load
362 * those as well.
363 *
364 * @param string $path Absolute path to the JSON file
365 */
366 public function load( $path ) {
367 $this->loadFromQueue(); // First clear the queue
368 $this->queue( $path );
369 $this->loadFromQueue();
370 }
371
372 /**
373 * Whether a thing has been loaded
374 * @param string $name
375 * @return bool
376 */
377 public function isLoaded( $name ) {
378 return isset( $this->loaded[$name] );
379 }
380
381 /**
382 * @param string $name
383 * @return array
384 */
385 public function getAttribute( $name ) {
386 if ( isset( $this->attributes[$name] ) ) {
387 return $this->attributes[$name];
388 } else {
389 return [];
390 }
391 }
392
393 /**
394 * Get information about all things
395 *
396 * @return array
397 */
398 public function getAllThings() {
399 return $this->loaded;
400 }
401
402 /**
403 * Mark a thing as loaded
404 *
405 * @param string $name
406 * @param array $credits
407 */
408 protected function markLoaded( $name, array $credits ) {
409 $this->loaded[$name] = $credits;
410 }
411
412 /**
413 * Fully expand autoloader paths
414 *
415 * @param string $dir
416 * @param array $files
417 * @return array
418 */
419 protected function processAutoLoader( $dir, array $files ) {
420 // Make paths absolute, relative to the JSON file
421 foreach ( $files as &$file ) {
422 $file = "$dir/$file";
423 }
424 return $files;
425 }
426 }