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',
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/4.0/',
286 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
289 'url' => 'https://creativecommons.org/licenses/by-sa/4.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/4.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 * Environment check for DB types.
698 protected function envCheckDB() {
703 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
704 // config-type-sqlite
705 foreach ( self
::getDBTypes() as $name ) {
706 $allNames[] = wfMessage( "config-type-$name" )->text();
709 $databases = $this->getCompiledDBs();
711 $databases = array_flip( $databases );
712 foreach ( array_keys( $databases ) as $db ) {
713 $installer = $this->getDBInstaller( $db );
714 $status = $installer->checkPrerequisites();
715 if ( !$status->isGood() ) {
716 $this->showStatusMessage( $status );
718 if ( !$status->isOK() ) {
719 unset( $databases[$db] );
722 $databases = array_flip( $databases );
724 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
726 // @todo FIXME: This only works for the web installer!
734 * Environment check for register_globals.
735 * Prevent installation if enabled
738 protected function envCheckRegisterGlobals() {
739 if ( wfIniGetBool( 'register_globals' ) ) {
740 $this->showMessage( 'config-register-globals-error' );
748 * Some versions of libxml+PHP break < and > encoding horribly
751 protected function envCheckBrokenXML() {
752 $test = new PhpXmlBugTester();
754 $this->showError( 'config-brokenlibxml' );
763 * Environment check for magic_quotes_(gpc|runtime|sybase).
766 protected function envCheckMagicQuotes() {
768 foreach ( array( 'gpc', 'runtime', 'sybase' ) as $magicJunk ) {
769 if ( wfIniGetBool( "magic_quotes_$magicJunk" ) ) {
770 $this->showError( "config-magic-quotes-$magicJunk" );
779 * Environment check for mbstring.func_overload.
782 protected function envCheckMbstring() {
783 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
784 $this->showError( 'config-mbstring' );
793 * Environment check for safe_mode.
796 protected function envCheckSafeMode() {
797 if ( wfIniGetBool( 'safe_mode' ) ) {
798 $this->setVar( '_SafeMode', true );
799 $this->showMessage( 'config-safe-mode' );
806 * Environment check for the XML module.
809 protected function envCheckXML() {
810 if ( !function_exists( "utf8_encode" ) ) {
811 $this->showError( 'config-xml-bad' );
820 * Environment check for the PCRE module.
822 * @note If this check were to fail, the parser would
823 * probably throw an exception before the result
824 * of this check is shown to the user.
827 protected function envCheckPCRE() {
828 MediaWiki\
suppressWarnings();
829 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
830 // Need to check for \p support too, as PCRE can be compiled
831 // with utf8 support, but not unicode property support.
832 // check that \p{Zs} (space separators) matches
833 // U+3000 (Ideographic space)
834 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
835 MediaWiki\restoreWarnings
();
836 if ( $regexd != '--' ||
$regexprop != '--' ) {
837 $this->showError( 'config-pcre-no-utf8' );
846 * Environment check for available memory.
849 protected function envCheckMemory() {
850 $limit = ini_get( 'memory_limit' );
852 if ( !$limit ||
$limit == -1 ) {
856 $n = wfShorthandToInteger( $limit );
858 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
859 $newLimit = "{$this->minMemorySize}M";
861 if ( ini_set( "memory_limit", $newLimit ) === false ) {
862 $this->showMessage( 'config-memory-bad', $limit );
864 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
865 $this->setVar( '_RaiseMemory', true );
873 * Environment check for compiled object cache types.
875 protected function envCheckCache() {
877 foreach ( $this->objectCaches
as $name => $function ) {
878 if ( function_exists( $function ) ) {
879 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
882 $caches[$name] = true;
887 $key = 'config-no-cache';
888 // PHP >=5.5 is called APCu, earlier versions use APC (T61998).
889 if ( !wfIsHHVM() && version_compare( PHP_VERSION
, '5.5', '>=' ) ) {
890 // config-no-cache-apcu
893 $this->showMessage( $key );
896 $this->setVar( '_Caches', $caches );
900 * Scare user to death if they have mod_security or mod_security2
903 protected function envCheckModSecurity() {
904 if ( self
::apacheModulePresent( 'mod_security' )
905 || self
::apacheModulePresent( 'mod_security2' ) ) {
906 $this->showMessage( 'config-mod-security' );
913 * Search for GNU diff3.
916 protected function envCheckDiff3() {
917 $names = array( "gdiff3", "diff3", "diff3.exe" );
918 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
920 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
923 $this->setVar( 'wgDiff3', $diff3 );
925 $this->setVar( 'wgDiff3', false );
926 $this->showMessage( 'config-diff3-bad' );
933 * Environment check for ImageMagick and GD.
936 protected function envCheckGraphics() {
937 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
938 $versionInfo = array( '$1 -version', 'ImageMagick' );
939 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
941 $this->setVar( 'wgImageMagickConvertCommand', '' );
943 $this->setVar( 'wgImageMagickConvertCommand', $convert );
944 $this->showMessage( 'config-imagemagick', $convert );
947 } elseif ( function_exists( 'imagejpeg' ) ) {
948 $this->showMessage( 'config-gd' );
950 $this->showMessage( 'config-no-scaling' );
962 protected function envCheckGit() {
963 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
964 $versionInfo = array( '$1 --version', 'git version' );
966 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
969 $this->setVar( 'wgGitBin', $git );
970 $this->showMessage( 'config-git', $git );
972 $this->setVar( 'wgGitBin', false );
973 $this->showMessage( 'config-git-bad' );
980 * Environment check to inform user which server we've assumed.
984 protected function envCheckServer() {
985 $server = $this->envGetDefaultServer();
986 if ( $server !== null ) {
987 $this->showMessage( 'config-using-server', $server );
993 * Environment check to inform user which paths we've assumed.
997 protected function envCheckPath() {
1000 $this->getVar( 'wgServer' ),
1001 $this->getVar( 'wgScriptPath' )
1007 * Environment check for preferred locale in shell
1010 protected function envCheckShellLocale() {
1011 $os = php_uname( 's' );
1012 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1014 if ( !in_array( $os, $supported ) ) {
1018 # Get a list of available locales.
1020 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1026 $lines = array_map( 'trim', explode( "\n", $lines ) );
1027 $candidatesByLocale = array();
1028 $candidatesByLang = array();
1030 foreach ( $lines as $line ) {
1031 if ( $line === '' ) {
1035 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1039 list( , $lang, , , ) = $m;
1041 $candidatesByLocale[$m[0]] = $m;
1042 $candidatesByLang[$lang][] = $m;
1045 # Try the current value of LANG.
1046 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1047 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1052 # Try the most common ones.
1053 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1054 foreach ( $commonLocales as $commonLocale ) {
1055 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1056 $this->setVar( 'wgShellLocale', $commonLocale );
1062 # Is there an available locale in the Wiki's language?
1063 $wikiLang = $this->getVar( 'wgLanguageCode' );
1065 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1066 $m = reset( $candidatesByLang[$wikiLang] );
1067 $this->setVar( 'wgShellLocale', $m[0] );
1072 # Are there any at all?
1073 if ( count( $candidatesByLocale ) ) {
1074 $m = reset( $candidatesByLocale );
1075 $this->setVar( 'wgShellLocale', $m[0] );
1085 * Environment check for the permissions of the uploads directory
1088 protected function envCheckUploadsDirectory() {
1091 $dir = $IP . '/images/';
1092 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1093 $safe = !$this->dirIsExecutable( $dir, $url );
1096 $this->showMessage( 'config-uploads-not-safe', $dir );
1103 * Checks if suhosin.get.max_value_length is set, and if so generate
1104 * a warning because it decreases ResourceLoader performance.
1107 protected function envCheckSuhosinMaxValueLength() {
1108 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1109 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1110 // Only warn if the value is below the sane 1024
1111 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1118 * Convert a hex string representing a Unicode code point to that code point.
1122 protected function unicodeChar( $c ) {
1126 } elseif ( $c <= 0x7FF ) {
1127 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1128 } elseif ( $c <= 0xFFFF ) {
1129 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F ) .
1130 chr( 0x80 |
$c & 0x3F );
1131 } elseif ( $c <= 0x10FFFF ) {
1132 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F ) .
1133 chr( 0x80 |
$c >> 6 & 0x3F ) .
1134 chr( 0x80 |
$c & 0x3F );
1141 * Check the libicu version
1143 protected function envCheckLibicu() {
1145 * This needs to be updated something that the latest libicu
1146 * will properly normalize. This normalization was found at
1147 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1148 * Note that we use the hex representation to create the code
1149 * points in order to avoid any Unicode-destroying during transit.
1151 $not_normal_c = $this->unicodeChar( "FA6C" );
1152 $normal_c = $this->unicodeChar( "242EE" );
1154 $useNormalizer = 'php';
1155 $needsUpdate = false;
1157 if ( function_exists( 'normalizer_normalize' ) ) {
1158 $useNormalizer = 'intl';
1159 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1160 if ( $intl !== $normal_c ) {
1161 $needsUpdate = true;
1165 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1166 if ( $useNormalizer === 'php' ) {
1167 $this->showMessage( 'config-unicode-pure-php-warning' );
1169 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1170 if ( $needsUpdate ) {
1171 $this->showMessage( 'config-unicode-update-warning' );
1179 protected function envCheckCtype() {
1180 if ( !function_exists( 'ctype_digit' ) ) {
1181 $this->showError( 'config-ctype' );
1192 protected function envCheckIconv() {
1193 if ( !function_exists( 'iconv' ) ) {
1194 $this->showError( 'config-iconv' );
1205 protected function envCheckJSON() {
1206 if ( !function_exists( 'json_decode' ) ) {
1207 $this->showError( 'config-json' );
1216 * Environment prep for the server hostname.
1218 protected function envPrepServer() {
1219 $server = $this->envGetDefaultServer();
1220 if ( $server !== null ) {
1221 $this->setVar( 'wgServer', $server );
1226 * Helper function to be called from envPrepServer()
1229 abstract protected function envGetDefaultServer();
1232 * Environment prep for setting $IP and $wgScriptPath.
1234 protected function envPrepPath() {
1236 $IP = dirname( dirname( __DIR__
) );
1237 $this->setVar( 'IP', $IP );
1241 * Get an array of likely places we can find executables. Check a bunch
1242 * of known Unix-like defaults, as well as the PATH environment variable
1243 * (which should maybe make it work for Windows?)
1247 protected static function getPossibleBinPaths() {
1249 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1250 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1251 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1256 * Search a path for any of the given executable names. Returns the
1257 * executable name if found. Also checks the version string returned
1258 * by each executable.
1260 * Used only by environment checks.
1262 * @param string $path Path to search
1263 * @param array $names Array of executable names
1264 * @param array|bool $versionInfo False or array with two members:
1265 * 0 => Command to run for version check, with $1 for the full executable name
1266 * 1 => String to compare the output with
1268 * If $versionInfo is not false, only executables with a version
1269 * matching $versionInfo[1] will be returned.
1270 * @return bool|string
1272 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1273 if ( !is_array( $names ) ) {
1274 $names = array( $names );
1277 foreach ( $names as $name ) {
1278 $command = $path . DIRECTORY_SEPARATOR
. $name;
1280 MediaWiki\
suppressWarnings();
1281 $file_exists = file_exists( $command );
1282 MediaWiki\restoreWarnings
();
1284 if ( $file_exists ) {
1285 if ( !$versionInfo ) {
1289 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1290 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1300 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1301 * @see locateExecutable()
1302 * @param array $names Array of possible names.
1303 * @param array|bool $versionInfo Default: false or array with two members:
1304 * 0 => Command to run for version check, with $1 for the full executable name
1305 * 1 => String to compare the output with
1307 * If $versionInfo is not false, only executables with a version
1308 * matching $versionInfo[1] will be returned.
1309 * @return bool|string
1311 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1312 foreach ( self
::getPossibleBinPaths() as $path ) {
1313 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1314 if ( $exe !== false ) {
1323 * Checks if scripts located in the given directory can be executed via the given URL.
1325 * Used only by environment checks.
1326 * @param string $dir
1327 * @param string $url
1328 * @return bool|int|string
1330 public function dirIsExecutable( $dir, $url ) {
1331 $scriptTypes = array(
1333 "<?php echo 'ex' . 'ec';",
1334 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1338 // it would be good to check other popular languages here, but it'll be slow.
1340 MediaWiki\
suppressWarnings();
1342 foreach ( $scriptTypes as $ext => $contents ) {
1343 foreach ( $contents as $source ) {
1344 $file = 'exectest.' . $ext;
1346 if ( !file_put_contents( $dir . $file, $source ) ) {
1351 $text = Http
::get( $url . $file, array( 'timeout' => 3 ), __METHOD__
);
1352 } catch ( Exception
$e ) {
1353 // Http::get throws with allow_url_fopen = false and no curl extension.
1356 unlink( $dir . $file );
1358 if ( $text == 'exec' ) {
1359 MediaWiki\restoreWarnings
();
1366 MediaWiki\restoreWarnings
();
1372 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1374 * @param string $moduleName Name of module to check.
1377 public static function apacheModulePresent( $moduleName ) {
1378 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1381 // try it the hard way
1383 phpinfo( INFO_MODULES
);
1384 $info = ob_get_clean();
1386 return strpos( $info, $moduleName ) !== false;
1390 * ParserOptions are constructed before we determined the language, so fix it
1392 * @param Language $lang
1394 public function setParserLanguage( $lang ) {
1395 $this->parserOptions
->setTargetLanguage( $lang );
1396 $this->parserOptions
->setUserLang( $lang );
1400 * Overridden by WebInstaller to provide lastPage parameters.
1401 * @param string $page
1404 protected function getDocUrl( $page ) {
1405 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1409 * Finds extensions that follow the format /$directory/Name/Name.php,
1410 * and returns an array containing the value for 'Name' for each found extension.
1412 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1414 * @param string $directory Directory to search in
1417 public function findExtensions( $directory = 'extensions' ) {
1418 if ( $this->getVar( 'IP' ) === null ) {
1422 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1423 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1427 // extensions -> extension.json, skins -> skin.json
1428 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1430 $dh = opendir( $extDir );
1432 while ( ( $file = readdir( $dh ) ) !== false ) {
1433 if ( !is_dir( "$extDir/$file" ) ) {
1436 if ( file_exists( "$extDir/$file/$jsonFile" ) ||
file_exists( "$extDir/$file/$file.php" ) ) {
1441 natcasesort( $exts );
1447 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1448 * but will fall back to another if the default skin is missing and some other one is present
1451 * @param string[] $skinNames Names of installed skins.
1454 public function getDefaultSkin( array $skinNames ) {
1455 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1456 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1457 return $defaultSkin;
1459 return $skinNames[0];
1464 * Installs the auto-detected extensions.
1468 protected function includeExtensions() {
1470 $exts = $this->getVar( '_Extensions' );
1471 $IP = $this->getVar( 'IP' );
1474 * We need to include DefaultSettings before including extensions to avoid
1475 * warnings about unset variables. However, the only thing we really
1476 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1477 * if the extension has hidden hook registration in $wgExtensionFunctions,
1478 * but we're not opening that can of worms
1479 * @see https://phabricator.wikimedia.org/T28857
1481 global $wgAutoloadClasses;
1482 $wgAutoloadClasses = array();
1485 require "$IP/includes/DefaultSettings.php";
1487 foreach ( $exts as $e ) {
1488 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1489 $queue["$IP/extensions/$e/extension.json"] = 1;
1491 require_once "$IP/extensions/$e/$e.php";
1495 $registry = new ExtensionRegistry();
1496 $data = $registry->readFromQueue( $queue );
1497 $wgAutoloadClasses +
= $data['autoload'];
1499 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1500 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1502 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1503 $hooksWeWant = array_merge_recursive(
1505 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1508 // Unset everyone else's hooks. Lord knows what someone might be doing
1509 // in ParserFirstCallInit (see bug 27171)
1510 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1512 return Status
::newGood();
1516 * Get an array of install steps. Should always be in the format of
1518 * 'name' => 'someuniquename',
1519 * 'callback' => array( $obj, 'method' ),
1521 * There must be a config-install-$name message defined per step, which will
1522 * be shown on install.
1524 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1527 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1528 $coreInstallSteps = array(
1529 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1530 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1531 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1532 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1533 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1534 array( 'name' => 'updates', 'callback' => array( $installer, 'insertUpdateKeys' ) ),
1535 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1536 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1539 // Build the array of install steps starting from the core install list,
1540 // then adding any callbacks that wanted to attach after a given step
1541 foreach ( $coreInstallSteps as $step ) {
1542 $this->installSteps
[] = $step;
1543 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1544 $this->installSteps
= array_merge(
1545 $this->installSteps
,
1546 $this->extraInstallSteps
[$step['name']]
1551 // Prepend any steps that want to be at the beginning
1552 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1553 $this->installSteps
= array_merge(
1554 $this->extraInstallSteps
['BEGINNING'],
1559 // Extensions should always go first, chance to tie into hooks and such
1560 if ( count( $this->getVar( '_Extensions' ) ) ) {
1561 array_unshift( $this->installSteps
,
1562 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1564 $this->installSteps
[] = array(
1565 'name' => 'extension-tables',
1566 'callback' => array( $installer, 'createExtensionTables' )
1570 return $this->installSteps
;
1574 * Actually perform the installation.
1576 * @param callable $startCB A callback array for the beginning of each step
1577 * @param callable $endCB A callback array for the end of each step
1579 * @return array Array of Status objects
1581 public function performInstallation( $startCB, $endCB ) {
1582 $installResults = array();
1583 $installer = $this->getDBInstaller();
1584 $installer->preInstall();
1585 $steps = $this->getInstallSteps( $installer );
1586 foreach ( $steps as $stepObj ) {
1587 $name = $stepObj['name'];
1588 call_user_func_array( $startCB, array( $name ) );
1590 // Perform the callback step
1591 $status = call_user_func( $stepObj['callback'], $installer );
1593 // Output and save the results
1594 call_user_func( $endCB, $name, $status );
1595 $installResults[$name] = $status;
1597 // If we've hit some sort of fatal, we need to bail.
1598 // Callback already had a chance to do output above.
1599 if ( !$status->isOk() ) {
1603 if ( $status->isOk() ) {
1604 $this->setVar( '_InstallDone', true );
1607 return $installResults;
1611 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1615 public function generateKeys() {
1616 $keys = array( 'wgSecretKey' => 64 );
1617 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1618 $keys['wgUpgradeKey'] = 16;
1621 return $this->doGenerateKeys( $keys );
1625 * Generate a secret value for variables using our CryptRand generator.
1626 * Produce a warning if the random source was insecure.
1628 * @param array $keys
1631 protected function doGenerateKeys( $keys ) {
1632 $status = Status
::newGood();
1635 foreach ( $keys as $name => $length ) {
1636 $secretKey = MWCryptRand
::generateHex( $length, true );
1637 if ( !MWCryptRand
::wasStrong() ) {
1641 $this->setVar( $name, $secretKey );
1645 $names = array_keys( $keys );
1646 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1648 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1655 * Create the first user account, grant it sysop and bureaucrat rights
1659 protected function createSysop() {
1660 $name = $this->getVar( '_AdminName' );
1661 $user = User
::newFromName( $name );
1664 // We should've validated this earlier anyway!
1665 return Status
::newFatal( 'config-admin-error-user', $name );
1668 if ( $user->idForName() == 0 ) {
1669 $user->addToDatabase();
1672 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1673 } catch ( PasswordError
$pwe ) {
1674 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1677 $user->addGroup( 'sysop' );
1678 $user->addGroup( 'bureaucrat' );
1679 if ( $this->getVar( '_AdminEmail' ) ) {
1680 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1682 $user->saveSettings();
1684 // Update user count
1685 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1686 $ssUpdate->doUpdate();
1688 $status = Status
::newGood();
1690 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1691 $this->subscribeToMediaWikiAnnounce( $status );
1700 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1702 'email' => $this->getVar( '_AdminEmail' ),
1707 // Mailman doesn't support as many languages as we do, so check to make
1708 // sure their selected language is available
1709 $myLang = $this->getVar( '_UserLang' );
1710 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1711 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1712 $params['language'] = $myLang;
1715 if ( MWHttpRequest
::canMakeRequests() ) {
1716 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1717 array( 'method' => 'POST', 'postData' => $params ), __METHOD__
)->execute();
1718 if ( !$res->isOK() ) {
1719 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1722 $s->warning( 'config-install-subscribe-notpossible' );
1727 * Insert Main Page with default content.
1729 * @param DatabaseInstaller $installer
1732 protected function createMainpage( DatabaseInstaller
$installer ) {
1733 $status = Status
::newGood();
1735 $page = WikiPage
::factory( Title
::newMainPage() );
1736 $content = new WikitextContent(
1737 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1738 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1741 $page->doEditContent( $content,
1745 User
::newFromName( 'MediaWiki default' )
1747 } catch ( Exception
$e ) {
1748 // using raw, because $wgShowExceptionDetails can not be set yet
1749 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1756 * Override the necessary bits of the config to run an installation.
1758 public static function overrideConfig() {
1759 define( 'MW_NO_SESSION', 1 );
1761 // Don't access the database
1762 $GLOBALS['wgUseDatabaseMessages'] = false;
1763 // Don't cache langconv tables
1764 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1766 $GLOBALS['wgShowExceptionDetails'] = true;
1767 // Don't break forms
1768 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1770 // Extended debugging
1771 $GLOBALS['wgShowSQLErrors'] = true;
1772 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1774 // Allow multiple ob_flush() calls
1775 $GLOBALS['wgDisableOutputCompression'] = true;
1777 // Use a sensible cookie prefix (not my_wiki)
1778 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1780 // Some of the environment checks make shell requests, remove limits
1781 $GLOBALS['wgMaxShellMemory'] = 0;
1785 * Add an installation step following the given step.
1787 * @param callable $callback A valid installation callback array, in this form:
1788 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1789 * @param string $findStep The step to find. Omit to put the step at the beginning
1791 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1792 $this->extraInstallSteps
[$findStep][] = $callback;
1796 * Disable the time limit for execution.
1797 * Some long-running pages (Install, Upgrade) will want to do this
1799 protected function disableTimeLimit() {
1800 MediaWiki\
suppressWarnings();
1801 set_time_limit( 0 );
1802 MediaWiki\restoreWarnings
();