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 // Define MW_ENTRY_POINT if it's not already, so that config code can check the
56 // value without using defined()
57 if ( !defined( 'MW_ENTRY_POINT' ) ) {
59 * The entry point, which may be either the script filename without the
60 * file extension, or "cli" for maintenance scripts, or "unknown" for any
61 * entry point that does not set the constant.
63 define( 'MW_ENTRY_POINT', 'unknown' );
66 // Start the autoloader, so that extensions can derive classes from core files
67 require_once "$IP/includes/AutoLoader.php";
69 // Load global constants
70 require_once "$IP/includes/Defines.php";
72 // Load default settings
73 require_once "$IP/includes/DefaultSettings.php";
75 // Load global functions
76 require_once "$IP/includes/GlobalFunctions.php";
78 // Load composer's autoloader if present
79 if ( is_readable( "$IP/vendor/autoload.php" ) ) {
80 require_once "$IP/vendor/autoload.php";
81 } elseif ( file_exists( "$IP/vendor/autoload.php" ) ) {
82 die( "$IP/vendor/autoload.php exists but is not readable" );
85 // Assert that composer dependencies were successfully loaded
86 // Purposely no leading \ due to it breaking HHVM RepoAuthorative mode
87 // PHP works fine with both versions
88 // See https://github.com/facebook/hhvm/issues/5833
89 if ( !interface_exists( 'Psr\Log\LoggerInterface' ) ) {
91 'MediaWiki requires the <a href="https://github.com/php-fig/log">PSR-3 logging ' .
92 "library</a> to be present. This library is not embedded directly in MediaWiki's " .
93 "git repository and must be installed separately by the end user.\n\n" .
94 'Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git' .
95 '#Fetch_external_libraries">mediawiki.org</a> for help on installing ' .
96 'the required components.'
99 trigger_error( $message, E_USER_ERROR
);
104 * Changes to the PHP environment that don't vary on configuration.
107 // Install a header callback
108 MediaWiki\HeaderCallback
::register();
110 // Set the encoding used by PHP for reading HTTP input, and writing output.
111 // This is also the default for mbstring functions.
112 mb_internal_encoding( 'UTF-8' );
115 * Load LocalSettings.php
118 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
119 call_user_func( MW_CONFIG_CALLBACK
);
121 if ( !defined( 'MW_CONFIG_FILE' ) ) {
122 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
124 require_once MW_CONFIG_FILE
;
128 * Customization point after all loading (constants, functions, classes,
129 * DefaultSettings, LocalSettings). Specifically, this is before usage of
130 * settings, before instantiation of Profiler (and other singletons), and
131 * before any setup functions or hooks run.
134 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
135 call_user_func( MW_SETUP_CALLBACK
);
142 // Load queued extensions
143 ExtensionRegistry
::getInstance()->loadFromQueue();
144 // Don't let any other extensions load
145 ExtensionRegistry
::getInstance()->finish();
147 // Set the configured locale on all requests for consisteny
148 putenv( "LC_ALL=$wgShellLocale" );
149 setlocale( LC_ALL
, $wgShellLocale );
151 // Set various default paths sensibly...
152 if ( $wgScript === false ) {
153 $wgScript = "$wgScriptPath/index.php";
155 if ( $wgLoadScript === false ) {
156 $wgLoadScript = "$wgScriptPath/load.php";
158 if ( $wgRestPath === false ) {
159 $wgRestPath = "$wgScriptPath/rest.php";
162 if ( $wgArticlePath === false ) {
163 if ( $wgUsePathInfo ) {
164 $wgArticlePath = "$wgScript/$1";
166 $wgArticlePath = "$wgScript?title=$1";
170 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
171 // 'view' is assumed the default action path everywhere in the code
172 // but is rarely filled in $wgActionPaths
173 $wgActionPaths['view'] = $wgArticlePath;
176 if ( $wgResourceBasePath === null ) {
177 $wgResourceBasePath = $wgScriptPath;
179 if ( $wgStylePath === false ) {
180 $wgStylePath = "$wgResourceBasePath/skins";
182 if ( $wgLocalStylePath === false ) {
183 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
184 $wgLocalStylePath = "$wgScriptPath/skins";
186 if ( $wgExtensionAssetsPath === false ) {
187 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
190 if ( $wgLogo === false ) {
191 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
194 if ( $wgUploadPath === false ) {
195 $wgUploadPath = "$wgScriptPath/images";
197 if ( $wgUploadDirectory === false ) {
198 $wgUploadDirectory = "$IP/images";
200 if ( $wgReadOnlyFile === false ) {
201 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
203 if ( $wgFileCacheDirectory === false ) {
204 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
206 if ( $wgDeletedDirectory === false ) {
207 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
210 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
211 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
214 // Fix path to icon images after they were moved in 1.24
215 if ( $wgRightsIcon ) {
216 $wgRightsIcon = str_replace(
217 "{$wgStylePath}/common/images/",
218 "{$wgResourceBasePath}/resources/assets/licenses/",
223 if ( isset( $wgFooterIcons['copyright']['copyright'] )
224 && $wgFooterIcons['copyright']['copyright'] === []
226 if ( $wgRightsIcon ||
$wgRightsText ) {
227 $wgFooterIcons['copyright']['copyright'] = [
228 'url' => $wgRightsUrl,
229 'src' => $wgRightsIcon,
230 'alt' => $wgRightsText,
235 if ( isset( $wgFooterIcons['poweredby'] )
236 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
237 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
239 $wgFooterIcons['poweredby']['mediawiki']['src'] =
240 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
241 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
242 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
243 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
247 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
248 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
250 * Note that this is the definition of editinterface and it can be granted to
251 * all users if desired.
253 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
256 * The canonical names of namespaces 6 and 7 are, as of v1.14, "File"
257 * and "File_talk". The old names "Image" and "Image_talk" are
258 * retained as aliases for backwards compatibility.
260 $wgNamespaceAliases['Image'] = NS_FILE
;
261 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
264 * Initialise $wgLockManagers to include basic FS version
266 $wgLockManagers[] = [
267 'name' => 'fsLockManager',
268 'class' => FSLockManager
::class,
269 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
271 $wgLockManagers[] = [
272 'name' => 'nullLockManager',
273 'class' => NullLockManager
::class,
277 * Default parameters for the "<gallery>" tag.
278 * @see DefaultSettings.php for description of the fields.
280 $wgGalleryOptions +
= [
283 'imageHeight' => 120,
284 'captionLength' => true,
286 'showDimensions' => true,
287 'mode' => 'traditional',
291 * Shortcuts for $wgLocalFileRepo
293 if ( !$wgLocalFileRepo ) {
295 'class' => LocalRepo
::class,
297 'directory' => $wgUploadDirectory,
298 'scriptDirUrl' => $wgScriptPath,
299 'url' => $wgUploadBaseUrl ?
$wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
300 'hashLevels' => $wgHashedUploadDirectory ?
2 : 0,
301 'thumbScriptUrl' => $wgThumbnailScriptPath,
302 'transformVia404' => !$wgGenerateThumbnailOnParse,
303 'deletedDir' => $wgDeletedDirectory,
304 'deletedHashLevels' => $wgHashedUploadDirectory ?
3 : 0
308 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
309 // Create a default FileBackend name.
310 // FileBackendGroup will register a default, if absent from $wgFileBackends.
311 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
315 * Shortcuts for $wgForeignFileRepos
317 if ( $wgUseSharedUploads ) {
318 if ( $wgSharedUploadDBname ) {
319 $wgForeignFileRepos[] = [
320 'class' => ForeignDBRepo
::class,
322 'directory' => $wgSharedUploadDirectory,
323 'url' => $wgSharedUploadPath,
324 'hashLevels' => $wgHashedSharedUploadDirectory ?
2 : 0,
325 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
326 'transformVia404' => !$wgGenerateThumbnailOnParse,
327 'dbType' => $wgDBtype,
328 'dbServer' => $wgDBserver,
329 'dbUser' => $wgDBuser,
330 'dbPassword' => $wgDBpassword,
331 'dbName' => $wgSharedUploadDBname,
332 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG
: 0 ) | DBO_DEFAULT
,
333 'tablePrefix' => $wgSharedUploadDBprefix,
334 'hasSharedCache' => $wgCacheSharedUploads,
335 'descBaseUrl' => $wgRepositoryBaseUrl,
336 'fetchDescription' => $wgFetchCommonsDescriptions,
339 $wgForeignFileRepos[] = [
340 'class' => FileRepo
::class,
342 'directory' => $wgSharedUploadDirectory,
343 'url' => $wgSharedUploadPath,
344 'hashLevels' => $wgHashedSharedUploadDirectory ?
2 : 0,
345 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
346 'transformVia404' => !$wgGenerateThumbnailOnParse,
347 'descBaseUrl' => $wgRepositoryBaseUrl,
348 'fetchDescription' => $wgFetchCommonsDescriptions,
352 if ( $wgUseInstantCommons ) {
353 $wgForeignFileRepos[] = [
354 'class' => ForeignAPIRepo
::class,
355 'name' => 'wikimediacommons',
356 'apibase' => 'https://commons.wikimedia.org/w/api.php',
357 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
358 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
360 'transformVia404' => true,
361 'fetchDescription' => true,
362 'descriptionCacheExpiry' => 43200,
363 'apiThumbCacheExpiry' => 0,
366 foreach ( $wgForeignFileRepos as &$repo ) {
367 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo
::class ) {
368 $repo['directory'] = $wgUploadDirectory; // b/c
370 if ( !isset( $repo['backend'] ) ) {
371 $repo['backend'] = $repo['name'] . '-backend';
374 unset( $repo ); // no global pollution; destroy reference
376 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
377 // Ensure that default user options are not invalid, since that breaks Special:Preferences
378 $wgDefaultUserOptions['rcdays'] = min(
379 $wgDefaultUserOptions['rcdays'],
380 ceil( $rcMaxAgeDays )
382 $wgDefaultUserOptions['watchlistdays'] = min(
383 $wgDefaultUserOptions['watchlistdays'],
384 ceil( $rcMaxAgeDays )
386 unset( $rcMaxAgeDays );
389 // Hard deprecated in 1.34.
390 wfDeprecated( '$wgSkipSkin – use $wgSkipSkins instead', '1.23' );
391 $wgSkipSkins[] = $wgSkipSkin;
394 $wgSkipSkins[] = 'fallback';
395 $wgSkipSkins[] = 'apioutput';
397 if ( $wgLocalInterwiki ) {
398 // Hard deprecated in 1.34.
399 wfDeprecated( '$wgLocalInterwiki – use $wgLocalInterwikis instead', '1.23' );
400 // @phan-suppress-next-line PhanUndeclaredVariableDim
401 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
404 // Set default shared prefix
405 if ( $wgSharedPrefix === false ) {
406 $wgSharedPrefix = $wgDBprefix;
409 // Set default shared schema
410 if ( $wgSharedSchema === false ) {
411 $wgSharedSchema = $wgDBmwschema;
414 if ( !$wgCookiePrefix ) {
415 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
416 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
417 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
418 $wgCookiePrefix = $wgSharedDB;
419 } elseif ( $wgDBprefix ) {
420 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
422 $wgCookiePrefix = $wgDBname;
425 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
427 if ( $wgEnableEmail ) {
428 $wgUseEnotif = $wgEnotifUserTalk ||
$wgEnotifWatchlist;
430 // Disable all other email settings automatically if $wgEnableEmail
431 // is set to false. - T65678
432 $wgAllowHTMLEmail = false;
433 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
434 $wgEnableUserEmail = false;
435 $wgEnotifFromEditor = false;
436 $wgEnotifImpersonal = false;
437 $wgEnotifMaxRecips = 0;
438 $wgEnotifMinorEdits = false;
439 $wgEnotifRevealEditorAddress = false;
440 $wgEnotifUseRealName = false;
441 $wgEnotifUserTalk = false;
442 $wgEnotifWatchlist = false;
443 unset( $wgGroupPermissions['user']['sendemail'] );
444 $wgUseEnotif = false;
445 $wgUserEmailUseReplyTo = false;
446 $wgUsersNotifiedOnAllChanges = [];
449 if ( $wgMetaNamespace === false ) {
450 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
453 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
454 if ( $wgResourceLoaderMaxQueryLength === false ) {
455 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
456 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
457 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
459 $wgResourceLoaderMaxQueryLength = 2000;
461 unset( $suhosinMaxValueLength );
464 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
466 $wgMinUploadChunkSize = min(
467 $wgMinUploadChunkSize,
468 UploadBase
::getMaxUploadSize( 'file' ),
469 UploadBase
::getMaxPhpUploadSize(),
470 ( wfShorthandToInteger(
471 ini_get( 'post_max_size' ) ?
: ini_get( 'hhvm.server.max_post_size' ),
473 ) ?
: PHP_INT_MAX
) - 1024 // Leave some room for other POST parameters
477 * Definitions of the NS_ constants are in Defines.php
480 $wgCanonicalNamespaceNames = NamespaceInfo
::$canonicalNames;
483 if ( is_array( $wgExtraNamespaces ) ) {
484 $wgCanonicalNamespaceNames +
= $wgExtraNamespaces;
487 // Hard-deprecate setting $wgDummyLanguageCodes in LocalSettings.php
488 if ( count( $wgDummyLanguageCodes ) !== 0 ) {
489 wfDeprecated( '$wgDummyLanguageCodes', '1.29' );
491 // Merge in the legacy language codes, incorporating overrides from the config
492 $wgDummyLanguageCodes +
= [
493 // Internal language codes of the private-use area which get mapped to
495 'qqq' => 'qqq', // Used for message documentation
496 'qqx' => 'qqx', // Used for viewing message keys
497 ] +
$wgExtraLanguageCodes + LanguageCode
::getDeprecatedCodeMapping();
498 // Merge in (inverted) BCP 47 mappings
499 foreach ( LanguageCode
::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
500 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
501 if ( !isset( $wgDummyLanguageCodes[$bcp47] ) ) {
502 $wgDummyLanguageCodes[$bcp47] = $wgDummyLanguageCodes[$code] ??
$code;
506 // These are now the same, always
507 // To determine the user language, use $wgLang->getCode()
508 $wgContLanguageCode = $wgLanguageCode;
510 // Temporary backwards-compatibility reading of old Squid-named CDN settings as of MediaWiki 1.34,
511 // to support sysadmins who fail to update their settings immediately:
513 if ( isset( $wgUseSquid ) ) {
514 // If the sysadmin is still setting a value of $wgUseSquid to true but $wgUseCdn is the default of
515 // false, to be safe, assume they do want this still, so enable it.
516 if ( !$wgUseCdn && $wgUseSquid ) {
517 $wgUseCdn = $wgUseSquid;
518 wfDeprecated( '$wgUseSquid enabled but $wgUseCdn disabled; enabling CDN functions', '1.34' );
521 // Backwards-compatibility for extensions that read this value.
522 $wgUseSquid = $wgUseCdn;
525 if ( isset( $wgSquidServers ) ) {
526 // If the sysadmin is still setting a value of $wgSquidServers but $wgCdnServers is the default of
527 // empty, to be safe, assume they do want these servers to be still used, so use them.
528 if ( !empty( $wgSquidServers ) && empty( $wgCdnServers ) ) {
529 $wgCdnServers = $wgSquidServers;
530 wfDeprecated( '$wgSquidServers set, $wgCdnServers empty; using them', '1.34' );
533 // Backwards-compatibility for extensions that read this value.
534 $wgSquidServers = $wgCdnServers;
537 if ( isset( $wgSquidServersNoPurge ) ) {
538 // If the sysadmin is still setting values in $wgSquidServersNoPurge but $wgCdnServersNoPurge is
539 // the default of empty, to be safe, assume they do want these servers to be still used, so use
541 if ( !empty( $wgSquidServersNoPurge ) && empty( $wgCdnServersNoPurge ) ) {
542 $wgCdnServersNoPurge = $wgSquidServersNoPurge;
543 wfDeprecated( '$wgSquidServersNoPurge set, $wgCdnServersNoPurge empty; using them', '1.34' );
546 // Backwards-compatibility for extensions that read this value.
547 $wgSquidServersNoPurge = $wgCdnServersNoPurge;
550 if ( isset( $wgSquidMaxage ) ) {
551 // If the sysadmin is still setting a value of $wgSquidMaxage and it's higher than $wgCdnMaxAge,
552 // to be safe, assume they want the higher (lower performance requirement) value, so use that.
553 if ( $wgCdnMaxAge < $wgSquidMaxage ) {
554 $wgCdnMaxAge = $wgSquidMaxage;
555 wfDeprecated( '$wgSquidMaxage set higher than $wgCdnMaxAge; using the higher value', '1.34' );
558 // Backwards-compatibility for extensions that read this value.
559 $wgSquidMaxage = $wgCdnMaxAge;
562 // Easy to forget to falsify $wgDebugToolbar for static caches.
563 // If file cache or CDN cache is on, just disable this (DWIMD).
564 if ( $wgUseFileCache ||
$wgUseCdn ) {
565 $wgDebugToolbar = false;
568 // Blacklisted file extensions shouldn't appear on the "allowed" list
569 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
571 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
572 Wikimedia\
suppressWarnings();
573 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
574 Wikimedia\restoreWarnings
();
577 if ( $wgNewUserLog ) {
578 // Add new user log type
579 $wgLogTypes[] = 'newusers';
580 $wgLogNames['newusers'] = 'newuserlogpage';
581 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
582 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter
::class;
583 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter
::class;
584 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter
::class;
585 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter
::class;
586 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter
::class;
589 if ( $wgPageCreationLog ) {
590 // Add page creation log type
591 $wgLogTypes[] = 'create';
592 $wgLogActionsHandlers['create/create'] = LogFormatter
::class;
595 if ( $wgPageLanguageUseDB ) {
596 $wgLogTypes[] = 'pagelang';
597 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter
::class;
600 if ( $wgCookieSecure === 'detect' ) {
601 $wgCookieSecure = ( WebRequest
::detectProtocol() === 'https' );
604 if ( $wgProfileOnly ) {
605 // Hard deprecated in 1.34.
607 '$wgProfileOnly set the log file in $wgDebugLogGroups[\'profileoutput\'] instead',
610 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
611 $wgDebugLogFile = '';
614 // Backwards compatibility with old password limits
615 if ( $wgMinimalPasswordLength !== false ) {
616 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
619 if ( $wgMaximalPasswordLength !== false ) {
620 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
623 if ( $wgPHPSessionHandling !== 'enable' &&
624 $wgPHPSessionHandling !== 'warn' &&
625 $wgPHPSessionHandling !== 'disable'
627 $wgPHPSessionHandling = 'warn';
629 if ( defined( 'MW_NO_SESSION' ) ) {
630 // If the entry point wants no session, force 'disable' here unless they
631 // specifically set it to the (undocumented) 'warn'.
632 $wgPHPSessionHandling = MW_NO_SESSION
=== 'warn' ?
'warn' : 'disable';
635 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
636 // all the memory from logging SQL queries on maintenance scripts
637 global $wgCommandLineMode;
638 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
642 // Reset the global service locator, so any services that have already been created will be
643 // re-created while taking into account any custom settings and extensions.
644 MediaWikiServices
::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
646 // Define a constant that indicates that the bootstrapping of the service locator
648 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
650 MWExceptionHandler
::installHandler();
652 // T48998: Bail out early if $wgArticlePath is non-absolute
653 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
654 if ( $
$varName && !preg_match( '/^(https?:\/\/|\/)/', $
$varName ) ) {
655 throw new FatalError(
656 "If you use a relative URL for \$$varName, it must start " .
657 'with a slash (<code>/</code>).<br><br>See ' .
658 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
659 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
664 if ( $wgCanonicalServer === false ) {
665 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP
);
669 $serverParts = wfParseUrl( $wgCanonicalServer );
670 if ( $wgServerName !== false ) {
671 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
672 . 'not customized. Overwriting $wgServerName.' );
674 $wgServerName = $serverParts['host'];
675 unset( $serverParts );
677 // Set defaults for configuration variables
678 // that are derived from the server name by default
679 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
680 if ( !$wgEmergencyContact ) {
681 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
683 if ( !$wgPasswordSender ) {
684 $wgPasswordSender = 'apache@' . $wgServerName;
686 if ( !$wgNoReplyAddress ) {
687 $wgNoReplyAddress = $wgPasswordSender;
690 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
691 $wgSecureLogin = false;
692 wfWarn( 'Secure login was enabled on a server that only supports '
693 . 'HTTP or HTTPS. Disabling secure login.' );
696 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
698 // Now that GlobalFunctions is loaded, set defaults that depend on it.
699 if ( $wgTmpDirectory === false ) {
700 $wgTmpDirectory = wfTempDir();
703 // We don't use counters anymore. Left here for extensions still
704 // expecting this to exist. Should be removed sometime 1.26 or later.
705 if ( !isset( $wgDisableCounters ) ) {
706 $wgDisableCounters = true;
709 if ( $wgMainWANCache === false ) {
710 // Setup a WAN cache from $wgMainCacheType with no relayer.
711 // Sites using multiple datacenters can configure a relayer.
712 $wgMainWANCache = 'mediawiki-main-default';
713 $wgWANObjectCaches[$wgMainWANCache] = [
714 'class' => WANObjectCache
::class,
715 'cacheId' => $wgMainCacheType
719 if ( $wgSharedDB && $wgSharedTables ) {
720 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
721 MediaWikiServices
::getInstance()->getDBLoadBalancer()->setTableAliases(
725 'dbname' => $wgSharedDB,
726 'schema' => $wgSharedSchema,
727 'prefix' => $wgSharedPrefix
733 // Raise the memory limit if it's too low
734 // Note, this makes use of wfDebug, and thus should not be before
735 // MWDebug::init() is called.
736 wfMemoryLimit( $wgMemoryLimit );
739 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
740 * that happens whenever you use a date function without the timezone being
741 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
743 if ( is_null( $wgLocaltimezone ) ) {
744 Wikimedia\
suppressWarnings();
745 $wgLocaltimezone = date_default_timezone_get();
746 Wikimedia\restoreWarnings
();
749 date_default_timezone_set( $wgLocaltimezone );
750 if ( is_null( $wgLocalTZoffset ) ) {
751 $wgLocalTZoffset = date( 'Z' ) / 60;
753 // The part after the System| is ignored, but rest of MW fills it
754 // out as the local offset.
755 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
757 if ( !$wgDBerrorLogTZ ) {
758 $wgDBerrorLogTZ = $wgLocaltimezone;
761 // Initialize the request object in $wgRequest
762 $wgRequest = RequestContext
::getMain()->getRequest(); // BackCompat
763 // Set user IP/agent information for agent session consistency purposes
764 $cpPosInfo = LBFactory
::getCPInfoFromCookieValue(
765 // The cookie has no prefix and is set by MediaWiki::preOutputCommit()
766 $wgRequest->getCookie( 'cpPosIndex', '' ),
767 // Mitigate broken client-side cookie expiration handling (T190082)
768 time() - ChronologyProtector
::POSITION_COOKIE_TTL
770 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
771 'IPAddress' => $wgRequest->getIP(),
772 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
773 'ChronologyProtection' => $wgRequest->getHeader( 'MediaWiki-Chronology-Protection' ),
774 'ChronologyPositionIndex' => $wgRequest->getInt( 'cpPosIndex', $cpPosInfo['index'] ),
775 'ChronologyClientId' => $cpPosInfo['clientId']
776 ??
$wgRequest->getHeader( 'MediaWiki-Chronology-Client-Id' )
779 // Make sure that object caching does not undermine the ChronologyProtector improvements
780 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
781 // The user is pinned to the primary DC, meaning that they made recent changes which should
782 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
783 // they use a blind TTL and could be stale if an object changes twice in a short time span.
784 MediaWikiServices
::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
787 // Useful debug output
788 if ( $wgCommandLineMode ) {
789 if ( isset( $self ) ) {
790 wfDebug( "\n\nStart command line script $self\n" );
793 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
794 $debug .= "HTTP HEADERS:\n";
795 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
796 $debug .= "$name: $value\n";
801 $wgMemc = ObjectCache
::getLocalClusterInstance();
802 $messageMemc = wfGetMessageCacheStorage();
804 // Most of the config is out, some might want to run hooks here.
805 Hooks
::run( 'SetupAfterCache' );
808 * @var Language $wgContLang
809 * @deprecated since 1.32, use the ContentLanguage service directly
811 $wgContLang = MediaWikiServices
::getInstance()->getContentLanguage();
813 // Now that variant lists may be available...
814 $wgRequest->interpolateTitle();
817 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
818 * session ID (if any) loaded at startup
820 $wgInitialSessionId = null;
821 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
822 // If session.auto_start is there, we can't touch session name
823 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
824 session_name( $wgSessionName ?
: $wgCookiePrefix . '_session' );
827 // Create the SessionManager singleton and set up our session handler,
828 // unless we're specifically asked not to.
829 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
830 MediaWiki\Session\PHPSessionHandler
::install(
831 MediaWiki\Session\SessionManager
::singleton()
835 // Initialize the session
837 $session = MediaWiki\Session\SessionManager
::getGlobalSession();
838 } catch ( OverflowException
$ex ) {
839 if ( isset( $ex->sessionInfos
) && count( $ex->sessionInfos
) >= 2 ) {
840 // The exception is because the request had multiple possible
841 // sessions tied for top priority. Report this to the user.
843 foreach ( $ex->sessionInfos
as $info ) {
844 $list[] = $info->getProvider()->describe( $wgContLang );
846 $list = $wgContLang->listToText( $list );
847 throw new HttpError( 400,
848 Message
::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
852 // Not the one we want, rethrow
856 if ( $session->isPersistent() ) {
857 $wgInitialSessionId = $session->getSessionId();
861 if ( MediaWiki\Session\PHPSessionHandler
::isEnabled() &&
862 ( $session->isPersistent() ||
$session->shouldRememberUser() ) &&
863 session_id() !== $session->getId()
865 // Start the PHP-session for backwards compatibility
866 if ( session_id() !== '' ) {
867 wfDebugLog( 'session', 'PHP session {old_id} was already started, changing to {new_id}', 'all', [
868 'old_id' => session_id(),
869 'new_id' => $session->getId(),
871 session_write_close();
873 session_id( $session->getId() );
879 // Even if we didn't set up a global Session, still install our session
880 // handler unless specifically requested not to.
881 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
882 MediaWiki\Session\PHPSessionHandler
::install(
883 MediaWiki\Session\SessionManager
::singleton()
891 $wgUser = RequestContext
::getMain()->getUser(); // BackCompat
894 * @var Language $wgLang
896 $wgLang = new StubUserLang
;
899 * @var OutputPage $wgOut
901 $wgOut = RequestContext
::getMain()->getOutput(); // BackCompat
904 * @var Parser $wgParser
905 * @deprecated since 1.32, use MediaWikiServices::getInstance()->getParser() instead
907 $wgParser = new StubObject( 'wgParser', function () {
908 return MediaWikiServices
::getInstance()->getParser();
912 * @var Title $wgTitle
916 // Extension setup functions
917 // Entries should be added to this variable during the inclusion
918 // of the extension file. This allows the extension to perform
919 // any necessary initialisation in the fully initialised environment
920 foreach ( $wgExtensionFunctions as $func ) {
921 call_user_func( $func );
924 // If the session user has a 0 id but a valid name, that means we need to
926 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
927 $sessionUser = MediaWiki\Session\SessionManager
::getGlobalSession()->getUser();
928 if ( $sessionUser->getId() === 0 && User
::isValidUserName( $sessionUser->getName() ) ) {
929 $res = MediaWiki\Auth\AuthManager
::singleton()->autoCreateUser(
931 MediaWiki\Auth\AuthManager
::AUTOCREATE_SOURCE_SESSION
,
934 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Autocreation attempt', [
935 'event' => 'autocreate',
940 unset( $sessionUser );
943 if ( !$wgCommandLineMode ) {
944 Pingback
::schedulePingback();
947 $wgFullyInitialised = true;