3 * Base code for MediaWiki installer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\MediaWikiServices
;
26 * This documentation group collects source code files with deployment functionality.
28 * @defgroup Deployment Deployment
32 * Base installer class.
34 * This class provides the base for installation and update functionality
35 * for both MediaWiki core and extensions.
40 abstract class Installer
{
43 * The oldest version of PCRE we can support.
45 * Defining this is necessary because PHP may be linked with a system version
46 * of PCRE, which may be older than that bundled with the minimum PHP version.
48 const MINIMUM_PCRE_VERSION
= '7.2';
56 * List of detected DBs, access using getCompiledDBs().
60 protected $compiledDBs;
63 * Cached DB installer instances, access using getDBInstaller().
67 protected $dbInstallers = [];
70 * Minimum memory size in MB.
74 protected $minMemorySize = 50;
77 * Cached Title, used by parse().
81 protected $parserTitle;
84 * Cached ParserOptions, used by parse().
88 protected $parserOptions;
91 * Known database types. These correspond to the class names <type>Installer,
92 * and are also MediaWiki database types valid for $wgDBtype.
94 * To add a new type, create a <type>Installer class and a Database<type>
95 * class, and add a config-type-<type> message to MessagesEn.php.
99 protected static $dbTypes = [
108 * A list of environment check methods called by doEnvironmentChecks().
109 * These may output warnings using showMessage(), and/or abort the
110 * installation process by returning false.
112 * For the WebInstaller these are only called on the Welcome page,
113 * if these methods have side-effects that should affect later page loads
114 * (as well as the generated stylesheet), use envPreps instead.
118 protected $envChecks = [
126 'envCheckModSecurity',
132 'envCheckShellLocale',
133 'envCheckUploadsDirectory',
135 'envCheckSuhosinMaxValueLength',
142 * A list of environment preparation methods called by doEnvironmentPreps().
146 protected $envPreps = [
152 * MediaWiki configuration globals that will eventually be passed through
153 * to LocalSettings.php. The names only are given here, the defaults
154 * typically come from DefaultSettings.php.
158 protected $defaultVarNames = [
169 'wgEmailAuthentication',
173 'wgImageMagickConvertCommand',
178 'wgDeletedDirectory',
182 'wgUseInstantCommons',
188 * Variables that are stored alongside globals, and are used for any
189 * configuration of the installation process aside from the MediaWiki
190 * configuration. Map of names to defaults.
194 protected $internalDefaults = [
196 '_Environment' => false,
197 '_RaiseMemory' => false,
198 '_UpgradeDone' => false,
199 '_InstallDone' => false,
201 '_InstallPassword' => '',
202 '_SameAccount' => true,
203 '_CreateDBAccount' => false,
204 '_NamespaceType' => 'site-name',
205 '_AdminName' => '', // will be set later, when the user selects language
206 '_AdminPassword' => '',
207 '_AdminPasswordConfirm' => '',
209 '_Subscribe' => false,
210 '_SkipOptional' => 'continue',
211 '_RightsProfile' => 'wiki',
212 '_LicenseCode' => 'none',
216 '_MemCachedServers' => '',
217 '_UpgradeKeySupplied' => false,
218 '_ExistingDBSettings' => false,
220 // $wgLogo is probably wrong (bug 48084); set something that will work.
221 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
222 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
223 'wgAuthenticationTokenVersion' => 1,
227 * The actual list of installation steps. This will be initialized by getInstallSteps()
231 private $installSteps = [];
234 * Extra steps for installation, for things like DatabaseInstallers to modify
238 protected $extraInstallSteps = [];
241 * Known object cache types and the functions used to test for their existence.
245 protected $objectCaches = [
246 'xcache' => 'xcache_get',
247 'apc' => 'apc_fetch',
248 'wincache' => 'wincache_ucache_get'
252 * User rights profiles.
256 public $rightsProfiles = [
259 '*' => [ 'edit' => false ]
263 'createaccount' => false,
269 'createaccount' => false,
283 'url' => 'https://creativecommons.org/licenses/by/4.0/',
284 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
287 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
288 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
291 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
292 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
295 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
296 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
300 'icon' => '$wgResourceBasePath/resources/assets/licenses/public-domain.png',
303 'url' => 'https://www.gnu.org/copyleft/fdl.html',
304 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
312 // Details will be filled in by the selector.
320 * URL to mediawiki-announce subscription
322 protected $mediaWikiAnnounceUrl =
323 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
326 * Supported language codes for Mailman
328 protected $mediaWikiAnnounceLanguages = [
329 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
330 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
331 'sl', 'sr', 'sv', 'tr', 'uk'
335 * UI interface for displaying a short message
336 * The parameters are like parameters to wfMessage().
337 * The messages will be in wikitext format, which will be converted to an
338 * output format such as HTML or text before being sent to the user.
341 abstract public function showMessage( $msg /*, ... */ );
344 * Same as showMessage(), but for displaying errors
347 abstract public function showError( $msg /*, ... */ );
350 * Show a message to the installing user by using a Status object
351 * @param Status $status
353 abstract public function showStatusMessage( Status
$status );
356 * Constructs a Config object that contains configuration settings that should be
357 * overwritten for the installation process.
361 * @param Config $baseConfig
363 * @return Config The config to use during installation.
365 public static function getInstallerConfig( Config
$baseConfig ) {
366 $configOverrides = new HashConfig();
368 // disable (problematic) object cache types explicitly, preserving all other (working) ones
370 $emptyCache = [ 'class' => 'EmptyBagOStuff' ];
373 CACHE_NONE
=> $emptyCache,
374 CACHE_DB
=> $emptyCache,
375 CACHE_ANYTHING
=> $emptyCache,
376 CACHE_MEMCACHED
=> $emptyCache,
377 ] +
$baseConfig->get( 'ObjectCaches' );
379 $configOverrides->set( 'ObjectCaches', $objectCaches );
381 // Load the installer's i18n.
382 $messageDirs = $baseConfig->get( 'MessagesDirs' );
383 $messageDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
385 $configOverrides->set( 'MessagesDirs', $messageDirs );
387 $installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
389 // make sure we use the installer config as the main config
390 $configRegistry = $baseConfig->get( 'ConfigRegistry' );
391 $configRegistry['main'] = function() use ( $installerConfig ) {
392 return $installerConfig;
395 $configOverrides->set( 'ConfigRegistry', $configRegistry );
397 return $installerConfig;
401 * Constructor, always call this from child classes.
403 public function __construct() {
404 global $wgMemc, $wgUser, $wgObjectCaches;
406 $defaultConfig = new GlobalVarConfig(); // all the stuff from DefaultSettings.php
407 $installerConfig = self
::getInstallerConfig( $defaultConfig );
409 // Reset all services and inject config overrides
410 MediaWiki\MediaWikiServices
::resetGlobalInstance( $installerConfig );
412 // Don't attempt to load user language options (T126177)
413 // This will be overridden in the web installer with the user-specified language
414 RequestContext
::getMain()->setLanguage( 'en' );
416 // Disable the i18n cache
417 // TODO: manage LocalisationCache singleton in MediaWikiServices
418 Language
::getLocalisationCache()->disableBackend();
420 // Disable all global services, since we don't have any configuration yet!
421 MediaWiki\MediaWikiServices
::disableStorageBackend();
423 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
424 // SqlBagOStuff will then throw since we just disabled wfGetDB)
425 $wgObjectCaches = MediaWikiServices
::getInstance()->getMainConfig()->get( 'ObjectCaches' );
426 $wgMemc = ObjectCache
::getInstance( CACHE_NONE
);
428 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
429 $wgUser = User
::newFromId( 0 );
430 RequestContext
::getMain()->setUser( $wgUser );
432 $this->settings
= $this->internalDefaults
;
434 foreach ( $this->defaultVarNames
as $var ) {
435 $this->settings
[$var] = $GLOBALS[$var];
438 $this->doEnvironmentPreps();
440 $this->compiledDBs
= [];
441 foreach ( self
::getDBTypes() as $type ) {
442 $installer = $this->getDBInstaller( $type );
444 if ( !$installer->isCompiled() ) {
447 $this->compiledDBs
[] = $type;
450 $this->parserTitle
= Title
::newFromText( 'Installer' );
451 $this->parserOptions
= new ParserOptions( $wgUser ); // language will be wrong :(
452 $this->parserOptions
->setEditSection( false );
456 * Get a list of known DB types.
460 public static function getDBTypes() {
461 return self
::$dbTypes;
465 * Do initial checks of the PHP environment. Set variables according to
466 * the observed environment.
468 * It's possible that this may be called under the CLI SAPI, not the SAPI
469 * that the wiki will primarily run under. In that case, the subclass should
470 * initialise variables such as wgScriptPath, before calling this function.
472 * Under the web subclass, it can already be assumed that PHP 5+ is in use
473 * and that sessions are working.
477 public function doEnvironmentChecks() {
478 // Php version has already been checked by entry scripts
479 // Show message here for information purposes
481 $this->showMessage( 'config-env-hhvm', HHVM_VERSION
);
483 $this->showMessage( 'config-env-php', PHP_VERSION
);
487 // Must go here because an old version of PCRE can prevent other checks from completing
488 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
489 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
490 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
493 foreach ( $this->envChecks
as $check ) {
494 $status = $this->$check();
495 if ( $status === false ) {
501 $this->setVar( '_Environment', $good );
503 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
506 public function doEnvironmentPreps() {
507 foreach ( $this->envPreps
as $prep ) {
513 * Set a MW configuration variable, or internal installer configuration variable.
515 * @param string $name
516 * @param mixed $value
518 public function setVar( $name, $value ) {
519 $this->settings
[$name] = $value;
523 * Get an MW configuration variable, or internal installer configuration variable.
524 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
525 * Installer variables are typically prefixed by an underscore.
527 * @param string $name
528 * @param mixed $default
532 public function getVar( $name, $default = null ) {
533 if ( !isset( $this->settings
[$name] ) ) {
536 return $this->settings
[$name];
541 * Get a list of DBs supported by current PHP setup
545 public function getCompiledDBs() {
546 return $this->compiledDBs
;
550 * Get an instance of DatabaseInstaller for the specified DB type.
552 * @param mixed $type DB installer for which is needed, false to use default.
554 * @return DatabaseInstaller
556 public function getDBInstaller( $type = false ) {
558 $type = $this->getVar( 'wgDBtype' );
561 $type = strtolower( $type );
563 if ( !isset( $this->dbInstallers
[$type] ) ) {
564 $class = ucfirst( $type ) . 'Installer';
565 $this->dbInstallers
[$type] = new $class( $this );
568 return $this->dbInstallers
[$type];
572 * Determine if LocalSettings.php exists. If it does, return its variables.
576 public static function getExistingLocalSettings() {
579 // You might be wondering why this is here. Well if you don't do this
580 // then some poorly-formed extensions try to call their own classes
581 // after immediately registering them. We really need to get extension
582 // registration out of the global scope and into a real format.
583 // @see https://phabricator.wikimedia.org/T69440
584 global $wgAutoloadClasses;
585 $wgAutoloadClasses = [];
587 // @codingStandardsIgnoreStart
588 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
589 // Define the required globals here, to ensure, the functions can do it work correctly.
590 global $wgExtensionDirectory, $wgStyleDirectory;
591 // @codingStandardsIgnoreEnd
593 MediaWiki\
suppressWarnings();
594 $_lsExists = file_exists( "$IP/LocalSettings.php" );
595 MediaWiki\restoreWarnings
();
602 require "$IP/includes/DefaultSettings.php";
603 require "$IP/LocalSettings.php";
605 return get_defined_vars();
609 * Get a fake password for sending back to the user in HTML.
610 * This is a security mechanism to avoid compromise of the password in the
611 * event of session ID compromise.
613 * @param string $realPassword
617 public function getFakePassword( $realPassword ) {
618 return str_repeat( '*', strlen( $realPassword ) );
622 * Set a variable which stores a password, except if the new value is a
623 * fake password in which case leave it as it is.
625 * @param string $name
626 * @param mixed $value
628 public function setPassword( $name, $value ) {
629 if ( !preg_match( '/^\*+$/', $value ) ) {
630 $this->setVar( $name, $value );
635 * On POSIX systems return the primary group of the webserver we're running under.
636 * On other systems just returns null.
638 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
639 * webserver user before he can install.
641 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
645 public static function maybeGetWebserverPrimaryGroup() {
646 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
647 # I don't know this, this isn't UNIX.
651 # posix_getegid() *not* getmygid() because we want the group of the webserver,
652 # not whoever owns the current script.
653 $gid = posix_getegid();
654 $group = posix_getpwuid( $gid )['name'];
660 * Convert wikitext $text to HTML.
662 * This is potentially error prone since many parser features require a complete
663 * installed MW database. The solution is to just not use those features when you
664 * write your messages. This appears to work well enough. Basic formatting and
665 * external links work just fine.
667 * But in case a translator decides to throw in a "#ifexist" or internal link or
668 * whatever, this function is guarded to catch the attempted DB access and to present
669 * some fallback text.
671 * @param string $text
672 * @param bool $lineStart
675 public function parse( $text, $lineStart = false ) {
679 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
680 $html = $out->getText();
681 } catch ( DBAccessError
$e ) {
682 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
684 if ( !empty( $this->debug
) ) {
685 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
693 * @return ParserOptions
695 public function getParserOptions() {
696 return $this->parserOptions
;
699 public function disableLinkPopups() {
700 $this->parserOptions
->setExternalLinkTarget( false );
703 public function restoreLinkPopups() {
704 global $wgExternalLinkTarget;
705 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
709 * Install step which adds a row to the site_stats table with appropriate
712 * @param DatabaseInstaller $installer
716 public function populateSiteStats( DatabaseInstaller
$installer ) {
717 $status = $installer->getConnection();
718 if ( !$status->isOK() ) {
721 $status->value
->insert(
725 'ss_total_edits' => 0,
726 'ss_good_articles' => 0,
727 'ss_total_pages' => 0,
734 return Status
::newGood();
738 * Environment check for DB types.
741 protected function envCheckDB() {
746 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
747 // config-type-sqlite
748 foreach ( self
::getDBTypes() as $name ) {
749 $allNames[] = wfMessage( "config-type-$name" )->text();
752 $databases = $this->getCompiledDBs();
754 $databases = array_flip( $databases );
755 foreach ( array_keys( $databases ) as $db ) {
756 $installer = $this->getDBInstaller( $db );
757 $status = $installer->checkPrerequisites();
758 if ( !$status->isGood() ) {
759 $this->showStatusMessage( $status );
761 if ( !$status->isOK() ) {
762 unset( $databases[$db] );
765 $databases = array_flip( $databases );
767 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
769 // @todo FIXME: This only works for the web installer!
777 * Some versions of libxml+PHP break < and > encoding horribly
780 protected function envCheckBrokenXML() {
781 $test = new PhpXmlBugTester();
783 $this->showError( 'config-brokenlibxml' );
792 * Environment check for mbstring.func_overload.
795 protected function envCheckMbstring() {
796 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
797 $this->showError( 'config-mbstring' );
802 if ( !function_exists( 'mb_substr' ) ) {
803 $this->showError( 'config-mbstring-absent' );
812 * Environment check for the XML module.
815 protected function envCheckXML() {
816 if ( !function_exists( "utf8_encode" ) ) {
817 $this->showError( 'config-xml-bad' );
826 * Environment check for the PCRE module.
828 * @note If this check were to fail, the parser would
829 * probably throw an exception before the result
830 * of this check is shown to the user.
833 protected function envCheckPCRE() {
834 MediaWiki\
suppressWarnings();
835 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
836 // Need to check for \p support too, as PCRE can be compiled
837 // with utf8 support, but not unicode property support.
838 // check that \p{Zs} (space separators) matches
839 // U+3000 (Ideographic space)
840 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
841 MediaWiki\restoreWarnings
();
842 if ( $regexd != '--' ||
$regexprop != '--' ) {
843 $this->showError( 'config-pcre-no-utf8' );
852 * Environment check for available memory.
855 protected function envCheckMemory() {
856 $limit = ini_get( 'memory_limit' );
858 if ( !$limit ||
$limit == -1 ) {
862 $n = wfShorthandToInteger( $limit );
864 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
865 $newLimit = "{$this->minMemorySize}M";
867 if ( ini_set( "memory_limit", $newLimit ) === false ) {
868 $this->showMessage( 'config-memory-bad', $limit );
870 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
871 $this->setVar( '_RaiseMemory', true );
879 * Environment check for compiled object cache types.
881 protected function envCheckCache() {
883 foreach ( $this->objectCaches
as $name => $function ) {
884 if ( function_exists( $function ) ) {
885 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
888 $caches[$name] = true;
893 $key = 'config-no-cache-apcu';
894 $this->showMessage( $key );
897 $this->setVar( '_Caches', $caches );
901 * Scare user to death if they have mod_security or mod_security2
904 protected function envCheckModSecurity() {
905 if ( self
::apacheModulePresent( 'mod_security' )
906 || self
::apacheModulePresent( 'mod_security2' ) ) {
907 $this->showMessage( 'config-mod-security' );
914 * Search for GNU diff3.
917 protected function envCheckDiff3() {
918 $names = [ "gdiff3", "diff3", "diff3.exe" ];
919 $versionInfo = [ '$1 --version 2>&1', 'GNU diffutils' ];
921 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
924 $this->setVar( 'wgDiff3', $diff3 );
926 $this->setVar( 'wgDiff3', false );
927 $this->showMessage( 'config-diff3-bad' );
934 * Environment check for ImageMagick and GD.
937 protected function envCheckGraphics() {
938 $names = [ wfIsWindows() ?
'convert.exe' : 'convert' ];
939 $versionInfo = [ '$1 -version', 'ImageMagick' ];
940 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
942 $this->setVar( 'wgImageMagickConvertCommand', '' );
944 $this->setVar( 'wgImageMagickConvertCommand', $convert );
945 $this->showMessage( 'config-imagemagick', $convert );
948 } elseif ( function_exists( 'imagejpeg' ) ) {
949 $this->showMessage( 'config-gd' );
951 $this->showMessage( 'config-no-scaling' );
963 protected function envCheckGit() {
964 $names = [ wfIsWindows() ?
'git.exe' : 'git' ];
965 $versionInfo = [ '$1 --version', 'git version' ];
967 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
970 $this->setVar( 'wgGitBin', $git );
971 $this->showMessage( 'config-git', $git );
973 $this->setVar( 'wgGitBin', false );
974 $this->showMessage( 'config-git-bad' );
981 * Environment check to inform user which server we've assumed.
985 protected function envCheckServer() {
986 $server = $this->envGetDefaultServer();
987 if ( $server !== null ) {
988 $this->showMessage( 'config-using-server', $server );
994 * Environment check to inform user which paths we've assumed.
998 protected function envCheckPath() {
1001 $this->getVar( 'wgServer' ),
1002 $this->getVar( 'wgScriptPath' )
1008 * Environment check for preferred locale in shell
1011 protected function envCheckShellLocale() {
1012 $os = php_uname( 's' );
1013 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
1015 if ( !in_array( $os, $supported ) ) {
1019 # Get a list of available locales.
1021 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1027 $lines = array_map( 'trim', explode( "\n", $lines ) );
1028 $candidatesByLocale = [];
1029 $candidatesByLang = [];
1031 foreach ( $lines as $line ) {
1032 if ( $line === '' ) {
1036 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1040 list( , $lang, , , ) = $m;
1042 $candidatesByLocale[$m[0]] = $m;
1043 $candidatesByLang[$lang][] = $m;
1046 # Try the current value of LANG.
1047 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1048 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1053 # Try the most common ones.
1054 $commonLocales = [ 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1055 foreach ( $commonLocales as $commonLocale ) {
1056 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1057 $this->setVar( 'wgShellLocale', $commonLocale );
1063 # Is there an available locale in the Wiki's language?
1064 $wikiLang = $this->getVar( 'wgLanguageCode' );
1066 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1067 $m = reset( $candidatesByLang[$wikiLang] );
1068 $this->setVar( 'wgShellLocale', $m[0] );
1073 # Are there any at all?
1074 if ( count( $candidatesByLocale ) ) {
1075 $m = reset( $candidatesByLocale );
1076 $this->setVar( 'wgShellLocale', $m[0] );
1086 * Environment check for the permissions of the uploads directory
1089 protected function envCheckUploadsDirectory() {
1092 $dir = $IP . '/images/';
1093 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1094 $safe = !$this->dirIsExecutable( $dir, $url );
1097 $this->showMessage( 'config-uploads-not-safe', $dir );
1104 * Checks if suhosin.get.max_value_length is set, and if so generate
1105 * a warning because it decreases ResourceLoader performance.
1108 protected function envCheckSuhosinMaxValueLength() {
1109 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1110 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1111 // Only warn if the value is below the sane 1024
1112 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1119 * Convert a hex string representing a Unicode code point to that code point.
1123 protected function unicodeChar( $c ) {
1127 } elseif ( $c <= 0x7FF ) {
1128 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1129 } elseif ( $c <= 0xFFFF ) {
1130 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F ) .
1131 chr( 0x80 |
$c & 0x3F );
1132 } elseif ( $c <= 0x10FFFF ) {
1133 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F ) .
1134 chr( 0x80 |
$c >> 6 & 0x3F ) .
1135 chr( 0x80 |
$c & 0x3F );
1142 * Check the libicu version
1144 protected function envCheckLibicu() {
1146 * This needs to be updated something that the latest libicu
1147 * will properly normalize. This normalization was found at
1148 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1149 * Note that we use the hex representation to create the code
1150 * points in order to avoid any Unicode-destroying during transit.
1152 $not_normal_c = $this->unicodeChar( "FA6C" );
1153 $normal_c = $this->unicodeChar( "242EE" );
1155 $useNormalizer = 'php';
1156 $needsUpdate = false;
1158 if ( function_exists( 'normalizer_normalize' ) ) {
1159 $useNormalizer = 'intl';
1160 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1161 if ( $intl !== $normal_c ) {
1162 $needsUpdate = true;
1166 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1167 if ( $useNormalizer === 'php' ) {
1168 $this->showMessage( 'config-unicode-pure-php-warning' );
1170 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1171 if ( $needsUpdate ) {
1172 $this->showMessage( 'config-unicode-update-warning' );
1180 protected function envCheckCtype() {
1181 if ( !function_exists( 'ctype_digit' ) ) {
1182 $this->showError( 'config-ctype' );
1193 protected function envCheckIconv() {
1194 if ( !function_exists( 'iconv' ) ) {
1195 $this->showError( 'config-iconv' );
1206 protected function envCheckJSON() {
1207 if ( !function_exists( 'json_decode' ) ) {
1208 $this->showError( 'config-json' );
1217 * Environment prep for the server hostname.
1219 protected function envPrepServer() {
1220 $server = $this->envGetDefaultServer();
1221 if ( $server !== null ) {
1222 $this->setVar( 'wgServer', $server );
1227 * Helper function to be called from envPrepServer()
1230 abstract protected function envGetDefaultServer();
1233 * Environment prep for setting $IP and $wgScriptPath.
1235 protected function envPrepPath() {
1237 $IP = dirname( dirname( __DIR__
) );
1238 $this->setVar( 'IP', $IP );
1242 * Get an array of likely places we can find executables. Check a bunch
1243 * of known Unix-like defaults, as well as the PATH environment variable
1244 * (which should maybe make it work for Windows?)
1248 protected static function getPossibleBinPaths() {
1250 [ '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1251 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ],
1252 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1257 * Search a path for any of the given executable names. Returns the
1258 * executable name if found. Also checks the version string returned
1259 * by each executable.
1261 * Used only by environment checks.
1263 * @param string $path Path to search
1264 * @param array $names Array of executable names
1265 * @param array|bool $versionInfo False or array with two members:
1266 * 0 => Command to run for version check, with $1 for the full executable name
1267 * 1 => String to compare the output with
1269 * If $versionInfo is not false, only executables with a version
1270 * matching $versionInfo[1] will be returned.
1271 * @return bool|string
1273 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1274 if ( !is_array( $names ) ) {
1275 $names = [ $names ];
1278 foreach ( $names as $name ) {
1279 $command = $path . DIRECTORY_SEPARATOR
. $name;
1281 MediaWiki\
suppressWarnings();
1282 $file_exists = is_executable( $command );
1283 MediaWiki\restoreWarnings
();
1285 if ( $file_exists ) {
1286 if ( !$versionInfo ) {
1290 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1291 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1301 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1302 * @see locateExecutable()
1303 * @param array $names Array of possible names.
1304 * @param array|bool $versionInfo Default: false or array with two members:
1305 * 0 => Command to run for version check, with $1 for the full executable name
1306 * 1 => String to compare the output with
1308 * If $versionInfo is not false, only executables with a version
1309 * matching $versionInfo[1] will be returned.
1310 * @return bool|string
1312 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1313 foreach ( self
::getPossibleBinPaths() as $path ) {
1314 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1315 if ( $exe !== false ) {
1324 * Checks if scripts located in the given directory can be executed via the given URL.
1326 * Used only by environment checks.
1327 * @param string $dir
1328 * @param string $url
1329 * @return bool|int|string
1331 public function dirIsExecutable( $dir, $url ) {
1334 "<?php echo 'ex' . 'ec';",
1335 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1339 // it would be good to check other popular languages here, but it'll be slow.
1341 MediaWiki\
suppressWarnings();
1343 foreach ( $scriptTypes as $ext => $contents ) {
1344 foreach ( $contents as $source ) {
1345 $file = 'exectest.' . $ext;
1347 if ( !file_put_contents( $dir . $file, $source ) ) {
1352 $text = Http
::get( $url . $file, [ 'timeout' => 3 ], __METHOD__
);
1353 } catch ( Exception
$e ) {
1354 // Http::get throws with allow_url_fopen = false and no curl extension.
1357 unlink( $dir . $file );
1359 if ( $text == 'exec' ) {
1360 MediaWiki\restoreWarnings
();
1367 MediaWiki\restoreWarnings
();
1373 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1375 * @param string $moduleName Name of module to check.
1378 public static function apacheModulePresent( $moduleName ) {
1379 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1382 // try it the hard way
1384 phpinfo( INFO_MODULES
);
1385 $info = ob_get_clean();
1387 return strpos( $info, $moduleName ) !== false;
1391 * ParserOptions are constructed before we determined the language, so fix it
1393 * @param Language $lang
1395 public function setParserLanguage( $lang ) {
1396 $this->parserOptions
->setTargetLanguage( $lang );
1397 $this->parserOptions
->setUserLang( $lang );
1401 * Overridden by WebInstaller to provide lastPage parameters.
1402 * @param string $page
1405 protected function getDocUrl( $page ) {
1406 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1410 * Finds extensions that follow the format /$directory/Name/Name.php,
1411 * and returns an array containing the value for 'Name' for each found extension.
1413 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1415 * @param string $directory Directory to search in
1418 public function findExtensions( $directory = 'extensions' ) {
1419 if ( $this->getVar( 'IP' ) === null ) {
1423 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1424 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1428 // extensions -> extension.json, skins -> skin.json
1429 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1431 $dh = opendir( $extDir );
1433 while ( ( $file = readdir( $dh ) ) !== false ) {
1434 if ( !is_dir( "$extDir/$file" ) ) {
1437 if ( file_exists( "$extDir/$file/$jsonFile" ) ||
file_exists( "$extDir/$file/$file.php" ) ) {
1442 natcasesort( $exts );
1448 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1449 * but will fall back to another if the default skin is missing and some other one is present
1452 * @param string[] $skinNames Names of installed skins.
1455 public function getDefaultSkin( array $skinNames ) {
1456 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1457 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1458 return $defaultSkin;
1460 return $skinNames[0];
1465 * Installs the auto-detected extensions.
1469 protected function includeExtensions() {
1471 $exts = $this->getVar( '_Extensions' );
1472 $IP = $this->getVar( 'IP' );
1475 * We need to include DefaultSettings before including extensions to avoid
1476 * warnings about unset variables. However, the only thing we really
1477 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1478 * if the extension has hidden hook registration in $wgExtensionFunctions,
1479 * but we're not opening that can of worms
1480 * @see https://phabricator.wikimedia.org/T28857
1482 global $wgAutoloadClasses;
1483 $wgAutoloadClasses = [];
1486 require "$IP/includes/DefaultSettings.php";
1488 foreach ( $exts as $e ) {
1489 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1490 $queue["$IP/extensions/$e/extension.json"] = 1;
1492 require_once "$IP/extensions/$e/$e.php";
1496 $registry = new ExtensionRegistry();
1497 $data = $registry->readFromQueue( $queue );
1498 $wgAutoloadClasses +
= $data['autoload'];
1500 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1501 $wgHooks['LoadExtensionSchemaUpdates'] : [];
1503 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1504 $hooksWeWant = array_merge_recursive(
1506 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1509 // Unset everyone else's hooks. Lord knows what someone might be doing
1510 // in ParserFirstCallInit (see bug 27171)
1511 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1513 return Status
::newGood();
1517 * Get an array of install steps. Should always be in the format of
1519 * 'name' => 'someuniquename',
1520 * 'callback' => array( $obj, 'method' ),
1522 * There must be a config-install-$name message defined per step, which will
1523 * be shown on install.
1525 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1528 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1529 $coreInstallSteps = [
1530 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1531 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1532 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1533 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1534 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1535 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1536 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1537 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1540 // Build the array of install steps starting from the core install list,
1541 // then adding any callbacks that wanted to attach after a given step
1542 foreach ( $coreInstallSteps as $step ) {
1543 $this->installSteps
[] = $step;
1544 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1545 $this->installSteps
= array_merge(
1546 $this->installSteps
,
1547 $this->extraInstallSteps
[$step['name']]
1552 // Prepend any steps that want to be at the beginning
1553 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1554 $this->installSteps
= array_merge(
1555 $this->extraInstallSteps
['BEGINNING'],
1560 // Extensions should always go first, chance to tie into hooks and such
1561 if ( count( $this->getVar( '_Extensions' ) ) ) {
1562 array_unshift( $this->installSteps
,
1563 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1565 $this->installSteps
[] = [
1566 'name' => 'extension-tables',
1567 'callback' => [ $installer, 'createExtensionTables' ]
1571 return $this->installSteps
;
1575 * Actually perform the installation.
1577 * @param callable $startCB A callback array for the beginning of each step
1578 * @param callable $endCB A callback array for the end of each step
1580 * @return array Array of Status objects
1582 public function performInstallation( $startCB, $endCB ) {
1583 $installResults = [];
1584 $installer = $this->getDBInstaller();
1585 $installer->preInstall();
1586 $steps = $this->getInstallSteps( $installer );
1587 foreach ( $steps as $stepObj ) {
1588 $name = $stepObj['name'];
1589 call_user_func_array( $startCB, [ $name ] );
1591 // Perform the callback step
1592 $status = call_user_func( $stepObj['callback'], $installer );
1594 // Output and save the results
1595 call_user_func( $endCB, $name, $status );
1596 $installResults[$name] = $status;
1598 // If we've hit some sort of fatal, we need to bail.
1599 // Callback already had a chance to do output above.
1600 if ( !$status->isOk() ) {
1604 if ( $status->isOk() ) {
1605 $this->setVar( '_InstallDone', true );
1608 return $installResults;
1612 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1616 public function generateKeys() {
1617 $keys = [ 'wgSecretKey' => 64 ];
1618 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1619 $keys['wgUpgradeKey'] = 16;
1622 return $this->doGenerateKeys( $keys );
1626 * Generate a secret value for variables using our CryptRand generator.
1627 * Produce a warning if the random source was insecure.
1629 * @param array $keys
1632 protected function doGenerateKeys( $keys ) {
1633 $status = Status
::newGood();
1636 foreach ( $keys as $name => $length ) {
1637 $secretKey = MWCryptRand
::generateHex( $length, true );
1638 if ( !MWCryptRand
::wasStrong() ) {
1642 $this->setVar( $name, $secretKey );
1646 $names = array_keys( $keys );
1647 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1649 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1656 * Create the first user account, grant it sysop and bureaucrat rights
1660 protected function createSysop() {
1661 $name = $this->getVar( '_AdminName' );
1662 $user = User
::newFromName( $name );
1665 // We should've validated this earlier anyway!
1666 return Status
::newFatal( 'config-admin-error-user', $name );
1669 if ( $user->idForName() == 0 ) {
1670 $user->addToDatabase();
1673 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1674 } catch ( PasswordError
$pwe ) {
1675 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1678 $user->addGroup( 'sysop' );
1679 $user->addGroup( 'bureaucrat' );
1680 if ( $this->getVar( '_AdminEmail' ) ) {
1681 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1683 $user->saveSettings();
1685 // Update user count
1686 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1687 $ssUpdate->doUpdate();
1689 $status = Status
::newGood();
1691 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1692 $this->subscribeToMediaWikiAnnounce( $status );
1701 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1703 'email' => $this->getVar( '_AdminEmail' ),
1708 // Mailman doesn't support as many languages as we do, so check to make
1709 // sure their selected language is available
1710 $myLang = $this->getVar( '_UserLang' );
1711 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1712 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1713 $params['language'] = $myLang;
1716 if ( MWHttpRequest
::canMakeRequests() ) {
1717 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1718 [ 'method' => 'POST', 'postData' => $params ], __METHOD__
)->execute();
1719 if ( !$res->isOK() ) {
1720 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1723 $s->warning( 'config-install-subscribe-notpossible' );
1728 * Insert Main Page with default content.
1730 * @param DatabaseInstaller $installer
1733 protected function createMainpage( DatabaseInstaller
$installer ) {
1734 $status = Status
::newGood();
1736 $page = WikiPage
::factory( Title
::newMainPage() );
1737 $content = new WikitextContent(
1738 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1739 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1742 $status = $page->doEditContent( $content,
1746 User
::newFromName( 'MediaWiki default' )
1748 } catch ( Exception
$e ) {
1749 // using raw, because $wgShowExceptionDetails can not be set yet
1750 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1757 * Override the necessary bits of the config to run an installation.
1759 public static function overrideConfig() {
1760 // Use PHP's built-in session handling, since MediaWiki's
1761 // SessionHandler can't work before we have an object cache set up.
1762 define( 'MW_NO_SESSION_HANDLER', 1 );
1764 // Don't access the database
1765 $GLOBALS['wgUseDatabaseMessages'] = false;
1766 // Don't cache langconv tables
1767 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1769 $GLOBALS['wgShowExceptionDetails'] = true;
1770 // Don't break forms
1771 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1773 // Extended debugging
1774 $GLOBALS['wgShowSQLErrors'] = true;
1775 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1777 // Allow multiple ob_flush() calls
1778 $GLOBALS['wgDisableOutputCompression'] = true;
1780 // Use a sensible cookie prefix (not my_wiki)
1781 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1783 // Some of the environment checks make shell requests, remove limits
1784 $GLOBALS['wgMaxShellMemory'] = 0;
1786 // Override the default CookieSessionProvider with a dummy
1787 // implementation that won't stomp on PHP's cookies.
1788 $GLOBALS['wgSessionProviders'] = [
1790 'class' => 'InstallerSessionProvider',
1797 // Don't try to use any object cache for SessionManager either.
1798 $GLOBALS['wgSessionCacheType'] = CACHE_NONE
;
1802 * Add an installation step following the given step.
1804 * @param callable $callback A valid installation callback array, in this form:
1805 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1806 * @param string $findStep The step to find. Omit to put the step at the beginning
1808 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1809 $this->extraInstallSteps
[$findStep][] = $callback;
1813 * Disable the time limit for execution.
1814 * Some long-running pages (Install, Upgrade) will want to do this
1816 protected function disableTimeLimit() {
1817 MediaWiki\
suppressWarnings();
1818 set_time_limit( 0 );
1819 MediaWiki\restoreWarnings
();