Use PHP_VERSION constant instead of phpversion() function call
[mediawiki.git] / includes / installer / Installer.php
blob4f406934791bc36d59389265a9380bac5d935798
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 /**
42 * The oldest version of PCRE we can support.
44 * Defining this is necessary because PHP may be linked with a system version
45 * of PCRE, which may be older than that bundled with the minimum PHP version.
47 const MINIMUM_PCRE_VERSION = '7.2';
49 /**
50 * @var array
52 protected $settings;
54 /**
55 * List of detected DBs, access using getCompiledDBs().
57 * @var array
59 protected $compiledDBs;
61 /**
62 * Cached DB installer instances, access using getDBInstaller().
64 * @var array
66 protected $dbInstallers = array();
68 /**
69 * Minimum memory size in MB.
71 * @var int
73 protected $minMemorySize = 50;
75 /**
76 * Cached Title, used by parse().
78 * @var Title
80 protected $parserTitle;
82 /**
83 * Cached ParserOptions, used by parse().
85 * @var ParserOptions
87 protected $parserOptions;
89 /**
90 * Known database types. These correspond to the class names <type>Installer,
91 * and are also MediaWiki database types valid for $wgDBtype.
93 * To add a new type, create a <type>Installer class and a Database<type>
94 * class, and add a config-type-<type> message to MessagesEn.php.
96 * @var array
98 protected static $dbTypes = array(
99 'mysql',
100 'postgres',
101 'oracle',
102 'mssql',
103 'sqlite',
107 * A list of environment check methods called by doEnvironmentChecks().
108 * These may output warnings using showMessage(), and/or abort the
109 * installation process by returning false.
111 * @var array
113 protected $envChecks = array(
114 'envCheckDB',
115 'envCheckRegisterGlobals',
116 'envCheckBrokenXML',
117 'envCheckMagicQuotes',
118 'envCheckMagicSybase',
119 'envCheckMbstring',
120 'envCheckSafeMode',
121 'envCheckXML',
122 'envCheckPCRE',
123 'envCheckMemory',
124 'envCheckCache',
125 'envCheckModSecurity',
126 'envCheckDiff3',
127 'envCheckGraphics',
128 'envCheckGit',
129 'envCheckServer',
130 'envCheckPath',
131 'envCheckExtension',
132 'envCheckShellLocale',
133 'envCheckUploadsDirectory',
134 'envCheckLibicu',
135 'envCheckSuhosinMaxValueLength',
136 'envCheckCtype',
137 'envCheckJSON',
141 * MediaWiki configuration globals that will eventually be passed through
142 * to LocalSettings.php. The names only are given here, the defaults
143 * typically come from DefaultSettings.php.
145 * @var array
147 protected $defaultVarNames = array(
148 'wgSitename',
149 'wgPasswordSender',
150 'wgLanguageCode',
151 'wgRightsIcon',
152 'wgRightsText',
153 'wgRightsUrl',
154 'wgMainCacheType',
155 'wgEnableEmail',
156 'wgEnableUserEmail',
157 'wgEnotifUserTalk',
158 'wgEnotifWatchlist',
159 'wgEmailAuthentication',
160 'wgDBtype',
161 'wgDiff3',
162 'wgImageMagickConvertCommand',
163 'wgGitBin',
164 'IP',
165 'wgScriptPath',
166 'wgScriptExtension',
167 'wgMetaNamespace',
168 'wgDeletedDirectory',
169 'wgEnableUploads',
170 'wgShellLocale',
171 'wgSecretKey',
172 'wgUseInstantCommons',
173 'wgUpgradeKey',
174 'wgDefaultSkin',
175 'wgResourceLoaderMaxQueryLength',
179 * Variables that are stored alongside globals, and are used for any
180 * configuration of the installation process aside from the MediaWiki
181 * configuration. Map of names to defaults.
183 * @var array
185 protected $internalDefaults = array(
186 '_UserLang' => 'en',
187 '_Environment' => false,
188 '_SafeMode' => false,
189 '_RaiseMemory' => false,
190 '_UpgradeDone' => false,
191 '_InstallDone' => false,
192 '_Caches' => array(),
193 '_InstallPassword' => '',
194 '_SameAccount' => true,
195 '_CreateDBAccount' => false,
196 '_NamespaceType' => 'site-name',
197 '_AdminName' => '', // will be set later, when the user selects language
198 '_AdminPassword' => '',
199 '_AdminPasswordConfirm' => '',
200 '_AdminEmail' => '',
201 '_Subscribe' => false,
202 '_SkipOptional' => 'continue',
203 '_RightsProfile' => 'wiki',
204 '_LicenseCode' => 'none',
205 '_CCDone' => false,
206 '_Extensions' => array(),
207 '_MemCachedServers' => '',
208 '_UpgradeKeySupplied' => false,
209 '_ExistingDBSettings' => false,
211 // $wgLogo is probably wrong (bug 48084); set something that will work.
212 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
213 'wgLogo' => '$wgStylePath/common/images/wiki.png',
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
352 Language::getLocalisationCache()->disableBackend();
353 // Disable LoadBalancer and wfGetDB etc.
354 LBFactory::disableBackend();
356 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
357 // SqlBagOStuff will then throw since we just disabled wfGetDB)
358 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
359 ObjectCache::clear();
360 $emptyCache = array( 'class' => 'EmptyBagOStuff' );
361 $GLOBALS['wgObjectCaches'] = array(
362 CACHE_NONE => $emptyCache,
363 CACHE_DB => $emptyCache,
364 CACHE_ANYTHING => $emptyCache,
365 CACHE_MEMCACHED => $emptyCache,
368 // Load the installer's i18n.
369 $wgMessagesDirs['MediawikiInstaller'] = __DIR__ . '/i18n';
371 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
372 $wgUser = User::newFromId( 0 );
374 $this->settings = $this->internalDefaults;
376 foreach ( $this->defaultVarNames as $var ) {
377 $this->settings[$var] = $GLOBALS[$var];
380 $this->compiledDBs = array();
381 foreach ( self::getDBTypes() as $type ) {
382 $installer = $this->getDBInstaller( $type );
384 if ( !$installer->isCompiled() ) {
385 continue;
387 $this->compiledDBs[] = $type;
390 $this->parserTitle = Title::newFromText( 'Installer' );
391 $this->parserOptions = new ParserOptions; // language will be wrong :(
392 $this->parserOptions->setEditSection( false );
396 * Get a list of known DB types.
398 * @return array
400 public static function getDBTypes() {
401 return self::$dbTypes;
405 * Do initial checks of the PHP environment. Set variables according to
406 * the observed environment.
408 * It's possible that this may be called under the CLI SAPI, not the SAPI
409 * that the wiki will primarily run under. In that case, the subclass should
410 * initialise variables such as wgScriptPath, before calling this function.
412 * Under the web subclass, it can already be assumed that PHP 5+ is in use
413 * and that sessions are working.
415 * @return Status
417 public function doEnvironmentChecks() {
418 // Php version has already been checked by entry scripts
419 // Show message here for information purposes
420 $this->showMessage( 'config-env-php', PHP_VERSION );
422 $good = true;
423 // Must go here because an old version of PCRE can prevent other checks from completing
424 list( $pcreVersion ) = explode( ' ', PCRE_VERSION, 2 );
425 if ( version_compare( $pcreVersion, self::MINIMUM_PCRE_VERSION, '<' ) ) {
426 $this->showError( 'config-pcre-old', self::MINIMUM_PCRE_VERSION, $pcreVersion );
427 $good = false;
428 } else {
429 foreach ( $this->envChecks as $check ) {
430 $status = $this->$check();
431 if ( $status === false ) {
432 $good = false;
437 $this->setVar( '_Environment', $good );
439 return $good ? Status::newGood() : Status::newFatal( 'config-env-bad' );
443 * Set a MW configuration variable, or internal installer configuration variable.
445 * @param string $name
446 * @param mixed $value
448 public function setVar( $name, $value ) {
449 $this->settings[$name] = $value;
453 * Get an MW configuration variable, or internal installer configuration variable.
454 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
455 * Installer variables are typically prefixed by an underscore.
457 * @param string $name
458 * @param mixed $default
460 * @return mixed
462 public function getVar( $name, $default = null ) {
463 if ( !isset( $this->settings[$name] ) ) {
464 return $default;
465 } else {
466 return $this->settings[$name];
471 * Get a list of DBs supported by current PHP setup
473 * @return array
475 public function getCompiledDBs() {
476 return $this->compiledDBs;
480 * Get an instance of DatabaseInstaller for the specified DB type.
482 * @param mixed $type DB installer for which is needed, false to use default.
484 * @return DatabaseInstaller
486 public function getDBInstaller( $type = false ) {
487 if ( !$type ) {
488 $type = $this->getVar( 'wgDBtype' );
491 $type = strtolower( $type );
493 if ( !isset( $this->dbInstallers[$type] ) ) {
494 $class = ucfirst( $type ) . 'Installer';
495 $this->dbInstallers[$type] = new $class( $this );
498 return $this->dbInstallers[$type];
502 * Determine if LocalSettings.php exists. If it does, return its variables.
504 * @return array
506 public static function getExistingLocalSettings() {
507 global $IP;
509 wfSuppressWarnings();
510 $_lsExists = file_exists( "$IP/LocalSettings.php" );
511 wfRestoreWarnings();
513 if ( !$_lsExists ) {
514 return false;
516 unset( $_lsExists );
518 require "$IP/includes/DefaultSettings.php";
519 require "$IP/LocalSettings.php";
521 return get_defined_vars();
525 * Get a fake password for sending back to the user in HTML.
526 * This is a security mechanism to avoid compromise of the password in the
527 * event of session ID compromise.
529 * @param string $realPassword
531 * @return string
533 public function getFakePassword( $realPassword ) {
534 return str_repeat( '*', strlen( $realPassword ) );
538 * Set a variable which stores a password, except if the new value is a
539 * fake password in which case leave it as it is.
541 * @param string $name
542 * @param mixed $value
544 public function setPassword( $name, $value ) {
545 if ( !preg_match( '/^\*+$/', $value ) ) {
546 $this->setVar( $name, $value );
551 * On POSIX systems return the primary group of the webserver we're running under.
552 * On other systems just returns null.
554 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
555 * webserver user before he can install.
557 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
559 * @return mixed
561 public static function maybeGetWebserverPrimaryGroup() {
562 if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
563 # I don't know this, this isn't UNIX.
564 return null;
567 # posix_getegid() *not* getmygid() because we want the group of the webserver,
568 # not whoever owns the current script.
569 $gid = posix_getegid();
570 $getpwuid = posix_getpwuid( $gid );
571 $group = $getpwuid['name'];
573 return $group;
577 * Convert wikitext $text to HTML.
579 * This is potentially error prone since many parser features require a complete
580 * installed MW database. The solution is to just not use those features when you
581 * write your messages. This appears to work well enough. Basic formatting and
582 * external links work just fine.
584 * But in case a translator decides to throw in a "#ifexist" or internal link or
585 * whatever, this function is guarded to catch the attempted DB access and to present
586 * some fallback text.
588 * @param string $text
589 * @param bool $lineStart
590 * @return string
592 public function parse( $text, $lineStart = false ) {
593 global $wgParser;
595 try {
596 $out = $wgParser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
597 $html = $out->getText();
598 } catch ( DBAccessError $e ) {
599 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
601 if ( !empty( $this->debug ) ) {
602 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
606 return $html;
610 * @return ParserOptions
612 public function getParserOptions() {
613 return $this->parserOptions;
616 public function disableLinkPopups() {
617 $this->parserOptions->setExternalLinkTarget( false );
620 public function restoreLinkPopups() {
621 global $wgExternalLinkTarget;
622 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
626 * Install step which adds a row to the site_stats table with appropriate
627 * initial values.
629 * @param DatabaseInstaller $installer
631 * @return Status
633 public function populateSiteStats( DatabaseInstaller $installer ) {
634 $status = $installer->getConnection();
635 if ( !$status->isOK() ) {
636 return $status;
638 $status->value->insert(
639 'site_stats',
640 array(
641 'ss_row_id' => 1,
642 'ss_total_views' => 0,
643 'ss_total_edits' => 0,
644 'ss_good_articles' => 0,
645 'ss_total_pages' => 0,
646 'ss_users' => 0,
647 'ss_images' => 0
649 __METHOD__, 'IGNORE'
652 return Status::newGood();
656 * Exports all wg* variables stored by the installer into global scope.
658 public function exportVars() {
659 foreach ( $this->settings as $name => $value ) {
660 if ( substr( $name, 0, 2 ) == 'wg' ) {
661 $GLOBALS[$name] = $value;
667 * Environment check for DB types.
668 * @return bool
670 protected function envCheckDB() {
671 global $wgLang;
673 $allNames = array();
675 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
676 // config-type-sqlite
677 foreach ( self::getDBTypes() as $name ) {
678 $allNames[] = wfMessage( "config-type-$name" )->text();
681 $databases = $this->getCompiledDBs();
683 $databases = array_flip( $databases );
684 foreach ( array_keys( $databases ) as $db ) {
685 $installer = $this->getDBInstaller( $db );
686 $status = $installer->checkPrerequisites();
687 if ( !$status->isGood() ) {
688 $this->showStatusMessage( $status );
690 if ( !$status->isOK() ) {
691 unset( $databases[$db] );
694 $databases = array_flip( $databases );
695 if ( !$databases ) {
696 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
698 // @todo FIXME: This only works for the web installer!
699 return false;
702 return true;
706 * Environment check for register_globals.
707 * Prevent installation if enabled
709 protected function envCheckRegisterGlobals() {
710 if ( wfIniGetBool( 'register_globals' ) ) {
711 $this->showMessage( 'config-register-globals-error' );
712 return false;
715 return true;
719 * Some versions of libxml+PHP break < and > encoding horribly
720 * @return bool
722 protected function envCheckBrokenXML() {
723 $test = new PhpXmlBugTester();
724 if ( !$test->ok ) {
725 $this->showError( 'config-brokenlibxml' );
727 return false;
730 return true;
734 * Environment check for magic_quotes_runtime.
735 * @return bool
737 protected function envCheckMagicQuotes() {
738 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
739 $this->showError( 'config-magic-quotes-runtime' );
741 return false;
744 return true;
748 * Environment check for magic_quotes_sybase.
749 * @return bool
751 protected function envCheckMagicSybase() {
752 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
753 $this->showError( 'config-magic-quotes-sybase' );
755 return false;
758 return true;
762 * Environment check for mbstring.func_overload.
763 * @return bool
765 protected function envCheckMbstring() {
766 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
767 $this->showError( 'config-mbstring' );
769 return false;
772 return true;
776 * Environment check for safe_mode.
777 * @return bool
779 protected function envCheckSafeMode() {
780 if ( wfIniGetBool( 'safe_mode' ) ) {
781 $this->setVar( '_SafeMode', true );
782 $this->showMessage( 'config-safe-mode' );
785 return true;
789 * Environment check for the XML module.
790 * @return bool
792 protected function envCheckXML() {
793 if ( !function_exists( "utf8_encode" ) ) {
794 $this->showError( 'config-xml-bad' );
796 return false;
799 return true;
803 * Environment check for the PCRE module.
805 * @note If this check were to fail, the parser would
806 * probably throw an exception before the result
807 * of this check is shown to the user.
808 * @return bool
810 protected function envCheckPCRE() {
811 wfSuppressWarnings();
812 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
813 // Need to check for \p support too, as PCRE can be compiled
814 // with utf8 support, but not unicode property support.
815 // check that \p{Zs} (space separators) matches
816 // U+3000 (Ideographic space)
817 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
818 wfRestoreWarnings();
819 if ( $regexd != '--' || $regexprop != '--' ) {
820 $this->showError( 'config-pcre-no-utf8' );
822 return false;
825 return true;
829 * Environment check for available memory.
830 * @return bool
832 protected function envCheckMemory() {
833 $limit = ini_get( 'memory_limit' );
835 if ( !$limit || $limit == -1 ) {
836 return true;
839 $n = wfShorthandToInteger( $limit );
841 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
842 $newLimit = "{$this->minMemorySize}M";
844 if ( ini_set( "memory_limit", $newLimit ) === false ) {
845 $this->showMessage( 'config-memory-bad', $limit );
846 } else {
847 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
848 $this->setVar( '_RaiseMemory', true );
852 return true;
856 * Environment check for compiled object cache types.
858 protected function envCheckCache() {
859 $caches = array();
860 foreach ( $this->objectCaches as $name => $function ) {
861 if ( function_exists( $function ) ) {
862 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
863 continue;
865 $caches[$name] = true;
869 if ( !$caches ) {
870 $this->showMessage( 'config-no-cache' );
873 $this->setVar( '_Caches', $caches );
877 * Scare user to death if they have mod_security
878 * @return bool
880 protected function envCheckModSecurity() {
881 if ( self::apacheModulePresent( 'mod_security' ) ) {
882 $this->showMessage( 'config-mod-security' );
885 return true;
889 * Search for GNU diff3.
890 * @return bool
892 protected function envCheckDiff3() {
893 $names = array( "gdiff3", "diff3", "diff3.exe" );
894 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
896 $diff3 = self::locateExecutableInDefaultPaths( $names, $versionInfo );
898 if ( $diff3 ) {
899 $this->setVar( 'wgDiff3', $diff3 );
900 } else {
901 $this->setVar( 'wgDiff3', false );
902 $this->showMessage( 'config-diff3-bad' );
905 return true;
909 * Environment check for ImageMagick and GD.
910 * @return bool
912 protected function envCheckGraphics() {
913 $names = array( wfIsWindows() ? 'convert.exe' : 'convert' );
914 $versionInfo = array( '$1 -version', 'ImageMagick' );
915 $convert = self::locateExecutableInDefaultPaths( $names, $versionInfo );
917 $this->setVar( 'wgImageMagickConvertCommand', '' );
918 if ( $convert ) {
919 $this->setVar( 'wgImageMagickConvertCommand', $convert );
920 $this->showMessage( 'config-imagemagick', $convert );
922 return true;
923 } elseif ( function_exists( 'imagejpeg' ) ) {
924 $this->showMessage( 'config-gd' );
925 } else {
926 $this->showMessage( 'config-no-scaling' );
929 return true;
933 * Search for git.
935 * @since 1.22
936 * @return bool
938 protected function envCheckGit() {
939 $names = array( wfIsWindows() ? 'git.exe' : 'git' );
940 $versionInfo = array( '$1 --version', 'git version' );
942 $git = self::locateExecutableInDefaultPaths( $names, $versionInfo );
944 if ( $git ) {
945 $this->setVar( 'wgGitBin', $git );
946 $this->showMessage( 'config-git', $git );
947 } else {
948 $this->setVar( 'wgGitBin', false );
949 $this->showMessage( 'config-git-bad' );
952 return true;
956 * Environment check for the server hostname.
958 protected function envCheckServer() {
959 $server = $this->envGetDefaultServer();
960 if ( $server !== null ) {
961 $this->showMessage( 'config-using-server', $server );
962 $this->setVar( 'wgServer', $server );
965 return true;
969 * Helper function to be called from envCheckServer()
970 * @return string
972 abstract protected function envGetDefaultServer();
975 * Environment check for setting $IP and $wgScriptPath.
976 * @return bool
978 protected function envCheckPath() {
979 global $IP;
980 $IP = dirname( dirname( __DIR__ ) );
981 $this->setVar( 'IP', $IP );
983 $this->showMessage(
984 'config-using-uri',
985 $this->getVar( 'wgServer' ),
986 $this->getVar( 'wgScriptPath' )
989 return true;
993 * Environment check for setting the preferred PHP file extension.
994 * @return bool
996 protected function envCheckExtension() {
997 // @todo FIXME: Detect this properly
998 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
999 $ext = 'php5';
1000 } else {
1001 $ext = 'php';
1003 $this->setVar( 'wgScriptExtension', ".$ext" );
1005 return true;
1009 * Environment check for preferred locale in shell
1010 * @return bool
1012 protected function envCheckShellLocale() {
1013 $os = php_uname( 's' );
1014 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1016 if ( !in_array( $os, $supported ) ) {
1017 return true;
1020 # Get a list of available locales.
1021 $ret = false;
1022 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1024 if ( $ret ) {
1025 return true;
1028 $lines = array_map( 'trim', explode( "\n", $lines ) );
1029 $candidatesByLocale = array();
1030 $candidatesByLang = array();
1032 foreach ( $lines as $line ) {
1033 if ( $line === '' ) {
1034 continue;
1037 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1038 continue;
1041 list( , $lang, , , ) = $m;
1043 $candidatesByLocale[$m[0]] = $m;
1044 $candidatesByLang[$lang][] = $m;
1047 # Try the current value of LANG.
1048 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1049 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1051 return true;
1054 # Try the most common ones.
1055 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1056 foreach ( $commonLocales as $commonLocale ) {
1057 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1058 $this->setVar( 'wgShellLocale', $commonLocale );
1060 return true;
1064 # Is there an available locale in the Wiki's language?
1065 $wikiLang = $this->getVar( 'wgLanguageCode' );
1067 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1068 $m = reset( $candidatesByLang[$wikiLang] );
1069 $this->setVar( 'wgShellLocale', $m[0] );
1071 return true;
1074 # Are there any at all?
1075 if ( count( $candidatesByLocale ) ) {
1076 $m = reset( $candidatesByLocale );
1077 $this->setVar( 'wgShellLocale', $m[0] );
1079 return true;
1082 # Give up.
1083 return true;
1087 * Environment check for the permissions of the uploads directory
1088 * @return bool
1090 protected function envCheckUploadsDirectory() {
1091 global $IP;
1093 $dir = $IP . '/images/';
1094 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1095 $safe = !$this->dirIsExecutable( $dir, $url );
1097 if ( !$safe ) {
1098 $this->showMessage( 'config-uploads-not-safe', $dir );
1101 return true;
1105 * Checks if suhosin.get.max_value_length is set, and if so generate
1106 * a warning because it decreases ResourceLoader performance.
1107 * @return bool
1109 protected function envCheckSuhosinMaxValueLength() {
1110 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1111 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1112 // Only warn if the value is below the sane 1024
1113 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1116 return true;
1120 * Convert a hex string representing a Unicode code point to that code point.
1121 * @param string $c
1122 * @return string
1124 protected function unicodeChar( $c ) {
1125 $c = hexdec( $c );
1126 if ( $c <= 0x7F ) {
1127 return chr( $c );
1128 } elseif ( $c <= 0x7FF ) {
1129 return chr( 0xC0 | $c >> 6 ) . chr( 0x80 | $c & 0x3F );
1130 } elseif ( $c <= 0xFFFF ) {
1131 return chr( 0xE0 | $c >> 12 ) . chr( 0x80 | $c >> 6 & 0x3F )
1132 . chr( 0x80 | $c & 0x3F );
1133 } elseif ( $c <= 0x10FFFF ) {
1134 return chr( 0xF0 | $c >> 18 ) . chr( 0x80 | $c >> 12 & 0x3F )
1135 . chr( 0x80 | $c >> 6 & 0x3F )
1136 . chr( 0x80 | $c & 0x3F );
1137 } else {
1138 return false;
1143 * Check the libicu version
1145 protected function envCheckLibicu() {
1146 $utf8 = function_exists( 'utf8_normalize' );
1147 $intl = function_exists( 'normalizer_normalize' );
1150 * This needs to be updated something that the latest libicu
1151 * will properly normalize. This normalization was found at
1152 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1153 * Note that we use the hex representation to create the code
1154 * points in order to avoid any Unicode-destroying during transit.
1156 $not_normal_c = $this->unicodeChar( "FA6C" );
1157 $normal_c = $this->unicodeChar( "242EE" );
1159 $useNormalizer = 'php';
1160 $needsUpdate = false;
1163 * We're going to prefer the pecl extension here unless
1164 * utf8_normalize is more up to date.
1166 if ( $utf8 ) {
1167 $useNormalizer = 'utf8';
1168 $utf8 = utf8_normalize( $not_normal_c, UtfNormal::UNORM_NFC );
1169 if ( $utf8 !== $normal_c ) {
1170 $needsUpdate = true;
1173 if ( $intl ) {
1174 $useNormalizer = 'intl';
1175 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1176 if ( $intl !== $normal_c ) {
1177 $needsUpdate = true;
1181 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1182 // 'config-unicode-using-intl'
1183 if ( $useNormalizer === 'php' ) {
1184 $this->showMessage( 'config-unicode-pure-php-warning' );
1185 } else {
1186 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1187 if ( $needsUpdate ) {
1188 $this->showMessage( 'config-unicode-update-warning' );
1194 * @return bool
1196 protected function envCheckCtype() {
1197 if ( !function_exists( 'ctype_digit' ) ) {
1198 $this->showError( 'config-ctype' );
1200 return false;
1203 return true;
1207 * @return bool
1209 protected function envCheckJSON() {
1210 if ( !function_exists( 'json_decode' ) ) {
1211 $this->showError( 'config-json' );
1213 return false;
1216 return true;
1220 * Get an array of likely places we can find executables. Check a bunch
1221 * of known Unix-like defaults, as well as the PATH environment variable
1222 * (which should maybe make it work for Windows?)
1224 * @return array
1226 protected static function getPossibleBinPaths() {
1227 return array_merge(
1228 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1229 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1230 explode( PATH_SEPARATOR, getenv( 'PATH' ) )
1235 * Search a path for any of the given executable names. Returns the
1236 * executable name if found. Also checks the version string returned
1237 * by each executable.
1239 * Used only by environment checks.
1241 * @param string $path path to search
1242 * @param array $names of executable names
1243 * @param array|bool $versionInfo False or array with two members:
1244 * 0 => Command to run for version check, with $1 for the full executable name
1245 * 1 => String to compare the output with
1247 * If $versionInfo is not false, only executables with a version
1248 * matching $versionInfo[1] will be returned.
1249 * @return bool|string
1251 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1252 if ( !is_array( $names ) ) {
1253 $names = array( $names );
1256 foreach ( $names as $name ) {
1257 $command = $path . DIRECTORY_SEPARATOR . $name;
1259 wfSuppressWarnings();
1260 $file_exists = file_exists( $command );
1261 wfRestoreWarnings();
1263 if ( $file_exists ) {
1264 if ( !$versionInfo ) {
1265 return $command;
1268 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1269 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1270 return $command;
1275 return false;
1279 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1280 * @see locateExecutable()
1281 * @param array $names Array of possible names.
1282 * @param array|bool $versionInfo Default: false or array with two members:
1283 * 0 => Command to run for version check, with $1 for the full executable name
1284 * 1 => String to compare the output with
1286 * If $versionInfo is not false, only executables with a version
1287 * matching $versionInfo[1] will be returned.
1288 * @return bool|string
1290 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1291 foreach ( self::getPossibleBinPaths() as $path ) {
1292 $exe = self::locateExecutable( $path, $names, $versionInfo );
1293 if ( $exe !== false ) {
1294 return $exe;
1298 return false;
1302 * Checks if scripts located in the given directory can be executed via the given URL.
1304 * Used only by environment checks.
1305 * @param string $dir
1306 * @param string $url
1307 * @return bool|int|string
1309 public function dirIsExecutable( $dir, $url ) {
1310 $scriptTypes = array(
1311 'php' => array(
1312 "<?php echo 'ex' . 'ec';",
1313 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1317 // it would be good to check other popular languages here, but it'll be slow.
1319 wfSuppressWarnings();
1321 foreach ( $scriptTypes as $ext => $contents ) {
1322 foreach ( $contents as $source ) {
1323 $file = 'exectest.' . $ext;
1325 if ( !file_put_contents( $dir . $file, $source ) ) {
1326 break;
1329 try {
1330 $text = Http::get( $url . $file, array( 'timeout' => 3 ) );
1331 } catch ( MWException $e ) {
1332 // Http::get throws with allow_url_fopen = false and no curl extension.
1333 $text = null;
1335 unlink( $dir . $file );
1337 if ( $text == 'exec' ) {
1338 wfRestoreWarnings();
1340 return $ext;
1345 wfRestoreWarnings();
1347 return false;
1351 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1353 * @param string $moduleName Name of module to check.
1354 * @return bool
1356 public static function apacheModulePresent( $moduleName ) {
1357 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1358 return true;
1360 // try it the hard way
1361 ob_start();
1362 phpinfo( INFO_MODULES );
1363 $info = ob_get_clean();
1365 return strpos( $info, $moduleName ) !== false;
1369 * ParserOptions are constructed before we determined the language, so fix it
1371 * @param Language $lang
1373 public function setParserLanguage( $lang ) {
1374 $this->parserOptions->setTargetLanguage( $lang );
1375 $this->parserOptions->setUserLang( $lang );
1379 * Overridden by WebInstaller to provide lastPage parameters.
1380 * @param string $page
1381 * @return string
1383 protected function getDocUrl( $page ) {
1384 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1388 * Finds extensions that follow the format /extensions/Name/Name.php,
1389 * and returns an array containing the value for 'Name' for each found extension.
1391 * @return array
1393 public function findExtensions() {
1394 if ( $this->getVar( 'IP' ) === null ) {
1395 return array();
1398 $extDir = $this->getVar( 'IP' ) . '/extensions';
1399 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1400 return array();
1403 $dh = opendir( $extDir );
1404 $exts = array();
1405 while ( ( $file = readdir( $dh ) ) !== false ) {
1406 if ( !is_dir( "$extDir/$file" ) ) {
1407 continue;
1409 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1410 $exts[] = $file;
1413 closedir( $dh );
1414 natcasesort( $exts );
1416 return $exts;
1420 * Installs the auto-detected extensions.
1422 * @return Status
1424 protected function includeExtensions() {
1425 global $IP;
1426 $exts = $this->getVar( '_Extensions' );
1427 $IP = $this->getVar( 'IP' );
1430 * We need to include DefaultSettings before including extensions to avoid
1431 * warnings about unset variables. However, the only thing we really
1432 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1433 * if the extension has hidden hook registration in $wgExtensionFunctions,
1434 * but we're not opening that can of worms
1435 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1437 global $wgAutoloadClasses;
1438 $wgAutoloadClasses = array();
1440 require "$IP/includes/DefaultSettings.php";
1442 foreach ( $exts as $e ) {
1443 require_once "$IP/extensions/$e/$e.php";
1446 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1447 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1449 // Unset everyone else's hooks. Lord knows what someone might be doing
1450 // in ParserFirstCallInit (see bug 27171)
1451 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1453 return Status::newGood();
1457 * Get an array of install steps. Should always be in the format of
1458 * array(
1459 * 'name' => 'someuniquename',
1460 * 'callback' => array( $obj, 'method' ),
1462 * There must be a config-install-$name message defined per step, which will
1463 * be shown on install.
1465 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1466 * @return array
1468 protected function getInstallSteps( DatabaseInstaller $installer ) {
1469 $coreInstallSteps = array(
1470 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1471 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1472 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1473 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1474 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1475 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1476 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1479 // Build the array of install steps starting from the core install list,
1480 // then adding any callbacks that wanted to attach after a given step
1481 foreach ( $coreInstallSteps as $step ) {
1482 $this->installSteps[] = $step;
1483 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1484 $this->installSteps = array_merge(
1485 $this->installSteps,
1486 $this->extraInstallSteps[$step['name']]
1491 // Prepend any steps that want to be at the beginning
1492 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1493 $this->installSteps = array_merge(
1494 $this->extraInstallSteps['BEGINNING'],
1495 $this->installSteps
1499 // Extensions should always go first, chance to tie into hooks and such
1500 if ( count( $this->getVar( '_Extensions' ) ) ) {
1501 array_unshift( $this->installSteps,
1502 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1504 $this->installSteps[] = array(
1505 'name' => 'extension-tables',
1506 'callback' => array( $installer, 'createExtensionTables' )
1510 return $this->installSteps;
1514 * Actually perform the installation.
1516 * @param callable $startCB A callback array for the beginning of each step
1517 * @param callable $endCB A callback array for the end of each step
1519 * @return array Array of Status objects
1521 public function performInstallation( $startCB, $endCB ) {
1522 $installResults = array();
1523 $installer = $this->getDBInstaller();
1524 $installer->preInstall();
1525 $steps = $this->getInstallSteps( $installer );
1526 foreach ( $steps as $stepObj ) {
1527 $name = $stepObj['name'];
1528 call_user_func_array( $startCB, array( $name ) );
1530 // Perform the callback step
1531 $status = call_user_func( $stepObj['callback'], $installer );
1533 // Output and save the results
1534 call_user_func( $endCB, $name, $status );
1535 $installResults[$name] = $status;
1537 // If we've hit some sort of fatal, we need to bail.
1538 // Callback already had a chance to do output above.
1539 if ( !$status->isOk() ) {
1540 break;
1543 if ( $status->isOk() ) {
1544 $this->setVar( '_InstallDone', true );
1547 return $installResults;
1551 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1553 * @return Status
1555 public function generateKeys() {
1556 $keys = array( 'wgSecretKey' => 64 );
1557 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1558 $keys['wgUpgradeKey'] = 16;
1561 return $this->doGenerateKeys( $keys );
1565 * Generate a secret value for variables using our CryptRand generator.
1566 * Produce a warning if the random source was insecure.
1568 * @param array $keys
1569 * @return Status
1571 protected function doGenerateKeys( $keys ) {
1572 $status = Status::newGood();
1574 $strong = true;
1575 foreach ( $keys as $name => $length ) {
1576 $secretKey = MWCryptRand::generateHex( $length, true );
1577 if ( !MWCryptRand::wasStrong() ) {
1578 $strong = false;
1581 $this->setVar( $name, $secretKey );
1584 if ( !$strong ) {
1585 $names = array_keys( $keys );
1586 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1587 global $wgLang;
1588 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1591 return $status;
1595 * Create the first user account, grant it sysop and bureaucrat rights
1597 * @return Status
1599 protected function createSysop() {
1600 $name = $this->getVar( '_AdminName' );
1601 $user = User::newFromName( $name );
1603 if ( !$user ) {
1604 // We should've validated this earlier anyway!
1605 return Status::newFatal( 'config-admin-error-user', $name );
1608 if ( $user->idForName() == 0 ) {
1609 $user->addToDatabase();
1611 try {
1612 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1613 } catch ( PasswordError $pwe ) {
1614 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1617 $user->addGroup( 'sysop' );
1618 $user->addGroup( 'bureaucrat' );
1619 if ( $this->getVar( '_AdminEmail' ) ) {
1620 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1622 $user->saveSettings();
1624 // Update user count
1625 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1626 $ssUpdate->doUpdate();
1628 $status = Status::newGood();
1630 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1631 $this->subscribeToMediaWikiAnnounce( $status );
1634 return $status;
1638 * @param Status $s
1640 private function subscribeToMediaWikiAnnounce( Status $s ) {
1641 $params = array(
1642 'email' => $this->getVar( '_AdminEmail' ),
1643 'language' => 'en',
1644 'digest' => 0
1647 // Mailman doesn't support as many languages as we do, so check to make
1648 // sure their selected language is available
1649 $myLang = $this->getVar( '_UserLang' );
1650 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1651 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1652 $params['language'] = $myLang;
1655 if ( MWHttpRequest::canMakeRequests() ) {
1656 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1657 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1658 if ( !$res->isOK() ) {
1659 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1661 } else {
1662 $s->warning( 'config-install-subscribe-notpossible' );
1667 * Insert Main Page with default content.
1669 * @param DatabaseInstaller $installer
1670 * @return Status
1672 protected function createMainpage( DatabaseInstaller $installer ) {
1673 $status = Status::newGood();
1674 try {
1675 $page = WikiPage::factory( Title::newMainPage() );
1676 $content = new WikitextContent(
1677 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1678 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1681 $page->doEditContent( $content,
1683 EDIT_NEW,
1684 false,
1685 User::newFromName( 'MediaWiki default' )
1687 } catch ( MWException $e ) {
1688 //using raw, because $wgShowExceptionDetails can not be set yet
1689 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1692 return $status;
1696 * Override the necessary bits of the config to run an installation.
1698 public static function overrideConfig() {
1699 define( 'MW_NO_SESSION', 1 );
1701 // Don't access the database
1702 $GLOBALS['wgUseDatabaseMessages'] = false;
1703 // Don't cache langconv tables
1704 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1705 // Debug-friendly
1706 $GLOBALS['wgShowExceptionDetails'] = true;
1707 // Don't break forms
1708 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1710 // Extended debugging
1711 $GLOBALS['wgShowSQLErrors'] = true;
1712 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1714 // Allow multiple ob_flush() calls
1715 $GLOBALS['wgDisableOutputCompression'] = true;
1717 // Use a sensible cookie prefix (not my_wiki)
1718 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1720 // Some of the environment checks make shell requests, remove limits
1721 $GLOBALS['wgMaxShellMemory'] = 0;
1723 // Don't bother embedding images into generated CSS, which is not cached
1724 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1725 return $less->toBool( false );
1730 * Add an installation step following the given step.
1732 * @param callable $callback A valid installation callback array, in this form:
1733 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1734 * @param string $findStep The step to find. Omit to put the step at the beginning
1736 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1737 $this->extraInstallSteps[$findStep][] = $callback;
1741 * Disable the time limit for execution.
1742 * Some long-running pages (Install, Upgrade) will want to do this
1744 protected function disableTimeLimit() {
1745 wfSuppressWarnings();
1746 set_time_limit( 0 );
1747 wfRestoreWarnings();