Merge "Request-local caching of DjVu dimensions"
[mediawiki.git] / includes / Setup.php
blobf7d8d08829c622d23aa2f1bdad3922ef672b4915
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
27 /**
28 * This file is not a valid entry point, perform no further processing unless
29 * MEDIAWIKI is defined
31 if ( !defined( 'MEDIAWIKI' ) ) {
32 exit( 1 );
35 $fname = 'Setup.php';
36 $ps_setup = Profiler::instance()->scopedProfileIn( $fname );
38 // If any extensions are still queued, force load them
39 ExtensionRegistry::getInstance()->loadFromQueue();
41 // Check to see if we are at the file scope
42 if ( !isset( $wgVersion ) ) {
43 echo "Error, Setup.php must be included from the file scope, after DefaultSettings.php\n";
44 die( 1 );
47 // Set various default paths sensibly...
48 $ps_default = Profiler::instance()->scopedProfileIn( $fname . '-defaults' );
50 if ( $wgScript === false ) {
51 $wgScript = "$wgScriptPath/index.php";
53 if ( $wgLoadScript === false ) {
54 $wgLoadScript = "$wgScriptPath/load.php";
57 if ( $wgArticlePath === false ) {
58 if ( $wgUsePathInfo ) {
59 $wgArticlePath = "$wgScript/$1";
60 } else {
61 $wgArticlePath = "$wgScript?title=$1";
65 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
66 // 'view' is assumed the default action path everywhere in the code
67 // but is rarely filled in $wgActionPaths
68 $wgActionPaths['view'] = $wgArticlePath;
71 if ( $wgResourceBasePath === null ) {
72 $wgResourceBasePath = $wgScriptPath;
74 if ( $wgStylePath === false ) {
75 $wgStylePath = "$wgResourceBasePath/skins";
77 if ( $wgLocalStylePath === false ) {
78 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
79 $wgLocalStylePath = "$wgScriptPath/skins";
81 if ( $wgExtensionAssetsPath === false ) {
82 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
85 if ( $wgLogo === false ) {
86 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
89 if ( $wgUploadPath === false ) {
90 $wgUploadPath = "$wgScriptPath/images";
92 if ( $wgUploadDirectory === false ) {
93 $wgUploadDirectory = "$IP/images";
95 if ( $wgReadOnlyFile === false ) {
96 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
98 if ( $wgFileCacheDirectory === false ) {
99 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
101 if ( $wgDeletedDirectory === false ) {
102 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
105 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
106 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
109 if ( $wgEnableParserCache === false ) {
110 $wgParserCacheType = CACHE_NONE;
113 // Fix path to icon images after they were moved in 1.24
114 if ( $wgRightsIcon ) {
115 $wgRightsIcon = str_replace(
116 "{$wgStylePath}/common/images/",
117 "{$wgResourceBasePath}/resources/assets/licenses/",
118 $wgRightsIcon
122 if ( isset( $wgFooterIcons['copyright'] )
123 && isset( $wgFooterIcons['copyright']['copyright'] )
124 && $wgFooterIcons['copyright']['copyright'] === []
126 if ( $wgCopyrightIcon ) {
127 $wgFooterIcons['copyright']['copyright'] = $wgCopyrightIcon;
128 } elseif ( $wgRightsIcon || $wgRightsText ) {
129 $wgFooterIcons['copyright']['copyright'] = [
130 'url' => $wgRightsUrl,
131 'src' => $wgRightsIcon,
132 'alt' => $wgRightsText,
134 } else {
135 unset( $wgFooterIcons['copyright']['copyright'] );
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 // Register skins
299 // Use a closure to avoid leaking into global state
300 call_user_func( function () use ( $wgValidSkinNames ) {
301 $factory = SkinFactory::getDefaultInstance();
302 foreach ( $wgValidSkinNames as $name => $skin ) {
303 $factory->register( $name, $skin, function () use ( $name, $skin ) {
304 $class = "Skin$skin";
305 return new $class( $name );
306 } );
308 // Register a hidden "fallback" skin
309 $factory->register( 'fallback', 'Fallback', function () {
310 return new SkinFallback;
311 } );
312 // Register a hidden skin for api output
313 $factory->register( 'apioutput', 'ApiOutput', function () {
314 return new SkinApi;
315 } );
316 } );
317 $wgSkipSkins[] = 'fallback';
318 $wgSkipSkins[] = 'apioutput';
320 if ( $wgLocalInterwiki ) {
321 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
324 // Set default shared prefix
325 if ( $wgSharedPrefix === false ) {
326 $wgSharedPrefix = $wgDBprefix;
329 // Set default shared schema
330 if ( $wgSharedSchema === false ) {
331 $wgSharedSchema = $wgDBmwschema;
334 if ( !$wgCookiePrefix ) {
335 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
336 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
337 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
338 $wgCookiePrefix = $wgSharedDB;
339 } elseif ( $wgDBprefix ) {
340 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
341 } else {
342 $wgCookiePrefix = $wgDBname;
345 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
347 if ( $wgEnableEmail ) {
348 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
349 } else {
350 // Disable all other email settings automatically if $wgEnableEmail
351 // is set to false. - bug 63678
352 $wgAllowHTMLEmail = false;
353 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
354 $wgEnableUserEmail = false;
355 $wgEnotifFromEditor = false;
356 $wgEnotifImpersonal = false;
357 $wgEnotifMaxRecips = 0;
358 $wgEnotifMinorEdits = false;
359 $wgEnotifRevealEditorAddress = false;
360 $wgEnotifUseRealName = false;
361 $wgEnotifUserTalk = false;
362 $wgEnotifWatchlist = false;
363 unset( $wgGroupPermissions['user']['sendemail'] );
364 $wgUseEnotif = false;
365 $wgUserEmailUseReplyTo = false;
366 $wgUsersNotifiedOnAllChanges = [];
369 // Doesn't make sense to have if disabled.
370 if ( !$wgEnotifMinorEdits ) {
371 $wgHiddenPrefs[] = 'enotifminoredits';
374 if ( $wgMetaNamespace === false ) {
375 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
378 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
379 if ( $wgResourceLoaderMaxQueryLength === false ) {
380 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
381 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
382 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
383 } else {
384 $wgResourceLoaderMaxQueryLength = 2000;
386 unset( $suhosinMaxValueLength );
389 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
390 // upload size.
391 $wgMinUploadChunkSize = min(
392 $wgMinUploadChunkSize,
393 UploadBase::getMaxUploadSize( 'file' ),
394 UploadBase::getMaxPhpUploadSize(),
395 ( wfShorthandToInteger(
396 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
397 PHP_INT_MAX
398 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
402 * Definitions of the NS_ constants are in Defines.php
403 * @private
405 $wgCanonicalNamespaceNames = [
406 NS_MEDIA => 'Media',
407 NS_SPECIAL => 'Special',
408 NS_TALK => 'Talk',
409 NS_USER => 'User',
410 NS_USER_TALK => 'User_talk',
411 NS_PROJECT => 'Project',
412 NS_PROJECT_TALK => 'Project_talk',
413 NS_FILE => 'File',
414 NS_FILE_TALK => 'File_talk',
415 NS_MEDIAWIKI => 'MediaWiki',
416 NS_MEDIAWIKI_TALK => 'MediaWiki_talk',
417 NS_TEMPLATE => 'Template',
418 NS_TEMPLATE_TALK => 'Template_talk',
419 NS_HELP => 'Help',
420 NS_HELP_TALK => 'Help_talk',
421 NS_CATEGORY => 'Category',
422 NS_CATEGORY_TALK => 'Category_talk',
425 /// @todo UGLY UGLY
426 if ( is_array( $wgExtraNamespaces ) ) {
427 $wgCanonicalNamespaceNames = $wgCanonicalNamespaceNames + $wgExtraNamespaces;
430 // These are now the same, always
431 // To determine the user language, use $wgLang->getCode()
432 $wgContLanguageCode = $wgLanguageCode;
434 // Easy to forget to falsify $wgDebugToolbar for static caches.
435 // If file cache or CDN cache is on, just disable this (DWIMD).
436 if ( $wgUseFileCache || $wgUseSquid ) {
437 $wgDebugToolbar = false;
440 // We always output HTML5 since 1.22, overriding these is no longer supported
441 // we set them here for extensions that depend on its value.
442 $wgHtml5 = true;
443 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
444 $wgJsMimeType = 'text/javascript';
446 // Blacklisted file extensions shouldn't appear on the "allowed" list
447 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
449 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
450 MediaWiki\suppressWarnings();
451 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
452 MediaWiki\restoreWarnings();
455 if ( $wgNewUserLog ) {
456 // Add a new log type
457 $wgLogTypes[] = 'newusers';
458 $wgLogNames['newusers'] = 'newuserlogpage';
459 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
460 $wgLogActionsHandlers['newusers/newusers'] = 'NewUsersLogFormatter';
461 $wgLogActionsHandlers['newusers/create'] = 'NewUsersLogFormatter';
462 $wgLogActionsHandlers['newusers/create2'] = 'NewUsersLogFormatter';
463 $wgLogActionsHandlers['newusers/byemail'] = 'NewUsersLogFormatter';
464 $wgLogActionsHandlers['newusers/autocreate'] = 'NewUsersLogFormatter';
467 if ( $wgPageLanguageUseDB ) {
468 $wgLogTypes[] = 'pagelang';
469 $wgLogActionsHandlers['pagelang/pagelang'] = 'PageLangLogFormatter';
472 if ( $wgCookieSecure === 'detect' ) {
473 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
476 if ( $wgProfileOnly ) {
477 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
478 $wgDebugLogFile = '';
481 // Backwards compatibility with old password limits
482 if ( $wgMinimalPasswordLength !== false ) {
483 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
486 if ( $wgMaximalPasswordLength !== false ) {
487 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
490 // Backwards compatibility warning
491 if ( !$wgSessionsInObjectCache && !$wgSessionsInMemcached ) {
492 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
493 if ( $wgSessionHandler ) {
494 wfDeprecated( '$wgSessionsHandler', '1.27' );
496 $cacheType = get_class( ObjectCache::getInstance( $wgSessionCacheType ) );
497 wfDebugLog(
498 'caches',
499 "Session data will be stored in \"$cacheType\" cache with " .
500 "expiry $wgObjectCacheSessionExpiry seconds"
503 $wgSessionsInObjectCache = true;
505 if ( $wgPHPSessionHandling !== 'enable' &&
506 $wgPHPSessionHandling !== 'warn' &&
507 $wgPHPSessionHandling !== 'disable'
509 $wgPHPSessionHandling = 'warn';
511 if ( defined( 'MW_NO_SESSION' ) ) {
512 // If the entry point wants no session, force 'disable' here unless they
513 // specifically set it to the (undocumented) 'warn'.
514 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
517 Profiler::instance()->scopedProfileOut( $ps_default );
519 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
520 // all the memory from logging SQL queries on maintenance scripts
521 global $wgCommandLineMode;
522 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
523 MWDebug::init();
526 if ( !class_exists( 'AutoLoader' ) ) {
527 require_once "$IP/includes/AutoLoader.php";
530 // Install a header callback to prevent caching of responses with cookies (T127993)
531 if ( !$wgCommandLineMode ) {
532 header_register_callback( function () {
533 $headers = [];
534 foreach ( headers_list() as $header ) {
535 list( $name, $value ) = explode( ':', $header, 2 );
536 $headers[strtolower( trim( $name ) )][] = trim( $value );
539 if ( isset( $headers['set-cookie'] ) ) {
540 $cacheControl = isset( $headers['cache-control'] )
541 ? implode( ', ', $headers['cache-control'] )
542 : '';
544 if ( !preg_match( '/(?:^|,)\s*(?:private|no-cache|no-store)\s*(?:$|,)/i', $cacheControl ) ) {
545 header( 'Expires: Thu, 01 Jan 1970 00:00:00 GMT' );
546 header( 'Cache-Control: private, max-age=0, s-maxage=0' );
547 MediaWiki\Logger\LoggerFactory::getInstance( 'cache-cookies' )->warning(
548 'Cookies set on {url} with Cache-Control "{cache-control}"', [
549 'url' => WebRequest::getGlobalRequestURL(),
550 'cookies' => $headers['set-cookie'],
551 'cache-control' => $cacheControl ?: '<not set>',
556 } );
559 MWExceptionHandler::installHandler();
561 require_once "$IP/includes/compat/normal/UtfNormalUtil.php";
563 $ps_validation = Profiler::instance()->scopedProfileIn( $fname . '-validation' );
565 // T48998: Bail out early if $wgArticlePath is non-absolute
566 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
567 if ( $$varName && !preg_match( '/^(https?:\/\/|\/)/', $$varName ) ) {
568 throw new FatalError(
569 "If you use a relative URL for \$$varName, it must start " .
570 'with a slash (<code>/</code>).<br><br>See ' .
571 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
572 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
577 Profiler::instance()->scopedProfileOut( $ps_validation );
579 $ps_default2 = Profiler::instance()->scopedProfileIn( $fname . '-defaults2' );
581 if ( $wgCanonicalServer === false ) {
582 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP );
585 // Set server name
586 $serverParts = wfParseUrl( $wgCanonicalServer );
587 if ( $wgServerName !== false ) {
588 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
589 . 'not customized. Overwriting $wgServerName.' );
591 $wgServerName = $serverParts['host'];
592 unset( $serverParts );
594 // Set defaults for configuration variables
595 // that are derived from the server name by default
596 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
597 if ( !$wgEmergencyContact ) {
598 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
600 if ( !$wgPasswordSender ) {
601 $wgPasswordSender = 'apache@' . $wgServerName;
603 if ( !$wgNoReplyAddress ) {
604 $wgNoReplyAddress = $wgPasswordSender;
607 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
608 $wgSecureLogin = false;
609 wfWarn( 'Secure login was enabled on a server that only supports '
610 . 'HTTP or HTTPS. Disabling secure login.' );
613 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
615 // Now that GlobalFunctions is loaded, set defaults that depend on it.
616 if ( $wgTmpDirectory === false ) {
617 $wgTmpDirectory = wfTempDir();
620 // We don't use counters anymore. Left here for extensions still
621 // expecting this to exist. Should be removed sometime 1.26 or later.
622 if ( !isset( $wgDisableCounters ) ) {
623 $wgDisableCounters = true;
626 if ( $wgMainWANCache === false ) {
627 // Setup a WAN cache from $wgMainCacheType with no relayer.
628 // Sites using multiple datacenters can configure a relayer.
629 $wgMainWANCache = 'mediawiki-main-default';
630 $wgWANObjectCaches[$wgMainWANCache] = [
631 'class' => 'WANObjectCache',
632 'cacheId' => $wgMainCacheType,
633 'pool' => 'mediawiki-main-default',
634 'relayerConfig' => [ 'class' => 'EventRelayerNull' ]
638 Profiler::instance()->scopedProfileOut( $ps_default2 );
640 $ps_misc = Profiler::instance()->scopedProfileIn( $fname . '-misc1' );
642 // Raise the memory limit if it's too low
643 wfMemoryLimit();
646 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
647 * that happens whenever you use a date function without the timezone being
648 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
650 if ( is_null( $wgLocaltimezone ) ) {
651 MediaWiki\suppressWarnings();
652 $wgLocaltimezone = date_default_timezone_get();
653 MediaWiki\restoreWarnings();
656 date_default_timezone_set( $wgLocaltimezone );
657 if ( is_null( $wgLocalTZoffset ) ) {
658 $wgLocalTZoffset = date( 'Z' ) / 60;
661 if ( !$wgDBerrorLogTZ ) {
662 $wgDBerrorLogTZ = $wgLocaltimezone;
665 // initialize the request object in $wgRequest
666 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
668 // Useful debug output
669 if ( $wgCommandLineMode ) {
670 wfDebug( "\n\nStart command line script $self\n" );
671 } else {
672 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
674 if ( $wgDebugPrintHttpHeaders ) {
675 $debug .= "HTTP HEADERS:\n";
677 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
678 $debug .= "$name: $value\n";
681 wfDebug( $debug );
684 Profiler::instance()->scopedProfileOut( $ps_misc );
685 $ps_memcached = Profiler::instance()->scopedProfileIn( $fname . '-memcached' );
687 $wgMemc = wfGetMainCache();
688 $messageMemc = wfGetMessageCacheStorage();
689 $parserMemc = wfGetParserCacheStorage();
691 wfDebugLog( 'caches',
692 'cluster: ' . get_class( $wgMemc ) .
693 ', WAN: ' . $wgMainWANCache .
694 ', stash: ' . $wgMainStash .
695 ', message: ' . get_class( $messageMemc ) .
696 ', parser: ' . get_class( $parserMemc ) );
698 Profiler::instance()->scopedProfileOut( $ps_memcached );
700 // Most of the config is out, some might want to run hooks here.
701 Hooks::run( 'SetupAfterCache' );
703 $ps_globals = Profiler::instance()->scopedProfileIn( $fname . '-globals' );
706 * @var Language $wgContLang
708 $wgContLang = Language::factory( $wgLanguageCode );
709 $wgContLang->initEncoding();
710 $wgContLang->initContLang();
712 // Now that variant lists may be available...
713 $wgRequest->interpolateTitle();
715 if ( !is_object( $wgAuth ) ) {
716 $wgAuth = new AuthPlugin;
717 Hooks::run( 'AuthPluginSetup', [ &$wgAuth ] );
720 // Set up the session
721 $ps_session = Profiler::instance()->scopedProfileIn( $fname . '-session' );
723 * @var MediaWiki\\Session\\SessionId|null $wgInitialSessionId The persistent
724 * session ID (if any) loaded at startup
726 $wgInitialSessionId = null;
727 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
728 // If session.auto_start is there, we can't touch session name
729 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
730 session_name( $wgSessionName ? $wgSessionName : $wgCookiePrefix . '_session' );
733 // Create the SessionManager singleton and set up our session handler,
734 // unless we're specifically asked not to.
735 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
736 MediaWiki\Session\PHPSessionHandler::install(
737 MediaWiki\Session\SessionManager::singleton()
741 // Initialize the session
742 try {
743 $session = MediaWiki\Session\SessionManager::getGlobalSession();
744 } catch ( OverflowException $ex ) {
745 if ( isset( $ex->sessionInfos ) && count( $ex->sessionInfos ) >= 2 ) {
746 // The exception is because the request had multiple possible
747 // sessions tied for top priority. Report this to the user.
748 $list = [];
749 foreach ( $ex->sessionInfos as $info ) {
750 $list[] = $info->getProvider()->describe( $wgContLang );
752 $list = $wgContLang->listToText( $list );
753 throw new HttpError( 400,
754 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
758 // Not the one we want, rethrow
759 throw $ex;
762 if ( $session->isPersistent() ) {
763 $wgInitialSessionId = $session->getSessionId();
766 $session->renew();
767 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
768 ( $session->isPersistent() || $session->shouldRememberUser() )
770 // Start the PHP-session for backwards compatibility
771 session_id( $session->getId() );
772 MediaWiki\quietCall( 'session_start' );
775 unset( $session );
776 } else {
777 // Even if we didn't set up a global Session, still install our session
778 // handler unless specifically requested not to.
779 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
780 MediaWiki\Session\PHPSessionHandler::install(
781 MediaWiki\Session\SessionManager::singleton()
785 Profiler::instance()->scopedProfileOut( $ps_session );
788 * @var User $wgUser
790 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
793 * @var Language $wgLang
795 $wgLang = new StubUserLang;
798 * @var OutputPage $wgOut
800 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
803 * @var Parser $wgParser
805 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], [ $wgParserConf ] );
808 * @var Title $wgTitle
810 $wgTitle = null;
812 Profiler::instance()->scopedProfileOut( $ps_globals );
813 $ps_extensions = Profiler::instance()->scopedProfileIn( $fname . '-extensions' );
815 // Extension setup functions
816 // Entries should be added to this variable during the inclusion
817 // of the extension file. This allows the extension to perform
818 // any necessary initialisation in the fully initialised environment
819 foreach ( $wgExtensionFunctions as $func ) {
820 // Allow closures in PHP 5.3+
821 if ( is_object( $func ) && $func instanceof Closure ) {
822 $profName = $fname . '-extensions-closure';
823 } elseif ( is_array( $func ) ) {
824 if ( is_object( $func[0] ) ) {
825 $profName = $fname . '-extensions-' . get_class( $func[0] ) . '::' . $func[1];
826 } else {
827 $profName = $fname . '-extensions-' . implode( '::', $func );
829 } else {
830 $profName = $fname . '-extensions-' . strval( $func );
833 $ps_ext_func = Profiler::instance()->scopedProfileIn( $profName );
834 call_user_func( $func );
835 Profiler::instance()->scopedProfileOut( $ps_ext_func );
838 // If the session user has a 0 id but a valid name, that means we need to
839 // autocreate it.
840 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
841 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
842 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
843 $ps_autocreate = Profiler::instance()->scopedProfileIn( $fname . '-autocreate' );
844 MediaWiki\Session\SessionManager::autoCreateUser( $sessionUser );
845 Profiler::instance()->scopedProfileOut( $ps_autocreate );
847 unset( $sessionUser );
850 wfDebug( "Fully initialised\n" );
851 $wgFullyInitialised = true;
853 Profiler::instance()->scopedProfileOut( $ps_extensions );
854 Profiler::instance()->scopedProfileOut( $ps_setup );