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