Merge "Add CollationFa"
[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 if ( !class_exists( 'AutoLoader' ) ) {
503 require_once "$IP/includes/AutoLoader.php";
504 }
505
506 // Reset the global service locator, so any services that have already been created will be
507 // re-created while taking into account any custom settings and extensions.
508 MediaWikiServices::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
509
510 if ( $wgSharedDB && $wgSharedTables ) {
511 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
512 MediaWikiServices::getInstance()->getDBLoadBalancer()->setTableAliases(
513 array_fill_keys(
514 $wgSharedTables,
515 [
516 'dbname' => $wgSharedDB,
517 'schema' => $wgSharedSchema,
518 'prefix' => $wgSharedPrefix
519 ]
520 )
521 );
522 }
523
524 // Define a constant that indicates that the bootstrapping of the service locator
525 // is complete.
526 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
527
528 // Install a header callback to prevent caching of responses with cookies (T127993)
529 if ( !$wgCommandLineMode ) {
530 header_register_callback( function () {
531 $headers = [];
532 foreach ( headers_list() as $header ) {
533 list( $name, $value ) = explode( ':', $header, 2 );
534 $headers[strtolower( trim( $name ) )][] = trim( $value );
535 }
536
537 if ( isset( $headers['set-cookie'] ) ) {
538 $cacheControl = isset( $headers['cache-control'] )
539 ? implode( ', ', $headers['cache-control'] )
540 : '';
541
542 if ( !preg_match( '/(?:^|,)\s*(?:private|no-cache|no-store)\s*(?:$|,)/i', $cacheControl ) ) {
543 header( 'Expires: Thu, 01 Jan 1970 00:00:00 GMT' );
544 header( 'Cache-Control: private, max-age=0, s-maxage=0' );
545 MediaWiki\Logger\LoggerFactory::getInstance( 'cache-cookies' )->warning(
546 'Cookies set on {url} with Cache-Control "{cache-control}"', [
547 'url' => WebRequest::getGlobalRequestURL(),
548 'cookies' => $headers['set-cookie'],
549 'cache-control' => $cacheControl ?: '<not set>',
550 ]
551 );
552 }
553 }
554 } );
555 }
556
557 MWExceptionHandler::installHandler();
558
559 require_once "$IP/includes/compat/normal/UtfNormalUtil.php";
560
561 $ps_validation = Profiler::instance()->scopedProfileIn( $fname . '-validation' );
562
563 // T48998: Bail out early if $wgArticlePath is non-absolute
564 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
565 if ( $$varName && !preg_match( '/^(https?:\/\/|\/)/', $$varName ) ) {
566 throw new FatalError(
567 "If you use a relative URL for \$$varName, it must start " .
568 'with a slash (<code>/</code>).<br><br>See ' .
569 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
570 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
571 );
572 }
573 }
574
575 Profiler::instance()->scopedProfileOut( $ps_validation );
576
577 $ps_default2 = Profiler::instance()->scopedProfileIn( $fname . '-defaults2' );
578
579 if ( $wgCanonicalServer === false ) {
580 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP );
581 }
582
583 // Set server name
584 $serverParts = wfParseUrl( $wgCanonicalServer );
585 if ( $wgServerName !== false ) {
586 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
587 . 'not customized. Overwriting $wgServerName.' );
588 }
589 $wgServerName = $serverParts['host'];
590 unset( $serverParts );
591
592 // Set defaults for configuration variables
593 // that are derived from the server name by default
594 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
595 if ( !$wgEmergencyContact ) {
596 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
597 }
598 if ( !$wgPasswordSender ) {
599 $wgPasswordSender = 'apache@' . $wgServerName;
600 }
601 if ( !$wgNoReplyAddress ) {
602 $wgNoReplyAddress = $wgPasswordSender;
603 }
604
605 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
606 $wgSecureLogin = false;
607 wfWarn( 'Secure login was enabled on a server that only supports '
608 . 'HTTP or HTTPS. Disabling secure login.' );
609 }
610
611 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
612
613 // Now that GlobalFunctions is loaded, set defaults that depend on it.
614 if ( $wgTmpDirectory === false ) {
615 $wgTmpDirectory = wfTempDir();
616 }
617
618 // We don't use counters anymore. Left here for extensions still
619 // expecting this to exist. Should be removed sometime 1.26 or later.
620 if ( !isset( $wgDisableCounters ) ) {
621 $wgDisableCounters = true;
622 }
623
624 if ( $wgMainWANCache === false ) {
625 // Setup a WAN cache from $wgMainCacheType with no relayer.
626 // Sites using multiple datacenters can configure a relayer.
627 $wgMainWANCache = 'mediawiki-main-default';
628 $wgWANObjectCaches[$wgMainWANCache] = [
629 'class' => 'WANObjectCache',
630 'cacheId' => $wgMainCacheType,
631 'channels' => [ 'purge' => 'wancache-main-default-purge' ]
632 ];
633 }
634
635 Profiler::instance()->scopedProfileOut( $ps_default2 );
636
637 $ps_misc = Profiler::instance()->scopedProfileIn( $fname . '-misc1' );
638
639 // Raise the memory limit if it's too low
640 wfMemoryLimit();
641
642 /**
643 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
644 * that happens whenever you use a date function without the timezone being
645 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
646 */
647 if ( is_null( $wgLocaltimezone ) ) {
648 MediaWiki\suppressWarnings();
649 $wgLocaltimezone = date_default_timezone_get();
650 MediaWiki\restoreWarnings();
651 }
652
653 date_default_timezone_set( $wgLocaltimezone );
654 if ( is_null( $wgLocalTZoffset ) ) {
655 $wgLocalTZoffset = date( 'Z' ) / 60;
656 }
657 // The part after the System| is ignored, but rest of MW fills it
658 // out as the local offset.
659 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
660
661 if ( !$wgDBerrorLogTZ ) {
662 $wgDBerrorLogTZ = $wgLocaltimezone;
663 }
664
665 // initialize the request object in $wgRequest
666 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
667 // Set user IP/agent information for causal consistency purposes
668 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
669 'IPAddress' => $wgRequest->getIP(),
670 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
671 'ChronologyProtection' => $wgRequest->getHeader( 'ChronologyProtection' )
672 ] );
673
674 // Useful debug output
675 if ( $wgCommandLineMode ) {
676 wfDebug( "\n\nStart command line script $self\n" );
677 } else {
678 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
679
680 if ( $wgDebugPrintHttpHeaders ) {
681 $debug .= "HTTP HEADERS:\n";
682
683 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
684 $debug .= "$name: $value\n";
685 }
686 }
687 wfDebug( $debug );
688 }
689
690 Profiler::instance()->scopedProfileOut( $ps_misc );
691 $ps_memcached = Profiler::instance()->scopedProfileIn( $fname . '-memcached' );
692
693 $wgMemc = wfGetMainCache();
694 $messageMemc = wfGetMessageCacheStorage();
695 $parserMemc = wfGetParserCacheStorage();
696
697 wfDebugLog( 'caches',
698 'cluster: ' . get_class( $wgMemc ) .
699 ', WAN: ' . ( $wgMainWANCache === CACHE_NONE ? 'CACHE_NONE' : $wgMainWANCache ) .
700 ', stash: ' . $wgMainStash .
701 ', message: ' . get_class( $messageMemc ) .
702 ', parser: ' . get_class( $parserMemc ) .
703 ', session: ' . get_class( ObjectCache::getInstance( $wgSessionCacheType ) )
704 );
705
706 Profiler::instance()->scopedProfileOut( $ps_memcached );
707
708 // Most of the config is out, some might want to run hooks here.
709 Hooks::run( 'SetupAfterCache' );
710
711 $ps_globals = Profiler::instance()->scopedProfileIn( $fname . '-globals' );
712
713 /**
714 * @var Language $wgContLang
715 */
716 $wgContLang = Language::factory( $wgLanguageCode );
717 $wgContLang->initContLang();
718
719 // Now that variant lists may be available...
720 $wgRequest->interpolateTitle();
721
722 if ( !is_object( $wgAuth ) ) {
723 $wgAuth = new MediaWiki\Auth\AuthManagerAuthPlugin;
724 Hooks::run( 'AuthPluginSetup', [ &$wgAuth ] );
725 }
726 if ( $wgAuth && !$wgAuth instanceof MediaWiki\Auth\AuthManagerAuthPlugin ) {
727 MediaWiki\Auth\AuthManager::singleton()->forcePrimaryAuthenticationProviders( [
728 new MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider( [
729 'authoritative' => false,
730 ] ),
731 new MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider( $wgAuth ),
732 new MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider( [
733 'authoritative' => true,
734 ] ),
735 ], '$wgAuth is ' . get_class( $wgAuth ) );
736 }
737
738 // Set up the session
739 $ps_session = Profiler::instance()->scopedProfileIn( $fname . '-session' );
740 /**
741 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
742 * session ID (if any) loaded at startup
743 */
744 $wgInitialSessionId = null;
745 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
746 // If session.auto_start is there, we can't touch session name
747 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
748 session_name( $wgSessionName ? $wgSessionName : $wgCookiePrefix . '_session' );
749 }
750
751 // Create the SessionManager singleton and set up our session handler,
752 // unless we're specifically asked not to.
753 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
754 MediaWiki\Session\PHPSessionHandler::install(
755 MediaWiki\Session\SessionManager::singleton()
756 );
757 }
758
759 // Initialize the session
760 try {
761 $session = MediaWiki\Session\SessionManager::getGlobalSession();
762 } catch ( OverflowException $ex ) {
763 if ( isset( $ex->sessionInfos ) && count( $ex->sessionInfos ) >= 2 ) {
764 // The exception is because the request had multiple possible
765 // sessions tied for top priority. Report this to the user.
766 $list = [];
767 foreach ( $ex->sessionInfos as $info ) {
768 $list[] = $info->getProvider()->describe( $wgContLang );
769 }
770 $list = $wgContLang->listToText( $list );
771 throw new HttpError( 400,
772 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
773 );
774 }
775
776 // Not the one we want, rethrow
777 throw $ex;
778 }
779
780 if ( $session->isPersistent() ) {
781 $wgInitialSessionId = $session->getSessionId();
782 }
783
784 $session->renew();
785 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
786 ( $session->isPersistent() || $session->shouldRememberUser() )
787 ) {
788 // Start the PHP-session for backwards compatibility
789 session_id( $session->getId() );
790 MediaWiki\quietCall( 'session_start' );
791 }
792
793 unset( $session );
794 } else {
795 // Even if we didn't set up a global Session, still install our session
796 // handler unless specifically requested not to.
797 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
798 MediaWiki\Session\PHPSessionHandler::install(
799 MediaWiki\Session\SessionManager::singleton()
800 );
801 }
802 }
803 Profiler::instance()->scopedProfileOut( $ps_session );
804
805 /**
806 * @var User $wgUser
807 */
808 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
809
810 /**
811 * @var Language $wgLang
812 */
813 $wgLang = new StubUserLang;
814
815 /**
816 * @var OutputPage $wgOut
817 */
818 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
819
820 /**
821 * @var Parser $wgParser
822 */
823 $wgParser = new StubObject( 'wgParser', function () {
824 return MediaWikiServices::getInstance()->getParser();
825 } );
826
827 /**
828 * @var Title $wgTitle
829 */
830 $wgTitle = null;
831
832 Profiler::instance()->scopedProfileOut( $ps_globals );
833 $ps_extensions = Profiler::instance()->scopedProfileIn( $fname . '-extensions' );
834
835 // Extension setup functions
836 // Entries should be added to this variable during the inclusion
837 // of the extension file. This allows the extension to perform
838 // any necessary initialisation in the fully initialised environment
839 foreach ( $wgExtensionFunctions as $func ) {
840 // Allow closures in PHP 5.3+
841 if ( is_object( $func ) && $func instanceof Closure ) {
842 $profName = $fname . '-extensions-closure';
843 } elseif ( is_array( $func ) ) {
844 if ( is_object( $func[0] ) ) {
845 $profName = $fname . '-extensions-' . get_class( $func[0] ) . '::' . $func[1];
846 } else {
847 $profName = $fname . '-extensions-' . implode( '::', $func );
848 }
849 } else {
850 $profName = $fname . '-extensions-' . strval( $func );
851 }
852
853 $ps_ext_func = Profiler::instance()->scopedProfileIn( $profName );
854 call_user_func( $func );
855 Profiler::instance()->scopedProfileOut( $ps_ext_func );
856 }
857
858 // If the session user has a 0 id but a valid name, that means we need to
859 // autocreate it.
860 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
861 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
862 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
863 $ps_autocreate = Profiler::instance()->scopedProfileIn( $fname . '-autocreate' );
864 $res = MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
865 $sessionUser,
866 MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
867 true
868 );
869 Profiler::instance()->scopedProfileOut( $ps_autocreate );
870 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Autocreation attempt', [
871 'event' => 'autocreate',
872 'status' => $res,
873 ] );
874 unset( $res );
875 }
876 unset( $sessionUser );
877 }
878
879 if ( !$wgCommandLineMode ) {
880 Pingback::schedulePingback();
881 }
882
883 wfDebug( "Fully initialised\n" );
884 $wgFullyInitialised = true;
885
886 Profiler::instance()->scopedProfileOut( $ps_extensions );
887 Profiler::instance()->scopedProfileOut( $ps_setup );