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