registration: Improve duplicate config setting exception
[lhc/web/wiklou.git] / includes / registration / ExtensionProcessor.php
1 <?php
2
3 class ExtensionProcessor implements Processor {
4
5 /**
6 * Keys that should be set to $GLOBALS
7 *
8 * @var array
9 */
10 protected static $globalSettings = [
11 'ActionFilteredLogs',
12 'Actions',
13 'AddGroups',
14 'APIFormatModules',
15 'APIListModules',
16 'APIMetaModules',
17 'APIModules',
18 'APIPropModules',
19 'AuthManagerAutoConfig',
20 'AvailableRights',
21 'CentralIdLookupProviders',
22 'ChangeCredentialsBlacklist',
23 'ConfigRegistry',
24 'ContentHandlers',
25 'DefaultUserOptions',
26 'ExtensionEntryPointListFiles',
27 'ExtensionFunctions',
28 'FeedClasses',
29 'FileExtensions',
30 'FilterLogTypes',
31 'GrantPermissionGroups',
32 'GrantPermissions',
33 'GroupPermissions',
34 'GroupsAddToSelf',
35 'GroupsRemoveFromSelf',
36 'HiddenPrefs',
37 'ImplicitGroups',
38 'JobClasses',
39 'LogActions',
40 'LogActionsHandlers',
41 'LogHeaders',
42 'LogNames',
43 'LogRestrictions',
44 'LogTypes',
45 'MediaHandlers',
46 'PasswordPolicy',
47 'RateLimits',
48 'RecentChangesFlags',
49 'RemoveCredentialsBlacklist',
50 'RemoveGroups',
51 'ResourceLoaderLESSVars',
52 'ResourceLoaderSources',
53 'RevokePermissions',
54 'SessionProviders',
55 'SpecialPages',
56 'ValidSkinNames',
57 ];
58
59 /**
60 * Top-level attributes that come from MW core
61 *
62 * @var string[]
63 */
64 protected static $coreAttributes = [
65 'SkinOOUIThemes',
66 'TrackingCategories',
67 ];
68
69 /**
70 * Mapping of global settings to their specific merge strategies.
71 *
72 * @see ExtensionRegistry::exportExtractedData
73 * @see getExtractedInfo
74 * @var array
75 */
76 protected static $mergeStrategies = [
77 'wgAuthManagerAutoConfig' => 'array_plus_2d',
78 'wgCapitalLinkOverrides' => 'array_plus',
79 'wgExtensionCredits' => 'array_merge_recursive',
80 'wgExtraGenderNamespaces' => 'array_plus',
81 'wgGrantPermissions' => 'array_plus_2d',
82 'wgGroupPermissions' => 'array_plus_2d',
83 'wgHooks' => 'array_merge_recursive',
84 'wgNamespaceContentModels' => 'array_plus',
85 'wgNamespaceProtection' => 'array_plus',
86 'wgNamespacesWithSubpages' => 'array_plus',
87 'wgPasswordPolicy' => 'array_merge_recursive',
88 'wgRateLimits' => 'array_plus_2d',
89 'wgRevokePermissions' => 'array_plus_2d',
90 ];
91
92 /**
93 * Keys that are part of the extension credits
94 *
95 * @var array
96 */
97 protected static $creditsAttributes = [
98 'name',
99 'namemsg',
100 'author',
101 'version',
102 'url',
103 'description',
104 'descriptionmsg',
105 'license-name',
106 ];
107
108 /**
109 * Things that are not 'attributes', but are not in
110 * $globalSettings or $creditsAttributes.
111 *
112 * @var array
113 */
114 protected static $notAttributes = [
115 'callback',
116 'Hooks',
117 'namespaces',
118 'ResourceFileModulePaths',
119 'ResourceModules',
120 'ResourceModuleSkinStyles',
121 'ExtensionMessagesFiles',
122 'MessagesDirs',
123 'type',
124 'config',
125 'config_prefix',
126 'ServiceWiringFiles',
127 'ParserTestFiles',
128 'AutoloadClasses',
129 'manifest_version',
130 'load_composer_autoloader',
131 ];
132
133 /**
134 * Stuff that is going to be set to $GLOBALS
135 *
136 * Some keys are pre-set to arrays so we can += to them
137 *
138 * @var array
139 */
140 protected $globals = [
141 'wgExtensionMessagesFiles' => [],
142 'wgMessagesDirs' => [],
143 ];
144
145 /**
146 * Things that should be define()'d
147 *
148 * @var array
149 */
150 protected $defines = [];
151
152 /**
153 * Things to be called once registration of these extensions are done
154 * keyed by the name of the extension that it belongs to
155 *
156 * @var callable[]
157 */
158 protected $callbacks = [];
159
160 /**
161 * @var array
162 */
163 protected $credits = [];
164
165 /**
166 * Any thing else in the $info that hasn't
167 * already been processed
168 *
169 * @var array
170 */
171 protected $attributes = [];
172
173 /**
174 * Extension attributes, keyed by name =>
175 * settings.
176 *
177 * @var array
178 */
179 protected $extAttributes = [];
180
181 /**
182 * @param string $path
183 * @param array $info
184 * @param int $version manifest_version for info
185 * @return array
186 */
187 public function extractInfo( $path, array $info, $version ) {
188 $dir = dirname( $path );
189 $this->extractHooks( $info );
190 $this->extractExtensionMessagesFiles( $dir, $info );
191 $this->extractMessagesDirs( $dir, $info );
192 $this->extractNamespaces( $info );
193 $this->extractResourceLoaderModules( $dir, $info );
194 if ( isset( $info['ServiceWiringFiles'] ) ) {
195 $this->extractPathBasedGlobal(
196 'wgServiceWiringFiles',
197 $dir,
198 $info['ServiceWiringFiles']
199 );
200 }
201 if ( isset( $info['ParserTestFiles'] ) ) {
202 $this->extractPathBasedGlobal(
203 'wgParserTestFiles',
204 $dir,
205 $info['ParserTestFiles']
206 );
207 }
208 $name = $this->extractCredits( $path, $info );
209 if ( isset( $info['callback'] ) ) {
210 $this->callbacks[$name] = $info['callback'];
211 }
212
213 // config should be after all core globals are extracted,
214 // so duplicate setting detection will work fully
215 if ( $version === 2 ) {
216 $this->extractConfig2( $info, $dir );
217 } else {
218 // $version === 1
219 $this->extractConfig1( $info );
220 }
221
222 if ( $version === 2 ) {
223 $this->extractAttributes( $path, $info );
224 }
225
226 foreach ( $info as $key => $val ) {
227 // If it's a global setting,
228 if ( in_array( $key, self::$globalSettings ) ) {
229 $this->storeToArray( $path, "wg$key", $val, $this->globals );
230 continue;
231 }
232 // Ignore anything that starts with a @
233 if ( $key[0] === '@' ) {
234 continue;
235 }
236
237 if ( $version === 2 ) {
238 // Only whitelisted attributes are set
239 if ( in_array( $key, self::$coreAttributes ) ) {
240 $this->storeToArray( $path, $key, $val, $this->attributes );
241 }
242 } else {
243 // version === 1
244 if ( !in_array( $key, self::$notAttributes )
245 && !in_array( $key, self::$creditsAttributes )
246 ) {
247 // If it's not blacklisted, it's an attribute
248 $this->storeToArray( $path, $key, $val, $this->attributes );
249 }
250 }
251
252 }
253 }
254
255 /**
256 * @param string $path
257 * @param array $info
258 */
259 protected function extractAttributes( $path, array $info ) {
260 if ( isset( $info['attributes'] ) ) {
261 foreach ( $info['attributes'] as $extName => $value ) {
262 $this->storeToArray( $path, $extName, $value, $this->extAttributes );
263 }
264 }
265 }
266
267 public function getExtractedInfo() {
268 // Make sure the merge strategies are set
269 foreach ( $this->globals as $key => $val ) {
270 if ( isset( self::$mergeStrategies[$key] ) ) {
271 $this->globals[$key][ExtensionRegistry::MERGE_STRATEGY] = self::$mergeStrategies[$key];
272 }
273 }
274
275 // Merge $this->extAttributes into $this->attributes depending on what is loaded
276 foreach ( $this->extAttributes as $extName => $value ) {
277 // Only set the attribute if $extName is loaded (and hence present in credits)
278 if ( isset( $this->credits[$extName] ) ) {
279 foreach ( $value as $attrName => $attrValue ) {
280 $this->storeToArray(
281 '', // Don't provide a path since it's impossible to generate an error here
282 $extName . $attrName,
283 $attrValue,
284 $this->attributes
285 );
286 }
287 unset( $this->extAttributes[$extName] );
288 }
289 }
290
291 return [
292 'globals' => $this->globals,
293 'defines' => $this->defines,
294 'callbacks' => $this->callbacks,
295 'credits' => $this->credits,
296 'attributes' => $this->attributes,
297 ];
298 }
299
300 public function getRequirements( array $info ) {
301 return isset( $info['requires'] ) ? $info['requires'] : [];
302 }
303
304 protected function extractHooks( array $info ) {
305 if ( isset( $info['Hooks'] ) ) {
306 foreach ( $info['Hooks'] as $name => $value ) {
307 if ( is_array( $value ) ) {
308 foreach ( $value as $callback ) {
309 $this->globals['wgHooks'][$name][] = $callback;
310 }
311 } else {
312 $this->globals['wgHooks'][$name][] = $value;
313 }
314 }
315 }
316 }
317
318 /**
319 * Register namespaces with the appropriate global settings
320 *
321 * @param array $info
322 */
323 protected function extractNamespaces( array $info ) {
324 if ( isset( $info['namespaces'] ) ) {
325 foreach ( $info['namespaces'] as $ns ) {
326 if ( defined( $ns['constant'] ) ) {
327 // If the namespace constant is already defined, use it.
328 // This allows namespace IDs to be overwritten locally.
329 $id = constant( $ns['constant'] );
330 } else {
331 $id = $ns['id'];
332 $this->defines[ $ns['constant'] ] = $id;
333 }
334
335 if ( !( isset( $ns['conditional'] ) && $ns['conditional'] ) ) {
336 // If it is not conditional, register it
337 $this->attributes['ExtensionNamespaces'][$id] = $ns['name'];
338 }
339 if ( isset( $ns['gender'] ) ) {
340 $this->globals['wgExtraGenderNamespaces'][$id] = $ns['gender'];
341 }
342 if ( isset( $ns['subpages'] ) && $ns['subpages'] ) {
343 $this->globals['wgNamespacesWithSubpages'][$id] = true;
344 }
345 if ( isset( $ns['content'] ) && $ns['content'] ) {
346 $this->globals['wgContentNamespaces'][] = $id;
347 }
348 if ( isset( $ns['defaultcontentmodel'] ) ) {
349 $this->globals['wgNamespaceContentModels'][$id] = $ns['defaultcontentmodel'];
350 }
351 if ( isset( $ns['protection'] ) ) {
352 $this->globals['wgNamespaceProtection'][$id] = $ns['protection'];
353 }
354 if ( isset( $ns['capitallinkoverride'] ) ) {
355 $this->globals['wgCapitalLinkOverrides'][$id] = $ns['capitallinkoverride'];
356 }
357 }
358 }
359 }
360
361 protected function extractResourceLoaderModules( $dir, array $info ) {
362 $defaultPaths = isset( $info['ResourceFileModulePaths'] )
363 ? $info['ResourceFileModulePaths']
364 : false;
365 if ( isset( $defaultPaths['localBasePath'] ) ) {
366 if ( $defaultPaths['localBasePath'] === '' ) {
367 // Avoid double slashes (e.g. /extensions/Example//path)
368 $defaultPaths['localBasePath'] = $dir;
369 } else {
370 $defaultPaths['localBasePath'] = "$dir/{$defaultPaths['localBasePath']}";
371 }
372 }
373
374 foreach ( [ 'ResourceModules', 'ResourceModuleSkinStyles' ] as $setting ) {
375 if ( isset( $info[$setting] ) ) {
376 foreach ( $info[$setting] as $name => $data ) {
377 if ( isset( $data['localBasePath'] ) ) {
378 if ( $data['localBasePath'] === '' ) {
379 // Avoid double slashes (e.g. /extensions/Example//path)
380 $data['localBasePath'] = $dir;
381 } else {
382 $data['localBasePath'] = "$dir/{$data['localBasePath']}";
383 }
384 }
385 if ( $defaultPaths ) {
386 $data += $defaultPaths;
387 }
388 $this->globals["wg$setting"][$name] = $data;
389 }
390 }
391 }
392 }
393
394 protected function extractExtensionMessagesFiles( $dir, array $info ) {
395 if ( isset( $info['ExtensionMessagesFiles'] ) ) {
396 foreach ( $info['ExtensionMessagesFiles'] as &$file ) {
397 $file = "$dir/$file";
398 }
399 $this->globals["wgExtensionMessagesFiles"] += $info['ExtensionMessagesFiles'];
400 }
401 }
402
403 /**
404 * Set message-related settings, which need to be expanded to use
405 * absolute paths
406 *
407 * @param string $dir
408 * @param array $info
409 */
410 protected function extractMessagesDirs( $dir, array $info ) {
411 if ( isset( $info['MessagesDirs'] ) ) {
412 foreach ( $info['MessagesDirs'] as $name => $files ) {
413 foreach ( (array)$files as $file ) {
414 $this->globals["wgMessagesDirs"][$name][] = "$dir/$file";
415 }
416 }
417 }
418 }
419
420 /**
421 * @param string $path
422 * @param array $info
423 * @return string Name of thing
424 * @throws Exception
425 */
426 protected function extractCredits( $path, array $info ) {
427 $credits = [
428 'path' => $path,
429 'type' => isset( $info['type'] ) ? $info['type'] : 'other',
430 ];
431 foreach ( self::$creditsAttributes as $attr ) {
432 if ( isset( $info[$attr] ) ) {
433 $credits[$attr] = $info[$attr];
434 }
435 }
436
437 $name = $credits['name'];
438
439 // If someone is loading the same thing twice, throw
440 // a nice error (T121493)
441 if ( isset( $this->credits[$name] ) ) {
442 $firstPath = $this->credits[$name]['path'];
443 $secondPath = $credits['path'];
444 throw new Exception( "It was attempted to load $name twice, from $firstPath and $secondPath." );
445 }
446
447 $this->credits[$name] = $credits;
448 $this->globals['wgExtensionCredits'][$credits['type']][] = $credits;
449
450 return $name;
451 }
452
453 /**
454 * Set configuration settings for manifest_version == 1
455 * @todo In the future, this should be done via Config interfaces
456 *
457 * @param array $info
458 */
459 protected function extractConfig1( array $info ) {
460 if ( isset( $info['config'] ) ) {
461 if ( isset( $info['config']['_prefix'] ) ) {
462 $prefix = $info['config']['_prefix'];
463 unset( $info['config']['_prefix'] );
464 } else {
465 $prefix = 'wg';
466 }
467 foreach ( $info['config'] as $key => $val ) {
468 if ( $key[0] !== '@' ) {
469 $this->addConfigGlobal( "$prefix$key", $val, $info['name'] );
470 }
471 }
472 }
473 }
474
475 /**
476 * Set configuration settings for manifest_version == 2
477 * @todo In the future, this should be done via Config interfaces
478 *
479 * @param array $info
480 * @param string $dir
481 */
482 protected function extractConfig2( array $info, $dir ) {
483 if ( isset( $info['config_prefix'] ) ) {
484 $prefix = $info['config_prefix'];
485 } else {
486 $prefix = 'wg';
487 }
488 if ( isset( $info['config'] ) ) {
489 foreach ( $info['config'] as $key => $data ) {
490 $value = $data['value'];
491 if ( isset( $data['merge_strategy'] ) ) {
492 $value[ExtensionRegistry::MERGE_STRATEGY] = $data['merge_strategy'];
493 }
494 if ( isset( $data['path'] ) && $data['path'] ) {
495 $value = "$dir/$value";
496 }
497 $this->addConfigGlobal( "$prefix$key", $value, $info['name'] );
498 }
499 }
500 }
501
502 /**
503 * Helper function to set a value to a specific global, if it isn't set already.
504 *
505 * @param string $key The config key with the prefix and anything
506 * @param mixed $value The value of the config
507 * @param string $extName Name of the extension
508 */
509 private function addConfigGlobal( $key, $value, $extName ) {
510 if ( array_key_exists( $key, $this->globals ) ) {
511 throw new RuntimeException(
512 "The configuration setting '$key' was already set by MediaWiki core or"
513 . " another extension, and cannot be set again by $extName." );
514 }
515 $this->globals[$key] = $value;
516 }
517
518 protected function extractPathBasedGlobal( $global, $dir, $paths ) {
519 foreach ( $paths as $path ) {
520 $this->globals[$global][] = "$dir/$path";
521 }
522 }
523
524 /**
525 * @param string $path
526 * @param string $name
527 * @param array $value
528 * @param array &$array
529 * @throws InvalidArgumentException
530 */
531 protected function storeToArray( $path, $name, $value, &$array ) {
532 if ( !is_array( $value ) ) {
533 throw new InvalidArgumentException( "The value for '$name' should be an array (from $path)" );
534 }
535 if ( isset( $array[$name] ) ) {
536 $array[$name] = array_merge_recursive( $array[$name], $value );
537 } else {
538 $array[$name] = $value;
539 }
540 }
541
542 public function getExtraAutoloaderPaths( $dir, array $info ) {
543 $paths = [];
544 if ( isset( $info['load_composer_autoloader'] ) && $info['load_composer_autoloader'] === true ) {
545 $paths[] = "$dir/vendor/autoload.php";
546 }
547 return $paths;
548 }
549 }