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' ) ) {
39 * Pre-config setup: Before loading LocalSettings.php
42 // Sanity check (T5782, T122807)
43 if ( ini_get( 'mbstring.func_overload' ) ) {
44 die( 'MediaWiki does not support installations where mbstring.func_overload is non-zero.' );
47 // Start the autoloader, so that extensions can derive classes from core files
48 require_once "$IP/includes/AutoLoader.php";
50 // Load up some global defines
51 require_once "$IP/includes/Defines.php";
53 // Load default settings
54 require_once "$IP/includes/DefaultSettings.php";
56 // Load global functions
57 require_once "$IP/includes/GlobalFunctions.php";
59 // Load composer's autoloader if present
60 if ( is_readable( "$IP/vendor/autoload.php" ) ) {
61 require_once "$IP/vendor/autoload.php";
64 // Assert that composer dependencies were successfully loaded
65 // Purposely no leading \ due to it breaking HHVM RepoAuthorative mode
66 // PHP works fine with both versions
67 // See https://github.com/facebook/hhvm/issues/5833
68 if ( !interface_exists( 'Psr\Log\LoggerInterface' ) ) {
70 'MediaWiki requires the <a href="https://github.com/php-fig/log">PSR-3 logging ' .
71 "library</a> to be present. This library is not embedded directly in MediaWiki's " .
72 "git repository and must be installed separately by the end user.\n\n" .
73 'Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git' .
74 '#Fetch_external_libraries">mediawiki.org</a> for help on installing ' .
75 'the required components.'
78 trigger_error( $message, E_USER_ERROR
);
82 // Install a header callback
83 MediaWiki\HeaderCallback
::register();
86 * Load LocalSettings.php
89 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
90 call_user_func( MW_CONFIG_CALLBACK
);
92 if ( !defined( 'MW_CONFIG_FILE' ) ) {
93 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
95 require_once MW_CONFIG_FILE
;
99 * Customization point after all loading (constants, functions, classes,
100 * DefaultSettings, LocalSettings). Specifically, this is before usage of
101 * settings, before instantiation of Profiler (and other singletons), and
102 * before any setup functions or hooks run.
105 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
106 call_user_func( MW_SETUP_CALLBACK
);
113 $fname = 'Setup.php';
114 $ps_setup = Profiler
::instance()->scopedProfileIn( $fname );
116 // Load queued extensions
117 ExtensionRegistry
::getInstance()->loadFromQueue();
118 // Don't let any other extensions load
119 ExtensionRegistry
::getInstance()->finish();
121 // Check to see if we are at the file scope
122 if ( !isset( $wgVersion ) ) {
123 echo "Error, Setup.php must be included from the file scope, after DefaultSettings.php\n";
127 mb_internal_encoding( 'UTF-8' );
129 // Set the configured locale on all requests for consisteny
130 putenv( "LC_ALL=$wgShellLocale" );
131 setlocale( LC_ALL
, $wgShellLocale );
133 // Set various default paths sensibly...
134 $ps_default = Profiler
::instance()->scopedProfileIn( $fname . '-defaults' );
136 if ( $wgScript === false ) {
137 $wgScript = "$wgScriptPath/index.php";
139 if ( $wgLoadScript === false ) {
140 $wgLoadScript = "$wgScriptPath/load.php";
143 if ( $wgArticlePath === false ) {
144 if ( $wgUsePathInfo ) {
145 $wgArticlePath = "$wgScript/$1";
147 $wgArticlePath = "$wgScript?title=$1";
151 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
152 // 'view' is assumed the default action path everywhere in the code
153 // but is rarely filled in $wgActionPaths
154 $wgActionPaths['view'] = $wgArticlePath;
157 if ( $wgResourceBasePath === null ) {
158 $wgResourceBasePath = $wgScriptPath;
160 if ( $wgStylePath === false ) {
161 $wgStylePath = "$wgResourceBasePath/skins";
163 if ( $wgLocalStylePath === false ) {
164 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
165 $wgLocalStylePath = "$wgScriptPath/skins";
167 if ( $wgExtensionAssetsPath === false ) {
168 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
171 if ( $wgLogo === false ) {
172 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
175 if ( $wgUploadPath === false ) {
176 $wgUploadPath = "$wgScriptPath/images";
178 if ( $wgUploadDirectory === false ) {
179 $wgUploadDirectory = "$IP/images";
181 if ( $wgReadOnlyFile === false ) {
182 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
184 if ( $wgFileCacheDirectory === false ) {
185 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
187 if ( $wgDeletedDirectory === false ) {
188 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
191 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
192 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
195 if ( $wgEnableParserCache === false ) {
196 $wgParserCacheType = CACHE_NONE
;
199 // Fix path to icon images after they were moved in 1.24
200 if ( $wgRightsIcon ) {
201 $wgRightsIcon = str_replace(
202 "{$wgStylePath}/common/images/",
203 "{$wgResourceBasePath}/resources/assets/licenses/",
208 if ( isset( $wgFooterIcons['copyright']['copyright'] )
209 && $wgFooterIcons['copyright']['copyright'] === []
211 if ( $wgRightsIcon ||
$wgRightsText ) {
212 $wgFooterIcons['copyright']['copyright'] = [
213 'url' => $wgRightsUrl,
214 'src' => $wgRightsIcon,
215 'alt' => $wgRightsText,
220 if ( isset( $wgFooterIcons['poweredby'] )
221 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
222 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
224 $wgFooterIcons['poweredby']['mediawiki']['src'] =
225 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
226 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
227 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
228 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
232 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
233 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
235 * Note that this is the definition of editinterface and it can be granted to
236 * all users if desired.
238 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
241 * The canonical names of namespaces 6 and 7 are, as of v1.14, "File"
242 * and "File_talk". The old names "Image" and "Image_talk" are
243 * retained as aliases for backwards compatibility.
245 $wgNamespaceAliases['Image'] = NS_FILE
;
246 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
249 * Initialise $wgLockManagers to include basic FS version
251 $wgLockManagers[] = [
252 'name' => 'fsLockManager',
253 'class' => FSLockManager
::class,
254 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
256 $wgLockManagers[] = [
257 'name' => 'nullLockManager',
258 'class' => NullLockManager
::class,
262 * Default parameters for the "<gallery>" tag.
263 * @see DefaultSettings.php for description of the fields.
265 $wgGalleryOptions +
= [
268 'imageHeight' => 120,
269 'captionLength' => true,
271 'showDimensions' => true,
272 'mode' => 'traditional',
276 * Shortcuts for $wgLocalFileRepo
278 if ( !$wgLocalFileRepo ) {
280 'class' => LocalRepo
::class,
282 'directory' => $wgUploadDirectory,
283 'scriptDirUrl' => $wgScriptPath,
284 'url' => $wgUploadBaseUrl ?
$wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
285 'hashLevels' => $wgHashedUploadDirectory ?
2 : 0,
286 'thumbScriptUrl' => $wgThumbnailScriptPath,
287 'transformVia404' => !$wgGenerateThumbnailOnParse,
288 'deletedDir' => $wgDeletedDirectory,
289 'deletedHashLevels' => $wgHashedUploadDirectory ?
3 : 0
293 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
294 // Create a default FileBackend name.
295 // FileBackendGroup will register a default, if absent from $wgFileBackends.
296 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
300 * Shortcuts for $wgForeignFileRepos
302 if ( $wgUseSharedUploads ) {
303 if ( $wgSharedUploadDBname ) {
304 $wgForeignFileRepos[] = [
305 'class' => ForeignDBRepo
::class,
307 'directory' => $wgSharedUploadDirectory,
308 'url' => $wgSharedUploadPath,
309 'hashLevels' => $wgHashedSharedUploadDirectory ?
2 : 0,
310 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
311 'transformVia404' => !$wgGenerateThumbnailOnParse,
312 'dbType' => $wgDBtype,
313 'dbServer' => $wgDBserver,
314 'dbUser' => $wgDBuser,
315 'dbPassword' => $wgDBpassword,
316 'dbName' => $wgSharedUploadDBname,
317 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG
: 0 ) | DBO_DEFAULT
,
318 'tablePrefix' => $wgSharedUploadDBprefix,
319 'hasSharedCache' => $wgCacheSharedUploads,
320 'descBaseUrl' => $wgRepositoryBaseUrl,
321 'fetchDescription' => $wgFetchCommonsDescriptions,
324 $wgForeignFileRepos[] = [
325 'class' => FileRepo
::class,
327 'directory' => $wgSharedUploadDirectory,
328 'url' => $wgSharedUploadPath,
329 'hashLevels' => $wgHashedSharedUploadDirectory ?
2 : 0,
330 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
331 'transformVia404' => !$wgGenerateThumbnailOnParse,
332 'descBaseUrl' => $wgRepositoryBaseUrl,
333 'fetchDescription' => $wgFetchCommonsDescriptions,
337 if ( $wgUseInstantCommons ) {
338 $wgForeignFileRepos[] = [
339 'class' => ForeignAPIRepo
::class,
340 'name' => 'wikimediacommons',
341 'apibase' => 'https://commons.wikimedia.org/w/api.php',
342 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
343 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
345 'transformVia404' => true,
346 'fetchDescription' => true,
347 'descriptionCacheExpiry' => 43200,
348 'apiThumbCacheExpiry' => 0,
351 foreach ( $wgForeignFileRepos as &$repo ) {
352 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo
::class ) {
353 $repo['directory'] = $wgUploadDirectory; // b/c
355 if ( !isset( $repo['backend'] ) ) {
356 $repo['backend'] = $repo['name'] . '-backend';
359 unset( $repo ); // no global pollution; destroy reference
361 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
362 if ( $wgRCFilterByAge ) {
363 // Trim down $wgRCLinkDays so that it only lists links which are valid
364 // as determined by $wgRCMaxAge.
365 // Note that we allow 1 link higher than the max for things like 56 days but a 60 day link.
366 sort( $wgRCLinkDays );
368 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
369 for ( $i = 0; $i < count( $wgRCLinkDays ); $i++
) {
370 if ( $wgRCLinkDays[$i] >= $rcMaxAgeDays ) {
371 $wgRCLinkDays = array_slice( $wgRCLinkDays, 0, $i +
1, false );
376 // Ensure that default user options are not invalid, since that breaks Special:Preferences
377 $wgDefaultUserOptions['rcdays'] = min(
378 $wgDefaultUserOptions['rcdays'],
379 ceil( $rcMaxAgeDays )
381 $wgDefaultUserOptions['watchlistdays'] = min(
382 $wgDefaultUserOptions['watchlistdays'],
383 ceil( $rcMaxAgeDays )
385 unset( $rcMaxAgeDays );
388 $wgSkipSkins[] = $wgSkipSkin;
391 $wgSkipSkins[] = 'fallback';
392 $wgSkipSkins[] = 'apioutput';
394 if ( $wgLocalInterwiki ) {
395 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
398 // Set default shared prefix
399 if ( $wgSharedPrefix === false ) {
400 $wgSharedPrefix = $wgDBprefix;
403 // Set default shared schema
404 if ( $wgSharedSchema === false ) {
405 $wgSharedSchema = $wgDBmwschema;
408 if ( !$wgCookiePrefix ) {
409 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
410 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
411 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
412 $wgCookiePrefix = $wgSharedDB;
413 } elseif ( $wgDBprefix ) {
414 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
416 $wgCookiePrefix = $wgDBname;
419 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
421 if ( $wgEnableEmail ) {
422 $wgUseEnotif = $wgEnotifUserTalk ||
$wgEnotifWatchlist;
424 // Disable all other email settings automatically if $wgEnableEmail
425 // is set to false. - T65678
426 $wgAllowHTMLEmail = false;
427 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
428 $wgEnableUserEmail = false;
429 $wgEnotifFromEditor = false;
430 $wgEnotifImpersonal = false;
431 $wgEnotifMaxRecips = 0;
432 $wgEnotifMinorEdits = false;
433 $wgEnotifRevealEditorAddress = false;
434 $wgEnotifUseRealName = false;
435 $wgEnotifUserTalk = false;
436 $wgEnotifWatchlist = false;
437 unset( $wgGroupPermissions['user']['sendemail'] );
438 $wgUseEnotif = false;
439 $wgUserEmailUseReplyTo = false;
440 $wgUsersNotifiedOnAllChanges = [];
443 if ( $wgMetaNamespace === false ) {
444 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
447 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
448 if ( $wgResourceLoaderMaxQueryLength === false ) {
449 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
450 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
451 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
453 $wgResourceLoaderMaxQueryLength = 2000;
455 unset( $suhosinMaxValueLength );
458 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
460 $wgMinUploadChunkSize = min(
461 $wgMinUploadChunkSize,
462 UploadBase
::getMaxUploadSize( 'file' ),
463 UploadBase
::getMaxPhpUploadSize(),
464 ( wfShorthandToInteger(
465 ini_get( 'post_max_size' ) ?
: ini_get( 'hhvm.server.max_post_size' ),
467 ) ?
: PHP_INT_MAX
) - 1024 // Leave some room for other POST parameters
471 * Definitions of the NS_ constants are in Defines.php
474 $wgCanonicalNamespaceNames = [
476 NS_SPECIAL
=> 'Special',
479 NS_USER_TALK
=> 'User_talk',
480 NS_PROJECT
=> 'Project',
481 NS_PROJECT_TALK
=> 'Project_talk',
483 NS_FILE_TALK
=> 'File_talk',
484 NS_MEDIAWIKI
=> 'MediaWiki',
485 NS_MEDIAWIKI_TALK
=> 'MediaWiki_talk',
486 NS_TEMPLATE
=> 'Template',
487 NS_TEMPLATE_TALK
=> 'Template_talk',
489 NS_HELP_TALK
=> 'Help_talk',
490 NS_CATEGORY
=> 'Category',
491 NS_CATEGORY_TALK
=> 'Category_talk',
495 if ( is_array( $wgExtraNamespaces ) ) {
496 $wgCanonicalNamespaceNames = $wgCanonicalNamespaceNames +
$wgExtraNamespaces;
499 // Merge in the legacy language codes, incorporating overrides from the config
500 $wgDummyLanguageCodes +
= [
501 'qqq' => 'qqq', // Used for message documentation
502 'qqx' => 'qqx', // Used for viewing message keys
503 ] +
$wgExtraLanguageCodes + LanguageCode
::getDeprecatedCodeMapping();
505 // These are now the same, always
506 // To determine the user language, use $wgLang->getCode()
507 $wgContLanguageCode = $wgLanguageCode;
509 // Easy to forget to falsify $wgDebugToolbar for static caches.
510 // If file cache or CDN cache is on, just disable this (DWIMD).
511 if ( $wgUseFileCache ||
$wgUseSquid ) {
512 $wgDebugToolbar = false;
515 // We always output HTML5 since 1.22, overriding these is no longer supported
516 // we set them here for extensions that depend on its value.
518 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
519 $wgJsMimeType = 'text/javascript';
521 // Blacklisted file extensions shouldn't appear on the "allowed" list
522 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
524 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
525 Wikimedia\
suppressWarnings();
526 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
527 Wikimedia\restoreWarnings
();
530 if ( $wgNewUserLog ) {
531 // Add new user log type
532 $wgLogTypes[] = 'newusers';
533 $wgLogNames['newusers'] = 'newuserlogpage';
534 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
535 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter
::class;
536 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter
::class;
537 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter
::class;
538 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter
::class;
539 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter
::class;
542 if ( $wgPageCreationLog ) {
543 // Add page creation log type
544 $wgLogTypes[] = 'create';
545 $wgLogActionsHandlers['create/create'] = LogFormatter
::class;
548 if ( $wgPageLanguageUseDB ) {
549 $wgLogTypes[] = 'pagelang';
550 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter
::class;
553 if ( $wgCookieSecure === 'detect' ) {
554 $wgCookieSecure = ( WebRequest
::detectProtocol() === 'https' );
557 if ( $wgProfileOnly ) {
558 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
559 $wgDebugLogFile = '';
562 // Backwards compatibility with old password limits
563 if ( $wgMinimalPasswordLength !== false ) {
564 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
567 if ( $wgMaximalPasswordLength !== false ) {
568 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
571 // Backwards compatibility warning
572 if ( !$wgSessionsInObjectCache ) {
573 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
574 if ( $wgSessionHandler ) {
575 wfDeprecated( '$wgSessionsHandler', '1.27' );
577 $cacheType = get_class( ObjectCache
::getInstance( $wgSessionCacheType ) );
580 "Session data will be stored in \"$cacheType\" cache with " .
581 "expiry $wgObjectCacheSessionExpiry seconds"
584 $wgSessionsInObjectCache = true;
586 if ( $wgPHPSessionHandling !== 'enable' &&
587 $wgPHPSessionHandling !== 'warn' &&
588 $wgPHPSessionHandling !== 'disable'
590 $wgPHPSessionHandling = 'warn';
592 if ( defined( 'MW_NO_SESSION' ) ) {
593 // If the entry point wants no session, force 'disable' here unless they
594 // specifically set it to the (undocumented) 'warn'.
595 $wgPHPSessionHandling = MW_NO_SESSION
=== 'warn' ?
'warn' : 'disable';
598 Profiler
::instance()->scopedProfileOut( $ps_default );
600 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
601 // all the memory from logging SQL queries on maintenance scripts
602 global $wgCommandLineMode;
603 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
607 // Reset the global service locator, so any services that have already been created will be
608 // re-created while taking into account any custom settings and extensions.
609 MediaWikiServices
::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
611 if ( $wgSharedDB && $wgSharedTables ) {
612 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
613 MediaWikiServices
::getInstance()->getDBLoadBalancer()->setTableAliases(
617 'dbname' => $wgSharedDB,
618 'schema' => $wgSharedSchema,
619 'prefix' => $wgSharedPrefix
625 // Define a constant that indicates that the bootstrapping of the service locator
627 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
629 MWExceptionHandler
::installHandler();
631 // T48998: Bail out early if $wgArticlePath is non-absolute
632 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
633 if ( $
$varName && !preg_match( '/^(https?:\/\/|\/)/', $
$varName ) ) {
634 throw new FatalError(
635 "If you use a relative URL for \$$varName, it must start " .
636 'with a slash (<code>/</code>).<br><br>See ' .
637 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
638 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
643 $ps_default2 = Profiler
::instance()->scopedProfileIn( $fname . '-defaults2' );
645 if ( $wgCanonicalServer === false ) {
646 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP
);
650 $serverParts = wfParseUrl( $wgCanonicalServer );
651 if ( $wgServerName !== false ) {
652 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
653 . 'not customized. Overwriting $wgServerName.' );
655 $wgServerName = $serverParts['host'];
656 unset( $serverParts );
658 // Set defaults for configuration variables
659 // that are derived from the server name by default
660 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
661 if ( !$wgEmergencyContact ) {
662 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
664 if ( !$wgPasswordSender ) {
665 $wgPasswordSender = 'apache@' . $wgServerName;
667 if ( !$wgNoReplyAddress ) {
668 $wgNoReplyAddress = $wgPasswordSender;
671 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
672 $wgSecureLogin = false;
673 wfWarn( 'Secure login was enabled on a server that only supports '
674 . 'HTTP or HTTPS. Disabling secure login.' );
677 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
679 // Now that GlobalFunctions is loaded, set defaults that depend on it.
680 if ( $wgTmpDirectory === false ) {
681 $wgTmpDirectory = wfTempDir();
684 // We don't use counters anymore. Left here for extensions still
685 // expecting this to exist. Should be removed sometime 1.26 or later.
686 if ( !isset( $wgDisableCounters ) ) {
687 $wgDisableCounters = true;
690 if ( $wgMainWANCache === false ) {
691 // Setup a WAN cache from $wgMainCacheType with no relayer.
692 // Sites using multiple datacenters can configure a relayer.
693 $wgMainWANCache = 'mediawiki-main-default';
694 $wgWANObjectCaches[$wgMainWANCache] = [
695 'class' => WANObjectCache
::class,
696 'cacheId' => $wgMainCacheType,
697 'channels' => [ 'purge' => 'wancache-main-default-purge' ]
701 Profiler
::instance()->scopedProfileOut( $ps_default2 );
703 $ps_misc = Profiler
::instance()->scopedProfileIn( $fname . '-misc' );
705 // Raise the memory limit if it's too low
709 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
710 * that happens whenever you use a date function without the timezone being
711 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
713 if ( is_null( $wgLocaltimezone ) ) {
714 Wikimedia\
suppressWarnings();
715 $wgLocaltimezone = date_default_timezone_get();
716 Wikimedia\restoreWarnings
();
719 date_default_timezone_set( $wgLocaltimezone );
720 if ( is_null( $wgLocalTZoffset ) ) {
721 $wgLocalTZoffset = date( 'Z' ) / 60;
723 // The part after the System| is ignored, but rest of MW fills it
724 // out as the local offset.
725 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
727 if ( !$wgDBerrorLogTZ ) {
728 $wgDBerrorLogTZ = $wgLocaltimezone;
731 // Initialize the request object in $wgRequest
732 $wgRequest = RequestContext
::getMain()->getRequest(); // BackCompat
733 // Set user IP/agent information for agent session consistency purposes
734 $cpPosInfo = LBFactory
::getCPInfoFromCookieValue(
735 // The cookie has no prefix and is set by MediaWiki::preOutputCommit()
736 $wgRequest->getCookie( 'cpPosIndex', '' ),
737 // Mitigate broken client-side cookie expiration handling (T190082)
738 time() - ChronologyProtector
::POSITION_COOKIE_TTL
740 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
741 'IPAddress' => $wgRequest->getIP(),
742 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
743 'ChronologyProtection' => $wgRequest->getHeader( 'ChronologyProtection' ),
744 'ChronologyPositionIndex' => $wgRequest->getInt( 'cpPosIndex', $cpPosInfo['index'] ),
745 'ChronologyClientId' => $cpPosInfo['clientId']
748 // Make sure that object caching does not undermine the ChronologyProtector improvements
749 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
750 // The user is pinned to the primary DC, meaning that they made recent changes which should
751 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
752 // they use a blind TTL and could be stale if an object changes twice in a short time span.
753 MediaWikiServices
::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
756 // Useful debug output
757 if ( $wgCommandLineMode ) {
758 wfDebug( "\n\nStart command line script $self\n" );
760 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
762 if ( $wgDebugPrintHttpHeaders ) {
763 $debug .= "HTTP HEADERS:\n";
765 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
766 $debug .= "$name: $value\n";
772 $wgMemc = ObjectCache
::getLocalClusterInstance();
773 $messageMemc = wfGetMessageCacheStorage();
775 wfDebugLog( 'caches',
776 'cluster: ' . get_class( $wgMemc ) .
777 ', WAN: ' . ( $wgMainWANCache === CACHE_NONE ?
'CACHE_NONE' : $wgMainWANCache ) .
778 ', stash: ' . $wgMainStash .
779 ', message: ' . get_class( $messageMemc ) .
780 ', session: ' . get_class( ObjectCache
::getInstance( $wgSessionCacheType ) )
783 Profiler
::instance()->scopedProfileOut( $ps_misc );
785 // Most of the config is out, some might want to run hooks here.
786 Hooks
::run( 'SetupAfterCache' );
788 $ps_globals = Profiler
::instance()->scopedProfileIn( $fname . '-globals' );
791 * @var Language $wgContLang
792 * @deprecated since 1.32, use the ContentLanguage service directly
794 $wgContLang = MediaWikiServices
::getInstance()->getContentLanguage();
796 // Now that variant lists may be available...
797 $wgRequest->interpolateTitle();
799 if ( !is_object( $wgAuth ) ) {
800 $wgAuth = new MediaWiki\Auth\AuthManagerAuthPlugin
;
801 Hooks
::run( 'AuthPluginSetup', [ &$wgAuth ] );
803 if ( $wgAuth && !$wgAuth instanceof MediaWiki\Auth\AuthManagerAuthPlugin
) {
804 MediaWiki\Auth\AuthManager
::singleton()->forcePrimaryAuthenticationProviders( [
805 new MediaWiki\Auth\
TemporaryPasswordPrimaryAuthenticationProvider( [
806 'authoritative' => false,
808 new MediaWiki\Auth\
AuthPluginPrimaryAuthenticationProvider( $wgAuth ),
809 new MediaWiki\Auth\
LocalPasswordPrimaryAuthenticationProvider( [
810 'authoritative' => true,
812 ], '$wgAuth is ' . get_class( $wgAuth ) );
816 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
817 * session ID (if any) loaded at startup
819 $wgInitialSessionId = null;
820 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
821 // If session.auto_start is there, we can't touch session name
822 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
823 session_name( $wgSessionName ?
: $wgCookiePrefix . '_session' );
826 // Create the SessionManager singleton and set up our session handler,
827 // unless we're specifically asked not to.
828 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
829 MediaWiki\Session\PHPSessionHandler
::install(
830 MediaWiki\Session\SessionManager
::singleton()
834 // Initialize the session
836 $session = MediaWiki\Session\SessionManager
::getGlobalSession();
837 } catch ( OverflowException
$ex ) {
838 if ( isset( $ex->sessionInfos
) && count( $ex->sessionInfos
) >= 2 ) {
839 // The exception is because the request had multiple possible
840 // sessions tied for top priority. Report this to the user.
842 foreach ( $ex->sessionInfos
as $info ) {
843 $list[] = $info->getProvider()->describe( $wgContLang );
845 $list = $wgContLang->listToText( $list );
846 throw new HttpError( 400,
847 Message
::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
851 // Not the one we want, rethrow
855 if ( $session->isPersistent() ) {
856 $wgInitialSessionId = $session->getSessionId();
860 if ( MediaWiki\Session\PHPSessionHandler
::isEnabled() &&
861 ( $session->isPersistent() ||
$session->shouldRememberUser() )
863 // Start the PHP-session for backwards compatibility
864 session_id( $session->getId() );
865 Wikimedia\
quietCall( 'session_start' );
870 // Even if we didn't set up a global Session, still install our session
871 // handler unless specifically requested not to.
872 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
873 MediaWiki\Session\PHPSessionHandler
::install(
874 MediaWiki\Session\SessionManager
::singleton()
882 $wgUser = RequestContext
::getMain()->getUser(); // BackCompat
885 * @var Language $wgLang
887 $wgLang = new StubUserLang
;
890 * @var OutputPage $wgOut
892 $wgOut = RequestContext
::getMain()->getOutput(); // BackCompat
895 * @var Parser $wgParser
896 * @deprecated since 1.32, use MediaWikiServices::getParser() instead
898 $wgParser = new StubObject( 'wgParser', function () {
899 return MediaWikiServices
::getInstance()->getParser();
903 * @var Title $wgTitle
907 Profiler
::instance()->scopedProfileOut( $ps_globals );
908 $ps_extensions = Profiler
::instance()->scopedProfileIn( $fname . '-extensions' );
910 // Extension setup functions
911 // Entries should be added to this variable during the inclusion
912 // of the extension file. This allows the extension to perform
913 // any necessary initialisation in the fully initialised environment
914 foreach ( $wgExtensionFunctions as $func ) {
915 call_user_func( $func );
918 // If the session user has a 0 id but a valid name, that means we need to
920 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
921 $sessionUser = MediaWiki\Session\SessionManager
::getGlobalSession()->getUser();
922 if ( $sessionUser->getId() === 0 && User
::isValidUserName( $sessionUser->getName() ) ) {
923 $res = MediaWiki\Auth\AuthManager
::singleton()->autoCreateUser(
925 MediaWiki\Auth\AuthManager
::AUTOCREATE_SOURCE_SESSION
,
928 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Autocreation attempt', [
929 'event' => 'autocreate',
934 unset( $sessionUser );
937 if ( !$wgCommandLineMode ) {
938 Pingback
::schedulePingback();
941 $wgFullyInitialised = true;
943 Profiler
::instance()->scopedProfileOut( $ps_extensions );
944 Profiler
::instance()->scopedProfileOut( $ps_setup );