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