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
{
32 * Cached DB installer instances, access using getDBInstaller().
36 protected $dbInstallers = array();
39 * Minimum memory size in MB.
43 protected $minMemorySize = 50;
46 * Cached Title, used by parse().
50 protected $parserTitle;
53 * Cached ParserOptions, used by parse().
57 protected $parserOptions;
60 * Known database types. These correspond to the class names <type>Installer,
61 * and are also MediaWiki database types valid for $wgDBtype.
63 * To add a new type, create a <type>Installer class and a Database<type>
64 * class, and add a config-type-<type> message to MessagesEn.php.
68 protected static $dbTypes = array(
76 * A list of environment check methods called by doEnvironmentChecks().
77 * These may output warnings using showMessage(), and/or abort the
78 * installation process by returning false.
82 protected $envChecks = array(
84 'envCheckRegisterGlobals',
87 'envCheckMagicQuotes',
88 'envCheckMagicSybase',
100 'envCheckShellLocale',
101 'envCheckUploadsDirectory',
106 * MediaWiki configuration globals that will eventually be passed through
107 * to LocalSettings.php. The names only are given here, the defaults
108 * typically come from DefaultSettings.php.
112 protected $defaultVarNames = array(
124 'wgEmailAuthentication',
127 'wgImageMagickConvertCommand',
132 'wgDeletedDirectory',
137 'wgUseInstantCommons',
143 * Variables that are stored alongside globals, and are used for any
144 * configuration of the installation process aside from the MediaWiki
145 * configuration. Map of names to defaults.
149 protected $internalDefaults = array(
151 '_Environment' => false,
152 '_CompiledDBs' => array(),
153 '_SafeMode' => false,
154 '_RaiseMemory' => false,
155 '_UpgradeDone' => false,
156 '_InstallDone' => false,
157 '_Caches' => array(),
158 '_InstallUser' => 'root',
159 '_InstallPassword' => '',
160 '_SameAccount' => true,
161 '_CreateDBAccount' => false,
162 '_NamespaceType' => 'site-name',
163 '_AdminName' => '', // will be set later, when the user selects language
164 '_AdminPassword' => '',
165 '_AdminPassword2' => '',
167 '_Subscribe' => false,
168 '_SkipOptional' => 'continue',
169 '_RightsProfile' => 'wiki',
170 '_LicenseCode' => 'none',
172 '_Extensions' => array(),
173 '_MemCachedServers' => '',
174 '_UpgradeKeySupplied' => false,
175 '_ExistingDBSettings' => false,
179 * The actual list of installation steps. This will be initialized by getInstallSteps()
183 private $installSteps = array();
186 * Extra steps for installation, for things like DatabaseInstallers to modify
190 protected $extraInstallSteps = array();
193 * Known object cache types and the functions used to test for their existence.
197 protected $objectCaches = array(
198 'xcache' => 'xcache_get',
199 'apc' => 'apc_fetch',
200 'eaccel' => 'eaccelerator_get',
201 'wincache' => 'wincache_ucache_get'
205 * User rights profiles.
209 public $rightsProfiles = array(
212 '*' => array( 'edit' => false )
216 'createaccount' => false,
222 'createaccount' => false,
234 public $licenses = array(
236 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
237 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
239 'cc-by-nc-sa' => array(
240 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
241 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
244 'url' => 'http://creativecommons.org/licenses/publicdomain/',
245 'icon' => '{$wgStylePath}/common/images/public-domain.png',
248 'url' => 'http://www.gnu.org/licenses/old-licenses/fdl-1.2.html',
249 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
251 'gfdl-current' => array(
252 'url' => 'http://www.gnu.org/copyleft/fdl.html',
253 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
260 'cc-choose' => array(
261 // Details will be filled in by the selector.
269 * URL to mediawiki-announce subscription
271 protected $mediaWikiAnnounceUrl = 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
274 * Supported language codes for Mailman
276 protected $mediaWikiAnnounceLanguages = array(
277 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
278 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
279 'sl', 'sr', 'sv', 'tr', 'uk'
283 * UI interface for displaying a short message
284 * The parameters are like parameters to wfMsg().
285 * The messages will be in wikitext format, which will be converted to an
286 * output format such as HTML or text before being sent to the user.
288 public abstract function showMessage( $msg /*, ... */ );
291 * Show a message to the installing user by using a Status object
292 * @param $status Status
294 public abstract function showStatusMessage( Status
$status );
297 * Constructor, always call this from child classes.
299 public function __construct() {
300 global $wgExtensionMessagesFiles, $wgUser, $wgHooks;
302 // Disable the i18n cache and LoadBalancer
303 Language
::getLocalisationCache()->disableBackend();
304 LBFactory
::disableBackend();
306 // Load the installer's i18n file.
307 $wgExtensionMessagesFiles['MediawikiInstaller'] =
308 dirname( __FILE__
) . '/Installer.i18n.php';
310 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
311 $wgUser = User
::newFromId( 0 );
313 // Set our custom <doclink> hook.
314 $wgHooks['ParserFirstCallInit'][] = array( $this, 'registerDocLink' );
316 $this->settings
= $this->internalDefaults
;
318 foreach ( $this->defaultVarNames
as $var ) {
319 $this->settings
[$var] = $GLOBALS[$var];
322 foreach ( self
::getDBTypes() as $type ) {
323 $installer = $this->getDBInstaller( $type );
325 if ( !$installer->isCompiled() ) {
329 $defaults = $installer->getGlobalDefaults();
331 foreach ( $installer->getGlobalNames() as $var ) {
332 if ( isset( $defaults[$var] ) ) {
333 $this->settings
[$var] = $defaults[$var];
335 $this->settings
[$var] = $GLOBALS[$var];
340 $this->parserTitle
= Title
::newFromText( 'Installer' );
341 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
342 $this->parserOptions
->setEditSection( false );
346 * Get a list of known DB types.
348 public static function getDBTypes() {
349 return self
::$dbTypes;
353 * Do initial checks of the PHP environment. Set variables according to
354 * the observed environment.
356 * It's possible that this may be called under the CLI SAPI, not the SAPI
357 * that the wiki will primarily run under. In that case, the subclass should
358 * initialise variables such as wgScriptPath, before calling this function.
360 * Under the web subclass, it can already be assumed that PHP 5+ is in use
361 * and that sessions are working.
365 public function doEnvironmentChecks() {
366 $this->showMessage( 'config-env-php', phpversion() );
370 foreach ( $this->envChecks
as $check ) {
371 $status = $this->$check();
372 if ( $status === false ) {
377 $this->setVar( '_Environment', $good );
379 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
383 * Set a MW configuration variable, or internal installer configuration variable.
385 * @param $name String
386 * @param $value Mixed
388 public function setVar( $name, $value ) {
389 $this->settings
[$name] = $value;
393 * Get an MW configuration variable, or internal installer configuration variable.
394 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
395 * Installer variables are typically prefixed by an underscore.
397 * @param $name String
398 * @param $default Mixed
402 public function getVar( $name, $default = null ) {
403 if ( !isset( $this->settings
[$name] ) ) {
406 return $this->settings
[$name];
411 * Get an instance of DatabaseInstaller for the specified DB type.
413 * @param $type Mixed: DB installer for which is needed, false to use default.
415 * @return DatabaseInstaller
417 public function getDBInstaller( $type = false ) {
419 $type = $this->getVar( 'wgDBtype' );
422 $type = strtolower( $type );
424 if ( !isset( $this->dbInstallers
[$type] ) ) {
425 $class = ucfirst( $type ). 'Installer';
426 $this->dbInstallers
[$type] = new $class( $this );
429 return $this->dbInstallers
[$type];
433 * Determine if LocalSettings.php exists. If it does, return its variables,
434 * merged with those from AdminSettings.php, as an array.
438 public function getExistingLocalSettings() {
441 wfSuppressWarnings();
442 $_lsExists = file_exists( "$IP/LocalSettings.php" );
450 require( "$IP/includes/DefaultSettings.php" );
451 require( "$IP/LocalSettings.php" );
452 if ( file_exists( "$IP/AdminSettings.php" ) ) {
453 require( "$IP/AdminSettings.php" );
455 return get_defined_vars();
459 * Get a fake password for sending back to the user in HTML.
460 * This is a security mechanism to avoid compromise of the password in the
461 * event of session ID compromise.
463 * @param $realPassword String
467 public function getFakePassword( $realPassword ) {
468 return str_repeat( '*', strlen( $realPassword ) );
472 * Set a variable which stores a password, except if the new value is a
473 * fake password in which case leave it as it is.
475 * @param $name String
476 * @param $value Mixed
478 public function setPassword( $name, $value ) {
479 if ( !preg_match( '/^\*+$/', $value ) ) {
480 $this->setVar( $name, $value );
485 * On POSIX systems return the primary group of the webserver we're running under.
486 * On other systems just returns null.
488 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
489 * webserver user before he can install.
491 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
495 public static function maybeGetWebserverPrimaryGroup() {
496 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
497 # I don't know this, this isn't UNIX.
501 # posix_getegid() *not* getmygid() because we want the group of the webserver,
502 # not whoever owns the current script.
503 $gid = posix_getegid();
504 $getpwuid = posix_getpwuid( $gid );
505 $group = $getpwuid['name'];
511 * Convert wikitext $text to HTML.
513 * This is potentially error prone since many parser features require a complete
514 * installed MW database. The solution is to just not use those features when you
515 * write your messages. This appears to work well enough. Basic formatting and
516 * external links work just fine.
518 * But in case a translator decides to throw in a #ifexist or internal link or
519 * whatever, this function is guarded to catch the attempted DB access and to present
520 * some fallback text.
522 * @param $text String
523 * @param $lineStart Boolean
526 public function parse( $text, $lineStart = false ) {
530 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
531 $html = $out->getText();
532 } catch ( DBAccessError
$e ) {
533 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
535 if ( !empty( $this->debug
) ) {
536 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
543 public function getParserOptions() {
544 return $this->parserOptions
;
547 public function disableLinkPopups() {
548 $this->parserOptions
->setExternalLinkTarget( false );
551 public function restoreLinkPopups() {
552 global $wgExternalLinkTarget;
553 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
557 * Install step which adds a row to the site_stats table with appropriate
560 public function populateSiteStats( DatabaseInstaller
$installer ) {
561 $status = $installer->getConnection();
562 if ( !$status->isOK() ) {
565 $status->value
->insert( 'site_stats', array(
567 'ss_total_views' => 0,
568 'ss_total_edits' => 0,
569 'ss_good_articles' => 0,
570 'ss_total_pages' => 0,
574 __METHOD__
, 'IGNORE' );
575 return Status
::newGood();
579 * Exports all wg* variables stored by the installer into global scope.
581 public function exportVars() {
582 foreach ( $this->settings
as $name => $value ) {
583 if ( substr( $name, 0, 2 ) == 'wg' ) {
584 $GLOBALS[$name] = $value;
590 * Environment check for DB types.
592 protected function envCheckDB() {
595 $compiledDBs = array();
598 foreach ( self
::getDBTypes() as $name ) {
599 $db = $this->getDBInstaller( $name );
600 $readableName = wfMsg( 'config-type-' . $name );
602 if ( $db->isCompiled() ) {
603 $compiledDBs[] = $name;
605 $allNames[] = $readableName;
608 $this->setVar( '_CompiledDBs', $compiledDBs );
610 if ( !$compiledDBs ) {
611 $this->showMessage( 'config-no-db' );
612 // FIXME: this only works for the web installer!
613 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
617 // Check for FTS3 full-text search module
618 $sqlite = $this->getDBInstaller( 'sqlite' );
619 if ( $sqlite->isCompiled() ) {
620 $db = new DatabaseSqliteStandalone( ':memory:' );
621 if( $db->getFulltextSearchModule() != 'FTS3' ) {
622 $this->showMessage( 'config-no-fts3' );
628 * Environment check for register_globals.
630 protected function envCheckRegisterGlobals() {
631 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
632 $this->showMessage( 'config-register-globals' );
637 * Some versions of libxml+PHP break < and > encoding horribly
639 protected function envCheckBrokenXML() {
640 $test = new PhpXmlBugTester();
642 $this->showMessage( 'config-brokenlibxml' );
648 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
649 * reference parameters to __call() are not converted to null
651 protected function envCheckPHP531() {
652 $test = new PhpRefCallBugTester
;
655 $this->showMessage( 'config-using531' );
661 * Environment check for magic_quotes_runtime.
663 protected function envCheckMagicQuotes() {
664 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
665 $this->showMessage( 'config-magic-quotes-runtime' );
671 * Environment check for magic_quotes_sybase.
673 protected function envCheckMagicSybase() {
674 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
675 $this->showMessage( 'config-magic-quotes-sybase' );
681 * Environment check for mbstring.func_overload.
683 protected function envCheckMbstring() {
684 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
685 $this->showMessage( 'config-mbstring' );
691 * Environment check for zend.ze1_compatibility_mode.
693 protected function envCheckZE1() {
694 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
695 $this->showMessage( 'config-ze1' );
701 * Environment check for safe_mode.
703 protected function envCheckSafeMode() {
704 if ( wfIniGetBool( 'safe_mode' ) ) {
705 $this->setVar( '_SafeMode', true );
706 $this->showMessage( 'config-safe-mode' );
711 * Environment check for the XML module.
713 protected function envCheckXML() {
714 if ( !function_exists( "utf8_encode" ) ) {
715 $this->showMessage( 'config-xml-bad' );
721 * Environment check for the PCRE module.
723 protected function envCheckPCRE() {
724 if ( !function_exists( 'preg_match' ) ) {
725 $this->showMessage( 'config-pcre' );
728 wfSuppressWarnings();
729 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
731 if ( $regexd != '--' ) {
732 $this->showMessage( 'config-pcre-no-utf8' );
738 * Environment check for available memory.
740 protected function envCheckMemory() {
741 $limit = ini_get( 'memory_limit' );
743 if ( !$limit ||
$limit == -1 ) {
747 $n = wfShorthandToInteger( $limit );
749 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
750 $newLimit = "{$this->minMemorySize}M";
752 if( ini_set( "memory_limit", $newLimit ) === false ) {
753 $this->showMessage( 'config-memory-bad', $limit );
755 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
756 $this->setVar( '_RaiseMemory', true );
764 * Environment check for compiled object cache types.
766 protected function envCheckCache() {
768 foreach ( $this->objectCaches
as $name => $function ) {
769 if ( function_exists( $function ) ) {
770 $caches[$name] = true;
775 $this->showMessage( 'config-no-cache' );
778 $this->setVar( '_Caches', $caches );
782 * Search for GNU diff3.
784 protected function envCheckDiff3() {
785 $names = array( "gdiff3", "diff3", "diff3.exe" );
786 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
788 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
791 $this->setVar( 'wgDiff3', $diff3 );
793 $this->setVar( 'wgDiff3', false );
794 $this->showMessage( 'config-diff3-bad' );
799 * Environment check for ImageMagick and GD.
801 protected function envCheckGraphics() {
802 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
803 $convert = self
::locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
806 $this->setVar( 'wgImageMagickConvertCommand', $convert );
807 $this->showMessage( 'config-imagemagick', $convert );
809 } elseif ( function_exists( 'imagejpeg' ) ) {
810 $this->showMessage( 'config-gd' );
813 $this->showMessage( 'no-scaling' );
818 * Environment check for setting $IP and $wgScriptPath.
820 protected function envCheckPath() {
822 $IP = dirname( dirname( dirname( __FILE__
) ) );
824 $this->setVar( 'IP', $IP );
826 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
827 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
828 // to get the path to the current script... hopefully it's reliable. SIGH
829 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
830 $path = $_SERVER['PHP_SELF'];
831 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
832 $path = $_SERVER['SCRIPT_NAME'];
833 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
834 // Some kind soul has set it for us already (e.g. debconf)
837 $this->showMessage( 'config-no-uri' );
841 $uri = preg_replace( '{^(.*)/(mw-)?config.*$}', '$1', $path );
842 $this->setVar( 'wgScriptPath', $uri );
846 * Environment check for setting the preferred PHP file extension.
848 protected function envCheckExtension() {
849 // FIXME: detect this properly
850 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
855 $this->setVar( 'wgScriptExtension', ".$ext" );
861 protected function envCheckShellLocale() {
862 $os = php_uname( 's' );
863 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
865 if ( !in_array( $os, $supported ) ) {
869 # Get a list of available locales.
871 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
877 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
878 $candidatesByLocale = array();
879 $candidatesByLang = array();
881 foreach ( $lines as $line ) {
882 if ( $line === '' ) {
886 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
890 list( $all, $lang, $territory, $charset, $modifier ) = $m;
892 $candidatesByLocale[$m[0]] = $m;
893 $candidatesByLang[$lang][] = $m;
896 # Try the current value of LANG.
897 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
898 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
902 # Try the most common ones.
903 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
904 foreach ( $commonLocales as $commonLocale ) {
905 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
906 $this->setVar( 'wgShellLocale', $commonLocale );
911 # Is there an available locale in the Wiki's language?
912 $wikiLang = $this->getVar( 'wgLanguageCode' );
914 if ( isset( $candidatesByLang[$wikiLang] ) ) {
915 $m = reset( $candidatesByLang[$wikiLang] );
916 $this->setVar( 'wgShellLocale', $m[0] );
920 # Are there any at all?
921 if ( count( $candidatesByLocale ) ) {
922 $m = reset( $candidatesByLocale );
923 $this->setVar( 'wgShellLocale', $m[0] );
934 protected function envCheckUploadsDirectory() {
935 global $IP, $wgServer;
937 $dir = $IP . '/images/';
938 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
939 $safe = !$this->dirIsExecutable( $dir, $url );
944 $this->showMessage( 'config-uploads-not-safe', $dir );
949 * Convert a hex string representing a Unicode code point to that code point.
953 protected function unicodeChar( $c ) {
957 } else if ($c <= 0x7FF) {
958 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
959 } else if ($c <= 0xFFFF) {
960 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
961 . chr(0x80 |
$c & 0x3F);
962 } else if ($c <= 0x10FFFF) {
963 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
964 . chr(0x80 |
$c >> 6 & 0x3F)
965 . chr(0x80 |
$c & 0x3F);
973 * Check the libicu version
975 protected function envCheckLibicu() {
976 $utf8 = function_exists( 'utf8_normalize' );
977 $intl = function_exists( 'normalizer_normalize' );
980 * This needs to be updated something that the latest libicu
981 * will properly normalize. This normalization was found at
982 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
983 * Note that we use the hex representation to create the code
984 * points in order to avoid any Unicode-destroying during transit.
986 $not_normal_c = $this->unicodeChar("FA6C");
987 $normal_c = $this->unicodeChar("242EE");
989 $useNormalizer = 'php';
990 $needsUpdate = false;
993 * We're going to prefer the pecl extension here unless
994 * utf8_normalize is more up to date.
997 $useNormalizer = 'utf8';
998 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
999 if ( $utf8 !== $normal_c ) $needsUpdate = true;
1002 $useNormalizer = 'intl';
1003 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1004 if ( $intl !== $normal_c ) $needsUpdate = true;
1007 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
1008 if( $useNormalizer === 'php' ) {
1009 $this->showMessage( 'config-unicode-pure-php-warning' );
1011 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1012 if( $needsUpdate ) {
1013 $this->showMessage( 'config-unicode-update-warning' );
1019 * Get an array of likely places we can find executables. Check a bunch
1020 * of known Unix-like defaults, as well as the PATH environment variable
1021 * (which should maybe make it work for Windows?)
1025 protected static function getPossibleBinPaths() {
1027 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1028 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1029 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1034 * Search a path for any of the given executable names. Returns the
1035 * executable name if found. Also checks the version string returned
1036 * by each executable.
1038 * Used only by environment checks.
1040 * @param $path String: path to search
1041 * @param $names Array of executable names
1042 * @param $versionInfo Boolean false or array with two members:
1043 * 0 => Command to run for version check, with $1 for the full executable name
1044 * 1 => String to compare the output with
1046 * If $versionInfo is not false, only executables with a version
1047 * matching $versionInfo[1] will be returned.
1049 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1050 if ( !is_array( $names ) ) {
1051 $names = array( $names );
1054 foreach ( $names as $name ) {
1055 $command = $path . DIRECTORY_SEPARATOR
. $name;
1057 wfSuppressWarnings();
1058 $file_exists = file_exists( $command );
1059 wfRestoreWarnings();
1061 if ( $file_exists ) {
1062 if ( !$versionInfo ) {
1066 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1067 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1076 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1077 * @see locateExecutable()
1079 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1080 foreach( self
::getPossibleBinPaths() as $path ) {
1081 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1082 if( $exe !== false ) {
1090 * Checks if scripts located in the given directory can be executed via the given URL.
1092 * Used only by environment checks.
1094 public function dirIsExecutable( $dir, $url ) {
1095 $scriptTypes = array(
1097 "<?php echo 'ex' . 'ec';",
1098 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1102 // it would be good to check other popular languages here, but it'll be slow.
1104 wfSuppressWarnings();
1106 foreach ( $scriptTypes as $ext => $contents ) {
1107 foreach ( $contents as $source ) {
1108 $file = 'exectest.' . $ext;
1110 if ( !file_put_contents( $dir . $file, $source ) ) {
1114 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1115 unlink( $dir . $file );
1117 if ( $text == 'exec' ) {
1118 wfRestoreWarnings();
1124 wfRestoreWarnings();
1130 * Register tag hook below.
1132 * @todo Move this to WebInstaller with the two things below?
1134 * @param $parser Parser
1136 public function registerDocLink( Parser
&$parser ) {
1137 $parser->setHook( 'doclink', array( $this, 'docLink' ) );
1142 * ParserOptions are constructed before we determined the language, so fix it
1144 public function setParserLanguage( $lang ) {
1145 $this->parserOptions
->setTargetLanguage( $lang );
1146 $this->parserOptions
->setUserLang( $lang->getCode() );
1150 * Extension tag hook for a documentation link.
1152 public function docLink( $linkText, $attribs, $parser ) {
1153 $url = $this->getDocUrl( $attribs['href'] );
1154 return '<a href="' . htmlspecialchars( $url ) . '">' .
1155 htmlspecialchars( $linkText ) .
1160 * Overridden by WebInstaller to provide lastPage parameters.
1162 protected function getDocUrl( $page ) {
1163 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1167 * Finds extensions that follow the format /extensions/Name/Name.php,
1168 * and returns an array containing the value for 'Name' for each found extension.
1172 public function findExtensions() {
1173 if( $this->getVar( 'IP' ) === null ) {
1178 $dir = $this->getVar( 'IP' ) . '/extensions';
1179 $dh = opendir( $dir );
1181 while ( ( $file = readdir( $dh ) ) !== false ) {
1182 if( file_exists( "$dir/$file/$file.php" ) ) {
1191 * Installs the auto-detected extensions.
1195 protected function includeExtensions() {
1197 $exts = $this->getVar( '_Extensions' );
1198 $IP = $this->getVar( 'IP' );
1199 $path = $IP . '/extensions';
1202 * We need to include DefaultSettings before including extensions to avoid
1203 * warnings about unset variables. However, the only thing we really
1204 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1205 * if the extension has hidden hook registration in $wgExtensionFunctions,
1206 * but we're not opening that can of worms
1207 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1209 global $wgHooks, $wgAutoloadClasses;
1210 require( "$IP/includes/DefaultSettings.php" );
1212 foreach( $exts as $e ) {
1213 require( "$path/$e/$e.php" );
1216 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1217 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1219 // Unset everyone else's hooks. Lord knows what someone might be doing
1220 // in ParserFirstCallInit (see bug 27171)
1222 $wgHooks = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1224 return Status
::newGood();
1228 * Get an array of install steps. Should always be in the format of
1230 * 'name' => 'someuniquename',
1231 * 'callback' => array( $obj, 'method' ),
1233 * There must be a config-install-$name message defined per step, which will
1234 * be shown on install.
1236 * @param $installer DatabaseInstaller so we can make callbacks
1239 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1240 $coreInstallSteps = array(
1241 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1242 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1243 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1244 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1245 array( 'name' => 'secretkey', 'callback' => array( $this, 'generateSecretKey' ) ),
1246 array( 'name' => 'upgradekey', 'callback' => array( $this, 'generateUpgradeKey' ) ),
1247 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1248 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1251 // Build the array of install steps starting from the core install list,
1252 // then adding any callbacks that wanted to attach after a given step
1253 foreach( $coreInstallSteps as $step ) {
1254 $this->installSteps
[] = $step;
1255 if( isset( $this->extraInstallSteps
[ $step['name'] ] ) ) {
1256 $this->installSteps
= array_merge(
1257 $this->installSteps
,
1258 $this->extraInstallSteps
[ $step['name'] ]
1263 // Prepend any steps that want to be at the beginning
1264 if( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1265 $this->installSteps
= array_merge(
1266 $this->extraInstallSteps
['BEGINNING'],
1271 // Extensions should always go first, chance to tie into hooks and such
1272 if( count( $this->getVar( '_Extensions' ) ) ) {
1273 array_unshift( $this->installSteps
,
1274 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1276 $this->installSteps
[] = array(
1277 'name' => 'extension-tables',
1278 'callback' => array( $installer, 'createExtensionTables' )
1281 return $this->installSteps
;
1285 * Actually perform the installation.
1287 * @param $startCB Array A callback array for the beginning of each step
1288 * @param $endCB Array A callback array for the end of each step
1290 * @return Array of Status objects
1292 public function performInstallation( $startCB, $endCB ) {
1293 $installResults = array();
1294 $installer = $this->getDBInstaller();
1295 $installer->preInstall();
1296 $steps = $this->getInstallSteps( $installer );
1297 foreach( $steps as $stepObj ) {
1298 $name = $stepObj['name'];
1299 call_user_func_array( $startCB, array( $name ) );
1301 // Perform the callback step
1302 $status = call_user_func( $stepObj['callback'], $installer );
1304 // Output and save the results
1305 call_user_func( $endCB, $name, $status );
1306 $installResults[$name] = $status;
1308 // If we've hit some sort of fatal, we need to bail.
1309 // Callback already had a chance to do output above.
1310 if( !$status->isOk() ) {
1314 if( $status->isOk() ) {
1315 $this->setVar( '_InstallDone', true );
1317 return $installResults;
1321 * Generate $wgSecretKey. Will warn if we had to use mt_rand() instead of
1326 protected function generateSecretKey() {
1327 return $this->generateSecret( 'wgSecretKey' );
1331 * Generate a secret value for a variable using either
1332 * /dev/urandom or mt_rand() Produce a warning in the later case.
1336 protected function generateSecret( $secretName, $length = 64 ) {
1337 if ( wfIsWindows() ) {
1340 wfSuppressWarnings();
1341 $file = fopen( "/dev/urandom", "r" );
1342 wfRestoreWarnings();
1345 $status = Status
::newGood();
1348 $secretKey = bin2hex( fread( $file, $length / 2 ) );
1353 for ( $i = 0; $i < $length / 8; $i++
) {
1354 $secretKey .= dechex( mt_rand( 0, 0x7fffffff ) );
1357 $status->warning( 'config-insecure-secret', '$' . $secretName );
1360 $this->setVar( $secretName, $secretKey );
1366 * Generate a default $wgUpgradeKey. Will warn if we had to use
1367 * mt_rand() instead of /dev/urandom
1371 public function generateUpgradeKey() {
1372 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1373 return $this->generateSecret( 'wgUpgradeKey', 16 );
1375 return Status
::newGood();
1379 * Create the first user account, grant it sysop and bureaucrat rights
1383 protected function createSysop() {
1384 $name = $this->getVar( '_AdminName' );
1385 $user = User
::newFromName( $name );
1388 // We should've validated this earlier anyway!
1389 return Status
::newFatal( 'config-admin-error-user', $name );
1392 if ( $user->idForName() == 0 ) {
1393 $user->addToDatabase();
1396 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1397 } catch( PasswordError
$pwe ) {
1398 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1401 $user->addGroup( 'sysop' );
1402 $user->addGroup( 'bureaucrat' );
1403 if( $this->getVar( '_AdminEmail' ) ) {
1404 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1406 $user->saveSettings();
1408 // Update user count
1409 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1410 $ssUpdate->doUpdate();
1412 $status = Status
::newGood();
1414 if( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1415 $this->subscribeToMediaWikiAnnounce( $status );
1421 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1423 'email' => $this->getVar( '_AdminEmail' ),
1428 // Mailman doesn't support as many languages as we do, so check to make
1429 // sure their selected language is available
1430 $myLang = $this->getVar( '_UserLang' );
1431 if( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1432 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1433 $params['language'] = $myLang;
1436 $res = Http
::post( $this->mediaWikiAnnounceUrl
, array( 'postData' => $params ) );
1438 $s->warning( 'config-install-subscribe-fail' );
1443 * Insert Main Page with default content.
1447 protected function createMainpage( DatabaseInstaller
$installer ) {
1448 $status = Status
::newGood();
1450 $article = new Article( Title
::newMainPage() );
1451 $article->doEdit( wfMsgForContent( 'mainpagetext' ) . "\n\n" .
1452 wfMsgForContent( 'mainpagedocfooter' ),
1456 User
::newFromName( 'MediaWiki default' ) );
1457 } catch (MWException
$e) {
1458 //using raw, because $wgShowExceptionDetails can not be set yet
1459 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1466 * Override the necessary bits of the config to run an installation.
1468 public static function overrideConfig() {
1469 define( 'MW_NO_SESSION', 1 );
1471 // Don't access the database
1472 $GLOBALS['wgUseDatabaseMessages'] = false;
1474 $GLOBALS['wgShowExceptionDetails'] = true;
1475 // Don't break forms
1476 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1478 // Extended debugging
1479 $GLOBALS['wgShowSQLErrors'] = true;
1480 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1482 // Allow multiple ob_flush() calls
1483 $GLOBALS['wgDisableOutputCompression'] = true;
1485 // Use a sensible cookie prefix (not my_wiki)
1486 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1488 // Some of the environment checks make shell requests, remove limits
1489 $GLOBALS['wgMaxShellMemory'] = 0;
1493 * Add an installation step following the given step.
1495 * @param $callback Array A valid installation callback array, in this form:
1496 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1497 * @param $findStep String the step to find. Omit to put the step at the beginning
1499 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1500 $this->extraInstallSteps
[$findStep][] = $callback;