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