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