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 up some global defines
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
);
92 // Install a header callback
93 MediaWiki\HeaderCallback
::register();
96 * Load LocalSettings.php
99 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
100 call_user_func( MW_CONFIG_CALLBACK
);
102 if ( !defined( 'MW_CONFIG_FILE' ) ) {
103 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
105 require_once MW_CONFIG_FILE
;
109 * Customization point after all loading (constants, functions, classes,
110 * DefaultSettings, LocalSettings). Specifically, this is before usage of
111 * settings, before instantiation of Profiler (and other singletons), and
112 * before any setup functions or hooks run.
115 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
116 call_user_func( MW_SETUP_CALLBACK
);
123 $fname = 'Setup.php';
124 $ps_setup = Profiler
::instance()->scopedProfileIn( $fname );
126 // Load queued extensions
127 ExtensionRegistry
::getInstance()->loadFromQueue();
128 // Don't let any other extensions load
129 ExtensionRegistry
::getInstance()->finish();
131 mb_internal_encoding( 'UTF-8' );
133 // Set the configured locale on all requests for consisteny
134 putenv( "LC_ALL=$wgShellLocale" );
135 setlocale( LC_ALL
, $wgShellLocale );
137 // Set various default paths sensibly...
138 $ps_default = Profiler
::instance()->scopedProfileIn( $fname . '-defaults' );
140 if ( $wgScript === false ) {
141 $wgScript = "$wgScriptPath/index.php";
143 if ( $wgLoadScript === false ) {
144 $wgLoadScript = "$wgScriptPath/load.php";
147 if ( $wgArticlePath === false ) {
148 if ( $wgUsePathInfo ) {
149 $wgArticlePath = "$wgScript/$1";
151 $wgArticlePath = "$wgScript?title=$1";
155 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
156 // 'view' is assumed the default action path everywhere in the code
157 // but is rarely filled in $wgActionPaths
158 $wgActionPaths['view'] = $wgArticlePath;
161 if ( $wgResourceBasePath === null ) {
162 $wgResourceBasePath = $wgScriptPath;
164 if ( $wgStylePath === false ) {
165 $wgStylePath = "$wgResourceBasePath/skins";
167 if ( $wgLocalStylePath === false ) {
168 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
169 $wgLocalStylePath = "$wgScriptPath/skins";
171 if ( $wgExtensionAssetsPath === false ) {
172 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
175 if ( $wgLogo === false ) {
176 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
179 if ( $wgUploadPath === false ) {
180 $wgUploadPath = "$wgScriptPath/images";
182 if ( $wgUploadDirectory === false ) {
183 $wgUploadDirectory = "$IP/images";
185 if ( $wgReadOnlyFile === false ) {
186 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
188 if ( $wgFileCacheDirectory === false ) {
189 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
191 if ( $wgDeletedDirectory === false ) {
192 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
195 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
196 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
199 if ( $wgEnableParserCache === false ) {
200 $wgParserCacheType = CACHE_NONE
;
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 $wgSkipSkins[] = $wgSkipSkin;
394 $wgSkipSkins[] = 'fallback';
395 $wgSkipSkins[] = 'apioutput';
397 if ( $wgLocalInterwiki ) {
398 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
401 // Set default shared prefix
402 if ( $wgSharedPrefix === false ) {
403 $wgSharedPrefix = $wgDBprefix;
406 // Set default shared schema
407 if ( $wgSharedSchema === false ) {
408 $wgSharedSchema = $wgDBmwschema;
411 if ( !$wgCookiePrefix ) {
412 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
413 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
414 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
415 $wgCookiePrefix = $wgSharedDB;
416 } elseif ( $wgDBprefix ) {
417 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
419 $wgCookiePrefix = $wgDBname;
422 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
424 if ( $wgEnableEmail ) {
425 $wgUseEnotif = $wgEnotifUserTalk ||
$wgEnotifWatchlist;
427 // Disable all other email settings automatically if $wgEnableEmail
428 // is set to false. - T65678
429 $wgAllowHTMLEmail = false;
430 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
431 $wgEnableUserEmail = false;
432 $wgEnotifFromEditor = false;
433 $wgEnotifImpersonal = false;
434 $wgEnotifMaxRecips = 0;
435 $wgEnotifMinorEdits = false;
436 $wgEnotifRevealEditorAddress = false;
437 $wgEnotifUseRealName = false;
438 $wgEnotifUserTalk = false;
439 $wgEnotifWatchlist = false;
440 unset( $wgGroupPermissions['user']['sendemail'] );
441 $wgUseEnotif = false;
442 $wgUserEmailUseReplyTo = false;
443 $wgUsersNotifiedOnAllChanges = [];
446 if ( $wgMetaNamespace === false ) {
447 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
450 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
451 if ( $wgResourceLoaderMaxQueryLength === false ) {
452 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
453 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
454 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
456 $wgResourceLoaderMaxQueryLength = 2000;
458 unset( $suhosinMaxValueLength );
461 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
463 $wgMinUploadChunkSize = min(
464 $wgMinUploadChunkSize,
465 UploadBase
::getMaxUploadSize( 'file' ),
466 UploadBase
::getMaxPhpUploadSize(),
467 ( wfShorthandToInteger(
468 ini_get( 'post_max_size' ) ?
: ini_get( 'hhvm.server.max_post_size' ),
470 ) ?
: PHP_INT_MAX
) - 1024 // Leave some room for other POST parameters
474 * Definitions of the NS_ constants are in Defines.php
477 $wgCanonicalNamespaceNames = [
479 NS_SPECIAL
=> 'Special',
482 NS_USER_TALK
=> 'User_talk',
483 NS_PROJECT
=> 'Project',
484 NS_PROJECT_TALK
=> 'Project_talk',
486 NS_FILE_TALK
=> 'File_talk',
487 NS_MEDIAWIKI
=> 'MediaWiki',
488 NS_MEDIAWIKI_TALK
=> 'MediaWiki_talk',
489 NS_TEMPLATE
=> 'Template',
490 NS_TEMPLATE_TALK
=> 'Template_talk',
492 NS_HELP_TALK
=> 'Help_talk',
493 NS_CATEGORY
=> 'Category',
494 NS_CATEGORY_TALK
=> 'Category_talk',
498 if ( is_array( $wgExtraNamespaces ) ) {
499 $wgCanonicalNamespaceNames = $wgCanonicalNamespaceNames +
$wgExtraNamespaces;
502 // Hard-deprecate setting $wgDummyLanguageCodes in LocalSettings.php
503 if ( count( $wgDummyLanguageCodes ) !== 0 ) {
504 wfDeprecated( '$wgDummyLanguageCodes', '1.29' );
506 // Merge in the legacy language codes, incorporating overrides from the config
507 $wgDummyLanguageCodes +
= [
508 // Internal language codes of the private-use area which get mapped to
510 'qqq' => 'qqq', // Used for message documentation
511 'qqx' => 'qqx', // Used for viewing message keys
512 ] +
$wgExtraLanguageCodes + LanguageCode
::getDeprecatedCodeMapping();
513 // Merge in (inverted) BCP 47 mappings
514 foreach ( LanguageCode
::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
515 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
516 if ( !isset( $wgDummyLanguageCodes[$bcp47] ) ) {
517 $wgDummyLanguageCodes[$bcp47] = $wgDummyLanguageCodes[$code] ??
$code;
521 // These are now the same, always
522 // To determine the user language, use $wgLang->getCode()
523 $wgContLanguageCode = $wgLanguageCode;
525 // Easy to forget to falsify $wgDebugToolbar for static caches.
526 // If file cache or CDN cache is on, just disable this (DWIMD).
527 if ( $wgUseFileCache ||
$wgUseSquid ) {
528 $wgDebugToolbar = false;
531 // We always output HTML5 since 1.22, overriding these is no longer supported
532 // we set them here for extensions that depend on its value.
534 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
535 $wgJsMimeType = 'text/javascript';
537 // Blacklisted file extensions shouldn't appear on the "allowed" list
538 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
540 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
541 Wikimedia\
suppressWarnings();
542 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
543 Wikimedia\restoreWarnings
();
546 if ( $wgNewUserLog ) {
547 // Add new user log type
548 $wgLogTypes[] = 'newusers';
549 $wgLogNames['newusers'] = 'newuserlogpage';
550 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
551 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter
::class;
552 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter
::class;
553 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter
::class;
554 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter
::class;
555 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter
::class;
558 if ( $wgPageCreationLog ) {
559 // Add page creation log type
560 $wgLogTypes[] = 'create';
561 $wgLogActionsHandlers['create/create'] = LogFormatter
::class;
564 if ( $wgPageLanguageUseDB ) {
565 $wgLogTypes[] = 'pagelang';
566 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter
::class;
569 if ( $wgCookieSecure === 'detect' ) {
570 $wgCookieSecure = ( WebRequest
::detectProtocol() === 'https' );
573 if ( $wgProfileOnly ) {
574 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
575 $wgDebugLogFile = '';
578 // Backwards compatibility with old password limits
579 if ( $wgMinimalPasswordLength !== false ) {
580 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
583 if ( $wgMaximalPasswordLength !== false ) {
584 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
587 // Backwards compatibility warning
588 if ( !$wgSessionsInObjectCache ) {
589 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
590 if ( $wgSessionHandler ) {
591 wfDeprecated( '$wgSessionsHandler', '1.27' );
593 $cacheType = get_class( ObjectCache
::getInstance( $wgSessionCacheType ) );
596 "Session data will be stored in \"$cacheType\" cache with " .
597 "expiry $wgObjectCacheSessionExpiry seconds"
600 $wgSessionsInObjectCache = true;
602 if ( $wgPHPSessionHandling !== 'enable' &&
603 $wgPHPSessionHandling !== 'warn' &&
604 $wgPHPSessionHandling !== 'disable'
606 $wgPHPSessionHandling = 'warn';
608 if ( defined( 'MW_NO_SESSION' ) ) {
609 // If the entry point wants no session, force 'disable' here unless they
610 // specifically set it to the (undocumented) 'warn'.
611 $wgPHPSessionHandling = MW_NO_SESSION
=== 'warn' ?
'warn' : 'disable';
614 Profiler
::instance()->scopedProfileOut( $ps_default );
616 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
617 // all the memory from logging SQL queries on maintenance scripts
618 global $wgCommandLineMode;
619 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
623 // Reset the global service locator, so any services that have already been created will be
624 // re-created while taking into account any custom settings and extensions.
625 MediaWikiServices
::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
627 if ( $wgSharedDB && $wgSharedTables ) {
628 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
629 MediaWikiServices
::getInstance()->getDBLoadBalancer()->setTableAliases(
633 'dbname' => $wgSharedDB,
634 'schema' => $wgSharedSchema,
635 'prefix' => $wgSharedPrefix
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,
713 'channels' => [ 'purge' => 'wancache-main-default-purge' ]
717 Profiler
::instance()->scopedProfileOut( $ps_default2 );
719 $ps_misc = Profiler
::instance()->scopedProfileIn( $fname . '-misc' );
721 // Raise the memory limit if it's too low
725 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
726 * that happens whenever you use a date function without the timezone being
727 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
729 if ( is_null( $wgLocaltimezone ) ) {
730 Wikimedia\
suppressWarnings();
731 $wgLocaltimezone = date_default_timezone_get();
732 Wikimedia\restoreWarnings
();
735 date_default_timezone_set( $wgLocaltimezone );
736 if ( is_null( $wgLocalTZoffset ) ) {
737 $wgLocalTZoffset = date( 'Z' ) / 60;
739 // The part after the System| is ignored, but rest of MW fills it
740 // out as the local offset.
741 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
743 if ( !$wgDBerrorLogTZ ) {
744 $wgDBerrorLogTZ = $wgLocaltimezone;
747 // Initialize the request object in $wgRequest
748 $wgRequest = RequestContext
::getMain()->getRequest(); // BackCompat
749 // Set user IP/agent information for agent session consistency purposes
750 $cpPosInfo = LBFactory
::getCPInfoFromCookieValue(
751 // The cookie has no prefix and is set by MediaWiki::preOutputCommit()
752 $wgRequest->getCookie( 'cpPosIndex', '' ),
753 // Mitigate broken client-side cookie expiration handling (T190082)
754 time() - ChronologyProtector
::POSITION_COOKIE_TTL
756 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
757 'IPAddress' => $wgRequest->getIP(),
758 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
759 'ChronologyProtection' => $wgRequest->getHeader( 'ChronologyProtection' ),
760 'ChronologyPositionIndex' => $wgRequest->getInt( 'cpPosIndex', $cpPosInfo['index'] ),
761 'ChronologyClientId' => $cpPosInfo['clientId']
764 // Make sure that object caching does not undermine the ChronologyProtector improvements
765 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
766 // The user is pinned to the primary DC, meaning that they made recent changes which should
767 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
768 // they use a blind TTL and could be stale if an object changes twice in a short time span.
769 MediaWikiServices
::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
772 // Useful debug output
773 if ( $wgCommandLineMode ) {
774 wfDebug( "\n\nStart command line script $self\n" );
776 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
778 if ( $wgDebugPrintHttpHeaders ) {
779 $debug .= "HTTP HEADERS:\n";
781 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
782 $debug .= "$name: $value\n";
788 $wgMemc = ObjectCache
::getLocalClusterInstance();
789 $messageMemc = wfGetMessageCacheStorage();
791 wfDebugLog( 'caches',
792 'cluster: ' . get_class( $wgMemc ) .
793 ', WAN: ' . ( $wgMainWANCache === CACHE_NONE ?
'CACHE_NONE' : $wgMainWANCache ) .
794 ', stash: ' . $wgMainStash .
795 ', message: ' . get_class( $messageMemc ) .
796 ', session: ' . get_class( ObjectCache
::getInstance( $wgSessionCacheType ) )
799 Profiler
::instance()->scopedProfileOut( $ps_misc );
801 // Most of the config is out, some might want to run hooks here.
802 Hooks
::run( 'SetupAfterCache' );
804 $ps_globals = Profiler
::instance()->scopedProfileIn( $fname . '-globals' );
807 * @var Language $wgContLang
808 * @deprecated since 1.32, use the ContentLanguage service directly
810 $wgContLang = MediaWikiServices
::getInstance()->getContentLanguage();
812 // Now that variant lists may be available...
813 $wgRequest->interpolateTitle();
815 if ( !is_object( $wgAuth ) ) {
816 $wgAuth = new MediaWiki\Auth\AuthManagerAuthPlugin
;
817 Hooks
::run( 'AuthPluginSetup', [ &$wgAuth ] );
819 if ( $wgAuth && !$wgAuth instanceof MediaWiki\Auth\AuthManagerAuthPlugin
) {
820 MediaWiki\Auth\AuthManager
::singleton()->forcePrimaryAuthenticationProviders( [
821 new MediaWiki\Auth\
TemporaryPasswordPrimaryAuthenticationProvider( [
822 'authoritative' => false,
824 new MediaWiki\Auth\
AuthPluginPrimaryAuthenticationProvider( $wgAuth ),
825 new MediaWiki\Auth\
LocalPasswordPrimaryAuthenticationProvider( [
826 'authoritative' => true,
828 ], '$wgAuth is ' . get_class( $wgAuth ) );
832 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
833 * session ID (if any) loaded at startup
835 $wgInitialSessionId = null;
836 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
837 // If session.auto_start is there, we can't touch session name
838 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
839 session_name( $wgSessionName ?
: $wgCookiePrefix . '_session' );
842 // Create the SessionManager singleton and set up our session handler,
843 // unless we're specifically asked not to.
844 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
845 MediaWiki\Session\PHPSessionHandler
::install(
846 MediaWiki\Session\SessionManager
::singleton()
850 // Initialize the session
852 $session = MediaWiki\Session\SessionManager
::getGlobalSession();
853 } catch ( OverflowException
$ex ) {
854 if ( isset( $ex->sessionInfos
) && count( $ex->sessionInfos
) >= 2 ) {
855 // The exception is because the request had multiple possible
856 // sessions tied for top priority. Report this to the user.
858 foreach ( $ex->sessionInfos
as $info ) {
859 $list[] = $info->getProvider()->describe( $wgContLang );
861 $list = $wgContLang->listToText( $list );
862 throw new HttpError( 400,
863 Message
::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
867 // Not the one we want, rethrow
871 if ( $session->isPersistent() ) {
872 $wgInitialSessionId = $session->getSessionId();
876 if ( MediaWiki\Session\PHPSessionHandler
::isEnabled() &&
877 ( $session->isPersistent() ||
$session->shouldRememberUser() ) &&
878 session_id() !== $session->getId()
880 // Start the PHP-session for backwards compatibility
881 if ( session_id() !== '' ) {
882 wfDebugLog( 'session', 'PHP session {old_id} was already started, changing to {new_id}', 'all', [
883 'old_id' => session_id(),
884 'new_id' => $session->getId(),
886 session_write_close();
888 session_id( $session->getId() );
894 // Even if we didn't set up a global Session, still install our session
895 // handler unless specifically requested not to.
896 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
897 MediaWiki\Session\PHPSessionHandler
::install(
898 MediaWiki\Session\SessionManager
::singleton()
906 $wgUser = RequestContext
::getMain()->getUser(); // BackCompat
909 * @var Language $wgLang
911 $wgLang = new StubUserLang
;
914 * @var OutputPage $wgOut
916 $wgOut = RequestContext
::getMain()->getOutput(); // BackCompat
919 * @var Parser $wgParser
920 * @deprecated since 1.32, use MediaWikiServices::getParser() instead
922 $wgParser = new StubObject( 'wgParser', function () {
923 return MediaWikiServices
::getInstance()->getParser();
927 * @var Title $wgTitle
931 Profiler
::instance()->scopedProfileOut( $ps_globals );
932 $ps_extensions = Profiler
::instance()->scopedProfileIn( $fname . '-extensions' );
934 // Extension setup functions
935 // Entries should be added to this variable during the inclusion
936 // of the extension file. This allows the extension to perform
937 // any necessary initialisation in the fully initialised environment
938 foreach ( $wgExtensionFunctions as $func ) {
939 call_user_func( $func );
942 // If the session user has a 0 id but a valid name, that means we need to
944 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
945 $sessionUser = MediaWiki\Session\SessionManager
::getGlobalSession()->getUser();
946 if ( $sessionUser->getId() === 0 && User
::isValidUserName( $sessionUser->getName() ) ) {
947 $res = MediaWiki\Auth\AuthManager
::singleton()->autoCreateUser(
949 MediaWiki\Auth\AuthManager
::AUTOCREATE_SOURCE_SESSION
,
952 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Autocreation attempt', [
953 'event' => 'autocreate',
958 unset( $sessionUser );
961 if ( !$wgCommandLineMode ) {
962 Pingback
::schedulePingback();
965 $wgFullyInitialised = true;
967 Profiler
::instance()->scopedProfileOut( $ps_extensions );
968 Profiler
::instance()->scopedProfileOut( $ps_setup );