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