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