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.
340 abstract public function showMessage( $msg /*, ... */ );
343 * Same as showMessage(), but for displaying errors
346 abstract public function showError( $msg /*, ... */ );
349 * Show a message to the installing user by using a Status object
350 * @param Status $status
352 abstract public function showStatusMessage( Status
$status );
355 * Constructs a Config object that contains configuration settings that should be
356 * overwritten for the installation process.
360 * @param Config $baseConfig
362 * @return Config The config to use during installation.
364 public static function getInstallerConfig( Config
$baseConfig ) {
365 $configOverrides = new HashConfig();
367 // disable (problematic) object cache types explicitly, preserving all other (working) ones
369 $emptyCache = [ 'class' => EmptyBagOStuff
::class ];
372 CACHE_NONE
=> $emptyCache,
373 CACHE_DB
=> $emptyCache,
374 CACHE_ANYTHING
=> $emptyCache,
375 CACHE_MEMCACHED
=> $emptyCache,
376 ] +
$baseConfig->get( 'ObjectCaches' );
378 $configOverrides->set( 'ObjectCaches', $objectCaches );
380 // Load the installer's i18n.
381 $messageDirs = $baseConfig->get( 'MessagesDirs' );
382 $messageDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
384 $configOverrides->set( 'MessagesDirs', $messageDirs );
386 $installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
388 // make sure we use the installer config as the main config
389 $configRegistry = $baseConfig->get( 'ConfigRegistry' );
390 $configRegistry['main'] = function () use ( $installerConfig ) {
391 return $installerConfig;
394 $configOverrides->set( 'ConfigRegistry', $configRegistry );
396 return $installerConfig;
400 * Constructor, always call this from child classes.
402 public function __construct() {
403 global $wgMemc, $wgUser, $wgObjectCaches;
405 $defaultConfig = new GlobalVarConfig(); // all the stuff from DefaultSettings.php
406 $installerConfig = self
::getInstallerConfig( $defaultConfig );
408 // Reset all services and inject config overrides
409 MediaWikiServices
::resetGlobalInstance( $installerConfig );
411 // Don't attempt to load user language options (T126177)
412 // This will be overridden in the web installer with the user-specified language
413 RequestContext
::getMain()->setLanguage( 'en' );
415 // Disable the i18n cache
416 // TODO: manage LocalisationCache singleton in MediaWikiServices
417 Language
::getLocalisationCache()->disableBackend();
419 // Disable all global services, since we don't have any configuration yet!
420 MediaWikiServices
::disableStorageBackend();
422 $mwServices = MediaWikiServices
::getInstance();
423 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
424 // SqlBagOStuff will then throw since we just disabled wfGetDB)
425 $wgObjectCaches = $mwServices->getMainConfig()->get( 'ObjectCaches' );
426 $wgMemc = ObjectCache
::getInstance( CACHE_NONE
);
428 // Disable interwiki lookup, to avoid database access during parses
429 $mwServices->redefineService( 'InterwikiLookup', function () {
430 return new NullInterwikiLookup();
433 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
434 $wgUser = User
::newFromId( 0 );
435 RequestContext
::getMain()->setUser( $wgUser );
437 $this->settings
= $this->internalDefaults
;
439 foreach ( $this->defaultVarNames
as $var ) {
440 $this->settings
[$var] = $GLOBALS[$var];
443 $this->doEnvironmentPreps();
445 $this->compiledDBs
= [];
446 foreach ( self
::getDBTypes() as $type ) {
447 $installer = $this->getDBInstaller( $type );
449 if ( !$installer->isCompiled() ) {
452 $this->compiledDBs
[] = $type;
455 $this->parserTitle
= Title
::newFromText( 'Installer' );
456 $this->parserOptions
= new ParserOptions( $wgUser ); // language will be wrong :(
457 // Don't try to access DB before user language is initialised
458 $this->setParserLanguage( Language
::factory( 'en' ) );
462 * Get a list of known DB types.
466 public static function getDBTypes() {
467 return self
::$dbTypes;
471 * Do initial checks of the PHP environment. Set variables according to
472 * the observed environment.
474 * It's possible that this may be called under the CLI SAPI, not the SAPI
475 * that the wiki will primarily run under. In that case, the subclass should
476 * initialise variables such as wgScriptPath, before calling this function.
478 * Under the web subclass, it can already be assumed that PHP 5+ is in use
479 * and that sessions are working.
483 public function doEnvironmentChecks() {
484 // Php version has already been checked by entry scripts
485 // Show message here for information purposes
487 $this->showMessage( 'config-env-hhvm', HHVM_VERSION
);
489 $this->showMessage( 'config-env-php', PHP_VERSION
);
493 // Must go here because an old version of PCRE can prevent other checks from completing
494 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
495 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
496 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
499 foreach ( $this->envChecks
as $check ) {
500 $status = $this->$check();
501 if ( $status === false ) {
507 $this->setVar( '_Environment', $good );
509 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
512 public function doEnvironmentPreps() {
513 foreach ( $this->envPreps
as $prep ) {
519 * Set a MW configuration variable, or internal installer configuration variable.
521 * @param string $name
522 * @param mixed $value
524 public function setVar( $name, $value ) {
525 $this->settings
[$name] = $value;
529 * Get an MW configuration variable, or internal installer configuration variable.
530 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
531 * Installer variables are typically prefixed by an underscore.
533 * @param string $name
534 * @param mixed $default
538 public function getVar( $name, $default = null ) {
539 if ( !isset( $this->settings
[$name] ) ) {
542 return $this->settings
[$name];
547 * Get a list of DBs supported by current PHP setup
551 public function getCompiledDBs() {
552 return $this->compiledDBs
;
556 * Get the DatabaseInstaller class name for this type
558 * @param string $type database type ($wgDBtype)
559 * @return string Class name
562 public static function getDBInstallerClass( $type ) {
563 return ucfirst( $type ) . 'Installer';
567 * Get an instance of DatabaseInstaller for the specified DB type.
569 * @param mixed $type DB installer for which is needed, false to use default.
571 * @return DatabaseInstaller
573 public function getDBInstaller( $type = false ) {
575 $type = $this->getVar( 'wgDBtype' );
578 $type = strtolower( $type );
580 if ( !isset( $this->dbInstallers
[$type] ) ) {
581 $class = self
::getDBInstallerClass( $type );
582 $this->dbInstallers
[$type] = new $class( $this );
585 return $this->dbInstallers
[$type];
589 * Determine if LocalSettings.php exists. If it does, return its variables.
591 * @return array|false
593 public static function getExistingLocalSettings() {
596 // You might be wondering why this is here. Well if you don't do this
597 // then some poorly-formed extensions try to call their own classes
598 // after immediately registering them. We really need to get extension
599 // registration out of the global scope and into a real format.
600 // @see https://phabricator.wikimedia.org/T69440
601 global $wgAutoloadClasses;
602 $wgAutoloadClasses = [];
604 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
605 // Define the required globals here, to ensure, the functions can do it work correctly.
606 // phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables
607 global $wgExtensionDirectory, $wgStyleDirectory;
609 Wikimedia\
suppressWarnings();
610 $_lsExists = file_exists( "$IP/LocalSettings.php" );
611 Wikimedia\restoreWarnings
();
618 require "$IP/includes/DefaultSettings.php";
619 require "$IP/LocalSettings.php";
621 return get_defined_vars();
625 * Get a fake password for sending back to the user in HTML.
626 * This is a security mechanism to avoid compromise of the password in the
627 * event of session ID compromise.
629 * @param string $realPassword
633 public function getFakePassword( $realPassword ) {
634 return str_repeat( '*', strlen( $realPassword ) );
638 * Set a variable which stores a password, except if the new value is a
639 * fake password in which case leave it as it is.
641 * @param string $name
642 * @param mixed $value
644 public function setPassword( $name, $value ) {
645 if ( !preg_match( '/^\*+$/', $value ) ) {
646 $this->setVar( $name, $value );
651 * On POSIX systems return the primary group of the webserver we're running under.
652 * On other systems just returns null.
654 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
655 * webserver user before he can install.
657 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
661 public static function maybeGetWebserverPrimaryGroup() {
662 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
663 # I don't know this, this isn't UNIX.
667 # posix_getegid() *not* getmygid() because we want the group of the webserver,
668 # not whoever owns the current script.
669 $gid = posix_getegid();
670 $group = posix_getpwuid( $gid )['name'];
676 * Convert wikitext $text to HTML.
678 * This is potentially error prone since many parser features require a complete
679 * installed MW database. The solution is to just not use those features when you
680 * write your messages. This appears to work well enough. Basic formatting and
681 * external links work just fine.
683 * But in case a translator decides to throw in a "#ifexist" or internal link or
684 * whatever, this function is guarded to catch the attempted DB access and to present
685 * some fallback text.
687 * @param string $text
688 * @param bool $lineStart
691 public function parse( $text, $lineStart = false ) {
695 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
696 $html = $out->getText( [
697 'enableSectionEditLinks' => false,
700 } catch ( MediaWiki\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() {
762 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
763 // config-type-sqlite
764 foreach ( self
::getDBTypes() as $name ) {
765 $allNames[] = wfMessage( "config-type-$name" )->text();
768 $databases = $this->getCompiledDBs();
770 $databases = array_flip( $databases );
771 foreach ( array_keys( $databases ) as $db ) {
772 $installer = $this->getDBInstaller( $db );
773 $status = $installer->checkPrerequisites();
774 if ( !$status->isGood() ) {
775 $this->showStatusMessage( $status );
777 if ( !$status->isOK() ) {
778 unset( $databases[$db] );
781 $databases = array_flip( $databases );
783 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
785 // @todo FIXME: This only works for the web installer!
793 * Some versions of libxml+PHP break < and > encoding horribly
796 protected function envCheckBrokenXML() {
797 $test = new PhpXmlBugTester();
799 $this->showError( 'config-brokenlibxml' );
808 * Environment check for the PCRE module.
810 * @note If this check were to fail, the parser would
811 * probably throw an exception before the result
812 * of this check is shown to the user.
815 protected function envCheckPCRE() {
816 Wikimedia\
suppressWarnings();
817 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
818 // Need to check for \p support too, as PCRE can be compiled
819 // with utf8 support, but not unicode property support.
820 // check that \p{Zs} (space separators) matches
821 // U+3000 (Ideographic space)
822 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
823 Wikimedia\restoreWarnings
();
824 if ( $regexd != '--' ||
$regexprop != '--' ) {
825 $this->showError( 'config-pcre-no-utf8' );
834 * Environment check for available memory.
837 protected function envCheckMemory() {
838 $limit = ini_get( 'memory_limit' );
840 if ( !$limit ||
$limit == -1 ) {
844 $n = wfShorthandToInteger( $limit );
846 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
847 $newLimit = "{$this->minMemorySize}M";
849 if ( ini_set( "memory_limit", $newLimit ) === false ) {
850 $this->showMessage( 'config-memory-bad', $limit );
852 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
853 $this->setVar( '_RaiseMemory', true );
861 * Environment check for compiled object cache types.
863 protected function envCheckCache() {
865 foreach ( $this->objectCaches
as $name => $function ) {
866 if ( function_exists( $function ) ) {
867 $caches[$name] = true;
872 $key = 'config-no-cache-apcu';
873 $this->showMessage( $key );
876 $this->setVar( '_Caches', $caches );
880 * Scare user to death if they have mod_security or mod_security2
883 protected function envCheckModSecurity() {
884 if ( self
::apacheModulePresent( 'mod_security' )
885 || self
::apacheModulePresent( 'mod_security2' ) ) {
886 $this->showMessage( 'config-mod-security' );
893 * Search for GNU diff3.
896 protected function envCheckDiff3() {
897 $names = [ "gdiff3", "diff3" ];
898 if ( wfIsWindows() ) {
899 $names[] = 'diff3.exe';
901 $versionInfo = [ '--version', 'GNU diffutils' ];
903 $diff3 = ExecutableFinder
::findInDefaultPaths( $names, $versionInfo );
906 $this->setVar( 'wgDiff3', $diff3 );
908 $this->setVar( 'wgDiff3', false );
909 $this->showMessage( 'config-diff3-bad' );
916 * Environment check for ImageMagick and GD.
919 protected function envCheckGraphics() {
920 $names = wfIsWindows() ?
'convert.exe' : 'convert';
921 $versionInfo = [ '-version', 'ImageMagick' ];
922 $convert = ExecutableFinder
::findInDefaultPaths( $names, $versionInfo );
924 $this->setVar( 'wgImageMagickConvertCommand', '' );
926 $this->setVar( 'wgImageMagickConvertCommand', $convert );
927 $this->showMessage( 'config-imagemagick', $convert );
930 } elseif ( function_exists( 'imagejpeg' ) ) {
931 $this->showMessage( 'config-gd' );
933 $this->showMessage( 'config-no-scaling' );
945 protected function envCheckGit() {
946 $names = wfIsWindows() ?
'git.exe' : 'git';
947 $versionInfo = [ '--version', 'git version' ];
949 $git = ExecutableFinder
::findInDefaultPaths( $names, $versionInfo );
952 $this->setVar( 'wgGitBin', $git );
953 $this->showMessage( 'config-git', $git );
955 $this->setVar( 'wgGitBin', false );
956 $this->showMessage( 'config-git-bad' );
963 * Environment check to inform user which server we've assumed.
967 protected function envCheckServer() {
968 $server = $this->envGetDefaultServer();
969 if ( $server !== null ) {
970 $this->showMessage( 'config-using-server', $server );
976 * Environment check to inform user which paths we've assumed.
980 protected function envCheckPath() {
983 $this->getVar( 'wgServer' ),
984 $this->getVar( 'wgScriptPath' )
990 * Environment check for preferred locale in shell
993 protected function envCheckShellLocale() {
994 $os = php_uname( 's' );
995 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
997 if ( !in_array( $os, $supported ) ) {
1001 if ( Shell
::isDisabled() ) {
1005 # Get a list of available locales.
1006 $result = Shell
::command( '/usr/bin/locale', '-a' )
1009 if ( $result->getExitCode() != 0 ) {
1013 $lines = $result->getStdout();
1014 $lines = array_map( 'trim', explode( "\n", $lines ) );
1015 $candidatesByLocale = [];
1016 $candidatesByLang = [];
1017 foreach ( $lines as $line ) {
1018 if ( $line === '' ) {
1022 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1026 list( , $lang, , , ) = $m;
1028 $candidatesByLocale[$m[0]] = $m;
1029 $candidatesByLang[$lang][] = $m;
1032 # Try the current value of LANG.
1033 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1034 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1039 # Try the most common ones.
1040 $commonLocales = [ 'C.UTF-8', 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1041 foreach ( $commonLocales as $commonLocale ) {
1042 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1043 $this->setVar( 'wgShellLocale', $commonLocale );
1049 # Is there an available locale in the Wiki's language?
1050 $wikiLang = $this->getVar( 'wgLanguageCode' );
1052 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1053 $m = reset( $candidatesByLang[$wikiLang] );
1054 $this->setVar( 'wgShellLocale', $m[0] );
1059 # Are there any at all?
1060 if ( count( $candidatesByLocale ) ) {
1061 $m = reset( $candidatesByLocale );
1062 $this->setVar( 'wgShellLocale', $m[0] );
1072 * Environment check for the permissions of the uploads directory
1075 protected function envCheckUploadsDirectory() {
1078 $dir = $IP . '/images/';
1079 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1080 $safe = !$this->dirIsExecutable( $dir, $url );
1083 $this->showMessage( 'config-uploads-not-safe', $dir );
1090 * Checks if suhosin.get.max_value_length is set, and if so generate
1091 * a warning because it decreases ResourceLoader performance.
1094 protected function envCheckSuhosinMaxValueLength() {
1095 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1096 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1097 // Only warn if the value is below the sane 1024
1098 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1105 * Checks if we're running on 64 bit or not. 32 bit is becoming increasingly
1106 * hard to support, so let's at least warn people.
1110 protected function envCheck64Bit() {
1111 if ( PHP_INT_SIZE
== 4 ) {
1112 $this->showMessage( 'config-using-32bit' );
1119 * Convert a hex string representing a Unicode code point to that code point.
1121 * @return string|false
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' );
1178 * Environment prep for the server hostname.
1180 protected function envPrepServer() {
1181 $server = $this->envGetDefaultServer();
1182 if ( $server !== null ) {
1183 $this->setVar( 'wgServer', $server );
1188 * Helper function to be called from envPrepServer()
1191 abstract protected function envGetDefaultServer();
1194 * Environment prep for setting $IP and $wgScriptPath.
1196 protected function envPrepPath() {
1198 $IP = dirname( dirname( __DIR__
) );
1199 $this->setVar( 'IP', $IP );
1203 * Checks if scripts located in the given directory can be executed via the given URL.
1205 * Used only by environment checks.
1206 * @param string $dir
1207 * @param string $url
1208 * @return bool|int|string
1210 public function dirIsExecutable( $dir, $url ) {
1213 "<?php echo 'ex' . 'ec';",
1214 "#!/var/env php\n<?php echo 'ex' . 'ec';",
1218 // it would be good to check other popular languages here, but it'll be slow.
1220 Wikimedia\
suppressWarnings();
1222 foreach ( $scriptTypes as $ext => $contents ) {
1223 foreach ( $contents as $source ) {
1224 $file = 'exectest.' . $ext;
1226 if ( !file_put_contents( $dir . $file, $source ) ) {
1231 $text = Http
::get( $url . $file, [ 'timeout' => 3 ], __METHOD__
);
1232 } catch ( Exception
$e ) {
1233 // Http::get throws with allow_url_fopen = false and no curl extension.
1236 unlink( $dir . $file );
1238 if ( $text == 'exec' ) {
1239 Wikimedia\restoreWarnings
();
1246 Wikimedia\restoreWarnings
();
1252 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1254 * @param string $moduleName Name of module to check.
1257 public static function apacheModulePresent( $moduleName ) {
1258 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1261 // try it the hard way
1263 phpinfo( INFO_MODULES
);
1264 $info = ob_get_clean();
1266 return strpos( $info, $moduleName ) !== false;
1270 * ParserOptions are constructed before we determined the language, so fix it
1272 * @param Language $lang
1274 public function setParserLanguage( $lang ) {
1275 $this->parserOptions
->setTargetLanguage( $lang );
1276 $this->parserOptions
->setUserLang( $lang );
1280 * Overridden by WebInstaller to provide lastPage parameters.
1281 * @param string $page
1284 protected function getDocUrl( $page ) {
1285 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1289 * Finds extensions that follow the format /$directory/Name/Name.php,
1290 * and returns an array containing the value for 'Name' for each found extension.
1292 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1294 * @param string $directory Directory to search in
1295 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1297 public function findExtensions( $directory = 'extensions' ) {
1298 if ( $this->getVar( 'IP' ) === null ) {
1302 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1303 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1307 // extensions -> extension.json, skins -> skin.json
1308 $jsonFile = substr( $directory, 0, strlen( $directory ) - 1 ) . '.json';
1310 $dh = opendir( $extDir );
1312 while ( ( $file = readdir( $dh ) ) !== false ) {
1313 if ( !is_dir( "$extDir/$file" ) ) {
1316 $fullJsonFile = "$extDir/$file/$jsonFile";
1317 $isJson = file_exists( $fullJsonFile );
1320 // Only fallback to PHP file if JSON doesn't exist
1321 $fullPhpFile = "$extDir/$file/$file.php";
1322 $isPhp = file_exists( $fullPhpFile );
1324 if ( $isJson ||
$isPhp ) {
1325 // Extension exists. Now see if there are screenshots
1327 if ( is_dir( "$extDir/$file/screenshots" ) ) {
1328 $paths = glob( "$extDir/$file/screenshots/*.png" );
1329 foreach ( $paths as $path ) {
1330 $exts[$file]['screenshots'][] = str_replace( $extDir, "../$directory", $path );
1336 $info = $this->readExtension( $fullJsonFile );
1337 if ( $info === false ) {
1340 $exts[$file] +
= $info;
1344 uksort( $exts, 'strnatcasecmp' );
1350 * @param string $fullJsonFile
1351 * @param array $extDeps
1352 * @param array $skinDeps
1354 * @return array|bool False if this extension can't be loaded
1356 private function readExtension( $fullJsonFile, $extDeps = [], $skinDeps = [] ) {
1361 $extDir = $this->getVar( 'IP' ) . '/extensions';
1362 foreach ( $extDeps as $dep ) {
1363 $fname = "$extDir/$dep/extension.json";
1364 if ( !file_exists( $fname ) ) {
1371 $skinDir = $this->getVar( 'IP' ) . '/skins';
1372 foreach ( $skinDeps as $dep ) {
1373 $fname = "$skinDir/$dep/skin.json";
1374 if ( !file_exists( $fname ) ) {
1380 $registry = new ExtensionRegistry();
1382 $info = $registry->readFromQueue( $load );
1383 } catch ( ExtensionDependencyError
$e ) {
1384 if ( $e->incompatibleCore ||
$e->incompatibleSkins
1385 ||
$e->incompatibleExtensions
1387 // If something is incompatible with a dependency, we have no real
1388 // option besides skipping it
1390 } elseif ( $e->missingExtensions ||
$e->missingSkins
) {
1391 // There's an extension missing in the dependency tree,
1392 // so add those to the dependency list and try again
1393 return $this->readExtension(
1395 array_merge( $extDeps, $e->missingExtensions
),
1396 array_merge( $skinDeps, $e->missingSkins
)
1399 // Some other kind of dependency error?
1403 // The order of credits will be the order of $load,
1404 // so the first extension is the one we want to load,
1405 // everything else is a dependency
1407 foreach ( $info['credits'] as $name => $credit ) {
1410 // Extension we want to load
1413 $type = basename( $credit['path'] ) === 'skin.json' ?
'skins' : 'extensions';
1414 $ret['requires'][$type][] = $credit['name'];
1416 $credits = array_values( $info['credits'] )[0];
1417 if ( isset( $credits['url'] ) ) {
1418 $ret['url'] = $credits['url'];
1420 $ret['type'] = $credits['type'];
1426 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1427 * but will fall back to another if the default skin is missing and some other one is present
1430 * @param string[] $skinNames Names of installed skins.
1433 public function getDefaultSkin( array $skinNames ) {
1434 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1435 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1436 return $defaultSkin;
1438 return $skinNames[0];
1443 * Installs the auto-detected extensions.
1447 protected function includeExtensions() {
1449 $exts = $this->getVar( '_Extensions' );
1450 $IP = $this->getVar( 'IP' );
1452 // Marker for DatabaseUpdater::loadExtensions so we don't
1453 // double load extensions
1454 define( 'MW_EXTENSIONS_LOADED', true );
1457 * We need to include DefaultSettings before including extensions to avoid
1458 * warnings about unset variables. However, the only thing we really
1459 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1460 * if the extension has hidden hook registration in $wgExtensionFunctions,
1461 * but we're not opening that can of worms
1462 * @see https://phabricator.wikimedia.org/T28857
1464 global $wgAutoloadClasses;
1465 $wgAutoloadClasses = [];
1468 require "$IP/includes/DefaultSettings.php";
1470 foreach ( $exts as $e ) {
1471 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1472 $queue["$IP/extensions/$e/extension.json"] = 1;
1474 require_once "$IP/extensions/$e/$e.php";
1478 $registry = new ExtensionRegistry();
1479 $data = $registry->readFromQueue( $queue );
1480 $wgAutoloadClasses +
= $data['autoload'];
1482 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1483 /** @suppress PhanUndeclaredVariable $wgHooks is set by DefaultSettings */
1484 $wgHooks['LoadExtensionSchemaUpdates'] : [];
1486 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1487 $hooksWeWant = array_merge_recursive(
1489 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1492 // Unset everyone else's hooks. Lord knows what someone might be doing
1493 // in ParserFirstCallInit (see T29171)
1494 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1496 return Status
::newGood();
1500 * Get an array of install steps. Should always be in the format of
1502 * 'name' => 'someuniquename',
1503 * 'callback' => [ $obj, 'method' ],
1505 * There must be a config-install-$name message defined per step, which will
1506 * be shown on install.
1508 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1511 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1512 $coreInstallSteps = [
1513 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1514 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1515 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1516 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1517 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1518 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1519 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1520 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1523 // Build the array of install steps starting from the core install list,
1524 // then adding any callbacks that wanted to attach after a given step
1525 foreach ( $coreInstallSteps as $step ) {
1526 $this->installSteps
[] = $step;
1527 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1528 $this->installSteps
= array_merge(
1529 $this->installSteps
,
1530 $this->extraInstallSteps
[$step['name']]
1535 // Prepend any steps that want to be at the beginning
1536 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1537 $this->installSteps
= array_merge(
1538 $this->extraInstallSteps
['BEGINNING'],
1543 // Extensions should always go first, chance to tie into hooks and such
1544 if ( count( $this->getVar( '_Extensions' ) ) ) {
1545 array_unshift( $this->installSteps
,
1546 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1548 $this->installSteps
[] = [
1549 'name' => 'extension-tables',
1550 'callback' => [ $installer, 'createExtensionTables' ]
1554 return $this->installSteps
;
1558 * Actually perform the installation.
1560 * @param callable $startCB A callback array for the beginning of each step
1561 * @param callable $endCB A callback array for the end of each step
1563 * @return array Array of Status objects
1565 public function performInstallation( $startCB, $endCB ) {
1566 $installResults = [];
1567 $installer = $this->getDBInstaller();
1568 $installer->preInstall();
1569 $steps = $this->getInstallSteps( $installer );
1570 foreach ( $steps as $stepObj ) {
1571 $name = $stepObj['name'];
1572 call_user_func_array( $startCB, [ $name ] );
1574 // Perform the callback step
1575 $status = call_user_func( $stepObj['callback'], $installer );
1577 // Output and save the results
1578 call_user_func( $endCB, $name, $status );
1579 $installResults[$name] = $status;
1581 // If we've hit some sort of fatal, we need to bail.
1582 // Callback already had a chance to do output above.
1583 if ( !$status->isOk() ) {
1587 if ( $status->isOk() ) {
1589 'config-install-success',
1590 $this->getVar( 'wgServer' ),
1591 $this->getVar( 'wgScriptPath' )
1593 $this->setVar( '_InstallDone', true );
1596 return $installResults;
1600 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1604 public function generateKeys() {
1605 $keys = [ 'wgSecretKey' => 64 ];
1606 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1607 $keys['wgUpgradeKey'] = 16;
1610 return $this->doGenerateKeys( $keys );
1614 * Generate a secret value for variables using our CryptRand generator.
1615 * Produce a warning if the random source was insecure.
1617 * @param array $keys
1620 protected function doGenerateKeys( $keys ) {
1621 $status = Status
::newGood();
1624 foreach ( $keys as $name => $length ) {
1625 $secretKey = MWCryptRand
::generateHex( $length, true );
1626 if ( !MWCryptRand
::wasStrong() ) {
1630 $this->setVar( $name, $secretKey );
1634 $names = array_keys( $keys );
1635 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1637 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1644 * Create the first user account, grant it sysop and bureaucrat rights
1648 protected function createSysop() {
1649 $name = $this->getVar( '_AdminName' );
1650 $user = User
::newFromName( $name );
1653 // We should've validated this earlier anyway!
1654 return Status
::newFatal( 'config-admin-error-user', $name );
1657 if ( $user->idForName() == 0 ) {
1658 $user->addToDatabase();
1661 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1662 } catch ( PasswordError
$pwe ) {
1663 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1666 $user->addGroup( 'sysop' );
1667 $user->addGroup( 'bureaucrat' );
1668 if ( $this->getVar( '_AdminEmail' ) ) {
1669 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1671 $user->saveSettings();
1673 // Update user count
1674 $ssUpdate = SiteStatsUpdate
::factory( [ 'users' => 1 ] );
1675 $ssUpdate->doUpdate();
1677 $status = Status
::newGood();
1679 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1680 $this->subscribeToMediaWikiAnnounce( $status );
1689 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1691 'email' => $this->getVar( '_AdminEmail' ),
1696 // Mailman doesn't support as many languages as we do, so check to make
1697 // sure their selected language is available
1698 $myLang = $this->getVar( '_UserLang' );
1699 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1700 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1701 $params['language'] = $myLang;
1704 if ( MWHttpRequest
::canMakeRequests() ) {
1705 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1706 [ 'method' => 'POST', 'postData' => $params ], __METHOD__
)->execute();
1707 if ( !$res->isOK() ) {
1708 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1711 $s->warning( 'config-install-subscribe-notpossible' );
1716 * Insert Main Page with default content.
1718 * @param DatabaseInstaller $installer
1721 protected function createMainpage( DatabaseInstaller
$installer ) {
1722 $status = Status
::newGood();
1723 $title = Title
::newMainPage();
1724 if ( $title->exists() ) {
1725 $status->warning( 'config-install-mainpage-exists' );
1729 $page = WikiPage
::factory( $title );
1730 $content = new WikitextContent(
1731 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1732 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1735 $status = $page->doEditContent( $content,
1739 User
::newFromName( 'MediaWiki default' )
1741 } catch ( Exception
$e ) {
1742 // using raw, because $wgShowExceptionDetails can not be set yet
1743 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1750 * Override the necessary bits of the config to run an installation.
1752 public static function overrideConfig() {
1753 // Use PHP's built-in session handling, since MediaWiki's
1754 // SessionHandler can't work before we have an object cache set up.
1755 define( 'MW_NO_SESSION_HANDLER', 1 );
1757 // Don't access the database
1758 $GLOBALS['wgUseDatabaseMessages'] = false;
1759 // Don't cache langconv tables
1760 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1762 $GLOBALS['wgShowExceptionDetails'] = true;
1763 // Don't break forms
1764 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1766 // Extended debugging
1767 $GLOBALS['wgShowSQLErrors'] = true;
1768 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1770 // Allow multiple ob_flush() calls
1771 $GLOBALS['wgDisableOutputCompression'] = true;
1773 // Use a sensible cookie prefix (not my_wiki)
1774 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1776 // Some of the environment checks make shell requests, remove limits
1777 $GLOBALS['wgMaxShellMemory'] = 0;
1779 // Override the default CookieSessionProvider with a dummy
1780 // implementation that won't stomp on PHP's cookies.
1781 $GLOBALS['wgSessionProviders'] = [
1783 'class' => InstallerSessionProvider
::class,
1790 // Don't try to use any object cache for SessionManager either.
1791 $GLOBALS['wgSessionCacheType'] = CACHE_NONE
;
1795 * Add an installation step following the given step.
1797 * @param callable $callback A valid installation callback array, in this form:
1798 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1799 * @param string $findStep The step to find. Omit to put the step at the beginning
1801 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1802 $this->extraInstallSteps
[$findStep][] = $callback;
1806 * Disable the time limit for execution.
1807 * Some long-running pages (Install, Upgrade) will want to do this
1809 protected function disableTimeLimit() {
1810 Wikimedia\
suppressWarnings();
1811 set_time_limit( 0 );
1812 Wikimedia\restoreWarnings
();