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\Database
;
26 use Wikimedia\Rdbms\DBConnectionError
;
27 use Wikimedia\Rdbms\DBExpectedError
;
28 use Wikimedia\Rdbms\IDatabase
;
29 use Wikimedia\Rdbms\LBFactorySingle
;
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.
138 * @return string|bool
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.
180 * @suppress PhanUndeclaredMethod
182 public function getConnection() {
184 return Status
::newGood( $this->db
);
187 $status = $this->openConnection();
188 if ( $status->isOK() ) {
189 $this->db
= $status->value
;
191 $this->db
->clearFlag( DBO_TRX
);
192 $this->db
->commit( __METHOD__
);
199 * Apply a SQL source file to the database as part of running an installation step.
201 * @param string $sourceFileMethod
202 * @param string $stepName
203 * @param bool $archiveTableMustNotExist
206 private function stepApplySourceFile(
209 $archiveTableMustNotExist = false
211 $status = $this->getConnection();
212 if ( !$status->isOK() ) {
215 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
217 if ( $archiveTableMustNotExist && $this->db
->tableExists( 'archive', __METHOD__
) ) {
218 $status->warning( "config-$stepName-tables-exist" );
224 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
225 $this->db
->begin( __METHOD__
);
227 $error = $this->db
->sourceFile(
228 call_user_func( [ $this, $sourceFileMethod ], $this->db
)
230 if ( $error !== true ) {
231 $this->db
->reportQueryError( $error, 0, '', __METHOD__
);
232 $this->db
->rollback( __METHOD__
);
233 $status->fatal( "config-$stepName-tables-failed", $error );
235 $this->db
->commit( __METHOD__
);
237 // Resume normal operations
238 if ( $status->isOK() ) {
246 * Create database tables from scratch.
250 public function createTables() {
251 return $this->stepApplySourceFile( 'getSchemaPath', 'install', true );
255 * Insert update keys into table to prevent running unneded updates.
259 public function insertUpdateKeys() {
260 return $this->stepApplySourceFile( 'getUpdateKeysPath', 'updates', false );
264 * Return a path to the DBMS-specific SQL file if it exists,
265 * otherwise default SQL file
267 * @param IDatabase $db
268 * @param string $filename
271 private function getSqlFilePath( $db, $filename ) {
274 $dbmsSpecificFilePath = "$IP/maintenance/" . $db->getType() . "/$filename";
275 if ( file_exists( $dbmsSpecificFilePath ) ) {
276 return $dbmsSpecificFilePath;
278 return "$IP/maintenance/$filename";
283 * Return a path to the DBMS-specific schema file,
284 * otherwise default to tables.sql
286 * @param IDatabase $db
289 public function getSchemaPath( $db ) {
290 return $this->getSqlFilePath( $db, 'tables.sql' );
294 * Return a path to the DBMS-specific update key file,
295 * otherwise default to update-keys.sql
297 * @param IDatabase $db
300 public function getUpdateKeysPath( $db ) {
301 return $this->getSqlFilePath( $db, 'update-keys.sql' );
305 * Create the tables for each extension the user enabled
308 public function createExtensionTables() {
309 $status = $this->getConnection();
310 if ( !$status->isOK() ) {
314 // Now run updates to create tables for old extensions
315 DatabaseUpdater
::newForDB( $this->db
)->doUpdates( [ 'extensions' ] );
321 * Get the DBMS-specific options for LocalSettings.php generation.
325 abstract public function getLocalSettings();
328 * Override this to provide DBMS-specific schema variables, to be
329 * substituted into tables.sql and other schema files.
332 public function getSchemaVars() {
337 * Set appropriate schema variables in the current database connection.
339 * This should be called after any request data has been imported, but before
340 * any write operations to the database.
342 public function setupSchemaVars() {
343 $status = $this->getConnection();
344 if ( $status->isOK() ) {
345 // @phan-suppress-next-line PhanUndeclaredMethod
346 $status->value
->setSchemaVars( $this->getSchemaVars() );
348 $msg = __METHOD__
. ': unexpected error while establishing'
349 . ' a database connection with message: '
350 . $status->getMessage()->plain();
351 throw new MWException( $msg );
356 * Set up LBFactory so that wfGetDB() etc. works.
357 * We set up a special LBFactory instance which returns the current
358 * installer connection.
360 public function enableLB() {
361 $status = $this->getConnection();
362 if ( !$status->isOK() ) {
363 throw new MWException( __METHOD__
. ': unexpected DB connection error' );
366 MediaWikiServices
::resetGlobalInstance();
367 $services = MediaWikiServices
::getInstance();
369 $connection = $status->value
;
370 $services->redefineService( 'DBLoadBalancerFactory', function () use ( $connection ) {
371 return LBFactorySingle
::newFromConnection( $connection );
376 * Perform database upgrades
378 * @suppress SecurityCheck-XSS Escaping provided by $this->outputHandler
381 public function doUpgrade() {
382 $this->setupSchemaVars();
386 ob_start( [ $this, 'outputHandler' ] );
387 $up = DatabaseUpdater
::newForDB( $this->db
);
391 } catch ( MWException
$e ) {
392 echo "\nAn error occurred:\n";
395 } catch ( Exception
$e ) {
396 echo "\nAn error occurred:\n";
397 echo $e->getMessage();
406 * Allow DB installers a chance to make last-minute changes before installation
407 * occurs. This happens before setupDatabase() or createTables() is called, but
408 * long after the constructor. Helpful for things like modifying setup steps :)
410 public function preInstall() {
414 * Allow DB installers a chance to make checks before upgrade.
416 public function preUpgrade() {
420 * Get an array of MW configuration globals that will be configured by this class.
423 public function getGlobalNames() {
424 return $this->globalNames
;
428 * Construct and initialise parent.
429 * This is typically only called from Installer::getDBInstaller()
430 * @param WebInstaller $parent
432 public function __construct( $parent ) {
433 $this->parent
= $parent;
437 * Convenience function.
438 * Check if a named extension is present.
440 * @param string $name
443 protected static function checkExtension( $name ) {
444 return extension_loaded( $name );
448 * Get the internationalised name for this DBMS.
451 public function getReadableName() {
452 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite
453 return wfMessage( 'config-type-' . $this->getName() )->text();
457 * Get a name=>value map of MW configuration globals for the default values.
460 public function getGlobalDefaults() {
462 foreach ( $this->getGlobalNames() as $var ) {
463 if ( isset( $GLOBALS[$var] ) ) {
464 $defaults[$var] = $GLOBALS[$var];
471 * Get a name=>value map of internal variables used during installation.
474 public function getInternalDefaults() {
475 return $this->internalDefaults
;
479 * Get a variable, taking local defaults into account.
481 * @param mixed|null $default
484 public function getVar( $var, $default = null ) {
485 $defaults = $this->getGlobalDefaults();
486 $internal = $this->getInternalDefaults();
487 if ( isset( $defaults[$var] ) ) {
488 $default = $defaults[$var];
489 } elseif ( isset( $internal[$var] ) ) {
490 $default = $internal[$var];
493 return $this->parent
->getVar( $var, $default );
497 * Convenience alias for $this->parent->setVar()
498 * @param string $name
499 * @param mixed $value
501 public function setVar( $name, $value ) {
502 $this->parent
->setVar( $name, $value );
506 * Get a labelled text box to configure a local variable.
509 * @param string $label
510 * @param array $attribs
511 * @param string $helpData
514 public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
515 $name = $this->getName() . '_' . $var;
516 $value = $this->getVar( $var );
517 if ( !isset( $attribs ) ) {
521 return $this->parent
->getTextBox( [
524 'attribs' => $attribs,
525 'controlName' => $name,
532 * Get a labelled password box to configure a local variable.
533 * Implements password hiding.
536 * @param string $label
537 * @param array $attribs
538 * @param string $helpData
541 public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
542 $name = $this->getName() . '_' . $var;
543 $value = $this->getVar( $var );
544 if ( !isset( $attribs ) ) {
548 return $this->parent
->getPasswordBox( [
551 'attribs' => $attribs,
552 'controlName' => $name,
559 * Get a labelled checkbox to configure a local boolean variable.
562 * @param string $label
563 * @param array $attribs Optional.
564 * @param string $helpData Optional.
567 public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
568 $name = $this->getName() . '_' . $var;
569 $value = $this->getVar( $var );
571 return $this->parent
->getCheckBox( [
574 'attribs' => $attribs,
575 'controlName' => $name,
582 * Get a set of labelled radio buttons.
584 * @param array $params Parameters are:
585 * var: The variable to be configured (required)
586 * label: The message name for the label (required)
587 * itemLabelPrefix: The message name prefix for the item labels (required)
588 * values: List of allowed values (required)
589 * itemAttribs Array of attribute arrays, outer key is the value name (optional)
593 public function getRadioSet( $params ) {
594 $params['controlName'] = $this->getName() . '_' . $params['var'];
595 $params['value'] = $this->getVar( $params['var'] );
597 return $this->parent
->getRadioSet( $params );
601 * Convenience function to set variables based on form data.
602 * Assumes that variables containing "password" in the name are (potentially
604 * @param array $varNames
607 public function setVarsFromRequest( $varNames ) {
608 return $this->parent
->setVarsFromRequest( $varNames, $this->getName() . '_' );
612 * Determine whether an existing installation of MediaWiki is present in
613 * the configured administrative connection. Returns true if there is
614 * such a wiki, false if the database doesn't exist.
616 * Traditionally, this is done by testing for the existence of either
617 * the revision table or the cur table.
621 public function needsUpgrade() {
622 $status = $this->getConnection();
623 if ( !$status->isOK() ) {
628 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
629 } catch ( DBConnectionError
$e ) {
630 // Don't catch DBConnectionError
632 } catch ( DBExpectedError
$e ) {
636 return $this->db
->tableExists( 'cur', __METHOD__
) ||
637 $this->db
->tableExists( 'revision', __METHOD__
);
641 * Get a standard install-user fieldset.
645 public function getInstallUserBox() {
646 return Html
::openElement( 'fieldset' ) .
647 Html
::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
650 'config-db-username',
652 $this->parent
->getHelpBox( 'config-db-install-username' )
654 $this->getPasswordBox(
656 'config-db-password',
658 $this->parent
->getHelpBox( 'config-db-install-password' )
660 Html
::closeElement( 'fieldset' );
664 * Submit a standard install user fieldset.
667 public function submitInstallUserBox() {
668 $this->setVarsFromRequest( [ '_InstallUser', '_InstallPassword' ] );
670 return Status
::newGood();
674 * Get a standard web-user fieldset
675 * @param string|bool $noCreateMsg Message to display instead of the creation checkbox.
676 * Set this to false to show a creation checkbox (default).
680 public function getWebUserBox( $noCreateMsg = false ) {
681 $wrapperStyle = $this->getVar( '_SameAccount' ) ?
'display: none' : '';
682 $s = Html
::openElement( 'fieldset' ) .
683 Html
::element( 'legend', [], wfMessage( 'config-db-web-account' )->text() ) .
685 '_SameAccount', 'config-db-web-account-same',
686 [ 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' ]
688 Html
::openElement( 'div', [ 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ] ) .
689 $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
690 $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
691 $this->parent
->getHelpBox( 'config-db-web-help' );
692 if ( $noCreateMsg ) {
693 $s .= Html
::warningBox( wfMessage( $noCreateMsg )->plain(), 'config-warning-box' );
695 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
697 $s .= Html
::closeElement( 'div' ) . Html
::closeElement( 'fieldset' );
703 * Submit the form from getWebUserBox().
707 public function submitWebUserBox() {
708 $this->setVarsFromRequest(
709 [ 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' ]
712 if ( $this->getVar( '_SameAccount' ) ) {
713 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
714 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
717 if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
718 return Status
::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
721 return Status
::newGood();
725 * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
729 public function populateInterwikiTable() {
730 $status = $this->getConnection();
731 if ( !$status->isOK() ) {
734 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
736 if ( $this->db
->selectRow( 'interwiki', '1', [], __METHOD__
) ) {
737 $status->warning( 'config-install-interwiki-exists' );
742 Wikimedia\
suppressWarnings();
743 $rows = file( "$IP/maintenance/interwiki.list",
744 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
);
745 Wikimedia\restoreWarnings
();
748 return Status
::newFatal( 'config-install-interwiki-list' );
750 foreach ( $rows as $row ) {
751 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
756 $interwikis[] = array_combine(
757 [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
761 $this->db
->insert( 'interwiki', $interwikis, __METHOD__
);
763 return Status
::newGood();
766 public function outputHandler( $string ) {
767 return htmlspecialchars( $string );