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',
140 * A list of environment preparation methods called by doEnvironmentPreps().
144 protected $envPreps = [
150 * MediaWiki configuration globals that will eventually be passed through
151 * to LocalSettings.php. The names only are given here, the defaults
152 * typically come from DefaultSettings.php.
156 protected $defaultVarNames = [
167 'wgEmailAuthentication',
171 'wgImageMagickConvertCommand',
176 'wgDeletedDirectory',
180 'wgUseInstantCommons',
187 * Variables that are stored alongside globals, and are used for any
188 * configuration of the installation process aside from the MediaWiki
189 * configuration. Map of names to defaults.
193 protected $internalDefaults = [
195 '_Environment' => false,
196 '_RaiseMemory' => false,
197 '_UpgradeDone' => false,
198 '_InstallDone' => false,
200 '_InstallPassword' => '',
201 '_SameAccount' => true,
202 '_CreateDBAccount' => false,
203 '_NamespaceType' => 'site-name',
204 '_AdminName' => '', // will be set later, when the user selects language
205 '_AdminPassword' => '',
206 '_AdminPasswordConfirm' => '',
208 '_Subscribe' => false,
209 '_SkipOptional' => 'continue',
210 '_RightsProfile' => 'wiki',
211 '_LicenseCode' => 'none',
215 '_MemCachedServers' => '',
216 '_UpgradeKeySupplied' => false,
217 '_ExistingDBSettings' => false,
219 // $wgLogo is probably wrong (T50084); set something that will work.
220 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
221 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
222 'wgAuthenticationTokenVersion' => 1,
226 * The actual list of installation steps. This will be initialized by getInstallSteps()
230 private $installSteps = [];
233 * Extra steps for installation, for things like DatabaseInstallers to modify
237 protected $extraInstallSteps = [];
240 * Known object cache types and the functions used to test for their existence.
244 protected $objectCaches = [
245 'xcache' => 'xcache_get',
246 'apc' => 'apc_fetch',
247 'apcu' => 'apcu_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',
299 'url' => 'https://www.gnu.org/copyleft/fdl.html',
300 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
308 // Details will be filled in by the selector.
316 * URL to mediawiki-announce subscription
318 protected $mediaWikiAnnounceUrl =
319 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
322 * Supported language codes for Mailman
324 protected $mediaWikiAnnounceLanguages = [
325 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
326 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
327 'sl', 'sr', 'sv', 'tr', 'uk'
331 * UI interface for displaying a short message
332 * The parameters are like parameters to wfMessage().
333 * The messages will be in wikitext format, which will be converted to an
334 * output format such as HTML or text before being sent to the user.
337 abstract public function showMessage( $msg /*, ... */ );
340 * Same as showMessage(), but for displaying errors
343 abstract public function showError( $msg /*, ... */ );
346 * Show a message to the installing user by using a Status object
347 * @param Status $status
349 abstract public function showStatusMessage( Status
$status );
352 * Constructs a Config object that contains configuration settings that should be
353 * overwritten for the installation process.
357 * @param Config $baseConfig
359 * @return Config The config to use during installation.
361 public static function getInstallerConfig( Config
$baseConfig ) {
362 $configOverrides = new HashConfig();
364 // disable (problematic) object cache types explicitly, preserving all other (working) ones
366 $emptyCache = [ 'class' => 'EmptyBagOStuff' ];
369 CACHE_NONE
=> $emptyCache,
370 CACHE_DB
=> $emptyCache,
371 CACHE_ANYTHING
=> $emptyCache,
372 CACHE_MEMCACHED
=> $emptyCache,
373 ] +
$baseConfig->get( 'ObjectCaches' );
375 $configOverrides->set( 'ObjectCaches', $objectCaches );
377 // Load the installer's i18n.
378 $messageDirs = $baseConfig->get( 'MessagesDirs' );
379 $messageDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
381 $configOverrides->set( 'MessagesDirs', $messageDirs );
383 $installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
385 // make sure we use the installer config as the main config
386 $configRegistry = $baseConfig->get( 'ConfigRegistry' );
387 $configRegistry['main'] = function() use ( $installerConfig ) {
388 return $installerConfig;
391 $configOverrides->set( 'ConfigRegistry', $configRegistry );
393 return $installerConfig;
397 * Constructor, always call this from child classes.
399 public function __construct() {
400 global $wgMemc, $wgUser, $wgObjectCaches;
402 $defaultConfig = new GlobalVarConfig(); // all the stuff from DefaultSettings.php
403 $installerConfig = self
::getInstallerConfig( $defaultConfig );
405 // Reset all services and inject config overrides
406 MediaWiki\MediaWikiServices
::resetGlobalInstance( $installerConfig );
408 // Don't attempt to load user language options (T126177)
409 // This will be overridden in the web installer with the user-specified language
410 RequestContext
::getMain()->setLanguage( 'en' );
412 // Disable the i18n cache
413 // TODO: manage LocalisationCache singleton in MediaWikiServices
414 Language
::getLocalisationCache()->disableBackend();
416 // Disable all global services, since we don't have any configuration yet!
417 MediaWiki\MediaWikiServices
::disableStorageBackend();
419 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
420 // SqlBagOStuff will then throw since we just disabled wfGetDB)
421 $wgObjectCaches = MediaWikiServices
::getInstance()->getMainConfig()->get( 'ObjectCaches' );
422 $wgMemc = ObjectCache
::getInstance( CACHE_NONE
);
424 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
425 $wgUser = User
::newFromId( 0 );
426 RequestContext
::getMain()->setUser( $wgUser );
428 $this->settings
= $this->internalDefaults
;
430 foreach ( $this->defaultVarNames
as $var ) {
431 $this->settings
[$var] = $GLOBALS[$var];
434 $this->doEnvironmentPreps();
436 $this->compiledDBs
= [];
437 foreach ( self
::getDBTypes() as $type ) {
438 $installer = $this->getDBInstaller( $type );
440 if ( !$installer->isCompiled() ) {
443 $this->compiledDBs
[] = $type;
446 $this->parserTitle
= Title
::newFromText( 'Installer' );
447 $this->parserOptions
= new ParserOptions( $wgUser ); // language will be wrong :(
448 $this->parserOptions
->setEditSection( false );
449 // Don't try to access DB before user language is initialised
450 $this->setParserLanguage( Language
::factory( 'en' ) );
454 * Get a list of known DB types.
458 public static function getDBTypes() {
459 return self
::$dbTypes;
463 * Do initial checks of the PHP environment. Set variables according to
464 * the observed environment.
466 * It's possible that this may be called under the CLI SAPI, not the SAPI
467 * that the wiki will primarily run under. In that case, the subclass should
468 * initialise variables such as wgScriptPath, before calling this function.
470 * Under the web subclass, it can already be assumed that PHP 5+ is in use
471 * and that sessions are working.
475 public function doEnvironmentChecks() {
476 // Php version has already been checked by entry scripts
477 // Show message here for information purposes
479 $this->showMessage( 'config-env-hhvm', HHVM_VERSION
);
481 $this->showMessage( 'config-env-php', PHP_VERSION
);
485 // Must go here because an old version of PCRE can prevent other checks from completing
486 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
487 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
488 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
491 foreach ( $this->envChecks
as $check ) {
492 $status = $this->$check();
493 if ( $status === false ) {
499 $this->setVar( '_Environment', $good );
501 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
504 public function doEnvironmentPreps() {
505 foreach ( $this->envPreps
as $prep ) {
511 * Set a MW configuration variable, or internal installer configuration variable.
513 * @param string $name
514 * @param mixed $value
516 public function setVar( $name, $value ) {
517 $this->settings
[$name] = $value;
521 * Get an MW configuration variable, or internal installer configuration variable.
522 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
523 * Installer variables are typically prefixed by an underscore.
525 * @param string $name
526 * @param mixed $default
530 public function getVar( $name, $default = null ) {
531 if ( !isset( $this->settings
[$name] ) ) {
534 return $this->settings
[$name];
539 * Get a list of DBs supported by current PHP setup
543 public function getCompiledDBs() {
544 return $this->compiledDBs
;
548 * Get an instance of DatabaseInstaller for the specified DB type.
550 * @param mixed $type DB installer for which is needed, false to use default.
552 * @return DatabaseInstaller
554 public function getDBInstaller( $type = false ) {
556 $type = $this->getVar( 'wgDBtype' );
559 $type = strtolower( $type );
561 if ( !isset( $this->dbInstallers
[$type] ) ) {
562 $class = ucfirst( $type ) . 'Installer';
563 $this->dbInstallers
[$type] = new $class( $this );
566 return $this->dbInstallers
[$type];
570 * Determine if LocalSettings.php exists. If it does, return its variables.
572 * @return array|false
574 public static function getExistingLocalSettings() {
577 // You might be wondering why this is here. Well if you don't do this
578 // then some poorly-formed extensions try to call their own classes
579 // after immediately registering them. We really need to get extension
580 // registration out of the global scope and into a real format.
581 // @see https://phabricator.wikimedia.org/T69440
582 global $wgAutoloadClasses;
583 $wgAutoloadClasses = [];
585 // @codingStandardsIgnoreStart
586 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
587 // Define the required globals here, to ensure, the functions can do it work correctly.
588 global $wgExtensionDirectory, $wgStyleDirectory;
589 // @codingStandardsIgnoreEnd
591 MediaWiki\
suppressWarnings();
592 $_lsExists = file_exists( "$IP/LocalSettings.php" );
593 MediaWiki\restoreWarnings
();
600 require "$IP/includes/DefaultSettings.php";
601 require "$IP/LocalSettings.php";
603 return get_defined_vars();
607 * Get a fake password for sending back to the user in HTML.
608 * This is a security mechanism to avoid compromise of the password in the
609 * event of session ID compromise.
611 * @param string $realPassword
615 public function getFakePassword( $realPassword ) {
616 return str_repeat( '*', strlen( $realPassword ) );
620 * Set a variable which stores a password, except if the new value is a
621 * fake password in which case leave it as it is.
623 * @param string $name
624 * @param mixed $value
626 public function setPassword( $name, $value ) {
627 if ( !preg_match( '/^\*+$/', $value ) ) {
628 $this->setVar( $name, $value );
633 * On POSIX systems return the primary group of the webserver we're running under.
634 * On other systems just returns null.
636 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
637 * webserver user before he can install.
639 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
643 public static function maybeGetWebserverPrimaryGroup() {
644 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
645 # I don't know this, this isn't UNIX.
649 # posix_getegid() *not* getmygid() because we want the group of the webserver,
650 # not whoever owns the current script.
651 $gid = posix_getegid();
652 $group = posix_getpwuid( $gid )['name'];
658 * Convert wikitext $text to HTML.
660 * This is potentially error prone since many parser features require a complete
661 * installed MW database. The solution is to just not use those features when you
662 * write your messages. This appears to work well enough. Basic formatting and
663 * external links work just fine.
665 * But in case a translator decides to throw in a "#ifexist" or internal link or
666 * whatever, this function is guarded to catch the attempted DB access and to present
667 * some fallback text.
669 * @param string $text
670 * @param bool $lineStart
673 public function parse( $text, $lineStart = false ) {
677 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
678 $html = $out->getText();
679 } catch ( MediaWiki\Services\ServiceDisabledException
$e ) {
680 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
682 if ( !empty( $this->debug
) ) {
683 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
691 * @return ParserOptions
693 public function getParserOptions() {
694 return $this->parserOptions
;
697 public function disableLinkPopups() {
698 $this->parserOptions
->setExternalLinkTarget( false );
701 public function restoreLinkPopups() {
702 global $wgExternalLinkTarget;
703 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
707 * Install step which adds a row to the site_stats table with appropriate
710 * @param DatabaseInstaller $installer
714 public function populateSiteStats( DatabaseInstaller
$installer ) {
715 $status = $installer->getConnection();
716 if ( !$status->isOK() ) {
719 $status->value
->insert(
723 'ss_total_edits' => 0,
724 'ss_good_articles' => 0,
725 'ss_total_pages' => 0,
727 'ss_active_users' => 0,
733 return Status
::newGood();
737 * Environment check for DB types.
740 protected function envCheckDB() {
745 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
746 // config-type-sqlite
747 foreach ( self
::getDBTypes() as $name ) {
748 $allNames[] = wfMessage( "config-type-$name" )->text();
751 $databases = $this->getCompiledDBs();
753 $databases = array_flip( $databases );
754 foreach ( array_keys( $databases ) as $db ) {
755 $installer = $this->getDBInstaller( $db );
756 $status = $installer->checkPrerequisites();
757 if ( !$status->isGood() ) {
758 $this->showStatusMessage( $status );
760 if ( !$status->isOK() ) {
761 unset( $databases[$db] );
764 $databases = array_flip( $databases );
766 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
768 // @todo FIXME: This only works for the web installer!
776 * Some versions of libxml+PHP break < and > encoding horribly
779 protected function envCheckBrokenXML() {
780 $test = new PhpXmlBugTester();
782 $this->showError( 'config-brokenlibxml' );
791 * Environment check for the PCRE module.
793 * @note If this check were to fail, the parser would
794 * probably throw an exception before the result
795 * of this check is shown to the user.
798 protected function envCheckPCRE() {
799 MediaWiki\
suppressWarnings();
800 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
801 // Need to check for \p support too, as PCRE can be compiled
802 // with utf8 support, but not unicode property support.
803 // check that \p{Zs} (space separators) matches
804 // U+3000 (Ideographic space)
805 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
806 MediaWiki\restoreWarnings
();
807 if ( $regexd != '--' ||
$regexprop != '--' ) {
808 $this->showError( 'config-pcre-no-utf8' );
817 * Environment check for available memory.
820 protected function envCheckMemory() {
821 $limit = ini_get( 'memory_limit' );
823 if ( !$limit ||
$limit == -1 ) {
827 $n = wfShorthandToInteger( $limit );
829 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
830 $newLimit = "{$this->minMemorySize}M";
832 if ( ini_set( "memory_limit", $newLimit ) === false ) {
833 $this->showMessage( 'config-memory-bad', $limit );
835 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
836 $this->setVar( '_RaiseMemory', true );
844 * Environment check for compiled object cache types.
846 protected function envCheckCache() {
848 foreach ( $this->objectCaches
as $name => $function ) {
849 if ( function_exists( $function ) ) {
850 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
853 $caches[$name] = true;
858 $key = 'config-no-cache-apcu';
859 $this->showMessage( $key );
862 $this->setVar( '_Caches', $caches );
866 * Scare user to death if they have mod_security or mod_security2
869 protected function envCheckModSecurity() {
870 if ( self
::apacheModulePresent( 'mod_security' )
871 || self
::apacheModulePresent( 'mod_security2' ) ) {
872 $this->showMessage( 'config-mod-security' );
879 * Search for GNU diff3.
882 protected function envCheckDiff3() {
883 $names = [ "gdiff3", "diff3", "diff3.exe" ];
884 $versionInfo = [ '$1 --version 2>&1', 'GNU diffutils' ];
886 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
889 $this->setVar( 'wgDiff3', $diff3 );
891 $this->setVar( 'wgDiff3', false );
892 $this->showMessage( 'config-diff3-bad' );
899 * Environment check for ImageMagick and GD.
902 protected function envCheckGraphics() {
903 $names = [ wfIsWindows() ?
'convert.exe' : 'convert' ];
904 $versionInfo = [ '$1 -version', 'ImageMagick' ];
905 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
907 $this->setVar( 'wgImageMagickConvertCommand', '' );
909 $this->setVar( 'wgImageMagickConvertCommand', $convert );
910 $this->showMessage( 'config-imagemagick', $convert );
913 } elseif ( function_exists( 'imagejpeg' ) ) {
914 $this->showMessage( 'config-gd' );
916 $this->showMessage( 'config-no-scaling' );
928 protected function envCheckGit() {
929 $names = [ wfIsWindows() ?
'git.exe' : 'git' ];
930 $versionInfo = [ '$1 --version', 'git version' ];
932 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
935 $this->setVar( 'wgGitBin', $git );
936 $this->showMessage( 'config-git', $git );
938 $this->setVar( 'wgGitBin', false );
939 $this->showMessage( 'config-git-bad' );
946 * Environment check to inform user which server we've assumed.
950 protected function envCheckServer() {
951 $server = $this->envGetDefaultServer();
952 if ( $server !== null ) {
953 $this->showMessage( 'config-using-server', $server );
959 * Environment check to inform user which paths we've assumed.
963 protected function envCheckPath() {
966 $this->getVar( 'wgServer' ),
967 $this->getVar( 'wgScriptPath' )
973 * Environment check for preferred locale in shell
976 protected function envCheckShellLocale() {
977 $os = php_uname( 's' );
978 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
980 if ( !in_array( $os, $supported ) ) {
984 # Get a list of available locales.
986 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
992 $lines = array_map( 'trim', explode( "\n", $lines ) );
993 $candidatesByLocale = [];
994 $candidatesByLang = [];
996 foreach ( $lines as $line ) {
997 if ( $line === '' ) {
1001 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1005 list( , $lang, , , ) = $m;
1007 $candidatesByLocale[$m[0]] = $m;
1008 $candidatesByLang[$lang][] = $m;
1011 # Try the current value of LANG.
1012 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1013 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1018 # Try the most common ones.
1019 $commonLocales = [ 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1020 foreach ( $commonLocales as $commonLocale ) {
1021 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1022 $this->setVar( 'wgShellLocale', $commonLocale );
1028 # Is there an available locale in the Wiki's language?
1029 $wikiLang = $this->getVar( 'wgLanguageCode' );
1031 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1032 $m = reset( $candidatesByLang[$wikiLang] );
1033 $this->setVar( 'wgShellLocale', $m[0] );
1038 # Are there any at all?
1039 if ( count( $candidatesByLocale ) ) {
1040 $m = reset( $candidatesByLocale );
1041 $this->setVar( 'wgShellLocale', $m[0] );
1051 * Environment check for the permissions of the uploads directory
1054 protected function envCheckUploadsDirectory() {
1057 $dir = $IP . '/images/';
1058 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1059 $safe = !$this->dirIsExecutable( $dir, $url );
1062 $this->showMessage( 'config-uploads-not-safe', $dir );
1069 * Checks if suhosin.get.max_value_length is set, and if so generate
1070 * a warning because it decreases ResourceLoader performance.
1073 protected function envCheckSuhosinMaxValueLength() {
1074 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1075 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1076 // Only warn if the value is below the sane 1024
1077 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1084 * Convert a hex string representing a Unicode code point to that code point.
1086 * @return string|false
1088 protected function unicodeChar( $c ) {
1092 } elseif ( $c <= 0x7FF ) {
1093 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1094 } elseif ( $c <= 0xFFFF ) {
1095 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F ) .
1096 chr( 0x80 |
$c & 0x3F );
1097 } elseif ( $c <= 0x10FFFF ) {
1098 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F ) .
1099 chr( 0x80 |
$c >> 6 & 0x3F ) .
1100 chr( 0x80 |
$c & 0x3F );
1107 * Check the libicu version
1109 protected function envCheckLibicu() {
1111 * This needs to be updated something that the latest libicu
1112 * will properly normalize. This normalization was found at
1113 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1114 * Note that we use the hex representation to create the code
1115 * points in order to avoid any Unicode-destroying during transit.
1117 $not_normal_c = $this->unicodeChar( "FA6C" );
1118 $normal_c = $this->unicodeChar( "242EE" );
1120 $useNormalizer = 'php';
1121 $needsUpdate = false;
1123 if ( function_exists( 'normalizer_normalize' ) ) {
1124 $useNormalizer = 'intl';
1125 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1126 if ( $intl !== $normal_c ) {
1127 $needsUpdate = true;
1131 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1132 if ( $useNormalizer === 'php' ) {
1133 $this->showMessage( 'config-unicode-pure-php-warning' );
1135 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1136 if ( $needsUpdate ) {
1137 $this->showMessage( 'config-unicode-update-warning' );
1143 * Environment prep for the server hostname.
1145 protected function envPrepServer() {
1146 $server = $this->envGetDefaultServer();
1147 if ( $server !== null ) {
1148 $this->setVar( 'wgServer', $server );
1153 * Helper function to be called from envPrepServer()
1156 abstract protected function envGetDefaultServer();
1159 * Environment prep for setting $IP and $wgScriptPath.
1161 protected function envPrepPath() {
1163 $IP = dirname( dirname( __DIR__
) );
1164 $this->setVar( 'IP', $IP );
1168 * Get an array of likely places we can find executables. Check a bunch
1169 * of known Unix-like defaults, as well as the PATH environment variable
1170 * (which should maybe make it work for Windows?)
1174 protected static function getPossibleBinPaths() {
1176 [ '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1177 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ],
1178 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1183 * Search a path for any of the given executable names. Returns the
1184 * executable name if found. Also checks the version string returned
1185 * by each executable.
1187 * Used only by environment checks.
1189 * @param string $path Path to search
1190 * @param array $names Array of executable names
1191 * @param array|bool $versionInfo False or array with two members:
1192 * 0 => Command to run for version check, with $1 for the full executable name
1193 * 1 => String to compare the output with
1195 * If $versionInfo is not false, only executables with a version
1196 * matching $versionInfo[1] will be returned.
1197 * @return bool|string
1199 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1200 if ( !is_array( $names ) ) {
1201 $names = [ $names ];
1204 foreach ( $names as $name ) {
1205 $command = $path . DIRECTORY_SEPARATOR
. $name;
1207 MediaWiki\
suppressWarnings();
1208 $file_exists = is_executable( $command );
1209 MediaWiki\restoreWarnings
();
1211 if ( $file_exists ) {
1212 if ( !$versionInfo ) {
1216 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1217 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1227 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1228 * @see locateExecutable()
1229 * @param array $names Array of possible names.
1230 * @param array|bool $versionInfo Default: false or array with two members:
1231 * 0 => Command to run for version check, with $1 for the full executable name
1232 * 1 => String to compare the output with
1234 * If $versionInfo is not false, only executables with a version
1235 * matching $versionInfo[1] will be returned.
1236 * @return bool|string
1238 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1239 foreach ( self
::getPossibleBinPaths() as $path ) {
1240 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1241 if ( $exe !== false ) {
1250 * Checks if scripts located in the given directory can be executed via the given URL.
1252 * Used only by environment checks.
1253 * @param string $dir
1254 * @param string $url
1255 * @return bool|int|string
1257 public function dirIsExecutable( $dir, $url ) {
1260 "<?php echo 'ex' . 'ec';",
1261 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1265 // it would be good to check other popular languages here, but it'll be slow.
1267 MediaWiki\
suppressWarnings();
1269 foreach ( $scriptTypes as $ext => $contents ) {
1270 foreach ( $contents as $source ) {
1271 $file = 'exectest.' . $ext;
1273 if ( !file_put_contents( $dir . $file, $source ) ) {
1278 $text = Http
::get( $url . $file, [ 'timeout' => 3 ], __METHOD__
);
1279 } catch ( Exception
$e ) {
1280 // Http::get throws with allow_url_fopen = false and no curl extension.
1283 unlink( $dir . $file );
1285 if ( $text == 'exec' ) {
1286 MediaWiki\restoreWarnings
();
1293 MediaWiki\restoreWarnings
();
1299 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1301 * @param string $moduleName Name of module to check.
1304 public static function apacheModulePresent( $moduleName ) {
1305 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1308 // try it the hard way
1310 phpinfo( INFO_MODULES
);
1311 $info = ob_get_clean();
1313 return strpos( $info, $moduleName ) !== false;
1317 * ParserOptions are constructed before we determined the language, so fix it
1319 * @param Language $lang
1321 public function setParserLanguage( $lang ) {
1322 $this->parserOptions
->setTargetLanguage( $lang );
1323 $this->parserOptions
->setUserLang( $lang );
1327 * Overridden by WebInstaller to provide lastPage parameters.
1328 * @param string $page
1331 protected function getDocUrl( $page ) {
1332 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1336 * Finds extensions that follow the format /$directory/Name/Name.php,
1337 * and returns an array containing the value for 'Name' for each found extension.
1339 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1341 * @param string $directory Directory to search in
1344 public function findExtensions( $directory = 'extensions' ) {
1345 if ( $this->getVar( 'IP' ) === null ) {
1349 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1350 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1354 // extensions -> extension.json, skins -> skin.json
1355 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1357 $dh = opendir( $extDir );
1359 while ( ( $file = readdir( $dh ) ) !== false ) {
1360 if ( !is_dir( "$extDir/$file" ) ) {
1363 if ( file_exists( "$extDir/$file/$jsonFile" ) ||
file_exists( "$extDir/$file/$file.php" ) ) {
1368 natcasesort( $exts );
1374 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1375 * but will fall back to another if the default skin is missing and some other one is present
1378 * @param string[] $skinNames Names of installed skins.
1381 public function getDefaultSkin( array $skinNames ) {
1382 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1383 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1384 return $defaultSkin;
1386 return $skinNames[0];
1391 * Installs the auto-detected extensions.
1395 protected function includeExtensions() {
1397 $exts = $this->getVar( '_Extensions' );
1398 $IP = $this->getVar( 'IP' );
1401 * We need to include DefaultSettings before including extensions to avoid
1402 * warnings about unset variables. However, the only thing we really
1403 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1404 * if the extension has hidden hook registration in $wgExtensionFunctions,
1405 * but we're not opening that can of worms
1406 * @see https://phabricator.wikimedia.org/T28857
1408 global $wgAutoloadClasses;
1409 $wgAutoloadClasses = [];
1412 require "$IP/includes/DefaultSettings.php";
1414 foreach ( $exts as $e ) {
1415 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1416 $queue["$IP/extensions/$e/extension.json"] = 1;
1418 require_once "$IP/extensions/$e/$e.php";
1422 $registry = new ExtensionRegistry();
1423 $data = $registry->readFromQueue( $queue );
1424 $wgAutoloadClasses +
= $data['autoload'];
1426 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1427 /** @suppress PhanUndeclaredVariable $wgHooks is set by DefaultSettings */
1428 $wgHooks['LoadExtensionSchemaUpdates'] : [];
1430 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1431 $hooksWeWant = array_merge_recursive(
1433 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1436 // Unset everyone else's hooks. Lord knows what someone might be doing
1437 // in ParserFirstCallInit (see T29171)
1438 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1440 return Status
::newGood();
1444 * Get an array of install steps. Should always be in the format of
1446 * 'name' => 'someuniquename',
1447 * 'callback' => [ $obj, 'method' ],
1449 * There must be a config-install-$name message defined per step, which will
1450 * be shown on install.
1452 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1455 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1456 $coreInstallSteps = [
1457 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1458 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1459 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1460 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1461 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1462 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1463 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1464 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1467 // Build the array of install steps starting from the core install list,
1468 // then adding any callbacks that wanted to attach after a given step
1469 foreach ( $coreInstallSteps as $step ) {
1470 $this->installSteps
[] = $step;
1471 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1472 $this->installSteps
= array_merge(
1473 $this->installSteps
,
1474 $this->extraInstallSteps
[$step['name']]
1479 // Prepend any steps that want to be at the beginning
1480 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1481 $this->installSteps
= array_merge(
1482 $this->extraInstallSteps
['BEGINNING'],
1487 // Extensions should always go first, chance to tie into hooks and such
1488 if ( count( $this->getVar( '_Extensions' ) ) ) {
1489 array_unshift( $this->installSteps
,
1490 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1492 $this->installSteps
[] = [
1493 'name' => 'extension-tables',
1494 'callback' => [ $installer, 'createExtensionTables' ]
1498 return $this->installSteps
;
1502 * Actually perform the installation.
1504 * @param callable $startCB A callback array for the beginning of each step
1505 * @param callable $endCB A callback array for the end of each step
1507 * @return array Array of Status objects
1509 public function performInstallation( $startCB, $endCB ) {
1510 $installResults = [];
1511 $installer = $this->getDBInstaller();
1512 $installer->preInstall();
1513 $steps = $this->getInstallSteps( $installer );
1514 foreach ( $steps as $stepObj ) {
1515 $name = $stepObj['name'];
1516 call_user_func_array( $startCB, [ $name ] );
1518 // Perform the callback step
1519 $status = call_user_func( $stepObj['callback'], $installer );
1521 // Output and save the results
1522 call_user_func( $endCB, $name, $status );
1523 $installResults[$name] = $status;
1525 // If we've hit some sort of fatal, we need to bail.
1526 // Callback already had a chance to do output above.
1527 if ( !$status->isOk() ) {
1531 if ( $status->isOk() ) {
1532 $this->setVar( '_InstallDone', true );
1535 return $installResults;
1539 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1543 public function generateKeys() {
1544 $keys = [ 'wgSecretKey' => 64 ];
1545 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1546 $keys['wgUpgradeKey'] = 16;
1549 return $this->doGenerateKeys( $keys );
1553 * Generate a secret value for variables using our CryptRand generator.
1554 * Produce a warning if the random source was insecure.
1556 * @param array $keys
1559 protected function doGenerateKeys( $keys ) {
1560 $status = Status
::newGood();
1563 foreach ( $keys as $name => $length ) {
1564 $secretKey = MWCryptRand
::generateHex( $length, true );
1565 if ( !MWCryptRand
::wasStrong() ) {
1569 $this->setVar( $name, $secretKey );
1573 $names = array_keys( $keys );
1574 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1576 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1583 * Create the first user account, grant it sysop and bureaucrat rights
1587 protected function createSysop() {
1588 $name = $this->getVar( '_AdminName' );
1589 $user = User
::newFromName( $name );
1592 // We should've validated this earlier anyway!
1593 return Status
::newFatal( 'config-admin-error-user', $name );
1596 if ( $user->idForName() == 0 ) {
1597 $user->addToDatabase();
1600 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1601 } catch ( PasswordError
$pwe ) {
1602 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1605 $user->addGroup( 'sysop' );
1606 $user->addGroup( 'bureaucrat' );
1607 if ( $this->getVar( '_AdminEmail' ) ) {
1608 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1610 $user->saveSettings();
1612 // Update user count
1613 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1614 $ssUpdate->doUpdate();
1616 $status = Status
::newGood();
1618 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1619 $this->subscribeToMediaWikiAnnounce( $status );
1628 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1630 'email' => $this->getVar( '_AdminEmail' ),
1635 // Mailman doesn't support as many languages as we do, so check to make
1636 // sure their selected language is available
1637 $myLang = $this->getVar( '_UserLang' );
1638 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1639 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1640 $params['language'] = $myLang;
1643 if ( MWHttpRequest
::canMakeRequests() ) {
1644 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1645 [ 'method' => 'POST', 'postData' => $params ], __METHOD__
)->execute();
1646 if ( !$res->isOK() ) {
1647 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1650 $s->warning( 'config-install-subscribe-notpossible' );
1655 * Insert Main Page with default content.
1657 * @param DatabaseInstaller $installer
1660 protected function createMainpage( DatabaseInstaller
$installer ) {
1661 $status = Status
::newGood();
1662 $title = Title
::newMainPage();
1663 if ( $title->exists() ) {
1664 $status->warning( 'config-install-mainpage-exists' );
1668 $page = WikiPage
::factory( $title );
1669 $content = new WikitextContent(
1670 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1671 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1674 $status = $page->doEditContent( $content,
1678 User
::newFromName( 'MediaWiki default' )
1680 } catch ( Exception
$e ) {
1681 // using raw, because $wgShowExceptionDetails can not be set yet
1682 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1689 * Override the necessary bits of the config to run an installation.
1691 public static function overrideConfig() {
1692 // Use PHP's built-in session handling, since MediaWiki's
1693 // SessionHandler can't work before we have an object cache set up.
1694 define( 'MW_NO_SESSION_HANDLER', 1 );
1696 // Don't access the database
1697 $GLOBALS['wgUseDatabaseMessages'] = false;
1698 // Don't cache langconv tables
1699 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1701 $GLOBALS['wgShowExceptionDetails'] = true;
1702 // Don't break forms
1703 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1705 // Extended debugging
1706 $GLOBALS['wgShowSQLErrors'] = true;
1707 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1709 // Allow multiple ob_flush() calls
1710 $GLOBALS['wgDisableOutputCompression'] = true;
1712 // Use a sensible cookie prefix (not my_wiki)
1713 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1715 // Some of the environment checks make shell requests, remove limits
1716 $GLOBALS['wgMaxShellMemory'] = 0;
1718 // Override the default CookieSessionProvider with a dummy
1719 // implementation that won't stomp on PHP's cookies.
1720 $GLOBALS['wgSessionProviders'] = [
1722 'class' => 'InstallerSessionProvider',
1729 // Don't try to use any object cache for SessionManager either.
1730 $GLOBALS['wgSessionCacheType'] = CACHE_NONE
;
1734 * Add an installation step following the given step.
1736 * @param callable $callback A valid installation callback array, in this form:
1737 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1738 * @param string $findStep The step to find. Omit to put the step at the beginning
1740 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1741 $this->extraInstallSteps
[$findStep][] = $callback;
1745 * Disable the time limit for execution.
1746 * Some long-running pages (Install, Upgrade) will want to do this
1748 protected function disableTimeLimit() {
1749 MediaWiki\
suppressWarnings();
1750 set_time_limit( 0 );
1751 MediaWiki\restoreWarnings
();