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(
155 * MediaWiki configuration globals that will eventually be passed through
156 * to LocalSettings.php. The names only are given here, the defaults
157 * typically come from DefaultSettings.php.
161 protected $defaultVarNames = array(
173 'wgEmailAuthentication',
176 'wgImageMagickConvertCommand',
182 'wgDeletedDirectory',
186 'wgUseInstantCommons',
189 'wgResourceLoaderMaxQueryLength',
193 * Variables that are stored alongside globals, and are used for any
194 * configuration of the installation process aside from the MediaWiki
195 * configuration. Map of names to defaults.
199 protected $internalDefaults = array(
201 '_Environment' => false,
202 '_SafeMode' => false,
203 '_RaiseMemory' => false,
204 '_UpgradeDone' => false,
205 '_InstallDone' => false,
206 '_Caches' => array(),
207 '_InstallPassword' => '',
208 '_SameAccount' => true,
209 '_CreateDBAccount' => false,
210 '_NamespaceType' => 'site-name',
211 '_AdminName' => '', // will be set later, when the user selects language
212 '_AdminPassword' => '',
213 '_AdminPasswordConfirm' => '',
215 '_Subscribe' => false,
216 '_SkipOptional' => 'continue',
217 '_RightsProfile' => 'wiki',
218 '_LicenseCode' => 'none',
220 '_Extensions' => array(),
222 '_MemCachedServers' => '',
223 '_UpgradeKeySupplied' => false,
224 '_ExistingDBSettings' => false,
226 // $wgLogo is probably wrong (bug 48084); set something that will work.
227 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
228 'wgLogo' => '$wgScriptPath/resources/assets/wiki.png',
232 * The actual list of installation steps. This will be initialized by getInstallSteps()
236 private $installSteps = array();
239 * Extra steps for installation, for things like DatabaseInstallers to modify
243 protected $extraInstallSteps = array();
246 * Known object cache types and the functions used to test for their existence.
250 protected $objectCaches = array(
251 'xcache' => 'xcache_get',
252 'apc' => 'apc_fetch',
253 'wincache' => 'wincache_ucache_get'
257 * User rights profiles.
261 public $rightsProfiles = array(
264 '*' => array( 'edit' => false )
268 'createaccount' => false,
274 'createaccount' => false,
286 public $licenses = array(
288 'url' => 'http://creativecommons.org/licenses/by/3.0/',
289 'icon' => '{$wgResourceBasePath}/resources/assets/licenses/cc-by.png',
292 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
293 'icon' => '{$wgResourceBasePath}/resources/assets/licenses/cc-by-sa.png',
295 'cc-by-nc-sa' => array(
296 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
297 'icon' => '{$wgResourceBasePath}/resources/assets/licenses/cc-by-nc-sa.png',
300 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
301 'icon' => '{$wgResourceBasePath}/resources/assets/licenses/cc-0.png',
305 'icon' => '{$wgResourceBasePath}/resources/assets/licenses/public-domain.png',
308 'url' => 'http://www.gnu.org/copyleft/fdl.html',
309 'icon' => '{$wgResourceBasePath}/resources/assets/licenses/gnu-fdl.png',
316 'cc-choose' => array(
317 // Details will be filled in by the selector.
325 * URL to mediawiki-announce subscription
327 protected $mediaWikiAnnounceUrl =
328 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
331 * Supported language codes for Mailman
333 protected $mediaWikiAnnounceLanguages = array(
334 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
335 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
336 'sl', 'sr', 'sv', 'tr', 'uk'
340 * UI interface for displaying a short message
341 * The parameters are like parameters to wfMessage().
342 * The messages will be in wikitext format, which will be converted to an
343 * output format such as HTML or text before being sent to the user.
346 abstract public function showMessage( $msg /*, ... */ );
349 * Same as showMessage(), but for displaying errors
352 abstract public function showError( $msg /*, ... */ );
355 * Show a message to the installing user by using a Status object
356 * @param Status $status
358 abstract public function showStatusMessage( Status
$status );
361 * Constructor, always call this from child classes.
363 public function __construct() {
364 global $wgMessagesDirs, $wgUser;
366 // Disable the i18n cache
367 Language
::getLocalisationCache()->disableBackend();
368 // Disable LoadBalancer and wfGetDB etc.
369 LBFactory
::disableBackend();
371 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
372 // SqlBagOStuff will then throw since we just disabled wfGetDB)
373 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
374 ObjectCache
::clear();
375 $emptyCache = array( 'class' => 'EmptyBagOStuff' );
376 $GLOBALS['wgObjectCaches'] = array(
377 CACHE_NONE
=> $emptyCache,
378 CACHE_DB
=> $emptyCache,
379 CACHE_ANYTHING
=> $emptyCache,
380 CACHE_MEMCACHED
=> $emptyCache,
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 );
389 $this->settings
= $this->internalDefaults
;
391 foreach ( $this->defaultVarNames
as $var ) {
392 $this->settings
[$var] = $GLOBALS[$var];
395 $this->doEnvironmentPreps();
397 $this->compiledDBs
= array();
398 foreach ( self
::getDBTypes() as $type ) {
399 $installer = $this->getDBInstaller( $type );
401 if ( !$installer->isCompiled() ) {
404 $this->compiledDBs
[] = $type;
407 $this->parserTitle
= Title
::newFromText( 'Installer' );
408 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
409 $this->parserOptions
->setEditSection( false );
413 * Get a list of known DB types.
417 public static function getDBTypes() {
418 return self
::$dbTypes;
422 * Do initial checks of the PHP environment. Set variables according to
423 * the observed environment.
425 * It's possible that this may be called under the CLI SAPI, not the SAPI
426 * that the wiki will primarily run under. In that case, the subclass should
427 * initialise variables such as wgScriptPath, before calling this function.
429 * Under the web subclass, it can already be assumed that PHP 5+ is in use
430 * and that sessions are working.
434 public function doEnvironmentChecks() {
435 // Php version has already been checked by entry scripts
436 // Show message here for information purposes
438 $this->showMessage( 'config-env-hhvm', HHVM_VERSION
);
440 $this->showMessage( 'config-env-php', PHP_VERSION
);
444 // Must go here because an old version of PCRE can prevent other checks from completing
445 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
446 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
447 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
450 foreach ( $this->envChecks
as $check ) {
451 $status = $this->$check();
452 if ( $status === false ) {
458 $this->setVar( '_Environment', $good );
460 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
463 public function doEnvironmentPreps() {
464 foreach ( $this->envPreps
as $prep ) {
470 * Set a MW configuration variable, or internal installer configuration variable.
472 * @param string $name
473 * @param mixed $value
475 public function setVar( $name, $value ) {
476 $this->settings
[$name] = $value;
480 * Get an MW configuration variable, or internal installer configuration variable.
481 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
482 * Installer variables are typically prefixed by an underscore.
484 * @param string $name
485 * @param mixed $default
489 public function getVar( $name, $default = null ) {
490 if ( !isset( $this->settings
[$name] ) ) {
493 return $this->settings
[$name];
498 * Get a list of DBs supported by current PHP setup
502 public function getCompiledDBs() {
503 return $this->compiledDBs
;
507 * Get an instance of DatabaseInstaller for the specified DB type.
509 * @param mixed $type DB installer for which is needed, false to use default.
511 * @return DatabaseInstaller
513 public function getDBInstaller( $type = false ) {
515 $type = $this->getVar( 'wgDBtype' );
518 $type = strtolower( $type );
520 if ( !isset( $this->dbInstallers
[$type] ) ) {
521 $class = ucfirst( $type ) . 'Installer';
522 $this->dbInstallers
[$type] = new $class( $this );
525 return $this->dbInstallers
[$type];
529 * Determine if LocalSettings.php exists. If it does, return its variables.
533 public static function getExistingLocalSettings() {
536 // You might be wondering why this is here. Well if you don't do this
537 // then some poorly-formed extensions try to call their own classes
538 // after immediately registering them. We really need to get extension
539 // registration out of the global scope and into a real format.
540 // @see https://bugzilla.wikimedia.org/67440
541 global $wgAutoloadClasses;
542 $wgAutoloadClasses = array();
544 wfSuppressWarnings();
545 $_lsExists = file_exists( "$IP/LocalSettings.php" );
553 require "$IP/includes/DefaultSettings.php";
554 require "$IP/LocalSettings.php";
556 return get_defined_vars();
560 * Get a fake password for sending back to the user in HTML.
561 * This is a security mechanism to avoid compromise of the password in the
562 * event of session ID compromise.
564 * @param string $realPassword
568 public function getFakePassword( $realPassword ) {
569 return str_repeat( '*', strlen( $realPassword ) );
573 * Set a variable which stores a password, except if the new value is a
574 * fake password in which case leave it as it is.
576 * @param string $name
577 * @param mixed $value
579 public function setPassword( $name, $value ) {
580 if ( !preg_match( '/^\*+$/', $value ) ) {
581 $this->setVar( $name, $value );
586 * On POSIX systems return the primary group of the webserver we're running under.
587 * On other systems just returns null.
589 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
590 * webserver user before he can install.
592 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
596 public static function maybeGetWebserverPrimaryGroup() {
597 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
598 # I don't know this, this isn't UNIX.
602 # posix_getegid() *not* getmygid() because we want the group of the webserver,
603 # not whoever owns the current script.
604 $gid = posix_getegid();
605 $getpwuid = posix_getpwuid( $gid );
606 $group = $getpwuid['name'];
612 * Convert wikitext $text to HTML.
614 * This is potentially error prone since many parser features require a complete
615 * installed MW database. The solution is to just not use those features when you
616 * write your messages. This appears to work well enough. Basic formatting and
617 * external links work just fine.
619 * But in case a translator decides to throw in a "#ifexist" or internal link or
620 * whatever, this function is guarded to catch the attempted DB access and to present
621 * some fallback text.
623 * @param string $text
624 * @param bool $lineStart
627 public function parse( $text, $lineStart = false ) {
631 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
632 $html = $out->getText();
633 } catch ( DBAccessError
$e ) {
634 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
636 if ( !empty( $this->debug
) ) {
637 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
645 * @return ParserOptions
647 public function getParserOptions() {
648 return $this->parserOptions
;
651 public function disableLinkPopups() {
652 $this->parserOptions
->setExternalLinkTarget( false );
655 public function restoreLinkPopups() {
656 global $wgExternalLinkTarget;
657 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
661 * Install step which adds a row to the site_stats table with appropriate
664 * @param DatabaseInstaller $installer
668 public function populateSiteStats( DatabaseInstaller
$installer ) {
669 $status = $installer->getConnection();
670 if ( !$status->isOK() ) {
673 $status->value
->insert(
677 'ss_total_views' => 0,
678 'ss_total_edits' => 0,
679 'ss_good_articles' => 0,
680 'ss_total_pages' => 0,
687 return Status
::newGood();
691 * Exports all wg* variables stored by the installer into global scope.
693 public function exportVars() {
694 foreach ( $this->settings
as $name => $value ) {
695 if ( substr( $name, 0, 2 ) == 'wg' ) {
696 $GLOBALS[$name] = $value;
702 * Environment check for DB types.
705 protected function envCheckDB() {
710 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
711 // config-type-sqlite
712 foreach ( self
::getDBTypes() as $name ) {
713 $allNames[] = wfMessage( "config-type-$name" )->text();
716 $databases = $this->getCompiledDBs();
718 $databases = array_flip( $databases );
719 foreach ( array_keys( $databases ) as $db ) {
720 $installer = $this->getDBInstaller( $db );
721 $status = $installer->checkPrerequisites();
722 if ( !$status->isGood() ) {
723 $this->showStatusMessage( $status );
725 if ( !$status->isOK() ) {
726 unset( $databases[$db] );
729 $databases = array_flip( $databases );
731 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
733 // @todo FIXME: This only works for the web installer!
741 * Environment check for register_globals.
742 * Prevent installation if enabled
745 protected function envCheckRegisterGlobals() {
746 if ( wfIniGetBool( 'register_globals' ) ) {
747 $this->showMessage( 'config-register-globals-error' );
755 * Some versions of libxml+PHP break < and > encoding horribly
758 protected function envCheckBrokenXML() {
759 $test = new PhpXmlBugTester();
761 $this->showError( 'config-brokenlibxml' );
770 * Environment check for magic_quotes_(gpc|runtime|sybase).
773 protected function envCheckMagicQuotes() {
775 foreach ( array( 'gpc', 'runtime', 'sybase' ) as $magicJunk ) {
776 if ( wfIniGetBool( "magic_quotes_$magicJunk" ) ) {
777 $this->showError( "config-magic-quotes-$magicJunk" );
786 * Environment check for mbstring.func_overload.
789 protected function envCheckMbstring() {
790 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
791 $this->showError( 'config-mbstring' );
800 * Environment check for safe_mode.
803 protected function envCheckSafeMode() {
804 if ( wfIniGetBool( 'safe_mode' ) ) {
805 $this->setVar( '_SafeMode', true );
806 $this->showMessage( 'config-safe-mode' );
813 * Environment check for the XML module.
816 protected function envCheckXML() {
817 if ( !function_exists( "utf8_encode" ) ) {
818 $this->showError( 'config-xml-bad' );
827 * Environment check for the PCRE module.
829 * @note If this check were to fail, the parser would
830 * probably throw an exception before the result
831 * of this check is shown to the user.
834 protected function envCheckPCRE() {
835 wfSuppressWarnings();
836 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
837 // Need to check for \p support too, as PCRE can be compiled
838 // with utf8 support, but not unicode property support.
839 // check that \p{Zs} (space separators) matches
840 // U+3000 (Ideographic space)
841 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
843 if ( $regexd != '--' ||
$regexprop != '--' ) {
844 $this->showError( 'config-pcre-no-utf8' );
853 * Environment check for available memory.
856 protected function envCheckMemory() {
857 $limit = ini_get( 'memory_limit' );
859 if ( !$limit ||
$limit == -1 ) {
863 $n = wfShorthandToInteger( $limit );
865 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
866 $newLimit = "{$this->minMemorySize}M";
868 if ( ini_set( "memory_limit", $newLimit ) === false ) {
869 $this->showMessage( 'config-memory-bad', $limit );
871 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
872 $this->setVar( '_RaiseMemory', true );
880 * Environment check for compiled object cache types.
882 protected function envCheckCache() {
884 foreach ( $this->objectCaches
as $name => $function ) {
885 if ( function_exists( $function ) ) {
886 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
889 $caches[$name] = true;
894 $this->showMessage( 'config-no-cache' );
897 $this->setVar( '_Caches', $caches );
901 * Scare user to death if they have mod_security or mod_security2
904 protected function envCheckModSecurity() {
905 if ( self
::apacheModulePresent( 'mod_security' )
906 || self
::apacheModulePresent( 'mod_security2' ) ) {
907 $this->showMessage( 'config-mod-security' );
914 * Search for GNU diff3.
917 protected function envCheckDiff3() {
918 $names = array( "gdiff3", "diff3", "diff3.exe" );
919 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
921 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
924 $this->setVar( 'wgDiff3', $diff3 );
926 $this->setVar( 'wgDiff3', false );
927 $this->showMessage( 'config-diff3-bad' );
934 * Environment check for ImageMagick and GD.
937 protected function envCheckGraphics() {
938 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
939 $versionInfo = array( '$1 -version', 'ImageMagick' );
940 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
942 $this->setVar( 'wgImageMagickConvertCommand', '' );
944 $this->setVar( 'wgImageMagickConvertCommand', $convert );
945 $this->showMessage( 'config-imagemagick', $convert );
948 } elseif ( function_exists( 'imagejpeg' ) ) {
949 $this->showMessage( 'config-gd' );
951 $this->showMessage( 'config-no-scaling' );
963 protected function envCheckGit() {
964 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
965 $versionInfo = array( '$1 --version', 'git version' );
967 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
970 $this->setVar( 'wgGitBin', $git );
971 $this->showMessage( 'config-git', $git );
973 $this->setVar( 'wgGitBin', false );
974 $this->showMessage( 'config-git-bad' );
981 * Environment check to inform user which server we've assumed.
985 protected function envCheckServer() {
986 $server = $this->envGetDefaultServer();
987 if ( $server !== null ) {
988 $this->showMessage( 'config-using-server', $server );
994 * Environment check to inform user which paths we've assumed.
998 protected function envCheckPath() {
1001 $this->getVar( 'wgServer' ),
1002 $this->getVar( 'wgScriptPath' )
1008 * Environment check for preferred locale in shell
1011 protected function envCheckShellLocale() {
1012 $os = php_uname( 's' );
1013 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1015 if ( !in_array( $os, $supported ) ) {
1019 # Get a list of available locales.
1021 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1027 $lines = array_map( 'trim', explode( "\n", $lines ) );
1028 $candidatesByLocale = array();
1029 $candidatesByLang = array();
1031 foreach ( $lines as $line ) {
1032 if ( $line === '' ) {
1036 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1040 list( , $lang, , , ) = $m;
1042 $candidatesByLocale[$m[0]] = $m;
1043 $candidatesByLang[$lang][] = $m;
1046 # Try the current value of LANG.
1047 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1048 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1053 # Try the most common ones.
1054 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1055 foreach ( $commonLocales as $commonLocale ) {
1056 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1057 $this->setVar( 'wgShellLocale', $commonLocale );
1063 # Is there an available locale in the Wiki's language?
1064 $wikiLang = $this->getVar( 'wgLanguageCode' );
1066 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1067 $m = reset( $candidatesByLang[$wikiLang] );
1068 $this->setVar( 'wgShellLocale', $m[0] );
1073 # Are there any at all?
1074 if ( count( $candidatesByLocale ) ) {
1075 $m = reset( $candidatesByLocale );
1076 $this->setVar( 'wgShellLocale', $m[0] );
1086 * Environment check for the permissions of the uploads directory
1089 protected function envCheckUploadsDirectory() {
1092 $dir = $IP . '/images/';
1093 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1094 $safe = !$this->dirIsExecutable( $dir, $url );
1097 $this->showMessage( 'config-uploads-not-safe', $dir );
1104 * Checks if suhosin.get.max_value_length is set, and if so generate
1105 * a warning because it decreases ResourceLoader performance.
1108 protected function envCheckSuhosinMaxValueLength() {
1109 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1110 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1111 // Only warn if the value is below the sane 1024
1112 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1119 * Convert a hex string representing a Unicode code point to that code point.
1123 protected function unicodeChar( $c ) {
1127 } elseif ( $c <= 0x7FF ) {
1128 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1129 } elseif ( $c <= 0xFFFF ) {
1130 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1131 . chr( 0x80 |
$c & 0x3F );
1132 } elseif ( $c <= 0x10FFFF ) {
1133 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1134 . chr( 0x80 |
$c >> 6 & 0x3F )
1135 . chr( 0x80 |
$c & 0x3F );
1142 * Check the libicu version
1144 protected function envCheckLibicu() {
1145 $utf8 = function_exists( 'utf8_normalize' );
1146 $intl = function_exists( 'normalizer_normalize' );
1149 * This needs to be updated something that the latest libicu
1150 * will properly normalize. This normalization was found at
1151 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1152 * Note that we use the hex representation to create the code
1153 * points in order to avoid any Unicode-destroying during transit.
1155 $not_normal_c = $this->unicodeChar( "FA6C" );
1156 $normal_c = $this->unicodeChar( "242EE" );
1158 $useNormalizer = 'php';
1159 $needsUpdate = false;
1162 * We're going to prefer the pecl extension here unless
1163 * utf8_normalize is more up to date.
1166 $useNormalizer = 'utf8';
1167 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1168 if ( $utf8 !== $normal_c ) {
1169 $needsUpdate = true;
1173 $useNormalizer = 'intl';
1174 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1175 if ( $intl !== $normal_c ) {
1176 $needsUpdate = true;
1180 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1181 // 'config-unicode-using-intl'
1182 if ( $useNormalizer === 'php' ) {
1183 $this->showMessage( 'config-unicode-pure-php-warning' );
1185 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1186 if ( $needsUpdate ) {
1187 $this->showMessage( 'config-unicode-update-warning' );
1195 protected function envCheckCtype() {
1196 if ( !function_exists( 'ctype_digit' ) ) {
1197 $this->showError( 'config-ctype' );
1208 protected function envCheckIconv() {
1209 if ( !function_exists( 'iconv' ) ) {
1210 $this->showError( 'config-iconv' );
1221 protected function envCheckJSON() {
1222 if ( !function_exists( 'json_decode' ) ) {
1223 $this->showError( 'config-json' );
1232 * Environment prep for the server hostname.
1234 protected function envPrepServer() {
1235 $server = $this->envGetDefaultServer();
1236 if ( $server !== null ) {
1237 $this->setVar( 'wgServer', $server );
1242 * Helper function to be called from envPrepServer()
1245 abstract protected function envGetDefaultServer();
1248 * Environment prep for setting the preferred PHP file extension.
1250 protected function envPrepExtension() {
1251 // @todo FIXME: Detect this properly
1252 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1257 $this->setVar( 'wgScriptExtension', $ext );
1261 * Environment prep for setting $IP and $wgScriptPath.
1263 protected function envPrepPath() {
1265 $IP = dirname( dirname( __DIR__
) );
1266 $this->setVar( 'IP', $IP );
1270 * Get an array of likely places we can find executables. Check a bunch
1271 * of known Unix-like defaults, as well as the PATH environment variable
1272 * (which should maybe make it work for Windows?)
1276 protected static function getPossibleBinPaths() {
1278 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1279 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1280 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1285 * Search a path for any of the given executable names. Returns the
1286 * executable name if found. Also checks the version string returned
1287 * by each executable.
1289 * Used only by environment checks.
1291 * @param string $path Path to search
1292 * @param array $names Array of executable names
1293 * @param array|bool $versionInfo False or array with two members:
1294 * 0 => Command to run for version check, with $1 for the full executable name
1295 * 1 => String to compare the output with
1297 * If $versionInfo is not false, only executables with a version
1298 * matching $versionInfo[1] will be returned.
1299 * @return bool|string
1301 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1302 if ( !is_array( $names ) ) {
1303 $names = array( $names );
1306 foreach ( $names as $name ) {
1307 $command = $path . DIRECTORY_SEPARATOR
. $name;
1309 wfSuppressWarnings();
1310 $file_exists = file_exists( $command );
1311 wfRestoreWarnings();
1313 if ( $file_exists ) {
1314 if ( !$versionInfo ) {
1318 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1319 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1329 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1330 * @see locateExecutable()
1331 * @param array $names Array of possible names.
1332 * @param array|bool $versionInfo Default: false or array with two members:
1333 * 0 => Command to run for version check, with $1 for the full executable name
1334 * 1 => String to compare the output with
1336 * If $versionInfo is not false, only executables with a version
1337 * matching $versionInfo[1] will be returned.
1338 * @return bool|string
1340 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1341 foreach ( self
::getPossibleBinPaths() as $path ) {
1342 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1343 if ( $exe !== false ) {
1352 * Checks if scripts located in the given directory can be executed via the given URL.
1354 * Used only by environment checks.
1355 * @param string $dir
1356 * @param string $url
1357 * @return bool|int|string
1359 public function dirIsExecutable( $dir, $url ) {
1360 $scriptTypes = array(
1362 "<?php echo 'ex' . 'ec';",
1363 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1367 // it would be good to check other popular languages here, but it'll be slow.
1369 wfSuppressWarnings();
1371 foreach ( $scriptTypes as $ext => $contents ) {
1372 foreach ( $contents as $source ) {
1373 $file = 'exectest.' . $ext;
1375 if ( !file_put_contents( $dir . $file, $source ) ) {
1380 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1381 } catch ( MWException
$e ) {
1382 // Http::get throws with allow_url_fopen = false and no curl extension.
1385 unlink( $dir . $file );
1387 if ( $text == 'exec' ) {
1388 wfRestoreWarnings();
1395 wfRestoreWarnings();
1401 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1403 * @param string $moduleName Name of module to check.
1406 public static function apacheModulePresent( $moduleName ) {
1407 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1410 // try it the hard way
1412 phpinfo( INFO_MODULES
);
1413 $info = ob_get_clean();
1415 return strpos( $info, $moduleName ) !== false;
1419 * ParserOptions are constructed before we determined the language, so fix it
1421 * @param Language $lang
1423 public function setParserLanguage( $lang ) {
1424 $this->parserOptions
->setTargetLanguage( $lang );
1425 $this->parserOptions
->setUserLang( $lang );
1429 * Overridden by WebInstaller to provide lastPage parameters.
1430 * @param string $page
1433 protected function getDocUrl( $page ) {
1434 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1438 * Finds extensions that follow the format /$directory/Name/Name.php,
1439 * and returns an array containing the value for 'Name' for each found extension.
1441 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1443 * @param string $directory Directory to search in
1446 public function findExtensions( $directory = 'extensions' ) {
1447 if ( $this->getVar( 'IP' ) === null ) {
1451 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1452 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1456 $dh = opendir( $extDir );
1458 while ( ( $file = readdir( $dh ) ) !== false ) {
1459 if ( !is_dir( "$extDir/$file" ) ) {
1462 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1467 natcasesort( $exts );
1473 * Returns a default value to be used for $wgDefaultSkin: the preferred skin, if available among
1474 * the installed skins, or any other one otherwise.
1476 * @param string[] $skinNames Names of installed skins.
1479 public function getDefaultSkin( array $skinNames ) {
1480 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1481 if ( in_array( $defaultSkin, $skinNames ) ) {
1482 return $defaultSkin;
1484 return $skinNames[0];
1489 * Installs the auto-detected extensions.
1493 protected function includeExtensions() {
1495 $exts = $this->getVar( '_Extensions' );
1496 $IP = $this->getVar( 'IP' );
1499 * We need to include DefaultSettings before including extensions to avoid
1500 * warnings about unset variables. However, the only thing we really
1501 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1502 * if the extension has hidden hook registration in $wgExtensionFunctions,
1503 * but we're not opening that can of worms
1504 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1506 global $wgAutoloadClasses;
1507 $wgAutoloadClasses = array();
1509 require "$IP/includes/DefaultSettings.php";
1511 foreach ( $exts as $e ) {
1512 require_once "$IP/extensions/$e/$e.php";
1515 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1516 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1518 // Unset everyone else's hooks. Lord knows what someone might be doing
1519 // in ParserFirstCallInit (see bug 27171)
1520 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1522 return Status
::newGood();
1526 * Get an array of install steps. Should always be in the format of
1528 * 'name' => 'someuniquename',
1529 * 'callback' => array( $obj, 'method' ),
1531 * There must be a config-install-$name message defined per step, which will
1532 * be shown on install.
1534 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1537 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1538 $coreInstallSteps = array(
1539 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1540 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1541 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1542 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1543 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1544 array( 'name' => 'updates', 'callback' => array( $installer, 'insertUpdateKeys' ) ),
1545 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1546 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1549 // Build the array of install steps starting from the core install list,
1550 // then adding any callbacks that wanted to attach after a given step
1551 foreach ( $coreInstallSteps as $step ) {
1552 $this->installSteps
[] = $step;
1553 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1554 $this->installSteps
= array_merge(
1555 $this->installSteps
,
1556 $this->extraInstallSteps
[$step['name']]
1561 // Prepend any steps that want to be at the beginning
1562 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1563 $this->installSteps
= array_merge(
1564 $this->extraInstallSteps
['BEGINNING'],
1569 // Extensions should always go first, chance to tie into hooks and such
1570 if ( count( $this->getVar( '_Extensions' ) ) ) {
1571 array_unshift( $this->installSteps
,
1572 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1574 $this->installSteps
[] = array(
1575 'name' => 'extension-tables',
1576 'callback' => array( $installer, 'createExtensionTables' )
1580 return $this->installSteps
;
1584 * Actually perform the installation.
1586 * @param callable $startCB A callback array for the beginning of each step
1587 * @param callable $endCB A callback array for the end of each step
1589 * @return array Array of Status objects
1591 public function performInstallation( $startCB, $endCB ) {
1592 $installResults = array();
1593 $installer = $this->getDBInstaller();
1594 $installer->preInstall();
1595 $steps = $this->getInstallSteps( $installer );
1596 foreach ( $steps as $stepObj ) {
1597 $name = $stepObj['name'];
1598 call_user_func_array( $startCB, array( $name ) );
1600 // Perform the callback step
1601 $status = call_user_func( $stepObj['callback'], $installer );
1603 // Output and save the results
1604 call_user_func( $endCB, $name, $status );
1605 $installResults[$name] = $status;
1607 // If we've hit some sort of fatal, we need to bail.
1608 // Callback already had a chance to do output above.
1609 if ( !$status->isOk() ) {
1613 if ( $status->isOk() ) {
1614 $this->setVar( '_InstallDone', true );
1617 return $installResults;
1621 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1625 public function generateKeys() {
1626 $keys = array( 'wgSecretKey' => 64 );
1627 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1628 $keys['wgUpgradeKey'] = 16;
1631 return $this->doGenerateKeys( $keys );
1635 * Generate a secret value for variables using our CryptRand generator.
1636 * Produce a warning if the random source was insecure.
1638 * @param array $keys
1641 protected function doGenerateKeys( $keys ) {
1642 $status = Status
::newGood();
1645 foreach ( $keys as $name => $length ) {
1646 $secretKey = MWCryptRand
::generateHex( $length, true );
1647 if ( !MWCryptRand
::wasStrong() ) {
1651 $this->setVar( $name, $secretKey );
1655 $names = array_keys( $keys );
1656 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1658 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1665 * Create the first user account, grant it sysop and bureaucrat rights
1669 protected function createSysop() {
1670 $name = $this->getVar( '_AdminName' );
1671 $user = User
::newFromName( $name );
1674 // We should've validated this earlier anyway!
1675 return Status
::newFatal( 'config-admin-error-user', $name );
1678 if ( $user->idForName() == 0 ) {
1679 $user->addToDatabase();
1682 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1683 } catch ( PasswordError
$pwe ) {
1684 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1687 $user->addGroup( 'sysop' );
1688 $user->addGroup( 'bureaucrat' );
1689 if ( $this->getVar( '_AdminEmail' ) ) {
1690 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1692 $user->saveSettings();
1694 // Update user count
1695 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1696 $ssUpdate->doUpdate();
1698 $status = Status
::newGood();
1700 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1701 $this->subscribeToMediaWikiAnnounce( $status );
1710 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1712 'email' => $this->getVar( '_AdminEmail' ),
1717 // Mailman doesn't support as many languages as we do, so check to make
1718 // sure their selected language is available
1719 $myLang = $this->getVar( '_UserLang' );
1720 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1721 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1722 $params['language'] = $myLang;
1725 if ( MWHttpRequest
::canMakeRequests() ) {
1726 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1727 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1728 if ( !$res->isOK() ) {
1729 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1732 $s->warning( 'config-install-subscribe-notpossible' );
1737 * Insert Main Page with default content.
1739 * @param DatabaseInstaller $installer
1742 protected function createMainpage( DatabaseInstaller
$installer ) {
1743 $status = Status
::newGood();
1745 $page = WikiPage
::factory( Title
::newMainPage() );
1746 $content = new WikitextContent(
1747 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1748 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1751 $page->doEditContent( $content,
1755 User
::newFromName( 'MediaWiki default' )
1757 } catch ( MWException
$e ) {
1758 //using raw, because $wgShowExceptionDetails can not be set yet
1759 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1766 * Override the necessary bits of the config to run an installation.
1768 public static function overrideConfig() {
1769 define( 'MW_NO_SESSION', 1 );
1771 // Don't access the database
1772 $GLOBALS['wgUseDatabaseMessages'] = false;
1773 // Don't cache langconv tables
1774 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1776 $GLOBALS['wgShowExceptionDetails'] = true;
1777 // Don't break forms
1778 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1780 // Extended debugging
1781 $GLOBALS['wgShowSQLErrors'] = true;
1782 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1784 // Allow multiple ob_flush() calls
1785 $GLOBALS['wgDisableOutputCompression'] = true;
1787 // Use a sensible cookie prefix (not my_wiki)
1788 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1790 // Some of the environment checks make shell requests, remove limits
1791 $GLOBALS['wgMaxShellMemory'] = 0;
1795 * Add an installation step following the given step.
1797 * @param callable $callback A valid installation callback array, in this form:
1798 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1799 * @param string $findStep The step to find. Omit to put the step at the beginning
1801 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1802 $this->extraInstallSteps
[$findStep][] = $callback;
1806 * Disable the time limit for execution.
1807 * Some long-running pages (Install, Upgrade) will want to do this
1809 protected function disableTimeLimit() {
1810 wfSuppressWarnings();
1811 set_time_limit( 0 );
1812 wfRestoreWarnings();