Move Blob class to Rdbms namespaces
[mediawiki.git] / includes / installer / DatabaseInstaller.php
blob030553599fcd6dd26620302de7c89d75f60dd906
1 <?php
2 /**
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
20 * @file
21 * @ingroup Deployment
23 use Wikimedia\Rdbms\LBFactorySingle;
25 /**
26 * Base class for DBMS-specific installation helper classes.
28 * @ingroup Deployment
29 * @since 1.17
31 abstract class DatabaseInstaller {
33 /**
34 * The Installer object.
36 * @todo Naming this parent is confusing, 'installer' would be clearer.
38 * @var WebInstaller
40 public $parent;
42 /**
43 * The database connection.
45 * @var Database
47 public $db = null;
49 /**
50 * Internal variables for installation.
52 * @var array
54 protected $internalDefaults = [];
56 /**
57 * Array of MW configuration globals this class uses.
59 * @var array
61 protected $globalNames = [];
63 /**
64 * Return the internal name, e.g. 'mysql', or 'sqlite'.
66 abstract public function getName();
68 /**
69 * @return bool Returns true if the client library is compiled in.
71 abstract public function isCompiled();
73 /**
74 * Checks for installation prerequisites other than those checked by isCompiled()
75 * @since 1.19
76 * @return Status
78 public function checkPrerequisites() {
79 return Status::newGood();
82 /**
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();
91 /**
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.
98 * @return Status
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.
107 * @return bool
109 public function getSettingsForm() {
110 return false;
114 * Set variables based on the request array, assuming it was submitted via
115 * the form return by getSettingsForm().
117 * @return Status
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
127 * its value member.
129 * @return Status
131 abstract public function openConnection();
134 * Create the database and return a Status object indicating success or
135 * failure.
137 * @return Status
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.
148 * @return Status
150 public function getConnection() {
151 if ( $this->db ) {
152 return Status::newGood( $this->db );
155 $status = $this->openConnection();
156 if ( $status->isOK() ) {
157 $this->db = $status->value;
158 // Enable autocommit
159 $this->db->clearFlag( DBO_TRX );
160 $this->db->commit( __METHOD__ );
163 return $status;
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
172 * @return Status
174 private function stepApplySourceFile(
175 $sourceFileMethod,
176 $stepName,
177 $archiveTableMustNotExist = false
179 $status = $this->getConnection();
180 if ( !$status->isOK() ) {
181 return $status;
183 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
185 if ( $archiveTableMustNotExist && $this->db->tableExists( 'archive', __METHOD__ ) ) {
186 $status->warning( "config-$stepName-tables-exist" );
187 $this->enableLB();
189 return $status;
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 );
202 } else {
203 $this->db->commit( __METHOD__ );
205 // Resume normal operations
206 if ( $status->isOK() ) {
207 $this->enableLB();
210 return $status;
214 * Create database tables from scratch.
216 * @return Status
218 public function createTables() {
219 return $this->stepApplySourceFile( 'getSchemaPath', 'install', true );
223 * Insert update keys into table to prevent running unneded updates.
225 * @return Status
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
237 * @return string
239 private function getSqlFilePath( $db, $filename ) {
240 global $IP;
242 $dbmsSpecificFilePath = "$IP/maintenance/" . $db->getType() . "/$filename";
243 if ( file_exists( $dbmsSpecificFilePath ) ) {
244 return $dbmsSpecificFilePath;
245 } else {
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
255 * @return string
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
266 * @return string
268 public function getUpdateKeysPath( $db ) {
269 return $this->getSqlFilePath( $db, 'update-keys.sql' );
273 * Create the tables for each extension the user enabled
274 * @return Status
276 public function createExtensionTables() {
277 $status = $this->getConnection();
278 if ( !$status->isOK() ) {
279 return $status;
282 // Now run updates to create tables for old extensions
283 DatabaseUpdater::newForDB( $this->db )->doUpdates( [ 'extensions' ] );
285 return $status;
289 * Get the DBMS-specific options for LocalSettings.php generation.
291 * @return string
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.
298 * @return array
300 public function getSchemaVars() {
301 return [];
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() );
314 } else {
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 );
339 } );
343 * Perform database upgrades
345 * @return bool
347 public function doUpgrade() {
348 $this->setupSchemaVars();
349 $this->enableLB();
351 $ret = true;
352 ob_start( [ $this, 'outputHandler' ] );
353 $up = DatabaseUpdater::newForDB( $this->db );
354 try {
355 $up->doUpdates();
356 } catch ( MWException $e ) {
357 echo "\nAn error occurred:\n";
358 echo $e->getText();
359 $ret = false;
360 } catch ( Exception $e ) {
361 echo "\nAn error occurred:\n";
362 echo $e->getMessage();
363 $ret = false;
365 $up->purgeCache();
366 ob_end_flush();
368 return $ret;
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.
387 * @return array
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
407 * @return bool
409 protected static function checkExtension( $name ) {
410 return extension_loaded( $name );
414 * Get the internationalised name for this DBMS.
415 * @return string
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.
425 * @return array
427 public function getGlobalDefaults() {
428 $defaults = [];
429 foreach ( $this->getGlobalNames() as $var ) {
430 if ( isset( $GLOBALS[$var] ) ) {
431 $defaults[$var] = $GLOBALS[$var];
434 return $defaults;
438 * Get a name=>value map of internal variables used during installation.
439 * @return array
441 public function getInternalDefaults() {
442 return $this->internalDefaults;
446 * Get a variable, taking local defaults into account.
447 * @param string $var
448 * @param mixed|null $default
449 * @return mixed
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.
475 * @param string $var
476 * @param string $label
477 * @param array $attribs
478 * @param string $helpData
479 * @return string
481 public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
482 $name = $this->getName() . '_' . $var;
483 $value = $this->getVar( $var );
484 if ( !isset( $attribs ) ) {
485 $attribs = [];
488 return $this->parent->getTextBox( [
489 'var' => $var,
490 'label' => $label,
491 'attribs' => $attribs,
492 'controlName' => $name,
493 'value' => $value,
494 'help' => $helpData
495 ] );
499 * Get a labelled password box to configure a local variable.
500 * Implements password hiding.
502 * @param string $var
503 * @param string $label
504 * @param array $attribs
505 * @param string $helpData
506 * @return string
508 public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
509 $name = $this->getName() . '_' . $var;
510 $value = $this->getVar( $var );
511 if ( !isset( $attribs ) ) {
512 $attribs = [];
515 return $this->parent->getPasswordBox( [
516 'var' => $var,
517 'label' => $label,
518 'attribs' => $attribs,
519 'controlName' => $name,
520 'value' => $value,
521 'help' => $helpData
522 ] );
526 * Get a labelled checkbox to configure a local boolean variable.
528 * @param string $var
529 * @param string $label
530 * @param array $attribs Optional.
531 * @param string $helpData Optional.
532 * @return string
534 public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
535 $name = $this->getName() . '_' . $var;
536 $value = $this->getVar( $var );
538 return $this->parent->getCheckBox( [
539 'var' => $var,
540 'label' => $label,
541 'attribs' => $attribs,
542 'controlName' => $name,
543 'value' => $value,
544 'help' => $helpData
545 ] );
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)
558 * @return string
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
570 * fake) passwords.
571 * @param array $varNames
572 * @return array
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.
586 * @return bool
588 public function needsUpgrade() {
589 $status = $this->getConnection();
590 if ( !$status->isOK() ) {
591 return false;
594 if ( !$this->db->selectDB( $this->getVar( 'wgDBname' ) ) ) {
595 return false;
598 return $this->db->tableExists( 'cur', __METHOD__ ) ||
599 $this->db->tableExists( 'revision', __METHOD__ );
603 * Get a standard install-user fieldset.
605 * @return string
607 public function getInstallUserBox() {
608 return Html::openElement( 'fieldset' ) .
609 Html::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
610 $this->getTextBox(
611 '_InstallUser',
612 'config-db-username',
613 [ 'dir' => 'ltr' ],
614 $this->parent->getHelpBox( 'config-db-install-username' )
616 $this->getPasswordBox(
617 '_InstallPassword',
618 'config-db-password',
619 [ 'dir' => 'ltr' ],
620 $this->parent->getHelpBox( 'config-db-install-password' )
622 Html::closeElement( 'fieldset' );
626 * Submit a standard install user fieldset.
627 * @return Status
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).
640 * @return string
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() ) .
646 $this->getCheckBox(
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() );
656 } else {
657 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
659 $s .= Html::closeElement( 'div' ) . Html::closeElement( 'fieldset' );
661 return $s;
665 * Submit the form from getWebUserBox().
667 * @return Status
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.
689 * @return Status
691 public function populateInterwikiTable() {
692 $status = $this->getConnection();
693 if ( !$status->isOK() ) {
694 return $status;
696 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
698 if ( $this->db->selectRow( 'interwiki', '*', [], __METHOD__ ) ) {
699 $status->warning( 'config-install-interwiki-exists' );
701 return $status;
703 global $IP;
704 MediaWiki\suppressWarnings();
705 $rows = file( "$IP/maintenance/interwiki.list",
706 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
707 MediaWiki\restoreWarnings();
708 $interwikis = [];
709 if ( !$rows ) {
710 return Status::newFatal( 'config-install-interwiki-list' );
712 foreach ( $rows as $row ) {
713 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
714 if ( $row == "" ) {
715 continue;
717 $row .= "|";
718 $interwikis[] = array_combine(
719 [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
720 explode( '|', $row )
723 $this->db->insert( 'interwiki', $interwikis, __METHOD__ );
725 return Status::newGood();
728 public function outputHandler( $string ) {
729 return htmlspecialchars( $string );