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" );
233 require( "$IP/includes/DefaultSettings.php" );
234 require( "$IP/LocalSettings.php" );
235 if ( file_exists( "$IP/AdminSettings.php" ) ) {
236 require( "$IP/AdminSettings.php" );
238 return get_defined_vars();
242 * Get a fake password for sending back to the user in HTML.
243 * This is a security mechanism to avoid compromise of the password in the
244 * event of session ID compromise.
246 * @param $realPassword String
250 public function getFakePassword( $realPassword ) {
251 return str_repeat( '*', strlen( $realPassword ) );
255 * Set a variable which stores a password, except if the new value is a
256 * fake password in which case leave it as it is.
258 * @param $name String
259 * @param $value Mixed
261 public function setPassword( $name, $value ) {
262 if ( !preg_match( '/^\*+$/', $value ) ) {
263 $this->setVar( $name, $value );
268 * On POSIX systems return the primary group of the webserver we're running under.
269 * On other systems just returns null.
271 * This is used to advice the user that he should chgrp his config/data/images directory as the
272 * webserver user before he can install.
274 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
278 public static function maybeGetWebserverPrimaryGroup() {
279 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
280 # I don't know this, this isn't UNIX.
284 # posix_getegid() *not* getmygid() because we want the group of the webserver,
285 # not whoever owns the current script.
286 $gid = posix_getegid();
287 $getpwuid = posix_getpwuid( $gid );
288 $group = $getpwuid['name'];
294 * Convert wikitext $text to HTML.
296 * This is potentially error prone since many parser features require a complete
297 * installed MW database. The solution is to just not use those features when you
298 * write your messages. This appears to work well enough. Basic formatting and
299 * external links work just fine.
301 * But in case a translator decides to throw in a #ifexist or internal link or
302 * whatever, this function is guarded to catch the attempted DB access and to present
303 * some fallback text.
305 * @param $text String
306 * @param $lineStart Boolean
309 public function parse( $text, $lineStart = false ) {
313 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
314 $html = $out->getText();
315 } catch ( DBAccessError
$e ) {
316 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
318 if ( !empty( $this->debug
) ) {
319 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
326 public function getParserOptions() {
327 return $this->parserOptions
;
330 public function disableLinkPopups() {
331 $this->parserOptions
->setExternalLinkTarget( false );
334 public function restoreLinkPopups() {
335 global $wgExternalLinkTarget;
336 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
342 * @param $installer DatabaseInstaller
346 public function installTables( DatabaseInstaller
&$installer ) {
347 $status = $installer->createTables();
349 if( $status->isOK() ) {
350 LBFactory
::enableBackend();
357 * Exports all wg* variables stored by the installer into global scope.
359 public function exportVars() {
360 foreach ( $this->settings
as $name => $value ) {
361 if ( substr( $name, 0, 2 ) == 'wg' ) {
362 $GLOBALS[$name] = $value;
368 * Environment check for DB types.
370 protected function envCheckDB() {
373 $compiledDBs = array();
374 $goodNames = array();
377 foreach ( self
::getDBTypes() as $name ) {
378 $db = $this->getDBInstaller( $name );
379 $readableName = wfMsg( 'config-type-' . $name );
381 if ( $db->isCompiled() ) {
382 $compiledDBs[] = $name;
383 $goodNames[] = $readableName;
386 $allNames[] = $readableName;
389 $this->setVar( '_CompiledDBs', $compiledDBs );
391 if ( !$compiledDBs ) {
392 $this->showMessage( 'config-no-db' );
393 // FIXME: this only works for the web installer!
394 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
398 // Check for FTS3 full-text search module
399 $sqlite = $this->getDBInstaller( 'sqlite' );
400 if ( $sqlite->isCompiled() ) {
401 $db = new DatabaseSqliteStandalone( ':memory:' );
402 if( $db->getFulltextSearchModule() != 'FTS3' ) {
403 $this->showMessage( 'config-no-fts3' );
409 * Environment check for register_globals.
411 protected function envCheckRegisterGlobals() {
412 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
413 $this->showMessage( 'config-register-globals' );
418 * Some versions of libxml+PHP break < and > encoding horribly
420 protected function envCheckBrokenXML() {
421 $test = new PhpXmlBugTester();
423 $this->showMessage( 'config-brokenlibxml' );
429 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
430 * reference parameters to __call() are not converted to null
432 protected function envCheckPHP531() {
433 $test = new PhpRefCallBugTester
;
436 $this->showMessage( 'config-using531' );
442 * Environment check for magic_quotes_runtime.
444 protected function envCheckMagicQuotes() {
445 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
446 $this->showMessage( 'config-magic-quotes-runtime' );
452 * Environment check for magic_quotes_sybase.
454 protected function envCheckMagicSybase() {
455 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
456 $this->showMessage( 'config-magic-quotes-sybase' );
462 * Environment check for mbstring.func_overload.
464 protected function envCheckMbstring() {
465 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
466 $this->showMessage( 'config-mbstring' );
472 * Environment check for zend.ze1_compatibility_mode.
474 protected function envCheckZE1() {
475 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
476 $this->showMessage( 'config-ze1' );
482 * Environment check for safe_mode.
484 protected function envCheckSafeMode() {
485 if ( wfIniGetBool( 'safe_mode' ) ) {
486 $this->setVar( '_SafeMode', true );
487 $this->showMessage( 'config-safe-mode' );
492 * Environment check for the XML module.
494 protected function envCheckXML() {
495 if ( !function_exists( "utf8_encode" ) ) {
496 $this->showMessage( 'config-xml-bad' );
502 * Environment check for the PCRE module.
504 protected function envCheckPCRE() {
505 if ( !function_exists( 'preg_match' ) ) {
506 $this->showMessage( 'config-pcre' );
509 wfSuppressWarnings();
510 $regexd = preg_replace( '/[\x{0400}-\x{04FF}]/u', '', '-АБВГД-' );
512 if ( $regexd != '--' ) {
513 $this->showMessage( 'config-pcre-no-utf8' );
519 * Environment check for available memory.
521 protected function envCheckMemory() {
522 $limit = ini_get( 'memory_limit' );
524 if ( !$limit ||
$limit == -1 ) {
528 $n = intval( $limit );
530 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $limit ), $m ) ) {
531 $n = intval( $m[1] * ( 1024 * 1024 ) );
534 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
535 $newLimit = "{$this->minMemorySize}M";
537 if( ini_set( "memory_limit", $newLimit ) === false ) {
538 $this->showMessage( 'config-memory-bad', $limit );
540 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
541 $this->setVar( '_RaiseMemory', true );
549 * Environment check for compiled object cache types.
551 protected function envCheckCache() {
553 foreach ( $this->objectCaches
as $name => $function ) {
554 if ( function_exists( $function ) ) {
555 $caches[$name] = true;
560 $this->showMessage( 'config-no-cache' );
563 $this->setVar( '_Caches', $caches );
567 * Search for GNU diff3.
569 protected function envCheckDiff3() {
570 $names = array( "gdiff3", "diff3", "diff3.exe" );
571 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
573 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
576 $this->setVar( 'wgDiff3', $diff3 );
578 $this->setVar( 'wgDiff3', false );
579 $this->showMessage( 'config-diff3-bad' );
584 * Environment check for ImageMagick and GD.
586 protected function envCheckGraphics() {
587 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
588 $convert = self
::locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
591 $this->setVar( 'wgImageMagickConvertCommand', $convert );
592 $this->showMessage( 'config-imagemagick', $convert );
594 } elseif ( function_exists( 'imagejpeg' ) ) {
595 $this->showMessage( 'config-gd' );
598 $this->showMessage( 'no-scaling' );
603 * Environment check for setting $IP and $wgScriptPath.
605 protected function envCheckPath() {
607 $IP = dirname( dirname( dirname( __FILE__
) ) );
609 $this->setVar( 'IP', $IP );
611 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
612 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
613 // to get the path to the current script... hopefully it's reliable. SIGH
614 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
615 $path = $_SERVER['PHP_SELF'];
616 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
617 $path = $_SERVER['SCRIPT_NAME'];
618 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
619 // Some kind soul has set it for us already (e.g. debconf)
622 $this->showMessage( 'config-no-uri' );
626 $uri = preg_replace( '{^(.*)/config.*$}', '$1', $path );
627 $this->setVar( 'wgScriptPath', $uri );
631 * Environment check for setting the preferred PHP file extension.
633 protected function envCheckExtension() {
634 // FIXME: detect this properly
635 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
640 $this->setVar( 'wgScriptExtension', ".$ext" );
646 protected function envCheckShellLocale() {
647 $os = php_uname( 's' );
648 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
650 if ( !in_array( $os, $supported ) ) {
654 # Get a list of available locales.
656 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
662 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
663 $candidatesByLocale = array();
664 $candidatesByLang = array();
666 foreach ( $lines as $line ) {
667 if ( $line === '' ) {
671 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
675 list( $all, $lang, $territory, $charset, $modifier ) = $m;
677 $candidatesByLocale[$m[0]] = $m;
678 $candidatesByLang[$lang][] = $m;
681 # Try the current value of LANG.
682 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
683 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
687 # Try the most common ones.
688 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
689 foreach ( $commonLocales as $commonLocale ) {
690 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
691 $this->setVar( 'wgShellLocale', $commonLocale );
696 # Is there an available locale in the Wiki's language?
697 $wikiLang = $this->getVar( 'wgLanguageCode' );
699 if ( isset( $candidatesByLang[$wikiLang] ) ) {
700 $m = reset( $candidatesByLang[$wikiLang] );
701 $this->setVar( 'wgShellLocale', $m[0] );
705 # Are there any at all?
706 if ( count( $candidatesByLocale ) ) {
707 $m = reset( $candidatesByLocale );
708 $this->setVar( 'wgShellLocale', $m[0] );
719 protected function envCheckUploadsDirectory() {
720 global $IP, $wgServer;
722 $dir = $IP . '/images/';
723 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
724 $safe = !$this->dirIsExecutable( $dir, $url );
729 $this->showMessage( 'config-uploads-not-safe', $dir );
734 * Convert a hex string representing a Unicode code point to that code point.
738 protected function unicodeChar( $c ) {
742 } else if ($c <= 0x7FF) {
743 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
744 } else if ($c <= 0xFFFF) {
745 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
746 . chr(0x80 |
$c & 0x3F);
747 } else if ($c <= 0x10FFFF) {
748 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
749 . chr(0x80 |
$c >> 6 & 0x3F)
750 . chr(0x80 |
$c & 0x3F);
758 * Check the libicu version
760 protected function envCheckLibicu() {
761 $utf8 = function_exists( 'utf8_normalize' );
762 $intl = function_exists( 'normalizer_normalize' );
765 * This needs to be updated something that the latest libicu
766 * will properly normalize. This normalization was found at
767 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
768 * Note that we use the hex representation to create the code
769 * points in order to avoid any Unicode-destroying during transit.
771 $not_normal_c = $this->unicodeChar("FA6C");
772 $normal_c = $this->unicodeChar("242EE");
774 $useNormalizer = 'php';
775 $needsUpdate = false;
778 * We're going to prefer the pecl extension here unless
779 * utf8_normalize is more up to date.
782 $useNormalizer = 'utf8';
783 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
784 if ( $utf8 !== $normal_c ) $needsUpdate = true;
787 $useNormalizer = 'intl';
788 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
789 if ( $intl !== $normal_c ) $needsUpdate = true;
792 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
793 if( $useNormalizer === 'php' ) {
794 $this->showMessage( 'config-unicode-pure-php-warning' );
796 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
798 $this->showMessage( 'config-unicode-update-warning' );
804 * Get an array of likely places we can find executables. Check a bunch
805 * of known Unix-like defaults, as well as the PATH environment variable
806 * (which should maybe make it work for Windows?)
810 protected static function getPossibleBinPaths() {
812 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
813 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
814 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
819 * Search a path for any of the given executable names. Returns the
820 * executable name if found. Also checks the version string returned
821 * by each executable.
823 * Used only by environment checks.
825 * @param $path String: path to search
826 * @param $names Array of executable names
827 * @param $versionInfo Boolean false or array with two members:
828 * 0 => Command to run for version check, with $1 for the full executable name
829 * 1 => String to compare the output with
831 * If $versionInfo is not false, only executables with a version
832 * matching $versionInfo[1] will be returned.
834 public static function locateExecutable( $path, $names, $versionInfo = false ) {
835 if ( !is_array( $names ) ) {
836 $names = array( $names );
839 foreach ( $names as $name ) {
840 $command = $path . DIRECTORY_SEPARATOR
. $name;
842 wfSuppressWarnings();
843 $file_exists = file_exists( $command );
846 if ( $file_exists ) {
847 if ( !$versionInfo ) {
851 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
852 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
861 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
862 * @see locateExecutable()
864 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
865 foreach( self
::getPossibleBinPaths() as $path ) {
866 $exe = self
::locateExecutable( $path, $names, $versionInfo );
867 if( $exe !== false ) {
875 * Checks if scripts located in the given directory can be executed via the given URL.
877 * Used only by environment checks.
879 public function dirIsExecutable( $dir, $url ) {
880 $scriptTypes = array(
882 "<?php echo 'ex' . 'ec';",
883 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
887 // it would be good to check other popular languages here, but it'll be slow.
889 wfSuppressWarnings();
891 foreach ( $scriptTypes as $ext => $contents ) {
892 foreach ( $contents as $source ) {
893 $file = 'exectest.' . $ext;
895 if ( !file_put_contents( $dir . $file, $source ) ) {
899 $text = Http
::get( $url . $file );
900 unlink( $dir . $file );
902 if ( $text == 'exec' ) {