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