3 * Base code for MediaWiki installer.
5 * DO NOT PATCH THIS FILE IF YOU NEED TO CHANGE INSTALLER BEHAVIOR IN YOUR PACKAGE!
6 * See mw-config/overrides/README for details.
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.
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.
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
27 use MediaWiki\Interwiki\NullInterwikiLookup
;
28 use MediaWiki\MediaWikiServices
;
29 use MediaWiki\Shell\Shell
;
32 * This documentation group collects source code files with deployment functionality.
34 * @defgroup Deployment Deployment
38 * Base installer class.
40 * This class provides the base for installation and update functionality
41 * for both MediaWiki core and extensions.
46 abstract class Installer
{
49 * The oldest version of PCRE we can support.
51 * Defining this is necessary because PHP may be linked with a system version
52 * of PCRE, which may be older than that bundled with the minimum PHP version.
54 const MINIMUM_PCRE_VERSION
= '7.2';
62 * List of detected DBs, access using getCompiledDBs().
66 protected $compiledDBs;
69 * Cached DB installer instances, access using getDBInstaller().
73 protected $dbInstallers = [];
76 * Minimum memory size in MB.
80 protected $minMemorySize = 50;
83 * Cached Title, used by parse().
87 protected $parserTitle;
90 * Cached ParserOptions, used by parse().
94 protected $parserOptions;
97 * Known database types. These correspond to the class names <type>Installer,
98 * and are also MediaWiki database types valid for $wgDBtype.
100 * To add a new type, create a <type>Installer class and a Database<type>
101 * class, and add a config-type-<type> message to MessagesEn.php.
105 protected static $dbTypes = [
114 * A list of environment check methods called by doEnvironmentChecks().
115 * These may output warnings using showMessage(), and/or abort the
116 * installation process by returning false.
118 * For the WebInstaller these are only called on the Welcome page,
119 * if these methods have side-effects that should affect later page loads
120 * (as well as the generated stylesheet), use envPreps instead.
124 protected $envChecks = [
130 'envCheckModSecurity',
136 'envCheckShellLocale',
137 'envCheckUploadsDirectory',
139 'envCheckSuhosinMaxValueLength',
144 * A list of environment preparation methods called by doEnvironmentPreps().
148 protected $envPreps = [
154 * MediaWiki configuration globals that will eventually be passed through
155 * to LocalSettings.php. The names only are given here, the defaults
156 * typically come from DefaultSettings.php.
160 protected $defaultVarNames = [
171 'wgEmailAuthentication',
175 'wgImageMagickConvertCommand',
180 'wgDeletedDirectory',
184 'wgUseInstantCommons',
191 * Variables that are stored alongside globals, and are used for any
192 * configuration of the installation process aside from the MediaWiki
193 * configuration. Map of names to defaults.
197 protected $internalDefaults = [
199 '_Environment' => false,
200 '_RaiseMemory' => false,
201 '_UpgradeDone' => false,
202 '_InstallDone' => false,
204 '_InstallPassword' => '',
205 '_SameAccount' => true,
206 '_CreateDBAccount' => false,
207 '_NamespaceType' => 'site-name',
208 '_AdminName' => '', // will be set later, when the user selects language
209 '_AdminPassword' => '',
210 '_AdminPasswordConfirm' => '',
212 '_Subscribe' => false,
213 '_SkipOptional' => 'continue',
214 '_RightsProfile' => 'wiki',
215 '_LicenseCode' => 'none',
219 '_MemCachedServers' => '',
220 '_UpgradeKeySupplied' => false,
221 '_ExistingDBSettings' => false,
223 // $wgLogo is probably wrong (T50084); set something that will work.
224 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
225 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
226 'wgAuthenticationTokenVersion' => 1,
230 * The actual list of installation steps. This will be initialized by getInstallSteps()
234 private $installSteps = [];
237 * Extra steps for installation, for things like DatabaseInstallers to modify
241 protected $extraInstallSteps = [];
244 * Known object cache types and the functions used to test for their existence.
248 protected $objectCaches = [
249 'apc' => 'apc_fetch',
250 'apcu' => 'apcu_fetch',
251 'wincache' => 'wincache_ucache_get'
255 * User rights profiles.
259 public $rightsProfiles = [
262 '*' => [ 'edit' => false ]
266 'createaccount' => false,
272 'createaccount' => false,
286 'url' => 'https://creativecommons.org/licenses/by/4.0/',
287 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
290 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
291 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
294 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
295 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
298 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
299 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
302 'url' => 'https://www.gnu.org/copyleft/fdl.html',
303 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
311 // Details will be filled in by the selector.
319 * URL to mediawiki-announce subscription
321 protected $mediaWikiAnnounceUrl =
322 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
325 * Supported language codes for Mailman
327 protected $mediaWikiAnnounceLanguages = [
328 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
329 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
330 'sl', 'sr', 'sv', 'tr', 'uk'
334 * UI interface for displaying a short message
335 * The parameters are like parameters to wfMessage().
336 * The messages will be in wikitext format, which will be converted to an
337 * output format such as HTML or text before being sent to the user.
339 * @param mixed ...$params
341 abstract public function showMessage( $msg, ...$params );
344 * Same as showMessage(), but for displaying errors
346 * @param mixed ...$params
348 abstract public function showError( $msg, ...$params );
351 * Show a message to the installing user by using a Status object
352 * @param Status $status
354 abstract public function showStatusMessage( Status
$status );
357 * Constructs a Config object that contains configuration settings that should be
358 * overwritten for the installation process.
362 * @param Config $baseConfig
364 * @return Config The config to use during installation.
366 public static function getInstallerConfig( Config
$baseConfig ) {
367 $configOverrides = new HashConfig();
369 // disable (problematic) object cache types explicitly, preserving all other (working) ones
371 $emptyCache = [ 'class' => EmptyBagOStuff
::class ];
374 CACHE_NONE
=> $emptyCache,
375 CACHE_DB
=> $emptyCache,
376 CACHE_ANYTHING
=> $emptyCache,
377 CACHE_MEMCACHED
=> $emptyCache,
378 ] +
$baseConfig->get( 'ObjectCaches' );
380 $configOverrides->set( 'ObjectCaches', $objectCaches );
382 // Load the installer's i18n.
383 $messageDirs = $baseConfig->get( 'MessagesDirs' );
384 $messageDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
386 $configOverrides->set( 'MessagesDirs', $messageDirs );
388 $installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
390 // make sure we use the installer config as the main config
391 $configRegistry = $baseConfig->get( 'ConfigRegistry' );
392 $configRegistry['main'] = function () use ( $installerConfig ) {
393 return $installerConfig;
396 $configOverrides->set( 'ConfigRegistry', $configRegistry );
398 return $installerConfig;
402 * Constructor, always call this from child classes.
404 public function __construct() {
405 global $wgMemc, $wgUser, $wgObjectCaches;
407 $defaultConfig = new GlobalVarConfig(); // all the stuff from DefaultSettings.php
408 $installerConfig = self
::getInstallerConfig( $defaultConfig );
410 // Reset all services and inject config overrides
411 MediaWikiServices
::resetGlobalInstance( $installerConfig );
413 // Don't attempt to load user language options (T126177)
414 // This will be overridden in the web installer with the user-specified language
415 RequestContext
::getMain()->setLanguage( 'en' );
417 // Disable the i18n cache
418 // TODO: manage LocalisationCache singleton in MediaWikiServices
419 Language
::getLocalisationCache()->disableBackend();
421 // Disable all global services, since we don't have any configuration yet!
422 MediaWikiServices
::disableStorageBackend();
424 $mwServices = MediaWikiServices
::getInstance();
425 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
426 // SqlBagOStuff will then throw since we just disabled wfGetDB)
427 $wgObjectCaches = $mwServices->getMainConfig()->get( 'ObjectCaches' );
428 $wgMemc = ObjectCache
::getInstance( CACHE_NONE
);
430 // Disable interwiki lookup, to avoid database access during parses
431 $mwServices->redefineService( 'InterwikiLookup', function () {
432 return new NullInterwikiLookup();
435 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
436 $wgUser = User
::newFromId( 0 );
437 RequestContext
::getMain()->setUser( $wgUser );
439 $this->settings
= $this->internalDefaults
;
441 foreach ( $this->defaultVarNames
as $var ) {
442 $this->settings
[$var] = $GLOBALS[$var];
445 $this->doEnvironmentPreps();
447 $this->compiledDBs
= [];
448 foreach ( self
::getDBTypes() as $type ) {
449 $installer = $this->getDBInstaller( $type );
451 if ( !$installer->isCompiled() ) {
454 $this->compiledDBs
[] = $type;
457 $this->parserTitle
= Title
::newFromText( 'Installer' );
458 $this->parserOptions
= new ParserOptions( $wgUser ); // language will be wrong :(
459 $this->parserOptions
->setTidy( true );
460 // Don't try to access DB before user language is initialised
461 $this->setParserLanguage( Language
::factory( 'en' ) );
465 * Get a list of known DB types.
469 public static function getDBTypes() {
470 return self
::$dbTypes;
474 * Do initial checks of the PHP environment. Set variables according to
475 * the observed environment.
477 * It's possible that this may be called under the CLI SAPI, not the SAPI
478 * that the wiki will primarily run under. In that case, the subclass should
479 * initialise variables such as wgScriptPath, before calling this function.
481 * Under the web subclass, it can already be assumed that PHP 5+ is in use
482 * and that sessions are working.
486 public function doEnvironmentChecks() {
487 // Php version has already been checked by entry scripts
488 // Show message here for information purposes
490 $this->showMessage( 'config-env-hhvm', HHVM_VERSION
);
492 $this->showMessage( 'config-env-php', PHP_VERSION
);
496 // Must go here because an old version of PCRE can prevent other checks from completing
497 $pcreVersion = explode( ' ', PCRE_VERSION
, 2 )[0];
498 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
499 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
502 foreach ( $this->envChecks
as $check ) {
503 $status = $this->$check();
504 if ( $status === false ) {
510 $this->setVar( '_Environment', $good );
512 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
515 public function doEnvironmentPreps() {
516 foreach ( $this->envPreps
as $prep ) {
522 * Set a MW configuration variable, or internal installer configuration variable.
524 * @param string $name
525 * @param mixed $value
527 public function setVar( $name, $value ) {
528 $this->settings
[$name] = $value;
532 * Get an MW configuration variable, or internal installer configuration variable.
533 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
534 * Installer variables are typically prefixed by an underscore.
536 * @param string $name
537 * @param mixed|null $default
541 public function getVar( $name, $default = null ) {
542 return $this->settings
[$name] ??
$default;
546 * Get a list of DBs supported by current PHP setup
550 public function getCompiledDBs() {
551 return $this->compiledDBs
;
555 * Get the DatabaseInstaller class name for this type
557 * @param string $type database type ($wgDBtype)
558 * @return string Class name
561 public static function getDBInstallerClass( $type ) {
562 return ucfirst( $type ) . 'Installer';
566 * Get an instance of DatabaseInstaller for the specified DB type.
568 * @param mixed $type DB installer for which is needed, false to use default.
570 * @return DatabaseInstaller
572 public function getDBInstaller( $type = false ) {
574 $type = $this->getVar( 'wgDBtype' );
577 $type = strtolower( $type );
579 if ( !isset( $this->dbInstallers
[$type] ) ) {
580 $class = self
::getDBInstallerClass( $type );
581 $this->dbInstallers
[$type] = new $class( $this );
584 return $this->dbInstallers
[$type];
588 * Determine if LocalSettings.php exists. If it does, return its variables.
590 * @return array|false
592 public static function getExistingLocalSettings() {
595 // You might be wondering why this is here. Well if you don't do this
596 // then some poorly-formed extensions try to call their own classes
597 // after immediately registering them. We really need to get extension
598 // registration out of the global scope and into a real format.
599 // @see https://phabricator.wikimedia.org/T69440
600 global $wgAutoloadClasses;
601 $wgAutoloadClasses = [];
603 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
604 // Define the required globals here, to ensure, the functions can do it work correctly.
605 // phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables
606 global $wgExtensionDirectory, $wgStyleDirectory;
608 Wikimedia\
suppressWarnings();
609 $_lsExists = file_exists( "$IP/LocalSettings.php" );
610 Wikimedia\restoreWarnings
();
617 require "$IP/includes/DefaultSettings.php";
618 require "$IP/LocalSettings.php";
620 return get_defined_vars();
624 * Get a fake password for sending back to the user in HTML.
625 * This is a security mechanism to avoid compromise of the password in the
626 * event of session ID compromise.
628 * @param string $realPassword
632 public function getFakePassword( $realPassword ) {
633 return str_repeat( '*', strlen( $realPassword ) );
637 * Set a variable which stores a password, except if the new value is a
638 * fake password in which case leave it as it is.
640 * @param string $name
641 * @param mixed $value
643 public function setPassword( $name, $value ) {
644 if ( !preg_match( '/^\*+$/', $value ) ) {
645 $this->setVar( $name, $value );
650 * On POSIX systems return the primary group of the webserver we're running under.
651 * On other systems just returns null.
653 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
654 * webserver user before he can install.
656 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
660 public static function maybeGetWebserverPrimaryGroup() {
661 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
662 # I don't know this, this isn't UNIX.
666 # posix_getegid() *not* getmygid() because we want the group of the webserver,
667 # not whoever owns the current script.
668 $gid = posix_getegid();
669 $group = posix_getpwuid( $gid )['name'];
675 * Convert wikitext $text to HTML.
677 * This is potentially error prone since many parser features require a complete
678 * installed MW database. The solution is to just not use those features when you
679 * write your messages. This appears to work well enough. Basic formatting and
680 * external links work just fine.
682 * But in case a translator decides to throw in a "#ifexist" or internal link or
683 * whatever, this function is guarded to catch the attempted DB access and to present
684 * some fallback text.
686 * @param string $text
687 * @param bool $lineStart
690 public function parse( $text, $lineStart = false ) {
691 $parser = MediaWikiServices
::getInstance()->getParser();
694 $out = $parser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
695 $html = $out->getText( [
696 'enableSectionEditLinks' => false,
699 $html = Parser
::stripOuterParagraph( $html );
700 } catch ( Wikimedia\Services\ServiceDisabledException
$e ) {
701 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
708 * @return ParserOptions
710 public function getParserOptions() {
711 return $this->parserOptions
;
714 public function disableLinkPopups() {
715 $this->parserOptions
->setExternalLinkTarget( false );
718 public function restoreLinkPopups() {
719 global $wgExternalLinkTarget;
720 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
724 * Install step which adds a row to the site_stats table with appropriate
727 * @param DatabaseInstaller $installer
731 public function populateSiteStats( DatabaseInstaller
$installer ) {
732 $status = $installer->getConnection();
733 if ( !$status->isOK() ) {
736 $status->value
->insert(
740 'ss_total_edits' => 0,
741 'ss_good_articles' => 0,
742 'ss_total_pages' => 0,
744 'ss_active_users' => 0,
750 return Status
::newGood();
754 * Environment check for DB types.
757 protected function envCheckDB() {
759 /** @var string|null $dbType The user-specified database type */
760 $dbType = $this->getVar( 'wgDBtype' );
764 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
765 // config-type-sqlite
766 foreach ( self
::getDBTypes() as $name ) {
767 $allNames[] = wfMessage( "config-type-$name" )->text();
770 $databases = $this->getCompiledDBs();
772 $databases = array_flip( $databases );
774 foreach ( array_keys( $databases ) as $db ) {
775 $installer = $this->getDBInstaller( $db );
776 $status = $installer->checkPrerequisites();
777 if ( !$status->isGood() ) {
778 if ( !$this instanceof WebInstaller
&& $db === $dbType ) {
779 // Strictly check the key database type instead of just outputting message
780 // Note: No perform this check run from the web installer, since this method always called by
781 // the welcome page under web installation, so $dbType will always be 'mysql'
784 $this->showStatusMessage( $status );
785 unset( $databases[$db] );
788 $databases = array_flip( $databases );
790 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
797 * Some versions of libxml+PHP break < and > encoding horribly
800 protected function envCheckBrokenXML() {
801 $test = new PhpXmlBugTester();
803 $this->showError( 'config-brokenlibxml' );
812 * Environment check for the PCRE module.
814 * @note If this check were to fail, the parser would
815 * probably throw an exception before the result
816 * of this check is shown to the user.
819 protected function envCheckPCRE() {
820 Wikimedia\
suppressWarnings();
821 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
822 // Need to check for \p support too, as PCRE can be compiled
823 // with utf8 support, but not unicode property support.
824 // check that \p{Zs} (space separators) matches
825 // U+3000 (Ideographic space)
826 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\u{3000}-" );
827 Wikimedia\restoreWarnings
();
828 if ( $regexd != '--' ||
$regexprop != '--' ) {
829 $this->showError( 'config-pcre-no-utf8' );
838 * Environment check for available memory.
841 protected function envCheckMemory() {
842 $limit = ini_get( 'memory_limit' );
844 if ( !$limit ||
$limit == -1 ) {
848 $n = wfShorthandToInteger( $limit );
850 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
851 $newLimit = "{$this->minMemorySize}M";
853 if ( ini_set( "memory_limit", $newLimit ) === false ) {
854 $this->showMessage( 'config-memory-bad', $limit );
856 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
857 $this->setVar( '_RaiseMemory', true );
865 * Environment check for compiled object cache types.
867 protected function envCheckCache() {
869 foreach ( $this->objectCaches
as $name => $function ) {
870 if ( function_exists( $function ) ) {
871 $caches[$name] = true;
876 $this->showMessage( 'config-no-cache-apcu' );
879 $this->setVar( '_Caches', $caches );
883 * Scare user to death if they have mod_security or mod_security2
886 protected function envCheckModSecurity() {
887 if ( self
::apacheModulePresent( 'mod_security' )
888 || self
::apacheModulePresent( 'mod_security2' ) ) {
889 $this->showMessage( 'config-mod-security' );
896 * Search for GNU diff3.
899 protected function envCheckDiff3() {
900 $names = [ "gdiff3", "diff3" ];
901 if ( wfIsWindows() ) {
902 $names[] = 'diff3.exe';
904 $versionInfo = [ '--version', 'GNU diffutils' ];
906 $diff3 = ExecutableFinder
::findInDefaultPaths( $names, $versionInfo );
909 $this->setVar( 'wgDiff3', $diff3 );
911 $this->setVar( 'wgDiff3', false );
912 $this->showMessage( 'config-diff3-bad' );
919 * Environment check for ImageMagick and GD.
922 protected function envCheckGraphics() {
923 $names = wfIsWindows() ?
'convert.exe' : 'convert';
924 $versionInfo = [ '-version', 'ImageMagick' ];
925 $convert = ExecutableFinder
::findInDefaultPaths( $names, $versionInfo );
927 $this->setVar( 'wgImageMagickConvertCommand', '' );
929 $this->setVar( 'wgImageMagickConvertCommand', $convert );
930 $this->showMessage( 'config-imagemagick', $convert );
933 } elseif ( function_exists( 'imagejpeg' ) ) {
934 $this->showMessage( 'config-gd' );
936 $this->showMessage( 'config-no-scaling' );
948 protected function envCheckGit() {
949 $names = wfIsWindows() ?
'git.exe' : 'git';
950 $versionInfo = [ '--version', 'git version' ];
952 $git = ExecutableFinder
::findInDefaultPaths( $names, $versionInfo );
955 $this->setVar( 'wgGitBin', $git );
956 $this->showMessage( 'config-git', $git );
958 $this->setVar( 'wgGitBin', false );
959 $this->showMessage( 'config-git-bad' );
966 * Environment check to inform user which server we've assumed.
970 protected function envCheckServer() {
971 $server = $this->envGetDefaultServer();
972 if ( $server !== null ) {
973 $this->showMessage( 'config-using-server', $server );
979 * Environment check to inform user which paths we've assumed.
983 protected function envCheckPath() {
986 $this->getVar( 'wgServer' ),
987 $this->getVar( 'wgScriptPath' )
993 * Environment check for preferred locale in shell
996 protected function envCheckShellLocale() {
997 $os = php_uname( 's' );
998 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
1000 if ( !in_array( $os, $supported ) ) {
1004 if ( Shell
::isDisabled() ) {
1008 # Get a list of available locales.
1009 $result = Shell
::command( '/usr/bin/locale', '-a' )
1012 if ( $result->getExitCode() != 0 ) {
1016 $lines = $result->getStdout();
1017 $lines = array_map( 'trim', explode( "\n", $lines ) );
1018 $candidatesByLocale = [];
1019 $candidatesByLang = [];
1020 foreach ( $lines as $line ) {
1021 if ( $line === '' ) {
1025 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1029 list( , $lang, , , ) = $m;
1031 $candidatesByLocale[$m[0]] = $m;
1032 $candidatesByLang[$lang][] = $m;
1035 # Try the current value of LANG.
1036 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1037 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1042 # Try the most common ones.
1043 $commonLocales = [ 'C.UTF-8', 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1044 foreach ( $commonLocales as $commonLocale ) {
1045 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1046 $this->setVar( 'wgShellLocale', $commonLocale );
1052 # Is there an available locale in the Wiki's language?
1053 $wikiLang = $this->getVar( 'wgLanguageCode' );
1055 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1056 $m = reset( $candidatesByLang[$wikiLang] );
1057 $this->setVar( 'wgShellLocale', $m[0] );
1062 # Are there any at all?
1063 if ( count( $candidatesByLocale ) ) {
1064 $m = reset( $candidatesByLocale );
1065 $this->setVar( 'wgShellLocale', $m[0] );
1075 * Environment check for the permissions of the uploads directory
1078 protected function envCheckUploadsDirectory() {
1081 $dir = $IP . '/images/';
1082 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1083 $safe = !$this->dirIsExecutable( $dir, $url );
1086 $this->showMessage( 'config-uploads-not-safe', $dir );
1093 * Checks if suhosin.get.max_value_length is set, and if so generate
1094 * a warning because it decreases ResourceLoader performance.
1097 protected function envCheckSuhosinMaxValueLength() {
1098 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1099 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1100 // Only warn if the value is below the sane 1024
1101 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1108 * Checks if we're running on 64 bit or not. 32 bit is becoming increasingly
1109 * hard to support, so let's at least warn people.
1113 protected function envCheck64Bit() {
1114 if ( PHP_INT_SIZE
== 4 ) {
1115 $this->showMessage( 'config-using-32bit' );
1122 * Check the libicu version
1124 protected function envCheckLibicu() {
1126 * This needs to be updated something that the latest libicu
1127 * will properly normalize. This normalization was found at
1128 * https://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1129 * Note that we use the hex representation to create the code
1130 * points in order to avoid any Unicode-destroying during transit.
1132 $not_normal_c = "\u{FA6C}";
1133 $normal_c = "\u{242EE}";
1135 $useNormalizer = 'php';
1136 $needsUpdate = false;
1138 if ( function_exists( 'normalizer_normalize' ) ) {
1139 $useNormalizer = 'intl';
1140 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1141 if ( $intl !== $normal_c ) {
1142 $needsUpdate = true;
1146 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1147 if ( $useNormalizer === 'php' ) {
1148 $this->showMessage( 'config-unicode-pure-php-warning' );
1150 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1151 if ( $needsUpdate ) {
1152 $this->showMessage( 'config-unicode-update-warning' );
1158 * Environment prep for the server hostname.
1160 protected function envPrepServer() {
1161 $server = $this->envGetDefaultServer();
1162 if ( $server !== null ) {
1163 $this->setVar( 'wgServer', $server );
1168 * Helper function to be called from envPrepServer()
1171 abstract protected function envGetDefaultServer();
1174 * Environment prep for setting $IP and $wgScriptPath.
1176 protected function envPrepPath() {
1178 $IP = dirname( dirname( __DIR__
) );
1179 $this->setVar( 'IP', $IP );
1183 * Checks if scripts located in the given directory can be executed via the given URL.
1185 * Used only by environment checks.
1186 * @param string $dir
1187 * @param string $url
1188 * @return bool|int|string
1190 public function dirIsExecutable( $dir, $url ) {
1193 "<?php echo 'exec';",
1194 "#!/var/env php\n<?php echo 'exec';",
1198 // it would be good to check other popular languages here, but it'll be slow.
1200 Wikimedia\
suppressWarnings();
1202 foreach ( $scriptTypes as $ext => $contents ) {
1203 foreach ( $contents as $source ) {
1204 $file = 'exectest.' . $ext;
1206 if ( !file_put_contents( $dir . $file, $source ) ) {
1211 $text = MediaWikiServices
::getInstance()->getHttpRequestFactory()->
1212 get( $url . $file, [ 'timeout' => 3 ], __METHOD__
);
1213 } catch ( Exception
$e ) {
1214 // HttpRequestFactory::get can throw with allow_url_fopen = false and no curl
1218 unlink( $dir . $file );
1220 if ( $text == 'exec' ) {
1221 Wikimedia\restoreWarnings
();
1228 Wikimedia\restoreWarnings
();
1234 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1236 * @param string $moduleName Name of module to check.
1239 public static function apacheModulePresent( $moduleName ) {
1240 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1243 // try it the hard way
1245 phpinfo( INFO_MODULES
);
1246 $info = ob_get_clean();
1248 return strpos( $info, $moduleName ) !== false;
1252 * ParserOptions are constructed before we determined the language, so fix it
1254 * @param Language $lang
1256 public function setParserLanguage( $lang ) {
1257 $this->parserOptions
->setTargetLanguage( $lang );
1258 $this->parserOptions
->setUserLang( $lang );
1262 * Overridden by WebInstaller to provide lastPage parameters.
1263 * @param string $page
1266 protected function getDocUrl( $page ) {
1267 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1271 * Find extensions or skins in a subdirectory of $IP.
1272 * Returns an array containing the value for 'Name' for each found extension.
1274 * @param string $directory Directory to search in, relative to $IP, must be either "extensions"
1276 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1278 public function findExtensions( $directory = 'extensions' ) {
1279 switch ( $directory ) {
1281 return $this->findExtensionsByType( 'extension', 'extensions' );
1283 return $this->findExtensionsByType( 'skin', 'skins' );
1285 throw new InvalidArgumentException( "Invalid extension type" );
1290 * Find extensions or skins, and return an array containing the value for 'Name' for each found
1293 * @param string $type Either "extension" or "skin"
1294 * @param string $directory Directory to search in, relative to $IP
1295 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1297 protected function findExtensionsByType( $type = 'extension', $directory = 'extensions' ) {
1298 if ( $this->getVar( 'IP' ) === null ) {
1302 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1303 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1307 $dh = opendir( $extDir );
1309 while ( ( $file = readdir( $dh ) ) !== false ) {
1310 if ( !is_dir( "$extDir/$file" ) ) {
1313 $status = $this->getExtensionInfo( $type, $directory, $file );
1314 if ( $status->isOK() ) {
1315 $exts[$file] = $status->value
;
1319 uksort( $exts, 'strnatcasecmp' );
1325 * @param string $type Either "extension" or "skin"
1326 * @param string $parentRelPath The parent directory relative to $IP
1327 * @param string $name The extension or skin name
1328 * @return Status An object containing an error list. If there were no errors, an associative
1329 * array of information about the extension can be found in $status->value.
1331 protected function getExtensionInfo( $type, $parentRelPath, $name ) {
1332 if ( $this->getVar( 'IP' ) === null ) {
1333 throw new Exception( 'Cannot find extensions since the IP variable is not yet set' );
1335 if ( $type !== 'extension' && $type !== 'skin' ) {
1336 throw new InvalidArgumentException( "Invalid extension type" );
1338 $absDir = $this->getVar( 'IP' ) . "/$parentRelPath/$name";
1339 $relDir = "../$parentRelPath/$name";
1340 if ( !is_dir( $absDir ) ) {
1341 return Status
::newFatal( 'config-extension-not-found', $name );
1343 $jsonFile = $type . '.json';
1344 $fullJsonFile = "$absDir/$jsonFile";
1345 $isJson = file_exists( $fullJsonFile );
1348 // Only fallback to PHP file if JSON doesn't exist
1349 $fullPhpFile = "$absDir/$name.php";
1350 $isPhp = file_exists( $fullPhpFile );
1352 if ( !$isJson && !$isPhp ) {
1353 return Status
::newFatal( 'config-extension-not-found', $name );
1356 // Extension exists. Now see if there are screenshots
1358 if ( is_dir( "$absDir/screenshots" ) ) {
1359 $paths = glob( "$absDir/screenshots/*.png" );
1360 foreach ( $paths as $path ) {
1361 $info['screenshots'][] = str_replace( $absDir, $relDir, $path );
1366 $jsonStatus = $this->readExtension( $fullJsonFile );
1367 if ( !$jsonStatus->isOK() ) {
1370 $info +
= $jsonStatus->value
;
1373 return Status
::newGood( $info );
1377 * @param string $fullJsonFile
1378 * @param array $extDeps
1379 * @param array $skinDeps
1381 * @return Status On success, an array of extension information is in $status->value. On
1382 * failure, the Status object will have an error list.
1384 private function readExtension( $fullJsonFile, $extDeps = [], $skinDeps = [] ) {
1389 $extDir = $this->getVar( 'IP' ) . '/extensions';
1390 foreach ( $extDeps as $dep ) {
1391 $fname = "$extDir/$dep/extension.json";
1392 if ( !file_exists( $fname ) ) {
1393 return Status
::newFatal( 'config-extension-not-found', $dep );
1399 $skinDir = $this->getVar( 'IP' ) . '/skins';
1400 foreach ( $skinDeps as $dep ) {
1401 $fname = "$skinDir/$dep/skin.json";
1402 if ( !file_exists( $fname ) ) {
1403 return Status
::newFatal( 'config-extension-not-found', $dep );
1408 $registry = new ExtensionRegistry();
1410 $info = $registry->readFromQueue( $load );
1411 } catch ( ExtensionDependencyError
$e ) {
1412 if ( $e->incompatibleCore ||
$e->incompatibleSkins
1413 ||
$e->incompatibleExtensions
1415 // If something is incompatible with a dependency, we have no real
1416 // option besides skipping it
1417 return Status
::newFatal( 'config-extension-dependency',
1418 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1419 } elseif ( $e->missingExtensions ||
$e->missingSkins
) {
1420 // There's an extension missing in the dependency tree,
1421 // so add those to the dependency list and try again
1422 return $this->readExtension(
1424 array_merge( $extDeps, $e->missingExtensions
),
1425 array_merge( $skinDeps, $e->missingSkins
)
1428 // Some other kind of dependency error?
1429 return Status
::newFatal( 'config-extension-dependency',
1430 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1433 // The order of credits will be the order of $load,
1434 // so the first extension is the one we want to load,
1435 // everything else is a dependency
1437 foreach ( $info['credits'] as $name => $credit ) {
1440 // Extension we want to load
1443 $type = basename( $credit['path'] ) === 'skin.json' ?
'skins' : 'extensions';
1444 $ret['requires'][$type][] = $credit['name'];
1446 $credits = array_values( $info['credits'] )[0];
1447 if ( isset( $credits['url'] ) ) {
1448 $ret['url'] = $credits['url'];
1450 $ret['type'] = $credits['type'];
1452 return Status
::newGood( $ret );
1456 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1457 * but will fall back to another if the default skin is missing and some other one is present
1460 * @param string[] $skinNames Names of installed skins.
1463 public function getDefaultSkin( array $skinNames ) {
1464 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1465 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1466 return $defaultSkin;
1468 return $skinNames[0];
1473 * Installs the auto-detected extensions.
1475 * @suppress SecurityCheck-OTHER It thinks $exts/$IP is user controlled but they are not.
1478 protected function includeExtensions() {
1480 $exts = $this->getVar( '_Extensions' );
1481 $IP = $this->getVar( 'IP' );
1483 // Marker for DatabaseUpdater::loadExtensions so we don't
1484 // double load extensions
1485 define( 'MW_EXTENSIONS_LOADED', true );
1488 * We need to include DefaultSettings before including extensions to avoid
1489 * warnings about unset variables. However, the only thing we really
1490 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1491 * if the extension has hidden hook registration in $wgExtensionFunctions,
1492 * but we're not opening that can of worms
1493 * @see https://phabricator.wikimedia.org/T28857
1495 global $wgAutoloadClasses;
1496 $wgAutoloadClasses = [];
1499 require "$IP/includes/DefaultSettings.php";
1501 foreach ( $exts as $e ) {
1502 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1503 $queue["$IP/extensions/$e/extension.json"] = 1;
1505 require_once "$IP/extensions/$e/$e.php";
1509 $registry = new ExtensionRegistry();
1510 $data = $registry->readFromQueue( $queue );
1511 $wgAutoloadClasses +
= $data['autoload'];
1513 // @phan-suppress-next-line PhanUndeclaredVariable $wgHooks is set by DefaultSettings
1514 $hooksWeWant = $wgHooks['LoadExtensionSchemaUpdates'] ??
[];
1516 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1517 $hooksWeWant = array_merge_recursive(
1519 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1522 // Unset everyone else's hooks. Lord knows what someone might be doing
1523 // in ParserFirstCallInit (see T29171)
1524 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1526 return Status
::newGood();
1530 * Get an array of install steps. Should always be in the format of
1532 * 'name' => 'someuniquename',
1533 * 'callback' => [ $obj, 'method' ],
1535 * There must be a config-install-$name message defined per step, which will
1536 * be shown on install.
1538 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1541 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1542 $coreInstallSteps = [
1543 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1544 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1545 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1546 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1547 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1548 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1549 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1550 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1553 // Build the array of install steps starting from the core install list,
1554 // then adding any callbacks that wanted to attach after a given step
1555 foreach ( $coreInstallSteps as $step ) {
1556 $this->installSteps
[] = $step;
1557 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1558 $this->installSteps
= array_merge(
1559 $this->installSteps
,
1560 $this->extraInstallSteps
[$step['name']]
1565 // Prepend any steps that want to be at the beginning
1566 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1567 $this->installSteps
= array_merge(
1568 $this->extraInstallSteps
['BEGINNING'],
1573 // Extensions should always go first, chance to tie into hooks and such
1574 if ( count( $this->getVar( '_Extensions' ) ) ) {
1575 array_unshift( $this->installSteps
,
1576 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1578 $this->installSteps
[] = [
1579 'name' => 'extension-tables',
1580 'callback' => [ $installer, 'createExtensionTables' ]
1584 return $this->installSteps
;
1588 * Actually perform the installation.
1590 * @param callable $startCB A callback array for the beginning of each step
1591 * @param callable $endCB A callback array for the end of each step
1593 * @return Status[] Array of Status objects
1595 public function performInstallation( $startCB, $endCB ) {
1596 $installResults = [];
1597 $installer = $this->getDBInstaller();
1598 $installer->preInstall();
1599 $steps = $this->getInstallSteps( $installer );
1600 foreach ( $steps as $stepObj ) {
1601 $name = $stepObj['name'];
1602 call_user_func_array( $startCB, [ $name ] );
1604 // Perform the callback step
1605 $status = call_user_func( $stepObj['callback'], $installer );
1607 // Output and save the results
1608 call_user_func( $endCB, $name, $status );
1609 $installResults[$name] = $status;
1611 // If we've hit some sort of fatal, we need to bail.
1612 // Callback already had a chance to do output above.
1613 if ( !$status->isOk() ) {
1617 if ( $status->isOk() ) {
1619 'config-install-db-success'
1621 $this->setVar( '_InstallDone', true );
1624 return $installResults;
1628 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1632 public function generateKeys() {
1633 $keys = [ 'wgSecretKey' => 64 ];
1634 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1635 $keys['wgUpgradeKey'] = 16;
1638 return $this->doGenerateKeys( $keys );
1642 * Generate a secret value for variables using a secure generator.
1644 * @param array $keys
1647 protected function doGenerateKeys( $keys ) {
1648 $status = Status
::newGood();
1650 foreach ( $keys as $name => $length ) {
1651 $secretKey = MWCryptRand
::generateHex( $length );
1652 $this->setVar( $name, $secretKey );
1659 * Create the first user account, grant it sysop, bureaucrat and interface-admin rights
1663 protected function createSysop() {
1664 $name = $this->getVar( '_AdminName' );
1665 $user = User
::newFromName( $name );
1668 // We should've validated this earlier anyway!
1669 return Status
::newFatal( 'config-admin-error-user', $name );
1672 if ( $user->idForName() == 0 ) {
1673 $user->addToDatabase();
1676 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1677 } catch ( PasswordError
$pwe ) {
1678 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1681 $user->addGroup( 'sysop' );
1682 $user->addGroup( 'bureaucrat' );
1683 $user->addGroup( 'interface-admin' );
1684 if ( $this->getVar( '_AdminEmail' ) ) {
1685 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1687 $user->saveSettings();
1689 // Update user count
1690 $ssUpdate = SiteStatsUpdate
::factory( [ 'users' => 1 ] );
1691 $ssUpdate->doUpdate();
1693 $status = Status
::newGood();
1695 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1696 $this->subscribeToMediaWikiAnnounce( $status );
1705 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1707 'email' => $this->getVar( '_AdminEmail' ),
1712 // Mailman doesn't support as many languages as we do, so check to make
1713 // sure their selected language is available
1714 $myLang = $this->getVar( '_UserLang' );
1715 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1716 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1717 $params['language'] = $myLang;
1720 if ( MWHttpRequest
::canMakeRequests() ) {
1721 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1722 [ 'method' => 'POST', 'postData' => $params ], __METHOD__
)->execute();
1723 if ( !$res->isOK() ) {
1724 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1727 $s->warning( 'config-install-subscribe-notpossible' );
1732 * Insert Main Page with default content.
1734 * @param DatabaseInstaller $installer
1737 protected function createMainpage( DatabaseInstaller
$installer ) {
1738 $status = Status
::newGood();
1739 $title = Title
::newMainPage();
1740 if ( $title->exists() ) {
1741 $status->warning( 'config-install-mainpage-exists' );
1745 $page = WikiPage
::factory( $title );
1746 $content = new WikitextContent(
1747 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1748 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1751 $status = $page->doEditContent( $content,
1755 User
::newFromName( 'MediaWiki default' )
1757 } catch ( Exception
$e ) {
1758 // using raw, because $wgShowExceptionDetails can not be set yet
1759 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1766 * Override the necessary bits of the config to run an installation.
1768 public static function overrideConfig() {
1769 // Use PHP's built-in session handling, since MediaWiki's
1770 // SessionHandler can't work before we have an object cache set up.
1771 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
1772 define( 'MW_NO_SESSION_HANDLER', 1 );
1775 // Don't access the database
1776 $GLOBALS['wgUseDatabaseMessages'] = false;
1777 // Don't cache langconv tables
1778 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1780 $GLOBALS['wgShowExceptionDetails'] = true;
1781 $GLOBALS['wgShowHostnames'] = true;
1782 // Don't break forms
1783 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1785 // Allow multiple ob_flush() calls
1786 $GLOBALS['wgDisableOutputCompression'] = true;
1788 // Use a sensible cookie prefix (not my_wiki)
1789 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1791 // Some of the environment checks make shell requests, remove limits
1792 $GLOBALS['wgMaxShellMemory'] = 0;
1794 // Override the default CookieSessionProvider with a dummy
1795 // implementation that won't stomp on PHP's cookies.
1796 $GLOBALS['wgSessionProviders'] = [
1798 'class' => InstallerSessionProvider
::class,
1805 // Don't try to use any object cache for SessionManager either.
1806 $GLOBALS['wgSessionCacheType'] = CACHE_NONE
;
1810 * Add an installation step following the given step.
1812 * @param array $callback A valid installation callback array, in this form:
1813 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1814 * @param string $findStep The step to find. Omit to put the step at the beginning
1816 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1817 $this->extraInstallSteps
[$findStep][] = $callback;
1821 * Disable the time limit for execution.
1822 * Some long-running pages (Install, Upgrade) will want to do this
1824 protected function disableTimeLimit() {
1825 Wikimedia\
suppressWarnings();
1826 set_time_limit( 0 );
1827 Wikimedia\restoreWarnings
();