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