Merge "mediawiki.api: Use then() in getToken instead of manual Deferred wrapping"
[mediawiki.git] / includes / installer / Installer.php
blob17c5ab230bcf018afbd10b4f4cabc2e2c02b0a7c
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 'wgShellLocale',
174 'wgSecretKey',
175 'wgUseInstantCommons',
176 'wgUpgradeKey',
177 'wgDefaultSkin',
178 'wgResourceLoaderMaxQueryLength',
182 * Variables that are stored alongside globals, and are used for any
183 * configuration of the installation process aside from the MediaWiki
184 * configuration. Map of names to defaults.
186 * @var array
188 protected $internalDefaults = array(
189 '_UserLang' => 'en',
190 '_Environment' => false,
191 '_SafeMode' => false,
192 '_RaiseMemory' => false,
193 '_UpgradeDone' => false,
194 '_InstallDone' => false,
195 '_Caches' => array(),
196 '_InstallPassword' => '',
197 '_SameAccount' => true,
198 '_CreateDBAccount' => false,
199 '_NamespaceType' => 'site-name',
200 '_AdminName' => '', // will be set later, when the user selects language
201 '_AdminPassword' => '',
202 '_AdminPasswordConfirm' => '',
203 '_AdminEmail' => '',
204 '_Subscribe' => false,
205 '_SkipOptional' => 'continue',
206 '_RightsProfile' => 'wiki',
207 '_LicenseCode' => 'none',
208 '_CCDone' => false,
209 '_Extensions' => array(),
210 '_MemCachedServers' => '',
211 '_UpgradeKeySupplied' => false,
212 '_ExistingDBSettings' => false,
214 // $wgLogo is probably wrong (bug 48084); set something that will work.
215 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
216 'wgLogo' => '$wgStylePath/common/images/wiki.png',
220 * The actual list of installation steps. This will be initialized by getInstallSteps()
222 * @var array
224 private $installSteps = array();
227 * Extra steps for installation, for things like DatabaseInstallers to modify
229 * @var array
231 protected $extraInstallSteps = array();
234 * Known object cache types and the functions used to test for their existence.
236 * @var array
238 protected $objectCaches = array(
239 'xcache' => 'xcache_get',
240 'apc' => 'apc_fetch',
241 'wincache' => 'wincache_ucache_get'
245 * User rights profiles.
247 * @var array
249 public $rightsProfiles = array(
250 'wiki' => array(),
251 'no-anon' => array(
252 '*' => array( 'edit' => false )
254 'fishbowl' => array(
255 '*' => array(
256 'createaccount' => false,
257 'edit' => false,
260 'private' => array(
261 '*' => array(
262 'createaccount' => false,
263 'edit' => false,
264 'read' => false,
270 * License types.
272 * @var array
274 public $licenses = array(
275 'cc-by' => array(
276 'url' => 'http://creativecommons.org/licenses/by/3.0/',
277 'icon' => '{$wgStylePath}/common/images/cc-by.png',
279 'cc-by-sa' => array(
280 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
281 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
283 'cc-by-nc-sa' => array(
284 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
285 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
287 'cc-0' => array(
288 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
289 'icon' => '{$wgStylePath}/common/images/cc-0.png',
291 'pd' => array(
292 'url' => '',
293 'icon' => '{$wgStylePath}/common/images/public-domain.png',
295 'gfdl' => array(
296 'url' => 'http://www.gnu.org/copyleft/fdl.html',
297 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
299 'none' => array(
300 'url' => '',
301 'icon' => '',
302 'text' => ''
304 'cc-choose' => array(
305 // Details will be filled in by the selector.
306 'url' => '',
307 'icon' => '',
308 'text' => '',
313 * URL to mediawiki-announce subscription
315 protected $mediaWikiAnnounceUrl =
316 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
319 * Supported language codes for Mailman
321 protected $mediaWikiAnnounceLanguages = array(
322 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
323 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
324 'sl', 'sr', 'sv', 'tr', 'uk'
328 * UI interface for displaying a short message
329 * The parameters are like parameters to wfMessage().
330 * The messages will be in wikitext format, which will be converted to an
331 * output format such as HTML or text before being sent to the user.
332 * @param string $msg
334 abstract public function showMessage( $msg /*, ... */ );
337 * Same as showMessage(), but for displaying errors
338 * @param string $msg
340 abstract public function showError( $msg /*, ... */ );
343 * Show a message to the installing user by using a Status object
344 * @param Status $status
346 abstract public function showStatusMessage( Status $status );
349 * Constructor, always call this from child classes.
351 public function __construct() {
352 global $wgMessagesDirs, $wgUser;
354 // Disable the i18n cache and LoadBalancer
355 Language::getLocalisationCache()->disableBackend();
356 LBFactory::disableBackend();
358 // Load the installer's i18n.
359 $wgMessagesDirs['MediawikiInstaller'] = __DIR__ . '/i18n';
361 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
362 $wgUser = User::newFromId( 0 );
364 $this->settings = $this->internalDefaults;
366 foreach ( $this->defaultVarNames as $var ) {
367 $this->settings[$var] = $GLOBALS[$var];
370 $compiledDBs = array();
371 foreach ( self::getDBTypes() as $type ) {
372 $installer = $this->getDBInstaller( $type );
374 if ( !$installer->isCompiled() ) {
375 continue;
377 $compiledDBs[] = $type;
379 $defaults = $installer->getGlobalDefaults();
381 foreach ( $installer->getGlobalNames() as $var ) {
382 if ( isset( $defaults[$var] ) ) {
383 $this->settings[$var] = $defaults[$var];
384 } else {
385 $this->settings[$var] = $GLOBALS[$var];
389 $this->compiledDBs = $compiledDBs;
391 $this->parserTitle = Title::newFromText( 'Installer' );
392 $this->parserOptions = new ParserOptions; // language will be wrong :(
393 $this->parserOptions->setEditSection( false );
397 * Get a list of known DB types.
399 * @return array
401 public static function getDBTypes() {
402 return self::$dbTypes;
406 * Do initial checks of the PHP environment. Set variables according to
407 * the observed environment.
409 * It's possible that this may be called under the CLI SAPI, not the SAPI
410 * that the wiki will primarily run under. In that case, the subclass should
411 * initialise variables such as wgScriptPath, before calling this function.
413 * Under the web subclass, it can already be assumed that PHP 5+ is in use
414 * and that sessions are working.
416 * @return Status
418 public function doEnvironmentChecks() {
419 $phpVersion = phpversion();
420 if ( version_compare( $phpVersion, self::MINIMUM_PHP_VERSION, '>=' ) ) {
421 $this->showMessage( 'config-env-php', $phpVersion );
422 $good = true;
423 } else {
424 $this->showMessage( 'config-env-php-toolow', $phpVersion, self::MINIMUM_PHP_VERSION );
425 $good = false;
428 // Must go here because an old version of PCRE can prevent other checks from completing
429 if ( $good ) {
430 list( $pcreVersion ) = explode( ' ', PCRE_VERSION, 2 );
431 if ( version_compare( $pcreVersion, self::MINIMUM_PCRE_VERSION, '<' ) ) {
432 $this->showError( 'config-pcre-old', self::MINIMUM_PCRE_VERSION, $pcreVersion );
433 $good = false;
437 if ( $good ) {
438 foreach ( $this->envChecks as $check ) {
439 $status = $this->$check();
440 if ( $status === false ) {
441 $good = false;
446 $this->setVar( '_Environment', $good );
448 return $good ? Status::newGood() : Status::newFatal( 'config-env-bad' );
452 * Set a MW configuration variable, or internal installer configuration variable.
454 * @param string $name
455 * @param mixed $value
457 public function setVar( $name, $value ) {
458 $this->settings[$name] = $value;
462 * Get an MW configuration variable, or internal installer configuration variable.
463 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
464 * Installer variables are typically prefixed by an underscore.
466 * @param string $name
467 * @param mixed $default
469 * @return mixed
471 public function getVar( $name, $default = null ) {
472 if ( !isset( $this->settings[$name] ) ) {
473 return $default;
474 } else {
475 return $this->settings[$name];
480 * Get a list of DBs supported by current PHP setup
482 * @return array
484 public function getCompiledDBs() {
485 return $this->compiledDBs;
489 * Get an instance of DatabaseInstaller for the specified DB type.
491 * @param mixed $type DB installer for which is needed, false to use default.
493 * @return DatabaseInstaller
495 public function getDBInstaller( $type = false ) {
496 if ( !$type ) {
497 $type = $this->getVar( 'wgDBtype' );
500 $type = strtolower( $type );
502 if ( !isset( $this->dbInstallers[$type] ) ) {
503 $class = ucfirst( $type ) . 'Installer';
504 $this->dbInstallers[$type] = new $class( $this );
507 return $this->dbInstallers[$type];
511 * Determine if LocalSettings.php exists. If it does, return its variables.
513 * @return array
515 public static function getExistingLocalSettings() {
516 global $IP;
518 wfSuppressWarnings();
519 $_lsExists = file_exists( "$IP/LocalSettings.php" );
520 wfRestoreWarnings();
522 if ( !$_lsExists ) {
523 return false;
525 unset( $_lsExists );
527 require "$IP/includes/DefaultSettings.php";
528 require "$IP/LocalSettings.php";
530 return get_defined_vars();
534 * Get a fake password for sending back to the user in HTML.
535 * This is a security mechanism to avoid compromise of the password in the
536 * event of session ID compromise.
538 * @param string $realPassword
540 * @return string
542 public function getFakePassword( $realPassword ) {
543 return str_repeat( '*', strlen( $realPassword ) );
547 * Set a variable which stores a password, except if the new value is a
548 * fake password in which case leave it as it is.
550 * @param string $name
551 * @param mixed $value
553 public function setPassword( $name, $value ) {
554 if ( !preg_match( '/^\*+$/', $value ) ) {
555 $this->setVar( $name, $value );
560 * On POSIX systems return the primary group of the webserver we're running under.
561 * On other systems just returns null.
563 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
564 * webserver user before he can install.
566 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
568 * @return mixed
570 public static function maybeGetWebserverPrimaryGroup() {
571 if ( !function_exists( 'posix_getegid' ) || !function_exists( 'posix_getpwuid' ) ) {
572 # I don't know this, this isn't UNIX.
573 return null;
576 # posix_getegid() *not* getmygid() because we want the group of the webserver,
577 # not whoever owns the current script.
578 $gid = posix_getegid();
579 $getpwuid = posix_getpwuid( $gid );
580 $group = $getpwuid['name'];
582 return $group;
586 * Convert wikitext $text to HTML.
588 * This is potentially error prone since many parser features require a complete
589 * installed MW database. The solution is to just not use those features when you
590 * write your messages. This appears to work well enough. Basic formatting and
591 * external links work just fine.
593 * But in case a translator decides to throw in a "#ifexist" or internal link or
594 * whatever, this function is guarded to catch the attempted DB access and to present
595 * some fallback text.
597 * @param string $text
598 * @param bool $lineStart
599 * @return string
601 public function parse( $text, $lineStart = false ) {
602 global $wgParser;
604 try {
605 $out = $wgParser->parse( $text, $this->parserTitle, $this->parserOptions, $lineStart );
606 $html = $out->getText();
607 } catch ( DBAccessError $e ) {
608 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
610 if ( !empty( $this->debug ) ) {
611 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
615 return $html;
619 * @return ParserOptions
621 public function getParserOptions() {
622 return $this->parserOptions;
625 public function disableLinkPopups() {
626 $this->parserOptions->setExternalLinkTarget( false );
629 public function restoreLinkPopups() {
630 global $wgExternalLinkTarget;
631 $this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
635 * Install step which adds a row to the site_stats table with appropriate
636 * initial values.
638 * @param DatabaseInstaller $installer
640 * @return Status
642 public function populateSiteStats( DatabaseInstaller $installer ) {
643 $status = $installer->getConnection();
644 if ( !$status->isOK() ) {
645 return $status;
647 $status->value->insert(
648 'site_stats',
649 array(
650 'ss_row_id' => 1,
651 'ss_total_views' => 0,
652 'ss_total_edits' => 0,
653 'ss_good_articles' => 0,
654 'ss_total_pages' => 0,
655 'ss_users' => 0,
656 'ss_images' => 0
658 __METHOD__, 'IGNORE'
661 return Status::newGood();
665 * Exports all wg* variables stored by the installer into global scope.
667 public function exportVars() {
668 foreach ( $this->settings as $name => $value ) {
669 if ( substr( $name, 0, 2 ) == 'wg' ) {
670 $GLOBALS[$name] = $value;
676 * Environment check for DB types.
677 * @return bool
679 protected function envCheckDB() {
680 global $wgLang;
682 $allNames = array();
684 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
685 // config-type-sqlite
686 foreach ( self::getDBTypes() as $name ) {
687 $allNames[] = wfMessage( "config-type-$name" )->text();
690 $databases = $this->getCompiledDBs();
692 $databases = array_flip( $databases );
693 foreach ( array_keys( $databases ) as $db ) {
694 $installer = $this->getDBInstaller( $db );
695 $status = $installer->checkPrerequisites();
696 if ( !$status->isGood() ) {
697 $this->showStatusMessage( $status );
699 if ( !$status->isOK() ) {
700 unset( $databases[$db] );
703 $databases = array_flip( $databases );
704 if ( !$databases ) {
705 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
707 // @todo FIXME: This only works for the web installer!
708 return false;
711 return true;
715 * Environment check for register_globals.
717 protected function envCheckRegisterGlobals() {
718 if ( wfIniGetBool( 'register_globals' ) ) {
719 $this->showMessage( 'config-register-globals' );
724 * Some versions of libxml+PHP break < and > encoding horribly
725 * @return bool
727 protected function envCheckBrokenXML() {
728 $test = new PhpXmlBugTester();
729 if ( !$test->ok ) {
730 $this->showError( 'config-brokenlibxml' );
732 return false;
735 return true;
739 * Environment check for magic_quotes_runtime.
740 * @return bool
742 protected function envCheckMagicQuotes() {
743 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
744 $this->showError( 'config-magic-quotes-runtime' );
746 return false;
749 return true;
753 * Environment check for magic_quotes_sybase.
754 * @return bool
756 protected function envCheckMagicSybase() {
757 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
758 $this->showError( 'config-magic-quotes-sybase' );
760 return false;
763 return true;
767 * Environment check for mbstring.func_overload.
768 * @return bool
770 protected function envCheckMbstring() {
771 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
772 $this->showError( 'config-mbstring' );
774 return false;
777 return true;
781 * Environment check for safe_mode.
782 * @return bool
784 protected function envCheckSafeMode() {
785 if ( wfIniGetBool( 'safe_mode' ) ) {
786 $this->setVar( '_SafeMode', true );
787 $this->showMessage( 'config-safe-mode' );
790 return true;
794 * Environment check for the XML module.
795 * @return bool
797 protected function envCheckXML() {
798 if ( !function_exists( "utf8_encode" ) ) {
799 $this->showError( 'config-xml-bad' );
801 return false;
804 return true;
808 * Environment check for the PCRE module.
810 * @note If this check were to fail, the parser would
811 * probably throw an exception before the result
812 * of this check is shown to the user.
813 * @return bool
815 protected function envCheckPCRE() {
816 wfSuppressWarnings();
817 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
818 // Need to check for \p support too, as PCRE can be compiled
819 // with utf8 support, but not unicode property support.
820 // check that \p{Zs} (space separators) matches
821 // U+3000 (Ideographic space)
822 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
823 wfRestoreWarnings();
824 if ( $regexd != '--' || $regexprop != '--' ) {
825 $this->showError( 'config-pcre-no-utf8' );
827 return false;
830 return true;
834 * Environment check for available memory.
835 * @return bool
837 protected function envCheckMemory() {
838 $limit = ini_get( 'memory_limit' );
840 if ( !$limit || $limit == -1 ) {
841 return true;
844 $n = wfShorthandToInteger( $limit );
846 if ( $n < $this->minMemorySize * 1024 * 1024 ) {
847 $newLimit = "{$this->minMemorySize}M";
849 if ( ini_set( "memory_limit", $newLimit ) === false ) {
850 $this->showMessage( 'config-memory-bad', $limit );
851 } else {
852 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
853 $this->setVar( '_RaiseMemory', true );
857 return true;
861 * Environment check for compiled object cache types.
863 protected function envCheckCache() {
864 $caches = array();
865 foreach ( $this->objectCaches as $name => $function ) {
866 if ( function_exists( $function ) ) {
867 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
868 continue;
870 $caches[$name] = true;
874 if ( !$caches ) {
875 $this->showMessage( 'config-no-cache' );
878 $this->setVar( '_Caches', $caches );
882 * Scare user to death if they have mod_security
883 * @return bool
885 protected function envCheckModSecurity() {
886 if ( self::apacheModulePresent( 'mod_security' ) ) {
887 $this->showMessage( 'config-mod-security' );
890 return true;
894 * Search for GNU diff3.
895 * @return bool
897 protected function envCheckDiff3() {
898 $names = array( "gdiff3", "diff3", "diff3.exe" );
899 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
901 $diff3 = self::locateExecutableInDefaultPaths( $names, $versionInfo );
903 if ( $diff3 ) {
904 $this->setVar( 'wgDiff3', $diff3 );
905 } else {
906 $this->setVar( 'wgDiff3', false );
907 $this->showMessage( 'config-diff3-bad' );
910 return true;
914 * Environment check for ImageMagick and GD.
915 * @return bool
917 protected function envCheckGraphics() {
918 $names = array( wfIsWindows() ? 'convert.exe' : 'convert' );
919 $versionInfo = array( '$1 -version', 'ImageMagick' );
920 $convert = self::locateExecutableInDefaultPaths( $names, $versionInfo );
922 $this->setVar( 'wgImageMagickConvertCommand', '' );
923 if ( $convert ) {
924 $this->setVar( 'wgImageMagickConvertCommand', $convert );
925 $this->showMessage( 'config-imagemagick', $convert );
927 return true;
928 } elseif ( function_exists( 'imagejpeg' ) ) {
929 $this->showMessage( 'config-gd' );
930 } else {
931 $this->showMessage( 'config-no-scaling' );
934 return true;
938 * Search for git.
940 * @since 1.22
941 * @return bool
943 protected function envCheckGit() {
944 $names = array( wfIsWindows() ? 'git.exe' : 'git' );
945 $versionInfo = array( '$1 --version', 'git version' );
947 $git = self::locateExecutableInDefaultPaths( $names, $versionInfo );
949 if ( $git ) {
950 $this->setVar( 'wgGitBin', $git );
951 $this->showMessage( 'config-git', $git );
952 } else {
953 $this->setVar( 'wgGitBin', false );
954 $this->showMessage( 'config-git-bad' );
957 return true;
961 * Environment check for the server hostname.
963 protected function envCheckServer() {
964 $server = $this->envGetDefaultServer();
965 if ( $server !== null ) {
966 $this->showMessage( 'config-using-server', $server );
967 $this->setVar( 'wgServer', $server );
970 return true;
974 * Helper function to be called from envCheckServer()
975 * @return string
977 abstract protected function envGetDefaultServer();
980 * Environment check for setting $IP and $wgScriptPath.
981 * @return bool
983 protected function envCheckPath() {
984 global $IP;
985 $IP = dirname( dirname( __DIR__ ) );
986 $this->setVar( 'IP', $IP );
988 $this->showMessage(
989 'config-using-uri',
990 $this->getVar( 'wgServer' ),
991 $this->getVar( 'wgScriptPath' )
994 return true;
998 * Environment check for setting the preferred PHP file extension.
999 * @return bool
1001 protected function envCheckExtension() {
1002 // @todo FIXME: Detect this properly
1003 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1004 $ext = 'php5';
1005 } else {
1006 $ext = 'php';
1008 $this->setVar( 'wgScriptExtension', ".$ext" );
1010 return true;
1014 * Environment check for preferred locale in shell
1015 * @return bool
1017 protected function envCheckShellLocale() {
1018 $os = php_uname( 's' );
1019 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1021 if ( !in_array( $os, $supported ) ) {
1022 return true;
1025 # Get a list of available locales.
1026 $ret = false;
1027 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1029 if ( $ret ) {
1030 return true;
1033 $lines = array_map( 'trim', explode( "\n", $lines ) );
1034 $candidatesByLocale = array();
1035 $candidatesByLang = array();
1037 foreach ( $lines as $line ) {
1038 if ( $line === '' ) {
1039 continue;
1042 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1043 continue;
1046 list( , $lang, , , ) = $m;
1048 $candidatesByLocale[$m[0]] = $m;
1049 $candidatesByLang[$lang][] = $m;
1052 # Try the current value of LANG.
1053 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1054 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1056 return true;
1059 # Try the most common ones.
1060 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1061 foreach ( $commonLocales as $commonLocale ) {
1062 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1063 $this->setVar( 'wgShellLocale', $commonLocale );
1065 return true;
1069 # Is there an available locale in the Wiki's language?
1070 $wikiLang = $this->getVar( 'wgLanguageCode' );
1072 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1073 $m = reset( $candidatesByLang[$wikiLang] );
1074 $this->setVar( 'wgShellLocale', $m[0] );
1076 return true;
1079 # Are there any at all?
1080 if ( count( $candidatesByLocale ) ) {
1081 $m = reset( $candidatesByLocale );
1082 $this->setVar( 'wgShellLocale', $m[0] );
1084 return true;
1087 # Give up.
1088 return true;
1092 * Environment check for the permissions of the uploads directory
1093 * @return bool
1095 protected function envCheckUploadsDirectory() {
1096 global $IP;
1098 $dir = $IP . '/images/';
1099 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1100 $safe = !$this->dirIsExecutable( $dir, $url );
1102 if ( !$safe ) {
1103 $this->showMessage( 'config-uploads-not-safe', $dir );
1106 return true;
1110 * Checks if suhosin.get.max_value_length is set, and if so generate
1111 * a warning because it decreases ResourceLoader performance.
1112 * @return bool
1114 protected function envCheckSuhosinMaxValueLength() {
1115 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1116 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1117 // Only warn if the value is below the sane 1024
1118 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1121 return true;
1125 * Convert a hex string representing a Unicode code point to that code point.
1126 * @param string $c
1127 * @return string
1129 protected function unicodeChar( $c ) {
1130 $c = hexdec( $c );
1131 if ( $c <= 0x7F ) {
1132 return chr( $c );
1133 } elseif ( $c <= 0x7FF ) {
1134 return chr( 0xC0 | $c >> 6 ) . chr( 0x80 | $c & 0x3F );
1135 } elseif ( $c <= 0xFFFF ) {
1136 return chr( 0xE0 | $c >> 12 ) . chr( 0x80 | $c >> 6 & 0x3F )
1137 . chr( 0x80 | $c & 0x3F );
1138 } elseif ( $c <= 0x10FFFF ) {
1139 return chr( 0xF0 | $c >> 18 ) . chr( 0x80 | $c >> 12 & 0x3F )
1140 . chr( 0x80 | $c >> 6 & 0x3F )
1141 . chr( 0x80 | $c & 0x3F );
1142 } else {
1143 return false;
1148 * Check the libicu version
1150 protected function envCheckLibicu() {
1151 $utf8 = function_exists( 'utf8_normalize' );
1152 $intl = function_exists( 'normalizer_normalize' );
1155 * This needs to be updated something that the latest libicu
1156 * will properly normalize. This normalization was found at
1157 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1158 * Note that we use the hex representation to create the code
1159 * points in order to avoid any Unicode-destroying during transit.
1161 $not_normal_c = $this->unicodeChar( "FA6C" );
1162 $normal_c = $this->unicodeChar( "242EE" );
1164 $useNormalizer = 'php';
1165 $needsUpdate = false;
1168 * We're going to prefer the pecl extension here unless
1169 * utf8_normalize is more up to date.
1171 if ( $utf8 ) {
1172 $useNormalizer = 'utf8';
1173 $utf8 = utf8_normalize( $not_normal_c, UtfNormal::UNORM_NFC );
1174 if ( $utf8 !== $normal_c ) {
1175 $needsUpdate = true;
1178 if ( $intl ) {
1179 $useNormalizer = 'intl';
1180 $intl = normalizer_normalize( $not_normal_c, Normalizer::FORM_C );
1181 if ( $intl !== $normal_c ) {
1182 $needsUpdate = true;
1186 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1187 // 'config-unicode-using-intl'
1188 if ( $useNormalizer === 'php' ) {
1189 $this->showMessage( 'config-unicode-pure-php-warning' );
1190 } else {
1191 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1192 if ( $needsUpdate ) {
1193 $this->showMessage( 'config-unicode-update-warning' );
1199 * @return bool
1201 protected function envCheckCtype() {
1202 if ( !function_exists( 'ctype_digit' ) ) {
1203 $this->showError( 'config-ctype' );
1205 return false;
1208 return true;
1212 * @return bool
1214 protected function envCheckJSON() {
1215 if ( !function_exists( 'json_decode' ) ) {
1216 $this->showError( 'config-json' );
1218 return false;
1221 return true;
1225 * Get an array of likely places we can find executables. Check a bunch
1226 * of known Unix-like defaults, as well as the PATH environment variable
1227 * (which should maybe make it work for Windows?)
1229 * @return array
1231 protected static function getPossibleBinPaths() {
1232 return array_merge(
1233 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1234 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1235 explode( PATH_SEPARATOR, getenv( 'PATH' ) )
1240 * Search a path for any of the given executable names. Returns the
1241 * executable name if found. Also checks the version string returned
1242 * by each executable.
1244 * Used only by environment checks.
1246 * @param string $path path to search
1247 * @param array $names of executable names
1248 * @param array|bool $versionInfo False or array with two members:
1249 * 0 => Command to run for version check, with $1 for the full executable name
1250 * 1 => String to compare the output with
1252 * If $versionInfo is not false, only executables with a version
1253 * matching $versionInfo[1] will be returned.
1254 * @return bool|string
1256 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1257 if ( !is_array( $names ) ) {
1258 $names = array( $names );
1261 foreach ( $names as $name ) {
1262 $command = $path . DIRECTORY_SEPARATOR . $name;
1264 wfSuppressWarnings();
1265 $file_exists = file_exists( $command );
1266 wfRestoreWarnings();
1268 if ( $file_exists ) {
1269 if ( !$versionInfo ) {
1270 return $command;
1273 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1274 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1275 return $command;
1280 return false;
1284 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1285 * @see locateExecutable()
1286 * @param array $names Array of possible names.
1287 * @param array|bool $versionInfo Default: false or array with two members:
1288 * 0 => Command to run for version check, with $1 for the full executable name
1289 * 1 => String to compare the output with
1291 * If $versionInfo is not false, only executables with a version
1292 * matching $versionInfo[1] will be returned.
1293 * @return bool|string
1295 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1296 foreach ( self::getPossibleBinPaths() as $path ) {
1297 $exe = self::locateExecutable( $path, $names, $versionInfo );
1298 if ( $exe !== false ) {
1299 return $exe;
1303 return false;
1307 * Checks if scripts located in the given directory can be executed via the given URL.
1309 * Used only by environment checks.
1310 * @param string $dir
1311 * @param string $url
1312 * @return bool|int|string
1314 public function dirIsExecutable( $dir, $url ) {
1315 $scriptTypes = array(
1316 'php' => array(
1317 "<?php echo 'ex' . 'ec';",
1318 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1322 // it would be good to check other popular languages here, but it'll be slow.
1324 wfSuppressWarnings();
1326 foreach ( $scriptTypes as $ext => $contents ) {
1327 foreach ( $contents as $source ) {
1328 $file = 'exectest.' . $ext;
1330 if ( !file_put_contents( $dir . $file, $source ) ) {
1331 break;
1334 try {
1335 $text = Http::get( $url . $file, array( 'timeout' => 3 ) );
1336 } catch ( MWException $e ) {
1337 // Http::get throws with allow_url_fopen = false and no curl extension.
1338 $text = null;
1340 unlink( $dir . $file );
1342 if ( $text == 'exec' ) {
1343 wfRestoreWarnings();
1345 return $ext;
1350 wfRestoreWarnings();
1352 return false;
1356 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1358 * @param string $moduleName Name of module to check.
1359 * @return bool
1361 public static function apacheModulePresent( $moduleName ) {
1362 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1363 return true;
1365 // try it the hard way
1366 ob_start();
1367 phpinfo( INFO_MODULES );
1368 $info = ob_get_clean();
1370 return strpos( $info, $moduleName ) !== false;
1374 * ParserOptions are constructed before we determined the language, so fix it
1376 * @param Language $lang
1378 public function setParserLanguage( $lang ) {
1379 $this->parserOptions->setTargetLanguage( $lang );
1380 $this->parserOptions->setUserLang( $lang );
1384 * Overridden by WebInstaller to provide lastPage parameters.
1385 * @param string $page
1386 * @return string
1388 protected function getDocUrl( $page ) {
1389 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1393 * Finds extensions that follow the format /extensions/Name/Name.php,
1394 * and returns an array containing the value for 'Name' for each found extension.
1396 * @return array
1398 public function findExtensions() {
1399 if ( $this->getVar( 'IP' ) === null ) {
1400 return array();
1403 $extDir = $this->getVar( 'IP' ) . '/extensions';
1404 if ( !is_readable( $extDir ) || !is_dir( $extDir ) ) {
1405 return array();
1408 $dh = opendir( $extDir );
1409 $exts = array();
1410 while ( ( $file = readdir( $dh ) ) !== false ) {
1411 if ( !is_dir( "$extDir/$file" ) ) {
1412 continue;
1414 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1415 $exts[] = $file;
1418 closedir( $dh );
1419 natcasesort( $exts );
1421 return $exts;
1425 * Installs the auto-detected extensions.
1427 * @return Status
1429 protected function includeExtensions() {
1430 global $IP;
1431 $exts = $this->getVar( '_Extensions' );
1432 $IP = $this->getVar( 'IP' );
1435 * We need to include DefaultSettings before including extensions to avoid
1436 * warnings about unset variables. However, the only thing we really
1437 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1438 * if the extension has hidden hook registration in $wgExtensionFunctions,
1439 * but we're not opening that can of worms
1440 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1442 global $wgAutoloadClasses;
1443 $wgAutoloadClasses = array();
1445 require "$IP/includes/DefaultSettings.php";
1447 foreach ( $exts as $e ) {
1448 require_once "$IP/extensions/$e/$e.php";
1451 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1452 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1454 // Unset everyone else's hooks. Lord knows what someone might be doing
1455 // in ParserFirstCallInit (see bug 27171)
1456 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1458 return Status::newGood();
1462 * Get an array of install steps. Should always be in the format of
1463 * array(
1464 * 'name' => 'someuniquename',
1465 * 'callback' => array( $obj, 'method' ),
1467 * There must be a config-install-$name message defined per step, which will
1468 * be shown on install.
1470 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1471 * @return array
1473 protected function getInstallSteps( DatabaseInstaller $installer ) {
1474 $coreInstallSteps = array(
1475 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1476 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1477 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1478 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1479 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1480 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1481 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1484 // Build the array of install steps starting from the core install list,
1485 // then adding any callbacks that wanted to attach after a given step
1486 foreach ( $coreInstallSteps as $step ) {
1487 $this->installSteps[] = $step;
1488 if ( isset( $this->extraInstallSteps[$step['name']] ) ) {
1489 $this->installSteps = array_merge(
1490 $this->installSteps,
1491 $this->extraInstallSteps[$step['name']]
1496 // Prepend any steps that want to be at the beginning
1497 if ( isset( $this->extraInstallSteps['BEGINNING'] ) ) {
1498 $this->installSteps = array_merge(
1499 $this->extraInstallSteps['BEGINNING'],
1500 $this->installSteps
1504 // Extensions should always go first, chance to tie into hooks and such
1505 if ( count( $this->getVar( '_Extensions' ) ) ) {
1506 array_unshift( $this->installSteps,
1507 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1509 $this->installSteps[] = array(
1510 'name' => 'extension-tables',
1511 'callback' => array( $installer, 'createExtensionTables' )
1515 return $this->installSteps;
1519 * Actually perform the installation.
1521 * @param array $startCB A callback array for the beginning of each step
1522 * @param array $endCB A callback array for the end of each step
1524 * @return array Array of Status objects
1526 public function performInstallation( $startCB, $endCB ) {
1527 $installResults = array();
1528 $installer = $this->getDBInstaller();
1529 $installer->preInstall();
1530 $steps = $this->getInstallSteps( $installer );
1531 foreach ( $steps as $stepObj ) {
1532 $name = $stepObj['name'];
1533 call_user_func_array( $startCB, array( $name ) );
1535 // Perform the callback step
1536 $status = call_user_func( $stepObj['callback'], $installer );
1538 // Output and save the results
1539 call_user_func( $endCB, $name, $status );
1540 $installResults[$name] = $status;
1542 // If we've hit some sort of fatal, we need to bail.
1543 // Callback already had a chance to do output above.
1544 if ( !$status->isOk() ) {
1545 break;
1548 if ( $status->isOk() ) {
1549 $this->setVar( '_InstallDone', true );
1552 return $installResults;
1556 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1558 * @return Status
1560 public function generateKeys() {
1561 $keys = array( 'wgSecretKey' => 64 );
1562 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1563 $keys['wgUpgradeKey'] = 16;
1566 return $this->doGenerateKeys( $keys );
1570 * Generate a secret value for variables using our CryptRand generator.
1571 * Produce a warning if the random source was insecure.
1573 * @param array $keys
1574 * @return Status
1576 protected function doGenerateKeys( $keys ) {
1577 $status = Status::newGood();
1579 $strong = true;
1580 foreach ( $keys as $name => $length ) {
1581 $secretKey = MWCryptRand::generateHex( $length, true );
1582 if ( !MWCryptRand::wasStrong() ) {
1583 $strong = false;
1586 $this->setVar( $name, $secretKey );
1589 if ( !$strong ) {
1590 $names = array_keys( $keys );
1591 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1592 global $wgLang;
1593 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1596 return $status;
1600 * Create the first user account, grant it sysop and bureaucrat rights
1602 * @return Status
1604 protected function createSysop() {
1605 $name = $this->getVar( '_AdminName' );
1606 $user = User::newFromName( $name );
1608 if ( !$user ) {
1609 // We should've validated this earlier anyway!
1610 return Status::newFatal( 'config-admin-error-user', $name );
1613 if ( $user->idForName() == 0 ) {
1614 $user->addToDatabase();
1616 try {
1617 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1618 } catch ( PasswordError $pwe ) {
1619 return Status::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1622 $user->addGroup( 'sysop' );
1623 $user->addGroup( 'bureaucrat' );
1624 if ( $this->getVar( '_AdminEmail' ) ) {
1625 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1627 $user->saveSettings();
1629 // Update user count
1630 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1631 $ssUpdate->doUpdate();
1633 $status = Status::newGood();
1635 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1636 $this->subscribeToMediaWikiAnnounce( $status );
1639 return $status;
1643 * @param Status $s
1645 private function subscribeToMediaWikiAnnounce( Status $s ) {
1646 $params = array(
1647 'email' => $this->getVar( '_AdminEmail' ),
1648 'language' => 'en',
1649 'digest' => 0
1652 // Mailman doesn't support as many languages as we do, so check to make
1653 // sure their selected language is available
1654 $myLang = $this->getVar( '_UserLang' );
1655 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages ) ) {
1656 $myLang = $myLang == 'pt-br' ? 'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1657 $params['language'] = $myLang;
1660 if ( MWHttpRequest::canMakeRequests() ) {
1661 $res = MWHttpRequest::factory( $this->mediaWikiAnnounceUrl,
1662 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1663 if ( !$res->isOK() ) {
1664 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1666 } else {
1667 $s->warning( 'config-install-subscribe-notpossible' );
1672 * Insert Main Page with default content.
1674 * @param DatabaseInstaller $installer
1675 * @return Status
1677 protected function createMainpage( DatabaseInstaller $installer ) {
1678 $status = Status::newGood();
1679 try {
1680 $page = WikiPage::factory( Title::newMainPage() );
1681 $content = new WikitextContent(
1682 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1683 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1686 $page->doEditContent( $content,
1688 EDIT_NEW,
1689 false,
1690 User::newFromName( 'MediaWiki default' )
1692 } catch ( MWException $e ) {
1693 //using raw, because $wgShowExceptionDetails can not be set yet
1694 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1697 return $status;
1701 * Override the necessary bits of the config to run an installation.
1703 public static function overrideConfig() {
1704 define( 'MW_NO_SESSION', 1 );
1706 // Don't access the database
1707 $GLOBALS['wgUseDatabaseMessages'] = false;
1708 // Don't cache langconv tables
1709 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE;
1710 // Debug-friendly
1711 $GLOBALS['wgShowExceptionDetails'] = true;
1712 // Don't break forms
1713 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1715 // Extended debugging
1716 $GLOBALS['wgShowSQLErrors'] = true;
1717 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1719 // Allow multiple ob_flush() calls
1720 $GLOBALS['wgDisableOutputCompression'] = true;
1722 // Use a sensible cookie prefix (not my_wiki)
1723 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1725 // Some of the environment checks make shell requests, remove limits
1726 $GLOBALS['wgMaxShellMemory'] = 0;
1728 // Don't bother embedding images into generated CSS, which is not cached
1729 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1730 return $less->toBool( false );
1735 * Add an installation step following the given step.
1737 * @param array $callback A valid installation callback array, in this form:
1738 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1739 * @param string $findStep The step to find. Omit to put the step at the beginning
1741 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1742 $this->extraInstallSteps[$findStep][] = $callback;
1746 * Disable the time limit for execution.
1747 * Some long-running pages (Install, Upgrade) will want to do this
1749 protected function disableTimeLimit() {
1750 wfSuppressWarnings();
1751 set_time_limit( 0 );
1752 wfRestoreWarnings();