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