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 = [];
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 = [
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 = [
125 'envCheckModSecurity',
131 'envCheckShellLocale',
132 'envCheckUploadsDirectory',
134 'envCheckSuhosinMaxValueLength',
141 * A list of environment preparation methods called by doEnvironmentPreps().
145 protected $envPreps = [
151 * MediaWiki configuration globals that will eventually be passed through
152 * to LocalSettings.php. The names only are given here, the defaults
153 * typically come from DefaultSettings.php.
157 protected $defaultVarNames = [
168 'wgEmailAuthentication',
172 'wgImageMagickConvertCommand',
177 'wgDeletedDirectory',
181 'wgUseInstantCommons',
187 * Variables that are stored alongside globals, and are used for any
188 * configuration of the installation process aside from the MediaWiki
189 * configuration. Map of names to defaults.
193 protected $internalDefaults = [
195 '_Environment' => false,
196 '_RaiseMemory' => false,
197 '_UpgradeDone' => false,
198 '_InstallDone' => false,
200 '_InstallPassword' => '',
201 '_SameAccount' => true,
202 '_CreateDBAccount' => false,
203 '_NamespaceType' => 'site-name',
204 '_AdminName' => '', // will be set later, when the user selects language
205 '_AdminPassword' => '',
206 '_AdminPasswordConfirm' => '',
208 '_Subscribe' => false,
209 '_SkipOptional' => 'continue',
210 '_RightsProfile' => 'wiki',
211 '_LicenseCode' => 'none',
215 '_MemCachedServers' => '',
216 '_UpgradeKeySupplied' => false,
217 '_ExistingDBSettings' => false,
219 // $wgLogo is probably wrong (bug 48084); set something that will work.
220 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
221 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
222 'wgAuthenticationTokenVersion' => 1,
226 * The actual list of installation steps. This will be initialized by getInstallSteps()
230 private $installSteps = [];
233 * Extra steps for installation, for things like DatabaseInstallers to modify
237 protected $extraInstallSteps = [];
240 * Known object cache types and the functions used to test for their existence.
244 protected $objectCaches = [
245 'xcache' => 'xcache_get',
246 'apc' => 'apc_fetch',
247 'wincache' => 'wincache_ucache_get'
251 * User rights profiles.
255 public $rightsProfiles = [
258 '*' => [ 'edit' => false ]
262 'createaccount' => false,
268 'createaccount' => false,
282 'url' => 'https://creativecommons.org/licenses/by/4.0/',
283 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
286 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
287 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
290 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
291 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
294 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
295 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
299 'icon' => '$wgResourceBasePath/resources/assets/licenses/public-domain.png',
302 'url' => 'https://www.gnu.org/copyleft/fdl.html',
303 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
311 // Details will be filled in by the selector.
319 * URL to mediawiki-announce subscription
321 protected $mediaWikiAnnounceUrl =
322 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
325 * Supported language codes for Mailman
327 protected $mediaWikiAnnounceLanguages = [
328 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
329 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
330 'sl', 'sr', 'sv', 'tr', 'uk'
334 * UI interface for displaying a short message
335 * The parameters are like parameters to wfMessage().
336 * The messages will be in wikitext format, which will be converted to an
337 * output format such as HTML or text before being sent to the user.
340 abstract public function showMessage( $msg /*, ... */ );
343 * Same as showMessage(), but for displaying errors
346 abstract public function showError( $msg /*, ... */ );
349 * Show a message to the installing user by using a Status object
350 * @param Status $status
352 abstract public function showStatusMessage( Status
$status );
355 * Constructor, always call this from child classes.
357 public function __construct() {
358 global $wgMessagesDirs, $wgUser;
360 // Don't attempt to load user language options (T126177)
361 // This will be overridden in the web installer with the user-specified language
362 RequestContext
::getMain()->setLanguage( 'en' );
364 // Disable the i18n cache
365 Language
::getLocalisationCache()->disableBackend();
366 // Disable LoadBalancer and wfGetDB etc.
367 LBFactory
::disableBackend();
369 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
370 // SqlBagOStuff will then throw since we just disabled wfGetDB)
371 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
372 ObjectCache
::clear();
373 $emptyCache = [ 'class' => 'EmptyBagOStuff' ];
374 // disable (problematic) object cache types explicitly, preserving all other (working) ones
376 $GLOBALS['wgObjectCaches'] = [
377 CACHE_NONE
=> $emptyCache,
378 CACHE_DB
=> $emptyCache,
379 CACHE_ANYTHING
=> $emptyCache,
380 CACHE_MEMCACHED
=> $emptyCache,
381 ] +
$GLOBALS['wgObjectCaches'];
383 // Load the installer's i18n.
384 $wgMessagesDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
386 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
387 $wgUser = User
::newFromId( 0 );
388 RequestContext
::getMain()->setUser( $wgUser );
390 $this->settings
= $this->internalDefaults
;
392 foreach ( $this->defaultVarNames
as $var ) {
393 $this->settings
[$var] = $GLOBALS[$var];
396 $this->doEnvironmentPreps();
398 $this->compiledDBs
= [];
399 foreach ( self
::getDBTypes() as $type ) {
400 $installer = $this->getDBInstaller( $type );
402 if ( !$installer->isCompiled() ) {
405 $this->compiledDBs
[] = $type;
408 $this->parserTitle
= Title
::newFromText( 'Installer' );
409 $this->parserOptions
= new ParserOptions( $wgUser ); // language will be wrong :(
410 $this->parserOptions
->setEditSection( false );
414 * Get a list of known DB types.
418 public static function getDBTypes() {
419 return self
::$dbTypes;
423 * Do initial checks of the PHP environment. Set variables according to
424 * the observed environment.
426 * It's possible that this may be called under the CLI SAPI, not the SAPI
427 * that the wiki will primarily run under. In that case, the subclass should
428 * initialise variables such as wgScriptPath, before calling this function.
430 * Under the web subclass, it can already be assumed that PHP 5+ is in use
431 * and that sessions are working.
435 public function doEnvironmentChecks() {
436 // Php version has already been checked by entry scripts
437 // Show message here for information purposes
439 $this->showMessage( 'config-env-hhvm', HHVM_VERSION
);
441 $this->showMessage( 'config-env-php', PHP_VERSION
);
445 // Must go here because an old version of PCRE can prevent other checks from completing
446 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
447 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
448 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
451 foreach ( $this->envChecks
as $check ) {
452 $status = $this->$check();
453 if ( $status === false ) {
459 $this->setVar( '_Environment', $good );
461 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
464 public function doEnvironmentPreps() {
465 foreach ( $this->envPreps
as $prep ) {
471 * Set a MW configuration variable, or internal installer configuration variable.
473 * @param string $name
474 * @param mixed $value
476 public function setVar( $name, $value ) {
477 $this->settings
[$name] = $value;
481 * Get an MW configuration variable, or internal installer configuration variable.
482 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
483 * Installer variables are typically prefixed by an underscore.
485 * @param string $name
486 * @param mixed $default
490 public function getVar( $name, $default = null ) {
491 if ( !isset( $this->settings
[$name] ) ) {
494 return $this->settings
[$name];
499 * Get a list of DBs supported by current PHP setup
503 public function getCompiledDBs() {
504 return $this->compiledDBs
;
508 * Get an instance of DatabaseInstaller for the specified DB type.
510 * @param mixed $type DB installer for which is needed, false to use default.
512 * @return DatabaseInstaller
514 public function getDBInstaller( $type = false ) {
516 $type = $this->getVar( 'wgDBtype' );
519 $type = strtolower( $type );
521 if ( !isset( $this->dbInstallers
[$type] ) ) {
522 $class = ucfirst( $type ) . 'Installer';
523 $this->dbInstallers
[$type] = new $class( $this );
526 return $this->dbInstallers
[$type];
530 * Determine if LocalSettings.php exists. If it does, return its variables.
534 public static function getExistingLocalSettings() {
537 // You might be wondering why this is here. Well if you don't do this
538 // then some poorly-formed extensions try to call their own classes
539 // after immediately registering them. We really need to get extension
540 // registration out of the global scope and into a real format.
541 // @see https://phabricator.wikimedia.org/T69440
542 global $wgAutoloadClasses;
543 $wgAutoloadClasses = [];
545 // @codingStandardsIgnoreStart
546 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
547 // Define the required globals here, to ensure, the functions can do it work correctly.
548 global $wgExtensionDirectory, $wgStyleDirectory;
549 // @codingStandardsIgnoreEnd
551 MediaWiki\
suppressWarnings();
552 $_lsExists = file_exists( "$IP/LocalSettings.php" );
553 MediaWiki\restoreWarnings
();
560 require "$IP/includes/DefaultSettings.php";
561 require "$IP/LocalSettings.php";
563 return get_defined_vars();
567 * Get a fake password for sending back to the user in HTML.
568 * This is a security mechanism to avoid compromise of the password in the
569 * event of session ID compromise.
571 * @param string $realPassword
575 public function getFakePassword( $realPassword ) {
576 return str_repeat( '*', strlen( $realPassword ) );
580 * Set a variable which stores a password, except if the new value is a
581 * fake password in which case leave it as it is.
583 * @param string $name
584 * @param mixed $value
586 public function setPassword( $name, $value ) {
587 if ( !preg_match( '/^\*+$/', $value ) ) {
588 $this->setVar( $name, $value );
593 * On POSIX systems return the primary group of the webserver we're running under.
594 * On other systems just returns null.
596 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
597 * webserver user before he can install.
599 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
603 public static function maybeGetWebserverPrimaryGroup() {
604 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
605 # I don't know this, this isn't UNIX.
609 # posix_getegid() *not* getmygid() because we want the group of the webserver,
610 # not whoever owns the current script.
611 $gid = posix_getegid();
612 $getpwuid = posix_getpwuid( $gid );
613 $group = $getpwuid['name'];
619 * Convert wikitext $text to HTML.
621 * This is potentially error prone since many parser features require a complete
622 * installed MW database. The solution is to just not use those features when you
623 * write your messages. This appears to work well enough. Basic formatting and
624 * external links work just fine.
626 * But in case a translator decides to throw in a "#ifexist" or internal link or
627 * whatever, this function is guarded to catch the attempted DB access and to present
628 * some fallback text.
630 * @param string $text
631 * @param bool $lineStart
634 public function parse( $text, $lineStart = false ) {
638 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
639 $html = $out->getText();
640 } catch ( DBAccessError
$e ) {
641 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
643 if ( !empty( $this->debug
) ) {
644 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
652 * @return ParserOptions
654 public function getParserOptions() {
655 return $this->parserOptions
;
658 public function disableLinkPopups() {
659 $this->parserOptions
->setExternalLinkTarget( false );
662 public function restoreLinkPopups() {
663 global $wgExternalLinkTarget;
664 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
668 * Install step which adds a row to the site_stats table with appropriate
671 * @param DatabaseInstaller $installer
675 public function populateSiteStats( DatabaseInstaller
$installer ) {
676 $status = $installer->getConnection();
677 if ( !$status->isOK() ) {
680 $status->value
->insert(
684 'ss_total_edits' => 0,
685 'ss_good_articles' => 0,
686 'ss_total_pages' => 0,
693 return Status
::newGood();
697 * Environment check for DB types.
700 protected function envCheckDB() {
705 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
706 // config-type-sqlite
707 foreach ( self
::getDBTypes() as $name ) {
708 $allNames[] = wfMessage( "config-type-$name" )->text();
711 $databases = $this->getCompiledDBs();
713 $databases = array_flip( $databases );
714 foreach ( array_keys( $databases ) as $db ) {
715 $installer = $this->getDBInstaller( $db );
716 $status = $installer->checkPrerequisites();
717 if ( !$status->isGood() ) {
718 $this->showStatusMessage( $status );
720 if ( !$status->isOK() ) {
721 unset( $databases[$db] );
724 $databases = array_flip( $databases );
726 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
728 // @todo FIXME: This only works for the web installer!
736 * Some versions of libxml+PHP break < and > encoding horribly
739 protected function envCheckBrokenXML() {
740 $test = new PhpXmlBugTester();
742 $this->showError( 'config-brokenlibxml' );
751 * Environment check for mbstring.func_overload.
754 protected function envCheckMbstring() {
755 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
756 $this->showError( 'config-mbstring' );
765 * Environment check for the XML module.
768 protected function envCheckXML() {
769 if ( !function_exists( "utf8_encode" ) ) {
770 $this->showError( 'config-xml-bad' );
779 * Environment check for the PCRE module.
781 * @note If this check were to fail, the parser would
782 * probably throw an exception before the result
783 * of this check is shown to the user.
786 protected function envCheckPCRE() {
787 MediaWiki\
suppressWarnings();
788 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
789 // Need to check for \p support too, as PCRE can be compiled
790 // with utf8 support, but not unicode property support.
791 // check that \p{Zs} (space separators) matches
792 // U+3000 (Ideographic space)
793 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
794 MediaWiki\restoreWarnings
();
795 if ( $regexd != '--' ||
$regexprop != '--' ) {
796 $this->showError( 'config-pcre-no-utf8' );
805 * Environment check for available memory.
808 protected function envCheckMemory() {
809 $limit = ini_get( 'memory_limit' );
811 if ( !$limit ||
$limit == -1 ) {
815 $n = wfShorthandToInteger( $limit );
817 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
818 $newLimit = "{$this->minMemorySize}M";
820 if ( ini_set( "memory_limit", $newLimit ) === false ) {
821 $this->showMessage( 'config-memory-bad', $limit );
823 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
824 $this->setVar( '_RaiseMemory', true );
832 * Environment check for compiled object cache types.
834 protected function envCheckCache() {
836 foreach ( $this->objectCaches
as $name => $function ) {
837 if ( function_exists( $function ) ) {
838 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
841 $caches[$name] = true;
846 $key = 'config-no-cache-apcu';
847 $this->showMessage( $key );
850 $this->setVar( '_Caches', $caches );
854 * Scare user to death if they have mod_security or mod_security2
857 protected function envCheckModSecurity() {
858 if ( self
::apacheModulePresent( 'mod_security' )
859 || self
::apacheModulePresent( 'mod_security2' ) ) {
860 $this->showMessage( 'config-mod-security' );
867 * Search for GNU diff3.
870 protected function envCheckDiff3() {
871 $names = [ "gdiff3", "diff3", "diff3.exe" ];
872 $versionInfo = [ '$1 --version 2>&1', 'GNU diffutils' ];
874 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
877 $this->setVar( 'wgDiff3', $diff3 );
879 $this->setVar( 'wgDiff3', false );
880 $this->showMessage( 'config-diff3-bad' );
887 * Environment check for ImageMagick and GD.
890 protected function envCheckGraphics() {
891 $names = [ wfIsWindows() ?
'convert.exe' : 'convert' ];
892 $versionInfo = [ '$1 -version', 'ImageMagick' ];
893 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
895 $this->setVar( 'wgImageMagickConvertCommand', '' );
897 $this->setVar( 'wgImageMagickConvertCommand', $convert );
898 $this->showMessage( 'config-imagemagick', $convert );
901 } elseif ( function_exists( 'imagejpeg' ) ) {
902 $this->showMessage( 'config-gd' );
904 $this->showMessage( 'config-no-scaling' );
916 protected function envCheckGit() {
917 $names = [ wfIsWindows() ?
'git.exe' : 'git' ];
918 $versionInfo = [ '$1 --version', 'git version' ];
920 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
923 $this->setVar( 'wgGitBin', $git );
924 $this->showMessage( 'config-git', $git );
926 $this->setVar( 'wgGitBin', false );
927 $this->showMessage( 'config-git-bad' );
934 * Environment check to inform user which server we've assumed.
938 protected function envCheckServer() {
939 $server = $this->envGetDefaultServer();
940 if ( $server !== null ) {
941 $this->showMessage( 'config-using-server', $server );
947 * Environment check to inform user which paths we've assumed.
951 protected function envCheckPath() {
954 $this->getVar( 'wgServer' ),
955 $this->getVar( 'wgScriptPath' )
961 * Environment check for preferred locale in shell
964 protected function envCheckShellLocale() {
965 $os = php_uname( 's' );
966 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
968 if ( !in_array( $os, $supported ) ) {
972 # Get a list of available locales.
974 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
980 $lines = array_map( 'trim', explode( "\n", $lines ) );
981 $candidatesByLocale = [];
982 $candidatesByLang = [];
984 foreach ( $lines as $line ) {
985 if ( $line === '' ) {
989 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
993 list( , $lang, , , ) = $m;
995 $candidatesByLocale[$m[0]] = $m;
996 $candidatesByLang[$lang][] = $m;
999 # Try the current value of LANG.
1000 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1001 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1006 # Try the most common ones.
1007 $commonLocales = [ 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1008 foreach ( $commonLocales as $commonLocale ) {
1009 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1010 $this->setVar( 'wgShellLocale', $commonLocale );
1016 # Is there an available locale in the Wiki's language?
1017 $wikiLang = $this->getVar( 'wgLanguageCode' );
1019 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1020 $m = reset( $candidatesByLang[$wikiLang] );
1021 $this->setVar( 'wgShellLocale', $m[0] );
1026 # Are there any at all?
1027 if ( count( $candidatesByLocale ) ) {
1028 $m = reset( $candidatesByLocale );
1029 $this->setVar( 'wgShellLocale', $m[0] );
1039 * Environment check for the permissions of the uploads directory
1042 protected function envCheckUploadsDirectory() {
1045 $dir = $IP . '/images/';
1046 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1047 $safe = !$this->dirIsExecutable( $dir, $url );
1050 $this->showMessage( 'config-uploads-not-safe', $dir );
1057 * Checks if suhosin.get.max_value_length is set, and if so generate
1058 * a warning because it decreases ResourceLoader performance.
1061 protected function envCheckSuhosinMaxValueLength() {
1062 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1063 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1064 // Only warn if the value is below the sane 1024
1065 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1072 * Convert a hex string representing a Unicode code point to that code point.
1076 protected function unicodeChar( $c ) {
1080 } elseif ( $c <= 0x7FF ) {
1081 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1082 } elseif ( $c <= 0xFFFF ) {
1083 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F ) .
1084 chr( 0x80 |
$c & 0x3F );
1085 } elseif ( $c <= 0x10FFFF ) {
1086 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F ) .
1087 chr( 0x80 |
$c >> 6 & 0x3F ) .
1088 chr( 0x80 |
$c & 0x3F );
1095 * Check the libicu version
1097 protected function envCheckLibicu() {
1099 * This needs to be updated something that the latest libicu
1100 * will properly normalize. This normalization was found at
1101 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1102 * Note that we use the hex representation to create the code
1103 * points in order to avoid any Unicode-destroying during transit.
1105 $not_normal_c = $this->unicodeChar( "FA6C" );
1106 $normal_c = $this->unicodeChar( "242EE" );
1108 $useNormalizer = 'php';
1109 $needsUpdate = false;
1111 if ( function_exists( 'normalizer_normalize' ) ) {
1112 $useNormalizer = 'intl';
1113 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1114 if ( $intl !== $normal_c ) {
1115 $needsUpdate = true;
1119 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1120 if ( $useNormalizer === 'php' ) {
1121 $this->showMessage( 'config-unicode-pure-php-warning' );
1123 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1124 if ( $needsUpdate ) {
1125 $this->showMessage( 'config-unicode-update-warning' );
1133 protected function envCheckCtype() {
1134 if ( !function_exists( 'ctype_digit' ) ) {
1135 $this->showError( 'config-ctype' );
1146 protected function envCheckIconv() {
1147 if ( !function_exists( 'iconv' ) ) {
1148 $this->showError( 'config-iconv' );
1159 protected function envCheckJSON() {
1160 if ( !function_exists( 'json_decode' ) ) {
1161 $this->showError( 'config-json' );
1170 * Environment prep for the server hostname.
1172 protected function envPrepServer() {
1173 $server = $this->envGetDefaultServer();
1174 if ( $server !== null ) {
1175 $this->setVar( 'wgServer', $server );
1180 * Helper function to be called from envPrepServer()
1183 abstract protected function envGetDefaultServer();
1186 * Environment prep for setting $IP and $wgScriptPath.
1188 protected function envPrepPath() {
1190 $IP = dirname( dirname( __DIR__
) );
1191 $this->setVar( 'IP', $IP );
1195 * Get an array of likely places we can find executables. Check a bunch
1196 * of known Unix-like defaults, as well as the PATH environment variable
1197 * (which should maybe make it work for Windows?)
1201 protected static function getPossibleBinPaths() {
1203 [ '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1204 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ],
1205 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1210 * Search a path for any of the given executable names. Returns the
1211 * executable name if found. Also checks the version string returned
1212 * by each executable.
1214 * Used only by environment checks.
1216 * @param string $path Path to search
1217 * @param array $names Array of executable names
1218 * @param array|bool $versionInfo False or array with two members:
1219 * 0 => Command to run for version check, with $1 for the full executable name
1220 * 1 => String to compare the output with
1222 * If $versionInfo is not false, only executables with a version
1223 * matching $versionInfo[1] will be returned.
1224 * @return bool|string
1226 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1227 if ( !is_array( $names ) ) {
1228 $names = [ $names ];
1231 foreach ( $names as $name ) {
1232 $command = $path . DIRECTORY_SEPARATOR
. $name;
1234 MediaWiki\
suppressWarnings();
1235 $file_exists = file_exists( $command );
1236 MediaWiki\restoreWarnings
();
1238 if ( $file_exists ) {
1239 if ( !$versionInfo ) {
1243 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1244 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1254 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1255 * @see locateExecutable()
1256 * @param array $names Array of possible names.
1257 * @param array|bool $versionInfo Default: false or array with two members:
1258 * 0 => Command to run for version check, with $1 for the full executable name
1259 * 1 => String to compare the output with
1261 * If $versionInfo is not false, only executables with a version
1262 * matching $versionInfo[1] will be returned.
1263 * @return bool|string
1265 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1266 foreach ( self
::getPossibleBinPaths() as $path ) {
1267 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1268 if ( $exe !== false ) {
1277 * Checks if scripts located in the given directory can be executed via the given URL.
1279 * Used only by environment checks.
1280 * @param string $dir
1281 * @param string $url
1282 * @return bool|int|string
1284 public function dirIsExecutable( $dir, $url ) {
1287 "<?php echo 'ex' . 'ec';",
1288 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1292 // it would be good to check other popular languages here, but it'll be slow.
1294 MediaWiki\
suppressWarnings();
1296 foreach ( $scriptTypes as $ext => $contents ) {
1297 foreach ( $contents as $source ) {
1298 $file = 'exectest.' . $ext;
1300 if ( !file_put_contents( $dir . $file, $source ) ) {
1305 $text = Http
::get( $url . $file, [ 'timeout' => 3 ], __METHOD__
);
1306 } catch ( Exception
$e ) {
1307 // Http::get throws with allow_url_fopen = false and no curl extension.
1310 unlink( $dir . $file );
1312 if ( $text == 'exec' ) {
1313 MediaWiki\restoreWarnings
();
1320 MediaWiki\restoreWarnings
();
1326 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1328 * @param string $moduleName Name of module to check.
1331 public static function apacheModulePresent( $moduleName ) {
1332 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1335 // try it the hard way
1337 phpinfo( INFO_MODULES
);
1338 $info = ob_get_clean();
1340 return strpos( $info, $moduleName ) !== false;
1344 * ParserOptions are constructed before we determined the language, so fix it
1346 * @param Language $lang
1348 public function setParserLanguage( $lang ) {
1349 $this->parserOptions
->setTargetLanguage( $lang );
1350 $this->parserOptions
->setUserLang( $lang );
1354 * Overridden by WebInstaller to provide lastPage parameters.
1355 * @param string $page
1358 protected function getDocUrl( $page ) {
1359 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1363 * Finds extensions that follow the format /$directory/Name/Name.php,
1364 * and returns an array containing the value for 'Name' for each found extension.
1366 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1368 * @param string $directory Directory to search in
1371 public function findExtensions( $directory = 'extensions' ) {
1372 if ( $this->getVar( 'IP' ) === null ) {
1376 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1377 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1381 // extensions -> extension.json, skins -> skin.json
1382 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1384 $dh = opendir( $extDir );
1386 while ( ( $file = readdir( $dh ) ) !== false ) {
1387 if ( !is_dir( "$extDir/$file" ) ) {
1390 if ( file_exists( "$extDir/$file/$jsonFile" ) ||
file_exists( "$extDir/$file/$file.php" ) ) {
1395 natcasesort( $exts );
1401 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1402 * but will fall back to another if the default skin is missing and some other one is present
1405 * @param string[] $skinNames Names of installed skins.
1408 public function getDefaultSkin( array $skinNames ) {
1409 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1410 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1411 return $defaultSkin;
1413 return $skinNames[0];
1418 * Installs the auto-detected extensions.
1422 protected function includeExtensions() {
1424 $exts = $this->getVar( '_Extensions' );
1425 $IP = $this->getVar( 'IP' );
1428 * We need to include DefaultSettings before including extensions to avoid
1429 * warnings about unset variables. However, the only thing we really
1430 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1431 * if the extension has hidden hook registration in $wgExtensionFunctions,
1432 * but we're not opening that can of worms
1433 * @see https://phabricator.wikimedia.org/T28857
1435 global $wgAutoloadClasses;
1436 $wgAutoloadClasses = [];
1439 require "$IP/includes/DefaultSettings.php";
1441 foreach ( $exts as $e ) {
1442 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1443 $queue["$IP/extensions/$e/extension.json"] = 1;
1445 require_once "$IP/extensions/$e/$e.php";
1449 $registry = new ExtensionRegistry();
1450 $data = $registry->readFromQueue( $queue );
1451 $wgAutoloadClasses +
= $data['autoload'];
1453 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1454 $wgHooks['LoadExtensionSchemaUpdates'] : [];
1456 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1457 $hooksWeWant = array_merge_recursive(
1459 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1462 // Unset everyone else's hooks. Lord knows what someone might be doing
1463 // in ParserFirstCallInit (see bug 27171)
1464 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1466 return Status
::newGood();
1470 * Get an array of install steps. Should always be in the format of
1472 * 'name' => 'someuniquename',
1473 * 'callback' => array( $obj, 'method' ),
1475 * There must be a config-install-$name message defined per step, which will
1476 * be shown on install.
1478 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1481 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1482 $coreInstallSteps = [
1483 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1484 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1485 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1486 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1487 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1488 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1489 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1490 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1493 // Build the array of install steps starting from the core install list,
1494 // then adding any callbacks that wanted to attach after a given step
1495 foreach ( $coreInstallSteps as $step ) {
1496 $this->installSteps
[] = $step;
1497 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1498 $this->installSteps
= array_merge(
1499 $this->installSteps
,
1500 $this->extraInstallSteps
[$step['name']]
1505 // Prepend any steps that want to be at the beginning
1506 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1507 $this->installSteps
= array_merge(
1508 $this->extraInstallSteps
['BEGINNING'],
1513 // Extensions should always go first, chance to tie into hooks and such
1514 if ( count( $this->getVar( '_Extensions' ) ) ) {
1515 array_unshift( $this->installSteps
,
1516 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1518 $this->installSteps
[] = [
1519 'name' => 'extension-tables',
1520 'callback' => [ $installer, 'createExtensionTables' ]
1524 return $this->installSteps
;
1528 * Actually perform the installation.
1530 * @param callable $startCB A callback array for the beginning of each step
1531 * @param callable $endCB A callback array for the end of each step
1533 * @return array Array of Status objects
1535 public function performInstallation( $startCB, $endCB ) {
1536 $installResults = [];
1537 $installer = $this->getDBInstaller();
1538 $installer->preInstall();
1539 $steps = $this->getInstallSteps( $installer );
1540 foreach ( $steps as $stepObj ) {
1541 $name = $stepObj['name'];
1542 call_user_func_array( $startCB, [ $name ] );
1544 // Perform the callback step
1545 $status = call_user_func( $stepObj['callback'], $installer );
1547 // Output and save the results
1548 call_user_func( $endCB, $name, $status );
1549 $installResults[$name] = $status;
1551 // If we've hit some sort of fatal, we need to bail.
1552 // Callback already had a chance to do output above.
1553 if ( !$status->isOk() ) {
1557 if ( $status->isOk() ) {
1558 $this->setVar( '_InstallDone', true );
1561 return $installResults;
1565 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1569 public function generateKeys() {
1570 $keys = [ 'wgSecretKey' => 64 ];
1571 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1572 $keys['wgUpgradeKey'] = 16;
1575 return $this->doGenerateKeys( $keys );
1579 * Generate a secret value for variables using our CryptRand generator.
1580 * Produce a warning if the random source was insecure.
1582 * @param array $keys
1585 protected function doGenerateKeys( $keys ) {
1586 $status = Status
::newGood();
1589 foreach ( $keys as $name => $length ) {
1590 $secretKey = MWCryptRand
::generateHex( $length, true );
1591 if ( !MWCryptRand
::wasStrong() ) {
1595 $this->setVar( $name, $secretKey );
1599 $names = array_keys( $keys );
1600 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1602 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1609 * Create the first user account, grant it sysop and bureaucrat rights
1613 protected function createSysop() {
1614 $name = $this->getVar( '_AdminName' );
1615 $user = User
::newFromName( $name );
1618 // We should've validated this earlier anyway!
1619 return Status
::newFatal( 'config-admin-error-user', $name );
1622 if ( $user->idForName() == 0 ) {
1623 $user->addToDatabase();
1626 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1627 } catch ( PasswordError
$pwe ) {
1628 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1631 $user->addGroup( 'sysop' );
1632 $user->addGroup( 'bureaucrat' );
1633 if ( $this->getVar( '_AdminEmail' ) ) {
1634 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1636 $user->saveSettings();
1638 // Update user count
1639 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1640 $ssUpdate->doUpdate();
1642 $status = Status
::newGood();
1644 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1645 $this->subscribeToMediaWikiAnnounce( $status );
1654 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1656 'email' => $this->getVar( '_AdminEmail' ),
1661 // Mailman doesn't support as many languages as we do, so check to make
1662 // sure their selected language is available
1663 $myLang = $this->getVar( '_UserLang' );
1664 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1665 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1666 $params['language'] = $myLang;
1669 if ( MWHttpRequest
::canMakeRequests() ) {
1670 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1671 [ 'method' => 'POST', 'postData' => $params ], __METHOD__
)->execute();
1672 if ( !$res->isOK() ) {
1673 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1676 $s->warning( 'config-install-subscribe-notpossible' );
1681 * Insert Main Page with default content.
1683 * @param DatabaseInstaller $installer
1686 protected function createMainpage( DatabaseInstaller
$installer ) {
1687 $status = Status
::newGood();
1689 $page = WikiPage
::factory( Title
::newMainPage() );
1690 $content = new WikitextContent(
1691 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1692 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1695 $page->doEditContent( $content,
1699 User
::newFromName( 'MediaWiki default' )
1701 } catch ( Exception
$e ) {
1702 // using raw, because $wgShowExceptionDetails can not be set yet
1703 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1710 * Override the necessary bits of the config to run an installation.
1712 public static function overrideConfig() {
1713 // Use PHP's built-in session handling, since MediaWiki's
1714 // SessionHandler can't work before we have an object cache set up.
1715 define( 'MW_NO_SESSION_HANDLER', 1 );
1717 // Don't access the database
1718 $GLOBALS['wgUseDatabaseMessages'] = false;
1719 // Don't cache langconv tables
1720 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1722 $GLOBALS['wgShowExceptionDetails'] = true;
1723 // Don't break forms
1724 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1726 // Extended debugging
1727 $GLOBALS['wgShowSQLErrors'] = true;
1728 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1730 // Allow multiple ob_flush() calls
1731 $GLOBALS['wgDisableOutputCompression'] = true;
1733 // Use a sensible cookie prefix (not my_wiki)
1734 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1736 // Some of the environment checks make shell requests, remove limits
1737 $GLOBALS['wgMaxShellMemory'] = 0;
1739 // Override the default CookieSessionProvider with a dummy
1740 // implementation that won't stomp on PHP's cookies.
1741 $GLOBALS['wgSessionProviders'] = [
1743 'class' => 'InstallerSessionProvider',
1750 // Don't try to use any object cache for SessionManager either.
1751 $GLOBALS['wgSessionCacheType'] = CACHE_NONE
;
1755 * Add an installation step following the given step.
1757 * @param callable $callback A valid installation callback array, in this form:
1758 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1759 * @param string $findStep The step to find. Omit to put the step at the beginning
1761 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1762 $this->extraInstallSteps
[$findStep][] = $callback;
1766 * Disable the time limit for execution.
1767 * Some long-running pages (Install, Upgrade) will want to do this
1769 protected function disableTimeLimit() {
1770 MediaWiki\
suppressWarnings();
1771 set_time_limit( 0 );
1772 MediaWiki\restoreWarnings
();