3 * Base code for MediaWiki installer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * This documentation group collects source code files with deployment functionality.
27 * @defgroup Deployment Deployment
31 * Base installer class.
33 * This class provides the base for installation and update functionality
34 * for both MediaWiki core and extensions.
39 abstract class Installer
{
41 // This is the absolute minimum PHP version we can support
42 const MINIMUM_PHP_VERSION
= '5.3.2';
45 * The oldest version of PCRE we can support.
47 * Defining this is necessary because PHP may be linked with a system version
48 * of PCRE, which may be older than that bundled with the minimum PHP version.
50 const MINIMUM_PCRE_VERSION
= '7.2';
58 * List of detected DBs, access using getCompiledDBs().
62 protected $compiledDBs;
65 * Cached DB installer instances, access using getDBInstaller().
69 protected $dbInstallers = array();
72 * Minimum memory size in MB.
76 protected $minMemorySize = 50;
79 * Cached Title, used by parse().
83 protected $parserTitle;
86 * Cached ParserOptions, used by parse().
90 protected $parserOptions;
93 * Known database types. These correspond to the class names <type>Installer,
94 * and are also MediaWiki database types valid for $wgDBtype.
96 * To add a new type, create a <type>Installer class and a Database<type>
97 * class, and add a config-type-<type> message to MessagesEn.php.
101 protected static $dbTypes = array(
109 * A list of environment check methods called by doEnvironmentChecks().
110 * These may output warnings using showMessage(), and/or abort the
111 * installation process by returning false.
115 protected $envChecks = array(
117 'envCheckRegisterGlobals',
120 'envCheckMagicQuotes',
121 'envCheckMagicSybase',
129 'envCheckModSecurity',
136 'envCheckShellLocale',
137 'envCheckUploadsDirectory',
139 'envCheckSuhosinMaxValueLength',
145 * MediaWiki configuration globals that will eventually be passed through
146 * to LocalSettings.php. The names only are given here, the defaults
147 * typically come from DefaultSettings.php.
151 protected $defaultVarNames = array(
163 'wgEmailAuthentication',
166 'wgImageMagickConvertCommand',
172 'wgDeletedDirectory',
177 'wgUseInstantCommons',
180 'wgResourceLoaderMaxQueryLength',
184 * Variables that are stored alongside globals, and are used for any
185 * configuration of the installation process aside from the MediaWiki
186 * configuration. Map of names to defaults.
190 protected $internalDefaults = array(
192 '_Environment' => false,
193 '_SafeMode' => false,
194 '_RaiseMemory' => false,
195 '_UpgradeDone' => false,
196 '_InstallDone' => false,
197 '_Caches' => array(),
198 '_InstallPassword' => '',
199 '_SameAccount' => true,
200 '_CreateDBAccount' => false,
201 '_NamespaceType' => 'site-name',
202 '_AdminName' => '', // will be set later, when the user selects language
203 '_AdminPassword' => '',
204 '_AdminPassword2' => '',
206 '_Subscribe' => false,
207 '_SkipOptional' => 'continue',
208 '_RightsProfile' => 'wiki',
209 '_LicenseCode' => 'none',
211 '_Extensions' => array(),
212 '_MemCachedServers' => '',
213 '_UpgradeKeySupplied' => false,
214 '_ExistingDBSettings' => false,
218 * The actual list of installation steps. This will be initialized by getInstallSteps()
222 private $installSteps = array();
225 * Extra steps for installation, for things like DatabaseInstallers to modify
229 protected $extraInstallSteps = array();
232 * Known object cache types and the functions used to test for their existence.
236 protected $objectCaches = array(
237 'xcache' => 'xcache_get',
238 'apc' => 'apc_fetch',
239 'wincache' => 'wincache_ucache_get'
243 * User rights profiles.
247 public $rightsProfiles = array(
250 '*' => array( 'edit' => false )
254 'createaccount' => false,
260 'createaccount' => false,
272 public $licenses = array(
274 'url' => 'http://creativecommons.org/licenses/by/3.0/',
275 'icon' => '{$wgStylePath}/common/images/cc-by.png',
278 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
279 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
281 'cc-by-nc-sa' => array(
282 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
283 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
286 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
287 'icon' => '{$wgStylePath}/common/images/cc-0.png',
291 'icon' => '{$wgStylePath}/common/images/public-domain.png',
294 'url' => 'http://www.gnu.org/copyleft/fdl.html',
295 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
302 'cc-choose' => array(
303 // Details will be filled in by the selector.
311 * URL to mediawiki-announce subscription
313 protected $mediaWikiAnnounceUrl =
314 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
317 * Supported language codes for Mailman
319 protected $mediaWikiAnnounceLanguages = array(
320 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
321 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
322 'sl', 'sr', 'sv', 'tr', 'uk'
326 * UI interface for displaying a short message
327 * The parameters are like parameters to wfMessage().
328 * The messages will be in wikitext format, which will be converted to an
329 * output format such as HTML or text before being sent to the user.
332 abstract public function showMessage( $msg /*, ... */ );
335 * Same as showMessage(), but for displaying errors
338 abstract public function showError( $msg /*, ... */ );
341 * Show a message to the installing user by using a Status object
342 * @param $status Status
344 abstract public function showStatusMessage( Status
$status );
347 * Constructor, always call this from child classes.
349 public function __construct() {
350 global $wgExtensionMessagesFiles, $wgUser;
352 // Disable the i18n cache and LoadBalancer
353 Language
::getLocalisationCache()->disableBackend();
354 LBFactory
::disableBackend();
356 // Load the installer's i18n file.
357 $wgExtensionMessagesFiles['MediawikiInstaller'] =
358 __DIR__
. '/Installer.i18n.php';
360 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
361 $wgUser = User
::newFromId( 0 );
363 $this->settings
= $this->internalDefaults
;
365 foreach ( $this->defaultVarNames
as $var ) {
366 $this->settings
[$var] = $GLOBALS[$var];
369 $compiledDBs = array();
370 foreach ( self
::getDBTypes() as $type ) {
371 $installer = $this->getDBInstaller( $type );
373 if ( !$installer->isCompiled() ) {
376 $compiledDBs[] = $type;
378 $defaults = $installer->getGlobalDefaults();
380 foreach ( $installer->getGlobalNames() as $var ) {
381 if ( isset( $defaults[$var] ) ) {
382 $this->settings
[$var] = $defaults[$var];
384 $this->settings
[$var] = $GLOBALS[$var];
388 $this->compiledDBs
= $compiledDBs;
390 $this->parserTitle
= Title
::newFromText( 'Installer' );
391 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
392 $this->parserOptions
->setEditSection( false );
396 * Get a list of known DB types.
400 public static function getDBTypes() {
401 return self
::$dbTypes;
405 * Do initial checks of the PHP environment. Set variables according to
406 * the observed environment.
408 * It's possible that this may be called under the CLI SAPI, not the SAPI
409 * that the wiki will primarily run under. In that case, the subclass should
410 * initialise variables such as wgScriptPath, before calling this function.
412 * Under the web subclass, it can already be assumed that PHP 5+ is in use
413 * and that sessions are working.
417 public function doEnvironmentChecks() {
418 $phpVersion = phpversion();
419 if ( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
420 $this->showMessage( 'config-env-php', $phpVersion );
423 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
427 // Must go here because an old version of PCRE can prevent other checks from completing
429 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
430 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
431 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
437 foreach ( $this->envChecks
as $check ) {
438 $status = $this->$check();
439 if ( $status === false ) {
445 $this->setVar( '_Environment', $good );
447 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
451 * Set a MW configuration variable, or internal installer configuration variable.
453 * @param $name String
454 * @param $value Mixed
456 public function setVar( $name, $value ) {
457 $this->settings
[$name] = $value;
461 * Get an MW configuration variable, or internal installer configuration variable.
462 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
463 * Installer variables are typically prefixed by an underscore.
465 * @param $name String
466 * @param $default Mixed
470 public function getVar( $name, $default = null ) {
471 if ( !isset( $this->settings
[$name] ) ) {
474 return $this->settings
[$name];
479 * Get a list of DBs supported by current PHP setup
483 public function getCompiledDBs() {
484 return $this->compiledDBs
;
488 * Get an instance of DatabaseInstaller for the specified DB type.
490 * @param $type Mixed: DB installer for which is needed, false to use default.
492 * @return DatabaseInstaller
494 public function getDBInstaller( $type = false ) {
496 $type = $this->getVar( 'wgDBtype' );
499 $type = strtolower( $type );
501 if ( !isset( $this->dbInstallers
[$type] ) ) {
502 $class = ucfirst( $type ) . 'Installer';
503 $this->dbInstallers
[$type] = new $class( $this );
506 return $this->dbInstallers
[$type];
510 * Determine if LocalSettings.php exists. If it does, return its variables,
511 * merged with those from AdminSettings.php, as an array.
515 public static function getExistingLocalSettings() {
518 wfSuppressWarnings();
519 $_lsExists = file_exists( "$IP/LocalSettings.php" );
527 require "$IP/includes/DefaultSettings.php";
528 require "$IP/LocalSettings.php";
529 if ( file_exists( "$IP/AdminSettings.php" ) ) {
530 require "$IP/AdminSettings.php";
533 return get_defined_vars();
537 * Get a fake password for sending back to the user in HTML.
538 * This is a security mechanism to avoid compromise of the password in the
539 * event of session ID compromise.
541 * @param $realPassword String
545 public function getFakePassword( $realPassword ) {
546 return str_repeat( '*', strlen( $realPassword ) );
550 * Set a variable which stores a password, except if the new value is a
551 * fake password in which case leave it as it is.
553 * @param $name String
554 * @param $value Mixed
556 public function setPassword( $name, $value ) {
557 if ( !preg_match( '/^\*+$/', $value ) ) {
558 $this->setVar( $name, $value );
563 * On POSIX systems return the primary group of the webserver we're running under.
564 * On other systems just returns null.
566 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
567 * webserver user before he can install.
569 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
573 public static function maybeGetWebserverPrimaryGroup() {
574 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
575 # I don't know this, this isn't UNIX.
579 # posix_getegid() *not* getmygid() because we want the group of the webserver,
580 # not whoever owns the current script.
581 $gid = posix_getegid();
582 $getpwuid = posix_getpwuid( $gid );
583 $group = $getpwuid['name'];
589 * Convert wikitext $text to HTML.
591 * This is potentially error prone since many parser features require a complete
592 * installed MW database. The solution is to just not use those features when you
593 * write your messages. This appears to work well enough. Basic formatting and
594 * external links work just fine.
596 * But in case a translator decides to throw in a "#ifexist" or internal link or
597 * whatever, this function is guarded to catch the attempted DB access and to present
598 * some fallback text.
600 * @param $text String
601 * @param $lineStart Boolean
604 public function parse( $text, $lineStart = false ) {
608 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
609 $html = $out->getText();
610 } catch ( DBAccessError
$e ) {
611 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
613 if ( !empty( $this->debug
) ) {
614 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
622 * @return ParserOptions
624 public function getParserOptions() {
625 return $this->parserOptions
;
628 public function disableLinkPopups() {
629 $this->parserOptions
->setExternalLinkTarget( false );
632 public function restoreLinkPopups() {
633 global $wgExternalLinkTarget;
634 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
638 * Install step which adds a row to the site_stats table with appropriate
641 * @param $installer DatabaseInstaller
645 public function populateSiteStats( DatabaseInstaller
$installer ) {
646 $status = $installer->getConnection();
647 if ( !$status->isOK() ) {
650 $status->value
->insert( 'site_stats', array(
652 'ss_total_views' => 0,
653 'ss_total_edits' => 0,
654 'ss_good_articles' => 0,
655 'ss_total_pages' => 0,
658 __METHOD__
, 'IGNORE' );
660 return Status
::newGood();
664 * Exports all wg* variables stored by the installer into global scope.
666 public function exportVars() {
667 foreach ( $this->settings
as $name => $value ) {
668 if ( substr( $name, 0, 2 ) == 'wg' ) {
669 $GLOBALS[$name] = $value;
675 * Environment check for DB types.
678 protected function envCheckDB() {
683 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
684 // config-type-sqlite
685 foreach ( self
::getDBTypes() as $name ) {
686 $allNames[] = wfMessage( "config-type-$name" )->text();
689 $databases = $this->getCompiledDBs();
691 $databases = array_flip( $databases );
692 foreach ( array_keys( $databases ) as $db ) {
693 $installer = $this->getDBInstaller( $db );
694 $status = $installer->checkPrerequisites();
695 if ( !$status->isGood() ) {
696 $this->showStatusMessage( $status );
698 if ( !$status->isOK() ) {
699 unset( $databases[$db] );
702 $databases = array_flip( $databases );
704 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
706 // @todo FIXME: This only works for the web installer!
714 * Environment check for register_globals.
716 protected function envCheckRegisterGlobals() {
717 if ( wfIniGetBool( 'register_globals' ) ) {
718 $this->showMessage( 'config-register-globals' );
723 * Some versions of libxml+PHP break < and > encoding horribly
726 protected function envCheckBrokenXML() {
727 $test = new PhpXmlBugTester();
729 $this->showError( 'config-brokenlibxml' );
738 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
739 * reference parameters to __call() are not converted to null
742 protected function envCheckPHP531() {
743 $test = new PhpRefCallBugTester
;
746 $this->showError( 'config-using531', phpversion() );
755 * Environment check for magic_quotes_runtime.
758 protected function envCheckMagicQuotes() {
759 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
760 $this->showError( 'config-magic-quotes-runtime' );
769 * Environment check for magic_quotes_sybase.
772 protected function envCheckMagicSybase() {
773 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
774 $this->showError( 'config-magic-quotes-sybase' );
783 * Environment check for mbstring.func_overload.
786 protected function envCheckMbstring() {
787 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
788 $this->showError( 'config-mbstring' );
797 * Environment check for zend.ze1_compatibility_mode.
800 protected function envCheckZE1() {
801 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
802 $this->showError( 'config-ze1' );
811 * Environment check for safe_mode.
814 protected function envCheckSafeMode() {
815 if ( wfIniGetBool( 'safe_mode' ) ) {
816 $this->setVar( '_SafeMode', true );
817 $this->showMessage( 'config-safe-mode' );
824 * Environment check for the XML module.
827 protected function envCheckXML() {
828 if ( !function_exists( "utf8_encode" ) ) {
829 $this->showError( 'config-xml-bad' );
838 * Environment check for the PCRE module.
840 * @note If this check were to fail, the parser would
841 * probably throw an exception before the result
842 * of this check is shown to the user.
845 protected function envCheckPCRE() {
846 wfSuppressWarnings();
847 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
848 // Need to check for \p support too, as PCRE can be compiled
849 // with utf8 support, but not unicode property support.
850 // check that \p{Zs} (space separators) matches
851 // U+3000 (Ideographic space)
852 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
854 if ( $regexd != '--' ||
$regexprop != '--' ) {
855 $this->showError( 'config-pcre-no-utf8' );
864 * Environment check for available memory.
867 protected function envCheckMemory() {
868 $limit = ini_get( 'memory_limit' );
870 if ( !$limit ||
$limit == -1 ) {
874 $n = wfShorthandToInteger( $limit );
876 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
877 $newLimit = "{$this->minMemorySize}M";
879 if ( ini_set( "memory_limit", $newLimit ) === false ) {
880 $this->showMessage( 'config-memory-bad', $limit );
882 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
883 $this->setVar( '_RaiseMemory', true );
891 * Environment check for compiled object cache types.
893 protected function envCheckCache() {
895 foreach ( $this->objectCaches
as $name => $function ) {
896 if ( function_exists( $function ) ) {
897 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
900 $caches[$name] = true;
905 $this->showMessage( 'config-no-cache' );
908 $this->setVar( '_Caches', $caches );
912 * Scare user to death if they have mod_security
915 protected function envCheckModSecurity() {
916 if ( self
::apacheModulePresent( 'mod_security' ) ) {
917 $this->showMessage( 'config-mod-security' );
924 * Search for GNU diff3.
927 protected function envCheckDiff3() {
928 $names = array( "gdiff3", "diff3", "diff3.exe" );
929 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
931 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
934 $this->setVar( 'wgDiff3', $diff3 );
936 $this->setVar( 'wgDiff3', false );
937 $this->showMessage( 'config-diff3-bad' );
944 * Environment check for ImageMagick and GD.
947 protected function envCheckGraphics() {
948 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
949 $versionInfo = array( '$1 -version', 'ImageMagick' );
950 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
952 $this->setVar( 'wgImageMagickConvertCommand', '' );
954 $this->setVar( 'wgImageMagickConvertCommand', $convert );
955 $this->showMessage( 'config-imagemagick', $convert );
958 } elseif ( function_exists( 'imagejpeg' ) ) {
959 $this->showMessage( 'config-gd' );
961 $this->showMessage( 'config-no-scaling' );
973 protected function envCheckGit() {
974 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
975 $versionInfo = array( '$1 --version', 'git version' );
977 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
980 $this->setVar( 'wgGitBin', $git );
981 $this->showMessage( 'config-git', $git );
983 $this->setVar( 'wgGitBin', false );
984 $this->showMessage( 'config-git-bad' );
991 * Environment check for the server hostname.
993 protected function envCheckServer() {
994 $server = $this->envGetDefaultServer();
995 if ( $server !== null ) {
996 $this->showMessage( 'config-using-server', $server );
997 $this->setVar( 'wgServer', $server );
1004 * Helper function to be called from envCheckServer()
1007 abstract protected function envGetDefaultServer();
1010 * Environment check for setting $IP and $wgScriptPath.
1013 protected function envCheckPath() {
1015 $IP = dirname( dirname( __DIR__
) );
1016 $this->setVar( 'IP', $IP );
1020 $this->getVar( 'wgServer' ),
1021 $this->getVar( 'wgScriptPath' )
1028 * Environment check for setting the preferred PHP file extension.
1031 protected function envCheckExtension() {
1032 // @todo FIXME: Detect this properly
1033 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1038 $this->setVar( 'wgScriptExtension', ".$ext" );
1044 * Environment check for preferred locale in shell
1047 protected function envCheckShellLocale() {
1048 $os = php_uname( 's' );
1049 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1051 if ( !in_array( $os, $supported ) ) {
1055 # Get a list of available locales.
1057 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1063 $lines = array_map( 'trim', explode( "\n", $lines ) );
1064 $candidatesByLocale = array();
1065 $candidatesByLang = array();
1067 foreach ( $lines as $line ) {
1068 if ( $line === '' ) {
1072 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1076 list( , $lang, , , ) = $m;
1078 $candidatesByLocale[$m[0]] = $m;
1079 $candidatesByLang[$lang][] = $m;
1082 # Try the current value of LANG.
1083 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1084 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1089 # Try the most common ones.
1090 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1091 foreach ( $commonLocales as $commonLocale ) {
1092 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1093 $this->setVar( 'wgShellLocale', $commonLocale );
1099 # Is there an available locale in the Wiki's language?
1100 $wikiLang = $this->getVar( 'wgLanguageCode' );
1102 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1103 $m = reset( $candidatesByLang[$wikiLang] );
1104 $this->setVar( 'wgShellLocale', $m[0] );
1109 # Are there any at all?
1110 if ( count( $candidatesByLocale ) ) {
1111 $m = reset( $candidatesByLocale );
1112 $this->setVar( 'wgShellLocale', $m[0] );
1122 * Environment check for the permissions of the uploads directory
1125 protected function envCheckUploadsDirectory() {
1128 $dir = $IP . '/images/';
1129 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1130 $safe = !$this->dirIsExecutable( $dir, $url );
1133 $this->showMessage( 'config-uploads-not-safe', $dir );
1140 * Checks if suhosin.get.max_value_length is set, and if so generate
1141 * a warning because it decreases ResourceLoader performance.
1144 protected function envCheckSuhosinMaxValueLength() {
1145 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1146 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1147 // Only warn if the value is below the sane 1024
1148 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1155 * Convert a hex string representing a Unicode code point to that code point.
1159 protected function unicodeChar( $c ) {
1163 } elseif ( $c <= 0x7FF ) {
1164 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1165 } elseif ( $c <= 0xFFFF ) {
1166 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1167 . chr( 0x80 |
$c & 0x3F );
1168 } elseif ( $c <= 0x10FFFF ) {
1169 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1170 . chr( 0x80 |
$c >> 6 & 0x3F )
1171 . chr( 0x80 |
$c & 0x3F );
1178 * Check the libicu version
1180 protected function envCheckLibicu() {
1181 $utf8 = function_exists( 'utf8_normalize' );
1182 $intl = function_exists( 'normalizer_normalize' );
1185 * This needs to be updated something that the latest libicu
1186 * will properly normalize. This normalization was found at
1187 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1188 * Note that we use the hex representation to create the code
1189 * points in order to avoid any Unicode-destroying during transit.
1191 $not_normal_c = $this->unicodeChar( "FA6C" );
1192 $normal_c = $this->unicodeChar( "242EE" );
1194 $useNormalizer = 'php';
1195 $needsUpdate = false;
1198 * We're going to prefer the pecl extension here unless
1199 * utf8_normalize is more up to date.
1202 $useNormalizer = 'utf8';
1203 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1204 if ( $utf8 !== $normal_c ) {
1205 $needsUpdate = true;
1209 $useNormalizer = 'intl';
1210 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1211 if ( $intl !== $normal_c ) {
1212 $needsUpdate = true;
1216 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1217 // 'config-unicode-using-intl'
1218 if ( $useNormalizer === 'php' ) {
1219 $this->showMessage( 'config-unicode-pure-php-warning' );
1221 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1222 if ( $needsUpdate ) {
1223 $this->showMessage( 'config-unicode-update-warning' );
1231 protected function envCheckCtype() {
1232 if ( !function_exists( 'ctype_digit' ) ) {
1233 $this->showError( 'config-ctype' );
1244 protected function envCheckJSON() {
1245 if ( !function_exists( 'json_decode' ) ) {
1246 $this->showError( 'config-json' );
1255 * Get an array of likely places we can find executables. Check a bunch
1256 * of known Unix-like defaults, as well as the PATH environment variable
1257 * (which should maybe make it work for Windows?)
1261 protected static function getPossibleBinPaths() {
1263 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1264 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1265 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1270 * Search a path for any of the given executable names. Returns the
1271 * executable name if found. Also checks the version string returned
1272 * by each executable.
1274 * Used only by environment checks.
1276 * @param string $path path to search
1277 * @param array $names of executable names
1278 * @param $versionInfo Boolean false or array with two members:
1279 * 0 => Command to run for version check, with $1 for the full executable name
1280 * 1 => String to compare the output with
1282 * If $versionInfo is not false, only executables with a version
1283 * matching $versionInfo[1] will be returned.
1284 * @return bool|string
1286 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1287 if ( !is_array( $names ) ) {
1288 $names = array( $names );
1291 foreach ( $names as $name ) {
1292 $command = $path . DIRECTORY_SEPARATOR
. $name;
1294 wfSuppressWarnings();
1295 $file_exists = file_exists( $command );
1296 wfRestoreWarnings();
1298 if ( $file_exists ) {
1299 if ( !$versionInfo ) {
1303 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1304 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1314 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1315 * @see locateExecutable()
1316 * @param array $names Array of possible names.
1317 * @param array|bool $versionInfo Default: false or array with two members:
1318 * 0 => Command to run for version check, with $1 for the full executable name
1319 * 1 => String to compare the output with
1321 * If $versionInfo is not false, only executables with a version
1322 * matching $versionInfo[1] will be returned.
1323 * @return bool|string
1325 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1326 foreach ( self
::getPossibleBinPaths() as $path ) {
1327 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1328 if ( $exe !== false ) {
1337 * Checks if scripts located in the given directory can be executed via the given URL.
1339 * Used only by environment checks.
1340 * @param $dir string
1341 * @param $url string
1342 * @return bool|int|string
1344 public function dirIsExecutable( $dir, $url ) {
1345 $scriptTypes = array(
1347 "<?php echo 'ex' . 'ec';",
1348 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1352 // it would be good to check other popular languages here, but it'll be slow.
1354 wfSuppressWarnings();
1356 foreach ( $scriptTypes as $ext => $contents ) {
1357 foreach ( $contents as $source ) {
1358 $file = 'exectest.' . $ext;
1360 if ( !file_put_contents( $dir . $file, $source ) ) {
1365 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1366 } catch ( MWException
$e ) {
1367 // Http::get throws with allow_url_fopen = false and no curl extension.
1370 unlink( $dir . $file );
1372 if ( $text == 'exec' ) {
1373 wfRestoreWarnings();
1380 wfRestoreWarnings();
1386 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1388 * @param string $moduleName Name of module to check.
1391 public static function apacheModulePresent( $moduleName ) {
1392 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1395 // try it the hard way
1397 phpinfo( INFO_MODULES
);
1398 $info = ob_get_clean();
1400 return strpos( $info, $moduleName ) !== false;
1404 * ParserOptions are constructed before we determined the language, so fix it
1406 * @param $lang Language
1408 public function setParserLanguage( $lang ) {
1409 $this->parserOptions
->setTargetLanguage( $lang );
1410 $this->parserOptions
->setUserLang( $lang );
1414 * Overridden by WebInstaller to provide lastPage parameters.
1415 * @param $page string
1418 protected function getDocUrl( $page ) {
1419 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1423 * Finds extensions that follow the format /extensions/Name/Name.php,
1424 * and returns an array containing the value for 'Name' for each found extension.
1428 public function findExtensions() {
1429 if ( $this->getVar( 'IP' ) === null ) {
1433 $extDir = $this->getVar( 'IP' ) . '/extensions';
1434 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1438 $dh = opendir( $extDir );
1440 while ( ( $file = readdir( $dh ) ) !== false ) {
1441 if ( !is_dir( "$extDir/$file" ) ) {
1444 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1449 natcasesort( $exts );
1455 * Installs the auto-detected extensions.
1459 protected function includeExtensions() {
1461 $exts = $this->getVar( '_Extensions' );
1462 $IP = $this->getVar( 'IP' );
1465 * We need to include DefaultSettings before including extensions to avoid
1466 * warnings about unset variables. However, the only thing we really
1467 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1468 * if the extension has hidden hook registration in $wgExtensionFunctions,
1469 * but we're not opening that can of worms
1470 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1472 global $wgAutoloadClasses;
1473 $wgAutoloadClasses = array();
1475 require "$IP/includes/DefaultSettings.php";
1477 foreach ( $exts as $e ) {
1478 require_once "$IP/extensions/$e/$e.php";
1481 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1482 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1484 // Unset everyone else's hooks. Lord knows what someone might be doing
1485 // in ParserFirstCallInit (see bug 27171)
1486 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1488 return Status
::newGood();
1492 * Get an array of install steps. Should always be in the format of
1494 * 'name' => 'someuniquename',
1495 * 'callback' => array( $obj, 'method' ),
1497 * There must be a config-install-$name message defined per step, which will
1498 * be shown on install.
1500 * @param $installer DatabaseInstaller so we can make callbacks
1503 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1504 $coreInstallSteps = array(
1505 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1506 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1507 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1508 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1509 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1510 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1511 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1514 // Build the array of install steps starting from the core install list,
1515 // then adding any callbacks that wanted to attach after a given step
1516 foreach ( $coreInstallSteps as $step ) {
1517 $this->installSteps
[] = $step;
1518 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1519 $this->installSteps
= array_merge(
1520 $this->installSteps
,
1521 $this->extraInstallSteps
[$step['name']]
1526 // Prepend any steps that want to be at the beginning
1527 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1528 $this->installSteps
= array_merge(
1529 $this->extraInstallSteps
['BEGINNING'],
1534 // Extensions should always go first, chance to tie into hooks and such
1535 if ( count( $this->getVar( '_Extensions' ) ) ) {
1536 array_unshift( $this->installSteps
,
1537 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1539 $this->installSteps
[] = array(
1540 'name' => 'extension-tables',
1541 'callback' => array( $installer, 'createExtensionTables' )
1545 return $this->installSteps
;
1549 * Actually perform the installation.
1551 * @param array $startCB A callback array for the beginning of each step
1552 * @param array $endCB A callback array for the end of each step
1554 * @return Array of Status objects
1556 public function performInstallation( $startCB, $endCB ) {
1557 $installResults = array();
1558 $installer = $this->getDBInstaller();
1559 $installer->preInstall();
1560 $steps = $this->getInstallSteps( $installer );
1561 foreach ( $steps as $stepObj ) {
1562 $name = $stepObj['name'];
1563 call_user_func_array( $startCB, array( $name ) );
1565 // Perform the callback step
1566 $status = call_user_func( $stepObj['callback'], $installer );
1568 // Output and save the results
1569 call_user_func( $endCB, $name, $status );
1570 $installResults[$name] = $status;
1572 // If we've hit some sort of fatal, we need to bail.
1573 // Callback already had a chance to do output above.
1574 if ( !$status->isOk() ) {
1578 if ( $status->isOk() ) {
1579 $this->setVar( '_InstallDone', true );
1582 return $installResults;
1586 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1590 public function generateKeys() {
1591 $keys = array( 'wgSecretKey' => 64 );
1592 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1593 $keys['wgUpgradeKey'] = 16;
1596 return $this->doGenerateKeys( $keys );
1600 * Generate a secret value for variables using our CryptRand generator.
1601 * Produce a warning if the random source was insecure.
1603 * @param $keys Array
1606 protected function doGenerateKeys( $keys ) {
1607 $status = Status
::newGood();
1610 foreach ( $keys as $name => $length ) {
1611 $secretKey = MWCryptRand
::generateHex( $length, true );
1612 if ( !MWCryptRand
::wasStrong() ) {
1616 $this->setVar( $name, $secretKey );
1620 $names = array_keys( $keys );
1621 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1623 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1630 * Create the first user account, grant it sysop and bureaucrat rights
1634 protected function createSysop() {
1635 $name = $this->getVar( '_AdminName' );
1636 $user = User
::newFromName( $name );
1639 // We should've validated this earlier anyway!
1640 return Status
::newFatal( 'config-admin-error-user', $name );
1643 if ( $user->idForName() == 0 ) {
1644 $user->addToDatabase();
1647 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1648 } catch ( PasswordError
$pwe ) {
1649 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1652 $user->addGroup( 'sysop' );
1653 $user->addGroup( 'bureaucrat' );
1654 if ( $this->getVar( '_AdminEmail' ) ) {
1655 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1657 $user->saveSettings();
1659 // Update user count
1660 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1661 $ssUpdate->doUpdate();
1663 $status = Status
::newGood();
1665 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1666 $this->subscribeToMediaWikiAnnounce( $status );
1675 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1677 'email' => $this->getVar( '_AdminEmail' ),
1682 // Mailman doesn't support as many languages as we do, so check to make
1683 // sure their selected language is available
1684 $myLang = $this->getVar( '_UserLang' );
1685 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1686 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1687 $params['language'] = $myLang;
1690 if ( MWHttpRequest
::canMakeRequests() ) {
1691 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1692 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1693 if ( !$res->isOK() ) {
1694 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1697 $s->warning( 'config-install-subscribe-notpossible' );
1702 * Insert Main Page with default content.
1704 * @param $installer DatabaseInstaller
1707 protected function createMainpage( DatabaseInstaller
$installer ) {
1708 $status = Status
::newGood();
1710 $page = WikiPage
::factory( Title
::newMainPage() );
1711 $content = new WikitextContent(
1712 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1713 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1716 $page->doEditContent( $content,
1720 User
::newFromName( 'MediaWiki default' )
1722 } catch ( MWException
$e ) {
1723 //using raw, because $wgShowExceptionDetails can not be set yet
1724 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1731 * Override the necessary bits of the config to run an installation.
1733 public static function overrideConfig() {
1734 define( 'MW_NO_SESSION', 1 );
1736 // Don't access the database
1737 $GLOBALS['wgUseDatabaseMessages'] = false;
1738 // Don't cache langconv tables
1739 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1741 $GLOBALS['wgShowExceptionDetails'] = true;
1742 // Don't break forms
1743 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1745 // Extended debugging
1746 $GLOBALS['wgShowSQLErrors'] = true;
1747 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1749 // Allow multiple ob_flush() calls
1750 $GLOBALS['wgDisableOutputCompression'] = true;
1752 // Use a sensible cookie prefix (not my_wiki)
1753 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1755 // Some of the environment checks make shell requests, remove limits
1756 $GLOBALS['wgMaxShellMemory'] = 0;
1758 // Don't bother embedding images into generated CSS, which is not cached
1759 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1760 return $less->toBool( false );
1765 * Add an installation step following the given step.
1767 * @param array $callback A valid installation callback array, in this form:
1768 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1769 * @param string $findStep the step to find. Omit to put the step at the beginning
1771 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1772 $this->extraInstallSteps
[$findStep][] = $callback;
1776 * Disable the time limit for execution.
1777 * Some long-running pages (Install, Upgrade) will want to do this
1779 protected function disableTimeLimit() {
1780 wfSuppressWarnings();
1781 set_time_limit( 0 );
1782 wfRestoreWarnings();