3 * Include most things that are needed to make MediaWiki work.
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.
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.
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.
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
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\Rdbms\LBFactory
;
28 use Wikimedia\Rdbms\ChronologyProtector
;
31 * This file is not a valid entry point, perform no further processing unless
32 * MEDIAWIKI is defined
34 if ( !defined( 'MEDIAWIKI' ) ) {
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";
44 unset( $wgScopeTest );
47 * Pre-config setup: Before loading LocalSettings.php
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.' );
55 // Start the autoloader, so that extensions can derive classes from core files
56 require_once "$IP/includes/AutoLoader.php";
58 // Load global constants
59 require_once "$IP/includes/Defines.php";
61 // Load default settings
62 require_once "$IP/includes/DefaultSettings.php";
64 // Load global functions
65 require_once "$IP/includes/GlobalFunctions.php";
67 // Load composer's autoloader if present
68 if ( is_readable( "$IP/vendor/autoload.php" ) ) {
69 require_once "$IP/vendor/autoload.php";
70 } elseif ( file_exists( "$IP/vendor/autoload.php" ) ) {
71 die( "$IP/vendor/autoload.php exists but is not readable" );
74 // Assert that composer dependencies were successfully loaded
75 // Purposely no leading \ due to it breaking HHVM RepoAuthorative mode
76 // PHP works fine with both versions
77 // See https://github.com/facebook/hhvm/issues/5833
78 if ( !interface_exists( 'Psr\Log\LoggerInterface' ) ) {
80 'MediaWiki requires the <a href="https://github.com/php-fig/log">PSR-3 logging ' .
81 "library</a> to be present. This library is not embedded directly in MediaWiki's " .
82 "git repository and must be installed separately by the end user.\n\n" .
83 'Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git' .
84 '#Fetch_external_libraries">mediawiki.org</a> for help on installing ' .
85 'the required components.'
88 trigger_error( $message, E_USER_ERROR
);
93 * Changes to the PHP environment that don't vary on configuration.
96 // Install a header callback
97 MediaWiki\HeaderCallback
::register();
99 // Set the encoding used by reading HTTP input, writing HTTP output.
100 // This is also the default for mbstring functions.
101 mb_internal_encoding( 'UTF-8' );
104 * Load LocalSettings.php
107 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
108 call_user_func( MW_CONFIG_CALLBACK
);
110 if ( !defined( 'MW_CONFIG_FILE' ) ) {
111 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
113 require_once MW_CONFIG_FILE
;
117 * Customization point after all loading (constants, functions, classes,
118 * DefaultSettings, LocalSettings). Specifically, this is before usage of
119 * settings, before instantiation of Profiler (and other singletons), and
120 * before any setup functions or hooks run.
123 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
124 call_user_func( MW_SETUP_CALLBACK
);
131 $fname = 'Setup.php';
132 $ps_setup = Profiler
::instance()->scopedProfileIn( $fname );
134 // Load queued extensions
135 ExtensionRegistry
::getInstance()->loadFromQueue();
136 // Don't let any other extensions load
137 ExtensionRegistry
::getInstance()->finish();
139 // Set the configured locale on all requests for consisteny
140 putenv( "LC_ALL=$wgShellLocale" );
141 setlocale( LC_ALL
, $wgShellLocale );
143 // Set various default paths sensibly...
144 $ps_default = Profiler
::instance()->scopedProfileIn( $fname . '-defaults' );
146 if ( $wgScript === false ) {
147 $wgScript = "$wgScriptPath/index.php";
149 if ( $wgLoadScript === false ) {
150 $wgLoadScript = "$wgScriptPath/load.php";
152 if ( $wgRestPath === false ) {
153 $wgRestPath = "$wgScriptPath/rest.php";
156 if ( $wgArticlePath === false ) {
157 if ( $wgUsePathInfo ) {
158 $wgArticlePath = "$wgScript/$1";
160 $wgArticlePath = "$wgScript?title=$1";
164 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
165 // 'view' is assumed the default action path everywhere in the code
166 // but is rarely filled in $wgActionPaths
167 $wgActionPaths['view'] = $wgArticlePath;
170 if ( $wgResourceBasePath === null ) {
171 $wgResourceBasePath = $wgScriptPath;
173 if ( $wgStylePath === false ) {
174 $wgStylePath = "$wgResourceBasePath/skins";
176 if ( $wgLocalStylePath === false ) {
177 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
178 $wgLocalStylePath = "$wgScriptPath/skins";
180 if ( $wgExtensionAssetsPath === false ) {
181 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
184 if ( $wgLogo === false ) {
185 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
188 if ( $wgUploadPath === false ) {
189 $wgUploadPath = "$wgScriptPath/images";
191 if ( $wgUploadDirectory === false ) {
192 $wgUploadDirectory = "$IP/images";
194 if ( $wgReadOnlyFile === false ) {
195 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
197 if ( $wgFileCacheDirectory === false ) {
198 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
200 if ( $wgDeletedDirectory === false ) {
201 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
204 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
205 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
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/",
217 if ( isset( $wgFooterIcons['copyright']['copyright'] )
218 && $wgFooterIcons['copyright']['copyright'] === []
220 if ( $wgRightsIcon ||
$wgRightsText ) {
221 $wgFooterIcons['copyright']['copyright'] = [
222 'url' => $wgRightsUrl,
223 'src' => $wgRightsIcon,
224 'alt' => $wgRightsText,
229 if ( isset( $wgFooterIcons['poweredby'] )
230 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
231 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
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";
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.
244 * Note that this is the definition of editinterface and it can be granted to
245 * all users if desired.
247 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
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.
254 $wgNamespaceAliases['Image'] = NS_FILE
;
255 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
258 * Initialise $wgLockManagers to include basic FS version
260 $wgLockManagers[] = [
261 'name' => 'fsLockManager',
262 'class' => FSLockManager
::class,
263 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
265 $wgLockManagers[] = [
266 'name' => 'nullLockManager',
267 'class' => NullLockManager
::class,
271 * Default parameters for the "<gallery>" tag.
272 * @see DefaultSettings.php for description of the fields.
274 $wgGalleryOptions +
= [
277 'imageHeight' => 120,
278 'captionLength' => true,
280 'showDimensions' => true,
281 'mode' => 'traditional',
285 * Shortcuts for $wgLocalFileRepo
287 if ( !$wgLocalFileRepo ) {
289 'class' => LocalRepo
::class,
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
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';
309 * Shortcuts for $wgForeignFileRepos
311 if ( $wgUseSharedUploads ) {
312 if ( $wgSharedUploadDBname ) {
313 $wgForeignFileRepos[] = [
314 'class' => ForeignDBRepo
::class,
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,
333 $wgForeignFileRepos[] = [
334 'class' => FileRepo
::class,
336 'directory' => $wgSharedUploadDirectory,
337 'url' => $wgSharedUploadPath,
338 'hashLevels' => $wgHashedSharedUploadDirectory ?
2 : 0,
339 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
340 'transformVia404' => !$wgGenerateThumbnailOnParse,
341 'descBaseUrl' => $wgRepositoryBaseUrl,
342 'fetchDescription' => $wgFetchCommonsDescriptions,
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',
354 'transformVia404' => true,
355 'fetchDescription' => true,
356 'descriptionCacheExpiry' => 43200,
357 'apiThumbCacheExpiry' => 0,
360 foreach ( $wgForeignFileRepos as &$repo ) {
361 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo
::class ) {
362 $repo['directory'] = $wgUploadDirectory; // b/c
364 if ( !isset( $repo['backend'] ) ) {
365 $repo['backend'] = $repo['name'] . '-backend';
368 unset( $repo ); // no global pollution; destroy reference
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 )
376 $wgDefaultUserOptions['watchlistdays'] = min(
377 $wgDefaultUserOptions['watchlistdays'],
378 ceil( $rcMaxAgeDays )
380 unset( $rcMaxAgeDays );
383 // Hard deprecated in 1.34.
384 wfDeprecated( '$wgSkipSkin – use $wgSkipSkins instead', '1.23' );
385 $wgSkipSkins[] = $wgSkipSkin;
388 $wgSkipSkins[] = 'fallback';
389 $wgSkipSkins[] = 'apioutput';
391 if ( $wgLocalInterwiki ) {
392 // Hard deprecated in 1.34.
393 wfDeprecated( '$wgLocalInterwiki – use $wgLocalInterwikis instead', '1.23' );
394 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
397 // Set default shared prefix
398 if ( $wgSharedPrefix === false ) {
399 $wgSharedPrefix = $wgDBprefix;
402 // Set default shared schema
403 if ( $wgSharedSchema === false ) {
404 $wgSharedSchema = $wgDBmwschema;
407 if ( !$wgCookiePrefix ) {
408 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
409 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
410 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
411 $wgCookiePrefix = $wgSharedDB;
412 } elseif ( $wgDBprefix ) {
413 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
415 $wgCookiePrefix = $wgDBname;
418 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
420 if ( $wgEnableEmail ) {
421 $wgUseEnotif = $wgEnotifUserTalk ||
$wgEnotifWatchlist;
423 // Disable all other email settings automatically if $wgEnableEmail
424 // is set to false. - T65678
425 $wgAllowHTMLEmail = false;
426 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
427 $wgEnableUserEmail = false;
428 $wgEnotifFromEditor = false;
429 $wgEnotifImpersonal = false;
430 $wgEnotifMaxRecips = 0;
431 $wgEnotifMinorEdits = false;
432 $wgEnotifRevealEditorAddress = false;
433 $wgEnotifUseRealName = false;
434 $wgEnotifUserTalk = false;
435 $wgEnotifWatchlist = false;
436 unset( $wgGroupPermissions['user']['sendemail'] );
437 $wgUseEnotif = false;
438 $wgUserEmailUseReplyTo = false;
439 $wgUsersNotifiedOnAllChanges = [];
442 if ( $wgMetaNamespace === false ) {
443 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
446 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
447 if ( $wgResourceLoaderMaxQueryLength === false ) {
448 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
449 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
450 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
452 $wgResourceLoaderMaxQueryLength = 2000;
454 unset( $suhosinMaxValueLength );
457 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
459 $wgMinUploadChunkSize = min(
460 $wgMinUploadChunkSize,
461 UploadBase
::getMaxUploadSize( 'file' ),
462 UploadBase
::getMaxPhpUploadSize(),
463 ( wfShorthandToInteger(
464 ini_get( 'post_max_size' ) ?
: ini_get( 'hhvm.server.max_post_size' ),
466 ) ?
: PHP_INT_MAX
) - 1024 // Leave some room for other POST parameters
470 * Definitions of the NS_ constants are in Defines.php
473 $wgCanonicalNamespaceNames = NamespaceInfo
::$canonicalNames;
476 if ( is_array( $wgExtraNamespaces ) ) {
477 $wgCanonicalNamespaceNames +
= $wgExtraNamespaces;
480 // Hard-deprecate setting $wgDummyLanguageCodes in LocalSettings.php
481 if ( count( $wgDummyLanguageCodes ) !== 0 ) {
482 wfDeprecated( '$wgDummyLanguageCodes', '1.29' );
484 // Merge in the legacy language codes, incorporating overrides from the config
485 $wgDummyLanguageCodes +
= [
486 // Internal language codes of the private-use area which get mapped to
488 'qqq' => 'qqq', // Used for message documentation
489 'qqx' => 'qqx', // Used for viewing message keys
490 ] +
$wgExtraLanguageCodes + LanguageCode
::getDeprecatedCodeMapping();
491 // Merge in (inverted) BCP 47 mappings
492 foreach ( LanguageCode
::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
493 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
494 if ( !isset( $wgDummyLanguageCodes[$bcp47] ) ) {
495 $wgDummyLanguageCodes[$bcp47] = $wgDummyLanguageCodes[$code] ??
$code;
499 // These are now the same, always
500 // To determine the user language, use $wgLang->getCode()
501 $wgContLanguageCode = $wgLanguageCode;
503 // Temporary backwards-compatibility reading of old Squid-named CDN settings as of MediaWiki 1.34,
504 // to support sysadmins who fail to update their settings immediately:
506 if ( isset( $wgUseSquid ) ) {
507 // If the sysadmin is still setting a value of $wgUseSquid to true but $wgUseCdn is the default of
508 // false, to be safe, assume they do want this still, so enable it.
509 if ( !$wgUseCdn && $wgUseSquid ) {
510 $wgUseCdn = $wgUseSquid;
511 wfDeprecated( '$wgUseSquid enabled but $wgUseCdn disabled; enabling CDN functions', '1.34' );
514 // Backwards-compatibility for extensions that read this value.
515 $wgUseSquid = $wgUseCdn;
518 if ( isset( $wgSquidServers ) ) {
519 // If the sysadmin is still setting a value of $wgSquidServers but $wgCdnServers is the default of
520 // empty, to be safe, assume they do want these servers to be still used, so use them.
521 if ( !empty( $wgSquidServers ) && empty( $wgCdnServers ) ) {
522 $wgCdnServers = $wgSquidServers;
523 wfDeprecated( '$wgSquidServers set, $wgCdnServers empty; using them', '1.34' );
526 // Backwards-compatibility for extensions that read this value.
527 $wgSquidServers = $wgCdnServers;
530 if ( isset( $wgSquidServersNoPurge ) ) {
531 // If the sysadmin is still setting values in $wgSquidServersNoPurge but $wgCdnServersNoPurge is
532 // the default of empty, to be safe, assume they do want these servers to be still used, so use
534 if ( !empty( $wgSquidServersNoPurge ) && empty( $wgCdnServersNoPurge ) ) {
535 $wgCdnServersNoPurge = $wgSquidServersNoPurge;
536 wfDeprecated( '$wgSquidServersNoPurge set, $wgCdnServersNoPurge empty; using them', '1.34' );
539 // Backwards-compatibility for extensions that read this value.
540 $wgSquidServersNoPurge = $wgCdnServersNoPurge;
543 if ( isset( $wgSquidMaxage ) ) {
544 // If the sysadmin is still setting a value of $wgSquidMaxage and it's higher than $wgCdnMaxAge,
545 // to be safe, assume they want the higher (lower performance requirement) value, so use that.
546 if ( $wgCdnMaxAge < $wgSquidMaxage ) {
547 $wgCdnMaxAge = $wgSquidMaxage;
548 wfDeprecated( '$wgSquidMaxage set higher than $wgCdnMaxAge; using the higher value', '1.34' );
551 // Backwards-compatibility for extensions that read this value.
552 $wgSquidMaxage = $wgCdnMaxAge;
555 // Easy to forget to falsify $wgDebugToolbar for static caches.
556 // If file cache or CDN cache is on, just disable this (DWIMD).
557 if ( $wgUseFileCache ||
$wgUseCdn ) {
558 $wgDebugToolbar = false;
561 // Blacklisted file extensions shouldn't appear on the "allowed" list
562 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
564 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
565 Wikimedia\
suppressWarnings();
566 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
567 Wikimedia\restoreWarnings
();
570 if ( $wgNewUserLog ) {
571 // Add new user log type
572 $wgLogTypes[] = 'newusers';
573 $wgLogNames['newusers'] = 'newuserlogpage';
574 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
575 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter
::class;
576 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter
::class;
577 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter
::class;
578 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter
::class;
579 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter
::class;
582 if ( $wgPageCreationLog ) {
583 // Add page creation log type
584 $wgLogTypes[] = 'create';
585 $wgLogActionsHandlers['create/create'] = LogFormatter
::class;
588 if ( $wgPageLanguageUseDB ) {
589 $wgLogTypes[] = 'pagelang';
590 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter
::class;
593 if ( $wgCookieSecure === 'detect' ) {
594 $wgCookieSecure = ( WebRequest
::detectProtocol() === 'https' );
597 if ( $wgProfileOnly ) {
598 // Hard deprecated in 1.34.
600 '$wgProfileOnly set the log file in $wgDebugLogGroups[\'profileoutput\'] instead',
603 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
604 $wgDebugLogFile = '';
607 // Backwards compatibility with old password limits
608 if ( $wgMinimalPasswordLength !== false ) {
609 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
612 if ( $wgMaximalPasswordLength !== false ) {
613 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
616 if ( $wgPHPSessionHandling !== 'enable' &&
617 $wgPHPSessionHandling !== 'warn' &&
618 $wgPHPSessionHandling !== 'disable'
620 $wgPHPSessionHandling = 'warn';
622 if ( defined( 'MW_NO_SESSION' ) ) {
623 // If the entry point wants no session, force 'disable' here unless they
624 // specifically set it to the (undocumented) 'warn'.
625 $wgPHPSessionHandling = MW_NO_SESSION
=== 'warn' ?
'warn' : 'disable';
628 Profiler
::instance()->scopedProfileOut( $ps_default );
630 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
631 // all the memory from logging SQL queries on maintenance scripts
632 global $wgCommandLineMode;
633 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
637 // Reset the global service locator, so any services that have already been created will be
638 // re-created while taking into account any custom settings and extensions.
639 MediaWikiServices
::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
641 // Define a constant that indicates that the bootstrapping of the service locator
643 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
645 MWExceptionHandler
::installHandler();
647 // T48998: Bail out early if $wgArticlePath is non-absolute
648 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
649 if ( $
$varName && !preg_match( '/^(https?:\/\/|\/)/', $
$varName ) ) {
650 throw new FatalError(
651 "If you use a relative URL for \$$varName, it must start " .
652 'with a slash (<code>/</code>).<br><br>See ' .
653 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
654 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
659 $ps_default2 = Profiler
::instance()->scopedProfileIn( $fname . '-defaults2' );
661 if ( $wgCanonicalServer === false ) {
662 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP
);
666 $serverParts = wfParseUrl( $wgCanonicalServer );
667 if ( $wgServerName !== false ) {
668 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
669 . 'not customized. Overwriting $wgServerName.' );
671 $wgServerName = $serverParts['host'];
672 unset( $serverParts );
674 // Set defaults for configuration variables
675 // that are derived from the server name by default
676 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
677 if ( !$wgEmergencyContact ) {
678 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
680 if ( !$wgPasswordSender ) {
681 $wgPasswordSender = 'apache@' . $wgServerName;
683 if ( !$wgNoReplyAddress ) {
684 $wgNoReplyAddress = $wgPasswordSender;
687 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
688 $wgSecureLogin = false;
689 wfWarn( 'Secure login was enabled on a server that only supports '
690 . 'HTTP or HTTPS. Disabling secure login.' );
693 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
695 // Now that GlobalFunctions is loaded, set defaults that depend on it.
696 if ( $wgTmpDirectory === false ) {
697 $wgTmpDirectory = wfTempDir();
700 // We don't use counters anymore. Left here for extensions still
701 // expecting this to exist. Should be removed sometime 1.26 or later.
702 if ( !isset( $wgDisableCounters ) ) {
703 $wgDisableCounters = true;
706 if ( $wgMainWANCache === false ) {
707 // Setup a WAN cache from $wgMainCacheType with no relayer.
708 // Sites using multiple datacenters can configure a relayer.
709 $wgMainWANCache = 'mediawiki-main-default';
710 $wgWANObjectCaches[$wgMainWANCache] = [
711 'class' => WANObjectCache
::class,
712 'cacheId' => $wgMainCacheType
716 if ( $wgSharedDB && $wgSharedTables ) {
717 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
718 MediaWikiServices
::getInstance()->getDBLoadBalancer()->setTableAliases(
722 'dbname' => $wgSharedDB,
723 'schema' => $wgSharedSchema,
724 'prefix' => $wgSharedPrefix
730 Profiler
::instance()->scopedProfileOut( $ps_default2 );
732 $ps_misc = Profiler
::instance()->scopedProfileIn( $fname . '-misc' );
734 // Raise the memory limit if it's too low
735 // Note, this makes use of wfDebug, and thus should not be before
736 // MWDebug::init() is called.
737 wfMemoryLimit( $wgMemoryLimit );
740 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
741 * that happens whenever you use a date function without the timezone being
742 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
744 if ( is_null( $wgLocaltimezone ) ) {
745 Wikimedia\
suppressWarnings();
746 $wgLocaltimezone = date_default_timezone_get();
747 Wikimedia\restoreWarnings
();
750 date_default_timezone_set( $wgLocaltimezone );
751 if ( is_null( $wgLocalTZoffset ) ) {
752 $wgLocalTZoffset = date( 'Z' ) / 60;
754 // The part after the System| is ignored, but rest of MW fills it
755 // out as the local offset.
756 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
758 if ( !$wgDBerrorLogTZ ) {
759 $wgDBerrorLogTZ = $wgLocaltimezone;
762 // Initialize the request object in $wgRequest
763 $wgRequest = RequestContext
::getMain()->getRequest(); // BackCompat
764 // Set user IP/agent information for agent session consistency purposes
765 $cpPosInfo = LBFactory
::getCPInfoFromCookieValue(
766 // The cookie has no prefix and is set by MediaWiki::preOutputCommit()
767 $wgRequest->getCookie( 'cpPosIndex', '' ),
768 // Mitigate broken client-side cookie expiration handling (T190082)
769 time() - ChronologyProtector
::POSITION_COOKIE_TTL
771 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
772 'IPAddress' => $wgRequest->getIP(),
773 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
774 'ChronologyProtection' => $wgRequest->getHeader( 'MediaWiki-Chronology-Protection' ),
775 'ChronologyPositionIndex' => $wgRequest->getInt( 'cpPosIndex', $cpPosInfo['index'] ),
776 'ChronologyClientId' => $cpPosInfo['clientId']
777 ??
$wgRequest->getHeader( 'MediaWiki-Chronology-Client-Id' )
780 // Make sure that object caching does not undermine the ChronologyProtector improvements
781 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
782 // The user is pinned to the primary DC, meaning that they made recent changes which should
783 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
784 // they use a blind TTL and could be stale if an object changes twice in a short time span.
785 MediaWikiServices
::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
788 // Useful debug output
789 if ( $wgCommandLineMode ) {
790 if ( isset( $self ) ) {
791 wfDebug( "\n\nStart command line script $self\n" );
794 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
795 $debug .= "HTTP HEADERS:\n";
796 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
797 $debug .= "$name: $value\n";
802 $wgMemc = ObjectCache
::getLocalClusterInstance();
803 $messageMemc = wfGetMessageCacheStorage();
805 wfDebugLog( 'caches',
806 'cluster: ' . get_class( $wgMemc ) .
807 ', WAN: ' . ( $wgMainWANCache === CACHE_NONE ?
'CACHE_NONE' : $wgMainWANCache ) .
808 ', stash: ' . $wgMainStash .
809 ', message: ' . get_class( $messageMemc ) .
810 ', session: ' . get_class( ObjectCache
::getInstance( $wgSessionCacheType ) )
813 Profiler
::instance()->scopedProfileOut( $ps_misc );
815 // Most of the config is out, some might want to run hooks here.
816 Hooks
::run( 'SetupAfterCache' );
818 $ps_globals = Profiler
::instance()->scopedProfileIn( $fname . '-globals' );
821 * @var Language $wgContLang
822 * @deprecated since 1.32, use the ContentLanguage service directly
824 $wgContLang = MediaWikiServices
::getInstance()->getContentLanguage();
826 // Now that variant lists may be available...
827 $wgRequest->interpolateTitle();
830 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
831 * session ID (if any) loaded at startup
833 $wgInitialSessionId = null;
834 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
835 // If session.auto_start is there, we can't touch session name
836 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
837 session_name( $wgSessionName ?
: $wgCookiePrefix . '_session' );
840 // Create the SessionManager singleton and set up our session handler,
841 // unless we're specifically asked not to.
842 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
843 MediaWiki\Session\PHPSessionHandler
::install(
844 MediaWiki\Session\SessionManager
::singleton()
848 // Initialize the session
850 $session = MediaWiki\Session\SessionManager
::getGlobalSession();
851 } catch ( OverflowException
$ex ) {
852 if ( isset( $ex->sessionInfos
) && count( $ex->sessionInfos
) >= 2 ) {
853 // The exception is because the request had multiple possible
854 // sessions tied for top priority. Report this to the user.
856 foreach ( $ex->sessionInfos
as $info ) {
857 $list[] = $info->getProvider()->describe( $wgContLang );
859 $list = $wgContLang->listToText( $list );
860 throw new HttpError( 400,
861 Message
::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
865 // Not the one we want, rethrow
869 if ( $session->isPersistent() ) {
870 $wgInitialSessionId = $session->getSessionId();
874 if ( MediaWiki\Session\PHPSessionHandler
::isEnabled() &&
875 ( $session->isPersistent() ||
$session->shouldRememberUser() ) &&
876 session_id() !== $session->getId()
878 // Start the PHP-session for backwards compatibility
879 if ( session_id() !== '' ) {
880 wfDebugLog( 'session', 'PHP session {old_id} was already started, changing to {new_id}', 'all', [
881 'old_id' => session_id(),
882 'new_id' => $session->getId(),
884 session_write_close();
886 session_id( $session->getId() );
892 // Even if we didn't set up a global Session, still install our session
893 // handler unless specifically requested not to.
894 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
895 MediaWiki\Session\PHPSessionHandler
::install(
896 MediaWiki\Session\SessionManager
::singleton()
904 $wgUser = RequestContext
::getMain()->getUser(); // BackCompat
907 * @var Language $wgLang
909 $wgLang = new StubUserLang
;
912 * @var OutputPage $wgOut
914 $wgOut = RequestContext
::getMain()->getOutput(); // BackCompat
917 * @var Parser $wgParser
918 * @deprecated since 1.32, use MediaWikiServices::getInstance()->getParser() instead
920 $wgParser = new StubObject( 'wgParser', function () {
921 return MediaWikiServices
::getInstance()->getParser();
925 * @var Title $wgTitle
929 Profiler
::instance()->scopedProfileOut( $ps_globals );
930 $ps_extensions = Profiler
::instance()->scopedProfileIn( $fname . '-extensions' );
932 // Extension setup functions
933 // Entries should be added to this variable during the inclusion
934 // of the extension file. This allows the extension to perform
935 // any necessary initialisation in the fully initialised environment
936 foreach ( $wgExtensionFunctions as $func ) {
937 call_user_func( $func );
940 // If the session user has a 0 id but a valid name, that means we need to
942 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
943 $sessionUser = MediaWiki\Session\SessionManager
::getGlobalSession()->getUser();
944 if ( $sessionUser->getId() === 0 && User
::isValidUserName( $sessionUser->getName() ) ) {
945 $res = MediaWiki\Auth\AuthManager
::singleton()->autoCreateUser(
947 MediaWiki\Auth\AuthManager
::AUTOCREATE_SOURCE_SESSION
,
950 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Autocreation attempt', [
951 'event' => 'autocreate',
956 unset( $sessionUser );
959 if ( !$wgCommandLineMode ) {
960 Pingback
::schedulePingback();
963 $wgFullyInitialised = true;
965 Profiler
::instance()->scopedProfileOut( $ps_extensions );
966 Profiler
::instance()->scopedProfileOut( $ps_setup );