Allow reset of global services.
[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 // Register skins
295 // Use a closure to avoid leaking into global state
296 call_user_func( function () use ( $wgValidSkinNames ) {
297 $factory = SkinFactory::getDefaultInstance();
298 foreach ( $wgValidSkinNames as $name => $skin ) {
299 $factory->register( $name, $skin, function () use ( $name, $skin ) {
300 $class = "Skin$skin";
301 return new $class( $name );
302 } );
303 }
304 // Register a hidden "fallback" skin
305 $factory->register( 'fallback', 'Fallback', function () {
306 return new SkinFallback;
307 } );
308 // Register a hidden skin for api output
309 $factory->register( 'apioutput', 'ApiOutput', function () {
310 return new SkinApi;
311 } );
312 } );
313 $wgSkipSkins[] = 'fallback';
314 $wgSkipSkins[] = 'apioutput';
315
316 if ( $wgLocalInterwiki ) {
317 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
318 }
319
320 // Set default shared prefix
321 if ( $wgSharedPrefix === false ) {
322 $wgSharedPrefix = $wgDBprefix;
323 }
324
325 // Set default shared schema
326 if ( $wgSharedSchema === false ) {
327 $wgSharedSchema = $wgDBmwschema;
328 }
329
330 if ( !$wgCookiePrefix ) {
331 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
332 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
333 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
334 $wgCookiePrefix = $wgSharedDB;
335 } elseif ( $wgDBprefix ) {
336 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
337 } else {
338 $wgCookiePrefix = $wgDBname;
339 }
340 }
341 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
342
343 if ( $wgEnableEmail ) {
344 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
345 } else {
346 // Disable all other email settings automatically if $wgEnableEmail
347 // is set to false. - bug 63678
348 $wgAllowHTMLEmail = false;
349 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
350 $wgEnableUserEmail = false;
351 $wgEnotifFromEditor = false;
352 $wgEnotifImpersonal = false;
353 $wgEnotifMaxRecips = 0;
354 $wgEnotifMinorEdits = false;
355 $wgEnotifRevealEditorAddress = false;
356 $wgEnotifUseRealName = false;
357 $wgEnotifUserTalk = false;
358 $wgEnotifWatchlist = false;
359 unset( $wgGroupPermissions['user']['sendemail'] );
360 $wgUseEnotif = false;
361 $wgUserEmailUseReplyTo = false;
362 $wgUsersNotifiedOnAllChanges = [];
363 }
364
365 // Doesn't make sense to have if disabled.
366 if ( !$wgEnotifMinorEdits ) {
367 $wgHiddenPrefs[] = 'enotifminoredits';
368 }
369
370 if ( $wgMetaNamespace === false ) {
371 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
372 }
373
374 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
375 if ( $wgResourceLoaderMaxQueryLength === false ) {
376 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
377 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
378 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
379 } else {
380 $wgResourceLoaderMaxQueryLength = 2000;
381 }
382 unset( $suhosinMaxValueLength );
383 }
384
385 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
386 // upload size.
387 $wgMinUploadChunkSize = min(
388 $wgMinUploadChunkSize,
389 UploadBase::getMaxUploadSize( 'file' ),
390 UploadBase::getMaxPhpUploadSize(),
391 ( wfShorthandToInteger(
392 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
393 PHP_INT_MAX
394 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
395 );
396
397 /**
398 * Definitions of the NS_ constants are in Defines.php
399 * @private
400 */
401 $wgCanonicalNamespaceNames = [
402 NS_MEDIA => 'Media',
403 NS_SPECIAL => 'Special',
404 NS_TALK => 'Talk',
405 NS_USER => 'User',
406 NS_USER_TALK => 'User_talk',
407 NS_PROJECT => 'Project',
408 NS_PROJECT_TALK => 'Project_talk',
409 NS_FILE => 'File',
410 NS_FILE_TALK => 'File_talk',
411 NS_MEDIAWIKI => 'MediaWiki',
412 NS_MEDIAWIKI_TALK => 'MediaWiki_talk',
413 NS_TEMPLATE => 'Template',
414 NS_TEMPLATE_TALK => 'Template_talk',
415 NS_HELP => 'Help',
416 NS_HELP_TALK => 'Help_talk',
417 NS_CATEGORY => 'Category',
418 NS_CATEGORY_TALK => 'Category_talk',
419 ];
420
421 /// @todo UGLY UGLY
422 if ( is_array( $wgExtraNamespaces ) ) {
423 $wgCanonicalNamespaceNames = $wgCanonicalNamespaceNames + $wgExtraNamespaces;
424 }
425
426 // These are now the same, always
427 // To determine the user language, use $wgLang->getCode()
428 $wgContLanguageCode = $wgLanguageCode;
429
430 // Easy to forget to falsify $wgDebugToolbar for static caches.
431 // If file cache or CDN cache is on, just disable this (DWIMD).
432 if ( $wgUseFileCache || $wgUseSquid ) {
433 $wgDebugToolbar = false;
434 }
435
436 // We always output HTML5 since 1.22, overriding these is no longer supported
437 // we set them here for extensions that depend on its value.
438 $wgHtml5 = true;
439 $wgXhtmlDefaultNamespace = 'http://www.w3.org/1999/xhtml';
440 $wgJsMimeType = 'text/javascript';
441
442 // Blacklisted file extensions shouldn't appear on the "allowed" list
443 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
444
445 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
446 MediaWiki\suppressWarnings();
447 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
448 MediaWiki\restoreWarnings();
449 }
450
451 if ( $wgNewUserLog ) {
452 // Add a new log type
453 $wgLogTypes[] = 'newusers';
454 $wgLogNames['newusers'] = 'newuserlogpage';
455 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
456 $wgLogActionsHandlers['newusers/newusers'] = 'NewUsersLogFormatter';
457 $wgLogActionsHandlers['newusers/create'] = 'NewUsersLogFormatter';
458 $wgLogActionsHandlers['newusers/create2'] = 'NewUsersLogFormatter';
459 $wgLogActionsHandlers['newusers/byemail'] = 'NewUsersLogFormatter';
460 $wgLogActionsHandlers['newusers/autocreate'] = 'NewUsersLogFormatter';
461 }
462
463 if ( $wgPageLanguageUseDB ) {
464 $wgLogTypes[] = 'pagelang';
465 $wgLogActionsHandlers['pagelang/pagelang'] = 'PageLangLogFormatter';
466 }
467
468 if ( $wgCookieSecure === 'detect' ) {
469 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
470 }
471
472 if ( $wgProfileOnly ) {
473 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
474 $wgDebugLogFile = '';
475 }
476
477 // Backwards compatibility with old password limits
478 if ( $wgMinimalPasswordLength !== false ) {
479 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
480 }
481
482 if ( $wgMaximalPasswordLength !== false ) {
483 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
484 }
485
486 // Backwards compatibility warning
487 if ( !$wgSessionsInObjectCache && !$wgSessionsInMemcached ) {
488 wfDeprecated( '$wgSessionsInObjectCache = false', '1.27' );
489 if ( $wgSessionHandler ) {
490 wfDeprecated( '$wgSessionsHandler', '1.27' );
491 }
492 $cacheType = get_class( ObjectCache::getInstance( $wgSessionCacheType ) );
493 wfDebugLog(
494 'caches',
495 "Session data will be stored in \"$cacheType\" cache with " .
496 "expiry $wgObjectCacheSessionExpiry seconds"
497 );
498 }
499 $wgSessionsInObjectCache = true;
500
501 if ( $wgPHPSessionHandling !== 'enable' &&
502 $wgPHPSessionHandling !== 'warn' &&
503 $wgPHPSessionHandling !== 'disable'
504 ) {
505 $wgPHPSessionHandling = 'warn';
506 }
507 if ( defined( 'MW_NO_SESSION' ) ) {
508 // If the entry point wants no session, force 'disable' here unless they
509 // specifically set it to the (undocumented) 'warn'.
510 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
511 }
512
513 Profiler::instance()->scopedProfileOut( $ps_default );
514
515 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
516 // all the memory from logging SQL queries on maintenance scripts
517 global $wgCommandLineMode;
518 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
519 MWDebug::init();
520 }
521
522 if ( !class_exists( 'AutoLoader' ) ) {
523 require_once "$IP/includes/AutoLoader.php";
524 }
525
526 // Reset the global service locator, so any services that have already been created will be
527 // re-created while taking into account any custom settings and extensions.
528 MediaWikiServices::resetGlobalInstance( new GlobalVarConfig() );
529
530 // Define a constant that indicates that the bootstrapping of the service locator
531 // is complete.
532 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
533
534 // Install a header callback to prevent caching of responses with cookies (T127993)
535 if ( !$wgCommandLineMode ) {
536 header_register_callback( function () {
537 $headers = [];
538 foreach ( headers_list() as $header ) {
539 list( $name, $value ) = explode( ':', $header, 2 );
540 $headers[strtolower( trim( $name ) )][] = trim( $value );
541 }
542
543 if ( isset( $headers['set-cookie'] ) ) {
544 $cacheControl = isset( $headers['cache-control'] )
545 ? implode( ', ', $headers['cache-control'] )
546 : '';
547
548 if ( !preg_match( '/(?:^|,)\s*(?:private|no-cache|no-store)\s*(?:$|,)/i', $cacheControl ) ) {
549 header( 'Expires: Thu, 01 Jan 1970 00:00:00 GMT' );
550 header( 'Cache-Control: private, max-age=0, s-maxage=0' );
551 MediaWiki\Logger\LoggerFactory::getInstance( 'cache-cookies' )->warning(
552 'Cookies set on {url} with Cache-Control "{cache-control}"', [
553 'url' => WebRequest::getGlobalRequestURL(),
554 'cookies' => $headers['set-cookie'],
555 'cache-control' => $cacheControl ?: '<not set>',
556 ]
557 );
558 }
559 }
560 } );
561 }
562
563 MWExceptionHandler::installHandler();
564
565 require_once "$IP/includes/compat/normal/UtfNormalUtil.php";
566
567 $ps_validation = Profiler::instance()->scopedProfileIn( $fname . '-validation' );
568
569 // T48998: Bail out early if $wgArticlePath is non-absolute
570 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
571 if ( $$varName && !preg_match( '/^(https?:\/\/|\/)/', $$varName ) ) {
572 throw new FatalError(
573 "If you use a relative URL for \$$varName, it must start " .
574 'with a slash (<code>/</code>).<br><br>See ' .
575 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
576 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
577 );
578 }
579 }
580
581 Profiler::instance()->scopedProfileOut( $ps_validation );
582
583 $ps_default2 = Profiler::instance()->scopedProfileIn( $fname . '-defaults2' );
584
585 if ( $wgCanonicalServer === false ) {
586 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP );
587 }
588
589 // Set server name
590 $serverParts = wfParseUrl( $wgCanonicalServer );
591 if ( $wgServerName !== false ) {
592 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
593 . 'not customized. Overwriting $wgServerName.' );
594 }
595 $wgServerName = $serverParts['host'];
596 unset( $serverParts );
597
598 // Set defaults for configuration variables
599 // that are derived from the server name by default
600 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
601 if ( !$wgEmergencyContact ) {
602 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
603 }
604 if ( !$wgPasswordSender ) {
605 $wgPasswordSender = 'apache@' . $wgServerName;
606 }
607 if ( !$wgNoReplyAddress ) {
608 $wgNoReplyAddress = $wgPasswordSender;
609 }
610
611 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
612 $wgSecureLogin = false;
613 wfWarn( 'Secure login was enabled on a server that only supports '
614 . 'HTTP or HTTPS. Disabling secure login.' );
615 }
616
617 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
618
619 // Now that GlobalFunctions is loaded, set defaults that depend on it.
620 if ( $wgTmpDirectory === false ) {
621 $wgTmpDirectory = wfTempDir();
622 }
623
624 // We don't use counters anymore. Left here for extensions still
625 // expecting this to exist. Should be removed sometime 1.26 or later.
626 if ( !isset( $wgDisableCounters ) ) {
627 $wgDisableCounters = true;
628 }
629
630 if ( $wgMainWANCache === false ) {
631 // Setup a WAN cache from $wgMainCacheType with no relayer.
632 // Sites using multiple datacenters can configure a relayer.
633 $wgMainWANCache = 'mediawiki-main-default';
634 $wgWANObjectCaches[$wgMainWANCache] = [
635 'class' => 'WANObjectCache',
636 'cacheId' => $wgMainCacheType,
637 'pool' => 'mediawiki-main-default',
638 'relayerConfig' => [ 'class' => 'EventRelayerNull' ]
639 ];
640 }
641
642 Profiler::instance()->scopedProfileOut( $ps_default2 );
643
644 $ps_misc = Profiler::instance()->scopedProfileIn( $fname . '-misc1' );
645
646 // Raise the memory limit if it's too low
647 wfMemoryLimit();
648
649 /**
650 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
651 * that happens whenever you use a date function without the timezone being
652 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
653 */
654 if ( is_null( $wgLocaltimezone ) ) {
655 MediaWiki\suppressWarnings();
656 $wgLocaltimezone = date_default_timezone_get();
657 MediaWiki\restoreWarnings();
658 }
659
660 date_default_timezone_set( $wgLocaltimezone );
661 if ( is_null( $wgLocalTZoffset ) ) {
662 $wgLocalTZoffset = date( 'Z' ) / 60;
663 }
664
665 if ( !$wgDBerrorLogTZ ) {
666 $wgDBerrorLogTZ = $wgLocaltimezone;
667 }
668
669 // initialize the request object in $wgRequest
670 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
671
672 // Useful debug output
673 if ( $wgCommandLineMode ) {
674 wfDebug( "\n\nStart command line script $self\n" );
675 } else {
676 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
677
678 if ( $wgDebugPrintHttpHeaders ) {
679 $debug .= "HTTP HEADERS:\n";
680
681 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
682 $debug .= "$name: $value\n";
683 }
684 }
685 wfDebug( $debug );
686 }
687
688 Profiler::instance()->scopedProfileOut( $ps_misc );
689 $ps_memcached = Profiler::instance()->scopedProfileIn( $fname . '-memcached' );
690
691 $wgMemc = ObjectCache::getLocalClusterInstance();
692 $messageMemc = wfGetMessageCacheStorage();
693 $parserMemc = wfGetParserCacheStorage();
694
695 wfDebugLog( 'caches',
696 'cluster: ' . get_class( $wgMemc ) .
697 ', WAN: ' . $wgMainWANCache .
698 ', stash: ' . $wgMainStash .
699 ', message: ' . get_class( $messageMemc ) .
700 ', parser: ' . get_class( $parserMemc ) );
701
702 Profiler::instance()->scopedProfileOut( $ps_memcached );
703
704 // Most of the config is out, some might want to run hooks here.
705 Hooks::run( 'SetupAfterCache' );
706
707 $ps_globals = Profiler::instance()->scopedProfileIn( $fname . '-globals' );
708
709 /**
710 * @var Language $wgContLang
711 */
712 $wgContLang = Language::factory( $wgLanguageCode );
713 $wgContLang->initEncoding();
714 $wgContLang->initContLang();
715
716 // Now that variant lists may be available...
717 $wgRequest->interpolateTitle();
718
719 if ( !is_object( $wgAuth ) ) {
720 $wgAuth = new AuthPlugin;
721 Hooks::run( 'AuthPluginSetup', [ &$wgAuth ] );
722 }
723
724 // Set up the session
725 $ps_session = Profiler::instance()->scopedProfileIn( $fname . '-session' );
726 /**
727 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
728 * session ID (if any) loaded at startup
729 */
730 $wgInitialSessionId = null;
731 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
732 // If session.auto_start is there, we can't touch session name
733 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
734 session_name( $wgSessionName ? $wgSessionName : $wgCookiePrefix . '_session' );
735 }
736
737 // Create the SessionManager singleton and set up our session handler,
738 // unless we're specifically asked not to.
739 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
740 MediaWiki\Session\PHPSessionHandler::install(
741 MediaWiki\Session\SessionManager::singleton()
742 );
743 }
744
745 // Initialize the session
746 try {
747 $session = MediaWiki\Session\SessionManager::getGlobalSession();
748 } catch ( OverflowException $ex ) {
749 if ( isset( $ex->sessionInfos ) && count( $ex->sessionInfos ) >= 2 ) {
750 // The exception is because the request had multiple possible
751 // sessions tied for top priority. Report this to the user.
752 $list = [];
753 foreach ( $ex->sessionInfos as $info ) {
754 $list[] = $info->getProvider()->describe( $wgContLang );
755 }
756 $list = $wgContLang->listToText( $list );
757 throw new HttpError( 400,
758 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
759 );
760 }
761
762 // Not the one we want, rethrow
763 throw $ex;
764 }
765
766 if ( $session->isPersistent() ) {
767 $wgInitialSessionId = $session->getSessionId();
768 }
769
770 $session->renew();
771 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
772 ( $session->isPersistent() || $session->shouldRememberUser() )
773 ) {
774 // Start the PHP-session for backwards compatibility
775 session_id( $session->getId() );
776 MediaWiki\quietCall( 'session_start' );
777 }
778
779 unset( $session );
780 } else {
781 // Even if we didn't set up a global Session, still install our session
782 // handler unless specifically requested not to.
783 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
784 MediaWiki\Session\PHPSessionHandler::install(
785 MediaWiki\Session\SessionManager::singleton()
786 );
787 }
788 }
789 Profiler::instance()->scopedProfileOut( $ps_session );
790
791 /**
792 * @var User $wgUser
793 */
794 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
795
796 /**
797 * @var Language $wgLang
798 */
799 $wgLang = new StubUserLang;
800
801 /**
802 * @var OutputPage $wgOut
803 */
804 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
805
806 /**
807 * @var Parser $wgParser
808 */
809 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], [ $wgParserConf ] );
810
811 /**
812 * @var Title $wgTitle
813 */
814 $wgTitle = null;
815
816 Profiler::instance()->scopedProfileOut( $ps_globals );
817 $ps_extensions = Profiler::instance()->scopedProfileIn( $fname . '-extensions' );
818
819 // Extension setup functions
820 // Entries should be added to this variable during the inclusion
821 // of the extension file. This allows the extension to perform
822 // any necessary initialisation in the fully initialised environment
823 foreach ( $wgExtensionFunctions as $func ) {
824 // Allow closures in PHP 5.3+
825 if ( is_object( $func ) && $func instanceof Closure ) {
826 $profName = $fname . '-extensions-closure';
827 } elseif ( is_array( $func ) ) {
828 if ( is_object( $func[0] ) ) {
829 $profName = $fname . '-extensions-' . get_class( $func[0] ) . '::' . $func[1];
830 } else {
831 $profName = $fname . '-extensions-' . implode( '::', $func );
832 }
833 } else {
834 $profName = $fname . '-extensions-' . strval( $func );
835 }
836
837 $ps_ext_func = Profiler::instance()->scopedProfileIn( $profName );
838 call_user_func( $func );
839 Profiler::instance()->scopedProfileOut( $ps_ext_func );
840 }
841
842 // If the session user has a 0 id but a valid name, that means we need to
843 // autocreate it.
844 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
845 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
846 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
847 $ps_autocreate = Profiler::instance()->scopedProfileIn( $fname . '-autocreate' );
848 MediaWiki\Session\SessionManager::autoCreateUser( $sessionUser );
849 Profiler::instance()->scopedProfileOut( $ps_autocreate );
850 }
851 unset( $sessionUser );
852 }
853
854 wfDebug( "Fully initialised\n" );
855 $wgFullyInitialised = true;
856
857 Profiler::instance()->scopedProfileOut( $ps_extensions );
858 Profiler::instance()->scopedProfileOut( $ps_setup );