3 * DBMS-specific installation helper.
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
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\Rdbms\LBFactorySingle
;
26 use Wikimedia\Rdbms\Database
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use Wikimedia\Rdbms\DBExpectedError
;
29 use Wikimedia\Rdbms\DBConnectionError
;
32 * Base class for DBMS-specific installation helper classes.
37 abstract class DatabaseInstaller
{
40 * The Installer object.
47 * @var string Set by subclasses
49 public static $minimumVersion;
52 * @var string Set by subclasses
54 protected static $notMinimumVersionMessage;
57 * The database connection.
64 * Internal variables for installation.
68 protected $internalDefaults = [];
71 * Array of MW configuration globals this class uses.
75 protected $globalNames = [];
78 * Whether the provided version meets the necessary requirements for this type
80 * @param string $serverVersion Output of Database::getServerVersion()
84 public static function meetsMinimumRequirement( $serverVersion ) {
85 if ( version_compare( $serverVersion, static::$minimumVersion ) < 0 ) {
86 return Status
::newFatal(
87 static::$notMinimumVersionMessage, static::$minimumVersion, $serverVersion
91 return Status
::newGood();
95 * Return the internal name, e.g. 'mysql', or 'sqlite'.
97 abstract public function getName();
100 * @return bool Returns true if the client library is compiled in.
102 abstract public function isCompiled();
105 * Checks for installation prerequisites other than those checked by isCompiled()
109 public function checkPrerequisites() {
110 return Status
::newGood();
114 * Get HTML for a web form that configures this database. Configuration
115 * at this time should be the minimum needed to connect and test
116 * whether install or upgrade is required.
118 * If this is called, $this->parent can be assumed to be a WebInstaller.
120 abstract public function getConnectForm();
123 * Set variables based on the request array, assuming it was submitted
124 * via the form returned by getConnectForm(). Validate the connection
125 * settings by attempting to connect with them.
127 * If this is called, $this->parent can be assumed to be a WebInstaller.
131 abstract public function submitConnectForm();
134 * Get HTML for a web form that retrieves settings used for installation.
135 * $this->parent can be assumed to be a WebInstaller.
136 * If the DB type has no settings beyond those already configured with
137 * getConnectForm(), this should return false.
140 public function getSettingsForm() {
145 * Set variables based on the request array, assuming it was submitted via
146 * the form return by getSettingsForm().
150 public function submitSettingsForm() {
151 return Status
::newGood();
155 * Open a connection to the database using the administrative user/password
156 * currently defined in the session, without any caching. Returns a status
157 * object. On success, the status object will contain a Database object in
162 abstract public function openConnection();
165 * Create the database and return a Status object indicating success or
170 abstract public function setupDatabase();
173 * Connect to the database using the administrative user/password currently
174 * defined in the session. Returns a status object. On success, the status
175 * object will contain a Database object in its value member.
177 * This will return a cached connection if one is available.
181 public function getConnection() {
183 return Status
::newGood( $this->db
);
186 $status = $this->openConnection();
187 if ( $status->isOK() ) {
188 $this->db
= $status->value
;
190 $this->db
->clearFlag( DBO_TRX
);
191 $this->db
->commit( __METHOD__
);
198 * Apply a SQL source file to the database as part of running an installation step.
200 * @param string $sourceFileMethod
201 * @param string $stepName
202 * @param bool $archiveTableMustNotExist
205 private function stepApplySourceFile(
208 $archiveTableMustNotExist = false
210 $status = $this->getConnection();
211 if ( !$status->isOK() ) {
214 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
216 if ( $archiveTableMustNotExist && $this->db
->tableExists( 'archive', __METHOD__
) ) {
217 $status->warning( "config-$stepName-tables-exist" );
223 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
224 $this->db
->begin( __METHOD__
);
226 $error = $this->db
->sourceFile(
227 call_user_func( [ $this, $sourceFileMethod ], $this->db
)
229 if ( $error !== true ) {
230 $this->db
->reportQueryError( $error, 0, '', __METHOD__
);
231 $this->db
->rollback( __METHOD__
);
232 $status->fatal( "config-$stepName-tables-failed", $error );
234 $this->db
->commit( __METHOD__
);
236 // Resume normal operations
237 if ( $status->isOK() ) {
245 * Create database tables from scratch.
249 public function createTables() {
250 return $this->stepApplySourceFile( 'getSchemaPath', 'install', true );
254 * Insert update keys into table to prevent running unneded updates.
258 public function insertUpdateKeys() {
259 return $this->stepApplySourceFile( 'getUpdateKeysPath', 'updates', false );
263 * Return a path to the DBMS-specific SQL file if it exists,
264 * otherwise default SQL file
266 * @param IDatabase $db
267 * @param string $filename
270 private function getSqlFilePath( $db, $filename ) {
273 $dbmsSpecificFilePath = "$IP/maintenance/" . $db->getType() . "/$filename";
274 if ( file_exists( $dbmsSpecificFilePath ) ) {
275 return $dbmsSpecificFilePath;
277 return "$IP/maintenance/$filename";
282 * Return a path to the DBMS-specific schema file,
283 * otherwise default to tables.sql
285 * @param IDatabase $db
288 public function getSchemaPath( $db ) {
289 return $this->getSqlFilePath( $db, 'tables.sql' );
293 * Return a path to the DBMS-specific update key file,
294 * otherwise default to update-keys.sql
296 * @param IDatabase $db
299 public function getUpdateKeysPath( $db ) {
300 return $this->getSqlFilePath( $db, 'update-keys.sql' );
304 * Create the tables for each extension the user enabled
307 public function createExtensionTables() {
308 $status = $this->getConnection();
309 if ( !$status->isOK() ) {
313 // Now run updates to create tables for old extensions
314 DatabaseUpdater
::newForDB( $this->db
)->doUpdates( [ 'extensions' ] );
320 * Get the DBMS-specific options for LocalSettings.php generation.
324 abstract public function getLocalSettings();
327 * Override this to provide DBMS-specific schema variables, to be
328 * substituted into tables.sql and other schema files.
331 public function getSchemaVars() {
336 * Set appropriate schema variables in the current database connection.
338 * This should be called after any request data has been imported, but before
339 * any write operations to the database.
341 public function setupSchemaVars() {
342 $status = $this->getConnection();
343 if ( $status->isOK() ) {
344 $status->value
->setSchemaVars( $this->getSchemaVars() );
346 $msg = __METHOD__
. ': unexpected error while establishing'
347 . ' a database connection with message: '
348 . $status->getMessage()->plain();
349 throw new MWException( $msg );
354 * Set up LBFactory so that wfGetDB() etc. works.
355 * We set up a special LBFactory instance which returns the current
356 * installer connection.
358 public function enableLB() {
359 $status = $this->getConnection();
360 if ( !$status->isOK() ) {
361 throw new MWException( __METHOD__
. ': unexpected DB connection error' );
364 MediaWikiServices
::resetGlobalInstance();
365 $services = MediaWikiServices
::getInstance();
367 $connection = $status->value
;
368 $services->redefineService( 'DBLoadBalancerFactory', function () use ( $connection ) {
369 return LBFactorySingle
::newFromConnection( $connection );
374 * Perform database upgrades
376 * @suppress SecurityCheck-XSS Escaping provided by $this->outputHandler
379 public function doUpgrade() {
380 $this->setupSchemaVars();
384 ob_start( [ $this, 'outputHandler' ] );
385 $up = DatabaseUpdater
::newForDB( $this->db
);
389 } catch ( MWException
$e ) {
390 echo "\nAn error occurred:\n";
393 } catch ( Exception
$e ) {
394 echo "\nAn error occurred:\n";
395 echo $e->getMessage();
404 * Allow DB installers a chance to make last-minute changes before installation
405 * occurs. This happens before setupDatabase() or createTables() is called, but
406 * long after the constructor. Helpful for things like modifying setup steps :)
408 public function preInstall() {
412 * Allow DB installers a chance to make checks before upgrade.
414 public function preUpgrade() {
418 * Get an array of MW configuration globals that will be configured by this class.
421 public function getGlobalNames() {
422 return $this->globalNames
;
426 * Construct and initialise parent.
427 * This is typically only called from Installer::getDBInstaller()
428 * @param WebInstaller $parent
430 public function __construct( $parent ) {
431 $this->parent
= $parent;
435 * Convenience function.
436 * Check if a named extension is present.
438 * @param string $name
441 protected static function checkExtension( $name ) {
442 return extension_loaded( $name );
446 * Get the internationalised name for this DBMS.
449 public function getReadableName() {
450 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite,
451 // config-type-oracle
452 return wfMessage( 'config-type-' . $this->getName() )->text();
456 * Get a name=>value map of MW configuration globals for the default values.
459 public function getGlobalDefaults() {
461 foreach ( $this->getGlobalNames() as $var ) {
462 if ( isset( $GLOBALS[$var] ) ) {
463 $defaults[$var] = $GLOBALS[$var];
470 * Get a name=>value map of internal variables used during installation.
473 public function getInternalDefaults() {
474 return $this->internalDefaults
;
478 * Get a variable, taking local defaults into account.
480 * @param mixed|null $default
483 public function getVar( $var, $default = null ) {
484 $defaults = $this->getGlobalDefaults();
485 $internal = $this->getInternalDefaults();
486 if ( isset( $defaults[$var] ) ) {
487 $default = $defaults[$var];
488 } elseif ( isset( $internal[$var] ) ) {
489 $default = $internal[$var];
492 return $this->parent
->getVar( $var, $default );
496 * Convenience alias for $this->parent->setVar()
497 * @param string $name
498 * @param mixed $value
500 public function setVar( $name, $value ) {
501 $this->parent
->setVar( $name, $value );
505 * Get a labelled text box to configure a local variable.
508 * @param string $label
509 * @param array $attribs
510 * @param string $helpData
513 public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
514 $name = $this->getName() . '_' . $var;
515 $value = $this->getVar( $var );
516 if ( !isset( $attribs ) ) {
520 return $this->parent
->getTextBox( [
523 'attribs' => $attribs,
524 'controlName' => $name,
531 * Get a labelled password box to configure a local variable.
532 * Implements password hiding.
535 * @param string $label
536 * @param array $attribs
537 * @param string $helpData
540 public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
541 $name = $this->getName() . '_' . $var;
542 $value = $this->getVar( $var );
543 if ( !isset( $attribs ) ) {
547 return $this->parent
->getPasswordBox( [
550 'attribs' => $attribs,
551 'controlName' => $name,
558 * Get a labelled checkbox to configure a local boolean variable.
561 * @param string $label
562 * @param array $attribs Optional.
563 * @param string $helpData Optional.
566 public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
567 $name = $this->getName() . '_' . $var;
568 $value = $this->getVar( $var );
570 return $this->parent
->getCheckBox( [
573 'attribs' => $attribs,
574 'controlName' => $name,
581 * Get a set of labelled radio buttons.
583 * @param array $params Parameters are:
584 * var: The variable to be configured (required)
585 * label: The message name for the label (required)
586 * itemLabelPrefix: The message name prefix for the item labels (required)
587 * values: List of allowed values (required)
588 * itemAttribs Array of attribute arrays, outer key is the value name (optional)
592 public function getRadioSet( $params ) {
593 $params['controlName'] = $this->getName() . '_' . $params['var'];
594 $params['value'] = $this->getVar( $params['var'] );
596 return $this->parent
->getRadioSet( $params );
600 * Convenience function to set variables based on form data.
601 * Assumes that variables containing "password" in the name are (potentially
603 * @param array $varNames
606 public function setVarsFromRequest( $varNames ) {
607 return $this->parent
->setVarsFromRequest( $varNames, $this->getName() . '_' );
611 * Determine whether an existing installation of MediaWiki is present in
612 * the configured administrative connection. Returns true if there is
613 * such a wiki, false if the database doesn't exist.
615 * Traditionally, this is done by testing for the existence of either
616 * the revision table or the cur table.
620 public function needsUpgrade() {
621 $status = $this->getConnection();
622 if ( !$status->isOK() ) {
627 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
628 } catch ( DBConnectionError
$e ) {
629 // Don't catch DBConnectionError
631 } catch ( DBExpectedError
$e ) {
635 return $this->db
->tableExists( 'cur', __METHOD__
) ||
636 $this->db
->tableExists( 'revision', __METHOD__
);
640 * Get a standard install-user fieldset.
644 public function getInstallUserBox() {
645 return Html
::openElement( 'fieldset' ) .
646 Html
::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
649 'config-db-username',
651 $this->parent
->getHelpBox( 'config-db-install-username' )
653 $this->getPasswordBox(
655 'config-db-password',
657 $this->parent
->getHelpBox( 'config-db-install-password' )
659 Html
::closeElement( 'fieldset' );
663 * Submit a standard install user fieldset.
666 public function submitInstallUserBox() {
667 $this->setVarsFromRequest( [ '_InstallUser', '_InstallPassword' ] );
669 return Status
::newGood();
673 * Get a standard web-user fieldset
674 * @param string|bool $noCreateMsg Message to display instead of the creation checkbox.
675 * Set this to false to show a creation checkbox (default).
679 public function getWebUserBox( $noCreateMsg = false ) {
680 $wrapperStyle = $this->getVar( '_SameAccount' ) ?
'display: none' : '';
681 $s = Html
::openElement( 'fieldset' ) .
682 Html
::element( 'legend', [], wfMessage( 'config-db-web-account' )->text() ) .
684 '_SameAccount', 'config-db-web-account-same',
685 [ 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' ]
687 Html
::openElement( 'div', [ 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ] ) .
688 $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
689 $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
690 $this->parent
->getHelpBox( 'config-db-web-help' );
691 if ( $noCreateMsg ) {
692 $s .= $this->parent
->getWarningBox( wfMessage( $noCreateMsg )->plain() );
694 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
696 $s .= Html
::closeElement( 'div' ) . Html
::closeElement( 'fieldset' );
702 * Submit the form from getWebUserBox().
706 public function submitWebUserBox() {
707 $this->setVarsFromRequest(
708 [ 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' ]
711 if ( $this->getVar( '_SameAccount' ) ) {
712 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
713 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
716 if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
717 return Status
::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
720 return Status
::newGood();
724 * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
728 public function populateInterwikiTable() {
729 $status = $this->getConnection();
730 if ( !$status->isOK() ) {
733 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
735 if ( $this->db
->selectRow( 'interwiki', '1', [], __METHOD__
) ) {
736 $status->warning( 'config-install-interwiki-exists' );
741 Wikimedia\
suppressWarnings();
742 $rows = file( "$IP/maintenance/interwiki.list",
743 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
);
744 Wikimedia\restoreWarnings
();
747 return Status
::newFatal( 'config-install-interwiki-list' );
749 foreach ( $rows as $row ) {
750 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
755 $interwikis[] = array_combine(
756 [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
760 $this->db
->insert( 'interwiki', $interwikis, __METHOD__
);
762 return Status
::newGood();
765 public function outputHandler( $string ) {
766 return htmlspecialchars( $string );