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(
87 'envCheckRegisterGlobals',
88 'envCheckMagicQuotes',
89 'envCheckMagicSybase',
100 'envCheckWriteableDir',
102 'envCheckShellLocale',
103 'envCheckUploadsDirectory',
108 * UI interface for displaying a short message
109 * The parameters are like parameters to wfMsg().
110 * The messages will be in wikitext format, which will be converted to an
111 * output format such as HTML or text before being sent to the user.
113 public abstract function showMessage( $msg /*, ... */ );
116 * Constructor, always call this from child classes.
118 public function __construct() {
119 // Disable the i18n cache and LoadBalancer
120 Language
::getLocalisationCache()->disableBackend();
121 LBFactory
::disableBackend();
125 * Get a list of known DB types.
127 public static function getDBTypes() {
128 return self
::$dbTypes;
132 * Do initial checks of the PHP environment. Set variables according to
133 * the observed environment.
135 * It's possible that this may be called under the CLI SAPI, not the SAPI
136 * that the wiki will primarily run under. In that case, the subclass should
137 * initialise variables such as wgScriptPath, before calling this function.
139 * Under the web subclass, it can already be assumed that PHP 5+ is in use
140 * and that sessions are working.
144 public function doEnvironmentChecks() {
145 $this->showMessage( 'config-env-php', phpversion() );
149 foreach ( $this->envChecks
as $check ) {
150 $status = $this->$check();
151 if ( $status === false ) {
156 $this->setVar( '_Environment', $good );
159 $this->showMessage( 'config-env-good' );
161 $this->showMessage( 'config-env-bad' );
168 * Set a MW configuration variable, or internal installer configuration variable.
170 * @param $name String
171 * @param $value Mixed
173 public function setVar( $name, $value ) {
174 $this->settings
[$name] = $value;
178 * Get an MW configuration variable, or internal installer configuration variable.
179 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
180 * Installer variables are typically prefixed by an underscore.
182 * @param $name String
183 * @param $default Mixed
187 public function getVar( $name, $default = null ) {
188 if ( !isset( $this->settings
[$name] ) ) {
191 return $this->settings
[$name];
196 * Get an instance of DatabaseInstaller for the specified DB type.
198 * @param $type Mixed: DB installer for which is needed, false to use default.
200 * @return DatabaseInstaller
202 public function getDBInstaller( $type = false ) {
204 $type = $this->getVar( 'wgDBtype' );
207 $type = strtolower( $type );
209 if ( !isset( $this->dbInstallers
[$type] ) ) {
210 $class = ucfirst( $type ). 'Installer';
211 $this->dbInstallers
[$type] = new $class( $this );
214 return $this->dbInstallers
[$type];
218 * Determine if LocalSettings exists. If it does, return an appropriate
219 * status for whether we should can upgrade or not.
223 public function getLocalSettingsStatus() {
226 $status = Status
::newGood();
228 wfSuppressWarnings();
229 $ls = file_exists( "$IP/LocalSettings.php" );
233 if( $this->getDBInstaller()->needsUpgrade() ) {
234 $status->warning( 'config-localsettings-upgrade' );
237 $status->fatal( 'config-localsettings-noupgrade' );
245 * Get a fake password for sending back to the user in HTML.
246 * This is a security mechanism to avoid compromise of the password in the
247 * event of session ID compromise.
249 * @param $realPassword String
253 public function getFakePassword( $realPassword ) {
254 return str_repeat( '*', strlen( $realPassword ) );
258 * Set a variable which stores a password, except if the new value is a
259 * fake password in which case leave it as it is.
261 * @param $name String
262 * @param $value Mixed
264 public function setPassword( $name, $value ) {
265 if ( !preg_match( '/^\*+$/', $value ) ) {
266 $this->setVar( $name, $value );
271 * On POSIX systems return the primary group of the webserver we're running under.
272 * On other systems just returns null.
274 * This is used to advice the user that he should chgrp his config/data/images directory as the
275 * webserver user before he can install.
277 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
281 public static function maybeGetWebserverPrimaryGroup() {
282 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
283 # I don't know this, this isn't UNIX.
287 # posix_getegid() *not* getmygid() because we want the group of the webserver,
288 # not whoever owns the current script.
289 $gid = posix_getegid();
290 $getpwuid = posix_getpwuid( $gid );
291 $group = $getpwuid['name'];
297 * Convert wikitext $text to HTML.
299 * This is potentially error prone since many parser features require a complete
300 * installed MW database. The solution is to just not use those features when you
301 * write your messages. This appears to work well enough. Basic formatting and
302 * external links work just fine.
304 * But in case a translator decides to throw in a #ifexist or internal link or
305 * whatever, this function is guarded to catch attempted DB access and to present
306 * some fallback text.
308 * @param $text String
309 * @param $lineStart Boolean
312 public function parse( $text, $lineStart = false ) {
316 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
317 $html = $out->getText();
318 } catch ( DBAccessError
$e ) {
319 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
321 if ( !empty( $this->debug
) ) {
322 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
332 * @param $installer DatabaseInstaller
336 public function installDatabase( DatabaseInstaller
&$installer ) {
338 $type = $this->getVar( 'wgDBtype' );
339 $status = Status
::newFatal( "config-no-db", $type );
341 $status = $installer->setupDatabase();
350 * @param $installer DatabaseInstaller
354 public function installTables( DatabaseInstaller
&$installer ) {
355 $status = $installer->createTables();
357 if( $status->isOK() ) {
358 LBFactory
::enableBackend();
367 * @param $installer DatabaseInstaller
371 public function installInterwiki( DatabaseInstaller
&$installer ) {
372 return $installer->populateInterwikiTable();
376 * Exports all wg* variables stored by the installer into global scope.
378 public function exportVars() {
379 foreach ( $this->settings
as $name => $value ) {
380 if ( substr( $name, 0, 2 ) == 'wg' ) {
381 $GLOBALS[$name] = $value;
387 * Check if we're installing the latest version.
389 public function envLatestVersion() {
392 $repository = wfGetRepository();
393 $currentVersion = $repository->getLatestCoreVersion();
395 $this->setVar( '_ExternalHTTP', true );
397 if ( $currentVersion === false ) {
398 # For when the request is successful but there's e.g. some silly man in
399 # the middle firewall blocking us, e.g. one of those annoying airport ones
400 $this->showMessage( 'config-env-latest-can-not-check', $repository->getLocation() );
404 if( version_compare( $wgVersion, $currentVersion, '<' ) ) {
405 $this->showMessage( 'config-env-latest-old' );
406 // FIXME: this only works for the web installer!
407 $this->showHelpBox( 'config-env-latest-help', $wgVersion, $currentVersion );
408 } elseif( version_compare( $wgVersion, $currentVersion, '>' ) ) {
409 $this->showMessage( 'config-env-latest-new' );
412 $this->showMessage( 'config-env-latest-ok' );
416 * Environment check for DB types.
418 public function envCheckDB() {
421 $compiledDBs = array();
422 $goodNames = array();
425 foreach ( self
::getDBTypes() as $name ) {
426 $db = $this->getDBInstaller( $name );
427 $readableName = wfMsg( 'config-type-' . $name );
429 if ( $db->isCompiled() ) {
430 $compiledDBs[] = $name;
431 $goodNames[] = $readableName;
434 $allNames[] = $readableName;
437 $this->setVar( '_CompiledDBs', $compiledDBs );
439 if ( !$compiledDBs ) {
440 $this->showMessage( 'config-no-db' );
441 // FIXME: this only works for the web installer!
442 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
446 $this->showMessage( 'config-have-db', $wgLang->listToText( $goodNames ), count( $goodNames ) );
450 * Environment check for register_globals.
452 public function envCheckRegisterGlobals() {
453 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
454 $this->showMessage( 'config-register-globals' );
459 * Environment check for magic_quotes_runtime.
461 public function envCheckMagicQuotes() {
462 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
463 $this->showMessage( 'config-magic-quotes-runtime' );
469 * Environment check for magic_quotes_sybase.
471 public function envCheckMagicSybase() {
472 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
473 $this->showMessage( 'config-magic-quotes-sybase' );
479 * Environment check for mbstring.func_overload.
481 public function envCheckMbstring() {
482 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
483 $this->showMessage( 'config-mbstring' );
489 * Environment check for zend.ze1_compatibility_mode.
491 public function envCheckZE1() {
492 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
493 $this->showMessage( 'config-ze1' );
499 * Environment check for safe_mode.
501 public function envCheckSafeMode() {
502 if ( wfIniGetBool( 'safe_mode' ) ) {
503 $this->setVar( '_SafeMode', true );
504 $this->showMessage( 'config-safe-mode' );
509 * Environment check for the XML module.
511 public function envCheckXML() {
512 if ( !function_exists( "utf8_encode" ) ) {
513 $this->showMessage( 'config-xml-bad' );
516 $this->showMessage( 'config-xml-good' );
520 * Environment check for the PCRE module.
522 public function envCheckPCRE() {
523 if ( !function_exists( 'preg_match' ) ) {
524 $this->showMessage( 'config-pcre' );
530 * Environment check for available memory.
532 public function envCheckMemory() {
533 $limit = ini_get( 'memory_limit' );
535 if ( !$limit ||
$limit == -1 ) {
536 $this->showMessage( 'config-memory-none' );
540 $n = intval( $limit );
542 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $limit ), $m ) ) {
543 $n = intval( $m[1] * ( 1024 * 1024 ) );
546 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
547 $newLimit = "{$this->minMemorySize}M";
549 if( ini_set( "memory_limit", $newLimit ) === false ) {
550 $this->showMessage( 'config-memory-bad', $limit );
552 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
553 $this->setVar( '_RaiseMemory', true );
556 $this->showMessage( 'config-memory-ok', $limit );
561 * Environment check for compiled object cache types.
563 public function envCheckCache() {
566 foreach ( $this->objectCaches
as $name => $function ) {
567 if ( function_exists( $function ) ) {
568 $caches[$name] = true;
569 $this->showMessage( 'config-' . $name );
574 $this->showMessage( 'config-no-cache' );
577 $this->setVar( '_Caches', $caches );
581 * Search for GNU diff3.
583 public function envCheckDiff3() {
584 $paths = array_merge(
592 explode( PATH_SEPARATOR
, getenv( "PATH" ) )
595 $names = array( "gdiff3", "diff3", "diff3.exe" );
596 $versionInfo = array( '$1 --version 2>&1', 'diff3 (GNU diffutils)' );
600 foreach ( $paths as $path ) {
601 $exe = $this->locateExecutable( $path, $names, $versionInfo );
603 if ($exe !== false) {
604 $this->setVar( 'wgDiff3', $exe );
611 $this->showMessage( 'config-diff3-good', $exe );
613 $this->setVar( 'wgDiff3', false );
614 $this->showMessage( 'config-diff3-bad' );
619 * Environment check for ImageMagick and GD.
621 public function envCheckGraphics() {
622 $imcheck = array( "/usr/bin", "/opt/csw/bin", "/usr/local/bin", "/sw/bin", "/opt/local/bin" );
624 foreach( $imcheck as $dir ) {
625 $im = "$dir/convert";
627 wfSuppressWarnings();
628 $file_exists = file_exists( $im );
632 $this->showMessage( 'config-imagemagick', $im );
633 $this->setVar( 'wgImageMagickConvertCommand', $im );
638 if ( function_exists( 'imagejpeg' ) ) {
639 $this->showMessage( 'config-gd' );
643 $this->showMessage( 'no-scaling' );
647 * Environment check for setting $IP and $wgScriptPath.
649 public function envCheckPath() {
651 $IP = dirname( dirname( dirname( __FILE__
) ) );
653 $this->setVar( 'IP', $IP );
654 $this->showMessage( 'config-dir', $IP );
656 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
657 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
658 // to get the path to the current script... hopefully it's reliable. SIGH
659 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
660 $path = $_SERVER['PHP_SELF'];
661 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
662 $path = $_SERVER['SCRIPT_NAME'];
663 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
664 // Some kind soul has set it for us already (e.g. debconf)
667 $this->showMessage( 'config-no-uri' );
671 $uri = preg_replace( '{^(.*)/config.*$}', '$1', $path );
672 $this->setVar( 'wgScriptPath', $uri );
673 $this->showMessage( 'config-uri', $uri );
677 * Environment check for writable config/ directory.
679 public function envCheckWriteableDir() {
680 $ipDir = $this->getVar( 'IP' );
681 $configDir = $ipDir . '/config';
683 if( !is_writeable( $configDir ) ) {
684 $webserverGroup = self
::maybeGetWebserverPrimaryGroup();
686 if ( $webserverGroup !== null ) {
687 $this->showMessage( 'config-dir-not-writable-group', $ipDir, $webserverGroup );
689 $this->showMessage( 'config-dir-not-writable-nogroup', $ipDir, $webserverGroup );
697 * Environment check for setting the preferred PHP file extension.
699 public function envCheckExtension() {
700 // FIXME: detect this properly
701 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
707 $this->setVar( 'wgScriptExtension', ".$ext" );
708 $this->showMessage( 'config-file-extension', $ext );
714 public function envCheckShellLocale() {
715 # Give up now if we're in safe mode or open_basedir.
716 # It's theoretically possible but tricky to work with.
717 if ( wfIniGetBool( "safe_mode" ) ||
ini_get( 'open_basedir' ) ||
!function_exists( 'exec' ) ) {
721 $os = php_uname( 's' );
722 $supported = array( 'Linux', 'SunOS', 'HP-UX' ); # Tested these
724 if ( !in_array( $os, $supported ) ) {
728 # Get a list of available locales.
729 $lines = $ret = false;
730 exec( '/usr/bin/locale -a', $lines, $ret );
736 $lines = wfArrayMap( 'trim', $lines );
737 $candidatesByLocale = array();
738 $candidatesByLang = array();
740 foreach ( $lines as $line ) {
741 if ( $line === '' ) {
745 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
749 list( $all, $lang, $territory, $charset, $modifier ) = $m;
751 $candidatesByLocale[$m[0]] = $m;
752 $candidatesByLang[$lang][] = $m;
755 # Try the current value of LANG.
756 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
757 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
758 $this->showMessage( 'config-shell-locale', getenv( 'LANG' ) );
762 # Try the most common ones.
763 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
764 foreach ( $commonLocales as $commonLocale ) {
765 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
766 $this->setVar( 'wgShellLocale', $commonLocale );
767 $this->showMessage( 'config-shell-locale', $commonLocale );
772 # Is there an available locale in the Wiki's language?
773 $wikiLang = $this->getVar( 'wgLanguageCode' );
775 if ( isset( $candidatesByLang[$wikiLang] ) ) {
776 $m = reset( $candidatesByLang[$wikiLang] );
777 $this->setVar( 'wgShellLocale', $m[0] );
778 $this->showMessage( 'config-shell-locale', $m[0] );
782 # Are there any at all?
783 if ( count( $candidatesByLocale ) ) {
784 $m = reset( $candidatesByLocale );
785 $this->setVar( 'wgShellLocale', $m[0] );
786 $this->showMessage( 'config-shell-locale', $m[0] );
797 public function envCheckUploadsDirectory() {
798 global $IP, $wgServer;
800 $dir = $IP . '/images/';
801 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
802 $safe = !$this->dirIsExecutable( $dir, $url );
805 $this->showMessage( 'config-uploads-safe' );
807 $this->showMessage( 'config-uploads-not-safe', $dir );
812 * Convert a hex string representing a Unicode code point to that code point.
816 protected function unicodeChar( $c ) {
820 } else if ($c <= 0x7FF) {
821 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
822 } else if ($c <= 0xFFFF) {
823 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
824 . chr(0x80 |
$c & 0x3F);
825 } else if ($c <= 0x10FFFF) {
826 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
827 . chr(0x80 |
$c >> 6 & 0x3F)
828 . chr(0x80 |
$c & 0x3F);
836 * Check the libicu version
838 public function envCheckLibicu() {
839 $utf8 = function_exists( 'utf8_normalize' );
840 $intl = function_exists( 'normalizer_normalize' );
843 * This needs to be updated something that the latest libicu
844 * will properly normalize. This normalization was found at
845 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
846 * Note that we use the hex representation to create the code
847 * points in order to avoid any Unicode-destroying during transit.
849 $not_normal_c = $this->unicodeChar("FA6C");
850 $normal_c = $this->unicodeChar("242EE");
852 $useNormalizer = 'php';
853 $needsUpdate = false;
856 * We're going to prefer the pecl extension here unless
857 * utf8_normalize is more up to date.
860 $useNormalizer = 'utf8';
861 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
862 if ( $utf8 !== $normal_c ) $needsUpdate = true;
865 $useNormalizer = 'intl';
866 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
867 if ( $intl !== $normal_c ) $needsUpdate = true;
870 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
871 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
872 if( $useNormalizer === 'php' ) {
873 $this->showMessage( 'config-unicode-pure-php-warning' );
874 } elseif( $needsUpdate ) {
875 $this->showMessage( 'config-unicode-update-warning' );
881 * Search a path for any of the given executable names. Returns the
882 * executable name if found. Also checks the version string returned
883 * by each executable.
885 * Used only by environment checks.
887 * @param $path String: path to search
888 * @param $names Array of executable names
889 * @param $versionInfo Boolean false or array with two members:
890 * 0 => Command to run for version check, with $1 for the path
891 * 1 => String to compare the output with
893 * If $versionInfo is not false, only executables with a version
894 * matching $versionInfo[1] will be returned.
896 protected function locateExecutable( $path, $names, $versionInfo = false ) {
897 if ( !is_array( $names ) ) {
898 $names = array( $names );
901 foreach ( $names as $name ) {
902 $command = "$path/$name";
904 wfSuppressWarnings();
905 $file_exists = file_exists( $command );
908 if ( $file_exists ) {
909 if ( !$versionInfo ) {
913 $file = str_replace( '$1', $command, $versionInfo[0] );
915 # Should maybe be wfShellExec( $file), but runs into a ulimit, see
916 # http://www.mediawiki.org/w/index.php?title=New-installer_issues&diff=prev&oldid=335456
917 if ( strstr( `
$file`
, $versionInfo[1]) !== false ) {
927 * Checks if scripts located in the given directory can be executed via the given URL.
929 * Used only by environment checks.
931 public function dirIsExecutable( $dir, $url ) {
932 $scriptTypes = array(
934 "<?php echo 'ex' . 'ec';",
935 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
939 // it would be good to check other popular languages here, but it'll be slow.
941 wfSuppressWarnings();
943 foreach ( $scriptTypes as $ext => $contents ) {
944 foreach ( $contents as $source ) {
945 $file = 'exectest.' . $ext;
947 if ( !file_put_contents( $dir . $file, $source ) ) {
951 $text = Http
::get( $url . $file );
952 unlink( $dir . $file );
954 if ( $text == 'exec' ) {