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.
113 protected $envChecks = array(
115 'envCheckRegisterGlobals',
117 'envCheckMagicQuotes',
118 'envCheckMagicSybase',
125 'envCheckModSecurity',
132 'envCheckShellLocale',
133 'envCheckUploadsDirectory',
135 'envCheckSuhosinMaxValueLength',
141 * MediaWiki configuration globals that will eventually be passed through
142 * to LocalSettings.php. The names only are given here, the defaults
143 * typically come from DefaultSettings.php.
147 protected $defaultVarNames = array(
159 'wgEmailAuthentication',
162 'wgImageMagickConvertCommand',
168 'wgDeletedDirectory',
172 'wgUseInstantCommons',
175 'wgResourceLoaderMaxQueryLength',
179 * Variables that are stored alongside globals, and are used for any
180 * configuration of the installation process aside from the MediaWiki
181 * configuration. Map of names to defaults.
185 protected $internalDefaults = array(
187 '_Environment' => false,
188 '_SafeMode' => false,
189 '_RaiseMemory' => false,
190 '_UpgradeDone' => false,
191 '_InstallDone' => false,
192 '_Caches' => array(),
193 '_InstallPassword' => '',
194 '_SameAccount' => true,
195 '_CreateDBAccount' => false,
196 '_NamespaceType' => 'site-name',
197 '_AdminName' => '', // will be set later, when the user selects language
198 '_AdminPassword' => '',
199 '_AdminPasswordConfirm' => '',
201 '_Subscribe' => false,
202 '_SkipOptional' => 'continue',
203 '_RightsProfile' => 'wiki',
204 '_LicenseCode' => 'none',
206 '_Extensions' => array(),
207 '_MemCachedServers' => '',
208 '_UpgradeKeySupplied' => false,
209 '_ExistingDBSettings' => false,
211 // $wgLogo is probably wrong (bug 48084); set something that will work.
212 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
213 'wgLogo' => '$wgStylePath/common/images/wiki.png',
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
352 Language
::getLocalisationCache()->disableBackend();
353 // Disable LoadBalancer and wfGetDB etc.
354 LBFactory
::disableBackend();
356 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
357 // SqlBagOStuff will then throw since we just disabled wfGetDB)
358 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
359 ObjectCache
::clear();
360 $emptyCache = array( 'class' => 'EmptyBagOStuff' );
361 $GLOBALS['wgObjectCaches'] = array(
362 CACHE_NONE
=> $emptyCache,
363 CACHE_DB
=> $emptyCache,
364 CACHE_ANYTHING
=> $emptyCache,
365 CACHE_MEMCACHED
=> $emptyCache,
368 // Load the installer's i18n.
369 $wgMessagesDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
371 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
372 $wgUser = User
::newFromId( 0 );
374 $this->settings
= $this->internalDefaults
;
376 foreach ( $this->defaultVarNames
as $var ) {
377 $this->settings
[$var] = $GLOBALS[$var];
380 $this->compiledDBs
= array();
381 foreach ( self
::getDBTypes() as $type ) {
382 $installer = $this->getDBInstaller( $type );
384 if ( !$installer->isCompiled() ) {
387 $this->compiledDBs
[] = $type;
390 $this->parserTitle
= Title
::newFromText( 'Installer' );
391 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
392 $this->parserOptions
->setEditSection( false );
396 * Get a list of known DB types.
400 public static function getDBTypes() {
401 return self
::$dbTypes;
405 * Do initial checks of the PHP environment. Set variables according to
406 * the observed environment.
408 * It's possible that this may be called under the CLI SAPI, not the SAPI
409 * that the wiki will primarily run under. In that case, the subclass should
410 * initialise variables such as wgScriptPath, before calling this function.
412 * Under the web subclass, it can already be assumed that PHP 5+ is in use
413 * and that sessions are working.
417 public function doEnvironmentChecks() {
418 // Php version has already been checked by entry scripts
419 // Show message here for information purposes
420 $this->showMessage( 'config-env-php', PHP_VERSION
);
423 // Must go here because an old version of PCRE can prevent other checks from completing
424 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
425 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
426 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
429 foreach ( $this->envChecks
as $check ) {
430 $status = $this->$check();
431 if ( $status === false ) {
437 $this->setVar( '_Environment', $good );
439 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
443 * Set a MW configuration variable, or internal installer configuration variable.
445 * @param string $name
446 * @param mixed $value
448 public function setVar( $name, $value ) {
449 $this->settings
[$name] = $value;
453 * Get an MW configuration variable, or internal installer configuration variable.
454 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
455 * Installer variables are typically prefixed by an underscore.
457 * @param string $name
458 * @param mixed $default
462 public function getVar( $name, $default = null ) {
463 if ( !isset( $this->settings
[$name] ) ) {
466 return $this->settings
[$name];
471 * Get a list of DBs supported by current PHP setup
475 public function getCompiledDBs() {
476 return $this->compiledDBs
;
480 * Get an instance of DatabaseInstaller for the specified DB type.
482 * @param mixed $type DB installer for which is needed, false to use default.
484 * @return DatabaseInstaller
486 public function getDBInstaller( $type = false ) {
488 $type = $this->getVar( 'wgDBtype' );
491 $type = strtolower( $type );
493 if ( !isset( $this->dbInstallers
[$type] ) ) {
494 $class = ucfirst( $type ) . 'Installer';
495 $this->dbInstallers
[$type] = new $class( $this );
498 return $this->dbInstallers
[$type];
502 * Determine if LocalSettings.php exists. If it does, return its variables.
506 public static function getExistingLocalSettings() {
509 wfSuppressWarnings();
510 $_lsExists = file_exists( "$IP/LocalSettings.php" );
518 require "$IP/includes/DefaultSettings.php";
519 require "$IP/LocalSettings.php";
521 return get_defined_vars();
525 * Get a fake password for sending back to the user in HTML.
526 * This is a security mechanism to avoid compromise of the password in the
527 * event of session ID compromise.
529 * @param string $realPassword
533 public function getFakePassword( $realPassword ) {
534 return str_repeat( '*', strlen( $realPassword ) );
538 * Set a variable which stores a password, except if the new value is a
539 * fake password in which case leave it as it is.
541 * @param string $name
542 * @param mixed $value
544 public function setPassword( $name, $value ) {
545 if ( !preg_match( '/^\*+$/', $value ) ) {
546 $this->setVar( $name, $value );
551 * On POSIX systems return the primary group of the webserver we're running under.
552 * On other systems just returns null.
554 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
555 * webserver user before he can install.
557 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
561 public static function maybeGetWebserverPrimaryGroup() {
562 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
563 # I don't know this, this isn't UNIX.
567 # posix_getegid() *not* getmygid() because we want the group of the webserver,
568 # not whoever owns the current script.
569 $gid = posix_getegid();
570 $getpwuid = posix_getpwuid( $gid );
571 $group = $getpwuid['name'];
577 * Convert wikitext $text to HTML.
579 * This is potentially error prone since many parser features require a complete
580 * installed MW database. The solution is to just not use those features when you
581 * write your messages. This appears to work well enough. Basic formatting and
582 * external links work just fine.
584 * But in case a translator decides to throw in a "#ifexist" or internal link or
585 * whatever, this function is guarded to catch the attempted DB access and to present
586 * some fallback text.
588 * @param string $text
589 * @param bool $lineStart
592 public function parse( $text, $lineStart = false ) {
596 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
597 $html = $out->getText();
598 } catch ( DBAccessError
$e ) {
599 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
601 if ( !empty( $this->debug
) ) {
602 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
610 * @return ParserOptions
612 public function getParserOptions() {
613 return $this->parserOptions
;
616 public function disableLinkPopups() {
617 $this->parserOptions
->setExternalLinkTarget( false );
620 public function restoreLinkPopups() {
621 global $wgExternalLinkTarget;
622 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
626 * Install step which adds a row to the site_stats table with appropriate
629 * @param DatabaseInstaller $installer
633 public function populateSiteStats( DatabaseInstaller
$installer ) {
634 $status = $installer->getConnection();
635 if ( !$status->isOK() ) {
638 $status->value
->insert(
642 'ss_total_views' => 0,
643 'ss_total_edits' => 0,
644 'ss_good_articles' => 0,
645 'ss_total_pages' => 0,
652 return Status
::newGood();
656 * Exports all wg* variables stored by the installer into global scope.
658 public function exportVars() {
659 foreach ( $this->settings
as $name => $value ) {
660 if ( substr( $name, 0, 2 ) == 'wg' ) {
661 $GLOBALS[$name] = $value;
667 * Environment check for DB types.
670 protected function envCheckDB() {
675 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
676 // config-type-sqlite
677 foreach ( self
::getDBTypes() as $name ) {
678 $allNames[] = wfMessage( "config-type-$name" )->text();
681 $databases = $this->getCompiledDBs();
683 $databases = array_flip( $databases );
684 foreach ( array_keys( $databases ) as $db ) {
685 $installer = $this->getDBInstaller( $db );
686 $status = $installer->checkPrerequisites();
687 if ( !$status->isGood() ) {
688 $this->showStatusMessage( $status );
690 if ( !$status->isOK() ) {
691 unset( $databases[$db] );
694 $databases = array_flip( $databases );
696 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
698 // @todo FIXME: This only works for the web installer!
706 * Environment check for register_globals.
707 * Prevent installation if enabled
709 protected function envCheckRegisterGlobals() {
710 if ( wfIniGetBool( 'register_globals' ) ) {
711 $this->showMessage( 'config-register-globals-error' );
719 * Some versions of libxml+PHP break < and > encoding horribly
722 protected function envCheckBrokenXML() {
723 $test = new PhpXmlBugTester();
725 $this->showError( 'config-brokenlibxml' );
734 * Environment check for magic_quotes_runtime.
737 protected function envCheckMagicQuotes() {
738 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
739 $this->showError( 'config-magic-quotes-runtime' );
748 * Environment check for magic_quotes_sybase.
751 protected function envCheckMagicSybase() {
752 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
753 $this->showError( 'config-magic-quotes-sybase' );
762 * Environment check for mbstring.func_overload.
765 protected function envCheckMbstring() {
766 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
767 $this->showError( 'config-mbstring' );
776 * Environment check for safe_mode.
779 protected function envCheckSafeMode() {
780 if ( wfIniGetBool( 'safe_mode' ) ) {
781 $this->setVar( '_SafeMode', true );
782 $this->showMessage( 'config-safe-mode' );
789 * Environment check for the XML module.
792 protected function envCheckXML() {
793 if ( !function_exists( "utf8_encode" ) ) {
794 $this->showError( 'config-xml-bad' );
803 * Environment check for the PCRE module.
805 * @note If this check were to fail, the parser would
806 * probably throw an exception before the result
807 * of this check is shown to the user.
810 protected function envCheckPCRE() {
811 wfSuppressWarnings();
812 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
813 // Need to check for \p support too, as PCRE can be compiled
814 // with utf8 support, but not unicode property support.
815 // check that \p{Zs} (space separators) matches
816 // U+3000 (Ideographic space)
817 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
819 if ( $regexd != '--' ||
$regexprop != '--' ) {
820 $this->showError( 'config-pcre-no-utf8' );
829 * Environment check for available memory.
832 protected function envCheckMemory() {
833 $limit = ini_get( 'memory_limit' );
835 if ( !$limit ||
$limit == -1 ) {
839 $n = wfShorthandToInteger( $limit );
841 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
842 $newLimit = "{$this->minMemorySize}M";
844 if ( ini_set( "memory_limit", $newLimit ) === false ) {
845 $this->showMessage( 'config-memory-bad', $limit );
847 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
848 $this->setVar( '_RaiseMemory', true );
856 * Environment check for compiled object cache types.
858 protected function envCheckCache() {
860 foreach ( $this->objectCaches
as $name => $function ) {
861 if ( function_exists( $function ) ) {
862 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
865 $caches[$name] = true;
870 $this->showMessage( 'config-no-cache' );
873 $this->setVar( '_Caches', $caches );
877 * Scare user to death if they have mod_security
880 protected function envCheckModSecurity() {
881 if ( self
::apacheModulePresent( 'mod_security' ) ) {
882 $this->showMessage( 'config-mod-security' );
889 * Search for GNU diff3.
892 protected function envCheckDiff3() {
893 $names = array( "gdiff3", "diff3", "diff3.exe" );
894 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
896 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
899 $this->setVar( 'wgDiff3', $diff3 );
901 $this->setVar( 'wgDiff3', false );
902 $this->showMessage( 'config-diff3-bad' );
909 * Environment check for ImageMagick and GD.
912 protected function envCheckGraphics() {
913 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
914 $versionInfo = array( '$1 -version', 'ImageMagick' );
915 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
917 $this->setVar( 'wgImageMagickConvertCommand', '' );
919 $this->setVar( 'wgImageMagickConvertCommand', $convert );
920 $this->showMessage( 'config-imagemagick', $convert );
923 } elseif ( function_exists( 'imagejpeg' ) ) {
924 $this->showMessage( 'config-gd' );
926 $this->showMessage( 'config-no-scaling' );
938 protected function envCheckGit() {
939 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
940 $versionInfo = array( '$1 --version', 'git version' );
942 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
945 $this->setVar( 'wgGitBin', $git );
946 $this->showMessage( 'config-git', $git );
948 $this->setVar( 'wgGitBin', false );
949 $this->showMessage( 'config-git-bad' );
956 * Environment check for the server hostname.
958 protected function envCheckServer() {
959 $server = $this->envGetDefaultServer();
960 if ( $server !== null ) {
961 $this->showMessage( 'config-using-server', $server );
962 $this->setVar( 'wgServer', $server );
969 * Helper function to be called from envCheckServer()
972 abstract protected function envGetDefaultServer();
975 * Environment check for setting $IP and $wgScriptPath.
978 protected function envCheckPath() {
980 $IP = dirname( dirname( __DIR__
) );
981 $this->setVar( 'IP', $IP );
985 $this->getVar( 'wgServer' ),
986 $this->getVar( 'wgScriptPath' )
993 * Environment check for setting the preferred PHP file extension.
996 protected function envCheckExtension() {
997 // @todo FIXME: Detect this properly
998 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1003 $this->setVar( 'wgScriptExtension', ".$ext" );
1009 * Environment check for preferred locale in shell
1012 protected function envCheckShellLocale() {
1013 $os = php_uname( 's' );
1014 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1016 if ( !in_array( $os, $supported ) ) {
1020 # Get a list of available locales.
1022 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1028 $lines = array_map( 'trim', explode( "\n", $lines ) );
1029 $candidatesByLocale = array();
1030 $candidatesByLang = array();
1032 foreach ( $lines as $line ) {
1033 if ( $line === '' ) {
1037 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1041 list( , $lang, , , ) = $m;
1043 $candidatesByLocale[$m[0]] = $m;
1044 $candidatesByLang[$lang][] = $m;
1047 # Try the current value of LANG.
1048 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1049 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1054 # Try the most common ones.
1055 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1056 foreach ( $commonLocales as $commonLocale ) {
1057 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1058 $this->setVar( 'wgShellLocale', $commonLocale );
1064 # Is there an available locale in the Wiki's language?
1065 $wikiLang = $this->getVar( 'wgLanguageCode' );
1067 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1068 $m = reset( $candidatesByLang[$wikiLang] );
1069 $this->setVar( 'wgShellLocale', $m[0] );
1074 # Are there any at all?
1075 if ( count( $candidatesByLocale ) ) {
1076 $m = reset( $candidatesByLocale );
1077 $this->setVar( 'wgShellLocale', $m[0] );
1087 * Environment check for the permissions of the uploads directory
1090 protected function envCheckUploadsDirectory() {
1093 $dir = $IP . '/images/';
1094 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1095 $safe = !$this->dirIsExecutable( $dir, $url );
1098 $this->showMessage( 'config-uploads-not-safe', $dir );
1105 * Checks if suhosin.get.max_value_length is set, and if so generate
1106 * a warning because it decreases ResourceLoader performance.
1109 protected function envCheckSuhosinMaxValueLength() {
1110 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1111 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1112 // Only warn if the value is below the sane 1024
1113 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1120 * Convert a hex string representing a Unicode code point to that code point.
1124 protected function unicodeChar( $c ) {
1128 } elseif ( $c <= 0x7FF ) {
1129 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1130 } elseif ( $c <= 0xFFFF ) {
1131 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1132 . chr( 0x80 |
$c & 0x3F );
1133 } elseif ( $c <= 0x10FFFF ) {
1134 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1135 . chr( 0x80 |
$c >> 6 & 0x3F )
1136 . chr( 0x80 |
$c & 0x3F );
1143 * Check the libicu version
1145 protected function envCheckLibicu() {
1146 $utf8 = function_exists( 'utf8_normalize' );
1147 $intl = function_exists( 'normalizer_normalize' );
1150 * This needs to be updated something that the latest libicu
1151 * will properly normalize. This normalization was found at
1152 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1153 * Note that we use the hex representation to create the code
1154 * points in order to avoid any Unicode-destroying during transit.
1156 $not_normal_c = $this->unicodeChar( "FA6C" );
1157 $normal_c = $this->unicodeChar( "242EE" );
1159 $useNormalizer = 'php';
1160 $needsUpdate = false;
1163 * We're going to prefer the pecl extension here unless
1164 * utf8_normalize is more up to date.
1167 $useNormalizer = 'utf8';
1168 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1169 if ( $utf8 !== $normal_c ) {
1170 $needsUpdate = true;
1174 $useNormalizer = 'intl';
1175 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1176 if ( $intl !== $normal_c ) {
1177 $needsUpdate = true;
1181 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8',
1182 // 'config-unicode-using-intl'
1183 if ( $useNormalizer === 'php' ) {
1184 $this->showMessage( 'config-unicode-pure-php-warning' );
1186 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1187 if ( $needsUpdate ) {
1188 $this->showMessage( 'config-unicode-update-warning' );
1196 protected function envCheckCtype() {
1197 if ( !function_exists( 'ctype_digit' ) ) {
1198 $this->showError( 'config-ctype' );
1209 protected function envCheckJSON() {
1210 if ( !function_exists( 'json_decode' ) ) {
1211 $this->showError( 'config-json' );
1220 * Get an array of likely places we can find executables. Check a bunch
1221 * of known Unix-like defaults, as well as the PATH environment variable
1222 * (which should maybe make it work for Windows?)
1226 protected static function getPossibleBinPaths() {
1228 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1229 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1230 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1235 * Search a path for any of the given executable names. Returns the
1236 * executable name if found. Also checks the version string returned
1237 * by each executable.
1239 * Used only by environment checks.
1241 * @param string $path path to search
1242 * @param array $names of executable names
1243 * @param array|bool $versionInfo False or array with two members:
1244 * 0 => Command to run for version check, with $1 for the full executable name
1245 * 1 => String to compare the output with
1247 * If $versionInfo is not false, only executables with a version
1248 * matching $versionInfo[1] will be returned.
1249 * @return bool|string
1251 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1252 if ( !is_array( $names ) ) {
1253 $names = array( $names );
1256 foreach ( $names as $name ) {
1257 $command = $path . DIRECTORY_SEPARATOR
. $name;
1259 wfSuppressWarnings();
1260 $file_exists = file_exists( $command );
1261 wfRestoreWarnings();
1263 if ( $file_exists ) {
1264 if ( !$versionInfo ) {
1268 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1269 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1279 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1280 * @see locateExecutable()
1281 * @param array $names Array of possible names.
1282 * @param array|bool $versionInfo Default: false or array with two members:
1283 * 0 => Command to run for version check, with $1 for the full executable name
1284 * 1 => String to compare the output with
1286 * If $versionInfo is not false, only executables with a version
1287 * matching $versionInfo[1] will be returned.
1288 * @return bool|string
1290 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1291 foreach ( self
::getPossibleBinPaths() as $path ) {
1292 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1293 if ( $exe !== false ) {
1302 * Checks if scripts located in the given directory can be executed via the given URL.
1304 * Used only by environment checks.
1305 * @param string $dir
1306 * @param string $url
1307 * @return bool|int|string
1309 public function dirIsExecutable( $dir, $url ) {
1310 $scriptTypes = array(
1312 "<?php echo 'ex' . 'ec';",
1313 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1317 // it would be good to check other popular languages here, but it'll be slow.
1319 wfSuppressWarnings();
1321 foreach ( $scriptTypes as $ext => $contents ) {
1322 foreach ( $contents as $source ) {
1323 $file = 'exectest.' . $ext;
1325 if ( !file_put_contents( $dir . $file, $source ) ) {
1330 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1331 } catch ( MWException
$e ) {
1332 // Http::get throws with allow_url_fopen = false and no curl extension.
1335 unlink( $dir . $file );
1337 if ( $text == 'exec' ) {
1338 wfRestoreWarnings();
1345 wfRestoreWarnings();
1351 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1353 * @param string $moduleName Name of module to check.
1356 public static function apacheModulePresent( $moduleName ) {
1357 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1360 // try it the hard way
1362 phpinfo( INFO_MODULES
);
1363 $info = ob_get_clean();
1365 return strpos( $info, $moduleName ) !== false;
1369 * ParserOptions are constructed before we determined the language, so fix it
1371 * @param Language $lang
1373 public function setParserLanguage( $lang ) {
1374 $this->parserOptions
->setTargetLanguage( $lang );
1375 $this->parserOptions
->setUserLang( $lang );
1379 * Overridden by WebInstaller to provide lastPage parameters.
1380 * @param string $page
1383 protected function getDocUrl( $page ) {
1384 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1388 * Finds extensions that follow the format /extensions/Name/Name.php,
1389 * and returns an array containing the value for 'Name' for each found extension.
1393 public function findExtensions() {
1394 if ( $this->getVar( 'IP' ) === null ) {
1398 $extDir = $this->getVar( 'IP' ) . '/extensions';
1399 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1403 $dh = opendir( $extDir );
1405 while ( ( $file = readdir( $dh ) ) !== false ) {
1406 if ( !is_dir( "$extDir/$file" ) ) {
1409 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1414 natcasesort( $exts );
1420 * Installs the auto-detected extensions.
1424 protected function includeExtensions() {
1426 $exts = $this->getVar( '_Extensions' );
1427 $IP = $this->getVar( 'IP' );
1430 * We need to include DefaultSettings before including extensions to avoid
1431 * warnings about unset variables. However, the only thing we really
1432 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1433 * if the extension has hidden hook registration in $wgExtensionFunctions,
1434 * but we're not opening that can of worms
1435 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1437 global $wgAutoloadClasses;
1438 $wgAutoloadClasses = array();
1440 require "$IP/includes/DefaultSettings.php";
1442 foreach ( $exts as $e ) {
1443 require_once "$IP/extensions/$e/$e.php";
1446 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1447 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1449 // Unset everyone else's hooks. Lord knows what someone might be doing
1450 // in ParserFirstCallInit (see bug 27171)
1451 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1453 return Status
::newGood();
1457 * Get an array of install steps. Should always be in the format of
1459 * 'name' => 'someuniquename',
1460 * 'callback' => array( $obj, 'method' ),
1462 * There must be a config-install-$name message defined per step, which will
1463 * be shown on install.
1465 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1468 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1469 $coreInstallSteps = array(
1470 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1471 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1472 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1473 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1474 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1475 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1476 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1479 // Build the array of install steps starting from the core install list,
1480 // then adding any callbacks that wanted to attach after a given step
1481 foreach ( $coreInstallSteps as $step ) {
1482 $this->installSteps
[] = $step;
1483 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1484 $this->installSteps
= array_merge(
1485 $this->installSteps
,
1486 $this->extraInstallSteps
[$step['name']]
1491 // Prepend any steps that want to be at the beginning
1492 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1493 $this->installSteps
= array_merge(
1494 $this->extraInstallSteps
['BEGINNING'],
1499 // Extensions should always go first, chance to tie into hooks and such
1500 if ( count( $this->getVar( '_Extensions' ) ) ) {
1501 array_unshift( $this->installSteps
,
1502 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1504 $this->installSteps
[] = array(
1505 'name' => 'extension-tables',
1506 'callback' => array( $installer, 'createExtensionTables' )
1510 return $this->installSteps
;
1514 * Actually perform the installation.
1516 * @param callable $startCB A callback array for the beginning of each step
1517 * @param callable $endCB A callback array for the end of each step
1519 * @return array Array of Status objects
1521 public function performInstallation( $startCB, $endCB ) {
1522 $installResults = array();
1523 $installer = $this->getDBInstaller();
1524 $installer->preInstall();
1525 $steps = $this->getInstallSteps( $installer );
1526 foreach ( $steps as $stepObj ) {
1527 $name = $stepObj['name'];
1528 call_user_func_array( $startCB, array( $name ) );
1530 // Perform the callback step
1531 $status = call_user_func( $stepObj['callback'], $installer );
1533 // Output and save the results
1534 call_user_func( $endCB, $name, $status );
1535 $installResults[$name] = $status;
1537 // If we've hit some sort of fatal, we need to bail.
1538 // Callback already had a chance to do output above.
1539 if ( !$status->isOk() ) {
1543 if ( $status->isOk() ) {
1544 $this->setVar( '_InstallDone', true );
1547 return $installResults;
1551 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1555 public function generateKeys() {
1556 $keys = array( 'wgSecretKey' => 64 );
1557 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1558 $keys['wgUpgradeKey'] = 16;
1561 return $this->doGenerateKeys( $keys );
1565 * Generate a secret value for variables using our CryptRand generator.
1566 * Produce a warning if the random source was insecure.
1568 * @param array $keys
1571 protected function doGenerateKeys( $keys ) {
1572 $status = Status
::newGood();
1575 foreach ( $keys as $name => $length ) {
1576 $secretKey = MWCryptRand
::generateHex( $length, true );
1577 if ( !MWCryptRand
::wasStrong() ) {
1581 $this->setVar( $name, $secretKey );
1585 $names = array_keys( $keys );
1586 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1588 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1595 * Create the first user account, grant it sysop and bureaucrat rights
1599 protected function createSysop() {
1600 $name = $this->getVar( '_AdminName' );
1601 $user = User
::newFromName( $name );
1604 // We should've validated this earlier anyway!
1605 return Status
::newFatal( 'config-admin-error-user', $name );
1608 if ( $user->idForName() == 0 ) {
1609 $user->addToDatabase();
1612 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1613 } catch ( PasswordError
$pwe ) {
1614 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1617 $user->addGroup( 'sysop' );
1618 $user->addGroup( 'bureaucrat' );
1619 if ( $this->getVar( '_AdminEmail' ) ) {
1620 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1622 $user->saveSettings();
1624 // Update user count
1625 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1626 $ssUpdate->doUpdate();
1628 $status = Status
::newGood();
1630 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1631 $this->subscribeToMediaWikiAnnounce( $status );
1640 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1642 'email' => $this->getVar( '_AdminEmail' ),
1647 // Mailman doesn't support as many languages as we do, so check to make
1648 // sure their selected language is available
1649 $myLang = $this->getVar( '_UserLang' );
1650 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1651 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1652 $params['language'] = $myLang;
1655 if ( MWHttpRequest
::canMakeRequests() ) {
1656 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1657 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1658 if ( !$res->isOK() ) {
1659 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1662 $s->warning( 'config-install-subscribe-notpossible' );
1667 * Insert Main Page with default content.
1669 * @param DatabaseInstaller $installer
1672 protected function createMainpage( DatabaseInstaller
$installer ) {
1673 $status = Status
::newGood();
1675 $page = WikiPage
::factory( Title
::newMainPage() );
1676 $content = new WikitextContent(
1677 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1678 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1681 $page->doEditContent( $content,
1685 User
::newFromName( 'MediaWiki default' )
1687 } catch ( MWException
$e ) {
1688 //using raw, because $wgShowExceptionDetails can not be set yet
1689 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1696 * Override the necessary bits of the config to run an installation.
1698 public static function overrideConfig() {
1699 define( 'MW_NO_SESSION', 1 );
1701 // Don't access the database
1702 $GLOBALS['wgUseDatabaseMessages'] = false;
1703 // Don't cache langconv tables
1704 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1706 $GLOBALS['wgShowExceptionDetails'] = true;
1707 // Don't break forms
1708 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1710 // Extended debugging
1711 $GLOBALS['wgShowSQLErrors'] = true;
1712 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1714 // Allow multiple ob_flush() calls
1715 $GLOBALS['wgDisableOutputCompression'] = true;
1717 // Use a sensible cookie prefix (not my_wiki)
1718 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1720 // Some of the environment checks make shell requests, remove limits
1721 $GLOBALS['wgMaxShellMemory'] = 0;
1723 // Don't bother embedding images into generated CSS, which is not cached
1724 $GLOBALS['wgResourceLoaderLESSFunctions']['embeddable'] = function ( $frame, $less ) {
1725 return $less->toBool( false );
1730 * Add an installation step following the given step.
1732 * @param callable $callback A valid installation callback array, in this form:
1733 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1734 * @param string $findStep The step to find. Omit to put the step at the beginning
1736 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1737 $this->extraInstallSteps
[$findStep][] = $callback;
1741 * Disable the time limit for execution.
1742 * Some long-running pages (Install, Upgrade) will want to do this
1744 protected function disableTimeLimit() {
1745 wfSuppressWarnings();
1746 set_time_limit( 0 );
1747 wfRestoreWarnings();