Merge "Use {{int:}} on MediaWiki:Blockedtext and MediaWiki:Autoblockedtext"
[lhc/web/wiklou.git] / includes / registration / ExtensionRegistry.php
1 <?php
2
3 /**
4 * ExtensionRegistry class
5 *
6 * The Registry loads JSON files, and uses a Processor
7 * to extract information from them. It also registers
8 * classes with the autoloader.
9 *
10 * @since 1.25
11 */
12 class ExtensionRegistry {
13
14 /**
15 * "requires" key that applies to MediaWiki core/$wgVersion
16 */
17 const MEDIAWIKI_CORE = 'MediaWiki';
18
19 /**
20 * Version of the highest supported manifest version
21 * Note: Update MANIFEST_VERSION_MW_VERSION when changing this
22 */
23 const MANIFEST_VERSION = 2;
24
25 /**
26 * MediaWiki version constraint representing what the current
27 * highest MANIFEST_VERSION is supported in
28 */
29 const MANIFEST_VERSION_MW_VERSION = '>= 1.29.0';
30
31 /**
32 * Version of the oldest supported manifest version
33 */
34 const OLDEST_MANIFEST_VERSION = 1;
35
36 /**
37 * Bump whenever the registration cache needs resetting
38 */
39 const CACHE_VERSION = 6;
40
41 /**
42 * Special key that defines the merge strategy
43 *
44 * @since 1.26
45 */
46 const MERGE_STRATEGY = '_merge_strategy';
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 * @codeCoverageIgnore
84 * @return ExtensionRegistry
85 */
86 public static function getInstance() {
87 if ( self::$instance === null ) {
88 self::$instance = new self();
89 }
90
91 return self::$instance;
92 }
93
94 /**
95 * @param string $path Absolute path to the JSON file
96 */
97 public function queue( $path ) {
98 global $wgExtensionInfoMTime;
99
100 $mtime = $wgExtensionInfoMTime;
101 if ( $mtime === false ) {
102 if ( file_exists( $path ) ) {
103 $mtime = filemtime( $path );
104 } else {
105 throw new Exception( "$path does not exist!" );
106 }
107 // @codeCoverageIgnoreStart
108 if ( !$mtime ) {
109 $err = error_get_last();
110 throw new Exception( "Couldn't stat $path: {$err['message']}" );
111 // @codeCoverageIgnoreEnd
112 }
113 }
114 $this->queued[$path] = $mtime;
115 }
116
117 /**
118 * @throws MWException If the queue is already marked as finished (no further things should
119 * be loaded then).
120 */
121 public function loadFromQueue() {
122 global $wgVersion, $wgDevelopmentWarnings;
123 if ( !$this->queued ) {
124 return;
125 }
126
127 if ( $this->finished ) {
128 throw new MWException(
129 "The following paths tried to load late: "
130 . implode( ', ', array_keys( $this->queued ) )
131 );
132 }
133
134 // A few more things to vary the cache on
135 $versions = [
136 'registration' => self::CACHE_VERSION,
137 'mediawiki' => $wgVersion
138 ];
139
140 // We use a try/catch because we don't want to fail here
141 // if $wgObjectCaches is not configured properly for APC setup
142 try {
143 // Don't use MediaWikiServices here to prevent instantiating it before extensions have
144 // been loaded
145 $cacheId = ObjectCache::detectLocalServerCache();
146 $cache = ObjectCache::newFromId( $cacheId );
147 } catch ( MWException $e ) {
148 $cache = new EmptyBagOStuff();
149 }
150 // See if this queue is in APC
151 $key = $cache->makeKey(
152 'registration',
153 md5( json_encode( $this->queued + $versions ) )
154 );
155 $data = $cache->get( $key );
156 if ( $data ) {
157 $this->exportExtractedData( $data );
158 } else {
159 $data = $this->readFromQueue( $this->queued );
160 $this->exportExtractedData( $data );
161 // Do this late since we don't want to extract it since we already
162 // did that, but it should be cached
163 $data['globals']['wgAutoloadClasses'] += $data['autoload'];
164 unset( $data['autoload'] );
165 if ( !( $data['warnings'] && $wgDevelopmentWarnings ) ) {
166 // If there were no warnings that were shown, cache it
167 $cache->set( $key, $data, 60 * 60 * 24 );
168 }
169 }
170 $this->queued = [];
171 }
172
173 /**
174 * Get the current load queue. Not intended to be used
175 * outside of the installer.
176 *
177 * @return array
178 */
179 public function getQueue() {
180 return $this->queued;
181 }
182
183 /**
184 * Clear the current load queue. Not intended to be used
185 * outside of the installer.
186 */
187 public function clearQueue() {
188 $this->queued = [];
189 }
190
191 /**
192 * After this is called, no more extensions can be loaded
193 *
194 * @since 1.29
195 */
196 public function finish() {
197 $this->finished = true;
198 }
199
200 /**
201 * Process a queue of extensions and return their extracted data
202 *
203 * @param array $queue keys are filenames, values are ignored
204 * @return array extracted info
205 * @throws Exception
206 * @throws ExtensionDependencyError
207 */
208 public function readFromQueue( array $queue ) {
209 global $wgVersion;
210 $autoloadClasses = [];
211 $autoloadNamespaces = [];
212 $autoloaderPaths = [];
213 $processor = new ExtensionProcessor();
214 $versionChecker = new VersionChecker( $wgVersion );
215 $extDependencies = [];
216 $incompatible = [];
217 $warnings = false;
218 foreach ( $queue as $path => $mtime ) {
219 $json = file_get_contents( $path );
220 if ( $json === false ) {
221 throw new Exception( "Unable to read $path, does it exist?" );
222 }
223 $info = json_decode( $json, /* $assoc = */ true );
224 if ( !is_array( $info ) ) {
225 throw new Exception( "$path is not a valid JSON file." );
226 }
227
228 if ( !isset( $info['manifest_version'] ) ) {
229 wfDeprecated(
230 "{$info['name']}'s extension.json or skin.json does not have manifest_version",
231 '1.29'
232 );
233 $warnings = true;
234 // For backwards-compatability, assume a version of 1
235 $info['manifest_version'] = 1;
236 }
237 $version = $info['manifest_version'];
238 if ( $version < self::OLDEST_MANIFEST_VERSION || $version > self::MANIFEST_VERSION ) {
239 $incompatible[] = "$path: unsupported manifest_version: {$version}";
240 }
241
242 $dir = dirname( $path );
243 if ( isset( $info['AutoloadClasses'] ) ) {
244 $autoload = $this->processAutoLoader( $dir, $info['AutoloadClasses'] );
245 $GLOBALS['wgAutoloadClasses'] += $autoload;
246 $autoloadClasses += $autoload;
247 }
248 if ( isset( $info['AutoloadNamespaces'] ) ) {
249 $autoloadNamespaces += $this->processAutoLoader( $dir, $info['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
366 /**
367 * Loads and processes the given JSON file without delay
368 *
369 * If some extensions are already queued, this will load
370 * those as well.
371 *
372 * @param string $path Absolute path to the JSON file
373 */
374 public function load( $path ) {
375 $this->loadFromQueue(); // First clear the queue
376 $this->queue( $path );
377 $this->loadFromQueue();
378 }
379
380 /**
381 * Whether a thing has been loaded
382 * @param string $name
383 * @return bool
384 */
385 public function isLoaded( $name ) {
386 return isset( $this->loaded[$name] );
387 }
388
389 /**
390 * @param string $name
391 * @return array
392 */
393 public function getAttribute( $name ) {
394 if ( isset( $this->attributes[$name] ) ) {
395 return $this->attributes[$name];
396 } else {
397 return [];
398 }
399 }
400
401 /**
402 * Get information about all things
403 *
404 * @return array
405 */
406 public function getAllThings() {
407 return $this->loaded;
408 }
409
410 /**
411 * Fully expand autoloader paths
412 *
413 * @param string $dir
414 * @param array $files
415 * @return array
416 */
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 }