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