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',
122 'envCheckMagicSybase',
129 'envCheckModSecurity',
135 'envCheckShellLocale',
136 'envCheckUploadsDirectory',
138 'envCheckSuhosinMaxValueLength',
145 * A list of environment preparation methods called by doEnvironmentPreps().
149 protected $envPreps = array(
156 * MediaWiki configuration globals that will eventually be passed through
157 * to LocalSettings.php. The names only are given here, the defaults
158 * typically come from DefaultSettings.php.
162 protected $defaultVarNames = array(
174 'wgEmailAuthentication',
177 'wgImageMagickConvertCommand',
183 'wgDeletedDirectory',
187 'wgUseInstantCommons',
190 'wgResourceLoaderMaxQueryLength',
194 * Variables that are stored alongside globals, and are used for any
195 * configuration of the installation process aside from the MediaWiki
196 * configuration. Map of names to defaults.
200 protected $internalDefaults = array(
202 '_Environment' => false,
203 '_SafeMode' => false,
204 '_RaiseMemory' => false,
205 '_UpgradeDone' => false,
206 '_InstallDone' => false,
207 '_Caches' => array(),
208 '_InstallPassword' => '',
209 '_SameAccount' => true,
210 '_CreateDBAccount' => false,
211 '_NamespaceType' => 'site-name',
212 '_AdminName' => '', // will be set later, when the user selects language
213 '_AdminPassword' => '',
214 '_AdminPasswordConfirm' => '',
216 '_Subscribe' => false,
217 '_SkipOptional' => 'continue',
218 '_RightsProfile' => 'wiki',
219 '_LicenseCode' => 'none',
221 '_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 * Shows messages to the user through a Status object
356 * @param Status $status
358 public function showStatusMessage( Status
$status ) {
359 $errors = array_merge( $status->getErrorsArray(), $status->getWarningsArray() );
361 foreach ( $errors as $error ) {
362 call_user_func( 'showMessage', $error );
368 * Constructor, always call this from child classes.
370 public function __construct() {
371 global $wgMessagesDirs, $wgUser;
373 // Disable the i18n cache
374 Language
::getLocalisationCache()->disableBackend();
375 // Disable LoadBalancer and wfGetDB etc.
376 LBFactory
::disableBackend();
378 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
379 // SqlBagOStuff will then throw since we just disabled wfGetDB)
380 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
381 ObjectCache
::clear();
382 $emptyCache = array( 'class' => 'EmptyBagOStuff' );
383 $GLOBALS['wgObjectCaches'] = array(
384 CACHE_NONE
=> $emptyCache,
385 CACHE_DB
=> $emptyCache,
386 CACHE_ANYTHING
=> $emptyCache,
387 CACHE_MEMCACHED
=> $emptyCache,
390 // Load the installer's i18n.
391 $wgMessagesDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
393 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
394 $wgUser = User
::newFromId( 0 );
396 $this->settings
= $this->internalDefaults
;
398 foreach ( $this->defaultVarNames
as $var ) {
399 $this->settings
[$var] = $GLOBALS[$var];
402 $this->doEnvironmentPreps();
404 $this->compiledDBs
= array();
405 foreach ( self
::getDBTypes() as $type ) {
406 $installer = $this->getDBInstaller( $type );
408 if ( !$installer->isCompiled() ) {
411 $this->compiledDBs
[] = $type;
414 $this->parserTitle
= Title
::newFromText( 'Installer' );
415 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
416 $this->parserOptions
->setEditSection( false );
420 * Get a list of known DB types.
424 public static function getDBTypes() {
425 return self
::$dbTypes;
429 * Do initial checks of the PHP environment. Set variables according to
430 * the observed environment.
432 * It's possible that this may be called under the CLI SAPI, not the SAPI
433 * that the wiki will primarily run under. In that case, the subclass should
434 * initialise variables such as wgScriptPath, before calling this function.
436 * Under the web subclass, it can already be assumed that PHP 5+ is in use
437 * and that sessions are working.
441 public function doEnvironmentChecks() {
442 // Php version has already been checked by entry scripts
443 // Show message here for information purposes
444 $this->showMessage( 'config-env-php', PHP_VERSION
);
447 // Must go here because an old version of PCRE can prevent other checks from completing
448 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
449 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
450 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
453 foreach ( $this->envChecks
as $check ) {
454 $status = $this->$check();
455 if ( $status === false ) {
461 $this->setVar( '_Environment', $good );
463 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
466 public function doEnvironmentPreps() {
467 foreach ( $this->envPreps
as $prep ) {
473 * Set a MW configuration variable, or internal installer configuration variable.
475 * @param string $name
476 * @param mixed $value
478 public function setVar( $name, $value ) {
479 $this->settings
[$name] = $value;
483 * Get an MW configuration variable, or internal installer configuration variable.
484 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
485 * Installer variables are typically prefixed by an underscore.
487 * @param string $name
488 * @param mixed $default
492 public function getVar( $name, $default = null ) {
493 if ( !isset( $this->settings
[$name] ) ) {
496 return $this->settings
[$name];
501 * Get a list of DBs supported by current PHP setup
505 public function getCompiledDBs() {
506 return $this->compiledDBs
;
510 * Get an instance of DatabaseInstaller for the specified DB type.
512 * @param mixed $type DB installer for which is needed, false to use default.
514 * @return DatabaseInstaller
516 public function getDBInstaller( $type = false ) {
518 $type = $this->getVar( 'wgDBtype' );
521 $type = strtolower( $type );
523 if ( !isset( $this->dbInstallers
[$type] ) ) {
524 $class = ucfirst( $type ) . 'Installer';
525 $this->dbInstallers
[$type] = new $class( $this );
528 return $this->dbInstallers
[$type];
532 * Determine if LocalSettings.php exists. If it does, return its variables.
536 public static function getExistingLocalSettings() {
539 wfSuppressWarnings();
540 $_lsExists = file_exists( "$IP/LocalSettings.php" );
548 require "$IP/includes/DefaultSettings.php";
549 require "$IP/LocalSettings.php";
551 return get_defined_vars();
555 * Get a fake password for sending back to the user in HTML.
556 * This is a security mechanism to avoid compromise of the password in the
557 * event of session ID compromise.
559 * @param string $realPassword
563 public function getFakePassword( $realPassword ) {
564 return str_repeat( '*', strlen( $realPassword ) );
568 * Set a variable which stores a password, except if the new value is a
569 * fake password in which case leave it as it is.
571 * @param string $name
572 * @param mixed $value
574 public function setPassword( $name, $value ) {
575 if ( !preg_match( '/^\*+$/', $value ) ) {
576 $this->setVar( $name, $value );
581 * On POSIX systems return the primary group of the webserver we're running under.
582 * On other systems just returns null.
584 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
585 * webserver user before he can install.
587 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
591 public static function maybeGetWebserverPrimaryGroup() {
592 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
593 # I don't know this, this isn't UNIX.
597 # posix_getegid() *not* getmygid() because we want the group of the webserver,
598 # not whoever owns the current script.
599 $gid = posix_getegid();
600 $getpwuid = posix_getpwuid( $gid );
601 $group = $getpwuid['name'];
607 * Convert wikitext $text to HTML.
609 * This is potentially error prone since many parser features require a complete
610 * installed MW database. The solution is to just not use those features when you
611 * write your messages. This appears to work well enough. Basic formatting and
612 * external links work just fine.
614 * But in case a translator decides to throw in a "#ifexist" or internal link or
615 * whatever, this function is guarded to catch the attempted DB access and to present
616 * some fallback text.
618 * @param string $text
619 * @param bool $lineStart
622 public function parse( $text, $lineStart = false ) {
626 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
627 $html = $out->getText();
628 } catch ( DBAccessError
$e ) {
629 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
631 if ( !empty( $this->debug
) ) {
632 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
640 * @return ParserOptions
642 public function getParserOptions() {
643 return $this->parserOptions
;
646 public function disableLinkPopups() {
647 $this->parserOptions
->setExternalLinkTarget( false );
650 public function restoreLinkPopups() {
651 global $wgExternalLinkTarget;
652 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
656 * Install step which adds a row to the site_stats table with appropriate
659 * @param DatabaseInstaller $installer
663 public function populateSiteStats( DatabaseInstaller
$installer ) {
664 $status = $installer->getConnection();
665 if ( !$status->isOK() ) {
668 $status->value
->insert(
672 'ss_total_views' => 0,
673 'ss_total_edits' => 0,
674 'ss_good_articles' => 0,
675 'ss_total_pages' => 0,
682 return Status
::newGood();
686 * Exports all wg* variables stored by the installer into global scope.
688 public function exportVars() {
689 foreach ( $this->settings
as $name => $value ) {
690 if ( substr( $name, 0, 2 ) == 'wg' ) {
691 $GLOBALS[$name] = $value;
697 * Environment check for DB types.
700 protected function envCheckDB() {
705 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
706 // config-type-sqlite
707 foreach ( self
::getDBTypes() as $name ) {
708 $allNames[] = wfMessage( "config-type-$name" )->text();
711 $databases = $this->getCompiledDBs();
713 $databases = array_flip( $databases );
714 foreach ( array_keys( $databases ) as $db ) {
715 $installer = $this->getDBInstaller( $db );
716 $status = $installer->checkPrerequisites();
717 if ( !$status->isGood() ) {
718 $this->showStatusMessage( $status );
720 if ( !$status->isOK() ) {
721 unset( $databases[$db] );
724 $databases = array_flip( $databases );
726 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
728 // @todo FIXME: This only works for the web installer!
736 * Environment check for register_globals.
737 * Prevent installation if enabled
739 protected function envCheckRegisterGlobals() {
740 if ( wfIniGetBool( 'register_globals' ) ) {
741 $this->showMessage( 'config-register-globals-error' );
749 * Some versions of libxml+PHP break < and > encoding horribly
752 protected function envCheckBrokenXML() {
753 $test = new PhpXmlBugTester();
755 $this->showError( 'config-brokenlibxml' );
764 * Environment check for magic_quotes_runtime.
767 protected function envCheckMagicQuotes() {
768 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
769 $this->showError( 'config-magic-quotes-runtime' );
778 * Environment check for magic_quotes_sybase.
781 protected function envCheckMagicSybase() {
782 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
783 $this->showError( 'config-magic-quotes-sybase' );
792 * Environment check for mbstring.func_overload.
795 protected function envCheckMbstring() {
796 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
797 $this->showError( 'config-mbstring' );
806 * Environment check for safe_mode.
809 protected function envCheckSafeMode() {
810 if ( wfIniGetBool( 'safe_mode' ) ) {
811 $this->setVar( '_SafeMode', true );
812 $this->showMessage( 'config-safe-mode' );
819 * Environment check for the XML module.
822 protected function envCheckXML() {
823 if ( !function_exists( "utf8_encode" ) ) {
824 $this->showError( 'config-xml-bad' );
833 * Environment check for the PCRE module.
835 * @note If this check were to fail, the parser would
836 * probably throw an exception before the result
837 * of this check is shown to the user.
840 protected function envCheckPCRE() {
841 wfSuppressWarnings();
842 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
843 // Need to check for \p support too, as PCRE can be compiled
844 // with utf8 support, but not unicode property support.
845 // check that \p{Zs} (space separators) matches
846 // U+3000 (Ideographic space)
847 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
849 if ( $regexd != '--' ||
$regexprop != '--' ) {
850 $this->showError( 'config-pcre-no-utf8' );
859 * Environment check for available memory.
862 protected function envCheckMemory() {
863 $limit = ini_get( 'memory_limit' );
865 if ( !$limit ||
$limit == -1 ) {
869 $n = wfShorthandToInteger( $limit );
871 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
872 $newLimit = "{$this->minMemorySize}M";
874 if ( ini_set( "memory_limit", $newLimit ) === false ) {
875 $this->showMessage( 'config-memory-bad', $limit );
877 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
878 $this->setVar( '_RaiseMemory', true );
886 * Environment check for compiled object cache types.
888 protected function envCheckCache() {
890 foreach ( $this->objectCaches
as $name => $function ) {
891 if ( function_exists( $function ) ) {
892 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
895 $caches[$name] = true;
900 $this->showMessage( 'config-no-cache' );
903 $this->setVar( '_Caches', $caches );
907 * Scare user to death if they have mod_security
910 protected function envCheckModSecurity() {
911 if ( self
::apacheModulePresent( 'mod_security' ) ) {
912 $this->showMessage( 'config-mod-security' );
919 * Search for GNU diff3.
922 protected function envCheckDiff3() {
923 $names = array( "gdiff3", "diff3", "diff3.exe" );
924 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
926 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
929 $this->setVar( 'wgDiff3', $diff3 );
931 $this->setVar( 'wgDiff3', false );
932 $this->showMessage( 'config-diff3-bad' );
939 * Environment check for ImageMagick and GD.
942 protected function envCheckGraphics() {
943 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
944 $versionInfo = array( '$1 -version', 'ImageMagick' );
945 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
947 $this->setVar( 'wgImageMagickConvertCommand', '' );
949 $this->setVar( 'wgImageMagickConvertCommand', $convert );
950 $this->showMessage( 'config-imagemagick', $convert );
953 } elseif ( function_exists( 'imagejpeg' ) ) {
954 $this->showMessage( 'config-gd' );
956 $this->showMessage( 'config-no-scaling' );
968 protected function envCheckGit() {
969 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
970 $versionInfo = array( '$1 --version', 'git version' );
972 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
975 $this->setVar( 'wgGitBin', $git );
976 $this->showMessage( 'config-git', $git );
978 $this->setVar( 'wgGitBin', false );
979 $this->showMessage( 'config-git-bad' );
986 * Environment check to inform user which server we've assumed.
990 protected function envCheckServer() {
991 $server = $this->envGetDefaultServer();
992 if ( $server !== null ) {
993 $this->showMessage( 'config-using-server', $server );
999 * Environment check to inform user which paths we've assumed.
1003 protected function envCheckPath() {
1006 $this->getVar( 'wgServer' ),
1007 $this->getVar( 'wgScriptPath' )
1013 * Environment check for preferred locale in shell
1016 protected function envCheckShellLocale() {
1017 $os = php_uname( 's' );
1018 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1020 if ( !in_array( $os, $supported ) ) {
1024 # Get a list of available locales.
1026 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1032 $lines = array_map( 'trim', explode( "\n", $lines ) );
1033 $candidatesByLocale = array();
1034 $candidatesByLang = array();
1036 foreach ( $lines as $line ) {
1037 if ( $line === '' ) {
1041 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1045 list( , $lang, , , ) = $m;
1047 $candidatesByLocale[$m[0]] = $m;
1048 $candidatesByLang[$lang][] = $m;
1051 # Try the current value of LANG.
1052 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1053 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1058 # Try the most common ones.
1059 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1060 foreach ( $commonLocales as $commonLocale ) {
1061 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1062 $this->setVar( 'wgShellLocale', $commonLocale );
1068 # Is there an available locale in the Wiki's language?
1069 $wikiLang = $this->getVar( 'wgLanguageCode' );
1071 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1072 $m = reset( $candidatesByLang[$wikiLang] );
1073 $this->setVar( 'wgShellLocale', $m[0] );
1078 # Are there any at all?
1079 if ( count( $candidatesByLocale ) ) {
1080 $m = reset( $candidatesByLocale );
1081 $this->setVar( 'wgShellLocale', $m[0] );
1091 * Environment check for the permissions of the uploads directory
1094 protected function envCheckUploadsDirectory() {
1097 $dir = $IP . '/images/';
1098 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1099 $safe = !$this->dirIsExecutable( $dir, $url );
1102 $this->showMessage( 'config-uploads-not-safe', $dir );
1109 * Checks if suhosin.get.max_value_length is set, and if so generate
1110 * a warning because it decreases ResourceLoader performance.
1113 protected function envCheckSuhosinMaxValueLength() {
1114 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1115 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1116 // Only warn if the value is below the sane 1024
1117 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1124 * Convert a hex string representing a Unicode code point to that code point.
1128 protected function unicodeChar( $c ) {
1132 } elseif ( $c <= 0x7FF ) {
1133 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1134 } elseif ( $c <= 0xFFFF ) {
1135 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1136 . chr( 0x80 |
$c & 0x3F );
1137 } elseif ( $c <= 0x10FFFF ) {
1138 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1139 . chr( 0x80 |
$c >> 6 & 0x3F )
1140 . chr( 0x80 |
$c & 0x3F );
1147 * Check the libicu version
1149 protected function envCheckLibicu() {
1150 $utf8 = function_exists( 'utf8_normalize' );
1151 $intl = function_exists( 'normalizer_normalize' );
1154 * This needs to be updated something that the latest libicu
1155 * will properly normalize. This normalization was found at
1156 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1157 * Note that we use the hex representation to create the code
1158 * points in order to avoid any Unicode-destroying during transit.
1160 $not_normal_c = $this->unicodeChar( "FA6C" );
1161 $normal_c = $this->unicodeChar( "242EE" );
1163 $useNormalizer = 'php';
1164 $needsUpdate = false;
1167 * We're going to prefer the pecl extension here unless
1168 * utf8_normalize is more up to date.
1171 $useNormalizer = 'utf8';
1172 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1173 if ( $utf8 !== $normal_c ) {
1174 $needsUpdate = true;
1178 $useNormalizer = 'intl';
1179 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1180 if ( $intl !== $normal_c ) {
1181 $needsUpdate = true;
1185 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1186 // 'config-unicode-using-intl'
1187 if ( $useNormalizer === 'php' ) {
1188 $this->showMessage( 'config-unicode-pure-php-warning' );
1190 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1191 if ( $needsUpdate ) {
1192 $this->showMessage( 'config-unicode-update-warning' );
1200 protected function envCheckCtype() {
1201 if ( !function_exists( 'ctype_digit' ) ) {
1202 $this->showError( 'config-ctype' );
1213 protected function envCheckIconv() {
1214 if ( !function_exists( 'iconv' ) ) {
1215 $this->showError( 'config-iconv' );
1226 protected function envCheckJSON() {
1227 if ( !function_exists( 'json_decode' ) ) {
1228 $this->showError( 'config-json' );
1237 * Environment prep for the server hostname.
1239 protected function envPrepServer() {
1240 $server = $this->envGetDefaultServer();
1241 if ( $server !== null ) {
1242 $this->setVar( 'wgServer', $server );
1247 * Helper function to be called from envPrepServer()
1250 abstract protected function envGetDefaultServer();
1253 * Environment prep for setting the preferred PHP file extension.
1255 protected function envPrepExtension() {
1256 // @todo FIXME: Detect this properly
1257 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1262 $this->setVar( 'wgScriptExtension', $ext );
1266 * Environment prep for setting $IP and $wgScriptPath.
1268 protected function envPrepPath() {
1270 $IP = dirname( dirname( __DIR__
) );
1271 $this->setVar( 'IP', $IP );
1275 * Get an array of likely places we can find executables. Check a bunch
1276 * of known Unix-like defaults, as well as the PATH environment variable
1277 * (which should maybe make it work for Windows?)
1281 protected static function getPossibleBinPaths() {
1283 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1284 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1285 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1290 * Search a path for any of the given executable names. Returns the
1291 * executable name if found. Also checks the version string returned
1292 * by each executable.
1294 * Used only by environment checks.
1296 * @param string $path path to search
1297 * @param array $names of executable names
1298 * @param array|bool $versionInfo False or array with two members:
1299 * 0 => Command to run for version check, with $1 for the full executable name
1300 * 1 => String to compare the output with
1302 * If $versionInfo is not false, only executables with a version
1303 * matching $versionInfo[1] will be returned.
1304 * @return bool|string
1306 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1307 if ( !is_array( $names ) ) {
1308 $names = array( $names );
1311 foreach ( $names as $name ) {
1312 $command = $path . DIRECTORY_SEPARATOR
. $name;
1314 wfSuppressWarnings();
1315 $file_exists = file_exists( $command );
1316 wfRestoreWarnings();
1318 if ( $file_exists ) {
1319 if ( !$versionInfo ) {
1323 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1324 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1334 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1335 * @see locateExecutable()
1336 * @param array $names Array of possible names.
1337 * @param array|bool $versionInfo Default: false or array with two members:
1338 * 0 => Command to run for version check, with $1 for the full executable name
1339 * 1 => String to compare the output with
1341 * If $versionInfo is not false, only executables with a version
1342 * matching $versionInfo[1] will be returned.
1343 * @return bool|string
1345 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1346 foreach ( self
::getPossibleBinPaths() as $path ) {
1347 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1348 if ( $exe !== false ) {
1357 * Checks if scripts located in the given directory can be executed via the given URL.
1359 * Used only by environment checks.
1360 * @param string $dir
1361 * @param string $url
1362 * @return bool|int|string
1364 public function dirIsExecutable( $dir, $url ) {
1365 $scriptTypes = array(
1367 "<?php echo 'ex' . 'ec';",
1368 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1372 // it would be good to check other popular languages here, but it'll be slow.
1374 wfSuppressWarnings();
1376 foreach ( $scriptTypes as $ext => $contents ) {
1377 foreach ( $contents as $source ) {
1378 $file = 'exectest.' . $ext;
1380 if ( !file_put_contents( $dir . $file, $source ) ) {
1385 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1386 } catch ( MWException
$e ) {
1387 // Http::get throws with allow_url_fopen = false and no curl extension.
1390 unlink( $dir . $file );
1392 if ( $text == 'exec' ) {
1393 wfRestoreWarnings();
1400 wfRestoreWarnings();
1406 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1408 * @param string $moduleName Name of module to check.
1411 public static function apacheModulePresent( $moduleName ) {
1412 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1415 // try it the hard way
1417 phpinfo( INFO_MODULES
);
1418 $info = ob_get_clean();
1420 return strpos( $info, $moduleName ) !== false;
1424 * ParserOptions are constructed before we determined the language, so fix it
1426 * @param Language $lang
1428 public function setParserLanguage( $lang ) {
1429 $this->parserOptions
->setTargetLanguage( $lang );
1430 $this->parserOptions
->setUserLang( $lang );
1434 * Overridden by WebInstaller to provide lastPage parameters.
1435 * @param string $page
1438 protected function getDocUrl( $page ) {
1439 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1443 * Finds extensions that follow the format /extensions/Name/Name.php,
1444 * and returns an array containing the value for 'Name' for each found extension.
1448 public function findExtensions() {
1449 if ( $this->getVar( 'IP' ) === null ) {
1453 $extDir = $this->getVar( 'IP' ) . '/extensions';
1454 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1458 $dh = opendir( $extDir );
1460 while ( ( $file = readdir( $dh ) ) !== false ) {
1461 if ( !is_dir( "$extDir/$file" ) ) {
1464 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1469 natcasesort( $exts );
1475 * Installs the auto-detected extensions.
1479 protected function includeExtensions() {
1481 $exts = $this->getVar( '_Extensions' );
1482 $IP = $this->getVar( 'IP' );
1485 * We need to include DefaultSettings before including extensions to avoid
1486 * warnings about unset variables. However, the only thing we really
1487 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1488 * if the extension has hidden hook registration in $wgExtensionFunctions,
1489 * but we're not opening that can of worms
1490 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1492 global $wgAutoloadClasses;
1493 $wgAutoloadClasses = array();
1495 require "$IP/includes/DefaultSettings.php";
1497 foreach ( $exts as $e ) {
1498 require_once "$IP/extensions/$e/$e.php";
1501 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1502 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1504 // Unset everyone else's hooks. Lord knows what someone might be doing
1505 // in ParserFirstCallInit (see bug 27171)
1506 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1508 return Status
::newGood();
1512 * Get an array of install steps. Should always be in the format of
1514 * 'name' => 'someuniquename',
1515 * 'callback' => array( $obj, 'method' ),
1517 * There must be a config-install-$name message defined per step, which will
1518 * be shown on install.
1520 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1523 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1524 $coreInstallSteps = array(
1525 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1526 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1527 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1528 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1529 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1530 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1531 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1534 // Build the array of install steps starting from the core install list,
1535 // then adding any callbacks that wanted to attach after a given step
1536 foreach ( $coreInstallSteps as $step ) {
1537 $this->installSteps
[] = $step;
1538 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1539 $this->installSteps
= array_merge(
1540 $this->installSteps
,
1541 $this->extraInstallSteps
[$step['name']]
1546 // Prepend any steps that want to be at the beginning
1547 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1548 $this->installSteps
= array_merge(
1549 $this->extraInstallSteps
['BEGINNING'],
1554 // Extensions should always go first, chance to tie into hooks and such
1555 if ( count( $this->getVar( '_Extensions' ) ) ) {
1556 array_unshift( $this->installSteps
,
1557 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1559 $this->installSteps
[] = array(
1560 'name' => 'extension-tables',
1561 'callback' => array( $installer, 'createExtensionTables' )
1565 return $this->installSteps
;
1569 * Actually perform the installation.
1571 * @param callable $startCB A callback array for the beginning of each step
1572 * @param callable $endCB A callback array for the end of each step
1574 * @return array Array of Status objects
1576 public function performInstallation( $startCB, $endCB ) {
1577 $installResults = array();
1578 $installer = $this->getDBInstaller();
1579 $installer->preInstall();
1580 $steps = $this->getInstallSteps( $installer );
1581 foreach ( $steps as $stepObj ) {
1582 $name = $stepObj['name'];
1583 call_user_func_array( $startCB, array( $name ) );
1585 // Perform the callback step
1586 $status = call_user_func( $stepObj['callback'], $installer );
1588 // Output and save the results
1589 call_user_func( $endCB, $name, $status );
1590 $installResults[$name] = $status;
1592 // If we've hit some sort of fatal, we need to bail.
1593 // Callback already had a chance to do output above.
1594 if ( !$status->isOk() ) {
1598 if ( $status->isOk() ) {
1599 $this->setVar( '_InstallDone', true );
1602 return $installResults;
1606 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1610 public function generateKeys() {
1611 $keys = array( 'wgSecretKey' => 64 );
1612 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1613 $keys['wgUpgradeKey'] = 16;
1616 return $this->doGenerateKeys( $keys );
1620 * Generate a secret value for variables using our CryptRand generator.
1621 * Produce a warning if the random source was insecure.
1623 * @param array $keys
1626 protected function doGenerateKeys( $keys ) {
1627 $status = Status
::newGood();
1630 foreach ( $keys as $name => $length ) {
1631 $secretKey = MWCryptRand
::generateHex( $length, true );
1632 if ( !MWCryptRand
::wasStrong() ) {
1636 $this->setVar( $name, $secretKey );
1640 $names = array_keys( $keys );
1641 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1643 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1650 * Create the first user account, grant it sysop and bureaucrat rights
1654 protected function createSysop() {
1655 $name = $this->getVar( '_AdminName' );
1656 $user = User
::newFromName( $name );
1659 // We should've validated this earlier anyway!
1660 return Status
::newFatal( 'config-admin-error-user', $name );
1663 if ( $user->idForName() == 0 ) {
1664 $user->addToDatabase();
1667 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1668 } catch ( PasswordError
$pwe ) {
1669 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1672 $user->addGroup( 'sysop' );
1673 $user->addGroup( 'bureaucrat' );
1674 if ( $this->getVar( '_AdminEmail' ) ) {
1675 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1677 $user->saveSettings();
1679 // Update user count
1680 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1681 $ssUpdate->doUpdate();
1683 $status = Status
::newGood();
1685 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1686 $this->subscribeToMediaWikiAnnounce( $status );
1695 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1697 'email' => $this->getVar( '_AdminEmail' ),
1702 // Mailman doesn't support as many languages as we do, so check to make
1703 // sure their selected language is available
1704 $myLang = $this->getVar( '_UserLang' );
1705 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1706 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1707 $params['language'] = $myLang;
1710 if ( MWHttpRequest
::canMakeRequests() ) {
1711 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1712 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1713 if ( !$res->isOK() ) {
1714 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1717 $s->warning( 'config-install-subscribe-notpossible' );
1722 * Insert Main Page with default content.
1724 * @param DatabaseInstaller $installer
1727 protected function createMainpage( DatabaseInstaller
$installer ) {
1728 $status = Status
::newGood();
1730 $page = WikiPage
::factory( Title
::newMainPage() );
1731 $content = new WikitextContent(
1732 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1733 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1736 $page->doEditContent( $content,
1740 User
::newFromName( 'MediaWiki default' )
1742 } catch ( MWException
$e ) {
1743 //using raw, because $wgShowExceptionDetails can not be set yet
1744 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1751 * Override the necessary bits of the config to run an installation.
1753 public static function overrideConfig() {
1754 define( 'MW_NO_SESSION', 1 );
1756 // Don't access the database
1757 $GLOBALS['wgUseDatabaseMessages'] = false;
1758 // Don't cache langconv tables
1759 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1761 $GLOBALS['wgShowExceptionDetails'] = true;
1762 // Don't break forms
1763 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1765 // Extended debugging
1766 $GLOBALS['wgShowSQLErrors'] = true;
1767 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1769 // Allow multiple ob_flush() calls
1770 $GLOBALS['wgDisableOutputCompression'] = true;
1772 // Use a sensible cookie prefix (not my_wiki)
1773 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1775 // Some of the environment checks make shell requests, remove limits
1776 $GLOBALS['wgMaxShellMemory'] = 0;
1778 // Don't bother embedding images into generated CSS, which is not cached
1779 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1780 return $less->toBool( false );
1785 * Add an installation step following the given step.
1787 * @param callable $callback A valid installation callback array, in this form:
1788 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1789 * @param string $findStep The step to find. Omit to put the step at the beginning
1791 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1792 $this->extraInstallSteps
[$findStep][] = $callback;
1796 * Disable the time limit for execution.
1797 * Some long-running pages (Install, Upgrade) will want to do this
1799 protected function disableTimeLimit() {
1800 wfSuppressWarnings();
1801 set_time_limit( 0 );
1802 wfRestoreWarnings();