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
437 $this->showMessage( 'config-env-php', PHP_VERSION
);
440 // Must go here because an old version of PCRE can prevent other checks from completing
441 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
442 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
443 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
446 foreach ( $this->envChecks
as $check ) {
447 $status = $this->$check();
448 if ( $status === false ) {
454 $this->setVar( '_Environment', $good );
456 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
459 public function doEnvironmentPreps() {
460 foreach ( $this->envPreps
as $prep ) {
466 * Set a MW configuration variable, or internal installer configuration variable.
468 * @param string $name
469 * @param mixed $value
471 public function setVar( $name, $value ) {
472 $this->settings
[$name] = $value;
476 * Get an MW configuration variable, or internal installer configuration variable.
477 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
478 * Installer variables are typically prefixed by an underscore.
480 * @param string $name
481 * @param mixed $default
485 public function getVar( $name, $default = null ) {
486 if ( !isset( $this->settings
[$name] ) ) {
489 return $this->settings
[$name];
494 * Get a list of DBs supported by current PHP setup
498 public function getCompiledDBs() {
499 return $this->compiledDBs
;
503 * Get an instance of DatabaseInstaller for the specified DB type.
505 * @param mixed $type DB installer for which is needed, false to use default.
507 * @return DatabaseInstaller
509 public function getDBInstaller( $type = false ) {
511 $type = $this->getVar( 'wgDBtype' );
514 $type = strtolower( $type );
516 if ( !isset( $this->dbInstallers
[$type] ) ) {
517 $class = ucfirst( $type ) . 'Installer';
518 $this->dbInstallers
[$type] = new $class( $this );
521 return $this->dbInstallers
[$type];
525 * Determine if LocalSettings.php exists. If it does, return its variables.
529 public static function getExistingLocalSettings() {
532 // You might be wondering why this is here. Well if you don't do this
533 // then some poorly-formed extensions try to call their own classes
534 // after immediately registering them. We really need to get extension
535 // registration out of the global scope and into a real format.
536 // @see https://bugzilla.wikimedia.org/67440
537 global $wgAutoloadClasses;
538 $wgAutoloadClasses = array();
540 wfSuppressWarnings();
541 $_lsExists = file_exists( "$IP/LocalSettings.php" );
549 require "$IP/includes/DefaultSettings.php";
550 require "$IP/LocalSettings.php";
552 return get_defined_vars();
556 * Get a fake password for sending back to the user in HTML.
557 * This is a security mechanism to avoid compromise of the password in the
558 * event of session ID compromise.
560 * @param string $realPassword
564 public function getFakePassword( $realPassword ) {
565 return str_repeat( '*', strlen( $realPassword ) );
569 * Set a variable which stores a password, except if the new value is a
570 * fake password in which case leave it as it is.
572 * @param string $name
573 * @param mixed $value
575 public function setPassword( $name, $value ) {
576 if ( !preg_match( '/^\*+$/', $value ) ) {
577 $this->setVar( $name, $value );
582 * On POSIX systems return the primary group of the webserver we're running under.
583 * On other systems just returns null.
585 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
586 * webserver user before he can install.
588 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
592 public static function maybeGetWebserverPrimaryGroup() {
593 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
594 # I don't know this, this isn't UNIX.
598 # posix_getegid() *not* getmygid() because we want the group of the webserver,
599 # not whoever owns the current script.
600 $gid = posix_getegid();
601 $getpwuid = posix_getpwuid( $gid );
602 $group = $getpwuid['name'];
608 * Convert wikitext $text to HTML.
610 * This is potentially error prone since many parser features require a complete
611 * installed MW database. The solution is to just not use those features when you
612 * write your messages. This appears to work well enough. Basic formatting and
613 * external links work just fine.
615 * But in case a translator decides to throw in a "#ifexist" or internal link or
616 * whatever, this function is guarded to catch the attempted DB access and to present
617 * some fallback text.
619 * @param string $text
620 * @param bool $lineStart
623 public function parse( $text, $lineStart = false ) {
627 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
628 $html = $out->getText();
629 } catch ( DBAccessError
$e ) {
630 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
632 if ( !empty( $this->debug
) ) {
633 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
641 * @return ParserOptions
643 public function getParserOptions() {
644 return $this->parserOptions
;
647 public function disableLinkPopups() {
648 $this->parserOptions
->setExternalLinkTarget( false );
651 public function restoreLinkPopups() {
652 global $wgExternalLinkTarget;
653 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
657 * Install step which adds a row to the site_stats table with appropriate
660 * @param DatabaseInstaller $installer
664 public function populateSiteStats( DatabaseInstaller
$installer ) {
665 $status = $installer->getConnection();
666 if ( !$status->isOK() ) {
669 $status->value
->insert(
673 'ss_total_views' => 0,
674 'ss_total_edits' => 0,
675 'ss_good_articles' => 0,
676 'ss_total_pages' => 0,
683 return Status
::newGood();
687 * Exports all wg* variables stored by the installer into global scope.
689 public function exportVars() {
690 foreach ( $this->settings
as $name => $value ) {
691 if ( substr( $name, 0, 2 ) == 'wg' ) {
692 $GLOBALS[$name] = $value;
698 * Environment check for DB types.
701 protected function envCheckDB() {
706 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
707 // config-type-sqlite
708 foreach ( self
::getDBTypes() as $name ) {
709 $allNames[] = wfMessage( "config-type-$name" )->text();
712 $databases = $this->getCompiledDBs();
714 $databases = array_flip( $databases );
715 foreach ( array_keys( $databases ) as $db ) {
716 $installer = $this->getDBInstaller( $db );
717 $status = $installer->checkPrerequisites();
718 if ( !$status->isGood() ) {
719 $this->showStatusMessage( $status );
721 if ( !$status->isOK() ) {
722 unset( $databases[$db] );
725 $databases = array_flip( $databases );
727 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
729 // @todo FIXME: This only works for the web installer!
737 * Environment check for register_globals.
738 * Prevent installation if enabled
741 protected function envCheckRegisterGlobals() {
742 if ( wfIniGetBool( 'register_globals' ) ) {
743 $this->showMessage( 'config-register-globals-error' );
751 * Some versions of libxml+PHP break < and > encoding horribly
754 protected function envCheckBrokenXML() {
755 $test = new PhpXmlBugTester();
757 $this->showError( 'config-brokenlibxml' );
766 * Environment check for magic_quotes_(gpc|runtime|sybase).
769 protected function envCheckMagicQuotes() {
771 foreach ( array( 'gpc', 'runtime', 'sybase' ) as $magicJunk ) {
772 if ( wfIniGetBool( "magic_quotes_$magicJunk" ) ) {
773 $this->showError( "config-magic-quotes-$magicJunk" );
782 * Environment check for mbstring.func_overload.
785 protected function envCheckMbstring() {
786 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
787 $this->showError( 'config-mbstring' );
796 * Environment check for safe_mode.
799 protected function envCheckSafeMode() {
800 if ( wfIniGetBool( 'safe_mode' ) ) {
801 $this->setVar( '_SafeMode', true );
802 $this->showMessage( 'config-safe-mode' );
809 * Environment check for the XML module.
812 protected function envCheckXML() {
813 if ( !function_exists( "utf8_encode" ) ) {
814 $this->showError( 'config-xml-bad' );
823 * Environment check for the PCRE module.
825 * @note If this check were to fail, the parser would
826 * probably throw an exception before the result
827 * of this check is shown to the user.
830 protected function envCheckPCRE() {
831 wfSuppressWarnings();
832 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
833 // Need to check for \p support too, as PCRE can be compiled
834 // with utf8 support, but not unicode property support.
835 // check that \p{Zs} (space separators) matches
836 // U+3000 (Ideographic space)
837 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
839 if ( $regexd != '--' ||
$regexprop != '--' ) {
840 $this->showError( 'config-pcre-no-utf8' );
849 * Environment check for available memory.
852 protected function envCheckMemory() {
853 $limit = ini_get( 'memory_limit' );
855 if ( !$limit ||
$limit == -1 ) {
859 $n = wfShorthandToInteger( $limit );
861 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
862 $newLimit = "{$this->minMemorySize}M";
864 if ( ini_set( "memory_limit", $newLimit ) === false ) {
865 $this->showMessage( 'config-memory-bad', $limit );
867 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
868 $this->setVar( '_RaiseMemory', true );
876 * Environment check for compiled object cache types.
878 protected function envCheckCache() {
880 foreach ( $this->objectCaches
as $name => $function ) {
881 if ( function_exists( $function ) ) {
882 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
885 $caches[$name] = true;
890 $this->showMessage( 'config-no-cache' );
893 $this->setVar( '_Caches', $caches );
897 * Scare user to death if they have mod_security
900 protected function envCheckModSecurity() {
901 if ( self
::apacheModulePresent( 'mod_security' ) ) {
902 $this->showMessage( 'config-mod-security' );
909 * Search for GNU diff3.
912 protected function envCheckDiff3() {
913 $names = array( "gdiff3", "diff3", "diff3.exe" );
914 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
916 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
919 $this->setVar( 'wgDiff3', $diff3 );
921 $this->setVar( 'wgDiff3', false );
922 $this->showMessage( 'config-diff3-bad' );
929 * Environment check for ImageMagick and GD.
932 protected function envCheckGraphics() {
933 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
934 $versionInfo = array( '$1 -version', 'ImageMagick' );
935 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
937 $this->setVar( 'wgImageMagickConvertCommand', '' );
939 $this->setVar( 'wgImageMagickConvertCommand', $convert );
940 $this->showMessage( 'config-imagemagick', $convert );
943 } elseif ( function_exists( 'imagejpeg' ) ) {
944 $this->showMessage( 'config-gd' );
946 $this->showMessage( 'config-no-scaling' );
958 protected function envCheckGit() {
959 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
960 $versionInfo = array( '$1 --version', 'git version' );
962 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
965 $this->setVar( 'wgGitBin', $git );
966 $this->showMessage( 'config-git', $git );
968 $this->setVar( 'wgGitBin', false );
969 $this->showMessage( 'config-git-bad' );
976 * Environment check to inform user which server we've assumed.
980 protected function envCheckServer() {
981 $server = $this->envGetDefaultServer();
982 if ( $server !== null ) {
983 $this->showMessage( 'config-using-server', $server );
989 * Environment check to inform user which paths we've assumed.
993 protected function envCheckPath() {
996 $this->getVar( 'wgServer' ),
997 $this->getVar( 'wgScriptPath' )
1003 * Environment check for preferred locale in shell
1006 protected function envCheckShellLocale() {
1007 $os = php_uname( 's' );
1008 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1010 if ( !in_array( $os, $supported ) ) {
1014 # Get a list of available locales.
1016 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1022 $lines = array_map( 'trim', explode( "\n", $lines ) );
1023 $candidatesByLocale = array();
1024 $candidatesByLang = array();
1026 foreach ( $lines as $line ) {
1027 if ( $line === '' ) {
1031 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1035 list( , $lang, , , ) = $m;
1037 $candidatesByLocale[$m[0]] = $m;
1038 $candidatesByLang[$lang][] = $m;
1041 # Try the current value of LANG.
1042 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1043 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1048 # Try the most common ones.
1049 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1050 foreach ( $commonLocales as $commonLocale ) {
1051 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1052 $this->setVar( 'wgShellLocale', $commonLocale );
1058 # Is there an available locale in the Wiki's language?
1059 $wikiLang = $this->getVar( 'wgLanguageCode' );
1061 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1062 $m = reset( $candidatesByLang[$wikiLang] );
1063 $this->setVar( 'wgShellLocale', $m[0] );
1068 # Are there any at all?
1069 if ( count( $candidatesByLocale ) ) {
1070 $m = reset( $candidatesByLocale );
1071 $this->setVar( 'wgShellLocale', $m[0] );
1081 * Environment check for the permissions of the uploads directory
1084 protected function envCheckUploadsDirectory() {
1087 $dir = $IP . '/images/';
1088 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1089 $safe = !$this->dirIsExecutable( $dir, $url );
1092 $this->showMessage( 'config-uploads-not-safe', $dir );
1099 * Checks if suhosin.get.max_value_length is set, and if so generate
1100 * a warning because it decreases ResourceLoader performance.
1103 protected function envCheckSuhosinMaxValueLength() {
1104 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1105 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1106 // Only warn if the value is below the sane 1024
1107 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1114 * Convert a hex string representing a Unicode code point to that code point.
1118 protected function unicodeChar( $c ) {
1122 } elseif ( $c <= 0x7FF ) {
1123 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1124 } elseif ( $c <= 0xFFFF ) {
1125 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1126 . chr( 0x80 |
$c & 0x3F );
1127 } elseif ( $c <= 0x10FFFF ) {
1128 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1129 . chr( 0x80 |
$c >> 6 & 0x3F )
1130 . chr( 0x80 |
$c & 0x3F );
1137 * Check the libicu version
1139 protected function envCheckLibicu() {
1140 $utf8 = function_exists( 'utf8_normalize' );
1141 $intl = function_exists( 'normalizer_normalize' );
1144 * This needs to be updated something that the latest libicu
1145 * will properly normalize. This normalization was found at
1146 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1147 * Note that we use the hex representation to create the code
1148 * points in order to avoid any Unicode-destroying during transit.
1150 $not_normal_c = $this->unicodeChar( "FA6C" );
1151 $normal_c = $this->unicodeChar( "242EE" );
1153 $useNormalizer = 'php';
1154 $needsUpdate = false;
1157 * We're going to prefer the pecl extension here unless
1158 * utf8_normalize is more up to date.
1161 $useNormalizer = 'utf8';
1162 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1163 if ( $utf8 !== $normal_c ) {
1164 $needsUpdate = true;
1168 $useNormalizer = 'intl';
1169 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1170 if ( $intl !== $normal_c ) {
1171 $needsUpdate = true;
1175 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1176 // 'config-unicode-using-intl'
1177 if ( $useNormalizer === 'php' ) {
1178 $this->showMessage( 'config-unicode-pure-php-warning' );
1180 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1181 if ( $needsUpdate ) {
1182 $this->showMessage( 'config-unicode-update-warning' );
1190 protected function envCheckCtype() {
1191 if ( !function_exists( 'ctype_digit' ) ) {
1192 $this->showError( 'config-ctype' );
1203 protected function envCheckIconv() {
1204 if ( !function_exists( 'iconv' ) ) {
1205 $this->showError( 'config-iconv' );
1216 protected function envCheckJSON() {
1217 if ( !function_exists( 'json_decode' ) ) {
1218 $this->showError( 'config-json' );
1227 * Environment prep for the server hostname.
1229 protected function envPrepServer() {
1230 $server = $this->envGetDefaultServer();
1231 if ( $server !== null ) {
1232 $this->setVar( 'wgServer', $server );
1237 * Helper function to be called from envPrepServer()
1240 abstract protected function envGetDefaultServer();
1243 * Environment prep for setting the preferred PHP file extension.
1245 protected function envPrepExtension() {
1246 // @todo FIXME: Detect this properly
1247 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1252 $this->setVar( 'wgScriptExtension', $ext );
1256 * Environment prep for setting $IP and $wgScriptPath.
1258 protected function envPrepPath() {
1260 $IP = dirname( dirname( __DIR__
) );
1261 $this->setVar( 'IP', $IP );
1265 * Get an array of likely places we can find executables. Check a bunch
1266 * of known Unix-like defaults, as well as the PATH environment variable
1267 * (which should maybe make it work for Windows?)
1271 protected static function getPossibleBinPaths() {
1273 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1274 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1275 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1280 * Search a path for any of the given executable names. Returns the
1281 * executable name if found. Also checks the version string returned
1282 * by each executable.
1284 * Used only by environment checks.
1286 * @param string $path Path to search
1287 * @param array $names Array of executable names
1288 * @param array|bool $versionInfo False or array with two members:
1289 * 0 => Command to run for version check, with $1 for the full executable name
1290 * 1 => String to compare the output with
1292 * If $versionInfo is not false, only executables with a version
1293 * matching $versionInfo[1] will be returned.
1294 * @return bool|string
1296 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1297 if ( !is_array( $names ) ) {
1298 $names = array( $names );
1301 foreach ( $names as $name ) {
1302 $command = $path . DIRECTORY_SEPARATOR
. $name;
1304 wfSuppressWarnings();
1305 $file_exists = file_exists( $command );
1306 wfRestoreWarnings();
1308 if ( $file_exists ) {
1309 if ( !$versionInfo ) {
1313 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1314 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1324 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1325 * @see locateExecutable()
1326 * @param array $names Array of possible names.
1327 * @param array|bool $versionInfo Default: false or array with two members:
1328 * 0 => Command to run for version check, with $1 for the full executable name
1329 * 1 => String to compare the output with
1331 * If $versionInfo is not false, only executables with a version
1332 * matching $versionInfo[1] will be returned.
1333 * @return bool|string
1335 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1336 foreach ( self
::getPossibleBinPaths() as $path ) {
1337 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1338 if ( $exe !== false ) {
1347 * Checks if scripts located in the given directory can be executed via the given URL.
1349 * Used only by environment checks.
1350 * @param string $dir
1351 * @param string $url
1352 * @return bool|int|string
1354 public function dirIsExecutable( $dir, $url ) {
1355 $scriptTypes = array(
1357 "<?php echo 'ex' . 'ec';",
1358 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1362 // it would be good to check other popular languages here, but it'll be slow.
1364 wfSuppressWarnings();
1366 foreach ( $scriptTypes as $ext => $contents ) {
1367 foreach ( $contents as $source ) {
1368 $file = 'exectest.' . $ext;
1370 if ( !file_put_contents( $dir . $file, $source ) ) {
1375 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1376 } catch ( MWException
$e ) {
1377 // Http::get throws with allow_url_fopen = false and no curl extension.
1380 unlink( $dir . $file );
1382 if ( $text == 'exec' ) {
1383 wfRestoreWarnings();
1390 wfRestoreWarnings();
1396 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1398 * @param string $moduleName Name of module to check.
1401 public static function apacheModulePresent( $moduleName ) {
1402 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1405 // try it the hard way
1407 phpinfo( INFO_MODULES
);
1408 $info = ob_get_clean();
1410 return strpos( $info, $moduleName ) !== false;
1414 * ParserOptions are constructed before we determined the language, so fix it
1416 * @param Language $lang
1418 public function setParserLanguage( $lang ) {
1419 $this->parserOptions
->setTargetLanguage( $lang );
1420 $this->parserOptions
->setUserLang( $lang );
1424 * Overridden by WebInstaller to provide lastPage parameters.
1425 * @param string $page
1428 protected function getDocUrl( $page ) {
1429 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1433 * Finds extensions that follow the format /$directory/Name/Name.php,
1434 * and returns an array containing the value for 'Name' for each found extension.
1436 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1438 * @param string $directory Directory to search in
1441 public function findExtensions( $directory = 'extensions' ) {
1442 if ( $this->getVar( 'IP' ) === null ) {
1446 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1447 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1451 $dh = opendir( $extDir );
1453 while ( ( $file = readdir( $dh ) ) !== false ) {
1454 if ( !is_dir( "$extDir/$file" ) ) {
1457 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1462 natcasesort( $exts );
1468 * Installs the auto-detected extensions.
1472 protected function includeExtensions() {
1474 $exts = $this->getVar( '_Extensions' );
1475 $IP = $this->getVar( 'IP' );
1478 * We need to include DefaultSettings before including extensions to avoid
1479 * warnings about unset variables. However, the only thing we really
1480 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1481 * if the extension has hidden hook registration in $wgExtensionFunctions,
1482 * but we're not opening that can of worms
1483 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1485 global $wgAutoloadClasses;
1486 $wgAutoloadClasses = array();
1488 require "$IP/includes/DefaultSettings.php";
1490 foreach ( $exts as $e ) {
1491 require_once "$IP/extensions/$e/$e.php";
1494 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1495 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1497 // Unset everyone else's hooks. Lord knows what someone might be doing
1498 // in ParserFirstCallInit (see bug 27171)
1499 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1501 return Status
::newGood();
1505 * Get an array of install steps. Should always be in the format of
1507 * 'name' => 'someuniquename',
1508 * 'callback' => array( $obj, 'method' ),
1510 * There must be a config-install-$name message defined per step, which will
1511 * be shown on install.
1513 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1516 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1517 $coreInstallSteps = array(
1518 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1519 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1520 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1521 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1522 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1523 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1524 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1527 // Build the array of install steps starting from the core install list,
1528 // then adding any callbacks that wanted to attach after a given step
1529 foreach ( $coreInstallSteps as $step ) {
1530 $this->installSteps
[] = $step;
1531 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1532 $this->installSteps
= array_merge(
1533 $this->installSteps
,
1534 $this->extraInstallSteps
[$step['name']]
1539 // Prepend any steps that want to be at the beginning
1540 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1541 $this->installSteps
= array_merge(
1542 $this->extraInstallSteps
['BEGINNING'],
1547 // Extensions should always go first, chance to tie into hooks and such
1548 if ( count( $this->getVar( '_Extensions' ) ) ) {
1549 array_unshift( $this->installSteps
,
1550 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1552 $this->installSteps
[] = array(
1553 'name' => 'extension-tables',
1554 'callback' => array( $installer, 'createExtensionTables' )
1558 return $this->installSteps
;
1562 * Actually perform the installation.
1564 * @param callable $startCB A callback array for the beginning of each step
1565 * @param callable $endCB A callback array for the end of each step
1567 * @return array Array of Status objects
1569 public function performInstallation( $startCB, $endCB ) {
1570 $installResults = array();
1571 $installer = $this->getDBInstaller();
1572 $installer->preInstall();
1573 $steps = $this->getInstallSteps( $installer );
1574 foreach ( $steps as $stepObj ) {
1575 $name = $stepObj['name'];
1576 call_user_func_array( $startCB, array( $name ) );
1578 // Perform the callback step
1579 $status = call_user_func( $stepObj['callback'], $installer );
1581 // Output and save the results
1582 call_user_func( $endCB, $name, $status );
1583 $installResults[$name] = $status;
1585 // If we've hit some sort of fatal, we need to bail.
1586 // Callback already had a chance to do output above.
1587 if ( !$status->isOk() ) {
1591 if ( $status->isOk() ) {
1592 $this->setVar( '_InstallDone', true );
1595 return $installResults;
1599 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1603 public function generateKeys() {
1604 $keys = array( 'wgSecretKey' => 64 );
1605 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1606 $keys['wgUpgradeKey'] = 16;
1609 return $this->doGenerateKeys( $keys );
1613 * Generate a secret value for variables using our CryptRand generator.
1614 * Produce a warning if the random source was insecure.
1616 * @param array $keys
1619 protected function doGenerateKeys( $keys ) {
1620 $status = Status
::newGood();
1623 foreach ( $keys as $name => $length ) {
1624 $secretKey = MWCryptRand
::generateHex( $length, true );
1625 if ( !MWCryptRand
::wasStrong() ) {
1629 $this->setVar( $name, $secretKey );
1633 $names = array_keys( $keys );
1634 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1636 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1643 * Create the first user account, grant it sysop and bureaucrat rights
1647 protected function createSysop() {
1648 $name = $this->getVar( '_AdminName' );
1649 $user = User
::newFromName( $name );
1652 // We should've validated this earlier anyway!
1653 return Status
::newFatal( 'config-admin-error-user', $name );
1656 if ( $user->idForName() == 0 ) {
1657 $user->addToDatabase();
1660 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1661 } catch ( PasswordError
$pwe ) {
1662 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1665 $user->addGroup( 'sysop' );
1666 $user->addGroup( 'bureaucrat' );
1667 if ( $this->getVar( '_AdminEmail' ) ) {
1668 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1670 $user->saveSettings();
1672 // Update user count
1673 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1674 $ssUpdate->doUpdate();
1676 $status = Status
::newGood();
1678 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1679 $this->subscribeToMediaWikiAnnounce( $status );
1688 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1690 'email' => $this->getVar( '_AdminEmail' ),
1695 // Mailman doesn't support as many languages as we do, so check to make
1696 // sure their selected language is available
1697 $myLang = $this->getVar( '_UserLang' );
1698 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1699 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1700 $params['language'] = $myLang;
1703 if ( MWHttpRequest
::canMakeRequests() ) {
1704 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1705 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1706 if ( !$res->isOK() ) {
1707 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1710 $s->warning( 'config-install-subscribe-notpossible' );
1715 * Insert Main Page with default content.
1717 * @param DatabaseInstaller $installer
1720 protected function createMainpage( DatabaseInstaller
$installer ) {
1721 $status = Status
::newGood();
1723 $page = WikiPage
::factory( Title
::newMainPage() );
1724 $content = new WikitextContent(
1725 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1726 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1729 $page->doEditContent( $content,
1733 User
::newFromName( 'MediaWiki default' )
1735 } catch ( MWException
$e ) {
1736 //using raw, because $wgShowExceptionDetails can not be set yet
1737 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1744 * Override the necessary bits of the config to run an installation.
1746 public static function overrideConfig() {
1747 define( 'MW_NO_SESSION', 1 );
1749 // Don't access the database
1750 $GLOBALS['wgUseDatabaseMessages'] = false;
1751 // Don't cache langconv tables
1752 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1754 $GLOBALS['wgShowExceptionDetails'] = true;
1755 // Don't break forms
1756 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1758 // Extended debugging
1759 $GLOBALS['wgShowSQLErrors'] = true;
1760 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1762 // Allow multiple ob_flush() calls
1763 $GLOBALS['wgDisableOutputCompression'] = true;
1765 // Use a sensible cookie prefix (not my_wiki)
1766 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1768 // Some of the environment checks make shell requests, remove limits
1769 $GLOBALS['wgMaxShellMemory'] = 0;
1771 // Don't bother embedding images into generated CSS, which is not cached
1772 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1773 return $less->toBool( false );
1778 * Add an installation step following the given step.
1780 * @param callable $callback A valid installation callback array, in this form:
1781 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1782 * @param string $findStep The step to find. Omit to put the step at the beginning
1784 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1785 $this->extraInstallSteps
[$findStep][] = $callback;
1789 * Disable the time limit for execution.
1790 * Some long-running pages (Install, Upgrade) will want to do this
1792 protected function disableTimeLimit() {
1793 wfSuppressWarnings();
1794 set_time_limit( 0 );
1795 wfRestoreWarnings();