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
{
42 * The oldest version of PCRE we can support.
44 * Defining this is necessary because PHP may be linked with a system version
45 * of PCRE, which may be older than that bundled with the minimum PHP version.
47 const MINIMUM_PCRE_VERSION
= '7.2';
55 * List of detected DBs, access using getCompiledDBs().
59 protected $compiledDBs;
62 * Cached DB installer instances, access using getDBInstaller().
66 protected $dbInstallers = array();
69 * Minimum memory size in MB.
73 protected $minMemorySize = 50;
76 * Cached Title, used by parse().
80 protected $parserTitle;
83 * Cached ParserOptions, used by parse().
87 protected $parserOptions;
90 * Known database types. These correspond to the class names <type>Installer,
91 * and are also MediaWiki database types valid for $wgDBtype.
93 * To add a new type, create a <type>Installer class and a Database<type>
94 * class, and add a config-type-<type> message to MessagesEn.php.
98 protected static $dbTypes = array(
107 * A list of environment check methods called by doEnvironmentChecks().
108 * These may output warnings using showMessage(), and/or abort the
109 * installation process by returning false.
111 * For the WebInstaller these are only called on the Welcome page,
112 * if these methods have side-effects that should affect later page loads
113 * (as well as the generated stylesheet), use envPreps instead.
117 protected $envChecks = array(
119 'envCheckRegisterGlobals',
121 'envCheckMagicQuotes',
128 'envCheckModSecurity',
134 'envCheckShellLocale',
135 'envCheckUploadsDirectory',
137 'envCheckSuhosinMaxValueLength',
144 * A list of environment preparation methods called by doEnvironmentPreps().
148 protected $envPreps = array(
154 * MediaWiki configuration globals that will eventually be passed through
155 * to LocalSettings.php. The names only are given here, the defaults
156 * typically come from DefaultSettings.php.
160 protected $defaultVarNames = array(
172 'wgEmailAuthentication',
175 'wgImageMagickConvertCommand',
180 'wgDeletedDirectory',
184 'wgUseInstantCommons',
190 * Variables that are stored alongside globals, and are used for any
191 * configuration of the installation process aside from the MediaWiki
192 * configuration. Map of names to defaults.
196 protected $internalDefaults = array(
198 '_Environment' => false,
199 '_SafeMode' => false,
200 '_RaiseMemory' => false,
201 '_UpgradeDone' => false,
202 '_InstallDone' => false,
203 '_Caches' => array(),
204 '_InstallPassword' => '',
205 '_SameAccount' => true,
206 '_CreateDBAccount' => false,
207 '_NamespaceType' => 'site-name',
208 '_AdminName' => '', // will be set later, when the user selects language
209 '_AdminPassword' => '',
210 '_AdminPasswordConfirm' => '',
212 '_Subscribe' => false,
213 '_SkipOptional' => 'continue',
214 '_RightsProfile' => 'wiki',
215 '_LicenseCode' => 'none',
217 '_Extensions' => array(),
219 '_MemCachedServers' => '',
220 '_UpgradeKeySupplied' => false,
221 '_ExistingDBSettings' => false,
223 // $wgLogo is probably wrong (bug 48084); set something that will work.
224 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
225 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
229 * The actual list of installation steps. This will be initialized by getInstallSteps()
233 private $installSteps = array();
236 * Extra steps for installation, for things like DatabaseInstallers to modify
240 protected $extraInstallSteps = array();
243 * Known object cache types and the functions used to test for their existence.
247 protected $objectCaches = array(
248 'xcache' => 'xcache_get',
249 'apc' => 'apc_fetch',
250 'wincache' => 'wincache_ucache_get'
254 * User rights profiles.
258 public $rightsProfiles = array(
261 '*' => array( 'edit' => false )
265 'createaccount' => false,
271 'createaccount' => false,
283 public $licenses = array(
285 'url' => 'https://creativecommons.org/licenses/by/3.0/',
286 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
289 'url' => 'https://creativecommons.org/licenses/by-sa/3.0/',
290 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
292 'cc-by-nc-sa' => array(
293 'url' => 'https://creativecommons.org/licenses/by-nc-sa/3.0/',
294 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
297 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
298 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
302 'icon' => '$wgResourceBasePath/resources/assets/licenses/public-domain.png',
305 'url' => 'https://www.gnu.org/copyleft/fdl.html',
306 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
313 'cc-choose' => array(
314 // Details will be filled in by the selector.
322 * URL to mediawiki-announce subscription
324 protected $mediaWikiAnnounceUrl =
325 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
328 * Supported language codes for Mailman
330 protected $mediaWikiAnnounceLanguages = array(
331 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
332 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
333 'sl', 'sr', 'sv', 'tr', 'uk'
337 * UI interface for displaying a short message
338 * The parameters are like parameters to wfMessage().
339 * The messages will be in wikitext format, which will be converted to an
340 * output format such as HTML or text before being sent to the user.
343 abstract public function showMessage( $msg /*, ... */ );
346 * Same as showMessage(), but for displaying errors
349 abstract public function showError( $msg /*, ... */ );
352 * Show a message to the installing user by using a Status object
353 * @param Status $status
355 abstract public function showStatusMessage( Status
$status );
358 * Constructor, always call this from child classes.
360 public function __construct() {
361 global $wgMessagesDirs, $wgUser;
363 // Disable the i18n cache
364 Language
::getLocalisationCache()->disableBackend();
365 // Disable LoadBalancer and wfGetDB etc.
366 LBFactory
::disableBackend();
368 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
369 // SqlBagOStuff will then throw since we just disabled wfGetDB)
370 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
371 ObjectCache
::clear();
372 $emptyCache = array( 'class' => 'EmptyBagOStuff' );
373 // disable (problematic) object cache types explicitly, preserving all other (working) ones
375 $GLOBALS['wgObjectCaches'] = array(
376 CACHE_NONE
=> $emptyCache,
377 CACHE_DB
=> $emptyCache,
378 CACHE_ANYTHING
=> $emptyCache,
379 CACHE_MEMCACHED
=> $emptyCache,
380 ) +
$GLOBALS['wgObjectCaches'];
382 // Load the installer's i18n.
383 $wgMessagesDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
385 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
386 $wgUser = User
::newFromId( 0 );
388 $this->settings
= $this->internalDefaults
;
390 foreach ( $this->defaultVarNames
as $var ) {
391 $this->settings
[$var] = $GLOBALS[$var];
394 $this->doEnvironmentPreps();
396 $this->compiledDBs
= array();
397 foreach ( self
::getDBTypes() as $type ) {
398 $installer = $this->getDBInstaller( $type );
400 if ( !$installer->isCompiled() ) {
403 $this->compiledDBs
[] = $type;
406 $this->parserTitle
= Title
::newFromText( 'Installer' );
407 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
408 $this->parserOptions
->setEditSection( false );
412 * Get a list of known DB types.
416 public static function getDBTypes() {
417 return self
::$dbTypes;
421 * Do initial checks of the PHP environment. Set variables according to
422 * the observed environment.
424 * It's possible that this may be called under the CLI SAPI, not the SAPI
425 * that the wiki will primarily run under. In that case, the subclass should
426 * initialise variables such as wgScriptPath, before calling this function.
428 * Under the web subclass, it can already be assumed that PHP 5+ is in use
429 * and that sessions are working.
433 public function doEnvironmentChecks() {
434 // Php version has already been checked by entry scripts
435 // Show message here for information purposes
437 $this->showMessage( 'config-env-hhvm', HHVM_VERSION
);
439 $this->showMessage( 'config-env-php', PHP_VERSION
);
443 // Must go here because an old version of PCRE can prevent other checks from completing
444 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
445 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
446 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
449 foreach ( $this->envChecks
as $check ) {
450 $status = $this->$check();
451 if ( $status === false ) {
457 $this->setVar( '_Environment', $good );
459 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
462 public function doEnvironmentPreps() {
463 foreach ( $this->envPreps
as $prep ) {
469 * Set a MW configuration variable, or internal installer configuration variable.
471 * @param string $name
472 * @param mixed $value
474 public function setVar( $name, $value ) {
475 $this->settings
[$name] = $value;
479 * Get an MW configuration variable, or internal installer configuration variable.
480 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
481 * Installer variables are typically prefixed by an underscore.
483 * @param string $name
484 * @param mixed $default
488 public function getVar( $name, $default = null ) {
489 if ( !isset( $this->settings
[$name] ) ) {
492 return $this->settings
[$name];
497 * Get a list of DBs supported by current PHP setup
501 public function getCompiledDBs() {
502 return $this->compiledDBs
;
506 * Get an instance of DatabaseInstaller for the specified DB type.
508 * @param mixed $type DB installer for which is needed, false to use default.
510 * @return DatabaseInstaller
512 public function getDBInstaller( $type = false ) {
514 $type = $this->getVar( 'wgDBtype' );
517 $type = strtolower( $type );
519 if ( !isset( $this->dbInstallers
[$type] ) ) {
520 $class = ucfirst( $type ) . 'Installer';
521 $this->dbInstallers
[$type] = new $class( $this );
524 return $this->dbInstallers
[$type];
528 * Determine if LocalSettings.php exists. If it does, return its variables.
532 public static function getExistingLocalSettings() {
535 // You might be wondering why this is here. Well if you don't do this
536 // then some poorly-formed extensions try to call their own classes
537 // after immediately registering them. We really need to get extension
538 // registration out of the global scope and into a real format.
539 // @see https://phabricator.wikimedia.org/T69440
540 global $wgAutoloadClasses;
541 $wgAutoloadClasses = array();
543 // @codingStandardsIgnoreStart
544 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
545 // Define the required globals here, to ensure, the functions can do it work correctly.
546 global $wgExtensionDirectory, $wgStyleDirectory;
547 // @codingStandardsIgnoreEnd
549 MediaWiki\
suppressWarnings();
550 $_lsExists = file_exists( "$IP/LocalSettings.php" );
551 MediaWiki\restoreWarnings
();
558 require "$IP/includes/DefaultSettings.php";
559 require "$IP/LocalSettings.php";
561 return get_defined_vars();
565 * Get a fake password for sending back to the user in HTML.
566 * This is a security mechanism to avoid compromise of the password in the
567 * event of session ID compromise.
569 * @param string $realPassword
573 public function getFakePassword( $realPassword ) {
574 return str_repeat( '*', strlen( $realPassword ) );
578 * Set a variable which stores a password, except if the new value is a
579 * fake password in which case leave it as it is.
581 * @param string $name
582 * @param mixed $value
584 public function setPassword( $name, $value ) {
585 if ( !preg_match( '/^\*+$/', $value ) ) {
586 $this->setVar( $name, $value );
591 * On POSIX systems return the primary group of the webserver we're running under.
592 * On other systems just returns null.
594 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
595 * webserver user before he can install.
597 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
601 public static function maybeGetWebserverPrimaryGroup() {
602 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
603 # I don't know this, this isn't UNIX.
607 # posix_getegid() *not* getmygid() because we want the group of the webserver,
608 # not whoever owns the current script.
609 $gid = posix_getegid();
610 $getpwuid = posix_getpwuid( $gid );
611 $group = $getpwuid['name'];
617 * Convert wikitext $text to HTML.
619 * This is potentially error prone since many parser features require a complete
620 * installed MW database. The solution is to just not use those features when you
621 * write your messages. This appears to work well enough. Basic formatting and
622 * external links work just fine.
624 * But in case a translator decides to throw in a "#ifexist" or internal link or
625 * whatever, this function is guarded to catch the attempted DB access and to present
626 * some fallback text.
628 * @param string $text
629 * @param bool $lineStart
632 public function parse( $text, $lineStart = false ) {
636 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
637 $html = $out->getText();
638 } catch ( DBAccessError
$e ) {
639 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
641 if ( !empty( $this->debug
) ) {
642 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
650 * @return ParserOptions
652 public function getParserOptions() {
653 return $this->parserOptions
;
656 public function disableLinkPopups() {
657 $this->parserOptions
->setExternalLinkTarget( false );
660 public function restoreLinkPopups() {
661 global $wgExternalLinkTarget;
662 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
666 * Install step which adds a row to the site_stats table with appropriate
669 * @param DatabaseInstaller $installer
673 public function populateSiteStats( DatabaseInstaller
$installer ) {
674 $status = $installer->getConnection();
675 if ( !$status->isOK() ) {
678 $status->value
->insert(
682 'ss_total_edits' => 0,
683 'ss_good_articles' => 0,
684 'ss_total_pages' => 0,
691 return Status
::newGood();
695 * Exports all wg* variables stored by the installer into global scope.
697 public function exportVars() {
698 foreach ( $this->settings
as $name => $value ) {
699 if ( substr( $name, 0, 2 ) == 'wg' ) {
700 $GLOBALS[$name] = $value;
706 * Environment check for DB types.
709 protected function envCheckDB() {
714 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
715 // config-type-sqlite
716 foreach ( self
::getDBTypes() as $name ) {
717 $allNames[] = wfMessage( "config-type-$name" )->text();
720 $databases = $this->getCompiledDBs();
722 $databases = array_flip( $databases );
723 foreach ( array_keys( $databases ) as $db ) {
724 $installer = $this->getDBInstaller( $db );
725 $status = $installer->checkPrerequisites();
726 if ( !$status->isGood() ) {
727 $this->showStatusMessage( $status );
729 if ( !$status->isOK() ) {
730 unset( $databases[$db] );
733 $databases = array_flip( $databases );
735 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
737 // @todo FIXME: This only works for the web installer!
745 * Environment check for register_globals.
746 * Prevent installation if enabled
749 protected function envCheckRegisterGlobals() {
750 if ( wfIniGetBool( 'register_globals' ) ) {
751 $this->showMessage( 'config-register-globals-error' );
759 * Some versions of libxml+PHP break < and > encoding horribly
762 protected function envCheckBrokenXML() {
763 $test = new PhpXmlBugTester();
765 $this->showError( 'config-brokenlibxml' );
774 * Environment check for magic_quotes_(gpc|runtime|sybase).
777 protected function envCheckMagicQuotes() {
779 foreach ( array( 'gpc', 'runtime', 'sybase' ) as $magicJunk ) {
780 if ( wfIniGetBool( "magic_quotes_$magicJunk" ) ) {
781 $this->showError( "config-magic-quotes-$magicJunk" );
790 * Environment check for mbstring.func_overload.
793 protected function envCheckMbstring() {
794 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
795 $this->showError( 'config-mbstring' );
804 * Environment check for safe_mode.
807 protected function envCheckSafeMode() {
808 if ( wfIniGetBool( 'safe_mode' ) ) {
809 $this->setVar( '_SafeMode', true );
810 $this->showMessage( 'config-safe-mode' );
817 * Environment check for the XML module.
820 protected function envCheckXML() {
821 if ( !function_exists( "utf8_encode" ) ) {
822 $this->showError( 'config-xml-bad' );
831 * Environment check for the PCRE module.
833 * @note If this check were to fail, the parser would
834 * probably throw an exception before the result
835 * of this check is shown to the user.
838 protected function envCheckPCRE() {
839 MediaWiki\
suppressWarnings();
840 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
841 // Need to check for \p support too, as PCRE can be compiled
842 // with utf8 support, but not unicode property support.
843 // check that \p{Zs} (space separators) matches
844 // U+3000 (Ideographic space)
845 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
846 MediaWiki\restoreWarnings
();
847 if ( $regexd != '--' ||
$regexprop != '--' ) {
848 $this->showError( 'config-pcre-no-utf8' );
857 * Environment check for available memory.
860 protected function envCheckMemory() {
861 $limit = ini_get( 'memory_limit' );
863 if ( !$limit ||
$limit == -1 ) {
867 $n = wfShorthandToInteger( $limit );
869 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
870 $newLimit = "{$this->minMemorySize}M";
872 if ( ini_set( "memory_limit", $newLimit ) === false ) {
873 $this->showMessage( 'config-memory-bad', $limit );
875 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
876 $this->setVar( '_RaiseMemory', true );
884 * Environment check for compiled object cache types.
886 protected function envCheckCache() {
888 foreach ( $this->objectCaches
as $name => $function ) {
889 if ( function_exists( $function ) ) {
890 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
893 $caches[$name] = true;
898 $this->showMessage( 'config-no-cache' );
901 $this->setVar( '_Caches', $caches );
905 * Scare user to death if they have mod_security or mod_security2
908 protected function envCheckModSecurity() {
909 if ( self
::apacheModulePresent( 'mod_security' )
910 || self
::apacheModulePresent( 'mod_security2' ) ) {
911 $this->showMessage( 'config-mod-security' );
918 * Search for GNU diff3.
921 protected function envCheckDiff3() {
922 $names = array( "gdiff3", "diff3", "diff3.exe" );
923 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
925 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
928 $this->setVar( 'wgDiff3', $diff3 );
930 $this->setVar( 'wgDiff3', false );
931 $this->showMessage( 'config-diff3-bad' );
938 * Environment check for ImageMagick and GD.
941 protected function envCheckGraphics() {
942 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
943 $versionInfo = array( '$1 -version', 'ImageMagick' );
944 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
946 $this->setVar( 'wgImageMagickConvertCommand', '' );
948 $this->setVar( 'wgImageMagickConvertCommand', $convert );
949 $this->showMessage( 'config-imagemagick', $convert );
952 } elseif ( function_exists( 'imagejpeg' ) ) {
953 $this->showMessage( 'config-gd' );
955 $this->showMessage( 'config-no-scaling' );
967 protected function envCheckGit() {
968 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
969 $versionInfo = array( '$1 --version', 'git version' );
971 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
974 $this->setVar( 'wgGitBin', $git );
975 $this->showMessage( 'config-git', $git );
977 $this->setVar( 'wgGitBin', false );
978 $this->showMessage( 'config-git-bad' );
985 * Environment check to inform user which server we've assumed.
989 protected function envCheckServer() {
990 $server = $this->envGetDefaultServer();
991 if ( $server !== null ) {
992 $this->showMessage( 'config-using-server', $server );
998 * Environment check to inform user which paths we've assumed.
1002 protected function envCheckPath() {
1005 $this->getVar( 'wgServer' ),
1006 $this->getVar( 'wgScriptPath' )
1012 * Environment check for preferred locale in shell
1015 protected function envCheckShellLocale() {
1016 $os = php_uname( 's' );
1017 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1019 if ( !in_array( $os, $supported ) ) {
1023 # Get a list of available locales.
1025 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1031 $lines = array_map( 'trim', explode( "\n", $lines ) );
1032 $candidatesByLocale = array();
1033 $candidatesByLang = array();
1035 foreach ( $lines as $line ) {
1036 if ( $line === '' ) {
1040 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1044 list( , $lang, , , ) = $m;
1046 $candidatesByLocale[$m[0]] = $m;
1047 $candidatesByLang[$lang][] = $m;
1050 # Try the current value of LANG.
1051 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1052 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1057 # Try the most common ones.
1058 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1059 foreach ( $commonLocales as $commonLocale ) {
1060 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1061 $this->setVar( 'wgShellLocale', $commonLocale );
1067 # Is there an available locale in the Wiki's language?
1068 $wikiLang = $this->getVar( 'wgLanguageCode' );
1070 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1071 $m = reset( $candidatesByLang[$wikiLang] );
1072 $this->setVar( 'wgShellLocale', $m[0] );
1077 # Are there any at all?
1078 if ( count( $candidatesByLocale ) ) {
1079 $m = reset( $candidatesByLocale );
1080 $this->setVar( 'wgShellLocale', $m[0] );
1090 * Environment check for the permissions of the uploads directory
1093 protected function envCheckUploadsDirectory() {
1096 $dir = $IP . '/images/';
1097 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1098 $safe = !$this->dirIsExecutable( $dir, $url );
1101 $this->showMessage( 'config-uploads-not-safe', $dir );
1108 * Checks if suhosin.get.max_value_length is set, and if so generate
1109 * a warning because it decreases ResourceLoader performance.
1112 protected function envCheckSuhosinMaxValueLength() {
1113 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1114 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1115 // Only warn if the value is below the sane 1024
1116 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1123 * Convert a hex string representing a Unicode code point to that code point.
1127 protected function unicodeChar( $c ) {
1131 } elseif ( $c <= 0x7FF ) {
1132 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1133 } elseif ( $c <= 0xFFFF ) {
1134 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F ) .
1135 chr( 0x80 |
$c & 0x3F );
1136 } elseif ( $c <= 0x10FFFF ) {
1137 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F ) .
1138 chr( 0x80 |
$c >> 6 & 0x3F ) .
1139 chr( 0x80 |
$c & 0x3F );
1146 * Check the libicu version
1148 protected function envCheckLibicu() {
1150 * This needs to be updated something that the latest libicu
1151 * will properly normalize. This normalization was found at
1152 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1153 * Note that we use the hex representation to create the code
1154 * points in order to avoid any Unicode-destroying during transit.
1156 $not_normal_c = $this->unicodeChar( "FA6C" );
1157 $normal_c = $this->unicodeChar( "242EE" );
1159 $useNormalizer = 'php';
1160 $needsUpdate = false;
1162 if ( function_exists( 'normalizer_normalize' ) ) {
1163 $useNormalizer = 'intl';
1164 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1165 if ( $intl !== $normal_c ) {
1166 $needsUpdate = true;
1170 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1171 if ( $useNormalizer === 'php' ) {
1172 $this->showMessage( 'config-unicode-pure-php-warning' );
1174 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1175 if ( $needsUpdate ) {
1176 $this->showMessage( 'config-unicode-update-warning' );
1184 protected function envCheckCtype() {
1185 if ( !function_exists( 'ctype_digit' ) ) {
1186 $this->showError( 'config-ctype' );
1197 protected function envCheckIconv() {
1198 if ( !function_exists( 'iconv' ) ) {
1199 $this->showError( 'config-iconv' );
1210 protected function envCheckJSON() {
1211 if ( !function_exists( 'json_decode' ) ) {
1212 $this->showError( 'config-json' );
1221 * Environment prep for the server hostname.
1223 protected function envPrepServer() {
1224 $server = $this->envGetDefaultServer();
1225 if ( $server !== null ) {
1226 $this->setVar( 'wgServer', $server );
1231 * Helper function to be called from envPrepServer()
1234 abstract protected function envGetDefaultServer();
1237 * Environment prep for setting $IP and $wgScriptPath.
1239 protected function envPrepPath() {
1241 $IP = dirname( dirname( __DIR__
) );
1242 $this->setVar( 'IP', $IP );
1246 * Get an array of likely places we can find executables. Check a bunch
1247 * of known Unix-like defaults, as well as the PATH environment variable
1248 * (which should maybe make it work for Windows?)
1252 protected static function getPossibleBinPaths() {
1254 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1255 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1256 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1261 * Search a path for any of the given executable names. Returns the
1262 * executable name if found. Also checks the version string returned
1263 * by each executable.
1265 * Used only by environment checks.
1267 * @param string $path Path to search
1268 * @param array $names Array of executable names
1269 * @param array|bool $versionInfo False or array with two members:
1270 * 0 => Command to run for version check, with $1 for the full executable name
1271 * 1 => String to compare the output with
1273 * If $versionInfo is not false, only executables with a version
1274 * matching $versionInfo[1] will be returned.
1275 * @return bool|string
1277 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1278 if ( !is_array( $names ) ) {
1279 $names = array( $names );
1282 foreach ( $names as $name ) {
1283 $command = $path . DIRECTORY_SEPARATOR
. $name;
1285 MediaWiki\
suppressWarnings();
1286 $file_exists = file_exists( $command );
1287 MediaWiki\restoreWarnings
();
1289 if ( $file_exists ) {
1290 if ( !$versionInfo ) {
1294 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1295 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1305 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1306 * @see locateExecutable()
1307 * @param array $names Array of possible names.
1308 * @param array|bool $versionInfo Default: false or array with two members:
1309 * 0 => Command to run for version check, with $1 for the full executable name
1310 * 1 => String to compare the output with
1312 * If $versionInfo is not false, only executables with a version
1313 * matching $versionInfo[1] will be returned.
1314 * @return bool|string
1316 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1317 foreach ( self
::getPossibleBinPaths() as $path ) {
1318 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1319 if ( $exe !== false ) {
1328 * Checks if scripts located in the given directory can be executed via the given URL.
1330 * Used only by environment checks.
1331 * @param string $dir
1332 * @param string $url
1333 * @return bool|int|string
1335 public function dirIsExecutable( $dir, $url ) {
1336 $scriptTypes = array(
1338 "<?php echo 'ex' . 'ec';",
1339 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1343 // it would be good to check other popular languages here, but it'll be slow.
1345 MediaWiki\
suppressWarnings();
1347 foreach ( $scriptTypes as $ext => $contents ) {
1348 foreach ( $contents as $source ) {
1349 $file = 'exectest.' . $ext;
1351 if ( !file_put_contents( $dir . $file, $source ) ) {
1356 $text = Http
::get( $url . $file, array( 'timeout' => 3 ), __METHOD__
);
1357 } catch ( Exception
$e ) {
1358 // Http::get throws with allow_url_fopen = false and no curl extension.
1361 unlink( $dir . $file );
1363 if ( $text == 'exec' ) {
1364 MediaWiki\restoreWarnings
();
1371 MediaWiki\restoreWarnings
();
1377 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1379 * @param string $moduleName Name of module to check.
1382 public static function apacheModulePresent( $moduleName ) {
1383 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1386 // try it the hard way
1388 phpinfo( INFO_MODULES
);
1389 $info = ob_get_clean();
1391 return strpos( $info, $moduleName ) !== false;
1395 * ParserOptions are constructed before we determined the language, so fix it
1397 * @param Language $lang
1399 public function setParserLanguage( $lang ) {
1400 $this->parserOptions
->setTargetLanguage( $lang );
1401 $this->parserOptions
->setUserLang( $lang );
1405 * Overridden by WebInstaller to provide lastPage parameters.
1406 * @param string $page
1409 protected function getDocUrl( $page ) {
1410 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1414 * Finds extensions that follow the format /$directory/Name/Name.php,
1415 * and returns an array containing the value for 'Name' for each found extension.
1417 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1419 * @param string $directory Directory to search in
1422 public function findExtensions( $directory = 'extensions' ) {
1423 if ( $this->getVar( 'IP' ) === null ) {
1427 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1428 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1432 // extensions -> extension.json, skins -> skin.json
1433 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1435 $dh = opendir( $extDir );
1437 while ( ( $file = readdir( $dh ) ) !== false ) {
1438 if ( !is_dir( "$extDir/$file" ) ) {
1441 if ( file_exists( "$extDir/$file/$jsonFile" ) ||
file_exists( "$extDir/$file/$file.php" ) ) {
1446 natcasesort( $exts );
1452 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1453 * but will fall back to another if the default skin is missing and some other one is present
1456 * @param string[] $skinNames Names of installed skins.
1459 public function getDefaultSkin( array $skinNames ) {
1460 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1461 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1462 return $defaultSkin;
1464 return $skinNames[0];
1469 * Installs the auto-detected extensions.
1473 protected function includeExtensions() {
1475 $exts = $this->getVar( '_Extensions' );
1476 $IP = $this->getVar( 'IP' );
1479 * We need to include DefaultSettings before including extensions to avoid
1480 * warnings about unset variables. However, the only thing we really
1481 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1482 * if the extension has hidden hook registration in $wgExtensionFunctions,
1483 * but we're not opening that can of worms
1484 * @see https://phabricator.wikimedia.org/T28857
1486 global $wgAutoloadClasses;
1487 $wgAutoloadClasses = array();
1490 require "$IP/includes/DefaultSettings.php";
1492 foreach ( $exts as $e ) {
1493 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1494 $queue["$IP/extensions/$e/extension.json"] = 1;
1496 require_once "$IP/extensions/$e/$e.php";
1500 $registry = new ExtensionRegistry();
1501 $data = $registry->readFromQueue( $queue );
1502 $wgAutoloadClasses +
= $data['autoload'];
1504 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1505 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1507 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1508 $hooksWeWant = array_merge_recursive(
1510 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1513 // Unset everyone else's hooks. Lord knows what someone might be doing
1514 // in ParserFirstCallInit (see bug 27171)
1515 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1517 return Status
::newGood();
1521 * Get an array of install steps. Should always be in the format of
1523 * 'name' => 'someuniquename',
1524 * 'callback' => array( $obj, 'method' ),
1526 * There must be a config-install-$name message defined per step, which will
1527 * be shown on install.
1529 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1532 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1533 $coreInstallSteps = array(
1534 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1535 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1536 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1537 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1538 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1539 array( 'name' => 'updates', 'callback' => array( $installer, 'insertUpdateKeys' ) ),
1540 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1541 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1544 // Build the array of install steps starting from the core install list,
1545 // then adding any callbacks that wanted to attach after a given step
1546 foreach ( $coreInstallSteps as $step ) {
1547 $this->installSteps
[] = $step;
1548 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1549 $this->installSteps
= array_merge(
1550 $this->installSteps
,
1551 $this->extraInstallSteps
[$step['name']]
1556 // Prepend any steps that want to be at the beginning
1557 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1558 $this->installSteps
= array_merge(
1559 $this->extraInstallSteps
['BEGINNING'],
1564 // Extensions should always go first, chance to tie into hooks and such
1565 if ( count( $this->getVar( '_Extensions' ) ) ) {
1566 array_unshift( $this->installSteps
,
1567 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1569 $this->installSteps
[] = array(
1570 'name' => 'extension-tables',
1571 'callback' => array( $installer, 'createExtensionTables' )
1575 return $this->installSteps
;
1579 * Actually perform the installation.
1581 * @param callable $startCB A callback array for the beginning of each step
1582 * @param callable $endCB A callback array for the end of each step
1584 * @return array Array of Status objects
1586 public function performInstallation( $startCB, $endCB ) {
1587 $installResults = array();
1588 $installer = $this->getDBInstaller();
1589 $installer->preInstall();
1590 $steps = $this->getInstallSteps( $installer );
1591 foreach ( $steps as $stepObj ) {
1592 $name = $stepObj['name'];
1593 call_user_func_array( $startCB, array( $name ) );
1595 // Perform the callback step
1596 $status = call_user_func( $stepObj['callback'], $installer );
1598 // Output and save the results
1599 call_user_func( $endCB, $name, $status );
1600 $installResults[$name] = $status;
1602 // If we've hit some sort of fatal, we need to bail.
1603 // Callback already had a chance to do output above.
1604 if ( !$status->isOk() ) {
1608 if ( $status->isOk() ) {
1609 $this->setVar( '_InstallDone', true );
1612 return $installResults;
1616 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1620 public function generateKeys() {
1621 $keys = array( 'wgSecretKey' => 64 );
1622 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1623 $keys['wgUpgradeKey'] = 16;
1626 return $this->doGenerateKeys( $keys );
1630 * Generate a secret value for variables using our CryptRand generator.
1631 * Produce a warning if the random source was insecure.
1633 * @param array $keys
1636 protected function doGenerateKeys( $keys ) {
1637 $status = Status
::newGood();
1640 foreach ( $keys as $name => $length ) {
1641 $secretKey = MWCryptRand
::generateHex( $length, true );
1642 if ( !MWCryptRand
::wasStrong() ) {
1646 $this->setVar( $name, $secretKey );
1650 $names = array_keys( $keys );
1651 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1653 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1660 * Create the first user account, grant it sysop and bureaucrat rights
1664 protected function createSysop() {
1665 $name = $this->getVar( '_AdminName' );
1666 $user = User
::newFromName( $name );
1669 // We should've validated this earlier anyway!
1670 return Status
::newFatal( 'config-admin-error-user', $name );
1673 if ( $user->idForName() == 0 ) {
1674 $user->addToDatabase();
1677 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1678 } catch ( PasswordError
$pwe ) {
1679 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1682 $user->addGroup( 'sysop' );
1683 $user->addGroup( 'bureaucrat' );
1684 if ( $this->getVar( '_AdminEmail' ) ) {
1685 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1687 $user->saveSettings();
1689 // Update user count
1690 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1691 $ssUpdate->doUpdate();
1693 $status = Status
::newGood();
1695 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1696 $this->subscribeToMediaWikiAnnounce( $status );
1705 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1707 'email' => $this->getVar( '_AdminEmail' ),
1712 // Mailman doesn't support as many languages as we do, so check to make
1713 // sure their selected language is available
1714 $myLang = $this->getVar( '_UserLang' );
1715 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1716 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1717 $params['language'] = $myLang;
1720 if ( MWHttpRequest
::canMakeRequests() ) {
1721 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1722 array( 'method' => 'POST', 'postData' => $params ), __METHOD__
)->execute();
1723 if ( !$res->isOK() ) {
1724 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1727 $s->warning( 'config-install-subscribe-notpossible' );
1732 * Insert Main Page with default content.
1734 * @param DatabaseInstaller $installer
1737 protected function createMainpage( DatabaseInstaller
$installer ) {
1738 $status = Status
::newGood();
1740 $page = WikiPage
::factory( Title
::newMainPage() );
1741 $content = new WikitextContent(
1742 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1743 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1746 $page->doEditContent( $content,
1750 User
::newFromName( 'MediaWiki default' )
1752 } catch ( Exception
$e ) {
1753 // using raw, because $wgShowExceptionDetails can not be set yet
1754 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1761 * Override the necessary bits of the config to run an installation.
1763 public static function overrideConfig() {
1764 define( 'MW_NO_SESSION', 1 );
1766 // Don't access the database
1767 $GLOBALS['wgUseDatabaseMessages'] = false;
1768 // Don't cache langconv tables
1769 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1771 $GLOBALS['wgShowExceptionDetails'] = true;
1772 // Don't break forms
1773 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1775 // Extended debugging
1776 $GLOBALS['wgShowSQLErrors'] = true;
1777 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1779 // Allow multiple ob_flush() calls
1780 $GLOBALS['wgDisableOutputCompression'] = true;
1782 // Use a sensible cookie prefix (not my_wiki)
1783 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1785 // Some of the environment checks make shell requests, remove limits
1786 $GLOBALS['wgMaxShellMemory'] = 0;
1790 * Add an installation step following the given step.
1792 * @param callable $callback A valid installation callback array, in this form:
1793 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1794 * @param string $findStep The step to find. Omit to put the step at the beginning
1796 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1797 $this->extraInstallSteps
[$findStep][] = $callback;
1801 * Disable the time limit for execution.
1802 * Some long-running pages (Install, Upgrade) will want to do this
1804 protected function disableTimeLimit() {
1805 MediaWiki\
suppressWarnings();
1806 set_time_limit( 0 );
1807 MediaWiki\restoreWarnings
();