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.0';
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 // Set our custom <doclink> hook.
321 $wgHooks['ParserFirstCallInit'][] = array( $this, 'registerDocLink' );
323 $this->settings
= $this->internalDefaults
;
325 foreach ( $this->defaultVarNames
as $var ) {
326 $this->settings
[$var] = $GLOBALS[$var];
329 foreach ( self
::getDBTypes() as $type ) {
330 $installer = $this->getDBInstaller( $type );
332 if ( !$installer->isCompiled() ) {
336 $defaults = $installer->getGlobalDefaults();
338 foreach ( $installer->getGlobalNames() as $var ) {
339 if ( isset( $defaults[$var] ) ) {
340 $this->settings
[$var] = $defaults[$var];
342 $this->settings
[$var] = $GLOBALS[$var];
347 $this->parserTitle
= Title
::newFromText( 'Installer' );
348 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
349 $this->parserOptions
->setEditSection( false );
353 * Get a list of known DB types.
355 public static function getDBTypes() {
356 return self
::$dbTypes;
360 * Do initial checks of the PHP environment. Set variables according to
361 * the observed environment.
363 * It's possible that this may be called under the CLI SAPI, not the SAPI
364 * that the wiki will primarily run under. In that case, the subclass should
365 * initialise variables such as wgScriptPath, before calling this function.
367 * Under the web subclass, it can already be assumed that PHP 5+ is in use
368 * and that sessions are working.
372 public function doEnvironmentChecks() {
373 $phpVersion = phpversion();
374 if( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
375 $this->showMessage( 'config-env-php', $phpVersion );
378 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
383 foreach ( $this->envChecks
as $check ) {
384 $status = $this->$check();
385 if ( $status === false ) {
391 $this->setVar( '_Environment', $good );
393 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
397 * Set a MW configuration variable, or internal installer configuration variable.
399 * @param $name String
400 * @param $value Mixed
402 public function setVar( $name, $value ) {
403 $this->settings
[$name] = $value;
407 * Get an MW configuration variable, or internal installer configuration variable.
408 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
409 * Installer variables are typically prefixed by an underscore.
411 * @param $name String
412 * @param $default Mixed
416 public function getVar( $name, $default = null ) {
417 if ( !isset( $this->settings
[$name] ) ) {
420 return $this->settings
[$name];
425 * Get an instance of DatabaseInstaller for the specified DB type.
427 * @param $type Mixed: DB installer for which is needed, false to use default.
429 * @return DatabaseInstaller
431 public function getDBInstaller( $type = false ) {
433 $type = $this->getVar( 'wgDBtype' );
436 $type = strtolower( $type );
438 if ( !isset( $this->dbInstallers
[$type] ) ) {
439 $class = ucfirst( $type ). 'Installer';
440 $this->dbInstallers
[$type] = new $class( $this );
443 return $this->dbInstallers
[$type];
447 * Determine if LocalSettings.php exists. If it does, return its variables,
448 * merged with those from AdminSettings.php, as an array.
452 public function getExistingLocalSettings() {
455 wfSuppressWarnings();
456 $_lsExists = file_exists( "$IP/LocalSettings.php" );
464 require( "$IP/includes/DefaultSettings.php" );
465 require( "$IP/LocalSettings.php" );
466 if ( file_exists( "$IP/AdminSettings.php" ) ) {
467 require( "$IP/AdminSettings.php" );
469 return get_defined_vars();
473 * Get a fake password for sending back to the user in HTML.
474 * This is a security mechanism to avoid compromise of the password in the
475 * event of session ID compromise.
477 * @param $realPassword String
481 public function getFakePassword( $realPassword ) {
482 return str_repeat( '*', strlen( $realPassword ) );
486 * Set a variable which stores a password, except if the new value is a
487 * fake password in which case leave it as it is.
489 * @param $name String
490 * @param $value Mixed
492 public function setPassword( $name, $value ) {
493 if ( !preg_match( '/^\*+$/', $value ) ) {
494 $this->setVar( $name, $value );
499 * On POSIX systems return the primary group of the webserver we're running under.
500 * On other systems just returns null.
502 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
503 * webserver user before he can install.
505 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
509 public static function maybeGetWebserverPrimaryGroup() {
510 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
511 # I don't know this, this isn't UNIX.
515 # posix_getegid() *not* getmygid() because we want the group of the webserver,
516 # not whoever owns the current script.
517 $gid = posix_getegid();
518 $getpwuid = posix_getpwuid( $gid );
519 $group = $getpwuid['name'];
525 * Convert wikitext $text to HTML.
527 * This is potentially error prone since many parser features require a complete
528 * installed MW database. The solution is to just not use those features when you
529 * write your messages. This appears to work well enough. Basic formatting and
530 * external links work just fine.
532 * But in case a translator decides to throw in a #ifexist or internal link or
533 * whatever, this function is guarded to catch the attempted DB access and to present
534 * some fallback text.
536 * @param $text String
537 * @param $lineStart Boolean
540 public function parse( $text, $lineStart = false ) {
544 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
545 $html = $out->getText();
546 } catch ( DBAccessError
$e ) {
547 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
549 if ( !empty( $this->debug
) ) {
550 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
557 public function getParserOptions() {
558 return $this->parserOptions
;
561 public function disableLinkPopups() {
562 $this->parserOptions
->setExternalLinkTarget( false );
565 public function restoreLinkPopups() {
566 global $wgExternalLinkTarget;
567 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
571 * Install step which adds a row to the site_stats table with appropriate
574 public function populateSiteStats( DatabaseInstaller
$installer ) {
575 $status = $installer->getConnection();
576 if ( !$status->isOK() ) {
579 $status->value
->insert( 'site_stats', array(
581 'ss_total_views' => 0,
582 'ss_total_edits' => 0,
583 'ss_good_articles' => 0,
584 'ss_total_pages' => 0,
588 __METHOD__
, 'IGNORE' );
589 return Status
::newGood();
593 * Exports all wg* variables stored by the installer into global scope.
595 public function exportVars() {
596 foreach ( $this->settings
as $name => $value ) {
597 if ( substr( $name, 0, 2 ) == 'wg' ) {
598 $GLOBALS[$name] = $value;
604 * Environment check for DB types.
606 protected function envCheckDB() {
609 $compiledDBs = array();
612 foreach ( self
::getDBTypes() as $name ) {
613 $db = $this->getDBInstaller( $name );
614 $readableName = wfMsg( 'config-type-' . $name );
616 if ( $db->isCompiled() ) {
617 $compiledDBs[] = $name;
619 $allNames[] = $readableName;
622 $this->setVar( '_CompiledDBs', $compiledDBs );
624 if ( !$compiledDBs ) {
625 $this->showMessage( 'config-no-db' );
626 // FIXME: this only works for the web installer!
627 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
631 // Check for FTS3 full-text search module
632 $sqlite = $this->getDBInstaller( 'sqlite' );
633 if ( $sqlite->isCompiled() ) {
634 $db = new DatabaseSqliteStandalone( ':memory:' );
635 if( $db->getFulltextSearchModule() != 'FTS3' ) {
636 $this->showMessage( 'config-no-fts3' );
642 * Environment check for register_globals.
644 protected function envCheckRegisterGlobals() {
645 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
646 $this->showMessage( 'config-register-globals' );
651 * Some versions of libxml+PHP break < and > encoding horribly
653 protected function envCheckBrokenXML() {
654 $test = new PhpXmlBugTester();
656 $this->showMessage( 'config-brokenlibxml' );
662 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
663 * reference parameters to __call() are not converted to null
665 protected function envCheckPHP531() {
666 $test = new PhpRefCallBugTester
;
669 $this->showMessage( 'config-using531', phpversion() );
675 * Environment check for magic_quotes_runtime.
677 protected function envCheckMagicQuotes() {
678 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
679 $this->showMessage( 'config-magic-quotes-runtime' );
685 * Environment check for magic_quotes_sybase.
687 protected function envCheckMagicSybase() {
688 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
689 $this->showMessage( 'config-magic-quotes-sybase' );
695 * Environment check for mbstring.func_overload.
697 protected function envCheckMbstring() {
698 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
699 $this->showMessage( 'config-mbstring' );
705 * Environment check for zend.ze1_compatibility_mode.
707 protected function envCheckZE1() {
708 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
709 $this->showMessage( 'config-ze1' );
715 * Environment check for safe_mode.
717 protected function envCheckSafeMode() {
718 if ( wfIniGetBool( 'safe_mode' ) ) {
719 $this->setVar( '_SafeMode', true );
720 $this->showMessage( 'config-safe-mode' );
725 * Environment check for the XML module.
727 protected function envCheckXML() {
728 if ( !function_exists( "utf8_encode" ) ) {
729 $this->showMessage( 'config-xml-bad' );
735 * Environment check for the PCRE module.
737 protected function envCheckPCRE() {
738 if ( !function_exists( 'preg_match' ) ) {
739 $this->showMessage( 'config-pcre' );
742 wfSuppressWarnings();
743 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
745 if ( $regexd != '--' ) {
746 $this->showMessage( 'config-pcre-no-utf8' );
752 * Environment check for available memory.
754 protected function envCheckMemory() {
755 $limit = ini_get( 'memory_limit' );
757 if ( !$limit ||
$limit == -1 ) {
761 $n = wfShorthandToInteger( $limit );
763 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
764 $newLimit = "{$this->minMemorySize}M";
766 if( ini_set( "memory_limit", $newLimit ) === false ) {
767 $this->showMessage( 'config-memory-bad', $limit );
769 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
770 $this->setVar( '_RaiseMemory', true );
778 * Environment check for compiled object cache types.
780 protected function envCheckCache() {
782 foreach ( $this->objectCaches
as $name => $function ) {
783 if ( function_exists( $function ) ) {
784 $caches[$name] = true;
789 $this->showMessage( 'config-no-cache' );
792 $this->setVar( '_Caches', $caches );
796 * Search for GNU diff3.
798 protected function envCheckDiff3() {
799 $names = array( "gdiff3", "diff3", "diff3.exe" );
800 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
802 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
805 $this->setVar( 'wgDiff3', $diff3 );
807 $this->setVar( 'wgDiff3', false );
808 $this->showMessage( 'config-diff3-bad' );
813 * Environment check for ImageMagick and GD.
815 protected function envCheckGraphics() {
816 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
817 $convert = self
::locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
819 $this->setVar( 'wgImageMagickConvertCommand', '' );
821 $this->setVar( 'wgImageMagickConvertCommand', $convert );
822 $this->showMessage( 'config-imagemagick', $convert );
824 } elseif ( function_exists( 'imagejpeg' ) ) {
825 $this->showMessage( 'config-gd' );
828 $this->showMessage( 'no-scaling' );
833 * Environment check for setting $IP and $wgScriptPath.
835 protected function envCheckPath() {
837 $IP = dirname( dirname( dirname( __FILE__
) ) );
839 $this->setVar( 'IP', $IP );
841 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
842 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
843 // to get the path to the current script... hopefully it's reliable. SIGH
844 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
845 $path = $_SERVER['PHP_SELF'];
846 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
847 $path = $_SERVER['SCRIPT_NAME'];
848 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
849 // Some kind soul has set it for us already (e.g. debconf)
852 $this->showMessage( 'config-no-uri' );
856 $uri = preg_replace( '{^(.*)/(mw-)?config.*$}', '$1', $path );
857 $this->setVar( 'wgScriptPath', $uri );
861 * Environment check for setting the preferred PHP file extension.
863 protected function envCheckExtension() {
864 // FIXME: detect this properly
865 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
870 $this->setVar( 'wgScriptExtension', ".$ext" );
876 protected function envCheckShellLocale() {
877 $os = php_uname( 's' );
878 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
880 if ( !in_array( $os, $supported ) ) {
884 # Get a list of available locales.
886 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
892 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
893 $candidatesByLocale = array();
894 $candidatesByLang = array();
896 foreach ( $lines as $line ) {
897 if ( $line === '' ) {
901 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
905 list( $all, $lang, $territory, $charset, $modifier ) = $m;
907 $candidatesByLocale[$m[0]] = $m;
908 $candidatesByLang[$lang][] = $m;
911 # Try the current value of LANG.
912 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
913 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
917 # Try the most common ones.
918 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
919 foreach ( $commonLocales as $commonLocale ) {
920 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
921 $this->setVar( 'wgShellLocale', $commonLocale );
926 # Is there an available locale in the Wiki's language?
927 $wikiLang = $this->getVar( 'wgLanguageCode' );
929 if ( isset( $candidatesByLang[$wikiLang] ) ) {
930 $m = reset( $candidatesByLang[$wikiLang] );
931 $this->setVar( 'wgShellLocale', $m[0] );
935 # Are there any at all?
936 if ( count( $candidatesByLocale ) ) {
937 $m = reset( $candidatesByLocale );
938 $this->setVar( 'wgShellLocale', $m[0] );
949 protected function envCheckUploadsDirectory() {
950 global $IP, $wgServer;
952 $dir = $IP . '/images/';
953 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
954 $safe = !$this->dirIsExecutable( $dir, $url );
959 $this->showMessage( 'config-uploads-not-safe', $dir );
964 * Convert a hex string representing a Unicode code point to that code point.
968 protected function unicodeChar( $c ) {
972 } else if ($c <= 0x7FF) {
973 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
974 } else if ($c <= 0xFFFF) {
975 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
976 . chr(0x80 |
$c & 0x3F);
977 } else if ($c <= 0x10FFFF) {
978 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
979 . chr(0x80 |
$c >> 6 & 0x3F)
980 . chr(0x80 |
$c & 0x3F);
988 * Check the libicu version
990 protected function envCheckLibicu() {
991 $utf8 = function_exists( 'utf8_normalize' );
992 $intl = function_exists( 'normalizer_normalize' );
995 * This needs to be updated something that the latest libicu
996 * will properly normalize. This normalization was found at
997 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
998 * Note that we use the hex representation to create the code
999 * points in order to avoid any Unicode-destroying during transit.
1001 $not_normal_c = $this->unicodeChar("FA6C");
1002 $normal_c = $this->unicodeChar("242EE");
1004 $useNormalizer = 'php';
1005 $needsUpdate = false;
1008 * We're going to prefer the pecl extension here unless
1009 * utf8_normalize is more up to date.
1012 $useNormalizer = 'utf8';
1013 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
1014 if ( $utf8 !== $normal_c ) $needsUpdate = true;
1017 $useNormalizer = 'intl';
1018 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1019 if ( $intl !== $normal_c ) $needsUpdate = true;
1022 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
1023 if( $useNormalizer === 'php' ) {
1024 $this->showMessage( 'config-unicode-pure-php-warning' );
1026 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1027 if( $needsUpdate ) {
1028 $this->showMessage( 'config-unicode-update-warning' );
1034 * Get an array of likely places we can find executables. Check a bunch
1035 * of known Unix-like defaults, as well as the PATH environment variable
1036 * (which should maybe make it work for Windows?)
1040 protected static function getPossibleBinPaths() {
1042 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1043 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1044 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1049 * Search a path for any of the given executable names. Returns the
1050 * executable name if found. Also checks the version string returned
1051 * by each executable.
1053 * Used only by environment checks.
1055 * @param $path String: path to search
1056 * @param $names Array of executable names
1057 * @param $versionInfo Boolean false or array with two members:
1058 * 0 => Command to run for version check, with $1 for the full executable name
1059 * 1 => String to compare the output with
1061 * If $versionInfo is not false, only executables with a version
1062 * matching $versionInfo[1] will be returned.
1064 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1065 if ( !is_array( $names ) ) {
1066 $names = array( $names );
1069 foreach ( $names as $name ) {
1070 $command = $path . DIRECTORY_SEPARATOR
. $name;
1072 wfSuppressWarnings();
1073 $file_exists = file_exists( $command );
1074 wfRestoreWarnings();
1076 if ( $file_exists ) {
1077 if ( !$versionInfo ) {
1081 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1082 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1091 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1092 * @see locateExecutable()
1094 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1095 foreach( self
::getPossibleBinPaths() as $path ) {
1096 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1097 if( $exe !== false ) {
1105 * Checks if scripts located in the given directory can be executed via the given URL.
1107 * Used only by environment checks.
1109 public function dirIsExecutable( $dir, $url ) {
1110 $scriptTypes = array(
1112 "<?php echo 'ex' . 'ec';",
1113 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1117 // it would be good to check other popular languages here, but it'll be slow.
1119 wfSuppressWarnings();
1121 foreach ( $scriptTypes as $ext => $contents ) {
1122 foreach ( $contents as $source ) {
1123 $file = 'exectest.' . $ext;
1125 if ( !file_put_contents( $dir . $file, $source ) ) {
1129 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1130 unlink( $dir . $file );
1132 if ( $text == 'exec' ) {
1133 wfRestoreWarnings();
1139 wfRestoreWarnings();
1145 * Register tag hook below.
1147 * @todo Move this to WebInstaller with the two things below?
1149 * @param $parser Parser
1151 public function registerDocLink( Parser
&$parser ) {
1152 $parser->setHook( 'doclink', array( $this, 'docLink' ) );
1157 * ParserOptions are constructed before we determined the language, so fix it
1159 public function setParserLanguage( $lang ) {
1160 $this->parserOptions
->setTargetLanguage( $lang );
1161 $this->parserOptions
->setUserLang( $lang->getCode() );
1165 * Extension tag hook for a documentation link.
1167 public function docLink( $linkText, $attribs, $parser ) {
1168 $url = $this->getDocUrl( $attribs['href'] );
1169 return '<a href="' . htmlspecialchars( $url ) . '">' .
1170 htmlspecialchars( $linkText ) .
1175 * Overridden by WebInstaller to provide lastPage parameters.
1177 protected function getDocUrl( $page ) {
1178 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1182 * Finds extensions that follow the format /extensions/Name/Name.php,
1183 * and returns an array containing the value for 'Name' for each found extension.
1187 public function findExtensions() {
1188 if( $this->getVar( 'IP' ) === null ) {
1193 $dir = $this->getVar( 'IP' ) . '/extensions';
1194 $dh = opendir( $dir );
1196 while ( ( $file = readdir( $dh ) ) !== false ) {
1197 if( file_exists( "$dir/$file/$file.php" ) ) {
1206 * Installs the auto-detected extensions.
1210 protected function includeExtensions() {
1212 $exts = $this->getVar( '_Extensions' );
1213 $IP = $this->getVar( 'IP' );
1214 $path = $IP . '/extensions';
1217 * We need to include DefaultSettings before including extensions to avoid
1218 * warnings about unset variables. However, the only thing we really
1219 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1220 * if the extension has hidden hook registration in $wgExtensionFunctions,
1221 * but we're not opening that can of worms
1222 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1224 global $wgHooks, $wgAutoloadClasses;
1225 require( "$IP/includes/DefaultSettings.php" );
1227 foreach( $exts as $e ) {
1228 require( "$path/$e/$e.php" );
1231 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1232 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1234 // Unset everyone else's hooks. Lord knows what someone might be doing
1235 // in ParserFirstCallInit (see bug 27171)
1237 $wgHooks = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1239 return Status
::newGood();
1243 * Get an array of install steps. Should always be in the format of
1245 * 'name' => 'someuniquename',
1246 * 'callback' => array( $obj, 'method' ),
1248 * There must be a config-install-$name message defined per step, which will
1249 * be shown on install.
1251 * @param $installer DatabaseInstaller so we can make callbacks
1254 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1255 $coreInstallSteps = array(
1256 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1257 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1258 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1259 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1260 array( 'name' => 'secretkey', 'callback' => array( $this, 'generateSecretKey' ) ),
1261 array( 'name' => 'upgradekey', 'callback' => array( $this, 'generateUpgradeKey' ) ),
1262 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1263 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1266 // Build the array of install steps starting from the core install list,
1267 // then adding any callbacks that wanted to attach after a given step
1268 foreach( $coreInstallSteps as $step ) {
1269 $this->installSteps
[] = $step;
1270 if( isset( $this->extraInstallSteps
[ $step['name'] ] ) ) {
1271 $this->installSteps
= array_merge(
1272 $this->installSteps
,
1273 $this->extraInstallSteps
[ $step['name'] ]
1278 // Prepend any steps that want to be at the beginning
1279 if( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1280 $this->installSteps
= array_merge(
1281 $this->extraInstallSteps
['BEGINNING'],
1286 // Extensions should always go first, chance to tie into hooks and such
1287 if( count( $this->getVar( '_Extensions' ) ) ) {
1288 array_unshift( $this->installSteps
,
1289 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1291 $this->installSteps
[] = array(
1292 'name' => 'extension-tables',
1293 'callback' => array( $installer, 'createExtensionTables' )
1296 return $this->installSteps
;
1300 * Actually perform the installation.
1302 * @param $startCB Array A callback array for the beginning of each step
1303 * @param $endCB Array A callback array for the end of each step
1305 * @return Array of Status objects
1307 public function performInstallation( $startCB, $endCB ) {
1308 $installResults = array();
1309 $installer = $this->getDBInstaller();
1310 $installer->preInstall();
1311 $steps = $this->getInstallSteps( $installer );
1312 foreach( $steps as $stepObj ) {
1313 $name = $stepObj['name'];
1314 call_user_func_array( $startCB, array( $name ) );
1316 // Perform the callback step
1317 $status = call_user_func( $stepObj['callback'], $installer );
1319 // Output and save the results
1320 call_user_func( $endCB, $name, $status );
1321 $installResults[$name] = $status;
1323 // If we've hit some sort of fatal, we need to bail.
1324 // Callback already had a chance to do output above.
1325 if( !$status->isOk() ) {
1329 if( $status->isOk() ) {
1330 $this->setVar( '_InstallDone', true );
1332 return $installResults;
1336 * Generate $wgSecretKey. Will warn if we had to use mt_rand() instead of
1341 protected function generateSecretKey() {
1342 return $this->generateSecret( 'wgSecretKey' );
1346 * Generate a secret value for a variable using either
1347 * /dev/urandom or mt_rand() Produce a warning in the later case.
1351 protected function generateSecret( $secretName, $length = 64 ) {
1352 if ( wfIsWindows() ) {
1355 wfSuppressWarnings();
1356 $file = fopen( "/dev/urandom", "r" );
1357 wfRestoreWarnings();
1360 $status = Status
::newGood();
1363 $secretKey = bin2hex( fread( $file, $length / 2 ) );
1368 for ( $i = 0; $i < $length / 8; $i++
) {
1369 $secretKey .= dechex( mt_rand( 0, 0x7fffffff ) );
1372 $status->warning( 'config-insecure-secret', '$' . $secretName );
1375 $this->setVar( $secretName, $secretKey );
1381 * Generate a default $wgUpgradeKey. Will warn if we had to use
1382 * mt_rand() instead of /dev/urandom
1386 public function generateUpgradeKey() {
1387 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1388 return $this->generateSecret( 'wgUpgradeKey', 16 );
1390 return Status
::newGood();
1394 * Create the first user account, grant it sysop and bureaucrat rights
1398 protected function createSysop() {
1399 $name = $this->getVar( '_AdminName' );
1400 $user = User
::newFromName( $name );
1403 // We should've validated this earlier anyway!
1404 return Status
::newFatal( 'config-admin-error-user', $name );
1407 if ( $user->idForName() == 0 ) {
1408 $user->addToDatabase();
1411 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1412 } catch( PasswordError
$pwe ) {
1413 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1416 $user->addGroup( 'sysop' );
1417 $user->addGroup( 'bureaucrat' );
1418 if( $this->getVar( '_AdminEmail' ) ) {
1419 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1421 $user->saveSettings();
1423 // Update user count
1424 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1425 $ssUpdate->doUpdate();
1427 $status = Status
::newGood();
1429 if( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1430 $this->subscribeToMediaWikiAnnounce( $status );
1436 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1438 'email' => $this->getVar( '_AdminEmail' ),
1443 // Mailman doesn't support as many languages as we do, so check to make
1444 // sure their selected language is available
1445 $myLang = $this->getVar( '_UserLang' );
1446 if( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1447 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1448 $params['language'] = $myLang;
1451 $res = Http
::post( $this->mediaWikiAnnounceUrl
, array( 'postData' => $params ) );
1453 $s->warning( 'config-install-subscribe-fail' );
1458 * Insert Main Page with default content.
1462 protected function createMainpage( DatabaseInstaller
$installer ) {
1463 $status = Status
::newGood();
1465 $article = new Article( Title
::newMainPage() );
1466 $article->doEdit( wfMsgForContent( 'mainpagetext' ) . "\n\n" .
1467 wfMsgForContent( 'mainpagedocfooter' ),
1471 User
::newFromName( 'MediaWiki default' ) );
1472 } catch (MWException
$e) {
1473 //using raw, because $wgShowExceptionDetails can not be set yet
1474 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1481 * Override the necessary bits of the config to run an installation.
1483 public static function overrideConfig() {
1484 define( 'MW_NO_SESSION', 1 );
1486 // Don't access the database
1487 $GLOBALS['wgUseDatabaseMessages'] = false;
1489 $GLOBALS['wgShowExceptionDetails'] = true;
1490 // Don't break forms
1491 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1493 // Extended debugging
1494 $GLOBALS['wgShowSQLErrors'] = true;
1495 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1497 // Allow multiple ob_flush() calls
1498 $GLOBALS['wgDisableOutputCompression'] = true;
1500 // Use a sensible cookie prefix (not my_wiki)
1501 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1503 // Some of the environment checks make shell requests, remove limits
1504 $GLOBALS['wgMaxShellMemory'] = 0;
1508 * Add an installation step following the given step.
1510 * @param $callback Array A valid installation callback array, in this form:
1511 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1512 * @param $findStep String the step to find. Omit to put the step at the beginning
1514 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1515 $this->extraInstallSteps
[$findStep][] = $callback;