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
26 use MediaWiki\MediaWikiServices
;
29 * This documentation group collects source code files with deployment functionality.
31 * @defgroup Deployment Deployment
35 * Base installer class.
37 * This class provides the base for installation and update functionality
38 * for both MediaWiki core and extensions.
43 abstract class Installer
{
46 * The oldest version of PCRE we can support.
48 * Defining this is necessary because PHP may be linked with a system version
49 * of PCRE, which may be older than that bundled with the minimum PHP version.
51 const MINIMUM_PCRE_VERSION
= '7.2';
59 * List of detected DBs, access using getCompiledDBs().
63 protected $compiledDBs;
66 * Cached DB installer instances, access using getDBInstaller().
70 protected $dbInstallers = [];
73 * Minimum memory size in MB.
77 protected $minMemorySize = 50;
80 * Cached Title, used by parse().
84 protected $parserTitle;
87 * Cached ParserOptions, used by parse().
91 protected $parserOptions;
94 * Known database types. These correspond to the class names <type>Installer,
95 * and are also MediaWiki database types valid for $wgDBtype.
97 * To add a new type, create a <type>Installer class and a Database<type>
98 * class, and add a config-type-<type> message to MessagesEn.php.
102 protected static $dbTypes = [
111 * A list of environment check methods called by doEnvironmentChecks().
112 * These may output warnings using showMessage(), and/or abort the
113 * installation process by returning false.
115 * For the WebInstaller these are only called on the Welcome page,
116 * if these methods have side-effects that should affect later page loads
117 * (as well as the generated stylesheet), use envPreps instead.
121 protected $envChecks = [
127 'envCheckModSecurity',
133 'envCheckShellLocale',
134 'envCheckUploadsDirectory',
136 'envCheckSuhosinMaxValueLength',
141 * A list of environment preparation methods called by doEnvironmentPreps().
145 protected $envPreps = [
151 * MediaWiki configuration globals that will eventually be passed through
152 * to LocalSettings.php. The names only are given here, the defaults
153 * typically come from DefaultSettings.php.
157 protected $defaultVarNames = [
168 'wgEmailAuthentication',
172 'wgImageMagickConvertCommand',
177 'wgDeletedDirectory',
181 '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 (T50084); 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 'apcu' => 'apcu_fetch',
249 'wincache' => 'wincache_ucache_get'
253 * User rights profiles.
257 public $rightsProfiles = [
260 '*' => [ 'edit' => false ]
264 'createaccount' => false,
270 'createaccount' => false,
284 'url' => 'https://creativecommons.org/licenses/by/4.0/',
285 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
288 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
289 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
292 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
293 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
296 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
297 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
300 'url' => 'https://www.gnu.org/copyleft/fdl.html',
301 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
309 // Details will be filled in by the selector.
317 * URL to mediawiki-announce subscription
319 protected $mediaWikiAnnounceUrl =
320 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
323 * Supported language codes for Mailman
325 protected $mediaWikiAnnounceLanguages = [
326 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
327 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
328 'sl', 'sr', 'sv', 'tr', 'uk'
332 * UI interface for displaying a short message
333 * The parameters are like parameters to wfMessage().
334 * The messages will be in wikitext format, which will be converted to an
335 * output format such as HTML or text before being sent to the user.
338 abstract public function showMessage( $msg /*, ... */ );
341 * Same as showMessage(), but for displaying errors
344 abstract public function showError( $msg /*, ... */ );
347 * Show a message to the installing user by using a Status object
348 * @param Status $status
350 abstract public function showStatusMessage( Status
$status );
353 * Constructs a Config object that contains configuration settings that should be
354 * overwritten for the installation process.
358 * @param Config $baseConfig
360 * @return Config The config to use during installation.
362 public static function getInstallerConfig( Config
$baseConfig ) {
363 $configOverrides = new HashConfig();
365 // disable (problematic) object cache types explicitly, preserving all other (working) ones
367 $emptyCache = [ 'class' => 'EmptyBagOStuff' ];
370 CACHE_NONE
=> $emptyCache,
371 CACHE_DB
=> $emptyCache,
372 CACHE_ANYTHING
=> $emptyCache,
373 CACHE_MEMCACHED
=> $emptyCache,
374 ] +
$baseConfig->get( 'ObjectCaches' );
376 $configOverrides->set( 'ObjectCaches', $objectCaches );
378 // Load the installer's i18n.
379 $messageDirs = $baseConfig->get( 'MessagesDirs' );
380 $messageDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
382 $configOverrides->set( 'MessagesDirs', $messageDirs );
384 $installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
386 // make sure we use the installer config as the main config
387 $configRegistry = $baseConfig->get( 'ConfigRegistry' );
388 $configRegistry['main'] = function () use ( $installerConfig ) {
389 return $installerConfig;
392 $configOverrides->set( 'ConfigRegistry', $configRegistry );
394 return $installerConfig;
398 * Constructor, always call this from child classes.
400 public function __construct() {
401 global $wgMemc, $wgUser, $wgObjectCaches;
403 $defaultConfig = new GlobalVarConfig(); // all the stuff from DefaultSettings.php
404 $installerConfig = self
::getInstallerConfig( $defaultConfig );
406 // Reset all services and inject config overrides
407 MediaWiki\MediaWikiServices
::resetGlobalInstance( $installerConfig );
409 // Don't attempt to load user language options (T126177)
410 // This will be overridden in the web installer with the user-specified language
411 RequestContext
::getMain()->setLanguage( 'en' );
413 // Disable the i18n cache
414 // TODO: manage LocalisationCache singleton in MediaWikiServices
415 Language
::getLocalisationCache()->disableBackend();
417 // Disable all global services, since we don't have any configuration yet!
418 MediaWiki\MediaWikiServices
::disableStorageBackend();
420 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
421 // SqlBagOStuff will then throw since we just disabled wfGetDB)
422 $wgObjectCaches = MediaWikiServices
::getInstance()->getMainConfig()->get( 'ObjectCaches' );
423 $wgMemc = ObjectCache
::getInstance( CACHE_NONE
);
425 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
426 $wgUser = User
::newFromId( 0 );
427 RequestContext
::getMain()->setUser( $wgUser );
429 $this->settings
= $this->internalDefaults
;
431 foreach ( $this->defaultVarNames
as $var ) {
432 $this->settings
[$var] = $GLOBALS[$var];
435 $this->doEnvironmentPreps();
437 $this->compiledDBs
= [];
438 foreach ( self
::getDBTypes() as $type ) {
439 $installer = $this->getDBInstaller( $type );
441 if ( !$installer->isCompiled() ) {
444 $this->compiledDBs
[] = $type;
447 $this->parserTitle
= Title
::newFromText( 'Installer' );
448 $this->parserOptions
= new ParserOptions( $wgUser ); // language will be wrong :(
449 $this->parserOptions
->setEditSection( false );
450 $this->parserOptions
->setWrapOutputClass( false );
451 // Don't try to access DB before user language is initialised
452 $this->setParserLanguage( Language
::factory( 'en' ) );
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 the DatabaseInstaller class name for this type
552 * @param string $type database type ($wgDBtype)
553 * @return string Class name
556 public static function getDBInstallerClass( $type ) {
557 return ucfirst( $type ) . 'Installer';
561 * Get an instance of DatabaseInstaller for the specified DB type.
563 * @param mixed $type DB installer for which is needed, false to use default.
565 * @return DatabaseInstaller
567 public function getDBInstaller( $type = false ) {
569 $type = $this->getVar( 'wgDBtype' );
572 $type = strtolower( $type );
574 if ( !isset( $this->dbInstallers
[$type] ) ) {
575 $class = self
::getDBInstallerClass( $type );
576 $this->dbInstallers
[$type] = new $class( $this );
579 return $this->dbInstallers
[$type];
583 * Determine if LocalSettings.php exists. If it does, return its variables.
585 * @return array|false
587 public static function getExistingLocalSettings() {
590 // You might be wondering why this is here. Well if you don't do this
591 // then some poorly-formed extensions try to call their own classes
592 // after immediately registering them. We really need to get extension
593 // registration out of the global scope and into a real format.
594 // @see https://phabricator.wikimedia.org/T69440
595 global $wgAutoloadClasses;
596 $wgAutoloadClasses = [];
598 // @codingStandardsIgnoreStart
599 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
600 // Define the required globals here, to ensure, the functions can do it work correctly.
601 global $wgExtensionDirectory, $wgStyleDirectory;
602 // @codingStandardsIgnoreEnd
604 MediaWiki\
suppressWarnings();
605 $_lsExists = file_exists( "$IP/LocalSettings.php" );
606 MediaWiki\restoreWarnings
();
613 require "$IP/includes/DefaultSettings.php";
614 require "$IP/LocalSettings.php";
616 return get_defined_vars();
620 * Get a fake password for sending back to the user in HTML.
621 * This is a security mechanism to avoid compromise of the password in the
622 * event of session ID compromise.
624 * @param string $realPassword
628 public function getFakePassword( $realPassword ) {
629 return str_repeat( '*', strlen( $realPassword ) );
633 * Set a variable which stores a password, except if the new value is a
634 * fake password in which case leave it as it is.
636 * @param string $name
637 * @param mixed $value
639 public function setPassword( $name, $value ) {
640 if ( !preg_match( '/^\*+$/', $value ) ) {
641 $this->setVar( $name, $value );
646 * On POSIX systems return the primary group of the webserver we're running under.
647 * On other systems just returns null.
649 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
650 * webserver user before he can install.
652 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
656 public static function maybeGetWebserverPrimaryGroup() {
657 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
658 # I don't know this, this isn't UNIX.
662 # posix_getegid() *not* getmygid() because we want the group of the webserver,
663 # not whoever owns the current script.
664 $gid = posix_getegid();
665 $group = posix_getpwuid( $gid )['name'];
671 * Convert wikitext $text to HTML.
673 * This is potentially error prone since many parser features require a complete
674 * installed MW database. The solution is to just not use those features when you
675 * write your messages. This appears to work well enough. Basic formatting and
676 * external links work just fine.
678 * But in case a translator decides to throw in a "#ifexist" or internal link or
679 * whatever, this function is guarded to catch the attempted DB access and to present
680 * some fallback text.
682 * @param string $text
683 * @param bool $lineStart
686 public function parse( $text, $lineStart = false ) {
690 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
691 $html = $out->getText( [
692 'enableSectionEditLinks' => false,
694 } catch ( MediaWiki\Services\ServiceDisabledException
$e ) {
695 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
697 if ( !empty( $this->debug
) ) {
698 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
706 * @return ParserOptions
708 public function getParserOptions() {
709 return $this->parserOptions
;
712 public function disableLinkPopups() {
713 $this->parserOptions
->setExternalLinkTarget( false );
716 public function restoreLinkPopups() {
717 global $wgExternalLinkTarget;
718 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
722 * Install step which adds a row to the site_stats table with appropriate
725 * @param DatabaseInstaller $installer
729 public function populateSiteStats( DatabaseInstaller
$installer ) {
730 $status = $installer->getConnection();
731 if ( !$status->isOK() ) {
734 $status->value
->insert(
738 'ss_total_edits' => 0,
739 'ss_good_articles' => 0,
740 'ss_total_pages' => 0,
742 'ss_active_users' => 0,
748 return Status
::newGood();
752 * Environment check for DB types.
755 protected function envCheckDB() {
760 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
761 // config-type-sqlite
762 foreach ( self
::getDBTypes() as $name ) {
763 $allNames[] = wfMessage( "config-type-$name" )->text();
766 $databases = $this->getCompiledDBs();
768 $databases = array_flip( $databases );
769 foreach ( array_keys( $databases ) as $db ) {
770 $installer = $this->getDBInstaller( $db );
771 $status = $installer->checkPrerequisites();
772 if ( !$status->isGood() ) {
773 $this->showStatusMessage( $status );
775 if ( !$status->isOK() ) {
776 unset( $databases[$db] );
779 $databases = array_flip( $databases );
781 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
783 // @todo FIXME: This only works for the web installer!
791 * Some versions of libxml+PHP break < and > encoding horribly
794 protected function envCheckBrokenXML() {
795 $test = new PhpXmlBugTester();
797 $this->showError( 'config-brokenlibxml' );
806 * Environment check for the PCRE module.
808 * @note If this check were to fail, the parser would
809 * probably throw an exception before the result
810 * of this check is shown to the user.
813 protected function envCheckPCRE() {
814 MediaWiki\
suppressWarnings();
815 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
816 // Need to check for \p support too, as PCRE can be compiled
817 // with utf8 support, but not unicode property support.
818 // check that \p{Zs} (space separators) matches
819 // U+3000 (Ideographic space)
820 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
821 MediaWiki\restoreWarnings
();
822 if ( $regexd != '--' ||
$regexprop != '--' ) {
823 $this->showError( 'config-pcre-no-utf8' );
832 * Environment check for available memory.
835 protected function envCheckMemory() {
836 $limit = ini_get( 'memory_limit' );
838 if ( !$limit ||
$limit == -1 ) {
842 $n = wfShorthandToInteger( $limit );
844 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
845 $newLimit = "{$this->minMemorySize}M";
847 if ( ini_set( "memory_limit", $newLimit ) === false ) {
848 $this->showMessage( 'config-memory-bad', $limit );
850 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
851 $this->setVar( '_RaiseMemory', true );
859 * Environment check for compiled object cache types.
861 protected function envCheckCache() {
863 foreach ( $this->objectCaches
as $name => $function ) {
864 if ( function_exists( $function ) ) {
865 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
868 $caches[$name] = true;
873 $key = 'config-no-cache-apcu';
874 $this->showMessage( $key );
877 $this->setVar( '_Caches', $caches );
881 * Scare user to death if they have mod_security or mod_security2
884 protected function envCheckModSecurity() {
885 if ( self
::apacheModulePresent( 'mod_security' )
886 || self
::apacheModulePresent( 'mod_security2' ) ) {
887 $this->showMessage( 'config-mod-security' );
894 * Search for GNU diff3.
897 protected function envCheckDiff3() {
898 $names = [ "gdiff3", "diff3" ];
899 if ( wfIsWindows() ) {
900 $names[] = 'diff3.exe';
902 $versionInfo = [ '--version', 'GNU diffutils' ];
904 $diff3 = ExecutableFinder
::findInDefaultPaths( $names, $versionInfo );
907 $this->setVar( 'wgDiff3', $diff3 );
909 $this->setVar( 'wgDiff3', false );
910 $this->showMessage( 'config-diff3-bad' );
917 * Environment check for ImageMagick and GD.
920 protected function envCheckGraphics() {
921 $names = wfIsWindows() ?
'convert.exe' : 'convert';
922 $versionInfo = [ '-version', 'ImageMagick' ];
923 $convert = ExecutableFinder
::findInDefaultPaths( $names, $versionInfo );
925 $this->setVar( 'wgImageMagickConvertCommand', '' );
927 $this->setVar( 'wgImageMagickConvertCommand', $convert );
928 $this->showMessage( 'config-imagemagick', $convert );
931 } elseif ( function_exists( 'imagejpeg' ) ) {
932 $this->showMessage( 'config-gd' );
934 $this->showMessage( 'config-no-scaling' );
946 protected function envCheckGit() {
947 $names = wfIsWindows() ?
'git.exe' : 'git';
948 $versionInfo = [ '--version', 'git version' ];
950 $git = ExecutableFinder
::findInDefaultPaths( $names, $versionInfo );
953 $this->setVar( 'wgGitBin', $git );
954 $this->showMessage( 'config-git', $git );
956 $this->setVar( 'wgGitBin', false );
957 $this->showMessage( 'config-git-bad' );
964 * Environment check to inform user which server we've assumed.
968 protected function envCheckServer() {
969 $server = $this->envGetDefaultServer();
970 if ( $server !== null ) {
971 $this->showMessage( 'config-using-server', $server );
977 * Environment check to inform user which paths we've assumed.
981 protected function envCheckPath() {
984 $this->getVar( 'wgServer' ),
985 $this->getVar( 'wgScriptPath' )
991 * Environment check for preferred locale in shell
994 protected function envCheckShellLocale() {
995 $os = php_uname( 's' );
996 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
998 if ( !in_array( $os, $supported ) ) {
1002 # Get a list of available locales.
1004 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1010 $lines = array_map( 'trim', explode( "\n", $lines ) );
1011 $candidatesByLocale = [];
1012 $candidatesByLang = [];
1014 foreach ( $lines as $line ) {
1015 if ( $line === '' ) {
1019 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1023 list( , $lang, , , ) = $m;
1025 $candidatesByLocale[$m[0]] = $m;
1026 $candidatesByLang[$lang][] = $m;
1029 # Try the current value of LANG.
1030 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1031 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1036 # Try the most common ones.
1037 $commonLocales = [ 'C.UTF-8', 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1038 foreach ( $commonLocales as $commonLocale ) {
1039 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1040 $this->setVar( 'wgShellLocale', $commonLocale );
1046 # Is there an available locale in the Wiki's language?
1047 $wikiLang = $this->getVar( 'wgLanguageCode' );
1049 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1050 $m = reset( $candidatesByLang[$wikiLang] );
1051 $this->setVar( 'wgShellLocale', $m[0] );
1056 # Are there any at all?
1057 if ( count( $candidatesByLocale ) ) {
1058 $m = reset( $candidatesByLocale );
1059 $this->setVar( 'wgShellLocale', $m[0] );
1069 * Environment check for the permissions of the uploads directory
1072 protected function envCheckUploadsDirectory() {
1075 $dir = $IP . '/images/';
1076 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1077 $safe = !$this->dirIsExecutable( $dir, $url );
1080 $this->showMessage( 'config-uploads-not-safe', $dir );
1087 * Checks if suhosin.get.max_value_length is set, and if so generate
1088 * a warning because it decreases ResourceLoader performance.
1091 protected function envCheckSuhosinMaxValueLength() {
1092 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1093 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1094 // Only warn if the value is below the sane 1024
1095 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1102 * Checks if we're running on 64 bit or not. 32 bit is becoming increasingly
1103 * hard to support, so let's at least warn people.
1107 protected function envCheck64Bit() {
1108 if ( PHP_INT_SIZE
== 4 ) {
1109 $this->showMessage( 'config-using-32bit' );
1116 * Convert a hex string representing a Unicode code point to that code point.
1118 * @return string|false
1120 protected function unicodeChar( $c ) {
1124 } elseif ( $c <= 0x7FF ) {
1125 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1126 } elseif ( $c <= 0xFFFF ) {
1127 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F ) .
1128 chr( 0x80 |
$c & 0x3F );
1129 } elseif ( $c <= 0x10FFFF ) {
1130 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F ) .
1131 chr( 0x80 |
$c >> 6 & 0x3F ) .
1132 chr( 0x80 |
$c & 0x3F );
1139 * Check the libicu version
1141 protected function envCheckLibicu() {
1143 * This needs to be updated something that the latest libicu
1144 * will properly normalize. This normalization was found at
1145 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1146 * Note that we use the hex representation to create the code
1147 * points in order to avoid any Unicode-destroying during transit.
1149 $not_normal_c = $this->unicodeChar( "FA6C" );
1150 $normal_c = $this->unicodeChar( "242EE" );
1152 $useNormalizer = 'php';
1153 $needsUpdate = false;
1155 if ( function_exists( 'normalizer_normalize' ) ) {
1156 $useNormalizer = 'intl';
1157 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1158 if ( $intl !== $normal_c ) {
1159 $needsUpdate = true;
1163 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1164 if ( $useNormalizer === 'php' ) {
1165 $this->showMessage( 'config-unicode-pure-php-warning' );
1167 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1168 if ( $needsUpdate ) {
1169 $this->showMessage( 'config-unicode-update-warning' );
1175 * Environment prep for the server hostname.
1177 protected function envPrepServer() {
1178 $server = $this->envGetDefaultServer();
1179 if ( $server !== null ) {
1180 $this->setVar( 'wgServer', $server );
1185 * Helper function to be called from envPrepServer()
1188 abstract protected function envGetDefaultServer();
1191 * Environment prep for setting $IP and $wgScriptPath.
1193 protected function envPrepPath() {
1195 $IP = dirname( dirname( __DIR__
) );
1196 $this->setVar( 'IP', $IP );
1200 * Checks if scripts located in the given directory can be executed via the given URL.
1202 * Used only by environment checks.
1203 * @param string $dir
1204 * @param string $url
1205 * @return bool|int|string
1207 public function dirIsExecutable( $dir, $url ) {
1210 "<?php echo 'ex' . 'ec';",
1211 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1215 // it would be good to check other popular languages here, but it'll be slow.
1217 MediaWiki\
suppressWarnings();
1219 foreach ( $scriptTypes as $ext => $contents ) {
1220 foreach ( $contents as $source ) {
1221 $file = 'exectest.' . $ext;
1223 if ( !file_put_contents( $dir . $file, $source ) ) {
1228 $text = Http
::get( $url . $file, [ 'timeout' => 3 ], __METHOD__
);
1229 } catch ( Exception
$e ) {
1230 // Http::get throws with allow_url_fopen = false and no curl extension.
1233 unlink( $dir . $file );
1235 if ( $text == 'exec' ) {
1236 MediaWiki\restoreWarnings
();
1243 MediaWiki\restoreWarnings
();
1249 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1251 * @param string $moduleName Name of module to check.
1254 public static function apacheModulePresent( $moduleName ) {
1255 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1258 // try it the hard way
1260 phpinfo( INFO_MODULES
);
1261 $info = ob_get_clean();
1263 return strpos( $info, $moduleName ) !== false;
1267 * ParserOptions are constructed before we determined the language, so fix it
1269 * @param Language $lang
1271 public function setParserLanguage( $lang ) {
1272 $this->parserOptions
->setTargetLanguage( $lang );
1273 $this->parserOptions
->setUserLang( $lang );
1277 * Overridden by WebInstaller to provide lastPage parameters.
1278 * @param string $page
1281 protected function getDocUrl( $page ) {
1282 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1286 * Finds extensions that follow the format /$directory/Name/Name.php,
1287 * and returns an array containing the value for 'Name' for each found extension.
1289 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1291 * @param string $directory Directory to search in
1292 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1294 public function findExtensions( $directory = 'extensions' ) {
1295 if ( $this->getVar( 'IP' ) === null ) {
1299 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1300 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1304 // extensions -> extension.json, skins -> skin.json
1305 $jsonFile = substr( $directory, 0, strlen( $directory ) - 1 ) . '.json';
1307 $dh = opendir( $extDir );
1309 while ( ( $file = readdir( $dh ) ) !== false ) {
1310 if ( !is_dir( "$extDir/$file" ) ) {
1313 if ( file_exists( "$extDir/$file/$jsonFile" ) ||
file_exists( "$extDir/$file/$file.php" ) ) {
1314 // Extension exists. Now see if there are screenshots
1316 if ( is_dir( "$extDir/$file/screenshots" ) ) {
1317 $paths = glob( "$extDir/$file/screenshots/*.png" );
1318 foreach ( $paths as $path ) {
1319 $exts[$file]['screenshots'][] = str_replace( $extDir, "../$directory", $path );
1326 uksort( $exts, 'strnatcasecmp' );
1332 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1333 * but will fall back to another if the default skin is missing and some other one is present
1336 * @param string[] $skinNames Names of installed skins.
1339 public function getDefaultSkin( array $skinNames ) {
1340 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1341 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1342 return $defaultSkin;
1344 return $skinNames[0];
1349 * Installs the auto-detected extensions.
1353 protected function includeExtensions() {
1355 $exts = $this->getVar( '_Extensions' );
1356 $IP = $this->getVar( 'IP' );
1359 * We need to include DefaultSettings before including extensions to avoid
1360 * warnings about unset variables. However, the only thing we really
1361 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1362 * if the extension has hidden hook registration in $wgExtensionFunctions,
1363 * but we're not opening that can of worms
1364 * @see https://phabricator.wikimedia.org/T28857
1366 global $wgAutoloadClasses;
1367 $wgAutoloadClasses = [];
1370 require "$IP/includes/DefaultSettings.php";
1372 foreach ( $exts as $e ) {
1373 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1374 $queue["$IP/extensions/$e/extension.json"] = 1;
1376 require_once "$IP/extensions/$e/$e.php";
1380 $registry = new ExtensionRegistry();
1381 $data = $registry->readFromQueue( $queue );
1382 $wgAutoloadClasses +
= $data['autoload'];
1384 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1385 /** @suppress PhanUndeclaredVariable $wgHooks is set by DefaultSettings */
1386 $wgHooks['LoadExtensionSchemaUpdates'] : [];
1388 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1389 $hooksWeWant = array_merge_recursive(
1391 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1394 // Unset everyone else's hooks. Lord knows what someone might be doing
1395 // in ParserFirstCallInit (see T29171)
1396 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1398 return Status
::newGood();
1402 * Get an array of install steps. Should always be in the format of
1404 * 'name' => 'someuniquename',
1405 * 'callback' => [ $obj, 'method' ],
1407 * There must be a config-install-$name message defined per step, which will
1408 * be shown on install.
1410 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1413 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1414 $coreInstallSteps = [
1415 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1416 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1417 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1418 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1419 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1420 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1421 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1422 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1425 // Build the array of install steps starting from the core install list,
1426 // then adding any callbacks that wanted to attach after a given step
1427 foreach ( $coreInstallSteps as $step ) {
1428 $this->installSteps
[] = $step;
1429 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1430 $this->installSteps
= array_merge(
1431 $this->installSteps
,
1432 $this->extraInstallSteps
[$step['name']]
1437 // Prepend any steps that want to be at the beginning
1438 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1439 $this->installSteps
= array_merge(
1440 $this->extraInstallSteps
['BEGINNING'],
1445 // Extensions should always go first, chance to tie into hooks and such
1446 if ( count( $this->getVar( '_Extensions' ) ) ) {
1447 array_unshift( $this->installSteps
,
1448 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1450 $this->installSteps
[] = [
1451 'name' => 'extension-tables',
1452 'callback' => [ $installer, 'createExtensionTables' ]
1456 return $this->installSteps
;
1460 * Actually perform the installation.
1462 * @param callable $startCB A callback array for the beginning of each step
1463 * @param callable $endCB A callback array for the end of each step
1465 * @return array Array of Status objects
1467 public function performInstallation( $startCB, $endCB ) {
1468 $installResults = [];
1469 $installer = $this->getDBInstaller();
1470 $installer->preInstall();
1471 $steps = $this->getInstallSteps( $installer );
1472 foreach ( $steps as $stepObj ) {
1473 $name = $stepObj['name'];
1474 call_user_func_array( $startCB, [ $name ] );
1476 // Perform the callback step
1477 $status = call_user_func( $stepObj['callback'], $installer );
1479 // Output and save the results
1480 call_user_func( $endCB, $name, $status );
1481 $installResults[$name] = $status;
1483 // If we've hit some sort of fatal, we need to bail.
1484 // Callback already had a chance to do output above.
1485 if ( !$status->isOk() ) {
1489 if ( $status->isOk() ) {
1491 'config-install-success',
1492 $this->getVar( 'wgServer' ),
1493 $this->getVar( 'wgScriptPath' )
1495 $this->setVar( '_InstallDone', true );
1498 return $installResults;
1502 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1506 public function generateKeys() {
1507 $keys = [ 'wgSecretKey' => 64 ];
1508 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1509 $keys['wgUpgradeKey'] = 16;
1512 return $this->doGenerateKeys( $keys );
1516 * Generate a secret value for variables using our CryptRand generator.
1517 * Produce a warning if the random source was insecure.
1519 * @param array $keys
1522 protected function doGenerateKeys( $keys ) {
1523 $status = Status
::newGood();
1526 foreach ( $keys as $name => $length ) {
1527 $secretKey = MWCryptRand
::generateHex( $length, true );
1528 if ( !MWCryptRand
::wasStrong() ) {
1532 $this->setVar( $name, $secretKey );
1536 $names = array_keys( $keys );
1537 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1539 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1546 * Create the first user account, grant it sysop and bureaucrat rights
1550 protected function createSysop() {
1551 $name = $this->getVar( '_AdminName' );
1552 $user = User
::newFromName( $name );
1555 // We should've validated this earlier anyway!
1556 return Status
::newFatal( 'config-admin-error-user', $name );
1559 if ( $user->idForName() == 0 ) {
1560 $user->addToDatabase();
1563 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1564 } catch ( PasswordError
$pwe ) {
1565 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1568 $user->addGroup( 'sysop' );
1569 $user->addGroup( 'bureaucrat' );
1570 if ( $this->getVar( '_AdminEmail' ) ) {
1571 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1573 $user->saveSettings();
1575 // Update user count
1576 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1577 $ssUpdate->doUpdate();
1579 $status = Status
::newGood();
1581 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1582 $this->subscribeToMediaWikiAnnounce( $status );
1591 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1593 'email' => $this->getVar( '_AdminEmail' ),
1598 // Mailman doesn't support as many languages as we do, so check to make
1599 // sure their selected language is available
1600 $myLang = $this->getVar( '_UserLang' );
1601 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1602 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1603 $params['language'] = $myLang;
1606 if ( MWHttpRequest
::canMakeRequests() ) {
1607 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1608 [ 'method' => 'POST', 'postData' => $params ], __METHOD__
)->execute();
1609 if ( !$res->isOK() ) {
1610 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1613 $s->warning( 'config-install-subscribe-notpossible' );
1618 * Insert Main Page with default content.
1620 * @param DatabaseInstaller $installer
1623 protected function createMainpage( DatabaseInstaller
$installer ) {
1624 $status = Status
::newGood();
1625 $title = Title
::newMainPage();
1626 if ( $title->exists() ) {
1627 $status->warning( 'config-install-mainpage-exists' );
1631 $page = WikiPage
::factory( $title );
1632 $content = new WikitextContent(
1633 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1634 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1637 $status = $page->doEditContent( $content,
1641 User
::newFromName( 'MediaWiki default' )
1643 } catch ( Exception
$e ) {
1644 // using raw, because $wgShowExceptionDetails can not be set yet
1645 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1652 * Override the necessary bits of the config to run an installation.
1654 public static function overrideConfig() {
1655 // Use PHP's built-in session handling, since MediaWiki's
1656 // SessionHandler can't work before we have an object cache set up.
1657 define( 'MW_NO_SESSION_HANDLER', 1 );
1659 // Don't access the database
1660 $GLOBALS['wgUseDatabaseMessages'] = false;
1661 // Don't cache langconv tables
1662 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1664 $GLOBALS['wgShowExceptionDetails'] = true;
1665 // Don't break forms
1666 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1668 // Extended debugging
1669 $GLOBALS['wgShowSQLErrors'] = true;
1670 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1672 // Allow multiple ob_flush() calls
1673 $GLOBALS['wgDisableOutputCompression'] = true;
1675 // Use a sensible cookie prefix (not my_wiki)
1676 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1678 // Some of the environment checks make shell requests, remove limits
1679 $GLOBALS['wgMaxShellMemory'] = 0;
1681 // Override the default CookieSessionProvider with a dummy
1682 // implementation that won't stomp on PHP's cookies.
1683 $GLOBALS['wgSessionProviders'] = [
1685 'class' => 'InstallerSessionProvider',
1692 // Don't try to use any object cache for SessionManager either.
1693 $GLOBALS['wgSessionCacheType'] = CACHE_NONE
;
1697 * Add an installation step following the given step.
1699 * @param callable $callback A valid installation callback array, in this form:
1700 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1701 * @param string $findStep The step to find. Omit to put the step at the beginning
1703 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1704 $this->extraInstallSteps
[$findStep][] = $callback;
1708 * Disable the time limit for execution.
1709 * Some long-running pages (Install, Upgrade) will want to do this
1711 protected function disableTimeLimit() {
1712 MediaWiki\
suppressWarnings();
1713 set_time_limit( 0 );
1714 MediaWiki\restoreWarnings
();