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' => '$wgStylePath/common/images/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' => '{$wgStylePath}/common/images/cc-by.png',
292 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
293 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
295 'cc-by-nc-sa' => array(
296 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
297 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
300 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
301 'icon' => '{$wgStylePath}/common/images/cc-0.png',
305 'icon' => '{$wgStylePath}/common/images/public-domain.png',
308 'url' => 'http://www.gnu.org/copyleft/fdl.html',
309 'icon' => '{$wgStylePath}/common/images/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;
543 wfSuppressWarnings();
544 $_lsExists = file_exists( "$IP/LocalSettings.php" );
552 require "$IP/includes/DefaultSettings.php";
553 require "$IP/LocalSettings.php";
555 return get_defined_vars();
559 * Get a fake password for sending back to the user in HTML.
560 * This is a security mechanism to avoid compromise of the password in the
561 * event of session ID compromise.
563 * @param string $realPassword
567 public function getFakePassword( $realPassword ) {
568 return str_repeat( '*', strlen( $realPassword ) );
572 * Set a variable which stores a password, except if the new value is a
573 * fake password in which case leave it as it is.
575 * @param string $name
576 * @param mixed $value
578 public function setPassword( $name, $value ) {
579 if ( !preg_match( '/^\*+$/', $value ) ) {
580 $this->setVar( $name, $value );
585 * On POSIX systems return the primary group of the webserver we're running under.
586 * On other systems just returns null.
588 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
589 * webserver user before he can install.
591 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
595 public static function maybeGetWebserverPrimaryGroup() {
596 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
597 # I don't know this, this isn't UNIX.
601 # posix_getegid() *not* getmygid() because we want the group of the webserver,
602 # not whoever owns the current script.
603 $gid = posix_getegid();
604 $getpwuid = posix_getpwuid( $gid );
605 $group = $getpwuid['name'];
611 * Convert wikitext $text to HTML.
613 * This is potentially error prone since many parser features require a complete
614 * installed MW database. The solution is to just not use those features when you
615 * write your messages. This appears to work well enough. Basic formatting and
616 * external links work just fine.
618 * But in case a translator decides to throw in a "#ifexist" or internal link or
619 * whatever, this function is guarded to catch the attempted DB access and to present
620 * some fallback text.
622 * @param string $text
623 * @param bool $lineStart
626 public function parse( $text, $lineStart = false ) {
630 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
631 $html = $out->getText();
632 } catch ( DBAccessError
$e ) {
633 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
635 if ( !empty( $this->debug
) ) {
636 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
644 * @return ParserOptions
646 public function getParserOptions() {
647 return $this->parserOptions
;
650 public function disableLinkPopups() {
651 $this->parserOptions
->setExternalLinkTarget( false );
654 public function restoreLinkPopups() {
655 global $wgExternalLinkTarget;
656 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
660 * Install step which adds a row to the site_stats table with appropriate
663 * @param DatabaseInstaller $installer
667 public function populateSiteStats( DatabaseInstaller
$installer ) {
668 $status = $installer->getConnection();
669 if ( !$status->isOK() ) {
672 $status->value
->insert(
676 'ss_total_views' => 0,
677 'ss_total_edits' => 0,
678 'ss_good_articles' => 0,
679 'ss_total_pages' => 0,
686 return Status
::newGood();
690 * Exports all wg* variables stored by the installer into global scope.
692 public function exportVars() {
693 foreach ( $this->settings
as $name => $value ) {
694 if ( substr( $name, 0, 2 ) == 'wg' ) {
695 $GLOBALS[$name] = $value;
701 * Environment check for DB types.
704 protected function envCheckDB() {
709 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
710 // config-type-sqlite
711 foreach ( self
::getDBTypes() as $name ) {
712 $allNames[] = wfMessage( "config-type-$name" )->text();
715 $databases = $this->getCompiledDBs();
717 $databases = array_flip( $databases );
718 foreach ( array_keys( $databases ) as $db ) {
719 $installer = $this->getDBInstaller( $db );
720 $status = $installer->checkPrerequisites();
721 if ( !$status->isGood() ) {
722 $this->showStatusMessage( $status );
724 if ( !$status->isOK() ) {
725 unset( $databases[$db] );
728 $databases = array_flip( $databases );
730 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
732 // @todo FIXME: This only works for the web installer!
740 * Environment check for register_globals.
741 * Prevent installation if enabled
743 protected function envCheckRegisterGlobals() {
744 if ( wfIniGetBool( 'register_globals' ) ) {
745 $this->showMessage( 'config-register-globals-error' );
753 * Some versions of libxml+PHP break < and > encoding horribly
756 protected function envCheckBrokenXML() {
757 $test = new PhpXmlBugTester();
759 $this->showError( 'config-brokenlibxml' );
768 * Environment check for magic_quotes_(gpc|runtime|sybase).
771 protected function envCheckMagicQuotes() {
773 foreach ( array( 'gpc', 'runtime', 'sybase' ) as $magicJunk ) {
774 if ( wfIniGetBool( "magic_quotes_$magicJunk" ) ) {
775 $this->showError( "config-magic-quotes-$magicJunk" );
784 * Environment check for mbstring.func_overload.
787 protected function envCheckMbstring() {
788 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
789 $this->showError( 'config-mbstring' );
798 * Environment check for safe_mode.
801 protected function envCheckSafeMode() {
802 if ( wfIniGetBool( 'safe_mode' ) ) {
803 $this->setVar( '_SafeMode', true );
804 $this->showMessage( 'config-safe-mode' );
811 * Environment check for the XML module.
814 protected function envCheckXML() {
815 if ( !function_exists( "utf8_encode" ) ) {
816 $this->showError( 'config-xml-bad' );
825 * Environment check for the PCRE module.
827 * @note If this check were to fail, the parser would
828 * probably throw an exception before the result
829 * of this check is shown to the user.
832 protected function envCheckPCRE() {
833 wfSuppressWarnings();
834 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
835 // Need to check for \p support too, as PCRE can be compiled
836 // with utf8 support, but not unicode property support.
837 // check that \p{Zs} (space separators) matches
838 // U+3000 (Ideographic space)
839 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
841 if ( $regexd != '--' ||
$regexprop != '--' ) {
842 $this->showError( 'config-pcre-no-utf8' );
851 * Environment check for available memory.
854 protected function envCheckMemory() {
855 $limit = ini_get( 'memory_limit' );
857 if ( !$limit ||
$limit == -1 ) {
861 $n = wfShorthandToInteger( $limit );
863 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
864 $newLimit = "{$this->minMemorySize}M";
866 if ( ini_set( "memory_limit", $newLimit ) === false ) {
867 $this->showMessage( 'config-memory-bad', $limit );
869 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
870 $this->setVar( '_RaiseMemory', true );
878 * Environment check for compiled object cache types.
880 protected function envCheckCache() {
882 foreach ( $this->objectCaches
as $name => $function ) {
883 if ( function_exists( $function ) ) {
884 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
887 $caches[$name] = true;
892 $this->showMessage( 'config-no-cache' );
895 $this->setVar( '_Caches', $caches );
899 * Scare user to death if they have mod_security
902 protected function envCheckModSecurity() {
903 if ( self
::apacheModulePresent( 'mod_security' ) ) {
904 $this->showMessage( 'config-mod-security' );
911 * Search for GNU diff3.
914 protected function envCheckDiff3() {
915 $names = array( "gdiff3", "diff3", "diff3.exe" );
916 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
918 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
921 $this->setVar( 'wgDiff3', $diff3 );
923 $this->setVar( 'wgDiff3', false );
924 $this->showMessage( 'config-diff3-bad' );
931 * Environment check for ImageMagick and GD.
934 protected function envCheckGraphics() {
935 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
936 $versionInfo = array( '$1 -version', 'ImageMagick' );
937 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
939 $this->setVar( 'wgImageMagickConvertCommand', '' );
941 $this->setVar( 'wgImageMagickConvertCommand', $convert );
942 $this->showMessage( 'config-imagemagick', $convert );
945 } elseif ( function_exists( 'imagejpeg' ) ) {
946 $this->showMessage( 'config-gd' );
948 $this->showMessage( 'config-no-scaling' );
960 protected function envCheckGit() {
961 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
962 $versionInfo = array( '$1 --version', 'git version' );
964 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
967 $this->setVar( 'wgGitBin', $git );
968 $this->showMessage( 'config-git', $git );
970 $this->setVar( 'wgGitBin', false );
971 $this->showMessage( 'config-git-bad' );
978 * Environment check to inform user which server we've assumed.
982 protected function envCheckServer() {
983 $server = $this->envGetDefaultServer();
984 if ( $server !== null ) {
985 $this->showMessage( 'config-using-server', $server );
991 * Environment check to inform user which paths we've assumed.
995 protected function envCheckPath() {
998 $this->getVar( 'wgServer' ),
999 $this->getVar( 'wgScriptPath' )
1005 * Environment check for preferred locale in shell
1008 protected function envCheckShellLocale() {
1009 $os = php_uname( 's' );
1010 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1012 if ( !in_array( $os, $supported ) ) {
1016 # Get a list of available locales.
1018 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1024 $lines = array_map( 'trim', explode( "\n", $lines ) );
1025 $candidatesByLocale = array();
1026 $candidatesByLang = array();
1028 foreach ( $lines as $line ) {
1029 if ( $line === '' ) {
1033 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1037 list( , $lang, , , ) = $m;
1039 $candidatesByLocale[$m[0]] = $m;
1040 $candidatesByLang[$lang][] = $m;
1043 # Try the current value of LANG.
1044 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1045 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1050 # Try the most common ones.
1051 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1052 foreach ( $commonLocales as $commonLocale ) {
1053 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1054 $this->setVar( 'wgShellLocale', $commonLocale );
1060 # Is there an available locale in the Wiki's language?
1061 $wikiLang = $this->getVar( 'wgLanguageCode' );
1063 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1064 $m = reset( $candidatesByLang[$wikiLang] );
1065 $this->setVar( 'wgShellLocale', $m[0] );
1070 # Are there any at all?
1071 if ( count( $candidatesByLocale ) ) {
1072 $m = reset( $candidatesByLocale );
1073 $this->setVar( 'wgShellLocale', $m[0] );
1083 * Environment check for the permissions of the uploads directory
1086 protected function envCheckUploadsDirectory() {
1089 $dir = $IP . '/images/';
1090 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1091 $safe = !$this->dirIsExecutable( $dir, $url );
1094 $this->showMessage( 'config-uploads-not-safe', $dir );
1101 * Checks if suhosin.get.max_value_length is set, and if so generate
1102 * a warning because it decreases ResourceLoader performance.
1105 protected function envCheckSuhosinMaxValueLength() {
1106 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1107 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1108 // Only warn if the value is below the sane 1024
1109 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1116 * Convert a hex string representing a Unicode code point to that code point.
1120 protected function unicodeChar( $c ) {
1124 } elseif ( $c <= 0x7FF ) {
1125 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1126 } elseif ( $c <= 0xFFFF ) {
1127 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1128 . chr( 0x80 |
$c & 0x3F );
1129 } elseif ( $c <= 0x10FFFF ) {
1130 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1131 . chr( 0x80 |
$c >> 6 & 0x3F )
1132 . chr( 0x80 |
$c & 0x3F );
1139 * Check the libicu version
1141 protected function envCheckLibicu() {
1142 $utf8 = function_exists( 'utf8_normalize' );
1143 $intl = function_exists( 'normalizer_normalize' );
1146 * This needs to be updated something that the latest libicu
1147 * will properly normalize. This normalization was found at
1148 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1149 * Note that we use the hex representation to create the code
1150 * points in order to avoid any Unicode-destroying during transit.
1152 $not_normal_c = $this->unicodeChar( "FA6C" );
1153 $normal_c = $this->unicodeChar( "242EE" );
1155 $useNormalizer = 'php';
1156 $needsUpdate = false;
1159 * We're going to prefer the pecl extension here unless
1160 * utf8_normalize is more up to date.
1163 $useNormalizer = 'utf8';
1164 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1165 if ( $utf8 !== $normal_c ) {
1166 $needsUpdate = true;
1170 $useNormalizer = 'intl';
1171 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1172 if ( $intl !== $normal_c ) {
1173 $needsUpdate = true;
1177 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1178 // 'config-unicode-using-intl'
1179 if ( $useNormalizer === 'php' ) {
1180 $this->showMessage( 'config-unicode-pure-php-warning' );
1182 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1183 if ( $needsUpdate ) {
1184 $this->showMessage( 'config-unicode-update-warning' );
1192 protected function envCheckCtype() {
1193 if ( !function_exists( 'ctype_digit' ) ) {
1194 $this->showError( 'config-ctype' );
1205 protected function envCheckIconv() {
1206 if ( !function_exists( 'iconv' ) ) {
1207 $this->showError( 'config-iconv' );
1218 protected function envCheckJSON() {
1219 if ( !function_exists( 'json_decode' ) ) {
1220 $this->showError( 'config-json' );
1229 * Environment prep for the server hostname.
1231 protected function envPrepServer() {
1232 $server = $this->envGetDefaultServer();
1233 if ( $server !== null ) {
1234 $this->setVar( 'wgServer', $server );
1239 * Helper function to be called from envPrepServer()
1242 abstract protected function envGetDefaultServer();
1245 * Environment prep for setting the preferred PHP file extension.
1247 protected function envPrepExtension() {
1248 // @todo FIXME: Detect this properly
1249 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1254 $this->setVar( 'wgScriptExtension', $ext );
1258 * Environment prep for setting $IP and $wgScriptPath.
1260 protected function envPrepPath() {
1262 $IP = dirname( dirname( __DIR__
) );
1263 $this->setVar( 'IP', $IP );
1267 * Get an array of likely places we can find executables. Check a bunch
1268 * of known Unix-like defaults, as well as the PATH environment variable
1269 * (which should maybe make it work for Windows?)
1273 protected static function getPossibleBinPaths() {
1275 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1276 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1277 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1282 * Search a path for any of the given executable names. Returns the
1283 * executable name if found. Also checks the version string returned
1284 * by each executable.
1286 * Used only by environment checks.
1288 * @param string $path Path to search
1289 * @param array $names Array of executable names
1290 * @param array|bool $versionInfo False or array with two members:
1291 * 0 => Command to run for version check, with $1 for the full executable name
1292 * 1 => String to compare the output with
1294 * If $versionInfo is not false, only executables with a version
1295 * matching $versionInfo[1] will be returned.
1296 * @return bool|string
1298 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1299 if ( !is_array( $names ) ) {
1300 $names = array( $names );
1303 foreach ( $names as $name ) {
1304 $command = $path . DIRECTORY_SEPARATOR
. $name;
1306 wfSuppressWarnings();
1307 $file_exists = file_exists( $command );
1308 wfRestoreWarnings();
1310 if ( $file_exists ) {
1311 if ( !$versionInfo ) {
1315 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1316 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1326 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1327 * @see locateExecutable()
1328 * @param array $names Array of possible names.
1329 * @param array|bool $versionInfo Default: false or array with two members:
1330 * 0 => Command to run for version check, with $1 for the full executable name
1331 * 1 => String to compare the output with
1333 * If $versionInfo is not false, only executables with a version
1334 * matching $versionInfo[1] will be returned.
1335 * @return bool|string
1337 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1338 foreach ( self
::getPossibleBinPaths() as $path ) {
1339 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1340 if ( $exe !== false ) {
1349 * Checks if scripts located in the given directory can be executed via the given URL.
1351 * Used only by environment checks.
1352 * @param string $dir
1353 * @param string $url
1354 * @return bool|int|string
1356 public function dirIsExecutable( $dir, $url ) {
1357 $scriptTypes = array(
1359 "<?php echo 'ex' . 'ec';",
1360 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1364 // it would be good to check other popular languages here, but it'll be slow.
1366 wfSuppressWarnings();
1368 foreach ( $scriptTypes as $ext => $contents ) {
1369 foreach ( $contents as $source ) {
1370 $file = 'exectest.' . $ext;
1372 if ( !file_put_contents( $dir . $file, $source ) ) {
1377 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1378 } catch ( MWException
$e ) {
1379 // Http::get throws with allow_url_fopen = false and no curl extension.
1382 unlink( $dir . $file );
1384 if ( $text == 'exec' ) {
1385 wfRestoreWarnings();
1392 wfRestoreWarnings();
1398 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1400 * @param string $moduleName Name of module to check.
1403 public static function apacheModulePresent( $moduleName ) {
1404 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1407 // try it the hard way
1409 phpinfo( INFO_MODULES
);
1410 $info = ob_get_clean();
1412 return strpos( $info, $moduleName ) !== false;
1416 * ParserOptions are constructed before we determined the language, so fix it
1418 * @param Language $lang
1420 public function setParserLanguage( $lang ) {
1421 $this->parserOptions
->setTargetLanguage( $lang );
1422 $this->parserOptions
->setUserLang( $lang );
1426 * Overridden by WebInstaller to provide lastPage parameters.
1427 * @param string $page
1430 protected function getDocUrl( $page ) {
1431 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1435 * Finds extensions that follow the format /$directory/Name/Name.php,
1436 * and returns an array containing the value for 'Name' for each found extension.
1438 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1440 * @param string $directory Directory to search in
1443 public function findExtensions( $directory = 'extensions' ) {
1444 if ( $this->getVar( 'IP' ) === null ) {
1448 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1449 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1453 $dh = opendir( $extDir );
1455 while ( ( $file = readdir( $dh ) ) !== false ) {
1456 if ( !is_dir( "$extDir/$file" ) ) {
1459 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1464 natcasesort( $exts );
1470 * Installs the auto-detected extensions.
1474 protected function includeExtensions() {
1476 $exts = $this->getVar( '_Extensions' );
1477 $IP = $this->getVar( 'IP' );
1480 * We need to include DefaultSettings before including extensions to avoid
1481 * warnings about unset variables. However, the only thing we really
1482 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1483 * if the extension has hidden hook registration in $wgExtensionFunctions,
1484 * but we're not opening that can of worms
1485 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1487 global $wgAutoloadClasses;
1488 $wgAutoloadClasses = array();
1490 require "$IP/includes/DefaultSettings.php";
1492 foreach ( $exts as $e ) {
1493 require_once "$IP/extensions/$e/$e.php";
1496 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1497 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1499 // Unset everyone else's hooks. Lord knows what someone might be doing
1500 // in ParserFirstCallInit (see bug 27171)
1501 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1503 return Status
::newGood();
1507 * Get an array of install steps. Should always be in the format of
1509 * 'name' => 'someuniquename',
1510 * 'callback' => array( $obj, 'method' ),
1512 * There must be a config-install-$name message defined per step, which will
1513 * be shown on install.
1515 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1518 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1519 $coreInstallSteps = array(
1520 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1521 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1522 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1523 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1524 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1525 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1526 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1529 // Build the array of install steps starting from the core install list,
1530 // then adding any callbacks that wanted to attach after a given step
1531 foreach ( $coreInstallSteps as $step ) {
1532 $this->installSteps
[] = $step;
1533 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1534 $this->installSteps
= array_merge(
1535 $this->installSteps
,
1536 $this->extraInstallSteps
[$step['name']]
1541 // Prepend any steps that want to be at the beginning
1542 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1543 $this->installSteps
= array_merge(
1544 $this->extraInstallSteps
['BEGINNING'],
1549 // Extensions should always go first, chance to tie into hooks and such
1550 if ( count( $this->getVar( '_Extensions' ) ) ) {
1551 array_unshift( $this->installSteps
,
1552 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1554 $this->installSteps
[] = array(
1555 'name' => 'extension-tables',
1556 'callback' => array( $installer, 'createExtensionTables' )
1560 return $this->installSteps
;
1564 * Actually perform the installation.
1566 * @param callable $startCB A callback array for the beginning of each step
1567 * @param callable $endCB A callback array for the end of each step
1569 * @return array Array of Status objects
1571 public function performInstallation( $startCB, $endCB ) {
1572 $installResults = array();
1573 $installer = $this->getDBInstaller();
1574 $installer->preInstall();
1575 $steps = $this->getInstallSteps( $installer );
1576 foreach ( $steps as $stepObj ) {
1577 $name = $stepObj['name'];
1578 call_user_func_array( $startCB, array( $name ) );
1580 // Perform the callback step
1581 $status = call_user_func( $stepObj['callback'], $installer );
1583 // Output and save the results
1584 call_user_func( $endCB, $name, $status );
1585 $installResults[$name] = $status;
1587 // If we've hit some sort of fatal, we need to bail.
1588 // Callback already had a chance to do output above.
1589 if ( !$status->isOk() ) {
1593 if ( $status->isOk() ) {
1594 $this->setVar( '_InstallDone', true );
1597 return $installResults;
1601 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1605 public function generateKeys() {
1606 $keys = array( 'wgSecretKey' => 64 );
1607 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1608 $keys['wgUpgradeKey'] = 16;
1611 return $this->doGenerateKeys( $keys );
1615 * Generate a secret value for variables using our CryptRand generator.
1616 * Produce a warning if the random source was insecure.
1618 * @param array $keys
1621 protected function doGenerateKeys( $keys ) {
1622 $status = Status
::newGood();
1625 foreach ( $keys as $name => $length ) {
1626 $secretKey = MWCryptRand
::generateHex( $length, true );
1627 if ( !MWCryptRand
::wasStrong() ) {
1631 $this->setVar( $name, $secretKey );
1635 $names = array_keys( $keys );
1636 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1638 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1645 * Create the first user account, grant it sysop and bureaucrat rights
1649 protected function createSysop() {
1650 $name = $this->getVar( '_AdminName' );
1651 $user = User
::newFromName( $name );
1654 // We should've validated this earlier anyway!
1655 return Status
::newFatal( 'config-admin-error-user', $name );
1658 if ( $user->idForName() == 0 ) {
1659 $user->addToDatabase();
1662 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1663 } catch ( PasswordError
$pwe ) {
1664 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1667 $user->addGroup( 'sysop' );
1668 $user->addGroup( 'bureaucrat' );
1669 if ( $this->getVar( '_AdminEmail' ) ) {
1670 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1672 $user->saveSettings();
1674 // Update user count
1675 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1676 $ssUpdate->doUpdate();
1678 $status = Status
::newGood();
1680 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1681 $this->subscribeToMediaWikiAnnounce( $status );
1690 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1692 'email' => $this->getVar( '_AdminEmail' ),
1697 // Mailman doesn't support as many languages as we do, so check to make
1698 // sure their selected language is available
1699 $myLang = $this->getVar( '_UserLang' );
1700 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1701 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1702 $params['language'] = $myLang;
1705 if ( MWHttpRequest
::canMakeRequests() ) {
1706 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1707 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1708 if ( !$res->isOK() ) {
1709 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1712 $s->warning( 'config-install-subscribe-notpossible' );
1717 * Insert Main Page with default content.
1719 * @param DatabaseInstaller $installer
1722 protected function createMainpage( DatabaseInstaller
$installer ) {
1723 $status = Status
::newGood();
1725 $page = WikiPage
::factory( Title
::newMainPage() );
1726 $content = new WikitextContent(
1727 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1728 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1731 $page->doEditContent( $content,
1735 User
::newFromName( 'MediaWiki default' )
1737 } catch ( MWException
$e ) {
1738 //using raw, because $wgShowExceptionDetails can not be set yet
1739 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1746 * Override the necessary bits of the config to run an installation.
1748 public static function overrideConfig() {
1749 define( 'MW_NO_SESSION', 1 );
1751 // Don't access the database
1752 $GLOBALS['wgUseDatabaseMessages'] = false;
1753 // Don't cache langconv tables
1754 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1756 $GLOBALS['wgShowExceptionDetails'] = true;
1757 // Don't break forms
1758 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1760 // Extended debugging
1761 $GLOBALS['wgShowSQLErrors'] = true;
1762 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1764 // Allow multiple ob_flush() calls
1765 $GLOBALS['wgDisableOutputCompression'] = true;
1767 // Use a sensible cookie prefix (not my_wiki)
1768 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1770 // Some of the environment checks make shell requests, remove limits
1771 $GLOBALS['wgMaxShellMemory'] = 0;
1773 // Don't bother embedding images into generated CSS, which is not cached
1774 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1775 return $less->toBool( false );
1780 * Add an installation step following the given step.
1782 * @param callable $callback A valid installation callback array, in this form:
1783 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1784 * @param string $findStep The step to find. Omit to put the step at the beginning
1786 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1787 $this->extraInstallSteps
[$findStep][] = $callback;
1791 * Disable the time limit for execution.
1792 * Some long-running pages (Install, Upgrade) will want to do this
1794 protected function disableTimeLimit() {
1795 wfSuppressWarnings();
1796 set_time_limit( 0 );
1797 wfRestoreWarnings();