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 * Get an array of likely places we can find executables. Check a bunch
387 * of known Unix-like defaults, as well as the PATH environment variable
388 * (which should maybe make it work for Windows?)
392 protected function getPossibleBinPaths() {
394 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
395 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
396 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
401 * Check if we're installing the latest version.
403 public function envLatestVersion() {
406 $repository = wfGetRepository();
407 $currentVersion = $repository->getLatestCoreVersion();
409 $this->setVar( '_ExternalHTTP', true );
411 if ( $currentVersion === false ) {
412 # For when the request is successful but there's e.g. some silly man in
413 # the middle firewall blocking us, e.g. one of those annoying airport ones
414 $this->showMessage( 'config-env-latest-can-not-check', $repository->getLocation() );
418 if( version_compare( $wgVersion, $currentVersion, '<' ) ) {
419 $this->showMessage( 'config-env-latest-old' );
420 // FIXME: this only works for the web installer!
421 $this->showHelpBox( 'config-env-latest-help', $wgVersion, $currentVersion );
422 } elseif( version_compare( $wgVersion, $currentVersion, '>' ) ) {
423 $this->showMessage( 'config-env-latest-new' );
426 $this->showMessage( 'config-env-latest-ok' );
430 * Environment check for DB types.
432 public function envCheckDB() {
435 $compiledDBs = array();
436 $goodNames = array();
439 foreach ( self
::getDBTypes() as $name ) {
440 $db = $this->getDBInstaller( $name );
441 $readableName = wfMsg( 'config-type-' . $name );
443 if ( $db->isCompiled() ) {
444 $compiledDBs[] = $name;
445 $goodNames[] = $readableName;
448 $allNames[] = $readableName;
451 $this->setVar( '_CompiledDBs', $compiledDBs );
453 if ( !$compiledDBs ) {
454 $this->showMessage( 'config-no-db' );
455 // FIXME: this only works for the web installer!
456 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
460 $this->showMessage( 'config-have-db', $wgLang->listToText( $goodNames ), count( $goodNames ) );
462 // Check for FTS3 full-text search module
463 $sqlite = $this->getDBInstaller( 'sqlite' );
464 if ( $sqlite->isCompiled() ) {
465 $db = new DatabaseSqliteStandalone( ':memory:' );
466 $this->showMessage( $db->getFulltextSearchModule() == 'FTS3'
474 * Environment check for register_globals.
476 public function envCheckRegisterGlobals() {
477 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
478 $this->showMessage( 'config-register-globals' );
483 * Environment check for magic_quotes_runtime.
485 public function envCheckMagicQuotes() {
486 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
487 $this->showMessage( 'config-magic-quotes-runtime' );
493 * Environment check for magic_quotes_sybase.
495 public function envCheckMagicSybase() {
496 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
497 $this->showMessage( 'config-magic-quotes-sybase' );
503 * Environment check for mbstring.func_overload.
505 public function envCheckMbstring() {
506 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
507 $this->showMessage( 'config-mbstring' );
513 * Environment check for zend.ze1_compatibility_mode.
515 public function envCheckZE1() {
516 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
517 $this->showMessage( 'config-ze1' );
523 * Environment check for safe_mode.
525 public function envCheckSafeMode() {
526 if ( wfIniGetBool( 'safe_mode' ) ) {
527 $this->setVar( '_SafeMode', true );
528 $this->showMessage( 'config-safe-mode' );
533 * Environment check for the XML module.
535 public function envCheckXML() {
536 if ( !function_exists( "utf8_encode" ) ) {
537 $this->showMessage( 'config-xml-bad' );
540 $this->showMessage( 'config-xml-good' );
544 * Environment check for the PCRE module.
546 public function envCheckPCRE() {
547 if ( !function_exists( 'preg_match' ) ) {
548 $this->showMessage( 'config-pcre' );
554 * Environment check for available memory.
556 public function envCheckMemory() {
557 $limit = ini_get( 'memory_limit' );
559 if ( !$limit ||
$limit == -1 ) {
560 $this->showMessage( 'config-memory-none' );
564 $n = intval( $limit );
566 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $limit ), $m ) ) {
567 $n = intval( $m[1] * ( 1024 * 1024 ) );
570 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
571 $newLimit = "{$this->minMemorySize}M";
573 if( ini_set( "memory_limit", $newLimit ) === false ) {
574 $this->showMessage( 'config-memory-bad', $limit );
576 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
577 $this->setVar( '_RaiseMemory', true );
580 $this->showMessage( 'config-memory-ok', $limit );
585 * Environment check for compiled object cache types.
587 public function envCheckCache() {
590 foreach ( $this->objectCaches
as $name => $function ) {
591 if ( function_exists( $function ) ) {
592 $caches[$name] = true;
593 $this->showMessage( 'config-' . $name );
598 $this->showMessage( 'config-no-cache' );
601 $this->setVar( '_Caches', $caches );
605 * Search for GNU diff3.
607 public function envCheckDiff3() {
608 $names = array( "gdiff3", "diff3", "diff3.exe" );
609 $versionInfo = array( '$1 --version 2>&1', 'diff3 (GNU diffutils)' );
613 foreach ( $this->getPossibleBinPaths() as $path ) {
614 $exe = $this->locateExecutable( $path, $names, $versionInfo );
616 if ($exe !== false) {
617 $this->setVar( 'wgDiff3', $exe );
624 $this->showMessage( 'config-diff3-good', $exe );
626 $this->setVar( 'wgDiff3', false );
627 $this->showMessage( 'config-diff3-bad' );
632 * Environment check for ImageMagick and GD.
634 public function envCheckGraphics() {
635 $names = array( 'convert', 'convert.exe' );
636 $haveConvert = false;
638 foreach ( $this->getPossibleBinPaths() as $path ) {
639 $exe = $this->locateExecutable( $path, $names );
641 if ($exe !== false) {
642 $this->setVar( 'wgImageMagickConvertCommand', $exe );
648 if ( $haveConvert ) {
649 $this->showMessage( 'config-imagemagick', $exe );
651 } elseif ( function_exists( 'imagejpeg' ) ) {
652 $this->showMessage( 'config-gd' );
655 $this->showMessage( 'no-scaling' );
660 * Environment check for setting $IP and $wgScriptPath.
662 public function envCheckPath() {
664 $IP = dirname( dirname( dirname( __FILE__
) ) );
666 $this->setVar( 'IP', $IP );
667 $this->showMessage( 'config-dir', $IP );
669 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
670 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
671 // to get the path to the current script... hopefully it's reliable. SIGH
672 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
673 $path = $_SERVER['PHP_SELF'];
674 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
675 $path = $_SERVER['SCRIPT_NAME'];
676 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
677 // Some kind soul has set it for us already (e.g. debconf)
680 $this->showMessage( 'config-no-uri' );
684 $uri = preg_replace( '{^(.*)/config.*$}', '$1', $path );
685 $this->setVar( 'wgScriptPath', $uri );
686 $this->showMessage( 'config-uri', $uri );
690 * Environment check for writable config/ directory.
692 public function envCheckWriteableDir() {
693 $ipDir = $this->getVar( 'IP' );
694 $configDir = $ipDir . '/config';
696 if( !is_writeable( $configDir ) ) {
697 $webserverGroup = self
::maybeGetWebserverPrimaryGroup();
699 if ( $webserverGroup !== null ) {
700 $this->showMessage( 'config-dir-not-writable-group', $ipDir, $webserverGroup );
702 $this->showMessage( 'config-dir-not-writable-nogroup', $ipDir, $webserverGroup );
710 * Environment check for setting the preferred PHP file extension.
712 public function envCheckExtension() {
713 // FIXME: detect this properly
714 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
720 $this->setVar( 'wgScriptExtension', ".$ext" );
721 $this->showMessage( 'config-file-extension', $ext );
727 public function envCheckShellLocale() {
728 # Give up now if we're in safe mode or open_basedir.
729 # It's theoretically possible but tricky to work with.
730 if ( wfIniGetBool( "safe_mode" ) ||
ini_get( 'open_basedir' ) ||
!function_exists( 'exec' ) ) {
734 $os = php_uname( 's' );
735 $supported = array( 'Linux', 'SunOS', 'HP-UX' ); # Tested these
737 if ( !in_array( $os, $supported ) ) {
741 # Get a list of available locales.
742 $lines = $ret = false;
743 exec( '/usr/bin/locale -a', $lines, $ret );
749 $lines = wfArrayMap( 'trim', $lines );
750 $candidatesByLocale = array();
751 $candidatesByLang = array();
753 foreach ( $lines as $line ) {
754 if ( $line === '' ) {
758 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
762 list( $all, $lang, $territory, $charset, $modifier ) = $m;
764 $candidatesByLocale[$m[0]] = $m;
765 $candidatesByLang[$lang][] = $m;
768 # Try the current value of LANG.
769 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
770 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
771 $this->showMessage( 'config-shell-locale', getenv( 'LANG' ) );
775 # Try the most common ones.
776 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
777 foreach ( $commonLocales as $commonLocale ) {
778 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
779 $this->setVar( 'wgShellLocale', $commonLocale );
780 $this->showMessage( 'config-shell-locale', $commonLocale );
785 # Is there an available locale in the Wiki's language?
786 $wikiLang = $this->getVar( 'wgLanguageCode' );
788 if ( isset( $candidatesByLang[$wikiLang] ) ) {
789 $m = reset( $candidatesByLang[$wikiLang] );
790 $this->setVar( 'wgShellLocale', $m[0] );
791 $this->showMessage( 'config-shell-locale', $m[0] );
795 # Are there any at all?
796 if ( count( $candidatesByLocale ) ) {
797 $m = reset( $candidatesByLocale );
798 $this->setVar( 'wgShellLocale', $m[0] );
799 $this->showMessage( 'config-shell-locale', $m[0] );
810 public function envCheckUploadsDirectory() {
811 global $IP, $wgServer;
813 $dir = $IP . '/images/';
814 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
815 $safe = !$this->dirIsExecutable( $dir, $url );
818 $this->showMessage( 'config-uploads-safe' );
820 $this->showMessage( 'config-uploads-not-safe', $dir );
825 * Convert a hex string representing a Unicode code point to that code point.
829 protected function unicodeChar( $c ) {
833 } else if ($c <= 0x7FF) {
834 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
835 } else if ($c <= 0xFFFF) {
836 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
837 . chr(0x80 |
$c & 0x3F);
838 } else if ($c <= 0x10FFFF) {
839 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
840 . chr(0x80 |
$c >> 6 & 0x3F)
841 . chr(0x80 |
$c & 0x3F);
849 * Check the libicu version
851 public function envCheckLibicu() {
852 $utf8 = function_exists( 'utf8_normalize' );
853 $intl = function_exists( 'normalizer_normalize' );
856 * This needs to be updated something that the latest libicu
857 * will properly normalize. This normalization was found at
858 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
859 * Note that we use the hex representation to create the code
860 * points in order to avoid any Unicode-destroying during transit.
862 $not_normal_c = $this->unicodeChar("FA6C");
863 $normal_c = $this->unicodeChar("242EE");
865 $useNormalizer = 'php';
866 $needsUpdate = false;
869 * We're going to prefer the pecl extension here unless
870 * utf8_normalize is more up to date.
873 $useNormalizer = 'utf8';
874 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
875 if ( $utf8 !== $normal_c ) $needsUpdate = true;
878 $useNormalizer = 'intl';
879 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
880 if ( $intl !== $normal_c ) $needsUpdate = true;
883 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
884 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
885 if( $useNormalizer === 'php' ) {
886 $this->showMessage( 'config-unicode-pure-php-warning' );
887 } elseif( $needsUpdate ) {
888 $this->showMessage( 'config-unicode-update-warning' );
894 * Search a path for any of the given executable names. Returns the
895 * executable name if found. Also checks the version string returned
896 * by each executable.
898 * Used only by environment checks.
900 * @param $path String: path to search
901 * @param $names Array of executable names
902 * @param $versionInfo Boolean false or array with two members:
903 * 0 => Command to run for version check, with $1 for the path
904 * 1 => String to compare the output with
906 * If $versionInfo is not false, only executables with a version
907 * matching $versionInfo[1] will be returned.
909 protected function locateExecutable( $path, $names, $versionInfo = false ) {
910 if ( !is_array( $names ) ) {
911 $names = array( $names );
914 foreach ( $names as $name ) {
915 $command = "$path/$name";
917 wfSuppressWarnings();
918 $file_exists = file_exists( $command );
921 if ( $file_exists ) {
922 if ( !$versionInfo ) {
926 $file = str_replace( '$1', $command, $versionInfo[0] );
928 # Should maybe be wfShellExec( $file), but runs into a ulimit, see
929 # http://www.mediawiki.org/w/index.php?title=New-installer_issues&diff=prev&oldid=335456
930 if ( strstr( `
$file`
, $versionInfo[1]) !== false ) {
940 * Checks if scripts located in the given directory can be executed via the given URL.
942 * Used only by environment checks.
944 public function dirIsExecutable( $dir, $url ) {
945 $scriptTypes = array(
947 "<?php echo 'ex' . 'ec';",
948 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
952 // it would be good to check other popular languages here, but it'll be slow.
954 wfSuppressWarnings();
956 foreach ( $scriptTypes as $ext => $contents ) {
957 foreach ( $contents as $source ) {
958 $file = 'exectest.' . $ext;
960 if ( !file_put_contents( $dir . $file, $source ) ) {
964 $text = Http
::get( $url . $file );
965 unlink( $dir . $file );
967 if ( $text == 'exec' ) {