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.php exists. If it does, return its variables,
217 * merged with those from AdminSettings.php, as an array.
221 public function getExistingLocalSettings() {
224 wfSuppressWarnings();
225 $_lsExists = file_exists( "$IP/LocalSettings.php" );
229 require( "$IP/includes/DefaultSettings.php" );
230 require( "$IP/LocalSettings.php" );
231 if ( file_exists( "$IP/AdminSettings.php" ) ) {
232 require( "$IP/AdminSettings.php" );
234 $vars = get_defined_vars();
235 unset( $vars['_lsExists'] );
243 * Get a fake password for sending back to the user in HTML.
244 * This is a security mechanism to avoid compromise of the password in the
245 * event of session ID compromise.
247 * @param $realPassword String
251 public function getFakePassword( $realPassword ) {
252 return str_repeat( '*', strlen( $realPassword ) );
256 * Set a variable which stores a password, except if the new value is a
257 * fake password in which case leave it as it is.
259 * @param $name String
260 * @param $value Mixed
262 public function setPassword( $name, $value ) {
263 if ( !preg_match( '/^\*+$/', $value ) ) {
264 $this->setVar( $name, $value );
269 * On POSIX systems return the primary group of the webserver we're running under.
270 * On other systems just returns null.
272 * This is used to advice the user that he should chgrp his config/data/images directory as the
273 * webserver user before he can install.
275 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
279 public static function maybeGetWebserverPrimaryGroup() {
280 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
281 # I don't know this, this isn't UNIX.
285 # posix_getegid() *not* getmygid() because we want the group of the webserver,
286 # not whoever owns the current script.
287 $gid = posix_getegid();
288 $getpwuid = posix_getpwuid( $gid );
289 $group = $getpwuid['name'];
295 * Convert wikitext $text to HTML.
297 * This is potentially error prone since many parser features require a complete
298 * installed MW database. The solution is to just not use those features when you
299 * write your messages. This appears to work well enough. Basic formatting and
300 * external links work just fine.
302 * But in case a translator decides to throw in a #ifexist or internal link or
303 * whatever, this function is guarded to catch the attempted DB access and to present
304 * some fallback text.
306 * @param $text String
307 * @param $lineStart Boolean
310 public function parse( $text, $lineStart = false ) {
314 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
315 $html = $out->getText();
316 } catch ( DBAccessError
$e ) {
317 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
319 if ( !empty( $this->debug
) ) {
320 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
327 public function getParserOptions() {
328 return $this->parserOptions
;
331 public function disableLinkPopups() {
332 $this->parserOptions
->setExternalLinkTarget( false );
335 public function restoreLinkPopups() {
336 global $wgExternalLinkTarget;
337 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
343 * @param $installer DatabaseInstaller
347 public function installTables( DatabaseInstaller
&$installer ) {
348 $status = $installer->createTables();
350 if( $status->isOK() ) {
351 LBFactory
::enableBackend();
358 * Exports all wg* variables stored by the installer into global scope.
360 public function exportVars() {
361 foreach ( $this->settings
as $name => $value ) {
362 if ( substr( $name, 0, 2 ) == 'wg' ) {
363 $GLOBALS[$name] = $value;
369 * Environment check for DB types.
371 protected function envCheckDB() {
374 $compiledDBs = array();
375 $goodNames = array();
378 foreach ( self
::getDBTypes() as $name ) {
379 $db = $this->getDBInstaller( $name );
380 $readableName = wfMsg( 'config-type-' . $name );
382 if ( $db->isCompiled() ) {
383 $compiledDBs[] = $name;
384 $goodNames[] = $readableName;
387 $allNames[] = $readableName;
390 $this->setVar( '_CompiledDBs', $compiledDBs );
392 if ( !$compiledDBs ) {
393 $this->showMessage( 'config-no-db' );
394 // FIXME: this only works for the web installer!
395 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
399 // Check for FTS3 full-text search module
400 $sqlite = $this->getDBInstaller( 'sqlite' );
401 if ( $sqlite->isCompiled() ) {
402 $db = new DatabaseSqliteStandalone( ':memory:' );
403 if( $db->getFulltextSearchModule() != 'FTS3' ) {
404 $this->showMessage( 'config-no-fts3' );
410 * Environment check for register_globals.
412 protected function envCheckRegisterGlobals() {
413 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
414 $this->showMessage( 'config-register-globals' );
419 * Some versions of libxml+PHP break < and > encoding horribly
421 protected function envCheckBrokenXML() {
422 $test = new PhpXmlBugTester();
424 $this->showMessage( 'config-brokenlibxml' );
430 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
431 * reference parameters to __call() are not converted to null
433 protected function envCheckPHP531() {
434 $test = new PhpRefCallBugTester
;
437 $this->showMessage( 'config-using531' );
443 * Environment check for magic_quotes_runtime.
445 protected function envCheckMagicQuotes() {
446 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
447 $this->showMessage( 'config-magic-quotes-runtime' );
453 * Environment check for magic_quotes_sybase.
455 protected function envCheckMagicSybase() {
456 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
457 $this->showMessage( 'config-magic-quotes-sybase' );
463 * Environment check for mbstring.func_overload.
465 protected function envCheckMbstring() {
466 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
467 $this->showMessage( 'config-mbstring' );
473 * Environment check for zend.ze1_compatibility_mode.
475 protected function envCheckZE1() {
476 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
477 $this->showMessage( 'config-ze1' );
483 * Environment check for safe_mode.
485 protected function envCheckSafeMode() {
486 if ( wfIniGetBool( 'safe_mode' ) ) {
487 $this->setVar( '_SafeMode', true );
488 $this->showMessage( 'config-safe-mode' );
493 * Environment check for the XML module.
495 protected function envCheckXML() {
496 if ( !function_exists( "utf8_encode" ) ) {
497 $this->showMessage( 'config-xml-bad' );
503 * Environment check for the PCRE module.
505 protected function envCheckPCRE() {
506 if ( !function_exists( 'preg_match' ) ) {
507 $this->showMessage( 'config-pcre' );
510 wfSuppressWarnings();
511 $regexd = preg_replace( '/[\x{0400}-\x{04FF}]/u', '', '-АБВГД-' );
513 if ( $regexd != '--' ) {
514 $this->showMessage( 'config-pcre-no-utf8' );
520 * Environment check for available memory.
522 protected function envCheckMemory() {
523 $limit = ini_get( 'memory_limit' );
525 if ( !$limit ||
$limit == -1 ) {
529 $n = intval( $limit );
531 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $limit ), $m ) ) {
532 $n = intval( $m[1] * ( 1024 * 1024 ) );
535 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
536 $newLimit = "{$this->minMemorySize}M";
538 if( ini_set( "memory_limit", $newLimit ) === false ) {
539 $this->showMessage( 'config-memory-bad', $limit );
541 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
542 $this->setVar( '_RaiseMemory', true );
550 * Environment check for compiled object cache types.
552 protected function envCheckCache() {
554 foreach ( $this->objectCaches
as $name => $function ) {
555 if ( function_exists( $function ) ) {
556 $caches[$name] = true;
561 $this->showMessage( 'config-no-cache' );
564 $this->setVar( '_Caches', $caches );
568 * Search for GNU diff3.
570 protected function envCheckDiff3() {
571 $names = array( "gdiff3", "diff3", "diff3.exe" );
572 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
574 $diff3 = $this->locateExecutableInDefaultPaths( $names, $versionInfo );
577 $this->setVar( 'wgDiff3', $diff3 );
579 $this->setVar( 'wgDiff3', false );
580 $this->showMessage( 'config-diff3-bad' );
585 * Environment check for ImageMagick and GD.
587 protected function envCheckGraphics() {
588 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
589 $convert = $this->locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
592 $this->setVar( 'wgImageMagickConvertCommand', $convert );
593 $this->showMessage( 'config-imagemagick', $convert );
595 } elseif ( function_exists( 'imagejpeg' ) ) {
596 $this->showMessage( 'config-gd' );
599 $this->showMessage( 'no-scaling' );
604 * Environment check for setting $IP and $wgScriptPath.
606 protected function envCheckPath() {
608 $IP = dirname( dirname( dirname( __FILE__
) ) );
610 $this->setVar( 'IP', $IP );
612 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
613 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
614 // to get the path to the current script... hopefully it's reliable. SIGH
615 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
616 $path = $_SERVER['PHP_SELF'];
617 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
618 $path = $_SERVER['SCRIPT_NAME'];
619 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
620 // Some kind soul has set it for us already (e.g. debconf)
623 $this->showMessage( 'config-no-uri' );
627 $uri = preg_replace( '{^(.*)/config.*$}', '$1', $path );
628 $this->setVar( 'wgScriptPath', $uri );
632 * Environment check for setting the preferred PHP file extension.
634 protected function envCheckExtension() {
635 // FIXME: detect this properly
636 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
641 $this->setVar( 'wgScriptExtension', ".$ext" );
647 protected function envCheckShellLocale() {
648 $os = php_uname( 's' );
649 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
651 if ( !in_array( $os, $supported ) ) {
655 # Get a list of available locales.
657 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
663 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
664 $candidatesByLocale = array();
665 $candidatesByLang = array();
667 foreach ( $lines as $line ) {
668 if ( $line === '' ) {
672 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
676 list( $all, $lang, $territory, $charset, $modifier ) = $m;
678 $candidatesByLocale[$m[0]] = $m;
679 $candidatesByLang[$lang][] = $m;
682 # Try the current value of LANG.
683 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
684 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
688 # Try the most common ones.
689 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
690 foreach ( $commonLocales as $commonLocale ) {
691 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
692 $this->setVar( 'wgShellLocale', $commonLocale );
697 # Is there an available locale in the Wiki's language?
698 $wikiLang = $this->getVar( 'wgLanguageCode' );
700 if ( isset( $candidatesByLang[$wikiLang] ) ) {
701 $m = reset( $candidatesByLang[$wikiLang] );
702 $this->setVar( 'wgShellLocale', $m[0] );
706 # Are there any at all?
707 if ( count( $candidatesByLocale ) ) {
708 $m = reset( $candidatesByLocale );
709 $this->setVar( 'wgShellLocale', $m[0] );
720 protected function envCheckUploadsDirectory() {
721 global $IP, $wgServer;
723 $dir = $IP . '/images/';
724 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
725 $safe = !$this->dirIsExecutable( $dir, $url );
730 $this->showMessage( 'config-uploads-not-safe', $dir );
735 * Convert a hex string representing a Unicode code point to that code point.
739 protected function unicodeChar( $c ) {
743 } else if ($c <= 0x7FF) {
744 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
745 } else if ($c <= 0xFFFF) {
746 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
747 . chr(0x80 |
$c & 0x3F);
748 } else if ($c <= 0x10FFFF) {
749 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
750 . chr(0x80 |
$c >> 6 & 0x3F)
751 . chr(0x80 |
$c & 0x3F);
759 * Check the libicu version
761 protected function envCheckLibicu() {
762 $utf8 = function_exists( 'utf8_normalize' );
763 $intl = function_exists( 'normalizer_normalize' );
766 * This needs to be updated something that the latest libicu
767 * will properly normalize. This normalization was found at
768 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
769 * Note that we use the hex representation to create the code
770 * points in order to avoid any Unicode-destroying during transit.
772 $not_normal_c = $this->unicodeChar("FA6C");
773 $normal_c = $this->unicodeChar("242EE");
775 $useNormalizer = 'php';
776 $needsUpdate = false;
779 * We're going to prefer the pecl extension here unless
780 * utf8_normalize is more up to date.
783 $useNormalizer = 'utf8';
784 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
785 if ( $utf8 !== $normal_c ) $needsUpdate = true;
788 $useNormalizer = 'intl';
789 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
790 if ( $intl !== $normal_c ) $needsUpdate = true;
793 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
794 if( $useNormalizer === 'php' ) {
795 $this->showMessage( 'config-unicode-pure-php-warning' );
797 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
799 $this->showMessage( 'config-unicode-update-warning' );
805 * Get an array of likely places we can find executables. Check a bunch
806 * of known Unix-like defaults, as well as the PATH environment variable
807 * (which should maybe make it work for Windows?)
811 protected static function getPossibleBinPaths() {
813 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
814 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
815 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
820 * Search a path for any of the given executable names. Returns the
821 * executable name if found. Also checks the version string returned
822 * by each executable.
824 * Used only by environment checks.
826 * @param $path String: path to search
827 * @param $names Array of executable names
828 * @param $versionInfo Boolean false or array with two members:
829 * 0 => Command to run for version check, with $1 for the full executable name
830 * 1 => String to compare the output with
832 * If $versionInfo is not false, only executables with a version
833 * matching $versionInfo[1] will be returned.
835 public static function locateExecutable( $path, $names, $versionInfo = false ) {
836 if ( !is_array( $names ) ) {
837 $names = array( $names );
840 foreach ( $names as $name ) {
841 $command = $path . DIRECTORY_SEPARATOR
. $name;
843 wfSuppressWarnings();
844 $file_exists = file_exists( $command );
847 if ( $file_exists ) {
848 if ( !$versionInfo ) {
852 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
853 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
862 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
863 * @see locateExecutable()
865 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
866 foreach( self
::getPossibleBinPaths() as $path ) {
867 $exe = self
::locateExecutable( $path, $names, $versionInfo );
868 if( $exe !== false ) {
876 * Checks if scripts located in the given directory can be executed via the given URL.
878 * Used only by environment checks.
880 public function dirIsExecutable( $dir, $url ) {
881 $scriptTypes = array(
883 "<?php echo 'ex' . 'ec';",
884 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
888 // it would be good to check other popular languages here, but it'll be slow.
890 wfSuppressWarnings();
892 foreach ( $scriptTypes as $ext => $contents ) {
893 foreach ( $contents as $source ) {
894 $file = 'exectest.' . $ext;
896 if ( !file_put_contents( $dir . $file, $source ) ) {
900 $text = Http
::get( $url . $file );
901 unlink( $dir . $file );
903 if ( $text == 'exec' ) {