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
;
24 use Wikimedia\Rdbms\Database
;
25 use Wikimedia\Rdbms\IDatabase
;
28 * Base class for DBMS-specific installation helper classes.
33 abstract class DatabaseInstaller
{
36 * The Installer object.
38 * @todo Naming this parent is confusing, 'installer' would be clearer.
45 * @var string Set by subclasses
47 public static $minimumVersion;
50 * @var string Set by subclasses
52 protected static $notMiniumumVerisonMessage;
55 * The database connection.
62 * Internal variables for installation.
66 protected $internalDefaults = [];
69 * Array of MW configuration globals this class uses.
73 protected $globalNames = [];
76 * Whether the provided version meets the necessary requirements for this type
78 * @param string $serverVersion Output of Database::getServerVersion()
82 public static function meetsMinimumRequirement( $serverVersion ) {
83 if ( version_compare( $serverVersion, static::$minimumVersion ) < 0 ) {
84 return Status
::newFatal(
85 static::$notMiniumumVerisonMessage, static::$minimumVersion, $serverVersion
89 return Status
::newGood();
93 * Return the internal name, e.g. 'mysql', or 'sqlite'.
95 abstract public function getName();
98 * @return bool Returns true if the client library is compiled in.
100 abstract public function isCompiled();
103 * Checks for installation prerequisites other than those checked by isCompiled()
107 public function checkPrerequisites() {
108 return Status
::newGood();
112 * Get HTML for a web form that configures this database. Configuration
113 * at this time should be the minimum needed to connect and test
114 * whether install or upgrade is required.
116 * If this is called, $this->parent can be assumed to be a WebInstaller.
118 abstract public function getConnectForm();
121 * Set variables based on the request array, assuming it was submitted
122 * via the form returned by getConnectForm(). Validate the connection
123 * settings by attempting to connect with them.
125 * If this is called, $this->parent can be assumed to be a WebInstaller.
129 abstract public function submitConnectForm();
132 * Get HTML for a web form that retrieves settings used for installation.
133 * $this->parent can be assumed to be a WebInstaller.
134 * If the DB type has no settings beyond those already configured with
135 * getConnectForm(), this should return false.
138 public function getSettingsForm() {
143 * Set variables based on the request array, assuming it was submitted via
144 * the form return by getSettingsForm().
148 public function submitSettingsForm() {
149 return Status
::newGood();
153 * Open a connection to the database using the administrative user/password
154 * currently defined in the session, without any caching. Returns a status
155 * object. On success, the status object will contain a Database object in
160 abstract public function openConnection();
163 * Create the database and return a Status object indicating success or
168 abstract public function setupDatabase();
171 * Connect to the database using the administrative user/password currently
172 * defined in the session. Returns a status object. On success, the status
173 * object will contain a Database object in its value member.
175 * This will return a cached connection if one is available.
179 public function getConnection() {
181 return Status
::newGood( $this->db
);
184 $status = $this->openConnection();
185 if ( $status->isOK() ) {
186 $this->db
= $status->value
;
188 $this->db
->clearFlag( DBO_TRX
);
189 $this->db
->commit( __METHOD__
);
196 * Apply a SQL source file to the database as part of running an installation step.
198 * @param string $sourceFileMethod
199 * @param string $stepName
200 * @param bool $archiveTableMustNotExist
203 private function stepApplySourceFile(
206 $archiveTableMustNotExist = false
208 $status = $this->getConnection();
209 if ( !$status->isOK() ) {
212 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
214 if ( $archiveTableMustNotExist && $this->db
->tableExists( 'archive', __METHOD__
) ) {
215 $status->warning( "config-$stepName-tables-exist" );
221 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
222 $this->db
->begin( __METHOD__
);
224 $error = $this->db
->sourceFile(
225 call_user_func( [ $this, $sourceFileMethod ], $this->db
)
227 if ( $error !== true ) {
228 $this->db
->reportQueryError( $error, 0, '', __METHOD__
);
229 $this->db
->rollback( __METHOD__
);
230 $status->fatal( "config-$stepName-tables-failed", $error );
232 $this->db
->commit( __METHOD__
);
234 // Resume normal operations
235 if ( $status->isOK() ) {
243 * Create database tables from scratch.
247 public function createTables() {
248 return $this->stepApplySourceFile( 'getSchemaPath', 'install', true );
252 * Insert update keys into table to prevent running unneded updates.
256 public function insertUpdateKeys() {
257 return $this->stepApplySourceFile( 'getUpdateKeysPath', 'updates', false );
261 * Return a path to the DBMS-specific SQL file if it exists,
262 * otherwise default SQL file
264 * @param IDatabase $db
265 * @param string $filename
268 private function getSqlFilePath( $db, $filename ) {
271 $dbmsSpecificFilePath = "$IP/maintenance/" . $db->getType() . "/$filename";
272 if ( file_exists( $dbmsSpecificFilePath ) ) {
273 return $dbmsSpecificFilePath;
275 return "$IP/maintenance/$filename";
280 * Return a path to the DBMS-specific schema file,
281 * otherwise default to tables.sql
283 * @param IDatabase $db
286 public function getSchemaPath( $db ) {
287 return $this->getSqlFilePath( $db, 'tables.sql' );
291 * Return a path to the DBMS-specific update key file,
292 * otherwise default to update-keys.sql
294 * @param IDatabase $db
297 public function getUpdateKeysPath( $db ) {
298 return $this->getSqlFilePath( $db, 'update-keys.sql' );
302 * Create the tables for each extension the user enabled
305 public function createExtensionTables() {
306 $status = $this->getConnection();
307 if ( !$status->isOK() ) {
311 // Now run updates to create tables for old extensions
312 DatabaseUpdater
::newForDB( $this->db
)->doUpdates( [ 'extensions' ] );
318 * Get the DBMS-specific options for LocalSettings.php generation.
322 abstract public function getLocalSettings();
325 * Override this to provide DBMS-specific schema variables, to be
326 * substituted into tables.sql and other schema files.
329 public function getSchemaVars() {
334 * Set appropriate schema variables in the current database connection.
336 * This should be called after any request data has been imported, but before
337 * any write operations to the database.
339 public function setupSchemaVars() {
340 $status = $this->getConnection();
341 if ( $status->isOK() ) {
342 $status->value
->setSchemaVars( $this->getSchemaVars() );
344 $msg = __METHOD__
. ': unexpected error while establishing'
345 . ' a database connection with message: '
346 . $status->getMessage()->plain();
347 throw new MWException( $msg );
352 * Set up LBFactory so that wfGetDB() etc. works.
353 * We set up a special LBFactory instance which returns the current
354 * installer connection.
356 public function enableLB() {
357 $status = $this->getConnection();
358 if ( !$status->isOK() ) {
359 throw new MWException( __METHOD__
. ': unexpected DB connection error' );
362 \MediaWiki\MediaWikiServices
::resetGlobalInstance();
363 $services = \MediaWiki\MediaWikiServices
::getInstance();
365 $connection = $status->value
;
366 $services->redefineService( 'DBLoadBalancerFactory', function () use ( $connection ) {
367 return LBFactorySingle
::newFromConnection( $connection );
372 * Perform database upgrades
376 public function doUpgrade() {
377 $this->setupSchemaVars();
381 ob_start( [ $this, 'outputHandler' ] );
382 $up = DatabaseUpdater
::newForDB( $this->db
);
385 } catch ( MWException
$e ) {
386 echo "\nAn error occurred:\n";
389 } catch ( Exception
$e ) {
390 echo "\nAn error occurred:\n";
391 echo $e->getMessage();
401 * Allow DB installers a chance to make last-minute changes before installation
402 * occurs. This happens before setupDatabase() or createTables() is called, but
403 * long after the constructor. Helpful for things like modifying setup steps :)
405 public function preInstall() {
409 * Allow DB installers a chance to make checks before upgrade.
411 public function preUpgrade() {
415 * Get an array of MW configuration globals that will be configured by this class.
418 public function getGlobalNames() {
419 return $this->globalNames
;
423 * Construct and initialise parent.
424 * This is typically only called from Installer::getDBInstaller()
425 * @param WebInstaller $parent
427 public function __construct( $parent ) {
428 $this->parent
= $parent;
432 * Convenience function.
433 * Check if a named extension is present.
435 * @param string $name
438 protected static function checkExtension( $name ) {
439 return extension_loaded( $name );
443 * Get the internationalised name for this DBMS.
446 public function getReadableName() {
447 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite,
448 // config-type-oracle
449 return wfMessage( 'config-type-' . $this->getName() )->text();
453 * Get a name=>value map of MW configuration globals for the default values.
456 public function getGlobalDefaults() {
458 foreach ( $this->getGlobalNames() as $var ) {
459 if ( isset( $GLOBALS[$var] ) ) {
460 $defaults[$var] = $GLOBALS[$var];
467 * Get a name=>value map of internal variables used during installation.
470 public function getInternalDefaults() {
471 return $this->internalDefaults
;
475 * Get a variable, taking local defaults into account.
477 * @param mixed|null $default
480 public function getVar( $var, $default = null ) {
481 $defaults = $this->getGlobalDefaults();
482 $internal = $this->getInternalDefaults();
483 if ( isset( $defaults[$var] ) ) {
484 $default = $defaults[$var];
485 } elseif ( isset( $internal[$var] ) ) {
486 $default = $internal[$var];
489 return $this->parent
->getVar( $var, $default );
493 * Convenience alias for $this->parent->setVar()
494 * @param string $name
495 * @param mixed $value
497 public function setVar( $name, $value ) {
498 $this->parent
->setVar( $name, $value );
502 * Get a labelled text box to configure a local variable.
505 * @param string $label
506 * @param array $attribs
507 * @param string $helpData
510 public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
511 $name = $this->getName() . '_' . $var;
512 $value = $this->getVar( $var );
513 if ( !isset( $attribs ) ) {
517 return $this->parent
->getTextBox( [
520 'attribs' => $attribs,
521 'controlName' => $name,
528 * Get a labelled password box to configure a local variable.
529 * Implements password hiding.
532 * @param string $label
533 * @param array $attribs
534 * @param string $helpData
537 public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
538 $name = $this->getName() . '_' . $var;
539 $value = $this->getVar( $var );
540 if ( !isset( $attribs ) ) {
544 return $this->parent
->getPasswordBox( [
547 'attribs' => $attribs,
548 'controlName' => $name,
555 * Get a labelled checkbox to configure a local boolean variable.
558 * @param string $label
559 * @param array $attribs Optional.
560 * @param string $helpData Optional.
563 public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
564 $name = $this->getName() . '_' . $var;
565 $value = $this->getVar( $var );
567 return $this->parent
->getCheckBox( [
570 'attribs' => $attribs,
571 'controlName' => $name,
578 * Get a set of labelled radio buttons.
580 * @param array $params Parameters are:
581 * var: The variable to be configured (required)
582 * label: The message name for the label (required)
583 * itemLabelPrefix: The message name prefix for the item labels (required)
584 * values: List of allowed values (required)
585 * itemAttribs Array of attribute arrays, outer key is the value name (optional)
589 public function getRadioSet( $params ) {
590 $params['controlName'] = $this->getName() . '_' . $params['var'];
591 $params['value'] = $this->getVar( $params['var'] );
593 return $this->parent
->getRadioSet( $params );
597 * Convenience function to set variables based on form data.
598 * Assumes that variables containing "password" in the name are (potentially
600 * @param array $varNames
603 public function setVarsFromRequest( $varNames ) {
604 return $this->parent
->setVarsFromRequest( $varNames, $this->getName() . '_' );
608 * Determine whether an existing installation of MediaWiki is present in
609 * the configured administrative connection. Returns true if there is
610 * such a wiki, false if the database doesn't exist.
612 * Traditionally, this is done by testing for the existence of either
613 * the revision table or the cur table.
617 public function needsUpgrade() {
618 $status = $this->getConnection();
619 if ( !$status->isOK() ) {
623 if ( !$this->db
->selectDB( $this->getVar( 'wgDBname' ) ) ) {
627 return $this->db
->tableExists( 'cur', __METHOD__
) ||
628 $this->db
->tableExists( 'revision', __METHOD__
);
632 * Get a standard install-user fieldset.
636 public function getInstallUserBox() {
637 return Html
::openElement( 'fieldset' ) .
638 Html
::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
641 'config-db-username',
643 $this->parent
->getHelpBox( 'config-db-install-username' )
645 $this->getPasswordBox(
647 'config-db-password',
649 $this->parent
->getHelpBox( 'config-db-install-password' )
651 Html
::closeElement( 'fieldset' );
655 * Submit a standard install user fieldset.
658 public function submitInstallUserBox() {
659 $this->setVarsFromRequest( [ '_InstallUser', '_InstallPassword' ] );
661 return Status
::newGood();
665 * Get a standard web-user fieldset
666 * @param string|bool $noCreateMsg Message to display instead of the creation checkbox.
667 * Set this to false to show a creation checkbox (default).
671 public function getWebUserBox( $noCreateMsg = false ) {
672 $wrapperStyle = $this->getVar( '_SameAccount' ) ?
'display: none' : '';
673 $s = Html
::openElement( 'fieldset' ) .
674 Html
::element( 'legend', [], wfMessage( 'config-db-web-account' )->text() ) .
676 '_SameAccount', 'config-db-web-account-same',
677 [ 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' ]
679 Html
::openElement( 'div', [ 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ] ) .
680 $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
681 $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
682 $this->parent
->getHelpBox( 'config-db-web-help' );
683 if ( $noCreateMsg ) {
684 $s .= $this->parent
->getWarningBox( wfMessage( $noCreateMsg )->plain() );
686 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
688 $s .= Html
::closeElement( 'div' ) . Html
::closeElement( 'fieldset' );
694 * Submit the form from getWebUserBox().
698 public function submitWebUserBox() {
699 $this->setVarsFromRequest(
700 [ 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' ]
703 if ( $this->getVar( '_SameAccount' ) ) {
704 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
705 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
708 if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
709 return Status
::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
712 return Status
::newGood();
716 * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
720 public function populateInterwikiTable() {
721 $status = $this->getConnection();
722 if ( !$status->isOK() ) {
725 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
727 if ( $this->db
->selectRow( 'interwiki', '1', [], __METHOD__
) ) {
728 $status->warning( 'config-install-interwiki-exists' );
733 Wikimedia\
suppressWarnings();
734 $rows = file( "$IP/maintenance/interwiki.list",
735 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
);
736 Wikimedia\restoreWarnings
();
739 return Status
::newFatal( 'config-install-interwiki-list' );
741 foreach ( $rows as $row ) {
742 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
747 $interwikis[] = array_combine(
748 [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
752 $this->db
->insert( 'interwiki', $interwikis, __METHOD__
);
754 return Status
::newGood();
757 public function outputHandler( $string ) {
758 return htmlspecialchars( $string );