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
{
41 // This is the absolute minimum PHP version we can support
42 const MINIMUM_PHP_VERSION
= '5.3.2';
45 * The oldest version of PCRE we can support.
47 * Defining this is necessary because PHP may be linked with a system version
48 * of PCRE, which may be older than that bundled with the minimum PHP version.
50 const MINIMUM_PCRE_VERSION
= '7.2';
58 * List of detected DBs, access using getCompiledDBs().
62 protected $compiledDBs;
65 * Cached DB installer instances, access using getDBInstaller().
69 protected $dbInstallers = array();
72 * Minimum memory size in MB.
76 protected $minMemorySize = 50;
79 * Cached Title, used by parse().
83 protected $parserTitle;
86 * Cached ParserOptions, used by parse().
90 protected $parserOptions;
93 * Known database types. These correspond to the class names <type>Installer,
94 * and are also MediaWiki database types valid for $wgDBtype.
96 * To add a new type, create a <type>Installer class and a Database<type>
97 * class, and add a config-type-<type> message to MessagesEn.php.
101 protected static $dbTypes = array(
110 * A list of environment check methods called by doEnvironmentChecks().
111 * These may output warnings using showMessage(), and/or abort the
112 * installation process by returning false.
116 protected $envChecks = array(
118 'envCheckRegisterGlobals',
120 'envCheckMagicQuotes',
121 'envCheckMagicSybase',
128 'envCheckModSecurity',
135 'envCheckShellLocale',
136 'envCheckUploadsDirectory',
138 'envCheckSuhosinMaxValueLength',
144 * MediaWiki configuration globals that will eventually be passed through
145 * to LocalSettings.php. The names only are given here, the defaults
146 * typically come from DefaultSettings.php.
150 protected $defaultVarNames = array(
162 'wgEmailAuthentication',
165 'wgImageMagickConvertCommand',
171 'wgDeletedDirectory',
176 'wgUseInstantCommons',
179 'wgResourceLoaderMaxQueryLength',
183 * Variables that are stored alongside globals, and are used for any
184 * configuration of the installation process aside from the MediaWiki
185 * configuration. Map of names to defaults.
189 protected $internalDefaults = array(
191 '_Environment' => false,
192 '_SafeMode' => false,
193 '_RaiseMemory' => false,
194 '_UpgradeDone' => false,
195 '_InstallDone' => false,
196 '_Caches' => array(),
197 '_InstallPassword' => '',
198 '_SameAccount' => true,
199 '_CreateDBAccount' => false,
200 '_NamespaceType' => 'site-name',
201 '_AdminName' => '', // will be set later, when the user selects language
202 '_AdminPassword' => '',
203 '_AdminPassword2' => '',
205 '_Subscribe' => false,
206 '_SkipOptional' => 'continue',
207 '_RightsProfile' => 'wiki',
208 '_LicenseCode' => 'none',
210 '_Extensions' => array(),
211 '_MemCachedServers' => '',
212 '_UpgradeKeySupplied' => false,
213 '_ExistingDBSettings' => false,
217 * The actual list of installation steps. This will be initialized by getInstallSteps()
221 private $installSteps = array();
224 * Extra steps for installation, for things like DatabaseInstallers to modify
228 protected $extraInstallSteps = array();
231 * Known object cache types and the functions used to test for their existence.
235 protected $objectCaches = array(
236 'xcache' => 'xcache_get',
237 'apc' => 'apc_fetch',
238 'wincache' => 'wincache_ucache_get'
242 * User rights profiles.
246 public $rightsProfiles = array(
249 '*' => array( 'edit' => false )
253 'createaccount' => false,
259 'createaccount' => false,
271 public $licenses = array(
273 'url' => 'http://creativecommons.org/licenses/by/3.0/',
274 'icon' => '{$wgStylePath}/common/images/cc-by.png',
277 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
278 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
280 'cc-by-nc-sa' => array(
281 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
282 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
285 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
286 'icon' => '{$wgStylePath}/common/images/cc-0.png',
290 'icon' => '{$wgStylePath}/common/images/public-domain.png',
293 'url' => 'http://www.gnu.org/copyleft/fdl.html',
294 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
301 'cc-choose' => array(
302 // Details will be filled in by the selector.
310 * URL to mediawiki-announce subscription
312 protected $mediaWikiAnnounceUrl =
313 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
316 * Supported language codes for Mailman
318 protected $mediaWikiAnnounceLanguages = array(
319 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
320 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
321 'sl', 'sr', 'sv', 'tr', 'uk'
325 * UI interface for displaying a short message
326 * The parameters are like parameters to wfMessage().
327 * The messages will be in wikitext format, which will be converted to an
328 * output format such as HTML or text before being sent to the user.
331 abstract public function showMessage( $msg /*, ... */ );
334 * Same as showMessage(), but for displaying errors
337 abstract public function showError( $msg /*, ... */ );
340 * Show a message to the installing user by using a Status object
341 * @param Status $status
343 abstract public function showStatusMessage( Status
$status );
346 * Constructor, always call this from child classes.
348 public function __construct() {
349 global $wgMessagesDirs, $wgUser;
351 // Disable the i18n cache and LoadBalancer
352 Language
::getLocalisationCache()->disableBackend();
353 LBFactory
::disableBackend();
355 // Load the installer's i18n.
356 $wgMessagesDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
358 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
359 $wgUser = User
::newFromId( 0 );
361 $this->settings
= $this->internalDefaults
;
363 foreach ( $this->defaultVarNames
as $var ) {
364 $this->settings
[$var] = $GLOBALS[$var];
367 $compiledDBs = array();
368 foreach ( self
::getDBTypes() as $type ) {
369 $installer = $this->getDBInstaller( $type );
371 if ( !$installer->isCompiled() ) {
374 $compiledDBs[] = $type;
376 $defaults = $installer->getGlobalDefaults();
378 foreach ( $installer->getGlobalNames() as $var ) {
379 if ( isset( $defaults[$var] ) ) {
380 $this->settings
[$var] = $defaults[$var];
382 $this->settings
[$var] = $GLOBALS[$var];
386 $this->compiledDBs
= $compiledDBs;
388 $this->parserTitle
= Title
::newFromText( 'Installer' );
389 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
390 $this->parserOptions
->setEditSection( false );
394 * Get a list of known DB types.
398 public static function getDBTypes() {
399 return self
::$dbTypes;
403 * Do initial checks of the PHP environment. Set variables according to
404 * the observed environment.
406 * It's possible that this may be called under the CLI SAPI, not the SAPI
407 * that the wiki will primarily run under. In that case, the subclass should
408 * initialise variables such as wgScriptPath, before calling this function.
410 * Under the web subclass, it can already be assumed that PHP 5+ is in use
411 * and that sessions are working.
415 public function doEnvironmentChecks() {
416 $phpVersion = phpversion();
417 if ( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
418 $this->showMessage( 'config-env-php', $phpVersion );
421 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
425 // Must go here because an old version of PCRE can prevent other checks from completing
427 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
428 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
429 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
435 foreach ( $this->envChecks
as $check ) {
436 $status = $this->$check();
437 if ( $status === false ) {
443 $this->setVar( '_Environment', $good );
445 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
449 * Set a MW configuration variable, or internal installer configuration variable.
451 * @param string $name
452 * @param mixed $value
454 public function setVar( $name, $value ) {
455 $this->settings
[$name] = $value;
459 * Get an MW configuration variable, or internal installer configuration variable.
460 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
461 * Installer variables are typically prefixed by an underscore.
463 * @param string $name
464 * @param mixed $default
468 public function getVar( $name, $default = null ) {
469 if ( !isset( $this->settings
[$name] ) ) {
472 return $this->settings
[$name];
477 * Get a list of DBs supported by current PHP setup
481 public function getCompiledDBs() {
482 return $this->compiledDBs
;
486 * Get an instance of DatabaseInstaller for the specified DB type.
488 * @param mixed $type DB installer for which is needed, false to use default.
490 * @return DatabaseInstaller
492 public function getDBInstaller( $type = false ) {
494 $type = $this->getVar( 'wgDBtype' );
497 $type = strtolower( $type );
499 if ( !isset( $this->dbInstallers
[$type] ) ) {
500 $class = ucfirst( $type ) . 'Installer';
501 $this->dbInstallers
[$type] = new $class( $this );
504 return $this->dbInstallers
[$type];
508 * Determine if LocalSettings.php exists. If it does, return its variables.
512 public static function getExistingLocalSettings() {
515 wfSuppressWarnings();
516 $_lsExists = file_exists( "$IP/LocalSettings.php" );
524 require "$IP/includes/DefaultSettings.php";
525 require "$IP/LocalSettings.php";
527 return get_defined_vars();
531 * Get a fake password for sending back to the user in HTML.
532 * This is a security mechanism to avoid compromise of the password in the
533 * event of session ID compromise.
535 * @param string $realPassword
539 public function getFakePassword( $realPassword ) {
540 return str_repeat( '*', strlen( $realPassword ) );
544 * Set a variable which stores a password, except if the new value is a
545 * fake password in which case leave it as it is.
547 * @param string $name
548 * @param mixed $value
550 public function setPassword( $name, $value ) {
551 if ( !preg_match( '/^\*+$/', $value ) ) {
552 $this->setVar( $name, $value );
557 * On POSIX systems return the primary group of the webserver we're running under.
558 * On other systems just returns null.
560 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
561 * webserver user before he can install.
563 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
567 public static function maybeGetWebserverPrimaryGroup() {
568 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
569 # I don't know this, this isn't UNIX.
573 # posix_getegid() *not* getmygid() because we want the group of the webserver,
574 # not whoever owns the current script.
575 $gid = posix_getegid();
576 $getpwuid = posix_getpwuid( $gid );
577 $group = $getpwuid['name'];
583 * Convert wikitext $text to HTML.
585 * This is potentially error prone since many parser features require a complete
586 * installed MW database. The solution is to just not use those features when you
587 * write your messages. This appears to work well enough. Basic formatting and
588 * external links work just fine.
590 * But in case a translator decides to throw in a "#ifexist" or internal link or
591 * whatever, this function is guarded to catch the attempted DB access and to present
592 * some fallback text.
594 * @param string $text
595 * @param bool $lineStart
598 public function parse( $text, $lineStart = false ) {
602 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
603 $html = $out->getText();
604 } catch ( DBAccessError
$e ) {
605 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
607 if ( !empty( $this->debug
) ) {
608 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
616 * @return ParserOptions
618 public function getParserOptions() {
619 return $this->parserOptions
;
622 public function disableLinkPopups() {
623 $this->parserOptions
->setExternalLinkTarget( false );
626 public function restoreLinkPopups() {
627 global $wgExternalLinkTarget;
628 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
632 * Install step which adds a row to the site_stats table with appropriate
635 * @param DatabaseInstaller $installer
639 public function populateSiteStats( DatabaseInstaller
$installer ) {
640 $status = $installer->getConnection();
641 if ( !$status->isOK() ) {
644 $status->value
->insert(
648 'ss_total_views' => 0,
649 'ss_total_edits' => 0,
650 'ss_good_articles' => 0,
651 'ss_total_pages' => 0,
658 return Status
::newGood();
662 * Exports all wg* variables stored by the installer into global scope.
664 public function exportVars() {
665 foreach ( $this->settings
as $name => $value ) {
666 if ( substr( $name, 0, 2 ) == 'wg' ) {
667 $GLOBALS[$name] = $value;
673 * Environment check for DB types.
676 protected function envCheckDB() {
681 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
682 // config-type-sqlite
683 foreach ( self
::getDBTypes() as $name ) {
684 $allNames[] = wfMessage( "config-type-$name" )->text();
687 $databases = $this->getCompiledDBs();
689 $databases = array_flip( $databases );
690 foreach ( array_keys( $databases ) as $db ) {
691 $installer = $this->getDBInstaller( $db );
692 $status = $installer->checkPrerequisites();
693 if ( !$status->isGood() ) {
694 $this->showStatusMessage( $status );
696 if ( !$status->isOK() ) {
697 unset( $databases[$db] );
700 $databases = array_flip( $databases );
702 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
704 // @todo FIXME: This only works for the web installer!
712 * Environment check for register_globals.
714 protected function envCheckRegisterGlobals() {
715 if ( wfIniGetBool( 'register_globals' ) ) {
716 $this->showMessage( 'config-register-globals' );
721 * Some versions of libxml+PHP break < and > encoding horribly
724 protected function envCheckBrokenXML() {
725 $test = new PhpXmlBugTester();
727 $this->showError( 'config-brokenlibxml' );
736 * Environment check for magic_quotes_runtime.
739 protected function envCheckMagicQuotes() {
740 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
741 $this->showError( 'config-magic-quotes-runtime' );
750 * Environment check for magic_quotes_sybase.
753 protected function envCheckMagicSybase() {
754 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
755 $this->showError( 'config-magic-quotes-sybase' );
764 * Environment check for mbstring.func_overload.
767 protected function envCheckMbstring() {
768 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
769 $this->showError( 'config-mbstring' );
778 * Environment check for safe_mode.
781 protected function envCheckSafeMode() {
782 if ( wfIniGetBool( 'safe_mode' ) ) {
783 $this->setVar( '_SafeMode', true );
784 $this->showMessage( 'config-safe-mode' );
791 * Environment check for the XML module.
794 protected function envCheckXML() {
795 if ( !function_exists( "utf8_encode" ) ) {
796 $this->showError( 'config-xml-bad' );
805 * Environment check for the PCRE module.
807 * @note If this check were to fail, the parser would
808 * probably throw an exception before the result
809 * of this check is shown to the user.
812 protected function envCheckPCRE() {
813 wfSuppressWarnings();
814 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
815 // Need to check for \p support too, as PCRE can be compiled
816 // with utf8 support, but not unicode property support.
817 // check that \p{Zs} (space separators) matches
818 // U+3000 (Ideographic space)
819 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
821 if ( $regexd != '--' ||
$regexprop != '--' ) {
822 $this->showError( 'config-pcre-no-utf8' );
831 * Environment check for available memory.
834 protected function envCheckMemory() {
835 $limit = ini_get( 'memory_limit' );
837 if ( !$limit ||
$limit == -1 ) {
841 $n = wfShorthandToInteger( $limit );
843 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
844 $newLimit = "{$this->minMemorySize}M";
846 if ( ini_set( "memory_limit", $newLimit ) === false ) {
847 $this->showMessage( 'config-memory-bad', $limit );
849 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
850 $this->setVar( '_RaiseMemory', true );
858 * Environment check for compiled object cache types.
860 protected function envCheckCache() {
862 foreach ( $this->objectCaches
as $name => $function ) {
863 if ( function_exists( $function ) ) {
864 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
867 $caches[$name] = true;
872 $this->showMessage( 'config-no-cache' );
875 $this->setVar( '_Caches', $caches );
879 * Scare user to death if they have mod_security
882 protected function envCheckModSecurity() {
883 if ( self
::apacheModulePresent( 'mod_security' ) ) {
884 $this->showMessage( 'config-mod-security' );
891 * Search for GNU diff3.
894 protected function envCheckDiff3() {
895 $names = array( "gdiff3", "diff3", "diff3.exe" );
896 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
898 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
901 $this->setVar( 'wgDiff3', $diff3 );
903 $this->setVar( 'wgDiff3', false );
904 $this->showMessage( 'config-diff3-bad' );
911 * Environment check for ImageMagick and GD.
914 protected function envCheckGraphics() {
915 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
916 $versionInfo = array( '$1 -version', 'ImageMagick' );
917 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
919 $this->setVar( 'wgImageMagickConvertCommand', '' );
921 $this->setVar( 'wgImageMagickConvertCommand', $convert );
922 $this->showMessage( 'config-imagemagick', $convert );
925 } elseif ( function_exists( 'imagejpeg' ) ) {
926 $this->showMessage( 'config-gd' );
928 $this->showMessage( 'config-no-scaling' );
940 protected function envCheckGit() {
941 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
942 $versionInfo = array( '$1 --version', 'git version' );
944 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
947 $this->setVar( 'wgGitBin', $git );
948 $this->showMessage( 'config-git', $git );
950 $this->setVar( 'wgGitBin', false );
951 $this->showMessage( 'config-git-bad' );
958 * Environment check for the server hostname.
960 protected function envCheckServer() {
961 $server = $this->envGetDefaultServer();
962 if ( $server !== null ) {
963 $this->showMessage( 'config-using-server', $server );
964 $this->setVar( 'wgServer', $server );
971 * Helper function to be called from envCheckServer()
974 abstract protected function envGetDefaultServer();
977 * Environment check for setting $IP and $wgScriptPath.
980 protected function envCheckPath() {
982 $IP = dirname( dirname( __DIR__
) );
983 $this->setVar( 'IP', $IP );
987 $this->getVar( 'wgServer' ),
988 $this->getVar( 'wgScriptPath' )
995 * Environment check for setting the preferred PHP file extension.
998 protected function envCheckExtension() {
999 // @todo FIXME: Detect this properly
1000 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1005 $this->setVar( 'wgScriptExtension', ".$ext" );
1011 * Environment check for preferred locale in shell
1014 protected function envCheckShellLocale() {
1015 $os = php_uname( 's' );
1016 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1018 if ( !in_array( $os, $supported ) ) {
1022 # Get a list of available locales.
1024 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1030 $lines = array_map( 'trim', explode( "\n", $lines ) );
1031 $candidatesByLocale = array();
1032 $candidatesByLang = array();
1034 foreach ( $lines as $line ) {
1035 if ( $line === '' ) {
1039 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1043 list( , $lang, , , ) = $m;
1045 $candidatesByLocale[$m[0]] = $m;
1046 $candidatesByLang[$lang][] = $m;
1049 # Try the current value of LANG.
1050 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1051 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1056 # Try the most common ones.
1057 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1058 foreach ( $commonLocales as $commonLocale ) {
1059 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1060 $this->setVar( 'wgShellLocale', $commonLocale );
1066 # Is there an available locale in the Wiki's language?
1067 $wikiLang = $this->getVar( 'wgLanguageCode' );
1069 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1070 $m = reset( $candidatesByLang[$wikiLang] );
1071 $this->setVar( 'wgShellLocale', $m[0] );
1076 # Are there any at all?
1077 if ( count( $candidatesByLocale ) ) {
1078 $m = reset( $candidatesByLocale );
1079 $this->setVar( 'wgShellLocale', $m[0] );
1089 * Environment check for the permissions of the uploads directory
1092 protected function envCheckUploadsDirectory() {
1095 $dir = $IP . '/images/';
1096 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1097 $safe = !$this->dirIsExecutable( $dir, $url );
1100 $this->showMessage( 'config-uploads-not-safe', $dir );
1107 * Checks if suhosin.get.max_value_length is set, and if so generate
1108 * a warning because it decreases ResourceLoader performance.
1111 protected function envCheckSuhosinMaxValueLength() {
1112 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1113 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1114 // Only warn if the value is below the sane 1024
1115 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1122 * Convert a hex string representing a Unicode code point to that code point.
1126 protected function unicodeChar( $c ) {
1130 } elseif ( $c <= 0x7FF ) {
1131 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1132 } elseif ( $c <= 0xFFFF ) {
1133 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1134 . chr( 0x80 |
$c & 0x3F );
1135 } elseif ( $c <= 0x10FFFF ) {
1136 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1137 . chr( 0x80 |
$c >> 6 & 0x3F )
1138 . chr( 0x80 |
$c & 0x3F );
1145 * Check the libicu version
1147 protected function envCheckLibicu() {
1148 $utf8 = function_exists( 'utf8_normalize' );
1149 $intl = function_exists( 'normalizer_normalize' );
1152 * This needs to be updated something that the latest libicu
1153 * will properly normalize. This normalization was found at
1154 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1155 * Note that we use the hex representation to create the code
1156 * points in order to avoid any Unicode-destroying during transit.
1158 $not_normal_c = $this->unicodeChar( "FA6C" );
1159 $normal_c = $this->unicodeChar( "242EE" );
1161 $useNormalizer = 'php';
1162 $needsUpdate = false;
1165 * We're going to prefer the pecl extension here unless
1166 * utf8_normalize is more up to date.
1169 $useNormalizer = 'utf8';
1170 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1171 if ( $utf8 !== $normal_c ) {
1172 $needsUpdate = true;
1176 $useNormalizer = 'intl';
1177 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1178 if ( $intl !== $normal_c ) {
1179 $needsUpdate = true;
1183 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1184 // 'config-unicode-using-intl'
1185 if ( $useNormalizer === 'php' ) {
1186 $this->showMessage( 'config-unicode-pure-php-warning' );
1188 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1189 if ( $needsUpdate ) {
1190 $this->showMessage( 'config-unicode-update-warning' );
1198 protected function envCheckCtype() {
1199 if ( !function_exists( 'ctype_digit' ) ) {
1200 $this->showError( 'config-ctype' );
1211 protected function envCheckJSON() {
1212 if ( !function_exists( 'json_decode' ) ) {
1213 $this->showError( 'config-json' );
1222 * Get an array of likely places we can find executables. Check a bunch
1223 * of known Unix-like defaults, as well as the PATH environment variable
1224 * (which should maybe make it work for Windows?)
1228 protected static function getPossibleBinPaths() {
1230 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1231 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1232 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1237 * Search a path for any of the given executable names. Returns the
1238 * executable name if found. Also checks the version string returned
1239 * by each executable.
1241 * Used only by environment checks.
1243 * @param string $path path to search
1244 * @param array $names of executable names
1245 * @param array|bool $versionInfo False or array with two members:
1246 * 0 => Command to run for version check, with $1 for the full executable name
1247 * 1 => String to compare the output with
1249 * If $versionInfo is not false, only executables with a version
1250 * matching $versionInfo[1] will be returned.
1251 * @return bool|string
1253 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1254 if ( !is_array( $names ) ) {
1255 $names = array( $names );
1258 foreach ( $names as $name ) {
1259 $command = $path . DIRECTORY_SEPARATOR
. $name;
1261 wfSuppressWarnings();
1262 $file_exists = file_exists( $command );
1263 wfRestoreWarnings();
1265 if ( $file_exists ) {
1266 if ( !$versionInfo ) {
1270 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1271 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1281 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1282 * @see locateExecutable()
1283 * @param array $names Array of possible names.
1284 * @param array|bool $versionInfo Default: false or array with two members:
1285 * 0 => Command to run for version check, with $1 for the full executable name
1286 * 1 => String to compare the output with
1288 * If $versionInfo is not false, only executables with a version
1289 * matching $versionInfo[1] will be returned.
1290 * @return bool|string
1292 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1293 foreach ( self
::getPossibleBinPaths() as $path ) {
1294 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1295 if ( $exe !== false ) {
1304 * Checks if scripts located in the given directory can be executed via the given URL.
1306 * Used only by environment checks.
1307 * @param string $dir
1308 * @param string $url
1309 * @return bool|int|string
1311 public function dirIsExecutable( $dir, $url ) {
1312 $scriptTypes = array(
1314 "<?php echo 'ex' . 'ec';",
1315 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1319 // it would be good to check other popular languages here, but it'll be slow.
1321 wfSuppressWarnings();
1323 foreach ( $scriptTypes as $ext => $contents ) {
1324 foreach ( $contents as $source ) {
1325 $file = 'exectest.' . $ext;
1327 if ( !file_put_contents( $dir . $file, $source ) ) {
1332 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1333 } catch ( MWException
$e ) {
1334 // Http::get throws with allow_url_fopen = false and no curl extension.
1337 unlink( $dir . $file );
1339 if ( $text == 'exec' ) {
1340 wfRestoreWarnings();
1347 wfRestoreWarnings();
1353 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1355 * @param string $moduleName Name of module to check.
1358 public static function apacheModulePresent( $moduleName ) {
1359 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1362 // try it the hard way
1364 phpinfo( INFO_MODULES
);
1365 $info = ob_get_clean();
1367 return strpos( $info, $moduleName ) !== false;
1371 * ParserOptions are constructed before we determined the language, so fix it
1373 * @param Language $lang
1375 public function setParserLanguage( $lang ) {
1376 $this->parserOptions
->setTargetLanguage( $lang );
1377 $this->parserOptions
->setUserLang( $lang );
1381 * Overridden by WebInstaller to provide lastPage parameters.
1382 * @param string $page
1385 protected function getDocUrl( $page ) {
1386 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1390 * Finds extensions that follow the format /extensions/Name/Name.php,
1391 * and returns an array containing the value for 'Name' for each found extension.
1395 public function findExtensions() {
1396 if ( $this->getVar( 'IP' ) === null ) {
1400 $extDir = $this->getVar( 'IP' ) . '/extensions';
1401 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1405 $dh = opendir( $extDir );
1407 while ( ( $file = readdir( $dh ) ) !== false ) {
1408 if ( !is_dir( "$extDir/$file" ) ) {
1411 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1416 natcasesort( $exts );
1422 * Installs the auto-detected extensions.
1426 protected function includeExtensions() {
1428 $exts = $this->getVar( '_Extensions' );
1429 $IP = $this->getVar( 'IP' );
1432 * We need to include DefaultSettings before including extensions to avoid
1433 * warnings about unset variables. However, the only thing we really
1434 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1435 * if the extension has hidden hook registration in $wgExtensionFunctions,
1436 * but we're not opening that can of worms
1437 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1439 global $wgAutoloadClasses;
1440 $wgAutoloadClasses = array();
1442 require "$IP/includes/DefaultSettings.php";
1444 foreach ( $exts as $e ) {
1445 require_once "$IP/extensions/$e/$e.php";
1448 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1449 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1451 // Unset everyone else's hooks. Lord knows what someone might be doing
1452 // in ParserFirstCallInit (see bug 27171)
1453 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1455 return Status
::newGood();
1459 * Get an array of install steps. Should always be in the format of
1461 * 'name' => 'someuniquename',
1462 * 'callback' => array( $obj, 'method' ),
1464 * There must be a config-install-$name message defined per step, which will
1465 * be shown on install.
1467 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1470 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1471 $coreInstallSteps = array(
1472 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1473 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1474 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1475 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1476 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1477 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1478 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1481 // Build the array of install steps starting from the core install list,
1482 // then adding any callbacks that wanted to attach after a given step
1483 foreach ( $coreInstallSteps as $step ) {
1484 $this->installSteps
[] = $step;
1485 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1486 $this->installSteps
= array_merge(
1487 $this->installSteps
,
1488 $this->extraInstallSteps
[$step['name']]
1493 // Prepend any steps that want to be at the beginning
1494 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1495 $this->installSteps
= array_merge(
1496 $this->extraInstallSteps
['BEGINNING'],
1501 // Extensions should always go first, chance to tie into hooks and such
1502 if ( count( $this->getVar( '_Extensions' ) ) ) {
1503 array_unshift( $this->installSteps
,
1504 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1506 $this->installSteps
[] = array(
1507 'name' => 'extension-tables',
1508 'callback' => array( $installer, 'createExtensionTables' )
1512 return $this->installSteps
;
1516 * Actually perform the installation.
1518 * @param array $startCB A callback array for the beginning of each step
1519 * @param array $endCB A callback array for the end of each step
1521 * @return array Array of Status objects
1523 public function performInstallation( $startCB, $endCB ) {
1524 $installResults = array();
1525 $installer = $this->getDBInstaller();
1526 $installer->preInstall();
1527 $steps = $this->getInstallSteps( $installer );
1528 foreach ( $steps as $stepObj ) {
1529 $name = $stepObj['name'];
1530 call_user_func_array( $startCB, array( $name ) );
1532 // Perform the callback step
1533 $status = call_user_func( $stepObj['callback'], $installer );
1535 // Output and save the results
1536 call_user_func( $endCB, $name, $status );
1537 $installResults[$name] = $status;
1539 // If we've hit some sort of fatal, we need to bail.
1540 // Callback already had a chance to do output above.
1541 if ( !$status->isOk() ) {
1545 if ( $status->isOk() ) {
1546 $this->setVar( '_InstallDone', true );
1549 return $installResults;
1553 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1557 public function generateKeys() {
1558 $keys = array( 'wgSecretKey' => 64 );
1559 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1560 $keys['wgUpgradeKey'] = 16;
1563 return $this->doGenerateKeys( $keys );
1567 * Generate a secret value for variables using our CryptRand generator.
1568 * Produce a warning if the random source was insecure.
1570 * @param array $keys
1573 protected function doGenerateKeys( $keys ) {
1574 $status = Status
::newGood();
1577 foreach ( $keys as $name => $length ) {
1578 $secretKey = MWCryptRand
::generateHex( $length, true );
1579 if ( !MWCryptRand
::wasStrong() ) {
1583 $this->setVar( $name, $secretKey );
1587 $names = array_keys( $keys );
1588 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1590 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1597 * Create the first user account, grant it sysop and bureaucrat rights
1601 protected function createSysop() {
1602 $name = $this->getVar( '_AdminName' );
1603 $user = User
::newFromName( $name );
1606 // We should've validated this earlier anyway!
1607 return Status
::newFatal( 'config-admin-error-user', $name );
1610 if ( $user->idForName() == 0 ) {
1611 $user->addToDatabase();
1614 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1615 } catch ( PasswordError
$pwe ) {
1616 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1619 $user->addGroup( 'sysop' );
1620 $user->addGroup( 'bureaucrat' );
1621 if ( $this->getVar( '_AdminEmail' ) ) {
1622 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1624 $user->saveSettings();
1626 // Update user count
1627 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1628 $ssUpdate->doUpdate();
1630 $status = Status
::newGood();
1632 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1633 $this->subscribeToMediaWikiAnnounce( $status );
1642 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1644 'email' => $this->getVar( '_AdminEmail' ),
1649 // Mailman doesn't support as many languages as we do, so check to make
1650 // sure their selected language is available
1651 $myLang = $this->getVar( '_UserLang' );
1652 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1653 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1654 $params['language'] = $myLang;
1657 if ( MWHttpRequest
::canMakeRequests() ) {
1658 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1659 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1660 if ( !$res->isOK() ) {
1661 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1664 $s->warning( 'config-install-subscribe-notpossible' );
1669 * Insert Main Page with default content.
1671 * @param DatabaseInstaller $installer
1674 protected function createMainpage( DatabaseInstaller
$installer ) {
1675 $status = Status
::newGood();
1677 $page = WikiPage
::factory( Title
::newMainPage() );
1678 $content = new WikitextContent(
1679 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1680 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1683 $page->doEditContent( $content,
1687 User
::newFromName( 'MediaWiki default' )
1689 } catch ( MWException
$e ) {
1690 //using raw, because $wgShowExceptionDetails can not be set yet
1691 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1698 * Override the necessary bits of the config to run an installation.
1700 public static function overrideConfig() {
1701 define( 'MW_NO_SESSION', 1 );
1703 // Don't access the database
1704 $GLOBALS['wgUseDatabaseMessages'] = false;
1705 // Don't cache langconv tables
1706 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1708 $GLOBALS['wgShowExceptionDetails'] = true;
1709 // Don't break forms
1710 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1712 // Extended debugging
1713 $GLOBALS['wgShowSQLErrors'] = true;
1714 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1716 // Allow multiple ob_flush() calls
1717 $GLOBALS['wgDisableOutputCompression'] = true;
1719 // Use a sensible cookie prefix (not my_wiki)
1720 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1722 // Some of the environment checks make shell requests, remove limits
1723 $GLOBALS['wgMaxShellMemory'] = 0;
1725 // Don't bother embedding images into generated CSS, which is not cached
1726 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1727 return $less->toBool( false );
1732 * Add an installation step following the given step.
1734 * @param array $callback A valid installation callback array, in this form:
1735 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1736 * @param string $findStep The step to find. Omit to put the step at the beginning
1738 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1739 $this->extraInstallSteps
[$findStep][] = $callback;
1743 * Disable the time limit for execution.
1744 * Some long-running pages (Install, Upgrade) will want to do this
1746 protected function disableTimeLimit() {
1747 wfSuppressWarnings();
1748 set_time_limit( 0 );
1749 wfRestoreWarnings();