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(
80 * A list of environment check methods called by doEnvironmentChecks().
81 * These may output warnings using showMessage(), and/or abort the
82 * installation process by returning false.
86 protected $envChecks = array(
88 'envCheckRegisterGlobals',
91 'envCheckMagicQuotes',
92 'envCheckMagicSybase',
104 'envCheckShellLocale',
105 'envCheckUploadsDirectory',
110 * MediaWiki configuration globals that will eventually be passed through
111 * to LocalSettings.php. The names only are given here, the defaults
112 * typically come from DefaultSettings.php.
116 protected $defaultVarNames = array(
128 'wgEmailAuthentication',
131 'wgImageMagickConvertCommand',
136 'wgDeletedDirectory',
141 'wgUseInstantCommons',
147 * Variables that are stored alongside globals, and are used for any
148 * configuration of the installation process aside from the MediaWiki
149 * configuration. Map of names to defaults.
153 protected $internalDefaults = array(
155 '_Environment' => false,
156 '_CompiledDBs' => array(),
157 '_SafeMode' => false,
158 '_RaiseMemory' => false,
159 '_UpgradeDone' => false,
160 '_InstallDone' => false,
161 '_Caches' => array(),
162 '_InstallUser' => 'root',
163 '_InstallPassword' => '',
164 '_SameAccount' => true,
165 '_CreateDBAccount' => false,
166 '_NamespaceType' => 'site-name',
167 '_AdminName' => '', // will be set later, when the user selects language
168 '_AdminPassword' => '',
169 '_AdminPassword2' => '',
171 '_Subscribe' => false,
172 '_SkipOptional' => 'continue',
173 '_RightsProfile' => 'wiki',
174 '_LicenseCode' => 'none',
176 '_Extensions' => array(),
177 '_MemCachedServers' => '',
178 '_UpgradeKeySupplied' => false,
179 '_ExistingDBSettings' => false,
183 * The actual list of installation steps. This will be initialized by getInstallSteps()
187 private $installSteps = array();
190 * Extra steps for installation, for things like DatabaseInstallers to modify
194 protected $extraInstallSteps = array();
197 * Known object cache types and the functions used to test for their existence.
201 protected $objectCaches = array(
202 'xcache' => 'xcache_get',
203 'apc' => 'apc_fetch',
204 'eaccel' => 'eaccelerator_get',
205 'wincache' => 'wincache_ucache_get'
209 * User rights profiles.
213 public $rightsProfiles = array(
216 '*' => array( 'edit' => false )
220 'createaccount' => false,
226 'createaccount' => false,
238 public $licenses = array(
240 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
241 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
243 'cc-by-nc-sa' => array(
244 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
245 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
248 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
249 'icon' => '{$wgStylePath}/common/images/cc-0.png',
252 'url' => 'http://creativecommons.org/licenses/publicdomain/',
253 'icon' => '{$wgStylePath}/common/images/public-domain.png',
256 'url' => 'http://www.gnu.org/licenses/old-licenses/fdl-1.2.html',
257 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
259 'gfdl-current' => array(
260 'url' => 'http://www.gnu.org/copyleft/fdl.html',
261 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
268 'cc-choose' => array(
269 // Details will be filled in by the selector.
277 * URL to mediawiki-announce subscription
279 protected $mediaWikiAnnounceUrl = 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
282 * Supported language codes for Mailman
284 protected $mediaWikiAnnounceLanguages = array(
285 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
286 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
287 'sl', 'sr', 'sv', 'tr', 'uk'
291 * UI interface for displaying a short message
292 * The parameters are like parameters to wfMsg().
293 * The messages will be in wikitext format, which will be converted to an
294 * output format such as HTML or text before being sent to the user.
296 public abstract function showMessage( $msg /*, ... */ );
299 * Show a message to the installing user by using a Status object
300 * @param $status Status
302 public abstract function showStatusMessage( Status
$status );
305 * Constructor, always call this from child classes.
307 public function __construct() {
308 global $wgExtensionMessagesFiles, $wgUser;
310 // Disable the i18n cache and LoadBalancer
311 Language
::getLocalisationCache()->disableBackend();
312 LBFactory
::disableBackend();
314 // Load the installer's i18n file.
315 $wgExtensionMessagesFiles['MediawikiInstaller'] =
316 dirname( __FILE__
) . '/Installer.i18n.php';
318 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
319 $wgUser = User
::newFromId( 0 );
321 $this->settings
= $this->internalDefaults
;
323 foreach ( $this->defaultVarNames
as $var ) {
324 $this->settings
[$var] = $GLOBALS[$var];
327 foreach ( self
::getDBTypes() as $type ) {
328 $installer = $this->getDBInstaller( $type );
330 if ( !$installer->isCompiled() ) {
334 $defaults = $installer->getGlobalDefaults();
336 foreach ( $installer->getGlobalNames() as $var ) {
337 if ( isset( $defaults[$var] ) ) {
338 $this->settings
[$var] = $defaults[$var];
340 $this->settings
[$var] = $GLOBALS[$var];
345 $this->parserTitle
= Title
::newFromText( 'Installer' );
346 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
347 $this->parserOptions
->setEditSection( false );
351 * Get a list of known DB types.
353 public static function getDBTypes() {
354 return self
::$dbTypes;
358 * Do initial checks of the PHP environment. Set variables according to
359 * the observed environment.
361 * It's possible that this may be called under the CLI SAPI, not the SAPI
362 * that the wiki will primarily run under. In that case, the subclass should
363 * initialise variables such as wgScriptPath, before calling this function.
365 * Under the web subclass, it can already be assumed that PHP 5+ is in use
366 * and that sessions are working.
370 public function doEnvironmentChecks() {
371 $phpVersion = phpversion();
372 if( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
373 $this->showMessage( 'config-env-php', $phpVersion );
376 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
381 foreach ( $this->envChecks
as $check ) {
382 $status = $this->$check();
383 if ( $status === false ) {
389 $this->setVar( '_Environment', $good );
391 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
395 * Set a MW configuration variable, or internal installer configuration variable.
397 * @param $name String
398 * @param $value Mixed
400 public function setVar( $name, $value ) {
401 $this->settings
[$name] = $value;
405 * Get an MW configuration variable, or internal installer configuration variable.
406 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
407 * Installer variables are typically prefixed by an underscore.
409 * @param $name String
410 * @param $default Mixed
414 public function getVar( $name, $default = null ) {
415 if ( !isset( $this->settings
[$name] ) ) {
418 return $this->settings
[$name];
423 * Get an instance of DatabaseInstaller for the specified DB type.
425 * @param $type Mixed: DB installer for which is needed, false to use default.
427 * @return DatabaseInstaller
429 public function getDBInstaller( $type = false ) {
431 $type = $this->getVar( 'wgDBtype' );
434 $type = strtolower( $type );
436 if ( !isset( $this->dbInstallers
[$type] ) ) {
437 $class = ucfirst( $type ). 'Installer';
438 $this->dbInstallers
[$type] = new $class( $this );
441 return $this->dbInstallers
[$type];
445 * Determine if LocalSettings.php exists. If it does, return its variables,
446 * merged with those from AdminSettings.php, as an array.
450 public function getExistingLocalSettings() {
453 wfSuppressWarnings();
454 $_lsExists = file_exists( "$IP/LocalSettings.php" );
462 require( "$IP/includes/DefaultSettings.php" );
463 require( "$IP/LocalSettings.php" );
464 if ( file_exists( "$IP/AdminSettings.php" ) ) {
465 require( "$IP/AdminSettings.php" );
467 return get_defined_vars();
471 * Get a fake password for sending back to the user in HTML.
472 * This is a security mechanism to avoid compromise of the password in the
473 * event of session ID compromise.
475 * @param $realPassword String
479 public function getFakePassword( $realPassword ) {
480 return str_repeat( '*', strlen( $realPassword ) );
484 * Set a variable which stores a password, except if the new value is a
485 * fake password in which case leave it as it is.
487 * @param $name String
488 * @param $value Mixed
490 public function setPassword( $name, $value ) {
491 if ( !preg_match( '/^\*+$/', $value ) ) {
492 $this->setVar( $name, $value );
497 * On POSIX systems return the primary group of the webserver we're running under.
498 * On other systems just returns null.
500 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
501 * webserver user before he can install.
503 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
507 public static function maybeGetWebserverPrimaryGroup() {
508 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
509 # I don't know this, this isn't UNIX.
513 # posix_getegid() *not* getmygid() because we want the group of the webserver,
514 # not whoever owns the current script.
515 $gid = posix_getegid();
516 $getpwuid = posix_getpwuid( $gid );
517 $group = $getpwuid['name'];
523 * Convert wikitext $text to HTML.
525 * This is potentially error prone since many parser features require a complete
526 * installed MW database. The solution is to just not use those features when you
527 * write your messages. This appears to work well enough. Basic formatting and
528 * external links work just fine.
530 * But in case a translator decides to throw in a #ifexist or internal link or
531 * whatever, this function is guarded to catch the attempted DB access and to present
532 * some fallback text.
534 * @param $text String
535 * @param $lineStart Boolean
538 public function parse( $text, $lineStart = false ) {
542 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
543 $html = $out->getText();
544 } catch ( DBAccessError
$e ) {
545 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
547 if ( !empty( $this->debug
) ) {
548 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
555 public function getParserOptions() {
556 return $this->parserOptions
;
559 public function disableLinkPopups() {
560 $this->parserOptions
->setExternalLinkTarget( false );
563 public function restoreLinkPopups() {
564 global $wgExternalLinkTarget;
565 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
569 * Install step which adds a row to the site_stats table with appropriate
572 public function populateSiteStats( DatabaseInstaller
$installer ) {
573 $status = $installer->getConnection();
574 if ( !$status->isOK() ) {
577 $status->value
->insert( 'site_stats', array(
579 'ss_total_views' => 0,
580 'ss_total_edits' => 0,
581 'ss_good_articles' => 0,
582 'ss_total_pages' => 0,
586 __METHOD__
, 'IGNORE' );
587 return Status
::newGood();
591 * Exports all wg* variables stored by the installer into global scope.
593 public function exportVars() {
594 foreach ( $this->settings
as $name => $value ) {
595 if ( substr( $name, 0, 2 ) == 'wg' ) {
596 $GLOBALS[$name] = $value;
602 * Environment check for DB types.
604 protected function envCheckDB() {
607 $compiledDBs = array();
610 foreach ( self
::getDBTypes() as $name ) {
611 if ( $this->getDBInstaller( $name )->isCompiled() ) {
612 $compiledDBs[] = $name;
614 $allNames[] = wfMsg( 'config-type-' . $name );
617 $this->setVar( '_CompiledDBs', $compiledDBs );
619 if ( !$compiledDBs ) {
620 $this->showMessage( 'config-no-db' );
621 // FIXME: this only works for the web installer!
622 $this->showHelpBox( 'config-no-db-help', $wgLang->commaList( $allNames ) );
626 // Check for FTS3 full-text search module
627 $sqlite = $this->getDBInstaller( 'sqlite' );
628 if ( $sqlite->isCompiled() ) {
629 if( DatabaseSqlite
::getFulltextSearchModule() != 'FTS3' ) {
630 $this->showMessage( 'config-no-fts3' );
636 * Environment check for register_globals.
638 protected function envCheckRegisterGlobals() {
639 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
640 $this->showMessage( 'config-register-globals' );
645 * Some versions of libxml+PHP break < and > encoding horribly
647 protected function envCheckBrokenXML() {
648 $test = new PhpXmlBugTester();
650 $this->showMessage( 'config-brokenlibxml' );
656 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
657 * reference parameters to __call() are not converted to null
659 protected function envCheckPHP531() {
660 $test = new PhpRefCallBugTester
;
663 $this->showMessage( 'config-using531', phpversion() );
669 * Environment check for magic_quotes_runtime.
671 protected function envCheckMagicQuotes() {
672 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
673 $this->showMessage( 'config-magic-quotes-runtime' );
679 * Environment check for magic_quotes_sybase.
681 protected function envCheckMagicSybase() {
682 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
683 $this->showMessage( 'config-magic-quotes-sybase' );
689 * Environment check for mbstring.func_overload.
691 protected function envCheckMbstring() {
692 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
693 $this->showMessage( 'config-mbstring' );
699 * Environment check for zend.ze1_compatibility_mode.
701 protected function envCheckZE1() {
702 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
703 $this->showMessage( 'config-ze1' );
709 * Environment check for safe_mode.
711 protected function envCheckSafeMode() {
712 if ( wfIniGetBool( 'safe_mode' ) ) {
713 $this->setVar( '_SafeMode', true );
714 $this->showMessage( 'config-safe-mode' );
719 * Environment check for the XML module.
721 protected function envCheckXML() {
722 if ( !function_exists( "utf8_encode" ) ) {
723 $this->showMessage( 'config-xml-bad' );
729 * Environment check for the PCRE module.
731 protected function envCheckPCRE() {
732 if ( !function_exists( 'preg_match' ) ) {
733 $this->showMessage( 'config-pcre' );
736 wfSuppressWarnings();
737 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
739 if ( $regexd != '--' ) {
740 $this->showMessage( 'config-pcre-no-utf8' );
746 * Environment check for available memory.
748 protected function envCheckMemory() {
749 $limit = ini_get( 'memory_limit' );
751 if ( !$limit ||
$limit == -1 ) {
755 $n = wfShorthandToInteger( $limit );
757 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
758 $newLimit = "{$this->minMemorySize}M";
760 if( ini_set( "memory_limit", $newLimit ) === false ) {
761 $this->showMessage( 'config-memory-bad', $limit );
763 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
764 $this->setVar( '_RaiseMemory', true );
772 * Environment check for compiled object cache types.
774 protected function envCheckCache() {
776 foreach ( $this->objectCaches
as $name => $function ) {
777 if ( function_exists( $function ) ) {
778 $caches[$name] = true;
783 $this->showMessage( 'config-no-cache' );
786 $this->setVar( '_Caches', $caches );
790 * Search for GNU diff3.
792 protected function envCheckDiff3() {
793 $names = array( "gdiff3", "diff3", "diff3.exe" );
794 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
796 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
799 $this->setVar( 'wgDiff3', $diff3 );
801 $this->setVar( 'wgDiff3', false );
802 $this->showMessage( 'config-diff3-bad' );
807 * Environment check for ImageMagick and GD.
809 protected function envCheckGraphics() {
810 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
811 $convert = self
::locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
813 $this->setVar( 'wgImageMagickConvertCommand', '' );
815 $this->setVar( 'wgImageMagickConvertCommand', $convert );
816 $this->showMessage( 'config-imagemagick', $convert );
818 } elseif ( function_exists( 'imagejpeg' ) ) {
819 $this->showMessage( 'config-gd' );
822 $this->showMessage( 'config-no-scaling' );
827 * Environment check for setting $IP and $wgScriptPath.
829 protected function envCheckPath() {
831 $IP = dirname( dirname( dirname( __FILE__
) ) );
833 $this->setVar( 'IP', $IP );
835 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
836 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
837 // to get the path to the current script... hopefully it's reliable. SIGH
838 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
839 $path = $_SERVER['PHP_SELF'];
840 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
841 $path = $_SERVER['SCRIPT_NAME'];
842 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
843 // Some kind soul has set it for us already (e.g. debconf)
846 $this->showMessage( 'config-no-uri' );
850 $uri = preg_replace( '{^(.*)/(mw-)?config.*$}', '$1', $path );
851 $this->setVar( 'wgScriptPath', $uri );
855 * Environment check for setting the preferred PHP file extension.
857 protected function envCheckExtension() {
858 // FIXME: detect this properly
859 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
864 $this->setVar( 'wgScriptExtension', ".$ext" );
870 protected function envCheckShellLocale() {
871 $os = php_uname( 's' );
872 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
874 if ( !in_array( $os, $supported ) ) {
878 # Get a list of available locales.
880 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
886 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
887 $candidatesByLocale = array();
888 $candidatesByLang = array();
890 foreach ( $lines as $line ) {
891 if ( $line === '' ) {
895 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
899 list( $all, $lang, $territory, $charset, $modifier ) = $m;
901 $candidatesByLocale[$m[0]] = $m;
902 $candidatesByLang[$lang][] = $m;
905 # Try the current value of LANG.
906 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
907 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
911 # Try the most common ones.
912 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
913 foreach ( $commonLocales as $commonLocale ) {
914 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
915 $this->setVar( 'wgShellLocale', $commonLocale );
920 # Is there an available locale in the Wiki's language?
921 $wikiLang = $this->getVar( 'wgLanguageCode' );
923 if ( isset( $candidatesByLang[$wikiLang] ) ) {
924 $m = reset( $candidatesByLang[$wikiLang] );
925 $this->setVar( 'wgShellLocale', $m[0] );
929 # Are there any at all?
930 if ( count( $candidatesByLocale ) ) {
931 $m = reset( $candidatesByLocale );
932 $this->setVar( 'wgShellLocale', $m[0] );
943 protected function envCheckUploadsDirectory() {
944 global $IP, $wgServer;
946 $dir = $IP . '/images/';
947 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
948 $safe = !$this->dirIsExecutable( $dir, $url );
953 $this->showMessage( 'config-uploads-not-safe', $dir );
958 * Convert a hex string representing a Unicode code point to that code point.
962 protected function unicodeChar( $c ) {
966 } else if ($c <= 0x7FF) {
967 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
968 } else if ($c <= 0xFFFF) {
969 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
970 . chr(0x80 |
$c & 0x3F);
971 } else if ($c <= 0x10FFFF) {
972 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
973 . chr(0x80 |
$c >> 6 & 0x3F)
974 . chr(0x80 |
$c & 0x3F);
982 * Check the libicu version
984 protected function envCheckLibicu() {
985 $utf8 = function_exists( 'utf8_normalize' );
986 $intl = function_exists( 'normalizer_normalize' );
989 * This needs to be updated something that the latest libicu
990 * will properly normalize. This normalization was found at
991 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
992 * Note that we use the hex representation to create the code
993 * points in order to avoid any Unicode-destroying during transit.
995 $not_normal_c = $this->unicodeChar("FA6C");
996 $normal_c = $this->unicodeChar("242EE");
998 $useNormalizer = 'php';
999 $needsUpdate = false;
1002 * We're going to prefer the pecl extension here unless
1003 * utf8_normalize is more up to date.
1006 $useNormalizer = 'utf8';
1007 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
1008 if ( $utf8 !== $normal_c ) $needsUpdate = true;
1011 $useNormalizer = 'intl';
1012 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1013 if ( $intl !== $normal_c ) $needsUpdate = true;
1016 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
1017 if( $useNormalizer === 'php' ) {
1018 $this->showMessage( 'config-unicode-pure-php-warning' );
1020 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1021 if( $needsUpdate ) {
1022 $this->showMessage( 'config-unicode-update-warning' );
1028 * Get an array of likely places we can find executables. Check a bunch
1029 * of known Unix-like defaults, as well as the PATH environment variable
1030 * (which should maybe make it work for Windows?)
1034 protected static function getPossibleBinPaths() {
1036 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1037 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1038 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1043 * Search a path for any of the given executable names. Returns the
1044 * executable name if found. Also checks the version string returned
1045 * by each executable.
1047 * Used only by environment checks.
1049 * @param $path String: path to search
1050 * @param $names Array of executable names
1051 * @param $versionInfo Boolean false or array with two members:
1052 * 0 => Command to run for version check, with $1 for the full executable name
1053 * 1 => String to compare the output with
1055 * If $versionInfo is not false, only executables with a version
1056 * matching $versionInfo[1] will be returned.
1058 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1059 if ( !is_array( $names ) ) {
1060 $names = array( $names );
1063 foreach ( $names as $name ) {
1064 $command = $path . DIRECTORY_SEPARATOR
. $name;
1066 wfSuppressWarnings();
1067 $file_exists = file_exists( $command );
1068 wfRestoreWarnings();
1070 if ( $file_exists ) {
1071 if ( !$versionInfo ) {
1075 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1076 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1085 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1086 * @see locateExecutable()
1088 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1089 foreach( self
::getPossibleBinPaths() as $path ) {
1090 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1091 if( $exe !== false ) {
1099 * Checks if scripts located in the given directory can be executed via the given URL.
1101 * Used only by environment checks.
1103 public function dirIsExecutable( $dir, $url ) {
1104 $scriptTypes = array(
1106 "<?php echo 'ex' . 'ec';",
1107 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1111 // it would be good to check other popular languages here, but it'll be slow.
1113 wfSuppressWarnings();
1115 foreach ( $scriptTypes as $ext => $contents ) {
1116 foreach ( $contents as $source ) {
1117 $file = 'exectest.' . $ext;
1119 if ( !file_put_contents( $dir . $file, $source ) ) {
1123 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1124 unlink( $dir . $file );
1126 if ( $text == 'exec' ) {
1127 wfRestoreWarnings();
1133 wfRestoreWarnings();
1139 * ParserOptions are constructed before we determined the language, so fix it
1141 public function setParserLanguage( $lang ) {
1142 $this->parserOptions
->setTargetLanguage( $lang );
1143 $this->parserOptions
->setUserLang( $lang->getCode() );
1147 * Overridden by WebInstaller to provide lastPage parameters.
1149 protected function getDocUrl( $page ) {
1150 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1154 * Finds extensions that follow the format /extensions/Name/Name.php,
1155 * and returns an array containing the value for 'Name' for each found extension.
1159 public function findExtensions() {
1160 if( $this->getVar( 'IP' ) === null ) {
1165 $dir = $this->getVar( 'IP' ) . '/extensions';
1166 $dh = opendir( $dir );
1168 while ( ( $file = readdir( $dh ) ) !== false ) {
1169 if( file_exists( "$dir/$file/$file.php" ) ) {
1178 * Installs the auto-detected extensions.
1182 protected function includeExtensions() {
1184 $exts = $this->getVar( '_Extensions' );
1185 $IP = $this->getVar( 'IP' );
1186 $path = $IP . '/extensions';
1189 * We need to include DefaultSettings before including extensions to avoid
1190 * warnings about unset variables. However, the only thing we really
1191 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1192 * if the extension has hidden hook registration in $wgExtensionFunctions,
1193 * but we're not opening that can of worms
1194 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1196 global $wgAutoloadClasses;
1197 $wgAutoloadClasses = array();
1199 require( "$IP/includes/DefaultSettings.php" );
1201 foreach( $exts as $e ) {
1202 require_once( "$path/$e/$e.php" );
1205 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1206 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1208 // Unset everyone else's hooks. Lord knows what someone might be doing
1209 // in ParserFirstCallInit (see bug 27171)
1210 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1212 return Status
::newGood();
1216 * Get an array of install steps. Should always be in the format of
1218 * 'name' => 'someuniquename',
1219 * 'callback' => array( $obj, 'method' ),
1221 * There must be a config-install-$name message defined per step, which will
1222 * be shown on install.
1224 * @param $installer DatabaseInstaller so we can make callbacks
1227 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1228 $coreInstallSteps = array(
1229 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1230 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1231 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1232 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1233 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1234 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1235 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1238 // Build the array of install steps starting from the core install list,
1239 // then adding any callbacks that wanted to attach after a given step
1240 foreach( $coreInstallSteps as $step ) {
1241 $this->installSteps
[] = $step;
1242 if( isset( $this->extraInstallSteps
[ $step['name'] ] ) ) {
1243 $this->installSteps
= array_merge(
1244 $this->installSteps
,
1245 $this->extraInstallSteps
[ $step['name'] ]
1250 // Prepend any steps that want to be at the beginning
1251 if( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1252 $this->installSteps
= array_merge(
1253 $this->extraInstallSteps
['BEGINNING'],
1258 // Extensions should always go first, chance to tie into hooks and such
1259 if( count( $this->getVar( '_Extensions' ) ) ) {
1260 array_unshift( $this->installSteps
,
1261 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1263 $this->installSteps
[] = array(
1264 'name' => 'extension-tables',
1265 'callback' => array( $installer, 'createExtensionTables' )
1268 return $this->installSteps
;
1272 * Actually perform the installation.
1274 * @param $startCB Array A callback array for the beginning of each step
1275 * @param $endCB Array A callback array for the end of each step
1277 * @return Array of Status objects
1279 public function performInstallation( $startCB, $endCB ) {
1280 $installResults = array();
1281 $installer = $this->getDBInstaller();
1282 $installer->preInstall();
1283 $steps = $this->getInstallSteps( $installer );
1284 foreach( $steps as $stepObj ) {
1285 $name = $stepObj['name'];
1286 call_user_func_array( $startCB, array( $name ) );
1288 // Perform the callback step
1289 $status = call_user_func( $stepObj['callback'], $installer );
1291 // Output and save the results
1292 call_user_func( $endCB, $name, $status );
1293 $installResults[$name] = $status;
1295 // If we've hit some sort of fatal, we need to bail.
1296 // Callback already had a chance to do output above.
1297 if( !$status->isOk() ) {
1301 if( $status->isOk() ) {
1302 $this->setVar( '_InstallDone', true );
1304 return $installResults;
1308 * Generate $wgSecretKey. Will warn if we had to use mt_rand() instead of
1313 public function generateKeys() {
1314 $keys = array( 'wgSecretKey' => 64 );
1315 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1316 $keys['wgUpgradeKey'] = 16;
1318 return $this->doGenerateKeys( $keys );
1322 * Generate a secret value for variables using either
1323 * /dev/urandom or mt_rand(). Produce a warning in the later case.
1325 * @param $keys Array
1328 protected function doGenerateKeys( $keys ) {
1329 $status = Status
::newGood();
1331 wfSuppressWarnings();
1332 $file = fopen( "/dev/urandom", "r" );
1333 wfRestoreWarnings();
1335 foreach ( $keys as $name => $length ) {
1337 $secretKey = bin2hex( fread( $file, $length / 2 ) );
1341 for ( $i = 0; $i < $length / 8; $i++
) {
1342 $secretKey .= dechex( mt_rand( 0, 0x7fffffff ) );
1346 $this->setVar( $name, $secretKey );
1352 $names = array_keys ( $keys );
1353 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1355 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1362 * Create the first user account, grant it sysop and bureaucrat rights
1366 protected function createSysop() {
1367 $name = $this->getVar( '_AdminName' );
1368 $user = User
::newFromName( $name );
1371 // We should've validated this earlier anyway!
1372 return Status
::newFatal( 'config-admin-error-user', $name );
1375 if ( $user->idForName() == 0 ) {
1376 $user->addToDatabase();
1379 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1380 } catch( PasswordError
$pwe ) {
1381 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1384 $user->addGroup( 'sysop' );
1385 $user->addGroup( 'bureaucrat' );
1386 if( $this->getVar( '_AdminEmail' ) ) {
1387 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1389 $user->saveSettings();
1391 // Update user count
1392 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1393 $ssUpdate->doUpdate();
1395 $status = Status
::newGood();
1397 if( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1398 $this->subscribeToMediaWikiAnnounce( $status );
1404 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1406 'email' => $this->getVar( '_AdminEmail' ),
1411 // Mailman doesn't support as many languages as we do, so check to make
1412 // sure their selected language is available
1413 $myLang = $this->getVar( '_UserLang' );
1414 if( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1415 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1416 $params['language'] = $myLang;
1419 $res = Http
::post( $this->mediaWikiAnnounceUrl
, array( 'postData' => $params ) );
1421 $s->warning( 'config-install-subscribe-fail' );
1426 * Insert Main Page with default content.
1430 protected function createMainpage( DatabaseInstaller
$installer ) {
1431 $status = Status
::newGood();
1433 $article = new Article( Title
::newMainPage() );
1434 $article->doEdit( wfMsgForContent( 'mainpagetext' ) . "\n\n" .
1435 wfMsgForContent( 'mainpagedocfooter' ),
1439 User
::newFromName( 'MediaWiki default' ) );
1440 } catch (MWException
$e) {
1441 //using raw, because $wgShowExceptionDetails can not be set yet
1442 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1449 * Override the necessary bits of the config to run an installation.
1451 public static function overrideConfig() {
1452 define( 'MW_NO_SESSION', 1 );
1454 // Don't access the database
1455 $GLOBALS['wgUseDatabaseMessages'] = false;
1457 $GLOBALS['wgShowExceptionDetails'] = true;
1458 // Don't break forms
1459 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1461 // Extended debugging
1462 $GLOBALS['wgShowSQLErrors'] = true;
1463 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1465 // Allow multiple ob_flush() calls
1466 $GLOBALS['wgDisableOutputCompression'] = true;
1468 // Use a sensible cookie prefix (not my_wiki)
1469 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1471 // Some of the environment checks make shell requests, remove limits
1472 $GLOBALS['wgMaxShellMemory'] = 0;
1476 * Add an installation step following the given step.
1478 * @param $callback Array A valid installation callback array, in this form:
1479 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1480 * @param $findStep String the step to find. Omit to put the step at the beginning
1482 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1483 $this->extraInstallSteps
[$findStep][] = $callback;