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 $GLOBALS['wgObjectCaches'] = array(
374 CACHE_NONE
=> $emptyCache,
375 CACHE_DB
=> $emptyCache,
376 CACHE_ANYTHING
=> $emptyCache,
377 CACHE_MEMCACHED
=> $emptyCache,
380 // Load the installer's i18n.
381 $wgMessagesDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
383 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
384 $wgUser = User
::newFromId( 0 );
386 $this->settings
= $this->internalDefaults
;
388 foreach ( $this->defaultVarNames
as $var ) {
389 $this->settings
[$var] = $GLOBALS[$var];
392 $this->doEnvironmentPreps();
394 $this->compiledDBs
= array();
395 foreach ( self
::getDBTypes() as $type ) {
396 $installer = $this->getDBInstaller( $type );
398 if ( !$installer->isCompiled() ) {
401 $this->compiledDBs
[] = $type;
404 $this->parserTitle
= Title
::newFromText( 'Installer' );
405 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
406 $this->parserOptions
->setEditSection( false );
410 * Get a list of known DB types.
414 public static function getDBTypes() {
415 return self
::$dbTypes;
419 * Do initial checks of the PHP environment. Set variables according to
420 * the observed environment.
422 * It's possible that this may be called under the CLI SAPI, not the SAPI
423 * that the wiki will primarily run under. In that case, the subclass should
424 * initialise variables such as wgScriptPath, before calling this function.
426 * Under the web subclass, it can already be assumed that PHP 5+ is in use
427 * and that sessions are working.
431 public function doEnvironmentChecks() {
432 // Php version has already been checked by entry scripts
433 // Show message here for information purposes
435 $this->showMessage( 'config-env-hhvm', HHVM_VERSION
);
437 $this->showMessage( 'config-env-php', PHP_VERSION
);
441 // Must go here because an old version of PCRE can prevent other checks from completing
442 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
443 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
444 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
447 foreach ( $this->envChecks
as $check ) {
448 $status = $this->$check();
449 if ( $status === false ) {
455 $this->setVar( '_Environment', $good );
457 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
460 public function doEnvironmentPreps() {
461 foreach ( $this->envPreps
as $prep ) {
467 * Set a MW configuration variable, or internal installer configuration variable.
469 * @param string $name
470 * @param mixed $value
472 public function setVar( $name, $value ) {
473 $this->settings
[$name] = $value;
477 * Get an MW configuration variable, or internal installer configuration variable.
478 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
479 * Installer variables are typically prefixed by an underscore.
481 * @param string $name
482 * @param mixed $default
486 public function getVar( $name, $default = null ) {
487 if ( !isset( $this->settings
[$name] ) ) {
490 return $this->settings
[$name];
495 * Get a list of DBs supported by current PHP setup
499 public function getCompiledDBs() {
500 return $this->compiledDBs
;
504 * Get an instance of DatabaseInstaller for the specified DB type.
506 * @param mixed $type DB installer for which is needed, false to use default.
508 * @return DatabaseInstaller
510 public function getDBInstaller( $type = false ) {
512 $type = $this->getVar( 'wgDBtype' );
515 $type = strtolower( $type );
517 if ( !isset( $this->dbInstallers
[$type] ) ) {
518 $class = ucfirst( $type ) . 'Installer';
519 $this->dbInstallers
[$type] = new $class( $this );
522 return $this->dbInstallers
[$type];
526 * Determine if LocalSettings.php exists. If it does, return its variables.
530 public static function getExistingLocalSettings() {
533 // You might be wondering why this is here. Well if you don't do this
534 // then some poorly-formed extensions try to call their own classes
535 // after immediately registering them. We really need to get extension
536 // registration out of the global scope and into a real format.
537 // @see https://phabricator.wikimedia.org/T69440
538 global $wgAutoloadClasses;
539 $wgAutoloadClasses = array();
541 // @codingStandardsIgnoreStart
542 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
543 // Define the required globals here, to ensure, the functions can do it work correctly.
544 global $wgExtensionDirectory, $wgStyleDirectory;
545 // @codingStandardsIgnoreEnd
547 MediaWiki\
suppressWarnings();
548 $_lsExists = file_exists( "$IP/LocalSettings.php" );
549 MediaWiki\restoreWarnings
();
556 require "$IP/includes/DefaultSettings.php";
557 require "$IP/LocalSettings.php";
559 return get_defined_vars();
563 * Get a fake password for sending back to the user in HTML.
564 * This is a security mechanism to avoid compromise of the password in the
565 * event of session ID compromise.
567 * @param string $realPassword
571 public function getFakePassword( $realPassword ) {
572 return str_repeat( '*', strlen( $realPassword ) );
576 * Set a variable which stores a password, except if the new value is a
577 * fake password in which case leave it as it is.
579 * @param string $name
580 * @param mixed $value
582 public function setPassword( $name, $value ) {
583 if ( !preg_match( '/^\*+$/', $value ) ) {
584 $this->setVar( $name, $value );
589 * On POSIX systems return the primary group of the webserver we're running under.
590 * On other systems just returns null.
592 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
593 * webserver user before he can install.
595 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
599 public static function maybeGetWebserverPrimaryGroup() {
600 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
601 # I don't know this, this isn't UNIX.
605 # posix_getegid() *not* getmygid() because we want the group of the webserver,
606 # not whoever owns the current script.
607 $gid = posix_getegid();
608 $getpwuid = posix_getpwuid( $gid );
609 $group = $getpwuid['name'];
615 * Convert wikitext $text to HTML.
617 * This is potentially error prone since many parser features require a complete
618 * installed MW database. The solution is to just not use those features when you
619 * write your messages. This appears to work well enough. Basic formatting and
620 * external links work just fine.
622 * But in case a translator decides to throw in a "#ifexist" or internal link or
623 * whatever, this function is guarded to catch the attempted DB access and to present
624 * some fallback text.
626 * @param string $text
627 * @param bool $lineStart
630 public function parse( $text, $lineStart = false ) {
634 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
635 $html = $out->getText();
636 } catch ( DBAccessError
$e ) {
637 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
639 if ( !empty( $this->debug
) ) {
640 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
648 * @return ParserOptions
650 public function getParserOptions() {
651 return $this->parserOptions
;
654 public function disableLinkPopups() {
655 $this->parserOptions
->setExternalLinkTarget( false );
658 public function restoreLinkPopups() {
659 global $wgExternalLinkTarget;
660 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
664 * Install step which adds a row to the site_stats table with appropriate
667 * @param DatabaseInstaller $installer
671 public function populateSiteStats( DatabaseInstaller
$installer ) {
672 $status = $installer->getConnection();
673 if ( !$status->isOK() ) {
676 $status->value
->insert(
680 'ss_total_edits' => 0,
681 'ss_good_articles' => 0,
682 'ss_total_pages' => 0,
689 return Status
::newGood();
693 * Exports all wg* variables stored by the installer into global scope.
695 public function exportVars() {
696 foreach ( $this->settings
as $name => $value ) {
697 if ( substr( $name, 0, 2 ) == 'wg' ) {
698 $GLOBALS[$name] = $value;
704 * Environment check for DB types.
707 protected function envCheckDB() {
712 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
713 // config-type-sqlite
714 foreach ( self
::getDBTypes() as $name ) {
715 $allNames[] = wfMessage( "config-type-$name" )->text();
718 $databases = $this->getCompiledDBs();
720 $databases = array_flip( $databases );
721 foreach ( array_keys( $databases ) as $db ) {
722 $installer = $this->getDBInstaller( $db );
723 $status = $installer->checkPrerequisites();
724 if ( !$status->isGood() ) {
725 $this->showStatusMessage( $status );
727 if ( !$status->isOK() ) {
728 unset( $databases[$db] );
731 $databases = array_flip( $databases );
733 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
735 // @todo FIXME: This only works for the web installer!
743 * Environment check for register_globals.
744 * Prevent installation if enabled
747 protected function envCheckRegisterGlobals() {
748 if ( wfIniGetBool( 'register_globals' ) ) {
749 $this->showMessage( 'config-register-globals-error' );
757 * Some versions of libxml+PHP break < and > encoding horribly
760 protected function envCheckBrokenXML() {
761 $test = new PhpXmlBugTester();
763 $this->showError( 'config-brokenlibxml' );
772 * Environment check for magic_quotes_(gpc|runtime|sybase).
775 protected function envCheckMagicQuotes() {
777 foreach ( array( 'gpc', 'runtime', 'sybase' ) as $magicJunk ) {
778 if ( wfIniGetBool( "magic_quotes_$magicJunk" ) ) {
779 $this->showError( "config-magic-quotes-$magicJunk" );
788 * Environment check for mbstring.func_overload.
791 protected function envCheckMbstring() {
792 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
793 $this->showError( 'config-mbstring' );
802 * Environment check for safe_mode.
805 protected function envCheckSafeMode() {
806 if ( wfIniGetBool( 'safe_mode' ) ) {
807 $this->setVar( '_SafeMode', true );
808 $this->showMessage( 'config-safe-mode' );
815 * Environment check for the XML module.
818 protected function envCheckXML() {
819 if ( !function_exists( "utf8_encode" ) ) {
820 $this->showError( 'config-xml-bad' );
829 * Environment check for the PCRE module.
831 * @note If this check were to fail, the parser would
832 * probably throw an exception before the result
833 * of this check is shown to the user.
836 protected function envCheckPCRE() {
837 MediaWiki\
suppressWarnings();
838 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
839 // Need to check for \p support too, as PCRE can be compiled
840 // with utf8 support, but not unicode property support.
841 // check that \p{Zs} (space separators) matches
842 // U+3000 (Ideographic space)
843 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
844 MediaWiki\restoreWarnings
();
845 if ( $regexd != '--' ||
$regexprop != '--' ) {
846 $this->showError( 'config-pcre-no-utf8' );
855 * Environment check for available memory.
858 protected function envCheckMemory() {
859 $limit = ini_get( 'memory_limit' );
861 if ( !$limit ||
$limit == -1 ) {
865 $n = wfShorthandToInteger( $limit );
867 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
868 $newLimit = "{$this->minMemorySize}M";
870 if ( ini_set( "memory_limit", $newLimit ) === false ) {
871 $this->showMessage( 'config-memory-bad', $limit );
873 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
874 $this->setVar( '_RaiseMemory', true );
882 * Environment check for compiled object cache types.
884 protected function envCheckCache() {
886 foreach ( $this->objectCaches
as $name => $function ) {
887 if ( function_exists( $function ) ) {
888 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
891 $caches[$name] = true;
896 $this->showMessage( 'config-no-cache' );
899 $this->setVar( '_Caches', $caches );
903 * Scare user to death if they have mod_security or mod_security2
906 protected function envCheckModSecurity() {
907 if ( self
::apacheModulePresent( 'mod_security' )
908 || self
::apacheModulePresent( 'mod_security2' ) ) {
909 $this->showMessage( 'config-mod-security' );
916 * Search for GNU diff3.
919 protected function envCheckDiff3() {
920 $names = array( "gdiff3", "diff3", "diff3.exe" );
921 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
923 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
926 $this->setVar( 'wgDiff3', $diff3 );
928 $this->setVar( 'wgDiff3', false );
929 $this->showMessage( 'config-diff3-bad' );
936 * Environment check for ImageMagick and GD.
939 protected function envCheckGraphics() {
940 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
941 $versionInfo = array( '$1 -version', 'ImageMagick' );
942 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
944 $this->setVar( 'wgImageMagickConvertCommand', '' );
946 $this->setVar( 'wgImageMagickConvertCommand', $convert );
947 $this->showMessage( 'config-imagemagick', $convert );
950 } elseif ( function_exists( 'imagejpeg' ) ) {
951 $this->showMessage( 'config-gd' );
953 $this->showMessage( 'config-no-scaling' );
965 protected function envCheckGit() {
966 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
967 $versionInfo = array( '$1 --version', 'git version' );
969 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
972 $this->setVar( 'wgGitBin', $git );
973 $this->showMessage( 'config-git', $git );
975 $this->setVar( 'wgGitBin', false );
976 $this->showMessage( 'config-git-bad' );
983 * Environment check to inform user which server we've assumed.
987 protected function envCheckServer() {
988 $server = $this->envGetDefaultServer();
989 if ( $server !== null ) {
990 $this->showMessage( 'config-using-server', $server );
996 * Environment check to inform user which paths we've assumed.
1000 protected function envCheckPath() {
1003 $this->getVar( 'wgServer' ),
1004 $this->getVar( 'wgScriptPath' )
1010 * Environment check for preferred locale in shell
1013 protected function envCheckShellLocale() {
1014 $os = php_uname( 's' );
1015 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1017 if ( !in_array( $os, $supported ) ) {
1021 # Get a list of available locales.
1023 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1029 $lines = array_map( 'trim', explode( "\n", $lines ) );
1030 $candidatesByLocale = array();
1031 $candidatesByLang = array();
1033 foreach ( $lines as $line ) {
1034 if ( $line === '' ) {
1038 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1042 list( , $lang, , , ) = $m;
1044 $candidatesByLocale[$m[0]] = $m;
1045 $candidatesByLang[$lang][] = $m;
1048 # Try the current value of LANG.
1049 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1050 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1055 # Try the most common ones.
1056 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1057 foreach ( $commonLocales as $commonLocale ) {
1058 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1059 $this->setVar( 'wgShellLocale', $commonLocale );
1065 # Is there an available locale in the Wiki's language?
1066 $wikiLang = $this->getVar( 'wgLanguageCode' );
1068 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1069 $m = reset( $candidatesByLang[$wikiLang] );
1070 $this->setVar( 'wgShellLocale', $m[0] );
1075 # Are there any at all?
1076 if ( count( $candidatesByLocale ) ) {
1077 $m = reset( $candidatesByLocale );
1078 $this->setVar( 'wgShellLocale', $m[0] );
1088 * Environment check for the permissions of the uploads directory
1091 protected function envCheckUploadsDirectory() {
1094 $dir = $IP . '/images/';
1095 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1096 $safe = !$this->dirIsExecutable( $dir, $url );
1099 $this->showMessage( 'config-uploads-not-safe', $dir );
1106 * Checks if suhosin.get.max_value_length is set, and if so generate
1107 * a warning because it decreases ResourceLoader performance.
1110 protected function envCheckSuhosinMaxValueLength() {
1111 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1112 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1113 // Only warn if the value is below the sane 1024
1114 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1121 * Convert a hex string representing a Unicode code point to that code point.
1125 protected function unicodeChar( $c ) {
1129 } elseif ( $c <= 0x7FF ) {
1130 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1131 } elseif ( $c <= 0xFFFF ) {
1132 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F ) .
1133 chr( 0x80 |
$c & 0x3F );
1134 } elseif ( $c <= 0x10FFFF ) {
1135 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F ) .
1136 chr( 0x80 |
$c >> 6 & 0x3F ) .
1137 chr( 0x80 |
$c & 0x3F );
1144 * Check the libicu version
1146 protected function envCheckLibicu() {
1148 * This needs to be updated something that the latest libicu
1149 * will properly normalize. This normalization was found at
1150 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1151 * Note that we use the hex representation to create the code
1152 * points in order to avoid any Unicode-destroying during transit.
1154 $not_normal_c = $this->unicodeChar( "FA6C" );
1155 $normal_c = $this->unicodeChar( "242EE" );
1157 $useNormalizer = 'php';
1158 $needsUpdate = false;
1160 if ( function_exists( 'normalizer_normalize' ) ) {
1161 $useNormalizer = 'intl';
1162 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1163 if ( $intl !== $normal_c ) {
1164 $needsUpdate = true;
1168 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1169 if ( $useNormalizer === 'php' ) {
1170 $this->showMessage( 'config-unicode-pure-php-warning' );
1172 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1173 if ( $needsUpdate ) {
1174 $this->showMessage( 'config-unicode-update-warning' );
1182 protected function envCheckCtype() {
1183 if ( !function_exists( 'ctype_digit' ) ) {
1184 $this->showError( 'config-ctype' );
1195 protected function envCheckIconv() {
1196 if ( !function_exists( 'iconv' ) ) {
1197 $this->showError( 'config-iconv' );
1208 protected function envCheckJSON() {
1209 if ( !function_exists( 'json_decode' ) ) {
1210 $this->showError( 'config-json' );
1219 * Environment prep for the server hostname.
1221 protected function envPrepServer() {
1222 $server = $this->envGetDefaultServer();
1223 if ( $server !== null ) {
1224 $this->setVar( 'wgServer', $server );
1229 * Helper function to be called from envPrepServer()
1232 abstract protected function envGetDefaultServer();
1235 * Environment prep for setting $IP and $wgScriptPath.
1237 protected function envPrepPath() {
1239 $IP = dirname( dirname( __DIR__
) );
1240 $this->setVar( 'IP', $IP );
1244 * Get an array of likely places we can find executables. Check a bunch
1245 * of known Unix-like defaults, as well as the PATH environment variable
1246 * (which should maybe make it work for Windows?)
1250 protected static function getPossibleBinPaths() {
1252 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1253 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1254 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1259 * Search a path for any of the given executable names. Returns the
1260 * executable name if found. Also checks the version string returned
1261 * by each executable.
1263 * Used only by environment checks.
1265 * @param string $path Path to search
1266 * @param array $names Array of executable names
1267 * @param array|bool $versionInfo False or array with two members:
1268 * 0 => Command to run for version check, with $1 for the full executable name
1269 * 1 => String to compare the output with
1271 * If $versionInfo is not false, only executables with a version
1272 * matching $versionInfo[1] will be returned.
1273 * @return bool|string
1275 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1276 if ( !is_array( $names ) ) {
1277 $names = array( $names );
1280 foreach ( $names as $name ) {
1281 $command = $path . DIRECTORY_SEPARATOR
. $name;
1283 MediaWiki\
suppressWarnings();
1284 $file_exists = file_exists( $command );
1285 MediaWiki\restoreWarnings
();
1287 if ( $file_exists ) {
1288 if ( !$versionInfo ) {
1292 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1293 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1303 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1304 * @see locateExecutable()
1305 * @param array $names Array of possible names.
1306 * @param array|bool $versionInfo Default: false or array with two members:
1307 * 0 => Command to run for version check, with $1 for the full executable name
1308 * 1 => String to compare the output with
1310 * If $versionInfo is not false, only executables with a version
1311 * matching $versionInfo[1] will be returned.
1312 * @return bool|string
1314 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1315 foreach ( self
::getPossibleBinPaths() as $path ) {
1316 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1317 if ( $exe !== false ) {
1326 * Checks if scripts located in the given directory can be executed via the given URL.
1328 * Used only by environment checks.
1329 * @param string $dir
1330 * @param string $url
1331 * @return bool|int|string
1333 public function dirIsExecutable( $dir, $url ) {
1334 $scriptTypes = array(
1336 "<?php echo 'ex' . 'ec';",
1337 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1341 // it would be good to check other popular languages here, but it'll be slow.
1343 MediaWiki\
suppressWarnings();
1345 foreach ( $scriptTypes as $ext => $contents ) {
1346 foreach ( $contents as $source ) {
1347 $file = 'exectest.' . $ext;
1349 if ( !file_put_contents( $dir . $file, $source ) ) {
1354 $text = Http
::get( $url . $file, array( 'timeout' => 3 ), __METHOD__
);
1355 } catch ( Exception
$e ) {
1356 // Http::get throws with allow_url_fopen = false and no curl extension.
1359 unlink( $dir . $file );
1361 if ( $text == 'exec' ) {
1362 MediaWiki\restoreWarnings
();
1369 MediaWiki\restoreWarnings
();
1375 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1377 * @param string $moduleName Name of module to check.
1380 public static function apacheModulePresent( $moduleName ) {
1381 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1384 // try it the hard way
1386 phpinfo( INFO_MODULES
);
1387 $info = ob_get_clean();
1389 return strpos( $info, $moduleName ) !== false;
1393 * ParserOptions are constructed before we determined the language, so fix it
1395 * @param Language $lang
1397 public function setParserLanguage( $lang ) {
1398 $this->parserOptions
->setTargetLanguage( $lang );
1399 $this->parserOptions
->setUserLang( $lang );
1403 * Overridden by WebInstaller to provide lastPage parameters.
1404 * @param string $page
1407 protected function getDocUrl( $page ) {
1408 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1412 * Finds extensions that follow the format /$directory/Name/Name.php,
1413 * and returns an array containing the value for 'Name' for each found extension.
1415 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1417 * @param string $directory Directory to search in
1420 public function findExtensions( $directory = 'extensions' ) {
1421 if ( $this->getVar( 'IP' ) === null ) {
1425 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1426 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1430 // extensions -> extension.json, skins -> skin.json
1431 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1433 $dh = opendir( $extDir );
1435 while ( ( $file = readdir( $dh ) ) !== false ) {
1436 if ( !is_dir( "$extDir/$file" ) ) {
1439 if ( file_exists( "$extDir/$file/$jsonFile" ) ||
file_exists( "$extDir/$file/$file.php" ) ) {
1444 natcasesort( $exts );
1450 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1451 * but will fall back to another if the default skin is missing and some other one is present
1454 * @param string[] $skinNames Names of installed skins.
1457 public function getDefaultSkin( array $skinNames ) {
1458 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1459 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1460 return $defaultSkin;
1462 return $skinNames[0];
1467 * Installs the auto-detected extensions.
1471 protected function includeExtensions() {
1473 $exts = $this->getVar( '_Extensions' );
1474 $IP = $this->getVar( 'IP' );
1477 * We need to include DefaultSettings before including extensions to avoid
1478 * warnings about unset variables. However, the only thing we really
1479 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1480 * if the extension has hidden hook registration in $wgExtensionFunctions,
1481 * but we're not opening that can of worms
1482 * @see https://phabricator.wikimedia.org/T28857
1484 global $wgAutoloadClasses;
1485 $wgAutoloadClasses = array();
1488 require "$IP/includes/DefaultSettings.php";
1490 foreach ( $exts as $e ) {
1491 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1492 $queue["$IP/extensions/$e/extension.json"] = 1;
1494 require_once "$IP/extensions/$e/$e.php";
1498 $registry = new ExtensionRegistry();
1499 $data = $registry->readFromQueue( $queue );
1500 $wgAutoloadClasses +
= $data['autoload'];
1502 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1503 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1505 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1506 $hooksWeWant = array_merge_recursive(
1508 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1511 // Unset everyone else's hooks. Lord knows what someone might be doing
1512 // in ParserFirstCallInit (see bug 27171)
1513 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1515 return Status
::newGood();
1519 * Get an array of install steps. Should always be in the format of
1521 * 'name' => 'someuniquename',
1522 * 'callback' => array( $obj, 'method' ),
1524 * There must be a config-install-$name message defined per step, which will
1525 * be shown on install.
1527 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1530 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1531 $coreInstallSteps = array(
1532 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1533 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1534 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1535 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1536 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1537 array( 'name' => 'updates', 'callback' => array( $installer, 'insertUpdateKeys' ) ),
1538 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1539 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1542 // Build the array of install steps starting from the core install list,
1543 // then adding any callbacks that wanted to attach after a given step
1544 foreach ( $coreInstallSteps as $step ) {
1545 $this->installSteps
[] = $step;
1546 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1547 $this->installSteps
= array_merge(
1548 $this->installSteps
,
1549 $this->extraInstallSteps
[$step['name']]
1554 // Prepend any steps that want to be at the beginning
1555 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1556 $this->installSteps
= array_merge(
1557 $this->extraInstallSteps
['BEGINNING'],
1562 // Extensions should always go first, chance to tie into hooks and such
1563 if ( count( $this->getVar( '_Extensions' ) ) ) {
1564 array_unshift( $this->installSteps
,
1565 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1567 $this->installSteps
[] = array(
1568 'name' => 'extension-tables',
1569 'callback' => array( $installer, 'createExtensionTables' )
1573 return $this->installSteps
;
1577 * Actually perform the installation.
1579 * @param callable $startCB A callback array for the beginning of each step
1580 * @param callable $endCB A callback array for the end of each step
1582 * @return array Array of Status objects
1584 public function performInstallation( $startCB, $endCB ) {
1585 $installResults = array();
1586 $installer = $this->getDBInstaller();
1587 $installer->preInstall();
1588 $steps = $this->getInstallSteps( $installer );
1589 foreach ( $steps as $stepObj ) {
1590 $name = $stepObj['name'];
1591 call_user_func_array( $startCB, array( $name ) );
1593 // Perform the callback step
1594 $status = call_user_func( $stepObj['callback'], $installer );
1596 // Output and save the results
1597 call_user_func( $endCB, $name, $status );
1598 $installResults[$name] = $status;
1600 // If we've hit some sort of fatal, we need to bail.
1601 // Callback already had a chance to do output above.
1602 if ( !$status->isOk() ) {
1606 if ( $status->isOk() ) {
1607 $this->setVar( '_InstallDone', true );
1610 return $installResults;
1614 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1618 public function generateKeys() {
1619 $keys = array( 'wgSecretKey' => 64 );
1620 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1621 $keys['wgUpgradeKey'] = 16;
1624 return $this->doGenerateKeys( $keys );
1628 * Generate a secret value for variables using our CryptRand generator.
1629 * Produce a warning if the random source was insecure.
1631 * @param array $keys
1634 protected function doGenerateKeys( $keys ) {
1635 $status = Status
::newGood();
1638 foreach ( $keys as $name => $length ) {
1639 $secretKey = MWCryptRand
::generateHex( $length, true );
1640 if ( !MWCryptRand
::wasStrong() ) {
1644 $this->setVar( $name, $secretKey );
1648 $names = array_keys( $keys );
1649 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1651 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1658 * Create the first user account, grant it sysop and bureaucrat rights
1662 protected function createSysop() {
1663 $name = $this->getVar( '_AdminName' );
1664 $user = User
::newFromName( $name );
1667 // We should've validated this earlier anyway!
1668 return Status
::newFatal( 'config-admin-error-user', $name );
1671 if ( $user->idForName() == 0 ) {
1672 $user->addToDatabase();
1675 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1676 } catch ( PasswordError
$pwe ) {
1677 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1680 $user->addGroup( 'sysop' );
1681 $user->addGroup( 'bureaucrat' );
1682 if ( $this->getVar( '_AdminEmail' ) ) {
1683 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1685 $user->saveSettings();
1687 // Update user count
1688 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1689 $ssUpdate->doUpdate();
1691 $status = Status
::newGood();
1693 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1694 $this->subscribeToMediaWikiAnnounce( $status );
1703 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1705 'email' => $this->getVar( '_AdminEmail' ),
1710 // Mailman doesn't support as many languages as we do, so check to make
1711 // sure their selected language is available
1712 $myLang = $this->getVar( '_UserLang' );
1713 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1714 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1715 $params['language'] = $myLang;
1718 if ( MWHttpRequest
::canMakeRequests() ) {
1719 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1720 array( 'method' => 'POST', 'postData' => $params ), __METHOD__
)->execute();
1721 if ( !$res->isOK() ) {
1722 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1725 $s->warning( 'config-install-subscribe-notpossible' );
1730 * Insert Main Page with default content.
1732 * @param DatabaseInstaller $installer
1735 protected function createMainpage( DatabaseInstaller
$installer ) {
1736 $status = Status
::newGood();
1738 $page = WikiPage
::factory( Title
::newMainPage() );
1739 $content = new WikitextContent(
1740 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1741 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1744 $page->doEditContent( $content,
1748 User
::newFromName( 'MediaWiki default' )
1750 } catch ( Exception
$e ) {
1751 //using raw, because $wgShowExceptionDetails can not be set yet
1752 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1759 * Override the necessary bits of the config to run an installation.
1761 public static function overrideConfig() {
1762 define( 'MW_NO_SESSION', 1 );
1764 // Don't access the database
1765 $GLOBALS['wgUseDatabaseMessages'] = false;
1766 // Don't cache langconv tables
1767 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1769 $GLOBALS['wgShowExceptionDetails'] = true;
1770 // Don't break forms
1771 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1773 // Extended debugging
1774 $GLOBALS['wgShowSQLErrors'] = true;
1775 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1777 // Allow multiple ob_flush() calls
1778 $GLOBALS['wgDisableOutputCompression'] = true;
1780 // Use a sensible cookie prefix (not my_wiki)
1781 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1783 // Some of the environment checks make shell requests, remove limits
1784 $GLOBALS['wgMaxShellMemory'] = 0;
1788 * Add an installation step following the given step.
1790 * @param callable $callback A valid installation callback array, in this form:
1791 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1792 * @param string $findStep The step to find. Omit to put the step at the beginning
1794 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1795 $this->extraInstallSteps
[$findStep][] = $callback;
1799 * Disable the time limit for execution.
1800 * Some long-running pages (Install, Upgrade) will want to do this
1802 protected function disableTimeLimit() {
1803 MediaWiki\
suppressWarnings();
1804 set_time_limit( 0 );
1805 MediaWiki\restoreWarnings
();