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";
72 // Assert that composer dependencies were successfully loaded
73 // Purposely no leading \ due to it breaking HHVM RepoAuthorative mode
74 // PHP works fine with both versions
75 // See https://github.com/facebook/hhvm/issues/5833
76 if ( !interface_exists( 'Psr\Log\LoggerInterface' ) ) {
78 'MediaWiki requires the <a href="https://github.com/php-fig/log">PSR-3 logging ' .
79 "library</a> to be present. This library is not embedded directly in MediaWiki's " .
80 "git repository and must be installed separately by the end user.\n\n" .
81 'Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git' .
82 '#Fetch_external_libraries">mediawiki.org</a> for help on installing ' .
83 'the required components.'
86 trigger_error( $message, E_USER_ERROR
);
90 // Install a header callback
91 MediaWiki\HeaderCallback
::register();
94 * Load LocalSettings.php
97 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
98 call_user_func( MW_CONFIG_CALLBACK
);
100 if ( !defined( 'MW_CONFIG_FILE' ) ) {
101 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
103 require_once MW_CONFIG_FILE
;
107 * Customization point after all loading (constants, functions, classes,
108 * DefaultSettings, LocalSettings). Specifically, this is before usage of
109 * settings, before instantiation of Profiler (and other singletons), and
110 * before any setup functions or hooks run.
113 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
114 call_user_func( MW_SETUP_CALLBACK
);
121 $fname = 'Setup.php';
122 $ps_setup = Profiler
::instance()->scopedProfileIn( $fname );
124 // Load queued extensions
125 ExtensionRegistry
::getInstance()->loadFromQueue();
126 // Don't let any other extensions load
127 ExtensionRegistry
::getInstance()->finish();
129 mb_internal_encoding( 'UTF-8' );
131 // Set the configured locale on all requests for consisteny
132 putenv( "LC_ALL=$wgShellLocale" );
133 setlocale( LC_ALL
, $wgShellLocale );
135 // Set various default paths sensibly...
136 $ps_default = Profiler
::instance()->scopedProfileIn( $fname . '-defaults' );
138 if ( $wgScript === false ) {
139 $wgScript = "$wgScriptPath/index.php";
141 if ( $wgLoadScript === false ) {
142 $wgLoadScript = "$wgScriptPath/load.php";
145 if ( $wgArticlePath === false ) {
146 if ( $wgUsePathInfo ) {
147 $wgArticlePath = "$wgScript/$1";
149 $wgArticlePath = "$wgScript?title=$1";
153 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
154 // 'view' is assumed the default action path everywhere in the code
155 // but is rarely filled in $wgActionPaths
156 $wgActionPaths['view'] = $wgArticlePath;
159 if ( $wgResourceBasePath === null ) {
160 $wgResourceBasePath = $wgScriptPath;
162 if ( $wgStylePath === false ) {
163 $wgStylePath = "$wgResourceBasePath/skins";
165 if ( $wgLocalStylePath === false ) {
166 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
167 $wgLocalStylePath = "$wgScriptPath/skins";
169 if ( $wgExtensionAssetsPath === false ) {
170 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
173 if ( $wgLogo === false ) {
174 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
177 if ( $wgUploadPath === false ) {
178 $wgUploadPath = "$wgScriptPath/images";
180 if ( $wgUploadDirectory === false ) {
181 $wgUploadDirectory = "$IP/images";
183 if ( $wgReadOnlyFile === false ) {
184 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
186 if ( $wgFileCacheDirectory === false ) {
187 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
189 if ( $wgDeletedDirectory === false ) {
190 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
193 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
194 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
197 // Fix path to icon images after they were moved in 1.24
198 if ( $wgRightsIcon ) {
199 $wgRightsIcon = str_replace(
200 "{$wgStylePath}/common/images/",
201 "{$wgResourceBasePath}/resources/assets/licenses/",
206 if ( isset( $wgFooterIcons['copyright']['copyright'] )
207 && $wgFooterIcons['copyright']['copyright'] === []
209 if ( $wgRightsIcon ||
$wgRightsText ) {
210 $wgFooterIcons['copyright']['copyright'] = [
211 'url' => $wgRightsUrl,
212 'src' => $wgRightsIcon,
213 'alt' => $wgRightsText,
218 if ( isset( $wgFooterIcons['poweredby'] )
219 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
220 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
222 $wgFooterIcons['poweredby']['mediawiki']['src'] =
223 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
224 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
225 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
226 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
230 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
231 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
233 * Note that this is the definition of editinterface and it can be granted to
234 * all users if desired.
236 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
239 * The canonical names of namespaces 6 and 7 are, as of v1.14, "File"
240 * and "File_talk". The old names "Image" and "Image_talk" are
241 * retained as aliases for backwards compatibility.
243 $wgNamespaceAliases['Image'] = NS_FILE
;
244 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
247 * Initialise $wgLockManagers to include basic FS version
249 $wgLockManagers[] = [
250 'name' => 'fsLockManager',
251 'class' => FSLockManager
::class,
252 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
254 $wgLockManagers[] = [
255 'name' => 'nullLockManager',
256 'class' => NullLockManager
::class,
260 * Default parameters for the "<gallery>" tag.
261 * @see DefaultSettings.php for description of the fields.
263 $wgGalleryOptions +
= [
266 'imageHeight' => 120,
267 'captionLength' => true,
269 'showDimensions' => true,
270 'mode' => 'traditional',
274 * Shortcuts for $wgLocalFileRepo
276 if ( !$wgLocalFileRepo ) {
278 'class' => LocalRepo
::class,
280 'directory' => $wgUploadDirectory,
281 'scriptDirUrl' => $wgScriptPath,
282 'url' => $wgUploadBaseUrl ?
$wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
283 'hashLevels' => $wgHashedUploadDirectory ?
2 : 0,
284 'thumbScriptUrl' => $wgThumbnailScriptPath,
285 'transformVia404' => !$wgGenerateThumbnailOnParse,
286 'deletedDir' => $wgDeletedDirectory,
287 'deletedHashLevels' => $wgHashedUploadDirectory ?
3 : 0
291 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
292 // Create a default FileBackend name.
293 // FileBackendGroup will register a default, if absent from $wgFileBackends.
294 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
298 * Shortcuts for $wgForeignFileRepos
300 if ( $wgUseSharedUploads ) {
301 if ( $wgSharedUploadDBname ) {
302 $wgForeignFileRepos[] = [
303 'class' => ForeignDBRepo
::class,
305 'directory' => $wgSharedUploadDirectory,
306 'url' => $wgSharedUploadPath,
307 'hashLevels' => $wgHashedSharedUploadDirectory ?
2 : 0,
308 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
309 'transformVia404' => !$wgGenerateThumbnailOnParse,
310 'dbType' => $wgDBtype,
311 'dbServer' => $wgDBserver,
312 'dbUser' => $wgDBuser,
313 'dbPassword' => $wgDBpassword,
314 'dbName' => $wgSharedUploadDBname,
315 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG
: 0 ) | DBO_DEFAULT
,
316 'tablePrefix' => $wgSharedUploadDBprefix,
317 'hasSharedCache' => $wgCacheSharedUploads,
318 'descBaseUrl' => $wgRepositoryBaseUrl,
319 'fetchDescription' => $wgFetchCommonsDescriptions,
322 $wgForeignFileRepos[] = [
323 'class' => FileRepo
::class,
325 'directory' => $wgSharedUploadDirectory,
326 'url' => $wgSharedUploadPath,
327 'hashLevels' => $wgHashedSharedUploadDirectory ?
2 : 0,
328 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
329 'transformVia404' => !$wgGenerateThumbnailOnParse,
330 'descBaseUrl' => $wgRepositoryBaseUrl,
331 'fetchDescription' => $wgFetchCommonsDescriptions,
335 if ( $wgUseInstantCommons ) {
336 $wgForeignFileRepos[] = [
337 'class' => ForeignAPIRepo
::class,
338 'name' => 'wikimediacommons',
339 'apibase' => 'https://commons.wikimedia.org/w/api.php',
340 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
341 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
343 'transformVia404' => true,
344 'fetchDescription' => true,
345 'descriptionCacheExpiry' => 43200,
346 'apiThumbCacheExpiry' => 0,
349 foreach ( $wgForeignFileRepos as &$repo ) {
350 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo
::class ) {
351 $repo['directory'] = $wgUploadDirectory; // b/c
353 if ( !isset( $repo['backend'] ) ) {
354 $repo['backend'] = $repo['name'] . '-backend';
357 unset( $repo ); // no global pollution; destroy reference
359 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
360 if ( $wgRCFilterByAge ) {
361 // Trim down $wgRCLinkDays so that it only lists links which are valid
362 // as determined by $wgRCMaxAge.
363 // Note that we allow 1 link higher than the max for things like 56 days but a 60 day link.
364 sort( $wgRCLinkDays );
366 foreach ( $wgRCLinkDays as $i => $days ) {
367 if ( $days >= $rcMaxAgeDays ) {
368 array_splice( $wgRCLinkDays, $i +
1 );
373 // Ensure that default user options are not invalid, since that breaks Special:Preferences
374 $wgDefaultUserOptions['rcdays'] = min(
375 $wgDefaultUserOptions['rcdays'],
376 ceil( $rcMaxAgeDays )
378 $wgDefaultUserOptions['watchlistdays'] = min(
379 $wgDefaultUserOptions['watchlistdays'],
380 ceil( $rcMaxAgeDays )
382 unset( $rcMaxAgeDays );
385 $wgSkipSkins[] = $wgSkipSkin;
388 $wgSkipSkins[] = 'fallback';
389 $wgSkipSkins[] = 'apioutput';
391 if ( $wgLocalInterwiki ) {
392 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
395 // Set default shared prefix
396 if ( $wgSharedPrefix === false ) {
397 $wgSharedPrefix = $wgDBprefix;
400 // Set default shared schema
401 if ( $wgSharedSchema === false ) {
402 $wgSharedSchema = $wgDBmwschema;
405 if ( !$wgCookiePrefix ) {
406 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
407 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
408 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
409 $wgCookiePrefix = $wgSharedDB;
410 } elseif ( $wgDBprefix ) {
411 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
413 $wgCookiePrefix = $wgDBname;
416 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
418 if ( $wgEnableEmail ) {
419 $wgUseEnotif = $wgEnotifUserTalk ||
$wgEnotifWatchlist;
421 // Disable all other email settings automatically if $wgEnableEmail
422 // is set to false. - T65678
423 $wgAllowHTMLEmail = false;
424 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
425 $wgEnableUserEmail = false;
426 $wgEnotifFromEditor = false;
427 $wgEnotifImpersonal = false;
428 $wgEnotifMaxRecips = 0;
429 $wgEnotifMinorEdits = false;
430 $wgEnotifRevealEditorAddress = false;
431 $wgEnotifUseRealName = false;
432 $wgEnotifUserTalk = false;
433 $wgEnotifWatchlist = false;
434 unset( $wgGroupPermissions['user']['sendemail'] );
435 $wgUseEnotif = false;
436 $wgUserEmailUseReplyTo = false;
437 $wgUsersNotifiedOnAllChanges = [];
440 if ( $wgMetaNamespace === false ) {
441 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
444 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
445 if ( $wgResourceLoaderMaxQueryLength === false ) {
446 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
447 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
448 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
450 $wgResourceLoaderMaxQueryLength = 2000;
452 unset( $suhosinMaxValueLength );
455 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
457 $wgMinUploadChunkSize = min(
458 $wgMinUploadChunkSize,
459 UploadBase
::getMaxUploadSize( 'file' ),
460 UploadBase
::getMaxPhpUploadSize(),
461 ( wfShorthandToInteger(
462 ini_get( 'post_max_size' ) ?
: ini_get( 'hhvm.server.max_post_size' ),
464 ) ?
: PHP_INT_MAX
) - 1024 // Leave some room for other POST parameters
468 * Definitions of the NS_ constants are in Defines.php
471 $wgCanonicalNamespaceNames = [
473 NS_SPECIAL
=> 'Special',
476 NS_USER_TALK
=> 'User_talk',
477 NS_PROJECT
=> 'Project',
478 NS_PROJECT_TALK
=> 'Project_talk',
480 NS_FILE_TALK
=> 'File_talk',
481 NS_MEDIAWIKI
=> 'MediaWiki',
482 NS_MEDIAWIKI_TALK
=> 'MediaWiki_talk',
483 NS_TEMPLATE
=> 'Template',
484 NS_TEMPLATE_TALK
=> 'Template_talk',
486 NS_HELP_TALK
=> 'Help_talk',
487 NS_CATEGORY
=> 'Category',
488 NS_CATEGORY_TALK
=> 'Category_talk',
492 if ( is_array( $wgExtraNamespaces ) ) {
493 $wgCanonicalNamespaceNames = $wgCanonicalNamespaceNames +
$wgExtraNamespaces;
496 // Hard-deprecate setting $wgDummyLanguageCodes in LocalSettings.php
497 if ( count( $wgDummyLanguageCodes ) !== 0 ) {
498 wfDeprecated( '$wgDummyLanguageCodes', '1.29' );
500 // Merge in the legacy language codes, incorporating overrides from the config
501 $wgDummyLanguageCodes +
= [
502 // Internal language codes of the private-use area which get mapped to
504 'qqq' => 'qqq', // Used for message documentation
505 'qqx' => 'qqx', // Used for viewing message keys
506 ] +
$wgExtraLanguageCodes + LanguageCode
::getDeprecatedCodeMapping();
507 // Merge in (inverted) BCP 47 mappings
508 foreach ( LanguageCode
::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
509 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
510 if ( !isset( $wgDummyLanguageCodes[$bcp47] ) ) {
511 $wgDummyLanguageCodes[$bcp47] = $wgDummyLanguageCodes[$code] ??
$code;
515 // These are now the same, always
516 // To determine the user language, use $wgLang->getCode()
517 $wgContLanguageCode = $wgLanguageCode;
519 // Easy to forget to falsify $wgDebugToolbar for static caches.
520 // If file cache or CDN cache is on, just disable this (DWIMD).
521 if ( $wgUseFileCache ||
$wgUseSquid ) {
522 $wgDebugToolbar = false;
525 // We always output HTML5 since 1.22, overriding these is no longer supported
526 // we set them here for extensions that depend on its value.
528 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
529 $wgJsMimeType = 'text/javascript';
531 // Blacklisted file extensions shouldn't appear on the "allowed" list
532 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
534 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
535 Wikimedia\
suppressWarnings();
536 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
537 Wikimedia\restoreWarnings
();
540 if ( $wgNewUserLog ) {
541 // Add new user log type
542 $wgLogTypes[] = 'newusers';
543 $wgLogNames['newusers'] = 'newuserlogpage';
544 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
545 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter
::class;
546 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter
::class;
547 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter
::class;
548 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter
::class;
549 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter
::class;
552 if ( $wgPageCreationLog ) {
553 // Add page creation log type
554 $wgLogTypes[] = 'create';
555 $wgLogActionsHandlers['create/create'] = LogFormatter
::class;
558 if ( $wgPageLanguageUseDB ) {
559 $wgLogTypes[] = 'pagelang';
560 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter
::class;
563 if ( $wgCookieSecure === 'detect' ) {
564 $wgCookieSecure = ( WebRequest
::detectProtocol() === 'https' );
567 if ( $wgProfileOnly ) {
568 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
569 $wgDebugLogFile = '';
572 // Backwards compatibility with old password limits
573 if ( $wgMinimalPasswordLength !== false ) {
574 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
577 if ( $wgMaximalPasswordLength !== false ) {
578 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
581 // Backwards compatibility warning
582 if ( !$wgSessionsInObjectCache ) {
583 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
584 if ( $wgSessionHandler ) {
585 wfDeprecated( '$wgSessionsHandler', '1.27' );
587 $cacheType = get_class( ObjectCache
::getInstance( $wgSessionCacheType ) );
590 "Session data will be stored in \"$cacheType\" cache with " .
591 "expiry $wgObjectCacheSessionExpiry seconds"
594 $wgSessionsInObjectCache = true;
596 if ( $wgPHPSessionHandling !== 'enable' &&
597 $wgPHPSessionHandling !== 'warn' &&
598 $wgPHPSessionHandling !== 'disable'
600 $wgPHPSessionHandling = 'warn';
602 if ( defined( 'MW_NO_SESSION' ) ) {
603 // If the entry point wants no session, force 'disable' here unless they
604 // specifically set it to the (undocumented) 'warn'.
605 $wgPHPSessionHandling = MW_NO_SESSION
=== 'warn' ?
'warn' : 'disable';
608 Profiler
::instance()->scopedProfileOut( $ps_default );
610 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
611 // all the memory from logging SQL queries on maintenance scripts
612 global $wgCommandLineMode;
613 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
617 // Reset the global service locator, so any services that have already been created will be
618 // re-created while taking into account any custom settings and extensions.
619 MediaWikiServices
::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
621 if ( $wgSharedDB && $wgSharedTables ) {
622 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
623 MediaWikiServices
::getInstance()->getDBLoadBalancer()->setTableAliases(
627 'dbname' => $wgSharedDB,
628 'schema' => $wgSharedSchema,
629 'prefix' => $wgSharedPrefix
635 // Define a constant that indicates that the bootstrapping of the service locator
637 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
639 MWExceptionHandler
::installHandler();
641 // T48998: Bail out early if $wgArticlePath is non-absolute
642 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
643 if ( $
$varName && !preg_match( '/^(https?:\/\/|\/)/', $
$varName ) ) {
644 throw new FatalError(
645 "If you use a relative URL for \$$varName, it must start " .
646 'with a slash (<code>/</code>).<br><br>See ' .
647 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
648 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
653 $ps_default2 = Profiler
::instance()->scopedProfileIn( $fname . '-defaults2' );
655 if ( $wgCanonicalServer === false ) {
656 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP
);
660 $serverParts = wfParseUrl( $wgCanonicalServer );
661 if ( $wgServerName !== false ) {
662 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
663 . 'not customized. Overwriting $wgServerName.' );
665 $wgServerName = $serverParts['host'];
666 unset( $serverParts );
668 // Set defaults for configuration variables
669 // that are derived from the server name by default
670 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
671 if ( !$wgEmergencyContact ) {
672 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
674 if ( !$wgPasswordSender ) {
675 $wgPasswordSender = 'apache@' . $wgServerName;
677 if ( !$wgNoReplyAddress ) {
678 $wgNoReplyAddress = $wgPasswordSender;
681 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
682 $wgSecureLogin = false;
683 wfWarn( 'Secure login was enabled on a server that only supports '
684 . 'HTTP or HTTPS. Disabling secure login.' );
687 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
689 // Now that GlobalFunctions is loaded, set defaults that depend on it.
690 if ( $wgTmpDirectory === false ) {
691 $wgTmpDirectory = wfTempDir();
694 // We don't use counters anymore. Left here for extensions still
695 // expecting this to exist. Should be removed sometime 1.26 or later.
696 if ( !isset( $wgDisableCounters ) ) {
697 $wgDisableCounters = true;
700 if ( $wgMainWANCache === false ) {
701 // Setup a WAN cache from $wgMainCacheType with no relayer.
702 // Sites using multiple datacenters can configure a relayer.
703 $wgMainWANCache = 'mediawiki-main-default';
704 $wgWANObjectCaches[$wgMainWANCache] = [
705 'class' => WANObjectCache
::class,
706 'cacheId' => $wgMainCacheType,
707 'channels' => [ 'purge' => 'wancache-main-default-purge' ]
711 Profiler
::instance()->scopedProfileOut( $ps_default2 );
713 $ps_misc = Profiler
::instance()->scopedProfileIn( $fname . '-misc' );
715 // Raise the memory limit if it's too low
719 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
720 * that happens whenever you use a date function without the timezone being
721 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
723 if ( is_null( $wgLocaltimezone ) ) {
724 Wikimedia\
suppressWarnings();
725 $wgLocaltimezone = date_default_timezone_get();
726 Wikimedia\restoreWarnings
();
729 date_default_timezone_set( $wgLocaltimezone );
730 if ( is_null( $wgLocalTZoffset ) ) {
731 $wgLocalTZoffset = date( 'Z' ) / 60;
733 // The part after the System| is ignored, but rest of MW fills it
734 // out as the local offset.
735 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
737 if ( !$wgDBerrorLogTZ ) {
738 $wgDBerrorLogTZ = $wgLocaltimezone;
741 // Initialize the request object in $wgRequest
742 $wgRequest = RequestContext
::getMain()->getRequest(); // BackCompat
743 // Set user IP/agent information for agent session consistency purposes
744 $cpPosInfo = LBFactory
::getCPInfoFromCookieValue(
745 // The cookie has no prefix and is set by MediaWiki::preOutputCommit()
746 $wgRequest->getCookie( 'cpPosIndex', '' ),
747 // Mitigate broken client-side cookie expiration handling (T190082)
748 time() - ChronologyProtector
::POSITION_COOKIE_TTL
750 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
751 'IPAddress' => $wgRequest->getIP(),
752 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
753 'ChronologyProtection' => $wgRequest->getHeader( 'ChronologyProtection' ),
754 'ChronologyPositionIndex' => $wgRequest->getInt( 'cpPosIndex', $cpPosInfo['index'] ),
755 'ChronologyClientId' => $cpPosInfo['clientId']
758 // Make sure that object caching does not undermine the ChronologyProtector improvements
759 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
760 // The user is pinned to the primary DC, meaning that they made recent changes which should
761 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
762 // they use a blind TTL and could be stale if an object changes twice in a short time span.
763 MediaWikiServices
::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
766 // Useful debug output
767 if ( $wgCommandLineMode ) {
768 wfDebug( "\n\nStart command line script $self\n" );
770 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
772 if ( $wgDebugPrintHttpHeaders ) {
773 $debug .= "HTTP HEADERS:\n";
775 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
776 $debug .= "$name: $value\n";
782 $wgMemc = ObjectCache
::getLocalClusterInstance();
783 $messageMemc = wfGetMessageCacheStorage();
785 wfDebugLog( 'caches',
786 'cluster: ' . get_class( $wgMemc ) .
787 ', WAN: ' . ( $wgMainWANCache === CACHE_NONE ?
'CACHE_NONE' : $wgMainWANCache ) .
788 ', stash: ' . $wgMainStash .
789 ', message: ' . get_class( $messageMemc ) .
790 ', session: ' . get_class( ObjectCache
::getInstance( $wgSessionCacheType ) )
793 Profiler
::instance()->scopedProfileOut( $ps_misc );
795 // Most of the config is out, some might want to run hooks here.
796 Hooks
::run( 'SetupAfterCache' );
798 $ps_globals = Profiler
::instance()->scopedProfileIn( $fname . '-globals' );
801 * @var Language $wgContLang
802 * @deprecated since 1.32, use the ContentLanguage service directly
804 $wgContLang = MediaWikiServices
::getInstance()->getContentLanguage();
806 // Now that variant lists may be available...
807 $wgRequest->interpolateTitle();
809 if ( !is_object( $wgAuth ) ) {
810 $wgAuth = new MediaWiki\Auth\AuthManagerAuthPlugin
;
811 Hooks
::run( 'AuthPluginSetup', [ &$wgAuth ] );
813 if ( $wgAuth && !$wgAuth instanceof MediaWiki\Auth\AuthManagerAuthPlugin
) {
814 MediaWiki\Auth\AuthManager
::singleton()->forcePrimaryAuthenticationProviders( [
815 new MediaWiki\Auth\
TemporaryPasswordPrimaryAuthenticationProvider( [
816 'authoritative' => false,
818 new MediaWiki\Auth\
AuthPluginPrimaryAuthenticationProvider( $wgAuth ),
819 new MediaWiki\Auth\
LocalPasswordPrimaryAuthenticationProvider( [
820 'authoritative' => true,
822 ], '$wgAuth is ' . get_class( $wgAuth ) );
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::getParser() instead
916 $wgParser = new StubObject( 'wgParser', function () {
917 return MediaWikiServices
::getInstance()->getParser();
921 * @var Title $wgTitle
925 Profiler
::instance()->scopedProfileOut( $ps_globals );
926 $ps_extensions = Profiler
::instance()->scopedProfileIn( $fname . '-extensions' );
928 // Extension setup functions
929 // Entries should be added to this variable during the inclusion
930 // of the extension file. This allows the extension to perform
931 // any necessary initialisation in the fully initialised environment
932 foreach ( $wgExtensionFunctions as $func ) {
933 call_user_func( $func );
936 // If the session user has a 0 id but a valid name, that means we need to
938 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
939 $sessionUser = MediaWiki\Session\SessionManager
::getGlobalSession()->getUser();
940 if ( $sessionUser->getId() === 0 && User
::isValidUserName( $sessionUser->getName() ) ) {
941 $res = MediaWiki\Auth\AuthManager
::singleton()->autoCreateUser(
943 MediaWiki\Auth\AuthManager
::AUTOCREATE_SOURCE_SESSION
,
946 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Autocreation attempt', [
947 'event' => 'autocreate',
952 unset( $sessionUser );
955 if ( !$wgCommandLineMode ) {
956 Pingback
::schedulePingback();
959 $wgFullyInitialised = true;
961 Profiler
::instance()->scopedProfileOut( $ps_extensions );
962 Profiler
::instance()->scopedProfileOut( $ps_setup );