filebackend: use self:: instead of FileBackend:: for some constant uses
[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 global constants
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 } elseif ( file_exists( "$IP/vendor/autoload.php" ) ) {
71 die( "$IP/vendor/autoload.php exists but is not readable" );
72 }
73
74 // Assert that composer dependencies were successfully loaded
75 // Purposely no leading \ due to it breaking HHVM RepoAuthorative mode
76 // PHP works fine with both versions
77 // See https://github.com/facebook/hhvm/issues/5833
78 if ( !interface_exists( 'Psr\Log\LoggerInterface' ) ) {
79 $message = (
80 'MediaWiki requires the <a href="https://github.com/php-fig/log">PSR-3 logging ' .
81 "library</a> to be present. This library is not embedded directly in MediaWiki's " .
82 "git repository and must be installed separately by the end user.\n\n" .
83 'Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git' .
84 '#Fetch_external_libraries">mediawiki.org</a> for help on installing ' .
85 'the required components.'
86 );
87 echo $message;
88 trigger_error( $message, E_USER_ERROR );
89 die( 1 );
90 }
91
92 /**
93 * Changes to the PHP environment that don't vary on configuration.
94 */
95
96 // Install a header callback
97 MediaWiki\HeaderCallback::register();
98
99 // Set the encoding used by PHP for reading HTTP input, and writing output.
100 // This is also the default for mbstring functions.
101 mb_internal_encoding( 'UTF-8' );
102
103 /**
104 * Load LocalSettings.php
105 */
106
107 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
108 call_user_func( MW_CONFIG_CALLBACK );
109 } else {
110 if ( !defined( 'MW_CONFIG_FILE' ) ) {
111 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
112 }
113 require_once MW_CONFIG_FILE;
114 }
115
116 /**
117 * Customization point after all loading (constants, functions, classes,
118 * DefaultSettings, LocalSettings). Specifically, this is before usage of
119 * settings, before instantiation of Profiler (and other singletons), and
120 * before any setup functions or hooks run.
121 */
122
123 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
124 call_user_func( MW_SETUP_CALLBACK );
125 }
126
127 /**
128 * Main setup
129 */
130
131 // Load queued extensions
132 ExtensionRegistry::getInstance()->loadFromQueue();
133 // Don't let any other extensions load
134 ExtensionRegistry::getInstance()->finish();
135
136 // Set the configured locale on all requests for consisteny
137 putenv( "LC_ALL=$wgShellLocale" );
138 setlocale( LC_ALL, $wgShellLocale );
139
140 // Set various default paths sensibly...
141 if ( $wgScript === false ) {
142 $wgScript = "$wgScriptPath/index.php";
143 }
144 if ( $wgLoadScript === false ) {
145 $wgLoadScript = "$wgScriptPath/load.php";
146 }
147 if ( $wgRestPath === false ) {
148 $wgRestPath = "$wgScriptPath/rest.php";
149 }
150
151 if ( $wgArticlePath === false ) {
152 if ( $wgUsePathInfo ) {
153 $wgArticlePath = "$wgScript/$1";
154 } else {
155 $wgArticlePath = "$wgScript?title=$1";
156 }
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 // Fix path to icon images after they were moved in 1.24
198 if ( $wgRightsIcon ) {
199 $wgRightsIcon = str_replace(
200 "{$wgStylePath}/common/images/",
201 "{$wgResourceBasePath}/resources/assets/licenses/",
202 $wgRightsIcon
203 );
204 }
205
206 if ( isset( $wgFooterIcons['copyright']['copyright'] )
207 && $wgFooterIcons['copyright']['copyright'] === []
208 ) {
209 if ( $wgRightsIcon || $wgRightsText ) {
210 $wgFooterIcons['copyright']['copyright'] = [
211 'url' => $wgRightsUrl,
212 'src' => $wgRightsIcon,
213 'alt' => $wgRightsText,
214 ];
215 }
216 }
217
218 if ( isset( $wgFooterIcons['poweredby'] )
219 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
220 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
221 ) {
222 $wgFooterIcons['poweredby']['mediawiki']['src'] =
223 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
224 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
225 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
226 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
227 }
228
229 /**
230 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
231 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
232 *
233 * Note that this is the definition of editinterface and it can be granted to
234 * all users if desired.
235 */
236 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
237
238 /**
239 * The canonical names of namespaces 6 and 7 are, as of v1.14, "File"
240 * and "File_talk". The old names "Image" and "Image_talk" are
241 * retained as aliases for backwards compatibility.
242 */
243 $wgNamespaceAliases['Image'] = NS_FILE;
244 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
245
246 /**
247 * Initialise $wgLockManagers to include basic FS version
248 */
249 $wgLockManagers[] = [
250 'name' => 'fsLockManager',
251 'class' => FSLockManager::class,
252 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
253 ];
254 $wgLockManagers[] = [
255 'name' => 'nullLockManager',
256 'class' => NullLockManager::class,
257 ];
258
259 /**
260 * Default parameters for the "<gallery>" tag.
261 * @see DefaultSettings.php for description of the fields.
262 */
263 $wgGalleryOptions += [
264 'imagesPerRow' => 0,
265 'imageWidth' => 120,
266 'imageHeight' => 120,
267 'captionLength' => true,
268 'showBytes' => true,
269 'showDimensions' => true,
270 'mode' => 'traditional',
271 ];
272
273 /**
274 * Shortcuts for $wgLocalFileRepo
275 */
276 if ( !$wgLocalFileRepo ) {
277 $wgLocalFileRepo = [
278 'class' => LocalRepo::class,
279 'name' => 'local',
280 'directory' => $wgUploadDirectory,
281 'scriptDirUrl' => $wgScriptPath,
282 'url' => $wgUploadBaseUrl ? $wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
283 'hashLevels' => $wgHashedUploadDirectory ? 2 : 0,
284 'thumbScriptUrl' => $wgThumbnailScriptPath,
285 'transformVia404' => !$wgGenerateThumbnailOnParse,
286 'deletedDir' => $wgDeletedDirectory,
287 'deletedHashLevels' => $wgHashedUploadDirectory ? 3 : 0
288 ];
289 }
290
291 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
292 // Create a default FileBackend name.
293 // FileBackendGroup will register a default, if absent from $wgFileBackends.
294 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
295 }
296
297 /**
298 * Shortcuts for $wgForeignFileRepos
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 foreach ( $wgForeignFileRepos as &$repo ) {
350 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo::class ) {
351 $repo['directory'] = $wgUploadDirectory; // b/c
352 }
353 if ( !isset( $repo['backend'] ) ) {
354 $repo['backend'] = $repo['name'] . '-backend';
355 }
356 }
357 unset( $repo ); // no global pollution; destroy reference
358
359 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
360 // Ensure that default user options are not invalid, since that breaks Special:Preferences
361 $wgDefaultUserOptions['rcdays'] = min(
362 $wgDefaultUserOptions['rcdays'],
363 ceil( $rcMaxAgeDays )
364 );
365 $wgDefaultUserOptions['watchlistdays'] = min(
366 $wgDefaultUserOptions['watchlistdays'],
367 ceil( $rcMaxAgeDays )
368 );
369 unset( $rcMaxAgeDays );
370
371 if ( $wgSkipSkin ) {
372 // Hard deprecated in 1.34.
373 wfDeprecated( '$wgSkipSkin – use $wgSkipSkins instead', '1.23' );
374 $wgSkipSkins[] = $wgSkipSkin;
375 }
376
377 $wgSkipSkins[] = 'fallback';
378 $wgSkipSkins[] = 'apioutput';
379
380 if ( $wgLocalInterwiki ) {
381 // Hard deprecated in 1.34.
382 wfDeprecated( '$wgLocalInterwiki – use $wgLocalInterwikis instead', '1.23' );
383 // @phan-suppress-next-line PhanUndeclaredVariableDim
384 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
385 }
386
387 // Set default shared prefix
388 if ( $wgSharedPrefix === false ) {
389 $wgSharedPrefix = $wgDBprefix;
390 }
391
392 // Set default shared schema
393 if ( $wgSharedSchema === false ) {
394 $wgSharedSchema = $wgDBmwschema;
395 }
396
397 if ( !$wgCookiePrefix ) {
398 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
399 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
400 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
401 $wgCookiePrefix = $wgSharedDB;
402 } elseif ( $wgDBprefix ) {
403 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
404 } else {
405 $wgCookiePrefix = $wgDBname;
406 }
407 }
408 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
409
410 if ( $wgEnableEmail ) {
411 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
412 } else {
413 // Disable all other email settings automatically if $wgEnableEmail
414 // is set to false. - T65678
415 $wgAllowHTMLEmail = false;
416 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
417 $wgEnableUserEmail = false;
418 $wgEnotifFromEditor = false;
419 $wgEnotifImpersonal = false;
420 $wgEnotifMaxRecips = 0;
421 $wgEnotifMinorEdits = false;
422 $wgEnotifRevealEditorAddress = false;
423 $wgEnotifUseRealName = false;
424 $wgEnotifUserTalk = false;
425 $wgEnotifWatchlist = false;
426 unset( $wgGroupPermissions['user']['sendemail'] );
427 $wgUseEnotif = false;
428 $wgUserEmailUseReplyTo = false;
429 $wgUsersNotifiedOnAllChanges = [];
430 }
431
432 if ( $wgMetaNamespace === false ) {
433 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
434 }
435
436 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
437 // upload size.
438 $wgMinUploadChunkSize = min(
439 $wgMinUploadChunkSize,
440 UploadBase::getMaxUploadSize( 'file' ),
441 UploadBase::getMaxPhpUploadSize(),
442 ( wfShorthandToInteger(
443 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
444 PHP_INT_MAX
445 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
446 );
447
448 /**
449 * Definitions of the NS_ constants are in Defines.php
450 * @private
451 */
452 $wgCanonicalNamespaceNames = NamespaceInfo::$canonicalNames;
453
454 /// @todo UGLY UGLY
455 if ( is_array( $wgExtraNamespaces ) ) {
456 $wgCanonicalNamespaceNames += $wgExtraNamespaces;
457 }
458
459 // Hard-deprecate setting $wgDummyLanguageCodes in LocalSettings.php
460 if ( count( $wgDummyLanguageCodes ) !== 0 ) {
461 wfDeprecated( '$wgDummyLanguageCodes', '1.29' );
462 }
463 // Merge in the legacy language codes, incorporating overrides from the config
464 $wgDummyLanguageCodes += [
465 // Internal language codes of the private-use area which get mapped to
466 // themselves.
467 'qqq' => 'qqq', // Used for message documentation
468 'qqx' => 'qqx', // Used for viewing message keys
469 ] + $wgExtraLanguageCodes + LanguageCode::getDeprecatedCodeMapping();
470 // Merge in (inverted) BCP 47 mappings
471 foreach ( LanguageCode::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
472 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
473 if ( !isset( $wgDummyLanguageCodes[$bcp47] ) ) {
474 $wgDummyLanguageCodes[$bcp47] = $wgDummyLanguageCodes[$code] ?? $code;
475 }
476 }
477
478 // These are now the same, always
479 // To determine the user language, use $wgLang->getCode()
480 $wgContLanguageCode = $wgLanguageCode;
481
482 // Temporary backwards-compatibility reading of old Squid-named CDN settings as of MediaWiki 1.34,
483 // to support sysadmins who fail to update their settings immediately:
484
485 if ( isset( $wgUseSquid ) ) {
486 // If the sysadmin is still setting a value of $wgUseSquid to true but $wgUseCdn is the default of
487 // false, to be safe, assume they do want this still, so enable it.
488 if ( !$wgUseCdn && $wgUseSquid ) {
489 $wgUseCdn = $wgUseSquid;
490 wfDeprecated( '$wgUseSquid enabled but $wgUseCdn disabled; enabling CDN functions', '1.34' );
491 }
492 } else {
493 // Backwards-compatibility for extensions that read this value.
494 $wgUseSquid = $wgUseCdn;
495 }
496
497 if ( isset( $wgSquidServers ) ) {
498 // If the sysadmin is still setting a value of $wgSquidServers but $wgCdnServers is the default of
499 // empty, to be safe, assume they do want these servers to be still used, so use them.
500 if ( !empty( $wgSquidServers ) && empty( $wgCdnServers ) ) {
501 $wgCdnServers = $wgSquidServers;
502 wfDeprecated( '$wgSquidServers set, $wgCdnServers empty; using them', '1.34' );
503 }
504 } else {
505 // Backwards-compatibility for extensions that read this value.
506 $wgSquidServers = $wgCdnServers;
507 }
508
509 if ( isset( $wgSquidServersNoPurge ) ) {
510 // If the sysadmin is still setting values in $wgSquidServersNoPurge but $wgCdnServersNoPurge is
511 // the default of empty, to be safe, assume they do want these servers to be still used, so use
512 // them.
513 if ( !empty( $wgSquidServersNoPurge ) && empty( $wgCdnServersNoPurge ) ) {
514 $wgCdnServersNoPurge = $wgSquidServersNoPurge;
515 wfDeprecated( '$wgSquidServersNoPurge set, $wgCdnServersNoPurge empty; using them', '1.34' );
516 }
517 } else {
518 // Backwards-compatibility for extensions that read this value.
519 $wgSquidServersNoPurge = $wgCdnServersNoPurge;
520 }
521
522 if ( isset( $wgSquidMaxage ) ) {
523 // If the sysadmin is still setting a value of $wgSquidMaxage and it's higher than $wgCdnMaxAge,
524 // to be safe, assume they want the higher (lower performance requirement) value, so use that.
525 if ( $wgCdnMaxAge < $wgSquidMaxage ) {
526 $wgCdnMaxAge = $wgSquidMaxage;
527 wfDeprecated( '$wgSquidMaxage set higher than $wgCdnMaxAge; using the higher value', '1.34' );
528 }
529 } else {
530 // Backwards-compatibility for extensions that read this value.
531 $wgSquidMaxage = $wgCdnMaxAge;
532 }
533
534 // Blacklisted file extensions shouldn't appear on the "allowed" list
535 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
536
537 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
538 Wikimedia\suppressWarnings();
539 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
540 Wikimedia\restoreWarnings();
541 }
542
543 if ( $wgNewUserLog ) {
544 // Add new user log type
545 $wgLogTypes[] = 'newusers';
546 $wgLogNames['newusers'] = 'newuserlogpage';
547 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
548 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter::class;
549 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter::class;
550 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter::class;
551 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter::class;
552 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter::class;
553 }
554
555 if ( $wgPageCreationLog ) {
556 // Add page creation log type
557 $wgLogTypes[] = 'create';
558 $wgLogActionsHandlers['create/create'] = LogFormatter::class;
559 }
560
561 if ( $wgPageLanguageUseDB ) {
562 $wgLogTypes[] = 'pagelang';
563 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter::class;
564 }
565
566 if ( $wgCookieSecure === 'detect' ) {
567 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
568 }
569
570 if ( $wgProfileOnly ) {
571 // Hard deprecated in 1.34.
572 wfDeprecated(
573 '$wgProfileOnly set the log file in $wgDebugLogGroups[\'profileoutput\'] instead',
574 '1.23'
575 );
576 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
577 $wgDebugLogFile = '';
578 }
579
580 // Backwards compatibility with old password limits
581 if ( $wgMinimalPasswordLength !== false ) {
582 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
583 }
584
585 if ( $wgMaximalPasswordLength !== false ) {
586 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
587 }
588
589 if ( $wgPHPSessionHandling !== 'enable' &&
590 $wgPHPSessionHandling !== 'warn' &&
591 $wgPHPSessionHandling !== 'disable'
592 ) {
593 $wgPHPSessionHandling = 'warn';
594 }
595 if ( defined( 'MW_NO_SESSION' ) ) {
596 // If the entry point wants no session, force 'disable' here unless they
597 // specifically set it to the (undocumented) 'warn'.
598 // @phan-suppress-next-line PhanUndeclaredConstant
599 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
600 }
601
602 MWDebug::setup();
603
604 // Reset the global service locator, so any services that have already been created will be
605 // re-created while taking into account any custom settings and extensions.
606 MediaWikiServices::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
607
608 // Define a constant that indicates that the bootstrapping of the service locator
609 // is complete.
610 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
611
612 MWExceptionHandler::installHandler();
613
614 // T48998: Bail out early if $wgArticlePath is non-absolute
615 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
616 if ( $$varName && !preg_match( '/^(https?:\/\/|\/)/', $$varName ) ) {
617 throw new FatalError(
618 "If you use a relative URL for \$$varName, it must start " .
619 'with a slash (<code>/</code>).<br><br>See ' .
620 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
621 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
622 );
623 }
624 }
625
626 if ( $wgCanonicalServer === false ) {
627 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP );
628 }
629
630 // Set server name
631 $serverParts = wfParseUrl( $wgCanonicalServer );
632 if ( $wgServerName !== false ) {
633 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
634 . 'not customized. Overwriting $wgServerName.' );
635 }
636 $wgServerName = $serverParts['host'];
637 unset( $serverParts );
638
639 // Set defaults for configuration variables
640 // that are derived from the server name by default
641 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
642 if ( !$wgEmergencyContact ) {
643 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
644 }
645 if ( !$wgPasswordSender ) {
646 $wgPasswordSender = 'apache@' . $wgServerName;
647 }
648 if ( !$wgNoReplyAddress ) {
649 $wgNoReplyAddress = $wgPasswordSender;
650 }
651
652 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
653 $wgSecureLogin = false;
654 wfWarn( 'Secure login was enabled on a server that only supports '
655 . 'HTTP or HTTPS. Disabling secure login.' );
656 }
657
658 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
659
660 // Now that GlobalFunctions is loaded, set defaults that depend on it.
661 if ( $wgTmpDirectory === false ) {
662 $wgTmpDirectory = wfTempDir();
663 }
664
665 // We don't use counters anymore. Left here for extensions still
666 // expecting this to exist. Should be removed sometime 1.26 or later.
667 if ( !isset( $wgDisableCounters ) ) {
668 $wgDisableCounters = true;
669 }
670
671 if ( $wgMainWANCache === false ) {
672 // Setup a WAN cache from $wgMainCacheType with no relayer.
673 // Sites using multiple datacenters can configure a relayer.
674 $wgMainWANCache = 'mediawiki-main-default';
675 $wgWANObjectCaches[$wgMainWANCache] = [
676 'class' => WANObjectCache::class,
677 'cacheId' => $wgMainCacheType
678 ];
679 }
680
681 if ( $wgSharedDB && $wgSharedTables ) {
682 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
683 MediaWikiServices::getInstance()->getDBLoadBalancer()->setTableAliases(
684 array_fill_keys(
685 $wgSharedTables,
686 [
687 'dbname' => $wgSharedDB,
688 'schema' => $wgSharedSchema,
689 'prefix' => $wgSharedPrefix
690 ]
691 )
692 );
693 }
694
695 // Raise the memory limit if it's too low
696 // Note, this makes use of wfDebug, and thus should not be before
697 // MWDebug::init() is called.
698 wfMemoryLimit( $wgMemoryLimit );
699
700 /**
701 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
702 * that happens whenever you use a date function without the timezone being
703 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
704 */
705 if ( is_null( $wgLocaltimezone ) ) {
706 Wikimedia\suppressWarnings();
707 $wgLocaltimezone = date_default_timezone_get();
708 Wikimedia\restoreWarnings();
709 }
710
711 date_default_timezone_set( $wgLocaltimezone );
712 if ( is_null( $wgLocalTZoffset ) ) {
713 $wgLocalTZoffset = date( 'Z' ) / 60;
714 }
715 // The part after the System| is ignored, but rest of MW fills it
716 // out as the local offset.
717 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
718
719 if ( !$wgDBerrorLogTZ ) {
720 $wgDBerrorLogTZ = $wgLocaltimezone;
721 }
722
723 // Initialize the request object in $wgRequest
724 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
725 // Set user IP/agent information for agent session consistency purposes
726 $cpPosInfo = LBFactory::getCPInfoFromCookieValue(
727 // The cookie has no prefix and is set by MediaWiki::preOutputCommit()
728 $wgRequest->getCookie( 'cpPosIndex', '' ),
729 // Mitigate broken client-side cookie expiration handling (T190082)
730 time() - ChronologyProtector::POSITION_COOKIE_TTL
731 );
732 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
733 'IPAddress' => $wgRequest->getIP(),
734 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
735 'ChronologyProtection' => $wgRequest->getHeader( 'MediaWiki-Chronology-Protection' ),
736 'ChronologyPositionIndex' => $wgRequest->getInt( 'cpPosIndex', $cpPosInfo['index'] ),
737 'ChronologyClientId' => $cpPosInfo['clientId']
738 ?? $wgRequest->getHeader( 'MediaWiki-Chronology-Client-Id' )
739 ] );
740 unset( $cpPosInfo );
741 // Make sure that object caching does not undermine the ChronologyProtector improvements
742 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
743 // The user is pinned to the primary DC, meaning that they made recent changes which should
744 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
745 // they use a blind TTL and could be stale if an object changes twice in a short time span.
746 MediaWikiServices::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
747 }
748
749 // Useful debug output
750 if ( $wgCommandLineMode ) {
751 if ( isset( $self ) ) {
752 wfDebug( "\n\nStart command line script $self\n" );
753 }
754 } else {
755 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
756 $debug .= "HTTP HEADERS:\n";
757 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
758 $debug .= "$name: $value\n";
759 }
760 wfDebug( $debug );
761 }
762
763 $wgMemc = ObjectCache::getLocalClusterInstance();
764 $messageMemc = wfGetMessageCacheStorage();
765
766 // Most of the config is out, some might want to run hooks here.
767 Hooks::run( 'SetupAfterCache' );
768
769 /**
770 * @var Language $wgContLang
771 * @deprecated since 1.32, use the ContentLanguage service directly
772 */
773 $wgContLang = MediaWikiServices::getInstance()->getContentLanguage();
774
775 // Now that variant lists may be available...
776 $wgRequest->interpolateTitle();
777
778 /**
779 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
780 * session ID (if any) loaded at startup
781 */
782 $wgInitialSessionId = null;
783 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
784 // If session.auto_start is there, we can't touch session name
785 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
786 session_name( $wgSessionName ?: $wgCookiePrefix . '_session' );
787 }
788
789 // Create the SessionManager singleton and set up our session handler,
790 // unless we're specifically asked not to.
791 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
792 MediaWiki\Session\PHPSessionHandler::install(
793 MediaWiki\Session\SessionManager::singleton()
794 );
795 }
796
797 // Initialize the session
798 try {
799 $session = MediaWiki\Session\SessionManager::getGlobalSession();
800 } catch ( OverflowException $ex ) {
801 if ( isset( $ex->sessionInfos ) && count( $ex->sessionInfos ) >= 2 ) {
802 // The exception is because the request had multiple possible
803 // sessions tied for top priority. Report this to the user.
804 $list = [];
805 foreach ( $ex->sessionInfos as $info ) {
806 $list[] = $info->getProvider()->describe( $wgContLang );
807 }
808 $list = $wgContLang->listToText( $list );
809 throw new HttpError( 400,
810 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
811 );
812 }
813
814 // Not the one we want, rethrow
815 throw $ex;
816 }
817
818 if ( $session->isPersistent() ) {
819 $wgInitialSessionId = $session->getSessionId();
820 }
821
822 $session->renew();
823 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
824 ( $session->isPersistent() || $session->shouldRememberUser() ) &&
825 session_id() !== $session->getId()
826 ) {
827 // Start the PHP-session for backwards compatibility
828 if ( session_id() !== '' ) {
829 wfDebugLog( 'session', 'PHP session {old_id} was already started, changing to {new_id}', 'all', [
830 'old_id' => session_id(),
831 'new_id' => $session->getId(),
832 ] );
833 session_write_close();
834 }
835 session_id( $session->getId() );
836 session_start();
837 }
838
839 unset( $session );
840 } else {
841 // Even if we didn't set up a global Session, still install our session
842 // handler unless specifically requested not to.
843 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
844 MediaWiki\Session\PHPSessionHandler::install(
845 MediaWiki\Session\SessionManager::singleton()
846 );
847 }
848 }
849
850 /**
851 * @var User $wgUser
852 */
853 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
854
855 /**
856 * @var Language $wgLang
857 */
858 $wgLang = new StubUserLang;
859
860 /**
861 * @var OutputPage $wgOut
862 */
863 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
864
865 /**
866 * @var Parser $wgParser
867 * @deprecated since 1.32, use MediaWikiServices::getInstance()->getParser() instead
868 */
869 $wgParser = new StubObject( 'wgParser', function () {
870 return MediaWikiServices::getInstance()->getParser();
871 } );
872
873 /**
874 * @var Title $wgTitle
875 */
876 $wgTitle = null;
877
878 // Extension setup functions
879 // Entries should be added to this variable during the inclusion
880 // of the extension file. This allows the extension to perform
881 // any necessary initialisation in the fully initialised environment
882 foreach ( $wgExtensionFunctions as $func ) {
883 call_user_func( $func );
884 }
885
886 // If the session user has a 0 id but a valid name, that means we need to
887 // autocreate it.
888 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
889 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
890 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
891 $res = MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
892 $sessionUser,
893 MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
894 true
895 );
896 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Autocreation attempt', [
897 'event' => 'autocreate',
898 'status' => $res,
899 ] );
900 unset( $res );
901 }
902 unset( $sessionUser );
903 }
904
905 if ( !$wgCommandLineMode ) {
906 Pingback::schedulePingback();
907 }
908
909 $wgFullyInitialised = true;