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