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(
110 * A list of environment check methods called by doEnvironmentChecks().
111 * These may output warnings using showMessage(), and/or abort the
112 * installation process by returning false.
116 protected $envChecks = array(
118 'envCheckRegisterGlobals',
120 'envCheckMagicQuotes',
121 'envCheckMagicSybase',
128 'envCheckModSecurity',
135 'envCheckShellLocale',
136 'envCheckUploadsDirectory',
138 'envCheckSuhosinMaxValueLength',
144 * MediaWiki configuration globals that will eventually be passed through
145 * to LocalSettings.php. The names only are given here, the defaults
146 * typically come from DefaultSettings.php.
150 protected $defaultVarNames = array(
162 'wgEmailAuthentication',
165 'wgImageMagickConvertCommand',
171 'wgDeletedDirectory',
175 'wgUseInstantCommons',
178 'wgResourceLoaderMaxQueryLength',
182 * Variables that are stored alongside globals, and are used for any
183 * configuration of the installation process aside from the MediaWiki
184 * configuration. Map of names to defaults.
188 protected $internalDefaults = array(
190 '_Environment' => false,
191 '_SafeMode' => false,
192 '_RaiseMemory' => false,
193 '_UpgradeDone' => false,
194 '_InstallDone' => false,
195 '_Caches' => array(),
196 '_InstallPassword' => '',
197 '_SameAccount' => true,
198 '_CreateDBAccount' => false,
199 '_NamespaceType' => 'site-name',
200 '_AdminName' => '', // will be set later, when the user selects language
201 '_AdminPassword' => '',
202 '_AdminPasswordConfirm' => '',
204 '_Subscribe' => false,
205 '_SkipOptional' => 'continue',
206 '_RightsProfile' => 'wiki',
207 '_LicenseCode' => 'none',
209 '_Extensions' => array(),
210 '_MemCachedServers' => '',
211 '_UpgradeKeySupplied' => false,
212 '_ExistingDBSettings' => false,
214 // $wgLogo is probably wrong (bug 48084); set something that will work.
215 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
216 'wgLogo' => '$wgStylePath/common/images/wiki.png',
220 * The actual list of installation steps. This will be initialized by getInstallSteps()
224 private $installSteps = array();
227 * Extra steps for installation, for things like DatabaseInstallers to modify
231 protected $extraInstallSteps = array();
234 * Known object cache types and the functions used to test for their existence.
238 protected $objectCaches = array(
239 'xcache' => 'xcache_get',
240 'apc' => 'apc_fetch',
241 'wincache' => 'wincache_ucache_get'
245 * User rights profiles.
249 public $rightsProfiles = array(
252 '*' => array( 'edit' => false )
256 'createaccount' => false,
262 'createaccount' => false,
274 public $licenses = array(
276 'url' => 'http://creativecommons.org/licenses/by/3.0/',
277 'icon' => '{$wgStylePath}/common/images/cc-by.png',
280 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
281 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
283 'cc-by-nc-sa' => array(
284 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
285 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
288 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
289 'icon' => '{$wgStylePath}/common/images/cc-0.png',
293 'icon' => '{$wgStylePath}/common/images/public-domain.png',
296 'url' => 'http://www.gnu.org/copyleft/fdl.html',
297 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
304 'cc-choose' => array(
305 // Details will be filled in by the selector.
313 * URL to mediawiki-announce subscription
315 protected $mediaWikiAnnounceUrl =
316 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
319 * Supported language codes for Mailman
321 protected $mediaWikiAnnounceLanguages = array(
322 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
323 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
324 'sl', 'sr', 'sv', 'tr', 'uk'
328 * UI interface for displaying a short message
329 * The parameters are like parameters to wfMessage().
330 * The messages will be in wikitext format, which will be converted to an
331 * output format such as HTML or text before being sent to the user.
334 abstract public function showMessage( $msg /*, ... */ );
337 * Same as showMessage(), but for displaying errors
340 abstract public function showError( $msg /*, ... */ );
343 * Show a message to the installing user by using a Status object
344 * @param Status $status
346 abstract public function showStatusMessage( Status
$status );
349 * Constructor, always call this from child classes.
351 public function __construct() {
352 global $wgMessagesDirs, $wgUser;
354 // Disable the i18n cache
355 Language
::getLocalisationCache()->disableBackend();
356 // Disable LoadBalancer and wfGetDB etc.
357 LBFactory
::disableBackend();
359 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
360 // SqlBagOStuff will then throw since we just disabled wfGetDB)
361 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
362 ObjectCache
::clear();
363 $emptyCache = array( 'class' => 'EmptyBagOStuff' );
364 $GLOBALS['wgObjectCaches'] = array(
365 CACHE_NONE
=> $emptyCache,
366 CACHE_DB
=> $emptyCache,
367 CACHE_ANYTHING
=> $emptyCache,
368 CACHE_MEMCACHED
=> $emptyCache,
371 // Load the installer's i18n.
372 $wgMessagesDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
374 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
375 $wgUser = User
::newFromId( 0 );
377 $this->settings
= $this->internalDefaults
;
379 foreach ( $this->defaultVarNames
as $var ) {
380 $this->settings
[$var] = $GLOBALS[$var];
383 $this->compiledDBs
= array();
384 foreach ( self
::getDBTypes() as $type ) {
385 $installer = $this->getDBInstaller( $type );
387 if ( !$installer->isCompiled() ) {
390 $this->compiledDBs
[] = $type;
393 $this->parserTitle
= Title
::newFromText( 'Installer' );
394 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
395 $this->parserOptions
->setEditSection( false );
399 * Get a list of known DB types.
403 public static function getDBTypes() {
404 return self
::$dbTypes;
408 * Do initial checks of the PHP environment. Set variables according to
409 * the observed environment.
411 * It's possible that this may be called under the CLI SAPI, not the SAPI
412 * that the wiki will primarily run under. In that case, the subclass should
413 * initialise variables such as wgScriptPath, before calling this function.
415 * Under the web subclass, it can already be assumed that PHP 5+ is in use
416 * and that sessions are working.
420 public function doEnvironmentChecks() {
421 $phpVersion = phpversion();
422 if ( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
423 $this->showMessage( 'config-env-php', $phpVersion );
426 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
430 // Must go here because an old version of PCRE can prevent other checks from completing
432 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
433 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
434 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
440 foreach ( $this->envChecks
as $check ) {
441 $status = $this->$check();
442 if ( $status === false ) {
448 $this->setVar( '_Environment', $good );
450 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
454 * Set a MW configuration variable, or internal installer configuration variable.
456 * @param string $name
457 * @param mixed $value
459 public function setVar( $name, $value ) {
460 $this->settings
[$name] = $value;
464 * Get an MW configuration variable, or internal installer configuration variable.
465 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
466 * Installer variables are typically prefixed by an underscore.
468 * @param string $name
469 * @param mixed $default
473 public function getVar( $name, $default = null ) {
474 if ( !isset( $this->settings
[$name] ) ) {
477 return $this->settings
[$name];
482 * Get a list of DBs supported by current PHP setup
486 public function getCompiledDBs() {
487 return $this->compiledDBs
;
491 * Get an instance of DatabaseInstaller for the specified DB type.
493 * @param mixed $type DB installer for which is needed, false to use default.
495 * @return DatabaseInstaller
497 public function getDBInstaller( $type = false ) {
499 $type = $this->getVar( 'wgDBtype' );
502 $type = strtolower( $type );
504 if ( !isset( $this->dbInstallers
[$type] ) ) {
505 $class = ucfirst( $type ) . 'Installer';
506 $this->dbInstallers
[$type] = new $class( $this );
509 return $this->dbInstallers
[$type];
513 * Determine if LocalSettings.php exists. If it does, return its variables.
517 public static function getExistingLocalSettings() {
520 wfSuppressWarnings();
521 $_lsExists = file_exists( "$IP/LocalSettings.php" );
529 require "$IP/includes/DefaultSettings.php";
530 require "$IP/LocalSettings.php";
532 return get_defined_vars();
536 * Get a fake password for sending back to the user in HTML.
537 * This is a security mechanism to avoid compromise of the password in the
538 * event of session ID compromise.
540 * @param string $realPassword
544 public function getFakePassword( $realPassword ) {
545 return str_repeat( '*', strlen( $realPassword ) );
549 * Set a variable which stores a password, except if the new value is a
550 * fake password in which case leave it as it is.
552 * @param string $name
553 * @param mixed $value
555 public function setPassword( $name, $value ) {
556 if ( !preg_match( '/^\*+$/', $value ) ) {
557 $this->setVar( $name, $value );
562 * On POSIX systems return the primary group of the webserver we're running under.
563 * On other systems just returns null.
565 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
566 * webserver user before he can install.
568 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
572 public static function maybeGetWebserverPrimaryGroup() {
573 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
574 # I don't know this, this isn't UNIX.
578 # posix_getegid() *not* getmygid() because we want the group of the webserver,
579 # not whoever owns the current script.
580 $gid = posix_getegid();
581 $getpwuid = posix_getpwuid( $gid );
582 $group = $getpwuid['name'];
588 * Convert wikitext $text to HTML.
590 * This is potentially error prone since many parser features require a complete
591 * installed MW database. The solution is to just not use those features when you
592 * write your messages. This appears to work well enough. Basic formatting and
593 * external links work just fine.
595 * But in case a translator decides to throw in a "#ifexist" or internal link or
596 * whatever, this function is guarded to catch the attempted DB access and to present
597 * some fallback text.
599 * @param string $text
600 * @param bool $lineStart
603 public function parse( $text, $lineStart = false ) {
607 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
608 $html = $out->getText();
609 } catch ( DBAccessError
$e ) {
610 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
612 if ( !empty( $this->debug
) ) {
613 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
621 * @return ParserOptions
623 public function getParserOptions() {
624 return $this->parserOptions
;
627 public function disableLinkPopups() {
628 $this->parserOptions
->setExternalLinkTarget( false );
631 public function restoreLinkPopups() {
632 global $wgExternalLinkTarget;
633 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
637 * Install step which adds a row to the site_stats table with appropriate
640 * @param DatabaseInstaller $installer
644 public function populateSiteStats( DatabaseInstaller
$installer ) {
645 $status = $installer->getConnection();
646 if ( !$status->isOK() ) {
649 $status->value
->insert(
653 'ss_total_views' => 0,
654 'ss_total_edits' => 0,
655 'ss_good_articles' => 0,
656 'ss_total_pages' => 0,
663 return Status
::newGood();
667 * Exports all wg* variables stored by the installer into global scope.
669 public function exportVars() {
670 foreach ( $this->settings
as $name => $value ) {
671 if ( substr( $name, 0, 2 ) == 'wg' ) {
672 $GLOBALS[$name] = $value;
678 * Environment check for DB types.
681 protected function envCheckDB() {
686 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
687 // config-type-sqlite
688 foreach ( self
::getDBTypes() as $name ) {
689 $allNames[] = wfMessage( "config-type-$name" )->text();
692 $databases = $this->getCompiledDBs();
694 $databases = array_flip( $databases );
695 foreach ( array_keys( $databases ) as $db ) {
696 $installer = $this->getDBInstaller( $db );
697 $status = $installer->checkPrerequisites();
698 if ( !$status->isGood() ) {
699 $this->showStatusMessage( $status );
701 if ( !$status->isOK() ) {
702 unset( $databases[$db] );
705 $databases = array_flip( $databases );
707 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
709 // @todo FIXME: This only works for the web installer!
717 * Environment check for register_globals.
718 * Prevent installation if enabled
720 protected function envCheckRegisterGlobals() {
721 if ( wfIniGetBool( 'register_globals' ) ) {
722 $this->showMessage( 'config-register-globals-error' );
730 * Some versions of libxml+PHP break < and > encoding horribly
733 protected function envCheckBrokenXML() {
734 $test = new PhpXmlBugTester();
736 $this->showError( 'config-brokenlibxml' );
745 * Environment check for magic_quotes_runtime.
748 protected function envCheckMagicQuotes() {
749 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
750 $this->showError( 'config-magic-quotes-runtime' );
759 * Environment check for magic_quotes_sybase.
762 protected function envCheckMagicSybase() {
763 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
764 $this->showError( 'config-magic-quotes-sybase' );
773 * Environment check for mbstring.func_overload.
776 protected function envCheckMbstring() {
777 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
778 $this->showError( 'config-mbstring' );
787 * Environment check for safe_mode.
790 protected function envCheckSafeMode() {
791 if ( wfIniGetBool( 'safe_mode' ) ) {
792 $this->setVar( '_SafeMode', true );
793 $this->showMessage( 'config-safe-mode' );
800 * Environment check for the XML module.
803 protected function envCheckXML() {
804 if ( !function_exists( "utf8_encode" ) ) {
805 $this->showError( 'config-xml-bad' );
814 * Environment check for the PCRE module.
816 * @note If this check were to fail, the parser would
817 * probably throw an exception before the result
818 * of this check is shown to the user.
821 protected function envCheckPCRE() {
822 wfSuppressWarnings();
823 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
824 // Need to check for \p support too, as PCRE can be compiled
825 // with utf8 support, but not unicode property support.
826 // check that \p{Zs} (space separators) matches
827 // U+3000 (Ideographic space)
828 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
830 if ( $regexd != '--' ||
$regexprop != '--' ) {
831 $this->showError( 'config-pcre-no-utf8' );
840 * Environment check for available memory.
843 protected function envCheckMemory() {
844 $limit = ini_get( 'memory_limit' );
846 if ( !$limit ||
$limit == -1 ) {
850 $n = wfShorthandToInteger( $limit );
852 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
853 $newLimit = "{$this->minMemorySize}M";
855 if ( ini_set( "memory_limit", $newLimit ) === false ) {
856 $this->showMessage( 'config-memory-bad', $limit );
858 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
859 $this->setVar( '_RaiseMemory', true );
867 * Environment check for compiled object cache types.
869 protected function envCheckCache() {
871 foreach ( $this->objectCaches
as $name => $function ) {
872 if ( function_exists( $function ) ) {
873 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
876 $caches[$name] = true;
881 $this->showMessage( 'config-no-cache' );
884 $this->setVar( '_Caches', $caches );
888 * Scare user to death if they have mod_security
891 protected function envCheckModSecurity() {
892 if ( self
::apacheModulePresent( 'mod_security' ) ) {
893 $this->showMessage( 'config-mod-security' );
900 * Search for GNU diff3.
903 protected function envCheckDiff3() {
904 $names = array( "gdiff3", "diff3", "diff3.exe" );
905 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
907 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
910 $this->setVar( 'wgDiff3', $diff3 );
912 $this->setVar( 'wgDiff3', false );
913 $this->showMessage( 'config-diff3-bad' );
920 * Environment check for ImageMagick and GD.
923 protected function envCheckGraphics() {
924 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
925 $versionInfo = array( '$1 -version', 'ImageMagick' );
926 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
928 $this->setVar( 'wgImageMagickConvertCommand', '' );
930 $this->setVar( 'wgImageMagickConvertCommand', $convert );
931 $this->showMessage( 'config-imagemagick', $convert );
934 } elseif ( function_exists( 'imagejpeg' ) ) {
935 $this->showMessage( 'config-gd' );
937 $this->showMessage( 'config-no-scaling' );
949 protected function envCheckGit() {
950 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
951 $versionInfo = array( '$1 --version', 'git version' );
953 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
956 $this->setVar( 'wgGitBin', $git );
957 $this->showMessage( 'config-git', $git );
959 $this->setVar( 'wgGitBin', false );
960 $this->showMessage( 'config-git-bad' );
967 * Environment check for the server hostname.
969 protected function envCheckServer() {
970 $server = $this->envGetDefaultServer();
971 if ( $server !== null ) {
972 $this->showMessage( 'config-using-server', $server );
973 $this->setVar( 'wgServer', $server );
980 * Helper function to be called from envCheckServer()
983 abstract protected function envGetDefaultServer();
986 * Environment check for setting $IP and $wgScriptPath.
989 protected function envCheckPath() {
991 $IP = dirname( dirname( __DIR__
) );
992 $this->setVar( 'IP', $IP );
996 $this->getVar( 'wgServer' ),
997 $this->getVar( 'wgScriptPath' )
1004 * Environment check for setting the preferred PHP file extension.
1007 protected function envCheckExtension() {
1008 // @todo FIXME: Detect this properly
1009 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1014 $this->setVar( 'wgScriptExtension', ".$ext" );
1020 * Environment check for preferred locale in shell
1023 protected function envCheckShellLocale() {
1024 $os = php_uname( 's' );
1025 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1027 if ( !in_array( $os, $supported ) ) {
1031 # Get a list of available locales.
1033 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1039 $lines = array_map( 'trim', explode( "\n", $lines ) );
1040 $candidatesByLocale = array();
1041 $candidatesByLang = array();
1043 foreach ( $lines as $line ) {
1044 if ( $line === '' ) {
1048 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1052 list( , $lang, , , ) = $m;
1054 $candidatesByLocale[$m[0]] = $m;
1055 $candidatesByLang[$lang][] = $m;
1058 # Try the current value of LANG.
1059 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1060 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1065 # Try the most common ones.
1066 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1067 foreach ( $commonLocales as $commonLocale ) {
1068 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1069 $this->setVar( 'wgShellLocale', $commonLocale );
1075 # Is there an available locale in the Wiki's language?
1076 $wikiLang = $this->getVar( 'wgLanguageCode' );
1078 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1079 $m = reset( $candidatesByLang[$wikiLang] );
1080 $this->setVar( 'wgShellLocale', $m[0] );
1085 # Are there any at all?
1086 if ( count( $candidatesByLocale ) ) {
1087 $m = reset( $candidatesByLocale );
1088 $this->setVar( 'wgShellLocale', $m[0] );
1098 * Environment check for the permissions of the uploads directory
1101 protected function envCheckUploadsDirectory() {
1104 $dir = $IP . '/images/';
1105 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1106 $safe = !$this->dirIsExecutable( $dir, $url );
1109 $this->showMessage( 'config-uploads-not-safe', $dir );
1116 * Checks if suhosin.get.max_value_length is set, and if so generate
1117 * a warning because it decreases ResourceLoader performance.
1120 protected function envCheckSuhosinMaxValueLength() {
1121 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1122 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1123 // Only warn if the value is below the sane 1024
1124 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1131 * Convert a hex string representing a Unicode code point to that code point.
1135 protected function unicodeChar( $c ) {
1139 } elseif ( $c <= 0x7FF ) {
1140 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1141 } elseif ( $c <= 0xFFFF ) {
1142 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1143 . chr( 0x80 |
$c & 0x3F );
1144 } elseif ( $c <= 0x10FFFF ) {
1145 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1146 . chr( 0x80 |
$c >> 6 & 0x3F )
1147 . chr( 0x80 |
$c & 0x3F );
1154 * Check the libicu version
1156 protected function envCheckLibicu() {
1157 $utf8 = function_exists( 'utf8_normalize' );
1158 $intl = function_exists( 'normalizer_normalize' );
1161 * This needs to be updated something that the latest libicu
1162 * will properly normalize. This normalization was found at
1163 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1164 * Note that we use the hex representation to create the code
1165 * points in order to avoid any Unicode-destroying during transit.
1167 $not_normal_c = $this->unicodeChar( "FA6C" );
1168 $normal_c = $this->unicodeChar( "242EE" );
1170 $useNormalizer = 'php';
1171 $needsUpdate = false;
1174 * We're going to prefer the pecl extension here unless
1175 * utf8_normalize is more up to date.
1178 $useNormalizer = 'utf8';
1179 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1180 if ( $utf8 !== $normal_c ) {
1181 $needsUpdate = true;
1185 $useNormalizer = 'intl';
1186 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1187 if ( $intl !== $normal_c ) {
1188 $needsUpdate = true;
1192 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1193 // 'config-unicode-using-intl'
1194 if ( $useNormalizer === 'php' ) {
1195 $this->showMessage( 'config-unicode-pure-php-warning' );
1197 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1198 if ( $needsUpdate ) {
1199 $this->showMessage( 'config-unicode-update-warning' );
1207 protected function envCheckCtype() {
1208 if ( !function_exists( 'ctype_digit' ) ) {
1209 $this->showError( 'config-ctype' );
1220 protected function envCheckJSON() {
1221 if ( !function_exists( 'json_decode' ) ) {
1222 $this->showError( 'config-json' );
1231 * Get an array of likely places we can find executables. Check a bunch
1232 * of known Unix-like defaults, as well as the PATH environment variable
1233 * (which should maybe make it work for Windows?)
1237 protected static function getPossibleBinPaths() {
1239 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1240 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1241 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1246 * Search a path for any of the given executable names. Returns the
1247 * executable name if found. Also checks the version string returned
1248 * by each executable.
1250 * Used only by environment checks.
1252 * @param string $path path to search
1253 * @param array $names of executable names
1254 * @param array|bool $versionInfo False or array with two members:
1255 * 0 => Command to run for version check, with $1 for the full executable name
1256 * 1 => String to compare the output with
1258 * If $versionInfo is not false, only executables with a version
1259 * matching $versionInfo[1] will be returned.
1260 * @return bool|string
1262 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1263 if ( !is_array( $names ) ) {
1264 $names = array( $names );
1267 foreach ( $names as $name ) {
1268 $command = $path . DIRECTORY_SEPARATOR
. $name;
1270 wfSuppressWarnings();
1271 $file_exists = file_exists( $command );
1272 wfRestoreWarnings();
1274 if ( $file_exists ) {
1275 if ( !$versionInfo ) {
1279 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1280 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1290 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1291 * @see locateExecutable()
1292 * @param array $names Array of possible names.
1293 * @param array|bool $versionInfo Default: false or array with two members:
1294 * 0 => Command to run for version check, with $1 for the full executable name
1295 * 1 => String to compare the output with
1297 * If $versionInfo is not false, only executables with a version
1298 * matching $versionInfo[1] will be returned.
1299 * @return bool|string
1301 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1302 foreach ( self
::getPossibleBinPaths() as $path ) {
1303 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1304 if ( $exe !== false ) {
1313 * Checks if scripts located in the given directory can be executed via the given URL.
1315 * Used only by environment checks.
1316 * @param string $dir
1317 * @param string $url
1318 * @return bool|int|string
1320 public function dirIsExecutable( $dir, $url ) {
1321 $scriptTypes = array(
1323 "<?php echo 'ex' . 'ec';",
1324 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1328 // it would be good to check other popular languages here, but it'll be slow.
1330 wfSuppressWarnings();
1332 foreach ( $scriptTypes as $ext => $contents ) {
1333 foreach ( $contents as $source ) {
1334 $file = 'exectest.' . $ext;
1336 if ( !file_put_contents( $dir . $file, $source ) ) {
1341 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1342 } catch ( MWException
$e ) {
1343 // Http::get throws with allow_url_fopen = false and no curl extension.
1346 unlink( $dir . $file );
1348 if ( $text == 'exec' ) {
1349 wfRestoreWarnings();
1356 wfRestoreWarnings();
1362 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1364 * @param string $moduleName Name of module to check.
1367 public static function apacheModulePresent( $moduleName ) {
1368 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1371 // try it the hard way
1373 phpinfo( INFO_MODULES
);
1374 $info = ob_get_clean();
1376 return strpos( $info, $moduleName ) !== false;
1380 * ParserOptions are constructed before we determined the language, so fix it
1382 * @param Language $lang
1384 public function setParserLanguage( $lang ) {
1385 $this->parserOptions
->setTargetLanguage( $lang );
1386 $this->parserOptions
->setUserLang( $lang );
1390 * Overridden by WebInstaller to provide lastPage parameters.
1391 * @param string $page
1394 protected function getDocUrl( $page ) {
1395 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1399 * Finds extensions that follow the format /extensions/Name/Name.php,
1400 * and returns an array containing the value for 'Name' for each found extension.
1404 public function findExtensions() {
1405 if ( $this->getVar( 'IP' ) === null ) {
1409 $extDir = $this->getVar( 'IP' ) . '/extensions';
1410 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1414 $dh = opendir( $extDir );
1416 while ( ( $file = readdir( $dh ) ) !== false ) {
1417 if ( !is_dir( "$extDir/$file" ) ) {
1420 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1425 natcasesort( $exts );
1431 * Installs the auto-detected extensions.
1435 protected function includeExtensions() {
1437 $exts = $this->getVar( '_Extensions' );
1438 $IP = $this->getVar( 'IP' );
1441 * We need to include DefaultSettings before including extensions to avoid
1442 * warnings about unset variables. However, the only thing we really
1443 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1444 * if the extension has hidden hook registration in $wgExtensionFunctions,
1445 * but we're not opening that can of worms
1446 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1448 global $wgAutoloadClasses;
1449 $wgAutoloadClasses = array();
1451 require "$IP/includes/DefaultSettings.php";
1453 foreach ( $exts as $e ) {
1454 require_once "$IP/extensions/$e/$e.php";
1457 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1458 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1460 // Unset everyone else's hooks. Lord knows what someone might be doing
1461 // in ParserFirstCallInit (see bug 27171)
1462 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1464 return Status
::newGood();
1468 * Get an array of install steps. Should always be in the format of
1470 * 'name' => 'someuniquename',
1471 * 'callback' => array( $obj, 'method' ),
1473 * There must be a config-install-$name message defined per step, which will
1474 * be shown on install.
1476 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1479 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1480 $coreInstallSteps = array(
1481 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1482 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1483 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1484 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1485 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1486 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1487 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1490 // Build the array of install steps starting from the core install list,
1491 // then adding any callbacks that wanted to attach after a given step
1492 foreach ( $coreInstallSteps as $step ) {
1493 $this->installSteps
[] = $step;
1494 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1495 $this->installSteps
= array_merge(
1496 $this->installSteps
,
1497 $this->extraInstallSteps
[$step['name']]
1502 // Prepend any steps that want to be at the beginning
1503 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1504 $this->installSteps
= array_merge(
1505 $this->extraInstallSteps
['BEGINNING'],
1510 // Extensions should always go first, chance to tie into hooks and such
1511 if ( count( $this->getVar( '_Extensions' ) ) ) {
1512 array_unshift( $this->installSteps
,
1513 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1515 $this->installSteps
[] = array(
1516 'name' => 'extension-tables',
1517 'callback' => array( $installer, 'createExtensionTables' )
1521 return $this->installSteps
;
1525 * Actually perform the installation.
1527 * @param callable $startCB A callback array for the beginning of each step
1528 * @param callable $endCB A callback array for the end of each step
1530 * @return array Array of Status objects
1532 public function performInstallation( $startCB, $endCB ) {
1533 $installResults = array();
1534 $installer = $this->getDBInstaller();
1535 $installer->preInstall();
1536 $steps = $this->getInstallSteps( $installer );
1537 foreach ( $steps as $stepObj ) {
1538 $name = $stepObj['name'];
1539 call_user_func_array( $startCB, array( $name ) );
1541 // Perform the callback step
1542 $status = call_user_func( $stepObj['callback'], $installer );
1544 // Output and save the results
1545 call_user_func( $endCB, $name, $status );
1546 $installResults[$name] = $status;
1548 // If we've hit some sort of fatal, we need to bail.
1549 // Callback already had a chance to do output above.
1550 if ( !$status->isOk() ) {
1554 if ( $status->isOk() ) {
1555 $this->setVar( '_InstallDone', true );
1558 return $installResults;
1562 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1566 public function generateKeys() {
1567 $keys = array( 'wgSecretKey' => 64 );
1568 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1569 $keys['wgUpgradeKey'] = 16;
1572 return $this->doGenerateKeys( $keys );
1576 * Generate a secret value for variables using our CryptRand generator.
1577 * Produce a warning if the random source was insecure.
1579 * @param array $keys
1582 protected function doGenerateKeys( $keys ) {
1583 $status = Status
::newGood();
1586 foreach ( $keys as $name => $length ) {
1587 $secretKey = MWCryptRand
::generateHex( $length, true );
1588 if ( !MWCryptRand
::wasStrong() ) {
1592 $this->setVar( $name, $secretKey );
1596 $names = array_keys( $keys );
1597 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1599 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1606 * Create the first user account, grant it sysop and bureaucrat rights
1610 protected function createSysop() {
1611 $name = $this->getVar( '_AdminName' );
1612 $user = User
::newFromName( $name );
1615 // We should've validated this earlier anyway!
1616 return Status
::newFatal( 'config-admin-error-user', $name );
1619 if ( $user->idForName() == 0 ) {
1620 $user->addToDatabase();
1623 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1624 } catch ( PasswordError
$pwe ) {
1625 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1628 $user->addGroup( 'sysop' );
1629 $user->addGroup( 'bureaucrat' );
1630 if ( $this->getVar( '_AdminEmail' ) ) {
1631 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1633 $user->saveSettings();
1635 // Update user count
1636 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1637 $ssUpdate->doUpdate();
1639 $status = Status
::newGood();
1641 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1642 $this->subscribeToMediaWikiAnnounce( $status );
1651 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1653 'email' => $this->getVar( '_AdminEmail' ),
1658 // Mailman doesn't support as many languages as we do, so check to make
1659 // sure their selected language is available
1660 $myLang = $this->getVar( '_UserLang' );
1661 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1662 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1663 $params['language'] = $myLang;
1666 if ( MWHttpRequest
::canMakeRequests() ) {
1667 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1668 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1669 if ( !$res->isOK() ) {
1670 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1673 $s->warning( 'config-install-subscribe-notpossible' );
1678 * Insert Main Page with default content.
1680 * @param DatabaseInstaller $installer
1683 protected function createMainpage( DatabaseInstaller
$installer ) {
1684 $status = Status
::newGood();
1686 $page = WikiPage
::factory( Title
::newMainPage() );
1687 $content = new WikitextContent(
1688 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1689 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1692 $page->doEditContent( $content,
1696 User
::newFromName( 'MediaWiki default' )
1698 } catch ( MWException
$e ) {
1699 //using raw, because $wgShowExceptionDetails can not be set yet
1700 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1707 * Override the necessary bits of the config to run an installation.
1709 public static function overrideConfig() {
1710 define( 'MW_NO_SESSION', 1 );
1712 // Don't access the database
1713 $GLOBALS['wgUseDatabaseMessages'] = false;
1714 // Don't cache langconv tables
1715 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1717 $GLOBALS['wgShowExceptionDetails'] = true;
1718 // Don't break forms
1719 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1721 // Extended debugging
1722 $GLOBALS['wgShowSQLErrors'] = true;
1723 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1725 // Allow multiple ob_flush() calls
1726 $GLOBALS['wgDisableOutputCompression'] = true;
1728 // Use a sensible cookie prefix (not my_wiki)
1729 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1731 // Some of the environment checks make shell requests, remove limits
1732 $GLOBALS['wgMaxShellMemory'] = 0;
1734 // Don't bother embedding images into generated CSS, which is not cached
1735 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1736 return $less->toBool( false );
1741 * Add an installation step following the given step.
1743 * @param callable $callback A valid installation callback array, in this form:
1744 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1745 * @param string $findStep The step to find. Omit to put the step at the beginning
1747 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1748 $this->extraInstallSteps
[$findStep][] = $callback;
1752 * Disable the time limit for execution.
1753 * Some long-running pages (Install, Upgrade) will want to do this
1755 protected function disableTimeLimit() {
1756 wfSuppressWarnings();
1757 set_time_limit( 0 );
1758 wfRestoreWarnings();