Debian Codegraph @

tests/phpunit/unit/includes/SetupDynamicConfigTest.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\Language\LanguageCode;
4 use MediaWiki\MainConfigNames;
5 use MediaWiki\MainConfigSchema;
6 use MediaWiki\Registration\ExtensionRegistry;
7 use MediaWiki\Settings\Config\ArrayConfigBuilder;
8 use MediaWiki\Settings\Config\ConfigSchemaAggregator;
9 use MediaWiki\Settings\Config\PhpIniSink;
10 use MediaWiki\Settings\DynamicDefaultValues;
11 use MediaWiki\Settings\SettingsBuilder;
12 use MediaWiki\Settings\Source\ReflectionSchemaSource;
13 use MediaWiki\Title\NamespaceInfo;
14
15 class SetupDynamicConfigTest extends MediaWikiUnitTestCase {
16 /** @var string */
17 private $originalDefaultTimezone;
18
19 /** @var string[] */
20 private $originalServerVars;
21
22 /**
23 * Stop $wgLocaltimezone from clobbering the default, and make sure the timezone is UTC
24 *
25 * @before
26 */
27 public function saveTimezoneSetUp(): void {
28 $this->originalDefaultTimezone = date_default_timezone_get();
29 date_default_timezone_set( 'UTC' );
30 }
31
32 /**
33 * @after
34 */
35 public function restoreTimezoneTearDown(): void {
36 date_default_timezone_set( $this->originalDefaultTimezone );
37 }
38
39 /**
40 * @before
41 */
42 public function serverVarsSetUp(): void {
43 $this->originalServerVars = $_SERVER;
44 }
45
46 /**
47 * @after
48 */
49 public function serverVarsTearDown(): void {
50 $_SERVER = $this->originalServerVars;
51 }
52
53 /**
54 * Returns a callback that replaces its single input with all occurrences of $find replaced
55 * with $replace. Arrays are traversed recursively, and values that are neither arrays nor
56 * strings are returned as-is. $find and $replace may be arrays of the same length, in which
57 * case all replacements are performed.
58 *
59 * @param string|string[] $find
60 * @param string|string[] $replace
61 * @return Closure
62 */
63 private static function recursiveReplaceCallback( $find, $replace ): Closure {
64 $callback = static function ( $val ) use ( $find, $replace, &$callback ) {
65 if ( is_array( $val ) ) {
66 return array_map( $callback, $val );
67 }
68 if ( !is_string( $val ) ) {
69 return $val;
70 }
71 return str_replace( $find, $replace, $val );
72 };
73 return $callback;
74 }
75
76 /**
77 * This method is made necessary by the fact that the dynamic default for DummyLanguageCodes is
78 * based on long lists that are returned from static methods that we can't override.
79 * Copy-pasting those lists into the expected results would be both fragile and hard to read.
80 *
81 * @param array $dummyLanguageCodes Value that DummyLanguageCodes was set to in configuration
82 * @param array $extraLanguageCodes Value that ExtraLanguageCodes was set to in configuration
83 * @return array Expected value after dynamic defaults
84 */
85 private static function getExpectedDummyLanguageCodes( array $dummyLanguageCodes,
86 array $extraLanguageCodes = MainConfigSchema::ExtraLanguageCodes['default']
87 ): array {
88 $expected = $dummyLanguageCodes + [ 'qqq' => 'qqq', 'qqx' => 'qqx' ] + $extraLanguageCodes
89 + LanguageCode::getDeprecatedCodeMapping();
90
91 // Copy-paste from SetupDynamicConfig
92 foreach ( LanguageCode::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
93 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
94 if ( !isset( $expected[$bcp47] ) ) {
95 $expected[$bcp47] = $expected[$code] ?? $code;
96 }
97 }
98
99 return $expected;
100 }
101
102 public static function provideGlobals(): Generator {
103 $expectedDefault = [
104 'ScriptPath' => '/wiki',
105 'Script' => '/wiki/index.php',
106 'LoadScript' => '/wiki/load.php',
107 'RestPath' => '/wiki/rest.php',
108 // XXX $wgUsePathInfo set based on PHP_SAPI, no good way to test?
109 // XXX Testing $wgArticlePath doesn't seem to work
110 'ResourceBasePath' => '/wiki',
111 'StylePath' => '/wiki/skins',
112 'LocalStylePath' => '/wiki/skins',
113 'ExtensionAssetsPath' => '/wiki/extensions',
114 'Logo' => '/wiki/resources/assets/change-your-logo.svg',
115 'UploadPath' => '/wiki/images',
116 'UploadDirectory' => '/install/path/images',
117 'ReadOnlyFile' => '/install/path/images/lock_yBgMBwiR',
118 'FileCacheDirectory' => '/install/path/images/cache',
119 'DeletedDirectory' => '/install/path/images/deleted',
120 'SharedPrefix' => '',
121 'SharedSchema' => null,
122 'MetaNamespace' => 'MediaWiki',
123 'EnableUserEmailMuteList' => false,
124 'EnableUserEmailBlacklist' => false,
125 'NamespaceProtection' => [ NS_MEDIAWIKI => 'editinterface' ],
126 'LockManagers' => [ [
127 'name' => 'fsLockManager',
128 'class' => FSLockManager::class,
129 'lockDirectory' => '/install/path/images/lockdir',
130 ], [
131 'name' => 'nullLockManager',
132 'class' => NullLockManager::class,
133 ] ],
134 // Can't really test this properly without being able to mock global functions
135 'ShowEXIF' => function_exists( 'exif_read_data' ),
136 'GalleryOptions' => [
137 'imagesPerRow' => 0,
138 'imageWidth' => 120,
139 'imageHeight' => 120,
140 'captionLength' => true,
141 'showBytes' => true,
142 'showDimensions' => true,
143 'mode' => 'traditional',
144 ],
145 'LocalFileRepo' => [
146 'class' => LocalRepo::class,
147 'name' => 'local',
148 'directory' => '/install/path/images',
149 'scriptDirUrl' => '/wiki',
150 'favicon' => '/favicon.ico',
151 'url' => '/wiki/images',
152 'hashLevels' => 2,
153 'thumbScriptUrl' => false,
154 'transformVia404' => false,
155 'deletedDir' => '/install/path/images/deleted',
156 'deletedHashLevels' => 3,
157 'updateCompatibleMetadata' => false,
158 'reserializeMetadata' => false,
159 'backend' => 'local-backend',
160 ],
161 'CookiePrefix' => 'my_wiki',
162 'Localtimezone' => 'UTC',
163 'LocalTZoffset' => 0,
164 'DBerrorLogTZ' => 'UTC',
165 'CanonicalNamespaceNames' => NamespaceInfo::CANONICAL_NAMES,
166 'DummyLanguageCodes' => self::getExpectedDummyLanguageCodes( [] ),
167 'SlaveLagWarning' => 10,
168 'DatabaseReplicaLagWarning' => 10,
169 'SlaveLagCritical' => 30,
170 'DatabaseReplicaLagCritical' => 30,
171 // This will be wrong if LocalSettings.php was last touched before May 16, 2003.
172 'CacheEpoch' => static function (): string {
173 // We need a callback that will be evaluated at test time, because otherwise this
174 // doesn't work on CI for some reason.
175 $ret = max( '20030516000000', gmdate( 'YmdHis', @filemtime( MW_CONFIG_FILE ) ) );
176 return $ret;
177 },
178 'RateLimits' => MainConfigSchema::getDefaultValue( 'RateLimits' ),
179 ];
180
181 foreach (
182 self::provideGlobalsInternal( $expectedDefault ) as $desc => $arr
183 ) {
184 if ( is_array( $arr[1] ) ) {
185 $arr[1] += $expectedDefault;
186 }
187 yield $desc => $arr;
188 }
189 }
190
191 private static function provideGlobalsInternal( array $expectedDefault ): Generator {
192 yield 'Nothing set' => [ [], [] ];
193 yield '$wgScriptPath set' => [
194 [ 'ScriptPath' => '/mywiki' ],
195 array_map( self::recursiveReplaceCallback( '/wiki', '/mywiki' ), $expectedDefault ),
196 ];
197 yield '$wgResourceBasePath set' => [
198 [ 'ResourceBasePath' => '/resources' ],
199 [
200 'ResourceBasePath' => '/resources',
201 'ExtensionAssetsPath' => '/resources/extensions',
202 'StylePath' => '/resources/skins',
203 'Logo' => '/resources/resources/assets/change-your-logo.svg',
204 ],
205 ];
206 yield '$wgUploadDirectory set' => [
207 [ 'UploadDirectory' => '/uploads' ],
208 [
209 'UploadDirectory' => '/uploads',
210 'ReadOnlyFile' => '/uploads/lock_yBgMBwiR',
211 'FileCacheDirectory' => '/uploads/cache',
212 'DeletedDirectory' => '/uploads/deleted',
213 'LockManagers' => [ [
214 'name' => 'fsLockManager',
215 'class' => FSLockManager::class,
216 'lockDirectory' => '/uploads/lockdir',
217 ], [
218 'name' => 'nullLockManager',
219 'class' => NullLockManager::class,
220 ] ],
221 'LocalFileRepo' => [
222 'class' => LocalRepo::class,
223 'name' => 'local',
224 'directory' => '/uploads',
225 'scriptDirUrl' => '/wiki',
226 'favicon' => '/favicon.ico',
227 'url' => '/wiki/images',
228 'hashLevels' => 2,
229 'thumbScriptUrl' => false,
230 'transformVia404' => false,
231 'deletedDir' => '/uploads/deleted',
232 'deletedHashLevels' => 3,
233 'updateCompatibleMetadata' => false,
234 'reserializeMetadata' => false,
235 'backend' => 'local-backend',
236 ],
237 ],
238 ];
239 yield '$wgCacheDirectory set' => [
240 [ 'CacheDirectory' => '/cache' ],
241 [ 'CacheDirectory' => '/cache' ],
242 ];
243 yield '$wgDBprefix set' => [
244 [ 'DBprefix' => 'prefix_' ],
245 [
246 'DBprefix' => 'prefix_',
247 'SharedPrefix' => 'prefix_',
248 'CookiePrefix' => 'my_wiki_prefix_',
249 ],
250 ];
251 yield '$wgDBmwschema set' => [
252 [ 'DBmwschema' => 'schema' ],
253 [
254 'DBmwschema' => 'schema',
255 'SharedSchema' => 'schema',
256 ],
257 ];
258 yield '$wgSitename set' => [
259 [ 'Sitename' => 'my site' ],
260 [
261 'Sitename' => 'my site',
262 'MetaNamespace' => 'my_site',
263 ],
264 ];
265 yield '$wgProhibitedFileExtensions set' => [
266 [ 'ProhibitedFileExtensions' => [ 'evil' ] ],
267 [
268 'ProhibitedFileExtensions' => [ 'evil' ],
269 'FileBlacklist' => [ 'evil' ],
270 ],
271 ];
272 yield '$wgProhibitedFileExtensions and $wgFileBlacklist set' => [
273 [
274 'ProhibitedFileExtensions' => [ 'evil' ],
275 'FileBlacklist' => [ 'eviler' ],
276 ],
277 [
278 'ProhibitedFileExtensions' => [ 'evil', 'eviler' ],
279 'FileBlacklist' => [ 'eviler' ],
280 ],
281 ];
282 yield '$wgMimeTypeExclusions set' => [
283 [ 'MimeTypeExclusions' => [ 'evil' ] ],
284 [
285 'MimeTypeExclusions' => [ 'evil' ],
286 'MimeTypeBlacklist' => [ 'evil' ],
287 ],
288 ];
289 yield '$wgMimeTypeExclusions and $wgMimeTypeBlacklist set' => [
290 [
291 'MimeTypeExclusions' => [ 'evil' ],
292 'MimeTypeBlacklist' => [ 'eviler' ],
293 ],
294 [
295 'MimeTypeExclusions' => [ 'evil', 'eviler' ],
296 'MimeTypeBlacklist' => [ 'eviler' ],
297 ],
298 ];
299 yield '$wgEnableUserEmailMuteList set' => [
300 [ 'EnableUserEmailMuteList' => true ],
301 [
302 'EnableUserEmailMuteList' => true,
303 'EnableUserEmailBlacklist' => true,
304 ],
305 ];
306 yield '$wgEnableUserEmailMuteList and $wgEnableUserEmailBlacklist both true' => [
307 [
308 'EnableUserEmailMuteList' => true,
309 'EnableUserEmailBlacklist' => true,
310 ],
311 [
312 'EnableUserEmailMuteList' => true,
313 'EnableUserEmailBlacklist' => true,
314 ],
315 ];
316 yield '$wgEnableUserEmailMuteList true and $wgEnableUserEmailBlacklist false' => [
317 [
318 'EnableUserEmailMuteList' => true,
319 'EnableUserEmailBlacklist' => false,
320 ],
321 [
322 'EnableUserEmailMuteList' => false,
323 'EnableUserEmailBlacklist' => false,
324 ],
325 ];
326 yield '$wgShortPagesNamespaceExclusions set' => [
327 [ 'ShortPagesNamespaceExclusions' => [ NS_TALK ] ],
328 [
329 'ShortPagesNamespaceExclusions' => [ NS_TALK ],
330 'ShortPagesNamespaceBlacklist' => [ NS_TALK ],
331 ],
332 ];
333 yield '$wgShortPagesNamespaceBlacklist set' => [
334 [ 'ShortPagesNamespaceBlacklist' => [ NS_PROJECT ] ],
335 [
336 'ShortPagesNamespaceExclusions' => [ NS_PROJECT ],
337 'ShortPagesNamespaceBlacklist' => [ NS_PROJECT ],
338 ],
339 ];
340 yield '$wgShortPagesNamespaceExclusions and $wgShortPagesNamespaceBlacklist set' => [
341 [
342 'ShortPagesNamespaceExclusions' => [ NS_TALK ],
343 'ShortPagesNamespaceBlacklist' => [ NS_PROJECT ],
344 ],
345 [
346 'ShortPagesNamespaceExclusions' => [ NS_PROJECT ],
347 'ShortPagesNamespaceBlacklist' => [ NS_PROJECT ],
348 ],
349 ];
350 yield '$wgFileExtension contains something from $wgProhibitedFileExtensions' => [
351 [
352 'FileExtensions' => [ 'a', 'b', 'c' ],
353 'ProhibitedFileExtensions' => [ 'b', 'd' ],
354 ],
355 [
356 'FileExtensions' => [ 'a', 'c' ],
357 'ProhibitedFileExtensions' => [ 'b', 'd' ],
358 ],
359 ];
360 yield '$wgRightsIcon old path convention' => [
361 [
362 'StylePath' => '/style',
363 'ResourceBasePath' => '/resources',
364 'RightsIcon' => '/style/common/images/rights.png',
365 ],
366 [
367 'StylePath' => '/style',
368 'ResourceBasePath' => '/resources',
369 'ExtensionAssetsPath' => '/resources/extensions',
370 'Logo' => '/resources/resources/assets/change-your-logo.svg',
371 'RightsIcon' => '/resources/resources/assets/licenses/rights.png',
372 ],
373 ];
374 yield 'Empty $wgFooterIcons[\'copyright\'][\'copyright\'], $wgRightsIcon set' => [
375 [
376 'RightsIcon' => 'ico',
377 'FooterIcons' => [ 'copyright' => [ 'copyright' => [] ] ],
378 ],
379 [
380 'FooterIcons' => [ 'copyright' => [ 'copyright' => [
381 'url' => null,
382 'src' => 'ico',
383 'alt' => null,
384 ] ] ],
385 ],
386 ];
387 yield 'Empty $wgFooterIcons[\'copyright\'][\'copyright\'], $wgRightsText set' => [
388 [
389 'RightsText' => 'text',
390 'FooterIcons' => [ 'copyright' => [ 'copyright' => [] ] ],
391 ],
392 [
393 'FooterIcons' => [ 'copyright' => [ 'copyright' => [
394 'url' => null,
395 'src' => null,
396 'alt' => 'text',
397 ] ] ],
398 ],
399 ];
400 yield '$wgFooterIcons[\'poweredby\'][\'mediawiki\'][\'src\'] === null' => [
401 [
402 'ResourceBasePath' => '/resources',
403 'FooterIcons' => [ 'poweredby' => [ 'mediawiki' => [ 'src' => null ] ] ],
404 ],
405 [
406 'ResourceBasePath' => '/resources',
407 'ExtensionAssetsPath' => '/resources/extensions',
408 'StylePath' => '/resources/skins',
409 'Logo' => '/resources/resources/assets/change-your-logo.svg',
410 'FooterIcons' => [ 'poweredby' => [ 'mediawiki' => [
411 'src' => '/resources/resources/assets/poweredby_mediawiki.svg',
412 ] ] ],
413 ],
414 ];
415 yield '$wgFooterIcons[\'poweredby\'][\'mediawiki\'][\'src\'] === \'\'' => [
416 [ 'FooterIcons' => [ 'poweredby' => [ 'mediawiki' => [ 'src' => '' ] ] ] ],
417 [ 'FooterIcons' => [ 'poweredby' => [ 'mediawiki' => [ 'src' => '' ] ] ] ],
418 ];
419 yield '$wgFooterIcons[\'poweredby\']=== []' => [
420 [ 'FooterIcons' => [ 'poweredby' => [] ] ],
421 [ 'FooterIcons' => [ 'poweredby' => [] ] ],
422 ];
423 yield '$wgNamespaceProtection set only for non-NS_MEDIAWIKI' => [
424 [ 'NamespaceProtection' => [ NS_PROJECT => 'editprotected' ] ],
425 [ 'NamespaceProtection' => [
426 NS_PROJECT => 'editprotected',
427 NS_MEDIAWIKI => 'editinterface',
428 ] ],
429 ];
430 yield '$wgNamespaceProtection[NS_MEDIAWIKI] not editinterface' => [
431 [ 'NamespaceProtection' => [ NS_MEDIAWIKI => 'editprotected' ] ],
432 [ 'NamespaceProtection' => [ NS_MEDIAWIKI => 'editinterface' ] ],
433 ];
434 yield 'Custom lock manager' => [
435 [ 'LockManagers' => [ [ 'foo' ] ] ],
436 [ 'LockManagers' => [ [ 'foo' ], [
437 'name' => 'fsLockManager',
438 'class' => FSLockManager::class,
439 'lockDirectory' => '/install/path/images/lockdir',
440 ], [
441 'name' => 'nullLockManager',
442 'class' => NullLockManager::class,
443 ] ] ],
444 ];
445 yield 'Customize some $wgGalleryOptions' => [
446 [ 'GalleryOptions' => [
447 'imagesPerRow' => 42,
448 'imageHeight' => -1,
449 'showBytes' => null,
450 'mode' => 'iconoclastic',
451 'custom' => 'Rembrandt',
452 ] ],
453 [ 'GalleryOptions' => [
454 'imagesPerRow' => 42,
455 'imageHeight' => -1,
456 'showBytes' => null,
457 'mode' => 'iconoclastic',
458 'custom' => 'Rembrandt',
459 'imageWidth' => 120,
460 'captionLength' => true,
461 'showDimensions' => true,
462 ] ],
463 ];
464 yield 'Set $wgLocalFileRepo' => [
465 [ 'LocalFileRepo' => [ 'name' => 'asdfgh' ] ],
466 [ 'LocalFileRepo' => [
467 'name' => 'asdfgh', 'backend' => 'asdfgh-backend'
468 ] ],
469 ];
470 $sharedUploadsExpected = [
471 'class' => FileRepo::class,
472 'name' => 'shared',
473 'directory' => null,
474 'url' => null,
475 'hashLevels' => 2,
476 'thumbScriptUrl' => false,
477 'transformVia404' => false,
478 'descBaseUrl' => 'https://commons.wikimedia.org/wiki/File:',
479 'fetchDescription' => false,
480 'backend' => 'shared-backend',
481 ];
482 yield '$wgUseSharedUploads' => [
483 [ 'UseSharedUploads' => true ],
484 [ 'ForeignFileRepos' => [ $sharedUploadsExpected ] ],
485 ];
486 $sharedUploadsDBnameExpected = [
487 'class' => ForeignDBRepo::class,
488 'name' => 'shared',
489 'directory' => null,
490 'url' => null,
491 'hashLevels' => 2,
492 'thumbScriptUrl' => false,
493 'transformVia404' => false,
494 'dbType' => 'mysql',
495 'dbServer' => 'localhost',
496 'dbUser' => 'wikiuser',
497 'dbPassword' => '',
498 'dbName' => 'shared_uploads',
499 'dbFlags' => DBO_DEFAULT,
500 'tablePrefix' => '',
501 'hasSharedCache' => true,
502 'descBaseUrl' => 'https://commons.wikimedia.org/wiki/File:',
503 'fetchDescription' => false,
504 'backend' => 'shared-backend',
505 ];
506 yield '$wgUseSharedUploads and $wgSharedUploadDBname' => [
507 [
508 'UseSharedUploads' => true,
509 'SharedUploadDBname' => 'shared_uploads',
510 ],
511 [ 'ForeignFileRepos' => [ $sharedUploadsDBnameExpected ] ],
512 ];
513 $instantCommonsExpected = [
514 'class' => ForeignAPIRepo::class,
515 'name' => 'wikimediacommons',
516 'apibase' => 'https://commons.wikimedia.org/w/api.php',
517 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
518 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
519 'hashLevels' => 2,
520 'transformVia404' => true,
521 'fetchDescription' => true,
522 'descriptionCacheExpiry' => 43200,
523 'apiThumbCacheExpiry' => 0,
524 'directory' => '/install/path/images',
525 'backend' => 'wikimediacommons-backend',
526 ];
527 yield '$wgUseInstantCommons' => [
528 [ 'UseInstantCommons' => true ],
529 [ 'ForeignFileRepos' => [ $instantCommonsExpected ] ],
530 ];
531 yield '$wgUseSharedUploads and $wgUseInstantCommons' => [
532 [
533 'UseSharedUploads' => true,
534 'UseInstantCommons' => true,
535 ],
536 [ 'ForeignFileRepos' => [
537 $sharedUploadsExpected, $instantCommonsExpected ]
538 ],
539 ];
540 yield '$wgUseSharedUploads and $wgSharedUploadDBname and $wgUseInstantCommons' => [
541 [
542 'UseSharedUploads' => true,
543 'SharedUploadDBname' => 'shared_uploads',
544 'UseInstantCommons' => true,
545 ],
546 [ 'ForeignFileRepos' => [
547 $sharedUploadsDBnameExpected, $instantCommonsExpected ]
548 ],
549 ];
550 yield 'ForeignAPIRepo with no directory' => [
551 [
552 'ForeignFileRepos' => [ [
553 'name' => 'foreigner',
554 'class' => ForeignAPIRepo::class,
555 ] ],
556 'UploadDirectory' => '/upload',
557 ],
558 [ 'ForeignFileRepos' => [ [
559 'name' => 'foreigner',
560 'class' => ForeignAPIRepo::class,
561 'directory' => '/upload',
562 'backend' => 'foreigner-backend',
563 ] ] ] + array_map(
564 self::recursiveReplaceCallback( '/install/path/images', '/upload' ),
565 $expectedDefault ),
566 ];
567 yield '$wgDefaultUserOptions days too high' => [
568 [
569 'DefaultUserOptions' => [
570 'rcdays' => 100,
571 'watchlistdays' => 75,
572 ],
573 'RCMaxAge' => 36 * 3600,
574 ],
575 [ 'DefaultUserOptions' => [
576 'rcdays' => 2.0,
577 'watchlistdays' => 2.0,
578 'timecorrection' => 'System|0',
579 ] ],
580 ];
581 yield '$wgSharedDB set' => [
582 [ 'SharedDB' => 'shared_db' ],
583 [ 'CookiePrefix' => 'shared_db' ],
584 ];
585 yield '$wgSharedDB and $wgSharedPrefix set' => [
586 [ 'SharedDB' => 'shared_db', 'SharedPrefix' => 'shared_prefix' ],
587 [
588 'CookiePrefix' => 'shared_db_shared_prefix',
589 'SharedPrefix' => 'shared_prefix',
590 ],
591 ];
592 yield '$wgSharedPrefix set with no $wgSharedDB' => [
593 [ 'SharedPrefix' => 'shared_prefix' ],
594 [ 'SharedPrefix' => 'shared_prefix' ],
595 ];
596 yield '$wgSharedDB set but user not in $wgSharedTables' => [
597 [ 'SharedDB' => 'shared_db', 'SharedTables' => [ 'user_properties' ] ],
598 [],
599 ];
600 yield '$wgSharedDB and $wgSharedPrefix set but user not in $wgSharedTables' => [
601 [
602 'SharedDB' => 'shared_db',
603 'SharedPrefix' => 'shared_prefix',
604 'SharedTables' => [ 'user_properties' ],
605 ],
606 [ 'SharedPrefix' => 'shared_prefix' ],
607 ];
608 yield '$wgCookiePrefix with allowed punctuation' => [
609 [ 'CookiePrefix' => "~!@#$%^&*()_-]{}|:<>/?\t\r\n\f" ],
610 [ 'CookiePrefix' => "~!@#$%^&*()_-]{}|:<>/?\t\r\n\f" ],
611 ];
612 yield '$wgCookiePrefix with bad characters' => [
613 [ 'CookiePrefix' => 'n=o,t;a l+l.o"w\'e\\d[' ],
614 [ 'CookiePrefix' => 'n_o_t_a_l_l_o_w_e_d_' ],
615 ];
616 yield '$wgEnableEmail set to false' => [
617 [
618 'EnableEmail' => false,
619 'AllowHTMLEmail' => true,
620 'EmailAuthentication' => true,
621 'EnableUserEmail' => true,
622 'EnotifFromEditor' => true,
623 'EnotifImpersonal' => true,
624 'EnotifMaxRecips' => 0,
625 'EnotifMinorEdits' => true,
626 'EnotifRevealEditorAddress' => true,
627 'EnotifUseRealName' => true,
628 'EnotifUserTalk' => true,
629 'EnotifWatchlist' => true,
630 'GroupPermissions' => [ 'user' => [ 'sendemail' => true ] ],
631 'UserEmailUseReplyTo' => true,
632 'UsersNotifiedOnAllChanges' => [ 'Admin' ],
633 ], [
634 'AllowHTMLEmail' => false,
635 'EmailAuthentication' => false,
636 'EnableUserEmail' => false,
637 'EnotifFromEditor' => false,
638 'EnotifImpersonal' => false,
639 'EnotifMaxRecips' => 0,
640 'EnotifMinorEdits' => false,
641 'EnotifRevealEditorAddress' => false,
642 'EnotifUseRealName' => false,
643 'EnotifUserTalk' => false,
644 'EnotifWatchlist' => false,
645 'GroupPermissions' => [ 'user' => [] ],
646 'UserEmailUseReplyTo' => false,
647 'UsersNotifiedOnAllChanges' => [],
648 ],
649 ];
650 yield 'Change PHP default timezone' => [
651 [ 'DefaultUserOptions' => [
652 'rcdays' => 0,
653 'watchlistdays' => 0,
654 ] ],
655 [
656 'Localtimezone' => 'America/Phoenix',
657 'LocalTZoffset' => -7 * 60,
658 'DefaultUserOptions' => [
659 'rcdays' => 0,
660 'watchlistdays' => 0,
661 'timecorrection' => 'System|' . ( -7 * 60 ),
662 ],
663 'DBerrorLogTZ' => 'America/Phoenix',
664 ],
665 static function ( self $testObj ): void {
666 // Pick a timezone with no DST
667 $testObj->assertTrue( date_default_timezone_set( 'America/Phoenix' ) );
668 },
669 ];
670 yield '$wgDBerrorLogTZ set' => [
671 [ 'DBerrorLogTZ' => 'America/Phoenix' ],
672 [ 'DBerrorLogTZ' => 'America/Phoenix' ],
673 ];
674 yield 'Setting $wgCanonicalNamespaceNames does nothing' => [
675 [ 'CanonicalNamespaceNames' => [ NS_MAIN => 'abc' ] ],
676 [],
677 ];
678 yield 'Setting $wgExtraNamespaces does not affect $wgCanonicalNamespaceNames' => [
679 [ 'ExtraNamespaces' => [ 100 => 'Extra' ] ],
680 [],
681 ];
682 yield '$wgDummyLanguageCodes set' => [
683 [ 'DummyLanguageCodes' => [ 'qqq' => 'qqqq', 'foo' => 'bar', 'bh' => 'hb' ] ],
684 [ 'DummyLanguageCodes' => self::getExpectedDummyLanguageCodes(
685 [ 'qqq' => 'qqqq', 'foo' => 'bar', 'bh' => 'hb' ] ) ],
686 ];
687 yield '$wgExtraLanguageCodes set' => [
688 [ 'ExtraLanguageCodes' => [ 'foo' => 'bar' ] ],
689 [ 'DummyLanguageCodes' => self::getExpectedDummyLanguageCodes( [],
690 [ 'foo' => 'bar' ] ) ],
691 ];
692 yield '$wgDummyLanguageCodes and $wgExtraLanguageCodes set' => [
693 [
694 'DummyLanguageCodes' => [ 'foo' => 'bar', 'abc' => 'def' ],
695 'ExtraLanguageCodes' => [ 'foo' => 'baz', 'ghi' => 'jkl' ],
696 ],
697 [ 'DummyLanguageCodes' => self::getExpectedDummyLanguageCodes(
698 [ 'foo' => 'bar', 'abc' => 'def' ], [ 'foo' => 'baz', 'ghi' => 'jkl' ] ) ],
699 ];
700 yield '$wgDatabaseReplicaLagWarning set' => [
701 [ 'DatabaseReplicaLagWarning' => 20 ],
702 [ 'DatabaseReplicaLagWarning' => 20, 'SlaveLagWarning' => 20 ],
703 ];
704 yield '$wgSlaveLagWarning set' => [
705 [ 'SlaveLagWarning' => 20 ],
706 [ 'DatabaseReplicaLagWarning' => 20, 'SlaveLagWarning' => 20 ],
707 ];
708 // XXX The settings are out of sync, this doesn't look intended
709 yield '$wgDatabaseReplicaLagWarning and $wgSlaveLagWarning set' => [
710 [ 'DatabaseReplicaLagWarning' => 20, 'SlaveLagWarning' => 30 ],
711 [ 'DatabaseReplicaLagWarning' => 20, 'SlaveLagWarning' => 30 ],
712 ];
713 yield '$wgDatabaseReplicaLagCritical set' => [
714 [ 'DatabaseReplicaLagCritical' => 40 ],
715 [ 'DatabaseReplicaLagCritical' => 40, 'SlaveLagCritical' => 40 ],
716 ];
717 yield '$wgSlaveLagCritical set' => [
718 [ 'SlaveLagCritical' => 40 ],
719 [ 'DatabaseReplicaLagCritical' => 40, 'SlaveLagCritical' => 40 ],
720 ];
721 // XXX The settings are out of sync, this doesn't look intended
722 yield '$wgDatabaseReplicaLagCritical and $wgSlaveLagCritical set' => [
723 [ 'DatabaseReplicaLagCritical' => 40, 'SlaveLagCritical' => 60 ],
724 [ 'DatabaseReplicaLagCritical' => 40, 'SlaveLagCritical' => 60 ],
725 ];
726 yield '$wgCacheEpoch set to before LocalSettings touched' => [
727 [ 'CacheEpoch' => static function () use ( $expectedDefault ): string {
728 return $expectedDefault['CacheEpoch']() - 1;
729 } ],
730 [ 'CacheEpoch' => static function () use ( $expectedDefault ): string {
731 $expected = $expectedDefault['CacheEpoch']();
732 // If the file exists, its mtime is later than what we set $wgCacheEpoch to and so
733 // it should override what we set.
734 return file_exists( MW_CONFIG_FILE ) ? $expected : $expected - 1;
735 } ],
736 ];
737 yield '$wgCacheEpoch set to after LocalSettings touched' => [
738 [ 'CacheEpoch' => static function () use ( $expectedDefault ): string {
739 return $expectedDefault['CacheEpoch']() + 1;
740 } ],
741 [ 'CacheEpoch' => static function () use ( $expectedDefault ): string {
742 return $expectedDefault['CacheEpoch']() + 1;
743 } ],
744 ];
745 yield '$wgInvalidateCacheOnLocalSettingsChange false' => [
746 [ 'InvalidateCacheOnLocalSettingsChange' => false ],
747 [ 'CacheEpoch' => '20030516000000' ],
748 ];
749 yield '$wgNewUserLog is true' => [
750 [ 'NewUserLog' => true ],
751 static function ( self $testObj, array $vars ) use ( $expectedDefault ): array {
752 $testObj->assertContains( 'newusers', $vars['LogTypes'] );
753 $testObj->assertSame( 'newuserlogpage', $vars['LogNames']['newusers'] );
754 $testObj->assertSame( 'newuserlogpagetext', $vars['LogHeaders']['newusers'] );
755 $testObj->assertSame( NewUsersLogFormatter::class,
756 $vars['LogActionsHandlers']['newusers/newusers'] );
757 $testObj->assertSame( NewUsersLogFormatter::class,
758 $vars['LogActionsHandlers']['newusers/create'] );
759 $testObj->assertSame( NewUsersLogFormatter::class,
760 $vars['LogActionsHandlers']['newusers/create2'] );
761 $testObj->assertSame( NewUsersLogFormatter::class,
762 $vars['LogActionsHandlers']['newusers/byemail'] );
763 $testObj->assertSame( NewUsersLogFormatter::class,
764 $vars['LogActionsHandlers']['newusers/autocreate'] );
765
766 return $expectedDefault;
767 },
768 ];
769 yield '$wgNewUserLog is false`' => [
770 [ 'NewUserLog' => false ],
771 static function ( self $testObj, array $vars ) use ( $expectedDefault ): array {
772 // Test that the new user log is not added to any of the various logging globals
773 $testObj->assertNotContains( 'newusers', $vars['LogTypes'] );
774 $testObj->assertArrayNotHasKey( 'newusers', $vars['LogNames'] );
775 $testObj->assertArrayNotHasKey( 'newusers', $vars['LogHeaders'] );
776 foreach ( $vars['LogActionsHandlers'] as $key => $unused ) {
777 $testObj->assertStringStartsNotWith( 'newusers', $key );
778 }
779
780 return $expectedDefault;
781 },
782 ];
783 yield '$wgPageCreationLog is true' => [
784 [ 'PageCreationLog' => true ],
785 static function ( self $testObj, array $vars ) use ( $expectedDefault ): array {
786 $testObj->assertContains( 'create', $vars['LogTypes'] );
787 $testObj->assertSame( LogFormatter::class,
788 $vars['LogActionsHandlers']['create/create'] );
789
790 return $expectedDefault;
791 },
792 ];
793 yield '$wgPageCreationLog is false`' => [
794 [ 'PageCreationLog' => false ],
795 static function ( self $testObj, array $vars ) use ( $expectedDefault ): array {
796 $testObj->assertNotContains( 'create', $vars['LogTypes'] );
797 $testObj->assertArrayNotHasKey( 'create/create', $vars['LogActionsHandlers'] );
798
799 return $expectedDefault;
800 },
801 ];
802 yield '$wgPageLanguageUseDB is true' => [
803 [ 'PageLanguageUseDB' => true ],
804 static function ( self $testObj, array $vars ) use ( $expectedDefault ): array {
805 $testObj->assertContains( 'pagelang', $vars['LogTypes'] );
806 $testObj->assertSame( PageLangLogFormatter::class,
807 $vars['LogActionsHandlers']['pagelang/pagelang']['class'] );
808
809 return $expectedDefault;
810 },
811 ];
812 yield '$wgPageLanguageUseDB is false' => [
813 [ 'PageLanguageUseDB' => false ],
814 static function ( self $testObj, array $vars ) use ( $expectedDefault ): array {
815 $testObj->assertNotContains( 'pagelang', $vars['LogTypes'] );
816 $testObj->assertArrayNotHasKey( 'pagelang/pagelang',
817 $vars['LogActionsHandlers'] );
818
819 return $expectedDefault;
820 },
821 ];
822 yield '$wgForceHTTPS is true, not HTTPS' => [
823 [ 'ForceHTTPS' => true ],
824 [ 'CookieSecure' => true ],
825 static function () {
826 $_SERVER['HTTPS'] = null;
827 $_SERVER['HTTP_X_FORWARDED_PROTO'] = null;
828 }
829 ];
830 yield '$wgForceHTTPS is true, HTTPS' => [
831 [ 'ForceHTTPS' => true ],
832 [ 'CookieSecure' => true ],
833 static function () {
834 $_SERVER['HTTPS'] = 'on';
835 $_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https';
836 }
837 ];
838 yield '$wgForceHTTPS is false, not HTTPS' => [
839 [ 'ForceHTTPS' => false ],
840 [ 'CookieSecure' => false ],
841 static function () {
842 $_SERVER['HTTPS'] = null;
843 $_SERVER['HTTP_X_FORWARDED_PROTO'] = null;
844 }
845 ];
846 yield '$wgForceHTTPS is false, HTTPS off' => [
847 [ 'ForceHTTPS' => false ],
848 [ 'CookieSecure' => false ],
849 static function () {
850 $_SERVER['HTTPS'] = 'off';
851 $_SERVER['HTTP_X_FORWARDED_PROTO'] = null;
852 }
853 ];
854 yield '$wgForceHTTPS is false, HTTPS' => [
855 [ 'ForceHTTPS' => false ],
856 [ 'CookieSecure' => true ],
857 static function () {
858 $_SERVER['HTTPS'] = 'on';
859 $_SERVER['HTTP_X_FORWARDED_PROTO'] = null;
860 }
861 ];
862 yield '$wgForceHTTPS is false, forwarded HTTPS' => [
863 [ 'ForceHTTPS' => false ],
864 [ 'CookieSecure' => true ],
865 static function () {
866 $_SERVER['HTTPS'] = null;
867 $_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https';
868 }
869 ];
870 yield 'Bogus $wgPHPSessionHandling' => [
871 [ 'PHPSessionHandling' => 'bogus' ],
872 [ 'PHPSessionHandling' => 'warn' ],
873 ];
874 yield 'Enable $wgPHPSessionHandling' => [
875 [ 'PHPSessionHandling' => 'enable' ],
876 [ 'PHPSessionHandling' => 'enable' ],
877 ];
878 yield 'Disable $wgPHPSessionHandling' => [
879 [ 'PHPSessionHandling' => 'disable' ],
880 [ 'PHPSessionHandling' => 'disable' ],
881 ];
882
883 // use old deprecated rate limit names
884 $rateLimits = [
885 'emailuser' => [
886 'newbie' => [ 1, 86400 ],
887 ],
888 'changetag' => [
889 'ip' => [ 1, 60 ],
890 'newbie' => [ 2, 60 ],
891 ],
892 ];
893
894 yield 'renamed $wgRateLimits' => [
895 [ 'RateLimits' => $rateLimits + $expectedDefault['RateLimits'] ],
896 static function ( self $testObj, array $vars ) use ( $expectedDefault, $rateLimits ): array {
897 $testObj->assertSame( $rateLimits['emailuser'], $vars['RateLimits']['sendemail'], 'emailuser' );
898 $testObj->assertSame( $rateLimits['changetag'], $vars['RateLimits']['changetags'], 'changetag' );
899 return [];
900 }
901 ];
902 // XXX No obvious way to test MW_NO_SESSION, because constants can't be undefined
903 }
904
905 /**
906 * Test that if the variables $test are set after DefaultSettings.php is loaded, then
907 * DynamicDefaultValues and SetupDynamicConfig.php will result in the variables
908 * in $expected being set to the given values.
909 * (This does not test that other variables aren't also set.)
910 *
911 * @dataProvider provideGlobals
912 * @covers \MediaWiki\Settings\DynamicDefaultValues
913 *
914 * @param array $test Keys are the names of variables, values are their values. If a value is
915 * callable, it will be called with no arguments to obtain the value.
916 * @param array|callable $expected Keys are the names of variables, values are their values. If
917 * a value is callable, it will be called with no arguments to obtain the value. If $expected
918 * is callable, then it will be called with $this and get_defined_vars() as arguments, and
919 * the returned array will be used for $expected.
920 * @param ?callable $setup Run before SetupDynamicConfig is included. $this is passed as an
921 * argument, and a ScopedCallback may optionally be returned.
922 */
923 public function testGlobals( array $test, $expected, ?callable $setup = null ): void {
924 $IP = '/install/path';
925
926 $configBuilder = new ArrayConfigBuilder();
927 $schemaSource = new ReflectionSchemaSource( MainConfigSchema::class );
928 $schemaDeclarations = $schemaSource->load()['config-schema'];
929
930 $schema = new ConfigSchemaAggregator();
931
932 // Declare schemas and apply default values
933 foreach ( $schemaDeclarations as $key => $sch ) {
934 $schema->addSchema( $key, $sch );
935
936 $val = $schema->getDefaultFor( $key );
937 $configBuilder->set( $key, $val );
938 }
939
940 // Apply test values
941 foreach ( $test as $key => $val ) {
942 // Some defaults don't work properly on CI if evaluated in the provider,
943 // so use a callback.
944 if ( is_callable( $val ) ) {
945 $val = $val();
946 }
947
948 $configBuilder->set( $key, $val );
949 }
950
951 $configBuilder->set( MainConfigNames::BaseDirectory, $IP );
952
953 if ( $setup ) {
954 $scopedCallback = $setup( $this );
955 }
956
957 $dynamicDefaults = new DynamicDefaultValues( $schema );
958 $dynamicDefaults->applyDynamicDefaults( $configBuilder );
959 $config = $configBuilder->build();
960
961 // Put the config variables into the local scope, so SetupDynamicConfig.php can use them.
962 foreach ( $config as $key => $val ) {
963 $var = "wg$key";
964 $$var = $val;
965 }
966
967 // phpcs:ignore MediaWiki.VariableAnalysis.MisleadingGlobalNames.Misleading$wgSettings
968 $wgSettings = new SettingsBuilder(
969 MW_INSTALL_PATH,
970 $this->createNoOpMock( ExtensionRegistry::class ),
971 $configBuilder,
972 $this->createNoOpMock( PhpIniSink::class )
973 );
974 require MW_INSTALL_PATH . '/includes/SetupDynamicConfig.php';
975
976 if ( is_callable( $expected ) ) {
977 $vars = get_defined_vars();
978
979 $newKeys = array_map( static function ( $key ) {
980 return substr( $key, 2 );
981 }, array_keys( $vars ) );
982 $vars = array_combine( $newKeys, $vars );
983
984 $expected = $expected( $this, $vars );
985 }
986
987 foreach ( $expected as $key => $val ) {
988 $var = "wg$key";
989 $this->assertSame( is_callable( $val ) ? $val() : $val,
990 $$var, "Unexpected value for \$$var" );
991 }
992 }
993
994 }