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
25 * Base class for DBMS-specific installation helper classes.
30 abstract class DatabaseInstaller
{
33 * The Installer object.
35 * @todo Naming this parent is confusing, 'installer' would be clearer.
42 * The database connection.
49 * Internal variables for installation.
53 protected $internalDefaults = [];
56 * Array of MW configuration globals this class uses.
60 protected $globalNames = [];
63 * Return the internal name, e.g. 'mysql', or 'sqlite'.
65 abstract public function getName();
68 * @return bool Returns true if the client library is compiled in.
70 abstract public function isCompiled();
73 * Checks for installation prerequisites other than those checked by isCompiled()
77 public function checkPrerequisites() {
78 return Status
::newGood();
82 * Get HTML for a web form that configures this database. Configuration
83 * at this time should be the minimum needed to connect and test
84 * whether install or upgrade is required.
86 * If this is called, $this->parent can be assumed to be a WebInstaller.
88 abstract public function getConnectForm();
91 * Set variables based on the request array, assuming it was submitted
92 * via the form returned by getConnectForm(). Validate the connection
93 * settings by attempting to connect with them.
95 * If this is called, $this->parent can be assumed to be a WebInstaller.
99 abstract public function submitConnectForm();
102 * Get HTML for a web form that retrieves settings used for installation.
103 * $this->parent can be assumed to be a WebInstaller.
104 * If the DB type has no settings beyond those already configured with
105 * getConnectForm(), this should return false.
108 public function getSettingsForm() {
113 * Set variables based on the request array, assuming it was submitted via
114 * the form return by getSettingsForm().
118 public function submitSettingsForm() {
119 return Status
::newGood();
123 * Open a connection to the database using the administrative user/password
124 * currently defined in the session, without any caching. Returns a status
125 * object. On success, the status object will contain a Database object in
130 abstract public function openConnection();
133 * Create the database and return a Status object indicating success or
138 abstract public function setupDatabase();
141 * Connect to the database using the administrative user/password currently
142 * defined in the session. Returns a status object. On success, the status
143 * object will contain a Database object in its value member.
145 * This will return a cached connection if one is available.
149 public function getConnection() {
151 return Status
::newGood( $this->db
);
154 $status = $this->openConnection();
155 if ( $status->isOK() ) {
156 $this->db
= $status->value
;
158 $this->db
->clearFlag( DBO_TRX
);
159 $this->db
->commit( __METHOD__
);
166 * Apply a SQL source file to the database as part of running an installation step.
168 * @param string $sourceFileMethod
169 * @param string $stepName
170 * @param string $archiveTableMustNotExist
173 private function stepApplySourceFile(
176 $archiveTableMustNotExist = false
178 $status = $this->getConnection();
179 if ( !$status->isOK() ) {
182 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
184 if ( $archiveTableMustNotExist && $this->db
->tableExists( 'archive', __METHOD__
) ) {
185 $status->warning( "config-$stepName-tables-exist" );
191 $this->db
->setFlag( DBO_DDLMODE
); // For Oracle's handling of schema files
192 $this->db
->begin( __METHOD__
);
194 $error = $this->db
->sourceFile(
195 call_user_func( [ $this->db
, $sourceFileMethod ] )
197 if ( $error !== true ) {
198 $this->db
->reportQueryError( $error, 0, '', __METHOD__
);
199 $this->db
->rollback( __METHOD__
);
200 $status->fatal( "config-$stepName-tables-failed", $error );
202 $this->db
->commit( __METHOD__
);
204 // Resume normal operations
205 if ( $status->isOK() ) {
213 * Create database tables from scratch.
217 public function createTables() {
218 return $this->stepApplySourceFile( 'getSchemaPath', 'install', true );
222 * Insert update keys into table to prevent running unneded updates.
226 public function insertUpdateKeys() {
227 return $this->stepApplySourceFile( 'getUpdateKeysPath', 'updates', false );
231 * Create the tables for each extension the user enabled
234 public function createExtensionTables() {
235 $status = $this->getConnection();
236 if ( !$status->isOK() ) {
240 // Now run updates to create tables for old extensions
241 DatabaseUpdater
::newForDB( $this->db
)->doUpdates( [ 'extensions' ] );
247 * Get the DBMS-specific options for LocalSettings.php generation.
251 abstract public function getLocalSettings();
254 * Override this to provide DBMS-specific schema variables, to be
255 * substituted into tables.sql and other schema files.
258 public function getSchemaVars() {
263 * Set appropriate schema variables in the current database connection.
265 * This should be called after any request data has been imported, but before
266 * any write operations to the database.
268 public function setupSchemaVars() {
269 $status = $this->getConnection();
270 if ( $status->isOK() ) {
271 $status->value
->setSchemaVars( $this->getSchemaVars() );
273 $msg = __METHOD__
. ': unexpected error while establishing'
274 . ' a database connection with message: '
275 . $status->getMessage()->plain();
276 throw new MWException( $msg );
281 * Set up LBFactory so that wfGetDB() etc. works.
282 * We set up a special LBFactory instance which returns the current
283 * installer connection.
285 public function enableLB() {
286 $status = $this->getConnection();
287 if ( !$status->isOK() ) {
288 throw new MWException( __METHOD__
. ': unexpected DB connection error' );
291 \MediaWiki\MediaWikiServices
::resetGlobalInstance();
292 $services = \MediaWiki\MediaWikiServices
::getInstance();
294 $connection = $status->value
;
295 $services->redefineService( 'DBLoadBalancerFactory', function() use ( $connection ) {
296 return new LBFactorySingle( [
297 'connection' => $connection ] );
303 * Perform database upgrades
307 public function doUpgrade() {
308 $this->setupSchemaVars();
312 ob_start( [ $this, 'outputHandler' ] );
313 $up = DatabaseUpdater
::newForDB( $this->db
);
316 } catch ( Exception
$e ) {
317 echo "\nAn error occurred:\n";
328 * Allow DB installers a chance to make last-minute changes before installation
329 * occurs. This happens before setupDatabase() or createTables() is called, but
330 * long after the constructor. Helpful for things like modifying setup steps :)
332 public function preInstall() {
336 * Allow DB installers a chance to make checks before upgrade.
338 public function preUpgrade() {
342 * Get an array of MW configuration globals that will be configured by this class.
345 public function getGlobalNames() {
346 return $this->globalNames
;
350 * Construct and initialise parent.
351 * This is typically only called from Installer::getDBInstaller()
352 * @param WebInstaller $parent
354 public function __construct( $parent ) {
355 $this->parent
= $parent;
359 * Convenience function.
360 * Check if a named extension is present.
362 * @param string $name
365 protected static function checkExtension( $name ) {
366 return extension_loaded( $name );
370 * Get the internationalised name for this DBMS.
373 public function getReadableName() {
374 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite,
375 // config-type-oracle
376 return wfMessage( 'config-type-' . $this->getName() )->text();
380 * Get a name=>value map of MW configuration globals for the default values.
383 public function getGlobalDefaults() {
385 foreach ( $this->getGlobalNames() as $var ) {
386 if ( isset( $GLOBALS[$var] ) ) {
387 $defaults[$var] = $GLOBALS[$var];
394 * Get a name=>value map of internal variables used during installation.
397 public function getInternalDefaults() {
398 return $this->internalDefaults
;
402 * Get a variable, taking local defaults into account.
404 * @param mixed|null $default
407 public function getVar( $var, $default = null ) {
408 $defaults = $this->getGlobalDefaults();
409 $internal = $this->getInternalDefaults();
410 if ( isset( $defaults[$var] ) ) {
411 $default = $defaults[$var];
412 } elseif ( isset( $internal[$var] ) ) {
413 $default = $internal[$var];
416 return $this->parent
->getVar( $var, $default );
420 * Convenience alias for $this->parent->setVar()
421 * @param string $name
422 * @param mixed $value
424 public function setVar( $name, $value ) {
425 $this->parent
->setVar( $name, $value );
429 * Get a labelled text box to configure a local variable.
432 * @param string $label
433 * @param array $attribs
434 * @param string $helpData
437 public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
438 $name = $this->getName() . '_' . $var;
439 $value = $this->getVar( $var );
440 if ( !isset( $attribs ) ) {
444 return $this->parent
->getTextBox( [
447 'attribs' => $attribs,
448 'controlName' => $name,
455 * Get a labelled password box to configure a local variable.
456 * Implements password hiding.
459 * @param string $label
460 * @param array $attribs
461 * @param string $helpData
464 public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
465 $name = $this->getName() . '_' . $var;
466 $value = $this->getVar( $var );
467 if ( !isset( $attribs ) ) {
471 return $this->parent
->getPasswordBox( [
474 'attribs' => $attribs,
475 'controlName' => $name,
482 * Get a labelled checkbox to configure a local boolean variable.
485 * @param string $label
486 * @param array $attribs Optional.
487 * @param string $helpData Optional.
490 public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
491 $name = $this->getName() . '_' . $var;
492 $value = $this->getVar( $var );
494 return $this->parent
->getCheckBox( [
497 'attribs' => $attribs,
498 'controlName' => $name,
505 * Get a set of labelled radio buttons.
507 * @param array $params Parameters are:
508 * var: The variable to be configured (required)
509 * label: The message name for the label (required)
510 * itemLabelPrefix: The message name prefix for the item labels (required)
511 * values: List of allowed values (required)
512 * itemAttribs Array of attribute arrays, outer key is the value name (optional)
516 public function getRadioSet( $params ) {
517 $params['controlName'] = $this->getName() . '_' . $params['var'];
518 $params['value'] = $this->getVar( $params['var'] );
520 return $this->parent
->getRadioSet( $params );
524 * Convenience function to set variables based on form data.
525 * Assumes that variables containing "password" in the name are (potentially
527 * @param array $varNames
530 public function setVarsFromRequest( $varNames ) {
531 return $this->parent
->setVarsFromRequest( $varNames, $this->getName() . '_' );
535 * Determine whether an existing installation of MediaWiki is present in
536 * the configured administrative connection. Returns true if there is
537 * such a wiki, false if the database doesn't exist.
539 * Traditionally, this is done by testing for the existence of either
540 * the revision table or the cur table.
544 public function needsUpgrade() {
545 $status = $this->getConnection();
546 if ( !$status->isOK() ) {
550 if ( !$this->db
->selectDB( $this->getVar( 'wgDBname' ) ) ) {
554 return $this->db
->tableExists( 'cur', __METHOD__
) ||
555 $this->db
->tableExists( 'revision', __METHOD__
);
559 * Get a standard install-user fieldset.
563 public function getInstallUserBox() {
564 return Html
::openElement( 'fieldset' ) .
565 Html
::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
568 'config-db-username',
570 $this->parent
->getHelpBox( 'config-db-install-username' )
572 $this->getPasswordBox(
574 'config-db-password',
576 $this->parent
->getHelpBox( 'config-db-install-password' )
578 Html
::closeElement( 'fieldset' );
582 * Submit a standard install user fieldset.
585 public function submitInstallUserBox() {
586 $this->setVarsFromRequest( [ '_InstallUser', '_InstallPassword' ] );
588 return Status
::newGood();
592 * Get a standard web-user fieldset
593 * @param string|bool $noCreateMsg Message to display instead of the creation checkbox.
594 * Set this to false to show a creation checkbox (default).
598 public function getWebUserBox( $noCreateMsg = false ) {
599 $wrapperStyle = $this->getVar( '_SameAccount' ) ?
'display: none' : '';
600 $s = Html
::openElement( 'fieldset' ) .
601 Html
::element( 'legend', [], wfMessage( 'config-db-web-account' )->text() ) .
603 '_SameAccount', 'config-db-web-account-same',
604 [ 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' ]
606 Html
::openElement( 'div', [ 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ] ) .
607 $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
608 $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
609 $this->parent
->getHelpBox( 'config-db-web-help' );
610 if ( $noCreateMsg ) {
611 $s .= $this->parent
->getWarningBox( wfMessage( $noCreateMsg )->plain() );
613 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
615 $s .= Html
::closeElement( 'div' ) . Html
::closeElement( 'fieldset' );
621 * Submit the form from getWebUserBox().
625 public function submitWebUserBox() {
626 $this->setVarsFromRequest(
627 [ 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' ]
630 if ( $this->getVar( '_SameAccount' ) ) {
631 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
632 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
635 if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
636 return Status
::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
639 return Status
::newGood();
643 * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
647 public function populateInterwikiTable() {
648 $status = $this->getConnection();
649 if ( !$status->isOK() ) {
652 $this->db
->selectDB( $this->getVar( 'wgDBname' ) );
654 if ( $this->db
->selectRow( 'interwiki', '*', [], __METHOD__
) ) {
655 $status->warning( 'config-install-interwiki-exists' );
660 MediaWiki\
suppressWarnings();
661 $rows = file( "$IP/maintenance/interwiki.list",
662 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
);
663 MediaWiki\restoreWarnings
();
666 return Status
::newFatal( 'config-install-interwiki-list' );
668 foreach ( $rows as $row ) {
669 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
674 $interwikis[] = array_combine(
675 [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
679 $this->db
->insert( 'interwiki', $interwikis, __METHOD__
);
681 return Status
::newGood();
684 public function outputHandler( $string ) {
685 return htmlspecialchars( $string );