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