Merge "Remove $wgSiteSupportPage"
[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 'scriptExtension' => '.php',
288 'url' => $wgUploadBaseUrl ? $wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
289 'hashLevels' => $wgHashedUploadDirectory ? 2 : 0,
290 'thumbScriptUrl' => $wgThumbnailScriptPath,
291 'transformVia404' => !$wgGenerateThumbnailOnParse,
292 'deletedDir' => $wgDeletedDirectory,
293 'deletedHashLevels' => $wgHashedUploadDirectory ? 3 : 0
294 ];
295 }
296 /**
297 * Initialise shared repo from backwards-compatible settings
298 */
299 if ( $wgUseSharedUploads ) {
300 if ( $wgSharedUploadDBname ) {
301 $wgForeignFileRepos[] = [
302 'class' => ForeignDBRepo::class,
303 'name' => 'shared',
304 'directory' => $wgSharedUploadDirectory,
305 'url' => $wgSharedUploadPath,
306 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
307 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
308 'transformVia404' => !$wgGenerateThumbnailOnParse,
309 'dbType' => $wgDBtype,
310 'dbServer' => $wgDBserver,
311 'dbUser' => $wgDBuser,
312 'dbPassword' => $wgDBpassword,
313 'dbName' => $wgSharedUploadDBname,
314 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG : 0 ) | DBO_DEFAULT,
315 'tablePrefix' => $wgSharedUploadDBprefix,
316 'hasSharedCache' => $wgCacheSharedUploads,
317 'descBaseUrl' => $wgRepositoryBaseUrl,
318 'fetchDescription' => $wgFetchCommonsDescriptions,
319 ];
320 } else {
321 $wgForeignFileRepos[] = [
322 'class' => FileRepo::class,
323 'name' => 'shared',
324 'directory' => $wgSharedUploadDirectory,
325 'url' => $wgSharedUploadPath,
326 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
327 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
328 'transformVia404' => !$wgGenerateThumbnailOnParse,
329 'descBaseUrl' => $wgRepositoryBaseUrl,
330 'fetchDescription' => $wgFetchCommonsDescriptions,
331 ];
332 }
333 }
334 if ( $wgUseInstantCommons ) {
335 $wgForeignFileRepos[] = [
336 'class' => ForeignAPIRepo::class,
337 'name' => 'wikimediacommons',
338 'apibase' => 'https://commons.wikimedia.org/w/api.php',
339 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
340 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
341 'hashLevels' => 2,
342 'transformVia404' => true,
343 'fetchDescription' => true,
344 'descriptionCacheExpiry' => 43200,
345 'apiThumbCacheExpiry' => 0,
346 ];
347 }
348 /*
349 * Add on default file backend config for file repos.
350 * FileBackendGroup will handle initializing the backends.
351 */
352 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
353 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
354 }
355 foreach ( $wgForeignFileRepos as &$repo ) {
356 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo::class ) {
357 $repo['directory'] = $wgUploadDirectory; // b/c
358 }
359 if ( !isset( $repo['backend'] ) ) {
360 $repo['backend'] = $repo['name'] . '-backend';
361 }
362 }
363 unset( $repo ); // no global pollution; destroy reference
364
365 // Convert this deprecated setting to modern system
366 if ( $wgExperimentalHtmlIds ) {
367 wfDeprecated( '$wgExperimentalHtmlIds', '1.30' );
368 $wgFragmentMode = [ 'html5-legacy', 'html5' ];
369 }
370
371 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
372 if ( $wgRCFilterByAge ) {
373 // Trim down $wgRCLinkDays so that it only lists links which are valid
374 // as determined by $wgRCMaxAge.
375 // Note that we allow 1 link higher than the max for things like 56 days but a 60 day link.
376 sort( $wgRCLinkDays );
377
378 // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall
379 for ( $i = 0; $i < count( $wgRCLinkDays ); $i++ ) {
380 if ( $wgRCLinkDays[$i] >= $rcMaxAgeDays ) {
381 $wgRCLinkDays = array_slice( $wgRCLinkDays, 0, $i + 1, false );
382 break;
383 }
384 }
385 }
386 // Ensure that default user options are not invalid, since that breaks Special:Preferences
387 $wgDefaultUserOptions['rcdays'] = min(
388 $wgDefaultUserOptions['rcdays'],
389 ceil( $rcMaxAgeDays )
390 );
391 $wgDefaultUserOptions['watchlistdays'] = min(
392 $wgDefaultUserOptions['watchlistdays'],
393 ceil( $rcMaxAgeDays )
394 );
395 unset( $rcMaxAgeDays );
396
397 if ( $wgSkipSkin ) {
398 $wgSkipSkins[] = $wgSkipSkin;
399 }
400
401 $wgSkipSkins[] = 'fallback';
402 $wgSkipSkins[] = 'apioutput';
403
404 if ( $wgLocalInterwiki ) {
405 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
406 }
407
408 // Set default shared prefix
409 if ( $wgSharedPrefix === false ) {
410 $wgSharedPrefix = $wgDBprefix;
411 }
412
413 // Set default shared schema
414 if ( $wgSharedSchema === false ) {
415 $wgSharedSchema = $wgDBmwschema;
416 }
417
418 if ( !$wgCookiePrefix ) {
419 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
420 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
421 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
422 $wgCookiePrefix = $wgSharedDB;
423 } elseif ( $wgDBprefix ) {
424 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
425 } else {
426 $wgCookiePrefix = $wgDBname;
427 }
428 }
429 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
430
431 if ( $wgEnableEmail ) {
432 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
433 } else {
434 // Disable all other email settings automatically if $wgEnableEmail
435 // is set to false. - T65678
436 $wgAllowHTMLEmail = false;
437 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
438 $wgEnableUserEmail = false;
439 $wgEnotifFromEditor = false;
440 $wgEnotifImpersonal = false;
441 $wgEnotifMaxRecips = 0;
442 $wgEnotifMinorEdits = false;
443 $wgEnotifRevealEditorAddress = false;
444 $wgEnotifUseRealName = false;
445 $wgEnotifUserTalk = false;
446 $wgEnotifWatchlist = false;
447 unset( $wgGroupPermissions['user']['sendemail'] );
448 $wgUseEnotif = false;
449 $wgUserEmailUseReplyTo = false;
450 $wgUsersNotifiedOnAllChanges = [];
451 }
452
453 if ( $wgMetaNamespace === false ) {
454 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
455 }
456
457 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
458 if ( $wgResourceLoaderMaxQueryLength === false ) {
459 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
460 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
461 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
462 } else {
463 $wgResourceLoaderMaxQueryLength = 2000;
464 }
465 unset( $suhosinMaxValueLength );
466 }
467
468 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
469 // upload size.
470 $wgMinUploadChunkSize = min(
471 $wgMinUploadChunkSize,
472 UploadBase::getMaxUploadSize( 'file' ),
473 UploadBase::getMaxPhpUploadSize(),
474 ( wfShorthandToInteger(
475 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
476 PHP_INT_MAX
477 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
478 );
479
480 /**
481 * Definitions of the NS_ constants are in Defines.php
482 * @private
483 */
484 $wgCanonicalNamespaceNames = [
485 NS_MEDIA => 'Media',
486 NS_SPECIAL => 'Special',
487 NS_TALK => 'Talk',
488 NS_USER => 'User',
489 NS_USER_TALK => 'User_talk',
490 NS_PROJECT => 'Project',
491 NS_PROJECT_TALK => 'Project_talk',
492 NS_FILE => 'File',
493 NS_FILE_TALK => 'File_talk',
494 NS_MEDIAWIKI => 'MediaWiki',
495 NS_MEDIAWIKI_TALK => 'MediaWiki_talk',
496 NS_TEMPLATE => 'Template',
497 NS_TEMPLATE_TALK => 'Template_talk',
498 NS_HELP => 'Help',
499 NS_HELP_TALK => 'Help_talk',
500 NS_CATEGORY => 'Category',
501 NS_CATEGORY_TALK => 'Category_talk',
502 ];
503
504 /// @todo UGLY UGLY
505 if ( is_array( $wgExtraNamespaces ) ) {
506 $wgCanonicalNamespaceNames = $wgCanonicalNamespaceNames + $wgExtraNamespaces;
507 }
508
509 // Merge in the legacy language codes, incorporating overrides from the config
510 $wgDummyLanguageCodes += [
511 'qqq' => 'qqq', // Used for message documentation
512 'qqx' => 'qqx', // Used for viewing message keys
513 ] + $wgExtraLanguageCodes + LanguageCode::getDeprecatedCodeMapping();
514
515 // These are now the same, always
516 // To determine the user language, use $wgLang->getCode()
517 $wgContLanguageCode = $wgLanguageCode;
518
519 // Easy to forget to falsify $wgDebugToolbar for static caches.
520 // If file cache or CDN cache is on, just disable this (DWIMD).
521 if ( $wgUseFileCache || $wgUseSquid ) {
522 $wgDebugToolbar = false;
523 }
524
525 // We always output HTML5 since 1.22, overriding these is no longer supported
526 // we set them here for extensions that depend on its value.
527 $wgHtml5 = true;
528 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
529 $wgJsMimeType = 'text/javascript';
530
531 // Blacklisted file extensions shouldn't appear on the "allowed" list
532 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
533
534 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
535 Wikimedia\suppressWarnings();
536 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
537 Wikimedia\restoreWarnings();
538 }
539
540 if ( $wgNewUserLog ) {
541 // Add a new log type
542 $wgLogTypes[] = 'newusers';
543 $wgLogNames['newusers'] = 'newuserlogpage';
544 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
545 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter::class;
546 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter::class;
547 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter::class;
548 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter::class;
549 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter::class;
550 }
551
552 if ( $wgPageLanguageUseDB ) {
553 $wgLogTypes[] = 'pagelang';
554 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter::class;
555 }
556
557 if ( $wgCookieSecure === 'detect' ) {
558 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
559 }
560
561 if ( $wgProfileOnly ) {
562 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
563 $wgDebugLogFile = '';
564 }
565
566 // Backwards compatibility with old password limits
567 if ( $wgMinimalPasswordLength !== false ) {
568 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
569 }
570
571 if ( $wgMaximalPasswordLength !== false ) {
572 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
573 }
574
575 // Backwards compatibility warning
576 if ( !$wgSessionsInObjectCache ) {
577 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
578 if ( $wgSessionHandler ) {
579 wfDeprecated( '$wgSessionsHandler', '1.27' );
580 }
581 $cacheType = get_class( ObjectCache::getInstance( $wgSessionCacheType ) );
582 wfDebugLog(
583 'caches',
584 "Session data will be stored in \"$cacheType\" cache with " .
585 "expiry $wgObjectCacheSessionExpiry seconds"
586 );
587 }
588 $wgSessionsInObjectCache = true;
589
590 if ( $wgPHPSessionHandling !== 'enable' &&
591 $wgPHPSessionHandling !== 'warn' &&
592 $wgPHPSessionHandling !== 'disable'
593 ) {
594 $wgPHPSessionHandling = 'warn';
595 }
596 if ( defined( 'MW_NO_SESSION' ) ) {
597 // If the entry point wants no session, force 'disable' here unless they
598 // specifically set it to the (undocumented) 'warn'.
599 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
600 }
601
602 Profiler::instance()->scopedProfileOut( $ps_default );
603
604 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
605 // all the memory from logging SQL queries on maintenance scripts
606 global $wgCommandLineMode;
607 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
608 MWDebug::init();
609 }
610
611 // Reset the global service locator, so any services that have already been created will be
612 // re-created while taking into account any custom settings and extensions.
613 MediaWikiServices::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
614
615 if ( $wgSharedDB && $wgSharedTables ) {
616 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
617 MediaWikiServices::getInstance()->getDBLoadBalancer()->setTableAliases(
618 array_fill_keys(
619 $wgSharedTables,
620 [
621 'dbname' => $wgSharedDB,
622 'schema' => $wgSharedSchema,
623 'prefix' => $wgSharedPrefix
624 ]
625 )
626 );
627 }
628
629 // Define a constant that indicates that the bootstrapping of the service locator
630 // is complete.
631 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
632
633 MWExceptionHandler::installHandler();
634
635 require_once "$IP/includes/compat/normal/UtfNormalUtil.php";
636
637 $ps_validation = Profiler::instance()->scopedProfileIn( $fname . '-validation' );
638
639 // T48998: Bail out early if $wgArticlePath is non-absolute
640 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
641 if ( $$varName && !preg_match( '/^(https?:\/\/|\/)/', $$varName ) ) {
642 throw new FatalError(
643 "If you use a relative URL for \$$varName, it must start " .
644 'with a slash (<code>/</code>).<br><br>See ' .
645 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
646 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
647 );
648 }
649 }
650
651 Profiler::instance()->scopedProfileOut( $ps_validation );
652
653 $ps_default2 = Profiler::instance()->scopedProfileIn( $fname . '-defaults2' );
654
655 if ( $wgCanonicalServer === false ) {
656 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP );
657 }
658
659 // Set server name
660 $serverParts = wfParseUrl( $wgCanonicalServer );
661 if ( $wgServerName !== false ) {
662 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
663 . 'not customized. Overwriting $wgServerName.' );
664 }
665 $wgServerName = $serverParts['host'];
666 unset( $serverParts );
667
668 // Set defaults for configuration variables
669 // that are derived from the server name by default
670 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
671 if ( !$wgEmergencyContact ) {
672 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
673 }
674 if ( !$wgPasswordSender ) {
675 $wgPasswordSender = 'apache@' . $wgServerName;
676 }
677 if ( !$wgNoReplyAddress ) {
678 $wgNoReplyAddress = $wgPasswordSender;
679 }
680
681 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
682 $wgSecureLogin = false;
683 wfWarn( 'Secure login was enabled on a server that only supports '
684 . 'HTTP or HTTPS. Disabling secure login.' );
685 }
686
687 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
688
689 // Now that GlobalFunctions is loaded, set defaults that depend on it.
690 if ( $wgTmpDirectory === false ) {
691 $wgTmpDirectory = wfTempDir();
692 }
693
694 // We don't use counters anymore. Left here for extensions still
695 // expecting this to exist. Should be removed sometime 1.26 or later.
696 if ( !isset( $wgDisableCounters ) ) {
697 $wgDisableCounters = true;
698 }
699
700 if ( $wgMainWANCache === false ) {
701 // Setup a WAN cache from $wgMainCacheType with no relayer.
702 // Sites using multiple datacenters can configure a relayer.
703 $wgMainWANCache = 'mediawiki-main-default';
704 $wgWANObjectCaches[$wgMainWANCache] = [
705 'class' => WANObjectCache::class,
706 'cacheId' => $wgMainCacheType,
707 'channels' => [ 'purge' => 'wancache-main-default-purge' ]
708 ];
709 }
710
711 Profiler::instance()->scopedProfileOut( $ps_default2 );
712
713 $ps_misc = Profiler::instance()->scopedProfileIn( $fname . '-misc1' );
714
715 // Raise the memory limit if it's too low
716 wfMemoryLimit();
717
718 /**
719 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
720 * that happens whenever you use a date function without the timezone being
721 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
722 */
723 if ( is_null( $wgLocaltimezone ) ) {
724 Wikimedia\suppressWarnings();
725 $wgLocaltimezone = date_default_timezone_get();
726 Wikimedia\restoreWarnings();
727 }
728
729 date_default_timezone_set( $wgLocaltimezone );
730 if ( is_null( $wgLocalTZoffset ) ) {
731 $wgLocalTZoffset = date( 'Z' ) / 60;
732 }
733 // The part after the System| is ignored, but rest of MW fills it
734 // out as the local offset.
735 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
736
737 if ( !$wgDBerrorLogTZ ) {
738 $wgDBerrorLogTZ = $wgLocaltimezone;
739 }
740
741 // Initialize the request object in $wgRequest
742 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
743 // Set user IP/agent information for agent session consistency purposes
744 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
745 'IPAddress' => $wgRequest->getIP(),
746 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
747 'ChronologyProtection' => $wgRequest->getHeader( 'ChronologyProtection' ),
748 // The cpPosIndex cookie has no prefix and is set by MediaWiki::preOutputCommit()
749 'ChronologyPositionIndex' =>
750 $wgRequest->getInt( 'cpPosIndex', (int)$wgRequest->getCookie( 'cpPosIndex', '' ) )
751 ] );
752 // Make sure that object caching does not undermine the ChronologyProtector improvements
753 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
754 // The user is pinned to the primary DC, meaning that they made recent changes which should
755 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
756 // they use a blind TTL and could be stale if an object changes twice in a short time span.
757 MediaWikiServices::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
758 }
759
760 // Useful debug output
761 if ( $wgCommandLineMode ) {
762 wfDebug( "\n\nStart command line script $self\n" );
763 } else {
764 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
765
766 if ( $wgDebugPrintHttpHeaders ) {
767 $debug .= "HTTP HEADERS:\n";
768
769 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
770 $debug .= "$name: $value\n";
771 }
772 }
773 wfDebug( $debug );
774 }
775
776 Profiler::instance()->scopedProfileOut( $ps_misc );
777 $ps_memcached = Profiler::instance()->scopedProfileIn( $fname . '-memcached' );
778
779 $wgMemc = wfGetMainCache();
780 $messageMemc = wfGetMessageCacheStorage();
781
782 /**
783 * @deprecated since 1.30
784 */
785 $parserMemc = new DeprecatedGlobal( 'parserMemc', function () {
786 return MediaWikiServices::getInstance()->getParserCache()->getCacheStorage();
787 }, '1.30' );
788
789 wfDebugLog( 'caches',
790 'cluster: ' . get_class( $wgMemc ) .
791 ', WAN: ' . ( $wgMainWANCache === CACHE_NONE ? 'CACHE_NONE' : $wgMainWANCache ) .
792 ', stash: ' . $wgMainStash .
793 ', message: ' . get_class( $messageMemc ) .
794 ', session: ' . get_class( ObjectCache::getInstance( $wgSessionCacheType ) )
795 );
796
797 Profiler::instance()->scopedProfileOut( $ps_memcached );
798
799 // Most of the config is out, some might want to run hooks here.
800 Hooks::run( 'SetupAfterCache' );
801
802 $ps_globals = Profiler::instance()->scopedProfileIn( $fname . '-globals' );
803
804 /**
805 * @var Language $wgContLang
806 */
807 $wgContLang = Language::factory( $wgLanguageCode );
808 $wgContLang->initContLang();
809
810 // Now that variant lists may be available...
811 $wgRequest->interpolateTitle();
812
813 if ( !is_object( $wgAuth ) ) {
814 $wgAuth = new MediaWiki\Auth\AuthManagerAuthPlugin;
815 Hooks::run( 'AuthPluginSetup', [ &$wgAuth ] );
816 }
817 if ( $wgAuth && !$wgAuth instanceof MediaWiki\Auth\AuthManagerAuthPlugin ) {
818 MediaWiki\Auth\AuthManager::singleton()->forcePrimaryAuthenticationProviders( [
819 new MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider( [
820 'authoritative' => false,
821 ] ),
822 new MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider( $wgAuth ),
823 new MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider( [
824 'authoritative' => true,
825 ] ),
826 ], '$wgAuth is ' . get_class( $wgAuth ) );
827 }
828
829 // Set up the session
830 $ps_session = Profiler::instance()->scopedProfileIn( $fname . '-session' );
831 /**
832 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
833 * session ID (if any) loaded at startup
834 */
835 $wgInitialSessionId = null;
836 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
837 // If session.auto_start is there, we can't touch session name
838 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
839 session_name( $wgSessionName ? $wgSessionName : $wgCookiePrefix . '_session' );
840 }
841
842 // Create the SessionManager singleton and set up our session handler,
843 // unless we're specifically asked not to.
844 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
845 MediaWiki\Session\PHPSessionHandler::install(
846 MediaWiki\Session\SessionManager::singleton()
847 );
848 }
849
850 // Initialize the session
851 try {
852 $session = MediaWiki\Session\SessionManager::getGlobalSession();
853 } catch ( OverflowException $ex ) {
854 if ( isset( $ex->sessionInfos ) && count( $ex->sessionInfos ) >= 2 ) {
855 // The exception is because the request had multiple possible
856 // sessions tied for top priority. Report this to the user.
857 $list = [];
858 foreach ( $ex->sessionInfos as $info ) {
859 $list[] = $info->getProvider()->describe( $wgContLang );
860 }
861 $list = $wgContLang->listToText( $list );
862 throw new HttpError( 400,
863 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
864 );
865 }
866
867 // Not the one we want, rethrow
868 throw $ex;
869 }
870
871 if ( $session->isPersistent() ) {
872 $wgInitialSessionId = $session->getSessionId();
873 }
874
875 $session->renew();
876 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
877 ( $session->isPersistent() || $session->shouldRememberUser() )
878 ) {
879 // Start the PHP-session for backwards compatibility
880 session_id( $session->getId() );
881 Wikimedia\quietCall( 'session_start' );
882 }
883
884 unset( $session );
885 } else {
886 // Even if we didn't set up a global Session, still install our session
887 // handler unless specifically requested not to.
888 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
889 MediaWiki\Session\PHPSessionHandler::install(
890 MediaWiki\Session\SessionManager::singleton()
891 );
892 }
893 }
894 Profiler::instance()->scopedProfileOut( $ps_session );
895
896 /**
897 * @var User $wgUser
898 */
899 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
900
901 /**
902 * @var Language $wgLang
903 */
904 $wgLang = new StubUserLang;
905
906 /**
907 * @var OutputPage $wgOut
908 */
909 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
910
911 /**
912 * @var Parser $wgParser
913 */
914 $wgParser = new StubObject( 'wgParser', function () {
915 return MediaWikiServices::getInstance()->getParser();
916 } );
917
918 /**
919 * @var Title $wgTitle
920 */
921 $wgTitle = null;
922
923 Profiler::instance()->scopedProfileOut( $ps_globals );
924 $ps_extensions = Profiler::instance()->scopedProfileIn( $fname . '-extensions' );
925
926 // Extension setup functions
927 // Entries should be added to this variable during the inclusion
928 // of the extension file. This allows the extension to perform
929 // any necessary initialisation in the fully initialised environment
930 foreach ( $wgExtensionFunctions as $func ) {
931 // Allow closures in PHP 5.3+
932 if ( is_object( $func ) && $func instanceof Closure ) {
933 $profName = $fname . '-extensions-closure';
934 } elseif ( is_array( $func ) ) {
935 if ( is_object( $func[0] ) ) {
936 $profName = $fname . '-extensions-' . get_class( $func[0] ) . '::' . $func[1];
937 } else {
938 $profName = $fname . '-extensions-' . implode( '::', $func );
939 }
940 } else {
941 $profName = $fname . '-extensions-' . strval( $func );
942 }
943
944 $ps_ext_func = Profiler::instance()->scopedProfileIn( $profName );
945 call_user_func( $func );
946 Profiler::instance()->scopedProfileOut( $ps_ext_func );
947 }
948
949 // If the session user has a 0 id but a valid name, that means we need to
950 // autocreate it.
951 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
952 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
953 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
954 $ps_autocreate = Profiler::instance()->scopedProfileIn( $fname . '-autocreate' );
955 $res = MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
956 $sessionUser,
957 MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
958 true
959 );
960 Profiler::instance()->scopedProfileOut( $ps_autocreate );
961 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Autocreation attempt', [
962 'event' => 'autocreate',
963 'status' => $res,
964 ] );
965 unset( $res );
966 }
967 unset( $sessionUser );
968 }
969
970 if ( !$wgCommandLineMode ) {
971 Pingback::schedulePingback();
972 }
973
974 $wgFullyInitialised = true;
975
976 Profiler::instance()->scopedProfileOut( $ps_extensions );
977 Profiler::instance()->scopedProfileOut( $ps_setup );