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