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://bugzilla.wikimedia.org/67440
538 global $wgAutoloadClasses;
539 $wgAutoloadClasses = array();
541 wfSuppressWarnings();
542 $_lsExists = file_exists( "$IP/LocalSettings.php" );
550 require "$IP/includes/DefaultSettings.php";
551 require "$IP/LocalSettings.php";
553 return get_defined_vars();
557 * Get a fake password for sending back to the user in HTML.
558 * This is a security mechanism to avoid compromise of the password in the
559 * event of session ID compromise.
561 * @param string $realPassword
565 public function getFakePassword( $realPassword ) {
566 return str_repeat( '*', strlen( $realPassword ) );
570 * Set a variable which stores a password, except if the new value is a
571 * fake password in which case leave it as it is.
573 * @param string $name
574 * @param mixed $value
576 public function setPassword( $name, $value ) {
577 if ( !preg_match( '/^\*+$/', $value ) ) {
578 $this->setVar( $name, $value );
583 * On POSIX systems return the primary group of the webserver we're running under.
584 * On other systems just returns null.
586 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
587 * webserver user before he can install.
589 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
593 public static function maybeGetWebserverPrimaryGroup() {
594 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
595 # I don't know this, this isn't UNIX.
599 # posix_getegid() *not* getmygid() because we want the group of the webserver,
600 # not whoever owns the current script.
601 $gid = posix_getegid();
602 $getpwuid = posix_getpwuid( $gid );
603 $group = $getpwuid['name'];
609 * Convert wikitext $text to HTML.
611 * This is potentially error prone since many parser features require a complete
612 * installed MW database. The solution is to just not use those features when you
613 * write your messages. This appears to work well enough. Basic formatting and
614 * external links work just fine.
616 * But in case a translator decides to throw in a "#ifexist" or internal link or
617 * whatever, this function is guarded to catch the attempted DB access and to present
618 * some fallback text.
620 * @param string $text
621 * @param bool $lineStart
624 public function parse( $text, $lineStart = false ) {
628 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
629 $html = $out->getText();
630 } catch ( DBAccessError
$e ) {
631 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
633 if ( !empty( $this->debug
) ) {
634 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
642 * @return ParserOptions
644 public function getParserOptions() {
645 return $this->parserOptions
;
648 public function disableLinkPopups() {
649 $this->parserOptions
->setExternalLinkTarget( false );
652 public function restoreLinkPopups() {
653 global $wgExternalLinkTarget;
654 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
658 * Install step which adds a row to the site_stats table with appropriate
661 * @param DatabaseInstaller $installer
665 public function populateSiteStats( DatabaseInstaller
$installer ) {
666 $status = $installer->getConnection();
667 if ( !$status->isOK() ) {
670 $status->value
->insert(
674 'ss_total_edits' => 0,
675 'ss_good_articles' => 0,
676 'ss_total_pages' => 0,
683 return Status
::newGood();
687 * Exports all wg* variables stored by the installer into global scope.
689 public function exportVars() {
690 foreach ( $this->settings
as $name => $value ) {
691 if ( substr( $name, 0, 2 ) == 'wg' ) {
692 $GLOBALS[$name] = $value;
698 * Environment check for DB types.
701 protected function envCheckDB() {
706 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
707 // config-type-sqlite
708 foreach ( self
::getDBTypes() as $name ) {
709 $allNames[] = wfMessage( "config-type-$name" )->text();
712 $databases = $this->getCompiledDBs();
714 $databases = array_flip( $databases );
715 foreach ( array_keys( $databases ) as $db ) {
716 $installer = $this->getDBInstaller( $db );
717 $status = $installer->checkPrerequisites();
718 if ( !$status->isGood() ) {
719 $this->showStatusMessage( $status );
721 if ( !$status->isOK() ) {
722 unset( $databases[$db] );
725 $databases = array_flip( $databases );
727 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
729 // @todo FIXME: This only works for the web installer!
737 * Environment check for register_globals.
738 * Prevent installation if enabled
741 protected function envCheckRegisterGlobals() {
742 if ( wfIniGetBool( 'register_globals' ) ) {
743 $this->showMessage( 'config-register-globals-error' );
751 * Some versions of libxml+PHP break < and > encoding horribly
754 protected function envCheckBrokenXML() {
755 $test = new PhpXmlBugTester();
757 $this->showError( 'config-brokenlibxml' );
766 * Environment check for magic_quotes_(gpc|runtime|sybase).
769 protected function envCheckMagicQuotes() {
771 foreach ( array( 'gpc', 'runtime', 'sybase' ) as $magicJunk ) {
772 if ( wfIniGetBool( "magic_quotes_$magicJunk" ) ) {
773 $this->showError( "config-magic-quotes-$magicJunk" );
782 * Environment check for mbstring.func_overload.
785 protected function envCheckMbstring() {
786 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
787 $this->showError( 'config-mbstring' );
796 * Environment check for safe_mode.
799 protected function envCheckSafeMode() {
800 if ( wfIniGetBool( 'safe_mode' ) ) {
801 $this->setVar( '_SafeMode', true );
802 $this->showMessage( 'config-safe-mode' );
809 * Environment check for the XML module.
812 protected function envCheckXML() {
813 if ( !function_exists( "utf8_encode" ) ) {
814 $this->showError( 'config-xml-bad' );
823 * Environment check for the PCRE module.
825 * @note If this check were to fail, the parser would
826 * probably throw an exception before the result
827 * of this check is shown to the user.
830 protected function envCheckPCRE() {
831 wfSuppressWarnings();
832 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
833 // Need to check for \p support too, as PCRE can be compiled
834 // with utf8 support, but not unicode property support.
835 // check that \p{Zs} (space separators) matches
836 // U+3000 (Ideographic space)
837 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
839 if ( $regexd != '--' ||
$regexprop != '--' ) {
840 $this->showError( 'config-pcre-no-utf8' );
849 * Environment check for available memory.
852 protected function envCheckMemory() {
853 $limit = ini_get( 'memory_limit' );
855 if ( !$limit ||
$limit == -1 ) {
859 $n = wfShorthandToInteger( $limit );
861 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
862 $newLimit = "{$this->minMemorySize}M";
864 if ( ini_set( "memory_limit", $newLimit ) === false ) {
865 $this->showMessage( 'config-memory-bad', $limit );
867 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
868 $this->setVar( '_RaiseMemory', true );
876 * Environment check for compiled object cache types.
878 protected function envCheckCache() {
880 foreach ( $this->objectCaches
as $name => $function ) {
881 if ( function_exists( $function ) ) {
882 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
885 $caches[$name] = true;
890 $this->showMessage( 'config-no-cache' );
893 $this->setVar( '_Caches', $caches );
897 * Scare user to death if they have mod_security or mod_security2
900 protected function envCheckModSecurity() {
901 if ( self
::apacheModulePresent( 'mod_security' )
902 || self
::apacheModulePresent( 'mod_security2' ) ) {
903 $this->showMessage( 'config-mod-security' );
910 * Search for GNU diff3.
913 protected function envCheckDiff3() {
914 $names = array( "gdiff3", "diff3", "diff3.exe" );
915 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
917 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
920 $this->setVar( 'wgDiff3', $diff3 );
922 $this->setVar( 'wgDiff3', false );
923 $this->showMessage( 'config-diff3-bad' );
930 * Environment check for ImageMagick and GD.
933 protected function envCheckGraphics() {
934 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
935 $versionInfo = array( '$1 -version', 'ImageMagick' );
936 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
938 $this->setVar( 'wgImageMagickConvertCommand', '' );
940 $this->setVar( 'wgImageMagickConvertCommand', $convert );
941 $this->showMessage( 'config-imagemagick', $convert );
944 } elseif ( function_exists( 'imagejpeg' ) ) {
945 $this->showMessage( 'config-gd' );
947 $this->showMessage( 'config-no-scaling' );
959 protected function envCheckGit() {
960 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
961 $versionInfo = array( '$1 --version', 'git version' );
963 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
966 $this->setVar( 'wgGitBin', $git );
967 $this->showMessage( 'config-git', $git );
969 $this->setVar( 'wgGitBin', false );
970 $this->showMessage( 'config-git-bad' );
977 * Environment check to inform user which server we've assumed.
981 protected function envCheckServer() {
982 $server = $this->envGetDefaultServer();
983 if ( $server !== null ) {
984 $this->showMessage( 'config-using-server', $server );
990 * Environment check to inform user which paths we've assumed.
994 protected function envCheckPath() {
997 $this->getVar( 'wgServer' ),
998 $this->getVar( 'wgScriptPath' )
1004 * Environment check for preferred locale in shell
1007 protected function envCheckShellLocale() {
1008 $os = php_uname( 's' );
1009 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1011 if ( !in_array( $os, $supported ) ) {
1015 # Get a list of available locales.
1017 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1023 $lines = array_map( 'trim', explode( "\n", $lines ) );
1024 $candidatesByLocale = array();
1025 $candidatesByLang = array();
1027 foreach ( $lines as $line ) {
1028 if ( $line === '' ) {
1032 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1036 list( , $lang, , , ) = $m;
1038 $candidatesByLocale[$m[0]] = $m;
1039 $candidatesByLang[$lang][] = $m;
1042 # Try the current value of LANG.
1043 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1044 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1049 # Try the most common ones.
1050 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1051 foreach ( $commonLocales as $commonLocale ) {
1052 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1053 $this->setVar( 'wgShellLocale', $commonLocale );
1059 # Is there an available locale in the Wiki's language?
1060 $wikiLang = $this->getVar( 'wgLanguageCode' );
1062 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1063 $m = reset( $candidatesByLang[$wikiLang] );
1064 $this->setVar( 'wgShellLocale', $m[0] );
1069 # Are there any at all?
1070 if ( count( $candidatesByLocale ) ) {
1071 $m = reset( $candidatesByLocale );
1072 $this->setVar( 'wgShellLocale', $m[0] );
1082 * Environment check for the permissions of the uploads directory
1085 protected function envCheckUploadsDirectory() {
1088 $dir = $IP . '/images/';
1089 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1090 $safe = !$this->dirIsExecutable( $dir, $url );
1093 $this->showMessage( 'config-uploads-not-safe', $dir );
1100 * Checks if suhosin.get.max_value_length is set, and if so generate
1101 * a warning because it decreases ResourceLoader performance.
1104 protected function envCheckSuhosinMaxValueLength() {
1105 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1106 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1107 // Only warn if the value is below the sane 1024
1108 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1115 * Convert a hex string representing a Unicode code point to that code point.
1119 protected function unicodeChar( $c ) {
1123 } elseif ( $c <= 0x7FF ) {
1124 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1125 } elseif ( $c <= 0xFFFF ) {
1126 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1127 . chr( 0x80 |
$c & 0x3F );
1128 } elseif ( $c <= 0x10FFFF ) {
1129 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1130 . chr( 0x80 |
$c >> 6 & 0x3F )
1131 . chr( 0x80 |
$c & 0x3F );
1138 * Check the libicu version
1140 protected function envCheckLibicu() {
1142 * This needs to be updated something that the latest libicu
1143 * will properly normalize. This normalization was found at
1144 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1145 * Note that we use the hex representation to create the code
1146 * points in order to avoid any Unicode-destroying during transit.
1148 $not_normal_c = $this->unicodeChar( "FA6C" );
1149 $normal_c = $this->unicodeChar( "242EE" );
1151 $useNormalizer = 'php';
1152 $needsUpdate = false;
1154 if ( function_exists( 'normalizer_normalize' ) ) {
1155 $useNormalizer = 'intl';
1156 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1157 if ( $intl !== $normal_c ) {
1158 $needsUpdate = true;
1162 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1163 if ( $useNormalizer === 'php' ) {
1164 $this->showMessage( 'config-unicode-pure-php-warning' );
1166 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1167 if ( $needsUpdate ) {
1168 $this->showMessage( 'config-unicode-update-warning' );
1176 protected function envCheckCtype() {
1177 if ( !function_exists( 'ctype_digit' ) ) {
1178 $this->showError( 'config-ctype' );
1189 protected function envCheckIconv() {
1190 if ( !function_exists( 'iconv' ) ) {
1191 $this->showError( 'config-iconv' );
1202 protected function envCheckJSON() {
1203 if ( !function_exists( 'json_decode' ) ) {
1204 $this->showError( 'config-json' );
1213 * Environment prep for the server hostname.
1215 protected function envPrepServer() {
1216 $server = $this->envGetDefaultServer();
1217 if ( $server !== null ) {
1218 $this->setVar( 'wgServer', $server );
1223 * Helper function to be called from envPrepServer()
1226 abstract protected function envGetDefaultServer();
1229 * Environment prep for setting $IP and $wgScriptPath.
1231 protected function envPrepPath() {
1233 $IP = dirname( dirname( __DIR__
) );
1234 $this->setVar( 'IP', $IP );
1238 * Get an array of likely places we can find executables. Check a bunch
1239 * of known Unix-like defaults, as well as the PATH environment variable
1240 * (which should maybe make it work for Windows?)
1244 protected static function getPossibleBinPaths() {
1246 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1247 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1248 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1253 * Search a path for any of the given executable names. Returns the
1254 * executable name if found. Also checks the version string returned
1255 * by each executable.
1257 * Used only by environment checks.
1259 * @param string $path Path to search
1260 * @param array $names Array of executable names
1261 * @param array|bool $versionInfo False or array with two members:
1262 * 0 => Command to run for version check, with $1 for the full executable name
1263 * 1 => String to compare the output with
1265 * If $versionInfo is not false, only executables with a version
1266 * matching $versionInfo[1] will be returned.
1267 * @return bool|string
1269 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1270 if ( !is_array( $names ) ) {
1271 $names = array( $names );
1274 foreach ( $names as $name ) {
1275 $command = $path . DIRECTORY_SEPARATOR
. $name;
1277 wfSuppressWarnings();
1278 $file_exists = file_exists( $command );
1279 wfRestoreWarnings();
1281 if ( $file_exists ) {
1282 if ( !$versionInfo ) {
1286 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1287 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1297 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1298 * @see locateExecutable()
1299 * @param array $names Array of possible names.
1300 * @param array|bool $versionInfo Default: false or array with two members:
1301 * 0 => Command to run for version check, with $1 for the full executable name
1302 * 1 => String to compare the output with
1304 * If $versionInfo is not false, only executables with a version
1305 * matching $versionInfo[1] will be returned.
1306 * @return bool|string
1308 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1309 foreach ( self
::getPossibleBinPaths() as $path ) {
1310 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1311 if ( $exe !== false ) {
1320 * Checks if scripts located in the given directory can be executed via the given URL.
1322 * Used only by environment checks.
1323 * @param string $dir
1324 * @param string $url
1325 * @return bool|int|string
1327 public function dirIsExecutable( $dir, $url ) {
1328 $scriptTypes = array(
1330 "<?php echo 'ex' . 'ec';",
1331 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1335 // it would be good to check other popular languages here, but it'll be slow.
1337 wfSuppressWarnings();
1339 foreach ( $scriptTypes as $ext => $contents ) {
1340 foreach ( $contents as $source ) {
1341 $file = 'exectest.' . $ext;
1343 if ( !file_put_contents( $dir . $file, $source ) ) {
1348 $text = Http
::get( $url . $file, array( 'timeout' => 3 ), __METHOD__
);
1349 } catch ( Exception
$e ) {
1350 // Http::get throws with allow_url_fopen = false and no curl extension.
1353 unlink( $dir . $file );
1355 if ( $text == 'exec' ) {
1356 wfRestoreWarnings();
1363 wfRestoreWarnings();
1369 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1371 * @param string $moduleName Name of module to check.
1374 public static function apacheModulePresent( $moduleName ) {
1375 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1378 // try it the hard way
1380 phpinfo( INFO_MODULES
);
1381 $info = ob_get_clean();
1383 return strpos( $info, $moduleName ) !== false;
1387 * ParserOptions are constructed before we determined the language, so fix it
1389 * @param Language $lang
1391 public function setParserLanguage( $lang ) {
1392 $this->parserOptions
->setTargetLanguage( $lang );
1393 $this->parserOptions
->setUserLang( $lang );
1397 * Overridden by WebInstaller to provide lastPage parameters.
1398 * @param string $page
1401 protected function getDocUrl( $page ) {
1402 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1406 * Finds extensions that follow the format /$directory/Name/Name.php,
1407 * and returns an array containing the value for 'Name' for each found extension.
1409 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1411 * @param string $directory Directory to search in
1414 public function findExtensions( $directory = 'extensions' ) {
1415 if ( $this->getVar( 'IP' ) === null ) {
1419 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1420 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1424 // extensions -> extension.json, skins -> skin.json
1425 $jsonFile = substr( $directory, 0, strlen( $directory ) -1 ) . '.json';
1427 $dh = opendir( $extDir );
1429 while ( ( $file = readdir( $dh ) ) !== false ) {
1430 if ( !is_dir( "$extDir/$file" ) ) {
1433 if ( file_exists( "$extDir/$file/$jsonFile" ) ||
file_exists( "$extDir/$file/$file.php" ) ) {
1438 natcasesort( $exts );
1444 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1445 * but will fall back to another if the default skin is missing and some other one is present
1448 * @param string[] $skinNames Names of installed skins.
1451 public function getDefaultSkin( array $skinNames ) {
1452 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1453 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1454 return $defaultSkin;
1456 return $skinNames[0];
1461 * Installs the auto-detected extensions.
1465 protected function includeExtensions() {
1467 $exts = $this->getVar( '_Extensions' );
1468 $IP = $this->getVar( 'IP' );
1471 * We need to include DefaultSettings before including extensions to avoid
1472 * warnings about unset variables. However, the only thing we really
1473 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1474 * if the extension has hidden hook registration in $wgExtensionFunctions,
1475 * but we're not opening that can of worms
1476 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1478 global $wgAutoloadClasses;
1479 $wgAutoloadClasses = array();
1482 require "$IP/includes/DefaultSettings.php";
1484 foreach ( $exts as $e ) {
1485 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1486 $queue["$IP/extensions/$e/extension.json"] = 1;
1488 require_once "$IP/extensions/$e/$e.php";
1492 $registry = new ExtensionRegistry();
1493 $data = $registry->readFromQueue( $queue );
1494 $wgAutoloadClasses +
= $data['autoload'];
1496 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1497 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1499 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1500 $hooksWeWant = array_merge_recursive(
1502 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1505 // Unset everyone else's hooks. Lord knows what someone might be doing
1506 // in ParserFirstCallInit (see bug 27171)
1507 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1509 return Status
::newGood();
1513 * Get an array of install steps. Should always be in the format of
1515 * 'name' => 'someuniquename',
1516 * 'callback' => array( $obj, 'method' ),
1518 * There must be a config-install-$name message defined per step, which will
1519 * be shown on install.
1521 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1524 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1525 $coreInstallSteps = array(
1526 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1527 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1528 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1529 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1530 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1531 array( 'name' => 'updates', 'callback' => array( $installer, 'insertUpdateKeys' ) ),
1532 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1533 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1536 // Build the array of install steps starting from the core install list,
1537 // then adding any callbacks that wanted to attach after a given step
1538 foreach ( $coreInstallSteps as $step ) {
1539 $this->installSteps
[] = $step;
1540 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1541 $this->installSteps
= array_merge(
1542 $this->installSteps
,
1543 $this->extraInstallSteps
[$step['name']]
1548 // Prepend any steps that want to be at the beginning
1549 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1550 $this->installSteps
= array_merge(
1551 $this->extraInstallSteps
['BEGINNING'],
1556 // Extensions should always go first, chance to tie into hooks and such
1557 if ( count( $this->getVar( '_Extensions' ) ) ) {
1558 array_unshift( $this->installSteps
,
1559 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1561 $this->installSteps
[] = array(
1562 'name' => 'extension-tables',
1563 'callback' => array( $installer, 'createExtensionTables' )
1567 return $this->installSteps
;
1571 * Actually perform the installation.
1573 * @param callable $startCB A callback array for the beginning of each step
1574 * @param callable $endCB A callback array for the end of each step
1576 * @return array Array of Status objects
1578 public function performInstallation( $startCB, $endCB ) {
1579 $installResults = array();
1580 $installer = $this->getDBInstaller();
1581 $installer->preInstall();
1582 $steps = $this->getInstallSteps( $installer );
1583 foreach ( $steps as $stepObj ) {
1584 $name = $stepObj['name'];
1585 call_user_func_array( $startCB, array( $name ) );
1587 // Perform the callback step
1588 $status = call_user_func( $stepObj['callback'], $installer );
1590 // Output and save the results
1591 call_user_func( $endCB, $name, $status );
1592 $installResults[$name] = $status;
1594 // If we've hit some sort of fatal, we need to bail.
1595 // Callback already had a chance to do output above.
1596 if ( !$status->isOk() ) {
1600 if ( $status->isOk() ) {
1601 $this->setVar( '_InstallDone', true );
1604 return $installResults;
1608 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1612 public function generateKeys() {
1613 $keys = array( 'wgSecretKey' => 64 );
1614 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1615 $keys['wgUpgradeKey'] = 16;
1618 return $this->doGenerateKeys( $keys );
1622 * Generate a secret value for variables using our CryptRand generator.
1623 * Produce a warning if the random source was insecure.
1625 * @param array $keys
1628 protected function doGenerateKeys( $keys ) {
1629 $status = Status
::newGood();
1632 foreach ( $keys as $name => $length ) {
1633 $secretKey = MWCryptRand
::generateHex( $length, true );
1634 if ( !MWCryptRand
::wasStrong() ) {
1638 $this->setVar( $name, $secretKey );
1642 $names = array_keys( $keys );
1643 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1645 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1652 * Create the first user account, grant it sysop and bureaucrat rights
1656 protected function createSysop() {
1657 $name = $this->getVar( '_AdminName' );
1658 $user = User
::newFromName( $name );
1661 // We should've validated this earlier anyway!
1662 return Status
::newFatal( 'config-admin-error-user', $name );
1665 if ( $user->idForName() == 0 ) {
1666 $user->addToDatabase();
1669 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1670 } catch ( PasswordError
$pwe ) {
1671 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1674 $user->addGroup( 'sysop' );
1675 $user->addGroup( 'bureaucrat' );
1676 if ( $this->getVar( '_AdminEmail' ) ) {
1677 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1679 $user->saveSettings();
1681 // Update user count
1682 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1683 $ssUpdate->doUpdate();
1685 $status = Status
::newGood();
1687 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1688 $this->subscribeToMediaWikiAnnounce( $status );
1697 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1699 'email' => $this->getVar( '_AdminEmail' ),
1704 // Mailman doesn't support as many languages as we do, so check to make
1705 // sure their selected language is available
1706 $myLang = $this->getVar( '_UserLang' );
1707 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1708 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1709 $params['language'] = $myLang;
1712 if ( MWHttpRequest
::canMakeRequests() ) {
1713 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1714 array( 'method' => 'POST', 'postData' => $params ), __METHOD__
)->execute();
1715 if ( !$res->isOK() ) {
1716 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1719 $s->warning( 'config-install-subscribe-notpossible' );
1724 * Insert Main Page with default content.
1726 * @param DatabaseInstaller $installer
1729 protected function createMainpage( DatabaseInstaller
$installer ) {
1730 $status = Status
::newGood();
1732 $page = WikiPage
::factory( Title
::newMainPage() );
1733 $content = new WikitextContent(
1734 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1735 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1738 $page->doEditContent( $content,
1742 User
::newFromName( 'MediaWiki default' )
1744 } catch ( Exception
$e ) {
1745 //using raw, because $wgShowExceptionDetails can not be set yet
1746 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1753 * Override the necessary bits of the config to run an installation.
1755 public static function overrideConfig() {
1756 define( 'MW_NO_SESSION', 1 );
1758 // Don't access the database
1759 $GLOBALS['wgUseDatabaseMessages'] = false;
1760 // Don't cache langconv tables
1761 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1763 $GLOBALS['wgShowExceptionDetails'] = true;
1764 // Don't break forms
1765 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1767 // Extended debugging
1768 $GLOBALS['wgShowSQLErrors'] = true;
1769 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1771 // Allow multiple ob_flush() calls
1772 $GLOBALS['wgDisableOutputCompression'] = true;
1774 // Use a sensible cookie prefix (not my_wiki)
1775 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1777 // Some of the environment checks make shell requests, remove limits
1778 $GLOBALS['wgMaxShellMemory'] = 0;
1782 * Add an installation step following the given step.
1784 * @param callable $callback A valid installation callback array, in this form:
1785 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1786 * @param string $findStep The step to find. Omit to put the step at the beginning
1788 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1789 $this->extraInstallSteps
[$findStep][] = $callback;
1793 * Disable the time limit for execution.
1794 * Some long-running pages (Install, Upgrade) will want to do this
1796 protected function disableTimeLimit() {
1797 wfSuppressWarnings();
1798 set_time_limit( 0 );
1799 wfRestoreWarnings();