Merge "Preload styles for 'jquery.tablesorter'"
[lhc/web/wiklou.git] / includes / Setup.php
1 <?php
2 /**
3 * Include most things that are needed to make MediaWiki work.
4 *
5 * This file is included by WebStart.php and doMaintenance.php so that both
6 * web and maintenance scripts share a final set up phase to include necessary
7 * files and create global object variables.
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26 use MediaWiki\MediaWikiServices;
27 use Wikimedia\Rdbms\LBFactory;
28 use Wikimedia\Rdbms\ChronologyProtector;
29
30 /**
31 * This file is not a valid entry point, perform no further processing unless
32 * MEDIAWIKI is defined
33 */
34 if ( !defined( 'MEDIAWIKI' ) ) {
35 exit( 1 );
36 }
37
38 // Check to see if we are at the file scope
39 $wgScopeTest = 'MediaWiki Setup.php scope test';
40 if ( !isset( $GLOBALS['wgScopeTest'] ) || $GLOBALS['wgScopeTest'] !== $wgScopeTest ) {
41 echo "Error, Setup.php must be included from the file scope.\n";
42 die( 1 );
43 }
44 unset( $wgScopeTest );
45
46 /**
47 * Pre-config setup: Before loading LocalSettings.php
48 */
49
50 // Sanity check (T5782, T122807)
51 if ( ini_get( 'mbstring.func_overload' ) ) {
52 die( 'MediaWiki does not support installations where mbstring.func_overload is non-zero.' );
53 }
54
55 // Start the autoloader, so that extensions can derive classes from core files
56 require_once "$IP/includes/AutoLoader.php";
57
58 // Load up some global defines
59 require_once "$IP/includes/Defines.php";
60
61 // Load default settings
62 require_once "$IP/includes/DefaultSettings.php";
63
64 // Load global functions
65 require_once "$IP/includes/GlobalFunctions.php";
66
67 // Load composer's autoloader if present
68 if ( is_readable( "$IP/vendor/autoload.php" ) ) {
69 require_once "$IP/vendor/autoload.php";
70 }
71
72 // Assert that composer dependencies were successfully loaded
73 // Purposely no leading \ due to it breaking HHVM RepoAuthorative mode
74 // PHP works fine with both versions
75 // See https://github.com/facebook/hhvm/issues/5833
76 if ( !interface_exists( 'Psr\Log\LoggerInterface' ) ) {
77 $message = (
78 'MediaWiki requires the <a href="https://github.com/php-fig/log">PSR-3 logging ' .
79 "library</a> to be present. This library is not embedded directly in MediaWiki's " .
80 "git repository and must be installed separately by the end user.\n\n" .
81 'Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git' .
82 '#Fetch_external_libraries">mediawiki.org</a> for help on installing ' .
83 'the required components.'
84 );
85 echo $message;
86 trigger_error( $message, E_USER_ERROR );
87 die( 1 );
88 }
89
90 // Install a header callback
91 MediaWiki\HeaderCallback::register();
92
93 /**
94 * Load LocalSettings.php
95 */
96
97 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
98 call_user_func( MW_CONFIG_CALLBACK );
99 } else {
100 if ( !defined( 'MW_CONFIG_FILE' ) ) {
101 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
102 }
103 require_once MW_CONFIG_FILE;
104 }
105
106 /**
107 * Customization point after all loading (constants, functions, classes,
108 * DefaultSettings, LocalSettings). Specifically, this is before usage of
109 * settings, before instantiation of Profiler (and other singletons), and
110 * before any setup functions or hooks run.
111 */
112
113 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
114 call_user_func( MW_SETUP_CALLBACK );
115 }
116
117 /**
118 * Main setup
119 */
120
121 $fname = 'Setup.php';
122 $ps_setup = Profiler::instance()->scopedProfileIn( $fname );
123
124 // Load queued extensions
125 ExtensionRegistry::getInstance()->loadFromQueue();
126 // Don't let any other extensions load
127 ExtensionRegistry::getInstance()->finish();
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 // Fix path to icon images after they were moved in 1.24
198 if ( $wgRightsIcon ) {
199 $wgRightsIcon = str_replace(
200 "{$wgStylePath}/common/images/",
201 "{$wgResourceBasePath}/resources/assets/licenses/",
202 $wgRightsIcon
203 );
204 }
205
206 if ( isset( $wgFooterIcons['copyright']['copyright'] )
207 && $wgFooterIcons['copyright']['copyright'] === []
208 ) {
209 if ( $wgRightsIcon || $wgRightsText ) {
210 $wgFooterIcons['copyright']['copyright'] = [
211 'url' => $wgRightsUrl,
212 'src' => $wgRightsIcon,
213 'alt' => $wgRightsText,
214 ];
215 }
216 }
217
218 if ( isset( $wgFooterIcons['poweredby'] )
219 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
220 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
221 ) {
222 $wgFooterIcons['poweredby']['mediawiki']['src'] =
223 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
224 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
225 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
226 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
227 }
228
229 /**
230 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
231 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
232 *
233 * Note that this is the definition of editinterface and it can be granted to
234 * all users if desired.
235 */
236 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
237
238 /**
239 * The canonical names of namespaces 6 and 7 are, as of v1.14, "File"
240 * and "File_talk". The old names "Image" and "Image_talk" are
241 * retained as aliases for backwards compatibility.
242 */
243 $wgNamespaceAliases['Image'] = NS_FILE;
244 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
245
246 /**
247 * Initialise $wgLockManagers to include basic FS version
248 */
249 $wgLockManagers[] = [
250 'name' => 'fsLockManager',
251 'class' => FSLockManager::class,
252 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
253 ];
254 $wgLockManagers[] = [
255 'name' => 'nullLockManager',
256 'class' => NullLockManager::class,
257 ];
258
259 /**
260 * Default parameters for the "<gallery>" tag.
261 * @see DefaultSettings.php for description of the fields.
262 */
263 $wgGalleryOptions += [
264 'imagesPerRow' => 0,
265 'imageWidth' => 120,
266 'imageHeight' => 120,
267 'captionLength' => true,
268 'showBytes' => true,
269 'showDimensions' => true,
270 'mode' => 'traditional',
271 ];
272
273 /**
274 * Shortcuts for $wgLocalFileRepo
275 */
276 if ( !$wgLocalFileRepo ) {
277 $wgLocalFileRepo = [
278 'class' => LocalRepo::class,
279 'name' => 'local',
280 'directory' => $wgUploadDirectory,
281 'scriptDirUrl' => $wgScriptPath,
282 'url' => $wgUploadBaseUrl ? $wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
283 'hashLevels' => $wgHashedUploadDirectory ? 2 : 0,
284 'thumbScriptUrl' => $wgThumbnailScriptPath,
285 'transformVia404' => !$wgGenerateThumbnailOnParse,
286 'deletedDir' => $wgDeletedDirectory,
287 'deletedHashLevels' => $wgHashedUploadDirectory ? 3 : 0
288 ];
289 }
290
291 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
292 // Create a default FileBackend name.
293 // FileBackendGroup will register a default, if absent from $wgFileBackends.
294 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
295 }
296
297 /**
298 * Shortcuts for $wgForeignFileRepos
299 */
300 if ( $wgUseSharedUploads ) {
301 if ( $wgSharedUploadDBname ) {
302 $wgForeignFileRepos[] = [
303 'class' => ForeignDBRepo::class,
304 'name' => 'shared',
305 'directory' => $wgSharedUploadDirectory,
306 'url' => $wgSharedUploadPath,
307 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
308 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
309 'transformVia404' => !$wgGenerateThumbnailOnParse,
310 'dbType' => $wgDBtype,
311 'dbServer' => $wgDBserver,
312 'dbUser' => $wgDBuser,
313 'dbPassword' => $wgDBpassword,
314 'dbName' => $wgSharedUploadDBname,
315 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG : 0 ) | DBO_DEFAULT,
316 'tablePrefix' => $wgSharedUploadDBprefix,
317 'hasSharedCache' => $wgCacheSharedUploads,
318 'descBaseUrl' => $wgRepositoryBaseUrl,
319 'fetchDescription' => $wgFetchCommonsDescriptions,
320 ];
321 } else {
322 $wgForeignFileRepos[] = [
323 'class' => FileRepo::class,
324 'name' => 'shared',
325 'directory' => $wgSharedUploadDirectory,
326 'url' => $wgSharedUploadPath,
327 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
328 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
329 'transformVia404' => !$wgGenerateThumbnailOnParse,
330 'descBaseUrl' => $wgRepositoryBaseUrl,
331 'fetchDescription' => $wgFetchCommonsDescriptions,
332 ];
333 }
334 }
335 if ( $wgUseInstantCommons ) {
336 $wgForeignFileRepos[] = [
337 'class' => ForeignAPIRepo::class,
338 'name' => 'wikimediacommons',
339 'apibase' => 'https://commons.wikimedia.org/w/api.php',
340 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
341 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
342 'hashLevels' => 2,
343 'transformVia404' => true,
344 'fetchDescription' => true,
345 'descriptionCacheExpiry' => 43200,
346 'apiThumbCacheExpiry' => 0,
347 ];
348 }
349 foreach ( $wgForeignFileRepos as &$repo ) {
350 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo::class ) {
351 $repo['directory'] = $wgUploadDirectory; // b/c
352 }
353 if ( !isset( $repo['backend'] ) ) {
354 $repo['backend'] = $repo['name'] . '-backend';
355 }
356 }
357 unset( $repo ); // no global pollution; destroy reference
358
359 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
360 if ( $wgRCFilterByAge ) {
361 // Trim down $wgRCLinkDays so that it only lists links which are valid
362 // as determined by $wgRCMaxAge.
363 // Note that we allow 1 link higher than the max for things like 56 days but a 60 day link.
364 sort( $wgRCLinkDays );
365
366 foreach ( $wgRCLinkDays as $i => $days ) {
367 if ( $days >= $rcMaxAgeDays ) {
368 array_splice( $wgRCLinkDays, $i + 1 );
369 break;
370 }
371 }
372 }
373 // Ensure that default user options are not invalid, since that breaks Special:Preferences
374 $wgDefaultUserOptions['rcdays'] = min(
375 $wgDefaultUserOptions['rcdays'],
376 ceil( $rcMaxAgeDays )
377 );
378 $wgDefaultUserOptions['watchlistdays'] = min(
379 $wgDefaultUserOptions['watchlistdays'],
380 ceil( $rcMaxAgeDays )
381 );
382 unset( $rcMaxAgeDays );
383
384 if ( $wgSkipSkin ) {
385 $wgSkipSkins[] = $wgSkipSkin;
386 }
387
388 $wgSkipSkins[] = 'fallback';
389 $wgSkipSkins[] = 'apioutput';
390
391 if ( $wgLocalInterwiki ) {
392 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
393 }
394
395 // Set default shared prefix
396 if ( $wgSharedPrefix === false ) {
397 $wgSharedPrefix = $wgDBprefix;
398 }
399
400 // Set default shared schema
401 if ( $wgSharedSchema === false ) {
402 $wgSharedSchema = $wgDBmwschema;
403 }
404
405 if ( !$wgCookiePrefix ) {
406 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
407 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
408 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
409 $wgCookiePrefix = $wgSharedDB;
410 } elseif ( $wgDBprefix ) {
411 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
412 } else {
413 $wgCookiePrefix = $wgDBname;
414 }
415 }
416 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
417
418 if ( $wgEnableEmail ) {
419 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
420 } else {
421 // Disable all other email settings automatically if $wgEnableEmail
422 // is set to false. - T65678
423 $wgAllowHTMLEmail = false;
424 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
425 $wgEnableUserEmail = false;
426 $wgEnotifFromEditor = false;
427 $wgEnotifImpersonal = false;
428 $wgEnotifMaxRecips = 0;
429 $wgEnotifMinorEdits = false;
430 $wgEnotifRevealEditorAddress = false;
431 $wgEnotifUseRealName = false;
432 $wgEnotifUserTalk = false;
433 $wgEnotifWatchlist = false;
434 unset( $wgGroupPermissions['user']['sendemail'] );
435 $wgUseEnotif = false;
436 $wgUserEmailUseReplyTo = false;
437 $wgUsersNotifiedOnAllChanges = [];
438 }
439
440 if ( $wgMetaNamespace === false ) {
441 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
442 }
443
444 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
445 if ( $wgResourceLoaderMaxQueryLength === false ) {
446 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
447 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
448 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
449 } else {
450 $wgResourceLoaderMaxQueryLength = 2000;
451 }
452 unset( $suhosinMaxValueLength );
453 }
454
455 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
456 // upload size.
457 $wgMinUploadChunkSize = min(
458 $wgMinUploadChunkSize,
459 UploadBase::getMaxUploadSize( 'file' ),
460 UploadBase::getMaxPhpUploadSize(),
461 ( wfShorthandToInteger(
462 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
463 PHP_INT_MAX
464 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
465 );
466
467 /**
468 * Definitions of the NS_ constants are in Defines.php
469 * @private
470 */
471 $wgCanonicalNamespaceNames = [
472 NS_MEDIA => 'Media',
473 NS_SPECIAL => 'Special',
474 NS_TALK => 'Talk',
475 NS_USER => 'User',
476 NS_USER_TALK => 'User_talk',
477 NS_PROJECT => 'Project',
478 NS_PROJECT_TALK => 'Project_talk',
479 NS_FILE => 'File',
480 NS_FILE_TALK => 'File_talk',
481 NS_MEDIAWIKI => 'MediaWiki',
482 NS_MEDIAWIKI_TALK => 'MediaWiki_talk',
483 NS_TEMPLATE => 'Template',
484 NS_TEMPLATE_TALK => 'Template_talk',
485 NS_HELP => 'Help',
486 NS_HELP_TALK => 'Help_talk',
487 NS_CATEGORY => 'Category',
488 NS_CATEGORY_TALK => 'Category_talk',
489 ];
490
491 /// @todo UGLY UGLY
492 if ( is_array( $wgExtraNamespaces ) ) {
493 $wgCanonicalNamespaceNames = $wgCanonicalNamespaceNames + $wgExtraNamespaces;
494 }
495
496 // Hard-deprecate setting $wgDummyLanguageCodes in LocalSettings.php
497 if ( count( $wgDummyLanguageCodes ) !== 0 ) {
498 wfDeprecated( '$wgDummyLanguageCodes', '1.29' );
499 }
500 // Merge in the legacy language codes, incorporating overrides from the config
501 $wgDummyLanguageCodes += [
502 // Internal language codes of the private-use area which get mapped to
503 // themselves.
504 'qqq' => 'qqq', // Used for message documentation
505 'qqx' => 'qqx', // Used for viewing message keys
506 ] + $wgExtraLanguageCodes + LanguageCode::getDeprecatedCodeMapping();
507 // Merge in (inverted) BCP 47 mappings
508 foreach ( LanguageCode::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
509 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
510 if ( !isset( $wgDummyLanguageCodes[$bcp47] ) ) {
511 $wgDummyLanguageCodes[$bcp47] = $wgDummyLanguageCodes[$code] ?? $code;
512 }
513 }
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 new user 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 ( $wgPageCreationLog ) {
553 // Add page creation log type
554 $wgLogTypes[] = 'create';
555 $wgLogActionsHandlers['create/create'] = LogFormatter::class;
556 }
557
558 if ( $wgPageLanguageUseDB ) {
559 $wgLogTypes[] = 'pagelang';
560 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter::class;
561 }
562
563 if ( $wgCookieSecure === 'detect' ) {
564 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
565 }
566
567 if ( $wgProfileOnly ) {
568 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
569 $wgDebugLogFile = '';
570 }
571
572 // Backwards compatibility with old password limits
573 if ( $wgMinimalPasswordLength !== false ) {
574 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
575 }
576
577 if ( $wgMaximalPasswordLength !== false ) {
578 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
579 }
580
581 // Backwards compatibility warning
582 if ( !$wgSessionsInObjectCache ) {
583 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
584 if ( $wgSessionHandler ) {
585 wfDeprecated( '$wgSessionsHandler', '1.27' );
586 }
587 $cacheType = get_class( ObjectCache::getInstance( $wgSessionCacheType ) );
588 wfDebugLog(
589 'caches',
590 "Session data will be stored in \"$cacheType\" cache with " .
591 "expiry $wgObjectCacheSessionExpiry seconds"
592 );
593 }
594 $wgSessionsInObjectCache = true;
595
596 if ( $wgPHPSessionHandling !== 'enable' &&
597 $wgPHPSessionHandling !== 'warn' &&
598 $wgPHPSessionHandling !== 'disable'
599 ) {
600 $wgPHPSessionHandling = 'warn';
601 }
602 if ( defined( 'MW_NO_SESSION' ) ) {
603 // If the entry point wants no session, force 'disable' here unless they
604 // specifically set it to the (undocumented) 'warn'.
605 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
606 }
607
608 Profiler::instance()->scopedProfileOut( $ps_default );
609
610 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
611 // all the memory from logging SQL queries on maintenance scripts
612 global $wgCommandLineMode;
613 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
614 MWDebug::init();
615 }
616
617 // Reset the global service locator, so any services that have already been created will be
618 // re-created while taking into account any custom settings and extensions.
619 MediaWikiServices::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
620
621 if ( $wgSharedDB && $wgSharedTables ) {
622 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
623 MediaWikiServices::getInstance()->getDBLoadBalancer()->setTableAliases(
624 array_fill_keys(
625 $wgSharedTables,
626 [
627 'dbname' => $wgSharedDB,
628 'schema' => $wgSharedSchema,
629 'prefix' => $wgSharedPrefix
630 ]
631 )
632 );
633 }
634
635 // Define a constant that indicates that the bootstrapping of the service locator
636 // is complete.
637 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
638
639 MWExceptionHandler::installHandler();
640
641 // T48998: Bail out early if $wgArticlePath is non-absolute
642 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
643 if ( $$varName && !preg_match( '/^(https?:\/\/|\/)/', $$varName ) ) {
644 throw new FatalError(
645 "If you use a relative URL for \$$varName, it must start " .
646 'with a slash (<code>/</code>).<br><br>See ' .
647 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
648 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
649 );
650 }
651 }
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 . '-misc' );
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 $cpPosInfo = LBFactory::getCPInfoFromCookieValue(
745 // The cookie has no prefix and is set by MediaWiki::preOutputCommit()
746 $wgRequest->getCookie( 'cpPosIndex', '' ),
747 // Mitigate broken client-side cookie expiration handling (T190082)
748 time() - ChronologyProtector::POSITION_COOKIE_TTL
749 );
750 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
751 'IPAddress' => $wgRequest->getIP(),
752 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
753 'ChronologyProtection' => $wgRequest->getHeader( 'ChronologyProtection' ),
754 'ChronologyPositionIndex' => $wgRequest->getInt( 'cpPosIndex', $cpPosInfo['index'] ),
755 'ChronologyClientId' => $cpPosInfo['clientId']
756 ] );
757 unset( $cpPosInfo );
758 // Make sure that object caching does not undermine the ChronologyProtector improvements
759 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
760 // The user is pinned to the primary DC, meaning that they made recent changes which should
761 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
762 // they use a blind TTL and could be stale if an object changes twice in a short time span.
763 MediaWikiServices::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
764 }
765
766 // Useful debug output
767 if ( $wgCommandLineMode ) {
768 wfDebug( "\n\nStart command line script $self\n" );
769 } else {
770 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
771
772 if ( $wgDebugPrintHttpHeaders ) {
773 $debug .= "HTTP HEADERS:\n";
774
775 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
776 $debug .= "$name: $value\n";
777 }
778 }
779 wfDebug( $debug );
780 }
781
782 $wgMemc = ObjectCache::getLocalClusterInstance();
783 $messageMemc = wfGetMessageCacheStorage();
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_misc );
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 * @deprecated since 1.32, use the ContentLanguage service directly
803 */
804 $wgContLang = MediaWikiServices::getInstance()->getContentLanguage();
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 /**
826 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
827 * session ID (if any) loaded at startup
828 */
829 $wgInitialSessionId = null;
830 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
831 // If session.auto_start is there, we can't touch session name
832 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
833 session_name( $wgSessionName ?: $wgCookiePrefix . '_session' );
834 }
835
836 // Create the SessionManager singleton and set up our session handler,
837 // unless we're specifically asked not to.
838 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
839 MediaWiki\Session\PHPSessionHandler::install(
840 MediaWiki\Session\SessionManager::singleton()
841 );
842 }
843
844 // Initialize the session
845 try {
846 $session = MediaWiki\Session\SessionManager::getGlobalSession();
847 } catch ( OverflowException $ex ) {
848 if ( isset( $ex->sessionInfos ) && count( $ex->sessionInfos ) >= 2 ) {
849 // The exception is because the request had multiple possible
850 // sessions tied for top priority. Report this to the user.
851 $list = [];
852 foreach ( $ex->sessionInfos as $info ) {
853 $list[] = $info->getProvider()->describe( $wgContLang );
854 }
855 $list = $wgContLang->listToText( $list );
856 throw new HttpError( 400,
857 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
858 );
859 }
860
861 // Not the one we want, rethrow
862 throw $ex;
863 }
864
865 if ( $session->isPersistent() ) {
866 $wgInitialSessionId = $session->getSessionId();
867 }
868
869 $session->renew();
870 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
871 ( $session->isPersistent() || $session->shouldRememberUser() ) &&
872 session_id() !== $session->getId()
873 ) {
874 // Start the PHP-session for backwards compatibility
875 if ( session_id() !== '' ) {
876 wfDebugLog( 'session', 'PHP session {old_id} was already started, changing to {new_id}', 'all', [
877 'old_id' => session_id(),
878 'new_id' => $session->getId(),
879 ] );
880 session_write_close();
881 }
882 session_id( $session->getId() );
883 session_start();
884 }
885
886 unset( $session );
887 } else {
888 // Even if we didn't set up a global Session, still install our session
889 // handler unless specifically requested not to.
890 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
891 MediaWiki\Session\PHPSessionHandler::install(
892 MediaWiki\Session\SessionManager::singleton()
893 );
894 }
895 }
896
897 /**
898 * @var User $wgUser
899 */
900 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
901
902 /**
903 * @var Language $wgLang
904 */
905 $wgLang = new StubUserLang;
906
907 /**
908 * @var OutputPage $wgOut
909 */
910 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
911
912 /**
913 * @var Parser $wgParser
914 * @deprecated since 1.32, use MediaWikiServices::getParser() instead
915 */
916 $wgParser = new StubObject( 'wgParser', function () {
917 return MediaWikiServices::getInstance()->getParser();
918 } );
919
920 /**
921 * @var Title $wgTitle
922 */
923 $wgTitle = null;
924
925 Profiler::instance()->scopedProfileOut( $ps_globals );
926 $ps_extensions = Profiler::instance()->scopedProfileIn( $fname . '-extensions' );
927
928 // Extension setup functions
929 // Entries should be added to this variable during the inclusion
930 // of the extension file. This allows the extension to perform
931 // any necessary initialisation in the fully initialised environment
932 foreach ( $wgExtensionFunctions as $func ) {
933 call_user_func( $func );
934 }
935
936 // If the session user has a 0 id but a valid name, that means we need to
937 // autocreate it.
938 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
939 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
940 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
941 $res = MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
942 $sessionUser,
943 MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
944 true
945 );
946 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Autocreation attempt', [
947 'event' => 'autocreate',
948 'status' => $res,
949 ] );
950 unset( $res );
951 }
952 unset( $sessionUser );
953 }
954
955 if ( !$wgCommandLineMode ) {
956 Pingback::schedulePingback();
957 }
958
959 $wgFullyInitialised = true;
960
961 Profiler::instance()->scopedProfileOut( $ps_extensions );
962 Profiler::instance()->scopedProfileOut( $ps_setup );