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';
50 * Cached DB installer instances, access using getDBInstaller().
54 protected $dbInstallers = array();
57 * Minimum memory size in MB.
61 protected $minMemorySize = 50;
64 * Cached Title, used by parse().
68 protected $parserTitle;
71 * Cached ParserOptions, used by parse().
75 protected $parserOptions;
78 * Known database types. These correspond to the class names <type>Installer,
79 * and are also MediaWiki database types valid for $wgDBtype.
81 * To add a new type, create a <type>Installer class and a Database<type>
82 * class, and add a config-type-<type> message to MessagesEn.php.
86 protected static $dbTypes = array(
94 * A list of environment check methods called by doEnvironmentChecks().
95 * These may output warnings using showMessage(), and/or abort the
96 * installation process by returning false.
100 protected $envChecks = array(
102 'envCheckRegisterGlobals',
105 'envCheckMagicQuotes',
106 'envCheckMagicSybase',
114 'envCheckModSecurity',
121 'envCheckShellLocale',
122 'envCheckUploadsDirectory',
124 'envCheckSuhosinMaxValueLength',
129 * MediaWiki configuration globals that will eventually be passed through
130 * to LocalSettings.php. The names only are given here, the defaults
131 * typically come from DefaultSettings.php.
135 protected $defaultVarNames = array(
147 'wgEmailAuthentication',
150 'wgImageMagickConvertCommand',
157 'wgDeletedDirectory',
162 'wgUseInstantCommons',
165 'wgResourceLoaderMaxQueryLength',
169 * Variables that are stored alongside globals, and are used for any
170 * configuration of the installation process aside from the MediaWiki
171 * configuration. Map of names to defaults.
175 protected $internalDefaults = array(
177 '_Environment' => false,
178 '_CompiledDBs' => array(),
179 '_SafeMode' => false,
180 '_RaiseMemory' => false,
181 '_UpgradeDone' => false,
182 '_InstallDone' => false,
183 '_Caches' => array(),
184 '_InstallPassword' => '',
185 '_SameAccount' => true,
186 '_CreateDBAccount' => false,
187 '_NamespaceType' => 'site-name',
188 '_AdminName' => '', // will be set later, when the user selects language
189 '_AdminPassword' => '',
190 '_AdminPassword2' => '',
192 '_Subscribe' => false,
193 '_SkipOptional' => 'continue',
194 '_RightsProfile' => 'wiki',
195 '_LicenseCode' => 'none',
197 '_Extensions' => array(),
198 '_MemCachedServers' => '',
199 '_UpgradeKeySupplied' => false,
200 '_ExistingDBSettings' => false,
204 * The actual list of installation steps. This will be initialized by getInstallSteps()
208 private $installSteps = array();
211 * Extra steps for installation, for things like DatabaseInstallers to modify
215 protected $extraInstallSteps = array();
218 * Known object cache types and the functions used to test for their existence.
222 protected $objectCaches = array(
223 'xcache' => 'xcache_get',
224 'apc' => 'apc_fetch',
225 'wincache' => 'wincache_ucache_get'
229 * User rights profiles.
233 public $rightsProfiles = array(
236 '*' => array( 'edit' => false )
240 'createaccount' => false,
246 'createaccount' => false,
258 public $licenses = array(
260 'url' => 'http://creativecommons.org/licenses/by/3.0/',
261 'icon' => '{$wgStylePath}/common/images/cc-by.png',
264 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
265 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
267 'cc-by-nc-sa' => array(
268 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
269 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
272 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
273 'icon' => '{$wgStylePath}/common/images/cc-0.png',
277 'icon' => '{$wgStylePath}/common/images/public-domain.png',
280 'url' => 'http://www.gnu.org/copyleft/fdl.html',
281 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
288 'cc-choose' => array(
289 // Details will be filled in by the selector.
297 * URL to mediawiki-announce subscription
299 protected $mediaWikiAnnounceUrl = 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
302 * Supported language codes for Mailman
304 protected $mediaWikiAnnounceLanguages = array(
305 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
306 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
307 'sl', 'sr', 'sv', 'tr', 'uk'
311 * UI interface for displaying a short message
312 * The parameters are like parameters to wfMessage().
313 * The messages will be in wikitext format, which will be converted to an
314 * output format such as HTML or text before being sent to the user.
317 abstract public function showMessage( $msg /*, ... */ );
320 * Same as showMessage(), but for displaying errors
323 abstract public function showError( $msg /*, ... */ );
326 * Show a message to the installing user by using a Status object
327 * @param $status Status
329 abstract public function showStatusMessage( Status
$status );
332 * Constructor, always call this from child classes.
334 public function __construct() {
335 global $wgExtensionMessagesFiles, $wgUser;
337 // Disable the i18n cache and LoadBalancer
338 Language
::getLocalisationCache()->disableBackend();
339 LBFactory
::disableBackend();
341 // Load the installer's i18n file.
342 $wgExtensionMessagesFiles['MediawikiInstaller'] =
343 __DIR__
. '/Installer.i18n.php';
345 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
346 $wgUser = User
::newFromId( 0 );
348 $this->settings
= $this->internalDefaults
;
350 foreach ( $this->defaultVarNames
as $var ) {
351 $this->settings
[$var] = $GLOBALS[$var];
354 $compiledDBs = array();
355 foreach ( self
::getDBTypes() as $type ) {
356 $installer = $this->getDBInstaller( $type );
358 if ( !$installer->isCompiled() ) {
361 $compiledDBs[] = $type;
363 $defaults = $installer->getGlobalDefaults();
365 foreach ( $installer->getGlobalNames() as $var ) {
366 if ( isset( $defaults[$var] ) ) {
367 $this->settings
[$var] = $defaults[$var];
369 $this->settings
[$var] = $GLOBALS[$var];
373 $this->setVar( '_CompiledDBs', $compiledDBs );
375 $this->parserTitle
= Title
::newFromText( 'Installer' );
376 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
377 $this->parserOptions
->setEditSection( false );
381 * Get a list of known DB types.
385 public static function getDBTypes() {
386 return self
::$dbTypes;
390 * Do initial checks of the PHP environment. Set variables according to
391 * the observed environment.
393 * It's possible that this may be called under the CLI SAPI, not the SAPI
394 * that the wiki will primarily run under. In that case, the subclass should
395 * initialise variables such as wgScriptPath, before calling this function.
397 * Under the web subclass, it can already be assumed that PHP 5+ is in use
398 * and that sessions are working.
402 public function doEnvironmentChecks() {
403 $phpVersion = phpversion();
404 if( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
405 $this->showMessage( 'config-env-php', $phpVersion );
408 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
413 foreach ( $this->envChecks
as $check ) {
414 $status = $this->$check();
415 if ( $status === false ) {
421 $this->setVar( '_Environment', $good );
423 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
427 * Set a MW configuration variable, or internal installer configuration variable.
429 * @param $name String
430 * @param $value Mixed
432 public function setVar( $name, $value ) {
433 $this->settings
[$name] = $value;
437 * Get an MW configuration variable, or internal installer configuration variable.
438 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
439 * Installer variables are typically prefixed by an underscore.
441 * @param $name String
442 * @param $default Mixed
446 public function getVar( $name, $default = null ) {
447 if ( !isset( $this->settings
[$name] ) ) {
450 return $this->settings
[$name];
455 * Get an instance of DatabaseInstaller for the specified DB type.
457 * @param $type Mixed: DB installer for which is needed, false to use default.
459 * @return DatabaseInstaller
461 public function getDBInstaller( $type = false ) {
463 $type = $this->getVar( 'wgDBtype' );
466 $type = strtolower( $type );
468 if ( !isset( $this->dbInstallers
[$type] ) ) {
469 $class = ucfirst( $type ) . 'Installer';
470 $this->dbInstallers
[$type] = new $class( $this );
473 return $this->dbInstallers
[$type];
477 * Determine if LocalSettings.php exists. If it does, return its variables,
478 * merged with those from AdminSettings.php, as an array.
482 public static function getExistingLocalSettings() {
485 wfSuppressWarnings();
486 $_lsExists = file_exists( "$IP/LocalSettings.php" );
494 require( "$IP/includes/DefaultSettings.php" );
495 require( "$IP/LocalSettings.php" );
496 if ( file_exists( "$IP/AdminSettings.php" ) ) {
497 require( "$IP/AdminSettings.php" );
499 return get_defined_vars();
503 * Get a fake password for sending back to the user in HTML.
504 * This is a security mechanism to avoid compromise of the password in the
505 * event of session ID compromise.
507 * @param $realPassword String
511 public function getFakePassword( $realPassword ) {
512 return str_repeat( '*', strlen( $realPassword ) );
516 * Set a variable which stores a password, except if the new value is a
517 * fake password in which case leave it as it is.
519 * @param $name String
520 * @param $value Mixed
522 public function setPassword( $name, $value ) {
523 if ( !preg_match( '/^\*+$/', $value ) ) {
524 $this->setVar( $name, $value );
529 * On POSIX systems return the primary group of the webserver we're running under.
530 * On other systems just returns null.
532 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
533 * webserver user before he can install.
535 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
539 public static function maybeGetWebserverPrimaryGroup() {
540 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
541 # I don't know this, this isn't UNIX.
545 # posix_getegid() *not* getmygid() because we want the group of the webserver,
546 # not whoever owns the current script.
547 $gid = posix_getegid();
548 $getpwuid = posix_getpwuid( $gid );
549 $group = $getpwuid['name'];
555 * Convert wikitext $text to HTML.
557 * This is potentially error prone since many parser features require a complete
558 * installed MW database. The solution is to just not use those features when you
559 * write your messages. This appears to work well enough. Basic formatting and
560 * external links work just fine.
562 * But in case a translator decides to throw in a "#ifexist" or internal link or
563 * whatever, this function is guarded to catch the attempted DB access and to present
564 * some fallback text.
566 * @param $text String
567 * @param $lineStart Boolean
570 public function parse( $text, $lineStart = false ) {
574 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
575 $html = $out->getText();
576 } catch ( DBAccessError
$e ) {
577 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
579 if ( !empty( $this->debug
) ) {
580 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
588 * @return ParserOptions
590 public function getParserOptions() {
591 return $this->parserOptions
;
594 public function disableLinkPopups() {
595 $this->parserOptions
->setExternalLinkTarget( false );
598 public function restoreLinkPopups() {
599 global $wgExternalLinkTarget;
600 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
604 * Install step which adds a row to the site_stats table with appropriate
607 * @param $installer DatabaseInstaller
611 public function populateSiteStats( DatabaseInstaller
$installer ) {
612 $status = $installer->getConnection();
613 if ( !$status->isOK() ) {
616 $status->value
->insert( 'site_stats', array(
618 'ss_total_views' => 0,
619 'ss_total_edits' => 0,
620 'ss_good_articles' => 0,
621 'ss_total_pages' => 0,
624 __METHOD__
, 'IGNORE' );
625 return Status
::newGood();
629 * Exports all wg* variables stored by the installer into global scope.
631 public function exportVars() {
632 foreach ( $this->settings
as $name => $value ) {
633 if ( substr( $name, 0, 2 ) == 'wg' ) {
634 $GLOBALS[$name] = $value;
640 * Environment check for DB types.
643 protected function envCheckDB() {
648 // Give grep a chance to find the usages:
649 // config-type-mysql, config-type-postgres, config-type-oracle, config-type-sqlite
650 foreach ( self
::getDBTypes() as $name ) {
651 $allNames[] = wfMessage( "config-type-$name" )->text();
654 // cache initially available databases to make sure that everything will be displayed correctly
655 // after a refresh on env checks page
656 $databases = $this->getVar( '_CompiledDBs-preFilter' );
658 $databases = $this->getVar( '_CompiledDBs' );
659 $this->setVar( '_CompiledDBs-preFilter', $databases );
662 $databases = array_flip ( $databases );
663 foreach ( array_keys( $databases ) as $db ) {
664 $installer = $this->getDBInstaller( $db );
665 $status = $installer->checkPrerequisites();
666 if ( !$status->isGood() ) {
667 $this->showStatusMessage( $status );
669 if ( !$status->isOK() ) {
670 unset( $databases[$db] );
673 $databases = array_flip( $databases );
675 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
676 // @todo FIXME: This only works for the web installer!
679 $this->setVar( '_CompiledDBs', $databases );
684 * Environment check for register_globals.
686 protected function envCheckRegisterGlobals() {
687 if( wfIniGetBool( 'register_globals' ) ) {
688 $this->showMessage( 'config-register-globals' );
693 * Some versions of libxml+PHP break < and > encoding horribly
696 protected function envCheckBrokenXML() {
697 $test = new PhpXmlBugTester();
699 $this->showError( 'config-brokenlibxml' );
706 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
707 * reference parameters to __call() are not converted to null
710 protected function envCheckPHP531() {
711 $test = new PhpRefCallBugTester
;
714 $this->showError( 'config-using531', phpversion() );
721 * Environment check for magic_quotes_runtime.
724 protected function envCheckMagicQuotes() {
725 if( wfIniGetBool( "magic_quotes_runtime" ) ) {
726 $this->showError( 'config-magic-quotes-runtime' );
733 * Environment check for magic_quotes_sybase.
736 protected function envCheckMagicSybase() {
737 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
738 $this->showError( 'config-magic-quotes-sybase' );
745 * Environment check for mbstring.func_overload.
748 protected function envCheckMbstring() {
749 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
750 $this->showError( 'config-mbstring' );
757 * Environment check for zend.ze1_compatibility_mode.
760 protected function envCheckZE1() {
761 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
762 $this->showError( 'config-ze1' );
769 * Environment check for safe_mode.
772 protected function envCheckSafeMode() {
773 if ( wfIniGetBool( 'safe_mode' ) ) {
774 $this->setVar( '_SafeMode', true );
775 $this->showMessage( 'config-safe-mode' );
781 * Environment check for the XML module.
784 protected function envCheckXML() {
785 if ( !function_exists( "utf8_encode" ) ) {
786 $this->showError( 'config-xml-bad' );
793 * Environment check for the PCRE module.
795 * @note If this check were to fail, the parser would
796 * probably throw an exception before the result
797 * of this check is shown to the user.
800 protected function envCheckPCRE() {
801 if ( !function_exists( 'preg_match' ) ) {
802 $this->showError( 'config-pcre' );
805 wfSuppressWarnings();
806 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
807 // Need to check for \p support too, as PCRE can be compiled
808 // with utf8 support, but not unicode property support.
809 // check that \p{Zs} (space separators) matches
810 // U+3000 (Ideographic space)
811 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
813 if ( $regexd != '--' ||
$regexprop != '--' ) {
814 $this->showError( 'config-pcre-no-utf8' );
821 * Environment check for available memory.
824 protected function envCheckMemory() {
825 $limit = ini_get( 'memory_limit' );
827 if ( !$limit ||
$limit == -1 ) {
831 $n = wfShorthandToInteger( $limit );
833 if( $n < $this->minMemorySize
* 1024 * 1024 ) {
834 $newLimit = "{$this->minMemorySize}M";
836 if( ini_set( "memory_limit", $newLimit ) === false ) {
837 $this->showMessage( 'config-memory-bad', $limit );
839 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
840 $this->setVar( '_RaiseMemory', true );
847 * Environment check for compiled object cache types.
849 protected function envCheckCache() {
851 foreach ( $this->objectCaches
as $name => $function ) {
852 if ( function_exists( $function ) ) {
853 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
856 $caches[$name] = true;
861 $this->showMessage( 'config-no-cache' );
864 $this->setVar( '_Caches', $caches );
868 * Scare user to death if they have mod_security
871 protected function envCheckModSecurity() {
872 if ( self
::apacheModulePresent( 'mod_security' ) ) {
873 $this->showMessage( 'config-mod-security' );
879 * Search for GNU diff3.
882 protected function envCheckDiff3() {
883 $names = array( "gdiff3", "diff3", "diff3.exe" );
884 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
886 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
889 $this->setVar( 'wgDiff3', $diff3 );
891 $this->setVar( 'wgDiff3', false );
892 $this->showMessage( 'config-diff3-bad' );
898 * Environment check for ImageMagick and GD.
901 protected function envCheckGraphics() {
902 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
903 $versionInfo = array( '$1 -version', 'ImageMagick' );
904 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
906 $this->setVar( 'wgImageMagickConvertCommand', '' );
908 $this->setVar( 'wgImageMagickConvertCommand', $convert );
909 $this->showMessage( 'config-imagemagick', $convert );
911 } elseif ( function_exists( 'imagejpeg' ) ) {
912 $this->showMessage( 'config-gd' );
915 $this->showMessage( 'config-no-scaling' );
926 protected function envCheckGit() {
927 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
928 $versionInfo = array( '$1 --version', 'git version' );
930 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
933 $this->setVar( 'wgGitBin', $git );
934 $this->showMessage( 'config-git', $git );
936 $this->setVar( 'wgGitBin', false );
937 $this->showMessage( 'config-git-bad' );
943 * Environment check for the server hostname.
945 protected function envCheckServer() {
946 $server = $this->envGetDefaultServer();
947 $this->showMessage( 'config-using-server', $server );
948 $this->setVar( 'wgServer', $server );
953 * Helper function to be called from envCheckServer()
956 abstract protected function envGetDefaultServer();
959 * Environment check for setting $IP and $wgScriptPath.
962 protected function envCheckPath() {
964 $IP = dirname( dirname( __DIR__
) );
965 $this->setVar( 'IP', $IP );
967 $this->showMessage( 'config-using-uri', $this->getVar( 'wgServer' ), $this->getVar( 'wgScriptPath' ) );
972 * Environment check for setting the preferred PHP file extension.
974 protected function envCheckExtension() {
975 // @todo FIXME: Detect this properly
976 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
981 $this->setVar( 'wgScriptExtension', ".$ext" );
989 protected function envCheckShellLocale() {
990 $os = php_uname( 's' );
991 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
993 if ( !in_array( $os, $supported ) ) {
997 # Get a list of available locales.
999 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1005 $lines = wfArrayMap( 'trim', explode( "\n", $lines ) );
1006 $candidatesByLocale = array();
1007 $candidatesByLang = array();
1009 foreach ( $lines as $line ) {
1010 if ( $line === '' ) {
1014 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1018 list( , $lang, , , ) = $m;
1020 $candidatesByLocale[$m[0]] = $m;
1021 $candidatesByLang[$lang][] = $m;
1024 # Try the current value of LANG.
1025 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1026 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1030 # Try the most common ones.
1031 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1032 foreach ( $commonLocales as $commonLocale ) {
1033 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1034 $this->setVar( 'wgShellLocale', $commonLocale );
1039 # Is there an available locale in the Wiki's language?
1040 $wikiLang = $this->getVar( 'wgLanguageCode' );
1042 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1043 $m = reset( $candidatesByLang[$wikiLang] );
1044 $this->setVar( 'wgShellLocale', $m[0] );
1048 # Are there any at all?
1049 if ( count( $candidatesByLocale ) ) {
1050 $m = reset( $candidatesByLocale );
1051 $this->setVar( 'wgShellLocale', $m[0] );
1063 protected function envCheckUploadsDirectory() {
1066 $dir = $IP . '/images/';
1067 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1068 $safe = !$this->dirIsExecutable( $dir, $url );
1071 $this->showMessage( 'config-uploads-not-safe', $dir );
1077 * Checks if suhosin.get.max_value_length is set, and if so, sets
1078 * $wgResourceLoaderMaxQueryLength to that value in the generated
1079 * LocalSettings file
1082 protected function envCheckSuhosinMaxValueLength() {
1083 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1084 if ( $maxValueLength > 0 ) {
1085 if( $maxValueLength < 1024 ) {
1086 # Only warn if the value is below the sane 1024
1087 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1090 $maxValueLength = -1;
1092 $this->setVar( 'wgResourceLoaderMaxQueryLength', $maxValueLength );
1097 * Convert a hex string representing a Unicode code point to that code point.
1101 protected function unicodeChar( $c ) {
1105 } elseif ( $c <= 0x7FF ) {
1106 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1107 } elseif ( $c <= 0xFFFF ) {
1108 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1109 . chr( 0x80 |
$c & 0x3F );
1110 } elseif ( $c <= 0x10FFFF ) {
1111 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1112 . chr( 0x80 |
$c >> 6 & 0x3F )
1113 . chr( 0x80 |
$c & 0x3F );
1120 * Check the libicu version
1122 protected function envCheckLibicu() {
1123 $utf8 = function_exists( 'utf8_normalize' );
1124 $intl = function_exists( 'normalizer_normalize' );
1127 * This needs to be updated something that the latest libicu
1128 * will properly normalize. This normalization was found at
1129 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1130 * Note that we use the hex representation to create the code
1131 * points in order to avoid any Unicode-destroying during transit.
1133 $not_normal_c = $this->unicodeChar( "FA6C" );
1134 $normal_c = $this->unicodeChar( "242EE" );
1136 $useNormalizer = 'php';
1137 $needsUpdate = false;
1140 * We're going to prefer the pecl extension here unless
1141 * utf8_normalize is more up to date.
1144 $useNormalizer = 'utf8';
1145 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1146 if ( $utf8 !== $normal_c ) {
1147 $needsUpdate = true;
1151 $useNormalizer = 'intl';
1152 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1153 if ( $intl !== $normal_c ) {
1154 $needsUpdate = true;
1158 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
1159 if( $useNormalizer === 'php' ) {
1160 $this->showMessage( 'config-unicode-pure-php-warning' );
1162 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1163 if( $needsUpdate ) {
1164 $this->showMessage( 'config-unicode-update-warning' );
1172 protected function envCheckCtype() {
1173 if ( !function_exists( 'ctype_digit' ) ) {
1174 $this->showError( 'config-ctype' );
1181 * Get an array of likely places we can find executables. Check a bunch
1182 * of known Unix-like defaults, as well as the PATH environment variable
1183 * (which should maybe make it work for Windows?)
1187 protected static function getPossibleBinPaths() {
1189 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1190 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1191 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1196 * Search a path for any of the given executable names. Returns the
1197 * executable name if found. Also checks the version string returned
1198 * by each executable.
1200 * Used only by environment checks.
1202 * @param string $path path to search
1203 * @param array $names of executable names
1204 * @param $versionInfo Boolean false or array with two members:
1205 * 0 => Command to run for version check, with $1 for the full executable name
1206 * 1 => String to compare the output with
1208 * If $versionInfo is not false, only executables with a version
1209 * matching $versionInfo[1] will be returned.
1210 * @return bool|string
1212 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1213 if ( !is_array( $names ) ) {
1214 $names = array( $names );
1217 foreach ( $names as $name ) {
1218 $command = $path . DIRECTORY_SEPARATOR
. $name;
1220 wfSuppressWarnings();
1221 $file_exists = file_exists( $command );
1222 wfRestoreWarnings();
1224 if ( $file_exists ) {
1225 if ( !$versionInfo ) {
1229 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1230 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1239 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1240 * @see locateExecutable()
1242 * @param $versionInfo bool
1243 * @return bool|string
1245 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1246 foreach( self
::getPossibleBinPaths() as $path ) {
1247 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1248 if( $exe !== false ) {
1256 * Checks if scripts located in the given directory can be executed via the given URL.
1258 * Used only by environment checks.
1259 * @param $dir string
1260 * @param $url string
1261 * @return bool|int|string
1263 public function dirIsExecutable( $dir, $url ) {
1264 $scriptTypes = array(
1266 "<?php echo 'ex' . 'ec';",
1267 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1271 // it would be good to check other popular languages here, but it'll be slow.
1273 wfSuppressWarnings();
1275 foreach ( $scriptTypes as $ext => $contents ) {
1276 foreach ( $contents as $source ) {
1277 $file = 'exectest.' . $ext;
1279 if ( !file_put_contents( $dir . $file, $source ) ) {
1284 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1286 catch( MWException
$e ) {
1287 // Http::get throws with allow_url_fopen = false and no curl extension.
1290 unlink( $dir . $file );
1292 if ( $text == 'exec' ) {
1293 wfRestoreWarnings();
1299 wfRestoreWarnings();
1305 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1307 * @param string $moduleName Name of module to check.
1310 public static function apacheModulePresent( $moduleName ) {
1311 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1314 // try it the hard way
1316 phpinfo( INFO_MODULES
);
1317 $info = ob_get_clean();
1318 return strpos( $info, $moduleName ) !== false;
1322 * ParserOptions are constructed before we determined the language, so fix it
1324 * @param $lang Language
1326 public function setParserLanguage( $lang ) {
1327 $this->parserOptions
->setTargetLanguage( $lang );
1328 $this->parserOptions
->setUserLang( $lang );
1332 * Overridden by WebInstaller to provide lastPage parameters.
1333 * @param $page string
1336 protected function getDocUrl( $page ) {
1337 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1341 * Finds extensions that follow the format /extensions/Name/Name.php,
1342 * and returns an array containing the value for 'Name' for each found extension.
1346 public function findExtensions() {
1347 if( $this->getVar( 'IP' ) === null ) {
1351 $extDir = $this->getVar( 'IP' ) . '/extensions';
1352 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1356 $dh = opendir( $extDir );
1358 while ( ( $file = readdir( $dh ) ) !== false ) {
1359 if( !is_dir( "$extDir/$file" ) ) {
1362 if( file_exists( "$extDir/$file/$file.php" ) ) {
1367 natcasesort( $exts );
1373 * Installs the auto-detected extensions.
1377 protected function includeExtensions() {
1379 $exts = $this->getVar( '_Extensions' );
1380 $IP = $this->getVar( 'IP' );
1383 * We need to include DefaultSettings before including extensions to avoid
1384 * warnings about unset variables. However, the only thing we really
1385 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1386 * if the extension has hidden hook registration in $wgExtensionFunctions,
1387 * but we're not opening that can of worms
1388 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1390 global $wgAutoloadClasses;
1391 $wgAutoloadClasses = array();
1393 require( "$IP/includes/DefaultSettings.php" );
1395 foreach( $exts as $e ) {
1396 require_once( "$IP/extensions/$e/$e.php" );
1399 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1400 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1402 // Unset everyone else's hooks. Lord knows what someone might be doing
1403 // in ParserFirstCallInit (see bug 27171)
1404 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1406 return Status
::newGood();
1410 * Get an array of install steps. Should always be in the format of
1412 * 'name' => 'someuniquename',
1413 * 'callback' => array( $obj, 'method' ),
1415 * There must be a config-install-$name message defined per step, which will
1416 * be shown on install.
1418 * @param $installer DatabaseInstaller so we can make callbacks
1421 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1422 $coreInstallSteps = array(
1423 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1424 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1425 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1426 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1427 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1428 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1429 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1432 // Build the array of install steps starting from the core install list,
1433 // then adding any callbacks that wanted to attach after a given step
1434 foreach( $coreInstallSteps as $step ) {
1435 $this->installSteps
[] = $step;
1436 if( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1437 $this->installSteps
= array_merge(
1438 $this->installSteps
,
1439 $this->extraInstallSteps
[$step['name']]
1444 // Prepend any steps that want to be at the beginning
1445 if( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1446 $this->installSteps
= array_merge(
1447 $this->extraInstallSteps
['BEGINNING'],
1452 // Extensions should always go first, chance to tie into hooks and such
1453 if( count( $this->getVar( '_Extensions' ) ) ) {
1454 array_unshift( $this->installSteps
,
1455 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1457 $this->installSteps
[] = array(
1458 'name' => 'extension-tables',
1459 'callback' => array( $installer, 'createExtensionTables' )
1462 return $this->installSteps
;
1466 * Actually perform the installation.
1468 * @param array $startCB A callback array for the beginning of each step
1469 * @param array $endCB A callback array for the end of each step
1471 * @return Array of Status objects
1473 public function performInstallation( $startCB, $endCB ) {
1474 $installResults = array();
1475 $installer = $this->getDBInstaller();
1476 $installer->preInstall();
1477 $steps = $this->getInstallSteps( $installer );
1478 foreach( $steps as $stepObj ) {
1479 $name = $stepObj['name'];
1480 call_user_func_array( $startCB, array( $name ) );
1482 // Perform the callback step
1483 $status = call_user_func( $stepObj['callback'], $installer );
1485 // Output and save the results
1486 call_user_func( $endCB, $name, $status );
1487 $installResults[$name] = $status;
1489 // If we've hit some sort of fatal, we need to bail.
1490 // Callback already had a chance to do output above.
1491 if( !$status->isOk() ) {
1495 if( $status->isOk() ) {
1496 $this->setVar( '_InstallDone', true );
1498 return $installResults;
1502 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1506 public function generateKeys() {
1507 $keys = array( 'wgSecretKey' => 64 );
1508 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1509 $keys['wgUpgradeKey'] = 16;
1511 return $this->doGenerateKeys( $keys );
1515 * Generate a secret value for variables using our CryptRand generator.
1516 * Produce a warning if the random source was insecure.
1518 * @param $keys Array
1521 protected function doGenerateKeys( $keys ) {
1522 $status = Status
::newGood();
1525 foreach ( $keys as $name => $length ) {
1526 $secretKey = MWCryptRand
::generateHex( $length, true );
1527 if ( !MWCryptRand
::wasStrong() ) {
1531 $this->setVar( $name, $secretKey );
1535 $names = array_keys( $keys );
1536 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1538 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1545 * Create the first user account, grant it sysop and bureaucrat rights
1549 protected function createSysop() {
1550 $name = $this->getVar( '_AdminName' );
1551 $user = User
::newFromName( $name );
1554 // We should've validated this earlier anyway!
1555 return Status
::newFatal( 'config-admin-error-user', $name );
1558 if ( $user->idForName() == 0 ) {
1559 $user->addToDatabase();
1562 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1563 } catch( PasswordError
$pwe ) {
1564 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1567 $user->addGroup( 'sysop' );
1568 $user->addGroup( 'bureaucrat' );
1569 if( $this->getVar( '_AdminEmail' ) ) {
1570 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1572 $user->saveSettings();
1574 // Update user count
1575 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1576 $ssUpdate->doUpdate();
1578 $status = Status
::newGood();
1580 if( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1581 $this->subscribeToMediaWikiAnnounce( $status );
1590 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1592 'email' => $this->getVar( '_AdminEmail' ),
1597 // Mailman doesn't support as many languages as we do, so check to make
1598 // sure their selected language is available
1599 $myLang = $this->getVar( '_UserLang' );
1600 if( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1601 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1602 $params['language'] = $myLang;
1605 if( MWHttpRequest
::canMakeRequests() ) {
1606 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1607 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1608 if( !$res->isOK() ) {
1609 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1612 $s->warning( 'config-install-subscribe-notpossible' );
1617 * Insert Main Page with default content.
1619 * @param $installer DatabaseInstaller
1622 protected function createMainpage( DatabaseInstaller
$installer ) {
1623 $status = Status
::newGood();
1625 $page = WikiPage
::factory( Title
::newMainPage() );
1626 $content = new WikitextContent(
1627 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1628 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1631 $page->doEditContent( $content,
1635 User
::newFromName( 'MediaWiki default' ) );
1636 } catch ( MWException
$e ) {
1637 //using raw, because $wgShowExceptionDetails can not be set yet
1638 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1645 * Override the necessary bits of the config to run an installation.
1647 public static function overrideConfig() {
1648 define( 'MW_NO_SESSION', 1 );
1650 // Don't access the database
1651 $GLOBALS['wgUseDatabaseMessages'] = false;
1652 // Don't cache langconv tables
1653 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1655 $GLOBALS['wgShowExceptionDetails'] = true;
1656 // Don't break forms
1657 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1659 // Extended debugging
1660 $GLOBALS['wgShowSQLErrors'] = true;
1661 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1663 // Allow multiple ob_flush() calls
1664 $GLOBALS['wgDisableOutputCompression'] = true;
1666 // Use a sensible cookie prefix (not my_wiki)
1667 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1669 // Some of the environment checks make shell requests, remove limits
1670 $GLOBALS['wgMaxShellMemory'] = 0;
1674 * Add an installation step following the given step.
1676 * @param array $callback A valid installation callback array, in this form:
1677 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1678 * @param string $findStep the step to find. Omit to put the step at the beginning
1680 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1681 $this->extraInstallSteps
[$findStep][] = $callback;
1685 * Disable the time limit for execution.
1686 * Some long-running pages (Install, Upgrade) will want to do this
1688 protected function disableTimeLimit() {
1689 wfSuppressWarnings();
1690 set_time_limit( 0 );
1691 wfRestoreWarnings();