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';
51 * List of detected DBs, access using getCompiledDBs().
55 protected $compiledDBs;
58 * Cached DB installer instances, access using getDBInstaller().
62 protected $dbInstallers = array();
65 * Minimum memory size in MB.
69 protected $minMemorySize = 50;
72 * Cached Title, used by parse().
76 protected $parserTitle;
79 * Cached ParserOptions, used by parse().
83 protected $parserOptions;
86 * Known database types. These correspond to the class names <type>Installer,
87 * and are also MediaWiki database types valid for $wgDBtype.
89 * To add a new type, create a <type>Installer class and a Database<type>
90 * class, and add a config-type-<type> message to MessagesEn.php.
94 protected static $dbTypes = array(
102 * A list of environment check methods called by doEnvironmentChecks().
103 * These may output warnings using showMessage(), and/or abort the
104 * installation process by returning false.
108 protected $envChecks = array(
110 'envCheckRegisterGlobals',
113 'envCheckMagicQuotes',
114 'envCheckMagicSybase',
122 'envCheckModSecurity',
129 'envCheckShellLocale',
130 'envCheckUploadsDirectory',
132 'envCheckSuhosinMaxValueLength',
137 * MediaWiki configuration globals that will eventually be passed through
138 * to LocalSettings.php. The names only are given here, the defaults
139 * typically come from DefaultSettings.php.
143 protected $defaultVarNames = array(
155 'wgEmailAuthentication',
158 'wgImageMagickConvertCommand',
165 'wgDeletedDirectory',
170 'wgUseInstantCommons',
173 'wgResourceLoaderMaxQueryLength',
177 * Variables that are stored alongside globals, and are used for any
178 * configuration of the installation process aside from the MediaWiki
179 * configuration. Map of names to defaults.
183 protected $internalDefaults = array(
185 '_Environment' => false,
186 '_SafeMode' => false,
187 '_RaiseMemory' => false,
188 '_UpgradeDone' => false,
189 '_InstallDone' => false,
190 '_Caches' => array(),
191 '_InstallPassword' => '',
192 '_SameAccount' => true,
193 '_CreateDBAccount' => false,
194 '_NamespaceType' => 'site-name',
195 '_AdminName' => '', // will be set later, when the user selects language
196 '_AdminPassword' => '',
197 '_AdminPassword2' => '',
199 '_Subscribe' => false,
200 '_SkipOptional' => 'continue',
201 '_RightsProfile' => 'wiki',
202 '_LicenseCode' => 'none',
204 '_Extensions' => array(),
205 '_MemCachedServers' => '',
206 '_UpgradeKeySupplied' => false,
207 '_ExistingDBSettings' => false,
211 * The actual list of installation steps. This will be initialized by getInstallSteps()
215 private $installSteps = array();
218 * Extra steps for installation, for things like DatabaseInstallers to modify
222 protected $extraInstallSteps = array();
225 * Known object cache types and the functions used to test for their existence.
229 protected $objectCaches = array(
230 'xcache' => 'xcache_get',
231 'apc' => 'apc_fetch',
232 'wincache' => 'wincache_ucache_get'
236 * User rights profiles.
240 public $rightsProfiles = array(
243 '*' => array( 'edit' => false )
247 'createaccount' => false,
253 'createaccount' => false,
265 public $licenses = array(
267 'url' => 'http://creativecommons.org/licenses/by/3.0/',
268 'icon' => '{$wgStylePath}/common/images/cc-by.png',
271 'url' => 'http://creativecommons.org/licenses/by-sa/3.0/',
272 'icon' => '{$wgStylePath}/common/images/cc-by-sa.png',
274 'cc-by-nc-sa' => array(
275 'url' => 'http://creativecommons.org/licenses/by-nc-sa/3.0/',
276 'icon' => '{$wgStylePath}/common/images/cc-by-nc-sa.png',
279 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
280 'icon' => '{$wgStylePath}/common/images/cc-0.png',
284 'icon' => '{$wgStylePath}/common/images/public-domain.png',
287 'url' => 'http://www.gnu.org/copyleft/fdl.html',
288 'icon' => '{$wgStylePath}/common/images/gnu-fdl.png',
295 'cc-choose' => array(
296 // Details will be filled in by the selector.
304 * URL to mediawiki-announce subscription
306 protected $mediaWikiAnnounceUrl = 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
309 * Supported language codes for Mailman
311 protected $mediaWikiAnnounceLanguages = array(
312 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
313 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
314 'sl', 'sr', 'sv', 'tr', 'uk'
318 * UI interface for displaying a short message
319 * The parameters are like parameters to wfMessage().
320 * The messages will be in wikitext format, which will be converted to an
321 * output format such as HTML or text before being sent to the user.
324 abstract public function showMessage( $msg /*, ... */ );
327 * Same as showMessage(), but for displaying errors
330 abstract public function showError( $msg /*, ... */ );
333 * Show a message to the installing user by using a Status object
334 * @param $status Status
336 abstract public function showStatusMessage( Status
$status );
339 * Constructor, always call this from child classes.
341 public function __construct() {
342 global $wgExtensionMessagesFiles, $wgUser;
344 // Disable the i18n cache and LoadBalancer
345 Language
::getLocalisationCache()->disableBackend();
346 LBFactory
::disableBackend();
348 // Load the installer's i18n file.
349 $wgExtensionMessagesFiles['MediawikiInstaller'] =
350 __DIR__
. '/Installer.i18n.php';
352 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
353 $wgUser = User
::newFromId( 0 );
355 $this->settings
= $this->internalDefaults
;
357 foreach ( $this->defaultVarNames
as $var ) {
358 $this->settings
[$var] = $GLOBALS[$var];
361 $compiledDBs = array();
362 foreach ( self
::getDBTypes() as $type ) {
363 $installer = $this->getDBInstaller( $type );
365 if ( !$installer->isCompiled() ) {
368 $compiledDBs[] = $type;
370 $defaults = $installer->getGlobalDefaults();
372 foreach ( $installer->getGlobalNames() as $var ) {
373 if ( isset( $defaults[$var] ) ) {
374 $this->settings
[$var] = $defaults[$var];
376 $this->settings
[$var] = $GLOBALS[$var];
380 $this->compiledDBs
= $compiledDBs;
382 $this->parserTitle
= Title
::newFromText( 'Installer' );
383 $this->parserOptions
= new ParserOptions
; // language will be wrong :(
384 $this->parserOptions
->setEditSection( false );
388 * Get a list of known DB types.
392 public static function getDBTypes() {
393 return self
::$dbTypes;
397 * Do initial checks of the PHP environment. Set variables according to
398 * the observed environment.
400 * It's possible that this may be called under the CLI SAPI, not the SAPI
401 * that the wiki will primarily run under. In that case, the subclass should
402 * initialise variables such as wgScriptPath, before calling this function.
404 * Under the web subclass, it can already be assumed that PHP 5+ is in use
405 * and that sessions are working.
409 public function doEnvironmentChecks() {
410 $phpVersion = phpversion();
411 if ( version_compare( $phpVersion, self
::MINIMUM_PHP_VERSION
, '>=' ) ) {
412 $this->showMessage( 'config-env-php', $phpVersion );
415 $this->showMessage( 'config-env-php-toolow', $phpVersion, self
::MINIMUM_PHP_VERSION
);
420 foreach ( $this->envChecks
as $check ) {
421 $status = $this->$check();
422 if ( $status === false ) {
428 $this->setVar( '_Environment', $good );
430 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
434 * Set a MW configuration variable, or internal installer configuration variable.
436 * @param $name String
437 * @param $value Mixed
439 public function setVar( $name, $value ) {
440 $this->settings
[$name] = $value;
444 * Get an MW configuration variable, or internal installer configuration variable.
445 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
446 * Installer variables are typically prefixed by an underscore.
448 * @param $name String
449 * @param $default Mixed
453 public function getVar( $name, $default = null ) {
454 if ( !isset( $this->settings
[$name] ) ) {
457 return $this->settings
[$name];
462 * Get a list of DBs supported by current PHP setup
466 public function getCompiledDBs() {
467 return $this->compiledDBs
;
471 * Get an instance of DatabaseInstaller for the specified DB type.
473 * @param $type Mixed: DB installer for which is needed, false to use default.
475 * @return DatabaseInstaller
477 public function getDBInstaller( $type = false ) {
479 $type = $this->getVar( 'wgDBtype' );
482 $type = strtolower( $type );
484 if ( !isset( $this->dbInstallers
[$type] ) ) {
485 $class = ucfirst( $type ) . 'Installer';
486 $this->dbInstallers
[$type] = new $class( $this );
489 return $this->dbInstallers
[$type];
493 * Determine if LocalSettings.php exists. If it does, return its variables,
494 * merged with those from AdminSettings.php, as an array.
498 public static function getExistingLocalSettings() {
501 wfSuppressWarnings();
502 $_lsExists = file_exists( "$IP/LocalSettings.php" );
510 require "$IP/includes/DefaultSettings.php";
511 require "$IP/LocalSettings.php";
512 if ( file_exists( "$IP/AdminSettings.php" ) ) {
513 require "$IP/AdminSettings.php";
515 return get_defined_vars();
519 * Get a fake password for sending back to the user in HTML.
520 * This is a security mechanism to avoid compromise of the password in the
521 * event of session ID compromise.
523 * @param $realPassword String
527 public function getFakePassword( $realPassword ) {
528 return str_repeat( '*', strlen( $realPassword ) );
532 * Set a variable which stores a password, except if the new value is a
533 * fake password in which case leave it as it is.
535 * @param $name String
536 * @param $value Mixed
538 public function setPassword( $name, $value ) {
539 if ( !preg_match( '/^\*+$/', $value ) ) {
540 $this->setVar( $name, $value );
545 * On POSIX systems return the primary group of the webserver we're running under.
546 * On other systems just returns null.
548 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
549 * webserver user before he can install.
551 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
555 public static function maybeGetWebserverPrimaryGroup() {
556 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
557 # I don't know this, this isn't UNIX.
561 # posix_getegid() *not* getmygid() because we want the group of the webserver,
562 # not whoever owns the current script.
563 $gid = posix_getegid();
564 $getpwuid = posix_getpwuid( $gid );
565 $group = $getpwuid['name'];
571 * Convert wikitext $text to HTML.
573 * This is potentially error prone since many parser features require a complete
574 * installed MW database. The solution is to just not use those features when you
575 * write your messages. This appears to work well enough. Basic formatting and
576 * external links work just fine.
578 * But in case a translator decides to throw in a "#ifexist" or internal link or
579 * whatever, this function is guarded to catch the attempted DB access and to present
580 * some fallback text.
582 * @param $text String
583 * @param $lineStart Boolean
586 public function parse( $text, $lineStart = false ) {
590 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
591 $html = $out->getText();
592 } catch ( DBAccessError
$e ) {
593 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
595 if ( !empty( $this->debug
) ) {
596 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
604 * @return ParserOptions
606 public function getParserOptions() {
607 return $this->parserOptions
;
610 public function disableLinkPopups() {
611 $this->parserOptions
->setExternalLinkTarget( false );
614 public function restoreLinkPopups() {
615 global $wgExternalLinkTarget;
616 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
620 * Install step which adds a row to the site_stats table with appropriate
623 * @param $installer DatabaseInstaller
627 public function populateSiteStats( DatabaseInstaller
$installer ) {
628 $status = $installer->getConnection();
629 if ( !$status->isOK() ) {
632 $status->value
->insert( 'site_stats', array(
634 'ss_total_views' => 0,
635 'ss_total_edits' => 0,
636 'ss_good_articles' => 0,
637 'ss_total_pages' => 0,
640 __METHOD__
, 'IGNORE' );
641 return Status
::newGood();
645 * Exports all wg* variables stored by the installer into global scope.
647 public function exportVars() {
648 foreach ( $this->settings
as $name => $value ) {
649 if ( substr( $name, 0, 2 ) == 'wg' ) {
650 $GLOBALS[$name] = $value;
656 * Environment check for DB types.
659 protected function envCheckDB() {
664 // Give grep a chance to find the usages:
665 // config-type-mysql, config-type-postgres, config-type-oracle, config-type-sqlite
666 foreach ( self
::getDBTypes() as $name ) {
667 $allNames[] = wfMessage( "config-type-$name" )->text();
670 $databases = $this->getCompiledDBs();
672 $databases = array_flip ( $databases );
673 foreach ( array_keys( $databases ) as $db ) {
674 $installer = $this->getDBInstaller( $db );
675 $status = $installer->checkPrerequisites();
676 if ( !$status->isGood() ) {
677 $this->showStatusMessage( $status );
679 if ( !$status->isOK() ) {
680 unset( $databases[$db] );
683 $databases = array_flip( $databases );
685 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
686 // @todo FIXME: This only works for the web installer!
693 * Environment check for register_globals.
695 protected function envCheckRegisterGlobals() {
696 if ( wfIniGetBool( 'register_globals' ) ) {
697 $this->showMessage( 'config-register-globals' );
702 * Some versions of libxml+PHP break < and > encoding horribly
705 protected function envCheckBrokenXML() {
706 $test = new PhpXmlBugTester();
708 $this->showError( 'config-brokenlibxml' );
715 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
716 * reference parameters to __call() are not converted to null
719 protected function envCheckPHP531() {
720 $test = new PhpRefCallBugTester
;
723 $this->showError( 'config-using531', phpversion() );
730 * Environment check for magic_quotes_runtime.
733 protected function envCheckMagicQuotes() {
734 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
735 $this->showError( 'config-magic-quotes-runtime' );
742 * Environment check for magic_quotes_sybase.
745 protected function envCheckMagicSybase() {
746 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
747 $this->showError( 'config-magic-quotes-sybase' );
754 * Environment check for mbstring.func_overload.
757 protected function envCheckMbstring() {
758 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
759 $this->showError( 'config-mbstring' );
766 * Environment check for zend.ze1_compatibility_mode.
769 protected function envCheckZE1() {
770 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
771 $this->showError( 'config-ze1' );
778 * Environment check for safe_mode.
781 protected function envCheckSafeMode() {
782 if ( wfIniGetBool( 'safe_mode' ) ) {
783 $this->setVar( '_SafeMode', true );
784 $this->showMessage( 'config-safe-mode' );
790 * Environment check for the XML module.
793 protected function envCheckXML() {
794 if ( !function_exists( "utf8_encode" ) ) {
795 $this->showError( 'config-xml-bad' );
802 * Environment check for the PCRE module.
804 * @note If this check were to fail, the parser would
805 * probably throw an exception before the result
806 * of this check is shown to the user.
809 protected function envCheckPCRE() {
810 if ( !function_exists( 'preg_match' ) ) {
811 $this->showError( 'config-pcre' );
814 wfSuppressWarnings();
815 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
816 // Need to check for \p support too, as PCRE can be compiled
817 // with utf8 support, but not unicode property support.
818 // check that \p{Zs} (space separators) matches
819 // U+3000 (Ideographic space)
820 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
822 if ( $regexd != '--' ||
$regexprop != '--' ) {
823 $this->showError( 'config-pcre-no-utf8' );
830 * Environment check for available memory.
833 protected function envCheckMemory() {
834 $limit = ini_get( 'memory_limit' );
836 if ( !$limit ||
$limit == -1 ) {
840 $n = wfShorthandToInteger( $limit );
842 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
843 $newLimit = "{$this->minMemorySize}M";
845 if ( ini_set( "memory_limit", $newLimit ) === false ) {
846 $this->showMessage( 'config-memory-bad', $limit );
848 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
849 $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' );
888 * Search for GNU diff3.
891 protected function envCheckDiff3() {
892 $names = array( "gdiff3", "diff3", "diff3.exe" );
893 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
895 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
898 $this->setVar( 'wgDiff3', $diff3 );
900 $this->setVar( 'wgDiff3', false );
901 $this->showMessage( 'config-diff3-bad' );
907 * Environment check for ImageMagick and GD.
910 protected function envCheckGraphics() {
911 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
912 $versionInfo = array( '$1 -version', 'ImageMagick' );
913 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
915 $this->setVar( 'wgImageMagickConvertCommand', '' );
917 $this->setVar( 'wgImageMagickConvertCommand', $convert );
918 $this->showMessage( 'config-imagemagick', $convert );
920 } elseif ( function_exists( 'imagejpeg' ) ) {
921 $this->showMessage( 'config-gd' );
924 $this->showMessage( 'config-no-scaling' );
935 protected function envCheckGit() {
936 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
937 $versionInfo = array( '$1 --version', 'git version' );
939 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
942 $this->setVar( 'wgGitBin', $git );
943 $this->showMessage( 'config-git', $git );
945 $this->setVar( 'wgGitBin', false );
946 $this->showMessage( 'config-git-bad' );
952 * Environment check for the server hostname.
954 protected function envCheckServer() {
955 $server = $this->envGetDefaultServer();
956 $this->showMessage( 'config-using-server', $server );
957 $this->setVar( 'wgServer', $server );
962 * Helper function to be called from envCheckServer()
965 abstract protected function envGetDefaultServer();
968 * Environment check for setting $IP and $wgScriptPath.
971 protected function envCheckPath() {
973 $IP = dirname( dirname( __DIR__
) );
974 $this->setVar( 'IP', $IP );
976 $this->showMessage( 'config-using-uri', $this->getVar( 'wgServer' ), $this->getVar( 'wgScriptPath' ) );
981 * Environment check for setting the preferred PHP file extension.
984 protected function envCheckExtension() {
985 // @todo FIXME: Detect this properly
986 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
991 $this->setVar( 'wgScriptExtension', ".$ext" );
996 * Environment check for preferred locale in shell
999 protected function envCheckShellLocale() {
1000 $os = php_uname( 's' );
1001 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1003 if ( !in_array( $os, $supported ) ) {
1007 # Get a list of available locales.
1009 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1015 $lines = array_map( 'trim', explode( "\n", $lines ) );
1016 $candidatesByLocale = array();
1017 $candidatesByLang = array();
1019 foreach ( $lines as $line ) {
1020 if ( $line === '' ) {
1024 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1028 list( , $lang, , , ) = $m;
1030 $candidatesByLocale[$m[0]] = $m;
1031 $candidatesByLang[$lang][] = $m;
1034 # Try the current value of LANG.
1035 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1036 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1040 # Try the most common ones.
1041 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1042 foreach ( $commonLocales as $commonLocale ) {
1043 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1044 $this->setVar( 'wgShellLocale', $commonLocale );
1049 # Is there an available locale in the Wiki's language?
1050 $wikiLang = $this->getVar( 'wgLanguageCode' );
1052 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1053 $m = reset( $candidatesByLang[$wikiLang] );
1054 $this->setVar( 'wgShellLocale', $m[0] );
1058 # Are there any at all?
1059 if ( count( $candidatesByLocale ) ) {
1060 $m = reset( $candidatesByLocale );
1061 $this->setVar( 'wgShellLocale', $m[0] );
1070 * Environment check for the permissions of the uploads directory
1073 protected function envCheckUploadsDirectory() {
1076 $dir = $IP . '/images/';
1077 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1078 $safe = !$this->dirIsExecutable( $dir, $url );
1081 $this->showMessage( 'config-uploads-not-safe', $dir );
1087 * Checks if suhosin.get.max_value_length is set, and if so generate
1088 * a warning because it decreases ResourceLoader performance.
1091 protected function envCheckSuhosinMaxValueLength() {
1092 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1093 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1094 // Only warn if the value is below the sane 1024
1095 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1101 * Convert a hex string representing a Unicode code point to that code point.
1105 protected function unicodeChar( $c ) {
1109 } elseif ( $c <= 0x7FF ) {
1110 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1111 } elseif ( $c <= 0xFFFF ) {
1112 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1113 . chr( 0x80 |
$c & 0x3F );
1114 } elseif ( $c <= 0x10FFFF ) {
1115 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1116 . chr( 0x80 |
$c >> 6 & 0x3F )
1117 . chr( 0x80 |
$c & 0x3F );
1124 * Check the libicu version
1126 protected function envCheckLibicu() {
1127 $utf8 = function_exists( 'utf8_normalize' );
1128 $intl = function_exists( 'normalizer_normalize' );
1131 * This needs to be updated something that the latest libicu
1132 * will properly normalize. This normalization was found at
1133 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1134 * Note that we use the hex representation to create the code
1135 * points in order to avoid any Unicode-destroying during transit.
1137 $not_normal_c = $this->unicodeChar( "FA6C" );
1138 $normal_c = $this->unicodeChar( "242EE" );
1140 $useNormalizer = 'php';
1141 $needsUpdate = false;
1144 * We're going to prefer the pecl extension here unless
1145 * utf8_normalize is more up to date.
1148 $useNormalizer = 'utf8';
1149 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1150 if ( $utf8 !== $normal_c ) {
1151 $needsUpdate = true;
1155 $useNormalizer = 'intl';
1156 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1157 if ( $intl !== $normal_c ) {
1158 $needsUpdate = true;
1162 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
1163 if ( $useNormalizer === 'php' ) {
1164 $this->showMessage( 'config-unicode-pure-php-warning' );
1166 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1167 if ( $needsUpdate ) {
1168 $this->showMessage( 'config-unicode-update-warning' );
1176 protected function envCheckCtype() {
1177 if ( !function_exists( 'ctype_digit' ) ) {
1178 $this->showError( 'config-ctype' );
1185 * Get an array of likely places we can find executables. Check a bunch
1186 * of known Unix-like defaults, as well as the PATH environment variable
1187 * (which should maybe make it work for Windows?)
1191 protected static function getPossibleBinPaths() {
1193 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1194 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1195 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1200 * Search a path for any of the given executable names. Returns the
1201 * executable name if found. Also checks the version string returned
1202 * by each executable.
1204 * Used only by environment checks.
1206 * @param string $path path to search
1207 * @param array $names of executable names
1208 * @param $versionInfo Boolean false or array with two members:
1209 * 0 => Command to run for version check, with $1 for the full executable name
1210 * 1 => String to compare the output with
1212 * If $versionInfo is not false, only executables with a version
1213 * matching $versionInfo[1] will be returned.
1214 * @return bool|string
1216 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1217 if ( !is_array( $names ) ) {
1218 $names = array( $names );
1221 foreach ( $names as $name ) {
1222 $command = $path . DIRECTORY_SEPARATOR
. $name;
1224 wfSuppressWarnings();
1225 $file_exists = file_exists( $command );
1226 wfRestoreWarnings();
1228 if ( $file_exists ) {
1229 if ( !$versionInfo ) {
1233 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1234 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1243 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1244 * @see locateExecutable()
1246 * @param $versionInfo bool
1247 * @return bool|string
1249 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1250 foreach ( self
::getPossibleBinPaths() as $path ) {
1251 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1252 if ( $exe !== false ) {
1260 * Checks if scripts located in the given directory can be executed via the given URL.
1262 * Used only by environment checks.
1263 * @param $dir string
1264 * @param $url string
1265 * @return bool|int|string
1267 public function dirIsExecutable( $dir, $url ) {
1268 $scriptTypes = array(
1270 "<?php echo 'ex' . 'ec';",
1271 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1275 // it would be good to check other popular languages here, but it'll be slow.
1277 wfSuppressWarnings();
1279 foreach ( $scriptTypes as $ext => $contents ) {
1280 foreach ( $contents as $source ) {
1281 $file = 'exectest.' . $ext;
1283 if ( !file_put_contents( $dir . $file, $source ) ) {
1288 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1290 catch ( MWException
$e ) {
1291 // Http::get throws with allow_url_fopen = false and no curl extension.
1294 unlink( $dir . $file );
1296 if ( $text == 'exec' ) {
1297 wfRestoreWarnings();
1303 wfRestoreWarnings();
1309 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1311 * @param string $moduleName Name of module to check.
1314 public static function apacheModulePresent( $moduleName ) {
1315 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1318 // try it the hard way
1320 phpinfo( INFO_MODULES
);
1321 $info = ob_get_clean();
1322 return strpos( $info, $moduleName ) !== false;
1326 * ParserOptions are constructed before we determined the language, so fix it
1328 * @param $lang Language
1330 public function setParserLanguage( $lang ) {
1331 $this->parserOptions
->setTargetLanguage( $lang );
1332 $this->parserOptions
->setUserLang( $lang );
1336 * Overridden by WebInstaller to provide lastPage parameters.
1337 * @param $page string
1340 protected function getDocUrl( $page ) {
1341 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1345 * Finds extensions that follow the format /extensions/Name/Name.php,
1346 * and returns an array containing the value for 'Name' for each found extension.
1350 public function findExtensions() {
1351 if ( $this->getVar( 'IP' ) === null ) {
1355 $extDir = $this->getVar( 'IP' ) . '/extensions';
1356 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1360 $dh = opendir( $extDir );
1362 while ( ( $file = readdir( $dh ) ) !== false ) {
1363 if ( !is_dir( "$extDir/$file" ) ) {
1366 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1371 natcasesort( $exts );
1377 * Installs the auto-detected extensions.
1381 protected function includeExtensions() {
1383 $exts = $this->getVar( '_Extensions' );
1384 $IP = $this->getVar( 'IP' );
1387 * We need to include DefaultSettings before including extensions to avoid
1388 * warnings about unset variables. However, the only thing we really
1389 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1390 * if the extension has hidden hook registration in $wgExtensionFunctions,
1391 * but we're not opening that can of worms
1392 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1394 global $wgAutoloadClasses;
1395 $wgAutoloadClasses = array();
1397 require "$IP/includes/DefaultSettings.php";
1399 foreach ( $exts as $e ) {
1400 require_once "$IP/extensions/$e/$e.php";
1403 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1404 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1406 // Unset everyone else's hooks. Lord knows what someone might be doing
1407 // in ParserFirstCallInit (see bug 27171)
1408 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1410 return Status
::newGood();
1414 * Get an array of install steps. Should always be in the format of
1416 * 'name' => 'someuniquename',
1417 * 'callback' => array( $obj, 'method' ),
1419 * There must be a config-install-$name message defined per step, which will
1420 * be shown on install.
1422 * @param $installer DatabaseInstaller so we can make callbacks
1425 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1426 $coreInstallSteps = array(
1427 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1428 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1429 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1430 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1431 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1432 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1433 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1436 // Build the array of install steps starting from the core install list,
1437 // then adding any callbacks that wanted to attach after a given step
1438 foreach ( $coreInstallSteps as $step ) {
1439 $this->installSteps
[] = $step;
1440 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1441 $this->installSteps
= array_merge(
1442 $this->installSteps
,
1443 $this->extraInstallSteps
[$step['name']]
1448 // Prepend any steps that want to be at the beginning
1449 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1450 $this->installSteps
= array_merge(
1451 $this->extraInstallSteps
['BEGINNING'],
1456 // Extensions should always go first, chance to tie into hooks and such
1457 if ( count( $this->getVar( '_Extensions' ) ) ) {
1458 array_unshift( $this->installSteps
,
1459 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1461 $this->installSteps
[] = array(
1462 'name' => 'extension-tables',
1463 'callback' => array( $installer, 'createExtensionTables' )
1466 return $this->installSteps
;
1470 * Actually perform the installation.
1472 * @param array $startCB A callback array for the beginning of each step
1473 * @param array $endCB A callback array for the end of each step
1475 * @return Array of Status objects
1477 public function performInstallation( $startCB, $endCB ) {
1478 $installResults = array();
1479 $installer = $this->getDBInstaller();
1480 $installer->preInstall();
1481 $steps = $this->getInstallSteps( $installer );
1482 foreach ( $steps as $stepObj ) {
1483 $name = $stepObj['name'];
1484 call_user_func_array( $startCB, array( $name ) );
1486 // Perform the callback step
1487 $status = call_user_func( $stepObj['callback'], $installer );
1489 // Output and save the results
1490 call_user_func( $endCB, $name, $status );
1491 $installResults[$name] = $status;
1493 // If we've hit some sort of fatal, we need to bail.
1494 // Callback already had a chance to do output above.
1495 if ( !$status->isOk() ) {
1499 if ( $status->isOk() ) {
1500 $this->setVar( '_InstallDone', true );
1502 return $installResults;
1506 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1510 public function generateKeys() {
1511 $keys = array( 'wgSecretKey' => 64 );
1512 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1513 $keys['wgUpgradeKey'] = 16;
1515 return $this->doGenerateKeys( $keys );
1519 * Generate a secret value for variables using our CryptRand generator.
1520 * Produce a warning if the random source was insecure.
1522 * @param $keys Array
1525 protected function doGenerateKeys( $keys ) {
1526 $status = Status
::newGood();
1529 foreach ( $keys as $name => $length ) {
1530 $secretKey = MWCryptRand
::generateHex( $length, true );
1531 if ( !MWCryptRand
::wasStrong() ) {
1535 $this->setVar( $name, $secretKey );
1539 $names = array_keys( $keys );
1540 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1542 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1549 * Create the first user account, grant it sysop and bureaucrat rights
1553 protected function createSysop() {
1554 $name = $this->getVar( '_AdminName' );
1555 $user = User
::newFromName( $name );
1558 // We should've validated this earlier anyway!
1559 return Status
::newFatal( 'config-admin-error-user', $name );
1562 if ( $user->idForName() == 0 ) {
1563 $user->addToDatabase();
1566 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1567 } catch ( PasswordError
$pwe ) {
1568 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1571 $user->addGroup( 'sysop' );
1572 $user->addGroup( 'bureaucrat' );
1573 if ( $this->getVar( '_AdminEmail' ) ) {
1574 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1576 $user->saveSettings();
1578 // Update user count
1579 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1580 $ssUpdate->doUpdate();
1582 $status = Status
::newGood();
1584 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1585 $this->subscribeToMediaWikiAnnounce( $status );
1594 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1596 'email' => $this->getVar( '_AdminEmail' ),
1601 // Mailman doesn't support as many languages as we do, so check to make
1602 // sure their selected language is available
1603 $myLang = $this->getVar( '_UserLang' );
1604 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1605 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1606 $params['language'] = $myLang;
1609 if ( MWHttpRequest
::canMakeRequests() ) {
1610 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1611 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1612 if ( !$res->isOK() ) {
1613 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1616 $s->warning( 'config-install-subscribe-notpossible' );
1621 * Insert Main Page with default content.
1623 * @param $installer DatabaseInstaller
1626 protected function createMainpage( DatabaseInstaller
$installer ) {
1627 $status = Status
::newGood();
1629 $page = WikiPage
::factory( Title
::newMainPage() );
1630 $content = new WikitextContent(
1631 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1632 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1635 $page->doEditContent( $content,
1639 User
::newFromName( 'MediaWiki default' ) );
1640 } catch ( MWException
$e ) {
1641 //using raw, because $wgShowExceptionDetails can not be set yet
1642 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1649 * Override the necessary bits of the config to run an installation.
1651 public static function overrideConfig() {
1652 define( 'MW_NO_SESSION', 1 );
1654 // Don't access the database
1655 $GLOBALS['wgUseDatabaseMessages'] = false;
1656 // Don't cache langconv tables
1657 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1659 $GLOBALS['wgShowExceptionDetails'] = true;
1660 // Don't break forms
1661 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1663 // Extended debugging
1664 $GLOBALS['wgShowSQLErrors'] = true;
1665 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1667 // Allow multiple ob_flush() calls
1668 $GLOBALS['wgDisableOutputCompression'] = true;
1670 // Use a sensible cookie prefix (not my_wiki)
1671 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1673 // Some of the environment checks make shell requests, remove limits
1674 $GLOBALS['wgMaxShellMemory'] = 0;
1678 * Add an installation step following the given step.
1680 * @param array $callback A valid installation callback array, in this form:
1681 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1682 * @param string $findStep the step to find. Omit to put the step at the beginning
1684 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1685 $this->extraInstallSteps
[$findStep][] = $callback;
1689 * Disable the time limit for execution.
1690 * Some long-running pages (Install, Upgrade) will want to do this
1692 protected function disableTimeLimit() {
1693 wfSuppressWarnings();
1694 set_time_limit( 0 );
1695 wfRestoreWarnings();