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
;
26 use Wikimedia\Rdbms\DBExpectedError
;
27 use Wikimedia\Rdbms\DBConnectionError
;
30 * Base class for DBMS-specific installation helper classes.
35 abstract class DatabaseInstaller
{
38 * The Installer object.
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
374 * @suppress SecurityCheck-XSS Escaping provided by $this->outputHandler
377 public function doUpgrade() {
378 $this->setupSchemaVars();
382 ob_start( [ $this, 'outputHandler' ] );
383 $up = DatabaseUpdater
::newForDB( $this->db
);
387 } catch ( MWException
$e ) {
388 echo "\nAn error occurred:\n";
391 } catch ( Exception
$e ) {
392 echo "\nAn error occurred:\n";
393 echo $e->getMessage();
402 * Allow DB installers a chance to make last-minute changes before installation
403 * occurs. This happens before setupDatabase() or createTables() is called, but
404 * long after the constructor. Helpful for things like modifying setup steps :)
406 public function preInstall() {
410 * Allow DB installers a chance to make checks before upgrade.
412 public function preUpgrade() {
416 * Get an array of MW configuration globals that will be configured by this class.
419 public function getGlobalNames() {
420 return $this->globalNames
;
424 * Construct and initialise parent.
425 * This is typically only called from Installer::getDBInstaller()
426 * @param WebInstaller $parent
428 public function __construct( $parent ) {
429 $this->parent
= $parent;
433 * Convenience function.
434 * Check if a named extension is present.
436 * @param string $name
439 protected static function checkExtension( $name ) {
440 return extension_loaded( $name );
444 * Get the internationalised name for this DBMS.
447 public function getReadableName() {
448 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite,
449 // config-type-oracle
450 return wfMessage( 'config-type-' . $this->getName() )->text();
454 * Get a name=>value map of MW configuration globals for the default values.
457 public function getGlobalDefaults() {
459 foreach ( $this->getGlobalNames() as $var ) {
460 if ( isset( $GLOBALS[$var] ) ) {
461 $defaults[$var] = $GLOBALS[$var];
468 * Get a name=>value map of internal variables used during installation.
471 public function getInternalDefaults() {
472 return $this->internalDefaults
;
476 * Get a variable, taking local defaults into account.
478 * @param mixed|null $default
481 public function getVar( $var, $default = null ) {
482 $defaults = $this->getGlobalDefaults();
483 $internal = $this->getInternalDefaults();
484 if ( isset( $defaults[$var] ) ) {
485 $default = $defaults[$var];
486 } elseif ( isset( $internal[$var] ) ) {
487 $default = $internal[$var];
490 return $this->parent
->getVar( $var, $default );
494 * Convenience alias for $this->parent->setVar()
495 * @param string $name
496 * @param mixed $value
498 public function setVar( $name, $value ) {
499 $this->parent
->setVar( $name, $value );
503 * Get a labelled text box to configure a local variable.
506 * @param string $label
507 * @param array $attribs
508 * @param string $helpData
511 public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
512 $name = $this->getName() . '_' . $var;
513 $value = $this->getVar( $var );
514 if ( !isset( $attribs ) ) {
518 return $this->parent
->getTextBox( [
521 'attribs' => $attribs,
522 'controlName' => $name,
529 * Get a labelled password box to configure a local variable.
530 * Implements password hiding.
533 * @param string $label
534 * @param array $attribs
535 * @param string $helpData
538 public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
539 $name = $this->getName() . '_' . $var;
540 $value = $this->getVar( $var );
541 if ( !isset( $attribs ) ) {
545 return $this->parent
->getPasswordBox( [
548 'attribs' => $attribs,
549 'controlName' => $name,
556 * Get a labelled checkbox to configure a local boolean variable.
559 * @param string $label
560 * @param array $attribs Optional.
561 * @param string $helpData Optional.
564 public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
565 $name = $this->getName() . '_' . $var;
566 $value = $this->getVar( $var );
568 return $this->parent
->getCheckBox( [
571 'attribs' => $attribs,
572 'controlName' => $name,
579 * Get a set of labelled radio buttons.
581 * @param array $params Parameters are:
582 * var: The variable to be configured (required)
583 * label: The message name for the label (required)
584 * itemLabelPrefix: The message name prefix for the item labels (required)
585 * values: List of allowed values (required)
586 * itemAttribs Array of attribute arrays, outer key is the value name (optional)
590 public function getRadioSet( $params ) {
591 $params['controlName'] = $this->getName() . '_' . $params['var'];
592 $params['value'] = $this->getVar( $params['var'] );
594 return $this->parent
->getRadioSet( $params );
598 * Convenience function to set variables based on form data.
599 * Assumes that variables containing "password" in the name are (potentially
601 * @param array $varNames
604 public function setVarsFromRequest( $varNames ) {
605 return $this->parent
->setVarsFromRequest( $varNames, $this->getName() . '_' );
609 * Determine whether an existing installation of MediaWiki is present in
610 * the configured administrative connection. Returns true if there is
611 * such a wiki, false if the database doesn't exist.
613 * Traditionally, this is done by testing for the existence of either
614 * the revision table or the cur table.
618 public function needsUpgrade() {
619 $status = $this->getConnection();
620 if ( !$status->isOK() ) {
625 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
626 } catch ( DBConnectionError
$e ) {
627 // Don't catch DBConnectionError
629 } catch ( DBExpectedError
$e ) {
633 return $this->db
->tableExists( 'cur', __METHOD__
) ||
634 $this->db
->tableExists( 'revision', __METHOD__
);
638 * Get a standard install-user fieldset.
642 public function getInstallUserBox() {
643 return Html
::openElement( 'fieldset' ) .
644 Html
::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
647 'config-db-username',
649 $this->parent
->getHelpBox( 'config-db-install-username' )
651 $this->getPasswordBox(
653 'config-db-password',
655 $this->parent
->getHelpBox( 'config-db-install-password' )
657 Html
::closeElement( 'fieldset' );
661 * Submit a standard install user fieldset.
664 public function submitInstallUserBox() {
665 $this->setVarsFromRequest( [ '_InstallUser', '_InstallPassword' ] );
667 return Status
::newGood();
671 * Get a standard web-user fieldset
672 * @param string|bool $noCreateMsg Message to display instead of the creation checkbox.
673 * Set this to false to show a creation checkbox (default).
677 public function getWebUserBox( $noCreateMsg = false ) {
678 $wrapperStyle = $this->getVar( '_SameAccount' ) ?
'display: none' : '';
679 $s = Html
::openElement( 'fieldset' ) .
680 Html
::element( 'legend', [], wfMessage( 'config-db-web-account' )->text() ) .
682 '_SameAccount', 'config-db-web-account-same',
683 [ 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' ]
685 Html
::openElement( 'div', [ 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ] ) .
686 $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
687 $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
688 $this->parent
->getHelpBox( 'config-db-web-help' );
689 if ( $noCreateMsg ) {
690 $s .= $this->parent
->getWarningBox( wfMessage( $noCreateMsg )->plain() );
692 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
694 $s .= Html
::closeElement( 'div' ) . Html
::closeElement( 'fieldset' );
700 * Submit the form from getWebUserBox().
704 public function submitWebUserBox() {
705 $this->setVarsFromRequest(
706 [ 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' ]
709 if ( $this->getVar( '_SameAccount' ) ) {
710 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
711 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
714 if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
715 return Status
::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
718 return Status
::newGood();
722 * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
726 public function populateInterwikiTable() {
727 $status = $this->getConnection();
728 if ( !$status->isOK() ) {
731 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
733 if ( $this->db
->selectRow( 'interwiki', '1', [], __METHOD__
) ) {
734 $status->warning( 'config-install-interwiki-exists' );
739 Wikimedia\
suppressWarnings();
740 $rows = file( "$IP/maintenance/interwiki.list",
741 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
);
742 Wikimedia\restoreWarnings
();
745 return Status
::newFatal( 'config-install-interwiki-list' );
747 foreach ( $rows as $row ) {
748 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
753 $interwikis[] = array_combine(
754 [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
758 $this->db
->insert( 'interwiki', $interwikis, __METHOD__
);
760 return Status
::newGood();
763 public function outputHandler( $string ) {
764 return htmlspecialchars( $string );