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(
86 'envCheckRegisterGlobals',
89 'envCheckMagicQuotes',
90 'envCheckMagicSybase',
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() {
147 foreach ( $this->envChecks
as $check ) {
148 $status = $this->$check();
149 if ( $status === false ) {
154 $this->setVar( '_Environment', $good );
157 $this->showMessage( 'config-env-good' );
159 $this->showMessage( 'config-env-bad' );
166 * Set a MW configuration variable, or internal installer configuration variable.
168 * @param $name String
169 * @param $value Mixed
171 public function setVar( $name, $value ) {
172 $this->settings
[$name] = $value;
176 * Get an MW configuration variable, or internal installer configuration variable.
177 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
178 * Installer variables are typically prefixed by an underscore.
180 * @param $name String
181 * @param $default Mixed
185 public function getVar( $name, $default = null ) {
186 if ( !isset( $this->settings
[$name] ) ) {
189 return $this->settings
[$name];
194 * Get an instance of DatabaseInstaller for the specified DB type.
196 * @param $type Mixed: DB installer for which is needed, false to use default.
198 * @return DatabaseInstaller
200 public function getDBInstaller( $type = false ) {
202 $type = $this->getVar( 'wgDBtype' );
205 $type = strtolower( $type );
207 if ( !isset( $this->dbInstallers
[$type] ) ) {
208 $class = ucfirst( $type ). 'Installer';
209 $this->dbInstallers
[$type] = new $class( $this );
212 return $this->dbInstallers
[$type];
216 * Determine if LocalSettings exists. If it does, return an appropriate
217 * status for whether upgrading is enabled or not.
221 public function getLocalSettingsStatus() {
224 $status = Status
::newGood();
226 wfSuppressWarnings();
227 $ls = file_exists( "$IP/LocalSettings.php" );
231 require( "$IP/includes/DefaultSettings.php" );
232 require_once( "$IP/LocalSettings.php" );
233 $vars = get_defined_vars();
234 if( isset( $vars['wgUpgradeKey'] ) && $vars['wgUpgradeKey'] ) {
235 $status->warning( 'config-localsettings-upgrade' );
236 $this->setVar( '_UpgradeKey', $vars['wgUpgradeKey' ] );
238 $status->fatal( 'config-localsettings-noupgrade' );
246 * Get a fake password for sending back to the user in HTML.
247 * This is a security mechanism to avoid compromise of the password in the
248 * event of session ID compromise.
250 * @param $realPassword String
254 public function getFakePassword( $realPassword ) {
255 return str_repeat( '*', strlen( $realPassword ) );
259 * Set a variable which stores a password, except if the new value is a
260 * fake password in which case leave it as it is.
262 * @param $name String
263 * @param $value Mixed
265 public function setPassword( $name, $value ) {
266 if ( !preg_match( '/^\*+$/', $value ) ) {
267 $this->setVar( $name, $value );
272 * On POSIX systems return the primary group of the webserver we're running under.
273 * On other systems just returns null.
275 * This is used to advice the user that he should chgrp his config/data/images directory as the
276 * webserver user before he can install.
278 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
282 public static function maybeGetWebserverPrimaryGroup() {
283 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
284 # I don't know this, this isn't UNIX.
288 # posix_getegid() *not* getmygid() because we want the group of the webserver,
289 # not whoever owns the current script.
290 $gid = posix_getegid();
291 $getpwuid = posix_getpwuid( $gid );
292 $group = $getpwuid['name'];
298 * Convert wikitext $text to HTML.
300 * This is potentially error prone since many parser features require a complete
301 * installed MW database. The solution is to just not use those features when you
302 * write your messages. This appears to work well enough. Basic formatting and
303 * external links work just fine.
305 * But in case a translator decides to throw in a #ifexist or internal link or
306 * whatever, this function is guarded to catch the attempted DB access and to present
307 * some fallback text.
309 * @param $text String
310 * @param $lineStart Boolean
313 public function parse( $text, $lineStart = false ) {
317 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
318 $html = $out->getText();
319 } catch ( DBAccessError
$e ) {
320 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
322 if ( !empty( $this->debug
) ) {
323 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
333 * @param $installer DatabaseInstaller
337 public function installTables( DatabaseInstaller
&$installer ) {
338 $status = $installer->createTables();
340 if( $status->isOK() ) {
341 LBFactory
::enableBackend();
348 * Exports all wg* variables stored by the installer into global scope.
350 public function exportVars() {
351 foreach ( $this->settings
as $name => $value ) {
352 if ( substr( $name, 0, 2 ) == 'wg' ) {
353 $GLOBALS[$name] = $value;
359 * Environment check for DB types.
361 protected function envCheckDB() {
364 $compiledDBs = array();
365 $goodNames = array();
368 foreach ( self
::getDBTypes() as $name ) {
369 $db = $this->getDBInstaller( $name );
370 $readableName = wfMsg( 'config-type-' . $name );
372 if ( $db->isCompiled() ) {
373 $compiledDBs[] = $name;
374 $goodNames[] = $readableName;
377 $allNames[] = $readableName;
380 $this->setVar( '_CompiledDBs', $compiledDBs );
382 if ( !$compiledDBs ) {
383 $this->showMessage( 'config-no-db' );
384 // FIXME: this only works for the web installer!
385 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
389 // Check for FTS3 full-text search module
390 $sqlite = $this->getDBInstaller( 'sqlite' );
391 if ( $sqlite->isCompiled() ) {
392 $db = new DatabaseSqliteStandalone( ':memory:' );
393 if( $db->getFulltextSearchModule() != 'FTS3' ) {
394 $this->showMessage( 'config-no-fts3' );
400 * Environment check for register_globals.
402 protected function envCheckRegisterGlobals() {
403 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
404 $this->showMessage( 'config-register-globals' );
409 * Some versions of libxml+PHP break < and > encoding horribly
411 protected function envCheckBrokenXML() {
412 $test = new PhpXmlBugTester();
414 $this->showMessage( 'config-brokenlibxml' );
420 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
421 * reference parameters to __call() are not converted to null
423 protected function envCheckPHP531() {
424 $test = new PhpRefCallBugTester
;
427 $this->showMessage( 'config-using531' );
433 * Environment check for magic_quotes_runtime.
435 protected function envCheckMagicQuotes() {
436 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
437 $this->showMessage( 'config-magic-quotes-runtime' );
443 * Environment check for magic_quotes_sybase.
445 protected function envCheckMagicSybase() {
446 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
447 $this->showMessage( 'config-magic-quotes-sybase' );
453 * Environment check for mbstring.func_overload.
455 protected function envCheckMbstring() {
456 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
457 $this->showMessage( 'config-mbstring' );
463 * Environment check for zend.ze1_compatibility_mode.
465 protected function envCheckZE1() {
466 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
467 $this->showMessage( 'config-ze1' );
473 * Environment check for safe_mode.
475 protected function envCheckSafeMode() {
476 if ( wfIniGetBool( 'safe_mode' ) ) {
477 $this->setVar( '_SafeMode', true );
478 $this->showMessage( 'config-safe-mode' );
483 * Environment check for the XML module.
485 protected function envCheckXML() {
486 if ( !function_exists( "utf8_encode" ) ) {
487 $this->showMessage( 'config-xml-bad' );
493 * Environment check for the PCRE module.
495 protected function envCheckPCRE() {
496 if ( !function_exists( 'preg_match' ) ) {
497 $this->showMessage( 'config-pcre' );
500 wfSuppressWarnings();
501 $regexd = preg_replace( '/[\x{0400}-\x{04FF}]/u', '', '-АБВГД-' );
503 if ( $regexd != '--' ) {
504 $this->showMessage( 'config-pcre-no-utf8' );
510 * Environment check for available memory.
512 protected function envCheckMemory() {
513 $limit = ini_get( 'memory_limit' );
515 if ( !$limit ||
$limit == -1 ) {
519 $n = intval( $limit );
521 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $limit ), $m ) ) {
522 $n = intval( $m[1] * ( 1024 * 1024 ) );
525 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
526 $newLimit = "{$this->minMemorySize}M";
528 if( ini_set( "memory_limit", $newLimit ) === false ) {
529 $this->showMessage( 'config-memory-bad', $limit );
531 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
532 $this->setVar( '_RaiseMemory', true );
540 * Environment check for compiled object cache types.
542 protected function envCheckCache() {
544 foreach ( $this->objectCaches
as $name => $function ) {
545 if ( function_exists( $function ) ) {
546 $caches[$name] = true;
551 $this->showMessage( 'config-no-cache' );
554 $this->setVar( '_Caches', $caches );
558 * Search for GNU diff3.
560 protected function envCheckDiff3() {
561 $names = array( "gdiff3", "diff3", "diff3.exe" );
562 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
564 $diff3 = $this->locateExecutableInDefaultPaths( $names, $versionInfo );
567 $this->setVar( 'wgDiff3', $diff3 );
569 $this->setVar( 'wgDiff3', false );
570 $this->showMessage( 'config-diff3-bad' );
575 * Environment check for ImageMagick and GD.
577 protected function envCheckGraphics() {
578 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
579 $convert = $this->locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
582 $this->setVar( 'wgImageMagickConvertCommand', $convert );
583 $this->showMessage( 'config-imagemagick', $convert );
585 } elseif ( function_exists( 'imagejpeg' ) ) {
586 $this->showMessage( 'config-gd' );
589 $this->showMessage( 'no-scaling' );
594 * Environment check for setting $IP and $wgScriptPath.
596 protected function envCheckPath() {
598 $IP = dirname( dirname( dirname( __FILE__
) ) );
600 $this->setVar( 'IP', $IP );
602 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
603 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
604 // to get the path to the current script... hopefully it's reliable. SIGH
605 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
606 $path = $_SERVER['PHP_SELF'];
607 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
608 $path = $_SERVER['SCRIPT_NAME'];
609 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
610 // Some kind soul has set it for us already (e.g. debconf)
613 $this->showMessage( 'config-no-uri' );
617 $uri = preg_replace( '{^(.*)/config.*$}', '$1', $path );
618 $this->setVar( 'wgScriptPath', $uri );
622 * Environment check for setting the preferred PHP file extension.
624 protected function envCheckExtension() {
625 // FIXME: detect this properly
626 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
631 $this->setVar( 'wgScriptExtension', ".$ext" );
637 protected function envCheckShellLocale() {
638 $os = php_uname( 's' );
639 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
641 if ( !in_array( $os, $supported ) ) {
645 # Get a list of available locales.
647 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
653 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
654 $candidatesByLocale = array();
655 $candidatesByLang = array();
657 foreach ( $lines as $line ) {
658 if ( $line === '' ) {
662 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
666 list( $all, $lang, $territory, $charset, $modifier ) = $m;
668 $candidatesByLocale[$m[0]] = $m;
669 $candidatesByLang[$lang][] = $m;
672 # Try the current value of LANG.
673 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
674 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
678 # Try the most common ones.
679 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
680 foreach ( $commonLocales as $commonLocale ) {
681 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
682 $this->setVar( 'wgShellLocale', $commonLocale );
687 # Is there an available locale in the Wiki's language?
688 $wikiLang = $this->getVar( 'wgLanguageCode' );
690 if ( isset( $candidatesByLang[$wikiLang] ) ) {
691 $m = reset( $candidatesByLang[$wikiLang] );
692 $this->setVar( 'wgShellLocale', $m[0] );
696 # Are there any at all?
697 if ( count( $candidatesByLocale ) ) {
698 $m = reset( $candidatesByLocale );
699 $this->setVar( 'wgShellLocale', $m[0] );
710 protected function envCheckUploadsDirectory() {
711 global $IP, $wgServer;
713 $dir = $IP . '/images/';
714 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
715 $safe = !$this->dirIsExecutable( $dir, $url );
720 $this->showMessage( 'config-uploads-not-safe', $dir );
725 * Convert a hex string representing a Unicode code point to that code point.
729 protected function unicodeChar( $c ) {
733 } else if ($c <= 0x7FF) {
734 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
735 } else if ($c <= 0xFFFF) {
736 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
737 . chr(0x80 |
$c & 0x3F);
738 } else if ($c <= 0x10FFFF) {
739 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
740 . chr(0x80 |
$c >> 6 & 0x3F)
741 . chr(0x80 |
$c & 0x3F);
749 * Check the libicu version
751 protected function envCheckLibicu() {
752 $utf8 = function_exists( 'utf8_normalize' );
753 $intl = function_exists( 'normalizer_normalize' );
756 * This needs to be updated something that the latest libicu
757 * will properly normalize. This normalization was found at
758 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
759 * Note that we use the hex representation to create the code
760 * points in order to avoid any Unicode-destroying during transit.
762 $not_normal_c = $this->unicodeChar("FA6C");
763 $normal_c = $this->unicodeChar("242EE");
765 $useNormalizer = 'php';
766 $needsUpdate = false;
769 * We're going to prefer the pecl extension here unless
770 * utf8_normalize is more up to date.
773 $useNormalizer = 'utf8';
774 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
775 if ( $utf8 !== $normal_c ) $needsUpdate = true;
778 $useNormalizer = 'intl';
779 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
780 if ( $intl !== $normal_c ) $needsUpdate = true;
783 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
784 if( $useNormalizer === 'php' ) {
785 $this->showMessage( 'config-unicode-pure-php-warning' );
787 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
789 $this->showMessage( 'config-unicode-update-warning' );
795 * Get an array of likely places we can find executables. Check a bunch
796 * of known Unix-like defaults, as well as the PATH environment variable
797 * (which should maybe make it work for Windows?)
801 protected static function getPossibleBinPaths() {
803 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
804 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
805 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
810 * Search a path for any of the given executable names. Returns the
811 * executable name if found. Also checks the version string returned
812 * by each executable.
814 * Used only by environment checks.
816 * @param $path String: path to search
817 * @param $names Array of executable names
818 * @param $versionInfo Boolean false or array with two members:
819 * 0 => Command to run for version check, with $1 for the full executable name
820 * 1 => String to compare the output with
822 * If $versionInfo is not false, only executables with a version
823 * matching $versionInfo[1] will be returned.
825 public static function locateExecutable( $path, $names, $versionInfo = false ) {
826 if ( !is_array( $names ) ) {
827 $names = array( $names );
830 foreach ( $names as $name ) {
831 $command = $path . DIRECTORY_SEPARATOR
. $name;
833 wfSuppressWarnings();
834 $file_exists = file_exists( $command );
837 if ( $file_exists ) {
838 if ( !$versionInfo ) {
842 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
843 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
852 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
853 * @see locateExecutable()
855 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
856 foreach( self
::getPossibleBinPaths() as $path ) {
857 $exe = self
::locateExecutable( $path, $names, $versionInfo );
858 if( $exe !== false ) {
866 * Checks if scripts located in the given directory can be executed via the given URL.
868 * Used only by environment checks.
870 public function dirIsExecutable( $dir, $url ) {
871 $scriptTypes = array(
873 "<?php echo 'ex' . 'ec';",
874 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
878 // it would be good to check other popular languages here, but it'll be slow.
880 wfSuppressWarnings();
882 foreach ( $scriptTypes as $ext => $contents ) {
883 foreach ( $contents as $source ) {
884 $file = 'exectest.' . $ext;
886 if ( !file_put_contents( $dir . $file, $source ) ) {
890 $text = Http
::get( $url . $file );
891 unlink( $dir . $file );
893 if ( $text == 'exec' ) {