Merge "Move libs/time/defines.php inclusion from GlobalFunctions to Defines.php"
[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' => 86400,
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. - bug 63678
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 // These are now the same, always
407 // To determine the user language, use $wgLang->getCode()
408 $wgContLanguageCode = $wgLanguageCode;
409
410 // Easy to forget to falsify $wgDebugToolbar for static caches.
411 // If file cache or CDN cache is on, just disable this (DWIMD).
412 if ( $wgUseFileCache || $wgUseSquid ) {
413 $wgDebugToolbar = false;
414 }
415
416 // We always output HTML5 since 1.22, overriding these is no longer supported
417 // we set them here for extensions that depend on its value.
418 $wgHtml5 = true;
419 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
420 $wgJsMimeType = 'text/javascript';
421
422 // Blacklisted file extensions shouldn't appear on the "allowed" list
423 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
424
425 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
426 MediaWiki\suppressWarnings();
427 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
428 MediaWiki\restoreWarnings();
429 }
430
431 if ( $wgNewUserLog ) {
432 // Add a new log type
433 $wgLogTypes[] = 'newusers';
434 $wgLogNames['newusers'] = 'newuserlogpage';
435 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
436 $wgLogActionsHandlers['newusers/newusers'] = 'NewUsersLogFormatter';
437 $wgLogActionsHandlers['newusers/create'] = 'NewUsersLogFormatter';
438 $wgLogActionsHandlers['newusers/create2'] = 'NewUsersLogFormatter';
439 $wgLogActionsHandlers['newusers/byemail'] = 'NewUsersLogFormatter';
440 $wgLogActionsHandlers['newusers/autocreate'] = 'NewUsersLogFormatter';
441 }
442
443 if ( $wgPageLanguageUseDB ) {
444 $wgLogTypes[] = 'pagelang';
445 $wgLogActionsHandlers['pagelang/pagelang'] = 'PageLangLogFormatter';
446 }
447
448 if ( $wgCookieSecure === 'detect' ) {
449 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
450 }
451
452 if ( $wgProfileOnly ) {
453 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
454 $wgDebugLogFile = '';
455 }
456
457 // Backwards compatibility with old password limits
458 if ( $wgMinimalPasswordLength !== false ) {
459 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
460 }
461
462 if ( $wgMaximalPasswordLength !== false ) {
463 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
464 }
465
466 // Backwards compatibility warning
467 if ( !$wgSessionsInObjectCache ) {
468 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
469 if ( $wgSessionHandler ) {
470 wfDeprecated( '$wgSessionsHandler', '1.27' );
471 }
472 $cacheType = get_class( ObjectCache::getInstance( $wgSessionCacheType ) );
473 wfDebugLog(
474 'caches',
475 "Session data will be stored in \"$cacheType\" cache with " .
476 "expiry $wgObjectCacheSessionExpiry seconds"
477 );
478 }
479 $wgSessionsInObjectCache = true;
480
481 if ( $wgPHPSessionHandling !== 'enable' &&
482 $wgPHPSessionHandling !== 'warn' &&
483 $wgPHPSessionHandling !== 'disable'
484 ) {
485 $wgPHPSessionHandling = 'warn';
486 }
487 if ( defined( 'MW_NO_SESSION' ) ) {
488 // If the entry point wants no session, force 'disable' here unless they
489 // specifically set it to the (undocumented) 'warn'.
490 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
491 }
492
493 Profiler::instance()->scopedProfileOut( $ps_default );
494
495 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
496 // all the memory from logging SQL queries on maintenance scripts
497 global $wgCommandLineMode;
498 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
499 MWDebug::init();
500 }
501
502 // Reset the global service locator, so any services that have already been created will be
503 // re-created while taking into account any custom settings and extensions.
504 MediaWikiServices::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
505
506 if ( $wgSharedDB && $wgSharedTables ) {
507 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
508 MediaWikiServices::getInstance()->getDBLoadBalancer()->setTableAliases(
509 array_fill_keys(
510 $wgSharedTables,
511 [
512 'dbname' => $wgSharedDB,
513 'schema' => $wgSharedSchema,
514 'prefix' => $wgSharedPrefix
515 ]
516 )
517 );
518 }
519
520 // Define a constant that indicates that the bootstrapping of the service locator
521 // is complete.
522 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
523
524 // Install a header callback to prevent caching of responses with cookies (T127993)
525 if ( !$wgCommandLineMode ) {
526 header_register_callback( function () {
527 $headers = [];
528 foreach ( headers_list() as $header ) {
529 list( $name, $value ) = explode( ':', $header, 2 );
530 $headers[strtolower( trim( $name ) )][] = trim( $value );
531 }
532
533 if ( isset( $headers['set-cookie'] ) ) {
534 $cacheControl = isset( $headers['cache-control'] )
535 ? implode( ', ', $headers['cache-control'] )
536 : '';
537
538 if ( !preg_match( '/(?:^|,)\s*(?:private|no-cache|no-store)\s*(?:$|,)/i', $cacheControl ) ) {
539 header( 'Expires: Thu, 01 Jan 1970 00:00:00 GMT' );
540 header( 'Cache-Control: private, max-age=0, s-maxage=0' );
541 MediaWiki\Logger\LoggerFactory::getInstance( 'cache-cookies' )->warning(
542 'Cookies set on {url} with Cache-Control "{cache-control}"', [
543 'url' => WebRequest::getGlobalRequestURL(),
544 'cookies' => $headers['set-cookie'],
545 'cache-control' => $cacheControl ?: '<not set>',
546 ]
547 );
548 }
549 }
550 } );
551 }
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 $parserMemc = wfGetParserCacheStorage();
692
693 wfDebugLog( 'caches',
694 'cluster: ' . get_class( $wgMemc ) .
695 ', WAN: ' . ( $wgMainWANCache === CACHE_NONE ? 'CACHE_NONE' : $wgMainWANCache ) .
696 ', stash: ' . $wgMainStash .
697 ', message: ' . get_class( $messageMemc ) .
698 ', parser: ' . get_class( $parserMemc ) .
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 );