Merge "Replace sorting classes with better naming convention"
[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 * @return array
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 ) {
309 return $info['requires'] ?? [];
310 }
311
312 protected function extractHooks( array $info ) {
313 if ( isset( $info['Hooks'] ) ) {
314 foreach ( $info['Hooks'] as $name => $value ) {
315 if ( is_array( $value ) ) {
316 foreach ( $value as $callback ) {
317 $this->globals['wgHooks'][$name][] = $callback;
318 }
319 } else {
320 $this->globals['wgHooks'][$name][] = $value;
321 }
322 }
323 }
324 }
325
326 /**
327 * Register namespaces with the appropriate global settings
328 *
329 * @param array $info
330 */
331 protected function extractNamespaces( array $info ) {
332 if ( isset( $info['namespaces'] ) ) {
333 foreach ( $info['namespaces'] as $ns ) {
334 if ( defined( $ns['constant'] ) ) {
335 // If the namespace constant is already defined, use it.
336 // This allows namespace IDs to be overwritten locally.
337 $id = constant( $ns['constant'] );
338 } else {
339 $id = $ns['id'];
340 $this->defines[ $ns['constant'] ] = $id;
341 }
342
343 if ( !( isset( $ns['conditional'] ) && $ns['conditional'] ) ) {
344 // If it is not conditional, register it
345 $this->attributes['ExtensionNamespaces'][$id] = $ns['name'];
346 }
347 if ( isset( $ns['gender'] ) ) {
348 $this->globals['wgExtraGenderNamespaces'][$id] = $ns['gender'];
349 }
350 if ( isset( $ns['subpages'] ) && $ns['subpages'] ) {
351 $this->globals['wgNamespacesWithSubpages'][$id] = true;
352 }
353 if ( isset( $ns['content'] ) && $ns['content'] ) {
354 $this->globals['wgContentNamespaces'][] = $id;
355 }
356 if ( isset( $ns['defaultcontentmodel'] ) ) {
357 $this->globals['wgNamespaceContentModels'][$id] = $ns['defaultcontentmodel'];
358 }
359 if ( isset( $ns['protection'] ) ) {
360 $this->globals['wgNamespaceProtection'][$id] = $ns['protection'];
361 }
362 if ( isset( $ns['capitallinkoverride'] ) ) {
363 $this->globals['wgCapitalLinkOverrides'][$id] = $ns['capitallinkoverride'];
364 }
365 }
366 }
367 }
368
369 protected function extractResourceLoaderModules( $dir, array $info ) {
370 $defaultPaths = $info['ResourceFileModulePaths'] ?? false;
371 if ( isset( $defaultPaths['localBasePath'] ) ) {
372 if ( $defaultPaths['localBasePath'] === '' ) {
373 // Avoid double slashes (e.g. /extensions/Example//path)
374 $defaultPaths['localBasePath'] = $dir;
375 } else {
376 $defaultPaths['localBasePath'] = "$dir/{$defaultPaths['localBasePath']}";
377 }
378 }
379
380 foreach ( [ 'ResourceModules', 'ResourceModuleSkinStyles' ] as $setting ) {
381 if ( isset( $info[$setting] ) ) {
382 foreach ( $info[$setting] as $name => $data ) {
383 if ( isset( $data['localBasePath'] ) ) {
384 if ( $data['localBasePath'] === '' ) {
385 // Avoid double slashes (e.g. /extensions/Example//path)
386 $data['localBasePath'] = $dir;
387 } else {
388 $data['localBasePath'] = "$dir/{$data['localBasePath']}";
389 }
390 }
391 if ( $defaultPaths ) {
392 $data += $defaultPaths;
393 }
394 $this->globals["wg$setting"][$name] = $data;
395 }
396 }
397 }
398
399 if ( isset( $info['QUnitTestModule'] ) ) {
400 $data = $info['QUnitTestModule'];
401 if ( isset( $data['localBasePath'] ) ) {
402 if ( $data['localBasePath'] === '' ) {
403 // Avoid double slashes (e.g. /extensions/Example//path)
404 $data['localBasePath'] = $dir;
405 } else {
406 $data['localBasePath'] = "$dir/{$data['localBasePath']}";
407 }
408 }
409 $this->attributes['QUnitTestModules']["test.{$info['name']}"] = $data;
410 }
411 }
412
413 protected function extractExtensionMessagesFiles( $dir, array $info ) {
414 if ( isset( $info['ExtensionMessagesFiles'] ) ) {
415 foreach ( $info['ExtensionMessagesFiles'] as &$file ) {
416 $file = "$dir/$file";
417 }
418 $this->globals["wgExtensionMessagesFiles"] += $info['ExtensionMessagesFiles'];
419 }
420 }
421
422 /**
423 * Set message-related settings, which need to be expanded to use
424 * absolute paths
425 *
426 * @param string $dir
427 * @param array $info
428 */
429 protected function extractMessagesDirs( $dir, array $info ) {
430 if ( isset( $info['MessagesDirs'] ) ) {
431 foreach ( $info['MessagesDirs'] as $name => $files ) {
432 foreach ( (array)$files as $file ) {
433 $this->globals["wgMessagesDirs"][$name][] = "$dir/$file";
434 }
435 }
436 }
437 }
438
439 /**
440 * @param string $path
441 * @param array $info
442 * @return string Name of thing
443 * @throws Exception
444 */
445 protected function extractCredits( $path, array $info ) {
446 $credits = [
447 'path' => $path,
448 'type' => $info['type'] ?? 'other',
449 ];
450 foreach ( self::$creditsAttributes as $attr ) {
451 if ( isset( $info[$attr] ) ) {
452 $credits[$attr] = $info[$attr];
453 }
454 }
455
456 $name = $credits['name'];
457
458 // If someone is loading the same thing twice, throw
459 // a nice error (T121493)
460 if ( isset( $this->credits[$name] ) ) {
461 $firstPath = $this->credits[$name]['path'];
462 $secondPath = $credits['path'];
463 throw new Exception( "It was attempted to load $name twice, from $firstPath and $secondPath." );
464 }
465
466 $this->credits[$name] = $credits;
467 $this->globals['wgExtensionCredits'][$credits['type']][] = $credits;
468
469 return $name;
470 }
471
472 /**
473 * Set configuration settings for manifest_version == 1
474 * @todo In the future, this should be done via Config interfaces
475 *
476 * @param array $info
477 */
478 protected function extractConfig1( array $info ) {
479 if ( isset( $info['config'] ) ) {
480 if ( isset( $info['config']['_prefix'] ) ) {
481 $prefix = $info['config']['_prefix'];
482 unset( $info['config']['_prefix'] );
483 } else {
484 $prefix = 'wg';
485 }
486 foreach ( $info['config'] as $key => $val ) {
487 if ( $key[0] !== '@' ) {
488 $this->addConfigGlobal( "$prefix$key", $val, $info['name'] );
489 }
490 }
491 }
492 }
493
494 /**
495 * Set configuration settings for manifest_version == 2
496 * @todo In the future, this should be done via Config interfaces
497 *
498 * @param array $info
499 * @param string $dir
500 */
501 protected function extractConfig2( array $info, $dir ) {
502 $prefix = $info['config_prefix'] ?? 'wg';
503 if ( isset( $info['config'] ) ) {
504 foreach ( $info['config'] as $key => $data ) {
505 $value = $data['value'];
506 if ( isset( $data['merge_strategy'] ) ) {
507 $value[ExtensionRegistry::MERGE_STRATEGY] = $data['merge_strategy'];
508 }
509 if ( isset( $data['path'] ) && $data['path'] ) {
510 $value = "$dir/$value";
511 }
512 $this->addConfigGlobal( "$prefix$key", $value, $info['name'] );
513 $data['providedby'] = $info['name'];
514 if ( isset( $info['ConfigRegistry'][0] ) ) {
515 $data['configregistry'] = array_keys( $info['ConfigRegistry'] )[0];
516 }
517 $this->config[$key] = $data;
518 }
519 }
520 }
521
522 /**
523 * Helper function to set a value to a specific global, if it isn't set already.
524 *
525 * @param string $key The config key with the prefix and anything
526 * @param mixed $value The value of the config
527 * @param string $extName Name of the extension
528 */
529 private function addConfigGlobal( $key, $value, $extName ) {
530 if ( array_key_exists( $key, $this->globals ) ) {
531 throw new RuntimeException(
532 "The configuration setting '$key' was already set by MediaWiki core or"
533 . " another extension, and cannot be set again by $extName." );
534 }
535 $this->globals[$key] = $value;
536 }
537
538 protected function extractPathBasedGlobal( $global, $dir, $paths ) {
539 foreach ( $paths as $path ) {
540 $this->globals[$global][] = "$dir/$path";
541 }
542 }
543
544 /**
545 * @param string $path
546 * @param string $name
547 * @param array $value
548 * @param array &$array
549 * @throws InvalidArgumentException
550 */
551 protected function storeToArray( $path, $name, $value, &$array ) {
552 if ( !is_array( $value ) ) {
553 throw new InvalidArgumentException( "The value for '$name' should be an array (from $path)" );
554 }
555 if ( isset( $array[$name] ) ) {
556 $array[$name] = array_merge_recursive( $array[$name], $value );
557 } else {
558 $array[$name] = $value;
559 }
560 }
561
562 public function getExtraAutoloaderPaths( $dir, array $info ) {
563 $paths = [];
564 if ( isset( $info['load_composer_autoloader'] ) && $info['load_composer_autoloader'] === true ) {
565 $paths[] = "$dir/vendor/autoload.php";
566 }
567 return $paths;
568 }
569 }