Debian Codegraph @

includes/installer/Installer.php

raw symbols SCIP
1 <?php
2 /**
3 * Base code for MediaWiki installer.
4 *
5 * DO NOT PATCH THIS FILE IF YOU NEED TO CHANGE INSTALLER BEHAVIOR IN YOUR PACKAGE!
6 * See mw-config/overrides/README for details.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Installer
25 */
26
27 namespace MediaWiki\Installer;
28
29 use AutoLoader;
30 use Exception;
31 use ExecutableFinder;
32 use GuzzleHttp\Psr7\Header;
33 use IntlChar;
34 use InvalidArgumentException;
35 use LogicException;
36 use MediaWiki\Config\Config;
37 use MediaWiki\Config\GlobalVarConfig;
38 use MediaWiki\Config\HashConfig;
39 use MediaWiki\Config\MultiConfig;
40 use MediaWiki\Content\WikitextContent;
41 use MediaWiki\Context\RequestContext;
42 use MediaWiki\Deferred\SiteStatsUpdate;
43 use MediaWiki\HookContainer\HookContainer;
44 use MediaWiki\HookContainer\StaticHookRegistry;
45 use MediaWiki\Interwiki\NullInterwikiLookup;
46 use MediaWiki\Language\Language;
47 use MediaWiki\MainConfigNames;
48 use MediaWiki\MainConfigSchema;
49 use MediaWiki\MediaWikiServices;
50 use MediaWiki\Parser\Parser;
51 use MediaWiki\Parser\ParserOptions;
52 use MediaWiki\Registration\ExtensionDependencyError;
53 use MediaWiki\Registration\ExtensionProcessor;
54 use MediaWiki\Registration\ExtensionRegistry;
55 use MediaWiki\Settings\SettingsBuilder;
56 use MediaWiki\Status\Status;
57 use MediaWiki\StubObject\StubGlobalUser;
58 use MediaWiki\Title\Title;
59 use MediaWiki\User\Options\StaticUserOptionsLookup;
60 use MediaWiki\User\User;
61 use MediaWiki\Utils\UrlUtils;
62 use MWCryptRand;
63 use MWLBFactory;
64 use RuntimeException;
65 use Wikimedia\AtEase\AtEase;
66 use Wikimedia\Message\MessageSpecifier;
67 use Wikimedia\ObjectCache\EmptyBagOStuff;
68 use Wikimedia\Rdbms\LBFactorySingle;
69 use Wikimedia\Services\ServiceDisabledException;
70
71 /**
72 * The Installer helps admins create or upgrade their wiki.
73 *
74 * The installer classes are exposed through these human interfaces:
75 *
76 * - The `maintenance/install.php` script, backed by CliInstaller.
77 * - The `maintenance/update.php` script, backed by DatabaseUpdater.
78 * - The `mw-config/index.php` web entry point, backed by WebInstaller.
79 *
80 * @defgroup Installer Installer
81 */
82
83 /**
84 * Base installer class.
85 *
86 * This class provides the base for installation and update functionality
87 * for both MediaWiki core and extensions.
88 *
89 * @ingroup Installer
90 * @since 1.17
91 */
92 abstract class Installer {
93
94 /**
95 * URL to mediawiki-announce list summary page
96 */
97 private const MEDIAWIKI_ANNOUNCE_URL =
98 'https://lists.wikimedia.org/postorius/lists/mediawiki-announce.lists.wikimedia.org/';
99
100 /**
101 * @var array
102 */
103 protected $settings;
104
105 /**
106 * List of detected DBs, access using getCompiledDBs().
107 *
108 * @var array
109 */
110 protected $compiledDBs;
111
112 /**
113 * Cached DB installer instances, access using getDBInstaller().
114 *
115 * @var array
116 */
117 protected $dbInstallers = [];
118
119 /**
120 * Minimum memory size in MiB.
121 *
122 * @var int
123 */
124 protected $minMemorySize = 50;
125
126 /**
127 * Cached Title, used by parse().
128 *
129 * @var Title
130 */
131 protected $parserTitle;
132
133 /**
134 * Cached ParserOptions, used by parse().
135 *
136 * @var ParserOptions
137 */
138 protected $parserOptions;
139
140 /**
141 * Known database types. These correspond to the class names <type>Installer,
142 * and are also MediaWiki database types valid for $wgDBtype.
143 *
144 * To add a new type, create a <type>Installer class and a Database<type>
145 * class, and add a config-type-<type> message to MessagesEn.php.
146 *
147 * @var array
148 */
149 protected static $dbTypes = [
150 'mysql',
151 'postgres',
152 'sqlite',
153 ];
154
155 /**
156 * A list of environment check methods called by doEnvironmentChecks().
157 * These may output warnings using showMessage(), and/or abort the
158 * installation process by returning false.
159 *
160 * For the WebInstaller these are only called on the Welcome page,
161 * if these methods have side-effects that should affect later page loads
162 * (as well as the generated stylesheet), use envPreps instead.
163 *
164 * @var array
165 */
166 protected $envChecks = [
167 'envCheckLibicu',
168 'envCheckDB',
169 'envCheckPCRE',
170 'envCheckMemory',
171 'envCheckCache',
172 'envCheckModSecurity',
173 'envCheckDiff3',
174 'envCheckGraphics',
175 'envCheckGit',
176 'envCheckServer',
177 'envCheckPath',
178 'envCheckUploadsDirectory',
179 'envCheckUploadsServerResponse',
180 'envCheck64Bit',
181 ];
182
183 /**
184 * A list of environment preparation methods called by doEnvironmentPreps().
185 *
186 * @var array
187 */
188 protected $envPreps = [
189 'envPrepServer',
190 'envPrepPath',
191 ];
192
193 /**
194 * MediaWiki configuration globals that will eventually be passed through
195 * to LocalSettings.php. The names only are given here, the defaults
196 * typically come from config-schema.yaml.
197 */
198 private const DEFAULT_VAR_NAMES = [
199 MainConfigNames::Sitename,
200 MainConfigNames::PasswordSender,
201 MainConfigNames::LanguageCode,
202 MainConfigNames::Localtimezone,
203 MainConfigNames::RightsIcon,
204 MainConfigNames::RightsText,
205 MainConfigNames::RightsUrl,
206 MainConfigNames::EnableEmail,
207 MainConfigNames::EnableUserEmail,
208 MainConfigNames::EnotifUserTalk,
209 MainConfigNames::EnotifWatchlist,
210 MainConfigNames::EmailAuthentication,
211 MainConfigNames::DBname,
212 MainConfigNames::DBtype,
213 MainConfigNames::Diff3,
214 MainConfigNames::ImageMagickConvertCommand,
215 MainConfigNames::GitBin,
216 MainConfigNames::ScriptPath,
217 MainConfigNames::MetaNamespace,
218 MainConfigNames::DeletedDirectory,
219 MainConfigNames::EnableUploads,
220 MainConfigNames::SecretKey,
221 MainConfigNames::UseInstantCommons,
222 MainConfigNames::UpgradeKey,
223 MainConfigNames::DefaultSkin,
224 MainConfigNames::Pingback,
225 ];
226
227 /**
228 * Variables that are stored alongside globals, and are used for any
229 * configuration of the installation process aside from the MediaWiki
230 * configuration. Map of names to defaults.
231 *
232 * @var array
233 */
234 protected $internalDefaults = [
235 '_UserLang' => 'en',
236 '_Environment' => false,
237 '_RaiseMemory' => false,
238 '_UpgradeDone' => false,
239 '_InstallDone' => false,
240 '_Caches' => [],
241 '_InstallPassword' => '',
242 '_SameAccount' => true,
243 '_CreateDBAccount' => false,
244 '_NamespaceType' => 'site-name',
245 '_AdminName' => '', // will be set later, when the user selects language
246 '_AdminPassword' => '',
247 '_AdminPasswordConfirm' => '',
248 '_AdminEmail' => '',
249 '_Subscribe' => false,
250 '_SkipOptional' => 'continue',
251 '_RightsProfile' => 'wiki',
252 '_LicenseCode' => 'none',
253 '_CCDone' => false,
254 '_Extensions' => [],
255 '_Skins' => [],
256 '_MemCachedServers' => '',
257 '_UpgradeKeySupplied' => false,
258 '_ExistingDBSettings' => false,
259 '_LogoWordmark' => '',
260 '_LogoWordmarkWidth' => 119,
261 '_LogoWordmarkHeight' => 18,
262 // Single quotes are intentional, LocalSettingsGenerator must output this unescaped.
263 '_Logo1x' => '$wgResourceBasePath/resources/assets/change-your-logo.svg',
264 '_LogoIcon' => '$wgResourceBasePath/resources/assets/change-your-logo-icon.svg',
265 '_LogoTagline' => '',
266 '_LogoTaglineWidth' => 117,
267 '_LogoTaglineHeight' => 13,
268 '_WithDevelopmentSettings' => false,
269 'wgAuthenticationTokenVersion' => 1,
270 ];
271
272 /**
273 * The actual list of installation steps. This will be initialized by getInstallSteps()
274 *
275 * @var array[]
276 * @phan-var array<int,array{name:string,callback:array{0:object,1:string}}>
277 */
278 private $installSteps = [];
279
280 /**
281 * Extra steps for installation, for things like DatabaseInstallers to modify
282 *
283 * @var array
284 */
285 protected $extraInstallSteps = [];
286
287 /**
288 * Known object cache types and the functions used to test for their existence.
289 *
290 * @var array
291 */
292 protected $objectCaches = [
293 'apcu' => 'apcu_fetch',
294 ];
295
296 /**
297 * User rights profiles.
298 *
299 * @var array
300 */
301 public $rightsProfiles = [
302 'wiki' => [],
303 'no-anon' => [
304 '*' => [ 'edit' => false ]
305 ],
306 'fishbowl' => [
307 '*' => [
308 'createaccount' => false,
309 'edit' => false,
310 ],
311 ],
312 'private' => [
313 '*' => [
314 'createaccount' => false,
315 'edit' => false,
316 'read' => false,
317 ],
318 ],
319 ];
320
321 /**
322 * License types.
323 *
324 * @var array
325 */
326 public $licenses = [
327 'cc-by' => [
328 'url' => 'https://creativecommons.org/licenses/by/4.0/',
329 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
330 ],
331 'cc-by-sa' => [
332 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
333 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
334 ],
335 'cc-by-nc-sa' => [
336 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
337 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
338 ],
339 'cc-0' => [
340 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
341 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
342 ],
343 'gfdl' => [
344 'url' => 'https://www.gnu.org/copyleft/fdl.html',
345 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
346 ],
347 'none' => [
348 'url' => '',
349 'icon' => '',
350 'text' => ''
351 ],
352 ];
353
354 /**
355 * @var HookContainer|null
356 */
357 protected $autoExtensionHookContainer;
358 protected array $virtualDomains = [];
359
360 /**
361 * Display a short neutral message
362 *
363 * @param string|MessageSpecifier $msg String of wikitext that will be converted
364 * to HTML, or interface message that will be parsed.
365 * @param mixed ...$params
366 */
367 abstract public function showMessage( $msg, ...$params );
368
369 /**
370 * Display a success message
371 *
372 * @param string|MessageSpecifier $msg String of wikitext that will be converted
373 * to HTML, or interface message that will be parsed.
374 * @param string|int|float ...$params Message parameters, same as wfMessage().
375 */
376 abstract public function showSuccess( $msg, ...$params );
377
378 /**
379 * Display a warning message
380 *
381 * @param string|MessageSpecifier $msg String of wikitext that will be converted
382 * to HTML, or interface message that will be parsed.
383 * @param string|int|float ...$params Message parameters, same as wfMessage().
384 */
385 abstract public function showWarning( $msg, ...$params );
386
387 /**
388 * Display an error message
389 *
390 * Avoid error fatigue in the installer. Use this only if something the
391 * user expects has failed and requires intervention to continue.
392 * If something non-essential failed that can be continued past with
393 * no action, use a warning instead.
394 *
395 * @param string|MessageSpecifier $msg
396 * @param mixed ...$params
397 */
398 abstract public function showError( $msg, ...$params );
399
400 /**
401 * Show a message to the installing user by using a Status object
402 * @param Status $status
403 */
404 abstract public function showStatusMessage( Status $status );
405
406 /**
407 * Constructs a Config object that contains configuration settings that should be
408 * overwritten for the installation process.
409 *
410 * @since 1.27
411 *
412 * @param Config $baseConfig
413 *
414 * @return Config The config to use during installation.
415 */
416 public static function getInstallerConfig( Config $baseConfig ) {
417 $configOverrides = new HashConfig();
418
419 // disable (problematic) object cache types explicitly, preserving all other (working) ones
420 // bug T113843
421 $emptyCache = [ 'class' => EmptyBagOStuff::class ];
422
423 $objectCaches = [
424 CACHE_NONE => $emptyCache,
425 CACHE_DB => $emptyCache,
426 CACHE_ANYTHING => $emptyCache,
427 CACHE_MEMCACHED => $emptyCache,
428 ] + $baseConfig->get( MainConfigNames::ObjectCaches );
429
430 $configOverrides->set( MainConfigNames::ObjectCaches, $objectCaches );
431
432 // Load the installer's i18n.
433 $messageDirs = $baseConfig->get( MainConfigNames::MessagesDirs );
434 $messageDirs['MediaWikiInstaller'] = __DIR__ . '/i18n';
435
436 $configOverrides->set( MainConfigNames::MessagesDirs, $messageDirs );
437
438 $installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
439
440 // make sure we use the installer config as the main config
441 $configRegistry = $baseConfig->get( MainConfigNames::ConfigRegistry );
442 $configRegistry['main'] = static function () use ( $installerConfig ) {
443 return $installerConfig;
444 };
445
446 $configOverrides->set( MainConfigNames::ConfigRegistry, $configRegistry );
447
448 return $installerConfig;
449 }
450
451 /**
452 * Constructor, always call this from child classes.
453 */
454 public function __construct() {
455 $defaultConfig = new GlobalVarConfig(); // all the defaults from config-schema.yaml.
456 $installerConfig = self::getInstallerConfig( $defaultConfig );
457
458 // Disable all storage services, since we don't have any configuration yet!
459 $this->resetMediaWikiServices( $installerConfig, [], true );
460
461 $this->settings = $this->getDefaultSettings();
462
463 $this->doEnvironmentPreps();
464
465 $this->compiledDBs = [];
466 foreach ( self::getDBTypes() as $type ) {
467 $installer = $this->getDBInstaller( $type );
468
469 if ( !$installer->isCompiled() ) {
470 continue;
471 }
472 $this->compiledDBs[] = $type;
473 }
474
475 $this->parserTitle = Title::newFromText( 'Installer' );
476 }
477
478 /**
479 * @return array
480 */
481 private function getDefaultSettings(): array {
482 global $wgLocaltimezone;
483
484 $ret = $this->internalDefaults;
485
486 foreach ( self::DEFAULT_VAR_NAMES as $name ) {
487 $var = "wg{$name}";
488 $ret[$var] = MainConfigSchema::getDefaultValue( $name );
489 }
490
491 // Set $wgLocaltimezone to the value of the global, which SetupDynamicConfig.php will have
492 // set to something that is a valid timezone.
493 $ret['wgLocaltimezone'] = $wgLocaltimezone;
494
495 return $ret;
496 }
497
498 /**
499 * Reset the global service container and associated global state
500 * to accommodate different stages of the installation.
501 * @since 1.35
502 *
503 * @param Config|null $installerConfig Config override. If null, the previous
504 * config will be inherited.
505 * @param array $serviceOverrides Service definition overrides. Values can be null to
506 * disable specific overrides that would be applied by default, namely
507 * 'InterwikiLookup' and 'UserOptionsLookup'.
508 * @param bool $disableStorage Whether MediaWikiServices::disableStorage() should be called.
509 *
510 * @return MediaWikiServices
511 */
512 public function resetMediaWikiServices(
513 ?Config $installerConfig = null,
514 $serviceOverrides = [],
515 bool $disableStorage = false
516 ) {
517 global $wgObjectCaches, $wgLang;
518
519 // Reset all services and inject config overrides.
520 // NOTE: This will reset existing instances, but not previous wiring overrides!
521 MediaWikiServices::resetGlobalInstance( $installerConfig );
522
523 $mwServices = MediaWikiServices::getInstance();
524
525 if ( $disableStorage ) {
526 $mwServices->disableStorage();
527 } else {
528 // Default to partially disabling services.
529
530 $serviceOverrides += [
531 // Disable interwiki lookup, to avoid database access during parses
532 'InterwikiLookup' => static function () {
533 return new NullInterwikiLookup();
534 },
535
536 // Disable user options database fetching, only rely on default options.
537 'UserOptionsLookup' => static function ( MediaWikiServices $services ) {
538 return new StaticUserOptionsLookup(
539 [],
540 $services->getMainConfig()->get( MainConfigNames::DefaultUserOptions )
541 );
542 },
543
544 // Restore to default wiring, in case it was overwritten by disableStorage()
545 'DBLoadBalancer' => static function ( MediaWikiServices $services ) {
546 return $services->getDBLoadBalancerFactory()->getMainLB();
547 },
548 ];
549 }
550
551 $lang = $this->getVar( '_UserLang', 'en' );
552
553 foreach ( $serviceOverrides as $name => $callback ) {
554 // Skip if the caller set $callback to null
555 // to suppress default overrides.
556 if ( $callback ) {
557 $mwServices->redefineService( $name, $callback );
558 }
559 }
560
561 // Disable i18n cache
562 $mwServices->getLocalisationCache()->disableBackend();
563
564 // Set a fake user.
565 // Note that this will reset the context's language,
566 // so set the user before setting the language.
567 $user = User::newFromId( 0 );
568 StubGlobalUser::setUser( $user );
569
570 RequestContext::getMain()->setUser( $user );
571
572 // Don't attempt to load user language options (T126177)
573 // This will be overridden in the web installer with the user-specified language
574 // Ensure $wgLang does not have a reference to a stale LocalisationCache instance
575 // (T241638, T261081)
576 RequestContext::getMain()->setLanguage( $lang );
577 $wgLang = RequestContext::getMain()->getLanguage();
578
579 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
580 // SqlBagOStuff will then throw since we just disabled wfGetDB)
581 $wgObjectCaches = $mwServices->getMainConfig()->get( MainConfigNames::ObjectCaches );
582
583 $this->parserOptions = new ParserOptions( $user ); // language will be wrong :(
584 // Don't try to access DB before user language is initialised
585 $this->setParserLanguage( $mwServices->getLanguageFactory()->getLanguage( 'en' ) );
586
587 return $mwServices;
588 }
589
590 /**
591 * Get a list of known DB types.
592 *
593 * @return array
594 */
595 public static function getDBTypes() {
596 return self::$dbTypes;
597 }
598
599 /**
600 * Do initial checks of the PHP environment. Set variables according to
601 * the observed environment.
602 *
603 * It's possible that this may be called under the CLI SAPI, not the SAPI
604 * that the wiki will primarily run under. In that case, the subclass should
605 * initialise variables such as wgScriptPath, before calling this function.
606 *
607 * It can already be assumed that a supported PHP version is in use. Under
608 * the web subclass, it can also be assumed that sessions are working.
609 *
610 * @return Status
611 */
612 public function doEnvironmentChecks() {
613 // PHP version has already been checked by entry scripts
614 // Show message here for information purposes
615 $this->showMessage( 'config-env-php', PHP_VERSION );
616
617 $good = true;
618 foreach ( $this->envChecks as $check ) {
619 $status = $this->$check();
620 if ( $status === false ) {
621 $good = false;
622 }
623 }
624
625 $this->setVar( '_Environment', $good );
626
627 return $good ? Status::newGood() : Status::newFatal( 'config-env-bad' );
628 }
629
630 public function doEnvironmentPreps() {
631 foreach ( $this->envPreps as $prep ) {
632 $this->$prep();
633 }
634 }
635
636 /**
637 * Set a MW configuration variable, or internal installer configuration variable.
638 *
639 * @param string $name
640 * @param mixed $value
641 */
642 public function setVar( $name, $value ) {
643 $this->settings[$name] = $value;
644 }
645
646 /**
647 * Get an MW configuration variable, or internal installer configuration variable.
648 * The defaults come from MainConfigSchema.
649 * Installer variables are typically prefixed by an underscore.
650 *
651 * @param string $name
652 * @param mixed|null $default
653 *
654 * @return mixed
655 */
656 public function getVar( $name, $default = null ) {
657 return $this->settings[$name] ?? $default;
658 }
659
660 /**
661 * Get a list of DBs supported by current PHP setup
662 *
663 * @return array
664 */
665 public function getCompiledDBs() {
666 return $this->compiledDBs;
667 }
668
669 /**
670 * Get the DatabaseInstaller class name for this type
671 *
672 * @param string $type database type ($wgDBtype)
673 * @return string Class name
674 * @since 1.30
675 */
676 public static function getDBInstallerClass( $type ) {
677 return '\\MediaWiki\\Installer\\' . ucfirst( $type ) . 'Installer';
678 }
679
680 /**
681 * Get an instance of DatabaseInstaller for the specified DB type.
682 *
683 * @param mixed $type DB installer for which is needed, false to use default.
684 *
685 * @return DatabaseInstaller
686 */
687 public function getDBInstaller( $type = false ) {
688 if ( !$type ) {
689 $type = $this->getVar( 'wgDBtype' );
690 }
691
692 $type = strtolower( $type );
693
694 if ( !isset( $this->dbInstallers[$type] ) ) {
695 $class = self::getDBInstallerClass( $type );
696 $this->dbInstallers[$type] = new $class( $this );
697 }
698
699 return $this->dbInstallers[$type];
700 }
701
702 /**
703 * Determine if LocalSettings.php exists. If it does, return its variables.
704 *
705 * @return array|false
706 */
707 public static function getExistingLocalSettings() {
708 $IP = wfDetectInstallPath();
709
710 // You might be wondering why this is here. Well if you don't do this
711 // then some poorly-formed extensions try to call their own classes
712 // after immediately registering them. We really need to get extension
713 // registration out of the global scope and into a real format.
714 // @see https://phabricator.wikimedia.org/T69440
715 global $wgAutoloadClasses;
716 $wgAutoloadClasses = [];
717
718 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
719 // Define the required globals here, to ensure, the functions can do it work correctly.
720 // phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables
721 global $wgExtensionDirectory, $wgStyleDirectory;
722
723 // This will also define MW_CONFIG_FILE
724 $lsFile = wfDetectLocalSettingsFile( $IP );
725 // phpcs:ignore Generic.PHP.NoSilencedErrors
726 $lsExists = @file_exists( $lsFile );
727
728 if ( !$lsExists ) {
729 return false;
730 }
731
732 if ( !str_ends_with( $lsFile, '.php' ) ) {
733 throw new RuntimeException(
734 'The installer cannot yet handle non-php settings files: ' . $lsFile . '. ' .
735 'Use `php maintenance/run.php update` to update an existing installation.'
736 );
737 }
738 unset( $lsExists );
739
740 // Extract the defaults into the current scope
741 foreach ( MainConfigSchema::listDefaultValues( 'wg' ) as $var => $value ) {
742 $$var = $value;
743 }
744
745 $wgExtensionDirectory = "$IP/extensions";
746 $wgStyleDirectory = "$IP/skins";
747
748 // NOTE: To support YAML settings files, this needs to start using SettingsBuilder.
749 // However, as of 1.38, YAML settings files are still experimental and
750 // SettingsBuilder is still unstable. For now, the installer will fail if
751 // the existing settings file is not PHP. The updater should still work though.
752 // NOTE: When adding support for YAML settings file, all references to LocalSettings.php
753 // in localisation messages need to be replaced.
754 // NOTE: This assumes simple variable assignments. More complex setups may involve
755 // settings coming from sub-required and/or functions that assign globals
756 // directly. This is fine here because this isn't used as the "real" include.
757 // It is only used for reading out a small set of variables that the installer
758 // validates and/or displays.
759 require $lsFile;
760
761 return get_defined_vars();
762 }
763
764 /**
765 * Get a fake password for sending back to the user in HTML.
766 * This is a security mechanism to avoid compromise of the password in the
767 * event of session ID compromise.
768 *
769 * @param string $realPassword
770 *
771 * @return string
772 */
773 public function getFakePassword( $realPassword ) {
774 return str_repeat( '*', strlen( $realPassword ) );
775 }
776
777 /**
778 * Set a variable which stores a password, except if the new value is a
779 * fake password in which case leave it as it is.
780 *
781 * @param string $name
782 * @param mixed $value
783 */
784 public function setPassword( $name, $value ) {
785 if ( !preg_match( '/^\*+$/', $value ) ) {
786 $this->setVar( $name, $value );
787 }
788 }
789
790 /**
791 * On POSIX systems return the primary group of the webserver we're running under.
792 * On other systems just returns null.
793 *
794 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
795 * webserver user before he can install.
796 *
797 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
798 *
799 * @return mixed
800 */
801 public static function maybeGetWebserverPrimaryGroup() {
802 if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
803 # I don't know this, this isn't UNIX.
804 return null;
805 }
806
807 # posix_getegid() *not* getmygid() because we want the group of the webserver,
808 # not whoever owns the current script.
809 $gid = posix_getegid();
810 return posix_getpwuid( $gid )['name'] ?? null;
811 }
812
813 /**
814 * Convert wikitext $text to HTML.
815 *
816 * This is potentially error prone since many parser features require a complete
817 * installed MW database. The solution is to just not use those features when you
818 * write your messages. This appears to work well enough. Basic formatting and
819 * external links work just fine.
820 *
821 * But in case a translator decides to throw in a "#ifexist" or internal link or
822 * whatever, this function is guarded to catch the attempted DB access and to present
823 * some fallback text.
824 *
825 * @param string $text
826 * @param bool $lineStart
827 * @return string
828 */
829 public function parse( $text, $lineStart = false ) {
830 $parser = MediaWikiServices::getInstance()->getParser();
831
832 try {
833 $out = $parser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
834 $pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline();
835 // TODO T371008 consider if using the Content framework makes sense instead of creating the pipeline
836 $html = $pipeline->run( $out, $this->parserOptions, [
837 'enableSectionEditLinks' => false,
838 'unwrap' => true,
839 ] )->getContentHolderText();
840 $html = Parser::stripOuterParagraph( $html );
841 } catch ( ServiceDisabledException $e ) {
842 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
843 }
844
845 return $html;
846 }
847
848 /**
849 * @return ParserOptions
850 */
851 public function getParserOptions() {
852 return $this->parserOptions;
853 }
854
855 public function disableLinkPopups() {
856 // T317647: This ParserOptions method is deprecated; we should be
857 // updating ExternalLinkTarget in the Configuration instead.
858 $this->parserOptions->setExternalLinkTarget( false );
859 }
860
861 public function restoreLinkPopups() {
862 // T317647: This ParserOptions method is deprecated; we should be
863 // updating ExternalLinkTarget in the Configuration instead.
864 global $wgExternalLinkTarget;
865 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
866 }
867
868 /**
869 * Install step which adds a row to the site_stats table with appropriate
870 * initial values.
871 *
872 * @param DatabaseInstaller $installer
873 *
874 * @return Status
875 */
876 public function populateSiteStats( DatabaseInstaller $installer ) {
877 $status = $installer->getConnection( DatabaseInstaller::CONN_CREATE_TABLES );
878 if ( !$status->isOK() ) {
879 return $status;
880 }
881 $status->getDB()->newInsertQueryBuilder()
882 ->insertInto( 'site_stats' )
883 ->ignore()
884 ->row( [
885 'ss_row_id' => 1,
886 'ss_total_edits' => 0,
887 'ss_good_articles' => 0,
888 'ss_total_pages' => 0,
889 'ss_users' => 0,
890 'ss_active_users' => 0,
891 'ss_images' => 0
892 ] )
893 ->caller( __METHOD__ )
894 ->execute();
895
896 return Status::newGood();
897 }
898
899 /**
900 * Environment check for DB types.
901 * @return bool
902 */
903 protected function envCheckDB() {
904 global $wgLang;
905 /** @var string|null $dbType The user-specified database type */
906 $dbType = $this->getVar( 'wgDBtype' );
907
908 $allNames = [];
909
910 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite
911 foreach ( self::getDBTypes() as $name ) {
912 $allNames[] = wfMessage( "config-type-$name" )->text();
913 }
914
915 $databases = $this->getCompiledDBs();
916
917 $databases = array_flip( $databases );
918 $ok = true;
919 foreach ( $databases as $db => $_ ) {
920 $installer = $this->getDBInstaller( $db );
921 $status = $installer->checkPrerequisites();
922 if ( !$status->isGood() ) {
923 if ( !$this instanceof WebInstaller && $db === $dbType ) {
924 // Strictly check the key database type instead of just outputting message
925 // Note: No perform this check run from the web installer, since this method always called by
926 // the welcome page under web installation, so $dbType will always be 'mysql'
927 $ok = false;
928 }
929 $this->showStatusMessage( $status );
930 unset( $databases[$db] );
931 }
932 }
933 $databases = array_flip( $databases );
934 if ( !$databases ) {
935 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
936 return false;
937 }
938 return $ok;
939 }
940
941 /**
942 * Check for known PCRE-related compatibility issues.
943 *
944 * @note We don't bother checking for Unicode support here. If it were
945 * missing, the parser would probably throw an exception before the
946 * result of this check is shown to the user.
947 *
948 * @return bool
949 */
950 protected function envCheckPCRE() {
951 // PCRE2 must be compiled using NEWLINE_DEFAULT other than 4 (ANY);
952 // otherwise, it will misidentify UTF-8 trailing byte value 0x85
953 // as a line ending character when in non-UTF mode.
954 if ( preg_match( '/^b.*c$/', 'bÄ…c' ) === 0 ) {
955 $this->showError( 'config-pcre-invalid-newline' );
956 return false;
957 }
958 return true;
959 }
960
961 /**
962 * Environment check for available memory.
963 * @return bool
964 */
965 protected function envCheckMemory() {
966 $limit = ini_get( 'memory_limit' );
967
968 if ( !$limit || $limit == -1 ) {
969 return true;
970 }
971
972 $n = wfShorthandToInteger( $limit );
973
974 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
975 $newLimit = "{$this->minMemorySize}M";
976
977 if ( ini_set( "memory_limit", $newLimit ) === false ) {
978 $this->showMessage( 'config-memory-bad', $limit );
979 } else {
980 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
981 $this->setVar( '_RaiseMemory', true );
982 }
983 }
984
985 return true;
986 }
987
988 /**
989 * Environment check for compiled object cache types.
990 */
991 protected function envCheckCache() {
992 $caches = [];
993 foreach ( $this->objectCaches as $name => $function ) {
994 if ( function_exists( $function ) ) {
995 $caches[$name] = true;
996 }
997 }
998
999 if ( !$caches ) {
1000 $this->showMessage( 'config-no-cache-apcu' );
1001 }
1002
1003 $this->setVar( '_Caches', $caches );
1004 }
1005
1006 /**
1007 * Scare user to death if they have mod_security or mod_security2
1008 * @return bool
1009 */
1010 protected function envCheckModSecurity() {
1011 if ( self::apacheModulePresent( 'mod_security' )
1012 || self::apacheModulePresent( 'mod_security2' ) ) {
1013 $this->showMessage( 'config-mod-security' );
1014 }
1015
1016 return true;
1017 }
1018
1019 /**
1020 * Search for GNU diff3.
1021 * @return bool
1022 */
1023 protected function envCheckDiff3() {
1024 $names = [ "gdiff3", "diff3" ];
1025 if ( wfIsWindows() ) {
1026 $names[] = 'diff3.exe';
1027 }
1028 $versionInfo = [ '--version', 'GNU diffutils' ];
1029
1030 $diff3 = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
1031
1032 if ( $diff3 ) {
1033 $this->setVar( 'wgDiff3', $diff3 );
1034 } else {
1035 $this->setVar( 'wgDiff3', false );
1036 $this->showMessage( 'config-diff3-bad' );
1037 }
1038
1039 return true;
1040 }
1041
1042 /**
1043 * Environment check for ImageMagick and GD.
1044 * @return bool
1045 */
1046 protected function envCheckGraphics() {
1047 $names = wfIsWindows() ? 'convert.exe' : 'convert';
1048 $versionInfo = [ '-version', 'ImageMagick' ];
1049 $convert = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
1050
1051 $this->setVar( 'wgImageMagickConvertCommand', '' );
1052 if ( $convert ) {
1053 $this->setVar( 'wgImageMagickConvertCommand', $convert );
1054 $this->showMessage( 'config-imagemagick', $convert );
1055 } elseif ( function_exists( 'imagejpeg' ) ) {
1056 $this->showMessage( 'config-gd' );
1057 } else {
1058 $this->showMessage( 'config-no-scaling' );
1059 }
1060
1061 return true;
1062 }
1063
1064 /**
1065 * Search for git.
1066 *
1067 * @since 1.22
1068 * @return bool
1069 */
1070 protected function envCheckGit() {
1071 $names = wfIsWindows() ? 'git.exe' : 'git';
1072 $versionInfo = [ '--version', 'git version' ];
1073
1074 $git = ExecutableFinder::findInDefaultPaths( $names, $versionInfo );
1075
1076 if ( $git ) {
1077 $this->setVar( 'wgGitBin', $git );
1078 $this->showMessage( 'config-git', $git );
1079 } else {
1080 $this->setVar( 'wgGitBin', false );
1081 $this->showMessage( 'config-git-bad' );
1082 }
1083
1084 return true;
1085 }
1086
1087 /**
1088 * Environment check to inform user which server we've assumed.
1089 *
1090 * @return bool
1091 */
1092 protected function envCheckServer() {
1093 $server = $this->envGetDefaultServer();
1094 if ( $server !== null ) {
1095 $this->showMessage( 'config-using-server', $server );
1096 }
1097 return true;
1098 }
1099
1100 /**
1101 * Environment check to inform user which paths we've assumed.
1102 *
1103 * @return bool
1104 */
1105 protected function envCheckPath() {
1106 $this->showMessage(
1107 'config-using-uri',
1108 $this->getVar( 'wgServer' ),
1109 $this->getVar( 'wgScriptPath' )
1110 );
1111 return true;
1112 }
1113
1114 /**
1115 * Environment check for the permissions of the uploads directory
1116 * @return bool
1117 */
1118 protected function envCheckUploadsDirectory() {
1119 global $IP;
1120
1121 $dir = $IP . '/images/';
1122 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1123 $safe = !$this->dirIsExecutable( $dir, $url );
1124
1125 if ( !$safe ) {
1126 $this->showWarning( 'config-uploads-not-safe', $dir );
1127 }
1128
1129 return true;
1130 }
1131
1132 protected function envCheckUploadsServerResponse() {
1133 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/README';
1134 $httpRequestFactory = MediaWikiServices::getInstance()->getHttpRequestFactory();
1135 $status = null;
1136
1137 $req = $httpRequestFactory->create(
1138 $url,
1139 [
1140 'method' => 'GET',
1141 'timeout' => 3,
1142 'followRedirects' => true
1143 ],
1144 __METHOD__
1145 );
1146 try {
1147 $status = $req->execute();
1148 } catch ( Exception $e ) {
1149 // HttpRequestFactory::get can throw with allow_url_fopen = false and no curl
1150 // extension.
1151 }
1152
1153 if ( !$status || !$status->isGood() ) {
1154 $this->showWarning( 'config-uploads-security-requesterror', 'X-Content-Type-Options: nosniff' );
1155 return true;
1156 }
1157
1158 $headerValue = $req->getResponseHeader( 'X-Content-Type-Options' ) ?? '';
1159 $responseList = Header::splitList( $headerValue );
1160 if ( !in_array( 'nosniff', $responseList, true ) ) {
1161 $this->showWarning( 'config-uploads-security-headers', 'X-Content-Type-Options: nosniff' );
1162 }
1163
1164 return true;
1165 }
1166
1167 /**
1168 * Checks if we're running on 64 bit or not. 32 bit is becoming increasingly
1169 * hard to support, so let's at least warn people.
1170 *
1171 * @return bool
1172 */
1173 protected function envCheck64Bit() {
1174 if ( PHP_INT_SIZE == 4 ) {
1175 $this->showMessage( 'config-using-32bit' );
1176 }
1177
1178 return true;
1179 }
1180
1181 /**
1182 * Check and display the libicu and Unicode versions
1183 */
1184 protected function envCheckLibicu() {
1185 $unicodeVersion = implode( '.', array_slice( IntlChar::getUnicodeVersion(), 0, 3 ) );
1186 $this->showMessage( 'config-env-icu', INTL_ICU_VERSION, $unicodeVersion );
1187 }
1188
1189 /**
1190 * Environment prep for the server hostname.
1191 */
1192 protected function envPrepServer() {
1193 $server = $this->envGetDefaultServer();
1194 if ( $server !== null ) {
1195 $this->setVar( 'wgServer', $server );
1196 }
1197 }
1198
1199 /**
1200 * Helper function to be called from envPrepServer()
1201 * @return string
1202 */
1203 abstract protected function envGetDefaultServer();
1204
1205 /**
1206 * Environment prep for setting $IP and $wgScriptPath.
1207 */
1208 protected function envPrepPath() {
1209 global $IP;
1210 $IP = dirname( dirname( __DIR__ ) );
1211 $this->setVar( 'IP', $IP );
1212 }
1213
1214 /**
1215 * Checks if scripts located in the given directory can be executed via the given URL.
1216 *
1217 * Used only by environment checks.
1218 * @param string $dir
1219 * @param string $url
1220 * @return bool|int|string
1221 */
1222 public function dirIsExecutable( $dir, $url ) {
1223 $scriptTypes = [
1224 'php' => [
1225 "<?php echo 'exec';",
1226 "#!/var/env php\n<?php echo 'exec';",
1227 ],
1228 ];
1229
1230 // it would be good to check other popular languages here, but it'll be slow.
1231 // TODO no need to have a loop if there is going to only be one script type
1232
1233 $httpRequestFactory = MediaWikiServices::getInstance()->getHttpRequestFactory();
1234
1235 AtEase::suppressWarnings();
1236
1237 foreach ( $scriptTypes as $ext => $contents ) {
1238 foreach ( $contents as $source ) {
1239 $file = 'exectest.' . $ext;
1240
1241 if ( !file_put_contents( $dir . $file, $source ) ) {
1242 break;
1243 }
1244
1245 try {
1246 $text = $httpRequestFactory->get(
1247 $url . $file,
1248 [ 'timeout' => 3 ],
1249 __METHOD__
1250 );
1251 } catch ( Exception $e ) {
1252 // HttpRequestFactory::get can throw with allow_url_fopen = false and no curl
1253 // extension.
1254 $text = null;
1255 }
1256 unlink( $dir . $file );
1257
1258 if ( $text == 'exec' ) {
1259 AtEase::restoreWarnings();
1260
1261 return $ext;
1262 }
1263 }
1264 }
1265
1266 AtEase::restoreWarnings();
1267
1268 return false;
1269 }
1270
1271 /**
1272 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1273 *
1274 * @param string $moduleName Name of module to check.
1275 * @return bool
1276 */
1277 public static function apacheModulePresent( $moduleName ) {
1278 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1279 return true;
1280 }
1281 // try it the hard way
1282 ob_start();
1283 phpinfo( INFO_MODULES );
1284 $info = ob_get_clean();
1285
1286 return strpos( $info, $moduleName ) !== false;
1287 }
1288
1289 /**
1290 * ParserOptions are constructed before we determined the language, so fix it
1291 *
1292 * @param Language $lang
1293 */
1294 public function setParserLanguage( $lang ) {
1295 $this->parserOptions->setTargetLanguage( $lang );
1296 $this->parserOptions->setUserLang( $lang );
1297 }
1298
1299 /**
1300 * Overridden by WebInstaller to provide lastPage parameters.
1301 * @param string $page
1302 * @return string
1303 */
1304 protected function getDocUrl( $page ) {
1305 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1306 }
1307
1308 /**
1309 * Find extensions or skins in a subdirectory of $IP.
1310 * Returns an array containing the value for 'Name' for each found extension.
1311 *
1312 * @param string $directory Directory to search in, relative to $IP, must be either "extensions"
1313 * or "skins"
1314 * @return Status An object containing an error list. If there were no errors, an associative
1315 * array of information about the extension can be found in $status->value.
1316 */
1317 public function findExtensions( $directory = 'extensions' ) {
1318 switch ( $directory ) {
1319 case 'extensions':
1320 return $this->findExtensionsByType( 'extension', 'extensions' );
1321 case 'skins':
1322 return $this->findExtensionsByType( 'skin', 'skins' );
1323 default:
1324 throw new InvalidArgumentException( "Invalid extension type" );
1325 }
1326 }
1327
1328 /**
1329 * Find extensions or skins, and return an array containing the value for 'Name' for each found
1330 * extension.
1331 *
1332 * @param string $type Either "extension" or "skin"
1333 * @param string $directory Directory to search in, relative to $IP
1334 * @return Status An object containing an error list. If there were no errors, an associative
1335 * array of information about the extension can be found in $status->value.
1336 */
1337 protected function findExtensionsByType( $type = 'extension', $directory = 'extensions' ) {
1338 if ( $this->getVar( 'IP' ) === null ) {
1339 return Status::newGood( [] );
1340 }
1341
1342 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1343 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1344 return Status::newGood( [] );
1345 }
1346
1347 $dh = opendir( $extDir );
1348 $exts = [];
1349 $status = new Status;
1350 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
1351 while ( ( $file = readdir( $dh ) ) !== false ) {
1352 // skip non-dirs and hidden directories
1353 if ( !is_dir( "$extDir/$file" ) || $file[0] === '.' ) {
1354 continue;
1355 }
1356 $extStatus = $this->getExtensionInfo( $type, $directory, $file );
1357 if ( $extStatus->isOK() ) {
1358 $exts[$file] = $extStatus->value;
1359 } elseif ( $extStatus->hasMessage( 'config-extension-not-found' ) ) {
1360 // (T225512) The directory is not actually an extension. Downgrade to warning.
1361 $status->warning( 'config-extension-not-found', $file );
1362 } else {
1363 $status->merge( $extStatus );
1364 }
1365 }
1366 closedir( $dh );
1367 uksort( $exts, 'strnatcasecmp' );
1368
1369 $status->value = $exts;
1370
1371 return $status;
1372 }
1373
1374 /**
1375 * @param string $type Either "extension" or "skin"
1376 * @param string $parentRelPath The parent directory relative to $IP
1377 * @param string $name The extension or skin name
1378 * @return Status An object containing an error list. If there were no errors, an associative
1379 * array of information about the extension can be found in $status->value.
1380 */
1381 protected function getExtensionInfo( $type, $parentRelPath, $name ) {
1382 if ( $this->getVar( 'IP' ) === null ) {
1383 throw new RuntimeException( 'Cannot find extensions since the IP variable is not yet set' );
1384 }
1385 if ( $type !== 'extension' && $type !== 'skin' ) {
1386 throw new InvalidArgumentException( "Invalid extension type" );
1387 }
1388 $absDir = $this->getVar( 'IP' ) . "/$parentRelPath/$name";
1389 $relDir = "../$parentRelPath/$name";
1390 if ( !is_dir( $absDir ) ) {
1391 return Status::newFatal( 'config-extension-not-found', $name );
1392 }
1393 $jsonFile = $type . '.json';
1394 $fullJsonFile = "$absDir/$jsonFile";
1395 $isJson = file_exists( $fullJsonFile );
1396 $isPhp = false;
1397 if ( !$isJson ) {
1398 // Only fallback to PHP file if JSON doesn't exist
1399 $fullPhpFile = "$absDir/$name.php";
1400 $isPhp = file_exists( $fullPhpFile );
1401 }
1402 if ( !$isJson && !$isPhp ) {
1403 return Status::newFatal( 'config-extension-not-found', $name );
1404 }
1405
1406 // Extension exists. Now see if there are screenshots
1407 $info = [];
1408 if ( is_dir( "$absDir/screenshots" ) ) {
1409 $paths = glob( "$absDir/screenshots/*.png" );
1410 foreach ( $paths as $path ) {
1411 $info['screenshots'][] = str_replace( $absDir, $relDir, $path );
1412 }
1413 }
1414
1415 if ( $isJson ) {
1416 $jsonStatus = $this->readExtension( $fullJsonFile );
1417 if ( !$jsonStatus->isOK() ) {
1418 return $jsonStatus;
1419 }
1420 $info += $jsonStatus->value;
1421 }
1422
1423 return Status::newGood( $info );
1424 }
1425
1426 /**
1427 * @param string $fullJsonFile
1428 * @param array $extDeps
1429 * @param array $skinDeps
1430 *
1431 * @return Status On success, an array of extension information is in $status->value. On
1432 * failure, the Status object will have an error list.
1433 */
1434 private function readExtension( $fullJsonFile, $extDeps = [], $skinDeps = [] ) {
1435 $load = [
1436 $fullJsonFile => 1
1437 ];
1438 if ( $extDeps ) {
1439 $extDir = $this->getVar( 'IP' ) . '/extensions';
1440 foreach ( $extDeps as $dep ) {
1441 $fname = "$extDir/$dep/extension.json";
1442 if ( !file_exists( $fname ) ) {
1443 return Status::newFatal( 'config-extension-not-found', $dep );
1444 }
1445 $load[$fname] = 1;
1446 }
1447 }
1448 if ( $skinDeps ) {
1449 $skinDir = $this->getVar( 'IP' ) . '/skins';
1450 foreach ( $skinDeps as $dep ) {
1451 $fname = "$skinDir/$dep/skin.json";
1452 if ( !file_exists( $fname ) ) {
1453 return Status::newFatal( 'config-extension-not-found', $dep );
1454 }
1455 $load[$fname] = 1;
1456 }
1457 }
1458 $registry = new ExtensionRegistry();
1459 try {
1460 $info = $registry->readFromQueue( $load );
1461 } catch ( ExtensionDependencyError $e ) {
1462 if ( $e->incompatibleCore || $e->incompatibleSkins
1463 || $e->incompatibleExtensions
1464 ) {
1465 // If something is incompatible with a dependency, we have no real
1466 // option besides skipping it
1467 return Status::newFatal( 'config-extension-dependency',
1468 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1469 } elseif ( $e->missingExtensions || $e->missingSkins ) {
1470 // There's an extension missing in the dependency tree,
1471 // so add those to the dependency list and try again
1472 $status = $this->readExtension(
1473 $fullJsonFile,
1474 array_merge( $extDeps, $e->missingExtensions ),
1475 array_merge( $skinDeps, $e->missingSkins )
1476 );
1477 if ( !$status->isOK() && !$status->hasMessage( 'config-extension-dependency' ) ) {
1478 $status = Status::newFatal( 'config-extension-dependency',
1479 basename( dirname( $fullJsonFile ) ), $status->getMessage() );
1480 }
1481 return $status;
1482 }
1483 // Some other kind of dependency error?
1484 return Status::newFatal( 'config-extension-dependency',
1485 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1486 }
1487 $ret = [];
1488 // The order of credits will be the order of $load,
1489 // so the first extension is the one we want to load,
1490 // everything else is a dependency
1491 $i = 0;
1492 foreach ( $info['credits'] as $credit ) {
1493 $i++;
1494 if ( $i == 1 ) {
1495 // Extension we want to load
1496 continue;
1497 }
1498 $type = basename( $credit['path'] ) === 'skin.json' ? 'skins' : 'extensions';
1499 $ret['requires'][$type][] = $credit['name'];
1500 }
1501 $credits = array_values( $info['credits'] )[0];
1502 if ( isset( $credits['url'] ) ) {
1503 $ret['url'] = $credits['url'];
1504 }
1505 $ret['type'] = $credits['type'];
1506
1507 return Status::newGood( $ret );
1508 }
1509
1510 /**
1511 * Returns a default value to be used for $wgDefaultSkin: normally the DefaultSkin from
1512 * config-schema.yaml, but will fall back to another if the default skin is missing
1513 * and some other one is present instead.
1514 *
1515 * @param string[] $skinNames Names of installed skins.
1516 * @return string
1517 */
1518 public function getDefaultSkin( array $skinNames ) {
1519 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1520
1521 if ( in_array( 'vector', $skinNames ) ) {
1522 $skinNames[] = 'vector-2022';
1523 }
1524
1525 // T346332: Minerva skin uses different name from its directory name
1526 if ( in_array( 'minervaneue', $skinNames ) ) {
1527 $minervaNeue = array_search( 'minervaneue', $skinNames );
1528 $skinNames[$minervaNeue] = 'minerva';
1529 }
1530
1531 if ( !$skinNames || in_array( $defaultSkin, $skinNames ) ) {
1532 return $defaultSkin;
1533 } else {
1534 return $skinNames[0];
1535 }
1536 }
1537
1538 /**
1539 * Installs the auto-detected extensions.
1540 *
1541 * @return Status
1542 */
1543 protected function includeExtensions() {
1544 // Marker for DatabaseUpdater::loadExtensions so we don't
1545 // double load extensions
1546 define( 'MW_EXTENSIONS_LOADED', true );
1547
1548 $legacySchemaHooks = $this->getAutoExtensionLegacyHooks();
1549 $data = $this->getAutoExtensionData();
1550 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1551 $legacySchemaHooks = array_merge( $legacySchemaHooks,
1552 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] );
1553 }
1554 $extDeprecatedHooks = $data['attributes']['DeprecatedHooks'] ?? [];
1555
1556 $this->autoExtensionHookContainer = new HookContainer(
1557 new StaticHookRegistry(
1558 [ 'LoadExtensionSchemaUpdates' => $legacySchemaHooks ],
1559 $data['attributes']['Hooks'] ?? [],
1560 $extDeprecatedHooks
1561 ),
1562 MediaWikiServices::getInstance()->getObjectFactory()
1563 );
1564 $this->virtualDomains = $data['attributes']['DatabaseVirtualDomains'] ?? [];
1565
1566 return Status::newGood();
1567 }
1568
1569 /**
1570 * Auto-detect extensions with an old style .php registration file, load
1571 * the extensions, and return the merged $wgHooks array.
1572 *
1573 * @suppress SecurityCheck-PathTraversal It thinks $exts/$IP is user controlled but they are not.
1574 * @return array
1575 */
1576 protected function getAutoExtensionLegacyHooks() {
1577 $exts = $this->getVar( '_Extensions' );
1578 $installPath = $this->getVar( 'IP' );
1579 $files = [];
1580 foreach ( $exts as $e ) {
1581 if ( file_exists( "$installPath/extensions/$e/$e.php" ) ) {
1582 $files[] = "$installPath/extensions/$e/$e.php";
1583 }
1584 }
1585
1586 if ( $files ) {
1587 return $this->includeExtensionFiles( $files );
1588 } else {
1589 return [];
1590 }
1591 }
1592
1593 /**
1594 * Include the specified extension PHP files. Populate $wgAutoloadClasses
1595 * and return the LoadExtensionSchemaUpdates hooks.
1596 *
1597 * @param string[] $files
1598 * @return array LoadExtensionSchemaUpdates legacy hooks
1599 */
1600 protected function includeExtensionFiles( $files ) {
1601 global $IP;
1602 $IP = $this->getVar( 'IP' );
1603
1604 /**
1605 * We need to define the $wgXyz variables before including extensions to avoid
1606 * warnings about unset variables. However, the only thing we really
1607 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1608 * if the extension has hidden hook registration in $wgExtensionFunctions,
1609 * but we're not opening that can of worms
1610 * @see https://phabricator.wikimedia.org/T28857
1611 */
1612 // Extract the defaults into the current scope
1613 foreach ( MainConfigSchema::listDefaultValues( 'wg' ) as $var => $value ) {
1614 $$var = $value;
1615 }
1616
1617 // phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables
1618 global $wgAutoloadClasses, $wgExtensionDirectory, $wgStyleDirectory;
1619 $wgExtensionDirectory = "$IP/extensions";
1620 $wgStyleDirectory = "$IP/skins";
1621
1622 foreach ( $files as $file ) {
1623 require_once $file;
1624 }
1625
1626 // @phpcs:disable MediaWiki.VariableAnalysis.MisleadingGlobalNames.Misleading$wgHooks
1627 // @phpcs:ignore Generic.Files.LineLength.TooLong
1628 // @phan-suppress-next-line PhanUndeclaredVariable,PhanCoalescingAlwaysNull $wgHooks is defined by MainConfigSchema
1629 $hooksWeWant = $wgHooks['LoadExtensionSchemaUpdates'] ?? [];
1630 // @phpcs:enable MediaWiki.VariableAnalysis.MisleadingGlobalNames.Misleading$wgHooks
1631
1632 // Ignore everyone else's hooks. Lord knows what someone might be doing
1633 // in ParserFirstCallInit (see T29171)
1634 return [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1635 }
1636
1637 /**
1638 * Auto-detect extensions with an extension.json file. Load the extensions,
1639 * register classes with the autoloader and return the merged registry data.
1640 *
1641 * @return array
1642 */
1643 protected function getAutoExtensionData() {
1644 $exts = $this->getVar( '_Extensions' );
1645 $installPath = $this->getVar( 'IP' );
1646
1647 $extensionProcessor = new ExtensionProcessor();
1648 foreach ( $exts as $e ) {
1649 $jsonPath = "$installPath/extensions/$e/extension.json";
1650 if ( file_exists( $jsonPath ) ) {
1651 $extensionProcessor->extractInfoFromFile( $jsonPath );
1652 }
1653 }
1654
1655 $autoload = $extensionProcessor->getExtractedAutoloadInfo();
1656 AutoLoader::loadFiles( $autoload['files'] );
1657 AutoLoader::registerClasses( $autoload['classes'] );
1658 AutoLoader::registerNamespaces( $autoload['namespaces'] );
1659
1660 return $extensionProcessor->getExtractedInfo();
1661 }
1662
1663 /**
1664 * Get the hook container previously populated by includeExtensions().
1665 *
1666 * @internal For use by DatabaseInstaller
1667 * @since 1.36
1668 * @return HookContainer
1669 */
1670 public function getAutoExtensionHookContainer() {
1671 if ( !$this->autoExtensionHookContainer ) {
1672 throw new LogicException( __METHOD__ .
1673 ': includeExtensions() has not been called' );
1674 }
1675 return $this->autoExtensionHookContainer;
1676 }
1677
1678 /**
1679 * Get the virtual domains
1680 *
1681 * @internal For use by DatabaseInstaller
1682 * @since 1.42
1683 * @return array
1684 */
1685 public function getVirtualDomains(): array {
1686 return $this->virtualDomains;
1687 }
1688
1689 /**
1690 * Get an array of install steps. Should always be in the format of
1691 * [
1692 * 'name' => 'someuniquename',
1693 * 'callback' => [ $obj, 'method' ],
1694 * ]
1695 * There must be a config-install-$name message defined per step, which will
1696 * be shown on install.
1697 *
1698 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1699 * @return array[]
1700 * @phan-return array<int,array{name:string,callback:array{0:object,1:string}}>
1701 */
1702 protected function getInstallSteps( DatabaseInstaller $installer ) {
1703 $coreInstallSteps = [
1704 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1705 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1706 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1707 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1708 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1709 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1710 [ 'name' => 'restore-services', 'callback' => [ $this, 'restoreServices' ] ],
1711 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1712 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1713 ];
1714
1715 // Build the array of install steps starting from the core install list,
1716 // then adding any callbacks that wanted to attach after a given step
1717 foreach ( $coreInstallSteps as $step ) {
1718 $this->installSteps[] = $step;
1719 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1720 $this->installSteps = array_merge(
1721 $this->installSteps,
1722 $this->extraInstallSteps[$step['name']]
1723 );
1724 }
1725 }
1726
1727 // Prepend any steps that want to be at the beginning
1728 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1729 $this->installSteps = array_merge(
1730 $this->extraInstallSteps['BEGINNING'],
1731 $this->installSteps
1732 );
1733 }
1734
1735 // Extensions should always go first, chance to tie into hooks and such
1736 if ( count( $this->getVar( '_Extensions' ) ) ) {
1737 array_unshift( $this->installSteps,
1738 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1739 );
1740 $this->installSteps[] = [
1741 'name' => 'extension-tables',
1742 'callback' => [ $installer, 'createExtensionTables' ]
1743 ];
1744 }
1745
1746 return $this->installSteps;
1747 }
1748
1749 /**
1750 * Actually perform the installation.
1751 *
1752 * @param callable $startCB A callback array for the beginning of each step
1753 * @param callable $endCB A callback array for the end of each step
1754 *
1755 * @return Status[]
1756 */
1757 public function performInstallation( $startCB, $endCB ) {
1758 $installResults = [];
1759 $installer = $this->getDBInstaller();
1760 $installer->preInstall();
1761 $steps = $this->getInstallSteps( $installer );
1762 foreach ( $steps as $stepObj ) {
1763 $name = $stepObj['name'];
1764 call_user_func_array( $startCB, [ $name ] );
1765
1766 // Perform the callback step
1767 $status = call_user_func( $stepObj['callback'], $installer );
1768
1769 // Output and save the results
1770 call_user_func( $endCB, $name, $status );
1771 $installResults[$name] = $status;
1772
1773 // If we've hit some sort of fatal, we need to bail.
1774 // Callback already had a chance to do output above.
1775 if ( !$status->isOK() ) {
1776 break;
1777 }
1778 }
1779 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
1780 // $steps has at least one element and that defines $status
1781 if ( $status->isOK() ) {
1782 $this->showSuccess(
1783 'config-install-db-success'
1784 );
1785 $this->setVar( '_InstallDone', true );
1786 }
1787
1788 return $installResults;
1789 }
1790
1791 /**
1792 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1793 *
1794 * @return Status
1795 */
1796 public function generateKeys() {
1797 $keys = [ 'wgSecretKey' => 64 ];
1798 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1799 $keys['wgUpgradeKey'] = 16;
1800 }
1801
1802 return $this->doGenerateKeys( $keys );
1803 }
1804
1805 /**
1806 * Restore services that have been redefined in the early stage of installation
1807 * @return Status
1808 */
1809 public function restoreServices() {
1810 // Apply wgServer, so it's available for database initialization hooks.
1811 $urlOptions = [
1812 UrlUtils::SERVER => $GLOBALS['wgServer'],
1813 ];
1814
1815 $connection = $this->getDBInstaller()
1816 ->definitelyGetConnection( DatabaseInstaller::CONN_CREATE_TABLES );
1817 $virtualDomains = array_merge(
1818 $this->getVirtualDomains(),
1819 MWLBFactory::CORE_VIRTUAL_DOMAINS
1820 );
1821
1822 $this->resetMediaWikiServices( null, [
1823 'DBLoadBalancerFactory' => static function () use ( $virtualDomains, $connection ) {
1824 return LBFactorySingle::newFromConnection(
1825 $connection,
1826 [ 'virtualDomains' => $virtualDomains ]
1827 );
1828 },
1829 'UrlUtils' => static function ( MediaWikiServices $services ) use ( $urlOptions ) {
1830 return new UrlUtils( $urlOptions );
1831 },
1832 'UserOptionsLookup' => static function ( MediaWikiServices $services ) {
1833 return $services->get( 'UserOptionsManager' );
1834 },
1835 ] );
1836 return Status::newGood();
1837 }
1838
1839 /**
1840 * Generate a secret value for variables using a secure generator.
1841 *
1842 * @param array $keys
1843 * @return Status
1844 */
1845 protected function doGenerateKeys( $keys ) {
1846 foreach ( $keys as $name => $length ) {
1847 $secretKey = MWCryptRand::generateHex( $length );
1848 $this->setVar( $name, $secretKey );
1849 }
1850 return Status::newGood();
1851 }
1852
1853 /**
1854 * Create the first user account, grant it sysop, bureaucrat and interface-admin rights
1855 *
1856 * @return Status
1857 */
1858 protected function createSysop() {
1859 $name = $this->getVar( '_AdminName' );
1860 $user = User::newFromName( $name );
1861
1862 if ( !$user ) {
1863 // We should've validated this earlier anyway!
1864 return Status::newFatal( 'config-admin-error-user', $name );
1865 }
1866
1867 if ( $user->idForName() == 0 ) {
1868 $user->addToDatabase();
1869
1870 $password = $this->getVar( '_AdminPassword' );
1871 $status = $user->changeAuthenticationData( [
1872 'username' => $user->getName(),
1873 'password' => $password,
1874 'retype' => $password,
1875 ] );
1876 if ( !$status->isGood() ) {
1877 return Status::newFatal( 'config-admin-error-password',
1878 $name, $status->getWikiText( false, false, $this->getVar( '_UserLang' ) ) );
1879 }
1880
1881 $userGroupManager = MediaWikiServices::getInstance()->getUserGroupManager();
1882 $userGroupManager->addUserToGroup( $user, 'sysop' );
1883 $userGroupManager->addUserToGroup( $user, 'bureaucrat' );
1884 $userGroupManager->addUserToGroup( $user, 'interface-admin' );
1885 if ( $this->getVar( '_AdminEmail' ) ) {
1886 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1887 }
1888 $user->saveSettings();
1889
1890 // Update user count
1891 $ssUpdate = SiteStatsUpdate::factory( [ 'users' => 1 ] );
1892 $ssUpdate->doUpdate();
1893 }
1894
1895 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1896 return $this->subscribeToMediaWikiAnnounce();
1897 }
1898 return Status::newGood();
1899 }
1900
1901 /**
1902 * @return Status
1903 */
1904 private function subscribeToMediaWikiAnnounce() {
1905 $status = Status::newGood();
1906 $http = MediaWikiServices::getInstance()->getHttpRequestFactory();
1907 if ( !$http->canMakeRequests() ) {
1908 $status->warning( 'config-install-subscribe-fail',
1909 wfMessage( 'config-install-subscribe-notpossible' ) );
1910 return $status;
1911 }
1912
1913 // Create subscription request
1914 $params = [ 'email' => $this->getVar( '_AdminEmail' ) ];
1915 $req = $http->create( self::MEDIAWIKI_ANNOUNCE_URL . 'anonymous_subscribe',
1916 [ 'method' => 'POST', 'postData' => $params ], __METHOD__ );
1917
1918 // Add headers needed to pass Django's CSRF checks
1919 $token = str_repeat( 'a', 64 );
1920 $req->setHeader( 'Referer', self::MEDIAWIKI_ANNOUNCE_URL );
1921 $req->setHeader( 'Cookie', "csrftoken=$token" );
1922 $req->setHeader( 'X-CSRFToken', $token );
1923
1924 // Send subscription request
1925 $reqStatus = $req->execute();
1926 if ( !$reqStatus->isOK() ) {
1927 $status->warning( 'config-install-subscribe-fail',
1928 Status::wrap( $reqStatus )->getMessage() );
1929 return $status;
1930 }
1931
1932 // Was the request submitted successfully?
1933 // The status message is displayed after a redirect, using Django's messages
1934 // framework, so load the list summary page and look for the expected text.
1935 // (Though parsing the cookie set by the framework may be possible, it isn't
1936 // simple, since the format of the cookie has changed between versions.)
1937 $checkReq = $http->create( self::MEDIAWIKI_ANNOUNCE_URL, [], __METHOD__ );
1938 $checkReq->setCookieJar( $req->getCookieJar() );
1939 if ( !$checkReq->execute()->isOK() ) {
1940 $status->warning( 'config-install-subscribe-possiblefail' );
1941 return $status;
1942 }
1943 $html = $checkReq->getContent();
1944 if ( strpos( $html, 'Please check your inbox for further instructions' ) !== false ) {
1945 // Success
1946 } elseif ( strpos( $html, 'Member already subscribed' ) !== false ) {
1947 $status->warning( 'config-install-subscribe-alreadysubscribed' );
1948 } elseif ( strpos( $html, 'Subscription request already pending' ) !== false ) {
1949 $status->warning( 'config-install-subscribe-alreadypending' );
1950 } else {
1951 $status->warning( 'config-install-subscribe-possiblefail' );
1952 }
1953 return $status;
1954 }
1955
1956 /**
1957 * Insert Main Page with default content.
1958 *
1959 * @param DatabaseInstaller $installer
1960 * @return Status
1961 */
1962 protected function createMainpage( DatabaseInstaller $installer ) {
1963 $status = Status::newGood();
1964 $title = Title::newMainPage();
1965 if ( $title->exists() ) {
1966 $status->warning( 'config-install-mainpage-exists' );
1967 return $status;
1968 }
1969 try {
1970 $page = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $title );
1971 $content = new WikitextContent(
1972 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1973 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1974 );
1975
1976 $status = $page->doUserEditContent(
1977 $content,
1978 User::newSystemUser( 'MediaWiki default' ),
1979 '',
1980 EDIT_NEW
1981 );
1982 } catch ( Exception $e ) {
1983 // using raw, because $wgShowExceptionDetails can not be set yet
1984 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1985 }
1986
1987 return $status;
1988 }
1989
1990 /**
1991 * Override the necessary bits of the config to run an installation.
1992 *
1993 * @param SettingsBuilder $settings
1994 */
1995 public static function overrideConfig( SettingsBuilder $settings ) {
1996 // Use PHP's built-in session handling, since MediaWiki's
1997 // SessionHandler can't work before we have an object cache set up.
1998 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
1999 define( 'MW_NO_SESSION_HANDLER', 1 );
2000 }
2001
2002 $settings->overrideConfigValues( [
2003
2004 // Don't access the database
2005 MainConfigNames::UseDatabaseMessages => false,
2006
2007 // Don't cache langconv tables
2008 MainConfigNames::LanguageConverterCacheType => CACHE_NONE,
2009
2010 // Don't try to cache ResourceLoader dependencies in the database
2011 MainConfigNames::ResourceLoaderUseObjectCacheForDeps => true,
2012
2013 // Debug-friendly
2014 MainConfigNames::ShowExceptionDetails => true,
2015 MainConfigNames::ShowHostnames => true,
2016
2017 // Don't break forms
2018 MainConfigNames::ExternalLinkTarget => '_blank',
2019
2020 // Allow multiple ob_flush() calls
2021 MainConfigNames::DisableOutputCompression => true,
2022
2023 // Use a sensible cookie prefix (not my_wiki)
2024 MainConfigNames::CookiePrefix => 'mw_installer',
2025
2026 // Some of the environment checks make shell requests, remove limits
2027 MainConfigNames::MaxShellMemory => 0,
2028
2029 // Override the default CookieSessionProvider with a dummy
2030 // implementation that won't stomp on PHP's cookies.
2031 MainConfigNames::SessionProviders => [
2032 [
2033 'class' => InstallerSessionProvider::class,
2034 'args' => [ [
2035 'priority' => 1,
2036 ] ]
2037 ]
2038 ],
2039
2040 // Don't use the DB as the main stash
2041 MainConfigNames::MainStash => CACHE_NONE,
2042
2043 // Don't try to use any object cache for SessionManager either.
2044 MainConfigNames::SessionCacheType => CACHE_NONE,
2045
2046 // Set a dummy $wgServer to bypass the check in Setup.php, the
2047 // web installer will automatically detect it and not use this value.
2048 MainConfigNames::Server => 'https://🌻.invalid',
2049 ] );
2050 }
2051
2052 /**
2053 * Add an installation step following the given step.
2054 *
2055 * @param array $callback A valid installation callback array, in this form:
2056 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
2057 * @param string $findStep The step to find. Omit to put the step at the beginning
2058 */
2059 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
2060 $this->extraInstallSteps[$findStep][] = $callback;
2061 }
2062
2063 /**
2064 * Disable the time limit for execution.
2065 * Some long-running pages (Install, Upgrade) will want to do this
2066 */
2067 protected function disableTimeLimit() {
2068 AtEase::suppressWarnings();
2069 set_time_limit( 0 );
2070 AtEase::restoreWarnings();
2071 }
2072 }