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 * List of detected DBs, access using getCompiledDBs().
54 protected $compiledDBs;
57 * Cached DB installer instances, access using getDBInstaller().
61 protected $dbInstallers = array();
64 * Minimum memory size in MB.
68 protected $minMemorySize = 50;
71 * Cached Title, used by parse().
75 protected $parserTitle;
78 * Cached ParserOptions, used by parse().
82 protected $parserOptions;
85 * Known database types. These correspond to the class names <type>Installer,
86 * and are also MediaWiki database types valid for $wgDBtype.
88 * To add a new type, create a <type>Installer class and a Database<type>
89 * class, and add a config-type-<type> message to MessagesEn.php.
93 protected static $dbTypes = array(
101 * A list of environment check methods called by doEnvironmentChecks().
102 * These may output warnings using showMessage(), and/or abort the
103 * installation process by returning false.
107 protected $envChecks = array(
109 'envCheckRegisterGlobals',
112 'envCheckMagicQuotes',
113 'envCheckMagicSybase',
121 'envCheckModSecurity',
128 'envCheckShellLocale',
129 'envCheckUploadsDirectory',
131 '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";
516 return get_defined_vars();
520 * Get a fake password for sending back to the user in HTML.
521 * This is a security mechanism to avoid compromise of the password in the
522 * event of session ID compromise.
524 * @param $realPassword String
528 public function getFakePassword( $realPassword ) {
529 return str_repeat( '*', strlen( $realPassword ) );
533 * Set a variable which stores a password, except if the new value is a
534 * fake password in which case leave it as it is.
536 * @param $name String
537 * @param $value Mixed
539 public function setPassword( $name, $value ) {
540 if ( !preg_match( '/^\*+$/', $value ) ) {
541 $this->setVar( $name, $value );
546 * On POSIX systems return the primary group of the webserver we're running under.
547 * On other systems just returns null.
549 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
550 * webserver user before he can install.
552 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
556 public static function maybeGetWebserverPrimaryGroup() {
557 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
558 # I don't know this, this isn't UNIX.
562 # posix_getegid() *not* getmygid() because we want the group of the webserver,
563 # not whoever owns the current script.
564 $gid = posix_getegid();
565 $getpwuid = posix_getpwuid( $gid );
566 $group = $getpwuid['name'];
572 * Convert wikitext $text to HTML.
574 * This is potentially error prone since many parser features require a complete
575 * installed MW database. The solution is to just not use those features when you
576 * write your messages. This appears to work well enough. Basic formatting and
577 * external links work just fine.
579 * But in case a translator decides to throw in a "#ifexist" or internal link or
580 * whatever, this function is guarded to catch the attempted DB access and to present
581 * some fallback text.
583 * @param $text String
584 * @param $lineStart Boolean
587 public function parse( $text, $lineStart = false ) {
591 $out = $wgParser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
592 $html = $out->getText();
593 } catch ( DBAccessError
$e ) {
594 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
596 if ( !empty( $this->debug
) ) {
597 $html .= "<!--\n" . $e->getTraceAsString() . "\n-->";
605 * @return ParserOptions
607 public function getParserOptions() {
608 return $this->parserOptions
;
611 public function disableLinkPopups() {
612 $this->parserOptions
->setExternalLinkTarget( false );
615 public function restoreLinkPopups() {
616 global $wgExternalLinkTarget;
617 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
621 * Install step which adds a row to the site_stats table with appropriate
624 * @param $installer DatabaseInstaller
628 public function populateSiteStats( DatabaseInstaller
$installer ) {
629 $status = $installer->getConnection();
630 if ( !$status->isOK() ) {
633 $status->value
->insert( 'site_stats', array(
635 'ss_total_views' => 0,
636 'ss_total_edits' => 0,
637 'ss_good_articles' => 0,
638 'ss_total_pages' => 0,
641 __METHOD__
, 'IGNORE' );
643 return Status
::newGood();
647 * Exports all wg* variables stored by the installer into global scope.
649 public function exportVars() {
650 foreach ( $this->settings
as $name => $value ) {
651 if ( substr( $name, 0, 2 ) == 'wg' ) {
652 $GLOBALS[$name] = $value;
658 * Environment check for DB types.
661 protected function envCheckDB() {
666 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
667 // config-type-sqlite
668 foreach ( self
::getDBTypes() as $name ) {
669 $allNames[] = wfMessage( "config-type-$name" )->text();
672 $databases = $this->getCompiledDBs();
674 $databases = array_flip( $databases );
675 foreach ( array_keys( $databases ) as $db ) {
676 $installer = $this->getDBInstaller( $db );
677 $status = $installer->checkPrerequisites();
678 if ( !$status->isGood() ) {
679 $this->showStatusMessage( $status );
681 if ( !$status->isOK() ) {
682 unset( $databases[$db] );
685 $databases = array_flip( $databases );
687 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ) );
689 // @todo FIXME: This only works for the web installer!
697 * Environment check for register_globals.
699 protected function envCheckRegisterGlobals() {
700 if ( wfIniGetBool( 'register_globals' ) ) {
701 $this->showMessage( 'config-register-globals' );
706 * Some versions of libxml+PHP break < and > encoding horribly
709 protected function envCheckBrokenXML() {
710 $test = new PhpXmlBugTester();
712 $this->showError( 'config-brokenlibxml' );
721 * Test PHP (probably 5.3.1, but it could regress again) to make sure that
722 * reference parameters to __call() are not converted to null
725 protected function envCheckPHP531() {
726 $test = new PhpRefCallBugTester
;
729 $this->showError( 'config-using531', phpversion() );
738 * Environment check for magic_quotes_runtime.
741 protected function envCheckMagicQuotes() {
742 if ( wfIniGetBool( "magic_quotes_runtime" ) ) {
743 $this->showError( 'config-magic-quotes-runtime' );
752 * Environment check for magic_quotes_sybase.
755 protected function envCheckMagicSybase() {
756 if ( wfIniGetBool( 'magic_quotes_sybase' ) ) {
757 $this->showError( 'config-magic-quotes-sybase' );
766 * Environment check for mbstring.func_overload.
769 protected function envCheckMbstring() {
770 if ( wfIniGetBool( 'mbstring.func_overload' ) ) {
771 $this->showError( 'config-mbstring' );
780 * Environment check for zend.ze1_compatibility_mode.
783 protected function envCheckZE1() {
784 if ( wfIniGetBool( 'zend.ze1_compatibility_mode' ) ) {
785 $this->showError( 'config-ze1' );
794 * Environment check for safe_mode.
797 protected function envCheckSafeMode() {
798 if ( wfIniGetBool( 'safe_mode' ) ) {
799 $this->setVar( '_SafeMode', true );
800 $this->showMessage( 'config-safe-mode' );
807 * Environment check for the XML module.
810 protected function envCheckXML() {
811 if ( !function_exists( "utf8_encode" ) ) {
812 $this->showError( 'config-xml-bad' );
821 * Environment check for the PCRE module.
823 * @note If this check were to fail, the parser would
824 * probably throw an exception before the result
825 * of this check is shown to the user.
828 protected function envCheckPCRE() {
829 if ( !function_exists( 'preg_match' ) ) {
830 $this->showError( 'config-pcre' );
834 wfSuppressWarnings();
835 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
836 // Need to check for \p support too, as PCRE can be compiled
837 // with utf8 support, but not unicode property support.
838 // check that \p{Zs} (space separators) matches
839 // U+3000 (Ideographic space)
840 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\xE3\x80\x80-" );
842 if ( $regexd != '--' ||
$regexprop != '--' ) {
843 $this->showError( 'config-pcre-no-utf8' );
852 * Environment check for available memory.
855 protected function envCheckMemory() {
856 $limit = ini_get( 'memory_limit' );
858 if ( !$limit ||
$limit == -1 ) {
862 $n = wfShorthandToInteger( $limit );
864 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
865 $newLimit = "{$this->minMemorySize}M";
867 if ( ini_set( "memory_limit", $newLimit ) === false ) {
868 $this->showMessage( 'config-memory-bad', $limit );
870 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
871 $this->setVar( '_RaiseMemory', true );
879 * Environment check for compiled object cache types.
881 protected function envCheckCache() {
883 foreach ( $this->objectCaches
as $name => $function ) {
884 if ( function_exists( $function ) ) {
885 if ( $name == 'xcache' && !wfIniGetBool( 'xcache.var_size' ) ) {
888 $caches[$name] = true;
893 $this->showMessage( 'config-no-cache' );
896 $this->setVar( '_Caches', $caches );
900 * Scare user to death if they have mod_security
903 protected function envCheckModSecurity() {
904 if ( self
::apacheModulePresent( 'mod_security' ) ) {
905 $this->showMessage( 'config-mod-security' );
912 * Search for GNU diff3.
915 protected function envCheckDiff3() {
916 $names = array( "gdiff3", "diff3", "diff3.exe" );
917 $versionInfo = array( '$1 --version 2>&1', 'GNU diffutils' );
919 $diff3 = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
922 $this->setVar( 'wgDiff3', $diff3 );
924 $this->setVar( 'wgDiff3', false );
925 $this->showMessage( 'config-diff3-bad' );
932 * Environment check for ImageMagick and GD.
935 protected function envCheckGraphics() {
936 $names = array( wfIsWindows() ?
'convert.exe' : 'convert' );
937 $versionInfo = array( '$1 -version', 'ImageMagick' );
938 $convert = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
940 $this->setVar( 'wgImageMagickConvertCommand', '' );
942 $this->setVar( 'wgImageMagickConvertCommand', $convert );
943 $this->showMessage( 'config-imagemagick', $convert );
946 } elseif ( function_exists( 'imagejpeg' ) ) {
947 $this->showMessage( 'config-gd' );
949 $this->showMessage( 'config-no-scaling' );
961 protected function envCheckGit() {
962 $names = array( wfIsWindows() ?
'git.exe' : 'git' );
963 $versionInfo = array( '$1 --version', 'git version' );
965 $git = self
::locateExecutableInDefaultPaths( $names, $versionInfo );
968 $this->setVar( 'wgGitBin', $git );
969 $this->showMessage( 'config-git', $git );
971 $this->setVar( 'wgGitBin', false );
972 $this->showMessage( 'config-git-bad' );
979 * Environment check for the server hostname.
981 protected function envCheckServer() {
982 $server = $this->envGetDefaultServer();
983 $this->showMessage( 'config-using-server', $server );
984 $this->setVar( 'wgServer', $server );
990 * Helper function to be called from envCheckServer()
993 abstract protected function envGetDefaultServer();
996 * Environment check for setting $IP and $wgScriptPath.
999 protected function envCheckPath() {
1001 $IP = dirname( dirname( __DIR__
) );
1002 $this->setVar( 'IP', $IP );
1004 $this->showMessage( 'config-using-uri', $this->getVar( 'wgServer' ), $this->getVar( 'wgScriptPath' ) );
1010 * Environment check for setting the preferred PHP file extension.
1013 protected function envCheckExtension() {
1014 // @todo FIXME: Detect this properly
1015 if ( defined( 'MW_INSTALL_PHP5_EXT' ) ) {
1020 $this->setVar( 'wgScriptExtension', ".$ext" );
1026 * Environment check for preferred locale in shell
1029 protected function envCheckShellLocale() {
1030 $os = php_uname( 's' );
1031 $supported = array( 'Linux', 'SunOS', 'HP-UX', 'Darwin' ); # Tested these
1033 if ( !in_array( $os, $supported ) ) {
1037 # Get a list of available locales.
1039 $lines = wfShellExec( '/usr/bin/locale -a', $ret );
1045 $lines = array_map( 'trim', explode( "\n", $lines ) );
1046 $candidatesByLocale = array();
1047 $candidatesByLang = array();
1049 foreach ( $lines as $line ) {
1050 if ( $line === '' ) {
1054 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1058 list( , $lang, , , ) = $m;
1060 $candidatesByLocale[$m[0]] = $m;
1061 $candidatesByLang[$lang][] = $m;
1064 # Try the current value of LANG.
1065 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1066 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1071 # Try the most common ones.
1072 $commonLocales = array( 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' );
1073 foreach ( $commonLocales as $commonLocale ) {
1074 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1075 $this->setVar( 'wgShellLocale', $commonLocale );
1081 # Is there an available locale in the Wiki's language?
1082 $wikiLang = $this->getVar( 'wgLanguageCode' );
1084 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1085 $m = reset( $candidatesByLang[$wikiLang] );
1086 $this->setVar( 'wgShellLocale', $m[0] );
1091 # Are there any at all?
1092 if ( count( $candidatesByLocale ) ) {
1093 $m = reset( $candidatesByLocale );
1094 $this->setVar( 'wgShellLocale', $m[0] );
1104 * Environment check for the permissions of the uploads directory
1107 protected function envCheckUploadsDirectory() {
1110 $dir = $IP . '/images/';
1111 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1112 $safe = !$this->dirIsExecutable( $dir, $url );
1115 $this->showMessage( 'config-uploads-not-safe', $dir );
1122 * Checks if suhosin.get.max_value_length is set, and if so generate
1123 * a warning because it decreases ResourceLoader performance.
1126 protected function envCheckSuhosinMaxValueLength() {
1127 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1128 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1129 // Only warn if the value is below the sane 1024
1130 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1137 * Convert a hex string representing a Unicode code point to that code point.
1141 protected function unicodeChar( $c ) {
1145 } elseif ( $c <= 0x7FF ) {
1146 return chr( 0xC0 |
$c >> 6 ) . chr( 0x80 |
$c & 0x3F );
1147 } elseif ( $c <= 0xFFFF ) {
1148 return chr( 0xE0 |
$c >> 12 ) . chr( 0x80 |
$c >> 6 & 0x3F )
1149 . chr( 0x80 |
$c & 0x3F );
1150 } elseif ( $c <= 0x10FFFF ) {
1151 return chr( 0xF0 |
$c >> 18 ) . chr( 0x80 |
$c >> 12 & 0x3F )
1152 . chr( 0x80 |
$c >> 6 & 0x3F )
1153 . chr( 0x80 |
$c & 0x3F );
1160 * Check the libicu version
1162 protected function envCheckLibicu() {
1163 $utf8 = function_exists( 'utf8_normalize' );
1164 $intl = function_exists( 'normalizer_normalize' );
1167 * This needs to be updated something that the latest libicu
1168 * will properly normalize. This normalization was found at
1169 * http://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1170 * Note that we use the hex representation to create the code
1171 * points in order to avoid any Unicode-destroying during transit.
1173 $not_normal_c = $this->unicodeChar( "FA6C" );
1174 $normal_c = $this->unicodeChar( "242EE" );
1176 $useNormalizer = 'php';
1177 $needsUpdate = false;
1180 * We're going to prefer the pecl extension here unless
1181 * utf8_normalize is more up to date.
1184 $useNormalizer = 'utf8';
1185 $utf8 = utf8_normalize( $not_normal_c, UtfNormal
::UNORM_NFC
);
1186 if ( $utf8 !== $normal_c ) {
1187 $needsUpdate = true;
1191 $useNormalizer = 'intl';
1192 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1193 if ( $intl !== $normal_c ) {
1194 $needsUpdate = true;
1198 // Uses messages 'config-unicode-using-php', 'config-unicode-using-utf8', 'config-unicode-using-intl'
1199 if ( $useNormalizer === 'php' ) {
1200 $this->showMessage( 'config-unicode-pure-php-warning' );
1202 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1203 if ( $needsUpdate ) {
1204 $this->showMessage( 'config-unicode-update-warning' );
1212 protected function envCheckCtype() {
1213 if ( !function_exists( 'ctype_digit' ) ) {
1214 $this->showError( 'config-ctype' );
1225 protected function envCheckJSON() {
1226 if ( !function_exists( 'json_decode' ) ) {
1227 $this->showError( 'config-json' );
1236 * Get an array of likely places we can find executables. Check a bunch
1237 * of known Unix-like defaults, as well as the PATH environment variable
1238 * (which should maybe make it work for Windows?)
1242 protected static function getPossibleBinPaths() {
1244 array( '/usr/bin', '/usr/local/bin', '/opt/csw/bin',
1245 '/usr/gnu/bin', '/usr/sfw/bin', '/sw/bin', '/opt/local/bin' ),
1246 explode( PATH_SEPARATOR
, getenv( 'PATH' ) )
1251 * Search a path for any of the given executable names. Returns the
1252 * executable name if found. Also checks the version string returned
1253 * by each executable.
1255 * Used only by environment checks.
1257 * @param string $path path to search
1258 * @param array $names of executable names
1259 * @param $versionInfo Boolean false or array with two members:
1260 * 0 => Command to run for version check, with $1 for the full executable name
1261 * 1 => String to compare the output with
1263 * If $versionInfo is not false, only executables with a version
1264 * matching $versionInfo[1] will be returned.
1265 * @return bool|string
1267 public static function locateExecutable( $path, $names, $versionInfo = false ) {
1268 if ( !is_array( $names ) ) {
1269 $names = array( $names );
1272 foreach ( $names as $name ) {
1273 $command = $path . DIRECTORY_SEPARATOR
. $name;
1275 wfSuppressWarnings();
1276 $file_exists = file_exists( $command );
1277 wfRestoreWarnings();
1279 if ( $file_exists ) {
1280 if ( !$versionInfo ) {
1284 $file = str_replace( '$1', wfEscapeShellArg( $command ), $versionInfo[0] );
1285 if ( strstr( wfShellExec( $file ), $versionInfo[1] ) !== false ) {
1295 * Same as locateExecutable(), but checks in getPossibleBinPaths() by default
1296 * @see locateExecutable()
1298 * @param $versionInfo bool
1299 * @return bool|string
1301 public static function locateExecutableInDefaultPaths( $names, $versionInfo = false ) {
1302 foreach ( self
::getPossibleBinPaths() as $path ) {
1303 $exe = self
::locateExecutable( $path, $names, $versionInfo );
1304 if ( $exe !== false ) {
1313 * Checks if scripts located in the given directory can be executed via the given URL.
1315 * Used only by environment checks.
1316 * @param $dir string
1317 * @param $url string
1318 * @return bool|int|string
1320 public function dirIsExecutable( $dir, $url ) {
1321 $scriptTypes = array(
1323 "<?php echo 'ex' . 'ec';",
1324 "#!/var/env php5\n<?php echo 'ex' . 'ec';",
1328 // it would be good to check other popular languages here, but it'll be slow.
1330 wfSuppressWarnings();
1332 foreach ( $scriptTypes as $ext => $contents ) {
1333 foreach ( $contents as $source ) {
1334 $file = 'exectest.' . $ext;
1336 if ( !file_put_contents( $dir . $file, $source ) ) {
1341 $text = Http
::get( $url . $file, array( 'timeout' => 3 ) );
1342 } catch ( MWException
$e ) {
1343 // Http::get throws with allow_url_fopen = false and no curl extension.
1346 unlink( $dir . $file );
1348 if ( $text == 'exec' ) {
1349 wfRestoreWarnings();
1356 wfRestoreWarnings();
1362 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1364 * @param string $moduleName Name of module to check.
1367 public static function apacheModulePresent( $moduleName ) {
1368 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1371 // try it the hard way
1373 phpinfo( INFO_MODULES
);
1374 $info = ob_get_clean();
1376 return strpos( $info, $moduleName ) !== false;
1380 * ParserOptions are constructed before we determined the language, so fix it
1382 * @param $lang Language
1384 public function setParserLanguage( $lang ) {
1385 $this->parserOptions
->setTargetLanguage( $lang );
1386 $this->parserOptions
->setUserLang( $lang );
1390 * Overridden by WebInstaller to provide lastPage parameters.
1391 * @param $page string
1394 protected function getDocUrl( $page ) {
1395 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1399 * Finds extensions that follow the format /extensions/Name/Name.php,
1400 * and returns an array containing the value for 'Name' for each found extension.
1404 public function findExtensions() {
1405 if ( $this->getVar( 'IP' ) === null ) {
1409 $extDir = $this->getVar( 'IP' ) . '/extensions';
1410 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1414 $dh = opendir( $extDir );
1416 while ( ( $file = readdir( $dh ) ) !== false ) {
1417 if ( !is_dir( "$extDir/$file" ) ) {
1420 if ( file_exists( "$extDir/$file/$file.php" ) ) {
1425 natcasesort( $exts );
1431 * Installs the auto-detected extensions.
1435 protected function includeExtensions() {
1437 $exts = $this->getVar( '_Extensions' );
1438 $IP = $this->getVar( 'IP' );
1441 * We need to include DefaultSettings before including extensions to avoid
1442 * warnings about unset variables. However, the only thing we really
1443 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1444 * if the extension has hidden hook registration in $wgExtensionFunctions,
1445 * but we're not opening that can of worms
1446 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=26857
1448 global $wgAutoloadClasses;
1449 $wgAutoloadClasses = array();
1451 require "$IP/includes/DefaultSettings.php";
1453 foreach ( $exts as $e ) {
1454 require_once "$IP/extensions/$e/$e.php";
1457 $hooksWeWant = isset( $wgHooks['LoadExtensionSchemaUpdates'] ) ?
1458 $wgHooks['LoadExtensionSchemaUpdates'] : array();
1460 // Unset everyone else's hooks. Lord knows what someone might be doing
1461 // in ParserFirstCallInit (see bug 27171)
1462 $GLOBALS['wgHooks'] = array( 'LoadExtensionSchemaUpdates' => $hooksWeWant );
1464 return Status
::newGood();
1468 * Get an array of install steps. Should always be in the format of
1470 * 'name' => 'someuniquename',
1471 * 'callback' => array( $obj, 'method' ),
1473 * There must be a config-install-$name message defined per step, which will
1474 * be shown on install.
1476 * @param $installer DatabaseInstaller so we can make callbacks
1479 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1480 $coreInstallSteps = array(
1481 array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
1482 array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
1483 array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
1484 array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
1485 array( 'name' => 'keys', 'callback' => array( $this, 'generateKeys' ) ),
1486 array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
1487 array( 'name' => 'mainpage', 'callback' => array( $this, 'createMainpage' ) ),
1490 // Build the array of install steps starting from the core install list,
1491 // then adding any callbacks that wanted to attach after a given step
1492 foreach ( $coreInstallSteps as $step ) {
1493 $this->installSteps
[] = $step;
1494 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1495 $this->installSteps
= array_merge(
1496 $this->installSteps
,
1497 $this->extraInstallSteps
[$step['name']]
1502 // Prepend any steps that want to be at the beginning
1503 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1504 $this->installSteps
= array_merge(
1505 $this->extraInstallSteps
['BEGINNING'],
1510 // Extensions should always go first, chance to tie into hooks and such
1511 if ( count( $this->getVar( '_Extensions' ) ) ) {
1512 array_unshift( $this->installSteps
,
1513 array( 'name' => 'extensions', 'callback' => array( $this, 'includeExtensions' ) )
1515 $this->installSteps
[] = array(
1516 'name' => 'extension-tables',
1517 'callback' => array( $installer, 'createExtensionTables' )
1521 return $this->installSteps
;
1525 * Actually perform the installation.
1527 * @param array $startCB A callback array for the beginning of each step
1528 * @param array $endCB A callback array for the end of each step
1530 * @return Array of Status objects
1532 public function performInstallation( $startCB, $endCB ) {
1533 $installResults = array();
1534 $installer = $this->getDBInstaller();
1535 $installer->preInstall();
1536 $steps = $this->getInstallSteps( $installer );
1537 foreach ( $steps as $stepObj ) {
1538 $name = $stepObj['name'];
1539 call_user_func_array( $startCB, array( $name ) );
1541 // Perform the callback step
1542 $status = call_user_func( $stepObj['callback'], $installer );
1544 // Output and save the results
1545 call_user_func( $endCB, $name, $status );
1546 $installResults[$name] = $status;
1548 // If we've hit some sort of fatal, we need to bail.
1549 // Callback already had a chance to do output above.
1550 if ( !$status->isOk() ) {
1554 if ( $status->isOk() ) {
1555 $this->setVar( '_InstallDone', true );
1558 return $installResults;
1562 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1566 public function generateKeys() {
1567 $keys = array( 'wgSecretKey' => 64 );
1568 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1569 $keys['wgUpgradeKey'] = 16;
1572 return $this->doGenerateKeys( $keys );
1576 * Generate a secret value for variables using our CryptRand generator.
1577 * Produce a warning if the random source was insecure.
1579 * @param $keys Array
1582 protected function doGenerateKeys( $keys ) {
1583 $status = Status
::newGood();
1586 foreach ( $keys as $name => $length ) {
1587 $secretKey = MWCryptRand
::generateHex( $length, true );
1588 if ( !MWCryptRand
::wasStrong() ) {
1592 $this->setVar( $name, $secretKey );
1596 $names = array_keys( $keys );
1597 $names = preg_replace( '/^(.*)$/', '\$$1', $names );
1599 $status->warning( 'config-insecure-keys', $wgLang->listToText( $names ), count( $names ) );
1606 * Create the first user account, grant it sysop and bureaucrat rights
1610 protected function createSysop() {
1611 $name = $this->getVar( '_AdminName' );
1612 $user = User
::newFromName( $name );
1615 // We should've validated this earlier anyway!
1616 return Status
::newFatal( 'config-admin-error-user', $name );
1619 if ( $user->idForName() == 0 ) {
1620 $user->addToDatabase();
1623 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1624 } catch ( PasswordError
$pwe ) {
1625 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1628 $user->addGroup( 'sysop' );
1629 $user->addGroup( 'bureaucrat' );
1630 if ( $this->getVar( '_AdminEmail' ) ) {
1631 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1633 $user->saveSettings();
1635 // Update user count
1636 $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
1637 $ssUpdate->doUpdate();
1639 $status = Status
::newGood();
1641 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1642 $this->subscribeToMediaWikiAnnounce( $status );
1651 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1653 'email' => $this->getVar( '_AdminEmail' ),
1658 // Mailman doesn't support as many languages as we do, so check to make
1659 // sure their selected language is available
1660 $myLang = $this->getVar( '_UserLang' );
1661 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1662 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1663 $params['language'] = $myLang;
1666 if ( MWHttpRequest
::canMakeRequests() ) {
1667 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1668 array( 'method' => 'POST', 'postData' => $params ) )->execute();
1669 if ( !$res->isOK() ) {
1670 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1673 $s->warning( 'config-install-subscribe-notpossible' );
1678 * Insert Main Page with default content.
1680 * @param $installer DatabaseInstaller
1683 protected function createMainpage( DatabaseInstaller
$installer ) {
1684 $status = Status
::newGood();
1686 $page = WikiPage
::factory( Title
::newMainPage() );
1687 $content = new WikitextContent(
1688 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1689 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1692 $page->doEditContent( $content,
1696 User
::newFromName( 'MediaWiki default' )
1698 } catch ( MWException
$e ) {
1699 //using raw, because $wgShowExceptionDetails can not be set yet
1700 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1707 * Override the necessary bits of the config to run an installation.
1709 public static function overrideConfig() {
1710 define( 'MW_NO_SESSION', 1 );
1712 // Don't access the database
1713 $GLOBALS['wgUseDatabaseMessages'] = false;
1714 // Don't cache langconv tables
1715 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1717 $GLOBALS['wgShowExceptionDetails'] = true;
1718 // Don't break forms
1719 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1721 // Extended debugging
1722 $GLOBALS['wgShowSQLErrors'] = true;
1723 $GLOBALS['wgShowDBErrorBacktrace'] = true;
1725 // Allow multiple ob_flush() calls
1726 $GLOBALS['wgDisableOutputCompression'] = true;
1728 // Use a sensible cookie prefix (not my_wiki)
1729 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1731 // Some of the environment checks make shell requests, remove limits
1732 $GLOBALS['wgMaxShellMemory'] = 0;
1736 * Add an installation step following the given step.
1738 * @param array $callback A valid installation callback array, in this form:
1739 * array( 'name' => 'some-unique-name', 'callback' => array( $obj, 'function' ) );
1740 * @param string $findStep the step to find. Omit to put the step at the beginning
1742 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1743 $this->extraInstallSteps
[$findStep][] = $callback;
1747 * Disable the time limit for execution.
1748 * Some long-running pages (Install, Upgrade) will want to do this
1750 protected function disableTimeLimit() {
1751 wfSuppressWarnings();
1752 set_time_limit( 0 );
1753 wfRestoreWarnings();