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',
175 'wgUseInstantCommons',
178 'wgResourceLoaderMaxQueryLength',
182 * Variables that are stored alongside globals, and are used for any
183 * configuration of the installation process aside from the MediaWiki
184 * configuration. Map of names to defaults.
188 protected $internalDefaults = array(
190 '_Environment' => false,
191 '_SafeMode' => false,
192 '_RaiseMemory' => false,
193 '_UpgradeDone' => false,
194 '_InstallDone' => false,
195 '_Caches' => array(),
196 '_InstallPassword' => '',
197 '_SameAccount' => true,
198 '_CreateDBAccount' => false,
199 '_NamespaceType' => 'site-name',
200 '_AdminName' => '', // will be set later, when the user selects language
201 '_AdminPassword' => '',
202 '_AdminPassword2' => '',
204 '_Subscribe' => false,
205 '_SkipOptional' => 'continue',
206 '_RightsProfile' => 'wiki',
207 '_LicenseCode' => 'none',
209 '_Extensions' => array(),
210 '_MemCachedServers' => '',
211 '_UpgradeKeySupplied' => false,
212 '_ExistingDBSettings' => false,
214 // $wgLogo is probably wrong (bug 48084); set something that will work.
215 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
216 'wgLogo' => '$wgStylePath/common/images/wiki.png',
220 * The actual list of installation steps. This will be initialized by getInstallSteps()
224 private $installSteps = array();
227 * Extra steps for installation, for things like DatabaseInstallers to modify
231 protected $extraInstallSteps = array();
234 * Known object cache types and the functions used to test for their existence.
238 protected $objectCaches = array(
239 'xcache' => 'xcache_get',
240 'apc' => 'apc_fetch',
241 'wincache' => 'wincache_ucache_get'
245 * User rights profiles.
249 public $rightsProfiles = array(
252 '*' => array( 'edit' => false )
256 'createaccount' => false,
262 'createaccount' => false,
274 public $licenses = array(
276 'url' => 'http://creativecommons.org/licenses/by/3.0/',
277 'icon' => '{$wgStylePath}/common/images/cc-by.png',
280 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
281 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
283 'cc-by-nc-sa' => array(
284 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
285 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
288 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
289 'icon' => '{$wgStylePath}/common/images/cc-0.png',
293 'icon' => '{$wgStylePath}/common/images/public-domain.png',
296 'url' => 'http://www.gnu.org/copyleft/fdl.html',
297 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
304 'cc-choose' => array(
305 // Details will be filled in by the selector.
313 * URL to mediawiki-announce subscription
315 protected $mediaWikiAnnounceUrl =
316 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
319 * Supported language codes for Mailman
321 protected $mediaWikiAnnounceLanguages = array(
322 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
323 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
324 'sl', 'sr', 'sv', 'tr', 'uk'
328 * UI interface for displaying a short message
329 * The parameters are like parameters to wfMessage().
330 * The messages will be in wikitext format, which will be converted to an
331 * output format such as HTML or text before being sent to the user.
334 abstract public function showMessage( $msg /*, ... */ );
337 * Same as showMessage(), but for displaying errors
340 abstract public function showError( $msg /*, ... */ );
343 * Show a message to the installing user by using a Status object
344 * @param $status Status
346 abstract public function showStatusMessage( Status
$status );
349 * Constructor, always call this from child classes.
351 public function __construct() {
352 global $wgExtensionMessagesFiles, $wgUser;
354 // Disable the i18n cache and LoadBalancer
355 Language
::getLocalisationCache()->disableBackend();
356 LBFactory
::disableBackend();
358 // Load the installer's i18n file.
359 $wgExtensionMessagesFiles['MediawikiInstaller'] =
360 __DIR__
. '/Installer.i18n.php';
362 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
363 $wgUser = User
::newFromId( 0 );
365 $this->settings
= $this->internalDefaults
;
367 foreach ( $this->defaultVarNames
as $var ) {
368 $this->settings
[$var] = $GLOBALS[$var];
371 $compiledDBs = array();
372 foreach ( self
::getDBTypes() as $type ) {
373 $installer = $this->getDBInstaller( $type );
375 if ( !$installer->isCompiled() ) {
378 $compiledDBs[] = $type;
380 $defaults = $installer->getGlobalDefaults();
382 foreach ( $installer->getGlobalNames() as $var ) {
383 if ( isset( $defaults[$var] ) ) {
384 $this->settings
[$var] = $defaults[$var];
386 $this->settings
[$var] = $GLOBALS[$var];
390 $this->compiledDBs
= $compiledDBs;
392 $this->parserTitle
= Title
::newFromText( 'Installer' );
393 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
394 $this->parserOptions
->setEditSection( false );
398 * Get a list of known DB types.
402 public static function getDBTypes() {
403 return self
::$dbTypes;
407 * Do initial checks of the PHP environment. Set variables according to
408 * the observed environment.
410 * It's possible that this may be called under the CLI SAPI, not the SAPI
411 * that the wiki will primarily run under. In that case, the subclass should
412 * initialise variables such as wgScriptPath, before calling this function.
414 * Under the web subclass, it can already be assumed that PHP 5+ is in use
415 * and that sessions are working.
419 public function doEnvironmentChecks() {
420 $phpVersion = phpversion();
421 if ( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
422 $this->showMessage( 'config-env-php', $phpVersion );
425 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
429 // Must go here because an old version of PCRE can prevent other checks from completing
431 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
432 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
433 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
439 foreach ( $this->envChecks
as $check ) {
440 $status = $this->$check();
441 if ( $status === false ) {
447 $this->setVar( '_Environment', $good );
449 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
453 * Set a MW configuration variable, or internal installer configuration variable.
455 * @param $name String
456 * @param $value Mixed
458 public function setVar( $name, $value ) {
459 $this->settings
[$name] = $value;
463 * Get an MW configuration variable, or internal installer configuration variable.
464 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
465 * Installer variables are typically prefixed by an underscore.
467 * @param $name String
468 * @param $default Mixed
472 public function getVar( $name, $default = null ) {
473 if ( !isset( $this->settings
[$name] ) ) {
476 return $this->settings
[$name];
481 * Get a list of DBs supported by current PHP setup
485 public function getCompiledDBs() {
486 return $this->compiledDBs
;
490 * Get an instance of DatabaseInstaller for the specified DB type.
492 * @param $type Mixed: DB installer for which is needed, false to use default.
494 * @return DatabaseInstaller
496 public function getDBInstaller( $type = false ) {
498 $type = $this->getVar( 'wgDBtype' );
501 $type = strtolower( $type );
503 if ( !isset( $this->dbInstallers
[$type] ) ) {
504 $class = ucfirst( $type ) . 'Installer';
505 $this->dbInstallers
[$type] = new $class( $this );
508 return $this->dbInstallers
[$type];
512 * Determine if LocalSettings.php exists. If it does, return its variables.
516 public static function getExistingLocalSettings() {
519 wfSuppressWarnings();
520 $_lsExists = file_exists( "$IP/LocalSettings.php" );
528 require "$IP/includes/DefaultSettings.php";
529 require "$IP/LocalSettings.php";
531 return get_defined_vars();
535 * Get a fake password for sending back to the user in HTML.
536 * This is a security mechanism to avoid compromise of the password in the
537 * event of session ID compromise.
539 * @param $realPassword String
543 public function getFakePassword( $realPassword ) {
544 return str_repeat( '*', strlen( $realPassword ) );
548 * Set a variable which stores a password, except if the new value is a
549 * fake password in which case leave it as it is.
551 * @param $name String
552 * @param $value Mixed
554 public function setPassword( $name, $value ) {
555 if ( !preg_match( '/^\*+$/', $value ) ) {
556 $this->setVar( $name, $value );
561 * On POSIX systems return the primary group of the webserver we're running under.
562 * On other systems just returns null.
564 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
565 * webserver user before he can install.
567 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
571 public static function maybeGetWebserverPrimaryGroup() {
572 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
573 # I don't know this, this isn't UNIX.
577 # posix_getegid() *not* getmygid() because we want the group of the webserver,
578 # not whoever owns the current script.
579 $gid = posix_getegid();
580 $getpwuid = posix_getpwuid( $gid );
581 $group = $getpwuid['name'];
587 * Convert wikitext $text to HTML.
589 * This is potentially error prone since many parser features require a complete
590 * installed MW database. The solution is to just not use those features when you
591 * write your messages. This appears to work well enough. Basic formatting and
592 * external links work just fine.
594 * But in case a translator decides to throw in a "#ifexist" or internal link or
595 * whatever, this function is guarded to catch the attempted DB access and to present
596 * some fallback text.
598 * @param $text String
599 * @param $lineStart Boolean
602 public function parse( $text, $lineStart = false ) {
606 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
607 $html = $out->getText();
608 } catch ( DBAccessError
$e ) {
609 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
611 if ( !empty( $this->debug
) ) {
612 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
620 * @return ParserOptions
622 public function getParserOptions() {
623 return $this->parserOptions
;
626 public function disableLinkPopups() {
627 $this->parserOptions
->setExternalLinkTarget( false );
630 public function restoreLinkPopups() {
631 global $wgExternalLinkTarget;
632 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
636 * Install step which adds a row to the site_stats table with appropriate
639 * @param $installer DatabaseInstaller
643 public function populateSiteStats( DatabaseInstaller
$installer ) {
644 $status = $installer->getConnection();
645 if ( !$status->isOK() ) {
648 $status->value
->insert(
652 'ss_total_views' => 0,
653 'ss_total_edits' => 0,
654 'ss_good_articles' => 0,
655 'ss_total_pages' => 0,
662 return Status
::newGood();
666 * Exports all wg* variables stored by the installer into global scope.
668 public function exportVars() {
669 foreach ( $this->settings
as $name => $value ) {
670 if ( substr( $name, 0, 2 ) == 'wg' ) {
671 $GLOBALS[$name] = $value;
677 * Environment check for DB types.
680 protected function envCheckDB() {
685 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
686 // config-type-sqlite
687 foreach ( self
::getDBTypes() as $name ) {
688 $allNames[] = wfMessage( "config-type-$name" )->text();
691 $databases = $this->getCompiledDBs();
693 $databases = array_flip( $databases );
694 foreach ( array_keys( $databases ) as $db ) {
695 $installer = $this->getDBInstaller( $db );
696 $status = $installer->checkPrerequisites();
697 if ( !$status->isGood() ) {
698 $this->showStatusMessage( $status );
700 if ( !$status->isOK() ) {
701 unset( $databases[$db] );
704 $databases = array_flip( $databases );
706 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
708 // @todo FIXME: This only works for the web installer!
716 * Environment check for register_globals.
718 protected function envCheckRegisterGlobals() {
719 if ( wfIniGetBool( 'register_globals' ) ) {
720 $this->showMessage( 'config-register-globals' );
725 * Some versions of libxml+PHP break < and > encoding horribly
728 protected function envCheckBrokenXML() {
729 $test = new PhpXmlBugTester();
731 $this->showError( 'config-brokenlibxml' );
740 * Environment check for magic_quotes_runtime.
743 protected function envCheckMagicQuotes() {
744 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
745 $this->showError( 'config-magic-quotes-runtime' );
754 * Environment check for magic_quotes_sybase.
757 protected function envCheckMagicSybase() {
758 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
759 $this->showError( 'config-magic-quotes-sybase' );
768 * Environment check for mbstring.func_overload.
771 protected function envCheckMbstring() {
772 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
773 $this->showError( 'config-mbstring' );
782 * Environment check for safe_mode.
785 protected function envCheckSafeMode() {
786 if ( wfIniGetBool( 'safe_mode' ) ) {
787 $this->setVar( '_SafeMode', true );
788 $this->showMessage( 'config-safe-mode' );
795 * Environment check for the XML module.
798 protected function envCheckXML() {
799 if ( !function_exists( "utf8_encode" ) ) {
800 $this->showError( 'config-xml-bad' );
809 * Environment check for the PCRE module.
811 * @note If this check were to fail, the parser would
812 * probably throw an exception before the result
813 * of this check is shown to the user.
816 protected function envCheckPCRE() {
817 wfSuppressWarnings();
818 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
819 // Need to check for \p support too, as PCRE can be compiled
820 // with utf8 support, but not unicode property support.
821 // check that \p{Zs} (space separators) matches
822 // U+3000 (Ideographic space)
823 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
825 if ( $regexd != '--' ||
$regexprop != '--' ) {
826 $this->showError( 'config-pcre-no-utf8' );
835 * Environment check for available memory.
838 protected function envCheckMemory() {
839 $limit = ini_get( 'memory_limit' );
841 if ( !$limit ||
$limit == -1 ) {
845 $n = wfShorthandToInteger( $limit );
847 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
848 $newLimit = "{$this->minMemorySize}M";
850 if ( ini_set( "memory_limit", $newLimit ) === false ) {
851 $this->showMessage( 'config-memory-bad', $limit );
853 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
854 $this->setVar( '_RaiseMemory', true );
862 * Environment check for compiled object cache types.
864 protected function envCheckCache() {
866 foreach ( $this->objectCaches
as $name => $function ) {
867 if ( function_exists( $function ) ) {
868 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
871 $caches[$name] = true;
876 $this->showMessage( 'config-no-cache' );
879 $this->setVar( '_Caches', $caches );
883 * Scare user to death if they have mod_security
886 protected function envCheckModSecurity() {
887 if ( self
::apacheModulePresent( 'mod_security' ) ) {
888 $this->showMessage( 'config-mod-security' );
895 * Search for GNU diff3.
898 protected function envCheckDiff3() {
899 $names = array( "gdiff3", "diff3", "diff3.exe" );
900 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
902 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
905 $this->setVar( 'wgDiff3', $diff3 );
907 $this->setVar( 'wgDiff3', false );
908 $this->showMessage( 'config-diff3-bad' );
915 * Environment check for ImageMagick and GD.
918 protected function envCheckGraphics() {
919 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
920 $versionInfo = array( '$1 -version', 'ImageMagick' );
921 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
923 $this->setVar( 'wgImageMagickConvertCommand', '' );
925 $this->setVar( 'wgImageMagickConvertCommand', $convert );
926 $this->showMessage( 'config-imagemagick', $convert );
929 } elseif ( function_exists( 'imagejpeg' ) ) {
930 $this->showMessage( 'config-gd' );
932 $this->showMessage( 'config-no-scaling' );
944 protected function envCheckGit() {
945 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
946 $versionInfo = array( '$1 --version', 'git version' );
948 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
951 $this->setVar( 'wgGitBin', $git );
952 $this->showMessage( 'config-git', $git );
954 $this->setVar( 'wgGitBin', false );
955 $this->showMessage( 'config-git-bad' );
962 * Environment check for the server hostname.
964 protected function envCheckServer() {
965 $server = $this->envGetDefaultServer();
966 if ( $server !== null ) {
967 $this->showMessage( 'config-using-server', $server );
968 $this->setVar( 'wgServer', $server );
975 * Helper function to be called from envCheckServer()
978 abstract protected function envGetDefaultServer();
981 * Environment check for setting $IP and $wgScriptPath.
984 protected function envCheckPath() {
986 $IP = dirname( dirname( __DIR__
) );
987 $this->setVar( 'IP', $IP );
991 $this->getVar( 'wgServer' ),
992 $this->getVar( 'wgScriptPath' )
999 * Environment check for setting the preferred PHP file extension.
1002 protected function envCheckExtension() {
1003 // @todo FIXME: Detect this properly
1004 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1009 $this->setVar( 'wgScriptExtension', ".$ext" );
1015 * Environment check for preferred locale in shell
1018 protected function envCheckShellLocale() {
1019 $os = php_uname( 's' );
1020 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1022 if ( !in_array( $os, $supported ) ) {
1026 # Get a list of available locales.
1028 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1034 $lines = array_map( 'trim', explode( "\n", $lines ) );
1035 $candidatesByLocale = array();
1036 $candidatesByLang = array();
1038 foreach ( $lines as $line ) {
1039 if ( $line === '' ) {
1043 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1047 list( , $lang, , , ) = $m;
1049 $candidatesByLocale[$m[0]] = $m;
1050 $candidatesByLang[$lang][] = $m;
1053 # Try the current value of LANG.
1054 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1055 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1060 # Try the most common ones.
1061 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1062 foreach ( $commonLocales as $commonLocale ) {
1063 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1064 $this->setVar( 'wgShellLocale', $commonLocale );
1070 # Is there an available locale in the Wiki's language?
1071 $wikiLang = $this->getVar( 'wgLanguageCode' );
1073 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1074 $m = reset( $candidatesByLang[$wikiLang] );
1075 $this->setVar( 'wgShellLocale', $m[0] );
1080 # Are there any at all?
1081 if ( count( $candidatesByLocale ) ) {
1082 $m = reset( $candidatesByLocale );
1083 $this->setVar( 'wgShellLocale', $m[0] );
1093 * Environment check for the permissions of the uploads directory
1096 protected function envCheckUploadsDirectory() {
1099 $dir = $IP . '/images/';
1100 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1101 $safe = !$this->dirIsExecutable( $dir, $url );
1104 $this->showMessage( 'config-uploads-not-safe', $dir );
1111 * Checks if suhosin.get.max_value_length is set, and if so generate
1112 * a warning because it decreases ResourceLoader performance.
1115 protected function envCheckSuhosinMaxValueLength() {
1116 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1117 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1118 // Only warn if the value is below the sane 1024
1119 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1126 * Convert a hex string representing a Unicode code point to that code point.
1130 protected function unicodeChar( $c ) {
1134 } elseif ( $c <= 0x7FF ) {
1135 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1136 } elseif ( $c <= 0xFFFF ) {
1137 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1138 . chr( 0x80 |
$c & 0x3F );
1139 } elseif ( $c <= 0x10FFFF ) {
1140 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1141 . chr( 0x80 |
$c >> 6 & 0x3F )
1142 . chr( 0x80 |
$c & 0x3F );
1149 * Check the libicu version
1151 protected function envCheckLibicu() {
1152 $utf8 = function_exists( 'utf8_normalize' );
1153 $intl = function_exists( 'normalizer_normalize' );
1156 * This needs to be updated something that the latest libicu
1157 * will properly normalize. This normalization was found at
1158 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1159 * Note that we use the hex representation to create the code
1160 * points in order to avoid any Unicode-destroying during transit.
1162 $not_normal_c = $this->unicodeChar( "FA6C" );
1163 $normal_c = $this->unicodeChar( "242EE" );
1165 $useNormalizer = 'php';
1166 $needsUpdate = false;
1169 * We're going to prefer the pecl extension here unless
1170 * utf8_normalize is more up to date.
1173 $useNormalizer = 'utf8';
1174 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1175 if ( $utf8 !== $normal_c ) {
1176 $needsUpdate = true;
1180 $useNormalizer = 'intl';
1181 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1182 if ( $intl !== $normal_c ) {
1183 $needsUpdate = true;
1187 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1188 // 'config-unicode-using-intl'
1189 if ( $useNormalizer === 'php' ) {
1190 $this->showMessage( 'config-unicode-pure-php-warning' );
1192 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1193 if ( $needsUpdate ) {
1194 $this->showMessage( 'config-unicode-update-warning' );
1202 protected function envCheckCtype() {
1203 if ( !function_exists( 'ctype_digit' ) ) {
1204 $this->showError( 'config-ctype' );
1215 protected function envCheckJSON() {
1216 if ( !function_exists( 'json_decode' ) ) {
1217 $this->showError( 'config-json' );
1226 * Get an array of likely places we can find executables. Check a bunch
1227 * of known Unix-like defaults, as well as the PATH environment variable
1228 * (which should maybe make it work for Windows?)
1232 protected static function getPossibleBinPaths() {
1234 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1235 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1236 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1241 * Search a path for any of the given executable names. Returns the
1242 * executable name if found. Also checks the version string returned
1243 * by each executable.
1245 * Used only by environment checks.
1247 * @param string $path path to search
1248 * @param array $names of executable names
1249 * @param $versionInfo Boolean false or array with two members:
1250 * 0 => Command to run for version check, with $1 for the full executable name
1251 * 1 => String to compare the output with
1253 * If $versionInfo is not false, only executables with a version
1254 * matching $versionInfo[1] will be returned.
1255 * @return bool|string
1257 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1258 if ( !is_array( $names ) ) {
1259 $names = array( $names );
1262 foreach ( $names as $name ) {
1263 $command = $path . DIRECTORY_SEPARATOR
. $name;
1265 wfSuppressWarnings();
1266 $file_exists = file_exists( $command );
1267 wfRestoreWarnings();
1269 if ( $file_exists ) {
1270 if ( !$versionInfo ) {
1274 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1275 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1285 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1286 * @see locateExecutable()
1287 * @param array $names Array of possible names.
1288 * @param array|bool $versionInfo Default: 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 locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1297 foreach ( self
::getPossibleBinPaths() as $path ) {
1298 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1299 if ( $exe !== false ) {
1308 * Checks if scripts located in the given directory can be executed via the given URL.
1310 * Used only by environment checks.
1311 * @param $dir string
1312 * @param $url string
1313 * @return bool|int|string
1315 public function dirIsExecutable( $dir, $url ) {
1316 $scriptTypes = array(
1318 "<?php echo 'ex' . 'ec';",
1319 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1323 // it would be good to check other popular languages here, but it'll be slow.
1325 wfSuppressWarnings();
1327 foreach ( $scriptTypes as $ext => $contents ) {
1328 foreach ( $contents as $source ) {
1329 $file = 'exectest.' . $ext;
1331 if ( !file_put_contents( $dir . $file, $source ) ) {
1336 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1337 } catch ( MWException
$e ) {
1338 // Http::get throws with allow_url_fopen = false and no curl extension.
1341 unlink( $dir . $file );
1343 if ( $text == 'exec' ) {
1344 wfRestoreWarnings();
1351 wfRestoreWarnings();
1357 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1359 * @param string $moduleName Name of module to check.
1362 public static function apacheModulePresent( $moduleName ) {
1363 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1366 // try it the hard way
1368 phpinfo( INFO_MODULES
);
1369 $info = ob_get_clean();
1371 return strpos( $info, $moduleName ) !== false;
1375 * ParserOptions are constructed before we determined the language, so fix it
1377 * @param $lang Language
1379 public function setParserLanguage( $lang ) {
1380 $this->parserOptions
->setTargetLanguage( $lang );
1381 $this->parserOptions
->setUserLang( $lang );
1385 * Overridden by WebInstaller to provide lastPage parameters.
1386 * @param $page string
1389 protected function getDocUrl( $page ) {
1390 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1394 * Finds extensions that follow the format /extensions/Name/Name.php,
1395 * and returns an array containing the value for 'Name' for each found extension.
1399 public function findExtensions() {
1400 if ( $this->getVar( 'IP' ) === null ) {
1404 $extDir = $this->getVar( 'IP' ) . '/extensions';
1405 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1409 $dh = opendir( $extDir );
1411 while ( ( $file = readdir( $dh ) ) !== false ) {
1412 if ( !is_dir( "$extDir/$file" ) ) {
1415 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1420 natcasesort( $exts );
1426 * Installs the auto-detected extensions.
1430 protected function includeExtensions() {
1432 $exts = $this->getVar( '_Extensions' );
1433 $IP = $this->getVar( 'IP' );
1436 * We need to include DefaultSettings before including extensions to avoid
1437 * warnings about unset variables. However, the only thing we really
1438 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1439 * if the extension has hidden hook registration in $wgExtensionFunctions,
1440 * but we're not opening that can of worms
1441 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1443 global $wgAutoloadClasses;
1444 $wgAutoloadClasses = array();
1446 require "$IP/includes/DefaultSettings.php";
1448 foreach ( $exts as $e ) {
1449 require_once "$IP/extensions/$e/$e.php";
1452 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1453 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1455 // Unset everyone else's hooks. Lord knows what someone might be doing
1456 // in ParserFirstCallInit (see bug 27171)
1457 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1459 return Status
::newGood();
1463 * Get an array of install steps. Should always be in the format of
1465 * 'name' => 'someuniquename',
1466 * 'callback' => array( $obj, 'method' ),
1468 * There must be a config-install-$name message defined per step, which will
1469 * be shown on install.
1471 * @param $installer DatabaseInstaller so we can make callbacks
1474 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1475 $coreInstallSteps = array(
1476 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1477 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1478 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1479 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1480 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1481 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1482 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1485 // Build the array of install steps starting from the core install list,
1486 // then adding any callbacks that wanted to attach after a given step
1487 foreach ( $coreInstallSteps as $step ) {
1488 $this->installSteps
[] = $step;
1489 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1490 $this->installSteps
= array_merge(
1491 $this->installSteps
,
1492 $this->extraInstallSteps
[$step['name']]
1497 // Prepend any steps that want to be at the beginning
1498 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1499 $this->installSteps
= array_merge(
1500 $this->extraInstallSteps
['BEGINNING'],
1505 // Extensions should always go first, chance to tie into hooks and such
1506 if ( count( $this->getVar( '_Extensions' ) ) ) {
1507 array_unshift( $this->installSteps
,
1508 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1510 $this->installSteps
[] = array(
1511 'name' => 'extension-tables',
1512 'callback' => array( $installer, 'createExtensionTables' )
1516 return $this->installSteps
;
1520 * Actually perform the installation.
1522 * @param array $startCB A callback array for the beginning of each step
1523 * @param array $endCB A callback array for the end of each step
1525 * @return Array of Status objects
1527 public function performInstallation( $startCB, $endCB ) {
1528 $installResults = array();
1529 $installer = $this->getDBInstaller();
1530 $installer->preInstall();
1531 $steps = $this->getInstallSteps( $installer );
1532 foreach ( $steps as $stepObj ) {
1533 $name = $stepObj['name'];
1534 call_user_func_array( $startCB, array( $name ) );
1536 // Perform the callback step
1537 $status = call_user_func( $stepObj['callback'], $installer );
1539 // Output and save the results
1540 call_user_func( $endCB, $name, $status );
1541 $installResults[$name] = $status;
1543 // If we've hit some sort of fatal, we need to bail.
1544 // Callback already had a chance to do output above.
1545 if ( !$status->isOk() ) {
1549 if ( $status->isOk() ) {
1550 $this->setVar( '_InstallDone', true );
1553 return $installResults;
1557 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1561 public function generateKeys() {
1562 $keys = array( 'wgSecretKey' => 64 );
1563 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1564 $keys['wgUpgradeKey'] = 16;
1567 return $this->doGenerateKeys( $keys );
1571 * Generate a secret value for variables using our CryptRand generator.
1572 * Produce a warning if the random source was insecure.
1574 * @param $keys Array
1577 protected function doGenerateKeys( $keys ) {
1578 $status = Status
::newGood();
1581 foreach ( $keys as $name => $length ) {
1582 $secretKey = MWCryptRand
::generateHex( $length, true );
1583 if ( !MWCryptRand
::wasStrong() ) {
1587 $this->setVar( $name, $secretKey );
1591 $names = array_keys( $keys );
1592 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1594 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1601 * Create the first user account, grant it sysop and bureaucrat rights
1605 protected function createSysop() {
1606 $name = $this->getVar( '_AdminName' );
1607 $user = User
::newFromName( $name );
1610 // We should've validated this earlier anyway!
1611 return Status
::newFatal( 'config-admin-error-user', $name );
1614 if ( $user->idForName() == 0 ) {
1615 $user->addToDatabase();
1618 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1619 } catch ( PasswordError
$pwe ) {
1620 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1623 $user->addGroup( 'sysop' );
1624 $user->addGroup( 'bureaucrat' );
1625 if ( $this->getVar( '_AdminEmail' ) ) {
1626 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1628 $user->saveSettings();
1630 // Update user count
1631 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1632 $ssUpdate->doUpdate();
1634 $status = Status
::newGood();
1636 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1637 $this->subscribeToMediaWikiAnnounce( $status );
1646 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1648 'email' => $this->getVar( '_AdminEmail' ),
1653 // Mailman doesn't support as many languages as we do, so check to make
1654 // sure their selected language is available
1655 $myLang = $this->getVar( '_UserLang' );
1656 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1657 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1658 $params['language'] = $myLang;
1661 if ( MWHttpRequest
::canMakeRequests() ) {
1662 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1663 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1664 if ( !$res->isOK() ) {
1665 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1668 $s->warning( 'config-install-subscribe-notpossible' );
1673 * Insert Main Page with default content.
1675 * @param $installer DatabaseInstaller
1678 protected function createMainpage( DatabaseInstaller
$installer ) {
1679 $status = Status
::newGood();
1681 $page = WikiPage
::factory( Title
::newMainPage() );
1682 $content = new WikitextContent(
1683 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1684 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1687 $page->doEditContent( $content,
1691 User
::newFromName( 'MediaWiki default' )
1693 } catch ( MWException
$e ) {
1694 //using raw, because $wgShowExceptionDetails can not be set yet
1695 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1702 * Override the necessary bits of the config to run an installation.
1704 public static function overrideConfig() {
1705 define( 'MW_NO_SESSION', 1 );
1707 // Don't access the database
1708 $GLOBALS['wgUseDatabaseMessages'] = false;
1709 // Don't cache langconv tables
1710 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1712 $GLOBALS['wgShowExceptionDetails'] = true;
1713 // Don't break forms
1714 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1716 // Extended debugging
1717 $GLOBALS['wgShowSQLErrors'] = true;
1718 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1720 // Allow multiple ob_flush() calls
1721 $GLOBALS['wgDisableOutputCompression'] = true;
1723 // Use a sensible cookie prefix (not my_wiki)
1724 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1726 // Some of the environment checks make shell requests, remove limits
1727 $GLOBALS['wgMaxShellMemory'] = 0;
1729 // Don't bother embedding images into generated CSS, which is not cached
1730 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1731 return $less->toBool( false );
1736 * Add an installation step following the given step.
1738 * @param array $callback A valid installation callback array, in this form:
1739 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1740 * @param string $findStep the step to find. Omit to put the step at the beginning
1742 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1743 $this->extraInstallSteps
[$findStep][] = $callback;
1747 * Disable the time limit for execution.
1748 * Some long-running pages (Install, Upgrade) will want to do this
1750 protected function disableTimeLimit() {
1751 wfSuppressWarnings();
1752 set_time_limit( 0 );
1753 wfRestoreWarnings();