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 upgrading is enabled 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 the 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 installTables( DatabaseInstaller
&$installer ) {
341 $status = $installer->createTables();
343 if( $status->isOK() ) {
344 LBFactory
::enableBackend();
351 * Exports all wg* variables stored by the installer into global scope.
353 public function exportVars() {
354 foreach ( $this->settings
as $name => $value ) {
355 if ( substr( $name, 0, 2 ) == 'wg' ) {
356 $GLOBALS[$name] = $value;
362 * Check if we're installing the latest version.
364 protected function envCheckMediaWikiVersion() {
367 if( !$this->getVar( '_ExternalHTTP' ) ) {
368 $this->showMessage( 'config-env-latest-disabled' );
372 $repository = wfGetRepository();
373 $currentVersion = $repository->getLatestCoreVersion();
375 if ( $currentVersion === false ) {
376 # For when the request is successful but there's e.g. some silly man in
377 # the middle firewall blocking us, e.g. one of those annoying airport ones
378 $this->showMessage( 'config-env-latest-can-not-check', $repository->getLocation() );
382 if( version_compare( $wgVersion, $currentVersion, '<' ) ) {
383 $this->showMessage( 'config-env-latest-old' );
384 // FIXME: this only works for the web installer!
385 $this->showHelpBox( 'config-env-latest-help', $wgVersion, $currentVersion );
386 } elseif( version_compare( $wgVersion, $currentVersion, '>' ) ) {
387 $this->showMessage( 'config-env-latest-new' );
389 $this->showMessage( 'config-env-latest-ok' );
394 * Environment check for DB types.
396 protected function envCheckDB() {
399 $compiledDBs = array();
400 $goodNames = array();
403 foreach ( self
::getDBTypes() as $name ) {
404 $db = $this->getDBInstaller( $name );
405 $readableName = wfMsg( 'config-type-' . $name );
407 if ( $db->isCompiled() ) {
408 $compiledDBs[] = $name;
409 $goodNames[] = $readableName;
412 $allNames[] = $readableName;
415 $this->setVar( '_CompiledDBs', $compiledDBs );
417 if ( !$compiledDBs ) {
418 $this->showMessage( 'config-no-db' );
419 // FIXME: this only works for the web installer!
420 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
424 $this->showMessage( 'config-have-db', $wgLang->listToText( $goodNames ), count( $goodNames ) );
426 // Check for FTS3 full-text search module
427 $sqlite = $this->getDBInstaller( 'sqlite' );
428 if ( $sqlite->isCompiled() ) {
429 $db = new DatabaseSqliteStandalone( ':memory:' );
430 $this->showMessage( $db->getFulltextSearchModule() == 'FTS3'
438 * Environment check for register_globals.
440 protected function envCheckRegisterGlobals() {
441 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
442 $this->showMessage( 'config-register-globals' );
447 * Some versions of libxml+PHP break < and > encoding horribly
449 protected function envCheckBrokenXML() {
450 $test = new PhpXmlBugTester();
452 $this->showMessage( 'config-brokenlibxml' );
458 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
459 * reference parameters to __call() are not converted to null
461 protected function envCheckPHP531() {
462 $test = new PhpRefCallBugTester
;
465 $this->showMessage( 'config-using531' );
471 * Environment check for magic_quotes_runtime.
473 protected function envCheckMagicQuotes() {
474 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
475 $this->showMessage( 'config-magic-quotes-runtime' );
481 * Environment check for magic_quotes_sybase.
483 protected function envCheckMagicSybase() {
484 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
485 $this->showMessage( 'config-magic-quotes-sybase' );
491 * Environment check for mbstring.func_overload.
493 protected function envCheckMbstring() {
494 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
495 $this->showMessage( 'config-mbstring' );
501 * Environment check for zend.ze1_compatibility_mode.
503 protected function envCheckZE1() {
504 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
505 $this->showMessage( 'config-ze1' );
511 * Environment check for safe_mode.
513 protected function envCheckSafeMode() {
514 if ( wfIniGetBool( 'safe_mode' ) ) {
515 $this->setVar( '_SafeMode', true );
516 $this->showMessage( 'config-safe-mode' );
521 * Environment check for the XML module.
523 protected function envCheckXML() {
524 if ( !function_exists( "utf8_encode" ) ) {
525 $this->showMessage( 'config-xml-bad' );
528 $this->showMessage( 'config-xml-good' );
532 * Environment check for the PCRE module.
534 protected function envCheckPCRE() {
535 if ( !function_exists( 'preg_match' ) ) {
536 $this->showMessage( 'config-pcre' );
539 wfSuppressWarnings();
540 $regexd = preg_replace( '/[\x{0400}-\x{04FF}]/u', '', '-АБВГД-' );
542 if ( $regexd != '--' ) {
543 $this->showMessage( 'config-pcre-no-utf8' );
549 * Environment check for available memory.
551 protected function envCheckMemory() {
552 $limit = ini_get( 'memory_limit' );
554 if ( !$limit ||
$limit == -1 ) {
555 $this->showMessage( 'config-memory-none' );
559 $n = intval( $limit );
561 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $limit ), $m ) ) {
562 $n = intval( $m[1] * ( 1024 * 1024 ) );
565 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
566 $newLimit = "{$this->minMemorySize}M";
568 if( ini_set( "memory_limit", $newLimit ) === false ) {
569 $this->showMessage( 'config-memory-bad', $limit );
571 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
572 $this->setVar( '_RaiseMemory', true );
575 $this->showMessage( 'config-memory-ok', $limit );
580 * Environment check for compiled object cache types.
582 protected function envCheckCache() {
585 foreach ( $this->objectCaches
as $name => $function ) {
586 if ( function_exists( $function ) ) {
587 $caches[$name] = true;
588 $this->showMessage( 'config-' . $name );
593 $this->showMessage( 'config-no-cache' );
596 $this->setVar( '_Caches', $caches );
600 * Search for GNU diff3.
602 protected function envCheckDiff3() {
603 $names = array( "gdiff3", "diff3", "diff3.exe" );
604 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
606 $diff3 = $this->locateExecutableInDefaultPaths( $names, $versionInfo );
609 $this->showMessage( 'config-diff3-good', $diff3 );
610 $this->setVar( 'wgDiff3', $diff3 );
612 $this->setVar( 'wgDiff3', false );
613 $this->showMessage( 'config-diff3-bad' );
618 * Environment check for ImageMagick and GD.
620 protected function envCheckGraphics() {
621 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
622 $convert = $this->locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
625 $this->setVar( 'wgImageMagickConvertCommand', $convert );
626 $this->showMessage( 'config-imagemagick', $convert );
628 } elseif ( function_exists( 'imagejpeg' ) ) {
629 $this->showMessage( 'config-gd' );
632 $this->showMessage( 'no-scaling' );
637 * Environment check for setting $IP and $wgScriptPath.
639 protected function envCheckPath() {
641 $IP = dirname( dirname( dirname( __FILE__
) ) );
643 $this->setVar( 'IP', $IP );
644 $this->showMessage( 'config-dir', $IP );
646 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
647 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
648 // to get the path to the current script... hopefully it's reliable. SIGH
649 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
650 $path = $_SERVER['PHP_SELF'];
651 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
652 $path = $_SERVER['SCRIPT_NAME'];
653 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
654 // Some kind soul has set it for us already (e.g. debconf)
657 $this->showMessage( 'config-no-uri' );
661 $uri = preg_replace( '{^(.*)/config.*$}', '$1', $path );
662 $this->setVar( 'wgScriptPath', $uri );
663 $this->showMessage( 'config-uri', $uri );
667 * Environment check for setting the preferred PHP file extension.
669 protected function envCheckExtension() {
670 // FIXME: detect this properly
671 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
677 $this->setVar( 'wgScriptExtension', ".$ext" );
678 $this->showMessage( 'config-file-extension', $ext );
684 protected function envCheckShellLocale() {
685 $os = php_uname( 's' );
686 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
688 if ( !in_array( $os, $supported ) ) {
692 # Get a list of available locales.
694 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
700 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
701 $candidatesByLocale = array();
702 $candidatesByLang = array();
704 foreach ( $lines as $line ) {
705 if ( $line === '' ) {
709 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
713 list( $all, $lang, $territory, $charset, $modifier ) = $m;
715 $candidatesByLocale[$m[0]] = $m;
716 $candidatesByLang[$lang][] = $m;
719 # Try the current value of LANG.
720 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
721 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
722 $this->showMessage( 'config-shell-locale', getenv( 'LANG' ) );
726 # Try the most common ones.
727 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
728 foreach ( $commonLocales as $commonLocale ) {
729 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
730 $this->setVar( 'wgShellLocale', $commonLocale );
731 $this->showMessage( 'config-shell-locale', $commonLocale );
736 # Is there an available locale in the Wiki's language?
737 $wikiLang = $this->getVar( 'wgLanguageCode' );
739 if ( isset( $candidatesByLang[$wikiLang] ) ) {
740 $m = reset( $candidatesByLang[$wikiLang] );
741 $this->setVar( 'wgShellLocale', $m[0] );
742 $this->showMessage( 'config-shell-locale', $m[0] );
746 # Are there any at all?
747 if ( count( $candidatesByLocale ) ) {
748 $m = reset( $candidatesByLocale );
749 $this->setVar( 'wgShellLocale', $m[0] );
750 $this->showMessage( 'config-shell-locale', $m[0] );
761 protected function envCheckUploadsDirectory() {
762 global $IP, $wgServer;
764 $dir = $IP . '/images/';
765 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
766 $safe = !$this->dirIsExecutable( $dir, $url );
769 $this->showMessage( 'config-uploads-safe' );
771 $this->showMessage( 'config-uploads-not-safe', $dir );
776 * Convert a hex string representing a Unicode code point to that code point.
780 protected function unicodeChar( $c ) {
784 } else if ($c <= 0x7FF) {
785 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
786 } else if ($c <= 0xFFFF) {
787 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
788 . chr(0x80 |
$c & 0x3F);
789 } else if ($c <= 0x10FFFF) {
790 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
791 . chr(0x80 |
$c >> 6 & 0x3F)
792 . chr(0x80 |
$c & 0x3F);
800 * Check the libicu version
802 protected function envCheckLibicu() {
803 $utf8 = function_exists( 'utf8_normalize' );
804 $intl = function_exists( 'normalizer_normalize' );
807 * This needs to be updated something that the latest libicu
808 * will properly normalize. This normalization was found at
809 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
810 * Note that we use the hex representation to create the code
811 * points in order to avoid any Unicode-destroying during transit.
813 $not_normal_c = $this->unicodeChar("FA6C");
814 $normal_c = $this->unicodeChar("242EE");
816 $useNormalizer = 'php';
817 $needsUpdate = false;
820 * We're going to prefer the pecl extension here unless
821 * utf8_normalize is more up to date.
824 $useNormalizer = 'utf8';
825 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
826 if ( $utf8 !== $normal_c ) $needsUpdate = true;
829 $useNormalizer = 'intl';
830 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
831 if ( $intl !== $normal_c ) $needsUpdate = true;
834 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
835 if( $useNormalizer === 'php' ) {
836 $this->showMessage( 'config-unicode-pure-php-warning' );
838 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
840 $this->showMessage( 'config-unicode-update-warning' );
846 * Get an array of likely places we can find executables. Check a bunch
847 * of known Unix-like defaults, as well as the PATH environment variable
848 * (which should maybe make it work for Windows?)
852 protected static function getPossibleBinPaths() {
854 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
855 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
856 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
861 * Search a path for any of the given executable names. Returns the
862 * executable name if found. Also checks the version string returned
863 * by each executable.
865 * Used only by environment checks.
867 * @param $path String: path to search
868 * @param $names Array of executable names
869 * @param $versionInfo Boolean false or array with two members:
870 * 0 => Command to run for version check, with $1 for the full executable name
871 * 1 => String to compare the output with
873 * If $versionInfo is not false, only executables with a version
874 * matching $versionInfo[1] will be returned.
876 public static function locateExecutable( $path, $names, $versionInfo = false ) {
877 if ( !is_array( $names ) ) {
878 $names = array( $names );
881 foreach ( $names as $name ) {
882 $command = $path . DIRECTORY_SEPARATOR
. $name;
884 wfSuppressWarnings();
885 $file_exists = file_exists( $command );
888 if ( $file_exists ) {
889 if ( !$versionInfo ) {
893 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
894 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
903 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
904 * @see locateExecutable()
906 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
907 foreach( self
::getPossibleBinPaths() as $path ) {
908 $exe = self
::locateExecutable( $path, $names, $versionInfo );
909 if( $exe !== false ) {
917 * Checks if scripts located in the given directory can be executed via the given URL.
919 * Used only by environment checks.
921 public function dirIsExecutable( $dir, $url ) {
922 $scriptTypes = array(
924 "<?php echo 'ex' . 'ec';",
925 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
929 // it would be good to check other popular languages here, but it'll be slow.
931 wfSuppressWarnings();
933 foreach ( $scriptTypes as $ext => $contents ) {
934 foreach ( $contents as $source ) {
935 $file = 'exectest.' . $ext;
937 if ( !file_put_contents( $dir . $file, $source ) ) {
941 $text = Http
::get( $url . $file );
942 unlink( $dir . $file );
944 if ( $text == 'exec' ) {