Set Redis::OPT_READ_TIMEOUT by default
[mediawiki.git] / includes / installer / Installer.php
blob372091a6c383671e6226495d8b9f9dcd98c4b007
1 <?php
2 /**
3 * Base code for MediaWiki installer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Deployment
24 /**
25 * This documentation group collects source code files with deployment functionality.
27 * @defgroup Deployment Deployment
30 /**
31 * Base installer class.
33 * This class provides the base for installation and update functionality
34 * for both MediaWiki core and extensions.
36 * @ingroup Deployment
37 * @since 1.17
39 abstract class Installer {
41 // This is the absolute minimum PHP version we can support
42 const MINIMUM_PHP_VERSION = '5.3.2';
44 /**
45 * The oldest version of PCRE we can support.
47 * Defining this is necessary because PHP may be linked with a system version
48 * of PCRE, which may be older than that bundled with the minimum PHP version.
50 const MINIMUM_PCRE_VERSION = '7.2';
52 /**
53 * @var array
55 protected $settings;
57 /**
58 * List of detected DBs, access using getCompiledDBs().
60 * @var array
62 protected $compiledDBs;
64 /**
65 * Cached DB installer instances, access using getDBInstaller().
67 * @var array
69 protected $dbInstallers = array();
71 /**
72 * Minimum memory size in MB.
74 * @var int
76 protected $minMemorySize = 50;
78 /**
79 * Cached Title, used by parse().
81 * @var Title
83 protected $parserTitle;
85 /**
86 * Cached ParserOptions, used by parse().
88 * @var ParserOptions
90 protected $parserOptions;
92 /**
93 * Known database types. These correspond to the class names <type>Installer,
94 * and are also MediaWiki database types valid for $wgDBtype.
96 * To add a new type, create a <type>Installer class and a Database<type>
97 * class, and add a config-type-<type> message to MessagesEn.php.
99 * @var array
101 protected static $dbTypes = array(
102 'mysql',
103 'postgres',
104 'oracle',
105 'mssql',
106 'sqlite',
110 * A list of environment check methods called by doEnvironmentChecks().
111 * These may output warnings using showMessage(), and/or abort the
112 * installation process by returning false.
114 * @var array
116 protected $envChecks = array(
117 'envCheckDB',
118 'envCheckRegisterGlobals',
119 'envCheckBrokenXML',
120 'envCheckMagicQuotes',
121 'envCheckMagicSybase',
122 'envCheckMbstring',
123 'envCheckSafeMode',
124 'envCheckXML',
125 'envCheckPCRE',
126 'envCheckMemory',
127 'envCheckCache',
128 'envCheckModSecurity',
129 'envCheckDiff3',
130 'envCheckGraphics',
131 'envCheckGit',
132 'envCheckServer',
133 'envCheckPath',
134 'envCheckExtension',
135 'envCheckShellLocale',
136 'envCheckUploadsDirectory',
137 'envCheckLibicu',
138 'envCheckSuhosinMaxValueLength',
139 'envCheckCtype',
140 'envCheckJSON',
144 * MediaWiki configuration globals that will eventually be passed through
145 * to LocalSettings.php. The names only are given here, the defaults
146 * typically come from DefaultSettings.php.
148 * @var array
150 protected $defaultVarNames = array(
151 'wgSitename',
152 'wgPasswordSender',
153 'wgLanguageCode',
154 'wgRightsIcon',
155 'wgRightsText',
156 'wgRightsUrl',
157 'wgMainCacheType',
158 'wgEnableEmail',
159 'wgEnableUserEmail',
160 'wgEnotifUserTalk',
161 'wgEnotifWatchlist',
162 'wgEmailAuthentication',
163 'wgDBtype',
164 'wgDiff3',
165 'wgImageMagickConvertCommand',
166 'wgGitBin',
167 'IP',
168 'wgScriptPath',
169 'wgScriptExtension',
170 'wgMetaNamespace',
171 'wgDeletedDirectory',
172 'wgEnableUploads',
173 'wgLogo',
174 'wgShellLocale',
175 'wgSecretKey',
176 'wgUseInstantCommons',
177 'wgUpgradeKey',
178 'wgDefaultSkin',
179 'wgResourceLoaderMaxQueryLength',
183 * Variables that are stored alongside globals, and are used for any
184 * configuration of the installation process aside from the MediaWiki
185 * configuration. Map of names to defaults.
187 * @var array
189 protected $internalDefaults = array(
190 '_UserLang' => 'en',
191 '_Environment' => false,
192 '_SafeMode' => false,
193 '_RaiseMemory' => false,
194 '_UpgradeDone' => false,
195 '_InstallDone' => false,
196 '_Caches' => array(),
197 '_InstallPassword' => '',
198 '_SameAccount' => true,
199 '_CreateDBAccount' => false,
200 '_NamespaceType' => 'site-name',
201 '_AdminName' => '', // will be set later, when the user selects language
202 '_AdminPassword' => '',
203 '_AdminPassword2' => '',
204 '_AdminEmail' => '',
205 '_Subscribe' => false,
206 '_SkipOptional' => 'continue',
207 '_RightsProfile' => 'wiki',
208 '_LicenseCode' => 'none',
209 '_CCDone' => false,
210 '_Extensions' => array(),
211 '_MemCachedServers' => '',
212 '_UpgradeKeySupplied' => false,
213 '_ExistingDBSettings' => false,
217 * The actual list of installation steps. This will be initialized by getInstallSteps()
219 * @var array
221 private $installSteps = array();
224 * Extra steps for installation, for things like DatabaseInstallers to modify
226 * @var array
228 protected $extraInstallSteps = array();
231 * Known object cache types and the functions used to test for their existence.
233 * @var array
235 protected $objectCaches = array(
236 'xcache' => 'xcache_get',
237 'apc' => 'apc_fetch',
238 'wincache' => 'wincache_ucache_get'
242 * User rights profiles.
244 * @var array
246 public $rightsProfiles = array(
247 'wiki' => array(),
248 'no-anon' => array(
249 '*' => array( 'edit' => false )
251 'fishbowl' => array(
252 '*' => array(
253 'createaccount' => false,
254 'edit' => false,
257 'private' => array(
258 '*' => array(
259 'createaccount' => false,
260 'edit' => false,
261 'read' => false,
267 * License types.
269 * @var array
271 public $licenses = array(
272 'cc-by' => array(
273 'url' => 'http://creativecommons.org/licenses/by/3.0/',
274 'icon' => '{$wgStylePath}/common/images/cc-by.png',
276 'cc-by-sa' => array(
277 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
278 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
280 'cc-by-nc-sa' => array(
281 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
282 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
284 'cc-0' => array(
285 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
286 'icon' => '{$wgStylePath}/common/images/cc-0.png',
288 'pd' => array(
289 'url' => '',
290 'icon' => '{$wgStylePath}/common/images/public-domain.png',
292 'gfdl' => array(
293 'url' => 'http://www.gnu.org/copyleft/fdl.html',
294 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
296 'none' => array(
297 'url' => '',
298 'icon' => '',
299 'text' => ''
301 'cc-choose' => array(
302 // Details will be filled in by the selector.
303 'url' => '',
304 'icon' => '',
305 'text' => '',
310 * URL to mediawiki-announce subscription
312 protected $mediaWikiAnnounceUrl =
313 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
316 * Supported language codes for Mailman
318 protected $mediaWikiAnnounceLanguages = array(
319 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
320 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
321 'sl', 'sr', 'sv', 'tr', 'uk'
325 * UI interface for displaying a short message
326 * The parameters are like parameters to wfMessage().
327 * The messages will be in wikitext format, which will be converted to an
328 * output format such as HTML or text before being sent to the user.
329 * @param string $msg
331 abstract public function showMessage( $msg /*, ... */ );
334 * Same as showMessage(), but for displaying errors
335 * @param string $msg
337 abstract public function showError( $msg /*, ... */ );
340 * Show a message to the installing user by using a Status object
341 * @param Status $status
343 abstract public function showStatusMessage( Status $status );
346 * Constructor, always call this from child classes.
348 public function __construct() {
349 global $wgMessagesDirs, $wgUser;
351 // Disable the i18n cache and LoadBalancer
352 Language::getLocalisationCache()->disableBackend();
353 LBFactory::disableBackend();
355 // Load the installer's i18n.
356 $wgMessagesDirs['MediawikiInstaller'] = __DIR__ . '/i18n';
358 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
359 $wgUser = User::newFromId( 0 );
361 $this->settings = $this->internalDefaults;
363 foreach ( $this->defaultVarNames as $var ) {
364 $this->settings[$var] = $GLOBALS[$var];
367 $compiledDBs = array();
368 foreach ( self::getDBTypes() as $type ) {
369 $installer = $this->getDBInstaller( $type );
371 if ( !$installer->isCompiled() ) {
372 continue;
374 $compiledDBs[] = $type;
376 $defaults = $installer->getGlobalDefaults();
378 foreach ( $installer->getGlobalNames() as $var ) {
379 if ( isset( $defaults[$var] ) ) {
380 $this->settings[$var] = $defaults[$var];
381 } else {
382 $this->settings[$var] = $GLOBALS[$var];
386 $this->compiledDBs = $compiledDBs;
388 $this->parserTitle = Title::newFromText( 'Installer' );
389 $this->parserOptions = new ParserOptions; // language will be wrong :(
390 $this->parserOptions->setEditSection( false );
394 * Get a list of known DB types.
396 * @return array
398 public static function getDBTypes() {
399 return self::$dbTypes;
403 * Do initial checks of the PHP environment. Set variables according to
404 * the observed environment.
406 * It's possible that this may be called under the CLI SAPI, not the SAPI
407 * that the wiki will primarily run under. In that case, the subclass should
408 * initialise variables such as wgScriptPath, before calling this function.
410 * Under the web subclass, it can already be assumed that PHP 5+ is in use
411 * and that sessions are working.
413 * @return Status
415 public function doEnvironmentChecks() {
416 $phpVersion = phpversion();
417 if ( version_compare( $phpVersion, self::MINIMUM_PHP_VERSION, '>=' ) ) {
418 $this->showMessage( 'config-env-php', $phpVersion );
419 $good = true;
420 } else {
421 $this->showMessage( 'config-env-php-toolow', $phpVersion, self::MINIMUM_PHP_VERSION );
422 $good = false;
425 // Must go here because an old version of PCRE can prevent other checks from completing
426 if ( $good ) {
427 list( $pcreVersion ) = explode( ' ', PCRE_VERSION, 2 );
428 if ( version_compare( $pcreVersion, self::MINIMUM_PCRE_VERSION, '<' ) ) {
429 $this->showError( 'config-pcre-old', self::MINIMUM_PCRE_VERSION, $pcreVersion );
430 $good = false;
434 if ( $good ) {
435 foreach ( $this->envChecks as $check ) {
436 $status = $this->$check();
437 if ( $status === false ) {
438 $good = false;
443 $this->setVar( '_Environment', $good );
445 return $good ? Status::newGood() : Status::newFatal( 'config-env-bad' );
449 * Set a MW configuration variable, or internal installer configuration variable.
451 * @param string $name
452 * @param mixed $value
454 public function setVar( $name, $value ) {
455 $this->settings[$name] = $value;
459 * Get an MW configuration variable, or internal installer configuration variable.
460 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
461 * Installer variables are typically prefixed by an underscore.
463 * @param string $name
464 * @param mixed $default
466 * @return mixed
468 public function getVar( $name, $default = null ) {
469 if ( !isset( $this->settings[$name] ) ) {
470 return $default;
471 } else {
472 return $this->settings[$name];
477 * Get a list of DBs supported by current PHP setup
479 * @return array
481 public function getCompiledDBs() {
482 return $this->compiledDBs;
486 * Get an instance of DatabaseInstaller for the specified DB type.
488 * @param mixed $type DB installer for which is needed, false to use default.
490 * @return DatabaseInstaller
492 public function getDBInstaller( $type = false ) {
493 if ( !$type ) {
494 $type = $this->getVar( 'wgDBtype' );
497 $type = strtolower( $type );
499 if ( !isset( $this->dbInstallers[$type] ) ) {
500 $class = ucfirst( $type ) . 'Installer';
501 $this->dbInstallers[$type] = new $class( $this );
504 return $this->dbInstallers[$type];
508 * Determine if LocalSettings.php exists. If it does, return its variables.
510 * @return array
512 public static function getExistingLocalSettings() {
513 global $IP;
515 wfSuppressWarnings();
516 $_lsExists = file_exists( "$IP/LocalSettings.php" );
517 wfRestoreWarnings();
519 if ( !$_lsExists ) {
520 return false;
522 unset( $_lsExists );
524 require "$IP/includes/DefaultSettings.php";
525 require "$IP/LocalSettings.php";
527 return get_defined_vars();
531 * Get a fake password for sending back to the user in HTML.
532 * This is a security mechanism to avoid compromise of the password in the
533 * event of session ID compromise.
535 * @param string $realPassword
537 * @return string
539 public function getFakePassword( $realPassword ) {
540 return str_repeat( '*', strlen( $realPassword ) );
544 * Set a variable which stores a password, except if the new value is a
545 * fake password in which case leave it as it is.
547 * @param string $name
548 * @param mixed $value
550 public function setPassword( $name, $value ) {
551 if ( !preg_match( '/^\*+$/', $value ) ) {
552 $this->setVar( $name, $value );
557 * On POSIX systems return the primary group of the webserver we're running under.
558 * On other systems just returns null.
560 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
561 * webserver user before he can install.
563 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
565 * @return mixed
567 public static function maybeGetWebserverPrimaryGroup() {
568 if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
569 # I don't know this, this isn't UNIX.
570 return null;
573 # posix_getegid() *not* getmygid() because we want the group of the webserver,
574 # not whoever owns the current script.
575 $gid = posix_getegid();
576 $getpwuid = posix_getpwuid( $gid );
577 $group = $getpwuid['name'];
579 return $group;
583 * Convert wikitext $text to HTML.
585 * This is potentially error prone since many parser features require a complete
586 * installed MW database. The solution is to just not use those features when you
587 * write your messages. This appears to work well enough. Basic formatting and
588 * external links work just fine.
590 * But in case a translator decides to throw in a "#ifexist" or internal link or
591 * whatever, this function is guarded to catch the attempted DB access and to present
592 * some fallback text.
594 * @param string $text
595 * @param bool $lineStart
596 * @return string
598 public function parse( $text, $lineStart = false ) {
599 global $wgParser;
601 try {
602 $out = $wgParser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
603 $html = $out->getText();
604 } catch ( DBAccessError $e ) {
605 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
607 if ( !empty( $this->debug ) ) {
608 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
612 return $html;
616 * @return ParserOptions
618 public function getParserOptions() {
619 return $this->parserOptions;
622 public function disableLinkPopups() {
623 $this->parserOptions->setExternalLinkTarget( false );
626 public function restoreLinkPopups() {
627 global $wgExternalLinkTarget;
628 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
632 * Install step which adds a row to the site_stats table with appropriate
633 * initial values.
635 * @param DatabaseInstaller $installer
637 * @return Status
639 public function populateSiteStats( DatabaseInstaller $installer ) {
640 $status = $installer->getConnection();
641 if ( !$status->isOK() ) {
642 return $status;
644 $status->value->insert(
645 'site_stats',
646 array(
647 'ss_row_id' => 1,
648 'ss_total_views' => 0,
649 'ss_total_edits' => 0,
650 'ss_good_articles' => 0,
651 'ss_total_pages' => 0,
652 'ss_users' => 0,
653 'ss_images' => 0
655 __METHOD__, 'IGNORE'
658 return Status::newGood();
662 * Exports all wg* variables stored by the installer into global scope.
664 public function exportVars() {
665 foreach ( $this->settings as $name => $value ) {
666 if ( substr( $name, 0, 2 ) == 'wg' ) {
667 $GLOBALS[$name] = $value;
673 * Environment check for DB types.
674 * @return bool
676 protected function envCheckDB() {
677 global $wgLang;
679 $allNames = array();
681 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
682 // config-type-sqlite
683 foreach ( self::getDBTypes() as $name ) {
684 $allNames[] = wfMessage( "config-type-$name" )->text();
687 $databases = $this->getCompiledDBs();
689 $databases = array_flip( $databases );
690 foreach ( array_keys( $databases ) as $db ) {
691 $installer = $this->getDBInstaller( $db );
692 $status = $installer->checkPrerequisites();
693 if ( !$status->isGood() ) {
694 $this->showStatusMessage( $status );
696 if ( !$status->isOK() ) {
697 unset( $databases[$db] );
700 $databases = array_flip( $databases );
701 if ( !$databases ) {
702 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
704 // @todo FIXME: This only works for the web installer!
705 return false;
708 return true;
712 * Environment check for register_globals.
714 protected function envCheckRegisterGlobals() {
715 if ( wfIniGetBool( 'register_globals' ) ) {
716 $this->showMessage( 'config-register-globals' );
721 * Some versions of libxml+PHP break < and > encoding horribly
722 * @return bool
724 protected function envCheckBrokenXML() {
725 $test = new PhpXmlBugTester();
726 if ( !$test->ok ) {
727 $this->showError( 'config-brokenlibxml' );
729 return false;
732 return true;
736 * Environment check for magic_quotes_runtime.
737 * @return bool
739 protected function envCheckMagicQuotes() {
740 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
741 $this->showError( 'config-magic-quotes-runtime' );
743 return false;
746 return true;
750 * Environment check for magic_quotes_sybase.
751 * @return bool
753 protected function envCheckMagicSybase() {
754 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
755 $this->showError( 'config-magic-quotes-sybase' );
757 return false;
760 return true;
764 * Environment check for mbstring.func_overload.
765 * @return bool
767 protected function envCheckMbstring() {
768 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
769 $this->showError( 'config-mbstring' );
771 return false;
774 return true;
778 * Environment check for safe_mode.
779 * @return bool
781 protected function envCheckSafeMode() {
782 if ( wfIniGetBool( 'safe_mode' ) ) {
783 $this->setVar( '_SafeMode', true );
784 $this->showMessage( 'config-safe-mode' );
787 return true;
791 * Environment check for the XML module.
792 * @return bool
794 protected function envCheckXML() {
795 if ( !function_exists( "utf8_encode" ) ) {
796 $this->showError( 'config-xml-bad' );
798 return false;
801 return true;
805 * Environment check for the PCRE module.
807 * @note If this check were to fail, the parser would
808 * probably throw an exception before the result
809 * of this check is shown to the user.
810 * @return bool
812 protected function envCheckPCRE() {
813 wfSuppressWarnings();
814 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
815 // Need to check for \p support too, as PCRE can be compiled
816 // with utf8 support, but not unicode property support.
817 // check that \p{Zs} (space separators) matches
818 // U+3000 (Ideographic space)
819 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
820 wfRestoreWarnings();
821 if ( $regexd != '--' || $regexprop != '--' ) {
822 $this->showError( 'config-pcre-no-utf8' );
824 return false;
827 return true;
831 * Environment check for available memory.
832 * @return bool
834 protected function envCheckMemory() {
835 $limit = ini_get( 'memory_limit' );
837 if ( !$limit || $limit == -1 ) {
838 return true;
841 $n = wfShorthandToInteger( $limit );
843 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
844 $newLimit = "{$this->minMemorySize}M";
846 if ( ini_set( "memory_limit", $newLimit ) === false ) {
847 $this->showMessage( 'config-memory-bad', $limit );
848 } else {
849 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
850 $this->setVar( '_RaiseMemory', true );
854 return true;
858 * Environment check for compiled object cache types.
860 protected function envCheckCache() {
861 $caches = array();
862 foreach ( $this->objectCaches as $name => $function ) {
863 if ( function_exists( $function ) ) {
864 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
865 continue;
867 $caches[$name] = true;
871 if ( !$caches ) {
872 $this->showMessage( 'config-no-cache' );
875 $this->setVar( '_Caches', $caches );
879 * Scare user to death if they have mod_security
880 * @return bool
882 protected function envCheckModSecurity() {
883 if ( self::apacheModulePresent( 'mod_security' ) ) {
884 $this->showMessage( 'config-mod-security' );
887 return true;
891 * Search for GNU diff3.
892 * @return bool
894 protected function envCheckDiff3() {
895 $names = array( "gdiff3", "diff3", "diff3.exe" );
896 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
898 $diff3 = self::locateExecutableInDefaultPaths( $names, $versionInfo );
900 if ( $diff3 ) {
901 $this->setVar( 'wgDiff3', $diff3 );
902 } else {
903 $this->setVar( 'wgDiff3', false );
904 $this->showMessage( 'config-diff3-bad' );
907 return true;
911 * Environment check for ImageMagick and GD.
912 * @return bool
914 protected function envCheckGraphics() {
915 $names = array( wfIsWindows() ? 'convert.exe' : 'convert' );
916 $versionInfo = array( '$1 -version', 'ImageMagick' );
917 $convert = self::locateExecutableInDefaultPaths( $names, $versionInfo );
919 $this->setVar( 'wgImageMagickConvertCommand', '' );
920 if ( $convert ) {
921 $this->setVar( 'wgImageMagickConvertCommand', $convert );
922 $this->showMessage( 'config-imagemagick', $convert );
924 return true;
925 } elseif ( function_exists( 'imagejpeg' ) ) {
926 $this->showMessage( 'config-gd' );
927 } else {
928 $this->showMessage( 'config-no-scaling' );
931 return true;
935 * Search for git.
937 * @since 1.22
938 * @return bool
940 protected function envCheckGit() {
941 $names = array( wfIsWindows() ? 'git.exe' : 'git' );
942 $versionInfo = array( '$1 --version', 'git version' );
944 $git = self::locateExecutableInDefaultPaths( $names, $versionInfo );
946 if ( $git ) {
947 $this->setVar( 'wgGitBin', $git );
948 $this->showMessage( 'config-git', $git );
949 } else {
950 $this->setVar( 'wgGitBin', false );
951 $this->showMessage( 'config-git-bad' );
954 return true;
958 * Environment check for the server hostname.
960 protected function envCheckServer() {
961 $server = $this->envGetDefaultServer();
962 if ( $server !== null ) {
963 $this->showMessage( 'config-using-server', $server );
964 $this->setVar( 'wgServer', $server );
967 return true;
971 * Helper function to be called from envCheckServer()
972 * @return string
974 abstract protected function envGetDefaultServer();
977 * Environment check for setting $IP and $wgScriptPath.
978 * @return bool
980 protected function envCheckPath() {
981 global $IP;
982 $IP = dirname( dirname( __DIR__ ) );
983 $this->setVar( 'IP', $IP );
985 $this->showMessage(
986 'config-using-uri',
987 $this->getVar( 'wgServer' ),
988 $this->getVar( 'wgScriptPath' )
991 return true;
995 * Environment check for setting the preferred PHP file extension.
996 * @return bool
998 protected function envCheckExtension() {
999 // @todo FIXME: Detect this properly
1000 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1001 $ext = 'php5';
1002 } else {
1003 $ext = 'php';
1005 $this->setVar( 'wgScriptExtension', ".$ext" );
1007 return true;
1011 * Environment check for preferred locale in shell
1012 * @return bool
1014 protected function envCheckShellLocale() {
1015 $os = php_uname( 's' );
1016 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1018 if ( !in_array( $os, $supported ) ) {
1019 return true;
1022 # Get a list of available locales.
1023 $ret = false;
1024 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1026 if ( $ret ) {
1027 return true;
1030 $lines = array_map( 'trim', explode( "\n", $lines ) );
1031 $candidatesByLocale = array();
1032 $candidatesByLang = array();
1034 foreach ( $lines as $line ) {
1035 if ( $line === '' ) {
1036 continue;
1039 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1040 continue;
1043 list( , $lang, , , ) = $m;
1045 $candidatesByLocale[$m[0]] = $m;
1046 $candidatesByLang[$lang][] = $m;
1049 # Try the current value of LANG.
1050 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1051 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1053 return true;
1056 # Try the most common ones.
1057 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1058 foreach ( $commonLocales as $commonLocale ) {
1059 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1060 $this->setVar( 'wgShellLocale', $commonLocale );
1062 return true;
1066 # Is there an available locale in the Wiki's language?
1067 $wikiLang = $this->getVar( 'wgLanguageCode' );
1069 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1070 $m = reset( $candidatesByLang[$wikiLang] );
1071 $this->setVar( 'wgShellLocale', $m[0] );
1073 return true;
1076 # Are there any at all?
1077 if ( count( $candidatesByLocale ) ) {
1078 $m = reset( $candidatesByLocale );
1079 $this->setVar( 'wgShellLocale', $m[0] );
1081 return true;
1084 # Give up.
1085 return true;
1089 * Environment check for the permissions of the uploads directory
1090 * @return bool
1092 protected function envCheckUploadsDirectory() {
1093 global $IP;
1095 $dir = $IP . '/images/';
1096 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1097 $safe = !$this->dirIsExecutable( $dir, $url );
1099 if ( !$safe ) {
1100 $this->showMessage( 'config-uploads-not-safe', $dir );
1103 return true;
1107 * Checks if suhosin.get.max_value_length is set, and if so generate
1108 * a warning because it decreases ResourceLoader performance.
1109 * @return bool
1111 protected function envCheckSuhosinMaxValueLength() {
1112 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1113 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1114 // Only warn if the value is below the sane 1024
1115 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1118 return true;
1122 * Convert a hex string representing a Unicode code point to that code point.
1123 * @param string $c
1124 * @return string
1126 protected function unicodeChar( $c ) {
1127 $c = hexdec( $c );
1128 if ( $c <= 0x7F ) {
1129 return chr( $c );
1130 } elseif ( $c <= 0x7FF ) {
1131 return chr( 0xC0 | $c >> 6 ) . chr( 0x80 | $c & 0x3F );
1132 } elseif ( $c <= 0xFFFF ) {
1133 return chr( 0xE0 | $c >> 12 ) . chr( 0x80 | $c >> 6 & 0x3F )
1134 . chr( 0x80 | $c & 0x3F );
1135 } elseif ( $c <= 0x10FFFF ) {
1136 return chr( 0xF0 | $c >> 18 ) . chr( 0x80 | $c >> 12 & 0x3F )
1137 . chr( 0x80 | $c >> 6 & 0x3F )
1138 . chr( 0x80 | $c & 0x3F );
1139 } else {
1140 return false;
1145 * Check the libicu version
1147 protected function envCheckLibicu() {
1148 $utf8 = function_exists( 'utf8_normalize' );
1149 $intl = function_exists( 'normalizer_normalize' );
1152 * This needs to be updated something that the latest libicu
1153 * will properly normalize. This normalization was found at
1154 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1155 * Note that we use the hex representation to create the code
1156 * points in order to avoid any Unicode-destroying during transit.
1158 $not_normal_c = $this->unicodeChar( "FA6C" );
1159 $normal_c = $this->unicodeChar( "242EE" );
1161 $useNormalizer = 'php';
1162 $needsUpdate = false;
1165 * We're going to prefer the pecl extension here unless
1166 * utf8_normalize is more up to date.
1168 if ( $utf8 ) {
1169 $useNormalizer = 'utf8';
1170 $utf8 = utf8_normalize( $not_normal_c, UtfNormal::UNORM_NFC );
1171 if ( $utf8 !== $normal_c ) {
1172 $needsUpdate = true;
1175 if ( $intl ) {
1176 $useNormalizer = 'intl';
1177 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1178 if ( $intl !== $normal_c ) {
1179 $needsUpdate = true;
1183 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1184 // 'config-unicode-using-intl'
1185 if ( $useNormalizer === 'php' ) {
1186 $this->showMessage( 'config-unicode-pure-php-warning' );
1187 } else {
1188 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1189 if ( $needsUpdate ) {
1190 $this->showMessage( 'config-unicode-update-warning' );
1196 * @return bool
1198 protected function envCheckCtype() {
1199 if ( !function_exists( 'ctype_digit' ) ) {
1200 $this->showError( 'config-ctype' );
1202 return false;
1205 return true;
1209 * @return bool
1211 protected function envCheckJSON() {
1212 if ( !function_exists( 'json_decode' ) ) {
1213 $this->showError( 'config-json' );
1215 return false;
1218 return true;
1222 * Get an array of likely places we can find executables. Check a bunch
1223 * of known Unix-like defaults, as well as the PATH environment variable
1224 * (which should maybe make it work for Windows?)
1226 * @return array
1228 protected static function getPossibleBinPaths() {
1229 return array_merge(
1230 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1231 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1232 explode( PATH_SEPARATOR, getenv( 'PATH' ) )
1237 * Search a path for any of the given executable names. Returns the
1238 * executable name if found. Also checks the version string returned
1239 * by each executable.
1241 * Used only by environment checks.
1243 * @param string $path path to search
1244 * @param array $names of executable names
1245 * @param array|bool $versionInfo False or array with two members:
1246 * 0 => Command to run for version check, with $1 for the full executable name
1247 * 1 => String to compare the output with
1249 * If $versionInfo is not false, only executables with a version
1250 * matching $versionInfo[1] will be returned.
1251 * @return bool|string
1253 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1254 if ( !is_array( $names ) ) {
1255 $names = array( $names );
1258 foreach ( $names as $name ) {
1259 $command = $path . DIRECTORY_SEPARATOR . $name;
1261 wfSuppressWarnings();
1262 $file_exists = file_exists( $command );
1263 wfRestoreWarnings();
1265 if ( $file_exists ) {
1266 if ( !$versionInfo ) {
1267 return $command;
1270 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1271 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1272 return $command;
1277 return false;
1281 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1282 * @see locateExecutable()
1283 * @param array $names Array of possible names.
1284 * @param array|bool $versionInfo Default: false or array with two members:
1285 * 0 => Command to run for version check, with $1 for the full executable name
1286 * 1 => String to compare the output with
1288 * If $versionInfo is not false, only executables with a version
1289 * matching $versionInfo[1] will be returned.
1290 * @return bool|string
1292 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1293 foreach ( self::getPossibleBinPaths() as $path ) {
1294 $exe = self::locateExecutable( $path, $names, $versionInfo );
1295 if ( $exe !== false ) {
1296 return $exe;
1300 return false;
1304 * Checks if scripts located in the given directory can be executed via the given URL.
1306 * Used only by environment checks.
1307 * @param string $dir
1308 * @param string $url
1309 * @return bool|int|string
1311 public function dirIsExecutable( $dir, $url ) {
1312 $scriptTypes = array(
1313 'php' => array(
1314 "<?php echo 'ex' . 'ec';",
1315 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1319 // it would be good to check other popular languages here, but it'll be slow.
1321 wfSuppressWarnings();
1323 foreach ( $scriptTypes as $ext => $contents ) {
1324 foreach ( $contents as $source ) {
1325 $file = 'exectest.' . $ext;
1327 if ( !file_put_contents( $dir . $file, $source ) ) {
1328 break;
1331 try {
1332 $text = Http::get( $url . $file, array( 'timeout' => 3 ) );
1333 } catch ( MWException $e ) {
1334 // Http::get throws with allow_url_fopen = false and no curl extension.
1335 $text = null;
1337 unlink( $dir . $file );
1339 if ( $text == 'exec' ) {
1340 wfRestoreWarnings();
1342 return $ext;
1347 wfRestoreWarnings();
1349 return false;
1353 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1355 * @param string $moduleName Name of module to check.
1356 * @return bool
1358 public static function apacheModulePresent( $moduleName ) {
1359 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1360 return true;
1362 // try it the hard way
1363 ob_start();
1364 phpinfo( INFO_MODULES );
1365 $info = ob_get_clean();
1367 return strpos( $info, $moduleName ) !== false;
1371 * ParserOptions are constructed before we determined the language, so fix it
1373 * @param Language $lang
1375 public function setParserLanguage( $lang ) {
1376 $this->parserOptions->setTargetLanguage( $lang );
1377 $this->parserOptions->setUserLang( $lang );
1381 * Overridden by WebInstaller to provide lastPage parameters.
1382 * @param string $page
1383 * @return string
1385 protected function getDocUrl( $page ) {
1386 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1390 * Finds extensions that follow the format /extensions/Name/Name.php,
1391 * and returns an array containing the value for 'Name' for each found extension.
1393 * @return array
1395 public function findExtensions() {
1396 if ( $this->getVar( 'IP' ) === null ) {
1397 return array();
1400 $extDir = $this->getVar( 'IP' ) . '/extensions';
1401 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1402 return array();
1405 $dh = opendir( $extDir );
1406 $exts = array();
1407 while ( ( $file = readdir( $dh ) ) !== false ) {
1408 if ( !is_dir( "$extDir/$file" ) ) {
1409 continue;
1411 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1412 $exts[] = $file;
1415 closedir( $dh );
1416 natcasesort( $exts );
1418 return $exts;
1422 * Installs the auto-detected extensions.
1424 * @return Status
1426 protected function includeExtensions() {
1427 global $IP;
1428 $exts = $this->getVar( '_Extensions' );
1429 $IP = $this->getVar( 'IP' );
1432 * We need to include DefaultSettings before including extensions to avoid
1433 * warnings about unset variables. However, the only thing we really
1434 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1435 * if the extension has hidden hook registration in $wgExtensionFunctions,
1436 * but we're not opening that can of worms
1437 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1439 global $wgAutoloadClasses;
1440 $wgAutoloadClasses = array();
1442 require "$IP/includes/DefaultSettings.php";
1444 foreach ( $exts as $e ) {
1445 require_once "$IP/extensions/$e/$e.php";
1448 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1449 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1451 // Unset everyone else's hooks. Lord knows what someone might be doing
1452 // in ParserFirstCallInit (see bug 27171)
1453 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1455 return Status::newGood();
1459 * Get an array of install steps. Should always be in the format of
1460 * array(
1461 * 'name' => 'someuniquename',
1462 * 'callback' => array( $obj, 'method' ),
1464 * There must be a config-install-$name message defined per step, which will
1465 * be shown on install.
1467 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1468 * @return array
1470 protected function getInstallSteps( DatabaseInstaller $installer ) {
1471 $coreInstallSteps = array(
1472 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1473 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1474 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1475 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1476 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1477 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1478 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1481 // Build the array of install steps starting from the core install list,
1482 // then adding any callbacks that wanted to attach after a given step
1483 foreach ( $coreInstallSteps as $step ) {
1484 $this->installSteps[] = $step;
1485 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1486 $this->installSteps = array_merge(
1487 $this->installSteps,
1488 $this->extraInstallSteps[$step['name']]
1493 // Prepend any steps that want to be at the beginning
1494 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1495 $this->installSteps = array_merge(
1496 $this->extraInstallSteps['BEGINNING'],
1497 $this->installSteps
1501 // Extensions should always go first, chance to tie into hooks and such
1502 if ( count( $this->getVar( '_Extensions' ) ) ) {
1503 array_unshift( $this->installSteps,
1504 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1506 $this->installSteps[] = array(
1507 'name' => 'extension-tables',
1508 'callback' => array( $installer, 'createExtensionTables' )
1512 return $this->installSteps;
1516 * Actually perform the installation.
1518 * @param array $startCB A callback array for the beginning of each step
1519 * @param array $endCB A callback array for the end of each step
1521 * @return array Array of Status objects
1523 public function performInstallation( $startCB, $endCB ) {
1524 $installResults = array();
1525 $installer = $this->getDBInstaller();
1526 $installer->preInstall();
1527 $steps = $this->getInstallSteps( $installer );
1528 foreach ( $steps as $stepObj ) {
1529 $name = $stepObj['name'];
1530 call_user_func_array( $startCB, array( $name ) );
1532 // Perform the callback step
1533 $status = call_user_func( $stepObj['callback'], $installer );
1535 // Output and save the results
1536 call_user_func( $endCB, $name, $status );
1537 $installResults[$name] = $status;
1539 // If we've hit some sort of fatal, we need to bail.
1540 // Callback already had a chance to do output above.
1541 if ( !$status->isOk() ) {
1542 break;
1545 if ( $status->isOk() ) {
1546 $this->setVar( '_InstallDone', true );
1549 return $installResults;
1553 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1555 * @return Status
1557 public function generateKeys() {
1558 $keys = array( 'wgSecretKey' => 64 );
1559 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1560 $keys['wgUpgradeKey'] = 16;
1563 return $this->doGenerateKeys( $keys );
1567 * Generate a secret value for variables using our CryptRand generator.
1568 * Produce a warning if the random source was insecure.
1570 * @param array $keys
1571 * @return Status
1573 protected function doGenerateKeys( $keys ) {
1574 $status = Status::newGood();
1576 $strong = true;
1577 foreach ( $keys as $name => $length ) {
1578 $secretKey = MWCryptRand::generateHex( $length, true );
1579 if ( !MWCryptRand::wasStrong() ) {
1580 $strong = false;
1583 $this->setVar( $name, $secretKey );
1586 if ( !$strong ) {
1587 $names = array_keys( $keys );
1588 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1589 global $wgLang;
1590 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1593 return $status;
1597 * Create the first user account, grant it sysop and bureaucrat rights
1599 * @return Status
1601 protected function createSysop() {
1602 $name = $this->getVar( '_AdminName' );
1603 $user = User::newFromName( $name );
1605 if ( !$user ) {
1606 // We should've validated this earlier anyway!
1607 return Status::newFatal( 'config-admin-error-user', $name );
1610 if ( $user->idForName() == 0 ) {
1611 $user->addToDatabase();
1613 try {
1614 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1615 } catch ( PasswordError $pwe ) {
1616 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1619 $user->addGroup( 'sysop' );
1620 $user->addGroup( 'bureaucrat' );
1621 if ( $this->getVar( '_AdminEmail' ) ) {
1622 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1624 $user->saveSettings();
1626 // Update user count
1627 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1628 $ssUpdate->doUpdate();
1630 $status = Status::newGood();
1632 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1633 $this->subscribeToMediaWikiAnnounce( $status );
1636 return $status;
1640 * @param Status $s
1642 private function subscribeToMediaWikiAnnounce( Status $s ) {
1643 $params = array(
1644 'email' => $this->getVar( '_AdminEmail' ),
1645 'language' => 'en',
1646 'digest' => 0
1649 // Mailman doesn't support as many languages as we do, so check to make
1650 // sure their selected language is available
1651 $myLang = $this->getVar( '_UserLang' );
1652 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1653 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1654 $params['language'] = $myLang;
1657 if ( MWHttpRequest::canMakeRequests() ) {
1658 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1659 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1660 if ( !$res->isOK() ) {
1661 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1663 } else {
1664 $s->warning( 'config-install-subscribe-notpossible' );
1669 * Insert Main Page with default content.
1671 * @param DatabaseInstaller $installer
1672 * @return Status
1674 protected function createMainpage( DatabaseInstaller $installer ) {
1675 $status = Status::newGood();
1676 try {
1677 $page = WikiPage::factory( Title::newMainPage() );
1678 $content = new WikitextContent(
1679 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1680 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1683 $page->doEditContent( $content,
1685 EDIT_NEW,
1686 false,
1687 User::newFromName( 'MediaWiki default' )
1689 } catch ( MWException $e ) {
1690 //using raw, because $wgShowExceptionDetails can not be set yet
1691 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1694 return $status;
1698 * Override the necessary bits of the config to run an installation.
1700 public static function overrideConfig() {
1701 define( 'MW_NO_SESSION', 1 );
1703 // Don't access the database
1704 $GLOBALS['wgUseDatabaseMessages'] = false;
1705 // Don't cache langconv tables
1706 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1707 // Debug-friendly
1708 $GLOBALS['wgShowExceptionDetails'] = true;
1709 // Don't break forms
1710 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1712 // Extended debugging
1713 $GLOBALS['wgShowSQLErrors'] = true;
1714 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1716 // Allow multiple ob_flush() calls
1717 $GLOBALS['wgDisableOutputCompression'] = true;
1719 // Use a sensible cookie prefix (not my_wiki)
1720 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1722 // Some of the environment checks make shell requests, remove limits
1723 $GLOBALS['wgMaxShellMemory'] = 0;
1725 // Don't bother embedding images into generated CSS, which is not cached
1726 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1727 return $less->toBool( false );
1732 * Add an installation step following the given step.
1734 * @param array $callback A valid installation callback array, in this form:
1735 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1736 * @param string $findStep The step to find. Omit to put the step at the beginning
1738 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1739 $this->extraInstallSteps[$findStep][] = $callback;
1743 * Disable the time limit for execution.
1744 * Some long-running pages (Install, Upgrade) will want to do this
1746 protected function disableTimeLimit() {
1747 wfSuppressWarnings();
1748 set_time_limit( 0 );
1749 wfRestoreWarnings();