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(
78 * A list of environment check methods called by doEnvironmentChecks().
79 * These may output warnings using showMessage(), and/or abort the
80 * installation process by returning false.
84 protected $envChecks = array(
85 'envCheckMediaWikiVersion',
87 'envCheckRegisterGlobals',
90 'envCheckMagicQuotes',
91 'envCheckMagicSybase',
103 'envCheckShellLocale',
104 'envCheckUploadsDirectory',
109 * UI interface for displaying a short message
110 * The parameters are like parameters to wfMsg().
111 * The messages will be in wikitext format, which will be converted to an
112 * output format such as HTML or text before being sent to the user.
114 public abstract function showMessage( $msg /*, ... */ );
117 * Constructor, always call this from child classes.
119 public function __construct() {
120 // Disable the i18n cache and LoadBalancer
121 Language
::getLocalisationCache()->disableBackend();
122 LBFactory
::disableBackend();
126 * Get a list of known DB types.
128 public static function getDBTypes() {
129 return self
::$dbTypes;
133 * Do initial checks of the PHP environment. Set variables according to
134 * the observed environment.
136 * It's possible that this may be called under the CLI SAPI, not the SAPI
137 * that the wiki will primarily run under. In that case, the subclass should
138 * initialise variables such as wgScriptPath, before calling this function.
140 * Under the web subclass, it can already be assumed that PHP 5+ is in use
141 * and that sessions are working.
145 public function doEnvironmentChecks() {
146 $this->showMessage( 'config-env-php', phpversion() );
150 foreach ( $this->envChecks
as $check ) {
151 $status = $this->$check();
152 if ( $status === false ) {
157 $this->setVar( '_Environment', $good );
160 $this->showMessage( 'config-env-good' );
162 $this->showMessage( 'config-env-bad' );
169 * Set a MW configuration variable, or internal installer configuration variable.
171 * @param $name String
172 * @param $value Mixed
174 public function setVar( $name, $value ) {
175 $this->settings
[$name] = $value;
179 * Get an MW configuration variable, or internal installer configuration variable.
180 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
181 * Installer variables are typically prefixed by an underscore.
183 * @param $name String
184 * @param $default Mixed
188 public function getVar( $name, $default = null ) {
189 if ( !isset( $this->settings
[$name] ) ) {
192 return $this->settings
[$name];
197 * Get an instance of DatabaseInstaller for the specified DB type.
199 * @param $type Mixed: DB installer for which is needed, false to use default.
201 * @return DatabaseInstaller
203 public function getDBInstaller( $type = false ) {
205 $type = $this->getVar( 'wgDBtype' );
208 $type = strtolower( $type );
210 if ( !isset( $this->dbInstallers
[$type] ) ) {
211 $class = ucfirst( $type ). 'Installer';
212 $this->dbInstallers
[$type] = new $class( $this );
215 return $this->dbInstallers
[$type];
219 * Determine if LocalSettings exists. If it does, return an appropriate
220 * status for whether we should can upgrade or not.
224 public function getLocalSettingsStatus() {
227 $status = Status
::newGood();
229 wfSuppressWarnings();
230 $ls = file_exists( "$IP/LocalSettings.php" );
234 require( "$IP/includes/DefaultSettings.php" );
235 require_once( "$IP/LocalSettings.php" );
236 $vars = get_defined_vars();
237 if( isset( $vars['wgUpgradeKey'] ) && $vars['wgUpgradeKey'] ) {
238 $status->warning( 'config-localsettings-upgrade' );
239 $this->setVar( '_UpgradeKey', $vars['wgUpgradeKey' ] );
241 $status->fatal( 'config-localsettings-noupgrade' );
249 * Get a fake password for sending back to the user in HTML.
250 * This is a security mechanism to avoid compromise of the password in the
251 * event of session ID compromise.
253 * @param $realPassword String
257 public function getFakePassword( $realPassword ) {
258 return str_repeat( '*', strlen( $realPassword ) );
262 * Set a variable which stores a password, except if the new value is a
263 * fake password in which case leave it as it is.
265 * @param $name String
266 * @param $value Mixed
268 public function setPassword( $name, $value ) {
269 if ( !preg_match( '/^\*+$/', $value ) ) {
270 $this->setVar( $name, $value );
275 * On POSIX systems return the primary group of the webserver we're running under.
276 * On other systems just returns null.
278 * This is used to advice the user that he should chgrp his config/data/images directory as the
279 * webserver user before he can install.
281 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
285 public static function maybeGetWebserverPrimaryGroup() {
286 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
287 # I don't know this, this isn't UNIX.
291 # posix_getegid() *not* getmygid() because we want the group of the webserver,
292 # not whoever owns the current script.
293 $gid = posix_getegid();
294 $getpwuid = posix_getpwuid( $gid );
295 $group = $getpwuid['name'];
301 * Convert wikitext $text to HTML.
303 * This is potentially error prone since many parser features require a complete
304 * installed MW database. The solution is to just not use those features when you
305 * write your messages. This appears to work well enough. Basic formatting and
306 * external links work just fine.
308 * But in case a translator decides to throw in a #ifexist or internal link or
309 * whatever, this function is guarded to catch attempted DB access and to present
310 * some fallback text.
312 * @param $text String
313 * @param $lineStart Boolean
316 public function parse( $text, $lineStart = false ) {
320 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
321 $html = $out->getText();
322 } catch ( DBAccessError
$e ) {
323 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
325 if ( !empty( $this->debug
) ) {
326 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
336 * @param $installer DatabaseInstaller
340 public function installDatabase( DatabaseInstaller
&$installer ) {
342 $type = $this->getVar( 'wgDBtype' );
343 $status = Status
::newFatal( "config-no-db", $type );
345 $status = $installer->setupDatabase();
354 * @param $installer DatabaseInstaller
358 public function installTables( DatabaseInstaller
&$installer ) {
359 $status = $installer->createTables();
361 if( $status->isOK() ) {
362 LBFactory
::enableBackend();
371 * @param $installer DatabaseInstaller
375 public function installInterwiki( DatabaseInstaller
&$installer ) {
376 return $installer->populateInterwikiTable();
380 * Exports all wg* variables stored by the installer into global scope.
382 public function exportVars() {
383 foreach ( $this->settings
as $name => $value ) {
384 if ( substr( $name, 0, 2 ) == 'wg' ) {
385 $GLOBALS[$name] = $value;
391 * Check if we're installing the latest version.
393 public function envCheckMediaWikiVersion() {
396 if( !$this->getVar( '_ExternalHTTP' ) ) {
397 $this->showMessage( 'config-env-latest-disabled' );
401 $repository = wfGetRepository();
402 $currentVersion = $repository->getLatestCoreVersion();
404 if ( $currentVersion === false ) {
405 # For when the request is successful but there's e.g. some silly man in
406 # the middle firewall blocking us, e.g. one of those annoying airport ones
407 $this->showMessage( 'config-env-latest-can-not-check', $repository->getLocation() );
411 if( version_compare( $wgVersion, $currentVersion, '<' ) ) {
412 $this->showMessage( 'config-env-latest-old' );
413 // FIXME: this only works for the web installer!
414 $this->showHelpBox( 'config-env-latest-help', $wgVersion, $currentVersion );
415 } elseif( version_compare( $wgVersion, $currentVersion, '>' ) ) {
416 $this->showMessage( 'config-env-latest-new' );
418 $this->showMessage( 'config-env-latest-ok' );
423 * Environment check for DB types.
425 public function envCheckDB() {
428 $compiledDBs = array();
429 $goodNames = array();
432 foreach ( self
::getDBTypes() as $name ) {
433 $db = $this->getDBInstaller( $name );
434 $readableName = wfMsg( 'config-type-' . $name );
436 if ( $db->isCompiled() ) {
437 $compiledDBs[] = $name;
438 $goodNames[] = $readableName;
441 $allNames[] = $readableName;
444 $this->setVar( '_CompiledDBs', $compiledDBs );
446 if ( !$compiledDBs ) {
447 $this->showMessage( 'config-no-db' );
448 // FIXME: this only works for the web installer!
449 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
453 $this->showMessage( 'config-have-db', $wgLang->listToText( $goodNames ), count( $goodNames ) );
455 // Check for FTS3 full-text search module
456 $sqlite = $this->getDBInstaller( 'sqlite' );
457 if ( $sqlite->isCompiled() ) {
458 $db = new DatabaseSqliteStandalone( ':memory:' );
459 $this->showMessage( $db->getFulltextSearchModule() == 'FTS3'
467 * Environment check for register_globals.
469 public function envCheckRegisterGlobals() {
470 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
471 $this->showMessage( 'config-register-globals' );
476 * Some versions of libxml+PHP break < and > encoding horribly
478 public function envCheckBrokenXML() {
479 $test = new PhpXmlBugTester();
481 $this->showMessage( 'config-brokenlibxml' );
487 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
488 * reference parameters to __call() are not converted to null
490 public function envCheckPHP531() {
491 $test = new PhpRefCallBugTester
;
494 $this->showMessage( 'config-using531' );
500 * Environment check for magic_quotes_runtime.
502 public function envCheckMagicQuotes() {
503 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
504 $this->showMessage( 'config-magic-quotes-runtime' );
510 * Environment check for magic_quotes_sybase.
512 public function envCheckMagicSybase() {
513 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
514 $this->showMessage( 'config-magic-quotes-sybase' );
520 * Environment check for mbstring.func_overload.
522 public function envCheckMbstring() {
523 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
524 $this->showMessage( 'config-mbstring' );
530 * Environment check for zend.ze1_compatibility_mode.
532 public function envCheckZE1() {
533 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
534 $this->showMessage( 'config-ze1' );
540 * Environment check for safe_mode.
542 public function envCheckSafeMode() {
543 if ( wfIniGetBool( 'safe_mode' ) ) {
544 $this->setVar( '_SafeMode', true );
545 $this->showMessage( 'config-safe-mode' );
550 * Environment check for the XML module.
552 public function envCheckXML() {
553 if ( !function_exists( "utf8_encode" ) ) {
554 $this->showMessage( 'config-xml-bad' );
557 $this->showMessage( 'config-xml-good' );
561 * Environment check for the PCRE module.
563 public function envCheckPCRE() {
564 if ( !function_exists( 'preg_match' ) ) {
565 $this->showMessage( 'config-pcre' );
571 * Environment check for available memory.
573 public function envCheckMemory() {
574 $limit = ini_get( 'memory_limit' );
576 if ( !$limit ||
$limit == -1 ) {
577 $this->showMessage( 'config-memory-none' );
581 $n = intval( $limit );
583 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $limit ), $m ) ) {
584 $n = intval( $m[1] * ( 1024 * 1024 ) );
587 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
588 $newLimit = "{$this->minMemorySize}M";
590 if( ini_set( "memory_limit", $newLimit ) === false ) {
591 $this->showMessage( 'config-memory-bad', $limit );
593 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
594 $this->setVar( '_RaiseMemory', true );
597 $this->showMessage( 'config-memory-ok', $limit );
602 * Environment check for compiled object cache types.
604 public function envCheckCache() {
607 foreach ( $this->objectCaches
as $name => $function ) {
608 if ( function_exists( $function ) ) {
609 $caches[$name] = true;
610 $this->showMessage( 'config-' . $name );
615 $this->showMessage( 'config-no-cache' );
618 $this->setVar( '_Caches', $caches );
622 * Search for GNU diff3.
624 public function envCheckDiff3() {
625 $names = array( "gdiff3", "diff3", "diff3.exe" );
626 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
628 $diff3 = $this->locateExecutableInDefaultPaths( $names, $versionInfo );
631 $this->showMessage( 'config-diff3-good', $diff3 );
632 $this->setVar( 'wgDiff3', $diff3 );
634 $this->setVar( 'wgDiff3', false );
635 $this->showMessage( 'config-diff3-bad' );
640 * Environment check for ImageMagick and GD.
642 public function envCheckGraphics() {
643 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
644 $convert = $this->locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
647 $this->setVar( 'wgImageMagickConvertCommand', $convert );
648 $this->showMessage( 'config-imagemagick', $convert );
650 } elseif ( function_exists( 'imagejpeg' ) ) {
651 $this->showMessage( 'config-gd' );
654 $this->showMessage( 'no-scaling' );
659 * Environment check for setting $IP and $wgScriptPath.
661 public function envCheckPath() {
663 $IP = dirname( dirname( dirname( __FILE__
) ) );
665 $this->setVar( 'IP', $IP );
666 $this->showMessage( 'config-dir', $IP );
668 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
669 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
670 // to get the path to the current script... hopefully it's reliable. SIGH
671 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
672 $path = $_SERVER['PHP_SELF'];
673 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
674 $path = $_SERVER['SCRIPT_NAME'];
675 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
676 // Some kind soul has set it for us already (e.g. debconf)
679 $this->showMessage( 'config-no-uri' );
683 $uri = preg_replace( '{^(.*)/config.*$}', '$1', $path );
684 $this->setVar( 'wgScriptPath', $uri );
685 $this->showMessage( 'config-uri', $uri );
689 * Environment check for setting the preferred PHP file extension.
691 public function envCheckExtension() {
692 // FIXME: detect this properly
693 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
699 $this->setVar( 'wgScriptExtension', ".$ext" );
700 $this->showMessage( 'config-file-extension', $ext );
706 public function envCheckShellLocale() {
707 $os = php_uname( 's' );
708 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
710 if ( !in_array( $os, $supported ) ) {
714 # Get a list of available locales.
716 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
722 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
723 $candidatesByLocale = array();
724 $candidatesByLang = array();
726 foreach ( $lines as $line ) {
727 if ( $line === '' ) {
731 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
735 list( $all, $lang, $territory, $charset, $modifier ) = $m;
737 $candidatesByLocale[$m[0]] = $m;
738 $candidatesByLang[$lang][] = $m;
741 # Try the current value of LANG.
742 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
743 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
744 $this->showMessage( 'config-shell-locale', getenv( 'LANG' ) );
748 # Try the most common ones.
749 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
750 foreach ( $commonLocales as $commonLocale ) {
751 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
752 $this->setVar( 'wgShellLocale', $commonLocale );
753 $this->showMessage( 'config-shell-locale', $commonLocale );
758 # Is there an available locale in the Wiki's language?
759 $wikiLang = $this->getVar( 'wgLanguageCode' );
761 if ( isset( $candidatesByLang[$wikiLang] ) ) {
762 $m = reset( $candidatesByLang[$wikiLang] );
763 $this->setVar( 'wgShellLocale', $m[0] );
764 $this->showMessage( 'config-shell-locale', $m[0] );
768 # Are there any at all?
769 if ( count( $candidatesByLocale ) ) {
770 $m = reset( $candidatesByLocale );
771 $this->setVar( 'wgShellLocale', $m[0] );
772 $this->showMessage( 'config-shell-locale', $m[0] );
783 public function envCheckUploadsDirectory() {
784 global $IP, $wgServer;
786 $dir = $IP . '/images/';
787 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
788 $safe = !$this->dirIsExecutable( $dir, $url );
791 $this->showMessage( 'config-uploads-safe' );
793 $this->showMessage( 'config-uploads-not-safe', $dir );
798 * Convert a hex string representing a Unicode code point to that code point.
802 protected function unicodeChar( $c ) {
806 } else if ($c <= 0x7FF) {
807 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
808 } else if ($c <= 0xFFFF) {
809 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
810 . chr(0x80 |
$c & 0x3F);
811 } else if ($c <= 0x10FFFF) {
812 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
813 . chr(0x80 |
$c >> 6 & 0x3F)
814 . chr(0x80 |
$c & 0x3F);
822 * Check the libicu version
824 public function envCheckLibicu() {
825 $utf8 = function_exists( 'utf8_normalize' );
826 $intl = function_exists( 'normalizer_normalize' );
829 * This needs to be updated something that the latest libicu
830 * will properly normalize. This normalization was found at
831 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
832 * Note that we use the hex representation to create the code
833 * points in order to avoid any Unicode-destroying during transit.
835 $not_normal_c = $this->unicodeChar("FA6C");
836 $normal_c = $this->unicodeChar("242EE");
838 $useNormalizer = 'php';
839 $needsUpdate = false;
842 * We're going to prefer the pecl extension here unless
843 * utf8_normalize is more up to date.
846 $useNormalizer = 'utf8';
847 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
848 if ( $utf8 !== $normal_c ) $needsUpdate = true;
851 $useNormalizer = 'intl';
852 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
853 if ( $intl !== $normal_c ) $needsUpdate = true;
856 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
857 if( $useNormalizer === 'php' ) {
858 $this->showMessage( 'config-unicode-pure-php-warning' );
860 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
862 $this->showMessage( 'config-unicode-update-warning' );
868 * Get an array of likely places we can find executables. Check a bunch
869 * of known Unix-like defaults, as well as the PATH environment variable
870 * (which should maybe make it work for Windows?)
874 protected static function getPossibleBinPaths() {
876 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
877 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
878 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
883 * Search a path for any of the given executable names. Returns the
884 * executable name if found. Also checks the version string returned
885 * by each executable.
887 * Used only by environment checks.
889 * @param $path String: path to search
890 * @param $names Array of executable names
891 * @param $versionInfo Boolean false or array with two members:
892 * 0 => Command to run for version check, with $1 for the path
893 * 1 => String to compare the output with
895 * If $versionInfo is not false, only executables with a version
896 * matching $versionInfo[1] will be returned.
898 public static function locateExecutable( $path, $names, $versionInfo = false ) {
899 if ( !is_array( $names ) ) {
900 $names = array( $names );
903 foreach ( $names as $name ) {
904 $command = $path . DIRECTORY_SEPARATOR
. $name;
906 wfSuppressWarnings();
907 $file_exists = file_exists( $command );
910 if ( $file_exists ) {
911 if ( !$versionInfo ) {
915 if ( wfIsWindows() ) {
916 $command = "\"$command\"";
918 $file = str_replace( '$1', $command, $versionInfo[0] );
919 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
928 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
929 * @see locateExecutable()
931 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
932 foreach( self
::getPossibleBinPaths() as $path ) {
933 $exe = self
::locateExecutable( $path, $names, $versionInfo );
934 if( $exe !== false ) {
942 * Checks if scripts located in the given directory can be executed via the given URL.
944 * Used only by environment checks.
946 public function dirIsExecutable( $dir, $url ) {
947 $scriptTypes = array(
949 "<?php echo 'ex' . 'ec';",
950 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
954 // it would be good to check other popular languages here, but it'll be slow.
956 wfSuppressWarnings();
958 foreach ( $scriptTypes as $ext => $contents ) {
959 foreach ( $contents as $source ) {
960 $file = 'exectest.' . $ext;
962 if ( !file_put_contents( $dir . $file, $source ) ) {
966 $text = Http
::get( $url . $file );
967 unlink( $dir . $file );
969 if ( $text == 'exec' ) {