Merge "Handle missing namespace prefix in XML dumps more gracefully"
[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 = 5;
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;
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 = wfMemcKey(
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 $cache->set( $key, $data, 60 * 60 * 24 );
155 }
156 $this->queued = [];
157 }
158
159 /**
160 * Get the current load queue. Not intended to be used
161 * outside of the installer.
162 *
163 * @return array
164 */
165 public function getQueue() {
166 return $this->queued;
167 }
168
169 /**
170 * Clear the current load queue. Not intended to be used
171 * outside of the installer.
172 */
173 public function clearQueue() {
174 $this->queued = [];
175 }
176
177 /**
178 * After this is called, no more extensions can be loaded
179 *
180 * @since 1.29
181 */
182 public function finish() {
183 $this->finished = true;
184 }
185
186 /**
187 * Process a queue of extensions and return their extracted data
188 *
189 * @param array $queue keys are filenames, values are ignored
190 * @return array extracted info
191 * @throws Exception
192 */
193 public function readFromQueue( array $queue ) {
194 global $wgVersion;
195 $autoloadClasses = [];
196 $autoloaderPaths = [];
197 $processor = new ExtensionProcessor();
198 $versionChecker = new VersionChecker( $wgVersion );
199 $extDependencies = [];
200 $incompatible = [];
201 foreach ( $queue as $path => $mtime ) {
202 $json = file_get_contents( $path );
203 if ( $json === false ) {
204 throw new Exception( "Unable to read $path, does it exist?" );
205 }
206 $info = json_decode( $json, /* $assoc = */ true );
207 if ( !is_array( $info ) ) {
208 throw new Exception( "$path is not a valid JSON file." );
209 }
210
211 if ( !isset( $info['manifest_version'] ) ) {
212 // For backwards-compatability, assume a version of 1
213 $info['manifest_version'] = 1;
214 }
215 $version = $info['manifest_version'];
216 if ( $version < self::OLDEST_MANIFEST_VERSION || $version > self::MANIFEST_VERSION ) {
217 $incompatible[] = "$path: unsupported manifest_version: {$version}";
218 }
219
220 $autoload = $this->processAutoLoader( dirname( $path ), $info );
221 // Set up the autoloader now so custom processors will work
222 $GLOBALS['wgAutoloadClasses'] += $autoload;
223 $autoloadClasses += $autoload;
224
225 // get all requirements/dependencies for this extension
226 $requires = $processor->getRequirements( $info );
227
228 // validate the information needed and add the requirements
229 if ( is_array( $requires ) && $requires && isset( $info['name'] ) ) {
230 $extDependencies[$info['name']] = $requires;
231 }
232
233 // Get extra paths for later inclusion
234 $autoloaderPaths = array_merge( $autoloaderPaths,
235 $processor->getExtraAutoloaderPaths( dirname( $path ), $info ) );
236 // Compatible, read and extract info
237 $processor->extractInfo( $path, $info, $version );
238 }
239 $data = $processor->getExtractedInfo();
240
241 // check for incompatible extensions
242 $incompatible = array_merge(
243 $incompatible,
244 $versionChecker
245 ->setLoadedExtensionsAndSkins( $data['credits'] )
246 ->checkArray( $extDependencies )
247 );
248
249 if ( $incompatible ) {
250 if ( count( $incompatible ) === 1 ) {
251 throw new Exception( $incompatible[0] );
252 } else {
253 throw new Exception( implode( "\n", $incompatible ) );
254 }
255 }
256
257 // Need to set this so we can += to it later
258 $data['globals']['wgAutoloadClasses'] = [];
259 $data['autoload'] = $autoloadClasses;
260 $data['autoloaderPaths'] = $autoloaderPaths;
261 return $data;
262 }
263
264 protected function exportExtractedData( array $info ) {
265 foreach ( $info['globals'] as $key => $val ) {
266 // If a merge strategy is set, read it and remove it from the value
267 // so it doesn't accidentally end up getting set.
268 if ( is_array( $val ) && isset( $val[self::MERGE_STRATEGY] ) ) {
269 $mergeStrategy = $val[self::MERGE_STRATEGY];
270 unset( $val[self::MERGE_STRATEGY] );
271 } else {
272 $mergeStrategy = 'array_merge';
273 }
274
275 // Optimistic: If the global is not set, or is an empty array, replace it entirely.
276 // Will be O(1) performance.
277 if ( !isset( $GLOBALS[$key] ) || ( is_array( $GLOBALS[$key] ) && !$GLOBALS[$key] ) ) {
278 $GLOBALS[$key] = $val;
279 continue;
280 }
281
282 if ( !is_array( $GLOBALS[$key] ) || !is_array( $val ) ) {
283 // config setting that has already been overridden, don't set it
284 continue;
285 }
286
287 switch ( $mergeStrategy ) {
288 case 'array_merge_recursive':
289 $GLOBALS[$key] = array_merge_recursive( $GLOBALS[$key], $val );
290 break;
291 case 'array_replace_recursive':
292 $GLOBALS[$key] = array_replace_recursive( $GLOBALS[$key], $val );
293 break;
294 case 'array_plus_2d':
295 $GLOBALS[$key] = wfArrayPlus2d( $GLOBALS[$key], $val );
296 break;
297 case 'array_plus':
298 $GLOBALS[$key] += $val;
299 break;
300 case 'array_merge':
301 $GLOBALS[$key] = array_merge( $val, $GLOBALS[$key] );
302 break;
303 default:
304 throw new UnexpectedValueException( "Unknown merge strategy '$mergeStrategy'" );
305 }
306 }
307
308 foreach ( $info['defines'] as $name => $val ) {
309 define( $name, $val );
310 }
311 foreach ( $info['autoloaderPaths'] as $path ) {
312 require_once $path;
313 }
314
315 $this->loaded += $info['credits'];
316 if ( $info['attributes'] ) {
317 if ( !$this->attributes ) {
318 $this->attributes = $info['attributes'];
319 } else {
320 $this->attributes = array_merge_recursive( $this->attributes, $info['attributes'] );
321 }
322 }
323
324 foreach ( $info['callbacks'] as $name => $cb ) {
325 call_user_func( $cb, $info['credits'][$name] );
326 }
327 }
328
329 /**
330 * Loads and processes the given JSON file without delay
331 *
332 * If some extensions are already queued, this will load
333 * those as well.
334 *
335 * @param string $path Absolute path to the JSON file
336 */
337 public function load( $path ) {
338 $this->loadFromQueue(); // First clear the queue
339 $this->queue( $path );
340 $this->loadFromQueue();
341 }
342
343 /**
344 * Whether a thing has been loaded
345 * @param string $name
346 * @return bool
347 */
348 public function isLoaded( $name ) {
349 return isset( $this->loaded[$name] );
350 }
351
352 /**
353 * @param string $name
354 * @return array
355 */
356 public function getAttribute( $name ) {
357 if ( isset( $this->attributes[$name] ) ) {
358 return $this->attributes[$name];
359 } else {
360 return [];
361 }
362 }
363
364 /**
365 * Get information about all things
366 *
367 * @return array
368 */
369 public function getAllThings() {
370 return $this->loaded;
371 }
372
373 /**
374 * Mark a thing as loaded
375 *
376 * @param string $name
377 * @param array $credits
378 */
379 protected function markLoaded( $name, array $credits ) {
380 $this->loaded[$name] = $credits;
381 }
382
383 /**
384 * Register classes with the autoloader
385 *
386 * @param string $dir
387 * @param array $info
388 * @return array
389 */
390 protected function processAutoLoader( $dir, array $info ) {
391 if ( isset( $info['AutoloadClasses'] ) ) {
392 // Make paths absolute, relative to the JSON file
393 return array_map( function( $file ) use ( $dir ) {
394 return "$dir/$file";
395 }, $info['AutoloadClasses'] );
396 } else {
397 return [];
398 }
399 }
400 }