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 * 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 $this->showMessage( 'config-no-cache' );
890 $this->setVar( '_Caches', $caches );
894 * Scare user to death if they have mod_security or mod_security2
897 protected function envCheckModSecurity() {
898 if ( self
::apacheModulePresent( 'mod_security' )
899 || self
::apacheModulePresent( 'mod_security2' ) ) {
900 $this->showMessage( 'config-mod-security' );
907 * Search for GNU diff3.
910 protected function envCheckDiff3() {
911 $names = array( "gdiff3", "diff3", "diff3.exe" );
912 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
914 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
917 $this->setVar( 'wgDiff3', $diff3 );
919 $this->setVar( 'wgDiff3', false );
920 $this->showMessage( 'config-diff3-bad' );
927 * Environment check for ImageMagick and GD.
930 protected function envCheckGraphics() {
931 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
932 $versionInfo = array( '$1 -version', 'ImageMagick' );
933 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
935 $this->setVar( 'wgImageMagickConvertCommand', '' );
937 $this->setVar( 'wgImageMagickConvertCommand', $convert );
938 $this->showMessage( 'config-imagemagick', $convert );
941 } elseif ( function_exists( 'imagejpeg' ) ) {
942 $this->showMessage( 'config-gd' );
944 $this->showMessage( 'config-no-scaling' );
956 protected function envCheckGit() {
957 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
958 $versionInfo = array( '$1 --version', 'git version' );
960 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
963 $this->setVar( 'wgGitBin', $git );
964 $this->showMessage( 'config-git', $git );
966 $this->setVar( 'wgGitBin', false );
967 $this->showMessage( 'config-git-bad' );
974 * Environment check to inform user which server we've assumed.
978 protected function envCheckServer() {
979 $server = $this->envGetDefaultServer();
980 if ( $server !== null ) {
981 $this->showMessage( 'config-using-server', $server );
987 * Environment check to inform user which paths we've assumed.
991 protected function envCheckPath() {
994 $this->getVar( 'wgServer' ),
995 $this->getVar( 'wgScriptPath' )
1001 * Environment check for preferred locale in shell
1004 protected function envCheckShellLocale() {
1005 $os = php_uname( 's' );
1006 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1008 if ( !in_array( $os, $supported ) ) {
1012 # Get a list of available locales.
1014 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1020 $lines = array_map( 'trim', explode( "\n", $lines ) );
1021 $candidatesByLocale = array();
1022 $candidatesByLang = array();
1024 foreach ( $lines as $line ) {
1025 if ( $line === '' ) {
1029 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1033 list( , $lang, , , ) = $m;
1035 $candidatesByLocale[$m[0]] = $m;
1036 $candidatesByLang[$lang][] = $m;
1039 # Try the current value of LANG.
1040 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1041 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1046 # Try the most common ones.
1047 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1048 foreach ( $commonLocales as $commonLocale ) {
1049 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1050 $this->setVar( 'wgShellLocale', $commonLocale );
1056 # Is there an available locale in the Wiki's language?
1057 $wikiLang = $this->getVar( 'wgLanguageCode' );
1059 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1060 $m = reset( $candidatesByLang[$wikiLang] );
1061 $this->setVar( 'wgShellLocale', $m[0] );
1066 # Are there any at all?
1067 if ( count( $candidatesByLocale ) ) {
1068 $m = reset( $candidatesByLocale );
1069 $this->setVar( 'wgShellLocale', $m[0] );
1079 * Environment check for the permissions of the uploads directory
1082 protected function envCheckUploadsDirectory() {
1085 $dir = $IP . '/images/';
1086 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1087 $safe = !$this->dirIsExecutable( $dir, $url );
1090 $this->showMessage( 'config-uploads-not-safe', $dir );
1097 * Checks if suhosin.get.max_value_length is set, and if so generate
1098 * a warning because it decreases ResourceLoader performance.
1101 protected function envCheckSuhosinMaxValueLength() {
1102 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1103 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1104 // Only warn if the value is below the sane 1024
1105 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1112 * Convert a hex string representing a Unicode code point to that code point.
1116 protected function unicodeChar( $c ) {
1120 } elseif ( $c <= 0x7FF ) {
1121 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1122 } elseif ( $c <= 0xFFFF ) {
1123 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F ) .
1124 chr( 0x80 |
$c & 0x3F );
1125 } elseif ( $c <= 0x10FFFF ) {
1126 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F ) .
1127 chr( 0x80 |
$c >> 6 & 0x3F ) .
1128 chr( 0x80 |
$c & 0x3F );
1135 * Check the libicu version
1137 protected function envCheckLibicu() {
1139 * This needs to be updated something that the latest libicu
1140 * will properly normalize. This normalization was found at
1141 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1142 * Note that we use the hex representation to create the code
1143 * points in order to avoid any Unicode-destroying during transit.
1145 $not_normal_c = $this->unicodeChar( "FA6C" );
1146 $normal_c = $this->unicodeChar( "242EE" );
1148 $useNormalizer = 'php';
1149 $needsUpdate = false;
1151 if ( function_exists( 'normalizer_normalize' ) ) {
1152 $useNormalizer = 'intl';
1153 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1154 if ( $intl !== $normal_c ) {
1155 $needsUpdate = true;
1159 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1160 if ( $useNormalizer === 'php' ) {
1161 $this->showMessage( 'config-unicode-pure-php-warning' );
1163 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1164 if ( $needsUpdate ) {
1165 $this->showMessage( 'config-unicode-update-warning' );
1173 protected function envCheckCtype() {
1174 if ( !function_exists( 'ctype_digit' ) ) {
1175 $this->showError( 'config-ctype' );
1186 protected function envCheckIconv() {
1187 if ( !function_exists( 'iconv' ) ) {
1188 $this->showError( 'config-iconv' );
1199 protected function envCheckJSON() {
1200 if ( !function_exists( 'json_decode' ) ) {
1201 $this->showError( 'config-json' );
1210 * Environment prep for the server hostname.
1212 protected function envPrepServer() {
1213 $server = $this->envGetDefaultServer();
1214 if ( $server !== null ) {
1215 $this->setVar( 'wgServer', $server );
1220 * Helper function to be called from envPrepServer()
1223 abstract protected function envGetDefaultServer();
1226 * Environment prep for setting $IP and $wgScriptPath.
1228 protected function envPrepPath() {
1230 $IP = dirname( dirname( __DIR__
) );
1231 $this->setVar( 'IP', $IP );
1235 * Get an array of likely places we can find executables. Check a bunch
1236 * of known Unix-like defaults, as well as the PATH environment variable
1237 * (which should maybe make it work for Windows?)
1241 protected static function getPossibleBinPaths() {
1243 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1244 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1245 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1250 * Search a path for any of the given executable names. Returns the
1251 * executable name if found. Also checks the version string returned
1252 * by each executable.
1254 * Used only by environment checks.
1256 * @param string $path Path to search
1257 * @param array $names Array of executable names
1258 * @param array|bool $versionInfo False or array with two members:
1259 * 0 => Command to run for version check, with $1 for the full executable name
1260 * 1 => String to compare the output with
1262 * If $versionInfo is not false, only executables with a version
1263 * matching $versionInfo[1] will be returned.
1264 * @return bool|string
1266 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1267 if ( !is_array( $names ) ) {
1268 $names = array( $names );
1271 foreach ( $names as $name ) {
1272 $command = $path . DIRECTORY_SEPARATOR
. $name;
1274 MediaWiki\
suppressWarnings();
1275 $file_exists = file_exists( $command );
1276 MediaWiki\restoreWarnings
();
1278 if ( $file_exists ) {
1279 if ( !$versionInfo ) {
1283 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1284 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1294 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1295 * @see locateExecutable()
1296 * @param array $names Array of possible names.
1297 * @param array|bool $versionInfo Default: false or array with two members:
1298 * 0 => Command to run for version check, with $1 for the full executable name
1299 * 1 => String to compare the output with
1301 * If $versionInfo is not false, only executables with a version
1302 * matching $versionInfo[1] will be returned.
1303 * @return bool|string
1305 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1306 foreach ( self
::getPossibleBinPaths() as $path ) {
1307 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1308 if ( $exe !== false ) {
1317 * Checks if scripts located in the given directory can be executed via the given URL.
1319 * Used only by environment checks.
1320 * @param string $dir
1321 * @param string $url
1322 * @return bool|int|string
1324 public function dirIsExecutable( $dir, $url ) {
1325 $scriptTypes = array(
1327 "<?php echo 'ex' . 'ec';",
1328 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1332 // it would be good to check other popular languages here, but it'll be slow.
1334 MediaWiki\
suppressWarnings();
1336 foreach ( $scriptTypes as $ext => $contents ) {
1337 foreach ( $contents as $source ) {
1338 $file = 'exectest.' . $ext;
1340 if ( !file_put_contents( $dir . $file, $source ) ) {
1345 $text = Http
::get( $url . $file, array( 'timeout' => 3 ), __METHOD__
);
1346 } catch ( Exception
$e ) {
1347 // Http::get throws with allow_url_fopen = false and no curl extension.
1350 unlink( $dir . $file );
1352 if ( $text == 'exec' ) {
1353 MediaWiki\restoreWarnings
();
1360 MediaWiki\restoreWarnings
();
1366 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1368 * @param string $moduleName Name of module to check.
1371 public static function apacheModulePresent( $moduleName ) {
1372 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1375 // try it the hard way
1377 phpinfo( INFO_MODULES
);
1378 $info = ob_get_clean();
1380 return strpos( $info, $moduleName ) !== false;
1384 * ParserOptions are constructed before we determined the language, so fix it
1386 * @param Language $lang
1388 public function setParserLanguage( $lang ) {
1389 $this->parserOptions
->setTargetLanguage( $lang );
1390 $this->parserOptions
->setUserLang( $lang );
1394 * Overridden by WebInstaller to provide lastPage parameters.
1395 * @param string $page
1398 protected function getDocUrl( $page ) {
1399 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1403 * Finds extensions that follow the format /$directory/Name/Name.php,
1404 * and returns an array containing the value for 'Name' for each found extension.
1406 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1408 * @param string $directory Directory to search in
1411 public function findExtensions( $directory = 'extensions' ) {
1412 if ( $this->getVar( 'IP' ) === null ) {
1416 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1417 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1421 // extensions -> extension.json, skins -> skin.json
1422 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1424 $dh = opendir( $extDir );
1426 while ( ( $file = readdir( $dh ) ) !== false ) {
1427 if ( !is_dir( "$extDir/$file" ) ) {
1430 if ( file_exists( "$extDir/$file/$jsonFile" ) ||
file_exists( "$extDir/$file/$file.php" ) ) {
1435 natcasesort( $exts );
1441 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1442 * but will fall back to another if the default skin is missing and some other one is present
1445 * @param string[] $skinNames Names of installed skins.
1448 public function getDefaultSkin( array $skinNames ) {
1449 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1450 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1451 return $defaultSkin;
1453 return $skinNames[0];
1458 * Installs the auto-detected extensions.
1462 protected function includeExtensions() {
1464 $exts = $this->getVar( '_Extensions' );
1465 $IP = $this->getVar( 'IP' );
1468 * We need to include DefaultSettings before including extensions to avoid
1469 * warnings about unset variables. However, the only thing we really
1470 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1471 * if the extension has hidden hook registration in $wgExtensionFunctions,
1472 * but we're not opening that can of worms
1473 * @see https://phabricator.wikimedia.org/T28857
1475 global $wgAutoloadClasses;
1476 $wgAutoloadClasses = array();
1479 require "$IP/includes/DefaultSettings.php";
1481 foreach ( $exts as $e ) {
1482 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1483 $queue["$IP/extensions/$e/extension.json"] = 1;
1485 require_once "$IP/extensions/$e/$e.php";
1489 $registry = new ExtensionRegistry();
1490 $data = $registry->readFromQueue( $queue );
1491 $wgAutoloadClasses +
= $data['autoload'];
1493 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1494 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1496 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1497 $hooksWeWant = array_merge_recursive(
1499 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1502 // Unset everyone else's hooks. Lord knows what someone might be doing
1503 // in ParserFirstCallInit (see bug 27171)
1504 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1506 return Status
::newGood();
1510 * Get an array of install steps. Should always be in the format of
1512 * 'name' => 'someuniquename',
1513 * 'callback' => array( $obj, 'method' ),
1515 * There must be a config-install-$name message defined per step, which will
1516 * be shown on install.
1518 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1521 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1522 $coreInstallSteps = array(
1523 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1524 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1525 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1526 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1527 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1528 array( 'name' => 'updates', 'callback' => array( $installer, 'insertUpdateKeys' ) ),
1529 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1530 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1533 // Build the array of install steps starting from the core install list,
1534 // then adding any callbacks that wanted to attach after a given step
1535 foreach ( $coreInstallSteps as $step ) {
1536 $this->installSteps
[] = $step;
1537 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1538 $this->installSteps
= array_merge(
1539 $this->installSteps
,
1540 $this->extraInstallSteps
[$step['name']]
1545 // Prepend any steps that want to be at the beginning
1546 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1547 $this->installSteps
= array_merge(
1548 $this->extraInstallSteps
['BEGINNING'],
1553 // Extensions should always go first, chance to tie into hooks and such
1554 if ( count( $this->getVar( '_Extensions' ) ) ) {
1555 array_unshift( $this->installSteps
,
1556 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1558 $this->installSteps
[] = array(
1559 'name' => 'extension-tables',
1560 'callback' => array( $installer, 'createExtensionTables' )
1564 return $this->installSteps
;
1568 * Actually perform the installation.
1570 * @param callable $startCB A callback array for the beginning of each step
1571 * @param callable $endCB A callback array for the end of each step
1573 * @return array Array of Status objects
1575 public function performInstallation( $startCB, $endCB ) {
1576 $installResults = array();
1577 $installer = $this->getDBInstaller();
1578 $installer->preInstall();
1579 $steps = $this->getInstallSteps( $installer );
1580 foreach ( $steps as $stepObj ) {
1581 $name = $stepObj['name'];
1582 call_user_func_array( $startCB, array( $name ) );
1584 // Perform the callback step
1585 $status = call_user_func( $stepObj['callback'], $installer );
1587 // Output and save the results
1588 call_user_func( $endCB, $name, $status );
1589 $installResults[$name] = $status;
1591 // If we've hit some sort of fatal, we need to bail.
1592 // Callback already had a chance to do output above.
1593 if ( !$status->isOk() ) {
1597 if ( $status->isOk() ) {
1598 $this->setVar( '_InstallDone', true );
1601 return $installResults;
1605 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1609 public function generateKeys() {
1610 $keys = array( 'wgSecretKey' => 64 );
1611 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1612 $keys['wgUpgradeKey'] = 16;
1615 return $this->doGenerateKeys( $keys );
1619 * Generate a secret value for variables using our CryptRand generator.
1620 * Produce a warning if the random source was insecure.
1622 * @param array $keys
1625 protected function doGenerateKeys( $keys ) {
1626 $status = Status
::newGood();
1629 foreach ( $keys as $name => $length ) {
1630 $secretKey = MWCryptRand
::generateHex( $length, true );
1631 if ( !MWCryptRand
::wasStrong() ) {
1635 $this->setVar( $name, $secretKey );
1639 $names = array_keys( $keys );
1640 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1642 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1649 * Create the first user account, grant it sysop and bureaucrat rights
1653 protected function createSysop() {
1654 $name = $this->getVar( '_AdminName' );
1655 $user = User
::newFromName( $name );
1658 // We should've validated this earlier anyway!
1659 return Status
::newFatal( 'config-admin-error-user', $name );
1662 if ( $user->idForName() == 0 ) {
1663 $user->addToDatabase();
1666 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1667 } catch ( PasswordError
$pwe ) {
1668 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1671 $user->addGroup( 'sysop' );
1672 $user->addGroup( 'bureaucrat' );
1673 if ( $this->getVar( '_AdminEmail' ) ) {
1674 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1676 $user->saveSettings();
1678 // Update user count
1679 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1680 $ssUpdate->doUpdate();
1682 $status = Status
::newGood();
1684 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1685 $this->subscribeToMediaWikiAnnounce( $status );
1694 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1696 'email' => $this->getVar( '_AdminEmail' ),
1701 // Mailman doesn't support as many languages as we do, so check to make
1702 // sure their selected language is available
1703 $myLang = $this->getVar( '_UserLang' );
1704 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1705 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1706 $params['language'] = $myLang;
1709 if ( MWHttpRequest
::canMakeRequests() ) {
1710 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1711 array( 'method' => 'POST', 'postData' => $params ), __METHOD__
)->execute();
1712 if ( !$res->isOK() ) {
1713 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1716 $s->warning( 'config-install-subscribe-notpossible' );
1721 * Insert Main Page with default content.
1723 * @param DatabaseInstaller $installer
1726 protected function createMainpage( DatabaseInstaller
$installer ) {
1727 $status = Status
::newGood();
1729 $page = WikiPage
::factory( Title
::newMainPage() );
1730 $content = new WikitextContent(
1731 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1732 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1735 $page->doEditContent( $content,
1739 User
::newFromName( 'MediaWiki default' )
1741 } catch ( Exception
$e ) {
1742 // using raw, because $wgShowExceptionDetails can not be set yet
1743 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1750 * Override the necessary bits of the config to run an installation.
1752 public static function overrideConfig() {
1753 define( 'MW_NO_SESSION', 1 );
1755 // Don't access the database
1756 $GLOBALS['wgUseDatabaseMessages'] = false;
1757 // Don't cache langconv tables
1758 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1760 $GLOBALS['wgShowExceptionDetails'] = true;
1761 // Don't break forms
1762 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1764 // Extended debugging
1765 $GLOBALS['wgShowSQLErrors'] = true;
1766 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1768 // Allow multiple ob_flush() calls
1769 $GLOBALS['wgDisableOutputCompression'] = true;
1771 // Use a sensible cookie prefix (not my_wiki)
1772 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1774 // Some of the environment checks make shell requests, remove limits
1775 $GLOBALS['wgMaxShellMemory'] = 0;
1779 * Add an installation step following the given step.
1781 * @param callable $callback A valid installation callback array, in this form:
1782 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1783 * @param string $findStep The step to find. Omit to put the step at the beginning
1785 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1786 $this->extraInstallSteps
[$findStep][] = $callback;
1790 * Disable the time limit for execution.
1791 * Some long-running pages (Install, Upgrade) will want to do this
1793 protected function disableTimeLimit() {
1794 MediaWiki\
suppressWarnings();
1795 set_time_limit( 0 );
1796 MediaWiki\restoreWarnings
();