FauxRequest: don’t override getValues()
[lhc/web/wiklou.git] / includes / Setup.php
1 <?php
2 /**
3 * Include most things that are needed to make MediaWiki work.
4 *
5 * This file is included by WebStart.php and doMaintenance.php so that both
6 * web and maintenance scripts share a final set up phase to include necessary
7 * files and create global object variables.
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26 use MediaWiki\MediaWikiServices;
27 use Wikimedia\Rdbms\LBFactory;
28 use Wikimedia\Rdbms\ChronologyProtector;
29
30 /**
31 * This file is not a valid entry point, perform no further processing unless
32 * MEDIAWIKI is defined
33 */
34 if ( !defined( 'MEDIAWIKI' ) ) {
35 exit( 1 );
36 }
37
38 // Check to see if we are at the file scope
39 $wgScopeTest = 'MediaWiki Setup.php scope test';
40 if ( !isset( $GLOBALS['wgScopeTest'] ) || $GLOBALS['wgScopeTest'] !== $wgScopeTest ) {
41 echo "Error, Setup.php must be included from the file scope.\n";
42 die( 1 );
43 }
44 unset( $wgScopeTest );
45
46 /**
47 * Pre-config setup: Before loading LocalSettings.php
48 */
49
50 // Sanity check (T5782, T122807)
51 if ( ini_get( 'mbstring.func_overload' ) ) {
52 die( 'MediaWiki does not support installations where mbstring.func_overload is non-zero.' );
53 }
54
55 // Define MW_ENTRY_POINT if it's not already, so that config code can check the
56 // value without using defined()
57 if ( !defined( 'MW_ENTRY_POINT' ) ) {
58 /**
59 * The entry point, which may be either the script filename without the
60 * file extension, or "cli" for maintenance scripts, or "unknown" for any
61 * entry point that does not set the constant.
62 */
63 define( 'MW_ENTRY_POINT', 'unknown' );
64 }
65
66 // Start the autoloader, so that extensions can derive classes from core files
67 require_once "$IP/includes/AutoLoader.php";
68
69 // Load global constants
70 require_once "$IP/includes/Defines.php";
71
72 // Load default settings
73 require_once "$IP/includes/DefaultSettings.php";
74
75 // Load global functions
76 require_once "$IP/includes/GlobalFunctions.php";
77
78 // Load composer's autoloader if present
79 if ( is_readable( "$IP/vendor/autoload.php" ) ) {
80 require_once "$IP/vendor/autoload.php";
81 } elseif ( file_exists( "$IP/vendor/autoload.php" ) ) {
82 die( "$IP/vendor/autoload.php exists but is not readable" );
83 }
84
85 // Assert that composer dependencies were successfully loaded
86 // Purposely no leading \ due to it breaking HHVM RepoAuthorative mode
87 // PHP works fine with both versions
88 // See https://github.com/facebook/hhvm/issues/5833
89 if ( !interface_exists( 'Psr\Log\LoggerInterface' ) ) {
90 $message = (
91 'MediaWiki requires the <a href="https://github.com/php-fig/log">PSR-3 logging ' .
92 "library</a> to be present. This library is not embedded directly in MediaWiki's " .
93 "git repository and must be installed separately by the end user.\n\n" .
94 'Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git' .
95 '#Fetch_external_libraries">mediawiki.org</a> for help on installing ' .
96 'the required components.'
97 );
98 echo $message;
99 trigger_error( $message, E_USER_ERROR );
100 die( 1 );
101 }
102
103 /**
104 * Changes to the PHP environment that don't vary on configuration.
105 */
106
107 // Install a header callback
108 MediaWiki\HeaderCallback::register();
109
110 // Set the encoding used by PHP for reading HTTP input, and writing output.
111 // This is also the default for mbstring functions.
112 mb_internal_encoding( 'UTF-8' );
113
114 /**
115 * Load LocalSettings.php
116 */
117
118 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
119 call_user_func( MW_CONFIG_CALLBACK );
120 } else {
121 if ( !defined( 'MW_CONFIG_FILE' ) ) {
122 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
123 }
124 require_once MW_CONFIG_FILE;
125 }
126
127 /**
128 * Customization point after all loading (constants, functions, classes,
129 * DefaultSettings, LocalSettings). Specifically, this is before usage of
130 * settings, before instantiation of Profiler (and other singletons), and
131 * before any setup functions or hooks run.
132 */
133
134 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
135 call_user_func( MW_SETUP_CALLBACK );
136 }
137
138 /**
139 * Main setup
140 */
141
142 // Load queued extensions
143 ExtensionRegistry::getInstance()->loadFromQueue();
144 // Don't let any other extensions load
145 ExtensionRegistry::getInstance()->finish();
146
147 // Set the configured locale on all requests for consisteny
148 putenv( "LC_ALL=$wgShellLocale" );
149 setlocale( LC_ALL, $wgShellLocale );
150
151 // Set various default paths sensibly...
152 if ( $wgScript === false ) {
153 $wgScript = "$wgScriptPath/index.php";
154 }
155 if ( $wgLoadScript === false ) {
156 $wgLoadScript = "$wgScriptPath/load.php";
157 }
158 if ( $wgRestPath === false ) {
159 $wgRestPath = "$wgScriptPath/rest.php";
160 }
161
162 if ( $wgArticlePath === false ) {
163 if ( $wgUsePathInfo ) {
164 $wgArticlePath = "$wgScript/$1";
165 } else {
166 $wgArticlePath = "$wgScript?title=$1";
167 }
168 }
169
170 if ( $wgResourceBasePath === null ) {
171 $wgResourceBasePath = $wgScriptPath;
172 }
173 if ( $wgStylePath === false ) {
174 $wgStylePath = "$wgResourceBasePath/skins";
175 }
176 if ( $wgLocalStylePath === false ) {
177 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
178 $wgLocalStylePath = "$wgScriptPath/skins";
179 }
180 if ( $wgExtensionAssetsPath === false ) {
181 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
182 }
183
184 if ( $wgLogo === false ) {
185 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
186 }
187
188 if ( $wgUploadPath === false ) {
189 $wgUploadPath = "$wgScriptPath/images";
190 }
191 if ( $wgUploadDirectory === false ) {
192 $wgUploadDirectory = "$IP/images";
193 }
194 if ( $wgReadOnlyFile === false ) {
195 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
196 }
197 if ( $wgFileCacheDirectory === false ) {
198 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
199 }
200 if ( $wgDeletedDirectory === false ) {
201 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
202 }
203
204 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
205 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
206 }
207
208 // Fix path to icon images after they were moved in 1.24
209 if ( $wgRightsIcon ) {
210 $wgRightsIcon = str_replace(
211 "{$wgStylePath}/common/images/",
212 "{$wgResourceBasePath}/resources/assets/licenses/",
213 $wgRightsIcon
214 );
215 }
216
217 if ( isset( $wgFooterIcons['copyright']['copyright'] )
218 && $wgFooterIcons['copyright']['copyright'] === []
219 ) {
220 if ( $wgRightsIcon || $wgRightsText ) {
221 $wgFooterIcons['copyright']['copyright'] = [
222 'url' => $wgRightsUrl,
223 'src' => $wgRightsIcon,
224 'alt' => $wgRightsText,
225 ];
226 }
227 }
228
229 if ( isset( $wgFooterIcons['poweredby'] )
230 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
231 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
232 ) {
233 $wgFooterIcons['poweredby']['mediawiki']['src'] =
234 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
235 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
236 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
237 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
238 }
239
240 /**
241 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
242 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
243 *
244 * Note that this is the definition of editinterface and it can be granted to
245 * all users if desired.
246 */
247 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
248
249 /**
250 * The canonical names of namespaces 6 and 7 are, as of v1.14, "File"
251 * and "File_talk". The old names "Image" and "Image_talk" are
252 * retained as aliases for backwards compatibility.
253 */
254 $wgNamespaceAliases['Image'] = NS_FILE;
255 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
256
257 /**
258 * Initialise $wgLockManagers to include basic FS version
259 */
260 $wgLockManagers[] = [
261 'name' => 'fsLockManager',
262 'class' => FSLockManager::class,
263 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
264 ];
265 $wgLockManagers[] = [
266 'name' => 'nullLockManager',
267 'class' => NullLockManager::class,
268 ];
269
270 /**
271 * Default parameters for the "<gallery>" tag.
272 * @see DefaultSettings.php for description of the fields.
273 */
274 $wgGalleryOptions += [
275 'imagesPerRow' => 0,
276 'imageWidth' => 120,
277 'imageHeight' => 120,
278 'captionLength' => true,
279 'showBytes' => true,
280 'showDimensions' => true,
281 'mode' => 'traditional',
282 ];
283
284 /**
285 * Shortcuts for $wgLocalFileRepo
286 */
287 if ( !$wgLocalFileRepo ) {
288 $wgLocalFileRepo = [
289 'class' => LocalRepo::class,
290 'name' => 'local',
291 'directory' => $wgUploadDirectory,
292 'scriptDirUrl' => $wgScriptPath,
293 'url' => $wgUploadBaseUrl ? $wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
294 'hashLevels' => $wgHashedUploadDirectory ? 2 : 0,
295 'thumbScriptUrl' => $wgThumbnailScriptPath,
296 'transformVia404' => !$wgGenerateThumbnailOnParse,
297 'deletedDir' => $wgDeletedDirectory,
298 'deletedHashLevels' => $wgHashedUploadDirectory ? 3 : 0
299 ];
300 }
301
302 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
303 // Create a default FileBackend name.
304 // FileBackendGroup will register a default, if absent from $wgFileBackends.
305 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
306 }
307
308 /**
309 * Shortcuts for $wgForeignFileRepos
310 */
311 if ( $wgUseSharedUploads ) {
312 if ( $wgSharedUploadDBname ) {
313 $wgForeignFileRepos[] = [
314 'class' => ForeignDBRepo::class,
315 'name' => 'shared',
316 'directory' => $wgSharedUploadDirectory,
317 'url' => $wgSharedUploadPath,
318 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
319 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
320 'transformVia404' => !$wgGenerateThumbnailOnParse,
321 'dbType' => $wgDBtype,
322 'dbServer' => $wgDBserver,
323 'dbUser' => $wgDBuser,
324 'dbPassword' => $wgDBpassword,
325 'dbName' => $wgSharedUploadDBname,
326 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG : 0 ) | DBO_DEFAULT,
327 'tablePrefix' => $wgSharedUploadDBprefix,
328 'hasSharedCache' => $wgCacheSharedUploads,
329 'descBaseUrl' => $wgRepositoryBaseUrl,
330 'fetchDescription' => $wgFetchCommonsDescriptions,
331 ];
332 } else {
333 $wgForeignFileRepos[] = [
334 'class' => FileRepo::class,
335 'name' => 'shared',
336 'directory' => $wgSharedUploadDirectory,
337 'url' => $wgSharedUploadPath,
338 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
339 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
340 'transformVia404' => !$wgGenerateThumbnailOnParse,
341 'descBaseUrl' => $wgRepositoryBaseUrl,
342 'fetchDescription' => $wgFetchCommonsDescriptions,
343 ];
344 }
345 }
346 if ( $wgUseInstantCommons ) {
347 $wgForeignFileRepos[] = [
348 'class' => ForeignAPIRepo::class,
349 'name' => 'wikimediacommons',
350 'apibase' => 'https://commons.wikimedia.org/w/api.php',
351 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
352 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
353 'hashLevels' => 2,
354 'transformVia404' => true,
355 'fetchDescription' => true,
356 'descriptionCacheExpiry' => 43200,
357 'apiThumbCacheExpiry' => 0,
358 ];
359 }
360 foreach ( $wgForeignFileRepos as &$repo ) {
361 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo::class ) {
362 $repo['directory'] = $wgUploadDirectory; // b/c
363 }
364 if ( !isset( $repo['backend'] ) ) {
365 $repo['backend'] = $repo['name'] . '-backend';
366 }
367 }
368 unset( $repo ); // no global pollution; destroy reference
369
370 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
371 // Ensure that default user options are not invalid, since that breaks Special:Preferences
372 $wgDefaultUserOptions['rcdays'] = min(
373 $wgDefaultUserOptions['rcdays'],
374 ceil( $rcMaxAgeDays )
375 );
376 $wgDefaultUserOptions['watchlistdays'] = min(
377 $wgDefaultUserOptions['watchlistdays'],
378 ceil( $rcMaxAgeDays )
379 );
380 unset( $rcMaxAgeDays );
381
382 if ( $wgSkipSkin ) {
383 // Hard deprecated in 1.34.
384 wfDeprecated( '$wgSkipSkin – use $wgSkipSkins instead', '1.23' );
385 $wgSkipSkins[] = $wgSkipSkin;
386 }
387
388 $wgSkipSkins[] = 'fallback';
389 $wgSkipSkins[] = 'apioutput';
390
391 if ( $wgLocalInterwiki ) {
392 // Hard deprecated in 1.34.
393 wfDeprecated( '$wgLocalInterwiki – use $wgLocalInterwikis instead', '1.23' );
394 // @phan-suppress-next-line PhanUndeclaredVariableDim
395 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
396 }
397
398 // Set default shared prefix
399 if ( $wgSharedPrefix === false ) {
400 $wgSharedPrefix = $wgDBprefix;
401 }
402
403 // Set default shared schema
404 if ( $wgSharedSchema === false ) {
405 $wgSharedSchema = $wgDBmwschema;
406 }
407
408 if ( !$wgCookiePrefix ) {
409 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
410 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
411 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
412 $wgCookiePrefix = $wgSharedDB;
413 } elseif ( $wgDBprefix ) {
414 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
415 } else {
416 $wgCookiePrefix = $wgDBname;
417 }
418 }
419 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
420
421 if ( $wgEnableEmail ) {
422 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
423 } else {
424 // Disable all other email settings automatically if $wgEnableEmail
425 // is set to false. - T65678
426 $wgAllowHTMLEmail = false;
427 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
428 $wgEnableUserEmail = false;
429 $wgEnotifFromEditor = false;
430 $wgEnotifImpersonal = false;
431 $wgEnotifMaxRecips = 0;
432 $wgEnotifMinorEdits = false;
433 $wgEnotifRevealEditorAddress = false;
434 $wgEnotifUseRealName = false;
435 $wgEnotifUserTalk = false;
436 $wgEnotifWatchlist = false;
437 unset( $wgGroupPermissions['user']['sendemail'] );
438 $wgUseEnotif = false;
439 $wgUserEmailUseReplyTo = false;
440 $wgUsersNotifiedOnAllChanges = [];
441 }
442
443 if ( $wgMetaNamespace === false ) {
444 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
445 }
446
447 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
448 // upload size.
449 $wgMinUploadChunkSize = min(
450 $wgMinUploadChunkSize,
451 UploadBase::getMaxUploadSize( 'file' ),
452 UploadBase::getMaxPhpUploadSize(),
453 ( wfShorthandToInteger(
454 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
455 PHP_INT_MAX
456 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
457 );
458
459 /**
460 * Definitions of the NS_ constants are in Defines.php
461 * @private
462 */
463 $wgCanonicalNamespaceNames = NamespaceInfo::$canonicalNames;
464
465 /// @todo UGLY UGLY
466 if ( is_array( $wgExtraNamespaces ) ) {
467 $wgCanonicalNamespaceNames += $wgExtraNamespaces;
468 }
469
470 // Hard-deprecate setting $wgDummyLanguageCodes in LocalSettings.php
471 if ( count( $wgDummyLanguageCodes ) !== 0 ) {
472 wfDeprecated( '$wgDummyLanguageCodes', '1.29' );
473 }
474 // Merge in the legacy language codes, incorporating overrides from the config
475 $wgDummyLanguageCodes += [
476 // Internal language codes of the private-use area which get mapped to
477 // themselves.
478 'qqq' => 'qqq', // Used for message documentation
479 'qqx' => 'qqx', // Used for viewing message keys
480 ] + $wgExtraLanguageCodes + LanguageCode::getDeprecatedCodeMapping();
481 // Merge in (inverted) BCP 47 mappings
482 foreach ( LanguageCode::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
483 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
484 if ( !isset( $wgDummyLanguageCodes[$bcp47] ) ) {
485 $wgDummyLanguageCodes[$bcp47] = $wgDummyLanguageCodes[$code] ?? $code;
486 }
487 }
488
489 // These are now the same, always
490 // To determine the user language, use $wgLang->getCode()
491 $wgContLanguageCode = $wgLanguageCode;
492
493 // Temporary backwards-compatibility reading of old Squid-named CDN settings as of MediaWiki 1.34,
494 // to support sysadmins who fail to update their settings immediately:
495
496 if ( isset( $wgUseSquid ) ) {
497 // If the sysadmin is still setting a value of $wgUseSquid to true but $wgUseCdn is the default of
498 // false, to be safe, assume they do want this still, so enable it.
499 if ( !$wgUseCdn && $wgUseSquid ) {
500 $wgUseCdn = $wgUseSquid;
501 wfDeprecated( '$wgUseSquid enabled but $wgUseCdn disabled; enabling CDN functions', '1.34' );
502 }
503 } else {
504 // Backwards-compatibility for extensions that read this value.
505 $wgUseSquid = $wgUseCdn;
506 }
507
508 if ( isset( $wgSquidServers ) ) {
509 // If the sysadmin is still setting a value of $wgSquidServers but $wgCdnServers is the default of
510 // empty, to be safe, assume they do want these servers to be still used, so use them.
511 if ( !empty( $wgSquidServers ) && empty( $wgCdnServers ) ) {
512 $wgCdnServers = $wgSquidServers;
513 wfDeprecated( '$wgSquidServers set, $wgCdnServers empty; using them', '1.34' );
514 }
515 } else {
516 // Backwards-compatibility for extensions that read this value.
517 $wgSquidServers = $wgCdnServers;
518 }
519
520 if ( isset( $wgSquidServersNoPurge ) ) {
521 // If the sysadmin is still setting values in $wgSquidServersNoPurge but $wgCdnServersNoPurge is
522 // the default of empty, to be safe, assume they do want these servers to be still used, so use
523 // them.
524 if ( !empty( $wgSquidServersNoPurge ) && empty( $wgCdnServersNoPurge ) ) {
525 $wgCdnServersNoPurge = $wgSquidServersNoPurge;
526 wfDeprecated( '$wgSquidServersNoPurge set, $wgCdnServersNoPurge empty; using them', '1.34' );
527 }
528 } else {
529 // Backwards-compatibility for extensions that read this value.
530 $wgSquidServersNoPurge = $wgCdnServersNoPurge;
531 }
532
533 if ( isset( $wgSquidMaxage ) ) {
534 // If the sysadmin is still setting a value of $wgSquidMaxage and it's higher than $wgCdnMaxAge,
535 // to be safe, assume they want the higher (lower performance requirement) value, so use that.
536 if ( $wgCdnMaxAge < $wgSquidMaxage ) {
537 $wgCdnMaxAge = $wgSquidMaxage;
538 wfDeprecated( '$wgSquidMaxage set higher than $wgCdnMaxAge; using the higher value', '1.34' );
539 }
540 } else {
541 // Backwards-compatibility for extensions that read this value.
542 $wgSquidMaxage = $wgCdnMaxAge;
543 }
544
545 // Blacklisted file extensions shouldn't appear on the "allowed" list
546 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
547
548 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
549 Wikimedia\suppressWarnings();
550 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
551 Wikimedia\restoreWarnings();
552 }
553
554 if ( $wgNewUserLog ) {
555 // Add new user log type
556 $wgLogTypes[] = 'newusers';
557 $wgLogNames['newusers'] = 'newuserlogpage';
558 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
559 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter::class;
560 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter::class;
561 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter::class;
562 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter::class;
563 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter::class;
564 }
565
566 if ( $wgPageCreationLog ) {
567 // Add page creation log type
568 $wgLogTypes[] = 'create';
569 $wgLogActionsHandlers['create/create'] = LogFormatter::class;
570 }
571
572 if ( $wgPageLanguageUseDB ) {
573 $wgLogTypes[] = 'pagelang';
574 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter::class;
575 }
576
577 if ( $wgCookieSecure === 'detect' ) {
578 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
579 }
580
581 if ( $wgProfileOnly ) {
582 // Hard deprecated in 1.34.
583 wfDeprecated(
584 '$wgProfileOnly set the log file in $wgDebugLogGroups[\'profileoutput\'] instead',
585 '1.23'
586 );
587 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
588 $wgDebugLogFile = '';
589 }
590
591 // Backwards compatibility with old password limits
592 if ( $wgMinimalPasswordLength !== false ) {
593 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
594 }
595
596 if ( $wgMaximalPasswordLength !== false ) {
597 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
598 }
599
600 if ( $wgPHPSessionHandling !== 'enable' &&
601 $wgPHPSessionHandling !== 'warn' &&
602 $wgPHPSessionHandling !== 'disable'
603 ) {
604 $wgPHPSessionHandling = 'warn';
605 }
606 if ( defined( 'MW_NO_SESSION' ) ) {
607 // If the entry point wants no session, force 'disable' here unless they
608 // specifically set it to the (undocumented) 'warn'.
609 // @phan-suppress-next-line PhanUndeclaredConstant
610 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
611 }
612
613 MWDebug::setup();
614
615 // Reset the global service locator, so any services that have already been created will be
616 // re-created while taking into account any custom settings and extensions.
617 MediaWikiServices::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
618
619 // Define a constant that indicates that the bootstrapping of the service locator
620 // is complete.
621 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
622
623 MWExceptionHandler::installHandler();
624
625 // T48998: Bail out early if $wgArticlePath is non-absolute
626 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
627 if ( $$varName && !preg_match( '/^(https?:\/\/|\/)/', $$varName ) ) {
628 throw new FatalError(
629 "If you use a relative URL for \$$varName, it must start " .
630 'with a slash (<code>/</code>).<br><br>See ' .
631 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
632 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
633 );
634 }
635 }
636
637 if ( $wgCanonicalServer === false ) {
638 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP );
639 }
640
641 // Set server name
642 $serverParts = wfParseUrl( $wgCanonicalServer );
643 if ( $wgServerName !== false ) {
644 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
645 . 'not customized. Overwriting $wgServerName.' );
646 }
647 $wgServerName = $serverParts['host'];
648 unset( $serverParts );
649
650 // Set defaults for configuration variables
651 // that are derived from the server name by default
652 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
653 if ( !$wgEmergencyContact ) {
654 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
655 }
656 if ( !$wgPasswordSender ) {
657 $wgPasswordSender = 'apache@' . $wgServerName;
658 }
659 if ( !$wgNoReplyAddress ) {
660 $wgNoReplyAddress = $wgPasswordSender;
661 }
662
663 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
664 $wgSecureLogin = false;
665 wfWarn( 'Secure login was enabled on a server that only supports '
666 . 'HTTP or HTTPS. Disabling secure login.' );
667 }
668
669 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
670
671 // Now that GlobalFunctions is loaded, set defaults that depend on it.
672 if ( $wgTmpDirectory === false ) {
673 $wgTmpDirectory = wfTempDir();
674 }
675
676 // We don't use counters anymore. Left here for extensions still
677 // expecting this to exist. Should be removed sometime 1.26 or later.
678 if ( !isset( $wgDisableCounters ) ) {
679 $wgDisableCounters = true;
680 }
681
682 if ( $wgMainWANCache === false ) {
683 // Setup a WAN cache from $wgMainCacheType with no relayer.
684 // Sites using multiple datacenters can configure a relayer.
685 $wgMainWANCache = 'mediawiki-main-default';
686 $wgWANObjectCaches[$wgMainWANCache] = [
687 'class' => WANObjectCache::class,
688 'cacheId' => $wgMainCacheType
689 ];
690 }
691
692 if ( $wgSharedDB && $wgSharedTables ) {
693 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
694 MediaWikiServices::getInstance()->getDBLoadBalancer()->setTableAliases(
695 array_fill_keys(
696 $wgSharedTables,
697 [
698 'dbname' => $wgSharedDB,
699 'schema' => $wgSharedSchema,
700 'prefix' => $wgSharedPrefix
701 ]
702 )
703 );
704 }
705
706 // Raise the memory limit if it's too low
707 // Note, this makes use of wfDebug, and thus should not be before
708 // MWDebug::init() is called.
709 wfMemoryLimit( $wgMemoryLimit );
710
711 /**
712 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
713 * that happens whenever you use a date function without the timezone being
714 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
715 */
716 if ( is_null( $wgLocaltimezone ) ) {
717 Wikimedia\suppressWarnings();
718 $wgLocaltimezone = date_default_timezone_get();
719 Wikimedia\restoreWarnings();
720 }
721
722 date_default_timezone_set( $wgLocaltimezone );
723 if ( is_null( $wgLocalTZoffset ) ) {
724 $wgLocalTZoffset = date( 'Z' ) / 60;
725 }
726 // The part after the System| is ignored, but rest of MW fills it
727 // out as the local offset.
728 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
729
730 if ( !$wgDBerrorLogTZ ) {
731 $wgDBerrorLogTZ = $wgLocaltimezone;
732 }
733
734 // Initialize the request object in $wgRequest
735 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
736 // Set user IP/agent information for agent session consistency purposes
737 $cpPosInfo = LBFactory::getCPInfoFromCookieValue(
738 // The cookie has no prefix and is set by MediaWiki::preOutputCommit()
739 $wgRequest->getCookie( 'cpPosIndex', '' ),
740 // Mitigate broken client-side cookie expiration handling (T190082)
741 time() - ChronologyProtector::POSITION_COOKIE_TTL
742 );
743 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
744 'IPAddress' => $wgRequest->getIP(),
745 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
746 'ChronologyProtection' => $wgRequest->getHeader( 'MediaWiki-Chronology-Protection' ),
747 'ChronologyPositionIndex' => $wgRequest->getInt( 'cpPosIndex', $cpPosInfo['index'] ),
748 'ChronologyClientId' => $cpPosInfo['clientId']
749 ?? $wgRequest->getHeader( 'MediaWiki-Chronology-Client-Id' )
750 ] );
751 unset( $cpPosInfo );
752 // Make sure that object caching does not undermine the ChronologyProtector improvements
753 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
754 // The user is pinned to the primary DC, meaning that they made recent changes which should
755 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
756 // they use a blind TTL and could be stale if an object changes twice in a short time span.
757 MediaWikiServices::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
758 }
759
760 // Useful debug output
761 if ( $wgCommandLineMode ) {
762 if ( isset( $self ) ) {
763 wfDebug( "\n\nStart command line script $self\n" );
764 }
765 } else {
766 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
767 $debug .= "HTTP HEADERS:\n";
768 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
769 $debug .= "$name: $value\n";
770 }
771 wfDebug( $debug );
772 }
773
774 $wgMemc = ObjectCache::getLocalClusterInstance();
775 $messageMemc = wfGetMessageCacheStorage();
776
777 // Most of the config is out, some might want to run hooks here.
778 Hooks::run( 'SetupAfterCache' );
779
780 /**
781 * @var Language $wgContLang
782 * @deprecated since 1.32, use the ContentLanguage service directly
783 */
784 $wgContLang = MediaWikiServices::getInstance()->getContentLanguage();
785
786 // Now that variant lists may be available...
787 $wgRequest->interpolateTitle();
788
789 /**
790 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
791 * session ID (if any) loaded at startup
792 */
793 $wgInitialSessionId = null;
794 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
795 // If session.auto_start is there, we can't touch session name
796 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
797 session_name( $wgSessionName ?: $wgCookiePrefix . '_session' );
798 }
799
800 // Create the SessionManager singleton and set up our session handler,
801 // unless we're specifically asked not to.
802 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
803 MediaWiki\Session\PHPSessionHandler::install(
804 MediaWiki\Session\SessionManager::singleton()
805 );
806 }
807
808 // Initialize the session
809 try {
810 $session = MediaWiki\Session\SessionManager::getGlobalSession();
811 } catch ( MediaWiki\Session\SessionOverflowException $ex ) {
812 // The exception is because the request had multiple possible
813 // sessions tied for top priority. Report this to the user.
814 $list = [];
815 foreach ( $ex->getSessionInfos() as $info ) {
816 $list[] = $info->getProvider()->describe( $wgContLang );
817 }
818 $list = $wgContLang->listToText( $list );
819 throw new HttpError( 400,
820 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
821 );
822 }
823
824 if ( $session->isPersistent() ) {
825 $wgInitialSessionId = $session->getSessionId();
826 }
827
828 $session->renew();
829 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
830 ( $session->isPersistent() || $session->shouldRememberUser() ) &&
831 session_id() !== $session->getId()
832 ) {
833 // Start the PHP-session for backwards compatibility
834 if ( session_id() !== '' ) {
835 wfDebugLog( 'session', 'PHP session {old_id} was already started, changing to {new_id}', 'all', [
836 'old_id' => session_id(),
837 'new_id' => $session->getId(),
838 ] );
839 session_write_close();
840 }
841 session_id( $session->getId() );
842 session_start();
843 }
844
845 unset( $session );
846 } else {
847 // Even if we didn't set up a global Session, still install our session
848 // handler unless specifically requested not to.
849 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
850 MediaWiki\Session\PHPSessionHandler::install(
851 MediaWiki\Session\SessionManager::singleton()
852 );
853 }
854 }
855
856 /**
857 * @var User $wgUser
858 */
859 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
860
861 /**
862 * @var Language $wgLang
863 */
864 $wgLang = new StubUserLang;
865
866 /**
867 * @var OutputPage $wgOut
868 */
869 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
870
871 /**
872 * @var Parser $wgParser
873 * @deprecated since 1.32, use MediaWikiServices::getInstance()->getParser() instead
874 */
875 $wgParser = new StubObject( 'wgParser', function () {
876 return MediaWikiServices::getInstance()->getParser();
877 } );
878
879 /**
880 * @var Title $wgTitle
881 */
882 $wgTitle = null;
883
884 // Extension setup functions
885 // Entries should be added to this variable during the inclusion
886 // of the extension file. This allows the extension to perform
887 // any necessary initialisation in the fully initialised environment
888 foreach ( $wgExtensionFunctions as $func ) {
889 call_user_func( $func );
890 }
891
892 // If the session user has a 0 id but a valid name, that means we need to
893 // autocreate it.
894 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
895 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
896 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
897 $res = MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
898 $sessionUser,
899 MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
900 true
901 );
902 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Autocreation attempt', [
903 'event' => 'autocreate',
904 'status' => $res,
905 ] );
906 unset( $res );
907 }
908 unset( $sessionUser );
909 }
910
911 if ( !$wgCommandLineMode ) {
912 Pingback::schedulePingback();
913 }
914
915 $wgFullyInitialised = true;