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(),
223 '_MemCachedServers' => '',
224 '_UpgradeKeySupplied' => false,
225 '_ExistingDBSettings' => false,
227 // $wgLogo is probably wrong (bug 48084); set something that will work.
228 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
229 'wgLogo' => '$wgStylePath/common/images/wiki.png',
233 * The actual list of installation steps. This will be initialized by getInstallSteps()
237 private $installSteps = array();
240 * Extra steps for installation, for things like DatabaseInstallers to modify
244 protected $extraInstallSteps = array();
247 * Known object cache types and the functions used to test for their existence.
251 protected $objectCaches = array(
252 'xcache' => 'xcache_get',
253 'apc' => 'apc_fetch',
254 'wincache' => 'wincache_ucache_get'
258 * User rights profiles.
262 public $rightsProfiles = array(
265 '*' => array( 'edit' => false )
269 'createaccount' => false,
275 'createaccount' => false,
287 public $licenses = array(
289 'url' => 'http://creativecommons.org/licenses/by/3.0/',
290 'icon' => '{$wgStylePath}/common/images/cc-by.png',
293 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
294 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
296 'cc-by-nc-sa' => array(
297 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
298 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
301 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
302 'icon' => '{$wgStylePath}/common/images/cc-0.png',
306 'icon' => '{$wgStylePath}/common/images/public-domain.png',
309 'url' => 'http://www.gnu.org/copyleft/fdl.html',
310 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
317 'cc-choose' => array(
318 // Details will be filled in by the selector.
326 * URL to mediawiki-announce subscription
328 protected $mediaWikiAnnounceUrl =
329 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
332 * Supported language codes for Mailman
334 protected $mediaWikiAnnounceLanguages = array(
335 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
336 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
337 'sl', 'sr', 'sv', 'tr', 'uk'
341 * UI interface for displaying a short message
342 * The parameters are like parameters to wfMessage().
343 * The messages will be in wikitext format, which will be converted to an
344 * output format such as HTML or text before being sent to the user.
347 abstract public function showMessage( $msg /*, ... */ );
350 * Same as showMessage(), but for displaying errors
353 abstract public function showError( $msg /*, ... */ );
356 * Shows messages to the user through a Status object
357 * @param Status $status
359 public function showStatusMessage( Status
$status ) {
360 $errors = array_merge( $status->getErrorsArray(), $status->getWarningsArray() );
362 foreach ( $errors as $error ) {
363 call_user_func( 'showMessage', $error );
369 * Constructor, always call this from child classes.
371 public function __construct() {
372 global $wgMessagesDirs, $wgUser;
374 // Disable the i18n cache
375 Language
::getLocalisationCache()->disableBackend();
376 // Disable LoadBalancer and wfGetDB etc.
377 LBFactory
::disableBackend();
379 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
380 // SqlBagOStuff will then throw since we just disabled wfGetDB)
381 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
382 ObjectCache
::clear();
383 $emptyCache = array( 'class' => 'EmptyBagOStuff' );
384 $GLOBALS['wgObjectCaches'] = array(
385 CACHE_NONE
=> $emptyCache,
386 CACHE_DB
=> $emptyCache,
387 CACHE_ANYTHING
=> $emptyCache,
388 CACHE_MEMCACHED
=> $emptyCache,
391 // Load the installer's i18n.
392 $wgMessagesDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
394 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
395 $wgUser = User
::newFromId( 0 );
397 $this->settings
= $this->internalDefaults
;
399 foreach ( $this->defaultVarNames
as $var ) {
400 $this->settings
[$var] = $GLOBALS[$var];
403 $this->doEnvironmentPreps();
405 $this->compiledDBs
= array();
406 foreach ( self
::getDBTypes() as $type ) {
407 $installer = $this->getDBInstaller( $type );
409 if ( !$installer->isCompiled() ) {
412 $this->compiledDBs
[] = $type;
415 $this->parserTitle
= Title
::newFromText( 'Installer' );
416 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
417 $this->parserOptions
->setEditSection( false );
421 * Get a list of known DB types.
425 public static function getDBTypes() {
426 return self
::$dbTypes;
430 * Do initial checks of the PHP environment. Set variables according to
431 * the observed environment.
433 * It's possible that this may be called under the CLI SAPI, not the SAPI
434 * that the wiki will primarily run under. In that case, the subclass should
435 * initialise variables such as wgScriptPath, before calling this function.
437 * Under the web subclass, it can already be assumed that PHP 5+ is in use
438 * and that sessions are working.
442 public function doEnvironmentChecks() {
443 // Php version has already been checked by entry scripts
444 // Show message here for information purposes
445 $this->showMessage( 'config-env-php', PHP_VERSION
);
448 // Must go here because an old version of PCRE can prevent other checks from completing
449 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
450 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
451 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
454 foreach ( $this->envChecks
as $check ) {
455 $status = $this->$check();
456 if ( $status === false ) {
462 $this->setVar( '_Environment', $good );
464 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
467 public function doEnvironmentPreps() {
468 foreach ( $this->envPreps
as $prep ) {
474 * Set a MW configuration variable, or internal installer configuration variable.
476 * @param string $name
477 * @param mixed $value
479 public function setVar( $name, $value ) {
480 $this->settings
[$name] = $value;
484 * Get an MW configuration variable, or internal installer configuration variable.
485 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
486 * Installer variables are typically prefixed by an underscore.
488 * @param string $name
489 * @param mixed $default
493 public function getVar( $name, $default = null ) {
494 if ( !isset( $this->settings
[$name] ) ) {
497 return $this->settings
[$name];
502 * Get a list of DBs supported by current PHP setup
506 public function getCompiledDBs() {
507 return $this->compiledDBs
;
511 * Get an instance of DatabaseInstaller for the specified DB type.
513 * @param mixed $type DB installer for which is needed, false to use default.
515 * @return DatabaseInstaller
517 public function getDBInstaller( $type = false ) {
519 $type = $this->getVar( 'wgDBtype' );
522 $type = strtolower( $type );
524 if ( !isset( $this->dbInstallers
[$type] ) ) {
525 $class = ucfirst( $type ) . 'Installer';
526 $this->dbInstallers
[$type] = new $class( $this );
529 return $this->dbInstallers
[$type];
533 * Determine if LocalSettings.php exists. If it does, return its variables.
537 public static function getExistingLocalSettings() {
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
740 protected function envCheckRegisterGlobals() {
741 if ( wfIniGetBool( 'register_globals' ) ) {
742 $this->showMessage( 'config-register-globals-error' );
750 * Some versions of libxml+PHP break < and > encoding horribly
753 protected function envCheckBrokenXML() {
754 $test = new PhpXmlBugTester();
756 $this->showError( 'config-brokenlibxml' );
765 * Environment check for magic_quotes_runtime.
768 protected function envCheckMagicQuotes() {
769 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
770 $this->showError( 'config-magic-quotes-runtime' );
779 * Environment check for magic_quotes_sybase.
782 protected function envCheckMagicSybase() {
783 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
784 $this->showError( 'config-magic-quotes-sybase' );
793 * Environment check for mbstring.func_overload.
796 protected function envCheckMbstring() {
797 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
798 $this->showError( 'config-mbstring' );
807 * Environment check for safe_mode.
810 protected function envCheckSafeMode() {
811 if ( wfIniGetBool( 'safe_mode' ) ) {
812 $this->setVar( '_SafeMode', true );
813 $this->showMessage( 'config-safe-mode' );
820 * Environment check for the XML module.
823 protected function envCheckXML() {
824 if ( !function_exists( "utf8_encode" ) ) {
825 $this->showError( 'config-xml-bad' );
834 * Environment check for the PCRE module.
836 * @note If this check were to fail, the parser would
837 * probably throw an exception before the result
838 * of this check is shown to the user.
841 protected function envCheckPCRE() {
842 wfSuppressWarnings();
843 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
844 // Need to check for \p support too, as PCRE can be compiled
845 // with utf8 support, but not unicode property support.
846 // check that \p{Zs} (space separators) matches
847 // U+3000 (Ideographic space)
848 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
850 if ( $regexd != '--' ||
$regexprop != '--' ) {
851 $this->showError( 'config-pcre-no-utf8' );
860 * Environment check for available memory.
863 protected function envCheckMemory() {
864 $limit = ini_get( 'memory_limit' );
866 if ( !$limit ||
$limit == -1 ) {
870 $n = wfShorthandToInteger( $limit );
872 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
873 $newLimit = "{$this->minMemorySize}M";
875 if ( ini_set( "memory_limit", $newLimit ) === false ) {
876 $this->showMessage( 'config-memory-bad', $limit );
878 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
879 $this->setVar( '_RaiseMemory', true );
887 * Environment check for compiled object cache types.
889 protected function envCheckCache() {
891 foreach ( $this->objectCaches
as $name => $function ) {
892 if ( function_exists( $function ) ) {
893 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
896 $caches[$name] = true;
901 $this->showMessage( 'config-no-cache' );
904 $this->setVar( '_Caches', $caches );
908 * Scare user to death if they have mod_security
911 protected function envCheckModSecurity() {
912 if ( self
::apacheModulePresent( 'mod_security' ) ) {
913 $this->showMessage( 'config-mod-security' );
920 * Search for GNU diff3.
923 protected function envCheckDiff3() {
924 $names = array( "gdiff3", "diff3", "diff3.exe" );
925 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
927 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
930 $this->setVar( 'wgDiff3', $diff3 );
932 $this->setVar( 'wgDiff3', false );
933 $this->showMessage( 'config-diff3-bad' );
940 * Environment check for ImageMagick and GD.
943 protected function envCheckGraphics() {
944 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
945 $versionInfo = array( '$1 -version', 'ImageMagick' );
946 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
948 $this->setVar( 'wgImageMagickConvertCommand', '' );
950 $this->setVar( 'wgImageMagickConvertCommand', $convert );
951 $this->showMessage( 'config-imagemagick', $convert );
954 } elseif ( function_exists( 'imagejpeg' ) ) {
955 $this->showMessage( 'config-gd' );
957 $this->showMessage( 'config-no-scaling' );
969 protected function envCheckGit() {
970 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
971 $versionInfo = array( '$1 --version', 'git version' );
973 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
976 $this->setVar( 'wgGitBin', $git );
977 $this->showMessage( 'config-git', $git );
979 $this->setVar( 'wgGitBin', false );
980 $this->showMessage( 'config-git-bad' );
987 * Environment check to inform user which server we've assumed.
991 protected function envCheckServer() {
992 $server = $this->envGetDefaultServer();
993 if ( $server !== null ) {
994 $this->showMessage( 'config-using-server', $server );
1000 * Environment check to inform user which paths we've assumed.
1004 protected function envCheckPath() {
1007 $this->getVar( 'wgServer' ),
1008 $this->getVar( 'wgScriptPath' )
1014 * Environment check for preferred locale in shell
1017 protected function envCheckShellLocale() {
1018 $os = php_uname( 's' );
1019 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1021 if ( !in_array( $os, $supported ) ) {
1025 # Get a list of available locales.
1027 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1033 $lines = array_map( 'trim', explode( "\n", $lines ) );
1034 $candidatesByLocale = array();
1035 $candidatesByLang = array();
1037 foreach ( $lines as $line ) {
1038 if ( $line === '' ) {
1042 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1046 list( , $lang, , , ) = $m;
1048 $candidatesByLocale[$m[0]] = $m;
1049 $candidatesByLang[$lang][] = $m;
1052 # Try the current value of LANG.
1053 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1054 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1059 # Try the most common ones.
1060 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1061 foreach ( $commonLocales as $commonLocale ) {
1062 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1063 $this->setVar( 'wgShellLocale', $commonLocale );
1069 # Is there an available locale in the Wiki's language?
1070 $wikiLang = $this->getVar( 'wgLanguageCode' );
1072 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1073 $m = reset( $candidatesByLang[$wikiLang] );
1074 $this->setVar( 'wgShellLocale', $m[0] );
1079 # Are there any at all?
1080 if ( count( $candidatesByLocale ) ) {
1081 $m = reset( $candidatesByLocale );
1082 $this->setVar( 'wgShellLocale', $m[0] );
1092 * Environment check for the permissions of the uploads directory
1095 protected function envCheckUploadsDirectory() {
1098 $dir = $IP . '/images/';
1099 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1100 $safe = !$this->dirIsExecutable( $dir, $url );
1103 $this->showMessage( 'config-uploads-not-safe', $dir );
1110 * Checks if suhosin.get.max_value_length is set, and if so generate
1111 * a warning because it decreases ResourceLoader performance.
1114 protected function envCheckSuhosinMaxValueLength() {
1115 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1116 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1117 // Only warn if the value is below the sane 1024
1118 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1125 * Convert a hex string representing a Unicode code point to that code point.
1129 protected function unicodeChar( $c ) {
1133 } elseif ( $c <= 0x7FF ) {
1134 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1135 } elseif ( $c <= 0xFFFF ) {
1136 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1137 . chr( 0x80 |
$c & 0x3F );
1138 } elseif ( $c <= 0x10FFFF ) {
1139 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1140 . chr( 0x80 |
$c >> 6 & 0x3F )
1141 . chr( 0x80 |
$c & 0x3F );
1148 * Check the libicu version
1150 protected function envCheckLibicu() {
1151 $utf8 = function_exists( 'utf8_normalize' );
1152 $intl = function_exists( 'normalizer_normalize' );
1155 * This needs to be updated something that the latest libicu
1156 * will properly normalize. This normalization was found at
1157 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1158 * Note that we use the hex representation to create the code
1159 * points in order to avoid any Unicode-destroying during transit.
1161 $not_normal_c = $this->unicodeChar( "FA6C" );
1162 $normal_c = $this->unicodeChar( "242EE" );
1164 $useNormalizer = 'php';
1165 $needsUpdate = false;
1168 * We're going to prefer the pecl extension here unless
1169 * utf8_normalize is more up to date.
1172 $useNormalizer = 'utf8';
1173 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1174 if ( $utf8 !== $normal_c ) {
1175 $needsUpdate = true;
1179 $useNormalizer = 'intl';
1180 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1181 if ( $intl !== $normal_c ) {
1182 $needsUpdate = true;
1186 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1187 // 'config-unicode-using-intl'
1188 if ( $useNormalizer === 'php' ) {
1189 $this->showMessage( 'config-unicode-pure-php-warning' );
1191 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1192 if ( $needsUpdate ) {
1193 $this->showMessage( 'config-unicode-update-warning' );
1201 protected function envCheckCtype() {
1202 if ( !function_exists( 'ctype_digit' ) ) {
1203 $this->showError( 'config-ctype' );
1214 protected function envCheckIconv() {
1215 if ( !function_exists( 'iconv' ) ) {
1216 $this->showError( 'config-iconv' );
1227 protected function envCheckJSON() {
1228 if ( !function_exists( 'json_decode' ) ) {
1229 $this->showError( 'config-json' );
1238 * Environment prep for the server hostname.
1240 protected function envPrepServer() {
1241 $server = $this->envGetDefaultServer();
1242 if ( $server !== null ) {
1243 $this->setVar( 'wgServer', $server );
1248 * Helper function to be called from envPrepServer()
1251 abstract protected function envGetDefaultServer();
1254 * Environment prep for setting the preferred PHP file extension.
1256 protected function envPrepExtension() {
1257 // @todo FIXME: Detect this properly
1258 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1263 $this->setVar( 'wgScriptExtension', $ext );
1267 * Environment prep for setting $IP and $wgScriptPath.
1269 protected function envPrepPath() {
1271 $IP = dirname( dirname( __DIR__
) );
1272 $this->setVar( 'IP', $IP );
1276 * Get an array of likely places we can find executables. Check a bunch
1277 * of known Unix-like defaults, as well as the PATH environment variable
1278 * (which should maybe make it work for Windows?)
1282 protected static function getPossibleBinPaths() {
1284 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1285 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1286 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1291 * Search a path for any of the given executable names. Returns the
1292 * executable name if found. Also checks the version string returned
1293 * by each executable.
1295 * Used only by environment checks.
1297 * @param string $path path to search
1298 * @param array $names of executable names
1299 * @param array|bool $versionInfo False or array with two members:
1300 * 0 => Command to run for version check, with $1 for the full executable name
1301 * 1 => String to compare the output with
1303 * If $versionInfo is not false, only executables with a version
1304 * matching $versionInfo[1] will be returned.
1305 * @return bool|string
1307 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1308 if ( !is_array( $names ) ) {
1309 $names = array( $names );
1312 foreach ( $names as $name ) {
1313 $command = $path . DIRECTORY_SEPARATOR
. $name;
1315 wfSuppressWarnings();
1316 $file_exists = file_exists( $command );
1317 wfRestoreWarnings();
1319 if ( $file_exists ) {
1320 if ( !$versionInfo ) {
1324 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1325 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1335 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1336 * @see locateExecutable()
1337 * @param array $names Array of possible names.
1338 * @param array|bool $versionInfo Default: false or array with two members:
1339 * 0 => Command to run for version check, with $1 for the full executable name
1340 * 1 => String to compare the output with
1342 * If $versionInfo is not false, only executables with a version
1343 * matching $versionInfo[1] will be returned.
1344 * @return bool|string
1346 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1347 foreach ( self
::getPossibleBinPaths() as $path ) {
1348 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1349 if ( $exe !== false ) {
1358 * Checks if scripts located in the given directory can be executed via the given URL.
1360 * Used only by environment checks.
1361 * @param string $dir
1362 * @param string $url
1363 * @return bool|int|string
1365 public function dirIsExecutable( $dir, $url ) {
1366 $scriptTypes = array(
1368 "<?php echo 'ex' . 'ec';",
1369 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1373 // it would be good to check other popular languages here, but it'll be slow.
1375 wfSuppressWarnings();
1377 foreach ( $scriptTypes as $ext => $contents ) {
1378 foreach ( $contents as $source ) {
1379 $file = 'exectest.' . $ext;
1381 if ( !file_put_contents( $dir . $file, $source ) ) {
1386 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1387 } catch ( MWException
$e ) {
1388 // Http::get throws with allow_url_fopen = false and no curl extension.
1391 unlink( $dir . $file );
1393 if ( $text == 'exec' ) {
1394 wfRestoreWarnings();
1401 wfRestoreWarnings();
1407 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1409 * @param string $moduleName Name of module to check.
1412 public static function apacheModulePresent( $moduleName ) {
1413 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1416 // try it the hard way
1418 phpinfo( INFO_MODULES
);
1419 $info = ob_get_clean();
1421 return strpos( $info, $moduleName ) !== false;
1425 * ParserOptions are constructed before we determined the language, so fix it
1427 * @param Language $lang
1429 public function setParserLanguage( $lang ) {
1430 $this->parserOptions
->setTargetLanguage( $lang );
1431 $this->parserOptions
->setUserLang( $lang );
1435 * Overridden by WebInstaller to provide lastPage parameters.
1436 * @param string $page
1439 protected function getDocUrl( $page ) {
1440 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1444 * Finds extensions that follow the format /$directory/Name/Name.php,
1445 * and returns an array containing the value for 'Name' for each found extension.
1447 * Reasonable values for $directory include 'extensions' (the default) and 'skins'.
1449 * @param string $directory Directory to search in
1452 public function findExtensions( $directory = 'extensions' ) {
1453 if ( $this->getVar( 'IP' ) === null ) {
1457 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1458 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1462 $dh = opendir( $extDir );
1464 while ( ( $file = readdir( $dh ) ) !== false ) {
1465 if ( !is_dir( "$extDir/$file" ) ) {
1468 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1473 natcasesort( $exts );
1479 * Installs the auto-detected extensions.
1483 protected function includeExtensions() {
1485 $exts = $this->getVar( '_Extensions' );
1486 $IP = $this->getVar( 'IP' );
1489 * We need to include DefaultSettings before including extensions to avoid
1490 * warnings about unset variables. However, the only thing we really
1491 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1492 * if the extension has hidden hook registration in $wgExtensionFunctions,
1493 * but we're not opening that can of worms
1494 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1496 global $wgAutoloadClasses;
1497 $wgAutoloadClasses = array();
1499 require "$IP/includes/DefaultSettings.php";
1501 foreach ( $exts as $e ) {
1502 require_once "$IP/extensions/$e/$e.php";
1505 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1506 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1508 // Unset everyone else's hooks. Lord knows what someone might be doing
1509 // in ParserFirstCallInit (see bug 27171)
1510 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1512 return Status
::newGood();
1516 * Get an array of install steps. Should always be in the format of
1518 * 'name' => 'someuniquename',
1519 * 'callback' => array( $obj, 'method' ),
1521 * There must be a config-install-$name message defined per step, which will
1522 * be shown on install.
1524 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1527 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1528 $coreInstallSteps = array(
1529 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1530 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1531 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1532 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1533 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1534 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1535 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1538 // Build the array of install steps starting from the core install list,
1539 // then adding any callbacks that wanted to attach after a given step
1540 foreach ( $coreInstallSteps as $step ) {
1541 $this->installSteps
[] = $step;
1542 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1543 $this->installSteps
= array_merge(
1544 $this->installSteps
,
1545 $this->extraInstallSteps
[$step['name']]
1550 // Prepend any steps that want to be at the beginning
1551 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1552 $this->installSteps
= array_merge(
1553 $this->extraInstallSteps
['BEGINNING'],
1558 // Extensions should always go first, chance to tie into hooks and such
1559 if ( count( $this->getVar( '_Extensions' ) ) ) {
1560 array_unshift( $this->installSteps
,
1561 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1563 $this->installSteps
[] = array(
1564 'name' => 'extension-tables',
1565 'callback' => array( $installer, 'createExtensionTables' )
1569 return $this->installSteps
;
1573 * Actually perform the installation.
1575 * @param callable $startCB A callback array for the beginning of each step
1576 * @param callable $endCB A callback array for the end of each step
1578 * @return array Array of Status objects
1580 public function performInstallation( $startCB, $endCB ) {
1581 $installResults = array();
1582 $installer = $this->getDBInstaller();
1583 $installer->preInstall();
1584 $steps = $this->getInstallSteps( $installer );
1585 foreach ( $steps as $stepObj ) {
1586 $name = $stepObj['name'];
1587 call_user_func_array( $startCB, array( $name ) );
1589 // Perform the callback step
1590 $status = call_user_func( $stepObj['callback'], $installer );
1592 // Output and save the results
1593 call_user_func( $endCB, $name, $status );
1594 $installResults[$name] = $status;
1596 // If we've hit some sort of fatal, we need to bail.
1597 // Callback already had a chance to do output above.
1598 if ( !$status->isOk() ) {
1602 if ( $status->isOk() ) {
1603 $this->setVar( '_InstallDone', true );
1606 return $installResults;
1610 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1614 public function generateKeys() {
1615 $keys = array( 'wgSecretKey' => 64 );
1616 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1617 $keys['wgUpgradeKey'] = 16;
1620 return $this->doGenerateKeys( $keys );
1624 * Generate a secret value for variables using our CryptRand generator.
1625 * Produce a warning if the random source was insecure.
1627 * @param array $keys
1630 protected function doGenerateKeys( $keys ) {
1631 $status = Status
::newGood();
1634 foreach ( $keys as $name => $length ) {
1635 $secretKey = MWCryptRand
::generateHex( $length, true );
1636 if ( !MWCryptRand
::wasStrong() ) {
1640 $this->setVar( $name, $secretKey );
1644 $names = array_keys( $keys );
1645 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1647 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1654 * Create the first user account, grant it sysop and bureaucrat rights
1658 protected function createSysop() {
1659 $name = $this->getVar( '_AdminName' );
1660 $user = User
::newFromName( $name );
1663 // We should've validated this earlier anyway!
1664 return Status
::newFatal( 'config-admin-error-user', $name );
1667 if ( $user->idForName() == 0 ) {
1668 $user->addToDatabase();
1671 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1672 } catch ( PasswordError
$pwe ) {
1673 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1676 $user->addGroup( 'sysop' );
1677 $user->addGroup( 'bureaucrat' );
1678 if ( $this->getVar( '_AdminEmail' ) ) {
1679 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1681 $user->saveSettings();
1683 // Update user count
1684 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1685 $ssUpdate->doUpdate();
1687 $status = Status
::newGood();
1689 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1690 $this->subscribeToMediaWikiAnnounce( $status );
1699 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1701 'email' => $this->getVar( '_AdminEmail' ),
1706 // Mailman doesn't support as many languages as we do, so check to make
1707 // sure their selected language is available
1708 $myLang = $this->getVar( '_UserLang' );
1709 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1710 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1711 $params['language'] = $myLang;
1714 if ( MWHttpRequest
::canMakeRequests() ) {
1715 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1716 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1717 if ( !$res->isOK() ) {
1718 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1721 $s->warning( 'config-install-subscribe-notpossible' );
1726 * Insert Main Page with default content.
1728 * @param DatabaseInstaller $installer
1731 protected function createMainpage( DatabaseInstaller
$installer ) {
1732 $status = Status
::newGood();
1734 $page = WikiPage
::factory( Title
::newMainPage() );
1735 $content = new WikitextContent(
1736 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1737 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1740 $page->doEditContent( $content,
1744 User
::newFromName( 'MediaWiki default' )
1746 } catch ( MWException
$e ) {
1747 //using raw, because $wgShowExceptionDetails can not be set yet
1748 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1755 * Override the necessary bits of the config to run an installation.
1757 public static function overrideConfig() {
1758 define( 'MW_NO_SESSION', 1 );
1760 // Don't access the database
1761 $GLOBALS['wgUseDatabaseMessages'] = false;
1762 // Don't cache langconv tables
1763 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1765 $GLOBALS['wgShowExceptionDetails'] = true;
1766 // Don't break forms
1767 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1769 // Extended debugging
1770 $GLOBALS['wgShowSQLErrors'] = true;
1771 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1773 // Allow multiple ob_flush() calls
1774 $GLOBALS['wgDisableOutputCompression'] = true;
1776 // Use a sensible cookie prefix (not my_wiki)
1777 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1779 // Some of the environment checks make shell requests, remove limits
1780 $GLOBALS['wgMaxShellMemory'] = 0;
1782 // Don't bother embedding images into generated CSS, which is not cached
1783 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1784 return $less->toBool( false );
1789 * Add an installation step following the given step.
1791 * @param callable $callback A valid installation callback array, in this form:
1792 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1793 * @param string $findStep The step to find. Omit to put the step at the beginning
1795 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1796 $this->extraInstallSteps
[$findStep][] = $callback;
1800 * Disable the time limit for execution.
1801 * Some long-running pages (Install, Upgrade) will want to do this
1803 protected function disableTimeLimit() {
1804 wfSuppressWarnings();
1805 set_time_limit( 0 );
1806 wfRestoreWarnings();