Merge "Use {{int:}} on MediaWiki:Blockedtext and MediaWiki:Autoblockedtext"
[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
28 /**
29 * This file is not a valid entry point, perform no further processing unless
30 * MEDIAWIKI is defined
31 */
32 if ( !defined( 'MEDIAWIKI' ) ) {
33 exit( 1 );
34 }
35
36 /**
37 * Pre-config setup: Before loading LocalSettings.php
38 */
39
40 // Sanity check (T5782, T122807)
41 if ( ini_get( 'mbstring.func_overload' ) ) {
42 die( 'MediaWiki does not support installations where mbstring.func_overload is non-zero.' );
43 }
44
45 // Start the autoloader, so that extensions can derive classes from core files
46 require_once "$IP/includes/AutoLoader.php";
47
48 // Load up some global defines
49 require_once "$IP/includes/Defines.php";
50
51 // Load default settings
52 require_once "$IP/includes/DefaultSettings.php";
53
54 // Load global functions
55 require_once "$IP/includes/GlobalFunctions.php";
56
57 // Load composer's autoloader if present
58 if ( is_readable( "$IP/vendor/autoload.php" ) ) {
59 require_once "$IP/vendor/autoload.php";
60 }
61
62 // Assert that composer dependencies were successfully loaded
63 // Purposely no leading \ due to it breaking HHVM RepoAuthorative mode
64 // PHP works fine with both versions
65 // See https://github.com/facebook/hhvm/issues/5833
66 if ( !interface_exists( 'Psr\Log\LoggerInterface' ) ) {
67 $message = (
68 'MediaWiki requires the <a href="https://github.com/php-fig/log">PSR-3 logging ' .
69 "library</a> to be present. This library is not embedded directly in MediaWiki's " .
70 "git repository and must be installed separately by the end user.\n\n" .
71 'Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git' .
72 '#Fetch_external_libraries">mediawiki.org</a> for help on installing ' .
73 'the required components.'
74 );
75 echo $message;
76 trigger_error( $message, E_USER_ERROR );
77 die( 1 );
78 }
79
80 // Install a header callback
81 MediaWiki\HeaderCallback::register();
82
83 /**
84 * Load LocalSettings.php
85 */
86
87 if ( is_readable( "$IP/StartProfiler.php" ) ) {
88 // @deprecated since 1.32: Use LocalSettings.php instead.
89 require "$IP/StartProfiler.php";
90 }
91
92 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
93 call_user_func( MW_CONFIG_CALLBACK );
94 } else {
95 if ( !defined( 'MW_CONFIG_FILE' ) ) {
96 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
97 }
98 require_once MW_CONFIG_FILE;
99 }
100
101 /**
102 * Customization point after all loading (constants, functions, classes,
103 * DefaultSettings, LocalSettings). Specifically, this is before usage of
104 * settings, before instantiation of Profiler (and other singletons), and
105 * before any setup functions or hooks run.
106 */
107
108 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
109 call_user_func( MW_SETUP_CALLBACK );
110 }
111
112 /**
113 * Main setup
114 */
115
116 $fname = 'Setup.php';
117 $ps_setup = Profiler::instance()->scopedProfileIn( $fname );
118
119 // Load queued extensions
120 ExtensionRegistry::getInstance()->loadFromQueue();
121 // Don't let any other extensions load
122 ExtensionRegistry::getInstance()->finish();
123
124 // Check to see if we are at the file scope
125 if ( !isset( $wgVersion ) ) {
126 echo "Error, Setup.php must be included from the file scope, after DefaultSettings.php\n";
127 die( 1 );
128 }
129
130 mb_internal_encoding( 'UTF-8' );
131
132 // Set the configured locale on all requests for consisteny
133 putenv( "LC_ALL=$wgShellLocale" );
134 setlocale( LC_ALL, $wgShellLocale );
135
136 // Set various default paths sensibly...
137 $ps_default = Profiler::instance()->scopedProfileIn( $fname . '-defaults' );
138
139 if ( $wgScript === false ) {
140 $wgScript = "$wgScriptPath/index.php";
141 }
142 if ( $wgLoadScript === false ) {
143 $wgLoadScript = "$wgScriptPath/load.php";
144 }
145
146 if ( $wgArticlePath === false ) {
147 if ( $wgUsePathInfo ) {
148 $wgArticlePath = "$wgScript/$1";
149 } else {
150 $wgArticlePath = "$wgScript?title=$1";
151 }
152 }
153
154 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
155 // 'view' is assumed the default action path everywhere in the code
156 // but is rarely filled in $wgActionPaths
157 $wgActionPaths['view'] = $wgArticlePath;
158 }
159
160 if ( $wgResourceBasePath === null ) {
161 $wgResourceBasePath = $wgScriptPath;
162 }
163 if ( $wgStylePath === false ) {
164 $wgStylePath = "$wgResourceBasePath/skins";
165 }
166 if ( $wgLocalStylePath === false ) {
167 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
168 $wgLocalStylePath = "$wgScriptPath/skins";
169 }
170 if ( $wgExtensionAssetsPath === false ) {
171 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
172 }
173
174 if ( $wgLogo === false ) {
175 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
176 }
177
178 if ( $wgUploadPath === false ) {
179 $wgUploadPath = "$wgScriptPath/images";
180 }
181 if ( $wgUploadDirectory === false ) {
182 $wgUploadDirectory = "$IP/images";
183 }
184 if ( $wgReadOnlyFile === false ) {
185 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
186 }
187 if ( $wgFileCacheDirectory === false ) {
188 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
189 }
190 if ( $wgDeletedDirectory === false ) {
191 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
192 }
193
194 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
195 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
196 }
197
198 if ( $wgEnableParserCache === false ) {
199 $wgParserCacheType = CACHE_NONE;
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 * Initialise $wgLocalFileRepo from backwards-compatible settings
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 * Initialise shared repo from backwards-compatible settings
297 */
298 if ( $wgUseSharedUploads ) {
299 if ( $wgSharedUploadDBname ) {
300 $wgForeignFileRepos[] = [
301 'class' => ForeignDBRepo::class,
302 'name' => 'shared',
303 'directory' => $wgSharedUploadDirectory,
304 'url' => $wgSharedUploadPath,
305 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
306 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
307 'transformVia404' => !$wgGenerateThumbnailOnParse,
308 'dbType' => $wgDBtype,
309 'dbServer' => $wgDBserver,
310 'dbUser' => $wgDBuser,
311 'dbPassword' => $wgDBpassword,
312 'dbName' => $wgSharedUploadDBname,
313 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG : 0 ) | DBO_DEFAULT,
314 'tablePrefix' => $wgSharedUploadDBprefix,
315 'hasSharedCache' => $wgCacheSharedUploads,
316 'descBaseUrl' => $wgRepositoryBaseUrl,
317 'fetchDescription' => $wgFetchCommonsDescriptions,
318 ];
319 } else {
320 $wgForeignFileRepos[] = [
321 'class' => FileRepo::class,
322 'name' => 'shared',
323 'directory' => $wgSharedUploadDirectory,
324 'url' => $wgSharedUploadPath,
325 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
326 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
327 'transformVia404' => !$wgGenerateThumbnailOnParse,
328 'descBaseUrl' => $wgRepositoryBaseUrl,
329 'fetchDescription' => $wgFetchCommonsDescriptions,
330 ];
331 }
332 }
333 if ( $wgUseInstantCommons ) {
334 $wgForeignFileRepos[] = [
335 'class' => ForeignAPIRepo::class,
336 'name' => 'wikimediacommons',
337 'apibase' => 'https://commons.wikimedia.org/w/api.php',
338 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
339 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
340 'hashLevels' => 2,
341 'transformVia404' => true,
342 'fetchDescription' => true,
343 'descriptionCacheExpiry' => 43200,
344 'apiThumbCacheExpiry' => 0,
345 ];
346 }
347 /*
348 * Add on default file backend config for file repos.
349 * FileBackendGroup will handle initializing the backends.
350 */
351 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
352 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
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 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
372 for ( $i = 0; $i < count( $wgRCLinkDays ); $i++ ) {
373 if ( $wgRCLinkDays[$i] >= $rcMaxAgeDays ) {
374 $wgRCLinkDays = array_slice( $wgRCLinkDays, 0, $i + 1, false );
375 break;
376 }
377 }
378 }
379 // Ensure that default user options are not invalid, since that breaks Special:Preferences
380 $wgDefaultUserOptions['rcdays'] = min(
381 $wgDefaultUserOptions['rcdays'],
382 ceil( $rcMaxAgeDays )
383 );
384 $wgDefaultUserOptions['watchlistdays'] = min(
385 $wgDefaultUserOptions['watchlistdays'],
386 ceil( $rcMaxAgeDays )
387 );
388 unset( $rcMaxAgeDays );
389
390 if ( $wgSkipSkin ) {
391 $wgSkipSkins[] = $wgSkipSkin;
392 }
393
394 $wgSkipSkins[] = 'fallback';
395 $wgSkipSkins[] = 'apioutput';
396
397 if ( $wgLocalInterwiki ) {
398 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
399 }
400
401 // Set default shared prefix
402 if ( $wgSharedPrefix === false ) {
403 $wgSharedPrefix = $wgDBprefix;
404 }
405
406 // Set default shared schema
407 if ( $wgSharedSchema === false ) {
408 $wgSharedSchema = $wgDBmwschema;
409 }
410
411 if ( !$wgCookiePrefix ) {
412 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
413 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
414 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
415 $wgCookiePrefix = $wgSharedDB;
416 } elseif ( $wgDBprefix ) {
417 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
418 } else {
419 $wgCookiePrefix = $wgDBname;
420 }
421 }
422 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
423
424 if ( $wgEnableEmail ) {
425 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
426 } else {
427 // Disable all other email settings automatically if $wgEnableEmail
428 // is set to false. - T65678
429 $wgAllowHTMLEmail = false;
430 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
431 $wgEnableUserEmail = false;
432 $wgEnotifFromEditor = false;
433 $wgEnotifImpersonal = false;
434 $wgEnotifMaxRecips = 0;
435 $wgEnotifMinorEdits = false;
436 $wgEnotifRevealEditorAddress = false;
437 $wgEnotifUseRealName = false;
438 $wgEnotifUserTalk = false;
439 $wgEnotifWatchlist = false;
440 unset( $wgGroupPermissions['user']['sendemail'] );
441 $wgUseEnotif = false;
442 $wgUserEmailUseReplyTo = false;
443 $wgUsersNotifiedOnAllChanges = [];
444 }
445
446 if ( $wgMetaNamespace === false ) {
447 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
448 }
449
450 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
451 if ( $wgResourceLoaderMaxQueryLength === false ) {
452 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
453 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
454 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
455 } else {
456 $wgResourceLoaderMaxQueryLength = 2000;
457 }
458 unset( $suhosinMaxValueLength );
459 }
460
461 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
462 // upload size.
463 $wgMinUploadChunkSize = min(
464 $wgMinUploadChunkSize,
465 UploadBase::getMaxUploadSize( 'file' ),
466 UploadBase::getMaxPhpUploadSize(),
467 ( wfShorthandToInteger(
468 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
469 PHP_INT_MAX
470 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
471 );
472
473 /**
474 * Definitions of the NS_ constants are in Defines.php
475 * @private
476 */
477 $wgCanonicalNamespaceNames = [
478 NS_MEDIA => 'Media',
479 NS_SPECIAL => 'Special',
480 NS_TALK => 'Talk',
481 NS_USER => 'User',
482 NS_USER_TALK => 'User_talk',
483 NS_PROJECT => 'Project',
484 NS_PROJECT_TALK => 'Project_talk',
485 NS_FILE => 'File',
486 NS_FILE_TALK => 'File_talk',
487 NS_MEDIAWIKI => 'MediaWiki',
488 NS_MEDIAWIKI_TALK => 'MediaWiki_talk',
489 NS_TEMPLATE => 'Template',
490 NS_TEMPLATE_TALK => 'Template_talk',
491 NS_HELP => 'Help',
492 NS_HELP_TALK => 'Help_talk',
493 NS_CATEGORY => 'Category',
494 NS_CATEGORY_TALK => 'Category_talk',
495 ];
496
497 /// @todo UGLY UGLY
498 if ( is_array( $wgExtraNamespaces ) ) {
499 $wgCanonicalNamespaceNames = $wgCanonicalNamespaceNames + $wgExtraNamespaces;
500 }
501
502 // Merge in the legacy language codes, incorporating overrides from the config
503 $wgDummyLanguageCodes += [
504 'qqq' => 'qqq', // Used for message documentation
505 'qqx' => 'qqx', // Used for viewing message keys
506 ] + $wgExtraLanguageCodes + LanguageCode::getDeprecatedCodeMapping();
507
508 // These are now the same, always
509 // To determine the user language, use $wgLang->getCode()
510 $wgContLanguageCode = $wgLanguageCode;
511
512 // Easy to forget to falsify $wgDebugToolbar for static caches.
513 // If file cache or CDN cache is on, just disable this (DWIMD).
514 if ( $wgUseFileCache || $wgUseSquid ) {
515 $wgDebugToolbar = false;
516 }
517
518 // We always output HTML5 since 1.22, overriding these is no longer supported
519 // we set them here for extensions that depend on its value.
520 $wgHtml5 = true;
521 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
522 $wgJsMimeType = 'text/javascript';
523
524 // Blacklisted file extensions shouldn't appear on the "allowed" list
525 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
526
527 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
528 Wikimedia\suppressWarnings();
529 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
530 Wikimedia\restoreWarnings();
531 }
532
533 if ( $wgNewUserLog ) {
534 // Add a new log type
535 $wgLogTypes[] = 'newusers';
536 $wgLogNames['newusers'] = 'newuserlogpage';
537 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
538 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter::class;
539 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter::class;
540 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter::class;
541 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter::class;
542 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter::class;
543 }
544
545 if ( $wgPageLanguageUseDB ) {
546 $wgLogTypes[] = 'pagelang';
547 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter::class;
548 }
549
550 if ( $wgCookieSecure === 'detect' ) {
551 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
552 }
553
554 if ( $wgProfileOnly ) {
555 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
556 $wgDebugLogFile = '';
557 }
558
559 // Backwards compatibility with old password limits
560 if ( $wgMinimalPasswordLength !== false ) {
561 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
562 }
563
564 if ( $wgMaximalPasswordLength !== false ) {
565 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
566 }
567
568 // Backwards compatibility warning
569 if ( !$wgSessionsInObjectCache ) {
570 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
571 if ( $wgSessionHandler ) {
572 wfDeprecated( '$wgSessionsHandler', '1.27' );
573 }
574 $cacheType = get_class( ObjectCache::getInstance( $wgSessionCacheType ) );
575 wfDebugLog(
576 'caches',
577 "Session data will be stored in \"$cacheType\" cache with " .
578 "expiry $wgObjectCacheSessionExpiry seconds"
579 );
580 }
581 $wgSessionsInObjectCache = true;
582
583 if ( $wgPHPSessionHandling !== 'enable' &&
584 $wgPHPSessionHandling !== 'warn' &&
585 $wgPHPSessionHandling !== 'disable'
586 ) {
587 $wgPHPSessionHandling = 'warn';
588 }
589 if ( defined( 'MW_NO_SESSION' ) ) {
590 // If the entry point wants no session, force 'disable' here unless they
591 // specifically set it to the (undocumented) 'warn'.
592 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
593 }
594
595 Profiler::instance()->scopedProfileOut( $ps_default );
596
597 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
598 // all the memory from logging SQL queries on maintenance scripts
599 global $wgCommandLineMode;
600 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
601 MWDebug::init();
602 }
603
604 // Reset the global service locator, so any services that have already been created will be
605 // re-created while taking into account any custom settings and extensions.
606 MediaWikiServices::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
607
608 if ( $wgSharedDB && $wgSharedTables ) {
609 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
610 MediaWikiServices::getInstance()->getDBLoadBalancer()->setTableAliases(
611 array_fill_keys(
612 $wgSharedTables,
613 [
614 'dbname' => $wgSharedDB,
615 'schema' => $wgSharedSchema,
616 'prefix' => $wgSharedPrefix
617 ]
618 )
619 );
620 }
621
622 // Define a constant that indicates that the bootstrapping of the service locator
623 // is complete.
624 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
625
626 MWExceptionHandler::installHandler();
627
628 require_once "$IP/includes/compat/normal/UtfNormalUtil.php";
629
630 $ps_validation = Profiler::instance()->scopedProfileIn( $fname . '-validation' );
631
632 // T48998: Bail out early if $wgArticlePath is non-absolute
633 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
634 if ( $$varName && !preg_match( '/^(https?:\/\/|\/)/', $$varName ) ) {
635 throw new FatalError(
636 "If you use a relative URL for \$$varName, it must start " .
637 'with a slash (<code>/</code>).<br><br>See ' .
638 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
639 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
640 );
641 }
642 }
643
644 Profiler::instance()->scopedProfileOut( $ps_validation );
645
646 $ps_default2 = Profiler::instance()->scopedProfileIn( $fname . '-defaults2' );
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 'channels' => [ 'purge' => 'wancache-main-default-purge' ]
701 ];
702 }
703
704 Profiler::instance()->scopedProfileOut( $ps_default2 );
705
706 $ps_misc = Profiler::instance()->scopedProfileIn( $fname . '-misc1' );
707
708 // Raise the memory limit if it's too low
709 wfMemoryLimit();
710
711 /**
712 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
713 * that happens whenever you use a date function without the timezone being
714 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
715 */
716 if ( is_null( $wgLocaltimezone ) ) {
717 Wikimedia\suppressWarnings();
718 $wgLocaltimezone = date_default_timezone_get();
719 Wikimedia\restoreWarnings();
720 }
721
722 date_default_timezone_set( $wgLocaltimezone );
723 if ( is_null( $wgLocalTZoffset ) ) {
724 $wgLocalTZoffset = date( 'Z' ) / 60;
725 }
726 // The part after the System| is ignored, but rest of MW fills it
727 // out as the local offset.
728 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
729
730 if ( !$wgDBerrorLogTZ ) {
731 $wgDBerrorLogTZ = $wgLocaltimezone;
732 }
733
734 // Initialize the request object in $wgRequest
735 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
736 // Set user IP/agent information for agent session consistency purposes
737 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
738 'IPAddress' => $wgRequest->getIP(),
739 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
740 'ChronologyProtection' => $wgRequest->getHeader( 'ChronologyProtection' ),
741 // The cpPosIndex cookie has no prefix and is set by MediaWiki::preOutputCommit()
742 'ChronologyPositionIndex' =>
743 $wgRequest->getInt( 'cpPosIndex', (int)$wgRequest->getCookie( 'cpPosIndex', '' ) )
744 ] );
745 // Make sure that object caching does not undermine the ChronologyProtector improvements
746 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
747 // The user is pinned to the primary DC, meaning that they made recent changes which should
748 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
749 // they use a blind TTL and could be stale if an object changes twice in a short time span.
750 MediaWikiServices::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
751 }
752
753 // Useful debug output
754 if ( $wgCommandLineMode ) {
755 wfDebug( "\n\nStart command line script $self\n" );
756 } else {
757 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
758
759 if ( $wgDebugPrintHttpHeaders ) {
760 $debug .= "HTTP HEADERS:\n";
761
762 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
763 $debug .= "$name: $value\n";
764 }
765 }
766 wfDebug( $debug );
767 }
768
769 Profiler::instance()->scopedProfileOut( $ps_misc );
770 $ps_memcached = Profiler::instance()->scopedProfileIn( $fname . '-memcached' );
771
772 $wgMemc = wfGetMainCache();
773 $messageMemc = wfGetMessageCacheStorage();
774
775 /**
776 * @deprecated since 1.30
777 */
778 $parserMemc = new DeprecatedGlobal( 'parserMemc', function () {
779 return MediaWikiServices::getInstance()->getParserCache()->getCacheStorage();
780 }, '1.30' );
781
782 wfDebugLog( 'caches',
783 'cluster: ' . get_class( $wgMemc ) .
784 ', WAN: ' . ( $wgMainWANCache === CACHE_NONE ? 'CACHE_NONE' : $wgMainWANCache ) .
785 ', stash: ' . $wgMainStash .
786 ', message: ' . get_class( $messageMemc ) .
787 ', session: ' . get_class( ObjectCache::getInstance( $wgSessionCacheType ) )
788 );
789
790 Profiler::instance()->scopedProfileOut( $ps_memcached );
791
792 // Most of the config is out, some might want to run hooks here.
793 Hooks::run( 'SetupAfterCache' );
794
795 $ps_globals = Profiler::instance()->scopedProfileIn( $fname . '-globals' );
796
797 /**
798 * @var Language $wgContLang
799 */
800 $wgContLang = Language::factory( $wgLanguageCode );
801 $wgContLang->initContLang();
802
803 // Now that variant lists may be available...
804 $wgRequest->interpolateTitle();
805
806 if ( !is_object( $wgAuth ) ) {
807 $wgAuth = new MediaWiki\Auth\AuthManagerAuthPlugin;
808 Hooks::run( 'AuthPluginSetup', [ &$wgAuth ] );
809 }
810 if ( $wgAuth && !$wgAuth instanceof MediaWiki\Auth\AuthManagerAuthPlugin ) {
811 MediaWiki\Auth\AuthManager::singleton()->forcePrimaryAuthenticationProviders( [
812 new MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider( [
813 'authoritative' => false,
814 ] ),
815 new MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider( $wgAuth ),
816 new MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider( [
817 'authoritative' => true,
818 ] ),
819 ], '$wgAuth is ' . get_class( $wgAuth ) );
820 }
821
822 // Set up the session
823 $ps_session = Profiler::instance()->scopedProfileIn( $fname . '-session' );
824 /**
825 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
826 * session ID (if any) loaded at startup
827 */
828 $wgInitialSessionId = null;
829 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
830 // If session.auto_start is there, we can't touch session name
831 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
832 session_name( $wgSessionName ? $wgSessionName : $wgCookiePrefix . '_session' );
833 }
834
835 // Create the SessionManager singleton and set up our session handler,
836 // unless we're specifically asked not to.
837 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
838 MediaWiki\Session\PHPSessionHandler::install(
839 MediaWiki\Session\SessionManager::singleton()
840 );
841 }
842
843 // Initialize the session
844 try {
845 $session = MediaWiki\Session\SessionManager::getGlobalSession();
846 } catch ( OverflowException $ex ) {
847 if ( isset( $ex->sessionInfos ) && count( $ex->sessionInfos ) >= 2 ) {
848 // The exception is because the request had multiple possible
849 // sessions tied for top priority. Report this to the user.
850 $list = [];
851 foreach ( $ex->sessionInfos as $info ) {
852 $list[] = $info->getProvider()->describe( $wgContLang );
853 }
854 $list = $wgContLang->listToText( $list );
855 throw new HttpError( 400,
856 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
857 );
858 }
859
860 // Not the one we want, rethrow
861 throw $ex;
862 }
863
864 if ( $session->isPersistent() ) {
865 $wgInitialSessionId = $session->getSessionId();
866 }
867
868 $session->renew();
869 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
870 ( $session->isPersistent() || $session->shouldRememberUser() )
871 ) {
872 // Start the PHP-session for backwards compatibility
873 session_id( $session->getId() );
874 Wikimedia\quietCall( 'session_start' );
875 }
876
877 unset( $session );
878 } else {
879 // Even if we didn't set up a global Session, still install our session
880 // handler unless specifically requested not to.
881 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
882 MediaWiki\Session\PHPSessionHandler::install(
883 MediaWiki\Session\SessionManager::singleton()
884 );
885 }
886 }
887 Profiler::instance()->scopedProfileOut( $ps_session );
888
889 /**
890 * @var User $wgUser
891 */
892 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
893
894 /**
895 * @var Language $wgLang
896 */
897 $wgLang = new StubUserLang;
898
899 /**
900 * @var OutputPage $wgOut
901 */
902 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
903
904 /**
905 * @var Parser $wgParser
906 */
907 $wgParser = new StubObject( 'wgParser', function () {
908 return MediaWikiServices::getInstance()->getParser();
909 } );
910
911 /**
912 * @var Title $wgTitle
913 */
914 $wgTitle = null;
915
916 Profiler::instance()->scopedProfileOut( $ps_globals );
917 $ps_extensions = Profiler::instance()->scopedProfileIn( $fname . '-extensions' );
918
919 // Extension setup functions
920 // Entries should be added to this variable during the inclusion
921 // of the extension file. This allows the extension to perform
922 // any necessary initialisation in the fully initialised environment
923 foreach ( $wgExtensionFunctions as $func ) {
924 // Allow closures in PHP 5.3+
925 if ( is_object( $func ) && $func instanceof Closure ) {
926 $profName = $fname . '-extensions-closure';
927 } elseif ( is_array( $func ) ) {
928 if ( is_object( $func[0] ) ) {
929 $profName = $fname . '-extensions-' . get_class( $func[0] ) . '::' . $func[1];
930 } else {
931 $profName = $fname . '-extensions-' . implode( '::', $func );
932 }
933 } else {
934 $profName = $fname . '-extensions-' . strval( $func );
935 }
936
937 $ps_ext_func = Profiler::instance()->scopedProfileIn( $profName );
938 call_user_func( $func );
939 Profiler::instance()->scopedProfileOut( $ps_ext_func );
940 }
941
942 // If the session user has a 0 id but a valid name, that means we need to
943 // autocreate it.
944 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
945 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
946 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
947 $ps_autocreate = Profiler::instance()->scopedProfileIn( $fname . '-autocreate' );
948 $res = MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
949 $sessionUser,
950 MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
951 true
952 );
953 Profiler::instance()->scopedProfileOut( $ps_autocreate );
954 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Autocreation attempt', [
955 'event' => 'autocreate',
956 'status' => $res,
957 ] );
958 unset( $res );
959 }
960 unset( $sessionUser );
961 }
962
963 if ( !$wgCommandLineMode ) {
964 Pingback::schedulePingback();
965 }
966
967 $wgFullyInitialised = true;
968
969 Profiler::instance()->scopedProfileOut( $ps_extensions );
970 Profiler::instance()->scopedProfileOut( $ps_setup );