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
23 use Wikimedia\Rdbms\LBFactorySingle
;
26 * Base class for DBMS-specific installation helper classes.
31 abstract class DatabaseInstaller
{
34 * The Installer object.
36 * @todo Naming this parent is confusing, 'installer' would be clearer.
43 * The database connection.
50 * Internal variables for installation.
54 protected $internalDefaults = [];
57 * Array of MW configuration globals this class uses.
61 protected $globalNames = [];
64 * Return the internal name, e.g. 'mysql', or 'sqlite'.
66 abstract public function getName();
69 * @return bool Returns true if the client library is compiled in.
71 abstract public function isCompiled();
74 * Checks for installation prerequisites other than those checked by isCompiled()
78 public function checkPrerequisites() {
79 return Status
::newGood();
83 * Get HTML for a web form that configures this database. Configuration
84 * at this time should be the minimum needed to connect and test
85 * whether install or upgrade is required.
87 * If this is called, $this->parent can be assumed to be a WebInstaller.
89 abstract public function getConnectForm();
92 * Set variables based on the request array, assuming it was submitted
93 * via the form returned by getConnectForm(). Validate the connection
94 * settings by attempting to connect with them.
96 * If this is called, $this->parent can be assumed to be a WebInstaller.
100 abstract public function submitConnectForm();
103 * Get HTML for a web form that retrieves settings used for installation.
104 * $this->parent can be assumed to be a WebInstaller.
105 * If the DB type has no settings beyond those already configured with
106 * getConnectForm(), this should return false.
109 public function getSettingsForm() {
114 * Set variables based on the request array, assuming it was submitted via
115 * the form return by getSettingsForm().
119 public function submitSettingsForm() {
120 return Status
::newGood();
124 * Open a connection to the database using the administrative user/password
125 * currently defined in the session, without any caching. Returns a status
126 * object. On success, the status object will contain a Database object in
131 abstract public function openConnection();
134 * Create the database and return a Status object indicating success or
139 abstract public function setupDatabase();
142 * Connect to the database using the administrative user/password currently
143 * defined in the session. Returns a status object. On success, the status
144 * object will contain a Database object in its value member.
146 * This will return a cached connection if one is available.
150 public function getConnection() {
152 return Status
::newGood( $this->db
);
155 $status = $this->openConnection();
156 if ( $status->isOK() ) {
157 $this->db
= $status->value
;
159 $this->db
->clearFlag( DBO_TRX
);
160 $this->db
->commit( __METHOD__
);
167 * Apply a SQL source file to the database as part of running an installation step.
169 * @param string $sourceFileMethod
170 * @param string $stepName
171 * @param bool $archiveTableMustNotExist
174 private function stepApplySourceFile(
177 $archiveTableMustNotExist = false
179 $status = $this->getConnection();
180 if ( !$status->isOK() ) {
183 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
185 if ( $archiveTableMustNotExist && $this->db
->tableExists( 'archive', __METHOD__
) ) {
186 $status->warning( "config-$stepName-tables-exist" );
192 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
193 $this->db
->begin( __METHOD__
);
195 $error = $this->db
->sourceFile(
196 call_user_func( [ $this, $sourceFileMethod ], $this->db
)
198 if ( $error !== true ) {
199 $this->db
->reportQueryError( $error, 0, '', __METHOD__
);
200 $this->db
->rollback( __METHOD__
);
201 $status->fatal( "config-$stepName-tables-failed", $error );
203 $this->db
->commit( __METHOD__
);
205 // Resume normal operations
206 if ( $status->isOK() ) {
214 * Create database tables from scratch.
218 public function createTables() {
219 return $this->stepApplySourceFile( 'getSchemaPath', 'install', true );
223 * Insert update keys into table to prevent running unneded updates.
227 public function insertUpdateKeys() {
228 return $this->stepApplySourceFile( 'getUpdateKeysPath', 'updates', false );
232 * Return a path to the DBMS-specific SQL file if it exists,
233 * otherwise default SQL file
235 * @param IDatabase $db
236 * @param string $filename
239 private function getSqlFilePath( $db, $filename ) {
242 $dbmsSpecificFilePath = "$IP/maintenance/" . $db->getType() . "/$filename";
243 if ( file_exists( $dbmsSpecificFilePath ) ) {
244 return $dbmsSpecificFilePath;
246 return "$IP/maintenance/$filename";
251 * Return a path to the DBMS-specific schema file,
252 * otherwise default to tables.sql
254 * @param IDatabase $db
257 public function getSchemaPath( $db ) {
258 return $this->getSqlFilePath( $db, 'tables.sql' );
262 * Return a path to the DBMS-specific update key file,
263 * otherwise default to update-keys.sql
265 * @param IDatabase $db
268 public function getUpdateKeysPath( $db ) {
269 return $this->getSqlFilePath( $db, 'update-keys.sql' );
273 * Create the tables for each extension the user enabled
276 public function createExtensionTables() {
277 $status = $this->getConnection();
278 if ( !$status->isOK() ) {
282 // Now run updates to create tables for old extensions
283 DatabaseUpdater
::newForDB( $this->db
)->doUpdates( [ 'extensions' ] );
289 * Get the DBMS-specific options for LocalSettings.php generation.
293 abstract public function getLocalSettings();
296 * Override this to provide DBMS-specific schema variables, to be
297 * substituted into tables.sql and other schema files.
300 public function getSchemaVars() {
305 * Set appropriate schema variables in the current database connection.
307 * This should be called after any request data has been imported, but before
308 * any write operations to the database.
310 public function setupSchemaVars() {
311 $status = $this->getConnection();
312 if ( $status->isOK() ) {
313 $status->value
->setSchemaVars( $this->getSchemaVars() );
315 $msg = __METHOD__
. ': unexpected error while establishing'
316 . ' a database connection with message: '
317 . $status->getMessage()->plain();
318 throw new MWException( $msg );
323 * Set up LBFactory so that wfGetDB() etc. works.
324 * We set up a special LBFactory instance which returns the current
325 * installer connection.
327 public function enableLB() {
328 $status = $this->getConnection();
329 if ( !$status->isOK() ) {
330 throw new MWException( __METHOD__
. ': unexpected DB connection error' );
333 \MediaWiki\MediaWikiServices
::resetGlobalInstance();
334 $services = \MediaWiki\MediaWikiServices
::getInstance();
336 $connection = $status->value
;
337 $services->redefineService( 'DBLoadBalancerFactory', function() use ( $connection ) {
338 return LBFactorySingle
::newFromConnection( $connection );
343 * Perform database upgrades
347 public function doUpgrade() {
348 $this->setupSchemaVars();
352 ob_start( [ $this, 'outputHandler' ] );
353 $up = DatabaseUpdater
::newForDB( $this->db
);
356 } catch ( MWException
$e ) {
357 echo "\nAn error occurred:\n";
360 } catch ( Exception
$e ) {
361 echo "\nAn error occurred:\n";
362 echo $e->getMessage();
372 * Allow DB installers a chance to make last-minute changes before installation
373 * occurs. This happens before setupDatabase() or createTables() is called, but
374 * long after the constructor. Helpful for things like modifying setup steps :)
376 public function preInstall() {
380 * Allow DB installers a chance to make checks before upgrade.
382 public function preUpgrade() {
386 * Get an array of MW configuration globals that will be configured by this class.
389 public function getGlobalNames() {
390 return $this->globalNames
;
394 * Construct and initialise parent.
395 * This is typically only called from Installer::getDBInstaller()
396 * @param WebInstaller $parent
398 public function __construct( $parent ) {
399 $this->parent
= $parent;
403 * Convenience function.
404 * Check if a named extension is present.
406 * @param string $name
409 protected static function checkExtension( $name ) {
410 return extension_loaded( $name );
414 * Get the internationalised name for this DBMS.
417 public function getReadableName() {
418 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite,
419 // config-type-oracle
420 return wfMessage( 'config-type-' . $this->getName() )->text();
424 * Get a name=>value map of MW configuration globals for the default values.
427 public function getGlobalDefaults() {
429 foreach ( $this->getGlobalNames() as $var ) {
430 if ( isset( $GLOBALS[$var] ) ) {
431 $defaults[$var] = $GLOBALS[$var];
438 * Get a name=>value map of internal variables used during installation.
441 public function getInternalDefaults() {
442 return $this->internalDefaults
;
446 * Get a variable, taking local defaults into account.
448 * @param mixed|null $default
451 public function getVar( $var, $default = null ) {
452 $defaults = $this->getGlobalDefaults();
453 $internal = $this->getInternalDefaults();
454 if ( isset( $defaults[$var] ) ) {
455 $default = $defaults[$var];
456 } elseif ( isset( $internal[$var] ) ) {
457 $default = $internal[$var];
460 return $this->parent
->getVar( $var, $default );
464 * Convenience alias for $this->parent->setVar()
465 * @param string $name
466 * @param mixed $value
468 public function setVar( $name, $value ) {
469 $this->parent
->setVar( $name, $value );
473 * Get a labelled text box to configure a local variable.
476 * @param string $label
477 * @param array $attribs
478 * @param string $helpData
481 public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
482 $name = $this->getName() . '_' . $var;
483 $value = $this->getVar( $var );
484 if ( !isset( $attribs ) ) {
488 return $this->parent
->getTextBox( [
491 'attribs' => $attribs,
492 'controlName' => $name,
499 * Get a labelled password box to configure a local variable.
500 * Implements password hiding.
503 * @param string $label
504 * @param array $attribs
505 * @param string $helpData
508 public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
509 $name = $this->getName() . '_' . $var;
510 $value = $this->getVar( $var );
511 if ( !isset( $attribs ) ) {
515 return $this->parent
->getPasswordBox( [
518 'attribs' => $attribs,
519 'controlName' => $name,
526 * Get a labelled checkbox to configure a local boolean variable.
529 * @param string $label
530 * @param array $attribs Optional.
531 * @param string $helpData Optional.
534 public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
535 $name = $this->getName() . '_' . $var;
536 $value = $this->getVar( $var );
538 return $this->parent
->getCheckBox( [
541 'attribs' => $attribs,
542 'controlName' => $name,
549 * Get a set of labelled radio buttons.
551 * @param array $params Parameters are:
552 * var: The variable to be configured (required)
553 * label: The message name for the label (required)
554 * itemLabelPrefix: The message name prefix for the item labels (required)
555 * values: List of allowed values (required)
556 * itemAttribs Array of attribute arrays, outer key is the value name (optional)
560 public function getRadioSet( $params ) {
561 $params['controlName'] = $this->getName() . '_' . $params['var'];
562 $params['value'] = $this->getVar( $params['var'] );
564 return $this->parent
->getRadioSet( $params );
568 * Convenience function to set variables based on form data.
569 * Assumes that variables containing "password" in the name are (potentially
571 * @param array $varNames
574 public function setVarsFromRequest( $varNames ) {
575 return $this->parent
->setVarsFromRequest( $varNames, $this->getName() . '_' );
579 * Determine whether an existing installation of MediaWiki is present in
580 * the configured administrative connection. Returns true if there is
581 * such a wiki, false if the database doesn't exist.
583 * Traditionally, this is done by testing for the existence of either
584 * the revision table or the cur table.
588 public function needsUpgrade() {
589 $status = $this->getConnection();
590 if ( !$status->isOK() ) {
594 if ( !$this->db
->selectDB( $this->getVar( 'wgDBname' ) ) ) {
598 return $this->db
->tableExists( 'cur', __METHOD__
) ||
599 $this->db
->tableExists( 'revision', __METHOD__
);
603 * Get a standard install-user fieldset.
607 public function getInstallUserBox() {
608 return Html
::openElement( 'fieldset' ) .
609 Html
::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
612 'config-db-username',
614 $this->parent
->getHelpBox( 'config-db-install-username' )
616 $this->getPasswordBox(
618 'config-db-password',
620 $this->parent
->getHelpBox( 'config-db-install-password' )
622 Html
::closeElement( 'fieldset' );
626 * Submit a standard install user fieldset.
629 public function submitInstallUserBox() {
630 $this->setVarsFromRequest( [ '_InstallUser', '_InstallPassword' ] );
632 return Status
::newGood();
636 * Get a standard web-user fieldset
637 * @param string|bool $noCreateMsg Message to display instead of the creation checkbox.
638 * Set this to false to show a creation checkbox (default).
642 public function getWebUserBox( $noCreateMsg = false ) {
643 $wrapperStyle = $this->getVar( '_SameAccount' ) ?
'display: none' : '';
644 $s = Html
::openElement( 'fieldset' ) .
645 Html
::element( 'legend', [], wfMessage( 'config-db-web-account' )->text() ) .
647 '_SameAccount', 'config-db-web-account-same',
648 [ 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' ]
650 Html
::openElement( 'div', [ 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ] ) .
651 $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
652 $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
653 $this->parent
->getHelpBox( 'config-db-web-help' );
654 if ( $noCreateMsg ) {
655 $s .= $this->parent
->getWarningBox( wfMessage( $noCreateMsg )->plain() );
657 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
659 $s .= Html
::closeElement( 'div' ) . Html
::closeElement( 'fieldset' );
665 * Submit the form from getWebUserBox().
669 public function submitWebUserBox() {
670 $this->setVarsFromRequest(
671 [ 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' ]
674 if ( $this->getVar( '_SameAccount' ) ) {
675 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
676 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
679 if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
680 return Status
::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
683 return Status
::newGood();
687 * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
691 public function populateInterwikiTable() {
692 $status = $this->getConnection();
693 if ( !$status->isOK() ) {
696 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
698 if ( $this->db
->selectRow( 'interwiki', '*', [], __METHOD__
) ) {
699 $status->warning( 'config-install-interwiki-exists' );
704 MediaWiki\
suppressWarnings();
705 $rows = file( "$IP/maintenance/interwiki.list",
706 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
);
707 MediaWiki\restoreWarnings
();
710 return Status
::newFatal( 'config-install-interwiki-list' );
712 foreach ( $rows as $row ) {
713 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
718 $interwikis[] = array_combine(
719 [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
723 $this->db
->insert( 'interwiki', $interwikis, __METHOD__
);
725 return Status
::newGood();
728 public function outputHandler( $string ) {
729 return htmlspecialchars( $string );