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
;
29 * This file is not a valid entry point, perform no further processing unless
30 * MEDIAWIKI is defined
32 if ( !defined( 'MEDIAWIKI' ) ) {
37 * Pre-config setup: Before loading LocalSettings.php
40 // Start the autoloader, so that extensions can derive classes from core files
41 require_once "$IP/includes/AutoLoader.php";
43 // Load up some global defines
44 require_once "$IP/includes/Defines.php";
46 // Load default settings
47 require_once "$IP/includes/DefaultSettings.php";
49 // Load global functions
50 require_once "$IP/includes/GlobalFunctions.php";
52 // Load composer's autoloader if present
53 if ( is_readable( "$IP/vendor/autoload.php" ) ) {
54 require_once "$IP/vendor/autoload.php";
57 // Assert that composer dependencies were successfully loaded
58 // Purposely no leading \ due to it breaking HHVM RepoAuthorative mode
59 // PHP works fine with both versions
60 // See https://github.com/facebook/hhvm/issues/5833
61 if ( !interface_exists( 'Psr\Log\LoggerInterface' ) ) {
63 'MediaWiki requires the <a href="https://github.com/php-fig/log">PSR-3 logging ' .
64 "library</a> to be present. This library is not embedded directly in MediaWiki's " .
65 "git repository and must be installed separately by the end user.\n\n" .
66 'Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git' .
67 '#Fetch_external_libraries">mediawiki.org</a> for help on installing ' .
68 'the required components.'
71 trigger_error( $message, E_USER_ERROR
);
75 // Install a header callback
76 MediaWiki\HeaderCallback
::register();
79 * Load LocalSettings.php
82 if ( is_readable( "$IP/StartProfiler.php" ) ) {
83 // @deprecated since 1.32: Use LocalSettings.php instead.
84 require "$IP/StartProfiler.php";
87 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
88 call_user_func( MW_CONFIG_CALLBACK
);
90 if ( !defined( 'MW_CONFIG_FILE' ) ) {
91 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
93 require_once MW_CONFIG_FILE
;
97 * Customization point after all loading (constants, functions, classes,
98 * DefaultSettings, LocalSettings). Specifically, this is before usage of
99 * settings, before instantiation of Profiler (and other singletons), and
100 * before any setup functions or hooks run.
103 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
104 call_user_func( MW_SETUP_CALLBACK
);
111 $fname = 'Setup.php';
112 $ps_setup = Profiler
::instance()->scopedProfileIn( $fname );
114 // Load queued extensions
115 ExtensionRegistry
::getInstance()->loadFromQueue();
116 // Don't let any other extensions load
117 ExtensionRegistry
::getInstance()->finish();
119 // Check to see if we are at the file scope
120 if ( !isset( $wgVersion ) ) {
121 echo "Error, Setup.php must be included from the file scope, after DefaultSettings.php\n";
125 mb_internal_encoding( 'UTF-8' );
127 // Set the configured locale on all requests for consisteny
128 putenv( "LC_ALL=$wgShellLocale" );
129 setlocale( LC_ALL
, $wgShellLocale );
131 // Set various default paths sensibly...
132 $ps_default = Profiler
::instance()->scopedProfileIn( $fname . '-defaults' );
134 if ( $wgScript === false ) {
135 $wgScript = "$wgScriptPath/index.php";
137 if ( $wgLoadScript === false ) {
138 $wgLoadScript = "$wgScriptPath/load.php";
141 if ( $wgArticlePath === false ) {
142 if ( $wgUsePathInfo ) {
143 $wgArticlePath = "$wgScript/$1";
145 $wgArticlePath = "$wgScript?title=$1";
149 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
150 // 'view' is assumed the default action path everywhere in the code
151 // but is rarely filled in $wgActionPaths
152 $wgActionPaths['view'] = $wgArticlePath;
155 if ( $wgResourceBasePath === null ) {
156 $wgResourceBasePath = $wgScriptPath;
158 if ( $wgStylePath === false ) {
159 $wgStylePath = "$wgResourceBasePath/skins";
161 if ( $wgLocalStylePath === false ) {
162 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
163 $wgLocalStylePath = "$wgScriptPath/skins";
165 if ( $wgExtensionAssetsPath === false ) {
166 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
169 if ( $wgLogo === false ) {
170 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
173 if ( $wgUploadPath === false ) {
174 $wgUploadPath = "$wgScriptPath/images";
176 if ( $wgUploadDirectory === false ) {
177 $wgUploadDirectory = "$IP/images";
179 if ( $wgReadOnlyFile === false ) {
180 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
182 if ( $wgFileCacheDirectory === false ) {
183 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
185 if ( $wgDeletedDirectory === false ) {
186 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
189 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
190 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
193 if ( $wgEnableParserCache === false ) {
194 $wgParserCacheType = CACHE_NONE
;
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 * Initialise $wgLocalFileRepo from backwards-compatible settings
276 if ( !$wgLocalFileRepo ) {
278 'class' => LocalRepo
::class,
280 'directory' => $wgUploadDirectory,
281 'scriptDirUrl' => $wgScriptPath,
282 'scriptExtension' => '.php',
283 'url' => $wgUploadBaseUrl ?
$wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
284 'hashLevels' => $wgHashedUploadDirectory ?
2 : 0,
285 'thumbScriptUrl' => $wgThumbnailScriptPath,
286 'transformVia404' => !$wgGenerateThumbnailOnParse,
287 'deletedDir' => $wgDeletedDirectory,
288 'deletedHashLevels' => $wgHashedUploadDirectory ?
3 : 0
292 * Initialise shared repo from backwards-compatible settings
294 if ( $wgUseSharedUploads ) {
295 if ( $wgSharedUploadDBname ) {
296 $wgForeignFileRepos[] = [
297 'class' => ForeignDBRepo
::class,
299 'directory' => $wgSharedUploadDirectory,
300 'url' => $wgSharedUploadPath,
301 'hashLevels' => $wgHashedSharedUploadDirectory ?
2 : 0,
302 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
303 'transformVia404' => !$wgGenerateThumbnailOnParse,
304 'dbType' => $wgDBtype,
305 'dbServer' => $wgDBserver,
306 'dbUser' => $wgDBuser,
307 'dbPassword' => $wgDBpassword,
308 'dbName' => $wgSharedUploadDBname,
309 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG
: 0 ) | DBO_DEFAULT
,
310 'tablePrefix' => $wgSharedUploadDBprefix,
311 'hasSharedCache' => $wgCacheSharedUploads,
312 'descBaseUrl' => $wgRepositoryBaseUrl,
313 'fetchDescription' => $wgFetchCommonsDescriptions,
316 $wgForeignFileRepos[] = [
317 'class' => FileRepo
::class,
319 'directory' => $wgSharedUploadDirectory,
320 'url' => $wgSharedUploadPath,
321 'hashLevels' => $wgHashedSharedUploadDirectory ?
2 : 0,
322 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
323 'transformVia404' => !$wgGenerateThumbnailOnParse,
324 'descBaseUrl' => $wgRepositoryBaseUrl,
325 'fetchDescription' => $wgFetchCommonsDescriptions,
329 if ( $wgUseInstantCommons ) {
330 $wgForeignFileRepos[] = [
331 'class' => ForeignAPIRepo
::class,
332 'name' => 'wikimediacommons',
333 'apibase' => 'https://commons.wikimedia.org/w/api.php',
334 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
335 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
337 'transformVia404' => true,
338 'fetchDescription' => true,
339 'descriptionCacheExpiry' => 43200,
340 'apiThumbCacheExpiry' => 0,
344 * Add on default file backend config for file repos.
345 * FileBackendGroup will handle initializing the backends.
347 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
348 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
350 foreach ( $wgForeignFileRepos as &$repo ) {
351 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo
::class ) {
352 $repo['directory'] = $wgUploadDirectory; // b/c
354 if ( !isset( $repo['backend'] ) ) {
355 $repo['backend'] = $repo['name'] . '-backend';
358 unset( $repo ); // no global pollution; destroy reference
360 // Convert this deprecated setting to modern system
361 if ( $wgExperimentalHtmlIds ) {
362 wfDeprecated( '$wgExperimentalHtmlIds', '1.30' );
363 $wgFragmentMode = [ 'html5-legacy', 'html5' ];
366 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
367 if ( $wgRCFilterByAge ) {
368 // Trim down $wgRCLinkDays so that it only lists links which are valid
369 // as determined by $wgRCMaxAge.
370 // Note that we allow 1 link higher than the max for things like 56 days but a 60 day link.
371 sort( $wgRCLinkDays );
373 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
374 for ( $i = 0; $i < count( $wgRCLinkDays ); $i++
) {
375 if ( $wgRCLinkDays[$i] >= $rcMaxAgeDays ) {
376 $wgRCLinkDays = array_slice( $wgRCLinkDays, 0, $i +
1, false );
381 // Ensure that default user options are not invalid, since that breaks Special:Preferences
382 $wgDefaultUserOptions['rcdays'] = min(
383 $wgDefaultUserOptions['rcdays'],
384 ceil( $rcMaxAgeDays )
386 $wgDefaultUserOptions['watchlistdays'] = min(
387 $wgDefaultUserOptions['watchlistdays'],
388 ceil( $rcMaxAgeDays )
390 unset( $rcMaxAgeDays );
393 $wgSkipSkins[] = $wgSkipSkin;
396 $wgSkipSkins[] = 'fallback';
397 $wgSkipSkins[] = 'apioutput';
399 if ( $wgLocalInterwiki ) {
400 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
403 // Set default shared prefix
404 if ( $wgSharedPrefix === false ) {
405 $wgSharedPrefix = $wgDBprefix;
408 // Set default shared schema
409 if ( $wgSharedSchema === false ) {
410 $wgSharedSchema = $wgDBmwschema;
413 if ( !$wgCookiePrefix ) {
414 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
415 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
416 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
417 $wgCookiePrefix = $wgSharedDB;
418 } elseif ( $wgDBprefix ) {
419 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
421 $wgCookiePrefix = $wgDBname;
424 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
426 if ( $wgEnableEmail ) {
427 $wgUseEnotif = $wgEnotifUserTalk ||
$wgEnotifWatchlist;
429 // Disable all other email settings automatically if $wgEnableEmail
430 // is set to false. - T65678
431 $wgAllowHTMLEmail = false;
432 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
433 $wgEnableUserEmail = false;
434 $wgEnotifFromEditor = false;
435 $wgEnotifImpersonal = false;
436 $wgEnotifMaxRecips = 0;
437 $wgEnotifMinorEdits = false;
438 $wgEnotifRevealEditorAddress = false;
439 $wgEnotifUseRealName = false;
440 $wgEnotifUserTalk = false;
441 $wgEnotifWatchlist = false;
442 unset( $wgGroupPermissions['user']['sendemail'] );
443 $wgUseEnotif = false;
444 $wgUserEmailUseReplyTo = false;
445 $wgUsersNotifiedOnAllChanges = [];
448 if ( $wgMetaNamespace === false ) {
449 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
452 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
453 if ( $wgResourceLoaderMaxQueryLength === false ) {
454 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
455 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
456 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
458 $wgResourceLoaderMaxQueryLength = 2000;
460 unset( $suhosinMaxValueLength );
463 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
465 $wgMinUploadChunkSize = min(
466 $wgMinUploadChunkSize,
467 UploadBase
::getMaxUploadSize( 'file' ),
468 UploadBase
::getMaxPhpUploadSize(),
469 ( wfShorthandToInteger(
470 ini_get( 'post_max_size' ) ?
: ini_get( 'hhvm.server.max_post_size' ),
472 ) ?
: PHP_INT_MAX
) - 1024 // Leave some room for other POST parameters
476 * Definitions of the NS_ constants are in Defines.php
479 $wgCanonicalNamespaceNames = [
481 NS_SPECIAL
=> 'Special',
484 NS_USER_TALK
=> 'User_talk',
485 NS_PROJECT
=> 'Project',
486 NS_PROJECT_TALK
=> 'Project_talk',
488 NS_FILE_TALK
=> 'File_talk',
489 NS_MEDIAWIKI
=> 'MediaWiki',
490 NS_MEDIAWIKI_TALK
=> 'MediaWiki_talk',
491 NS_TEMPLATE
=> 'Template',
492 NS_TEMPLATE_TALK
=> 'Template_talk',
494 NS_HELP_TALK
=> 'Help_talk',
495 NS_CATEGORY
=> 'Category',
496 NS_CATEGORY_TALK
=> 'Category_talk',
500 if ( is_array( $wgExtraNamespaces ) ) {
501 $wgCanonicalNamespaceNames = $wgCanonicalNamespaceNames +
$wgExtraNamespaces;
504 // Merge in the legacy language codes, incorporating overrides from the config
505 $wgDummyLanguageCodes +
= [
506 'qqq' => 'qqq', // Used for message documentation
507 'qqx' => 'qqx', // Used for viewing message keys
508 ] +
$wgExtraLanguageCodes + LanguageCode
::getDeprecatedCodeMapping();
510 // These are now the same, always
511 // To determine the user language, use $wgLang->getCode()
512 $wgContLanguageCode = $wgLanguageCode;
514 // Easy to forget to falsify $wgDebugToolbar for static caches.
515 // If file cache or CDN cache is on, just disable this (DWIMD).
516 if ( $wgUseFileCache ||
$wgUseSquid ) {
517 $wgDebugToolbar = false;
520 // We always output HTML5 since 1.22, overriding these is no longer supported
521 // we set them here for extensions that depend on its value.
523 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
524 $wgJsMimeType = 'text/javascript';
526 // Blacklisted file extensions shouldn't appear on the "allowed" list
527 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
529 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
530 Wikimedia\
suppressWarnings();
531 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
532 Wikimedia\restoreWarnings
();
535 if ( $wgNewUserLog ) {
536 // Add a new log type
537 $wgLogTypes[] = 'newusers';
538 $wgLogNames['newusers'] = 'newuserlogpage';
539 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
540 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter
::class;
541 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter
::class;
542 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter
::class;
543 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter
::class;
544 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter
::class;
547 if ( $wgPageLanguageUseDB ) {
548 $wgLogTypes[] = 'pagelang';
549 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter
::class;
552 if ( $wgCookieSecure === 'detect' ) {
553 $wgCookieSecure = ( WebRequest
::detectProtocol() === 'https' );
556 if ( $wgProfileOnly ) {
557 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
558 $wgDebugLogFile = '';
561 // Backwards compatibility with old password limits
562 if ( $wgMinimalPasswordLength !== false ) {
563 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
566 if ( $wgMaximalPasswordLength !== false ) {
567 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
570 // Backwards compatibility warning
571 if ( !$wgSessionsInObjectCache ) {
572 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
573 if ( $wgSessionHandler ) {
574 wfDeprecated( '$wgSessionsHandler', '1.27' );
576 $cacheType = get_class( ObjectCache
::getInstance( $wgSessionCacheType ) );
579 "Session data will be stored in \"$cacheType\" cache with " .
580 "expiry $wgObjectCacheSessionExpiry seconds"
583 $wgSessionsInObjectCache = true;
585 if ( $wgPHPSessionHandling !== 'enable' &&
586 $wgPHPSessionHandling !== 'warn' &&
587 $wgPHPSessionHandling !== 'disable'
589 $wgPHPSessionHandling = 'warn';
591 if ( defined( 'MW_NO_SESSION' ) ) {
592 // If the entry point wants no session, force 'disable' here unless they
593 // specifically set it to the (undocumented) 'warn'.
594 $wgPHPSessionHandling = MW_NO_SESSION
=== 'warn' ?
'warn' : 'disable';
597 Profiler
::instance()->scopedProfileOut( $ps_default );
599 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
600 // all the memory from logging SQL queries on maintenance scripts
601 global $wgCommandLineMode;
602 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
606 // Reset the global service locator, so any services that have already been created will be
607 // re-created while taking into account any custom settings and extensions.
608 MediaWikiServices
::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
610 if ( $wgSharedDB && $wgSharedTables ) {
611 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
612 MediaWikiServices
::getInstance()->getDBLoadBalancer()->setTableAliases(
616 'dbname' => $wgSharedDB,
617 'schema' => $wgSharedSchema,
618 'prefix' => $wgSharedPrefix
624 // Define a constant that indicates that the bootstrapping of the service locator
626 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
628 MWExceptionHandler
::installHandler();
630 require_once "$IP/includes/compat/normal/UtfNormalUtil.php";
632 $ps_validation = Profiler
::instance()->scopedProfileIn( $fname . '-validation' );
634 // T48998: Bail out early if $wgArticlePath is non-absolute
635 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
636 if ( $
$varName && !preg_match( '/^(https?:\/\/|\/)/', $
$varName ) ) {
637 throw new FatalError(
638 "If you use a relative URL for \$$varName, it must start " .
639 'with a slash (<code>/</code>).<br><br>See ' .
640 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
641 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
646 Profiler
::instance()->scopedProfileOut( $ps_validation );
648 $ps_default2 = Profiler
::instance()->scopedProfileIn( $fname . '-defaults2' );
650 if ( $wgCanonicalServer === false ) {
651 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP
);
655 $serverParts = wfParseUrl( $wgCanonicalServer );
656 if ( $wgServerName !== false ) {
657 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
658 . 'not customized. Overwriting $wgServerName.' );
660 $wgServerName = $serverParts['host'];
661 unset( $serverParts );
663 // Set defaults for configuration variables
664 // that are derived from the server name by default
665 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
666 if ( !$wgEmergencyContact ) {
667 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
669 if ( !$wgPasswordSender ) {
670 $wgPasswordSender = 'apache@' . $wgServerName;
672 if ( !$wgNoReplyAddress ) {
673 $wgNoReplyAddress = $wgPasswordSender;
676 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
677 $wgSecureLogin = false;
678 wfWarn( 'Secure login was enabled on a server that only supports '
679 . 'HTTP or HTTPS. Disabling secure login.' );
682 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
684 // Now that GlobalFunctions is loaded, set defaults that depend on it.
685 if ( $wgTmpDirectory === false ) {
686 $wgTmpDirectory = wfTempDir();
689 // We don't use counters anymore. Left here for extensions still
690 // expecting this to exist. Should be removed sometime 1.26 or later.
691 if ( !isset( $wgDisableCounters ) ) {
692 $wgDisableCounters = true;
695 if ( $wgMainWANCache === false ) {
696 // Setup a WAN cache from $wgMainCacheType with no relayer.
697 // Sites using multiple datacenters can configure a relayer.
698 $wgMainWANCache = 'mediawiki-main-default';
699 $wgWANObjectCaches[$wgMainWANCache] = [
700 'class' => WANObjectCache
::class,
701 'cacheId' => $wgMainCacheType,
702 'channels' => [ 'purge' => 'wancache-main-default-purge' ]
706 Profiler
::instance()->scopedProfileOut( $ps_default2 );
708 $ps_misc = Profiler
::instance()->scopedProfileIn( $fname . '-misc1' );
710 // Raise the memory limit if it's too low
714 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
715 * that happens whenever you use a date function without the timezone being
716 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
718 if ( is_null( $wgLocaltimezone ) ) {
719 Wikimedia\
suppressWarnings();
720 $wgLocaltimezone = date_default_timezone_get();
721 Wikimedia\restoreWarnings
();
724 date_default_timezone_set( $wgLocaltimezone );
725 if ( is_null( $wgLocalTZoffset ) ) {
726 $wgLocalTZoffset = date( 'Z' ) / 60;
728 // The part after the System| is ignored, but rest of MW fills it
729 // out as the local offset.
730 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
732 if ( !$wgDBerrorLogTZ ) {
733 $wgDBerrorLogTZ = $wgLocaltimezone;
736 // Initialize the request object in $wgRequest
737 $wgRequest = RequestContext
::getMain()->getRequest(); // BackCompat
738 // Set user IP/agent information for agent session consistency purposes
739 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
740 'IPAddress' => $wgRequest->getIP(),
741 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
742 'ChronologyProtection' => $wgRequest->getHeader( 'ChronologyProtection' ),
743 // The cpPosIndex cookie has no prefix and is set by MediaWiki::preOutputCommit()
744 'ChronologyPositionIndex' =>
745 $wgRequest->getInt( 'cpPosIndex', (int)$wgRequest->getCookie( 'cpPosIndex', '' ) )
747 // Make sure that object caching does not undermine the ChronologyProtector improvements
748 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
749 // The user is pinned to the primary DC, meaning that they made recent changes which should
750 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
751 // they use a blind TTL and could be stale if an object changes twice in a short time span.
752 MediaWikiServices
::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
755 // Useful debug output
756 if ( $wgCommandLineMode ) {
757 wfDebug( "\n\nStart command line script $self\n" );
759 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
761 if ( $wgDebugPrintHttpHeaders ) {
762 $debug .= "HTTP HEADERS:\n";
764 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
765 $debug .= "$name: $value\n";
771 Profiler
::instance()->scopedProfileOut( $ps_misc );
772 $ps_memcached = Profiler
::instance()->scopedProfileIn( $fname . '-memcached' );
774 $wgMemc = wfGetMainCache();
775 $messageMemc = wfGetMessageCacheStorage();
778 * @deprecated since 1.30
780 $parserMemc = new DeprecatedGlobal( 'parserMemc', function () {
781 return MediaWikiServices
::getInstance()->getParserCache()->getCacheStorage();
784 wfDebugLog( 'caches',
785 'cluster: ' . get_class( $wgMemc ) .
786 ', WAN: ' . ( $wgMainWANCache === CACHE_NONE ?
'CACHE_NONE' : $wgMainWANCache ) .
787 ', stash: ' . $wgMainStash .
788 ', message: ' . get_class( $messageMemc ) .
789 ', session: ' . get_class( ObjectCache
::getInstance( $wgSessionCacheType ) )
792 Profiler
::instance()->scopedProfileOut( $ps_memcached );
794 // Most of the config is out, some might want to run hooks here.
795 Hooks
::run( 'SetupAfterCache' );
797 $ps_globals = Profiler
::instance()->scopedProfileIn( $fname . '-globals' );
800 * @var Language $wgContLang
802 $wgContLang = Language
::factory( $wgLanguageCode );
803 $wgContLang->initContLang();
805 // Now that variant lists may be available...
806 $wgRequest->interpolateTitle();
808 if ( !is_object( $wgAuth ) ) {
809 $wgAuth = new MediaWiki\Auth\AuthManagerAuthPlugin
;
810 Hooks
::run( 'AuthPluginSetup', [ &$wgAuth ] );
812 if ( $wgAuth && !$wgAuth instanceof MediaWiki\Auth\AuthManagerAuthPlugin
) {
813 MediaWiki\Auth\AuthManager
::singleton()->forcePrimaryAuthenticationProviders( [
814 new MediaWiki\Auth\
TemporaryPasswordPrimaryAuthenticationProvider( [
815 'authoritative' => false,
817 new MediaWiki\Auth\
AuthPluginPrimaryAuthenticationProvider( $wgAuth ),
818 new MediaWiki\Auth\
LocalPasswordPrimaryAuthenticationProvider( [
819 'authoritative' => true,
821 ], '$wgAuth is ' . get_class( $wgAuth ) );
824 // Set up the session
825 $ps_session = Profiler
::instance()->scopedProfileIn( $fname . '-session' );
827 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
828 * session ID (if any) loaded at startup
830 $wgInitialSessionId = null;
831 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
832 // If session.auto_start is there, we can't touch session name
833 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
834 session_name( $wgSessionName ?
$wgSessionName : $wgCookiePrefix . '_session' );
837 // Create the SessionManager singleton and set up our session handler,
838 // unless we're specifically asked not to.
839 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
840 MediaWiki\Session\PHPSessionHandler
::install(
841 MediaWiki\Session\SessionManager
::singleton()
845 // Initialize the session
847 $session = MediaWiki\Session\SessionManager
::getGlobalSession();
848 } catch ( OverflowException
$ex ) {
849 if ( isset( $ex->sessionInfos
) && count( $ex->sessionInfos
) >= 2 ) {
850 // The exception is because the request had multiple possible
851 // sessions tied for top priority. Report this to the user.
853 foreach ( $ex->sessionInfos
as $info ) {
854 $list[] = $info->getProvider()->describe( $wgContLang );
856 $list = $wgContLang->listToText( $list );
857 throw new HttpError( 400,
858 Message
::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
862 // Not the one we want, rethrow
866 if ( $session->isPersistent() ) {
867 $wgInitialSessionId = $session->getSessionId();
871 if ( MediaWiki\Session\PHPSessionHandler
::isEnabled() &&
872 ( $session->isPersistent() ||
$session->shouldRememberUser() )
874 // Start the PHP-session for backwards compatibility
875 session_id( $session->getId() );
876 Wikimedia\
quietCall( 'session_start' );
881 // Even if we didn't set up a global Session, still install our session
882 // handler unless specifically requested not to.
883 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
884 MediaWiki\Session\PHPSessionHandler
::install(
885 MediaWiki\Session\SessionManager
::singleton()
889 Profiler
::instance()->scopedProfileOut( $ps_session );
894 $wgUser = RequestContext
::getMain()->getUser(); // BackCompat
897 * @var Language $wgLang
899 $wgLang = new StubUserLang
;
902 * @var OutputPage $wgOut
904 $wgOut = RequestContext
::getMain()->getOutput(); // BackCompat
907 * @var Parser $wgParser
909 $wgParser = new StubObject( 'wgParser', function () {
910 return MediaWikiServices
::getInstance()->getParser();
914 * @var Title $wgTitle
918 Profiler
::instance()->scopedProfileOut( $ps_globals );
919 $ps_extensions = Profiler
::instance()->scopedProfileIn( $fname . '-extensions' );
921 // Extension setup functions
922 // Entries should be added to this variable during the inclusion
923 // of the extension file. This allows the extension to perform
924 // any necessary initialisation in the fully initialised environment
925 foreach ( $wgExtensionFunctions as $func ) {
926 // Allow closures in PHP 5.3+
927 if ( is_object( $func ) && $func instanceof Closure
) {
928 $profName = $fname . '-extensions-closure';
929 } elseif ( is_array( $func ) ) {
930 if ( is_object( $func[0] ) ) {
931 $profName = $fname . '-extensions-' . get_class( $func[0] ) . '::' . $func[1];
933 $profName = $fname . '-extensions-' . implode( '::', $func );
936 $profName = $fname . '-extensions-' . strval( $func );
939 $ps_ext_func = Profiler
::instance()->scopedProfileIn( $profName );
940 call_user_func( $func );
941 Profiler
::instance()->scopedProfileOut( $ps_ext_func );
944 // If the session user has a 0 id but a valid name, that means we need to
946 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
947 $sessionUser = MediaWiki\Session\SessionManager
::getGlobalSession()->getUser();
948 if ( $sessionUser->getId() === 0 && User
::isValidUserName( $sessionUser->getName() ) ) {
949 $ps_autocreate = Profiler
::instance()->scopedProfileIn( $fname . '-autocreate' );
950 $res = MediaWiki\Auth\AuthManager
::singleton()->autoCreateUser(
952 MediaWiki\Auth\AuthManager
::AUTOCREATE_SOURCE_SESSION
,
955 Profiler
::instance()->scopedProfileOut( $ps_autocreate );
956 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Autocreation attempt', [
957 'event' => 'autocreate',
962 unset( $sessionUser );
965 if ( !$wgCommandLineMode ) {
966 Pingback
::schedulePingback();
969 $wgFullyInitialised = true;
971 Profiler
::instance()->scopedProfileOut( $ps_extensions );
972 Profiler
::instance()->scopedProfileOut( $ps_setup );