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
25 * This documentation group collects source code files with deployment functionality.
27 * @defgroup Deployment Deployment
31 * Base installer class.
33 * This class provides the base for installation and update functionality
34 * for both MediaWiki core and extensions.
39 abstract class Installer
{
41 // This is the absolute minimum PHP version we can support
42 const MINIMUM_PHP_VERSION
= '5.3.2';
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';
58 * List of detected DBs, access using getCompiledDBs().
62 protected $compiledDBs;
65 * Cached DB installer instances, access using getDBInstaller().
69 protected $dbInstallers = array();
72 * Minimum memory size in MB.
76 protected $minMemorySize = 50;
79 * Cached Title, used by parse().
83 protected $parserTitle;
86 * Cached ParserOptions, used by parse().
90 protected $parserOptions;
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.
101 protected static $dbTypes = array(
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.
116 protected $envChecks = array(
118 'envCheckRegisterGlobals',
120 'envCheckMagicQuotes',
121 'envCheckMagicSybase',
128 'envCheckModSecurity',
135 'envCheckShellLocale',
136 'envCheckUploadsDirectory',
138 'envCheckSuhosinMaxValueLength',
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.
150 protected $defaultVarNames = array(
162 'wgEmailAuthentication',
165 'wgImageMagickConvertCommand',
171 'wgDeletedDirectory',
175 'wgUseInstantCommons',
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.
188 protected $internalDefaults = array(
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' => '',
204 '_Subscribe' => false,
205 '_SkipOptional' => 'continue',
206 '_RightsProfile' => 'wiki',
207 '_LicenseCode' => 'none',
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()
224 private $installSteps = array();
227 * Extra steps for installation, for things like DatabaseInstallers to modify
231 protected $extraInstallSteps = array();
234 * Known object cache types and the functions used to test for their existence.
238 protected $objectCaches = array(
239 'xcache' => 'xcache_get',
240 'apc' => 'apc_fetch',
241 'wincache' => 'wincache_ucache_get'
245 * User rights profiles.
249 public $rightsProfiles = array(
252 '*' => array( 'edit' => false )
256 'createaccount' => false,
262 'createaccount' => false,
274 public $licenses = array(
276 'url' => 'http://creativecommons.org/licenses/by/3.0/',
277 'icon' => '{$wgStylePath}/common/images/cc-by.png',
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',
288 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
289 'icon' => '{$wgStylePath}/common/images/cc-0.png',
293 'icon' => '{$wgStylePath}/common/images/public-domain.png',
296 'url' => 'http://www.gnu.org/copyleft/fdl.html',
297 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
304 'cc-choose' => array(
305 // Details will be filled in by the selector.
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.
334 abstract public function showMessage( $msg /*, ... */ );
337 * Same as showMessage(), but for displaying errors
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
355 Language
::getLocalisationCache()->disableBackend();
356 // Disable LoadBalancer and wfGetDB etc.
357 LBFactory
::disableBackend();
359 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
360 // SqlBagOStuff will then throw since we just disabled wfGetDB)
361 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
362 ObjectCache
::clear();
363 $emptyCache = array( 'class' => 'EmptyBagOStuff' );
364 $GLOBALS['wgObjectCaches'] = array(
365 CACHE_NONE
=> $emptyCache,
366 CACHE_DB
=> $emptyCache,
367 CACHE_ANYTHING
=> $emptyCache,
368 CACHE_MEMCACHED
=> $emptyCache,
371 // Load the installer's i18n.
372 $wgMessagesDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
374 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
375 $wgUser = User
::newFromId( 0 );
377 $this->settings
= $this->internalDefaults
;
379 foreach ( $this->defaultVarNames
as $var ) {
380 $this->settings
[$var] = $GLOBALS[$var];
383 $compiledDBs = array();
384 foreach ( self
::getDBTypes() as $type ) {
385 $installer = $this->getDBInstaller( $type );
387 if ( !$installer->isCompiled() ) {
390 $compiledDBs[] = $type;
392 $defaults = $installer->getGlobalDefaults();
394 foreach ( $installer->getGlobalNames() as $var ) {
395 if ( isset( $defaults[$var] ) ) {
396 $this->settings
[$var] = $defaults[$var];
398 $this->settings
[$var] = $GLOBALS[$var];
402 $this->compiledDBs
= $compiledDBs;
404 $this->parserTitle
= Title
::newFromText( 'Installer' );
405 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
406 $this->parserOptions
->setEditSection( false );
410 * Get a list of known DB types.
414 public static function getDBTypes() {
415 return self
::$dbTypes;
419 * Do initial checks of the PHP environment. Set variables according to
420 * the observed environment.
422 * It's possible that this may be called under the CLI SAPI, not the SAPI
423 * that the wiki will primarily run under. In that case, the subclass should
424 * initialise variables such as wgScriptPath, before calling this function.
426 * Under the web subclass, it can already be assumed that PHP 5+ is in use
427 * and that sessions are working.
431 public function doEnvironmentChecks() {
432 $phpVersion = phpversion();
433 if ( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
434 $this->showMessage( 'config-env-php', $phpVersion );
437 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
441 // Must go here because an old version of PCRE can prevent other checks from completing
443 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
444 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
445 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
451 foreach ( $this->envChecks
as $check ) {
452 $status = $this->$check();
453 if ( $status === false ) {
459 $this->setVar( '_Environment', $good );
461 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
465 * Set a MW configuration variable, or internal installer configuration variable.
467 * @param string $name
468 * @param mixed $value
470 public function setVar( $name, $value ) {
471 $this->settings
[$name] = $value;
475 * Get an MW configuration variable, or internal installer configuration variable.
476 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
477 * Installer variables are typically prefixed by an underscore.
479 * @param string $name
480 * @param mixed $default
484 public function getVar( $name, $default = null ) {
485 if ( !isset( $this->settings
[$name] ) ) {
488 return $this->settings
[$name];
493 * Get a list of DBs supported by current PHP setup
497 public function getCompiledDBs() {
498 return $this->compiledDBs
;
502 * Get an instance of DatabaseInstaller for the specified DB type.
504 * @param mixed $type DB installer for which is needed, false to use default.
506 * @return DatabaseInstaller
508 public function getDBInstaller( $type = false ) {
510 $type = $this->getVar( 'wgDBtype' );
513 $type = strtolower( $type );
515 if ( !isset( $this->dbInstallers
[$type] ) ) {
516 $class = ucfirst( $type ) . 'Installer';
517 $this->dbInstallers
[$type] = new $class( $this );
520 return $this->dbInstallers
[$type];
524 * Determine if LocalSettings.php exists. If it does, return its variables.
528 public static function getExistingLocalSettings() {
531 wfSuppressWarnings();
532 $_lsExists = file_exists( "$IP/LocalSettings.php" );
540 require "$IP/includes/DefaultSettings.php";
541 require "$IP/LocalSettings.php";
543 return get_defined_vars();
547 * Get a fake password for sending back to the user in HTML.
548 * This is a security mechanism to avoid compromise of the password in the
549 * event of session ID compromise.
551 * @param string $realPassword
555 public function getFakePassword( $realPassword ) {
556 return str_repeat( '*', strlen( $realPassword ) );
560 * Set a variable which stores a password, except if the new value is a
561 * fake password in which case leave it as it is.
563 * @param string $name
564 * @param mixed $value
566 public function setPassword( $name, $value ) {
567 if ( !preg_match( '/^\*+$/', $value ) ) {
568 $this->setVar( $name, $value );
573 * On POSIX systems return the primary group of the webserver we're running under.
574 * On other systems just returns null.
576 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
577 * webserver user before he can install.
579 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
583 public static function maybeGetWebserverPrimaryGroup() {
584 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
585 # I don't know this, this isn't UNIX.
589 # posix_getegid() *not* getmygid() because we want the group of the webserver,
590 # not whoever owns the current script.
591 $gid = posix_getegid();
592 $getpwuid = posix_getpwuid( $gid );
593 $group = $getpwuid['name'];
599 * Convert wikitext $text to HTML.
601 * This is potentially error prone since many parser features require a complete
602 * installed MW database. The solution is to just not use those features when you
603 * write your messages. This appears to work well enough. Basic formatting and
604 * external links work just fine.
606 * But in case a translator decides to throw in a "#ifexist" or internal link or
607 * whatever, this function is guarded to catch the attempted DB access and to present
608 * some fallback text.
610 * @param string $text
611 * @param bool $lineStart
614 public function parse( $text, $lineStart = false ) {
618 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
619 $html = $out->getText();
620 } catch ( DBAccessError
$e ) {
621 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
623 if ( !empty( $this->debug
) ) {
624 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
632 * @return ParserOptions
634 public function getParserOptions() {
635 return $this->parserOptions
;
638 public function disableLinkPopups() {
639 $this->parserOptions
->setExternalLinkTarget( false );
642 public function restoreLinkPopups() {
643 global $wgExternalLinkTarget;
644 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
648 * Install step which adds a row to the site_stats table with appropriate
651 * @param DatabaseInstaller $installer
655 public function populateSiteStats( DatabaseInstaller
$installer ) {
656 $status = $installer->getConnection();
657 if ( !$status->isOK() ) {
660 $status->value
->insert(
664 'ss_total_views' => 0,
665 'ss_total_edits' => 0,
666 'ss_good_articles' => 0,
667 'ss_total_pages' => 0,
674 return Status
::newGood();
678 * Exports all wg* variables stored by the installer into global scope.
680 public function exportVars() {
681 foreach ( $this->settings
as $name => $value ) {
682 if ( substr( $name, 0, 2 ) == 'wg' ) {
683 $GLOBALS[$name] = $value;
689 * Environment check for DB types.
692 protected function envCheckDB() {
697 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
698 // config-type-sqlite
699 foreach ( self
::getDBTypes() as $name ) {
700 $allNames[] = wfMessage( "config-type-$name" )->text();
703 $databases = $this->getCompiledDBs();
705 $databases = array_flip( $databases );
706 foreach ( array_keys( $databases ) as $db ) {
707 $installer = $this->getDBInstaller( $db );
708 $status = $installer->checkPrerequisites();
709 if ( !$status->isGood() ) {
710 $this->showStatusMessage( $status );
712 if ( !$status->isOK() ) {
713 unset( $databases[$db] );
716 $databases = array_flip( $databases );
718 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
720 // @todo FIXME: This only works for the web installer!
728 * Environment check for register_globals.
730 protected function envCheckRegisterGlobals() {
731 if ( wfIniGetBool( 'register_globals' ) ) {
732 $this->showMessage( 'config-register-globals' );
737 * Some versions of libxml+PHP break < and > encoding horribly
740 protected function envCheckBrokenXML() {
741 $test = new PhpXmlBugTester();
743 $this->showError( 'config-brokenlibxml' );
752 * Environment check for magic_quotes_runtime.
755 protected function envCheckMagicQuotes() {
756 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
757 $this->showError( 'config-magic-quotes-runtime' );
766 * Environment check for magic_quotes_sybase.
769 protected function envCheckMagicSybase() {
770 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
771 $this->showError( 'config-magic-quotes-sybase' );
780 * Environment check for mbstring.func_overload.
783 protected function envCheckMbstring() {
784 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
785 $this->showError( 'config-mbstring' );
794 * Environment check for safe_mode.
797 protected function envCheckSafeMode() {
798 if ( wfIniGetBool( 'safe_mode' ) ) {
799 $this->setVar( '_SafeMode', true );
800 $this->showMessage( 'config-safe-mode' );
807 * Environment check for the XML module.
810 protected function envCheckXML() {
811 if ( !function_exists( "utf8_encode" ) ) {
812 $this->showError( 'config-xml-bad' );
821 * Environment check for the PCRE module.
823 * @note If this check were to fail, the parser would
824 * probably throw an exception before the result
825 * of this check is shown to the user.
828 protected function envCheckPCRE() {
829 wfSuppressWarnings();
830 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
831 // Need to check for \p support too, as PCRE can be compiled
832 // with utf8 support, but not unicode property support.
833 // check that \p{Zs} (space separators) matches
834 // U+3000 (Ideographic space)
835 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
837 if ( $regexd != '--' ||
$regexprop != '--' ) {
838 $this->showError( 'config-pcre-no-utf8' );
847 * Environment check for available memory.
850 protected function envCheckMemory() {
851 $limit = ini_get( 'memory_limit' );
853 if ( !$limit ||
$limit == -1 ) {
857 $n = wfShorthandToInteger( $limit );
859 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
860 $newLimit = "{$this->minMemorySize}M";
862 if ( ini_set( "memory_limit", $newLimit ) === false ) {
863 $this->showMessage( 'config-memory-bad', $limit );
865 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
866 $this->setVar( '_RaiseMemory', true );
874 * Environment check for compiled object cache types.
876 protected function envCheckCache() {
878 foreach ( $this->objectCaches
as $name => $function ) {
879 if ( function_exists( $function ) ) {
880 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
883 $caches[$name] = true;
888 $this->showMessage( 'config-no-cache' );
891 $this->setVar( '_Caches', $caches );
895 * Scare user to death if they have mod_security
898 protected function envCheckModSecurity() {
899 if ( self
::apacheModulePresent( 'mod_security' ) ) {
900 $this->showMessage( 'config-mod-security' );
907 * Search for GNU diff3.
910 protected function envCheckDiff3() {
911 $names = array( "gdiff3", "diff3", "diff3.exe" );
912 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
914 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
917 $this->setVar( 'wgDiff3', $diff3 );
919 $this->setVar( 'wgDiff3', false );
920 $this->showMessage( 'config-diff3-bad' );
927 * Environment check for ImageMagick and GD.
930 protected function envCheckGraphics() {
931 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
932 $versionInfo = array( '$1 -version', 'ImageMagick' );
933 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
935 $this->setVar( 'wgImageMagickConvertCommand', '' );
937 $this->setVar( 'wgImageMagickConvertCommand', $convert );
938 $this->showMessage( 'config-imagemagick', $convert );
941 } elseif ( function_exists( 'imagejpeg' ) ) {
942 $this->showMessage( 'config-gd' );
944 $this->showMessage( 'config-no-scaling' );
956 protected function envCheckGit() {
957 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
958 $versionInfo = array( '$1 --version', 'git version' );
960 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
963 $this->setVar( 'wgGitBin', $git );
964 $this->showMessage( 'config-git', $git );
966 $this->setVar( 'wgGitBin', false );
967 $this->showMessage( 'config-git-bad' );
974 * Environment check for the server hostname.
976 protected function envCheckServer() {
977 $server = $this->envGetDefaultServer();
978 if ( $server !== null ) {
979 $this->showMessage( 'config-using-server', $server );
980 $this->setVar( 'wgServer', $server );
987 * Helper function to be called from envCheckServer()
990 abstract protected function envGetDefaultServer();
993 * Environment check for setting $IP and $wgScriptPath.
996 protected function envCheckPath() {
998 $IP = dirname( dirname( __DIR__
) );
999 $this->setVar( 'IP', $IP );
1003 $this->getVar( 'wgServer' ),
1004 $this->getVar( 'wgScriptPath' )
1011 * Environment check for setting the preferred PHP file extension.
1014 protected function envCheckExtension() {
1015 // @todo FIXME: Detect this properly
1016 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1021 $this->setVar( 'wgScriptExtension', ".$ext" );
1027 * Environment check for preferred locale in shell
1030 protected function envCheckShellLocale() {
1031 $os = php_uname( 's' );
1032 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1034 if ( !in_array( $os, $supported ) ) {
1038 # Get a list of available locales.
1040 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1046 $lines = array_map( 'trim', explode( "\n", $lines ) );
1047 $candidatesByLocale = array();
1048 $candidatesByLang = array();
1050 foreach ( $lines as $line ) {
1051 if ( $line === '' ) {
1055 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1059 list( , $lang, , , ) = $m;
1061 $candidatesByLocale[$m[0]] = $m;
1062 $candidatesByLang[$lang][] = $m;
1065 # Try the current value of LANG.
1066 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1067 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1072 # Try the most common ones.
1073 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1074 foreach ( $commonLocales as $commonLocale ) {
1075 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1076 $this->setVar( 'wgShellLocale', $commonLocale );
1082 # Is there an available locale in the Wiki's language?
1083 $wikiLang = $this->getVar( 'wgLanguageCode' );
1085 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1086 $m = reset( $candidatesByLang[$wikiLang] );
1087 $this->setVar( 'wgShellLocale', $m[0] );
1092 # Are there any at all?
1093 if ( count( $candidatesByLocale ) ) {
1094 $m = reset( $candidatesByLocale );
1095 $this->setVar( 'wgShellLocale', $m[0] );
1105 * Environment check for the permissions of the uploads directory
1108 protected function envCheckUploadsDirectory() {
1111 $dir = $IP . '/images/';
1112 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1113 $safe = !$this->dirIsExecutable( $dir, $url );
1116 $this->showMessage( 'config-uploads-not-safe', $dir );
1123 * Checks if suhosin.get.max_value_length is set, and if so generate
1124 * a warning because it decreases ResourceLoader performance.
1127 protected function envCheckSuhosinMaxValueLength() {
1128 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1129 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1130 // Only warn if the value is below the sane 1024
1131 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1138 * Convert a hex string representing a Unicode code point to that code point.
1142 protected function unicodeChar( $c ) {
1146 } elseif ( $c <= 0x7FF ) {
1147 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1148 } elseif ( $c <= 0xFFFF ) {
1149 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1150 . chr( 0x80 |
$c & 0x3F );
1151 } elseif ( $c <= 0x10FFFF ) {
1152 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1153 . chr( 0x80 |
$c >> 6 & 0x3F )
1154 . chr( 0x80 |
$c & 0x3F );
1161 * Check the libicu version
1163 protected function envCheckLibicu() {
1164 $utf8 = function_exists( 'utf8_normalize' );
1165 $intl = function_exists( 'normalizer_normalize' );
1168 * This needs to be updated something that the latest libicu
1169 * will properly normalize. This normalization was found at
1170 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1171 * Note that we use the hex representation to create the code
1172 * points in order to avoid any Unicode-destroying during transit.
1174 $not_normal_c = $this->unicodeChar( "FA6C" );
1175 $normal_c = $this->unicodeChar( "242EE" );
1177 $useNormalizer = 'php';
1178 $needsUpdate = false;
1181 * We're going to prefer the pecl extension here unless
1182 * utf8_normalize is more up to date.
1185 $useNormalizer = 'utf8';
1186 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1187 if ( $utf8 !== $normal_c ) {
1188 $needsUpdate = true;
1192 $useNormalizer = 'intl';
1193 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1194 if ( $intl !== $normal_c ) {
1195 $needsUpdate = true;
1199 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1200 // 'config-unicode-using-intl'
1201 if ( $useNormalizer === 'php' ) {
1202 $this->showMessage( 'config-unicode-pure-php-warning' );
1204 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1205 if ( $needsUpdate ) {
1206 $this->showMessage( 'config-unicode-update-warning' );
1214 protected function envCheckCtype() {
1215 if ( !function_exists( 'ctype_digit' ) ) {
1216 $this->showError( 'config-ctype' );
1227 protected function envCheckJSON() {
1228 if ( !function_exists( 'json_decode' ) ) {
1229 $this->showError( 'config-json' );
1238 * Get an array of likely places we can find executables. Check a bunch
1239 * of known Unix-like defaults, as well as the PATH environment variable
1240 * (which should maybe make it work for Windows?)
1244 protected static function getPossibleBinPaths() {
1246 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1247 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1248 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1253 * Search a path for any of the given executable names. Returns the
1254 * executable name if found. Also checks the version string returned
1255 * by each executable.
1257 * Used only by environment checks.
1259 * @param string $path path to search
1260 * @param array $names of executable names
1261 * @param array|bool $versionInfo False or array with two members:
1262 * 0 => Command to run for version check, with $1 for the full executable name
1263 * 1 => String to compare the output with
1265 * If $versionInfo is not false, only executables with a version
1266 * matching $versionInfo[1] will be returned.
1267 * @return bool|string
1269 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1270 if ( !is_array( $names ) ) {
1271 $names = array( $names );
1274 foreach ( $names as $name ) {
1275 $command = $path . DIRECTORY_SEPARATOR
. $name;
1277 wfSuppressWarnings();
1278 $file_exists = file_exists( $command );
1279 wfRestoreWarnings();
1281 if ( $file_exists ) {
1282 if ( !$versionInfo ) {
1286 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1287 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1297 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1298 * @see locateExecutable()
1299 * @param array $names Array of possible names.
1300 * @param array|bool $versionInfo Default: false or array with two members:
1301 * 0 => Command to run for version check, with $1 for the full executable name
1302 * 1 => String to compare the output with
1304 * If $versionInfo is not false, only executables with a version
1305 * matching $versionInfo[1] will be returned.
1306 * @return bool|string
1308 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1309 foreach ( self
::getPossibleBinPaths() as $path ) {
1310 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1311 if ( $exe !== false ) {
1320 * Checks if scripts located in the given directory can be executed via the given URL.
1322 * Used only by environment checks.
1323 * @param string $dir
1324 * @param string $url
1325 * @return bool|int|string
1327 public function dirIsExecutable( $dir, $url ) {
1328 $scriptTypes = array(
1330 "<?php echo 'ex' . 'ec';",
1331 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1335 // it would be good to check other popular languages here, but it'll be slow.
1337 wfSuppressWarnings();
1339 foreach ( $scriptTypes as $ext => $contents ) {
1340 foreach ( $contents as $source ) {
1341 $file = 'exectest.' . $ext;
1343 if ( !file_put_contents( $dir . $file, $source ) ) {
1348 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1349 } catch ( MWException
$e ) {
1350 // Http::get throws with allow_url_fopen = false and no curl extension.
1353 unlink( $dir . $file );
1355 if ( $text == 'exec' ) {
1356 wfRestoreWarnings();
1363 wfRestoreWarnings();
1369 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1371 * @param string $moduleName Name of module to check.
1374 public static function apacheModulePresent( $moduleName ) {
1375 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1378 // try it the hard way
1380 phpinfo( INFO_MODULES
);
1381 $info = ob_get_clean();
1383 return strpos( $info, $moduleName ) !== false;
1387 * ParserOptions are constructed before we determined the language, so fix it
1389 * @param Language $lang
1391 public function setParserLanguage( $lang ) {
1392 $this->parserOptions
->setTargetLanguage( $lang );
1393 $this->parserOptions
->setUserLang( $lang );
1397 * Overridden by WebInstaller to provide lastPage parameters.
1398 * @param string $page
1401 protected function getDocUrl( $page ) {
1402 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1406 * Finds extensions that follow the format /extensions/Name/Name.php,
1407 * and returns an array containing the value for 'Name' for each found extension.
1411 public function findExtensions() {
1412 if ( $this->getVar( 'IP' ) === null ) {
1416 $extDir = $this->getVar( 'IP' ) . '/extensions';
1417 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1421 $dh = opendir( $extDir );
1423 while ( ( $file = readdir( $dh ) ) !== false ) {
1424 if ( !is_dir( "$extDir/$file" ) ) {
1427 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1432 natcasesort( $exts );
1438 * Installs the auto-detected extensions.
1442 protected function includeExtensions() {
1444 $exts = $this->getVar( '_Extensions' );
1445 $IP = $this->getVar( 'IP' );
1448 * We need to include DefaultSettings before including extensions to avoid
1449 * warnings about unset variables. However, the only thing we really
1450 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1451 * if the extension has hidden hook registration in $wgExtensionFunctions,
1452 * but we're not opening that can of worms
1453 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1455 global $wgAutoloadClasses;
1456 $wgAutoloadClasses = array();
1458 require "$IP/includes/DefaultSettings.php";
1460 foreach ( $exts as $e ) {
1461 require_once "$IP/extensions/$e/$e.php";
1464 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1465 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1467 // Unset everyone else's hooks. Lord knows what someone might be doing
1468 // in ParserFirstCallInit (see bug 27171)
1469 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1471 return Status
::newGood();
1475 * Get an array of install steps. Should always be in the format of
1477 * 'name' => 'someuniquename',
1478 * 'callback' => array( $obj, 'method' ),
1480 * There must be a config-install-$name message defined per step, which will
1481 * be shown on install.
1483 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1486 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1487 $coreInstallSteps = array(
1488 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1489 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1490 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1491 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1492 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1493 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1494 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1497 // Build the array of install steps starting from the core install list,
1498 // then adding any callbacks that wanted to attach after a given step
1499 foreach ( $coreInstallSteps as $step ) {
1500 $this->installSteps
[] = $step;
1501 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1502 $this->installSteps
= array_merge(
1503 $this->installSteps
,
1504 $this->extraInstallSteps
[$step['name']]
1509 // Prepend any steps that want to be at the beginning
1510 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1511 $this->installSteps
= array_merge(
1512 $this->extraInstallSteps
['BEGINNING'],
1517 // Extensions should always go first, chance to tie into hooks and such
1518 if ( count( $this->getVar( '_Extensions' ) ) ) {
1519 array_unshift( $this->installSteps
,
1520 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1522 $this->installSteps
[] = array(
1523 'name' => 'extension-tables',
1524 'callback' => array( $installer, 'createExtensionTables' )
1528 return $this->installSteps
;
1532 * Actually perform the installation.
1534 * @param array $startCB A callback array for the beginning of each step
1535 * @param array $endCB A callback array for the end of each step
1537 * @return array Array of Status objects
1539 public function performInstallation( $startCB, $endCB ) {
1540 $installResults = array();
1541 $installer = $this->getDBInstaller();
1542 $installer->preInstall();
1543 $steps = $this->getInstallSteps( $installer );
1544 foreach ( $steps as $stepObj ) {
1545 $name = $stepObj['name'];
1546 call_user_func_array( $startCB, array( $name ) );
1548 // Perform the callback step
1549 $status = call_user_func( $stepObj['callback'], $installer );
1551 // Output and save the results
1552 call_user_func( $endCB, $name, $status );
1553 $installResults[$name] = $status;
1555 // If we've hit some sort of fatal, we need to bail.
1556 // Callback already had a chance to do output above.
1557 if ( !$status->isOk() ) {
1561 if ( $status->isOk() ) {
1562 $this->setVar( '_InstallDone', true );
1565 return $installResults;
1569 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1573 public function generateKeys() {
1574 $keys = array( 'wgSecretKey' => 64 );
1575 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1576 $keys['wgUpgradeKey'] = 16;
1579 return $this->doGenerateKeys( $keys );
1583 * Generate a secret value for variables using our CryptRand generator.
1584 * Produce a warning if the random source was insecure.
1586 * @param array $keys
1589 protected function doGenerateKeys( $keys ) {
1590 $status = Status
::newGood();
1593 foreach ( $keys as $name => $length ) {
1594 $secretKey = MWCryptRand
::generateHex( $length, true );
1595 if ( !MWCryptRand
::wasStrong() ) {
1599 $this->setVar( $name, $secretKey );
1603 $names = array_keys( $keys );
1604 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1606 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1613 * Create the first user account, grant it sysop and bureaucrat rights
1617 protected function createSysop() {
1618 $name = $this->getVar( '_AdminName' );
1619 $user = User
::newFromName( $name );
1622 // We should've validated this earlier anyway!
1623 return Status
::newFatal( 'config-admin-error-user', $name );
1626 if ( $user->idForName() == 0 ) {
1627 $user->addToDatabase();
1630 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1631 } catch ( PasswordError
$pwe ) {
1632 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1635 $user->addGroup( 'sysop' );
1636 $user->addGroup( 'bureaucrat' );
1637 if ( $this->getVar( '_AdminEmail' ) ) {
1638 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1640 $user->saveSettings();
1642 // Update user count
1643 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1644 $ssUpdate->doUpdate();
1646 $status = Status
::newGood();
1648 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1649 $this->subscribeToMediaWikiAnnounce( $status );
1658 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1660 'email' => $this->getVar( '_AdminEmail' ),
1665 // Mailman doesn't support as many languages as we do, so check to make
1666 // sure their selected language is available
1667 $myLang = $this->getVar( '_UserLang' );
1668 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1669 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1670 $params['language'] = $myLang;
1673 if ( MWHttpRequest
::canMakeRequests() ) {
1674 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1675 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1676 if ( !$res->isOK() ) {
1677 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1680 $s->warning( 'config-install-subscribe-notpossible' );
1685 * Insert Main Page with default content.
1687 * @param DatabaseInstaller $installer
1690 protected function createMainpage( DatabaseInstaller
$installer ) {
1691 $status = Status
::newGood();
1693 $page = WikiPage
::factory( Title
::newMainPage() );
1694 $content = new WikitextContent(
1695 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1696 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1699 $page->doEditContent( $content,
1703 User
::newFromName( 'MediaWiki default' )
1705 } catch ( MWException
$e ) {
1706 //using raw, because $wgShowExceptionDetails can not be set yet
1707 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1714 * Override the necessary bits of the config to run an installation.
1716 public static function overrideConfig() {
1717 define( 'MW_NO_SESSION', 1 );
1719 // Don't access the database
1720 $GLOBALS['wgUseDatabaseMessages'] = false;
1721 // Don't cache langconv tables
1722 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1724 $GLOBALS['wgShowExceptionDetails'] = true;
1725 // Don't break forms
1726 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1728 // Extended debugging
1729 $GLOBALS['wgShowSQLErrors'] = true;
1730 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1732 // Allow multiple ob_flush() calls
1733 $GLOBALS['wgDisableOutputCompression'] = true;
1735 // Use a sensible cookie prefix (not my_wiki)
1736 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1738 // Some of the environment checks make shell requests, remove limits
1739 $GLOBALS['wgMaxShellMemory'] = 0;
1741 // Don't bother embedding images into generated CSS, which is not cached
1742 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1743 return $less->toBool( false );
1748 * Add an installation step following the given step.
1750 * @param array $callback A valid installation callback array, in this form:
1751 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1752 * @param string $findStep The step to find. Omit to put the step at the beginning
1754 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1755 $this->extraInstallSteps
[$findStep][] = $callback;
1759 * Disable the time limit for execution.
1760 * Some long-running pages (Install, Upgrade) will want to do this
1762 protected function disableTimeLimit() {
1763 wfSuppressWarnings();
1764 set_time_limit( 0 );
1765 wfRestoreWarnings();