Debian Codegraph @

includes/registration/ExtensionProcessor.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Registration;
4
5 use Exception;
6 use InvalidArgumentException;
7 use MediaWiki\MainConfigNames;
8 use MediaWiki\ResourceLoader\FilePath;
9 use RuntimeException;
10 use UnexpectedValueException;
11
12 /**
13 * Load extension manifests and then aggregate their contents.
14 *
15 * @ingroup ExtensionRegistry
16 * @newable since 1.39
17 */
18 class ExtensionProcessor implements Processor {
19
20 /**
21 * Keys that should be set to $GLOBALS
22 *
23 * @var array
24 */
25 protected static $globalSettings = [
26 MainConfigNames::ActionFilteredLogs,
27 MainConfigNames::Actions,
28 MainConfigNames::AddGroups,
29 MainConfigNames::APIFormatModules,
30 MainConfigNames::APIListModules,
31 MainConfigNames::APIMetaModules,
32 MainConfigNames::APIModules,
33 MainConfigNames::APIPropModules,
34 MainConfigNames::AuthManagerAutoConfig,
35 MainConfigNames::AvailableRights,
36 MainConfigNames::CentralIdLookupProviders,
37 MainConfigNames::ChangeCredentialsBlacklist,
38 MainConfigNames::ConditionalUserOptions,
39 MainConfigNames::ConfigRegistry,
40 MainConfigNames::ContentHandlers,
41 MainConfigNames::DefaultUserOptions,
42 MainConfigNames::ExtensionEntryPointListFiles,
43 MainConfigNames::ExtensionFunctions,
44 MainConfigNames::FeedClasses,
45 MainConfigNames::FileExtensions,
46 MainConfigNames::FilterLogTypes,
47 MainConfigNames::GrantPermissionGroups,
48 MainConfigNames::GrantPermissions,
49 MainConfigNames::GrantRiskGroups,
50 MainConfigNames::GroupPermissions,
51 MainConfigNames::GroupsAddToSelf,
52 MainConfigNames::GroupsRemoveFromSelf,
53 MainConfigNames::HiddenPrefs,
54 MainConfigNames::ImplicitGroups,
55 MainConfigNames::JobClasses,
56 MainConfigNames::LogActions,
57 MainConfigNames::LogActionsHandlers,
58 MainConfigNames::LogHeaders,
59 MainConfigNames::LogNames,
60 MainConfigNames::LogRestrictions,
61 MainConfigNames::LogTypes,
62 MainConfigNames::MediaHandlers,
63 MainConfigNames::OutputPipelineStages,
64 MainConfigNames::PasswordPolicy,
65 MainConfigNames::PrivilegedGroups,
66 MainConfigNames::RateLimits,
67 MainConfigNames::RawHtmlMessages,
68 MainConfigNames::ReauthenticateTime,
69 MainConfigNames::RecentChangesFlags,
70 MainConfigNames::RemoveCredentialsBlacklist,
71 MainConfigNames::RemoveGroups,
72 MainConfigNames::ResourceLoaderSources,
73 MainConfigNames::RevokePermissions,
74 MainConfigNames::SessionProviders,
75 MainConfigNames::SpecialPages,
76 MainConfigNames::UserRegistrationProviders,
77 ];
78
79 /**
80 * Top-level attributes that come from MW core
81 */
82 protected const CORE_ATTRIBS = [
83 'ParsoidModules',
84 'RestRoutes',
85 'SkinOOUIThemes',
86 'SkinCodexThemes',
87 'SearchMappings',
88 'TrackingCategories',
89 'LateJSConfigVarNames',
90 'TempUserSerialProviders',
91 'TempUserSerialMappings',
92 'DatabaseVirtualDomains',
93 'UserOptionsStoreProviders',
94 'LogParamsAllowedClasses',
95 ];
96
97 /**
98 * Mapping of global settings to their specific merge strategies.
99 *
100 * @see ExtensionRegistry::exportExtractedData
101 * @see getExtractedInfo
102 */
103 protected const MERGE_STRATEGIES = [
104 'wgAuthManagerAutoConfig' => 'array_plus_2d',
105 'wgCapitalLinkOverrides' => 'array_plus',
106 'wgExtraGenderNamespaces' => 'array_plus',
107 'wgGrantPermissions' => 'array_plus_2d',
108 'wgGroupPermissions' => 'array_plus_2d',
109 'wgHooks' => 'array_merge_recursive',
110 'wgNamespaceContentModels' => 'array_plus',
111 'wgNamespaceProtection' => 'array_plus',
112 'wgNamespacesWithSubpages' => 'array_plus',
113 'wgPasswordPolicy' => 'array_merge_recursive',
114 'wgRateLimits' => 'array_plus_2d',
115 'wgRevokePermissions' => 'array_plus_2d',
116 ];
117
118 /**
119 * Keys that are part of the extension credits
120 */
121 protected const CREDIT_ATTRIBS = [
122 'type',
123 'author',
124 'description',
125 'descriptionmsg',
126 'license-name',
127 'name',
128 'namemsg',
129 'url',
130 'version',
131 ];
132
133 /**
134 * Things that are not 'attributes', and are not in
135 * $globalSettings or CREDIT_ATTRIBS.
136 */
137 protected const NOT_ATTRIBS = [
138 'callback',
139 'config',
140 'config_prefix',
141 'load_composer_autoloader',
142 'manifest_version',
143 'namespaces',
144 'requires',
145 'AutoloadClasses',
146 'AutoloadNamespaces',
147 'ExtensionMessagesFiles',
148 'TranslationAliasesDirs',
149 'ForeignResourcesDir',
150 'Hooks',
151 'MessagePosterModule',
152 'MessagesDirs',
153 'OOUIThemePaths',
154 'QUnitTestModule',
155 'ResourceFileModulePaths',
156 'ResourceModuleSkinStyles',
157 'ResourceModules',
158 'ServiceWiringFiles',
159 ];
160
161 /**
162 * Stuff that is going to be set to $GLOBALS
163 *
164 * Some keys are pre-set to arrays, so we can += to them
165 *
166 * @var array
167 */
168 protected $globals = [
169 'wgExtensionMessagesFiles' => [],
170 'wgRestAPIAdditionalRouteFiles' => [],
171 'wgMessagesDirs' => [],
172 'TranslationAliasesDirs' => [],
173 ];
174
175 /**
176 * Things that should be define()'d
177 *
178 * @var array
179 */
180 protected $defines = [];
181
182 /**
183 * Things to be called once the registration of these extensions is done
184 *
185 * Keyed by the name of the extension that it belongs to
186 *
187 * @var callable[]
188 */
189 protected $callbacks = [];
190
191 /**
192 * @var array
193 */
194 protected $credits = [];
195
196 /**
197 * Autoloader information.
198 * Each element is an array of strings.
199 * 'files' is just a list, 'classes' and 'namespaces' are associative.
200 *
201 * @var string[][]
202 */
203 protected $autoload = [
204 'files' => [],
205 'classes' => [],
206 'namespaces' => [],
207 ];
208
209 /**
210 * Autoloader information for development.
211 * Same structure as $autoload.
212 *
213 * @var string[][]
214 */
215 protected $autoloadDev = [
216 'files' => [],
217 'classes' => [],
218 'namespaces' => [],
219 ];
220
221 /**
222 * Anything else in the $info that hasn't
223 * already been processed
224 *
225 * @var array
226 */
227 protected $attributes = [];
228
229 /**
230 * Extension attributes, keyed by name =>
231 * settings.
232 *
233 * @var array
234 */
235 protected $extAttributes = [];
236
237 /**
238 * Extracts extension info from the given JSON file.
239 *
240 * @param string $path
241 *
242 * @return void
243 */
244 public function extractInfoFromFile( string $path ) {
245 $json = file_get_contents( $path );
246 $info = json_decode( $json, true );
247
248 if ( !$info ) {
249 throw new RuntimeException( "Failed to load JSON data from $path" );
250 }
251
252 $this->extractInfo( $path, $info, $info['manifest_version'] );
253 }
254
255 /**
256 * @param string $path
257 * @param array $info
258 * @param int $version manifest_version for info
259 */
260 public function extractInfo( $path, array $info, $version ) {
261 $dir = dirname( $path );
262 $this->extractHooks( $info, $path );
263 $this->extractExtensionMessagesFiles( $dir, $info );
264 $this->extractRestModuleFiles( $dir, $info );
265 $this->extractMessagesDirs( $dir, $info );
266 $this->extractTranslationAliasesDirs( $dir, $info );
267 $this->extractSkins( $dir, $info );
268 $this->extractSkinImportPaths( $dir, $info );
269 $this->extractNamespaces( $info );
270 $this->extractImplicitRights( $info );
271 $this->extractResourceLoaderModules( $dir, $info );
272 if ( isset( $info['ServiceWiringFiles'] ) ) {
273 $this->extractPathBasedGlobal(
274 'wgServiceWiringFiles',
275 $dir,
276 $info['ServiceWiringFiles']
277 );
278 }
279 $name = $this->extractCredits( $path, $info );
280 if ( isset( $info['callback'] ) ) {
281 $this->callbacks[$name] = $info['callback'];
282 }
283
284 $this->extractAutoload( $info, $dir );
285
286 // config should be after all core globals are extracted,
287 // so duplicate setting detection will work fully
288 if ( $version >= 2 ) {
289 $this->extractConfig2( $info, $dir );
290 } else {
291 // $version === 1
292 $this->extractConfig1( $info );
293 }
294
295 // Record the extension name in the ParsoidModules property
296 if ( isset( $info['ParsoidModules'] ) ) {
297 foreach ( $info['ParsoidModules'] as &$module ) {
298 if ( is_string( $module ) ) {
299 $className = $module;
300 $module = [
301 'class' => $className,
302 ];
303 }
304 $module['name'] = $name;
305 }
306 }
307
308 $this->extractForeignResourcesDir( $info, $name, $dir );
309
310 if ( $version >= 2 ) {
311 $this->extractAttributes( $path, $info );
312 }
313
314 foreach ( $info as $key => $val ) {
315 // If it's a global setting,
316 if ( in_array( $key, self::$globalSettings ) ) {
317 $this->storeToArrayRecursive( $path, "wg$key", $val, $this->globals );
318 continue;
319 }
320 // Ignore anything that starts with a @
321 if ( $key[0] === '@' ) {
322 continue;
323 }
324
325 if ( $version >= 2 ) {
326 // Only allowed attributes are set
327 if ( in_array( $key, self::CORE_ATTRIBS ) ) {
328 $this->storeToArray( $path, $key, $val, $this->attributes );
329 }
330 } else {
331 // version === 1
332 if ( !in_array( $key, self::NOT_ATTRIBS )
333 && !in_array( $key, self::CREDIT_ATTRIBS )
334 ) {
335 // If it's not disallowed, it's an attribute
336 $this->storeToArrayRecursive( $path, $key, $val, $this->attributes );
337 }
338 }
339 }
340 }
341
342 /**
343 * @param string $path
344 * @param array $info
345 */
346 protected function extractAttributes( $path, array $info ) {
347 if ( isset( $info['attributes'] ) ) {
348 foreach ( $info['attributes'] as $extName => $value ) {
349 $this->storeToArrayRecursive( $path, $extName, $value, $this->extAttributes );
350 }
351 }
352 }
353
354 public function getExtractedInfo( bool $includeDev = false ) {
355 // Make sure the merge strategies are set
356 foreach ( $this->globals as $key => $val ) {
357 if ( isset( self::MERGE_STRATEGIES[$key] ) ) {
358 $this->globals[$key][ExtensionRegistry::MERGE_STRATEGY] = self::MERGE_STRATEGIES[$key];
359 }
360 }
361
362 // Merge $this->extAttributes into $this->attributes depending on what is loaded
363 foreach ( $this->extAttributes as $extName => $value ) {
364 // Only set the attribute if $extName is loaded (and hence present in credits)
365 if ( isset( $this->credits[$extName] ) ) {
366 foreach ( $value as $attrName => $attrValue ) {
367 $this->storeToArrayRecursive(
368 '', // Don't provide a path since it's impossible to generate an error here
369 $extName . $attrName,
370 $attrValue,
371 $this->attributes
372 );
373 }
374 unset( $this->extAttributes[$extName] );
375 }
376 }
377
378 $autoload = $this->getExtractedAutoloadInfo( $includeDev );
379
380 return [
381 'globals' => $this->globals,
382 'defines' => $this->defines,
383 'callbacks' => $this->callbacks,
384 'credits' => $this->credits,
385 'attributes' => $this->attributes,
386 'autoloaderPaths' => $autoload['files'],
387 'autoloaderClasses' => $autoload['classes'],
388 'autoloaderNS' => $autoload['namespaces'],
389 ];
390 }
391
392 public function getRequirements( array $info, $includeDev ) {
393 // Quick shortcuts
394 if ( !$includeDev || !isset( $info['dev-requires'] ) ) {
395 return $info['requires'] ?? [];
396 }
397
398 if ( !isset( $info['requires'] ) ) {
399 return $info['dev-requires'] ?? [];
400 }
401
402 // OK, we actually have to merge everything
403 $merged = [];
404
405 // Helper that combines version requirements by
406 // picking the non-null if one is, or combines
407 // the two. Note that it is not possible for
408 // both inputs to be null.
409 $pick = static function ( $a, $b ) {
410 if ( $a === null ) {
411 return $b;
412 } elseif ( $b === null ) {
413 return $a;
414 } else {
415 return "$a $b";
416 }
417 };
418
419 $req = $info['requires'];
420 $dev = $info['dev-requires'];
421 if ( isset( $req['MediaWiki'] ) || isset( $dev['MediaWiki'] ) ) {
422 $merged['MediaWiki'] = $pick(
423 $req['MediaWiki'] ?? null,
424 $dev['MediaWiki'] ?? null
425 );
426 }
427
428 $platform = array_merge(
429 array_keys( $req['platform'] ?? [] ),
430 array_keys( $dev['platform'] ?? [] )
431 );
432 if ( $platform ) {
433 foreach ( $platform as $pkey ) {
434 if ( $pkey === 'php' ) {
435 $value = $pick(
436 $req['platform']['php'] ?? null,
437 $dev['platform']['php'] ?? null
438 );
439 } else {
440 // Prefer dev value, but these should be constant
441 // anyway (ext-* and ability-*)
442 $value = $dev['platform'][$pkey] ?? $req['platform'][$pkey];
443 }
444 $merged['platform'][$pkey] = $value;
445 }
446 }
447
448 foreach ( [ 'extensions', 'skins' ] as $thing ) {
449 $things = array_merge(
450 array_keys( $req[$thing] ?? [] ),
451 array_keys( $dev[$thing] ?? [] )
452 );
453 foreach ( $things as $name ) {
454 $merged[$thing][$name] = $pick(
455 $req[$thing][$name] ?? null,
456 $dev[$thing][$name] ?? null
457 );
458 }
459 }
460
461 return $merged;
462 }
463
464 /**
465 * When handler value is an array, set $wgHooks or Hooks attribute
466 * Could be legacy hook e.g. 'GlobalFunctionName' or non-legacy hook
467 * referencing a handler definition from 'HookHandler' attribute
468 *
469 * @param array $callback Handler
470 * @param array $hookHandlersAttr handler definitions from 'HookHandler' attribute
471 * @param string $name
472 * @param string $path extension.json file path
473 *
474 * @throws UnexpectedValueException
475 */
476 private function setArrayHookHandler(
477 array $callback,
478 array $hookHandlersAttr,
479 string $name,
480 string $path
481 ) {
482 if ( isset( $callback['handler'] ) ) {
483 $handlerName = $callback['handler'];
484 $handlerDefinition = $hookHandlersAttr[$handlerName] ?? false;
485 if ( !$handlerDefinition ) {
486 throw new UnexpectedValueException(
487 "Missing handler definition for $name in HookHandlers attribute in $path"
488 );
489 }
490 $callback['handler'] = $handlerDefinition;
491 $callback['extensionPath'] = $path;
492 $this->attributes['Hooks'][$name][] = $callback;
493 } else {
494 foreach ( $callback as $callable ) {
495 if ( is_array( $callable ) ) {
496 if ( isset( $callable['handler'] ) ) { // Non-legacy style handler
497 $this->setArrayHookHandler( $callable, $hookHandlersAttr, $name, $path );
498 } else { // Legacy style handler array
499 $this->globals['wgHooks'][$name][] = $callable;
500 }
501 } elseif ( is_string( $callable ) ) {
502 $this->setStringHookHandler( $callable, $hookHandlersAttr, $name, $path );
503 }
504 }
505 }
506 }
507
508 /**
509 * When handler value is a string, set $wgHooks or Hooks attribute.
510 * Could be legacy hook e.g. 'GlobalFunctionName' or non-legacy hook
511 * referencing a handler definition from 'HookHandler' attribute
512 *
513 * @param string $callback Handler
514 * @param array $hookHandlersAttr handler definitions from 'HookHandler' attribute
515 * @param string $name
516 * @param string $path
517 */
518 private function setStringHookHandler(
519 string $callback,
520 array $hookHandlersAttr,
521 string $name,
522 string $path
523 ) {
524 if ( isset( $hookHandlersAttr[$callback] ) ) {
525 $handler = [
526 'handler' => $hookHandlersAttr[$callback],
527 'extensionPath' => $path
528 ];
529 $this->attributes['Hooks'][$name][] = $handler;
530 } else { // legacy style handler
531 $this->globals['wgHooks'][$name][] = $callback;
532 }
533 }
534
535 /**
536 * Extract hook information from Hooks and HookHandler attributes.
537 * Store hook in $wgHooks if a legacy style handler or the 'Hooks' attribute if
538 * a non-legacy handler
539 *
540 * @param array $info attributes and associated values from extension.json
541 * @param string $path path to extension.json
542 */
543 protected function extractHooks( array $info, string $path ) {
544 $extName = $info['name'];
545 if ( isset( $info['Hooks'] ) ) {
546 $hookHandlersAttr = [];
547 foreach ( $info['HookHandlers'] ?? [] as $name => $def ) {
548 $hookHandlersAttr[$name] = [ 'name' => "$extName-$name" ] + $def;
549 }
550 foreach ( $info['Hooks'] as $name => $callback ) {
551 if ( is_string( $callback ) ) {
552 $this->setStringHookHandler( $callback, $hookHandlersAttr, $name, $path );
553 } elseif ( is_array( $callback ) ) {
554 $this->setArrayHookHandler( $callback, $hookHandlersAttr, $name, $path );
555 }
556 }
557 }
558 if ( isset( $info['DeprecatedHooks'] ) ) {
559 $deprecatedHooks = [];
560 foreach ( $info['DeprecatedHooks'] as $name => $deprecatedHookInfo ) {
561 $deprecatedHookInfo += [ 'component' => $extName ];
562 $deprecatedHooks[$name] = $deprecatedHookInfo;
563 }
564 if ( isset( $this->attributes['DeprecatedHooks'] ) ) {
565 $this->attributes['DeprecatedHooks'] += $deprecatedHooks;
566 } else {
567 $this->attributes['DeprecatedHooks'] = $deprecatedHooks;
568 }
569 }
570 }
571
572 /**
573 * Register namespaces with the appropriate global settings
574 *
575 * @param array $info
576 */
577 protected function extractNamespaces( array $info ) {
578 if ( isset( $info['namespaces'] ) ) {
579 foreach ( $info['namespaces'] as $ns ) {
580 if ( defined( $ns['constant'] ) ) {
581 // If the namespace constant is already defined, use it.
582 // This allows namespace IDs to be overwritten locally.
583 $id = constant( $ns['constant'] );
584 } else {
585 $id = $ns['id'];
586 }
587 $this->defines[ $ns['constant'] ] = $id;
588
589 if ( !( isset( $ns['conditional'] ) && $ns['conditional'] ) ) {
590 // If it is not conditional, register it
591 $this->attributes['ExtensionNamespaces'][$id] = $ns['name'];
592 }
593 if ( isset( $ns['movable'] ) && !$ns['movable'] ) {
594 $this->attributes['ImmovableNamespaces'][] = $id;
595 }
596 if ( isset( $ns['gender'] ) ) {
597 $this->globals['wgExtraGenderNamespaces'][$id] = $ns['gender'];
598 }
599 if ( isset( $ns['subpages'] ) && $ns['subpages'] ) {
600 $this->globals['wgNamespacesWithSubpages'][$id] = true;
601 }
602 if ( isset( $ns['content'] ) && $ns['content'] ) {
603 $this->globals['wgContentNamespaces'][] = $id;
604 }
605 if ( isset( $ns['defaultcontentmodel'] ) ) {
606 $this->globals['wgNamespaceContentModels'][$id] = $ns['defaultcontentmodel'];
607 }
608 if ( isset( $ns['protection'] ) ) {
609 $this->globals['wgNamespaceProtection'][$id] = $ns['protection'];
610 }
611 if ( isset( $ns['capitallinkoverride'] ) ) {
612 $this->globals['wgCapitalLinkOverrides'][$id] = $ns['capitallinkoverride'];
613 }
614 if ( isset( $ns['includable'] ) && !$ns['includable'] ) {
615 $this->globals['wgNonincludableNamespaces'][] = $id;
616 }
617 }
618 }
619 }
620
621 protected function extractResourceLoaderModules( $dir, array $info ) {
622 $defaultPaths = $info['ResourceFileModulePaths'] ?? false;
623 if ( isset( $defaultPaths['localBasePath'] ) ) {
624 if ( $defaultPaths['localBasePath'] === '' ) {
625 // Avoid double slashes (e.g. /extensions/Example//path)
626 $defaultPaths['localBasePath'] = $dir;
627 } else {
628 $defaultPaths['localBasePath'] = "$dir/{$defaultPaths['localBasePath']}";
629 }
630 }
631
632 foreach ( [ 'ResourceModules', 'ResourceModuleSkinStyles', 'OOUIThemePaths' ] as $setting ) {
633 if ( isset( $info[$setting] ) ) {
634 foreach ( $info[$setting] as $name => $data ) {
635 if ( isset( $data['localBasePath'] ) ) {
636 if ( $data['localBasePath'] === '' ) {
637 // Avoid double slashes (e.g. /extensions/Example//path)
638 $data['localBasePath'] = $dir;
639 } else {
640 $data['localBasePath'] = "$dir/{$data['localBasePath']}";
641 }
642 }
643 if ( $defaultPaths ) {
644 $data += $defaultPaths;
645 }
646 $this->attributes[$setting][$name] = $data;
647 }
648 }
649 }
650
651 if ( isset( $info['QUnitTestModule'] ) ) {
652 $data = $info['QUnitTestModule'];
653 if ( isset( $data['localBasePath'] ) ) {
654 if ( $data['localBasePath'] === '' ) {
655 // Avoid double slashes (e.g. /extensions/Example//path)
656 $data['localBasePath'] = $dir;
657 } else {
658 $data['localBasePath'] = "$dir/{$data['localBasePath']}";
659 }
660 }
661 $this->attributes['QUnitTestModules']["test.{$info['name']}"] = $data;
662 }
663
664 if ( isset( $info['MessagePosterModule'] ) ) {
665 $data = $info['MessagePosterModule'];
666 $basePath = $data['localBasePath'] ?? '';
667 $baseDir = $basePath === '' ? $dir : "$dir/$basePath";
668 foreach ( $data['scripts'] ?? [] as $scripts ) {
669 $this->attributes['MessagePosterModule']['scripts'][] =
670 new FilePath( $scripts, $baseDir );
671 }
672 foreach ( $data['dependencies'] ?? [] as $dependency ) {
673 $this->attributes['MessagePosterModule']['dependencies'][] = $dependency;
674 }
675 }
676 }
677
678 protected function extractExtensionMessagesFiles( $dir, array $info ) {
679 if ( isset( $info['ExtensionMessagesFiles'] ) ) {
680 foreach ( $info['ExtensionMessagesFiles'] as &$file ) {
681 $file = "$dir/$file";
682 }
683 $this->globals["wgExtensionMessagesFiles"] += $info['ExtensionMessagesFiles'];
684 }
685 }
686
687 protected function extractRestModuleFiles( $dir, array $info ) {
688 $var = MainConfigNames::RestAPIAdditionalRouteFiles;
689 if ( isset( $info['RestModuleFiles'] ) ) {
690 foreach ( $info['RestModuleFiles'] as &$file ) {
691 $this->globals["wg$var"][] = "$dir/$file";
692 }
693 }
694 }
695
696 /**
697 * Set message-related settings, which need to be expanded to use
698 * absolute paths
699 *
700 * @param string $dir
701 * @param array $info
702 */
703 protected function extractMessagesDirs( $dir, array $info ) {
704 if ( isset( $info['MessagesDirs'] ) ) {
705 foreach ( $info['MessagesDirs'] as $name => $files ) {
706 foreach ( (array)$files as $file ) {
707 $this->globals["wgMessagesDirs"][$name][] = "$dir/$file";
708 }
709 }
710 }
711 }
712
713 /**
714 * Set localization related settings, which need to be expanded to use
715 * absolute paths
716 *
717 * @param string $dir
718 * @param array $info
719 */
720 protected function extractTranslationAliasesDirs( $dir, array $info ) {
721 foreach ( $info['TranslationAliasesDirs'] ?? [] as $name => $files ) {
722 foreach ( (array)$files as $file ) {
723 $this->globals['wgTranslationAliasesDirs'][$name][] = "$dir/$file";
724 }
725 }
726 }
727
728 /**
729 * Extract skins and handle path correction for templateDirectory.
730 *
731 * @param string $dir
732 * @param array $info
733 */
734 protected function extractSkins( $dir, array $info ) {
735 if ( isset( $info['ValidSkinNames'] ) ) {
736 foreach ( $info['ValidSkinNames'] as $skinKey => $data ) {
737 if ( isset( $data['args'][0] ) ) {
738 $templateDirectory = $data['args'][0]['templateDirectory'] ?? 'templates';
739 $data['args'][0]['templateDirectory'] = $dir . '/' . $templateDirectory;
740 }
741 $this->globals['wgValidSkinNames'][$skinKey] = $data;
742 }
743 }
744 }
745
746 /**
747 * Extract any user rights that should be granted implicitly.
748 *
749 * @param array $info
750 */
751 protected function extractImplicitRights( array $info ) {
752 // Rate limits are only configurable for rights that are either in wgImplicitRights
753 // or in wgAvailableRights. Extensions that define rate limits should not have to
754 // explicitly add them to wgImplicitRights as well, we can do that automatically.
755
756 if ( isset( $info['RateLimits'] ) ) {
757 $rights = array_keys( $info['RateLimits'] );
758
759 if ( isset( $info['AvailableRights'] ) ) {
760 $rights = array_diff( $rights, $info['AvailableRights'] );
761 }
762
763 $this->globals['wgImplicitRights'] = array_merge(
764 $this->globals['wgImplicitRights'] ?? [],
765 $rights
766 );
767 }
768 }
769
770 /**
771 * @param string $dir
772 * @param array $info
773 */
774 protected function extractSkinImportPaths( $dir, array $info ) {
775 if ( isset( $info['SkinLessImportPaths'] ) ) {
776 foreach ( $info['SkinLessImportPaths'] as $skin => $subpath ) {
777 $this->attributes['SkinLessImportPaths'][$skin] = "$dir/$subpath";
778 }
779 }
780 }
781
782 /**
783 * @param string $path
784 * @param array $info
785 *
786 * @return string Name of thing
787 * @throws Exception
788 */
789 protected function extractCredits( $path, array $info ) {
790 $credits = [
791 'path' => $path,
792 'type' => 'other',
793 ];
794 foreach ( self::CREDIT_ATTRIBS as $attr ) {
795 if ( isset( $info[$attr] ) ) {
796 $credits[$attr] = $info[$attr];
797 }
798 }
799
800 $name = $credits['name'];
801
802 // If someone is loading the same thing twice, throw
803 // a nice error (T121493)
804 if ( isset( $this->credits[$name] ) ) {
805 $firstPath = $this->credits[$name]['path'];
806 $secondPath = $credits['path'];
807 throw new InvalidArgumentException(
808 "It was attempted to load $name twice, from $firstPath and $secondPath."
809 );
810 }
811
812 $this->credits[$name] = $credits;
813
814 return $name;
815 }
816
817 protected function extractForeignResourcesDir( array $info, string $name, string $dir ): void {
818 if ( array_key_exists( 'ForeignResourcesDir', $info ) ) {
819 if ( !is_string( $info['ForeignResourcesDir'] ) ) {
820 throw new InvalidArgumentException( "Incorrect ForeignResourcesDir type, must be a string (in $name)" );
821 }
822 $this->attributes['ForeignResourcesDir'][$name] = "{$dir}/{$info['ForeignResourcesDir']}";
823 }
824 }
825
826 /**
827 * Set configuration settings for manifest_version == 1
828 *
829 * @todo In the future, this should be done via Config interfaces
830 *
831 * @param array $info
832 */
833 protected function extractConfig1( array $info ) {
834 if ( isset( $info['config'] ) ) {
835 if ( isset( $info['config']['_prefix'] ) ) {
836 $prefix = $info['config']['_prefix'];
837 unset( $info['config']['_prefix'] );
838 } else {
839 $prefix = 'wg';
840 }
841 foreach ( $info['config'] as $key => $val ) {
842 if ( $key[0] !== '@' ) {
843 $this->addConfigGlobal( "$prefix$key", $val, $info['name'] );
844 }
845 }
846 }
847 }
848
849 /**
850 * Applies a base path to the given string or string array.
851 *
852 * @param string[] $value
853 * @param string $dir
854 *
855 * @return string[]
856 */
857 private function applyPath( array $value, string $dir ): array {
858 $result = [];
859
860 foreach ( $value as $k => $v ) {
861 $result[$k] = $dir . '/' . $v;
862 }
863
864 return $result;
865 }
866
867 /**
868 * Set configuration settings for manifest_version == 2
869 *
870 * @todo In the future, this should be done via Config interfaces
871 *
872 * @param array $info
873 * @param string $dir
874 */
875 protected function extractConfig2( array $info, $dir ) {
876 $prefix = $info['config_prefix'] ?? 'wg';
877 if ( isset( $info['config'] ) ) {
878 foreach ( $info['config'] as $key => $data ) {
879 if ( !array_key_exists( 'value', $data ) ) {
880 throw new UnexpectedValueException( "Missing value for config $key" );
881 }
882
883 $value = $data['value'];
884 if ( isset( $data['path'] ) && $data['path'] ) {
885 if ( is_array( $value ) ) {
886 $value = $this->applyPath( $value, $dir );
887 } else {
888 $value = "$dir/$value";
889 }
890 }
891 if ( isset( $data['merge_strategy'] ) ) {
892 $value[ExtensionRegistry::MERGE_STRATEGY] = $data['merge_strategy'];
893 }
894 $this->addConfigGlobal( "$prefix$key", $value, $info['name'] );
895 $data['providedby'] = $info['name'];
896 if ( isset( $info['ConfigRegistry'][0] ) ) {
897 $data['configregistry'] = array_keys( $info['ConfigRegistry'] )[0];
898 }
899 }
900 }
901 }
902
903 /**
904 * Helper function to set a value to a specific global config variable if it isn't set already.
905 *
906 * @param string $key The config key with the prefix and anything
907 * @param mixed $value The value of the config
908 * @param string $extName Name of the extension
909 */
910 private function addConfigGlobal( $key, $value, $extName ) {
911 if ( array_key_exists( $key, $this->globals ) ) {
912 throw new RuntimeException(
913 "The configuration setting '$key' was already set by MediaWiki core or"
914 . " another extension, and cannot be set again by $extName." );
915 }
916 if ( isset( $value[ExtensionRegistry::MERGE_STRATEGY] ) &&
917 $value[ExtensionRegistry::MERGE_STRATEGY] === 'array_merge_recursive' ) {
918 wfDeprecatedMsg(
919 "Using the array_merge_recursive merge strategy in extension.json and skin.json" .
920 " was deprecated in MediaWiki 1.42",
921 "1.42"
922 );
923 }
924 $this->globals[$key] = $value;
925 }
926
927 protected function extractPathBasedGlobal( $global, $dir, $paths ) {
928 foreach ( $paths as $path ) {
929 $this->globals[$global][] = "$dir/$path";
930 }
931 }
932
933 /**
934 * Stores $value to $array; using array_merge_recursive() if $array already contains $name
935 *
936 * @param string $path
937 * @param string $name
938 * @param array $value
939 * @param array &$array
940 *
941 */
942 protected function storeToArrayRecursive( $path, $name, $value, &$array ) {
943 if ( !is_array( $value ) ) {
944 throw new InvalidArgumentException( "The value for '$name' should be an array (from $path)" );
945 }
946 if ( isset( $array[$name] ) ) {
947 $array[$name] = array_merge_recursive( $array[$name], $value );
948 } else {
949 $array[$name] = $value;
950 }
951 }
952
953 /**
954 * Stores $value to $array; using array_merge() if $array already contains $name
955 *
956 * @param string $path
957 * @param string $name
958 * @param array $value
959 * @param array &$array
960 *
961 * @throws InvalidArgumentException
962 */
963 protected function storeToArray( $path, $name, $value, &$array ) {
964 if ( !is_array( $value ) ) {
965 throw new InvalidArgumentException( "The value for '$name' should be an array (from $path)" );
966 }
967 if ( isset( $array[$name] ) ) {
968 $array[$name] = array_merge( $array[$name], $value );
969 } else {
970 $array[$name] = $value;
971 }
972 }
973
974 /**
975 * Returns the extracted autoload info.
976 * The autoload info is returned as an associative array with three keys:
977 * - files: a list of files to load, for use with Autoloader::loadFile()
978 * - classes: a map of class names to files, for use with Autoloader::registerClass()
979 * - namespaces: a map of namespace names to directories, for use
980 * with Autoloader::registerNamespace()
981 *
982 * @since 1.39
983 *
984 * @param bool $includeDev
985 *
986 * @return array[] The autoload info.
987 */
988 public function getExtractedAutoloadInfo( bool $includeDev = false ): array {
989 $autoload = $this->autoload;
990
991 if ( $includeDev ) {
992 $autoload['classes'] += $this->autoloadDev['classes'];
993 $autoload['namespaces'] += $this->autoloadDev['namespaces'];
994
995 // NOTE: This is here for completeness. Per MW 1.39,
996 // $this->autoloadDev['files'] is always empty.
997 // So avoid the performance hit of array_merge().
998 if ( !empty( $this->autoloadDev['files'] ) ) {
999 // NOTE: Don't use += with numeric keys!
1000 // Could use PHPUtils::pushArray.
1001 $autoload['files'] = array_merge(
1002 $autoload['files'],
1003 $this->autoloadDev['files']
1004 );
1005 }
1006 }
1007
1008 return $autoload;
1009 }
1010
1011 /**
1012 * @param array $info
1013 * @param string $dir
1014 */
1015 private function extractAutoload( array $info, string $dir ) {
1016 if ( isset( $info['load_composer_autoloader'] ) && $info['load_composer_autoloader'] === true ) {
1017 $file = "$dir/vendor/autoload.php";
1018 if ( file_exists( $file ) ) {
1019 $this->autoload['files'][] = $file;
1020 }
1021 }
1022
1023 if ( isset( $info['AutoloadClasses'] ) ) {
1024 $paths = $this->applyPath( $info['AutoloadClasses'], $dir );
1025 $this->autoload['classes'] += $paths;
1026 }
1027
1028 if ( isset( $info['AutoloadNamespaces'] ) ) {
1029 $paths = $this->applyPath( $info['AutoloadNamespaces'], $dir );
1030 $this->autoload['namespaces'] += $paths;
1031 }
1032
1033 if ( isset( $info['TestAutoloadClasses'] ) ) {
1034 $paths = $this->applyPath( $info['TestAutoloadClasses'], $dir );
1035 $this->autoloadDev['classes'] += $paths;
1036 }
1037
1038 if ( isset( $info['TestAutoloadNamespaces'] ) ) {
1039 $paths = $this->applyPath( $info['TestAutoloadNamespaces'], $dir );
1040 $this->autoloadDev['namespaces'] += $paths;
1041 }
1042 }
1043 }
1044
1045 /** @deprecated class alias since 1.43 */
1046 class_alias( ExtensionProcessor::class, 'ExtensionProcessor' );