Special case opus mime detction
[mediawiki.git] / includes / Setup.php
blobecd164d3bc94dc86cad9e1cae4c19343deb5c34b
1 <?php
2 /**
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
24 * @file
26 use MediaWiki\MediaWikiServices;
28 /**
29 * This file is not a valid entry point, perform no further processing unless
30 * MEDIAWIKI is defined
32 if ( !defined( 'MEDIAWIKI' ) ) {
33 exit( 1 );
36 $fname = 'Setup.php';
37 $ps_setup = Profiler::instance()->scopedProfileIn( $fname );
39 // Load queued extensions
40 ExtensionRegistry::getInstance()->loadFromQueue();
41 // Don't let any other extensions load
42 ExtensionRegistry::getInstance()->finish();
44 // Check to see if we are at the file scope
45 if ( !isset( $wgVersion ) ) {
46 echo "Error, Setup.php must be included from the file scope, after DefaultSettings.php\n";
47 die( 1 );
50 mb_internal_encoding( 'UTF-8' );
52 // Set various default paths sensibly...
53 $ps_default = Profiler::instance()->scopedProfileIn( $fname . '-defaults' );
55 if ( $wgScript === false ) {
56 $wgScript = "$wgScriptPath/index.php";
58 if ( $wgLoadScript === false ) {
59 $wgLoadScript = "$wgScriptPath/load.php";
62 if ( $wgArticlePath === false ) {
63 if ( $wgUsePathInfo ) {
64 $wgArticlePath = "$wgScript/$1";
65 } else {
66 $wgArticlePath = "$wgScript?title=$1";
70 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
71 // 'view' is assumed the default action path everywhere in the code
72 // but is rarely filled in $wgActionPaths
73 $wgActionPaths['view'] = $wgArticlePath;
76 if ( $wgResourceBasePath === null ) {
77 $wgResourceBasePath = $wgScriptPath;
79 if ( $wgStylePath === false ) {
80 $wgStylePath = "$wgResourceBasePath/skins";
82 if ( $wgLocalStylePath === false ) {
83 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
84 $wgLocalStylePath = "$wgScriptPath/skins";
86 if ( $wgExtensionAssetsPath === false ) {
87 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
90 if ( $wgLogo === false ) {
91 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
94 if ( $wgUploadPath === false ) {
95 $wgUploadPath = "$wgScriptPath/images";
97 if ( $wgUploadDirectory === false ) {
98 $wgUploadDirectory = "$IP/images";
100 if ( $wgReadOnlyFile === false ) {
101 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
103 if ( $wgFileCacheDirectory === false ) {
104 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
106 if ( $wgDeletedDirectory === false ) {
107 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
110 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
111 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
114 if ( $wgEnableParserCache === false ) {
115 $wgParserCacheType = CACHE_NONE;
118 // Fix path to icon images after they were moved in 1.24
119 if ( $wgRightsIcon ) {
120 $wgRightsIcon = str_replace(
121 "{$wgStylePath}/common/images/",
122 "{$wgResourceBasePath}/resources/assets/licenses/",
123 $wgRightsIcon
127 if ( isset( $wgFooterIcons['copyright']['copyright'] )
128 && $wgFooterIcons['copyright']['copyright'] === []
130 if ( $wgRightsIcon || $wgRightsText ) {
131 $wgFooterIcons['copyright']['copyright'] = [
132 'url' => $wgRightsUrl,
133 'src' => $wgRightsIcon,
134 'alt' => $wgRightsText,
139 if ( isset( $wgFooterIcons['poweredby'] )
140 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
141 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
143 $wgFooterIcons['poweredby']['mediawiki']['src'] =
144 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
145 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
146 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
147 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
151 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
152 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
154 * Note that this is the definition of editinterface and it can be granted to
155 * all users if desired.
157 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
160 * The canonical names of namespaces 6 and 7 are, as of v1.14, "File"
161 * and "File_talk". The old names "Image" and "Image_talk" are
162 * retained as aliases for backwards compatibility.
164 $wgNamespaceAliases['Image'] = NS_FILE;
165 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
168 * Initialise $wgLockManagers to include basic FS version
170 $wgLockManagers[] = [
171 'name' => 'fsLockManager',
172 'class' => 'FSLockManager',
173 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
175 $wgLockManagers[] = [
176 'name' => 'nullLockManager',
177 'class' => 'NullLockManager',
181 * Initialise $wgLocalFileRepo from backwards-compatible settings
183 if ( !$wgLocalFileRepo ) {
184 $wgLocalFileRepo = [
185 'class' => 'LocalRepo',
186 'name' => 'local',
187 'directory' => $wgUploadDirectory,
188 'scriptDirUrl' => $wgScriptPath,
189 'scriptExtension' => '.php',
190 'url' => $wgUploadBaseUrl ? $wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
191 'hashLevels' => $wgHashedUploadDirectory ? 2 : 0,
192 'thumbScriptUrl' => $wgThumbnailScriptPath,
193 'transformVia404' => !$wgGenerateThumbnailOnParse,
194 'deletedDir' => $wgDeletedDirectory,
195 'deletedHashLevels' => $wgHashedUploadDirectory ? 3 : 0
199 * Initialise shared repo from backwards-compatible settings
201 if ( $wgUseSharedUploads ) {
202 if ( $wgSharedUploadDBname ) {
203 $wgForeignFileRepos[] = [
204 'class' => 'ForeignDBRepo',
205 'name' => 'shared',
206 'directory' => $wgSharedUploadDirectory,
207 'url' => $wgSharedUploadPath,
208 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
209 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
210 'transformVia404' => !$wgGenerateThumbnailOnParse,
211 'dbType' => $wgDBtype,
212 'dbServer' => $wgDBserver,
213 'dbUser' => $wgDBuser,
214 'dbPassword' => $wgDBpassword,
215 'dbName' => $wgSharedUploadDBname,
216 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG : 0 ) | DBO_DEFAULT,
217 'tablePrefix' => $wgSharedUploadDBprefix,
218 'hasSharedCache' => $wgCacheSharedUploads,
219 'descBaseUrl' => $wgRepositoryBaseUrl,
220 'fetchDescription' => $wgFetchCommonsDescriptions,
222 } else {
223 $wgForeignFileRepos[] = [
224 'class' => 'FileRepo',
225 'name' => 'shared',
226 'directory' => $wgSharedUploadDirectory,
227 'url' => $wgSharedUploadPath,
228 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
229 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
230 'transformVia404' => !$wgGenerateThumbnailOnParse,
231 'descBaseUrl' => $wgRepositoryBaseUrl,
232 'fetchDescription' => $wgFetchCommonsDescriptions,
236 if ( $wgUseInstantCommons ) {
237 $wgForeignFileRepos[] = [
238 'class' => 'ForeignAPIRepo',
239 'name' => 'wikimediacommons',
240 'apibase' => 'https://commons.wikimedia.org/w/api.php',
241 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
242 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
243 'hashLevels' => 2,
244 'transformVia404' => true,
245 'fetchDescription' => true,
246 'descriptionCacheExpiry' => 43200,
247 'apiThumbCacheExpiry' => 86400,
251 * Add on default file backend config for file repos.
252 * FileBackendGroup will handle initializing the backends.
254 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
255 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
257 foreach ( $wgForeignFileRepos as &$repo ) {
258 if ( !isset( $repo['directory'] ) && $repo['class'] === 'ForeignAPIRepo' ) {
259 $repo['directory'] = $wgUploadDirectory; // b/c
261 if ( !isset( $repo['backend'] ) ) {
262 $repo['backend'] = $repo['name'] . '-backend';
265 unset( $repo ); // no global pollution; destroy reference
267 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
268 if ( $wgRCFilterByAge ) {
269 // Trim down $wgRCLinkDays so that it only lists links which are valid
270 // as determined by $wgRCMaxAge.
271 // Note that we allow 1 link higher than the max for things like 56 days but a 60 day link.
272 sort( $wgRCLinkDays );
274 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
275 for ( $i = 0; $i < count( $wgRCLinkDays ); $i++ ) {
276 // @codingStandardsIgnoreEnd
277 if ( $wgRCLinkDays[$i] >= $rcMaxAgeDays ) {
278 $wgRCLinkDays = array_slice( $wgRCLinkDays, 0, $i + 1, false );
279 break;
283 // Ensure that default user options are not invalid, since that breaks Special:Preferences
284 $wgDefaultUserOptions['rcdays'] = min(
285 $wgDefaultUserOptions['rcdays'],
286 ceil( $rcMaxAgeDays )
288 $wgDefaultUserOptions['watchlistdays'] = min(
289 $wgDefaultUserOptions['watchlistdays'],
290 ceil( $rcMaxAgeDays )
292 unset( $rcMaxAgeDays );
294 if ( $wgSkipSkin ) {
295 $wgSkipSkins[] = $wgSkipSkin;
298 $wgSkipSkins[] = 'fallback';
299 $wgSkipSkins[] = 'apioutput';
301 if ( $wgLocalInterwiki ) {
302 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
305 // Set default shared prefix
306 if ( $wgSharedPrefix === false ) {
307 $wgSharedPrefix = $wgDBprefix;
310 // Set default shared schema
311 if ( $wgSharedSchema === false ) {
312 $wgSharedSchema = $wgDBmwschema;
315 if ( !$wgCookiePrefix ) {
316 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
317 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
318 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
319 $wgCookiePrefix = $wgSharedDB;
320 } elseif ( $wgDBprefix ) {
321 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
322 } else {
323 $wgCookiePrefix = $wgDBname;
326 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
328 if ( $wgEnableEmail ) {
329 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
330 } else {
331 // Disable all other email settings automatically if $wgEnableEmail
332 // is set to false. - bug 63678
333 $wgAllowHTMLEmail = false;
334 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
335 $wgEnableUserEmail = false;
336 $wgEnotifFromEditor = false;
337 $wgEnotifImpersonal = false;
338 $wgEnotifMaxRecips = 0;
339 $wgEnotifMinorEdits = false;
340 $wgEnotifRevealEditorAddress = false;
341 $wgEnotifUseRealName = false;
342 $wgEnotifUserTalk = false;
343 $wgEnotifWatchlist = false;
344 unset( $wgGroupPermissions['user']['sendemail'] );
345 $wgUseEnotif = false;
346 $wgUserEmailUseReplyTo = false;
347 $wgUsersNotifiedOnAllChanges = [];
350 if ( $wgMetaNamespace === false ) {
351 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
354 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
355 if ( $wgResourceLoaderMaxQueryLength === false ) {
356 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
357 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
358 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
359 } else {
360 $wgResourceLoaderMaxQueryLength = 2000;
362 unset( $suhosinMaxValueLength );
365 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
366 // upload size.
367 $wgMinUploadChunkSize = min(
368 $wgMinUploadChunkSize,
369 UploadBase::getMaxUploadSize( 'file' ),
370 UploadBase::getMaxPhpUploadSize(),
371 ( wfShorthandToInteger(
372 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
373 PHP_INT_MAX
374 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
378 * Definitions of the NS_ constants are in Defines.php
379 * @private
381 $wgCanonicalNamespaceNames = [
382 NS_MEDIA => 'Media',
383 NS_SPECIAL => 'Special',
384 NS_TALK => 'Talk',
385 NS_USER => 'User',
386 NS_USER_TALK => 'User_talk',
387 NS_PROJECT => 'Project',
388 NS_PROJECT_TALK => 'Project_talk',
389 NS_FILE => 'File',
390 NS_FILE_TALK => 'File_talk',
391 NS_MEDIAWIKI => 'MediaWiki',
392 NS_MEDIAWIKI_TALK => 'MediaWiki_talk',
393 NS_TEMPLATE => 'Template',
394 NS_TEMPLATE_TALK => 'Template_talk',
395 NS_HELP => 'Help',
396 NS_HELP_TALK => 'Help_talk',
397 NS_CATEGORY => 'Category',
398 NS_CATEGORY_TALK => 'Category_talk',
401 /// @todo UGLY UGLY
402 if ( is_array( $wgExtraNamespaces ) ) {
403 $wgCanonicalNamespaceNames = $wgCanonicalNamespaceNames + $wgExtraNamespaces;
406 // These are now the same, always
407 // To determine the user language, use $wgLang->getCode()
408 $wgContLanguageCode = $wgLanguageCode;
410 // Easy to forget to falsify $wgDebugToolbar for static caches.
411 // If file cache or CDN cache is on, just disable this (DWIMD).
412 if ( $wgUseFileCache || $wgUseSquid ) {
413 $wgDebugToolbar = false;
416 // We always output HTML5 since 1.22, overriding these is no longer supported
417 // we set them here for extensions that depend on its value.
418 $wgHtml5 = true;
419 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
420 $wgJsMimeType = 'text/javascript';
422 // Blacklisted file extensions shouldn't appear on the "allowed" list
423 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
425 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
426 MediaWiki\suppressWarnings();
427 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
428 MediaWiki\restoreWarnings();
431 if ( $wgNewUserLog ) {
432 // Add a new log type
433 $wgLogTypes[] = 'newusers';
434 $wgLogNames['newusers'] = 'newuserlogpage';
435 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
436 $wgLogActionsHandlers['newusers/newusers'] = 'NewUsersLogFormatter';
437 $wgLogActionsHandlers['newusers/create'] = 'NewUsersLogFormatter';
438 $wgLogActionsHandlers['newusers/create2'] = 'NewUsersLogFormatter';
439 $wgLogActionsHandlers['newusers/byemail'] = 'NewUsersLogFormatter';
440 $wgLogActionsHandlers['newusers/autocreate'] = 'NewUsersLogFormatter';
443 if ( $wgPageLanguageUseDB ) {
444 $wgLogTypes[] = 'pagelang';
445 $wgLogActionsHandlers['pagelang/pagelang'] = 'PageLangLogFormatter';
448 if ( $wgCookieSecure === 'detect' ) {
449 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
452 if ( $wgProfileOnly ) {
453 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
454 $wgDebugLogFile = '';
457 // Backwards compatibility with old password limits
458 if ( $wgMinimalPasswordLength !== false ) {
459 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
462 if ( $wgMaximalPasswordLength !== false ) {
463 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
466 // Backwards compatibility warning
467 if ( !$wgSessionsInObjectCache ) {
468 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
469 if ( $wgSessionHandler ) {
470 wfDeprecated( '$wgSessionsHandler', '1.27' );
472 $cacheType = get_class( ObjectCache::getInstance( $wgSessionCacheType ) );
473 wfDebugLog(
474 'caches',
475 "Session data will be stored in \"$cacheType\" cache with " .
476 "expiry $wgObjectCacheSessionExpiry seconds"
479 $wgSessionsInObjectCache = true;
481 if ( $wgPHPSessionHandling !== 'enable' &&
482 $wgPHPSessionHandling !== 'warn' &&
483 $wgPHPSessionHandling !== 'disable'
485 $wgPHPSessionHandling = 'warn';
487 if ( defined( 'MW_NO_SESSION' ) ) {
488 // If the entry point wants no session, force 'disable' here unless they
489 // specifically set it to the (undocumented) 'warn'.
490 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
493 Profiler::instance()->scopedProfileOut( $ps_default );
495 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
496 // all the memory from logging SQL queries on maintenance scripts
497 global $wgCommandLineMode;
498 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
499 MWDebug::init();
502 // Reset the global service locator, so any services that have already been created will be
503 // re-created while taking into account any custom settings and extensions.
504 MediaWikiServices::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
506 if ( $wgSharedDB && $wgSharedTables ) {
507 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
508 MediaWikiServices::getInstance()->getDBLoadBalancer()->setTableAliases(
509 array_fill_keys(
510 $wgSharedTables,
512 'dbname' => $wgSharedDB,
513 'schema' => $wgSharedSchema,
514 'prefix' => $wgSharedPrefix
520 // Define a constant that indicates that the bootstrapping of the service locator
521 // is complete.
522 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
524 // Install a header callback to prevent caching of responses with cookies (T127993)
525 if ( !$wgCommandLineMode ) {
526 header_register_callback( function () {
527 $headers = [];
528 foreach ( headers_list() as $header ) {
529 list( $name, $value ) = explode( ':', $header, 2 );
530 $headers[strtolower( trim( $name ) )][] = trim( $value );
533 if ( isset( $headers['set-cookie'] ) ) {
534 $cacheControl = isset( $headers['cache-control'] )
535 ? implode( ', ', $headers['cache-control'] )
536 : '';
538 if ( !preg_match( '/(?:^|,)\s*(?:private|no-cache|no-store)\s*(?:$|,)/i', $cacheControl ) ) {
539 header( 'Expires: Thu, 01 Jan 1970 00:00:00 GMT' );
540 header( 'Cache-Control: private, max-age=0, s-maxage=0' );
541 MediaWiki\Logger\LoggerFactory::getInstance( 'cache-cookies' )->warning(
542 'Cookies set on {url} with Cache-Control "{cache-control}"', [
543 'url' => WebRequest::getGlobalRequestURL(),
544 'cookies' => $headers['set-cookie'],
545 'cache-control' => $cacheControl ?: '<not set>',
550 } );
553 MWExceptionHandler::installHandler();
555 require_once "$IP/includes/compat/normal/UtfNormalUtil.php";
557 $ps_validation = Profiler::instance()->scopedProfileIn( $fname . '-validation' );
559 // T48998: Bail out early if $wgArticlePath is non-absolute
560 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
561 if ( $$varName && !preg_match( '/^(https?:\/\/|\/)/', $$varName ) ) {
562 throw new FatalError(
563 "If you use a relative URL for \$$varName, it must start " .
564 'with a slash (<code>/</code>).<br><br>See ' .
565 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
566 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
571 Profiler::instance()->scopedProfileOut( $ps_validation );
573 $ps_default2 = Profiler::instance()->scopedProfileIn( $fname . '-defaults2' );
575 if ( $wgCanonicalServer === false ) {
576 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP );
579 // Set server name
580 $serverParts = wfParseUrl( $wgCanonicalServer );
581 if ( $wgServerName !== false ) {
582 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
583 . 'not customized. Overwriting $wgServerName.' );
585 $wgServerName = $serverParts['host'];
586 unset( $serverParts );
588 // Set defaults for configuration variables
589 // that are derived from the server name by default
590 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
591 if ( !$wgEmergencyContact ) {
592 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
594 if ( !$wgPasswordSender ) {
595 $wgPasswordSender = 'apache@' . $wgServerName;
597 if ( !$wgNoReplyAddress ) {
598 $wgNoReplyAddress = $wgPasswordSender;
601 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
602 $wgSecureLogin = false;
603 wfWarn( 'Secure login was enabled on a server that only supports '
604 . 'HTTP or HTTPS. Disabling secure login.' );
607 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
609 // Now that GlobalFunctions is loaded, set defaults that depend on it.
610 if ( $wgTmpDirectory === false ) {
611 $wgTmpDirectory = wfTempDir();
614 // We don't use counters anymore. Left here for extensions still
615 // expecting this to exist. Should be removed sometime 1.26 or later.
616 if ( !isset( $wgDisableCounters ) ) {
617 $wgDisableCounters = true;
620 if ( $wgMainWANCache === false ) {
621 // Setup a WAN cache from $wgMainCacheType with no relayer.
622 // Sites using multiple datacenters can configure a relayer.
623 $wgMainWANCache = 'mediawiki-main-default';
624 $wgWANObjectCaches[$wgMainWANCache] = [
625 'class' => 'WANObjectCache',
626 'cacheId' => $wgMainCacheType,
627 'channels' => [ 'purge' => 'wancache-main-default-purge' ]
631 Profiler::instance()->scopedProfileOut( $ps_default2 );
633 $ps_misc = Profiler::instance()->scopedProfileIn( $fname . '-misc1' );
635 // Raise the memory limit if it's too low
636 wfMemoryLimit();
639 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
640 * that happens whenever you use a date function without the timezone being
641 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
643 if ( is_null( $wgLocaltimezone ) ) {
644 MediaWiki\suppressWarnings();
645 $wgLocaltimezone = date_default_timezone_get();
646 MediaWiki\restoreWarnings();
649 date_default_timezone_set( $wgLocaltimezone );
650 if ( is_null( $wgLocalTZoffset ) ) {
651 $wgLocalTZoffset = date( 'Z' ) / 60;
653 // The part after the System| is ignored, but rest of MW fills it
654 // out as the local offset.
655 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
657 if ( !$wgDBerrorLogTZ ) {
658 $wgDBerrorLogTZ = $wgLocaltimezone;
661 // initialize the request object in $wgRequest
662 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
663 // Set user IP/agent information for causal consistency purposes
664 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
665 'IPAddress' => $wgRequest->getIP(),
666 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
667 'ChronologyProtection' => $wgRequest->getHeader( 'ChronologyProtection' )
668 ] );
670 // Useful debug output
671 if ( $wgCommandLineMode ) {
672 wfDebug( "\n\nStart command line script $self\n" );
673 } else {
674 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
676 if ( $wgDebugPrintHttpHeaders ) {
677 $debug .= "HTTP HEADERS:\n";
679 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
680 $debug .= "$name: $value\n";
683 wfDebug( $debug );
686 Profiler::instance()->scopedProfileOut( $ps_misc );
687 $ps_memcached = Profiler::instance()->scopedProfileIn( $fname . '-memcached' );
689 $wgMemc = wfGetMainCache();
690 $messageMemc = wfGetMessageCacheStorage();
691 $parserMemc = wfGetParserCacheStorage();
693 wfDebugLog( 'caches',
694 'cluster: ' . get_class( $wgMemc ) .
695 ', WAN: ' . ( $wgMainWANCache === CACHE_NONE ? 'CACHE_NONE' : $wgMainWANCache ) .
696 ', stash: ' . $wgMainStash .
697 ', message: ' . get_class( $messageMemc ) .
698 ', parser: ' . get_class( $parserMemc ) .
699 ', session: ' . get_class( ObjectCache::getInstance( $wgSessionCacheType ) )
702 Profiler::instance()->scopedProfileOut( $ps_memcached );
704 // Most of the config is out, some might want to run hooks here.
705 Hooks::run( 'SetupAfterCache' );
707 $ps_globals = Profiler::instance()->scopedProfileIn( $fname . '-globals' );
710 * @var Language $wgContLang
712 $wgContLang = Language::factory( $wgLanguageCode );
713 $wgContLang->initContLang();
715 // Now that variant lists may be available...
716 $wgRequest->interpolateTitle();
718 if ( !is_object( $wgAuth ) ) {
719 $wgAuth = new MediaWiki\Auth\AuthManagerAuthPlugin;
720 Hooks::run( 'AuthPluginSetup', [ &$wgAuth ] );
722 if ( $wgAuth && !$wgAuth instanceof MediaWiki\Auth\AuthManagerAuthPlugin ) {
723 MediaWiki\Auth\AuthManager::singleton()->forcePrimaryAuthenticationProviders( [
724 new MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider( [
725 'authoritative' => false,
726 ] ),
727 new MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider( $wgAuth ),
728 new MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider( [
729 'authoritative' => true,
730 ] ),
731 ], '$wgAuth is ' . get_class( $wgAuth ) );
734 // Set up the session
735 $ps_session = Profiler::instance()->scopedProfileIn( $fname . '-session' );
737 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
738 * session ID (if any) loaded at startup
740 $wgInitialSessionId = null;
741 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
742 // If session.auto_start is there, we can't touch session name
743 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
744 session_name( $wgSessionName ? $wgSessionName : $wgCookiePrefix . '_session' );
747 // Create the SessionManager singleton and set up our session handler,
748 // unless we're specifically asked not to.
749 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
750 MediaWiki\Session\PHPSessionHandler::install(
751 MediaWiki\Session\SessionManager::singleton()
755 // Initialize the session
756 try {
757 $session = MediaWiki\Session\SessionManager::getGlobalSession();
758 } catch ( OverflowException $ex ) {
759 if ( isset( $ex->sessionInfos ) && count( $ex->sessionInfos ) >= 2 ) {
760 // The exception is because the request had multiple possible
761 // sessions tied for top priority. Report this to the user.
762 $list = [];
763 foreach ( $ex->sessionInfos as $info ) {
764 $list[] = $info->getProvider()->describe( $wgContLang );
766 $list = $wgContLang->listToText( $list );
767 throw new HttpError( 400,
768 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
772 // Not the one we want, rethrow
773 throw $ex;
776 if ( $session->isPersistent() ) {
777 $wgInitialSessionId = $session->getSessionId();
780 $session->renew();
781 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
782 ( $session->isPersistent() || $session->shouldRememberUser() )
784 // Start the PHP-session for backwards compatibility
785 session_id( $session->getId() );
786 MediaWiki\quietCall( 'session_start' );
789 unset( $session );
790 } else {
791 // Even if we didn't set up a global Session, still install our session
792 // handler unless specifically requested not to.
793 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
794 MediaWiki\Session\PHPSessionHandler::install(
795 MediaWiki\Session\SessionManager::singleton()
799 Profiler::instance()->scopedProfileOut( $ps_session );
802 * @var User $wgUser
804 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
807 * @var Language $wgLang
809 $wgLang = new StubUserLang;
812 * @var OutputPage $wgOut
814 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
817 * @var Parser $wgParser
819 $wgParser = new StubObject( 'wgParser', function () {
820 return MediaWikiServices::getInstance()->getParser();
821 } );
824 * @var Title $wgTitle
826 $wgTitle = null;
828 Profiler::instance()->scopedProfileOut( $ps_globals );
829 $ps_extensions = Profiler::instance()->scopedProfileIn( $fname . '-extensions' );
831 // Extension setup functions
832 // Entries should be added to this variable during the inclusion
833 // of the extension file. This allows the extension to perform
834 // any necessary initialisation in the fully initialised environment
835 foreach ( $wgExtensionFunctions as $func ) {
836 // Allow closures in PHP 5.3+
837 if ( is_object( $func ) && $func instanceof Closure ) {
838 $profName = $fname . '-extensions-closure';
839 } elseif ( is_array( $func ) ) {
840 if ( is_object( $func[0] ) ) {
841 $profName = $fname . '-extensions-' . get_class( $func[0] ) . '::' . $func[1];
842 } else {
843 $profName = $fname . '-extensions-' . implode( '::', $func );
845 } else {
846 $profName = $fname . '-extensions-' . strval( $func );
849 $ps_ext_func = Profiler::instance()->scopedProfileIn( $profName );
850 call_user_func( $func );
851 Profiler::instance()->scopedProfileOut( $ps_ext_func );
854 // If the session user has a 0 id but a valid name, that means we need to
855 // autocreate it.
856 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
857 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
858 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
859 $ps_autocreate = Profiler::instance()->scopedProfileIn( $fname . '-autocreate' );
860 $res = MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
861 $sessionUser,
862 MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
863 true
865 Profiler::instance()->scopedProfileOut( $ps_autocreate );
866 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Autocreation attempt', [
867 'event' => 'autocreate',
868 'status' => $res,
869 ] );
870 unset( $res );
872 unset( $sessionUser );
875 if ( !$wgCommandLineMode ) {
876 Pingback::schedulePingback();
879 $wgFullyInitialised = true;
881 Profiler::instance()->scopedProfileOut( $ps_extensions );
882 Profiler::instance()->scopedProfileOut( $ps_setup );