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(
126 'envCheckModSecurity',
132 'envCheckShellLocale',
133 'envCheckUploadsDirectory',
135 'envCheckSuhosinMaxValueLength',
142 * A list of environment preparation methods called by doEnvironmentPreps().
146 protected $envPreps = array(
152 * MediaWiki configuration globals that will eventually be passed through
153 * to LocalSettings.php. The names only are given here, the defaults
154 * typically come from DefaultSettings.php.
158 protected $defaultVarNames = array(
169 'wgEmailAuthentication',
173 'wgImageMagickConvertCommand',
178 'wgDeletedDirectory',
182 'wgUseInstantCommons',
188 * Variables that are stored alongside globals, and are used for any
189 * configuration of the installation process aside from the MediaWiki
190 * configuration. Map of names to defaults.
194 protected $internalDefaults = array(
196 '_Environment' => false,
197 '_SafeMode' => false,
198 '_RaiseMemory' => false,
199 '_UpgradeDone' => false,
200 '_InstallDone' => false,
201 '_Caches' => array(),
202 '_InstallPassword' => '',
203 '_SameAccount' => true,
204 '_CreateDBAccount' => false,
205 '_NamespaceType' => 'site-name',
206 '_AdminName' => '', // will be set later, when the user selects language
207 '_AdminPassword' => '',
208 '_AdminPasswordConfirm' => '',
210 '_Subscribe' => false,
211 '_SkipOptional' => 'continue',
212 '_RightsProfile' => 'wiki',
213 '_LicenseCode' => 'none',
215 '_Extensions' => array(),
217 '_MemCachedServers' => '',
218 '_UpgradeKeySupplied' => false,
219 '_ExistingDBSettings' => false,
221 // $wgLogo is probably wrong (bug 48084); set something that will work.
222 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
223 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
224 'wgAuthenticationTokenVersion' => 1,
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 // Don't attempt to load user language options (T126177)
363 // This will be overridden in the web installer with the user-specified language
364 RequestContext
::getMain()->setLanguage( 'en' );
366 // Disable the i18n cache
367 Language
::getLocalisationCache()->disableBackend();
368 // Disable LoadBalancer and wfGetDB etc.
369 LBFactory
::disableBackend();
371 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
372 // SqlBagOStuff will then throw since we just disabled wfGetDB)
373 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
374 ObjectCache
::clear();
375 $emptyCache = array( 'class' => 'EmptyBagOStuff' );
376 // disable (problematic) object cache types explicitly, preserving all other (working) ones
378 $GLOBALS['wgObjectCaches'] = array(
379 CACHE_NONE
=> $emptyCache,
380 CACHE_DB
=> $emptyCache,
381 CACHE_ANYTHING
=> $emptyCache,
382 CACHE_MEMCACHED
=> $emptyCache,
383 ) +
$GLOBALS['wgObjectCaches'];
385 // Load the installer's i18n.
386 $wgMessagesDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
388 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
389 $wgUser = User
::newFromId( 0 );
390 RequestContext
::getMain()->setUser( $wgUser );
392 $this->settings
= $this->internalDefaults
;
394 foreach ( $this->defaultVarNames
as $var ) {
395 $this->settings
[$var] = $GLOBALS[$var];
398 $this->doEnvironmentPreps();
400 $this->compiledDBs
= array();
401 foreach ( self
::getDBTypes() as $type ) {
402 $installer = $this->getDBInstaller( $type );
404 if ( !$installer->isCompiled() ) {
407 $this->compiledDBs
[] = $type;
410 $this->parserTitle
= Title
::newFromText( 'Installer' );
411 $this->parserOptions
= new ParserOptions( $wgUser ); // language will be wrong :(
412 $this->parserOptions
->setEditSection( false );
416 * Get a list of known DB types.
420 public static function getDBTypes() {
421 return self
::$dbTypes;
425 * Do initial checks of the PHP environment. Set variables according to
426 * the observed environment.
428 * It's possible that this may be called under the CLI SAPI, not the SAPI
429 * that the wiki will primarily run under. In that case, the subclass should
430 * initialise variables such as wgScriptPath, before calling this function.
432 * Under the web subclass, it can already be assumed that PHP 5+ is in use
433 * and that sessions are working.
437 public function doEnvironmentChecks() {
438 // Php version has already been checked by entry scripts
439 // Show message here for information purposes
441 $this->showMessage( 'config-env-hhvm', HHVM_VERSION
);
443 $this->showMessage( 'config-env-php', PHP_VERSION
);
447 // Must go here because an old version of PCRE can prevent other checks from completing
448 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
449 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
450 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
453 foreach ( $this->envChecks
as $check ) {
454 $status = $this->$check();
455 if ( $status === false ) {
461 $this->setVar( '_Environment', $good );
463 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
466 public function doEnvironmentPreps() {
467 foreach ( $this->envPreps
as $prep ) {
473 * Set a MW configuration variable, or internal installer configuration variable.
475 * @param string $name
476 * @param mixed $value
478 public function setVar( $name, $value ) {
479 $this->settings
[$name] = $value;
483 * Get an MW configuration variable, or internal installer configuration variable.
484 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
485 * Installer variables are typically prefixed by an underscore.
487 * @param string $name
488 * @param mixed $default
492 public function getVar( $name, $default = null ) {
493 if ( !isset( $this->settings
[$name] ) ) {
496 return $this->settings
[$name];
501 * Get a list of DBs supported by current PHP setup
505 public function getCompiledDBs() {
506 return $this->compiledDBs
;
510 * Get an instance of DatabaseInstaller for the specified DB type.
512 * @param mixed $type DB installer for which is needed, false to use default.
514 * @return DatabaseInstaller
516 public function getDBInstaller( $type = false ) {
518 $type = $this->getVar( 'wgDBtype' );
521 $type = strtolower( $type );
523 if ( !isset( $this->dbInstallers
[$type] ) ) {
524 $class = ucfirst( $type ) . 'Installer';
525 $this->dbInstallers
[$type] = new $class( $this );
528 return $this->dbInstallers
[$type];
532 * Determine if LocalSettings.php exists. If it does, return its variables.
536 public static function getExistingLocalSettings() {
539 // You might be wondering why this is here. Well if you don't do this
540 // then some poorly-formed extensions try to call their own classes
541 // after immediately registering them. We really need to get extension
542 // registration out of the global scope and into a real format.
543 // @see https://phabricator.wikimedia.org/T69440
544 global $wgAutoloadClasses;
545 $wgAutoloadClasses = array();
547 // @codingStandardsIgnoreStart
548 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
549 // Define the required globals here, to ensure, the functions can do it work correctly.
550 global $wgExtensionDirectory, $wgStyleDirectory;
551 // @codingStandardsIgnoreEnd
553 MediaWiki\
suppressWarnings();
554 $_lsExists = file_exists( "$IP/LocalSettings.php" );
555 MediaWiki\restoreWarnings
();
562 require "$IP/includes/DefaultSettings.php";
563 require "$IP/LocalSettings.php";
565 return get_defined_vars();
569 * Get a fake password for sending back to the user in HTML.
570 * This is a security mechanism to avoid compromise of the password in the
571 * event of session ID compromise.
573 * @param string $realPassword
577 public function getFakePassword( $realPassword ) {
578 return str_repeat( '*', strlen( $realPassword ) );
582 * Set a variable which stores a password, except if the new value is a
583 * fake password in which case leave it as it is.
585 * @param string $name
586 * @param mixed $value
588 public function setPassword( $name, $value ) {
589 if ( !preg_match( '/^\*+$/', $value ) ) {
590 $this->setVar( $name, $value );
595 * On POSIX systems return the primary group of the webserver we're running under.
596 * On other systems just returns null.
598 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
599 * webserver user before he can install.
601 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
605 public static function maybeGetWebserverPrimaryGroup() {
606 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
607 # I don't know this, this isn't UNIX.
611 # posix_getegid() *not* getmygid() because we want the group of the webserver,
612 # not whoever owns the current script.
613 $gid = posix_getegid();
614 $getpwuid = posix_getpwuid( $gid );
615 $group = $getpwuid['name'];
621 * Convert wikitext $text to HTML.
623 * This is potentially error prone since many parser features require a complete
624 * installed MW database. The solution is to just not use those features when you
625 * write your messages. This appears to work well enough. Basic formatting and
626 * external links work just fine.
628 * But in case a translator decides to throw in a "#ifexist" or internal link or
629 * whatever, this function is guarded to catch the attempted DB access and to present
630 * some fallback text.
632 * @param string $text
633 * @param bool $lineStart
636 public function parse( $text, $lineStart = false ) {
640 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
641 $html = $out->getText();
642 } catch ( DBAccessError
$e ) {
643 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
645 if ( !empty( $this->debug
) ) {
646 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
654 * @return ParserOptions
656 public function getParserOptions() {
657 return $this->parserOptions
;
660 public function disableLinkPopups() {
661 $this->parserOptions
->setExternalLinkTarget( false );
664 public function restoreLinkPopups() {
665 global $wgExternalLinkTarget;
666 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
670 * Install step which adds a row to the site_stats table with appropriate
673 * @param DatabaseInstaller $installer
677 public function populateSiteStats( DatabaseInstaller
$installer ) {
678 $status = $installer->getConnection();
679 if ( !$status->isOK() ) {
682 $status->value
->insert(
686 'ss_total_edits' => 0,
687 'ss_good_articles' => 0,
688 'ss_total_pages' => 0,
695 return Status
::newGood();
699 * Environment check for DB types.
702 protected function envCheckDB() {
707 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
708 // config-type-sqlite
709 foreach ( self
::getDBTypes() as $name ) {
710 $allNames[] = wfMessage( "config-type-$name" )->text();
713 $databases = $this->getCompiledDBs();
715 $databases = array_flip( $databases );
716 foreach ( array_keys( $databases ) as $db ) {
717 $installer = $this->getDBInstaller( $db );
718 $status = $installer->checkPrerequisites();
719 if ( !$status->isGood() ) {
720 $this->showStatusMessage( $status );
722 if ( !$status->isOK() ) {
723 unset( $databases[$db] );
726 $databases = array_flip( $databases );
728 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
730 // @todo FIXME: This only works for the web installer!
738 * Some versions of libxml+PHP break < and > encoding horribly
741 protected function envCheckBrokenXML() {
742 $test = new PhpXmlBugTester();
744 $this->showError( 'config-brokenlibxml' );
753 * Environment check for mbstring.func_overload.
756 protected function envCheckMbstring() {
757 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
758 $this->showError( 'config-mbstring' );
767 * Environment check for safe_mode.
770 protected function envCheckSafeMode() {
771 if ( wfIniGetBool( 'safe_mode' ) ) {
772 $this->setVar( '_SafeMode', true );
773 $this->showMessage( 'config-safe-mode' );
780 * Environment check for the XML module.
783 protected function envCheckXML() {
784 if ( !function_exists( "utf8_encode" ) ) {
785 $this->showError( 'config-xml-bad' );
794 * Environment check for the PCRE module.
796 * @note If this check were to fail, the parser would
797 * probably throw an exception before the result
798 * of this check is shown to the user.
801 protected function envCheckPCRE() {
802 MediaWiki\
suppressWarnings();
803 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
804 // Need to check for \p support too, as PCRE can be compiled
805 // with utf8 support, but not unicode property support.
806 // check that \p{Zs} (space separators) matches
807 // U+3000 (Ideographic space)
808 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
809 MediaWiki\restoreWarnings
();
810 if ( $regexd != '--' ||
$regexprop != '--' ) {
811 $this->showError( 'config-pcre-no-utf8' );
820 * Environment check for available memory.
823 protected function envCheckMemory() {
824 $limit = ini_get( 'memory_limit' );
826 if ( !$limit ||
$limit == -1 ) {
830 $n = wfShorthandToInteger( $limit );
832 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
833 $newLimit = "{$this->minMemorySize}M";
835 if ( ini_set( "memory_limit", $newLimit ) === false ) {
836 $this->showMessage( 'config-memory-bad', $limit );
838 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
839 $this->setVar( '_RaiseMemory', true );
847 * Environment check for compiled object cache types.
849 protected function envCheckCache() {
851 foreach ( $this->objectCaches
as $name => $function ) {
852 if ( function_exists( $function ) ) {
853 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
856 $caches[$name] = true;
861 $key = 'config-no-cache';
862 // PHP >=5.5 is called APCu, earlier versions use APC (T61998).
863 if ( !wfIsHHVM() && version_compare( PHP_VERSION
, '5.5', '>=' ) ) {
864 // config-no-cache-apcu
867 $this->showMessage( $key );
870 $this->setVar( '_Caches', $caches );
874 * Scare user to death if they have mod_security or mod_security2
877 protected function envCheckModSecurity() {
878 if ( self
::apacheModulePresent( 'mod_security' )
879 || self
::apacheModulePresent( 'mod_security2' ) ) {
880 $this->showMessage( 'config-mod-security' );
887 * Search for GNU diff3.
890 protected function envCheckDiff3() {
891 $names = array( "gdiff3", "diff3", "diff3.exe" );
892 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
894 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
897 $this->setVar( 'wgDiff3', $diff3 );
899 $this->setVar( 'wgDiff3', false );
900 $this->showMessage( 'config-diff3-bad' );
907 * Environment check for ImageMagick and GD.
910 protected function envCheckGraphics() {
911 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
912 $versionInfo = array( '$1 -version', 'ImageMagick' );
913 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
915 $this->setVar( 'wgImageMagickConvertCommand', '' );
917 $this->setVar( 'wgImageMagickConvertCommand', $convert );
918 $this->showMessage( 'config-imagemagick', $convert );
921 } elseif ( function_exists( 'imagejpeg' ) ) {
922 $this->showMessage( 'config-gd' );
924 $this->showMessage( 'config-no-scaling' );
936 protected function envCheckGit() {
937 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
938 $versionInfo = array( '$1 --version', 'git version' );
940 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
943 $this->setVar( 'wgGitBin', $git );
944 $this->showMessage( 'config-git', $git );
946 $this->setVar( 'wgGitBin', false );
947 $this->showMessage( 'config-git-bad' );
954 * Environment check to inform user which server we've assumed.
958 protected function envCheckServer() {
959 $server = $this->envGetDefaultServer();
960 if ( $server !== null ) {
961 $this->showMessage( 'config-using-server', $server );
967 * Environment check to inform user which paths we've assumed.
971 protected function envCheckPath() {
974 $this->getVar( 'wgServer' ),
975 $this->getVar( 'wgScriptPath' )
981 * Environment check for preferred locale in shell
984 protected function envCheckShellLocale() {
985 $os = php_uname( 's' );
986 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
988 if ( !in_array( $os, $supported ) ) {
992 # Get a list of available locales.
994 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1000 $lines = array_map( 'trim', explode( "\n", $lines ) );
1001 $candidatesByLocale = array();
1002 $candidatesByLang = array();
1004 foreach ( $lines as $line ) {
1005 if ( $line === '' ) {
1009 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1013 list( , $lang, , , ) = $m;
1015 $candidatesByLocale[$m[0]] = $m;
1016 $candidatesByLang[$lang][] = $m;
1019 # Try the current value of LANG.
1020 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1021 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1026 # Try the most common ones.
1027 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1028 foreach ( $commonLocales as $commonLocale ) {
1029 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1030 $this->setVar( 'wgShellLocale', $commonLocale );
1036 # Is there an available locale in the Wiki's language?
1037 $wikiLang = $this->getVar( 'wgLanguageCode' );
1039 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1040 $m = reset( $candidatesByLang[$wikiLang] );
1041 $this->setVar( 'wgShellLocale', $m[0] );
1046 # Are there any at all?
1047 if ( count( $candidatesByLocale ) ) {
1048 $m = reset( $candidatesByLocale );
1049 $this->setVar( 'wgShellLocale', $m[0] );
1059 * Environment check for the permissions of the uploads directory
1062 protected function envCheckUploadsDirectory() {
1065 $dir = $IP . '/images/';
1066 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1067 $safe = !$this->dirIsExecutable( $dir, $url );
1070 $this->showMessage( 'config-uploads-not-safe', $dir );
1077 * Checks if suhosin.get.max_value_length is set, and if so generate
1078 * a warning because it decreases ResourceLoader performance.
1081 protected function envCheckSuhosinMaxValueLength() {
1082 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1083 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1084 // Only warn if the value is below the sane 1024
1085 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1092 * Convert a hex string representing a Unicode code point to that code point.
1096 protected function unicodeChar( $c ) {
1100 } elseif ( $c <= 0x7FF ) {
1101 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1102 } elseif ( $c <= 0xFFFF ) {
1103 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F ) .
1104 chr( 0x80 |
$c & 0x3F );
1105 } elseif ( $c <= 0x10FFFF ) {
1106 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F ) .
1107 chr( 0x80 |
$c >> 6 & 0x3F ) .
1108 chr( 0x80 |
$c & 0x3F );
1115 * Check the libicu version
1117 protected function envCheckLibicu() {
1119 * This needs to be updated something that the latest libicu
1120 * will properly normalize. This normalization was found at
1121 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1122 * Note that we use the hex representation to create the code
1123 * points in order to avoid any Unicode-destroying during transit.
1125 $not_normal_c = $this->unicodeChar( "FA6C" );
1126 $normal_c = $this->unicodeChar( "242EE" );
1128 $useNormalizer = 'php';
1129 $needsUpdate = false;
1131 if ( function_exists( 'normalizer_normalize' ) ) {
1132 $useNormalizer = 'intl';
1133 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1134 if ( $intl !== $normal_c ) {
1135 $needsUpdate = true;
1139 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1140 if ( $useNormalizer === 'php' ) {
1141 $this->showMessage( 'config-unicode-pure-php-warning' );
1143 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1144 if ( $needsUpdate ) {
1145 $this->showMessage( 'config-unicode-update-warning' );
1153 protected function envCheckCtype() {
1154 if ( !function_exists( 'ctype_digit' ) ) {
1155 $this->showError( 'config-ctype' );
1166 protected function envCheckIconv() {
1167 if ( !function_exists( 'iconv' ) ) {
1168 $this->showError( 'config-iconv' );
1179 protected function envCheckJSON() {
1180 if ( !function_exists( 'json_decode' ) ) {
1181 $this->showError( 'config-json' );
1190 * Environment prep for the server hostname.
1192 protected function envPrepServer() {
1193 $server = $this->envGetDefaultServer();
1194 if ( $server !== null ) {
1195 $this->setVar( 'wgServer', $server );
1200 * Helper function to be called from envPrepServer()
1203 abstract protected function envGetDefaultServer();
1206 * Environment prep for setting $IP and $wgScriptPath.
1208 protected function envPrepPath() {
1210 $IP = dirname( dirname( __DIR__
) );
1211 $this->setVar( 'IP', $IP );
1215 * Get an array of likely places we can find executables. Check a bunch
1216 * of known Unix-like defaults, as well as the PATH environment variable
1217 * (which should maybe make it work for Windows?)
1221 protected static function getPossibleBinPaths() {
1223 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1224 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1225 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1230 * Search a path for any of the given executable names. Returns the
1231 * executable name if found. Also checks the version string returned
1232 * by each executable.
1234 * Used only by environment checks.
1236 * @param string $path Path to search
1237 * @param array $names Array of executable names
1238 * @param array|bool $versionInfo False or array with two members:
1239 * 0 => Command to run for version check, with $1 for the full executable name
1240 * 1 => String to compare the output with
1242 * If $versionInfo is not false, only executables with a version
1243 * matching $versionInfo[1] will be returned.
1244 * @return bool|string
1246 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1247 if ( !is_array( $names ) ) {
1248 $names = array( $names );
1251 foreach ( $names as $name ) {
1252 $command = $path . DIRECTORY_SEPARATOR
. $name;
1254 MediaWiki\
suppressWarnings();
1255 $file_exists = file_exists( $command );
1256 MediaWiki\restoreWarnings
();
1258 if ( $file_exists ) {
1259 if ( !$versionInfo ) {
1263 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1264 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1274 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1275 * @see locateExecutable()
1276 * @param array $names Array of possible names.
1277 * @param array|bool $versionInfo Default: false or array with two members:
1278 * 0 => Command to run for version check, with $1 for the full executable name
1279 * 1 => String to compare the output with
1281 * If $versionInfo is not false, only executables with a version
1282 * matching $versionInfo[1] will be returned.
1283 * @return bool|string
1285 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1286 foreach ( self
::getPossibleBinPaths() as $path ) {
1287 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1288 if ( $exe !== false ) {
1297 * Checks if scripts located in the given directory can be executed via the given URL.
1299 * Used only by environment checks.
1300 * @param string $dir
1301 * @param string $url
1302 * @return bool|int|string
1304 public function dirIsExecutable( $dir, $url ) {
1305 $scriptTypes = array(
1307 "<?php echo 'ex' . 'ec';",
1308 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1312 // it would be good to check other popular languages here, but it'll be slow.
1314 MediaWiki\
suppressWarnings();
1316 foreach ( $scriptTypes as $ext => $contents ) {
1317 foreach ( $contents as $source ) {
1318 $file = 'exectest.' . $ext;
1320 if ( !file_put_contents( $dir . $file, $source ) ) {
1325 $text = Http
::get( $url . $file, array( 'timeout' => 3 ), __METHOD__
);
1326 } catch ( Exception
$e ) {
1327 // Http::get throws with allow_url_fopen = false and no curl extension.
1330 unlink( $dir . $file );
1332 if ( $text == 'exec' ) {
1333 MediaWiki\restoreWarnings
();
1340 MediaWiki\restoreWarnings
();
1346 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1348 * @param string $moduleName Name of module to check.
1351 public static function apacheModulePresent( $moduleName ) {
1352 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1355 // try it the hard way
1357 phpinfo( INFO_MODULES
);
1358 $info = ob_get_clean();
1360 return strpos( $info, $moduleName ) !== false;
1364 * ParserOptions are constructed before we determined the language, so fix it
1366 * @param Language $lang
1368 public function setParserLanguage( $lang ) {
1369 $this->parserOptions
->setTargetLanguage( $lang );
1370 $this->parserOptions
->setUserLang( $lang );
1374 * Overridden by WebInstaller to provide lastPage parameters.
1375 * @param string $page
1378 protected function getDocUrl( $page ) {
1379 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1383 * Finds extensions that follow the format /$directory/Name/Name.php,
1384 * and returns an array containing the value for 'Name' for each found extension.
1386 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1388 * @param string $directory Directory to search in
1391 public function findExtensions( $directory = 'extensions' ) {
1392 if ( $this->getVar( 'IP' ) === null ) {
1396 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1397 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1401 // extensions -> extension.json, skins -> skin.json
1402 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1404 $dh = opendir( $extDir );
1406 while ( ( $file = readdir( $dh ) ) !== false ) {
1407 if ( !is_dir( "$extDir/$file" ) ) {
1410 if ( file_exists( "$extDir/$file/$jsonFile" ) ||
file_exists( "$extDir/$file/$file.php" ) ) {
1415 natcasesort( $exts );
1421 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1422 * but will fall back to another if the default skin is missing and some other one is present
1425 * @param string[] $skinNames Names of installed skins.
1428 public function getDefaultSkin( array $skinNames ) {
1429 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1430 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1431 return $defaultSkin;
1433 return $skinNames[0];
1438 * Installs the auto-detected extensions.
1442 protected function includeExtensions() {
1444 $exts = $this->getVar( '_Extensions' );
1445 $IP = $this->getVar( 'IP' );
1448 * We need to include DefaultSettings before including extensions to avoid
1449 * warnings about unset variables. However, the only thing we really
1450 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1451 * if the extension has hidden hook registration in $wgExtensionFunctions,
1452 * but we're not opening that can of worms
1453 * @see https://phabricator.wikimedia.org/T28857
1455 global $wgAutoloadClasses;
1456 $wgAutoloadClasses = array();
1459 require "$IP/includes/DefaultSettings.php";
1461 foreach ( $exts as $e ) {
1462 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1463 $queue["$IP/extensions/$e/extension.json"] = 1;
1465 require_once "$IP/extensions/$e/$e.php";
1469 $registry = new ExtensionRegistry();
1470 $data = $registry->readFromQueue( $queue );
1471 $wgAutoloadClasses +
= $data['autoload'];
1473 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1474 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1476 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1477 $hooksWeWant = array_merge_recursive(
1479 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1482 // Unset everyone else's hooks. Lord knows what someone might be doing
1483 // in ParserFirstCallInit (see bug 27171)
1484 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1486 return Status
::newGood();
1490 * Get an array of install steps. Should always be in the format of
1492 * 'name' => 'someuniquename',
1493 * 'callback' => array( $obj, 'method' ),
1495 * There must be a config-install-$name message defined per step, which will
1496 * be shown on install.
1498 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1501 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1502 $coreInstallSteps = array(
1503 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1504 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1505 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1506 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1507 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1508 array( 'name' => 'updates', 'callback' => array( $installer, 'insertUpdateKeys' ) ),
1509 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1510 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1513 // Build the array of install steps starting from the core install list,
1514 // then adding any callbacks that wanted to attach after a given step
1515 foreach ( $coreInstallSteps as $step ) {
1516 $this->installSteps
[] = $step;
1517 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1518 $this->installSteps
= array_merge(
1519 $this->installSteps
,
1520 $this->extraInstallSteps
[$step['name']]
1525 // Prepend any steps that want to be at the beginning
1526 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1527 $this->installSteps
= array_merge(
1528 $this->extraInstallSteps
['BEGINNING'],
1533 // Extensions should always go first, chance to tie into hooks and such
1534 if ( count( $this->getVar( '_Extensions' ) ) ) {
1535 array_unshift( $this->installSteps
,
1536 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1538 $this->installSteps
[] = array(
1539 'name' => 'extension-tables',
1540 'callback' => array( $installer, 'createExtensionTables' )
1544 return $this->installSteps
;
1548 * Actually perform the installation.
1550 * @param callable $startCB A callback array for the beginning of each step
1551 * @param callable $endCB A callback array for the end of each step
1553 * @return array Array of Status objects
1555 public function performInstallation( $startCB, $endCB ) {
1556 $installResults = array();
1557 $installer = $this->getDBInstaller();
1558 $installer->preInstall();
1559 $steps = $this->getInstallSteps( $installer );
1560 foreach ( $steps as $stepObj ) {
1561 $name = $stepObj['name'];
1562 call_user_func_array( $startCB, array( $name ) );
1564 // Perform the callback step
1565 $status = call_user_func( $stepObj['callback'], $installer );
1567 // Output and save the results
1568 call_user_func( $endCB, $name, $status );
1569 $installResults[$name] = $status;
1571 // If we've hit some sort of fatal, we need to bail.
1572 // Callback already had a chance to do output above.
1573 if ( !$status->isOk() ) {
1577 if ( $status->isOk() ) {
1578 $this->setVar( '_InstallDone', true );
1581 return $installResults;
1585 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1589 public function generateKeys() {
1590 $keys = array( 'wgSecretKey' => 64 );
1591 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1592 $keys['wgUpgradeKey'] = 16;
1595 return $this->doGenerateKeys( $keys );
1599 * Generate a secret value for variables using our CryptRand generator.
1600 * Produce a warning if the random source was insecure.
1602 * @param array $keys
1605 protected function doGenerateKeys( $keys ) {
1606 $status = Status
::newGood();
1609 foreach ( $keys as $name => $length ) {
1610 $secretKey = MWCryptRand
::generateHex( $length, true );
1611 if ( !MWCryptRand
::wasStrong() ) {
1615 $this->setVar( $name, $secretKey );
1619 $names = array_keys( $keys );
1620 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1622 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1629 * Create the first user account, grant it sysop and bureaucrat rights
1633 protected function createSysop() {
1634 $name = $this->getVar( '_AdminName' );
1635 $user = User
::newFromName( $name );
1638 // We should've validated this earlier anyway!
1639 return Status
::newFatal( 'config-admin-error-user', $name );
1642 if ( $user->idForName() == 0 ) {
1643 $user->addToDatabase();
1646 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1647 } catch ( PasswordError
$pwe ) {
1648 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1651 $user->addGroup( 'sysop' );
1652 $user->addGroup( 'bureaucrat' );
1653 if ( $this->getVar( '_AdminEmail' ) ) {
1654 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1656 $user->saveSettings();
1658 // Update user count
1659 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1660 $ssUpdate->doUpdate();
1662 $status = Status
::newGood();
1664 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1665 $this->subscribeToMediaWikiAnnounce( $status );
1674 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1676 'email' => $this->getVar( '_AdminEmail' ),
1681 // Mailman doesn't support as many languages as we do, so check to make
1682 // sure their selected language is available
1683 $myLang = $this->getVar( '_UserLang' );
1684 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1685 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1686 $params['language'] = $myLang;
1689 if ( MWHttpRequest
::canMakeRequests() ) {
1690 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1691 array( 'method' => 'POST', 'postData' => $params ), __METHOD__
)->execute();
1692 if ( !$res->isOK() ) {
1693 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1696 $s->warning( 'config-install-subscribe-notpossible' );
1701 * Insert Main Page with default content.
1703 * @param DatabaseInstaller $installer
1706 protected function createMainpage( DatabaseInstaller
$installer ) {
1707 $status = Status
::newGood();
1709 $page = WikiPage
::factory( Title
::newMainPage() );
1710 $content = new WikitextContent(
1711 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1712 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1715 $page->doEditContent( $content,
1719 User
::newFromName( 'MediaWiki default' )
1721 } catch ( Exception
$e ) {
1722 // using raw, because $wgShowExceptionDetails can not be set yet
1723 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1730 * Override the necessary bits of the config to run an installation.
1732 public static function overrideConfig() {
1733 define( 'MW_NO_SESSION', 1 );
1735 // Don't access the database
1736 $GLOBALS['wgUseDatabaseMessages'] = false;
1737 // Don't cache langconv tables
1738 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1740 $GLOBALS['wgShowExceptionDetails'] = true;
1741 // Don't break forms
1742 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1744 // Extended debugging
1745 $GLOBALS['wgShowSQLErrors'] = true;
1746 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1748 // Allow multiple ob_flush() calls
1749 $GLOBALS['wgDisableOutputCompression'] = true;
1751 // Use a sensible cookie prefix (not my_wiki)
1752 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1754 // Some of the environment checks make shell requests, remove limits
1755 $GLOBALS['wgMaxShellMemory'] = 0;
1757 $GLOBALS['wgSessionProviders'] = array(
1759 'class' => 'InstallerSessionProvider',
1760 'args' => array( array(
1768 * Add an installation step following the given step.
1770 * @param callable $callback A valid installation callback array, in this form:
1771 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1772 * @param string $findStep The step to find. Omit to put the step at the beginning
1774 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1775 $this->extraInstallSteps
[$findStep][] = $callback;
1779 * Disable the time limit for execution.
1780 * Some long-running pages (Install, Upgrade) will want to do this
1782 protected function disableTimeLimit() {
1783 MediaWiki\
suppressWarnings();
1784 set_time_limit( 0 );
1785 MediaWiki\restoreWarnings
();