Setup: Move wgActionPath logic to PathRouter
[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 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
437 if ( $wgResourceLoaderMaxQueryLength === false ) {
438 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
439 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
440 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
441 } else {
442 $wgResourceLoaderMaxQueryLength = 2000;
443 }
444 unset( $suhosinMaxValueLength );
445 }
446
447 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
448 // upload size.
449 $wgMinUploadChunkSize = min(
450 $wgMinUploadChunkSize,
451 UploadBase::getMaxUploadSize( 'file' ),
452 UploadBase::getMaxPhpUploadSize(),
453 ( wfShorthandToInteger(
454 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
455 PHP_INT_MAX
456 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
457 );
458
459 /**
460 * Definitions of the NS_ constants are in Defines.php
461 * @private
462 */
463 $wgCanonicalNamespaceNames = NamespaceInfo::$canonicalNames;
464
465 /// @todo UGLY UGLY
466 if ( is_array( $wgExtraNamespaces ) ) {
467 $wgCanonicalNamespaceNames += $wgExtraNamespaces;
468 }
469
470 // Hard-deprecate setting $wgDummyLanguageCodes in LocalSettings.php
471 if ( count( $wgDummyLanguageCodes ) !== 0 ) {
472 wfDeprecated( '$wgDummyLanguageCodes', '1.29' );
473 }
474 // Merge in the legacy language codes, incorporating overrides from the config
475 $wgDummyLanguageCodes += [
476 // Internal language codes of the private-use area which get mapped to
477 // themselves.
478 'qqq' => 'qqq', // Used for message documentation
479 'qqx' => 'qqx', // Used for viewing message keys
480 ] + $wgExtraLanguageCodes + LanguageCode::getDeprecatedCodeMapping();
481 // Merge in (inverted) BCP 47 mappings
482 foreach ( LanguageCode::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
483 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
484 if ( !isset( $wgDummyLanguageCodes[$bcp47] ) ) {
485 $wgDummyLanguageCodes[$bcp47] = $wgDummyLanguageCodes[$code] ?? $code;
486 }
487 }
488
489 // These are now the same, always
490 // To determine the user language, use $wgLang->getCode()
491 $wgContLanguageCode = $wgLanguageCode;
492
493 // Temporary backwards-compatibility reading of old Squid-named CDN settings as of MediaWiki 1.34,
494 // to support sysadmins who fail to update their settings immediately:
495
496 if ( isset( $wgUseSquid ) ) {
497 // If the sysadmin is still setting a value of $wgUseSquid to true but $wgUseCdn is the default of
498 // false, to be safe, assume they do want this still, so enable it.
499 if ( !$wgUseCdn && $wgUseSquid ) {
500 $wgUseCdn = $wgUseSquid;
501 wfDeprecated( '$wgUseSquid enabled but $wgUseCdn disabled; enabling CDN functions', '1.34' );
502 }
503 } else {
504 // Backwards-compatibility for extensions that read this value.
505 $wgUseSquid = $wgUseCdn;
506 }
507
508 if ( isset( $wgSquidServers ) ) {
509 // If the sysadmin is still setting a value of $wgSquidServers but $wgCdnServers is the default of
510 // empty, to be safe, assume they do want these servers to be still used, so use them.
511 if ( !empty( $wgSquidServers ) && empty( $wgCdnServers ) ) {
512 $wgCdnServers = $wgSquidServers;
513 wfDeprecated( '$wgSquidServers set, $wgCdnServers empty; using them', '1.34' );
514 }
515 } else {
516 // Backwards-compatibility for extensions that read this value.
517 $wgSquidServers = $wgCdnServers;
518 }
519
520 if ( isset( $wgSquidServersNoPurge ) ) {
521 // If the sysadmin is still setting values in $wgSquidServersNoPurge but $wgCdnServersNoPurge is
522 // the default of empty, to be safe, assume they do want these servers to be still used, so use
523 // them.
524 if ( !empty( $wgSquidServersNoPurge ) && empty( $wgCdnServersNoPurge ) ) {
525 $wgCdnServersNoPurge = $wgSquidServersNoPurge;
526 wfDeprecated( '$wgSquidServersNoPurge set, $wgCdnServersNoPurge empty; using them', '1.34' );
527 }
528 } else {
529 // Backwards-compatibility for extensions that read this value.
530 $wgSquidServersNoPurge = $wgCdnServersNoPurge;
531 }
532
533 if ( isset( $wgSquidMaxage ) ) {
534 // If the sysadmin is still setting a value of $wgSquidMaxage and it's higher than $wgCdnMaxAge,
535 // to be safe, assume they want the higher (lower performance requirement) value, so use that.
536 if ( $wgCdnMaxAge < $wgSquidMaxage ) {
537 $wgCdnMaxAge = $wgSquidMaxage;
538 wfDeprecated( '$wgSquidMaxage set higher than $wgCdnMaxAge; using the higher value', '1.34' );
539 }
540 } else {
541 // Backwards-compatibility for extensions that read this value.
542 $wgSquidMaxage = $wgCdnMaxAge;
543 }
544
545 // Easy to forget to falsify $wgDebugToolbar for static caches.
546 // If file cache or CDN cache is on, just disable this (DWIMD).
547 if ( $wgUseFileCache || $wgUseCdn ) {
548 $wgDebugToolbar = false;
549 }
550
551 // Blacklisted file extensions shouldn't appear on the "allowed" list
552 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
553
554 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
555 Wikimedia\suppressWarnings();
556 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
557 Wikimedia\restoreWarnings();
558 }
559
560 if ( $wgNewUserLog ) {
561 // Add new user log type
562 $wgLogTypes[] = 'newusers';
563 $wgLogNames['newusers'] = 'newuserlogpage';
564 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
565 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter::class;
566 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter::class;
567 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter::class;
568 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter::class;
569 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter::class;
570 }
571
572 if ( $wgPageCreationLog ) {
573 // Add page creation log type
574 $wgLogTypes[] = 'create';
575 $wgLogActionsHandlers['create/create'] = LogFormatter::class;
576 }
577
578 if ( $wgPageLanguageUseDB ) {
579 $wgLogTypes[] = 'pagelang';
580 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter::class;
581 }
582
583 if ( $wgCookieSecure === 'detect' ) {
584 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
585 }
586
587 if ( $wgProfileOnly ) {
588 // Hard deprecated in 1.34.
589 wfDeprecated(
590 '$wgProfileOnly set the log file in $wgDebugLogGroups[\'profileoutput\'] instead',
591 '1.23'
592 );
593 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
594 $wgDebugLogFile = '';
595 }
596
597 // Backwards compatibility with old password limits
598 if ( $wgMinimalPasswordLength !== false ) {
599 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
600 }
601
602 if ( $wgMaximalPasswordLength !== false ) {
603 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
604 }
605
606 if ( $wgPHPSessionHandling !== 'enable' &&
607 $wgPHPSessionHandling !== 'warn' &&
608 $wgPHPSessionHandling !== 'disable'
609 ) {
610 $wgPHPSessionHandling = 'warn';
611 }
612 if ( defined( 'MW_NO_SESSION' ) ) {
613 // If the entry point wants no session, force 'disable' here unless they
614 // specifically set it to the (undocumented) 'warn'.
615 // @phan-suppress-next-line PhanUndeclaredConstant
616 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
617 }
618
619 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
620 // all the memory from logging SQL queries on maintenance scripts
621 global $wgCommandLineMode;
622 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
623 MWDebug::init();
624 }
625
626 // Reset the global service locator, so any services that have already been created will be
627 // re-created while taking into account any custom settings and extensions.
628 MediaWikiServices::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
629
630 // Define a constant that indicates that the bootstrapping of the service locator
631 // is complete.
632 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
633
634 MWExceptionHandler::installHandler();
635
636 // T48998: Bail out early if $wgArticlePath is non-absolute
637 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
638 if ( $$varName && !preg_match( '/^(https?:\/\/|\/)/', $$varName ) ) {
639 throw new FatalError(
640 "If you use a relative URL for \$$varName, it must start " .
641 'with a slash (<code>/</code>).<br><br>See ' .
642 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
643 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
644 );
645 }
646 }
647
648 if ( $wgCanonicalServer === false ) {
649 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP );
650 }
651
652 // Set server name
653 $serverParts = wfParseUrl( $wgCanonicalServer );
654 if ( $wgServerName !== false ) {
655 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
656 . 'not customized. Overwriting $wgServerName.' );
657 }
658 $wgServerName = $serverParts['host'];
659 unset( $serverParts );
660
661 // Set defaults for configuration variables
662 // that are derived from the server name by default
663 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
664 if ( !$wgEmergencyContact ) {
665 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
666 }
667 if ( !$wgPasswordSender ) {
668 $wgPasswordSender = 'apache@' . $wgServerName;
669 }
670 if ( !$wgNoReplyAddress ) {
671 $wgNoReplyAddress = $wgPasswordSender;
672 }
673
674 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
675 $wgSecureLogin = false;
676 wfWarn( 'Secure login was enabled on a server that only supports '
677 . 'HTTP or HTTPS. Disabling secure login.' );
678 }
679
680 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
681
682 // Now that GlobalFunctions is loaded, set defaults that depend on it.
683 if ( $wgTmpDirectory === false ) {
684 $wgTmpDirectory = wfTempDir();
685 }
686
687 // We don't use counters anymore. Left here for extensions still
688 // expecting this to exist. Should be removed sometime 1.26 or later.
689 if ( !isset( $wgDisableCounters ) ) {
690 $wgDisableCounters = true;
691 }
692
693 if ( $wgMainWANCache === false ) {
694 // Setup a WAN cache from $wgMainCacheType with no relayer.
695 // Sites using multiple datacenters can configure a relayer.
696 $wgMainWANCache = 'mediawiki-main-default';
697 $wgWANObjectCaches[$wgMainWANCache] = [
698 'class' => WANObjectCache::class,
699 'cacheId' => $wgMainCacheType
700 ];
701 }
702
703 if ( $wgSharedDB && $wgSharedTables ) {
704 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
705 MediaWikiServices::getInstance()->getDBLoadBalancer()->setTableAliases(
706 array_fill_keys(
707 $wgSharedTables,
708 [
709 'dbname' => $wgSharedDB,
710 'schema' => $wgSharedSchema,
711 'prefix' => $wgSharedPrefix
712 ]
713 )
714 );
715 }
716
717 // Raise the memory limit if it's too low
718 // Note, this makes use of wfDebug, and thus should not be before
719 // MWDebug::init() is called.
720 wfMemoryLimit( $wgMemoryLimit );
721
722 /**
723 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
724 * that happens whenever you use a date function without the timezone being
725 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
726 */
727 if ( is_null( $wgLocaltimezone ) ) {
728 Wikimedia\suppressWarnings();
729 $wgLocaltimezone = date_default_timezone_get();
730 Wikimedia\restoreWarnings();
731 }
732
733 date_default_timezone_set( $wgLocaltimezone );
734 if ( is_null( $wgLocalTZoffset ) ) {
735 $wgLocalTZoffset = date( 'Z' ) / 60;
736 }
737 // The part after the System| is ignored, but rest of MW fills it
738 // out as the local offset.
739 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
740
741 if ( !$wgDBerrorLogTZ ) {
742 $wgDBerrorLogTZ = $wgLocaltimezone;
743 }
744
745 // Initialize the request object in $wgRequest
746 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
747 // Set user IP/agent information for agent session consistency purposes
748 $cpPosInfo = LBFactory::getCPInfoFromCookieValue(
749 // The cookie has no prefix and is set by MediaWiki::preOutputCommit()
750 $wgRequest->getCookie( 'cpPosIndex', '' ),
751 // Mitigate broken client-side cookie expiration handling (T190082)
752 time() - ChronologyProtector::POSITION_COOKIE_TTL
753 );
754 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
755 'IPAddress' => $wgRequest->getIP(),
756 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
757 'ChronologyProtection' => $wgRequest->getHeader( 'MediaWiki-Chronology-Protection' ),
758 'ChronologyPositionIndex' => $wgRequest->getInt( 'cpPosIndex', $cpPosInfo['index'] ),
759 'ChronologyClientId' => $cpPosInfo['clientId']
760 ?? $wgRequest->getHeader( 'MediaWiki-Chronology-Client-Id' )
761 ] );
762 unset( $cpPosInfo );
763 // Make sure that object caching does not undermine the ChronologyProtector improvements
764 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
765 // The user is pinned to the primary DC, meaning that they made recent changes which should
766 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
767 // they use a blind TTL and could be stale if an object changes twice in a short time span.
768 MediaWikiServices::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
769 }
770
771 // Useful debug output
772 if ( $wgCommandLineMode ) {
773 if ( isset( $self ) ) {
774 wfDebug( "\n\nStart command line script $self\n" );
775 }
776 } else {
777 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
778 $debug .= "HTTP HEADERS:\n";
779 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
780 $debug .= "$name: $value\n";
781 }
782 wfDebug( $debug );
783 }
784
785 $wgMemc = ObjectCache::getLocalClusterInstance();
786 $messageMemc = wfGetMessageCacheStorage();
787
788 // Most of the config is out, some might want to run hooks here.
789 Hooks::run( 'SetupAfterCache' );
790
791 /**
792 * @var Language $wgContLang
793 * @deprecated since 1.32, use the ContentLanguage service directly
794 */
795 $wgContLang = MediaWikiServices::getInstance()->getContentLanguage();
796
797 // Now that variant lists may be available...
798 $wgRequest->interpolateTitle();
799
800 /**
801 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
802 * session ID (if any) loaded at startup
803 */
804 $wgInitialSessionId = null;
805 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
806 // If session.auto_start is there, we can't touch session name
807 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
808 session_name( $wgSessionName ?: $wgCookiePrefix . '_session' );
809 }
810
811 // Create the SessionManager singleton and set up our session handler,
812 // unless we're specifically asked not to.
813 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
814 MediaWiki\Session\PHPSessionHandler::install(
815 MediaWiki\Session\SessionManager::singleton()
816 );
817 }
818
819 // Initialize the session
820 try {
821 $session = MediaWiki\Session\SessionManager::getGlobalSession();
822 } catch ( OverflowException $ex ) {
823 if ( isset( $ex->sessionInfos ) && count( $ex->sessionInfos ) >= 2 ) {
824 // The exception is because the request had multiple possible
825 // sessions tied for top priority. Report this to the user.
826 $list = [];
827 foreach ( $ex->sessionInfos as $info ) {
828 $list[] = $info->getProvider()->describe( $wgContLang );
829 }
830 $list = $wgContLang->listToText( $list );
831 throw new HttpError( 400,
832 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
833 );
834 }
835
836 // Not the one we want, rethrow
837 throw $ex;
838 }
839
840 if ( $session->isPersistent() ) {
841 $wgInitialSessionId = $session->getSessionId();
842 }
843
844 $session->renew();
845 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
846 ( $session->isPersistent() || $session->shouldRememberUser() ) &&
847 session_id() !== $session->getId()
848 ) {
849 // Start the PHP-session for backwards compatibility
850 if ( session_id() !== '' ) {
851 wfDebugLog( 'session', 'PHP session {old_id} was already started, changing to {new_id}', 'all', [
852 'old_id' => session_id(),
853 'new_id' => $session->getId(),
854 ] );
855 session_write_close();
856 }
857 session_id( $session->getId() );
858 session_start();
859 }
860
861 unset( $session );
862 } else {
863 // Even if we didn't set up a global Session, still install our session
864 // handler unless specifically requested not to.
865 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
866 MediaWiki\Session\PHPSessionHandler::install(
867 MediaWiki\Session\SessionManager::singleton()
868 );
869 }
870 }
871
872 /**
873 * @var User $wgUser
874 */
875 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
876
877 /**
878 * @var Language $wgLang
879 */
880 $wgLang = new StubUserLang;
881
882 /**
883 * @var OutputPage $wgOut
884 */
885 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
886
887 /**
888 * @var Parser $wgParser
889 * @deprecated since 1.32, use MediaWikiServices::getInstance()->getParser() instead
890 */
891 $wgParser = new StubObject( 'wgParser', function () {
892 return MediaWikiServices::getInstance()->getParser();
893 } );
894
895 /**
896 * @var Title $wgTitle
897 */
898 $wgTitle = null;
899
900 // Extension setup functions
901 // Entries should be added to this variable during the inclusion
902 // of the extension file. This allows the extension to perform
903 // any necessary initialisation in the fully initialised environment
904 foreach ( $wgExtensionFunctions as $func ) {
905 call_user_func( $func );
906 }
907
908 // If the session user has a 0 id but a valid name, that means we need to
909 // autocreate it.
910 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
911 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
912 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
913 $res = MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
914 $sessionUser,
915 MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
916 true
917 );
918 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Autocreation attempt', [
919 'event' => 'autocreate',
920 'status' => $res,
921 ] );
922 unset( $res );
923 }
924 unset( $sessionUser );
925 }
926
927 if ( !$wgCommandLineMode ) {
928 Pingback::schedulePingback();
929 }
930
931 $wgFullyInitialised = true;