3 * Base code for MediaWiki installer.
10 * This documentation group collects source code files with deployment functionality.
12 * @defgroup Deployment Deployment
16 * Base installer class.
18 * This class provides the base for installation and update functionality
19 * for both MediaWiki core and extensions.
24 abstract class Installer
{
27 * TODO: make protected?
34 * Cached DB installer instances, access using getDBInstaller().
38 protected $dbInstallers = array();
41 * Minimum memory size in MB.
45 protected $minMemorySize = 50;
48 * Cached Title, used by parse().
52 protected $parserTitle;
55 * Cached ParserOptions, used by parse().
59 protected $parserOptions;
62 * Known database types. These correspond to the class names <type>Installer,
63 * and are also MediaWiki database types valid for $wgDBtype.
65 * To add a new type, create a <type>Installer class and a Database<type>
66 * class, and add a config-type-<type> message to MessagesEn.php.
70 protected static $dbTypes = array(
77 * A list of environment check methods called by doEnvironmentChecks().
78 * These may output warnings using showMessage(), and/or abort the
79 * installation process by returning false.
83 protected $envChecks = array(
86 'envCheckRegisterGlobals',
87 'envCheckMagicQuotes',
88 'envCheckMagicSybase',
99 'envCheckWriteableDir',
101 'envCheckShellLocale',
102 'envCheckUploadsDirectory',
107 * UI interface for displaying a short message
108 * The parameters are like parameters to wfMsg().
109 * The messages will be in wikitext format, which will be converted to an
110 * output format such as HTML or text before being sent to the user.
112 public abstract function showMessage( $msg /*, ... */ );
115 * Constructor, always call this from child classes.
117 public function __construct() {
118 // Disable the i18n cache and LoadBalancer
119 Language
::getLocalisationCache()->disableBackend();
120 LBFactory
::disableBackend();
124 * Get a list of known DB types.
126 public static function getDBTypes() {
127 return self
::$dbTypes;
131 * Do initial checks of the PHP environment. Set variables according to
132 * the observed environment.
134 * It's possible that this may be called under the CLI SAPI, not the SAPI
135 * that the wiki will primarily run under. In that case, the subclass should
136 * initialise variables such as wgScriptPath, before calling this function.
138 * Under the web subclass, it can already be assumed that PHP 5+ is in use
139 * and that sessions are working.
143 public function doEnvironmentChecks() {
144 $this->showMessage( 'config-env-php', phpversion() );
148 foreach ( $this->envChecks
as $check ) {
149 $status = $this->$check();
150 if ( $status === false ) {
155 $this->setVar( '_Environment', $good );
158 $this->showMessage( 'config-env-good' );
160 $this->showMessage( 'config-env-bad' );
167 * Set a MW configuration variable, or internal installer configuration variable.
169 * @param $name String
170 * @param $value Mixed
172 public function setVar( $name, $value ) {
173 $this->settings
[$name] = $value;
177 * Get an MW configuration variable, or internal installer configuration variable.
178 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
179 * Installer variables are typically prefixed by an underscore.
181 * @param $name String
182 * @param $default Mixed
186 public function getVar( $name, $default = null ) {
187 if ( !isset( $this->settings
[$name] ) ) {
190 return $this->settings
[$name];
195 * Get an instance of DatabaseInstaller for the specified DB type.
197 * @param $type Mixed: DB installer for which is needed, false to use default.
199 * @return DatabaseInstaller
201 public function getDBInstaller( $type = false ) {
203 $type = $this->getVar( 'wgDBtype' );
206 $type = strtolower( $type );
208 if ( !isset( $this->dbInstallers
[$type] ) ) {
209 $class = ucfirst( $type ). 'Installer';
210 $this->dbInstallers
[$type] = new $class( $this );
213 return $this->dbInstallers
[$type];
217 * Determine if LocalSettings exists. If it does, return an appropriate
218 * status for whether we should can upgrade or not.
222 public function getLocalSettingsStatus() {
225 $status = Status
::newGood();
227 wfSuppressWarnings();
228 $ls = file_exists( "$IP/LocalSettings.php" );
232 if( $this->getDBInstaller()->needsUpgrade() ) {
233 $status->warning( 'config-localsettings-upgrade' );
236 $status->fatal( 'config-localsettings-noupgrade' );
244 * Get a fake password for sending back to the user in HTML.
245 * This is a security mechanism to avoid compromise of the password in the
246 * event of session ID compromise.
248 * @param $realPassword String
252 public function getFakePassword( $realPassword ) {
253 return str_repeat( '*', strlen( $realPassword ) );
257 * Set a variable which stores a password, except if the new value is a
258 * fake password in which case leave it as it is.
260 * @param $name String
261 * @param $value Mixed
263 public function setPassword( $name, $value ) {
264 if ( !preg_match( '/^\*+$/', $value ) ) {
265 $this->setVar( $name, $value );
270 * On POSIX systems return the primary group of the webserver we're running under.
271 * On other systems just returns null.
273 * This is used to advice the user that he should chgrp his config/data/images directory as the
274 * webserver user before he can install.
276 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
280 public static function maybeGetWebserverPrimaryGroup() {
281 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
282 # I don't know this, this isn't UNIX.
286 # posix_getegid() *not* getmygid() because we want the group of the webserver,
287 # not whoever owns the current script.
288 $gid = posix_getegid();
289 $getpwuid = posix_getpwuid( $gid );
290 $group = $getpwuid['name'];
296 * Convert wikitext $text to HTML.
298 * This is potentially error prone since many parser features require a complete
299 * installed MW database. The solution is to just not use those features when you
300 * write your messages. This appears to work well enough. Basic formatting and
301 * external links work just fine.
303 * But in case a translator decides to throw in a #ifexist or internal link or
304 * whatever, this function is guarded to catch attempted DB access and to present
305 * some fallback text.
307 * @param $text String
308 * @param $lineStart Boolean
311 public function parse( $text, $lineStart = false ) {
315 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
316 $html = $out->getText();
317 } catch ( DBAccessError
$e ) {
318 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
320 if ( !empty( $this->debug
) ) {
321 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
331 * @param $installer DatabaseInstaller
335 public function installDatabase( DatabaseInstaller
&$installer ) {
337 $type = $this->getVar( 'wgDBtype' );
338 $status = Status
::newFatal( "config-no-db", $type );
340 $status = $installer->setupDatabase();
349 * @param $installer DatabaseInstaller
353 public function installTables( DatabaseInstaller
&$installer ) {
354 $status = $installer->createTables();
356 if( $status->isOK() ) {
357 LBFactory
::enableBackend();
366 * @param $installer DatabaseInstaller
370 public function installInterwiki( DatabaseInstaller
&$installer ) {
371 return $installer->populateInterwikiTable();
375 * Exports all wg* variables stored by the installer into global scope.
377 public function exportVars() {
378 foreach ( $this->settings
as $name => $value ) {
379 if ( substr( $name, 0, 2 ) == 'wg' ) {
380 $GLOBALS[$name] = $value;
386 * Check if we're installing the latest version.
388 public function envLatestVersion() {
391 $repository = wfGetRepository();
392 $currentVersion = $repository->getLatestCoreVersion();
394 $this->setVar( '_ExternalHTTP', true );
396 if ( $currentVersion === false ) {
397 # For when the request is successful but there's e.g. some silly man in
398 # the middle firewall blocking us, e.g. one of those annoying airport ones
399 $this->showMessage( 'config-env-latest-can-not-check', $repository->getLocation() );
403 if( version_compare( $wgVersion, $currentVersion, '<' ) ) {
404 $this->showMessage( 'config-env-latest-old' );
405 // FIXME: this only works for the web installer!
406 $this->showHelpBox( 'config-env-latest-help', $wgVersion, $currentVersion );
407 } elseif( version_compare( $wgVersion, $currentVersion, '>' ) ) {
408 $this->showMessage( 'config-env-latest-new' );
411 $this->showMessage( 'config-env-latest-ok' );
415 * Environment check for DB types.
417 public function envCheckDB() {
420 $compiledDBs = array();
421 $goodNames = array();
424 foreach ( self
::getDBTypes() as $name ) {
425 $db = $this->getDBInstaller( $name );
426 $readableName = wfMsg( 'config-type-' . $name );
428 if ( $db->isCompiled() ) {
429 $compiledDBs[] = $name;
430 $goodNames[] = $readableName;
433 $allNames[] = $readableName;
436 $this->setVar( '_CompiledDBs', $compiledDBs );
438 if ( !$compiledDBs ) {
439 $this->showMessage( 'config-no-db' );
440 // FIXME: this only works for the web installer!
441 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
445 $this->showMessage( 'config-have-db', $wgLang->listToText( $goodNames ), count( $goodNames ) );
449 * Environment check for register_globals.
451 public function envCheckRegisterGlobals() {
452 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
453 $this->showMessage( 'config-register-globals' );
458 * Environment check for magic_quotes_runtime.
460 public function envCheckMagicQuotes() {
461 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
462 $this->showMessage( 'config-magic-quotes-runtime' );
468 * Environment check for magic_quotes_sybase.
470 public function envCheckMagicSybase() {
471 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
472 $this->showMessage( 'config-magic-quotes-sybase' );
478 * Environment check for mbstring.func_overload.
480 public function envCheckMbstring() {
481 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
482 $this->showMessage( 'config-mbstring' );
488 * Environment check for zend.ze1_compatibility_mode.
490 public function envCheckZE1() {
491 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
492 $this->showMessage( 'config-ze1' );
498 * Environment check for safe_mode.
500 public function envCheckSafeMode() {
501 if ( wfIniGetBool( 'safe_mode' ) ) {
502 $this->setVar( '_SafeMode', true );
503 $this->showMessage( 'config-safe-mode' );
508 * Environment check for the XML module.
510 public function envCheckXML() {
511 if ( !function_exists( "utf8_encode" ) ) {
512 $this->showMessage( 'config-xml-bad' );
515 $this->showMessage( 'config-xml-good' );
519 * Environment check for the PCRE module.
521 public function envCheckPCRE() {
522 if ( !function_exists( 'preg_match' ) ) {
523 $this->showMessage( 'config-pcre' );
529 * Environment check for available memory.
531 public function envCheckMemory() {
532 $limit = ini_get( 'memory_limit' );
534 if ( !$limit ||
$limit == -1 ) {
535 $this->showMessage( 'config-memory-none' );
539 $n = intval( $limit );
541 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $limit ), $m ) ) {
542 $n = intval( $m[1] * ( 1024 * 1024 ) );
545 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
546 $newLimit = "{$this->minMemorySize}M";
548 if( ini_set( "memory_limit", $newLimit ) === false ) {
549 $this->showMessage( 'config-memory-bad', $limit );
551 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
552 $this->setVar( '_RaiseMemory', true );
555 $this->showMessage( 'config-memory-ok', $limit );
560 * Environment check for compiled object cache types.
562 public function envCheckCache() {
565 foreach ( $this->objectCaches
as $name => $function ) {
566 if ( function_exists( $function ) ) {
567 $caches[$name] = true;
568 $this->showMessage( 'config-' . $name );
573 $this->showMessage( 'config-no-cache' );
576 $this->setVar( '_Caches', $caches );
580 * Search for GNU diff3.
582 public function envCheckDiff3() {
583 $paths = array_merge(
591 explode( PATH_SEPARATOR
, getenv( "PATH" ) )
594 $names = array( "gdiff3", "diff3", "diff3.exe" );
595 $versionInfo = array( '$1 --version 2>&1', 'diff3 (GNU diffutils)' );
599 foreach ( $paths as $path ) {
600 $exe = $this->locateExecutable( $path, $names, $versionInfo );
602 if ($exe !== false) {
603 $this->setVar( 'wgDiff3', $exe );
610 $this->showMessage( 'config-diff3-good', $exe );
612 $this->setVar( 'wgDiff3', false );
613 $this->showMessage( 'config-diff3-bad' );
618 * Environment check for ImageMagick and GD.
620 public function envCheckGraphics() {
621 $imcheck = array( "/usr/bin", "/opt/csw/bin", "/usr/local/bin", "/sw/bin", "/opt/local/bin" );
623 foreach( $imcheck as $dir ) {
624 $im = "$dir/convert";
626 wfSuppressWarnings();
627 $file_exists = file_exists( $im );
631 $this->showMessage( 'config-imagemagick', $im );
632 $this->setVar( 'wgImageMagickConvertCommand', $im );
637 if ( function_exists( 'imagejpeg' ) ) {
638 $this->showMessage( 'config-gd' );
642 $this->showMessage( 'no-scaling' );
646 * Environment check for setting $IP and $wgScriptPath.
648 public function envCheckPath() {
650 $IP = dirname( dirname( dirname( __FILE__
) ) );
652 $this->setVar( 'IP', $IP );
653 $this->showMessage( 'config-dir', $IP );
655 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
656 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
657 // to get the path to the current script... hopefully it's reliable. SIGH
658 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
659 $path = $_SERVER['PHP_SELF'];
660 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
661 $path = $_SERVER['SCRIPT_NAME'];
662 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
663 // Some kind soul has set it for us already (e.g. debconf)
666 $this->showMessage( 'config-no-uri' );
670 $uri = preg_replace( '{^(.*)/config.*$}', '$1', $path );
671 $this->setVar( 'wgScriptPath', $uri );
672 $this->showMessage( 'config-uri', $uri );
676 * Environment check for writable config/ directory.
678 public function envCheckWriteableDir() {
679 $ipDir = $this->getVar( 'IP' );
680 $configDir = $ipDir . '/config';
682 if( !is_writeable( $configDir ) ) {
683 $webserverGroup = self
::maybeGetWebserverPrimaryGroup();
685 if ( $webserverGroup !== null ) {
686 $this->showMessage( 'config-dir-not-writable-group', $ipDir, $webserverGroup );
688 $this->showMessage( 'config-dir-not-writable-nogroup', $ipDir, $webserverGroup );
696 * Environment check for setting the preferred PHP file extension.
698 public function envCheckExtension() {
699 // FIXME: detect this properly
700 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
706 $this->setVar( 'wgScriptExtension', ".$ext" );
707 $this->showMessage( 'config-file-extension', $ext );
713 public function envCheckShellLocale() {
714 # Give up now if we're in safe mode or open_basedir.
715 # It's theoretically possible but tricky to work with.
716 if ( wfIniGetBool( "safe_mode" ) ||
ini_get( 'open_basedir' ) ||
!function_exists( 'exec' ) ) {
720 $os = php_uname( 's' );
721 $supported = array( 'Linux', 'SunOS', 'HP-UX' ); # Tested these
723 if ( !in_array( $os, $supported ) ) {
727 # Get a list of available locales.
728 $lines = $ret = false;
729 exec( '/usr/bin/locale -a', $lines, $ret );
735 $lines = wfArrayMap( 'trim', $lines );
736 $candidatesByLocale = array();
737 $candidatesByLang = array();
739 foreach ( $lines as $line ) {
740 if ( $line === '' ) {
744 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
748 list( $all, $lang, $territory, $charset, $modifier ) = $m;
750 $candidatesByLocale[$m[0]] = $m;
751 $candidatesByLang[$lang][] = $m;
754 # Try the current value of LANG.
755 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
756 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
757 $this->showMessage( 'config-shell-locale', getenv( 'LANG' ) );
761 # Try the most common ones.
762 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
763 foreach ( $commonLocales as $commonLocale ) {
764 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
765 $this->setVar( 'wgShellLocale', $commonLocale );
766 $this->showMessage( 'config-shell-locale', $commonLocale );
771 # Is there an available locale in the Wiki's language?
772 $wikiLang = $this->getVar( 'wgLanguageCode' );
774 if ( isset( $candidatesByLang[$wikiLang] ) ) {
775 $m = reset( $candidatesByLang[$wikiLang] );
776 $this->setVar( 'wgShellLocale', $m[0] );
777 $this->showMessage( 'config-shell-locale', $m[0] );
781 # Are there any at all?
782 if ( count( $candidatesByLocale ) ) {
783 $m = reset( $candidatesByLocale );
784 $this->setVar( 'wgShellLocale', $m[0] );
785 $this->showMessage( 'config-shell-locale', $m[0] );
796 public function envCheckUploadsDirectory() {
797 global $IP, $wgServer;
799 $dir = $IP . '/images/';
800 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
801 $safe = !$this->dirIsExecutable( $dir, $url );
804 $this->showMessage( 'config-uploads-safe' );
806 $this->showMessage( 'config-uploads-not-safe', $dir );
811 * Convert a hex string representing a Unicode code point to that code point.
815 protected function unicodeChar( $c ) {
819 } else if ($c <= 0x7FF) {
820 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
821 } else if ($c <= 0xFFFF) {
822 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
823 . chr(0x80 |
$c & 0x3F);
824 } else if ($c <= 0x10FFFF) {
825 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
826 . chr(0x80 |
$c >> 6 & 0x3F)
827 . chr(0x80 |
$c & 0x3F);
835 * Check the libicu version
837 public function envCheckLibicu() {
838 $utf8 = function_exists( 'utf8_normalize' );
839 $intl = function_exists( 'normalizer_normalize' );
842 * This needs to be updated something that the latest libicu
843 * will properly normalize. This normalization was found at
844 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
845 * Note that we use the hex representation to create the code
846 * points in order to avoid any Unicode-destroying during transit.
848 $not_normal_c = $this->unicodeChar("FA6C");
849 $normal_c = $this->unicodeChar("242EE");
851 $useNormalizer = 'php';
852 $needsUpdate = false;
855 * We're going to prefer the pecl extension here unless
856 * utf8_normalize is more up to date.
859 $useNormalizer = 'utf8';
860 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
861 if ( $utf8 !== $normal_c ) $needsUpdate = true;
864 $useNormalizer = 'intl';
865 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
866 if ( $intl !== $normal_c ) $needsUpdate = true;
869 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
870 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
871 if( $useNormalizer === 'php' ) {
872 $this->showMessage( 'config-unicode-pure-php-warning' );
873 } elseif( $needsUpdate ) {
874 $this->showMessage( 'config-unicode-update-warning' );
880 * Search a path for any of the given executable names. Returns the
881 * executable name if found. Also checks the version string returned
882 * by each executable.
884 * Used only by environment checks.
886 * @param $path String: path to search
887 * @param $names Array of executable names
888 * @param $versionInfo Boolean false or array with two members:
889 * 0 => Command to run for version check, with $1 for the path
890 * 1 => String to compare the output with
892 * If $versionInfo is not false, only executables with a version
893 * matching $versionInfo[1] will be returned.
895 protected function locateExecutable( $path, $names, $versionInfo = false ) {
896 if ( !is_array( $names ) ) {
897 $names = array( $names );
900 foreach ( $names as $name ) {
901 $command = "$path/$name";
903 wfSuppressWarnings();
904 $file_exists = file_exists( $command );
907 if ( $file_exists ) {
908 if ( !$versionInfo ) {
912 $file = str_replace( '$1', $command, $versionInfo[0] );
914 # Should maybe be wfShellExec( $file), but runs into a ulimit, see
915 # http://www.mediawiki.org/w/index.php?title=New-installer_issues&diff=prev&oldid=335456
916 if ( strstr( `
$file`
, $versionInfo[1]) !== false ) {
926 * Checks if scripts located in the given directory can be executed via the given URL.
928 * Used only by environment checks.
930 public function dirIsExecutable( $dir, $url ) {
931 $scriptTypes = array(
933 "<?php echo 'ex' . 'ec';",
934 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
938 // it would be good to check other popular languages here, but it'll be slow.
940 wfSuppressWarnings();
942 foreach ( $scriptTypes as $ext => $contents ) {
943 foreach ( $contents as $source ) {
944 $file = 'exectest.' . $ext;
946 if ( !file_put_contents( $dir . $file, $source ) ) {
950 $text = Http
::get( $url . $file );
951 unlink( $dir . $file );
953 if ( $text == 'exec' ) {