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
{
26 // This is the absolute minimum PHP version we can support
27 const MINIMUM_PHP_VERSION
= '5.2.3';
35 * Cached DB installer instances, access using getDBInstaller().
39 protected $dbInstallers = array();
42 * Minimum memory size in MB.
46 protected $minMemorySize = 50;
49 * Cached Title, used by parse().
53 protected $parserTitle;
56 * Cached ParserOptions, used by parse().
60 protected $parserOptions;
63 * Known database types. These correspond to the class names <type>Installer,
64 * and are also MediaWiki database types valid for $wgDBtype.
66 * To add a new type, create a <type>Installer class and a Database<type>
67 * class, and add a config-type-<type> message to MessagesEn.php.
71 protected static $dbTypes = array(
79 * A list of environment check methods called by doEnvironmentChecks().
80 * These may output warnings using showMessage(), and/or abort the
81 * installation process by returning false.
85 protected $envChecks = array(
87 'envCheckRegisterGlobals',
90 'envCheckMagicQuotes',
91 'envCheckMagicSybase',
103 'envCheckShellLocale',
104 'envCheckUploadsDirectory',
109 * MediaWiki configuration globals that will eventually be passed through
110 * to LocalSettings.php. The names only are given here, the defaults
111 * typically come from DefaultSettings.php.
115 protected $defaultVarNames = array(
127 'wgEmailAuthentication',
130 'wgImageMagickConvertCommand',
135 'wgDeletedDirectory',
140 'wgUseInstantCommons',
146 * Variables that are stored alongside globals, and are used for any
147 * configuration of the installation process aside from the MediaWiki
148 * configuration. Map of names to defaults.
152 protected $internalDefaults = array(
154 '_Environment' => false,
155 '_CompiledDBs' => array(),
156 '_SafeMode' => false,
157 '_RaiseMemory' => false,
158 '_UpgradeDone' => false,
159 '_InstallDone' => false,
160 '_Caches' => array(),
161 '_InstallUser' => 'root',
162 '_InstallPassword' => '',
163 '_SameAccount' => true,
164 '_CreateDBAccount' => false,
165 '_NamespaceType' => 'site-name',
166 '_AdminName' => '', // will be set later, when the user selects language
167 '_AdminPassword' => '',
168 '_AdminPassword2' => '',
170 '_Subscribe' => false,
171 '_SkipOptional' => 'continue',
172 '_RightsProfile' => 'wiki',
173 '_LicenseCode' => 'none',
175 '_Extensions' => array(),
176 '_MemCachedServers' => '',
177 '_UpgradeKeySupplied' => false,
178 '_ExistingDBSettings' => false,
182 * The actual list of installation steps. This will be initialized by getInstallSteps()
186 private $installSteps = array();
189 * Extra steps for installation, for things like DatabaseInstallers to modify
193 protected $extraInstallSteps = array();
196 * Known object cache types and the functions used to test for their existence.
200 protected $objectCaches = array(
201 'xcache' => 'xcache_get',
202 'apc' => 'apc_fetch',
203 'eaccel' => 'eaccelerator_get',
204 'wincache' => 'wincache_ucache_get'
208 * User rights profiles.
212 public $rightsProfiles = array(
215 '*' => array( 'edit' => false )
219 'createaccount' => false,
225 'createaccount' => false,
237 public $licenses = array(
239 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
240 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
242 'cc-by-nc-sa' => array(
243 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
244 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
247 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
248 'icon' => '{$wgStylePath}/common/images/cc-0.png',
251 'url' => 'http://creativecommons.org/licenses/publicdomain/',
252 'icon' => '{$wgStylePath}/common/images/public-domain.png',
255 'url' => 'http://www.gnu.org/licenses/old-licenses/fdl-1.2.html',
256 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
258 'gfdl-current' => array(
259 'url' => 'http://www.gnu.org/copyleft/fdl.html',
260 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
267 'cc-choose' => array(
268 // Details will be filled in by the selector.
276 * URL to mediawiki-announce subscription
278 protected $mediaWikiAnnounceUrl = 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
281 * Supported language codes for Mailman
283 protected $mediaWikiAnnounceLanguages = array(
284 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
285 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
286 'sl', 'sr', 'sv', 'tr', 'uk'
290 * UI interface for displaying a short message
291 * The parameters are like parameters to wfMsg().
292 * The messages will be in wikitext format, which will be converted to an
293 * output format such as HTML or text before being sent to the user.
295 public abstract function showMessage( $msg /*, ... */ );
298 * Show a message to the installing user by using a Status object
299 * @param $status Status
301 public abstract function showStatusMessage( Status
$status );
304 * Constructor, always call this from child classes.
306 public function __construct() {
307 global $wgExtensionMessagesFiles, $wgUser, $wgHooks;
309 // Disable the i18n cache and LoadBalancer
310 Language
::getLocalisationCache()->disableBackend();
311 LBFactory
::disableBackend();
313 // Load the installer's i18n file.
314 $wgExtensionMessagesFiles['MediawikiInstaller'] =
315 dirname( __FILE__
) . '/Installer.i18n.php';
317 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
318 $wgUser = User
::newFromId( 0 );
320 $this->settings
= $this->internalDefaults
;
322 foreach ( $this->defaultVarNames
as $var ) {
323 $this->settings
[$var] = $GLOBALS[$var];
326 foreach ( self
::getDBTypes() as $type ) {
327 $installer = $this->getDBInstaller( $type );
329 if ( !$installer->isCompiled() ) {
333 $defaults = $installer->getGlobalDefaults();
335 foreach ( $installer->getGlobalNames() as $var ) {
336 if ( isset( $defaults[$var] ) ) {
337 $this->settings
[$var] = $defaults[$var];
339 $this->settings
[$var] = $GLOBALS[$var];
344 $this->parserTitle
= Title
::newFromText( 'Installer' );
345 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
346 $this->parserOptions
->setEditSection( false );
350 * Get a list of known DB types.
352 public static function getDBTypes() {
353 return self
::$dbTypes;
357 * Do initial checks of the PHP environment. Set variables according to
358 * the observed environment.
360 * It's possible that this may be called under the CLI SAPI, not the SAPI
361 * that the wiki will primarily run under. In that case, the subclass should
362 * initialise variables such as wgScriptPath, before calling this function.
364 * Under the web subclass, it can already be assumed that PHP 5+ is in use
365 * and that sessions are working.
369 public function doEnvironmentChecks() {
370 $phpVersion = phpversion();
371 if( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
372 $this->showMessage( 'config-env-php', $phpVersion );
375 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
380 foreach ( $this->envChecks
as $check ) {
381 $status = $this->$check();
382 if ( $status === false ) {
388 $this->setVar( '_Environment', $good );
390 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
394 * Set a MW configuration variable, or internal installer configuration variable.
396 * @param $name String
397 * @param $value Mixed
399 public function setVar( $name, $value ) {
400 $this->settings
[$name] = $value;
404 * Get an MW configuration variable, or internal installer configuration variable.
405 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
406 * Installer variables are typically prefixed by an underscore.
408 * @param $name String
409 * @param $default Mixed
413 public function getVar( $name, $default = null ) {
414 if ( !isset( $this->settings
[$name] ) ) {
417 return $this->settings
[$name];
422 * Get an instance of DatabaseInstaller for the specified DB type.
424 * @param $type Mixed: DB installer for which is needed, false to use default.
426 * @return DatabaseInstaller
428 public function getDBInstaller( $type = false ) {
430 $type = $this->getVar( 'wgDBtype' );
433 $type = strtolower( $type );
435 if ( !isset( $this->dbInstallers
[$type] ) ) {
436 $class = ucfirst( $type ). 'Installer';
437 $this->dbInstallers
[$type] = new $class( $this );
440 return $this->dbInstallers
[$type];
444 * Determine if LocalSettings.php exists. If it does, return its variables,
445 * merged with those from AdminSettings.php, as an array.
449 public function getExistingLocalSettings() {
452 wfSuppressWarnings();
453 $_lsExists = file_exists( "$IP/LocalSettings.php" );
461 require( "$IP/includes/DefaultSettings.php" );
462 require( "$IP/LocalSettings.php" );
463 if ( file_exists( "$IP/AdminSettings.php" ) ) {
464 require( "$IP/AdminSettings.php" );
466 return get_defined_vars();
470 * Get a fake password for sending back to the user in HTML.
471 * This is a security mechanism to avoid compromise of the password in the
472 * event of session ID compromise.
474 * @param $realPassword String
478 public function getFakePassword( $realPassword ) {
479 return str_repeat( '*', strlen( $realPassword ) );
483 * Set a variable which stores a password, except if the new value is a
484 * fake password in which case leave it as it is.
486 * @param $name String
487 * @param $value Mixed
489 public function setPassword( $name, $value ) {
490 if ( !preg_match( '/^\*+$/', $value ) ) {
491 $this->setVar( $name, $value );
496 * On POSIX systems return the primary group of the webserver we're running under.
497 * On other systems just returns null.
499 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
500 * webserver user before he can install.
502 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
506 public static function maybeGetWebserverPrimaryGroup() {
507 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
508 # I don't know this, this isn't UNIX.
512 # posix_getegid() *not* getmygid() because we want the group of the webserver,
513 # not whoever owns the current script.
514 $gid = posix_getegid();
515 $getpwuid = posix_getpwuid( $gid );
516 $group = $getpwuid['name'];
522 * Convert wikitext $text to HTML.
524 * This is potentially error prone since many parser features require a complete
525 * installed MW database. The solution is to just not use those features when you
526 * write your messages. This appears to work well enough. Basic formatting and
527 * external links work just fine.
529 * But in case a translator decides to throw in a #ifexist or internal link or
530 * whatever, this function is guarded to catch the attempted DB access and to present
531 * some fallback text.
533 * @param $text String
534 * @param $lineStart Boolean
537 public function parse( $text, $lineStart = false ) {
541 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
542 $html = $out->getText();
543 } catch ( DBAccessError
$e ) {
544 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
546 if ( !empty( $this->debug
) ) {
547 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
554 public function getParserOptions() {
555 return $this->parserOptions
;
558 public function disableLinkPopups() {
559 $this->parserOptions
->setExternalLinkTarget( false );
562 public function restoreLinkPopups() {
563 global $wgExternalLinkTarget;
564 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
568 * Install step which adds a row to the site_stats table with appropriate
571 public function populateSiteStats( DatabaseInstaller
$installer ) {
572 $status = $installer->getConnection();
573 if ( !$status->isOK() ) {
576 $status->value
->insert( 'site_stats', array(
578 'ss_total_views' => 0,
579 'ss_total_edits' => 0,
580 'ss_good_articles' => 0,
581 'ss_total_pages' => 0,
585 __METHOD__
, 'IGNORE' );
586 return Status
::newGood();
590 * Exports all wg* variables stored by the installer into global scope.
592 public function exportVars() {
593 foreach ( $this->settings
as $name => $value ) {
594 if ( substr( $name, 0, 2 ) == 'wg' ) {
595 $GLOBALS[$name] = $value;
601 * Environment check for DB types.
603 protected function envCheckDB() {
606 $compiledDBs = array();
609 foreach ( self
::getDBTypes() as $name ) {
610 $db = $this->getDBInstaller( $name );
611 $readableName = wfMsg( 'config-type-' . $name );
613 if ( $db->isCompiled() ) {
614 $compiledDBs[] = $name;
616 $allNames[] = $readableName;
619 $this->setVar( '_CompiledDBs', $compiledDBs );
621 if ( !$compiledDBs ) {
622 $this->showMessage( 'config-no-db' );
623 // FIXME: this only works for the web installer!
624 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
628 // Check for FTS3 full-text search module
629 $sqlite = $this->getDBInstaller( 'sqlite' );
630 if ( $sqlite->isCompiled() ) {
631 $db = new DatabaseSqliteStandalone( ':memory:' );
632 if( $db->getFulltextSearchModule() != 'FTS3' ) {
633 $this->showMessage( 'config-no-fts3' );
639 * Environment check for register_globals.
641 protected function envCheckRegisterGlobals() {
642 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
643 $this->showMessage( 'config-register-globals' );
648 * Some versions of libxml+PHP break < and > encoding horribly
650 protected function envCheckBrokenXML() {
651 $test = new PhpXmlBugTester();
653 $this->showMessage( 'config-brokenlibxml' );
659 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
660 * reference parameters to __call() are not converted to null
662 protected function envCheckPHP531() {
663 $test = new PhpRefCallBugTester
;
666 $this->showMessage( 'config-using531', phpversion() );
672 * Environment check for magic_quotes_runtime.
674 protected function envCheckMagicQuotes() {
675 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
676 $this->showMessage( 'config-magic-quotes-runtime' );
682 * Environment check for magic_quotes_sybase.
684 protected function envCheckMagicSybase() {
685 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
686 $this->showMessage( 'config-magic-quotes-sybase' );
692 * Environment check for mbstring.func_overload.
694 protected function envCheckMbstring() {
695 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
696 $this->showMessage( 'config-mbstring' );
702 * Environment check for zend.ze1_compatibility_mode.
704 protected function envCheckZE1() {
705 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
706 $this->showMessage( 'config-ze1' );
712 * Environment check for safe_mode.
714 protected function envCheckSafeMode() {
715 if ( wfIniGetBool( 'safe_mode' ) ) {
716 $this->setVar( '_SafeMode', true );
717 $this->showMessage( 'config-safe-mode' );
722 * Environment check for the XML module.
724 protected function envCheckXML() {
725 if ( !function_exists( "utf8_encode" ) ) {
726 $this->showMessage( 'config-xml-bad' );
732 * Environment check for the PCRE module.
734 protected function envCheckPCRE() {
735 if ( !function_exists( 'preg_match' ) ) {
736 $this->showMessage( 'config-pcre' );
739 wfSuppressWarnings();
740 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
742 if ( $regexd != '--' ) {
743 $this->showMessage( 'config-pcre-no-utf8' );
749 * Environment check for available memory.
751 protected function envCheckMemory() {
752 $limit = ini_get( 'memory_limit' );
754 if ( !$limit ||
$limit == -1 ) {
758 $n = wfShorthandToInteger( $limit );
760 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
761 $newLimit = "{$this->minMemorySize}M";
763 if( ini_set( "memory_limit", $newLimit ) === false ) {
764 $this->showMessage( 'config-memory-bad', $limit );
766 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
767 $this->setVar( '_RaiseMemory', true );
775 * Environment check for compiled object cache types.
777 protected function envCheckCache() {
779 foreach ( $this->objectCaches
as $name => $function ) {
780 if ( function_exists( $function ) ) {
781 $caches[$name] = true;
786 $this->showMessage( 'config-no-cache' );
789 $this->setVar( '_Caches', $caches );
793 * Search for GNU diff3.
795 protected function envCheckDiff3() {
796 $names = array( "gdiff3", "diff3", "diff3.exe" );
797 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
799 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
802 $this->setVar( 'wgDiff3', $diff3 );
804 $this->setVar( 'wgDiff3', false );
805 $this->showMessage( 'config-diff3-bad' );
810 * Environment check for ImageMagick and GD.
812 protected function envCheckGraphics() {
813 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
814 $convert = self
::locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
816 $this->setVar( 'wgImageMagickConvertCommand', '' );
818 $this->setVar( 'wgImageMagickConvertCommand', $convert );
819 $this->showMessage( 'config-imagemagick', $convert );
821 } elseif ( function_exists( 'imagejpeg' ) ) {
822 $this->showMessage( 'config-gd' );
825 $this->showMessage( 'no-scaling' );
830 * Environment check for setting $IP and $wgScriptPath.
832 protected function envCheckPath() {
834 $IP = dirname( dirname( dirname( __FILE__
) ) );
836 $this->setVar( 'IP', $IP );
838 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
839 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
840 // to get the path to the current script... hopefully it's reliable. SIGH
841 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
842 $path = $_SERVER['PHP_SELF'];
843 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
844 $path = $_SERVER['SCRIPT_NAME'];
845 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
846 // Some kind soul has set it for us already (e.g. debconf)
849 $this->showMessage( 'config-no-uri' );
853 $uri = preg_replace( '{^(.*)/(mw-)?config.*$}', '$1', $path );
854 $this->setVar( 'wgScriptPath', $uri );
858 * Environment check for setting the preferred PHP file extension.
860 protected function envCheckExtension() {
861 // FIXME: detect this properly
862 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
867 $this->setVar( 'wgScriptExtension', ".$ext" );
873 protected function envCheckShellLocale() {
874 $os = php_uname( 's' );
875 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
877 if ( !in_array( $os, $supported ) ) {
881 # Get a list of available locales.
883 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
889 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
890 $candidatesByLocale = array();
891 $candidatesByLang = array();
893 foreach ( $lines as $line ) {
894 if ( $line === '' ) {
898 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
902 list( $all, $lang, $territory, $charset, $modifier ) = $m;
904 $candidatesByLocale[$m[0]] = $m;
905 $candidatesByLang[$lang][] = $m;
908 # Try the current value of LANG.
909 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
910 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
914 # Try the most common ones.
915 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
916 foreach ( $commonLocales as $commonLocale ) {
917 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
918 $this->setVar( 'wgShellLocale', $commonLocale );
923 # Is there an available locale in the Wiki's language?
924 $wikiLang = $this->getVar( 'wgLanguageCode' );
926 if ( isset( $candidatesByLang[$wikiLang] ) ) {
927 $m = reset( $candidatesByLang[$wikiLang] );
928 $this->setVar( 'wgShellLocale', $m[0] );
932 # Are there any at all?
933 if ( count( $candidatesByLocale ) ) {
934 $m = reset( $candidatesByLocale );
935 $this->setVar( 'wgShellLocale', $m[0] );
946 protected function envCheckUploadsDirectory() {
947 global $IP, $wgServer;
949 $dir = $IP . '/images/';
950 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
951 $safe = !$this->dirIsExecutable( $dir, $url );
956 $this->showMessage( 'config-uploads-not-safe', $dir );
961 * Convert a hex string representing a Unicode code point to that code point.
965 protected function unicodeChar( $c ) {
969 } else if ($c <= 0x7FF) {
970 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
971 } else if ($c <= 0xFFFF) {
972 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
973 . chr(0x80 |
$c & 0x3F);
974 } else if ($c <= 0x10FFFF) {
975 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
976 . chr(0x80 |
$c >> 6 & 0x3F)
977 . chr(0x80 |
$c & 0x3F);
985 * Check the libicu version
987 protected function envCheckLibicu() {
988 $utf8 = function_exists( 'utf8_normalize' );
989 $intl = function_exists( 'normalizer_normalize' );
992 * This needs to be updated something that the latest libicu
993 * will properly normalize. This normalization was found at
994 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
995 * Note that we use the hex representation to create the code
996 * points in order to avoid any Unicode-destroying during transit.
998 $not_normal_c = $this->unicodeChar("FA6C");
999 $normal_c = $this->unicodeChar("242EE");
1001 $useNormalizer = 'php';
1002 $needsUpdate = false;
1005 * We're going to prefer the pecl extension here unless
1006 * utf8_normalize is more up to date.
1009 $useNormalizer = 'utf8';
1010 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
1011 if ( $utf8 !== $normal_c ) $needsUpdate = true;
1014 $useNormalizer = 'intl';
1015 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1016 if ( $intl !== $normal_c ) $needsUpdate = true;
1019 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
1020 if( $useNormalizer === 'php' ) {
1021 $this->showMessage( 'config-unicode-pure-php-warning' );
1023 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1024 if( $needsUpdate ) {
1025 $this->showMessage( 'config-unicode-update-warning' );
1031 * Get an array of likely places we can find executables. Check a bunch
1032 * of known Unix-like defaults, as well as the PATH environment variable
1033 * (which should maybe make it work for Windows?)
1037 protected static function getPossibleBinPaths() {
1039 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1040 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1041 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1046 * Search a path for any of the given executable names. Returns the
1047 * executable name if found. Also checks the version string returned
1048 * by each executable.
1050 * Used only by environment checks.
1052 * @param $path String: path to search
1053 * @param $names Array of executable names
1054 * @param $versionInfo Boolean false or array with two members:
1055 * 0 => Command to run for version check, with $1 for the full executable name
1056 * 1 => String to compare the output with
1058 * If $versionInfo is not false, only executables with a version
1059 * matching $versionInfo[1] will be returned.
1061 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1062 if ( !is_array( $names ) ) {
1063 $names = array( $names );
1066 foreach ( $names as $name ) {
1067 $command = $path . DIRECTORY_SEPARATOR
. $name;
1069 wfSuppressWarnings();
1070 $file_exists = file_exists( $command );
1071 wfRestoreWarnings();
1073 if ( $file_exists ) {
1074 if ( !$versionInfo ) {
1078 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1079 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1088 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1089 * @see locateExecutable()
1091 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1092 foreach( self
::getPossibleBinPaths() as $path ) {
1093 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1094 if( $exe !== false ) {
1102 * Checks if scripts located in the given directory can be executed via the given URL.
1104 * Used only by environment checks.
1106 public function dirIsExecutable( $dir, $url ) {
1107 $scriptTypes = array(
1109 "<?php echo 'ex' . 'ec';",
1110 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1114 // it would be good to check other popular languages here, but it'll be slow.
1116 wfSuppressWarnings();
1118 foreach ( $scriptTypes as $ext => $contents ) {
1119 foreach ( $contents as $source ) {
1120 $file = 'exectest.' . $ext;
1122 if ( !file_put_contents( $dir . $file, $source ) ) {
1126 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1127 unlink( $dir . $file );
1129 if ( $text == 'exec' ) {
1130 wfRestoreWarnings();
1136 wfRestoreWarnings();
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 * Overridden by WebInstaller to provide lastPage parameters.
1152 protected function getDocUrl( $page ) {
1153 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1157 * Finds extensions that follow the format /extensions/Name/Name.php,
1158 * and returns an array containing the value for 'Name' for each found extension.
1162 public function findExtensions() {
1163 if( $this->getVar( 'IP' ) === null ) {
1168 $dir = $this->getVar( 'IP' ) . '/extensions';
1169 $dh = opendir( $dir );
1171 while ( ( $file = readdir( $dh ) ) !== false ) {
1172 if( file_exists( "$dir/$file/$file.php" ) ) {
1181 * Installs the auto-detected extensions.
1185 protected function includeExtensions() {
1187 $exts = $this->getVar( '_Extensions' );
1188 $IP = $this->getVar( 'IP' );
1189 $path = $IP . '/extensions';
1192 * We need to include DefaultSettings before including extensions to avoid
1193 * warnings about unset variables. However, the only thing we really
1194 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1195 * if the extension has hidden hook registration in $wgExtensionFunctions,
1196 * but we're not opening that can of worms
1197 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1199 global $wgHooks, $wgAutoloadClasses;
1200 require( "$IP/includes/DefaultSettings.php" );
1202 foreach( $exts as $e ) {
1203 require( "$path/$e/$e.php" );
1206 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1207 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1209 // Unset everyone else's hooks. Lord knows what someone might be doing
1210 // in ParserFirstCallInit (see bug 27171)
1212 $wgHooks = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1214 return Status
::newGood();
1218 * Get an array of install steps. Should always be in the format of
1220 * 'name' => 'someuniquename',
1221 * 'callback' => array( $obj, 'method' ),
1223 * There must be a config-install-$name message defined per step, which will
1224 * be shown on install.
1226 * @param $installer DatabaseInstaller so we can make callbacks
1229 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1230 $coreInstallSteps = array(
1231 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1232 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1233 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1234 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1235 array( 'name' => 'secretkey', 'callback' => array( $this, 'generateSecretKey' ) ),
1236 array( 'name' => 'upgradekey', 'callback' => array( $this, 'generateUpgradeKey' ) ),
1237 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1238 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1241 // Build the array of install steps starting from the core install list,
1242 // then adding any callbacks that wanted to attach after a given step
1243 foreach( $coreInstallSteps as $step ) {
1244 $this->installSteps
[] = $step;
1245 if( isset( $this->extraInstallSteps
[ $step['name'] ] ) ) {
1246 $this->installSteps
= array_merge(
1247 $this->installSteps
,
1248 $this->extraInstallSteps
[ $step['name'] ]
1253 // Prepend any steps that want to be at the beginning
1254 if( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1255 $this->installSteps
= array_merge(
1256 $this->extraInstallSteps
['BEGINNING'],
1261 // Extensions should always go first, chance to tie into hooks and such
1262 if( count( $this->getVar( '_Extensions' ) ) ) {
1263 array_unshift( $this->installSteps
,
1264 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1266 $this->installSteps
[] = array(
1267 'name' => 'extension-tables',
1268 'callback' => array( $installer, 'createExtensionTables' )
1271 return $this->installSteps
;
1275 * Actually perform the installation.
1277 * @param $startCB Array A callback array for the beginning of each step
1278 * @param $endCB Array A callback array for the end of each step
1280 * @return Array of Status objects
1282 public function performInstallation( $startCB, $endCB ) {
1283 $installResults = array();
1284 $installer = $this->getDBInstaller();
1285 $installer->preInstall();
1286 $steps = $this->getInstallSteps( $installer );
1287 foreach( $steps as $stepObj ) {
1288 $name = $stepObj['name'];
1289 call_user_func_array( $startCB, array( $name ) );
1291 // Perform the callback step
1292 $status = call_user_func( $stepObj['callback'], $installer );
1294 // Output and save the results
1295 call_user_func( $endCB, $name, $status );
1296 $installResults[$name] = $status;
1298 // If we've hit some sort of fatal, we need to bail.
1299 // Callback already had a chance to do output above.
1300 if( !$status->isOk() ) {
1304 if( $status->isOk() ) {
1305 $this->setVar( '_InstallDone', true );
1307 return $installResults;
1311 * Generate $wgSecretKey. Will warn if we had to use mt_rand() instead of
1316 protected function generateSecretKey() {
1317 return $this->generateSecret( 'wgSecretKey' );
1321 * Generate a secret value for a variable using either
1322 * /dev/urandom or mt_rand() Produce a warning in the later case.
1326 protected function generateSecret( $secretName, $length = 64 ) {
1327 if ( wfIsWindows() ) {
1330 wfSuppressWarnings();
1331 $file = fopen( "/dev/urandom", "r" );
1332 wfRestoreWarnings();
1335 $status = Status
::newGood();
1338 $secretKey = bin2hex( fread( $file, $length / 2 ) );
1343 for ( $i = 0; $i < $length / 8; $i++
) {
1344 $secretKey .= dechex( mt_rand( 0, 0x7fffffff ) );
1347 $status->warning( 'config-insecure-secret', '$' . $secretName );
1350 $this->setVar( $secretName, $secretKey );
1356 * Generate a default $wgUpgradeKey. Will warn if we had to use
1357 * mt_rand() instead of /dev/urandom
1361 public function generateUpgradeKey() {
1362 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1363 return $this->generateSecret( 'wgUpgradeKey', 16 );
1365 return Status
::newGood();
1369 * Create the first user account, grant it sysop and bureaucrat rights
1373 protected function createSysop() {
1374 $name = $this->getVar( '_AdminName' );
1375 $user = User
::newFromName( $name );
1378 // We should've validated this earlier anyway!
1379 return Status
::newFatal( 'config-admin-error-user', $name );
1382 if ( $user->idForName() == 0 ) {
1383 $user->addToDatabase();
1386 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1387 } catch( PasswordError
$pwe ) {
1388 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1391 $user->addGroup( 'sysop' );
1392 $user->addGroup( 'bureaucrat' );
1393 if( $this->getVar( '_AdminEmail' ) ) {
1394 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1396 $user->saveSettings();
1398 // Update user count
1399 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1400 $ssUpdate->doUpdate();
1402 $status = Status
::newGood();
1404 if( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1405 $this->subscribeToMediaWikiAnnounce( $status );
1411 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1413 'email' => $this->getVar( '_AdminEmail' ),
1418 // Mailman doesn't support as many languages as we do, so check to make
1419 // sure their selected language is available
1420 $myLang = $this->getVar( '_UserLang' );
1421 if( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1422 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1423 $params['language'] = $myLang;
1426 $res = Http
::post( $this->mediaWikiAnnounceUrl
, array( 'postData' => $params ) );
1428 $s->warning( 'config-install-subscribe-fail' );
1433 * Insert Main Page with default content.
1437 protected function createMainpage( DatabaseInstaller
$installer ) {
1438 $status = Status
::newGood();
1440 $article = new Article( Title
::newMainPage() );
1441 $article->doEdit( wfMsgForContent( 'mainpagetext' ) . "\n\n" .
1442 wfMsgForContent( 'mainpagedocfooter' ),
1446 User
::newFromName( 'MediaWiki default' ) );
1447 } catch (MWException
$e) {
1448 //using raw, because $wgShowExceptionDetails can not be set yet
1449 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1456 * Override the necessary bits of the config to run an installation.
1458 public static function overrideConfig() {
1459 define( 'MW_NO_SESSION', 1 );
1461 // Don't access the database
1462 $GLOBALS['wgUseDatabaseMessages'] = false;
1464 $GLOBALS['wgShowExceptionDetails'] = true;
1465 // Don't break forms
1466 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1468 // Extended debugging
1469 $GLOBALS['wgShowSQLErrors'] = true;
1470 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1472 // Allow multiple ob_flush() calls
1473 $GLOBALS['wgDisableOutputCompression'] = true;
1475 // Use a sensible cookie prefix (not my_wiki)
1476 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1478 // Some of the environment checks make shell requests, remove limits
1479 $GLOBALS['wgMaxShellMemory'] = 0;
1483 * Add an installation step following the given step.
1485 * @param $callback Array A valid installation callback array, in this form:
1486 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1487 * @param $findStep String the step to find. Omit to put the step at the beginning
1489 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1490 $this->extraInstallSteps
[$findStep][] = $callback;