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(
171 'wgEmailAuthentication',
174 'wgImageMagickConvertCommand',
179 'wgDeletedDirectory',
183 'wgUseInstantCommons',
189 * Variables that are stored alongside globals, and are used for any
190 * configuration of the installation process aside from the MediaWiki
191 * configuration. Map of names to defaults.
195 protected $internalDefaults = array(
197 '_Environment' => false,
198 '_SafeMode' => false,
199 '_RaiseMemory' => false,
200 '_UpgradeDone' => false,
201 '_InstallDone' => false,
202 '_Caches' => array(),
203 '_InstallPassword' => '',
204 '_SameAccount' => true,
205 '_CreateDBAccount' => false,
206 '_NamespaceType' => 'site-name',
207 '_AdminName' => '', // will be set later, when the user selects language
208 '_AdminPassword' => '',
209 '_AdminPasswordConfirm' => '',
211 '_Subscribe' => false,
212 '_SkipOptional' => 'continue',
213 '_RightsProfile' => 'wiki',
214 '_LicenseCode' => 'none',
216 '_Extensions' => array(),
218 '_MemCachedServers' => '',
219 '_UpgradeKeySupplied' => false,
220 '_ExistingDBSettings' => false,
222 // $wgLogo is probably wrong (bug 48084); set something that will work.
223 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
224 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
228 * The actual list of installation steps. This will be initialized by getInstallSteps()
232 private $installSteps = array();
235 * Extra steps for installation, for things like DatabaseInstallers to modify
239 protected $extraInstallSteps = array();
242 * Known object cache types and the functions used to test for their existence.
246 protected $objectCaches = array(
247 'xcache' => 'xcache_get',
248 'apc' => 'apc_fetch',
249 'wincache' => 'wincache_ucache_get'
253 * User rights profiles.
257 public $rightsProfiles = array(
260 '*' => array( 'edit' => false )
264 'createaccount' => false,
270 'createaccount' => false,
282 public $licenses = array(
284 'url' => 'https://creativecommons.org/licenses/by/4.0/',
285 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
288 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
289 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
291 'cc-by-nc-sa' => array(
292 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
293 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
296 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
297 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
301 'icon' => '$wgResourceBasePath/resources/assets/licenses/public-domain.png',
304 'url' => 'https://www.gnu.org/copyleft/fdl.html',
305 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
312 'cc-choose' => array(
313 // Details will be filled in by the selector.
321 * URL to mediawiki-announce subscription
323 protected $mediaWikiAnnounceUrl =
324 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
327 * Supported language codes for Mailman
329 protected $mediaWikiAnnounceLanguages = array(
330 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
331 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
332 'sl', 'sr', 'sv', 'tr', 'uk'
336 * UI interface for displaying a short message
337 * The parameters are like parameters to wfMessage().
338 * The messages will be in wikitext format, which will be converted to an
339 * output format such as HTML or text before being sent to the user.
342 abstract public function showMessage( $msg /*, ... */ );
345 * Same as showMessage(), but for displaying errors
348 abstract public function showError( $msg /*, ... */ );
351 * Show a message to the installing user by using a Status object
352 * @param Status $status
354 abstract public function showStatusMessage( Status
$status );
357 * Constructor, always call this from child classes.
359 public function __construct() {
360 global $wgMessagesDirs, $wgUser;
362 // Disable the i18n cache
363 Language
::getLocalisationCache()->disableBackend();
364 // Disable LoadBalancer and wfGetDB etc.
365 LBFactory
::disableBackend();
367 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
368 // SqlBagOStuff will then throw since we just disabled wfGetDB)
369 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
370 ObjectCache
::clear();
371 $emptyCache = array( 'class' => 'EmptyBagOStuff' );
372 // disable (problematic) object cache types explicitly, preserving all other (working) ones
374 $GLOBALS['wgObjectCaches'] = array(
375 CACHE_NONE
=> $emptyCache,
376 CACHE_DB
=> $emptyCache,
377 CACHE_ANYTHING
=> $emptyCache,
378 CACHE_MEMCACHED
=> $emptyCache,
379 ) +
$GLOBALS['wgObjectCaches'];
381 // Load the installer's i18n.
382 $wgMessagesDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
384 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
385 $wgUser = User
::newFromId( 0 );
387 $this->settings
= $this->internalDefaults
;
389 foreach ( $this->defaultVarNames
as $var ) {
390 $this->settings
[$var] = $GLOBALS[$var];
393 $this->doEnvironmentPreps();
395 $this->compiledDBs
= array();
396 foreach ( self
::getDBTypes() as $type ) {
397 $installer = $this->getDBInstaller( $type );
399 if ( !$installer->isCompiled() ) {
402 $this->compiledDBs
[] = $type;
405 $this->parserTitle
= Title
::newFromText( 'Installer' );
406 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
407 $this->parserOptions
->setEditSection( false );
411 * Get a list of known DB types.
415 public static function getDBTypes() {
416 return self
::$dbTypes;
420 * Do initial checks of the PHP environment. Set variables according to
421 * the observed environment.
423 * It's possible that this may be called under the CLI SAPI, not the SAPI
424 * that the wiki will primarily run under. In that case, the subclass should
425 * initialise variables such as wgScriptPath, before calling this function.
427 * Under the web subclass, it can already be assumed that PHP 5+ is in use
428 * and that sessions are working.
432 public function doEnvironmentChecks() {
433 // Php version has already been checked by entry scripts
434 // Show message here for information purposes
436 $this->showMessage( 'config-env-hhvm', HHVM_VERSION
);
438 $this->showMessage( 'config-env-php', PHP_VERSION
);
442 // Must go here because an old version of PCRE can prevent other checks from completing
443 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
444 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
445 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
448 foreach ( $this->envChecks
as $check ) {
449 $status = $this->$check();
450 if ( $status === false ) {
456 $this->setVar( '_Environment', $good );
458 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
461 public function doEnvironmentPreps() {
462 foreach ( $this->envPreps
as $prep ) {
468 * Set a MW configuration variable, or internal installer configuration variable.
470 * @param string $name
471 * @param mixed $value
473 public function setVar( $name, $value ) {
474 $this->settings
[$name] = $value;
478 * Get an MW configuration variable, or internal installer configuration variable.
479 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
480 * Installer variables are typically prefixed by an underscore.
482 * @param string $name
483 * @param mixed $default
487 public function getVar( $name, $default = null ) {
488 if ( !isset( $this->settings
[$name] ) ) {
491 return $this->settings
[$name];
496 * Get a list of DBs supported by current PHP setup
500 public function getCompiledDBs() {
501 return $this->compiledDBs
;
505 * Get an instance of DatabaseInstaller for the specified DB type.
507 * @param mixed $type DB installer for which is needed, false to use default.
509 * @return DatabaseInstaller
511 public function getDBInstaller( $type = false ) {
513 $type = $this->getVar( 'wgDBtype' );
516 $type = strtolower( $type );
518 if ( !isset( $this->dbInstallers
[$type] ) ) {
519 $class = ucfirst( $type ) . 'Installer';
520 $this->dbInstallers
[$type] = new $class( $this );
523 return $this->dbInstallers
[$type];
527 * Determine if LocalSettings.php exists. If it does, return its variables.
531 public static function getExistingLocalSettings() {
534 // You might be wondering why this is here. Well if you don't do this
535 // then some poorly-formed extensions try to call their own classes
536 // after immediately registering them. We really need to get extension
537 // registration out of the global scope and into a real format.
538 // @see https://phabricator.wikimedia.org/T69440
539 global $wgAutoloadClasses;
540 $wgAutoloadClasses = array();
542 // @codingStandardsIgnoreStart
543 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
544 // Define the required globals here, to ensure, the functions can do it work correctly.
545 global $wgExtensionDirectory, $wgStyleDirectory;
546 // @codingStandardsIgnoreEnd
548 MediaWiki\
suppressWarnings();
549 $_lsExists = file_exists( "$IP/LocalSettings.php" );
550 MediaWiki\restoreWarnings
();
557 require "$IP/includes/DefaultSettings.php";
558 require "$IP/LocalSettings.php";
560 return get_defined_vars();
564 * Get a fake password for sending back to the user in HTML.
565 * This is a security mechanism to avoid compromise of the password in the
566 * event of session ID compromise.
568 * @param string $realPassword
572 public function getFakePassword( $realPassword ) {
573 return str_repeat( '*', strlen( $realPassword ) );
577 * Set a variable which stores a password, except if the new value is a
578 * fake password in which case leave it as it is.
580 * @param string $name
581 * @param mixed $value
583 public function setPassword( $name, $value ) {
584 if ( !preg_match( '/^\*+$/', $value ) ) {
585 $this->setVar( $name, $value );
590 * On POSIX systems return the primary group of the webserver we're running under.
591 * On other systems just returns null.
593 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
594 * webserver user before he can install.
596 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
600 public static function maybeGetWebserverPrimaryGroup() {
601 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
602 # I don't know this, this isn't UNIX.
606 # posix_getegid() *not* getmygid() because we want the group of the webserver,
607 # not whoever owns the current script.
608 $gid = posix_getegid();
609 $getpwuid = posix_getpwuid( $gid );
610 $group = $getpwuid['name'];
616 * Convert wikitext $text to HTML.
618 * This is potentially error prone since many parser features require a complete
619 * installed MW database. The solution is to just not use those features when you
620 * write your messages. This appears to work well enough. Basic formatting and
621 * external links work just fine.
623 * But in case a translator decides to throw in a "#ifexist" or internal link or
624 * whatever, this function is guarded to catch the attempted DB access and to present
625 * some fallback text.
627 * @param string $text
628 * @param bool $lineStart
631 public function parse( $text, $lineStart = false ) {
635 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
636 $html = $out->getText();
637 } catch ( DBAccessError
$e ) {
638 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
640 if ( !empty( $this->debug
) ) {
641 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
649 * @return ParserOptions
651 public function getParserOptions() {
652 return $this->parserOptions
;
655 public function disableLinkPopups() {
656 $this->parserOptions
->setExternalLinkTarget( false );
659 public function restoreLinkPopups() {
660 global $wgExternalLinkTarget;
661 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
665 * Install step which adds a row to the site_stats table with appropriate
668 * @param DatabaseInstaller $installer
672 public function populateSiteStats( DatabaseInstaller
$installer ) {
673 $status = $installer->getConnection();
674 if ( !$status->isOK() ) {
677 $status->value
->insert(
681 'ss_total_edits' => 0,
682 'ss_good_articles' => 0,
683 'ss_total_pages' => 0,
690 return Status
::newGood();
694 * Environment check for DB types.
697 protected function envCheckDB() {
702 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
703 // config-type-sqlite
704 foreach ( self
::getDBTypes() as $name ) {
705 $allNames[] = wfMessage( "config-type-$name" )->text();
708 $databases = $this->getCompiledDBs();
710 $databases = array_flip( $databases );
711 foreach ( array_keys( $databases ) as $db ) {
712 $installer = $this->getDBInstaller( $db );
713 $status = $installer->checkPrerequisites();
714 if ( !$status->isGood() ) {
715 $this->showStatusMessage( $status );
717 if ( !$status->isOK() ) {
718 unset( $databases[$db] );
721 $databases = array_flip( $databases );
723 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
725 // @todo FIXME: This only works for the web installer!
733 * Environment check for register_globals.
734 * Prevent installation if enabled
737 protected function envCheckRegisterGlobals() {
738 if ( wfIniGetBool( 'register_globals' ) ) {
739 $this->showMessage( 'config-register-globals-error' );
747 * Some versions of libxml+PHP break < and > encoding horribly
750 protected function envCheckBrokenXML() {
751 $test = new PhpXmlBugTester();
753 $this->showError( 'config-brokenlibxml' );
762 * Environment check for magic_quotes_(gpc|runtime|sybase).
765 protected function envCheckMagicQuotes() {
767 foreach ( array( 'gpc', 'runtime', 'sybase' ) as $magicJunk ) {
768 if ( wfIniGetBool( "magic_quotes_$magicJunk" ) ) {
769 $this->showError( "config-magic-quotes-$magicJunk" );
778 * Environment check for mbstring.func_overload.
781 protected function envCheckMbstring() {
782 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
783 $this->showError( 'config-mbstring' );
792 * Environment check for safe_mode.
795 protected function envCheckSafeMode() {
796 if ( wfIniGetBool( 'safe_mode' ) ) {
797 $this->setVar( '_SafeMode', true );
798 $this->showMessage( 'config-safe-mode' );
805 * Environment check for the XML module.
808 protected function envCheckXML() {
809 if ( !function_exists( "utf8_encode" ) ) {
810 $this->showError( 'config-xml-bad' );
819 * Environment check for the PCRE module.
821 * @note If this check were to fail, the parser would
822 * probably throw an exception before the result
823 * of this check is shown to the user.
826 protected function envCheckPCRE() {
827 MediaWiki\
suppressWarnings();
828 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
829 // Need to check for \p support too, as PCRE can be compiled
830 // with utf8 support, but not unicode property support.
831 // check that \p{Zs} (space separators) matches
832 // U+3000 (Ideographic space)
833 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
834 MediaWiki\restoreWarnings
();
835 if ( $regexd != '--' ||
$regexprop != '--' ) {
836 $this->showError( 'config-pcre-no-utf8' );
845 * Environment check for available memory.
848 protected function envCheckMemory() {
849 $limit = ini_get( 'memory_limit' );
851 if ( !$limit ||
$limit == -1 ) {
855 $n = wfShorthandToInteger( $limit );
857 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
858 $newLimit = "{$this->minMemorySize}M";
860 if ( ini_set( "memory_limit", $newLimit ) === false ) {
861 $this->showMessage( 'config-memory-bad', $limit );
863 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
864 $this->setVar( '_RaiseMemory', true );
872 * Environment check for compiled object cache types.
874 protected function envCheckCache() {
876 foreach ( $this->objectCaches
as $name => $function ) {
877 if ( function_exists( $function ) ) {
878 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
881 $caches[$name] = true;
886 $key = 'config-no-cache';
887 // PHP >=5.5 is called APCu, earlier versions use APC (T61998).
888 if ( !wfIsHHVM() && version_compare( PHP_VERSION
, '5.5', '>=' ) ) {
889 // config-no-cache-apcu
892 $this->showMessage( $key );
895 $this->setVar( '_Caches', $caches );
899 * Scare user to death if they have mod_security or mod_security2
902 protected function envCheckModSecurity() {
903 if ( self
::apacheModulePresent( 'mod_security' )
904 || self
::apacheModulePresent( 'mod_security2' ) ) {
905 $this->showMessage( 'config-mod-security' );
912 * Search for GNU diff3.
915 protected function envCheckDiff3() {
916 $names = array( "gdiff3", "diff3", "diff3.exe" );
917 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
919 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
922 $this->setVar( 'wgDiff3', $diff3 );
924 $this->setVar( 'wgDiff3', false );
925 $this->showMessage( 'config-diff3-bad' );
932 * Environment check for ImageMagick and GD.
935 protected function envCheckGraphics() {
936 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
937 $versionInfo = array( '$1 -version', 'ImageMagick' );
938 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
940 $this->setVar( 'wgImageMagickConvertCommand', '' );
942 $this->setVar( 'wgImageMagickConvertCommand', $convert );
943 $this->showMessage( 'config-imagemagick', $convert );
946 } elseif ( function_exists( 'imagejpeg' ) ) {
947 $this->showMessage( 'config-gd' );
949 $this->showMessage( 'config-no-scaling' );
961 protected function envCheckGit() {
962 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
963 $versionInfo = array( '$1 --version', 'git version' );
965 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
968 $this->setVar( 'wgGitBin', $git );
969 $this->showMessage( 'config-git', $git );
971 $this->setVar( 'wgGitBin', false );
972 $this->showMessage( 'config-git-bad' );
979 * Environment check to inform user which server we've assumed.
983 protected function envCheckServer() {
984 $server = $this->envGetDefaultServer();
985 if ( $server !== null ) {
986 $this->showMessage( 'config-using-server', $server );
992 * Environment check to inform user which paths we've assumed.
996 protected function envCheckPath() {
999 $this->getVar( 'wgServer' ),
1000 $this->getVar( 'wgScriptPath' )
1006 * Environment check for preferred locale in shell
1009 protected function envCheckShellLocale() {
1010 $os = php_uname( 's' );
1011 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1013 if ( !in_array( $os, $supported ) ) {
1017 # Get a list of available locales.
1019 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1025 $lines = array_map( 'trim', explode( "\n", $lines ) );
1026 $candidatesByLocale = array();
1027 $candidatesByLang = array();
1029 foreach ( $lines as $line ) {
1030 if ( $line === '' ) {
1034 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1038 list( , $lang, , , ) = $m;
1040 $candidatesByLocale[$m[0]] = $m;
1041 $candidatesByLang[$lang][] = $m;
1044 # Try the current value of LANG.
1045 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1046 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1051 # Try the most common ones.
1052 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1053 foreach ( $commonLocales as $commonLocale ) {
1054 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1055 $this->setVar( 'wgShellLocale', $commonLocale );
1061 # Is there an available locale in the Wiki's language?
1062 $wikiLang = $this->getVar( 'wgLanguageCode' );
1064 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1065 $m = reset( $candidatesByLang[$wikiLang] );
1066 $this->setVar( 'wgShellLocale', $m[0] );
1071 # Are there any at all?
1072 if ( count( $candidatesByLocale ) ) {
1073 $m = reset( $candidatesByLocale );
1074 $this->setVar( 'wgShellLocale', $m[0] );
1084 * Environment check for the permissions of the uploads directory
1087 protected function envCheckUploadsDirectory() {
1090 $dir = $IP . '/images/';
1091 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1092 $safe = !$this->dirIsExecutable( $dir, $url );
1095 $this->showMessage( 'config-uploads-not-safe', $dir );
1102 * Checks if suhosin.get.max_value_length is set, and if so generate
1103 * a warning because it decreases ResourceLoader performance.
1106 protected function envCheckSuhosinMaxValueLength() {
1107 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1108 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1109 // Only warn if the value is below the sane 1024
1110 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1117 * Convert a hex string representing a Unicode code point to that code point.
1121 protected function unicodeChar( $c ) {
1125 } elseif ( $c <= 0x7FF ) {
1126 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1127 } elseif ( $c <= 0xFFFF ) {
1128 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F ) .
1129 chr( 0x80 |
$c & 0x3F );
1130 } elseif ( $c <= 0x10FFFF ) {
1131 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F ) .
1132 chr( 0x80 |
$c >> 6 & 0x3F ) .
1133 chr( 0x80 |
$c & 0x3F );
1140 * Check the libicu version
1142 protected function envCheckLibicu() {
1144 * This needs to be updated something that the latest libicu
1145 * will properly normalize. This normalization was found at
1146 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1147 * Note that we use the hex representation to create the code
1148 * points in order to avoid any Unicode-destroying during transit.
1150 $not_normal_c = $this->unicodeChar( "FA6C" );
1151 $normal_c = $this->unicodeChar( "242EE" );
1153 $useNormalizer = 'php';
1154 $needsUpdate = false;
1156 if ( function_exists( 'normalizer_normalize' ) ) {
1157 $useNormalizer = 'intl';
1158 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1159 if ( $intl !== $normal_c ) {
1160 $needsUpdate = true;
1164 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1165 if ( $useNormalizer === 'php' ) {
1166 $this->showMessage( 'config-unicode-pure-php-warning' );
1168 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1169 if ( $needsUpdate ) {
1170 $this->showMessage( 'config-unicode-update-warning' );
1178 protected function envCheckCtype() {
1179 if ( !function_exists( 'ctype_digit' ) ) {
1180 $this->showError( 'config-ctype' );
1191 protected function envCheckIconv() {
1192 if ( !function_exists( 'iconv' ) ) {
1193 $this->showError( 'config-iconv' );
1204 protected function envCheckJSON() {
1205 if ( !function_exists( 'json_decode' ) ) {
1206 $this->showError( 'config-json' );
1215 * Environment prep for the server hostname.
1217 protected function envPrepServer() {
1218 $server = $this->envGetDefaultServer();
1219 if ( $server !== null ) {
1220 $this->setVar( 'wgServer', $server );
1225 * Helper function to be called from envPrepServer()
1228 abstract protected function envGetDefaultServer();
1231 * Environment prep for setting $IP and $wgScriptPath.
1233 protected function envPrepPath() {
1235 $IP = dirname( dirname( __DIR__
) );
1236 $this->setVar( 'IP', $IP );
1240 * Get an array of likely places we can find executables. Check a bunch
1241 * of known Unix-like defaults, as well as the PATH environment variable
1242 * (which should maybe make it work for Windows?)
1246 protected static function getPossibleBinPaths() {
1248 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1249 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1250 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1255 * Search a path for any of the given executable names. Returns the
1256 * executable name if found. Also checks the version string returned
1257 * by each executable.
1259 * Used only by environment checks.
1261 * @param string $path Path to search
1262 * @param array $names Array of executable names
1263 * @param array|bool $versionInfo False or array with two members:
1264 * 0 => Command to run for version check, with $1 for the full executable name
1265 * 1 => String to compare the output with
1267 * If $versionInfo is not false, only executables with a version
1268 * matching $versionInfo[1] will be returned.
1269 * @return bool|string
1271 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1272 if ( !is_array( $names ) ) {
1273 $names = array( $names );
1276 foreach ( $names as $name ) {
1277 $command = $path . DIRECTORY_SEPARATOR
. $name;
1279 MediaWiki\
suppressWarnings();
1280 $file_exists = file_exists( $command );
1281 MediaWiki\restoreWarnings
();
1283 if ( $file_exists ) {
1284 if ( !$versionInfo ) {
1288 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1289 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1299 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1300 * @see locateExecutable()
1301 * @param array $names Array of possible names.
1302 * @param array|bool $versionInfo Default: false or array with two members:
1303 * 0 => Command to run for version check, with $1 for the full executable name
1304 * 1 => String to compare the output with
1306 * If $versionInfo is not false, only executables with a version
1307 * matching $versionInfo[1] will be returned.
1308 * @return bool|string
1310 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1311 foreach ( self
::getPossibleBinPaths() as $path ) {
1312 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1313 if ( $exe !== false ) {
1322 * Checks if scripts located in the given directory can be executed via the given URL.
1324 * Used only by environment checks.
1325 * @param string $dir
1326 * @param string $url
1327 * @return bool|int|string
1329 public function dirIsExecutable( $dir, $url ) {
1330 $scriptTypes = array(
1332 "<?php echo 'ex' . 'ec';",
1333 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1337 // it would be good to check other popular languages here, but it'll be slow.
1339 MediaWiki\
suppressWarnings();
1341 foreach ( $scriptTypes as $ext => $contents ) {
1342 foreach ( $contents as $source ) {
1343 $file = 'exectest.' . $ext;
1345 if ( !file_put_contents( $dir . $file, $source ) ) {
1350 $text = Http
::get( $url . $file, array( 'timeout' => 3 ), __METHOD__
);
1351 } catch ( Exception
$e ) {
1352 // Http::get throws with allow_url_fopen = false and no curl extension.
1355 unlink( $dir . $file );
1357 if ( $text == 'exec' ) {
1358 MediaWiki\restoreWarnings
();
1365 MediaWiki\restoreWarnings
();
1371 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1373 * @param string $moduleName Name of module to check.
1376 public static function apacheModulePresent( $moduleName ) {
1377 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1380 // try it the hard way
1382 phpinfo( INFO_MODULES
);
1383 $info = ob_get_clean();
1385 return strpos( $info, $moduleName ) !== false;
1389 * ParserOptions are constructed before we determined the language, so fix it
1391 * @param Language $lang
1393 public function setParserLanguage( $lang ) {
1394 $this->parserOptions
->setTargetLanguage( $lang );
1395 $this->parserOptions
->setUserLang( $lang );
1399 * Overridden by WebInstaller to provide lastPage parameters.
1400 * @param string $page
1403 protected function getDocUrl( $page ) {
1404 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1408 * Finds extensions that follow the format /$directory/Name/Name.php,
1409 * and returns an array containing the value for 'Name' for each found extension.
1411 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1413 * @param string $directory Directory to search in
1416 public function findExtensions( $directory = 'extensions' ) {
1417 if ( $this->getVar( 'IP' ) === null ) {
1421 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1422 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1426 // extensions -> extension.json, skins -> skin.json
1427 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1429 $dh = opendir( $extDir );
1431 while ( ( $file = readdir( $dh ) ) !== false ) {
1432 if ( !is_dir( "$extDir/$file" ) ) {
1435 if ( file_exists( "$extDir/$file/$jsonFile" ) ||
file_exists( "$extDir/$file/$file.php" ) ) {
1440 natcasesort( $exts );
1446 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1447 * but will fall back to another if the default skin is missing and some other one is present
1450 * @param string[] $skinNames Names of installed skins.
1453 public function getDefaultSkin( array $skinNames ) {
1454 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1455 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1456 return $defaultSkin;
1458 return $skinNames[0];
1463 * Installs the auto-detected extensions.
1467 protected function includeExtensions() {
1469 $exts = $this->getVar( '_Extensions' );
1470 $IP = $this->getVar( 'IP' );
1473 * We need to include DefaultSettings before including extensions to avoid
1474 * warnings about unset variables. However, the only thing we really
1475 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1476 * if the extension has hidden hook registration in $wgExtensionFunctions,
1477 * but we're not opening that can of worms
1478 * @see https://phabricator.wikimedia.org/T28857
1480 global $wgAutoloadClasses;
1481 $wgAutoloadClasses = array();
1484 require "$IP/includes/DefaultSettings.php";
1486 foreach ( $exts as $e ) {
1487 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1488 $queue["$IP/extensions/$e/extension.json"] = 1;
1490 require_once "$IP/extensions/$e/$e.php";
1494 $registry = new ExtensionRegistry();
1495 $data = $registry->readFromQueue( $queue );
1496 $wgAutoloadClasses +
= $data['autoload'];
1498 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1499 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1501 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1502 $hooksWeWant = array_merge_recursive(
1504 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1507 // Unset everyone else's hooks. Lord knows what someone might be doing
1508 // in ParserFirstCallInit (see bug 27171)
1509 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1511 return Status
::newGood();
1515 * Get an array of install steps. Should always be in the format of
1517 * 'name' => 'someuniquename',
1518 * 'callback' => array( $obj, 'method' ),
1520 * There must be a config-install-$name message defined per step, which will
1521 * be shown on install.
1523 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1526 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1527 $coreInstallSteps = array(
1528 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1529 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1530 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1531 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1532 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1533 array( 'name' => 'updates', 'callback' => array( $installer, 'insertUpdateKeys' ) ),
1534 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1535 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1538 // Build the array of install steps starting from the core install list,
1539 // then adding any callbacks that wanted to attach after a given step
1540 foreach ( $coreInstallSteps as $step ) {
1541 $this->installSteps
[] = $step;
1542 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1543 $this->installSteps
= array_merge(
1544 $this->installSteps
,
1545 $this->extraInstallSteps
[$step['name']]
1550 // Prepend any steps that want to be at the beginning
1551 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1552 $this->installSteps
= array_merge(
1553 $this->extraInstallSteps
['BEGINNING'],
1558 // Extensions should always go first, chance to tie into hooks and such
1559 if ( count( $this->getVar( '_Extensions' ) ) ) {
1560 array_unshift( $this->installSteps
,
1561 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1563 $this->installSteps
[] = array(
1564 'name' => 'extension-tables',
1565 'callback' => array( $installer, 'createExtensionTables' )
1569 return $this->installSteps
;
1573 * Actually perform the installation.
1575 * @param callable $startCB A callback array for the beginning of each step
1576 * @param callable $endCB A callback array for the end of each step
1578 * @return array Array of Status objects
1580 public function performInstallation( $startCB, $endCB ) {
1581 $installResults = array();
1582 $installer = $this->getDBInstaller();
1583 $installer->preInstall();
1584 $steps = $this->getInstallSteps( $installer );
1585 foreach ( $steps as $stepObj ) {
1586 $name = $stepObj['name'];
1587 call_user_func_array( $startCB, array( $name ) );
1589 // Perform the callback step
1590 $status = call_user_func( $stepObj['callback'], $installer );
1592 // Output and save the results
1593 call_user_func( $endCB, $name, $status );
1594 $installResults[$name] = $status;
1596 // If we've hit some sort of fatal, we need to bail.
1597 // Callback already had a chance to do output above.
1598 if ( !$status->isOk() ) {
1602 if ( $status->isOk() ) {
1603 $this->setVar( '_InstallDone', true );
1606 return $installResults;
1610 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1614 public function generateKeys() {
1615 $keys = array( 'wgSecretKey' => 64 );
1616 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1617 $keys['wgUpgradeKey'] = 16;
1620 return $this->doGenerateKeys( $keys );
1624 * Generate a secret value for variables using our CryptRand generator.
1625 * Produce a warning if the random source was insecure.
1627 * @param array $keys
1630 protected function doGenerateKeys( $keys ) {
1631 $status = Status
::newGood();
1634 foreach ( $keys as $name => $length ) {
1635 $secretKey = MWCryptRand
::generateHex( $length, true );
1636 if ( !MWCryptRand
::wasStrong() ) {
1640 $this->setVar( $name, $secretKey );
1644 $names = array_keys( $keys );
1645 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1647 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1654 * Create the first user account, grant it sysop and bureaucrat rights
1658 protected function createSysop() {
1659 $name = $this->getVar( '_AdminName' );
1660 $user = User
::newFromName( $name );
1663 // We should've validated this earlier anyway!
1664 return Status
::newFatal( 'config-admin-error-user', $name );
1667 if ( $user->idForName() == 0 ) {
1668 $user->addToDatabase();
1671 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1672 } catch ( PasswordError
$pwe ) {
1673 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1676 $user->addGroup( 'sysop' );
1677 $user->addGroup( 'bureaucrat' );
1678 if ( $this->getVar( '_AdminEmail' ) ) {
1679 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1681 $user->saveSettings();
1683 // Update user count
1684 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1685 $ssUpdate->doUpdate();
1687 $status = Status
::newGood();
1689 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1690 $this->subscribeToMediaWikiAnnounce( $status );
1699 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1701 'email' => $this->getVar( '_AdminEmail' ),
1706 // Mailman doesn't support as many languages as we do, so check to make
1707 // sure their selected language is available
1708 $myLang = $this->getVar( '_UserLang' );
1709 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1710 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1711 $params['language'] = $myLang;
1714 if ( MWHttpRequest
::canMakeRequests() ) {
1715 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1716 array( 'method' => 'POST', 'postData' => $params ), __METHOD__
)->execute();
1717 if ( !$res->isOK() ) {
1718 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1721 $s->warning( 'config-install-subscribe-notpossible' );
1726 * Insert Main Page with default content.
1728 * @param DatabaseInstaller $installer
1731 protected function createMainpage( DatabaseInstaller
$installer ) {
1732 $status = Status
::newGood();
1734 $page = WikiPage
::factory( Title
::newMainPage() );
1735 $content = new WikitextContent(
1736 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1737 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1740 $page->doEditContent( $content,
1744 User
::newFromName( 'MediaWiki default' )
1746 } catch ( Exception
$e ) {
1747 // using raw, because $wgShowExceptionDetails can not be set yet
1748 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1755 * Override the necessary bits of the config to run an installation.
1757 public static function overrideConfig() {
1758 define( 'MW_NO_SESSION', 1 );
1760 // Don't access the database
1761 $GLOBALS['wgUseDatabaseMessages'] = false;
1762 // Don't cache langconv tables
1763 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1765 $GLOBALS['wgShowExceptionDetails'] = true;
1766 // Don't break forms
1767 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1769 // Extended debugging
1770 $GLOBALS['wgShowSQLErrors'] = true;
1771 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1773 // Allow multiple ob_flush() calls
1774 $GLOBALS['wgDisableOutputCompression'] = true;
1776 // Use a sensible cookie prefix (not my_wiki)
1777 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1779 // Some of the environment checks make shell requests, remove limits
1780 $GLOBALS['wgMaxShellMemory'] = 0;
1784 * Add an installation step following the given step.
1786 * @param callable $callback A valid installation callback array, in this form:
1787 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1788 * @param string $findStep The step to find. Omit to put the step at the beginning
1790 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1791 $this->extraInstallSteps
[$findStep][] = $callback;
1795 * Disable the time limit for execution.
1796 * Some long-running pages (Install, Upgrade) will want to do this
1798 protected function disableTimeLimit() {
1799 MediaWiki\
suppressWarnings();
1800 set_time_limit( 0 );
1801 MediaWiki\restoreWarnings
();