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',
114 * MediaWiki configuration globals that will eventually be passed through
115 * to LocalSettings.php. The names only are given here, the defaults
116 * typically come from DefaultSettings.php.
120 protected $defaultVarNames = array(
132 'wgEmailAuthentication',
135 'wgImageMagickConvertCommand',
141 'wgDeletedDirectory',
146 'wgUseInstantCommons',
149 'wgResourceLoaderMaxQueryLength',
153 * Variables that are stored alongside globals, and are used for any
154 * configuration of the installation process aside from the MediaWiki
155 * configuration. Map of names to defaults.
159 protected $internalDefaults = array(
161 '_Environment' => false,
162 '_CompiledDBs' => array(),
163 '_SafeMode' => false,
164 '_RaiseMemory' => false,
165 '_UpgradeDone' => false,
166 '_InstallDone' => false,
167 '_Caches' => array(),
168 '_InstallPassword' => '',
169 '_SameAccount' => true,
170 '_CreateDBAccount' => false,
171 '_NamespaceType' => 'site-name',
172 '_AdminName' => '', // will be set later, when the user selects language
173 '_AdminPassword' => '',
174 '_AdminPassword2' => '',
176 '_Subscribe' => false,
177 '_SkipOptional' => 'continue',
178 '_RightsProfile' => 'wiki',
179 '_LicenseCode' => 'none',
181 '_Extensions' => array(),
182 '_MemCachedServers' => '',
183 '_UpgradeKeySupplied' => false,
184 '_ExistingDBSettings' => false,
188 * The actual list of installation steps. This will be initialized by getInstallSteps()
192 private $installSteps = array();
195 * Extra steps for installation, for things like DatabaseInstallers to modify
199 protected $extraInstallSteps = array();
202 * Known object cache types and the functions used to test for their existence.
206 protected $objectCaches = array(
207 'xcache' => 'xcache_get',
208 'apc' => 'apc_fetch',
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.
301 public abstract function showMessage( $msg /*, ... */ );
304 * Same as showMessage(), but for displaying errors
307 public abstract function showError( $msg /*, ... */ );
310 * Show a message to the installing user by using a Status object
311 * @param $status Status
313 public abstract function showStatusMessage( Status
$status );
316 * Constructor, always call this from child classes.
318 public function __construct() {
319 global $wgExtensionMessagesFiles, $wgUser;
321 // Disable the i18n cache and LoadBalancer
322 Language
::getLocalisationCache()->disableBackend();
323 LBFactory
::disableBackend();
325 // Load the installer's i18n file.
326 $wgExtensionMessagesFiles['MediawikiInstaller'] =
327 dirname( __FILE__
) . '/Installer.i18n.php';
329 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
330 $wgUser = User
::newFromId( 0 );
332 $this->settings
= $this->internalDefaults
;
334 foreach ( $this->defaultVarNames
as $var ) {
335 $this->settings
[$var] = $GLOBALS[$var];
338 $compiledDBs = array();
339 foreach ( self
::getDBTypes() as $type ) {
340 $installer = $this->getDBInstaller( $type );
342 if ( !$installer->isCompiled() ) {
345 $compiledDBs[] = $type;
347 $defaults = $installer->getGlobalDefaults();
349 foreach ( $installer->getGlobalNames() as $var ) {
350 if ( isset( $defaults[$var] ) ) {
351 $this->settings
[$var] = $defaults[$var];
353 $this->settings
[$var] = $GLOBALS[$var];
357 $this->setVar( '_CompiledDBs', $compiledDBs );
359 $this->parserTitle
= Title
::newFromText( 'Installer' );
360 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
361 $this->parserOptions
->setEditSection( false );
365 * Get a list of known DB types.
369 public static function getDBTypes() {
370 return self
::$dbTypes;
374 * Do initial checks of the PHP environment. Set variables according to
375 * the observed environment.
377 * It's possible that this may be called under the CLI SAPI, not the SAPI
378 * that the wiki will primarily run under. In that case, the subclass should
379 * initialise variables such as wgScriptPath, before calling this function.
381 * Under the web subclass, it can already be assumed that PHP 5+ is in use
382 * and that sessions are working.
386 public function doEnvironmentChecks() {
387 $phpVersion = phpversion();
388 if( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
389 $this->showMessage( 'config-env-php', $phpVersion );
392 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
397 foreach ( $this->envChecks
as $check ) {
398 $status = $this->$check();
399 if ( $status === false ) {
405 $this->setVar( '_Environment', $good );
407 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
411 * Set a MW configuration variable, or internal installer configuration variable.
413 * @param $name String
414 * @param $value Mixed
416 public function setVar( $name, $value ) {
417 $this->settings
[$name] = $value;
421 * Get an MW configuration variable, or internal installer configuration variable.
422 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
423 * Installer variables are typically prefixed by an underscore.
425 * @param $name String
426 * @param $default Mixed
430 public function getVar( $name, $default = null ) {
431 if ( !isset( $this->settings
[$name] ) ) {
434 return $this->settings
[$name];
439 * Get an instance of DatabaseInstaller for the specified DB type.
441 * @param $type Mixed: DB installer for which is needed, false to use default.
443 * @return DatabaseInstaller
445 public function getDBInstaller( $type = false ) {
447 $type = $this->getVar( 'wgDBtype' );
450 $type = strtolower( $type );
452 if ( !isset( $this->dbInstallers
[$type] ) ) {
453 $class = ucfirst( $type ). 'Installer';
454 $this->dbInstallers
[$type] = new $class( $this );
457 return $this->dbInstallers
[$type];
461 * Determine if LocalSettings.php exists. If it does, return its variables,
462 * merged with those from AdminSettings.php, as an array.
466 public static function getExistingLocalSettings() {
469 wfSuppressWarnings();
470 $_lsExists = file_exists( "$IP/LocalSettings.php" );
478 require( "$IP/includes/DefaultSettings.php" );
479 require( "$IP/LocalSettings.php" );
480 if ( file_exists( "$IP/AdminSettings.php" ) ) {
481 require( "$IP/AdminSettings.php" );
483 return get_defined_vars();
487 * Get a fake password for sending back to the user in HTML.
488 * This is a security mechanism to avoid compromise of the password in the
489 * event of session ID compromise.
491 * @param $realPassword String
495 public function getFakePassword( $realPassword ) {
496 return str_repeat( '*', strlen( $realPassword ) );
500 * Set a variable which stores a password, except if the new value is a
501 * fake password in which case leave it as it is.
503 * @param $name String
504 * @param $value Mixed
506 public function setPassword( $name, $value ) {
507 if ( !preg_match( '/^\*+$/', $value ) ) {
508 $this->setVar( $name, $value );
513 * On POSIX systems return the primary group of the webserver we're running under.
514 * On other systems just returns null.
516 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
517 * webserver user before he can install.
519 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
523 public static function maybeGetWebserverPrimaryGroup() {
524 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
525 # I don't know this, this isn't UNIX.
529 # posix_getegid() *not* getmygid() because we want the group of the webserver,
530 # not whoever owns the current script.
531 $gid = posix_getegid();
532 $getpwuid = posix_getpwuid( $gid );
533 $group = $getpwuid['name'];
539 * Convert wikitext $text to HTML.
541 * This is potentially error prone since many parser features require a complete
542 * installed MW database. The solution is to just not use those features when you
543 * write your messages. This appears to work well enough. Basic formatting and
544 * external links work just fine.
546 * But in case a translator decides to throw in a #ifexist or internal link or
547 * whatever, this function is guarded to catch the attempted DB access and to present
548 * some fallback text.
550 * @param $text String
551 * @param $lineStart Boolean
554 public function parse( $text, $lineStart = false ) {
558 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
559 $html = $out->getText();
560 } catch ( DBAccessError
$e ) {
561 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
563 if ( !empty( $this->debug
) ) {
564 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
572 * @return ParserOptions
574 public function getParserOptions() {
575 return $this->parserOptions
;
578 public function disableLinkPopups() {
579 $this->parserOptions
->setExternalLinkTarget( false );
582 public function restoreLinkPopups() {
583 global $wgExternalLinkTarget;
584 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
588 * Install step which adds a row to the site_stats table with appropriate
591 * @param $installer DatabaseInstaller
595 public function populateSiteStats( DatabaseInstaller
$installer ) {
596 $status = $installer->getConnection();
597 if ( !$status->isOK() ) {
600 $status->value
->insert( 'site_stats', array(
602 'ss_total_views' => 0,
603 'ss_total_edits' => 0,
604 'ss_good_articles' => 0,
605 'ss_total_pages' => 0,
608 __METHOD__
, 'IGNORE' );
609 return Status
::newGood();
613 * Exports all wg* variables stored by the installer into global scope.
615 public function exportVars() {
616 foreach ( $this->settings
as $name => $value ) {
617 if ( substr( $name, 0, 2 ) == 'wg' ) {
618 $GLOBALS[$name] = $value;
624 * Environment check for DB types.
627 protected function envCheckDB() {
632 foreach ( self
::getDBTypes() as $name ) {
633 $allNames[] = wfMsg( "config-type-$name" );
636 // cache initially available databases to make sure that everything will be displayed correctly
637 // after a refresh on env checks page
638 $databases = $this->getVar( '_CompiledDBs-preFilter' );
640 $databases = $this->getVar( '_CompiledDBs' );
641 $this->setVar( '_CompiledDBs-preFilter', $databases );
644 $databases = array_flip ( $databases );
645 foreach ( array_keys( $databases ) as $db ) {
646 $installer = $this->getDBInstaller( $db );
647 $status = $installer->checkPrerequisites();
648 if ( !$status->isGood() ) {
649 $this->showStatusMessage( $status );
651 if ( !$status->isOK() ) {
652 unset( $databases[$db] );
655 $databases = array_flip( $databases );
657 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
658 // @todo FIXME: This only works for the web installer!
661 $this->setVar( '_CompiledDBs', $databases );
666 * Environment check for register_globals.
668 protected function envCheckRegisterGlobals() {
669 if( wfIniGetBool( 'register_globals' ) ) {
670 $this->showMessage( 'config-register-globals' );
675 * Some versions of libxml+PHP break < and > encoding horribly
678 protected function envCheckBrokenXML() {
679 $test = new PhpXmlBugTester();
681 $this->showError( 'config-brokenlibxml' );
688 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
689 * reference parameters to __call() are not converted to null
692 protected function envCheckPHP531() {
693 $test = new PhpRefCallBugTester
;
696 $this->showError( 'config-using531', phpversion() );
703 * Environment check for magic_quotes_runtime.
706 protected function envCheckMagicQuotes() {
707 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
708 $this->showError( 'config-magic-quotes-runtime' );
715 * Environment check for magic_quotes_sybase.
718 protected function envCheckMagicSybase() {
719 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
720 $this->showError( 'config-magic-quotes-sybase' );
727 * Environment check for mbstring.func_overload.
730 protected function envCheckMbstring() {
731 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
732 $this->showError( 'config-mbstring' );
739 * Environment check for zend.ze1_compatibility_mode.
742 protected function envCheckZE1() {
743 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
744 $this->showError( 'config-ze1' );
751 * Environment check for safe_mode.
754 protected function envCheckSafeMode() {
755 if ( wfIniGetBool( 'safe_mode' ) ) {
756 $this->setVar( '_SafeMode', true );
757 $this->showMessage( 'config-safe-mode' );
763 * Environment check for the XML module.
766 protected function envCheckXML() {
767 if ( !function_exists( "utf8_encode" ) ) {
768 $this->showError( 'config-xml-bad' );
775 * Environment check for the PCRE module.
778 protected function envCheckPCRE() {
779 if ( !function_exists( 'preg_match' ) ) {
780 $this->showError( 'config-pcre' );
783 wfSuppressWarnings();
784 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
786 if ( $regexd != '--' ) {
787 $this->showError( 'config-pcre-no-utf8' );
794 * Environment check for available memory.
797 protected function envCheckMemory() {
798 $limit = ini_get( 'memory_limit' );
800 if ( !$limit ||
$limit == -1 ) {
804 $n = wfShorthandToInteger( $limit );
806 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
807 $newLimit = "{$this->minMemorySize}M";
809 if( ini_set( "memory_limit", $newLimit ) === false ) {
810 $this->showMessage( 'config-memory-bad', $limit );
812 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
813 $this->setVar( '_RaiseMemory', true );
820 * Environment check for compiled object cache types.
822 protected function envCheckCache() {
824 foreach ( $this->objectCaches
as $name => $function ) {
825 if ( function_exists( $function ) ) {
826 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
829 $caches[$name] = true;
834 $this->showMessage( 'config-no-cache' );
837 $this->setVar( '_Caches', $caches );
841 * Scare user to death if they have mod_security
844 protected function envCheckModSecurity() {
845 if ( self
::apacheModulePresent( 'mod_security' ) ) {
846 $this->showMessage( 'config-mod-security' );
852 * Search for GNU diff3.
855 protected function envCheckDiff3() {
856 $names = array( "gdiff3", "diff3", "diff3.exe" );
857 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
859 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
862 $this->setVar( 'wgDiff3', $diff3 );
864 $this->setVar( 'wgDiff3', false );
865 $this->showMessage( 'config-diff3-bad' );
871 * Environment check for ImageMagick and GD.
874 protected function envCheckGraphics() {
875 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
876 $convert = self
::locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
878 $this->setVar( 'wgImageMagickConvertCommand', '' );
880 $this->setVar( 'wgImageMagickConvertCommand', $convert );
881 $this->showMessage( 'config-imagemagick', $convert );
883 } elseif ( function_exists( 'imagejpeg' ) ) {
884 $this->showMessage( 'config-gd' );
887 $this->showMessage( 'config-no-scaling' );
893 * Environment check for the server hostname.
895 protected function envCheckServer() {
896 $server = $this->envGetDefaultServer();
897 $this->showMessage( 'config-using-server', $server );
898 $this->setVar( 'wgServer', $server );
903 * Helper function to be called from envCheckServer()
906 protected abstract function envGetDefaultServer();
909 * Environment check for setting $IP and $wgScriptPath.
912 protected function envCheckPath() {
914 $IP = dirname( dirname( dirname( __FILE__
) ) );
915 $this->setVar( 'IP', $IP );
917 $this->showMessage( 'config-using-uri', $this->getVar( 'wgServer' ), $this->getVar( 'wgScriptPath' ) );
922 * Environment check for setting the preferred PHP file extension.
924 protected function envCheckExtension() {
925 // @todo FIXME: Detect this properly
926 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
931 $this->setVar( 'wgScriptExtension', ".$ext" );
939 protected function envCheckShellLocale() {
940 $os = php_uname( 's' );
941 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
943 if ( !in_array( $os, $supported ) ) {
947 # Get a list of available locales.
949 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
955 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
956 $candidatesByLocale = array();
957 $candidatesByLang = array();
959 foreach ( $lines as $line ) {
960 if ( $line === '' ) {
964 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
968 list( $all, $lang, $territory, $charset, $modifier ) = $m;
970 $candidatesByLocale[$m[0]] = $m;
971 $candidatesByLang[$lang][] = $m;
974 # Try the current value of LANG.
975 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
976 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
980 # Try the most common ones.
981 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
982 foreach ( $commonLocales as $commonLocale ) {
983 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
984 $this->setVar( 'wgShellLocale', $commonLocale );
989 # Is there an available locale in the Wiki's language?
990 $wikiLang = $this->getVar( 'wgLanguageCode' );
992 if ( isset( $candidatesByLang[$wikiLang] ) ) {
993 $m = reset( $candidatesByLang[$wikiLang] );
994 $this->setVar( 'wgShellLocale', $m[0] );
998 # Are there any at all?
999 if ( count( $candidatesByLocale ) ) {
1000 $m = reset( $candidatesByLocale );
1001 $this->setVar( 'wgShellLocale', $m[0] );
1013 protected function envCheckUploadsDirectory() {
1016 $dir = $IP . '/images/';
1017 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1018 $safe = !$this->dirIsExecutable( $dir, $url );
1021 $this->showMessage( 'config-uploads-not-safe', $dir );
1027 * Checks if suhosin.get.max_value_length is set, and if so, sets
1028 * $wgResourceLoaderMaxQueryLength to that value in the generated
1029 * LocalSettings file
1032 protected function envCheckSuhosinMaxValueLength() {
1033 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1034 if ( $maxValueLength > 0 ) {
1035 if( $maxValueLength < 1024 ) {
1036 # Only warn if the value is below the sane 1024
1037 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1040 $maxValueLength = -1;
1042 $this->setVar( 'wgResourceLoaderMaxQueryLength', $maxValueLength );
1047 * Convert a hex string representing a Unicode code point to that code point.
1051 protected function unicodeChar( $c ) {
1055 } elseif ($c <= 0x7FF) {
1056 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
1057 } elseif ($c <= 0xFFFF) {
1058 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
1059 . chr(0x80 |
$c & 0x3F);
1060 } elseif ($c <= 0x10FFFF) {
1061 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
1062 . chr(0x80 |
$c >> 6 & 0x3F)
1063 . chr(0x80 |
$c & 0x3F);
1071 * Check the libicu version
1073 protected function envCheckLibicu() {
1074 $utf8 = function_exists( 'utf8_normalize' );
1075 $intl = function_exists( 'normalizer_normalize' );
1078 * This needs to be updated something that the latest libicu
1079 * will properly normalize. This normalization was found at
1080 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1081 * Note that we use the hex representation to create the code
1082 * points in order to avoid any Unicode-destroying during transit.
1084 $not_normal_c = $this->unicodeChar("FA6C");
1085 $normal_c = $this->unicodeChar("242EE");
1087 $useNormalizer = 'php';
1088 $needsUpdate = false;
1091 * We're going to prefer the pecl extension here unless
1092 * utf8_normalize is more up to date.
1095 $useNormalizer = 'utf8';
1096 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1097 if ( $utf8 !== $normal_c ) $needsUpdate = true;
1100 $useNormalizer = 'intl';
1101 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1102 if ( $intl !== $normal_c ) $needsUpdate = true;
1105 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
1106 if( $useNormalizer === 'php' ) {
1107 $this->showMessage( 'config-unicode-pure-php-warning' );
1109 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1110 if( $needsUpdate ) {
1111 $this->showMessage( 'config-unicode-update-warning' );
1119 protected function envCheckCtype() {
1120 if ( !function_exists( 'ctype_digit' ) ) {
1121 $this->showError( 'config-ctype' );
1128 * Get an array of likely places we can find executables. Check a bunch
1129 * of known Unix-like defaults, as well as the PATH environment variable
1130 * (which should maybe make it work for Windows?)
1134 protected static function getPossibleBinPaths() {
1136 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1137 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1138 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1143 * Search a path for any of the given executable names. Returns the
1144 * executable name if found. Also checks the version string returned
1145 * by each executable.
1147 * Used only by environment checks.
1149 * @param $path String: path to search
1150 * @param $names Array of executable names
1151 * @param $versionInfo Boolean false or array with two members:
1152 * 0 => Command to run for version check, with $1 for the full executable name
1153 * 1 => String to compare the output with
1155 * If $versionInfo is not false, only executables with a version
1156 * matching $versionInfo[1] will be returned.
1157 * @return bool|string
1159 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1160 if ( !is_array( $names ) ) {
1161 $names = array( $names );
1164 foreach ( $names as $name ) {
1165 $command = $path . DIRECTORY_SEPARATOR
. $name;
1167 wfSuppressWarnings();
1168 $file_exists = file_exists( $command );
1169 wfRestoreWarnings();
1171 if ( $file_exists ) {
1172 if ( !$versionInfo ) {
1176 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1177 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1186 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1187 * @see locateExecutable()
1189 * @param $versionInfo bool
1190 * @return bool|string
1192 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1193 foreach( self
::getPossibleBinPaths() as $path ) {
1194 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1195 if( $exe !== false ) {
1203 * Checks if scripts located in the given directory can be executed via the given URL.
1205 * Used only by environment checks.
1206 * @param $dir string
1207 * @param $url string
1208 * @return bool|int|string
1210 public function dirIsExecutable( $dir, $url ) {
1211 $scriptTypes = array(
1213 "<?php echo 'ex' . 'ec';",
1214 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1218 // it would be good to check other popular languages here, but it'll be slow.
1220 wfSuppressWarnings();
1222 foreach ( $scriptTypes as $ext => $contents ) {
1223 foreach ( $contents as $source ) {
1224 $file = 'exectest.' . $ext;
1226 if ( !file_put_contents( $dir . $file, $source ) ) {
1231 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1233 catch( MWException
$e ) {
1234 // Http::get throws with allow_url_fopen = false and no curl extension.
1237 unlink( $dir . $file );
1239 if ( $text == 'exec' ) {
1240 wfRestoreWarnings();
1246 wfRestoreWarnings();
1252 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1254 * @param $moduleName String: Name of module to check.
1257 public static function apacheModulePresent( $moduleName ) {
1258 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1261 // try it the hard way
1263 phpinfo( INFO_MODULES
);
1264 $info = ob_get_clean();
1265 return strpos( $info, $moduleName ) !== false;
1269 * ParserOptions are constructed before we determined the language, so fix it
1271 * @param $lang Language
1273 public function setParserLanguage( $lang ) {
1274 $this->parserOptions
->setTargetLanguage( $lang );
1275 $this->parserOptions
->setUserLang( $lang );
1279 * Overridden by WebInstaller to provide lastPage parameters.
1280 * @param $page string
1283 protected function getDocUrl( $page ) {
1284 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1288 * Finds extensions that follow the format /extensions/Name/Name.php,
1289 * and returns an array containing the value for 'Name' for each found extension.
1293 public function findExtensions() {
1294 if( $this->getVar( 'IP' ) === null ) {
1299 $extDir = $this->getVar( 'IP' ) . '/extensions';
1300 $dh = opendir( $extDir );
1302 while ( ( $file = readdir( $dh ) ) !== false ) {
1303 if( !is_dir( "$extDir/$file" ) ) {
1306 if( file_exists( "$extDir/$file/$file.php" ) ) {
1310 natcasesort( $exts );
1316 * Installs the auto-detected extensions.
1320 protected function includeExtensions() {
1322 $exts = $this->getVar( '_Extensions' );
1323 $IP = $this->getVar( 'IP' );
1326 * We need to include DefaultSettings before including extensions to avoid
1327 * warnings about unset variables. However, the only thing we really
1328 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1329 * if the extension has hidden hook registration in $wgExtensionFunctions,
1330 * but we're not opening that can of worms
1331 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1333 global $wgAutoloadClasses;
1334 $wgAutoloadClasses = array();
1336 require( "$IP/includes/DefaultSettings.php" );
1338 foreach( $exts as $e ) {
1339 require_once( "$IP/extensions/$e/$e.php" );
1342 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1343 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1345 // Unset everyone else's hooks. Lord knows what someone might be doing
1346 // in ParserFirstCallInit (see bug 27171)
1347 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1349 return Status
::newGood();
1353 * Get an array of install steps. Should always be in the format of
1355 * 'name' => 'someuniquename',
1356 * 'callback' => array( $obj, 'method' ),
1358 * There must be a config-install-$name message defined per step, which will
1359 * be shown on install.
1361 * @param $installer DatabaseInstaller so we can make callbacks
1364 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1365 $coreInstallSteps = array(
1366 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1367 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1368 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1369 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1370 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1371 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1372 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1375 // Build the array of install steps starting from the core install list,
1376 // then adding any callbacks that wanted to attach after a given step
1377 foreach( $coreInstallSteps as $step ) {
1378 $this->installSteps
[] = $step;
1379 if( isset( $this->extraInstallSteps
[ $step['name'] ] ) ) {
1380 $this->installSteps
= array_merge(
1381 $this->installSteps
,
1382 $this->extraInstallSteps
[ $step['name'] ]
1387 // Prepend any steps that want to be at the beginning
1388 if( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1389 $this->installSteps
= array_merge(
1390 $this->extraInstallSteps
['BEGINNING'],
1395 // Extensions should always go first, chance to tie into hooks and such
1396 if( count( $this->getVar( '_Extensions' ) ) ) {
1397 array_unshift( $this->installSteps
,
1398 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1400 $this->installSteps
[] = array(
1401 'name' => 'extension-tables',
1402 'callback' => array( $installer, 'createExtensionTables' )
1405 return $this->installSteps
;
1409 * Actually perform the installation.
1411 * @param $startCB Array A callback array for the beginning of each step
1412 * @param $endCB Array A callback array for the end of each step
1414 * @return Array of Status objects
1416 public function performInstallation( $startCB, $endCB ) {
1417 $installResults = array();
1418 $installer = $this->getDBInstaller();
1419 $installer->preInstall();
1420 $steps = $this->getInstallSteps( $installer );
1421 foreach( $steps as $stepObj ) {
1422 $name = $stepObj['name'];
1423 call_user_func_array( $startCB, array( $name ) );
1425 // Perform the callback step
1426 $status = call_user_func( $stepObj['callback'], $installer );
1428 // Output and save the results
1429 call_user_func( $endCB, $name, $status );
1430 $installResults[$name] = $status;
1432 // If we've hit some sort of fatal, we need to bail.
1433 // Callback already had a chance to do output above.
1434 if( !$status->isOk() ) {
1438 if( $status->isOk() ) {
1439 $this->setVar( '_InstallDone', true );
1441 return $installResults;
1445 * Generate $wgSecretKey. Will warn if we had to use mt_rand() instead of
1450 public function generateKeys() {
1451 $keys = array( 'wgSecretKey' => 64 );
1452 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1453 $keys['wgUpgradeKey'] = 16;
1455 return $this->doGenerateKeys( $keys );
1459 * Generate a secret value for variables using either
1460 * /dev/urandom or mt_rand(). Produce a warning in the later case.
1462 * @param $keys Array
1465 protected function doGenerateKeys( $keys ) {
1466 $status = Status
::newGood();
1468 wfSuppressWarnings();
1469 $file = fopen( "/dev/urandom", "r" );
1470 wfRestoreWarnings();
1472 foreach ( $keys as $name => $length ) {
1474 $secretKey = bin2hex( fread( $file, $length / 2 ) );
1478 for ( $i = 0; $i < $length / 8; $i++
) {
1479 $secretKey .= dechex( mt_rand( 0, 0x7fffffff ) );
1483 $this->setVar( $name, $secretKey );
1489 $names = array_keys ( $keys );
1490 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1492 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1499 * Create the first user account, grant it sysop and bureaucrat rights
1503 protected function createSysop() {
1504 $name = $this->getVar( '_AdminName' );
1505 $user = User
::newFromName( $name );
1508 // We should've validated this earlier anyway!
1509 return Status
::newFatal( 'config-admin-error-user', $name );
1512 if ( $user->idForName() == 0 ) {
1513 $user->addToDatabase();
1516 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1517 } catch( PasswordError
$pwe ) {
1518 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1521 $user->addGroup( 'sysop' );
1522 $user->addGroup( 'bureaucrat' );
1523 if( $this->getVar( '_AdminEmail' ) ) {
1524 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1526 $user->saveSettings();
1528 // Update user count
1529 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1530 $ssUpdate->doUpdate();
1532 $status = Status
::newGood();
1534 if( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1535 $this->subscribeToMediaWikiAnnounce( $status );
1544 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1546 'email' => $this->getVar( '_AdminEmail' ),
1551 // Mailman doesn't support as many languages as we do, so check to make
1552 // sure their selected language is available
1553 $myLang = $this->getVar( '_UserLang' );
1554 if( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1555 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1556 $params['language'] = $myLang;
1559 if( MWHttpRequest
::canMakeRequests() ) {
1560 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1561 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1562 if( !$res->isOK() ) {
1563 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1566 $s->warning( 'config-install-subscribe-notpossible' );
1571 * Insert Main Page with default content.
1573 * @param $installer DatabaseInstaller
1576 protected function createMainpage( DatabaseInstaller
$installer ) {
1577 $status = Status
::newGood();
1579 $page = WikiPage
::factory( Title
::newMainPage() );
1580 $page->doEdit( wfMsgForContent( 'mainpagetext' ) . "\n\n" .
1581 wfMsgForContent( 'mainpagedocfooter' ),
1585 User
::newFromName( 'MediaWiki default' ) );
1586 } catch (MWException
$e) {
1587 //using raw, because $wgShowExceptionDetails can not be set yet
1588 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1595 * Override the necessary bits of the config to run an installation.
1597 public static function overrideConfig() {
1598 define( 'MW_NO_SESSION', 1 );
1600 // Don't access the database
1601 $GLOBALS['wgUseDatabaseMessages'] = false;
1603 $GLOBALS['wgShowExceptionDetails'] = true;
1604 // Don't break forms
1605 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1607 // Extended debugging
1608 $GLOBALS['wgShowSQLErrors'] = true;
1609 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1611 // Allow multiple ob_flush() calls
1612 $GLOBALS['wgDisableOutputCompression'] = true;
1614 // Use a sensible cookie prefix (not my_wiki)
1615 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1617 // Some of the environment checks make shell requests, remove limits
1618 $GLOBALS['wgMaxShellMemory'] = 0;
1622 * Add an installation step following the given step.
1624 * @param $callback Array A valid installation callback array, in this form:
1625 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1626 * @param $findStep String the step to find. Omit to put the step at the beginning
1628 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1629 $this->extraInstallSteps
[$findStep][] = $callback;
1633 * Disable the time limit for execution.
1634 * Some long-running pages (Install, Upgrade) will want to do this
1636 protected function disableTimeLimit() {
1637 wfSuppressWarnings();
1638 set_time_limit( 0 );
1639 wfRestoreWarnings();