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',
100 'envCheckModSecurity',
106 'envCheckShellLocale',
107 'envCheckUploadsDirectory',
109 'envCheckSuhosinMaxValueLength',
113 * MediaWiki configuration globals that will eventually be passed through
114 * to LocalSettings.php. The names only are given here, the defaults
115 * typically come from DefaultSettings.php.
119 protected $defaultVarNames = array(
131 'wgEmailAuthentication',
134 'wgImageMagickConvertCommand',
140 'wgDeletedDirectory',
145 'wgUseInstantCommons',
148 'wgResourceLoaderMaxQueryLength',
152 * Variables that are stored alongside globals, and are used for any
153 * configuration of the installation process aside from the MediaWiki
154 * configuration. Map of names to defaults.
158 protected $internalDefaults = array(
160 '_Environment' => false,
161 '_CompiledDBs' => array(),
162 '_SafeMode' => false,
163 '_RaiseMemory' => false,
164 '_UpgradeDone' => false,
165 '_InstallDone' => false,
166 '_Caches' => array(),
167 '_InstallPassword' => '',
168 '_SameAccount' => true,
169 '_CreateDBAccount' => false,
170 '_NamespaceType' => 'site-name',
171 '_AdminName' => '', // will be set later, when the user selects language
172 '_AdminPassword' => '',
173 '_AdminPassword2' => '',
175 '_Subscribe' => false,
176 '_SkipOptional' => 'continue',
177 '_RightsProfile' => 'wiki',
178 '_LicenseCode' => 'none',
180 '_Extensions' => array(),
181 '_MemCachedServers' => '',
182 '_UpgradeKeySupplied' => false,
183 '_ExistingDBSettings' => false,
187 * The actual list of installation steps. This will be initialized by getInstallSteps()
191 private $installSteps = array();
194 * Extra steps for installation, for things like DatabaseInstallers to modify
198 protected $extraInstallSteps = array();
201 * Known object cache types and the functions used to test for their existence.
205 protected $objectCaches = array(
206 'xcache' => 'xcache_get',
207 'apc' => 'apc_fetch',
208 'eaccel' => 'eaccelerator_get',
209 'wincache' => 'wincache_ucache_get'
213 * User rights profiles.
217 public $rightsProfiles = array(
220 '*' => array( 'edit' => false )
224 'createaccount' => false,
230 'createaccount' => false,
242 public $licenses = array(
244 'url' => 'http://creativecommons.org/licenses/by/3.0/',
245 'icon' => '{$wgStylePath}/common/images/cc-by.png',
248 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
249 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
251 'cc-by-nc-sa' => array(
252 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
253 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
256 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
257 'icon' => '{$wgStylePath}/common/images/cc-0.png',
261 'icon' => '{$wgStylePath}/common/images/public-domain.png',
264 'url' => 'http://www.gnu.org/copyleft/fdl.html',
265 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
272 'cc-choose' => array(
273 // Details will be filled in by the selector.
281 * URL to mediawiki-announce subscription
283 protected $mediaWikiAnnounceUrl = 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
286 * Supported language codes for Mailman
288 protected $mediaWikiAnnounceLanguages = array(
289 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
290 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
291 'sl', 'sr', 'sv', 'tr', 'uk'
295 * UI interface for displaying a short message
296 * The parameters are like parameters to wfMsg().
297 * The messages will be in wikitext format, which will be converted to an
298 * output format such as HTML or text before being sent to the user.
300 public abstract function showMessage( $msg /*, ... */ );
303 * Same as showMessage(), but for displaying errors
305 public abstract function showError( $msg /*, ... */ );
308 * Show a message to the installing user by using a Status object
309 * @param $status Status
311 public abstract function showStatusMessage( Status
$status );
314 * Constructor, always call this from child classes.
316 public function __construct() {
317 global $wgExtensionMessagesFiles, $wgUser;
319 // Disable the i18n cache and LoadBalancer
320 Language
::getLocalisationCache()->disableBackend();
321 LBFactory
::disableBackend();
323 // Load the installer's i18n file.
324 $wgExtensionMessagesFiles['MediawikiInstaller'] =
325 dirname( __FILE__
) . '/Installer.i18n.php';
327 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
328 $wgUser = User
::newFromId( 0 );
330 $this->settings
= $this->internalDefaults
;
332 foreach ( $this->defaultVarNames
as $var ) {
333 $this->settings
[$var] = $GLOBALS[$var];
336 $compiledDBs = array();
337 foreach ( self
::getDBTypes() as $type ) {
338 $installer = $this->getDBInstaller( $type );
340 if ( !$installer->isCompiled() ) {
343 $compiledDBs[] = $type;
345 $defaults = $installer->getGlobalDefaults();
347 foreach ( $installer->getGlobalNames() as $var ) {
348 if ( isset( $defaults[$var] ) ) {
349 $this->settings
[$var] = $defaults[$var];
351 $this->settings
[$var] = $GLOBALS[$var];
355 $this->setVar( '_CompiledDBs', $compiledDBs );
357 $this->parserTitle
= Title
::newFromText( 'Installer' );
358 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
359 $this->parserOptions
->setEditSection( false );
363 * Get a list of known DB types.
367 public static function getDBTypes() {
368 return self
::$dbTypes;
372 * Do initial checks of the PHP environment. Set variables according to
373 * the observed environment.
375 * It's possible that this may be called under the CLI SAPI, not the SAPI
376 * that the wiki will primarily run under. In that case, the subclass should
377 * initialise variables such as wgScriptPath, before calling this function.
379 * Under the web subclass, it can already be assumed that PHP 5+ is in use
380 * and that sessions are working.
384 public function doEnvironmentChecks() {
385 $phpVersion = phpversion();
386 if( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
387 $this->showMessage( 'config-env-php', $phpVersion );
390 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
395 foreach ( $this->envChecks
as $check ) {
396 $status = $this->$check();
397 if ( $status === false ) {
403 $this->setVar( '_Environment', $good );
405 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
409 * Set a MW configuration variable, or internal installer configuration variable.
411 * @param $name String
412 * @param $value Mixed
414 public function setVar( $name, $value ) {
415 $this->settings
[$name] = $value;
419 * Get an MW configuration variable, or internal installer configuration variable.
420 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
421 * Installer variables are typically prefixed by an underscore.
423 * @param $name String
424 * @param $default Mixed
428 public function getVar( $name, $default = null ) {
429 if ( !isset( $this->settings
[$name] ) ) {
432 return $this->settings
[$name];
437 * Get an instance of DatabaseInstaller for the specified DB type.
439 * @param $type Mixed: DB installer for which is needed, false to use default.
441 * @return DatabaseInstaller
443 public function getDBInstaller( $type = false ) {
445 $type = $this->getVar( 'wgDBtype' );
448 $type = strtolower( $type );
450 if ( !isset( $this->dbInstallers
[$type] ) ) {
451 $class = ucfirst( $type ). 'Installer';
452 $this->dbInstallers
[$type] = new $class( $this );
455 return $this->dbInstallers
[$type];
459 * Determine if LocalSettings.php exists. If it does, return its variables,
460 * merged with those from AdminSettings.php, as an array.
464 public static function getExistingLocalSettings() {
467 wfSuppressWarnings();
468 $_lsExists = file_exists( "$IP/LocalSettings.php" );
476 require( "$IP/includes/DefaultSettings.php" );
477 require( "$IP/LocalSettings.php" );
478 if ( file_exists( "$IP/AdminSettings.php" ) ) {
479 require( "$IP/AdminSettings.php" );
481 return get_defined_vars();
485 * Get a fake password for sending back to the user in HTML.
486 * This is a security mechanism to avoid compromise of the password in the
487 * event of session ID compromise.
489 * @param $realPassword String
493 public function getFakePassword( $realPassword ) {
494 return str_repeat( '*', strlen( $realPassword ) );
498 * Set a variable which stores a password, except if the new value is a
499 * fake password in which case leave it as it is.
501 * @param $name String
502 * @param $value Mixed
504 public function setPassword( $name, $value ) {
505 if ( !preg_match( '/^\*+$/', $value ) ) {
506 $this->setVar( $name, $value );
511 * On POSIX systems return the primary group of the webserver we're running under.
512 * On other systems just returns null.
514 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
515 * webserver user before he can install.
517 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
521 public static function maybeGetWebserverPrimaryGroup() {
522 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
523 # I don't know this, this isn't UNIX.
527 # posix_getegid() *not* getmygid() because we want the group of the webserver,
528 # not whoever owns the current script.
529 $gid = posix_getegid();
530 $getpwuid = posix_getpwuid( $gid );
531 $group = $getpwuid['name'];
537 * Convert wikitext $text to HTML.
539 * This is potentially error prone since many parser features require a complete
540 * installed MW database. The solution is to just not use those features when you
541 * write your messages. This appears to work well enough. Basic formatting and
542 * external links work just fine.
544 * But in case a translator decides to throw in a #ifexist or internal link or
545 * whatever, this function is guarded to catch the attempted DB access and to present
546 * some fallback text.
548 * @param $text String
549 * @param $lineStart Boolean
552 public function parse( $text, $lineStart = false ) {
556 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
557 $html = $out->getText();
558 } catch ( DBAccessError
$e ) {
559 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
561 if ( !empty( $this->debug
) ) {
562 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
570 * @return ParserOptions
572 public function getParserOptions() {
573 return $this->parserOptions
;
576 public function disableLinkPopups() {
577 $this->parserOptions
->setExternalLinkTarget( false );
580 public function restoreLinkPopups() {
581 global $wgExternalLinkTarget;
582 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
586 * Install step which adds a row to the site_stats table with appropriate
589 * @param $installer DatabaseInstaller
593 public function populateSiteStats( DatabaseInstaller
$installer ) {
594 $status = $installer->getConnection();
595 if ( !$status->isOK() ) {
598 $status->value
->insert( 'site_stats', array(
600 'ss_total_views' => 0,
601 'ss_total_edits' => 0,
602 'ss_good_articles' => 0,
603 'ss_total_pages' => 0,
607 __METHOD__
, 'IGNORE' );
608 return Status
::newGood();
612 * Exports all wg* variables stored by the installer into global scope.
614 public function exportVars() {
615 foreach ( $this->settings
as $name => $value ) {
616 if ( substr( $name, 0, 2 ) == 'wg' ) {
617 $GLOBALS[$name] = $value;
623 * Environment check for DB types.
625 protected function envCheckDB() {
630 foreach ( self
::getDBTypes() as $name ) {
631 $allNames[] = wfMsg( "config-type-$name" );
634 if ( !$this->getVar( '_CompiledDBs' ) ) {
635 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
636 // @todo FIXME: This only works for the web installer!
640 // Check for FTS3 full-text search module
641 $sqlite = $this->getDBInstaller( 'sqlite' );
642 if ( $sqlite->isCompiled() ) {
643 if( DatabaseSqlite
::getFulltextSearchModule() != 'FTS3' ) {
644 $this->showMessage( 'config-no-fts3' );
650 * Environment check for register_globals.
652 protected function envCheckRegisterGlobals() {
653 if( wfIniGetBool( 'register_globals' ) ) {
654 $this->showMessage( 'config-register-globals' );
659 * Some versions of libxml+PHP break < and > encoding horribly
661 protected function envCheckBrokenXML() {
662 $test = new PhpXmlBugTester();
664 $this->showError( 'config-brokenlibxml' );
670 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
671 * reference parameters to __call() are not converted to null
673 protected function envCheckPHP531() {
674 $test = new PhpRefCallBugTester
;
677 $this->showError( 'config-using531', phpversion() );
683 * Environment check for magic_quotes_runtime.
685 protected function envCheckMagicQuotes() {
686 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
687 $this->showError( 'config-magic-quotes-runtime' );
693 * Environment check for magic_quotes_sybase.
695 protected function envCheckMagicSybase() {
696 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
697 $this->showError( 'config-magic-quotes-sybase' );
703 * Environment check for mbstring.func_overload.
705 protected function envCheckMbstring() {
706 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
707 $this->showError( 'config-mbstring' );
713 * Environment check for zend.ze1_compatibility_mode.
715 protected function envCheckZE1() {
716 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
717 $this->showError( 'config-ze1' );
723 * Environment check for safe_mode.
725 protected function envCheckSafeMode() {
726 if ( wfIniGetBool( 'safe_mode' ) ) {
727 $this->setVar( '_SafeMode', true );
728 $this->showMessage( 'config-safe-mode' );
733 * Environment check for the XML module.
735 protected function envCheckXML() {
736 if ( !function_exists( "utf8_encode" ) ) {
737 $this->showError( 'config-xml-bad' );
743 * Environment check for the PCRE module.
745 protected function envCheckPCRE() {
746 if ( !function_exists( 'preg_match' ) ) {
747 $this->showError( 'config-pcre' );
750 wfSuppressWarnings();
751 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
753 if ( $regexd != '--' ) {
754 $this->showError( 'config-pcre-no-utf8' );
760 * Environment check for available memory.
762 protected function envCheckMemory() {
763 $limit = ini_get( 'memory_limit' );
765 if ( !$limit ||
$limit == -1 ) {
769 $n = wfShorthandToInteger( $limit );
771 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
772 $newLimit = "{$this->minMemorySize}M";
774 if( ini_set( "memory_limit", $newLimit ) === false ) {
775 $this->showMessage( 'config-memory-bad', $limit );
777 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
778 $this->setVar( '_RaiseMemory', true );
786 * Environment check for compiled object cache types.
788 protected function envCheckCache() {
790 foreach ( $this->objectCaches
as $name => $function ) {
791 if ( function_exists( $function ) ) {
792 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
795 $caches[$name] = true;
800 $this->showMessage( 'config-no-cache' );
803 $this->setVar( '_Caches', $caches );
807 * Scare user to death if they have mod_security
809 protected function envCheckModSecurity() {
810 if ( self
::apacheModulePresent( 'mod_security' ) ) {
811 $this->showMessage( 'config-mod-security' );
816 * Search for GNU diff3.
818 protected function envCheckDiff3() {
819 $names = array( "gdiff3", "diff3", "diff3.exe" );
820 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
822 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
825 $this->setVar( 'wgDiff3', $diff3 );
827 $this->setVar( 'wgDiff3', false );
828 $this->showMessage( 'config-diff3-bad' );
833 * Environment check for ImageMagick and GD.
835 protected function envCheckGraphics() {
836 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
837 $convert = self
::locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
839 $this->setVar( 'wgImageMagickConvertCommand', '' );
841 $this->setVar( 'wgImageMagickConvertCommand', $convert );
842 $this->showMessage( 'config-imagemagick', $convert );
844 } elseif ( function_exists( 'imagejpeg' ) ) {
845 $this->showMessage( 'config-gd' );
848 $this->showMessage( 'config-no-scaling' );
853 * Environment check for the server hostname.
855 protected function envCheckServer() {
856 $server = WebRequest
::detectServer();
857 $this->showMessage( 'config-using-server', $server );
858 $this->setVar( 'wgServer', $server );
862 * Environment check for setting $IP and $wgScriptPath.
864 protected function envCheckPath() {
866 $IP = dirname( dirname( dirname( __FILE__
) ) );
867 $this->setVar( 'IP', $IP );
869 $this->showMessage( 'config-using-uri', $this->getVar( 'wgServer' ), $this->getVar( 'wgScriptPath' ) );
874 * Environment check for setting the preferred PHP file extension.
876 protected function envCheckExtension() {
877 // @todo FIXME: Detect this properly
878 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
883 $this->setVar( 'wgScriptExtension', ".$ext" );
889 protected function envCheckShellLocale() {
890 $os = php_uname( 's' );
891 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
893 if ( !in_array( $os, $supported ) ) {
897 # Get a list of available locales.
899 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
905 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
906 $candidatesByLocale = array();
907 $candidatesByLang = array();
909 foreach ( $lines as $line ) {
910 if ( $line === '' ) {
914 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
918 list( $all, $lang, $territory, $charset, $modifier ) = $m;
920 $candidatesByLocale[$m[0]] = $m;
921 $candidatesByLang[$lang][] = $m;
924 # Try the current value of LANG.
925 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
926 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
930 # Try the most common ones.
931 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
932 foreach ( $commonLocales as $commonLocale ) {
933 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
934 $this->setVar( 'wgShellLocale', $commonLocale );
939 # Is there an available locale in the Wiki's language?
940 $wikiLang = $this->getVar( 'wgLanguageCode' );
942 if ( isset( $candidatesByLang[$wikiLang] ) ) {
943 $m = reset( $candidatesByLang[$wikiLang] );
944 $this->setVar( 'wgShellLocale', $m[0] );
948 # Are there any at all?
949 if ( count( $candidatesByLocale ) ) {
950 $m = reset( $candidatesByLocale );
951 $this->setVar( 'wgShellLocale', $m[0] );
962 protected function envCheckUploadsDirectory() {
965 $dir = $IP . '/images/';
966 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
967 $safe = !$this->dirIsExecutable( $dir, $url );
972 $this->showMessage( 'config-uploads-not-safe', $dir );
977 * Checks if suhosin.get.max_value_length is set, and if so, sets
978 * $wgResourceLoaderMaxQueryLength to that value in the generated
981 protected function envCheckSuhosinMaxValueLength() {
982 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
983 if ( $maxValueLength > 0 ) {
984 if( $maxValueLength < 1024 ) {
985 # Only warn if the value is below the sane 1024
986 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
989 $maxValueLength = -1;
991 $this->setVar( 'wgResourceLoaderMaxQueryLength', $maxValueLength );
995 * Convert a hex string representing a Unicode code point to that code point.
999 protected function unicodeChar( $c ) {
1003 } elseif ($c <= 0x7FF) {
1004 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
1005 } elseif ($c <= 0xFFFF) {
1006 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
1007 . chr(0x80 |
$c & 0x3F);
1008 } elseif ($c <= 0x10FFFF) {
1009 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
1010 . chr(0x80 |
$c >> 6 & 0x3F)
1011 . chr(0x80 |
$c & 0x3F);
1019 * Check the libicu version
1021 protected function envCheckLibicu() {
1022 $utf8 = function_exists( 'utf8_normalize' );
1023 $intl = function_exists( 'normalizer_normalize' );
1026 * This needs to be updated something that the latest libicu
1027 * will properly normalize. This normalization was found at
1028 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1029 * Note that we use the hex representation to create the code
1030 * points in order to avoid any Unicode-destroying during transit.
1032 $not_normal_c = $this->unicodeChar("FA6C");
1033 $normal_c = $this->unicodeChar("242EE");
1035 $useNormalizer = 'php';
1036 $needsUpdate = false;
1039 * We're going to prefer the pecl extension here unless
1040 * utf8_normalize is more up to date.
1043 $useNormalizer = 'utf8';
1044 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1045 if ( $utf8 !== $normal_c ) $needsUpdate = true;
1048 $useNormalizer = 'intl';
1049 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1050 if ( $intl !== $normal_c ) $needsUpdate = true;
1053 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
1054 if( $useNormalizer === 'php' ) {
1055 $this->showMessage( 'config-unicode-pure-php-warning' );
1057 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1058 if( $needsUpdate ) {
1059 $this->showMessage( 'config-unicode-update-warning' );
1065 * Get an array of likely places we can find executables. Check a bunch
1066 * of known Unix-like defaults, as well as the PATH environment variable
1067 * (which should maybe make it work for Windows?)
1071 protected static function getPossibleBinPaths() {
1073 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1074 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1075 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1080 * Search a path for any of the given executable names. Returns the
1081 * executable name if found. Also checks the version string returned
1082 * by each executable.
1084 * Used only by environment checks.
1086 * @param $path String: path to search
1087 * @param $names Array of executable names
1088 * @param $versionInfo Boolean false or array with two members:
1089 * 0 => Command to run for version check, with $1 for the full executable name
1090 * 1 => String to compare the output with
1092 * If $versionInfo is not false, only executables with a version
1093 * matching $versionInfo[1] will be returned.
1095 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1096 if ( !is_array( $names ) ) {
1097 $names = array( $names );
1100 foreach ( $names as $name ) {
1101 $command = $path . DIRECTORY_SEPARATOR
. $name;
1103 wfSuppressWarnings();
1104 $file_exists = file_exists( $command );
1105 wfRestoreWarnings();
1107 if ( $file_exists ) {
1108 if ( !$versionInfo ) {
1112 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1113 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1122 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1123 * @see locateExecutable()
1125 * @param $versionInfo bool
1126 * @return bool|string
1128 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1129 foreach( self
::getPossibleBinPaths() as $path ) {
1130 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1131 if( $exe !== false ) {
1139 * Checks if scripts located in the given directory can be executed via the given URL.
1141 * Used only by environment checks.
1143 public function dirIsExecutable( $dir, $url ) {
1144 $scriptTypes = array(
1146 "<?php echo 'ex' . 'ec';",
1147 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1151 // it would be good to check other popular languages here, but it'll be slow.
1153 wfSuppressWarnings();
1155 foreach ( $scriptTypes as $ext => $contents ) {
1156 foreach ( $contents as $source ) {
1157 $file = 'exectest.' . $ext;
1159 if ( !file_put_contents( $dir . $file, $source ) ) {
1164 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1166 catch( MWException
$e ) {
1167 // Http::get throws with allow_url_fopen = false and no curl extension.
1170 unlink( $dir . $file );
1172 if ( $text == 'exec' ) {
1173 wfRestoreWarnings();
1179 wfRestoreWarnings();
1185 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1187 * @param $moduleName String: Name of module to check.
1190 public static function apacheModulePresent( $moduleName ) {
1191 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1194 // try it the hard way
1196 phpinfo( INFO_MODULES
);
1197 $info = ob_get_clean();
1198 return strpos( $info, $moduleName ) !== false;
1202 * ParserOptions are constructed before we determined the language, so fix it
1204 * @param $lang Language
1206 public function setParserLanguage( $lang ) {
1207 $this->parserOptions
->setTargetLanguage( $lang );
1208 $this->parserOptions
->setUserLang( $lang );
1212 * Overridden by WebInstaller to provide lastPage parameters.
1213 * @param $page stirng
1216 protected function getDocUrl( $page ) {
1217 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1221 * Finds extensions that follow the format /extensions/Name/Name.php,
1222 * and returns an array containing the value for 'Name' for each found extension.
1226 public function findExtensions() {
1227 if( $this->getVar( 'IP' ) === null ) {
1232 $extDir = $this->getVar( 'IP' ) . '/extensions';
1233 $dh = opendir( $extDir );
1235 while ( ( $file = readdir( $dh ) ) !== false ) {
1236 if( !is_dir( "$extDir/$file" ) ) {
1239 if( file_exists( "$extDir/$file/$file.php" ) ) {
1248 * Installs the auto-detected extensions.
1252 protected function includeExtensions() {
1254 $exts = $this->getVar( '_Extensions' );
1255 $IP = $this->getVar( 'IP' );
1258 * We need to include DefaultSettings before including extensions to avoid
1259 * warnings about unset variables. However, the only thing we really
1260 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1261 * if the extension has hidden hook registration in $wgExtensionFunctions,
1262 * but we're not opening that can of worms
1263 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1265 global $wgAutoloadClasses;
1266 $wgAutoloadClasses = array();
1268 require( "$IP/includes/DefaultSettings.php" );
1270 foreach( $exts as $e ) {
1271 require_once( "$IP/extensions/$e/$e.php" );
1274 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1275 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1277 // Unset everyone else's hooks. Lord knows what someone might be doing
1278 // in ParserFirstCallInit (see bug 27171)
1279 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1281 return Status
::newGood();
1285 * Get an array of install steps. Should always be in the format of
1287 * 'name' => 'someuniquename',
1288 * 'callback' => array( $obj, 'method' ),
1290 * There must be a config-install-$name message defined per step, which will
1291 * be shown on install.
1293 * @param $installer DatabaseInstaller so we can make callbacks
1296 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1297 $coreInstallSteps = array(
1298 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1299 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1300 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1301 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1302 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1303 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1304 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1307 // Build the array of install steps starting from the core install list,
1308 // then adding any callbacks that wanted to attach after a given step
1309 foreach( $coreInstallSteps as $step ) {
1310 $this->installSteps
[] = $step;
1311 if( isset( $this->extraInstallSteps
[ $step['name'] ] ) ) {
1312 $this->installSteps
= array_merge(
1313 $this->installSteps
,
1314 $this->extraInstallSteps
[ $step['name'] ]
1319 // Prepend any steps that want to be at the beginning
1320 if( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1321 $this->installSteps
= array_merge(
1322 $this->extraInstallSteps
['BEGINNING'],
1327 // Extensions should always go first, chance to tie into hooks and such
1328 if( count( $this->getVar( '_Extensions' ) ) ) {
1329 array_unshift( $this->installSteps
,
1330 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1332 $this->installSteps
[] = array(
1333 'name' => 'extension-tables',
1334 'callback' => array( $installer, 'createExtensionTables' )
1337 return $this->installSteps
;
1341 * Actually perform the installation.
1343 * @param $startCB Array A callback array for the beginning of each step
1344 * @param $endCB Array A callback array for the end of each step
1346 * @return Array of Status objects
1348 public function performInstallation( $startCB, $endCB ) {
1349 $installResults = array();
1350 $installer = $this->getDBInstaller();
1351 $installer->preInstall();
1352 $steps = $this->getInstallSteps( $installer );
1353 foreach( $steps as $stepObj ) {
1354 $name = $stepObj['name'];
1355 call_user_func_array( $startCB, array( $name ) );
1357 // Perform the callback step
1358 $status = call_user_func( $stepObj['callback'], $installer );
1360 // Output and save the results
1361 call_user_func( $endCB, $name, $status );
1362 $installResults[$name] = $status;
1364 // If we've hit some sort of fatal, we need to bail.
1365 // Callback already had a chance to do output above.
1366 if( !$status->isOk() ) {
1370 if( $status->isOk() ) {
1371 $this->setVar( '_InstallDone', true );
1373 return $installResults;
1377 * Generate $wgSecretKey. Will warn if we had to use mt_rand() instead of
1382 public function generateKeys() {
1383 $keys = array( 'wgSecretKey' => 64 );
1384 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1385 $keys['wgUpgradeKey'] = 16;
1387 return $this->doGenerateKeys( $keys );
1391 * Generate a secret value for variables using either
1392 * /dev/urandom or mt_rand(). Produce a warning in the later case.
1394 * @param $keys Array
1397 protected function doGenerateKeys( $keys ) {
1398 $status = Status
::newGood();
1400 wfSuppressWarnings();
1401 $file = fopen( "/dev/urandom", "r" );
1402 wfRestoreWarnings();
1404 foreach ( $keys as $name => $length ) {
1406 $secretKey = bin2hex( fread( $file, $length / 2 ) );
1410 for ( $i = 0; $i < $length / 8; $i++
) {
1411 $secretKey .= dechex( mt_rand( 0, 0x7fffffff ) );
1415 $this->setVar( $name, $secretKey );
1421 $names = array_keys ( $keys );
1422 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1424 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1431 * Create the first user account, grant it sysop and bureaucrat rights
1435 protected function createSysop() {
1436 $name = $this->getVar( '_AdminName' );
1437 $user = User
::newFromName( $name );
1440 // We should've validated this earlier anyway!
1441 return Status
::newFatal( 'config-admin-error-user', $name );
1444 if ( $user->idForName() == 0 ) {
1445 $user->addToDatabase();
1448 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1449 } catch( PasswordError
$pwe ) {
1450 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1453 $user->addGroup( 'sysop' );
1454 $user->addGroup( 'bureaucrat' );
1455 if( $this->getVar( '_AdminEmail' ) ) {
1456 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1458 $user->saveSettings();
1460 // Update user count
1461 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1462 $ssUpdate->doUpdate();
1464 $status = Status
::newGood();
1466 if( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1467 $this->subscribeToMediaWikiAnnounce( $status );
1473 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1475 'email' => $this->getVar( '_AdminEmail' ),
1480 // Mailman doesn't support as many languages as we do, so check to make
1481 // sure their selected language is available
1482 $myLang = $this->getVar( '_UserLang' );
1483 if( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1484 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1485 $params['language'] = $myLang;
1488 if( MWHttpRequest
::canMakeRequests() ) {
1489 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1490 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1491 if( !$res->isOK() ) {
1492 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1495 $s->warning( 'config-install-subscribe-notpossible' );
1500 * Insert Main Page with default content.
1502 * @param $installer DatabaseInstaller
1505 protected function createMainpage( DatabaseInstaller
$installer ) {
1506 $status = Status
::newGood();
1508 $article = new Article( Title
::newMainPage() );
1509 $article->doEdit( wfMsgForContent( 'mainpagetext' ) . "\n\n" .
1510 wfMsgForContent( 'mainpagedocfooter' ),
1514 User
::newFromName( 'MediaWiki default' ) );
1515 } catch (MWException
$e) {
1516 //using raw, because $wgShowExceptionDetails can not be set yet
1517 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1524 * Override the necessary bits of the config to run an installation.
1526 public static function overrideConfig() {
1527 define( 'MW_NO_SESSION', 1 );
1529 // Don't access the database
1530 $GLOBALS['wgUseDatabaseMessages'] = false;
1532 $GLOBALS['wgShowExceptionDetails'] = true;
1533 // Don't break forms
1534 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1536 // Extended debugging
1537 $GLOBALS['wgShowSQLErrors'] = true;
1538 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1540 // Allow multiple ob_flush() calls
1541 $GLOBALS['wgDisableOutputCompression'] = true;
1543 // Use a sensible cookie prefix (not my_wiki)
1544 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1546 // Some of the environment checks make shell requests, remove limits
1547 $GLOBALS['wgMaxShellMemory'] = 0;
1551 * Add an installation step following the given step.
1553 * @param $callback Array A valid installation callback array, in this form:
1554 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1555 * @param $findStep String the step to find. Omit to put the step at the beginning
1557 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1558 $this->extraInstallSteps
[$findStep][] = $callback;
1562 * Disable the time limit for execution.
1563 * Some long-running pages (Install, Upgrade) will want to do this
1565 protected function disableTimeLimit() {
1566 wfSuppressWarnings();
1567 set_time_limit( 0 );
1568 wfRestoreWarnings();