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