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