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