Merge "Enable configuration to supply options for Special:Search form"
[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', and 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 'QUnitTestModule',
123 'ExtensionMessagesFiles',
124 'MessagesDirs',
125 'type',
126 'config',
127 'config_prefix',
128 'ServiceWiringFiles',
129 'ParserTestFiles',
130 'AutoloadClasses',
131 'manifest_version',
132 'load_composer_autoloader',
133 ];
134
135 /**
136 * Stuff that is going to be set to $GLOBALS
137 *
138 * Some keys are pre-set to arrays so we can += to them
139 *
140 * @var array
141 */
142 protected $globals = [
143 'wgExtensionMessagesFiles' => [],
144 'wgMessagesDirs' => [],
145 ];
146
147 /**
148 * Things that should be define()'d
149 *
150 * @var array
151 */
152 protected $defines = [];
153
154 /**
155 * Things to be called once registration of these extensions are done
156 * keyed by the name of the extension that it belongs to
157 *
158 * @var callable[]
159 */
160 protected $callbacks = [];
161
162 /**
163 * @var array
164 */
165 protected $credits = [];
166
167 /**
168 * @var array
169 */
170 protected $config = [];
171
172 /**
173 * Any thing else in the $info that hasn't
174 * already been processed
175 *
176 * @var array
177 */
178 protected $attributes = [];
179
180 /**
181 * Extension attributes, keyed by name =>
182 * settings.
183 *
184 * @var array
185 */
186 protected $extAttributes = [];
187
188 /**
189 * @param string $path
190 * @param array $info
191 * @param int $version manifest_version for info
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, $includeDev ) {
308 // Quick shortcuts
309 if ( !$includeDev || !isset( $info['dev-requires'] ) ) {
310 return $info['requires'] ?? [];
311 }
312
313 if ( !isset( $info['requires'] ) ) {
314 return $info['dev-requires'] ?? [];
315 }
316
317 // OK, we actually have to merge everything
318 $merged = [];
319
320 // Helper that combines version requirements by
321 // picking the non-null if one is, or combines
322 // the two. Note that it is not possible for
323 // both inputs to be null.
324 $pick = function ( $a, $b ) {
325 if ( $a === null ) {
326 return $b;
327 } elseif ( $b === null ) {
328 return $a;
329 } else {
330 return "$a $b";
331 }
332 };
333
334 $req = $info['requires'];
335 $dev = $info['dev-requires'];
336 if ( isset( $req['MediaWiki'] ) || isset( $dev['MediaWiki'] ) ) {
337 $merged['MediaWiki'] = $pick(
338 $req['MediaWiki'] ?? null,
339 $dev['MediaWiki'] ?? null
340 );
341 }
342
343 $platform = array_merge(
344 array_keys( $req['platform'] ?? [] ),
345 array_keys( $dev['platform'] ?? [] )
346 );
347 if ( $platform ) {
348 foreach ( $platform as $pkey ) {
349 if ( $pkey === 'php' ) {
350 $value = $pick(
351 $req['platform']['php'] ?? null,
352 $dev['platform']['php'] ?? null
353 );
354 } else {
355 // Prefer dev value, but these should be constant
356 // anyways (ext-* and ability-*)
357 $value = $dev['platform'][$pkey] ?? $req['platform'][$pkey];
358 }
359 $merged['platform'][$pkey] = $value;
360 }
361 }
362
363 foreach ( [ 'extensions', 'skins' ] as $thing ) {
364 $things = array_merge(
365 array_keys( $req[$thing] ?? [] ),
366 array_keys( $dev[$thing] ?? [] )
367 );
368 foreach ( $things as $name ) {
369 $merged[$thing][$name] = $pick(
370 $req[$thing][$name] ?? null,
371 $dev[$thing][$name] ?? null
372 );
373 }
374 }
375
376 return $merged;
377 }
378
379 protected function extractHooks( array $info ) {
380 if ( isset( $info['Hooks'] ) ) {
381 foreach ( $info['Hooks'] as $name => $value ) {
382 if ( is_array( $value ) ) {
383 foreach ( $value as $callback ) {
384 $this->globals['wgHooks'][$name][] = $callback;
385 }
386 } else {
387 $this->globals['wgHooks'][$name][] = $value;
388 }
389 }
390 }
391 }
392
393 /**
394 * Register namespaces with the appropriate global settings
395 *
396 * @param array $info
397 */
398 protected function extractNamespaces( array $info ) {
399 if ( isset( $info['namespaces'] ) ) {
400 foreach ( $info['namespaces'] as $ns ) {
401 if ( defined( $ns['constant'] ) ) {
402 // If the namespace constant is already defined, use it.
403 // This allows namespace IDs to be overwritten locally.
404 $id = constant( $ns['constant'] );
405 } else {
406 $id = $ns['id'];
407 $this->defines[ $ns['constant'] ] = $id;
408 }
409
410 if ( !( isset( $ns['conditional'] ) && $ns['conditional'] ) ) {
411 // If it is not conditional, register it
412 $this->attributes['ExtensionNamespaces'][$id] = $ns['name'];
413 }
414 if ( isset( $ns['gender'] ) ) {
415 $this->globals['wgExtraGenderNamespaces'][$id] = $ns['gender'];
416 }
417 if ( isset( $ns['subpages'] ) && $ns['subpages'] ) {
418 $this->globals['wgNamespacesWithSubpages'][$id] = true;
419 }
420 if ( isset( $ns['content'] ) && $ns['content'] ) {
421 $this->globals['wgContentNamespaces'][] = $id;
422 }
423 if ( isset( $ns['defaultcontentmodel'] ) ) {
424 $this->globals['wgNamespaceContentModels'][$id] = $ns['defaultcontentmodel'];
425 }
426 if ( isset( $ns['protection'] ) ) {
427 $this->globals['wgNamespaceProtection'][$id] = $ns['protection'];
428 }
429 if ( isset( $ns['capitallinkoverride'] ) ) {
430 $this->globals['wgCapitalLinkOverrides'][$id] = $ns['capitallinkoverride'];
431 }
432 }
433 }
434 }
435
436 protected function extractResourceLoaderModules( $dir, array $info ) {
437 $defaultPaths = $info['ResourceFileModulePaths'] ?? false;
438 if ( isset( $defaultPaths['localBasePath'] ) ) {
439 if ( $defaultPaths['localBasePath'] === '' ) {
440 // Avoid double slashes (e.g. /extensions/Example//path)
441 $defaultPaths['localBasePath'] = $dir;
442 } else {
443 $defaultPaths['localBasePath'] = "$dir/{$defaultPaths['localBasePath']}";
444 }
445 }
446
447 foreach ( [ 'ResourceModules', 'ResourceModuleSkinStyles' ] as $setting ) {
448 if ( isset( $info[$setting] ) ) {
449 foreach ( $info[$setting] as $name => $data ) {
450 if ( isset( $data['localBasePath'] ) ) {
451 if ( $data['localBasePath'] === '' ) {
452 // Avoid double slashes (e.g. /extensions/Example//path)
453 $data['localBasePath'] = $dir;
454 } else {
455 $data['localBasePath'] = "$dir/{$data['localBasePath']}";
456 }
457 }
458 if ( $defaultPaths ) {
459 $data += $defaultPaths;
460 }
461 $this->globals["wg$setting"][$name] = $data;
462 }
463 }
464 }
465
466 if ( isset( $info['QUnitTestModule'] ) ) {
467 $data = $info['QUnitTestModule'];
468 if ( isset( $data['localBasePath'] ) ) {
469 if ( $data['localBasePath'] === '' ) {
470 // Avoid double slashes (e.g. /extensions/Example//path)
471 $data['localBasePath'] = $dir;
472 } else {
473 $data['localBasePath'] = "$dir/{$data['localBasePath']}";
474 }
475 }
476 $this->attributes['QUnitTestModules']["test.{$info['name']}"] = $data;
477 }
478 }
479
480 protected function extractExtensionMessagesFiles( $dir, array $info ) {
481 if ( isset( $info['ExtensionMessagesFiles'] ) ) {
482 foreach ( $info['ExtensionMessagesFiles'] as &$file ) {
483 $file = "$dir/$file";
484 }
485 $this->globals["wgExtensionMessagesFiles"] += $info['ExtensionMessagesFiles'];
486 }
487 }
488
489 /**
490 * Set message-related settings, which need to be expanded to use
491 * absolute paths
492 *
493 * @param string $dir
494 * @param array $info
495 */
496 protected function extractMessagesDirs( $dir, array $info ) {
497 if ( isset( $info['MessagesDirs'] ) ) {
498 foreach ( $info['MessagesDirs'] as $name => $files ) {
499 foreach ( (array)$files as $file ) {
500 $this->globals["wgMessagesDirs"][$name][] = "$dir/$file";
501 }
502 }
503 }
504 }
505
506 /**
507 * @param string $path
508 * @param array $info
509 * @return string Name of thing
510 * @throws Exception
511 */
512 protected function extractCredits( $path, array $info ) {
513 $credits = [
514 'path' => $path,
515 'type' => $info['type'] ?? 'other',
516 ];
517 foreach ( self::$creditsAttributes as $attr ) {
518 if ( isset( $info[$attr] ) ) {
519 $credits[$attr] = $info[$attr];
520 }
521 }
522
523 $name = $credits['name'];
524
525 // If someone is loading the same thing twice, throw
526 // a nice error (T121493)
527 if ( isset( $this->credits[$name] ) ) {
528 $firstPath = $this->credits[$name]['path'];
529 $secondPath = $credits['path'];
530 throw new Exception( "It was attempted to load $name twice, from $firstPath and $secondPath." );
531 }
532
533 $this->credits[$name] = $credits;
534 $this->globals['wgExtensionCredits'][$credits['type']][] = $credits;
535
536 return $name;
537 }
538
539 /**
540 * Set configuration settings for manifest_version == 1
541 * @todo In the future, this should be done via Config interfaces
542 *
543 * @param array $info
544 */
545 protected function extractConfig1( array $info ) {
546 if ( isset( $info['config'] ) ) {
547 if ( isset( $info['config']['_prefix'] ) ) {
548 $prefix = $info['config']['_prefix'];
549 unset( $info['config']['_prefix'] );
550 } else {
551 $prefix = 'wg';
552 }
553 foreach ( $info['config'] as $key => $val ) {
554 if ( $key[0] !== '@' ) {
555 $this->addConfigGlobal( "$prefix$key", $val, $info['name'] );
556 }
557 }
558 }
559 }
560
561 /**
562 * Set configuration settings for manifest_version == 2
563 * @todo In the future, this should be done via Config interfaces
564 *
565 * @param array $info
566 * @param string $dir
567 */
568 protected function extractConfig2( array $info, $dir ) {
569 $prefix = $info['config_prefix'] ?? 'wg';
570 if ( isset( $info['config'] ) ) {
571 foreach ( $info['config'] as $key => $data ) {
572 $value = $data['value'];
573 if ( isset( $data['merge_strategy'] ) ) {
574 $value[ExtensionRegistry::MERGE_STRATEGY] = $data['merge_strategy'];
575 }
576 if ( isset( $data['path'] ) && $data['path'] ) {
577 $value = "$dir/$value";
578 }
579 $this->addConfigGlobal( "$prefix$key", $value, $info['name'] );
580 $data['providedby'] = $info['name'];
581 if ( isset( $info['ConfigRegistry'][0] ) ) {
582 $data['configregistry'] = array_keys( $info['ConfigRegistry'] )[0];
583 }
584 $this->config[$key] = $data;
585 }
586 }
587 }
588
589 /**
590 * Helper function to set a value to a specific global, if it isn't set already.
591 *
592 * @param string $key The config key with the prefix and anything
593 * @param mixed $value The value of the config
594 * @param string $extName Name of the extension
595 */
596 private function addConfigGlobal( $key, $value, $extName ) {
597 if ( array_key_exists( $key, $this->globals ) ) {
598 throw new RuntimeException(
599 "The configuration setting '$key' was already set by MediaWiki core or"
600 . " another extension, and cannot be set again by $extName." );
601 }
602 $this->globals[$key] = $value;
603 }
604
605 protected function extractPathBasedGlobal( $global, $dir, $paths ) {
606 foreach ( $paths as $path ) {
607 $this->globals[$global][] = "$dir/$path";
608 }
609 }
610
611 /**
612 * @param string $path
613 * @param string $name
614 * @param array $value
615 * @param array &$array
616 * @throws InvalidArgumentException
617 */
618 protected function storeToArray( $path, $name, $value, &$array ) {
619 if ( !is_array( $value ) ) {
620 throw new InvalidArgumentException( "The value for '$name' should be an array (from $path)" );
621 }
622 if ( isset( $array[$name] ) ) {
623 $array[$name] = array_merge_recursive( $array[$name], $value );
624 } else {
625 $array[$name] = $value;
626 }
627 }
628
629 public function getExtraAutoloaderPaths( $dir, array $info ) {
630 $paths = [];
631 if ( isset( $info['load_composer_autoloader'] ) && $info['load_composer_autoloader'] === true ) {
632 $paths[] = "$dir/vendor/autoload.php";
633 }
634 return $paths;
635 }
636 }