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 PHP for reading HTTP input, and writing 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 // Load queued extensions
132 ExtensionRegistry
::getInstance()->loadFromQueue();
133 // Don't let any other extensions load
134 ExtensionRegistry
::getInstance()->finish();
136 // Set the configured locale on all requests for consisteny
137 putenv( "LC_ALL=$wgShellLocale" );
138 setlocale( LC_ALL
, $wgShellLocale );
140 // Set various default paths sensibly...
141 if ( $wgScript === false ) {
142 $wgScript = "$wgScriptPath/index.php";
144 if ( $wgLoadScript === false ) {
145 $wgLoadScript = "$wgScriptPath/load.php";
147 if ( $wgRestPath === false ) {
148 $wgRestPath = "$wgScriptPath/rest.php";
151 if ( $wgArticlePath === false ) {
152 if ( $wgUsePathInfo ) {
153 $wgArticlePath = "$wgScript/$1";
155 $wgArticlePath = "$wgScript?title=$1";
159 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
160 // 'view' is assumed the default action path everywhere in the code
161 // but is rarely filled in $wgActionPaths
162 $wgActionPaths['view'] = $wgArticlePath;
165 if ( $wgResourceBasePath === null ) {
166 $wgResourceBasePath = $wgScriptPath;
168 if ( $wgStylePath === false ) {
169 $wgStylePath = "$wgResourceBasePath/skins";
171 if ( $wgLocalStylePath === false ) {
172 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
173 $wgLocalStylePath = "$wgScriptPath/skins";
175 if ( $wgExtensionAssetsPath === false ) {
176 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
179 if ( $wgLogo === false ) {
180 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
183 if ( $wgUploadPath === false ) {
184 $wgUploadPath = "$wgScriptPath/images";
186 if ( $wgUploadDirectory === false ) {
187 $wgUploadDirectory = "$IP/images";
189 if ( $wgReadOnlyFile === false ) {
190 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
192 if ( $wgFileCacheDirectory === false ) {
193 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
195 if ( $wgDeletedDirectory === false ) {
196 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
199 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
200 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
203 // Fix path to icon images after they were moved in 1.24
204 if ( $wgRightsIcon ) {
205 $wgRightsIcon = str_replace(
206 "{$wgStylePath}/common/images/",
207 "{$wgResourceBasePath}/resources/assets/licenses/",
212 if ( isset( $wgFooterIcons['copyright']['copyright'] )
213 && $wgFooterIcons['copyright']['copyright'] === []
215 if ( $wgRightsIcon ||
$wgRightsText ) {
216 $wgFooterIcons['copyright']['copyright'] = [
217 'url' => $wgRightsUrl,
218 'src' => $wgRightsIcon,
219 'alt' => $wgRightsText,
224 if ( isset( $wgFooterIcons['poweredby'] )
225 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
226 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
228 $wgFooterIcons['poweredby']['mediawiki']['src'] =
229 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
230 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
231 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
232 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
236 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
237 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
239 * Note that this is the definition of editinterface and it can be granted to
240 * all users if desired.
242 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
245 * The canonical names of namespaces 6 and 7 are, as of v1.14, "File"
246 * and "File_talk". The old names "Image" and "Image_talk" are
247 * retained as aliases for backwards compatibility.
249 $wgNamespaceAliases['Image'] = NS_FILE
;
250 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
253 * Initialise $wgLockManagers to include basic FS version
255 $wgLockManagers[] = [
256 'name' => 'fsLockManager',
257 'class' => FSLockManager
::class,
258 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
260 $wgLockManagers[] = [
261 'name' => 'nullLockManager',
262 'class' => NullLockManager
::class,
266 * Default parameters for the "<gallery>" tag.
267 * @see DefaultSettings.php for description of the fields.
269 $wgGalleryOptions +
= [
272 'imageHeight' => 120,
273 'captionLength' => true,
275 'showDimensions' => true,
276 'mode' => 'traditional',
280 * Shortcuts for $wgLocalFileRepo
282 if ( !$wgLocalFileRepo ) {
284 'class' => LocalRepo
::class,
286 'directory' => $wgUploadDirectory,
287 'scriptDirUrl' => $wgScriptPath,
288 'url' => $wgUploadBaseUrl ?
$wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
289 'hashLevels' => $wgHashedUploadDirectory ?
2 : 0,
290 'thumbScriptUrl' => $wgThumbnailScriptPath,
291 'transformVia404' => !$wgGenerateThumbnailOnParse,
292 'deletedDir' => $wgDeletedDirectory,
293 'deletedHashLevels' => $wgHashedUploadDirectory ?
3 : 0
297 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
298 // Create a default FileBackend name.
299 // FileBackendGroup will register a default, if absent from $wgFileBackends.
300 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
304 * Shortcuts for $wgForeignFileRepos
306 if ( $wgUseSharedUploads ) {
307 if ( $wgSharedUploadDBname ) {
308 $wgForeignFileRepos[] = [
309 'class' => ForeignDBRepo
::class,
311 'directory' => $wgSharedUploadDirectory,
312 'url' => $wgSharedUploadPath,
313 'hashLevels' => $wgHashedSharedUploadDirectory ?
2 : 0,
314 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
315 'transformVia404' => !$wgGenerateThumbnailOnParse,
316 'dbType' => $wgDBtype,
317 'dbServer' => $wgDBserver,
318 'dbUser' => $wgDBuser,
319 'dbPassword' => $wgDBpassword,
320 'dbName' => $wgSharedUploadDBname,
321 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG
: 0 ) | DBO_DEFAULT
,
322 'tablePrefix' => $wgSharedUploadDBprefix,
323 'hasSharedCache' => $wgCacheSharedUploads,
324 'descBaseUrl' => $wgRepositoryBaseUrl,
325 'fetchDescription' => $wgFetchCommonsDescriptions,
328 $wgForeignFileRepos[] = [
329 'class' => FileRepo
::class,
331 'directory' => $wgSharedUploadDirectory,
332 'url' => $wgSharedUploadPath,
333 'hashLevels' => $wgHashedSharedUploadDirectory ?
2 : 0,
334 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
335 'transformVia404' => !$wgGenerateThumbnailOnParse,
336 'descBaseUrl' => $wgRepositoryBaseUrl,
337 'fetchDescription' => $wgFetchCommonsDescriptions,
341 if ( $wgUseInstantCommons ) {
342 $wgForeignFileRepos[] = [
343 'class' => ForeignAPIRepo
::class,
344 'name' => 'wikimediacommons',
345 'apibase' => 'https://commons.wikimedia.org/w/api.php',
346 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
347 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
349 'transformVia404' => true,
350 'fetchDescription' => true,
351 'descriptionCacheExpiry' => 43200,
352 'apiThumbCacheExpiry' => 0,
355 foreach ( $wgForeignFileRepos as &$repo ) {
356 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo
::class ) {
357 $repo['directory'] = $wgUploadDirectory; // b/c
359 if ( !isset( $repo['backend'] ) ) {
360 $repo['backend'] = $repo['name'] . '-backend';
363 unset( $repo ); // no global pollution; destroy reference
365 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
366 if ( $wgRCFilterByAge ) {
367 // Trim down $wgRCLinkDays so that it only lists links which are valid
368 // as determined by $wgRCMaxAge.
369 // Note that we allow 1 link higher than the max for things like 56 days but a 60 day link.
370 sort( $wgRCLinkDays );
372 foreach ( $wgRCLinkDays as $i => $days ) {
373 if ( $days >= $rcMaxAgeDays ) {
374 array_splice( $wgRCLinkDays, $i +
1 );
379 // Ensure that default user options are not invalid, since that breaks Special:Preferences
380 $wgDefaultUserOptions['rcdays'] = min(
381 $wgDefaultUserOptions['rcdays'],
382 ceil( $rcMaxAgeDays )
384 $wgDefaultUserOptions['watchlistdays'] = min(
385 $wgDefaultUserOptions['watchlistdays'],
386 ceil( $rcMaxAgeDays )
388 unset( $rcMaxAgeDays );
391 // Hard deprecated in 1.34.
392 wfDeprecated( '$wgSkipSkin – use $wgSkipSkins instead', '1.23' );
393 $wgSkipSkins[] = $wgSkipSkin;
396 $wgSkipSkins[] = 'fallback';
397 $wgSkipSkins[] = 'apioutput';
399 if ( $wgLocalInterwiki ) {
400 // Hard deprecated in 1.34.
401 wfDeprecated( '$wgLocalInterwiki – use $wgLocalInterwikis instead', '1.23' );
402 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
405 // Set default shared prefix
406 if ( $wgSharedPrefix === false ) {
407 $wgSharedPrefix = $wgDBprefix;
410 // Set default shared schema
411 if ( $wgSharedSchema === false ) {
412 $wgSharedSchema = $wgDBmwschema;
415 if ( !$wgCookiePrefix ) {
416 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
417 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
418 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
419 $wgCookiePrefix = $wgSharedDB;
420 } elseif ( $wgDBprefix ) {
421 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
423 $wgCookiePrefix = $wgDBname;
426 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
428 if ( $wgEnableEmail ) {
429 $wgUseEnotif = $wgEnotifUserTalk ||
$wgEnotifWatchlist;
431 // Disable all other email settings automatically if $wgEnableEmail
432 // is set to false. - T65678
433 $wgAllowHTMLEmail = false;
434 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
435 $wgEnableUserEmail = false;
436 $wgEnotifFromEditor = false;
437 $wgEnotifImpersonal = false;
438 $wgEnotifMaxRecips = 0;
439 $wgEnotifMinorEdits = false;
440 $wgEnotifRevealEditorAddress = false;
441 $wgEnotifUseRealName = false;
442 $wgEnotifUserTalk = false;
443 $wgEnotifWatchlist = false;
444 unset( $wgGroupPermissions['user']['sendemail'] );
445 $wgUseEnotif = false;
446 $wgUserEmailUseReplyTo = false;
447 $wgUsersNotifiedOnAllChanges = [];
450 if ( $wgMetaNamespace === false ) {
451 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
454 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
455 if ( $wgResourceLoaderMaxQueryLength === false ) {
456 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
457 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
458 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
460 $wgResourceLoaderMaxQueryLength = 2000;
462 unset( $suhosinMaxValueLength );
465 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
467 $wgMinUploadChunkSize = min(
468 $wgMinUploadChunkSize,
469 UploadBase
::getMaxUploadSize( 'file' ),
470 UploadBase
::getMaxPhpUploadSize(),
471 ( wfShorthandToInteger(
472 ini_get( 'post_max_size' ) ?
: ini_get( 'hhvm.server.max_post_size' ),
474 ) ?
: PHP_INT_MAX
) - 1024 // Leave some room for other POST parameters
478 * Definitions of the NS_ constants are in Defines.php
481 $wgCanonicalNamespaceNames = NamespaceInfo
::$canonicalNames;
484 if ( is_array( $wgExtraNamespaces ) ) {
485 $wgCanonicalNamespaceNames +
= $wgExtraNamespaces;
488 // Hard-deprecate setting $wgDummyLanguageCodes in LocalSettings.php
489 if ( count( $wgDummyLanguageCodes ) !== 0 ) {
490 wfDeprecated( '$wgDummyLanguageCodes', '1.29' );
492 // Merge in the legacy language codes, incorporating overrides from the config
493 $wgDummyLanguageCodes +
= [
494 // Internal language codes of the private-use area which get mapped to
496 'qqq' => 'qqq', // Used for message documentation
497 'qqx' => 'qqx', // Used for viewing message keys
498 ] +
$wgExtraLanguageCodes + LanguageCode
::getDeprecatedCodeMapping();
499 // Merge in (inverted) BCP 47 mappings
500 foreach ( LanguageCode
::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
501 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
502 if ( !isset( $wgDummyLanguageCodes[$bcp47] ) ) {
503 $wgDummyLanguageCodes[$bcp47] = $wgDummyLanguageCodes[$code] ??
$code;
507 // These are now the same, always
508 // To determine the user language, use $wgLang->getCode()
509 $wgContLanguageCode = $wgLanguageCode;
511 // Temporary backwards-compatibility reading of old Squid-named CDN settings as of MediaWiki 1.34,
512 // to support sysadmins who fail to update their settings immediately:
514 if ( isset( $wgUseSquid ) ) {
515 // If the sysadmin is still setting a value of $wgUseSquid to true but $wgUseCdn is the default of
516 // false, to be safe, assume they do want this still, so enable it.
517 if ( !$wgUseCdn && $wgUseSquid ) {
518 $wgUseCdn = $wgUseSquid;
519 wfDeprecated( '$wgUseSquid enabled but $wgUseCdn disabled; enabling CDN functions', '1.34' );
522 // Backwards-compatibility for extensions that read this value.
523 $wgUseSquid = $wgUseCdn;
526 if ( isset( $wgSquidServers ) ) {
527 // If the sysadmin is still setting a value of $wgSquidServers but $wgCdnServers is the default of
528 // empty, to be safe, assume they do want these servers to be still used, so use them.
529 if ( !empty( $wgSquidServers ) && empty( $wgCdnServers ) ) {
530 $wgCdnServers = $wgSquidServers;
531 wfDeprecated( '$wgSquidServers set, $wgCdnServers empty; using them', '1.34' );
534 // Backwards-compatibility for extensions that read this value.
535 $wgSquidServers = $wgCdnServers;
538 if ( isset( $wgSquidServersNoPurge ) ) {
539 // If the sysadmin is still setting values in $wgSquidServersNoPurge but $wgCdnServersNoPurge is
540 // the default of empty, to be safe, assume they do want these servers to be still used, so use
542 if ( !empty( $wgSquidServersNoPurge ) && empty( $wgCdnServersNoPurge ) ) {
543 $wgCdnServersNoPurge = $wgSquidServersNoPurge;
544 wfDeprecated( '$wgSquidServersNoPurge set, $wgCdnServersNoPurge empty; using them', '1.34' );
547 // Backwards-compatibility for extensions that read this value.
548 $wgSquidServersNoPurge = $wgCdnServersNoPurge;
551 if ( isset( $wgSquidMaxage ) ) {
552 // If the sysadmin is still setting a value of $wgSquidMaxage and it's higher than $wgCdnMaxAge,
553 // to be safe, assume they want the higher (lower performance requirement) value, so use that.
554 if ( $wgCdnMaxAge < $wgSquidMaxage ) {
555 $wgCdnMaxAge = $wgSquidMaxage;
556 wfDeprecated( '$wgSquidMaxage set higher than $wgCdnMaxAge; using the higher value', '1.34' );
559 // Backwards-compatibility for extensions that read this value.
560 $wgSquidMaxage = $wgCdnMaxAge;
563 // Easy to forget to falsify $wgDebugToolbar for static caches.
564 // If file cache or CDN cache is on, just disable this (DWIMD).
565 if ( $wgUseFileCache ||
$wgUseCdn ) {
566 $wgDebugToolbar = false;
569 // Blacklisted file extensions shouldn't appear on the "allowed" list
570 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
572 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
573 Wikimedia\
suppressWarnings();
574 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
575 Wikimedia\restoreWarnings
();
578 if ( $wgNewUserLog ) {
579 // Add new user log type
580 $wgLogTypes[] = 'newusers';
581 $wgLogNames['newusers'] = 'newuserlogpage';
582 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
583 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter
::class;
584 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter
::class;
585 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter
::class;
586 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter
::class;
587 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter
::class;
590 if ( $wgPageCreationLog ) {
591 // Add page creation log type
592 $wgLogTypes[] = 'create';
593 $wgLogActionsHandlers['create/create'] = LogFormatter
::class;
596 if ( $wgPageLanguageUseDB ) {
597 $wgLogTypes[] = 'pagelang';
598 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter
::class;
601 if ( $wgCookieSecure === 'detect' ) {
602 $wgCookieSecure = ( WebRequest
::detectProtocol() === 'https' );
605 if ( $wgProfileOnly ) {
606 // Hard deprecated in 1.34.
608 '$wgProfileOnly set the log file in $wgDebugLogGroups[\'profileoutput\'] instead',
611 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
612 $wgDebugLogFile = '';
615 // Backwards compatibility with old password limits
616 if ( $wgMinimalPasswordLength !== false ) {
617 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
620 if ( $wgMaximalPasswordLength !== false ) {
621 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
624 if ( $wgPHPSessionHandling !== 'enable' &&
625 $wgPHPSessionHandling !== 'warn' &&
626 $wgPHPSessionHandling !== 'disable'
628 $wgPHPSessionHandling = 'warn';
630 if ( defined( 'MW_NO_SESSION' ) ) {
631 // If the entry point wants no session, force 'disable' here unless they
632 // specifically set it to the (undocumented) 'warn'.
633 $wgPHPSessionHandling = MW_NO_SESSION
=== 'warn' ?
'warn' : 'disable';
636 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
637 // all the memory from logging SQL queries on maintenance scripts
638 global $wgCommandLineMode;
639 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
643 // Reset the global service locator, so any services that have already been created will be
644 // re-created while taking into account any custom settings and extensions.
645 MediaWikiServices
::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
647 // Define a constant that indicates that the bootstrapping of the service locator
649 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
651 MWExceptionHandler
::installHandler();
653 // T48998: Bail out early if $wgArticlePath is non-absolute
654 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
655 if ( $
$varName && !preg_match( '/^(https?:\/\/|\/)/', $
$varName ) ) {
656 throw new FatalError(
657 "If you use a relative URL for \$$varName, it must start " .
658 'with a slash (<code>/</code>).<br><br>See ' .
659 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
660 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
665 if ( $wgCanonicalServer === false ) {
666 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP
);
670 $serverParts = wfParseUrl( $wgCanonicalServer );
671 if ( $wgServerName !== false ) {
672 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
673 . 'not customized. Overwriting $wgServerName.' );
675 $wgServerName = $serverParts['host'];
676 unset( $serverParts );
678 // Set defaults for configuration variables
679 // that are derived from the server name by default
680 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
681 if ( !$wgEmergencyContact ) {
682 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
684 if ( !$wgPasswordSender ) {
685 $wgPasswordSender = 'apache@' . $wgServerName;
687 if ( !$wgNoReplyAddress ) {
688 $wgNoReplyAddress = $wgPasswordSender;
691 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
692 $wgSecureLogin = false;
693 wfWarn( 'Secure login was enabled on a server that only supports '
694 . 'HTTP or HTTPS. Disabling secure login.' );
697 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
699 // Now that GlobalFunctions is loaded, set defaults that depend on it.
700 if ( $wgTmpDirectory === false ) {
701 $wgTmpDirectory = wfTempDir();
704 // We don't use counters anymore. Left here for extensions still
705 // expecting this to exist. Should be removed sometime 1.26 or later.
706 if ( !isset( $wgDisableCounters ) ) {
707 $wgDisableCounters = true;
710 if ( $wgMainWANCache === false ) {
711 // Setup a WAN cache from $wgMainCacheType with no relayer.
712 // Sites using multiple datacenters can configure a relayer.
713 $wgMainWANCache = 'mediawiki-main-default';
714 $wgWANObjectCaches[$wgMainWANCache] = [
715 'class' => WANObjectCache
::class,
716 'cacheId' => $wgMainCacheType
720 if ( $wgSharedDB && $wgSharedTables ) {
721 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
722 MediaWikiServices
::getInstance()->getDBLoadBalancer()->setTableAliases(
726 'dbname' => $wgSharedDB,
727 'schema' => $wgSharedSchema,
728 'prefix' => $wgSharedPrefix
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 // Most of the config is out, some might want to run hooks here.
814 Hooks
::run( 'SetupAfterCache' );
817 * @var Language $wgContLang
818 * @deprecated since 1.32, use the ContentLanguage service directly
820 $wgContLang = MediaWikiServices
::getInstance()->getContentLanguage();
822 // Now that variant lists may be available...
823 $wgRequest->interpolateTitle();
826 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
827 * session ID (if any) loaded at startup
829 $wgInitialSessionId = null;
830 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
831 // If session.auto_start is there, we can't touch session name
832 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
833 session_name( $wgSessionName ?
: $wgCookiePrefix . '_session' );
836 // Create the SessionManager singleton and set up our session handler,
837 // unless we're specifically asked not to.
838 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
839 MediaWiki\Session\PHPSessionHandler
::install(
840 MediaWiki\Session\SessionManager
::singleton()
844 // Initialize the session
846 $session = MediaWiki\Session\SessionManager
::getGlobalSession();
847 } catch ( OverflowException
$ex ) {
848 if ( isset( $ex->sessionInfos
) && count( $ex->sessionInfos
) >= 2 ) {
849 // The exception is because the request had multiple possible
850 // sessions tied for top priority. Report this to the user.
852 foreach ( $ex->sessionInfos
as $info ) {
853 $list[] = $info->getProvider()->describe( $wgContLang );
855 $list = $wgContLang->listToText( $list );
856 throw new HttpError( 400,
857 Message
::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
861 // Not the one we want, rethrow
865 if ( $session->isPersistent() ) {
866 $wgInitialSessionId = $session->getSessionId();
870 if ( MediaWiki\Session\PHPSessionHandler
::isEnabled() &&
871 ( $session->isPersistent() ||
$session->shouldRememberUser() ) &&
872 session_id() !== $session->getId()
874 // Start the PHP-session for backwards compatibility
875 if ( session_id() !== '' ) {
876 wfDebugLog( 'session', 'PHP session {old_id} was already started, changing to {new_id}', 'all', [
877 'old_id' => session_id(),
878 'new_id' => $session->getId(),
880 session_write_close();
882 session_id( $session->getId() );
888 // Even if we didn't set up a global Session, still install our session
889 // handler unless specifically requested not to.
890 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
891 MediaWiki\Session\PHPSessionHandler
::install(
892 MediaWiki\Session\SessionManager
::singleton()
900 $wgUser = RequestContext
::getMain()->getUser(); // BackCompat
903 * @var Language $wgLang
905 $wgLang = new StubUserLang
;
908 * @var OutputPage $wgOut
910 $wgOut = RequestContext
::getMain()->getOutput(); // BackCompat
913 * @var Parser $wgParser
914 * @deprecated since 1.32, use MediaWikiServices::getInstance()->getParser() instead
916 $wgParser = new StubObject( 'wgParser', function () {
917 return MediaWikiServices
::getInstance()->getParser();
921 * @var Title $wgTitle
925 // Extension setup functions
926 // Entries should be added to this variable during the inclusion
927 // of the extension file. This allows the extension to perform
928 // any necessary initialisation in the fully initialised environment
929 foreach ( $wgExtensionFunctions as $func ) {
930 call_user_func( $func );
933 // If the session user has a 0 id but a valid name, that means we need to
935 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
936 $sessionUser = MediaWiki\Session\SessionManager
::getGlobalSession()->getUser();
937 if ( $sessionUser->getId() === 0 && User
::isValidUserName( $sessionUser->getName() ) ) {
938 $res = MediaWiki\Auth\AuthManager
::singleton()->autoCreateUser(
940 MediaWiki\Auth\AuthManager
::AUTOCREATE_SOURCE_SESSION
,
943 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Autocreation attempt', [
944 'event' => 'autocreate',
949 unset( $sessionUser );
952 if ( !$wgCommandLineMode ) {
953 Pingback
::schedulePingback();
956 $wgFullyInitialised = true;