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