CentralIdLookup: Add @since to factoryNonLocal()
[mediawiki.git] / includes / Setup.php
blob615db264870c3ace4b814b8ee357b1a48b01e02b
1 <?php
2 /**
3 * The setup for all MediaWiki processes (both web-based and CLI).
5 * This file must be included by all entry points (such as WebStart.php and doMaintenance.php).
6 * - The entry point MUST do these:
7 * - define the 'MEDIAWIKI' constant.
8 * - define the $IP global variable.
9 * - The entry point SHOULD do these:
10 * - define the 'MW_ENTRY_POINT' constant.
11 * - display an error if MW_CONFIG_CALLBACK is not defined and the
12 * the file specified in MW_CONFIG_FILE (or the $IP/LocalSettings.php default)
13 * does not exist. The error should either be sent before and instead
14 * of the Setup.php inclusion, or (if it needs classes and dependencies
15 * from core) the erorr can be displayed via a MW_CONFIG_CALLBACK,
16 * which must then abort the process to prevent the rest of Setup.php
17 * from executing.
19 * It does:
20 * - run-time environment checks,
21 * - load autoloaders, constants, default settings, and global functions,
22 * - load the site configuration (e.g. LocalSettings.php),
23 * - load the enabled extensions (via ExtensionRegistry),
24 * - expand any dynamic site configuration defaults and shortcuts
25 * - initialization of:
26 * - PHP run-time (setlocale, memory limit, default date timezone)
27 * - the debug logger (MWDebug)
28 * - the service container (MediaWikiServices)
29 * - the exception handler (MWExceptionHandler)
30 * - the session manager (SessionManager)
32 * This program is free software; you can redistribute it and/or modify
33 * it under the terms of the GNU General Public License as published by
34 * the Free Software Foundation; either version 2 of the License, or
35 * (at your option) any later version.
37 * This program is distributed in the hope that it will be useful,
38 * but WITHOUT ANY WARRANTY; without even the implied warranty of
39 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
40 * GNU General Public License for more details.
42 * You should have received a copy of the GNU General Public License along
43 * with this program; if not, write to the Free Software Foundation, Inc.,
44 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
45 * http://www.gnu.org/copyleft/gpl.html
47 * @file
50 use MediaWiki\Logger\LoggerFactory;
51 use MediaWiki\MediaWikiServices;
52 use Psr\Log\LoggerInterface;
53 use Wikimedia\Rdbms\ChronologyProtector;
54 use Wikimedia\Rdbms\LBFactory;
56 /**
57 * Environment checks
59 * These are inline checks done before we include any source files,
60 * and thus these conditions may be assumed by all source code.
63 // This file must be included from a valid entry point (e.g. WebStart.php, Maintenance.php)
64 if ( !defined( 'MEDIAWIKI' ) ) {
65 exit( 1 );
68 // This file must have global scope.
69 $wgScopeTest = 'MediaWiki Setup.php scope test';
70 if ( !isset( $GLOBALS['wgScopeTest'] ) || $GLOBALS['wgScopeTest'] !== $wgScopeTest ) {
71 echo "Error, Setup.php must be included from the file scope.\n";
72 die( 1 );
74 unset( $wgScopeTest );
76 // PHP must not be configured to overload mbstring functions. (T5782, T122807)
77 // This was deprecated by upstream in PHP 7.2, likely to be removed in PHP 8.0.
78 if ( ini_get( 'mbstring.func_overload' ) ) {
79 die( 'MediaWiki does not support installations where mbstring.func_overload is non-zero.' );
82 // The MW_ENTRY_POINT constant must always exists, to make it safe to access.
83 // For compat, we do support older and custom MW entryoints that don't set this,
84 // in which case we assign a default here.
85 if ( !defined( 'MW_ENTRY_POINT' ) ) {
86 /**
87 * The entry point, which may be either the script filename without the
88 * file extension, or "cli" for maintenance scripts, or "unknown" for any
89 * entry point that does not set the constant.
91 define( 'MW_ENTRY_POINT', 'unknown' );
94 /**
95 * Pre-config setup: Before loading LocalSettings.php
97 * These are changes and additions to runtime that don't vary on site configuration.
100 require_once "$IP/includes/AutoLoader.php";
101 require_once "$IP/includes/Defines.php";
102 require_once "$IP/includes/DefaultSettings.php";
103 require_once "$IP/includes/GlobalFunctions.php";
105 // Load composer's autoloader if present
106 if ( is_readable( "$IP/vendor/autoload.php" ) ) {
107 require_once "$IP/vendor/autoload.php";
108 } elseif ( file_exists( "$IP/vendor/autoload.php" ) ) {
109 die( "$IP/vendor/autoload.php exists but is not readable" );
112 // Assert that composer dependencies were successfully loaded
113 if ( !interface_exists( LoggerInterface::class ) ) {
114 $message = (
115 'MediaWiki requires the <a href="https://github.com/php-fig/log">PSR-3 logging ' .
116 "library</a> to be present. This library is not embedded directly in MediaWiki's " .
117 "git repository and must be installed separately by the end user.\n\n" .
118 'Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git' .
119 '#Fetch_external_libraries">mediawiki.org</a> for help on installing ' .
120 'the required components.'
122 echo $message;
123 trigger_error( $message, E_USER_ERROR );
124 die( 1 );
127 MediaWiki\HeaderCallback::register();
129 // Set the encoding used by PHP for reading HTTP input, and writing output.
130 // This is also the default for mbstring functions.
131 mb_internal_encoding( 'UTF-8' );
134 * Load LocalSettings.php
137 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
138 call_user_func( MW_CONFIG_CALLBACK );
139 } else {
140 if ( !defined( 'MW_CONFIG_FILE' ) ) {
141 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
143 require_once MW_CONFIG_FILE;
147 * Customization point after all loading (constants, functions, classes,
148 * DefaultSettings, LocalSettings). Specifically, this is before usage of
149 * settings, before instantiation of Profiler (and other singletons), and
150 * before any setup functions or hooks run.
153 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
154 call_user_func( MW_SETUP_CALLBACK );
158 * Load queued extensions
161 ExtensionRegistry::getInstance()->loadFromQueue();
162 // Don't let any other extensions load
163 ExtensionRegistry::getInstance()->finish();
165 // Set the configured locale on all requests for consistency
166 // This must be after LocalSettings.php (and is informed by the installer).
167 putenv( "LC_ALL=$wgShellLocale" );
168 setlocale( LC_ALL, $wgShellLocale );
171 * Expand dynamic defaults and shortcuts
174 if ( $wgScript === false ) {
175 $wgScript = "$wgScriptPath/index.php";
177 if ( $wgLoadScript === false ) {
178 $wgLoadScript = "$wgScriptPath/load.php";
180 if ( $wgRestPath === false ) {
181 $wgRestPath = "$wgScriptPath/rest.php";
183 if ( $wgArticlePath === false ) {
184 if ( $wgUsePathInfo ) {
185 $wgArticlePath = "$wgScript/$1";
186 } else {
187 $wgArticlePath = "$wgScript?title=$1";
190 if ( $wgResourceBasePath === null ) {
191 $wgResourceBasePath = $wgScriptPath;
193 if ( $wgStylePath === false ) {
194 $wgStylePath = "$wgResourceBasePath/skins";
196 if ( $wgLocalStylePath === false ) {
197 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
198 $wgLocalStylePath = "$wgScriptPath/skins";
200 if ( $wgExtensionAssetsPath === false ) {
201 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
204 // For backwards compatibility, the value of wgLogos is copied to wgLogo.
205 // This is because some extensions/skins may be using $config->get('Logo')
206 // to access the value.
207 if ( $wgLogos !== false && isset( $wgLogos['1x'] ) ) {
208 $wgLogo = $wgLogos['1x'];
210 if ( $wgLogo === false ) {
211 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
214 if ( $wgUploadPath === false ) {
215 $wgUploadPath = "$wgScriptPath/images";
217 if ( $wgUploadDirectory === false ) {
218 $wgUploadDirectory = "$IP/images";
220 if ( $wgReadOnlyFile === false ) {
221 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
223 if ( $wgFileCacheDirectory === false ) {
224 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
226 if ( $wgDeletedDirectory === false ) {
227 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
229 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
230 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
232 if ( $wgSharedPrefix === false ) {
233 $wgSharedPrefix = $wgDBprefix;
235 if ( $wgSharedSchema === false ) {
236 $wgSharedSchema = $wgDBmwschema;
238 if ( $wgMetaNamespace === false ) {
239 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
242 // Blacklisted file extensions shouldn't appear on the "allowed" list
243 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
245 // Fix path to icon images after they were moved in 1.24
246 if ( $wgRightsIcon ) {
247 $wgRightsIcon = str_replace(
248 "{$wgStylePath}/common/images/",
249 "{$wgResourceBasePath}/resources/assets/licenses/",
250 $wgRightsIcon
254 if ( isset( $wgFooterIcons['copyright']['copyright'] )
255 && $wgFooterIcons['copyright']['copyright'] === []
257 if ( $wgRightsIcon || $wgRightsText ) {
258 $wgFooterIcons['copyright']['copyright'] = [
259 'url' => $wgRightsUrl,
260 'src' => $wgRightsIcon,
261 'alt' => $wgRightsText,
266 if ( isset( $wgFooterIcons['poweredby'] )
267 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
268 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
270 $wgFooterIcons['poweredby']['mediawiki']['src'] =
271 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
272 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
273 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
274 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
278 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
279 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
281 * Note that this is the definition of editinterface and it can be granted to
282 * all users if desired.
284 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
287 * Initialise $wgLockManagers to include basic FS version
289 $wgLockManagers[] = [
290 'name' => 'fsLockManager',
291 'class' => FSLockManager::class,
292 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
294 $wgLockManagers[] = [
295 'name' => 'nullLockManager',
296 'class' => NullLockManager::class,
300 * Default parameters for the "<gallery>" tag.
301 * @see DefaultSettings.php for description of the fields.
303 $wgGalleryOptions += [
304 'imagesPerRow' => 0,
305 'imageWidth' => 120,
306 'imageHeight' => 120,
307 'captionLength' => true,
308 'showBytes' => true,
309 'showDimensions' => true,
310 'mode' => 'traditional',
314 * Shortcuts for $wgLocalFileRepo
316 if ( !$wgLocalFileRepo ) {
317 $wgLocalFileRepo = [
318 'class' => LocalRepo::class,
319 'name' => 'local',
320 'directory' => $wgUploadDirectory,
321 'scriptDirUrl' => $wgScriptPath,
322 'url' => $wgUploadBaseUrl ? $wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
323 'hashLevels' => $wgHashedUploadDirectory ? 2 : 0,
324 'thumbScriptUrl' => $wgThumbnailScriptPath,
325 'transformVia404' => !$wgGenerateThumbnailOnParse,
326 'deletedDir' => $wgDeletedDirectory,
327 'deletedHashLevels' => $wgHashedUploadDirectory ? 3 : 0
331 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
332 // Create a default FileBackend name.
333 // FileBackendGroup will register a default, if absent from $wgFileBackends.
334 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
338 * Shortcuts for $wgForeignFileRepos
340 if ( $wgUseSharedUploads ) {
341 if ( $wgSharedUploadDBname ) {
342 $wgForeignFileRepos[] = [
343 'class' => ForeignDBRepo::class,
344 'name' => 'shared',
345 'directory' => $wgSharedUploadDirectory,
346 'url' => $wgSharedUploadPath,
347 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
348 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
349 'transformVia404' => !$wgGenerateThumbnailOnParse,
350 'dbType' => $wgDBtype,
351 'dbServer' => $wgDBserver,
352 'dbUser' => $wgDBuser,
353 'dbPassword' => $wgDBpassword,
354 'dbName' => $wgSharedUploadDBname,
355 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG : 0 ) | DBO_DEFAULT,
356 'tablePrefix' => $wgSharedUploadDBprefix,
357 'hasSharedCache' => $wgCacheSharedUploads,
358 'descBaseUrl' => $wgRepositoryBaseUrl,
359 'fetchDescription' => $wgFetchCommonsDescriptions,
361 } else {
362 $wgForeignFileRepos[] = [
363 'class' => FileRepo::class,
364 'name' => 'shared',
365 'directory' => $wgSharedUploadDirectory,
366 'url' => $wgSharedUploadPath,
367 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
368 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
369 'transformVia404' => !$wgGenerateThumbnailOnParse,
370 'descBaseUrl' => $wgRepositoryBaseUrl,
371 'fetchDescription' => $wgFetchCommonsDescriptions,
375 if ( $wgUseInstantCommons ) {
376 $wgForeignFileRepos[] = [
377 'class' => ForeignAPIRepo::class,
378 'name' => 'wikimediacommons',
379 'apibase' => 'https://commons.wikimedia.org/w/api.php',
380 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
381 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
382 'hashLevels' => 2,
383 'transformVia404' => true,
384 'fetchDescription' => true,
385 'descriptionCacheExpiry' => 43200,
386 'apiThumbCacheExpiry' => 0,
389 foreach ( $wgForeignFileRepos as &$repo ) {
390 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo::class ) {
391 $repo['directory'] = $wgUploadDirectory; // b/c
393 if ( !isset( $repo['backend'] ) ) {
394 $repo['backend'] = $repo['name'] . '-backend';
397 unset( $repo ); // no global pollution; destroy reference
399 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
400 // Ensure that default user options are not invalid, since that breaks Special:Preferences
401 $wgDefaultUserOptions['rcdays'] = min(
402 $wgDefaultUserOptions['rcdays'],
403 ceil( $rcMaxAgeDays )
405 $wgDefaultUserOptions['watchlistdays'] = min(
406 $wgDefaultUserOptions['watchlistdays'],
407 ceil( $rcMaxAgeDays )
409 unset( $rcMaxAgeDays );
411 if ( !$wgCookiePrefix ) {
412 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
413 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
414 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
415 $wgCookiePrefix = $wgSharedDB;
416 } elseif ( $wgDBprefix ) {
417 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
418 } else {
419 $wgCookiePrefix = $wgDBname;
422 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
424 if ( $wgEnableEmail ) {
425 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
426 } else {
427 // Disable all other email settings automatically if $wgEnableEmail
428 // is set to false. - T65678
429 $wgAllowHTMLEmail = false;
430 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
431 $wgEnableUserEmail = false;
432 $wgEnotifFromEditor = false;
433 $wgEnotifImpersonal = false;
434 $wgEnotifMaxRecips = 0;
435 $wgEnotifMinorEdits = false;
436 $wgEnotifRevealEditorAddress = false;
437 $wgEnotifUseRealName = false;
438 $wgEnotifUserTalk = false;
439 $wgEnotifWatchlist = false;
440 unset( $wgGroupPermissions['user']['sendemail'] );
441 $wgUseEnotif = false;
442 $wgUserEmailUseReplyTo = false;
443 $wgUsersNotifiedOnAllChanges = [];
447 * Definitions of the NS_ constants are in Defines.php
448 * @internal
450 $wgCanonicalNamespaceNames = NamespaceInfo::CANONICAL_NAMES;
452 /// @todo UGLY UGLY
453 if ( is_array( $wgExtraNamespaces ) ) {
454 $wgCanonicalNamespaceNames += $wgExtraNamespaces;
457 // Hard-deprecate setting $wgDummyLanguageCodes in LocalSettings.php
458 if ( count( $wgDummyLanguageCodes ) !== 0 ) {
459 wfDeprecated( '$wgDummyLanguageCodes', '1.29' );
461 // Merge in the legacy language codes, incorporating overrides from the config
462 $wgDummyLanguageCodes += [
463 // Internal language codes of the private-use area which get mapped to
464 // themselves.
465 'qqq' => 'qqq', // Used for message documentation
466 'qqx' => 'qqx', // Used for viewing message keys
467 ] + $wgExtraLanguageCodes + LanguageCode::getDeprecatedCodeMapping();
468 // Merge in (inverted) BCP 47 mappings
469 foreach ( LanguageCode::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
470 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
471 if ( !isset( $wgDummyLanguageCodes[$bcp47] ) ) {
472 $wgDummyLanguageCodes[$bcp47] = $wgDummyLanguageCodes[$code] ?? $code;
476 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
477 Wikimedia\suppressWarnings();
478 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
479 Wikimedia\restoreWarnings();
482 if ( $wgNewUserLog ) {
483 // Add new user log type
484 $wgLogTypes[] = 'newusers';
485 $wgLogNames['newusers'] = 'newuserlogpage';
486 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
487 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter::class;
488 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter::class;
489 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter::class;
490 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter::class;
491 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter::class;
494 if ( $wgPageCreationLog ) {
495 // Add page creation log type
496 $wgLogTypes[] = 'create';
497 $wgLogActionsHandlers['create/create'] = LogFormatter::class;
500 if ( $wgPageLanguageUseDB ) {
501 $wgLogTypes[] = 'pagelang';
502 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter::class;
505 if ( $wgCookieSecure === 'detect' ) {
506 $wgCookieSecure = $wgForceHTTPS || ( WebRequest::detectProtocol() === 'https' );
509 // Backwards compatibility with old password limits
510 if ( $wgMinimalPasswordLength !== false ) {
511 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
514 if ( $wgMaximalPasswordLength !== false ) {
515 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
518 if ( $wgPHPSessionHandling !== 'enable' &&
519 $wgPHPSessionHandling !== 'warn' &&
520 $wgPHPSessionHandling !== 'disable'
522 $wgPHPSessionHandling = 'warn';
524 if ( defined( 'MW_NO_SESSION' ) ) {
525 // If the entry point wants no session, force 'disable' here unless they
526 // specifically set it to the (undocumented) 'warn'.
527 // @phan-suppress-next-line PhanUndeclaredConstant
528 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
531 MWDebug::setup();
533 // Reset the global service locator, so any services that have already been created will be
534 // re-created while taking into account any custom settings and extensions.
535 MediaWikiServices::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
537 // Define a constant that indicates that the bootstrapping of the service locator
538 // is complete.
539 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
541 MWExceptionHandler::installHandler();
543 // T30798: $wgServer must be explicitly set
544 // @phan-suppress-next-line PhanSuspiciousValueComparisonInGlobalScope
545 if ( $wgServer === false ) {
546 throw new FatalError(
547 '$wgServer must be set in LocalSettings.php. ' .
548 'See <a href="https://www.mediawiki.org/wiki/Manual:$wgServer">' .
549 'https://www.mediawiki.org/wiki/Manual:$wgServer</a>.'
553 if ( $wgCanonicalServer === false ) {
554 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP );
557 // Set server name
558 $serverParts = wfParseUrl( $wgCanonicalServer );
559 if ( $wgServerName !== false ) {
560 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
561 . 'not customized. Overwriting $wgServerName.' );
563 $wgServerName = $serverParts['host'];
564 unset( $serverParts );
566 // Set defaults for configuration variables
567 // that are derived from the server name by default
568 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
569 if ( !$wgEmergencyContact ) {
570 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
572 if ( !$wgPasswordSender ) {
573 $wgPasswordSender = 'apache@' . $wgServerName;
575 if ( !$wgNoReplyAddress ) {
576 $wgNoReplyAddress = $wgPasswordSender;
579 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
580 $wgSecureLogin = false;
581 wfWarn( 'Secure login was enabled on a server that only supports '
582 . 'HTTP or HTTPS. Disabling secure login.' );
585 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
587 // Now that GlobalFunctions is loaded, set defaults that depend on it.
588 if ( $wgTmpDirectory === false ) {
589 $wgTmpDirectory = wfTempDir();
592 if ( $wgMainWANCache === false ) {
593 // Setup a WAN cache from $wgMainCacheType
594 $wgMainWANCache = 'mediawiki-main-default';
595 $wgWANObjectCaches[$wgMainWANCache] = [
596 'class' => WANObjectCache::class,
597 'cacheId' => $wgMainCacheType,
601 if ( $wgSharedDB && $wgSharedTables ) {
602 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
603 MediaWikiServices::getInstance()->getDBLoadBalancer()->setTableAliases(
604 array_fill_keys(
605 $wgSharedTables,
607 'dbname' => $wgSharedDB,
608 'schema' => $wgSharedSchema,
609 'prefix' => $wgSharedPrefix
615 // Raise the memory limit if it's too low
616 // Note, this makes use of wfDebug, and thus should not be before
617 // MWDebug::init() is called.
618 wfMemoryLimit( $wgMemoryLimit );
621 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
622 * that happens whenever you use a date function without the timezone being
623 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
625 if ( $wgLocaltimezone === null ) {
626 Wikimedia\suppressWarnings();
627 $wgLocaltimezone = date_default_timezone_get();
628 Wikimedia\restoreWarnings();
631 date_default_timezone_set( $wgLocaltimezone );
632 if ( $wgLocalTZoffset === null ) {
633 $wgLocalTZoffset = (int)date( 'Z' ) / 60;
635 // The part after the System| is ignored, but rest of MW fills it
636 // out as the local offset.
637 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
639 if ( !$wgDBerrorLogTZ ) {
640 $wgDBerrorLogTZ = $wgLocaltimezone;
643 // Initialize the request object in $wgRequest
644 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
645 // Set user IP/agent information for agent session consistency purposes
646 $cpPosInfo = LBFactory::getCPInfoFromCookieValue(
647 // The cookie has no prefix and is set by MediaWiki::preOutputCommit()
648 $wgRequest->getCookie( 'cpPosIndex', '' ),
649 // Mitigate broken client-side cookie expiration handling (T190082)
650 time() - ChronologyProtector::POSITION_COOKIE_TTL
652 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
653 'IPAddress' => $wgRequest->getIP(),
654 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
655 'ChronologyProtection' => $wgRequest->getHeader( 'MediaWiki-Chronology-Protection' ),
656 'ChronologyPositionIndex' => $wgRequest->getInt( 'cpPosIndex', $cpPosInfo['index'] ),
657 'ChronologyClientId' => $cpPosInfo['clientId']
658 ?? $wgRequest->getHeader( 'MediaWiki-Chronology-Client-Id' )
659 ] );
660 unset( $cpPosInfo );
661 // Make sure that object caching does not undermine the ChronologyProtector improvements
662 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
663 // The user is pinned to the primary DC, meaning that they made recent changes which should
664 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
665 // they use a blind TTL and could be stale if an object changes twice in a short time span.
666 MediaWikiServices::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
669 // Useful debug output
670 ( function () {
671 global $wgCommandLineMode, $wgRequest;
672 $logger = LoggerFactory::getInstance( 'wfDebug' );
673 if ( $wgCommandLineMode ) {
674 $self = $_SERVER['PHP_SELF'] ?? '';
675 $logger->debug( "\n\nStart command line script $self" );
676 } else {
677 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
678 $debug .= "IP: " . $wgRequest->getIP() . "\n";
679 $debug .= "HTTP HEADERS:\n";
680 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
681 $debug .= "$name: $value\n";
683 $debug .= "(end headers)";
684 $logger->debug( $debug );
686 } )();
688 // Most of the config is out, some might want to run hooks here.
689 Hooks::runner()->onSetupAfterCache();
692 * @var Language $wgContLang
693 * @deprecated since 1.32, use the ContentLanguage service directly
695 $wgContLang = MediaWikiServices::getInstance()->getContentLanguage();
697 // Now that variant lists may be available...
698 $wgRequest->interpolateTitle();
701 * @var MediaWiki\Session\SessionId|null The persistent session ID (if any) loaded at startup
703 $wgInitialSessionId = null;
704 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
705 // If session.auto_start is there, we can't touch session name
706 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
707 session_name( $wgSessionName ?: $wgCookiePrefix . '_session' );
710 // Create the SessionManager singleton and set up our session handler,
711 // unless we're specifically asked not to.
712 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
713 MediaWiki\Session\PHPSessionHandler::install(
714 MediaWiki\Session\SessionManager::singleton()
718 // Initialize the session
719 try {
720 $session = MediaWiki\Session\SessionManager::getGlobalSession();
721 } catch ( MediaWiki\Session\SessionOverflowException $ex ) {
722 // The exception is because the request had multiple possible
723 // sessions tied for top priority. Report this to the user.
724 $list = [];
725 foreach ( $ex->getSessionInfos() as $info ) {
726 $list[] = $info->getProvider()->describe( $wgContLang );
728 $list = $wgContLang->listToText( $list );
729 throw new HttpError( 400,
730 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
734 if ( $session->isPersistent() ) {
735 $wgInitialSessionId = $session->getSessionId();
738 $session->renew();
739 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
740 ( $session->isPersistent() || $session->shouldRememberUser() ) &&
741 session_id() !== $session->getId()
743 // Start the PHP-session for backwards compatibility
744 if ( session_id() !== '' ) {
745 wfDebugLog( 'session', 'PHP session {old_id} was already started, changing to {new_id}', 'all', [
746 'old_id' => session_id(),
747 'new_id' => $session->getId(),
748 ] );
749 session_write_close();
751 session_id( $session->getId() );
752 session_start();
755 unset( $session );
756 } else {
757 // Even if we didn't set up a global Session, still install our session
758 // handler unless specifically requested not to.
759 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
760 MediaWiki\Session\PHPSessionHandler::install(
761 MediaWiki\Session\SessionManager::singleton()
767 * @var User $wgUser
768 * @deprecated since 1.35, use an available context source when possible, or, as a backup,
769 * RequestContext::getMain()
771 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
774 * @var Language $wgLang
776 $wgLang = new StubUserLang;
779 * @var OutputPage $wgOut
781 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
784 * @var Parser $wgParser
785 * @deprecated since 1.32, use MediaWikiServices::getInstance()->getParser() instead
787 $wgParser = new DeprecatedGlobal( 'wgParser', function () {
788 return MediaWikiServices::getInstance()->getParser();
789 }, '1.32' );
792 * @var Title $wgTitle
794 $wgTitle = null;
796 // Extension setup functions
797 // Entries should be added to this variable during the inclusion
798 // of the extension file. This allows the extension to perform
799 // any necessary initialisation in the fully initialised environment
800 foreach ( $wgExtensionFunctions as $func ) {
801 call_user_func( $func );
804 // If the session user has a 0 id but a valid name, that means we need to
805 // autocreate it.
806 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
807 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
808 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
809 $res = MediaWikiServices::getInstance()->getAuthManager()->autoCreateUser(
810 $sessionUser,
811 MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
812 true
814 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Autocreation attempt', [
815 'event' => 'autocreate',
816 'status' => $res,
817 ] );
818 unset( $res );
820 unset( $sessionUser );
823 if ( !$wgCommandLineMode ) {
824 Pingback::schedulePingback();
827 $wgFullyInitialised = true;