f9150548a3131842b1850188468da98ba3bf03d7
[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'] )
123 && 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 } else {
133 unset( $wgFooterIcons['copyright']['copyright'] );
134 }
135 }
136
137 if ( isset( $wgFooterIcons['poweredby'] )
138 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
139 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
140 ) {
141 $wgFooterIcons['poweredby']['mediawiki']['src'] =
142 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
143 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
144 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
145 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
146 }
147
148 /**
149 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
150 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
151 *
152 * Note that this is the definition of editinterface and it can be granted to
153 * all users if desired.
154 */
155 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
156
157 /**
158 * The canonical names of namespaces 6 and 7 are, as of v1.14, "File"
159 * and "File_talk". The old names "Image" and "Image_talk" are
160 * retained as aliases for backwards compatibility.
161 */
162 $wgNamespaceAliases['Image'] = NS_FILE;
163 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
164
165 /**
166 * Initialise $wgLockManagers to include basic FS version
167 */
168 $wgLockManagers[] = [
169 'name' => 'fsLockManager',
170 'class' => 'FSLockManager',
171 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
172 ];
173 $wgLockManagers[] = [
174 'name' => 'nullLockManager',
175 'class' => 'NullLockManager',
176 ];
177
178 /**
179 * Initialise $wgLocalFileRepo from backwards-compatible settings
180 */
181 if ( !$wgLocalFileRepo ) {
182 $wgLocalFileRepo = [
183 'class' => 'LocalRepo',
184 'name' => 'local',
185 'directory' => $wgUploadDirectory,
186 'scriptDirUrl' => $wgScriptPath,
187 'scriptExtension' => '.php',
188 'url' => $wgUploadBaseUrl ? $wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
189 'hashLevels' => $wgHashedUploadDirectory ? 2 : 0,
190 'thumbScriptUrl' => $wgThumbnailScriptPath,
191 'transformVia404' => !$wgGenerateThumbnailOnParse,
192 'deletedDir' => $wgDeletedDirectory,
193 'deletedHashLevels' => $wgHashedUploadDirectory ? 3 : 0
194 ];
195 }
196 /**
197 * Initialise shared repo from backwards-compatible settings
198 */
199 if ( $wgUseSharedUploads ) {
200 if ( $wgSharedUploadDBname ) {
201 $wgForeignFileRepos[] = [
202 'class' => 'ForeignDBRepo',
203 'name' => 'shared',
204 'directory' => $wgSharedUploadDirectory,
205 'url' => $wgSharedUploadPath,
206 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
207 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
208 'transformVia404' => !$wgGenerateThumbnailOnParse,
209 'dbType' => $wgDBtype,
210 'dbServer' => $wgDBserver,
211 'dbUser' => $wgDBuser,
212 'dbPassword' => $wgDBpassword,
213 'dbName' => $wgSharedUploadDBname,
214 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG : 0 ) | DBO_DEFAULT,
215 'tablePrefix' => $wgSharedUploadDBprefix,
216 'hasSharedCache' => $wgCacheSharedUploads,
217 'descBaseUrl' => $wgRepositoryBaseUrl,
218 'fetchDescription' => $wgFetchCommonsDescriptions,
219 ];
220 } else {
221 $wgForeignFileRepos[] = [
222 'class' => 'FileRepo',
223 'name' => 'shared',
224 'directory' => $wgSharedUploadDirectory,
225 'url' => $wgSharedUploadPath,
226 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
227 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
228 'transformVia404' => !$wgGenerateThumbnailOnParse,
229 'descBaseUrl' => $wgRepositoryBaseUrl,
230 'fetchDescription' => $wgFetchCommonsDescriptions,
231 ];
232 }
233 }
234 if ( $wgUseInstantCommons ) {
235 $wgForeignFileRepos[] = [
236 'class' => 'ForeignAPIRepo',
237 'name' => 'wikimediacommons',
238 'apibase' => 'https://commons.wikimedia.org/w/api.php',
239 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
240 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
241 'hashLevels' => 2,
242 'transformVia404' => true,
243 'fetchDescription' => true,
244 'descriptionCacheExpiry' => 43200,
245 'apiThumbCacheExpiry' => 86400,
246 ];
247 }
248 /*
249 * Add on default file backend config for file repos.
250 * FileBackendGroup will handle initializing the backends.
251 */
252 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
253 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
254 }
255 foreach ( $wgForeignFileRepos as &$repo ) {
256 if ( !isset( $repo['directory'] ) && $repo['class'] === 'ForeignAPIRepo' ) {
257 $repo['directory'] = $wgUploadDirectory; // b/c
258 }
259 if ( !isset( $repo['backend'] ) ) {
260 $repo['backend'] = $repo['name'] . '-backend';
261 }
262 }
263 unset( $repo ); // no global pollution; destroy reference
264
265 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
266 if ( $wgRCFilterByAge ) {
267 // Trim down $wgRCLinkDays so that it only lists links which are valid
268 // as determined by $wgRCMaxAge.
269 // Note that we allow 1 link higher than the max for things like 56 days but a 60 day link.
270 sort( $wgRCLinkDays );
271
272 // @codingStandardsIgnoreStart Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
273 for ( $i = 0; $i < count( $wgRCLinkDays ); $i++ ) {
274 // @codingStandardsIgnoreEnd
275 if ( $wgRCLinkDays[$i] >= $rcMaxAgeDays ) {
276 $wgRCLinkDays = array_slice( $wgRCLinkDays, 0, $i + 1, false );
277 break;
278 }
279 }
280 }
281 // Ensure that default user options are not invalid, since that breaks Special:Preferences
282 $wgDefaultUserOptions['rcdays'] = min(
283 $wgDefaultUserOptions['rcdays'],
284 ceil( $rcMaxAgeDays )
285 );
286 $wgDefaultUserOptions['watchlistdays'] = min(
287 $wgDefaultUserOptions['watchlistdays'],
288 ceil( $rcMaxAgeDays )
289 );
290 unset( $rcMaxAgeDays );
291
292 if ( $wgSkipSkin ) {
293 $wgSkipSkins[] = $wgSkipSkin;
294 }
295
296 // Register skins
297 // Use a closure to avoid leaking into global state
298 call_user_func( function () use ( $wgValidSkinNames ) {
299 $factory = SkinFactory::getDefaultInstance();
300 foreach ( $wgValidSkinNames as $name => $skin ) {
301 $factory->register( $name, $skin, function () use ( $name, $skin ) {
302 $class = "Skin$skin";
303 return new $class( $name );
304 } );
305 }
306 // Register a hidden "fallback" skin
307 $factory->register( 'fallback', 'Fallback', function () {
308 return new SkinFallback;
309 } );
310 // Register a hidden skin for api output
311 $factory->register( 'apioutput', 'ApiOutput', function () {
312 return new SkinApi;
313 } );
314 } );
315 $wgSkipSkins[] = 'fallback';
316 $wgSkipSkins[] = 'apioutput';
317
318 if ( $wgLocalInterwiki ) {
319 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
320 }
321
322 // Set default shared prefix
323 if ( $wgSharedPrefix === false ) {
324 $wgSharedPrefix = $wgDBprefix;
325 }
326
327 // Set default shared schema
328 if ( $wgSharedSchema === false ) {
329 $wgSharedSchema = $wgDBmwschema;
330 }
331
332 if ( !$wgCookiePrefix ) {
333 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
334 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
335 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
336 $wgCookiePrefix = $wgSharedDB;
337 } elseif ( $wgDBprefix ) {
338 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
339 } else {
340 $wgCookiePrefix = $wgDBname;
341 }
342 }
343 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
344
345 if ( $wgEnableEmail ) {
346 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
347 } else {
348 // Disable all other email settings automatically if $wgEnableEmail
349 // is set to false. - bug 63678
350 $wgAllowHTMLEmail = false;
351 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
352 $wgEnableUserEmail = false;
353 $wgEnotifFromEditor = false;
354 $wgEnotifImpersonal = false;
355 $wgEnotifMaxRecips = 0;
356 $wgEnotifMinorEdits = false;
357 $wgEnotifRevealEditorAddress = false;
358 $wgEnotifUseRealName = false;
359 $wgEnotifUserTalk = false;
360 $wgEnotifWatchlist = false;
361 unset( $wgGroupPermissions['user']['sendemail'] );
362 $wgUseEnotif = false;
363 $wgUserEmailUseReplyTo = false;
364 $wgUsersNotifiedOnAllChanges = [];
365 }
366
367 // Doesn't make sense to have if disabled.
368 if ( !$wgEnotifMinorEdits ) {
369 $wgHiddenPrefs[] = 'enotifminoredits';
370 }
371
372 if ( $wgMetaNamespace === false ) {
373 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
374 }
375
376 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
377 if ( $wgResourceLoaderMaxQueryLength === false ) {
378 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
379 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
380 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
381 } else {
382 $wgResourceLoaderMaxQueryLength = 2000;
383 }
384 unset( $suhosinMaxValueLength );
385 }
386
387 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
388 // upload size.
389 $wgMinUploadChunkSize = min(
390 $wgMinUploadChunkSize,
391 UploadBase::getMaxUploadSize( 'file' ),
392 UploadBase::getMaxPhpUploadSize(),
393 ( wfShorthandToInteger(
394 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
395 PHP_INT_MAX
396 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
397 );
398
399 /**
400 * Definitions of the NS_ constants are in Defines.php
401 * @private
402 */
403 $wgCanonicalNamespaceNames = [
404 NS_MEDIA => 'Media',
405 NS_SPECIAL => 'Special',
406 NS_TALK => 'Talk',
407 NS_USER => 'User',
408 NS_USER_TALK => 'User_talk',
409 NS_PROJECT => 'Project',
410 NS_PROJECT_TALK => 'Project_talk',
411 NS_FILE => 'File',
412 NS_FILE_TALK => 'File_talk',
413 NS_MEDIAWIKI => 'MediaWiki',
414 NS_MEDIAWIKI_TALK => 'MediaWiki_talk',
415 NS_TEMPLATE => 'Template',
416 NS_TEMPLATE_TALK => 'Template_talk',
417 NS_HELP => 'Help',
418 NS_HELP_TALK => 'Help_talk',
419 NS_CATEGORY => 'Category',
420 NS_CATEGORY_TALK => 'Category_talk',
421 ];
422
423 /// @todo UGLY UGLY
424 if ( is_array( $wgExtraNamespaces ) ) {
425 $wgCanonicalNamespaceNames = $wgCanonicalNamespaceNames + $wgExtraNamespaces;
426 }
427
428 // These are now the same, always
429 // To determine the user language, use $wgLang->getCode()
430 $wgContLanguageCode = $wgLanguageCode;
431
432 // Easy to forget to falsify $wgDebugToolbar for static caches.
433 // If file cache or CDN cache is on, just disable this (DWIMD).
434 if ( $wgUseFileCache || $wgUseSquid ) {
435 $wgDebugToolbar = false;
436 }
437
438 // We always output HTML5 since 1.22, overriding these is no longer supported
439 // we set them here for extensions that depend on its value.
440 $wgHtml5 = true;
441 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
442 $wgJsMimeType = 'text/javascript';
443
444 // Blacklisted file extensions shouldn't appear on the "allowed" list
445 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
446
447 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
448 MediaWiki\suppressWarnings();
449 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
450 MediaWiki\restoreWarnings();
451 }
452
453 if ( $wgNewUserLog ) {
454 // Add a new log type
455 $wgLogTypes[] = 'newusers';
456 $wgLogNames['newusers'] = 'newuserlogpage';
457 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
458 $wgLogActionsHandlers['newusers/newusers'] = 'NewUsersLogFormatter';
459 $wgLogActionsHandlers['newusers/create'] = 'NewUsersLogFormatter';
460 $wgLogActionsHandlers['newusers/create2'] = 'NewUsersLogFormatter';
461 $wgLogActionsHandlers['newusers/byemail'] = 'NewUsersLogFormatter';
462 $wgLogActionsHandlers['newusers/autocreate'] = 'NewUsersLogFormatter';
463 }
464
465 if ( $wgPageLanguageUseDB ) {
466 $wgLogTypes[] = 'pagelang';
467 $wgLogActionsHandlers['pagelang/pagelang'] = 'PageLangLogFormatter';
468 }
469
470 if ( $wgCookieSecure === 'detect' ) {
471 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
472 }
473
474 if ( $wgProfileOnly ) {
475 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
476 $wgDebugLogFile = '';
477 }
478
479 // Backwards compatibility with old password limits
480 if ( $wgMinimalPasswordLength !== false ) {
481 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
482 }
483
484 if ( $wgMaximalPasswordLength !== false ) {
485 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
486 }
487
488 // Backwards compatibility warning
489 if ( !$wgSessionsInObjectCache && !$wgSessionsInMemcached ) {
490 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
491 if ( $wgSessionHandler ) {
492 wfDeprecated( '$wgSessionsHandler', '1.27' );
493 }
494 $cacheType = get_class( ObjectCache::getInstance( $wgSessionCacheType ) );
495 wfDebugLog(
496 'caches',
497 "Session data will be stored in \"$cacheType\" cache with " .
498 "expiry $wgObjectCacheSessionExpiry seconds"
499 );
500 }
501 $wgSessionsInObjectCache = true;
502
503 if ( $wgPHPSessionHandling !== 'enable' &&
504 $wgPHPSessionHandling !== 'warn' &&
505 $wgPHPSessionHandling !== 'disable'
506 ) {
507 $wgPHPSessionHandling = 'warn';
508 }
509 if ( defined( 'MW_NO_SESSION' ) ) {
510 // If the entry point wants no session, force 'disable' here unless they
511 // specifically set it to the (undocumented) 'warn'.
512 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
513 }
514
515 Profiler::instance()->scopedProfileOut( $ps_default );
516
517 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
518 // all the memory from logging SQL queries on maintenance scripts
519 global $wgCommandLineMode;
520 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
521 MWDebug::init();
522 }
523
524 if ( !class_exists( 'AutoLoader' ) ) {
525 require_once "$IP/includes/AutoLoader.php";
526 }
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 'pool' => 'mediawiki-main-default',
632 'relayerConfig' => [ 'class' => 'EventRelayerNull' ]
633 ];
634 }
635
636 Profiler::instance()->scopedProfileOut( $ps_default2 );
637
638 $ps_misc = Profiler::instance()->scopedProfileIn( $fname . '-misc1' );
639
640 // Raise the memory limit if it's too low
641 wfMemoryLimit();
642
643 /**
644 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
645 * that happens whenever you use a date function without the timezone being
646 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
647 */
648 if ( is_null( $wgLocaltimezone ) ) {
649 MediaWiki\suppressWarnings();
650 $wgLocaltimezone = date_default_timezone_get();
651 MediaWiki\restoreWarnings();
652 }
653
654 date_default_timezone_set( $wgLocaltimezone );
655 if ( is_null( $wgLocalTZoffset ) ) {
656 $wgLocalTZoffset = date( 'Z' ) / 60;
657 }
658
659 if ( !$wgDBerrorLogTZ ) {
660 $wgDBerrorLogTZ = $wgLocaltimezone;
661 }
662
663 // initialize the request object in $wgRequest
664 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
665
666 // Useful debug output
667 if ( $wgCommandLineMode ) {
668 wfDebug( "\n\nStart command line script $self\n" );
669 } else {
670 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
671
672 if ( $wgDebugPrintHttpHeaders ) {
673 $debug .= "HTTP HEADERS:\n";
674
675 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
676 $debug .= "$name: $value\n";
677 }
678 }
679 wfDebug( $debug );
680 }
681
682 Profiler::instance()->scopedProfileOut( $ps_misc );
683 $ps_memcached = Profiler::instance()->scopedProfileIn( $fname . '-memcached' );
684
685 $wgMemc = wfGetMainCache();
686 $messageMemc = wfGetMessageCacheStorage();
687 $parserMemc = wfGetParserCacheStorage();
688
689 wfDebugLog( 'caches',
690 'cluster: ' . get_class( $wgMemc ) .
691 ', WAN: ' . $wgMainWANCache .
692 ', stash: ' . $wgMainStash .
693 ', message: ' . get_class( $messageMemc ) .
694 ', parser: ' . get_class( $parserMemc ) );
695
696 Profiler::instance()->scopedProfileOut( $ps_memcached );
697
698 // Most of the config is out, some might want to run hooks here.
699 Hooks::run( 'SetupAfterCache' );
700
701 $ps_globals = Profiler::instance()->scopedProfileIn( $fname . '-globals' );
702
703 /**
704 * @var Language $wgContLang
705 */
706 $wgContLang = Language::factory( $wgLanguageCode );
707 $wgContLang->initEncoding();
708 $wgContLang->initContLang();
709
710 // Now that variant lists may be available...
711 $wgRequest->interpolateTitle();
712
713 if ( !is_object( $wgAuth ) ) {
714 $wgAuth = new AuthPlugin;
715 Hooks::run( 'AuthPluginSetup', [ &$wgAuth ] );
716 }
717
718 // Set up the session
719 $ps_session = Profiler::instance()->scopedProfileIn( $fname . '-session' );
720 /**
721 * @var MediaWiki\\Session\\SessionId|null $wgInitialSessionId The persistent
722 * session ID (if any) loaded at startup
723 */
724 $wgInitialSessionId = null;
725 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
726 // If session.auto_start is there, we can't touch session name
727 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
728 session_name( $wgSessionName ? $wgSessionName : $wgCookiePrefix . '_session' );
729 }
730
731 // Create the SessionManager singleton and set up our session handler,
732 // unless we're specifically asked not to.
733 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
734 MediaWiki\Session\PHPSessionHandler::install(
735 MediaWiki\Session\SessionManager::singleton()
736 );
737 }
738
739 // Initialize the session
740 try {
741 $session = MediaWiki\Session\SessionManager::getGlobalSession();
742 } catch ( OverflowException $ex ) {
743 if ( isset( $ex->sessionInfos ) && count( $ex->sessionInfos ) >= 2 ) {
744 // The exception is because the request had multiple possible
745 // sessions tied for top priority. Report this to the user.
746 $list = [];
747 foreach ( $ex->sessionInfos as $info ) {
748 $list[] = $info->getProvider()->describe( $wgContLang );
749 }
750 $list = $wgContLang->listToText( $list );
751 throw new HttpError( 400,
752 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
753 );
754 }
755
756 // Not the one we want, rethrow
757 throw $ex;
758 }
759
760 if ( $session->isPersistent() ) {
761 $wgInitialSessionId = $session->getSessionId();
762 }
763
764 $session->renew();
765 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
766 ( $session->isPersistent() || $session->shouldRememberUser() )
767 ) {
768 // Start the PHP-session for backwards compatibility
769 session_id( $session->getId() );
770 MediaWiki\quietCall( 'session_start' );
771 }
772
773 unset( $session );
774 } else {
775 // Even if we didn't set up a global Session, still install our session
776 // handler unless specifically requested not to.
777 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
778 MediaWiki\Session\PHPSessionHandler::install(
779 MediaWiki\Session\SessionManager::singleton()
780 );
781 }
782 }
783 Profiler::instance()->scopedProfileOut( $ps_session );
784
785 /**
786 * @var User $wgUser
787 */
788 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
789
790 /**
791 * @var Language $wgLang
792 */
793 $wgLang = new StubUserLang;
794
795 /**
796 * @var OutputPage $wgOut
797 */
798 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
799
800 /**
801 * @var Parser $wgParser
802 */
803 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], [ $wgParserConf ] );
804
805 /**
806 * @var Title $wgTitle
807 */
808 $wgTitle = null;
809
810 Profiler::instance()->scopedProfileOut( $ps_globals );
811 $ps_extensions = Profiler::instance()->scopedProfileIn( $fname . '-extensions' );
812
813 // Extension setup functions
814 // Entries should be added to this variable during the inclusion
815 // of the extension file. This allows the extension to perform
816 // any necessary initialisation in the fully initialised environment
817 foreach ( $wgExtensionFunctions as $func ) {
818 // Allow closures in PHP 5.3+
819 if ( is_object( $func ) && $func instanceof Closure ) {
820 $profName = $fname . '-extensions-closure';
821 } elseif ( is_array( $func ) ) {
822 if ( is_object( $func[0] ) ) {
823 $profName = $fname . '-extensions-' . get_class( $func[0] ) . '::' . $func[1];
824 } else {
825 $profName = $fname . '-extensions-' . implode( '::', $func );
826 }
827 } else {
828 $profName = $fname . '-extensions-' . strval( $func );
829 }
830
831 $ps_ext_func = Profiler::instance()->scopedProfileIn( $profName );
832 call_user_func( $func );
833 Profiler::instance()->scopedProfileOut( $ps_ext_func );
834 }
835
836 // If the session user has a 0 id but a valid name, that means we need to
837 // autocreate it.
838 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
839 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
840 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
841 $ps_autocreate = Profiler::instance()->scopedProfileIn( $fname . '-autocreate' );
842 MediaWiki\Session\SessionManager::autoCreateUser( $sessionUser );
843 Profiler::instance()->scopedProfileOut( $ps_autocreate );
844 }
845 unset( $sessionUser );
846 }
847
848 wfDebug( "Fully initialised\n" );
849 $wgFullyInitialised = true;
850
851 Profiler::instance()->scopedProfileOut( $ps_extensions );
852 Profiler::instance()->scopedProfileOut( $ps_setup );