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',
107 'envCheckSuhosinMaxValueLength',
111 * MediaWiki configuration globals that will eventually be passed through
112 * to LocalSettings.php. The names only are given here, the defaults
113 * typically come from DefaultSettings.php.
117 protected $defaultVarNames = array(
129 'wgEmailAuthentication',
132 'wgImageMagickConvertCommand',
137 'wgDeletedDirectory',
142 'wgUseInstantCommons',
145 'wgResourceLoaderMaxQueryLength',
149 * Variables that are stored alongside globals, and are used for any
150 * configuration of the installation process aside from the MediaWiki
151 * configuration. Map of names to defaults.
155 protected $internalDefaults = array(
157 '_Environment' => false,
158 '_CompiledDBs' => array(),
159 '_SafeMode' => false,
160 '_RaiseMemory' => false,
161 '_UpgradeDone' => false,
162 '_InstallDone' => false,
163 '_Caches' => array(),
164 '_InstallUser' => 'root',
165 '_InstallPassword' => '',
166 '_SameAccount' => true,
167 '_CreateDBAccount' => false,
168 '_NamespaceType' => 'site-name',
169 '_AdminName' => '', // will be set later, when the user selects language
170 '_AdminPassword' => '',
171 '_AdminPassword2' => '',
173 '_Subscribe' => false,
174 '_SkipOptional' => 'continue',
175 '_RightsProfile' => 'wiki',
176 '_LicenseCode' => 'none',
178 '_Extensions' => array(),
179 '_MemCachedServers' => '',
180 '_UpgradeKeySupplied' => false,
181 '_ExistingDBSettings' => false,
185 * The actual list of installation steps. This will be initialized by getInstallSteps()
189 private $installSteps = array();
192 * Extra steps for installation, for things like DatabaseInstallers to modify
196 protected $extraInstallSteps = array();
199 * Known object cache types and the functions used to test for their existence.
203 protected $objectCaches = array(
204 'xcache' => 'xcache_get',
205 'apc' => 'apc_fetch',
206 'eaccel' => 'eaccelerator_get',
207 'wincache' => 'wincache_ucache_get'
211 * User rights profiles.
215 public $rightsProfiles = array(
218 '*' => array( 'edit' => false )
222 'createaccount' => false,
228 'createaccount' => false,
240 public $licenses = array(
242 'url' => 'http://creativecommons.org/licenses/by/3.0/',
243 'icon' => '{$wgStylePath}/common/images/cc-by.png',
246 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
247 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
249 'cc-by-nc-sa' => array(
250 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
251 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
254 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
255 'icon' => '{$wgStylePath}/common/images/cc-0.png',
259 'icon' => '{$wgStylePath}/common/images/public-domain.png',
262 'url' => 'http://www.gnu.org/copyleft/fdl.html',
263 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
270 'cc-choose' => array(
271 // Details will be filled in by the selector.
279 * URL to mediawiki-announce subscription
281 protected $mediaWikiAnnounceUrl = 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
284 * Supported language codes for Mailman
286 protected $mediaWikiAnnounceLanguages = array(
287 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
288 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
289 'sl', 'sr', 'sv', 'tr', 'uk'
293 * UI interface for displaying a short message
294 * The parameters are like parameters to wfMsg().
295 * The messages will be in wikitext format, which will be converted to an
296 * output format such as HTML or text before being sent to the user.
298 public abstract function showMessage( $msg /*, ... */ );
301 * Same as showMessage(), but for displaying errors
303 public abstract function showError( $msg /*, ... */ );
306 * Show a message to the installing user by using a Status object
307 * @param $status Status
309 public abstract function showStatusMessage( Status
$status );
312 * Constructor, always call this from child classes.
314 public function __construct() {
315 global $wgExtensionMessagesFiles, $wgUser;
317 // Disable the i18n cache and LoadBalancer
318 Language
::getLocalisationCache()->disableBackend();
319 LBFactory
::disableBackend();
321 // Load the installer's i18n file.
322 $wgExtensionMessagesFiles['MediawikiInstaller'] =
323 dirname( __FILE__
) . '/Installer.i18n.php';
325 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
326 $wgUser = User
::newFromId( 0 );
328 $this->settings
= $this->internalDefaults
;
330 foreach ( $this->defaultVarNames
as $var ) {
331 $this->settings
[$var] = $GLOBALS[$var];
334 foreach ( self
::getDBTypes() as $type ) {
335 $installer = $this->getDBInstaller( $type );
337 if ( !$installer->isCompiled() ) {
341 $defaults = $installer->getGlobalDefaults();
343 foreach ( $installer->getGlobalNames() as $var ) {
344 if ( isset( $defaults[$var] ) ) {
345 $this->settings
[$var] = $defaults[$var];
347 $this->settings
[$var] = $GLOBALS[$var];
352 $this->parserTitle
= Title
::newFromText( 'Installer' );
353 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
354 $this->parserOptions
->setEditSection( false );
358 * Get a list of known DB types.
362 public static function getDBTypes() {
363 return self
::$dbTypes;
367 * Do initial checks of the PHP environment. Set variables according to
368 * the observed environment.
370 * It's possible that this may be called under the CLI SAPI, not the SAPI
371 * that the wiki will primarily run under. In that case, the subclass should
372 * initialise variables such as wgScriptPath, before calling this function.
374 * Under the web subclass, it can already be assumed that PHP 5+ is in use
375 * and that sessions are working.
379 public function doEnvironmentChecks() {
380 $phpVersion = phpversion();
381 if( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
382 $this->showMessage( 'config-env-php', $phpVersion );
385 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
390 foreach ( $this->envChecks
as $check ) {
391 $status = $this->$check();
392 if ( $status === false ) {
398 $this->setVar( '_Environment', $good );
400 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
404 * Set a MW configuration variable, or internal installer configuration variable.
406 * @param $name String
407 * @param $value Mixed
409 public function setVar( $name, $value ) {
410 $this->settings
[$name] = $value;
414 * Get an MW configuration variable, or internal installer configuration variable.
415 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
416 * Installer variables are typically prefixed by an underscore.
418 * @param $name String
419 * @param $default Mixed
423 public function getVar( $name, $default = null ) {
424 if ( !isset( $this->settings
[$name] ) ) {
427 return $this->settings
[$name];
432 * Get an instance of DatabaseInstaller for the specified DB type.
434 * @param $type Mixed: DB installer for which is needed, false to use default.
436 * @return DatabaseInstaller
438 public function getDBInstaller( $type = false ) {
440 $type = $this->getVar( 'wgDBtype' );
443 $type = strtolower( $type );
445 if ( !isset( $this->dbInstallers
[$type] ) ) {
446 $class = ucfirst( $type ). 'Installer';
447 $this->dbInstallers
[$type] = new $class( $this );
450 return $this->dbInstallers
[$type];
454 * Determine if LocalSettings.php exists. If it does, return its variables,
455 * merged with those from AdminSettings.php, as an array.
459 public function getExistingLocalSettings() {
462 wfSuppressWarnings();
463 $_lsExists = file_exists( "$IP/LocalSettings.php" );
471 require( "$IP/includes/DefaultSettings.php" );
472 require( "$IP/LocalSettings.php" );
473 if ( file_exists( "$IP/AdminSettings.php" ) ) {
474 require( "$IP/AdminSettings.php" );
476 return get_defined_vars();
480 * Get a fake password for sending back to the user in HTML.
481 * This is a security mechanism to avoid compromise of the password in the
482 * event of session ID compromise.
484 * @param $realPassword String
488 public function getFakePassword( $realPassword ) {
489 return str_repeat( '*', strlen( $realPassword ) );
493 * Set a variable which stores a password, except if the new value is a
494 * fake password in which case leave it as it is.
496 * @param $name String
497 * @param $value Mixed
499 public function setPassword( $name, $value ) {
500 if ( !preg_match( '/^\*+$/', $value ) ) {
501 $this->setVar( $name, $value );
506 * On POSIX systems return the primary group of the webserver we're running under.
507 * On other systems just returns null.
509 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
510 * webserver user before he can install.
512 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
516 public static function maybeGetWebserverPrimaryGroup() {
517 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
518 # I don't know this, this isn't UNIX.
522 # posix_getegid() *not* getmygid() because we want the group of the webserver,
523 # not whoever owns the current script.
524 $gid = posix_getegid();
525 $getpwuid = posix_getpwuid( $gid );
526 $group = $getpwuid['name'];
532 * Convert wikitext $text to HTML.
534 * This is potentially error prone since many parser features require a complete
535 * installed MW database. The solution is to just not use those features when you
536 * write your messages. This appears to work well enough. Basic formatting and
537 * external links work just fine.
539 * But in case a translator decides to throw in a #ifexist or internal link or
540 * whatever, this function is guarded to catch the attempted DB access and to present
541 * some fallback text.
543 * @param $text String
544 * @param $lineStart Boolean
547 public function parse( $text, $lineStart = false ) {
551 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
552 $html = $out->getText();
553 } catch ( DBAccessError
$e ) {
554 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
556 if ( !empty( $this->debug
) ) {
557 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
565 * @return ParserOptions
567 public function getParserOptions() {
568 return $this->parserOptions
;
571 public function disableLinkPopups() {
572 $this->parserOptions
->setExternalLinkTarget( false );
575 public function restoreLinkPopups() {
576 global $wgExternalLinkTarget;
577 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
581 * Install step which adds a row to the site_stats table with appropriate
584 * @param $installer DatabaseInstaller
588 public function populateSiteStats( DatabaseInstaller
$installer ) {
589 $status = $installer->getConnection();
590 if ( !$status->isOK() ) {
593 $status->value
->insert( 'site_stats', array(
595 'ss_total_views' => 0,
596 'ss_total_edits' => 0,
597 'ss_good_articles' => 0,
598 'ss_total_pages' => 0,
602 __METHOD__
, 'IGNORE' );
603 return Status
::newGood();
607 * Exports all wg* variables stored by the installer into global scope.
609 public function exportVars() {
610 foreach ( $this->settings
as $name => $value ) {
611 if ( substr( $name, 0, 2 ) == 'wg' ) {
612 $GLOBALS[$name] = $value;
618 * Environment check for DB types.
620 protected function envCheckDB() {
623 $compiledDBs = array();
626 foreach ( self
::getDBTypes() as $name ) {
627 if ( $this->getDBInstaller( $name )->isCompiled() ) {
628 $compiledDBs[] = $name;
630 $allNames[] = wfMsg( 'config-type-' . $name );
633 $this->setVar( '_CompiledDBs', $compiledDBs );
635 if ( !$compiledDBs ) {
636 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
637 // @todo FIXME: This only works for the web installer!
641 // Check for FTS3 full-text search module
642 $sqlite = $this->getDBInstaller( 'sqlite' );
643 if ( $sqlite->isCompiled() ) {
644 if( DatabaseSqlite
::getFulltextSearchModule() != 'FTS3' ) {
645 $this->showMessage( 'config-no-fts3' );
651 * Environment check for register_globals.
653 protected function envCheckRegisterGlobals() {
654 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
655 $this->showMessage( 'config-register-globals' );
660 * Some versions of libxml+PHP break < and > encoding horribly
662 protected function envCheckBrokenXML() {
663 $test = new PhpXmlBugTester();
665 $this->showError( 'config-brokenlibxml' );
671 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
672 * reference parameters to __call() are not converted to null
674 protected function envCheckPHP531() {
675 $test = new PhpRefCallBugTester
;
678 $this->showError( 'config-using531', phpversion() );
684 * Environment check for magic_quotes_runtime.
686 protected function envCheckMagicQuotes() {
687 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
688 $this->showError( 'config-magic-quotes-runtime' );
694 * Environment check for magic_quotes_sybase.
696 protected function envCheckMagicSybase() {
697 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
698 $this->showError( 'config-magic-quotes-sybase' );
704 * Environment check for mbstring.func_overload.
706 protected function envCheckMbstring() {
707 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
708 $this->showError( 'config-mbstring' );
714 * Environment check for zend.ze1_compatibility_mode.
716 protected function envCheckZE1() {
717 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
718 $this->showError( 'config-ze1' );
724 * Environment check for safe_mode.
726 protected function envCheckSafeMode() {
727 if ( wfIniGetBool( 'safe_mode' ) ) {
728 $this->setVar( '_SafeMode', true );
729 $this->showMessage( 'config-safe-mode' );
734 * Environment check for the XML module.
736 protected function envCheckXML() {
737 if ( !function_exists( "utf8_encode" ) ) {
738 $this->showError( 'config-xml-bad' );
744 * Environment check for the PCRE module.
746 protected function envCheckPCRE() {
747 if ( !function_exists( 'preg_match' ) ) {
748 $this->showError( 'config-pcre' );
751 wfSuppressWarnings();
752 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
754 if ( $regexd != '--' ) {
755 $this->showError( 'config-pcre-no-utf8' );
761 * Environment check for available memory.
763 protected function envCheckMemory() {
764 $limit = ini_get( 'memory_limit' );
766 if ( !$limit ||
$limit == -1 ) {
770 $n = wfShorthandToInteger( $limit );
772 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
773 $newLimit = "{$this->minMemorySize}M";
775 if( ini_set( "memory_limit", $newLimit ) === false ) {
776 $this->showMessage( 'config-memory-bad', $limit );
778 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
779 $this->setVar( '_RaiseMemory', true );
787 * Environment check for compiled object cache types.
789 protected function envCheckCache() {
791 foreach ( $this->objectCaches
as $name => $function ) {
792 if ( function_exists( $function ) ) {
793 $caches[$name] = true;
798 $this->showMessage( 'config-no-cache' );
801 $this->setVar( '_Caches', $caches );
805 * Search for GNU diff3.
807 protected function envCheckDiff3() {
808 $names = array( "gdiff3", "diff3", "diff3.exe" );
809 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
811 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
814 $this->setVar( 'wgDiff3', $diff3 );
816 $this->setVar( 'wgDiff3', false );
817 $this->showMessage( 'config-diff3-bad' );
822 * Environment check for ImageMagick and GD.
824 protected function envCheckGraphics() {
825 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
826 $convert = self
::locateExecutableInDefaultPaths( $names, array( '$1 -version', 'ImageMagick' ) );
828 $this->setVar( 'wgImageMagickConvertCommand', '' );
830 $this->setVar( 'wgImageMagickConvertCommand', $convert );
831 $this->showMessage( 'config-imagemagick', $convert );
833 } elseif ( function_exists( 'imagejpeg' ) ) {
834 $this->showMessage( 'config-gd' );
837 $this->showMessage( 'config-no-scaling' );
842 * Environment check for setting $IP and $wgScriptPath.
844 protected function envCheckPath() {
846 $IP = dirname( dirname( dirname( __FILE__
) ) );
848 $this->setVar( 'IP', $IP );
850 // PHP_SELF isn't available sometimes, such as when PHP is CGI but
851 // cgi.fix_pathinfo is disabled. In that case, fall back to SCRIPT_NAME
852 // to get the path to the current script... hopefully it's reliable. SIGH
853 if ( !empty( $_SERVER['PHP_SELF'] ) ) {
854 $path = $_SERVER['PHP_SELF'];
855 } elseif ( !empty( $_SERVER['SCRIPT_NAME'] ) ) {
856 $path = $_SERVER['SCRIPT_NAME'];
857 } elseif ( $this->getVar( 'wgScriptPath' ) ) {
858 // Some kind soul has set it for us already (e.g. debconf)
861 $this->showError( 'config-no-uri' );
865 $uri = preg_replace( '{^(.*)/(mw-)?config.*$}', '$1', $path );
866 $this->setVar( 'wgScriptPath', $uri );
870 * Environment check for setting the preferred PHP file extension.
872 protected function envCheckExtension() {
873 // @todo FIXME: Detect this properly
874 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
879 $this->setVar( 'wgScriptExtension', ".$ext" );
885 protected function envCheckShellLocale() {
886 $os = php_uname( 's' );
887 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
889 if ( !in_array( $os, $supported ) ) {
893 # Get a list of available locales.
895 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
901 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
902 $candidatesByLocale = array();
903 $candidatesByLang = array();
905 foreach ( $lines as $line ) {
906 if ( $line === '' ) {
910 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
914 list( $all, $lang, $territory, $charset, $modifier ) = $m;
916 $candidatesByLocale[$m[0]] = $m;
917 $candidatesByLang[$lang][] = $m;
920 # Try the current value of LANG.
921 if ( isset( $candidatesByLocale[ getenv( 'LANG' ) ] ) ) {
922 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
926 # Try the most common ones.
927 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
928 foreach ( $commonLocales as $commonLocale ) {
929 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
930 $this->setVar( 'wgShellLocale', $commonLocale );
935 # Is there an available locale in the Wiki's language?
936 $wikiLang = $this->getVar( 'wgLanguageCode' );
938 if ( isset( $candidatesByLang[$wikiLang] ) ) {
939 $m = reset( $candidatesByLang[$wikiLang] );
940 $this->setVar( 'wgShellLocale', $m[0] );
944 # Are there any at all?
945 if ( count( $candidatesByLocale ) ) {
946 $m = reset( $candidatesByLocale );
947 $this->setVar( 'wgShellLocale', $m[0] );
958 protected function envCheckUploadsDirectory() {
959 global $IP, $wgServer;
961 $dir = $IP . '/images/';
962 $url = $wgServer . $this->getVar( 'wgScriptPath' ) . '/images/';
963 $safe = !$this->dirIsExecutable( $dir, $url );
968 $this->showMessage( 'config-uploads-not-safe', $dir );
973 * Checks if suhosin.get.max_value_length is set, and if so, sets
974 * $wgResourceLoaderMaxQueryLength to that value in the generated
977 protected function envCheckSuhosinMaxValueLength() {
978 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
979 if ( $maxValueLength > 0 ) {
980 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
982 $maxValueLength = -1;
984 $this->setVar( 'wgResourceLoaderMaxQueryLength', $maxValueLength );
988 * Convert a hex string representing a Unicode code point to that code point.
992 protected function unicodeChar( $c ) {
996 } else if ($c <= 0x7FF) {
997 return chr(0xC0 |
$c >> 6) . chr(0x80 |
$c & 0x3F);
998 } else if ($c <= 0xFFFF) {
999 return chr(0xE0 |
$c >> 12) . chr(0x80 |
$c >> 6 & 0x3F)
1000 . chr(0x80 |
$c & 0x3F);
1001 } else if ($c <= 0x10FFFF) {
1002 return chr(0xF0 |
$c >> 18) . chr(0x80 |
$c >> 12 & 0x3F)
1003 . chr(0x80 |
$c >> 6 & 0x3F)
1004 . chr(0x80 |
$c & 0x3F);
1012 * Check the libicu version
1014 protected function envCheckLibicu() {
1015 $utf8 = function_exists( 'utf8_normalize' );
1016 $intl = function_exists( 'normalizer_normalize' );
1019 * This needs to be updated something that the latest libicu
1020 * will properly normalize. This normalization was found at
1021 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1022 * Note that we use the hex representation to create the code
1023 * points in order to avoid any Unicode-destroying during transit.
1025 $not_normal_c = $this->unicodeChar("FA6C");
1026 $normal_c = $this->unicodeChar("242EE");
1028 $useNormalizer = 'php';
1029 $needsUpdate = false;
1032 * We're going to prefer the pecl extension here unless
1033 * utf8_normalize is more up to date.
1036 $useNormalizer = 'utf8';
1037 $utf8 = utf8_normalize( $not_normal_c, UNORM_NFC
);
1038 if ( $utf8 !== $normal_c ) $needsUpdate = true;
1041 $useNormalizer = 'intl';
1042 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1043 if ( $intl !== $normal_c ) $needsUpdate = true;
1046 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
1047 if( $useNormalizer === 'php' ) {
1048 $this->showMessage( 'config-unicode-pure-php-warning' );
1050 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1051 if( $needsUpdate ) {
1052 $this->showMessage( 'config-unicode-update-warning' );
1058 * Get an array of likely places we can find executables. Check a bunch
1059 * of known Unix-like defaults, as well as the PATH environment variable
1060 * (which should maybe make it work for Windows?)
1064 protected static function getPossibleBinPaths() {
1066 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1067 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1068 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1073 * Search a path for any of the given executable names. Returns the
1074 * executable name if found. Also checks the version string returned
1075 * by each executable.
1077 * Used only by environment checks.
1079 * @param $path String: path to search
1080 * @param $names Array of executable names
1081 * @param $versionInfo Boolean false or array with two members:
1082 * 0 => Command to run for version check, with $1 for the full executable name
1083 * 1 => String to compare the output with
1085 * If $versionInfo is not false, only executables with a version
1086 * matching $versionInfo[1] will be returned.
1088 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1089 if ( !is_array( $names ) ) {
1090 $names = array( $names );
1093 foreach ( $names as $name ) {
1094 $command = $path . DIRECTORY_SEPARATOR
. $name;
1096 wfSuppressWarnings();
1097 $file_exists = file_exists( $command );
1098 wfRestoreWarnings();
1100 if ( $file_exists ) {
1101 if ( !$versionInfo ) {
1105 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1106 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1115 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1116 * @see locateExecutable()
1118 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1119 foreach( self
::getPossibleBinPaths() as $path ) {
1120 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1121 if( $exe !== false ) {
1129 * Checks if scripts located in the given directory can be executed via the given URL.
1131 * Used only by environment checks.
1133 public function dirIsExecutable( $dir, $url ) {
1134 $scriptTypes = array(
1136 "<?php echo 'ex' . 'ec';",
1137 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1141 // it would be good to check other popular languages here, but it'll be slow.
1143 wfSuppressWarnings();
1145 foreach ( $scriptTypes as $ext => $contents ) {
1146 foreach ( $contents as $source ) {
1147 $file = 'exectest.' . $ext;
1149 if ( !file_put_contents( $dir . $file, $source ) ) {
1154 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1156 catch( MWException
$e ) {
1157 // Http::get throws with allow_url_fopen = false and no curl extension.
1160 unlink( $dir . $file );
1162 if ( $text == 'exec' ) {
1163 wfRestoreWarnings();
1169 wfRestoreWarnings();
1175 * ParserOptions are constructed before we determined the language, so fix it
1177 * @param $lang Language
1179 public function setParserLanguage( $lang ) {
1180 $this->parserOptions
->setTargetLanguage( $lang );
1181 $this->parserOptions
->setUserLang( $lang->getCode() );
1185 * Overridden by WebInstaller to provide lastPage parameters.
1187 protected function getDocUrl( $page ) {
1188 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1192 * Finds extensions that follow the format /extensions/Name/Name.php,
1193 * and returns an array containing the value for 'Name' for each found extension.
1197 public function findExtensions() {
1198 if( $this->getVar( 'IP' ) === null ) {
1203 $extDir = $this->getVar( 'IP' ) . '/extensions';
1204 $dh = opendir( $extDir );
1206 while ( ( $file = readdir( $dh ) ) !== false ) {
1207 if( !is_dir( "$extDir/$file" ) ) {
1210 if( file_exists( "$extDir/$file/$file.php" ) ) {
1219 * Installs the auto-detected extensions.
1223 protected function includeExtensions() {
1225 $exts = $this->getVar( '_Extensions' );
1226 $IP = $this->getVar( 'IP' );
1227 $path = $IP . '/extensions';
1230 * We need to include DefaultSettings before including extensions to avoid
1231 * warnings about unset variables. However, the only thing we really
1232 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1233 * if the extension has hidden hook registration in $wgExtensionFunctions,
1234 * but we're not opening that can of worms
1235 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1237 global $wgAutoloadClasses;
1238 $wgAutoloadClasses = array();
1240 require( "$IP/includes/DefaultSettings.php" );
1242 foreach( $exts as $e ) {
1243 require_once( "$path/$e/$e.php" );
1246 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1247 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1249 // Unset everyone else's hooks. Lord knows what someone might be doing
1250 // in ParserFirstCallInit (see bug 27171)
1251 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1253 return Status
::newGood();
1257 * Get an array of install steps. Should always be in the format of
1259 * 'name' => 'someuniquename',
1260 * 'callback' => array( $obj, 'method' ),
1262 * There must be a config-install-$name message defined per step, which will
1263 * be shown on install.
1265 * @param $installer DatabaseInstaller so we can make callbacks
1268 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1269 $coreInstallSteps = array(
1270 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1271 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1272 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1273 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1274 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1275 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1276 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1279 // Build the array of install steps starting from the core install list,
1280 // then adding any callbacks that wanted to attach after a given step
1281 foreach( $coreInstallSteps as $step ) {
1282 $this->installSteps
[] = $step;
1283 if( isset( $this->extraInstallSteps
[ $step['name'] ] ) ) {
1284 $this->installSteps
= array_merge(
1285 $this->installSteps
,
1286 $this->extraInstallSteps
[ $step['name'] ]
1291 // Prepend any steps that want to be at the beginning
1292 if( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1293 $this->installSteps
= array_merge(
1294 $this->extraInstallSteps
['BEGINNING'],
1299 // Extensions should always go first, chance to tie into hooks and such
1300 if( count( $this->getVar( '_Extensions' ) ) ) {
1301 array_unshift( $this->installSteps
,
1302 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1304 $this->installSteps
[] = array(
1305 'name' => 'extension-tables',
1306 'callback' => array( $installer, 'createExtensionTables' )
1309 return $this->installSteps
;
1313 * Actually perform the installation.
1315 * @param $startCB Array A callback array for the beginning of each step
1316 * @param $endCB Array A callback array for the end of each step
1318 * @return Array of Status objects
1320 public function performInstallation( $startCB, $endCB ) {
1321 $installResults = array();
1322 $installer = $this->getDBInstaller();
1323 $installer->preInstall();
1324 $steps = $this->getInstallSteps( $installer );
1325 foreach( $steps as $stepObj ) {
1326 $name = $stepObj['name'];
1327 call_user_func_array( $startCB, array( $name ) );
1329 // Perform the callback step
1330 $status = call_user_func( $stepObj['callback'], $installer );
1332 // Output and save the results
1333 call_user_func( $endCB, $name, $status );
1334 $installResults[$name] = $status;
1336 // If we've hit some sort of fatal, we need to bail.
1337 // Callback already had a chance to do output above.
1338 if( !$status->isOk() ) {
1342 if( $status->isOk() ) {
1343 $this->setVar( '_InstallDone', true );
1345 return $installResults;
1349 * Generate $wgSecretKey. Will warn if we had to use mt_rand() instead of
1354 public function generateKeys() {
1355 $keys = array( 'wgSecretKey' => 64 );
1356 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1357 $keys['wgUpgradeKey'] = 16;
1359 return $this->doGenerateKeys( $keys );
1363 * Generate a secret value for variables using either
1364 * /dev/urandom or mt_rand(). Produce a warning in the later case.
1366 * @param $keys Array
1369 protected function doGenerateKeys( $keys ) {
1370 $status = Status
::newGood();
1372 wfSuppressWarnings();
1373 $file = fopen( "/dev/urandom", "r" );
1374 wfRestoreWarnings();
1376 foreach ( $keys as $name => $length ) {
1378 $secretKey = bin2hex( fread( $file, $length / 2 ) );
1382 for ( $i = 0; $i < $length / 8; $i++
) {
1383 $secretKey .= dechex( mt_rand( 0, 0x7fffffff ) );
1387 $this->setVar( $name, $secretKey );
1393 $names = array_keys ( $keys );
1394 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1396 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1403 * Create the first user account, grant it sysop and bureaucrat rights
1407 protected function createSysop() {
1408 $name = $this->getVar( '_AdminName' );
1409 $user = User
::newFromName( $name );
1412 // We should've validated this earlier anyway!
1413 return Status
::newFatal( 'config-admin-error-user', $name );
1416 if ( $user->idForName() == 0 ) {
1417 $user->addToDatabase();
1420 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1421 } catch( PasswordError
$pwe ) {
1422 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1425 $user->addGroup( 'sysop' );
1426 $user->addGroup( 'bureaucrat' );
1427 if( $this->getVar( '_AdminEmail' ) ) {
1428 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1430 $user->saveSettings();
1432 // Update user count
1433 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1434 $ssUpdate->doUpdate();
1436 $status = Status
::newGood();
1438 if( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1439 $this->subscribeToMediaWikiAnnounce( $status );
1445 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1447 'email' => $this->getVar( '_AdminEmail' ),
1452 // Mailman doesn't support as many languages as we do, so check to make
1453 // sure their selected language is available
1454 $myLang = $this->getVar( '_UserLang' );
1455 if( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1456 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1457 $params['language'] = $myLang;
1460 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1461 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1462 if( !$res->isOK() ) {
1463 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1468 * Insert Main Page with default content.
1472 protected function createMainpage( DatabaseInstaller
$installer ) {
1473 $status = Status
::newGood();
1475 $article = new Article( Title
::newMainPage() );
1476 $article->doEdit( wfMsgForContent( 'mainpagetext' ) . "\n\n" .
1477 wfMsgForContent( 'mainpagedocfooter' ),
1481 User
::newFromName( 'MediaWiki default' ) );
1482 } catch (MWException
$e) {
1483 //using raw, because $wgShowExceptionDetails can not be set yet
1484 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1491 * Override the necessary bits of the config to run an installation.
1493 public static function overrideConfig() {
1494 define( 'MW_NO_SESSION', 1 );
1496 // Don't access the database
1497 $GLOBALS['wgUseDatabaseMessages'] = false;
1499 $GLOBALS['wgShowExceptionDetails'] = true;
1500 // Don't break forms
1501 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1503 // Extended debugging
1504 $GLOBALS['wgShowSQLErrors'] = true;
1505 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1507 // Allow multiple ob_flush() calls
1508 $GLOBALS['wgDisableOutputCompression'] = true;
1510 // Use a sensible cookie prefix (not my_wiki)
1511 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1513 // Some of the environment checks make shell requests, remove limits
1514 $GLOBALS['wgMaxShellMemory'] = 0;
1518 * Add an installation step following the given step.
1520 * @param $callback Array A valid installation callback array, in this form:
1521 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1522 * @param $findStep String the step to find. Omit to put the step at the beginning
1524 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1525 $this->extraInstallSteps
[$findStep][] = $callback;