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