Merge "Show absolute block expiry in user timezone on block logs"
[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
27 /**
28 * This file is not a valid entry point, perform no further processing unless
29 * MEDIAWIKI is defined
30 */
31 if ( !defined( 'MEDIAWIKI' ) ) {
32 exit( 1 );
33 }
34
35 $fname = 'Setup.php';
36 $ps_setup = Profiler::instance()->scopedProfileIn( $fname );
37
38 // If any extensions are still queued, force load them
39 ExtensionRegistry::getInstance()->loadFromQueue();
40
41 // Check to see if we are at the file scope
42 if ( !isset( $wgVersion ) ) {
43 echo "Error, Setup.php must be included from the file scope, after DefaultSettings.php\n";
44 die( 1 );
45 }
46
47 // Set various default paths sensibly...
48 $ps_default = Profiler::instance()->scopedProfileIn( $fname . '-defaults' );
49
50 if ( $wgScript === false ) {
51 $wgScript = "$wgScriptPath/index.php";
52 }
53 if ( $wgLoadScript === false ) {
54 $wgLoadScript = "$wgScriptPath/load.php";
55 }
56
57 if ( $wgArticlePath === false ) {
58 if ( $wgUsePathInfo ) {
59 $wgArticlePath = "$wgScript/$1";
60 } else {
61 $wgArticlePath = "$wgScript?title=$1";
62 }
63 }
64
65 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
66 // 'view' is assumed the default action path everywhere in the code
67 // but is rarely filled in $wgActionPaths
68 $wgActionPaths['view'] = $wgArticlePath;
69 }
70
71 if ( $wgResourceBasePath === null ) {
72 $wgResourceBasePath = $wgScriptPath;
73 }
74 if ( $wgStylePath === false ) {
75 $wgStylePath = "$wgResourceBasePath/skins";
76 }
77 if ( $wgLocalStylePath === false ) {
78 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
79 $wgLocalStylePath = "$wgScriptPath/skins";
80 }
81 if ( $wgExtensionAssetsPath === false ) {
82 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
83 }
84
85 if ( $wgLogo === false ) {
86 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
87 }
88
89 if ( $wgUploadPath === false ) {
90 $wgUploadPath = "$wgScriptPath/images";
91 }
92 if ( $wgUploadDirectory === false ) {
93 $wgUploadDirectory = "$IP/images";
94 }
95 if ( $wgReadOnlyFile === false ) {
96 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
97 }
98 if ( $wgFileCacheDirectory === false ) {
99 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
100 }
101 if ( $wgDeletedDirectory === false ) {
102 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
103 }
104
105 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
106 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
107 }
108
109 if ( $wgEnableParserCache === false ) {
110 $wgParserCacheType = CACHE_NONE;
111 }
112
113 // Fix path to icon images after they were moved in 1.24
114 if ( $wgRightsIcon ) {
115 $wgRightsIcon = str_replace(
116 "{$wgStylePath}/common/images/",
117 "{$wgResourceBasePath}/resources/assets/licenses/",
118 $wgRightsIcon
119 );
120 }
121
122 if ( isset( $wgFooterIcons['copyright']['copyright'] )
123 && $wgFooterIcons['copyright']['copyright'] === []
124 ) {
125 if ( $wgRightsIcon || $wgRightsText ) {
126 $wgFooterIcons['copyright']['copyright'] = [
127 'url' => $wgRightsUrl,
128 'src' => $wgRightsIcon,
129 'alt' => $wgRightsText,
130 ];
131 }
132 }
133
134 if ( isset( $wgFooterIcons['poweredby'] )
135 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
136 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
137 ) {
138 $wgFooterIcons['poweredby']['mediawiki']['src'] =
139 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
140 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
141 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
142 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
143 }
144
145 /**
146 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
147 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
148 *
149 * Note that this is the definition of editinterface and it can be granted to
150 * all users if desired.
151 */
152 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
153
154 /**
155 * The canonical names of namespaces 6 and 7 are, as of v1.14, "File"
156 * and "File_talk". The old names "Image" and "Image_talk" are
157 * retained as aliases for backwards compatibility.
158 */
159 $wgNamespaceAliases['Image'] = NS_FILE;
160 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
161
162 /**
163 * Initialise $wgLockManagers to include basic FS version
164 */
165 $wgLockManagers[] = [
166 'name' => 'fsLockManager',
167 'class' => 'FSLockManager',
168 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
169 ];
170 $wgLockManagers[] = [
171 'name' => 'nullLockManager',
172 'class' => 'NullLockManager',
173 ];
174
175 /**
176 * Initialise $wgLocalFileRepo from backwards-compatible settings
177 */
178 if ( !$wgLocalFileRepo ) {
179 $wgLocalFileRepo = [
180 'class' => 'LocalRepo',
181 'name' => 'local',
182 'directory' => $wgUploadDirectory,
183 'scriptDirUrl' => $wgScriptPath,
184 'scriptExtension' => '.php',
185 'url' => $wgUploadBaseUrl ? $wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
186 'hashLevels' => $wgHashedUploadDirectory ? 2 : 0,
187 'thumbScriptUrl' => $wgThumbnailScriptPath,
188 'transformVia404' => !$wgGenerateThumbnailOnParse,
189 'deletedDir' => $wgDeletedDirectory,
190 'deletedHashLevels' => $wgHashedUploadDirectory ? 3 : 0
191 ];
192 }
193 /**
194 * Initialise shared repo from backwards-compatible settings
195 */
196 if ( $wgUseSharedUploads ) {
197 if ( $wgSharedUploadDBname ) {
198 $wgForeignFileRepos[] = [
199 'class' => 'ForeignDBRepo',
200 'name' => 'shared',
201 'directory' => $wgSharedUploadDirectory,
202 'url' => $wgSharedUploadPath,
203 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
204 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
205 'transformVia404' => !$wgGenerateThumbnailOnParse,
206 'dbType' => $wgDBtype,
207 'dbServer' => $wgDBserver,
208 'dbUser' => $wgDBuser,
209 'dbPassword' => $wgDBpassword,
210 'dbName' => $wgSharedUploadDBname,
211 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG : 0 ) | DBO_DEFAULT,
212 'tablePrefix' => $wgSharedUploadDBprefix,
213 'hasSharedCache' => $wgCacheSharedUploads,
214 'descBaseUrl' => $wgRepositoryBaseUrl,
215 'fetchDescription' => $wgFetchCommonsDescriptions,
216 ];
217 } else {
218 $wgForeignFileRepos[] = [
219 'class' => 'FileRepo',
220 'name' => 'shared',
221 'directory' => $wgSharedUploadDirectory,
222 'url' => $wgSharedUploadPath,
223 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
224 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
225 'transformVia404' => !$wgGenerateThumbnailOnParse,
226 'descBaseUrl' => $wgRepositoryBaseUrl,
227 'fetchDescription' => $wgFetchCommonsDescriptions,
228 ];
229 }
230 }
231 if ( $wgUseInstantCommons ) {
232 $wgForeignFileRepos[] = [
233 'class' => 'ForeignAPIRepo',
234 'name' => 'wikimediacommons',
235 'apibase' => 'https://commons.wikimedia.org/w/api.php',
236 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
237 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
238 'hashLevels' => 2,
239 'transformVia404' => true,
240 'fetchDescription' => true,
241 'descriptionCacheExpiry' => 43200,
242 'apiThumbCacheExpiry' => 86400,
243 ];
244 }
245 /*
246 * Add on default file backend config for file repos.
247 * FileBackendGroup will handle initializing the backends.
248 */
249 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
250 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
251 }
252 foreach ( $wgForeignFileRepos as &$repo ) {
253 if ( !isset( $repo['directory'] ) && $repo['class'] === 'ForeignAPIRepo' ) {
254 $repo['directory'] = $wgUploadDirectory; // b/c
255 }
256 if ( !isset( $repo['backend'] ) ) {
257 $repo['backend'] = $repo['name'] . '-backend';
258 }
259 }
260 unset( $repo ); // no global pollution; destroy reference
261
262 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
263 if ( $wgRCFilterByAge ) {
264 // Trim down $wgRCLinkDays so that it only lists links which are valid
265 // as determined by $wgRCMaxAge.
266 // Note that we allow 1 link higher than the max for things like 56 days but a 60 day link.
267 sort( $wgRCLinkDays );
268
269 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
270 for ( $i = 0; $i < count( $wgRCLinkDays ); $i++ ) {
271 // @codingStandardsIgnoreEnd
272 if ( $wgRCLinkDays[$i] >= $rcMaxAgeDays ) {
273 $wgRCLinkDays = array_slice( $wgRCLinkDays, 0, $i + 1, false );
274 break;
275 }
276 }
277 }
278 // Ensure that default user options are not invalid, since that breaks Special:Preferences
279 $wgDefaultUserOptions['rcdays'] = min(
280 $wgDefaultUserOptions['rcdays'],
281 ceil( $rcMaxAgeDays )
282 );
283 $wgDefaultUserOptions['watchlistdays'] = min(
284 $wgDefaultUserOptions['watchlistdays'],
285 ceil( $rcMaxAgeDays )
286 );
287 unset( $rcMaxAgeDays );
288
289 if ( $wgSkipSkin ) {
290 $wgSkipSkins[] = $wgSkipSkin;
291 }
292
293 // Register skins
294 // Use a closure to avoid leaking into global state
295 call_user_func( function () use ( $wgValidSkinNames ) {
296 $factory = SkinFactory::getDefaultInstance();
297 foreach ( $wgValidSkinNames as $name => $skin ) {
298 $factory->register( $name, $skin, function () use ( $name, $skin ) {
299 $class = "Skin$skin";
300 return new $class( $name );
301 } );
302 }
303 // Register a hidden "fallback" skin
304 $factory->register( 'fallback', 'Fallback', function () {
305 return new SkinFallback;
306 } );
307 // Register a hidden skin for api output
308 $factory->register( 'apioutput', 'ApiOutput', function () {
309 return new SkinApi;
310 } );
311 } );
312 $wgSkipSkins[] = 'fallback';
313 $wgSkipSkins[] = 'apioutput';
314
315 if ( $wgLocalInterwiki ) {
316 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
317 }
318
319 // Set default shared prefix
320 if ( $wgSharedPrefix === false ) {
321 $wgSharedPrefix = $wgDBprefix;
322 }
323
324 // Set default shared schema
325 if ( $wgSharedSchema === false ) {
326 $wgSharedSchema = $wgDBmwschema;
327 }
328
329 if ( !$wgCookiePrefix ) {
330 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
331 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
332 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
333 $wgCookiePrefix = $wgSharedDB;
334 } elseif ( $wgDBprefix ) {
335 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
336 } else {
337 $wgCookiePrefix = $wgDBname;
338 }
339 }
340 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
341
342 if ( $wgEnableEmail ) {
343 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
344 } else {
345 // Disable all other email settings automatically if $wgEnableEmail
346 // is set to false. - bug 63678
347 $wgAllowHTMLEmail = false;
348 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
349 $wgEnableUserEmail = false;
350 $wgEnotifFromEditor = false;
351 $wgEnotifImpersonal = false;
352 $wgEnotifMaxRecips = 0;
353 $wgEnotifMinorEdits = false;
354 $wgEnotifRevealEditorAddress = false;
355 $wgEnotifUseRealName = false;
356 $wgEnotifUserTalk = false;
357 $wgEnotifWatchlist = false;
358 unset( $wgGroupPermissions['user']['sendemail'] );
359 $wgUseEnotif = false;
360 $wgUserEmailUseReplyTo = false;
361 $wgUsersNotifiedOnAllChanges = [];
362 }
363
364 // Doesn't make sense to have if disabled.
365 if ( !$wgEnotifMinorEdits ) {
366 $wgHiddenPrefs[] = 'enotifminoredits';
367 }
368
369 if ( $wgMetaNamespace === false ) {
370 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
371 }
372
373 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
374 if ( $wgResourceLoaderMaxQueryLength === false ) {
375 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
376 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
377 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
378 } else {
379 $wgResourceLoaderMaxQueryLength = 2000;
380 }
381 unset( $suhosinMaxValueLength );
382 }
383
384 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
385 // upload size.
386 $wgMinUploadChunkSize = min(
387 $wgMinUploadChunkSize,
388 UploadBase::getMaxUploadSize( 'file' ),
389 UploadBase::getMaxPhpUploadSize(),
390 ( wfShorthandToInteger(
391 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
392 PHP_INT_MAX
393 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
394 );
395
396 /**
397 * Definitions of the NS_ constants are in Defines.php
398 * @private
399 */
400 $wgCanonicalNamespaceNames = [
401 NS_MEDIA => 'Media',
402 NS_SPECIAL => 'Special',
403 NS_TALK => 'Talk',
404 NS_USER => 'User',
405 NS_USER_TALK => 'User_talk',
406 NS_PROJECT => 'Project',
407 NS_PROJECT_TALK => 'Project_talk',
408 NS_FILE => 'File',
409 NS_FILE_TALK => 'File_talk',
410 NS_MEDIAWIKI => 'MediaWiki',
411 NS_MEDIAWIKI_TALK => 'MediaWiki_talk',
412 NS_TEMPLATE => 'Template',
413 NS_TEMPLATE_TALK => 'Template_talk',
414 NS_HELP => 'Help',
415 NS_HELP_TALK => 'Help_talk',
416 NS_CATEGORY => 'Category',
417 NS_CATEGORY_TALK => 'Category_talk',
418 ];
419
420 /// @todo UGLY UGLY
421 if ( is_array( $wgExtraNamespaces ) ) {
422 $wgCanonicalNamespaceNames = $wgCanonicalNamespaceNames + $wgExtraNamespaces;
423 }
424
425 // These are now the same, always
426 // To determine the user language, use $wgLang->getCode()
427 $wgContLanguageCode = $wgLanguageCode;
428
429 // Easy to forget to falsify $wgDebugToolbar for static caches.
430 // If file cache or CDN cache is on, just disable this (DWIMD).
431 if ( $wgUseFileCache || $wgUseSquid ) {
432 $wgDebugToolbar = false;
433 }
434
435 // We always output HTML5 since 1.22, overriding these is no longer supported
436 // we set them here for extensions that depend on its value.
437 $wgHtml5 = true;
438 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
439 $wgJsMimeType = 'text/javascript';
440
441 // Blacklisted file extensions shouldn't appear on the "allowed" list
442 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
443
444 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
445 MediaWiki\suppressWarnings();
446 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
447 MediaWiki\restoreWarnings();
448 }
449
450 if ( $wgNewUserLog ) {
451 // Add a new log type
452 $wgLogTypes[] = 'newusers';
453 $wgLogNames['newusers'] = 'newuserlogpage';
454 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
455 $wgLogActionsHandlers['newusers/newusers'] = 'NewUsersLogFormatter';
456 $wgLogActionsHandlers['newusers/create'] = 'NewUsersLogFormatter';
457 $wgLogActionsHandlers['newusers/create2'] = 'NewUsersLogFormatter';
458 $wgLogActionsHandlers['newusers/byemail'] = 'NewUsersLogFormatter';
459 $wgLogActionsHandlers['newusers/autocreate'] = 'NewUsersLogFormatter';
460 }
461
462 if ( $wgPageLanguageUseDB ) {
463 $wgLogTypes[] = 'pagelang';
464 $wgLogActionsHandlers['pagelang/pagelang'] = 'PageLangLogFormatter';
465 }
466
467 if ( $wgCookieSecure === 'detect' ) {
468 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
469 }
470
471 if ( $wgProfileOnly ) {
472 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
473 $wgDebugLogFile = '';
474 }
475
476 // Backwards compatibility with old password limits
477 if ( $wgMinimalPasswordLength !== false ) {
478 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
479 }
480
481 if ( $wgMaximalPasswordLength !== false ) {
482 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
483 }
484
485 // Backwards compatibility warning
486 if ( !$wgSessionsInObjectCache && !$wgSessionsInMemcached ) {
487 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
488 if ( $wgSessionHandler ) {
489 wfDeprecated( '$wgSessionsHandler', '1.27' );
490 }
491 $cacheType = get_class( ObjectCache::getInstance( $wgSessionCacheType ) );
492 wfDebugLog(
493 'caches',
494 "Session data will be stored in \"$cacheType\" cache with " .
495 "expiry $wgObjectCacheSessionExpiry seconds"
496 );
497 }
498 $wgSessionsInObjectCache = true;
499
500 if ( $wgPHPSessionHandling !== 'enable' &&
501 $wgPHPSessionHandling !== 'warn' &&
502 $wgPHPSessionHandling !== 'disable'
503 ) {
504 $wgPHPSessionHandling = 'warn';
505 }
506 if ( defined( 'MW_NO_SESSION' ) ) {
507 // If the entry point wants no session, force 'disable' here unless they
508 // specifically set it to the (undocumented) 'warn'.
509 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
510 }
511
512 Profiler::instance()->scopedProfileOut( $ps_default );
513
514 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
515 // all the memory from logging SQL queries on maintenance scripts
516 global $wgCommandLineMode;
517 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
518 MWDebug::init();
519 }
520
521 if ( !class_exists( 'AutoLoader' ) ) {
522 require_once "$IP/includes/AutoLoader.php";
523 }
524
525 // Install a header callback to prevent caching of responses with cookies (T127993)
526 if ( !$wgCommandLineMode ) {
527 header_register_callback( function () {
528 $headers = [];
529 foreach ( headers_list() as $header ) {
530 list( $name, $value ) = explode( ':', $header, 2 );
531 $headers[strtolower( trim( $name ) )][] = trim( $value );
532 }
533
534 if ( isset( $headers['set-cookie'] ) ) {
535 $cacheControl = isset( $headers['cache-control'] )
536 ? implode( ', ', $headers['cache-control'] )
537 : '';
538
539 if ( !preg_match( '/(?:^|,)\s*(?:private|no-cache|no-store)\s*(?:$|,)/i', $cacheControl ) ) {
540 header( 'Expires: Thu, 01 Jan 1970 00:00:00 GMT' );
541 header( 'Cache-Control: private, max-age=0, s-maxage=0' );
542 MediaWiki\Logger\LoggerFactory::getInstance( 'cache-cookies' )->warning(
543 'Cookies set on {url} with Cache-Control "{cache-control}"', [
544 'url' => WebRequest::getGlobalRequestURL(),
545 'cookies' => $headers['set-cookie'],
546 'cache-control' => $cacheControl ?: '<not set>',
547 ]
548 );
549 }
550 }
551 } );
552 }
553
554 MWExceptionHandler::installHandler();
555
556 require_once "$IP/includes/compat/normal/UtfNormalUtil.php";
557
558 $ps_validation = Profiler::instance()->scopedProfileIn( $fname . '-validation' );
559
560 // T48998: Bail out early if $wgArticlePath is non-absolute
561 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
562 if ( $$varName && !preg_match( '/^(https?:\/\/|\/)/', $$varName ) ) {
563 throw new FatalError(
564 "If you use a relative URL for \$$varName, it must start " .
565 'with a slash (<code>/</code>).<br><br>See ' .
566 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
567 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
568 );
569 }
570 }
571
572 Profiler::instance()->scopedProfileOut( $ps_validation );
573
574 $ps_default2 = Profiler::instance()->scopedProfileIn( $fname . '-defaults2' );
575
576 if ( $wgCanonicalServer === false ) {
577 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP );
578 }
579
580 // Set server name
581 $serverParts = wfParseUrl( $wgCanonicalServer );
582 if ( $wgServerName !== false ) {
583 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
584 . 'not customized. Overwriting $wgServerName.' );
585 }
586 $wgServerName = $serverParts['host'];
587 unset( $serverParts );
588
589 // Set defaults for configuration variables
590 // that are derived from the server name by default
591 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
592 if ( !$wgEmergencyContact ) {
593 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
594 }
595 if ( !$wgPasswordSender ) {
596 $wgPasswordSender = 'apache@' . $wgServerName;
597 }
598 if ( !$wgNoReplyAddress ) {
599 $wgNoReplyAddress = $wgPasswordSender;
600 }
601
602 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
603 $wgSecureLogin = false;
604 wfWarn( 'Secure login was enabled on a server that only supports '
605 . 'HTTP or HTTPS. Disabling secure login.' );
606 }
607
608 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
609
610 // Now that GlobalFunctions is loaded, set defaults that depend on it.
611 if ( $wgTmpDirectory === false ) {
612 $wgTmpDirectory = wfTempDir();
613 }
614
615 // We don't use counters anymore. Left here for extensions still
616 // expecting this to exist. Should be removed sometime 1.26 or later.
617 if ( !isset( $wgDisableCounters ) ) {
618 $wgDisableCounters = true;
619 }
620
621 if ( $wgMainWANCache === false ) {
622 // Setup a WAN cache from $wgMainCacheType with no relayer.
623 // Sites using multiple datacenters can configure a relayer.
624 $wgMainWANCache = 'mediawiki-main-default';
625 $wgWANObjectCaches[$wgMainWANCache] = [
626 'class' => 'WANObjectCache',
627 'cacheId' => $wgMainCacheType,
628 'pool' => 'mediawiki-main-default',
629 'relayerConfig' => [ 'class' => 'EventRelayerNull' ]
630 ];
631 }
632
633 Profiler::instance()->scopedProfileOut( $ps_default2 );
634
635 $ps_misc = Profiler::instance()->scopedProfileIn( $fname . '-misc1' );
636
637 // Raise the memory limit if it's too low
638 wfMemoryLimit();
639
640 /**
641 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
642 * that happens whenever you use a date function without the timezone being
643 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
644 */
645 if ( is_null( $wgLocaltimezone ) ) {
646 MediaWiki\suppressWarnings();
647 $wgLocaltimezone = date_default_timezone_get();
648 MediaWiki\restoreWarnings();
649 }
650
651 date_default_timezone_set( $wgLocaltimezone );
652 if ( is_null( $wgLocalTZoffset ) ) {
653 $wgLocalTZoffset = date( 'Z' ) / 60;
654 }
655
656 if ( !$wgDBerrorLogTZ ) {
657 $wgDBerrorLogTZ = $wgLocaltimezone;
658 }
659
660 // initialize the request object in $wgRequest
661 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
662
663 // Useful debug output
664 if ( $wgCommandLineMode ) {
665 wfDebug( "\n\nStart command line script $self\n" );
666 } else {
667 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
668
669 if ( $wgDebugPrintHttpHeaders ) {
670 $debug .= "HTTP HEADERS:\n";
671
672 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
673 $debug .= "$name: $value\n";
674 }
675 }
676 wfDebug( $debug );
677 }
678
679 Profiler::instance()->scopedProfileOut( $ps_misc );
680 $ps_memcached = Profiler::instance()->scopedProfileIn( $fname . '-memcached' );
681
682 $wgMemc = wfGetMainCache();
683 $messageMemc = wfGetMessageCacheStorage();
684 $parserMemc = wfGetParserCacheStorage();
685
686 wfDebugLog( 'caches',
687 'cluster: ' . get_class( $wgMemc ) .
688 ', WAN: ' . $wgMainWANCache .
689 ', stash: ' . $wgMainStash .
690 ', message: ' . get_class( $messageMemc ) .
691 ', parser: ' . get_class( $parserMemc ) );
692
693 Profiler::instance()->scopedProfileOut( $ps_memcached );
694
695 // Most of the config is out, some might want to run hooks here.
696 Hooks::run( 'SetupAfterCache' );
697
698 $ps_globals = Profiler::instance()->scopedProfileIn( $fname . '-globals' );
699
700 /**
701 * @var Language $wgContLang
702 */
703 $wgContLang = Language::factory( $wgLanguageCode );
704 $wgContLang->initEncoding();
705 $wgContLang->initContLang();
706
707 // Now that variant lists may be available...
708 $wgRequest->interpolateTitle();
709
710 if ( !is_object( $wgAuth ) ) {
711 $wgAuth = new AuthPlugin;
712 Hooks::run( 'AuthPluginSetup', [ &$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', $wgParserConf['class'], [ $wgParserConf ] );
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 MediaWiki\Session\SessionManager::autoCreateUser( $sessionUser );
840 Profiler::instance()->scopedProfileOut( $ps_autocreate );
841 }
842 unset( $sessionUser );
843 }
844
845 wfDebug( "Fully initialised\n" );
846 $wgFullyInitialised = true;
847
848 Profiler::instance()->scopedProfileOut( $ps_extensions );
849 Profiler::instance()->scopedProfileOut( $ps_setup );