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