Merge "maintenance: Script to rename titles for Unicode uppercasing changes"
[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 up some global defines
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 // Install a header callback
93 MediaWiki\HeaderCallback::register();
94
95 /**
96 * Load LocalSettings.php
97 */
98
99 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
100 call_user_func( MW_CONFIG_CALLBACK );
101 } else {
102 if ( !defined( 'MW_CONFIG_FILE' ) ) {
103 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
104 }
105 require_once MW_CONFIG_FILE;
106 }
107
108 /**
109 * Customization point after all loading (constants, functions, classes,
110 * DefaultSettings, LocalSettings). Specifically, this is before usage of
111 * settings, before instantiation of Profiler (and other singletons), and
112 * before any setup functions or hooks run.
113 */
114
115 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
116 call_user_func( MW_SETUP_CALLBACK );
117 }
118
119 /**
120 * Main setup
121 */
122
123 $fname = 'Setup.php';
124 $ps_setup = Profiler::instance()->scopedProfileIn( $fname );
125
126 // Load queued extensions
127 ExtensionRegistry::getInstance()->loadFromQueue();
128 // Don't let any other extensions load
129 ExtensionRegistry::getInstance()->finish();
130
131 mb_internal_encoding( 'UTF-8' );
132
133 // Set the configured locale on all requests for consisteny
134 putenv( "LC_ALL=$wgShellLocale" );
135 setlocale( LC_ALL, $wgShellLocale );
136
137 // Set various default paths sensibly...
138 $ps_default = Profiler::instance()->scopedProfileIn( $fname . '-defaults' );
139
140 if ( $wgScript === false ) {
141 $wgScript = "$wgScriptPath/index.php";
142 }
143 if ( $wgLoadScript === false ) {
144 $wgLoadScript = "$wgScriptPath/load.php";
145 }
146 if ( $wgRestPath === false ) {
147 $wgRestPath = "$wgScriptPath/rest.php";
148 }
149
150 if ( $wgArticlePath === false ) {
151 if ( $wgUsePathInfo ) {
152 $wgArticlePath = "$wgScript/$1";
153 } else {
154 $wgArticlePath = "$wgScript?title=$1";
155 }
156 }
157
158 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
159 // 'view' is assumed the default action path everywhere in the code
160 // but is rarely filled in $wgActionPaths
161 $wgActionPaths['view'] = $wgArticlePath;
162 }
163
164 if ( $wgResourceBasePath === null ) {
165 $wgResourceBasePath = $wgScriptPath;
166 }
167 if ( $wgStylePath === false ) {
168 $wgStylePath = "$wgResourceBasePath/skins";
169 }
170 if ( $wgLocalStylePath === false ) {
171 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
172 $wgLocalStylePath = "$wgScriptPath/skins";
173 }
174 if ( $wgExtensionAssetsPath === false ) {
175 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
176 }
177
178 if ( $wgLogo === false ) {
179 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
180 }
181
182 if ( $wgUploadPath === false ) {
183 $wgUploadPath = "$wgScriptPath/images";
184 }
185 if ( $wgUploadDirectory === false ) {
186 $wgUploadDirectory = "$IP/images";
187 }
188 if ( $wgReadOnlyFile === false ) {
189 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
190 }
191 if ( $wgFileCacheDirectory === false ) {
192 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
193 }
194 if ( $wgDeletedDirectory === false ) {
195 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
196 }
197
198 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
199 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
200 }
201
202 // Fix path to icon images after they were moved in 1.24
203 if ( $wgRightsIcon ) {
204 $wgRightsIcon = str_replace(
205 "{$wgStylePath}/common/images/",
206 "{$wgResourceBasePath}/resources/assets/licenses/",
207 $wgRightsIcon
208 );
209 }
210
211 if ( isset( $wgFooterIcons['copyright']['copyright'] )
212 && $wgFooterIcons['copyright']['copyright'] === []
213 ) {
214 if ( $wgRightsIcon || $wgRightsText ) {
215 $wgFooterIcons['copyright']['copyright'] = [
216 'url' => $wgRightsUrl,
217 'src' => $wgRightsIcon,
218 'alt' => $wgRightsText,
219 ];
220 }
221 }
222
223 if ( isset( $wgFooterIcons['poweredby'] )
224 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
225 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
226 ) {
227 $wgFooterIcons['poweredby']['mediawiki']['src'] =
228 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
229 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
230 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
231 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
232 }
233
234 /**
235 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
236 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
237 *
238 * Note that this is the definition of editinterface and it can be granted to
239 * all users if desired.
240 */
241 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
242
243 /**
244 * The canonical names of namespaces 6 and 7 are, as of v1.14, "File"
245 * and "File_talk". The old names "Image" and "Image_talk" are
246 * retained as aliases for backwards compatibility.
247 */
248 $wgNamespaceAliases['Image'] = NS_FILE;
249 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
250
251 /**
252 * Initialise $wgLockManagers to include basic FS version
253 */
254 $wgLockManagers[] = [
255 'name' => 'fsLockManager',
256 'class' => FSLockManager::class,
257 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
258 ];
259 $wgLockManagers[] = [
260 'name' => 'nullLockManager',
261 'class' => NullLockManager::class,
262 ];
263
264 /**
265 * Default parameters for the "<gallery>" tag.
266 * @see DefaultSettings.php for description of the fields.
267 */
268 $wgGalleryOptions += [
269 'imagesPerRow' => 0,
270 'imageWidth' => 120,
271 'imageHeight' => 120,
272 'captionLength' => true,
273 'showBytes' => true,
274 'showDimensions' => true,
275 'mode' => 'traditional',
276 ];
277
278 /**
279 * Shortcuts for $wgLocalFileRepo
280 */
281 if ( !$wgLocalFileRepo ) {
282 $wgLocalFileRepo = [
283 'class' => LocalRepo::class,
284 'name' => 'local',
285 'directory' => $wgUploadDirectory,
286 'scriptDirUrl' => $wgScriptPath,
287 'url' => $wgUploadBaseUrl ? $wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
288 'hashLevels' => $wgHashedUploadDirectory ? 2 : 0,
289 'thumbScriptUrl' => $wgThumbnailScriptPath,
290 'transformVia404' => !$wgGenerateThumbnailOnParse,
291 'deletedDir' => $wgDeletedDirectory,
292 'deletedHashLevels' => $wgHashedUploadDirectory ? 3 : 0
293 ];
294 }
295
296 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
297 // Create a default FileBackend name.
298 // FileBackendGroup will register a default, if absent from $wgFileBackends.
299 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
300 }
301
302 /**
303 * Shortcuts for $wgForeignFileRepos
304 */
305 if ( $wgUseSharedUploads ) {
306 if ( $wgSharedUploadDBname ) {
307 $wgForeignFileRepos[] = [
308 'class' => ForeignDBRepo::class,
309 'name' => 'shared',
310 'directory' => $wgSharedUploadDirectory,
311 'url' => $wgSharedUploadPath,
312 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
313 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
314 'transformVia404' => !$wgGenerateThumbnailOnParse,
315 'dbType' => $wgDBtype,
316 'dbServer' => $wgDBserver,
317 'dbUser' => $wgDBuser,
318 'dbPassword' => $wgDBpassword,
319 'dbName' => $wgSharedUploadDBname,
320 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG : 0 ) | DBO_DEFAULT,
321 'tablePrefix' => $wgSharedUploadDBprefix,
322 'hasSharedCache' => $wgCacheSharedUploads,
323 'descBaseUrl' => $wgRepositoryBaseUrl,
324 'fetchDescription' => $wgFetchCommonsDescriptions,
325 ];
326 } else {
327 $wgForeignFileRepos[] = [
328 'class' => FileRepo::class,
329 'name' => 'shared',
330 'directory' => $wgSharedUploadDirectory,
331 'url' => $wgSharedUploadPath,
332 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
333 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
334 'transformVia404' => !$wgGenerateThumbnailOnParse,
335 'descBaseUrl' => $wgRepositoryBaseUrl,
336 'fetchDescription' => $wgFetchCommonsDescriptions,
337 ];
338 }
339 }
340 if ( $wgUseInstantCommons ) {
341 $wgForeignFileRepos[] = [
342 'class' => ForeignAPIRepo::class,
343 'name' => 'wikimediacommons',
344 'apibase' => 'https://commons.wikimedia.org/w/api.php',
345 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
346 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
347 'hashLevels' => 2,
348 'transformVia404' => true,
349 'fetchDescription' => true,
350 'descriptionCacheExpiry' => 43200,
351 'apiThumbCacheExpiry' => 0,
352 ];
353 }
354 foreach ( $wgForeignFileRepos as &$repo ) {
355 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo::class ) {
356 $repo['directory'] = $wgUploadDirectory; // b/c
357 }
358 if ( !isset( $repo['backend'] ) ) {
359 $repo['backend'] = $repo['name'] . '-backend';
360 }
361 }
362 unset( $repo ); // no global pollution; destroy reference
363
364 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
365 if ( $wgRCFilterByAge ) {
366 // Trim down $wgRCLinkDays so that it only lists links which are valid
367 // as determined by $wgRCMaxAge.
368 // Note that we allow 1 link higher than the max for things like 56 days but a 60 day link.
369 sort( $wgRCLinkDays );
370
371 foreach ( $wgRCLinkDays as $i => $days ) {
372 if ( $days >= $rcMaxAgeDays ) {
373 array_splice( $wgRCLinkDays, $i + 1 );
374 break;
375 }
376 }
377 }
378 // Ensure that default user options are not invalid, since that breaks Special:Preferences
379 $wgDefaultUserOptions['rcdays'] = min(
380 $wgDefaultUserOptions['rcdays'],
381 ceil( $rcMaxAgeDays )
382 );
383 $wgDefaultUserOptions['watchlistdays'] = min(
384 $wgDefaultUserOptions['watchlistdays'],
385 ceil( $rcMaxAgeDays )
386 );
387 unset( $rcMaxAgeDays );
388
389 if ( $wgSkipSkin ) {
390 $wgSkipSkins[] = $wgSkipSkin;
391 }
392
393 $wgSkipSkins[] = 'fallback';
394 $wgSkipSkins[] = 'apioutput';
395
396 if ( $wgLocalInterwiki ) {
397 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
398 }
399
400 // Set default shared prefix
401 if ( $wgSharedPrefix === false ) {
402 $wgSharedPrefix = $wgDBprefix;
403 }
404
405 // Set default shared schema
406 if ( $wgSharedSchema === false ) {
407 $wgSharedSchema = $wgDBmwschema;
408 }
409
410 if ( !$wgCookiePrefix ) {
411 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
412 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
413 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
414 $wgCookiePrefix = $wgSharedDB;
415 } elseif ( $wgDBprefix ) {
416 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
417 } else {
418 $wgCookiePrefix = $wgDBname;
419 }
420 }
421 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
422
423 if ( $wgEnableEmail ) {
424 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
425 } else {
426 // Disable all other email settings automatically if $wgEnableEmail
427 // is set to false. - T65678
428 $wgAllowHTMLEmail = false;
429 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
430 $wgEnableUserEmail = false;
431 $wgEnotifFromEditor = false;
432 $wgEnotifImpersonal = false;
433 $wgEnotifMaxRecips = 0;
434 $wgEnotifMinorEdits = false;
435 $wgEnotifRevealEditorAddress = false;
436 $wgEnotifUseRealName = false;
437 $wgEnotifUserTalk = false;
438 $wgEnotifWatchlist = false;
439 unset( $wgGroupPermissions['user']['sendemail'] );
440 $wgUseEnotif = false;
441 $wgUserEmailUseReplyTo = false;
442 $wgUsersNotifiedOnAllChanges = [];
443 }
444
445 if ( $wgMetaNamespace === false ) {
446 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
447 }
448
449 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
450 if ( $wgResourceLoaderMaxQueryLength === false ) {
451 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
452 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
453 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
454 } else {
455 $wgResourceLoaderMaxQueryLength = 2000;
456 }
457 unset( $suhosinMaxValueLength );
458 }
459
460 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
461 // upload size.
462 $wgMinUploadChunkSize = min(
463 $wgMinUploadChunkSize,
464 UploadBase::getMaxUploadSize( 'file' ),
465 UploadBase::getMaxPhpUploadSize(),
466 ( wfShorthandToInteger(
467 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
468 PHP_INT_MAX
469 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
470 );
471
472 /**
473 * Definitions of the NS_ constants are in Defines.php
474 * @private
475 */
476 $wgCanonicalNamespaceNames = [
477 NS_MEDIA => 'Media',
478 NS_SPECIAL => 'Special',
479 NS_TALK => 'Talk',
480 NS_USER => 'User',
481 NS_USER_TALK => 'User_talk',
482 NS_PROJECT => 'Project',
483 NS_PROJECT_TALK => 'Project_talk',
484 NS_FILE => 'File',
485 NS_FILE_TALK => 'File_talk',
486 NS_MEDIAWIKI => 'MediaWiki',
487 NS_MEDIAWIKI_TALK => 'MediaWiki_talk',
488 NS_TEMPLATE => 'Template',
489 NS_TEMPLATE_TALK => 'Template_talk',
490 NS_HELP => 'Help',
491 NS_HELP_TALK => 'Help_talk',
492 NS_CATEGORY => 'Category',
493 NS_CATEGORY_TALK => 'Category_talk',
494 ];
495
496 /// @todo UGLY UGLY
497 if ( is_array( $wgExtraNamespaces ) ) {
498 $wgCanonicalNamespaceNames += $wgExtraNamespaces;
499 }
500
501 // Hard-deprecate setting $wgDummyLanguageCodes in LocalSettings.php
502 if ( count( $wgDummyLanguageCodes ) !== 0 ) {
503 wfDeprecated( '$wgDummyLanguageCodes', '1.29' );
504 }
505 // Merge in the legacy language codes, incorporating overrides from the config
506 $wgDummyLanguageCodes += [
507 // Internal language codes of the private-use area which get mapped to
508 // themselves.
509 'qqq' => 'qqq', // Used for message documentation
510 'qqx' => 'qqx', // Used for viewing message keys
511 ] + $wgExtraLanguageCodes + LanguageCode::getDeprecatedCodeMapping();
512 // Merge in (inverted) BCP 47 mappings
513 foreach ( LanguageCode::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
514 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
515 if ( !isset( $wgDummyLanguageCodes[$bcp47] ) ) {
516 $wgDummyLanguageCodes[$bcp47] = $wgDummyLanguageCodes[$code] ?? $code;
517 }
518 }
519
520 // These are now the same, always
521 // To determine the user language, use $wgLang->getCode()
522 $wgContLanguageCode = $wgLanguageCode;
523
524 // Temporary backwards-compatibility reading of old Squid-named CDN settings as of MediaWiki 1.34,
525 // to support sysadmins who fail to update their settings immediately:
526
527 if ( isset( $wgUseSquid ) ) {
528 // If the sysadmin is still setting a value of $wgUseSquid to true but $wgUseCdn is the default of
529 // false, to be safe, assume they do want this still, so enable it.
530 if ( !$wgUseCdn && $wgUseSquid ) {
531 $wgUseCdn = $wgUseSquid;
532 wfDeprecated( '$wgUseSquid enabled but $wgUseCdn disabled; enabling CDN functions', '1.34' );
533 }
534 } else {
535 // Backwards-compatibility for extensions that read this value.
536 $wgUseSquid = $wgUseCdn;
537 }
538
539 if ( isset( $wgSquidServers ) ) {
540 // If the sysadmin is still setting a value of $wgSquidServers but $wgCdnServers is the default of
541 // empty, to be safe, assume they do want these servers to be still used, so use them.
542 if ( !empty( $wgSquidServers ) && empty( $wgCdnServers ) ) {
543 $wgCdnServers = $wgSquidServers;
544 wfDeprecated( '$wgSquidServers set, $wgCdnServers empty; using them', '1.34' );
545 }
546 } else {
547 // Backwards-compatibility for extensions that read this value.
548 $wgSquidServers = $wgCdnServers;
549 }
550
551 if ( isset( $wgSquidServersNoPurge ) ) {
552 // If the sysadmin is still setting values in $wgSquidServersNoPurge but $wgCdnServersNoPurge is
553 // the default of empty, to be safe, assume they do want these servers to be still used, so use
554 // them.
555 if ( !empty( $wgSquidServersNoPurge ) && empty( $wgCdnServersNoPurge ) ) {
556 $wgCdnServersNoPurge = $wgSquidServersNoPurge;
557 wfDeprecated( '$wgSquidServersNoPurge set, $wgCdnServersNoPurge empty; using them', '1.34' );
558 }
559 } else {
560 // Backwards-compatibility for extensions that read this value.
561 $wgSquidServersNoPurge = $wgCdnServersNoPurge;
562 }
563
564 if ( isset( $wgSquidMaxage ) ) {
565 // If the sysadmin is still setting a value of $wgSquidMaxage and it's higher than $wgCdnMaxAge,
566 // to be safe, assume they want the higher (lower performance requirement) value, so use that.
567 if ( $wgCdnMaxAge < $wgSquidMaxage ) {
568 $wgCdnMaxAge = $wgSquidMaxage;
569 wfDeprecated( '$wgSquidMaxage set higher than $wgCdnMaxAge; using the higher value', '1.34' );
570 }
571 } else {
572 // Backwards-compatibility for extensions that read this value.
573 $wgSquidMaxage = $wgCdnMaxAge;
574 }
575
576 // Easy to forget to falsify $wgDebugToolbar for static caches.
577 // If file cache or CDN cache is on, just disable this (DWIMD).
578 if ( $wgUseFileCache || $wgUseCdn ) {
579 $wgDebugToolbar = false;
580 }
581
582 // We always output HTML5 since 1.22, overriding these is no longer supported
583 // we set them here for extensions that depend on its value.
584 $wgHtml5 = true;
585 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
586 $wgJsMimeType = 'text/javascript';
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 wfMemoryLimit();
758
759 /**
760 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
761 * that happens whenever you use a date function without the timezone being
762 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
763 */
764 if ( is_null( $wgLocaltimezone ) ) {
765 Wikimedia\suppressWarnings();
766 $wgLocaltimezone = date_default_timezone_get();
767 Wikimedia\restoreWarnings();
768 }
769
770 date_default_timezone_set( $wgLocaltimezone );
771 if ( is_null( $wgLocalTZoffset ) ) {
772 $wgLocalTZoffset = date( 'Z' ) / 60;
773 }
774 // The part after the System| is ignored, but rest of MW fills it
775 // out as the local offset.
776 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
777
778 if ( !$wgDBerrorLogTZ ) {
779 $wgDBerrorLogTZ = $wgLocaltimezone;
780 }
781
782 // Initialize the request object in $wgRequest
783 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
784 // Set user IP/agent information for agent session consistency purposes
785 $cpPosInfo = LBFactory::getCPInfoFromCookieValue(
786 // The cookie has no prefix and is set by MediaWiki::preOutputCommit()
787 $wgRequest->getCookie( 'cpPosIndex', '' ),
788 // Mitigate broken client-side cookie expiration handling (T190082)
789 time() - ChronologyProtector::POSITION_COOKIE_TTL
790 );
791 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
792 'IPAddress' => $wgRequest->getIP(),
793 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
794 'ChronologyProtection' => $wgRequest->getHeader( 'MediaWiki-Chronology-Protection' ),
795 'ChronologyPositionIndex' => $wgRequest->getInt( 'cpPosIndex', $cpPosInfo['index'] ),
796 'ChronologyClientId' => $cpPosInfo['clientId']
797 ?? $wgRequest->getHeader( 'MediaWiki-Chronology-Client-Id' )
798 ] );
799 unset( $cpPosInfo );
800 // Make sure that object caching does not undermine the ChronologyProtector improvements
801 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
802 // The user is pinned to the primary DC, meaning that they made recent changes which should
803 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
804 // they use a blind TTL and could be stale if an object changes twice in a short time span.
805 MediaWikiServices::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
806 }
807
808 // Useful debug output
809 if ( $wgCommandLineMode ) {
810 if ( isset( $self ) ) {
811 wfDebug( "\n\nStart command line script $self\n" );
812 }
813 } else {
814 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
815
816 if ( $wgDebugPrintHttpHeaders ) {
817 $debug .= "HTTP HEADERS:\n";
818
819 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
820 $debug .= "$name: $value\n";
821 }
822 }
823 wfDebug( $debug );
824 }
825
826 $wgMemc = ObjectCache::getLocalClusterInstance();
827 $messageMemc = wfGetMessageCacheStorage();
828
829 wfDebugLog( 'caches',
830 'cluster: ' . get_class( $wgMemc ) .
831 ', WAN: ' . ( $wgMainWANCache === CACHE_NONE ? 'CACHE_NONE' : $wgMainWANCache ) .
832 ', stash: ' . $wgMainStash .
833 ', message: ' . get_class( $messageMemc ) .
834 ', session: ' . get_class( ObjectCache::getInstance( $wgSessionCacheType ) )
835 );
836
837 Profiler::instance()->scopedProfileOut( $ps_misc );
838
839 // Most of the config is out, some might want to run hooks here.
840 Hooks::run( 'SetupAfterCache' );
841
842 $ps_globals = Profiler::instance()->scopedProfileIn( $fname . '-globals' );
843
844 /**
845 * @var Language $wgContLang
846 * @deprecated since 1.32, use the ContentLanguage service directly
847 */
848 $wgContLang = MediaWikiServices::getInstance()->getContentLanguage();
849
850 // Now that variant lists may be available...
851 $wgRequest->interpolateTitle();
852
853 /**
854 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
855 * session ID (if any) loaded at startup
856 */
857 $wgInitialSessionId = null;
858 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
859 // If session.auto_start is there, we can't touch session name
860 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
861 session_name( $wgSessionName ?: $wgCookiePrefix . '_session' );
862 }
863
864 // Create the SessionManager singleton and set up our session handler,
865 // unless we're specifically asked not to.
866 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
867 MediaWiki\Session\PHPSessionHandler::install(
868 MediaWiki\Session\SessionManager::singleton()
869 );
870 }
871
872 // Initialize the session
873 try {
874 $session = MediaWiki\Session\SessionManager::getGlobalSession();
875 } catch ( OverflowException $ex ) {
876 if ( isset( $ex->sessionInfos ) && count( $ex->sessionInfos ) >= 2 ) {
877 // The exception is because the request had multiple possible
878 // sessions tied for top priority. Report this to the user.
879 $list = [];
880 foreach ( $ex->sessionInfos as $info ) {
881 $list[] = $info->getProvider()->describe( $wgContLang );
882 }
883 $list = $wgContLang->listToText( $list );
884 throw new HttpError( 400,
885 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
886 );
887 }
888
889 // Not the one we want, rethrow
890 throw $ex;
891 }
892
893 if ( $session->isPersistent() ) {
894 $wgInitialSessionId = $session->getSessionId();
895 }
896
897 $session->renew();
898 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
899 ( $session->isPersistent() || $session->shouldRememberUser() ) &&
900 session_id() !== $session->getId()
901 ) {
902 // Start the PHP-session for backwards compatibility
903 if ( session_id() !== '' ) {
904 wfDebugLog( 'session', 'PHP session {old_id} was already started, changing to {new_id}', 'all', [
905 'old_id' => session_id(),
906 'new_id' => $session->getId(),
907 ] );
908 session_write_close();
909 }
910 session_id( $session->getId() );
911 session_start();
912 }
913
914 unset( $session );
915 } else {
916 // Even if we didn't set up a global Session, still install our session
917 // handler unless specifically requested not to.
918 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
919 MediaWiki\Session\PHPSessionHandler::install(
920 MediaWiki\Session\SessionManager::singleton()
921 );
922 }
923 }
924
925 /**
926 * @var User $wgUser
927 */
928 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
929
930 /**
931 * @var Language $wgLang
932 */
933 $wgLang = new StubUserLang;
934
935 /**
936 * @var OutputPage $wgOut
937 */
938 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
939
940 /**
941 * @var Parser $wgParser
942 * @deprecated since 1.32, use MediaWikiServices::getInstance()->getParser() instead
943 */
944 $wgParser = new StubObject( 'wgParser', function () {
945 return MediaWikiServices::getInstance()->getParser();
946 } );
947
948 /**
949 * @var Title $wgTitle
950 */
951 $wgTitle = null;
952
953 Profiler::instance()->scopedProfileOut( $ps_globals );
954 $ps_extensions = Profiler::instance()->scopedProfileIn( $fname . '-extensions' );
955
956 // Extension setup functions
957 // Entries should be added to this variable during the inclusion
958 // of the extension file. This allows the extension to perform
959 // any necessary initialisation in the fully initialised environment
960 foreach ( $wgExtensionFunctions as $func ) {
961 call_user_func( $func );
962 }
963
964 // If the session user has a 0 id but a valid name, that means we need to
965 // autocreate it.
966 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
967 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
968 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
969 $res = MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
970 $sessionUser,
971 MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
972 true
973 );
974 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Autocreation attempt', [
975 'event' => 'autocreate',
976 'status' => $res,
977 ] );
978 unset( $res );
979 }
980 unset( $sessionUser );
981 }
982
983 if ( !$wgCommandLineMode ) {
984 Pingback::schedulePingback();
985 }
986
987 $wgFullyInitialised = true;
988
989 Profiler::instance()->scopedProfileOut( $ps_extensions );
990 Profiler::instance()->scopedProfileOut( $ps_setup );