Add lazy loading on Mediawiki powered-by icon
[mediawiki.git] / includes / installer / DatabaseInstaller.php
bloba3618f200e8e6785f383de579da613268f19ce4b
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 Installer
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\Rdbms\Database;
26 use Wikimedia\Rdbms\DBConnectionError;
27 use Wikimedia\Rdbms\DBExpectedError;
28 use Wikimedia\Rdbms\IDatabase;
29 use Wikimedia\Rdbms\LBFactorySingle;
31 /**
32 * Base class for DBMS-specific installation helper classes.
34 * @ingroup Installer
35 * @since 1.17
37 abstract class DatabaseInstaller {
39 /**
40 * The Installer object.
42 * @var WebInstaller
44 public $parent;
46 /**
47 * @var string Set by subclasses
49 public static $minimumVersion;
51 /**
52 * @var string Set by subclasses
54 protected static $notMinimumVersionMessage;
56 /**
57 * The database connection.
59 * @var Database
61 public $db = null;
63 /**
64 * Internal variables for installation.
66 * @var array
68 protected $internalDefaults = [];
70 /**
71 * Array of MW configuration globals this class uses.
73 * @var array
75 protected $globalNames = [];
77 /**
78 * Whether the provided version meets the necessary requirements for this type
80 * @param string $serverVersion Output of Database::getServerVersion()
81 * @return Status
82 * @since 1.30
84 public static function meetsMinimumRequirement( $serverVersion ) {
85 if ( version_compare( $serverVersion, static::$minimumVersion ) < 0 ) {
86 return Status::newFatal(
87 static::$notMinimumVersionMessage, static::$minimumVersion, $serverVersion
91 return Status::newGood();
94 /**
95 * Return the internal name, e.g. 'mysql', or 'sqlite'.
97 abstract public function getName();
99 /**
100 * @return bool Returns true if the client library is compiled in.
102 abstract public function isCompiled();
105 * Checks for installation prerequisites other than those checked by isCompiled()
106 * @since 1.19
107 * @return Status
109 public function checkPrerequisites() {
110 return Status::newGood();
114 * Get HTML for a web form that configures this database. Configuration
115 * at this time should be the minimum needed to connect and test
116 * whether install or upgrade is required.
118 * If this is called, $this->parent can be assumed to be a WebInstaller.
120 abstract public function getConnectForm();
123 * Set variables based on the request array, assuming it was submitted
124 * via the form returned by getConnectForm(). Validate the connection
125 * settings by attempting to connect with them.
127 * If this is called, $this->parent can be assumed to be a WebInstaller.
129 * @return Status
131 abstract public function submitConnectForm();
134 * Get HTML for a web form that retrieves settings used for installation.
135 * $this->parent can be assumed to be a WebInstaller.
136 * If the DB type has no settings beyond those already configured with
137 * getConnectForm(), this should return false.
138 * @return string|bool
140 public function getSettingsForm() {
141 return false;
145 * Set variables based on the request array, assuming it was submitted via
146 * the form return by getSettingsForm().
148 * @return Status
150 public function submitSettingsForm() {
151 return Status::newGood();
155 * Open a connection to the database using the administrative user/password
156 * currently defined in the session, without any caching. Returns a status
157 * object. On success, the status object will contain a Database object in
158 * its value member.
160 * @return Status
162 abstract public function openConnection();
165 * Create the database and return a Status object indicating success or
166 * failure.
168 * @return Status
170 abstract public function setupDatabase();
173 * Connect to the database using the administrative user/password currently
174 * defined in the session. Returns a status object. On success, the status
175 * object will contain a Database object in its value member.
177 * This will return a cached connection if one is available.
179 * @return Status
180 * @suppress PhanUndeclaredMethod
182 public function getConnection() {
183 if ( $this->db ) {
184 return Status::newGood( $this->db );
187 $status = $this->openConnection();
188 if ( $status->isOK() ) {
189 $this->db = $status->value;
190 // Enable autocommit
191 $this->db->clearFlag( DBO_TRX );
192 $this->db->commit( __METHOD__ );
195 return $status;
199 * Apply a SQL source file to the database as part of running an installation step.
201 * @param string $sourceFileMethod
202 * @param string $stepName
203 * @param bool $archiveTableMustNotExist
204 * @return Status
206 private function stepApplySourceFile(
207 $sourceFileMethod,
208 $stepName,
209 $archiveTableMustNotExist = false
211 $status = $this->getConnection();
212 if ( !$status->isOK() ) {
213 return $status;
215 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
217 if ( $archiveTableMustNotExist && $this->db->tableExists( 'archive', __METHOD__ ) ) {
218 $status->warning( "config-$stepName-tables-exist" );
219 $this->enableLB();
221 return $status;
224 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
225 $this->db->begin( __METHOD__ );
227 $error = $this->db->sourceFile(
228 call_user_func( [ $this, $sourceFileMethod ], $this->db )
230 if ( $error !== true ) {
231 $this->db->reportQueryError( $error, 0, '', __METHOD__ );
232 $this->db->rollback( __METHOD__ );
233 $status->fatal( "config-$stepName-tables-failed", $error );
234 } else {
235 $this->db->commit( __METHOD__ );
237 // Resume normal operations
238 if ( $status->isOK() ) {
239 $this->enableLB();
242 return $status;
246 * Create database tables from scratch.
248 * @return Status
250 public function createTables() {
251 return $this->stepApplySourceFile( 'getSchemaPath', 'install', true );
255 * Insert update keys into table to prevent running unneded updates.
257 * @return Status
259 public function insertUpdateKeys() {
260 return $this->stepApplySourceFile( 'getUpdateKeysPath', 'updates', false );
264 * Return a path to the DBMS-specific SQL file if it exists,
265 * otherwise default SQL file
267 * @param IDatabase $db
268 * @param string $filename
269 * @return string
271 private function getSqlFilePath( $db, $filename ) {
272 global $IP;
274 $dbmsSpecificFilePath = "$IP/maintenance/" . $db->getType() . "/$filename";
275 if ( file_exists( $dbmsSpecificFilePath ) ) {
276 return $dbmsSpecificFilePath;
277 } else {
278 return "$IP/maintenance/$filename";
283 * Return a path to the DBMS-specific schema file,
284 * otherwise default to tables.sql
286 * @param IDatabase $db
287 * @return string
289 public function getSchemaPath( $db ) {
290 return $this->getSqlFilePath( $db, 'tables.sql' );
294 * Return a path to the DBMS-specific update key file,
295 * otherwise default to update-keys.sql
297 * @param IDatabase $db
298 * @return string
300 public function getUpdateKeysPath( $db ) {
301 return $this->getSqlFilePath( $db, 'update-keys.sql' );
305 * Create the tables for each extension the user enabled
306 * @return Status
308 public function createExtensionTables() {
309 $status = $this->getConnection();
310 if ( !$status->isOK() ) {
311 return $status;
314 // Now run updates to create tables for old extensions
315 DatabaseUpdater::newForDB( $this->db )->doUpdates( [ 'extensions' ] );
317 return $status;
321 * Get the DBMS-specific options for LocalSettings.php generation.
323 * @return string
325 abstract public function getLocalSettings();
328 * Override this to provide DBMS-specific schema variables, to be
329 * substituted into tables.sql and other schema files.
330 * @return array
332 public function getSchemaVars() {
333 return [];
337 * Set appropriate schema variables in the current database connection.
339 * This should be called after any request data has been imported, but before
340 * any write operations to the database.
342 public function setupSchemaVars() {
343 $status = $this->getConnection();
344 if ( $status->isOK() ) {
345 // @phan-suppress-next-line PhanUndeclaredMethod
346 $status->value->setSchemaVars( $this->getSchemaVars() );
347 } else {
348 $msg = __METHOD__ . ': unexpected error while establishing'
349 . ' a database connection with message: '
350 . $status->getMessage()->plain();
351 throw new MWException( $msg );
356 * Set up LBFactory so that wfGetDB() etc. works.
357 * We set up a special LBFactory instance which returns the current
358 * installer connection.
360 public function enableLB() {
361 $status = $this->getConnection();
362 if ( !$status->isOK() ) {
363 throw new MWException( __METHOD__ . ': unexpected DB connection error' );
366 MediaWikiServices::resetGlobalInstance();
367 $services = MediaWikiServices::getInstance();
369 $connection = $status->value;
370 $services->redefineService( 'DBLoadBalancerFactory', function () use ( $connection ) {
371 return LBFactorySingle::newFromConnection( $connection );
372 } );
376 * Perform database upgrades
378 * @suppress SecurityCheck-XSS Escaping provided by $this->outputHandler
379 * @return bool
381 public function doUpgrade() {
382 $this->setupSchemaVars();
383 $this->enableLB();
385 $ret = true;
386 ob_start( [ $this, 'outputHandler' ] );
387 $up = DatabaseUpdater::newForDB( $this->db );
388 try {
389 $up->doUpdates();
390 $up->purgeCache();
391 } catch ( MWException $e ) {
392 echo "\nAn error occurred:\n";
393 echo $e->getText();
394 $ret = false;
395 } catch ( Exception $e ) {
396 echo "\nAn error occurred:\n";
397 echo $e->getMessage();
398 $ret = false;
400 ob_end_flush();
402 return $ret;
406 * Allow DB installers a chance to make last-minute changes before installation
407 * occurs. This happens before setupDatabase() or createTables() is called, but
408 * long after the constructor. Helpful for things like modifying setup steps :)
410 public function preInstall() {
414 * Allow DB installers a chance to make checks before upgrade.
416 public function preUpgrade() {
420 * Get an array of MW configuration globals that will be configured by this class.
421 * @return array
423 public function getGlobalNames() {
424 return $this->globalNames;
428 * Construct and initialise parent.
429 * This is typically only called from Installer::getDBInstaller()
430 * @param WebInstaller $parent
432 public function __construct( $parent ) {
433 $this->parent = $parent;
437 * Convenience function.
438 * Check if a named extension is present.
440 * @param string $name
441 * @return bool
443 protected static function checkExtension( $name ) {
444 return extension_loaded( $name );
448 * Get the internationalised name for this DBMS.
449 * @return string
451 public function getReadableName() {
452 // Messages: config-type-mysql, config-type-postgres, config-type-sqlite
453 return wfMessage( 'config-type-' . $this->getName() )->text();
457 * Get a name=>value map of MW configuration globals for the default values.
458 * @return array
460 public function getGlobalDefaults() {
461 $defaults = [];
462 foreach ( $this->getGlobalNames() as $var ) {
463 if ( isset( $GLOBALS[$var] ) ) {
464 $defaults[$var] = $GLOBALS[$var];
467 return $defaults;
471 * Get a name=>value map of internal variables used during installation.
472 * @return array
474 public function getInternalDefaults() {
475 return $this->internalDefaults;
479 * Get a variable, taking local defaults into account.
480 * @param string $var
481 * @param mixed|null $default
482 * @return mixed
484 public function getVar( $var, $default = null ) {
485 $defaults = $this->getGlobalDefaults();
486 $internal = $this->getInternalDefaults();
487 if ( isset( $defaults[$var] ) ) {
488 $default = $defaults[$var];
489 } elseif ( isset( $internal[$var] ) ) {
490 $default = $internal[$var];
493 return $this->parent->getVar( $var, $default );
497 * Convenience alias for $this->parent->setVar()
498 * @param string $name
499 * @param mixed $value
501 public function setVar( $name, $value ) {
502 $this->parent->setVar( $name, $value );
506 * Get a labelled text box to configure a local variable.
508 * @param string $var
509 * @param string $label
510 * @param array $attribs
511 * @param string $helpData
512 * @return string
514 public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
515 $name = $this->getName() . '_' . $var;
516 $value = $this->getVar( $var );
517 if ( !isset( $attribs ) ) {
518 $attribs = [];
521 return $this->parent->getTextBox( [
522 'var' => $var,
523 'label' => $label,
524 'attribs' => $attribs,
525 'controlName' => $name,
526 'value' => $value,
527 'help' => $helpData
528 ] );
532 * Get a labelled password box to configure a local variable.
533 * Implements password hiding.
535 * @param string $var
536 * @param string $label
537 * @param array $attribs
538 * @param string $helpData
539 * @return string
541 public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
542 $name = $this->getName() . '_' . $var;
543 $value = $this->getVar( $var );
544 if ( !isset( $attribs ) ) {
545 $attribs = [];
548 return $this->parent->getPasswordBox( [
549 'var' => $var,
550 'label' => $label,
551 'attribs' => $attribs,
552 'controlName' => $name,
553 'value' => $value,
554 'help' => $helpData
555 ] );
559 * Get a labelled checkbox to configure a local boolean variable.
561 * @param string $var
562 * @param string $label
563 * @param array $attribs Optional.
564 * @param string $helpData Optional.
565 * @return string
567 public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
568 $name = $this->getName() . '_' . $var;
569 $value = $this->getVar( $var );
571 return $this->parent->getCheckBox( [
572 'var' => $var,
573 'label' => $label,
574 'attribs' => $attribs,
575 'controlName' => $name,
576 'value' => $value,
577 'help' => $helpData
578 ] );
582 * Get a set of labelled radio buttons.
584 * @param array $params Parameters are:
585 * var: The variable to be configured (required)
586 * label: The message name for the label (required)
587 * itemLabelPrefix: The message name prefix for the item labels (required)
588 * values: List of allowed values (required)
589 * itemAttribs Array of attribute arrays, outer key is the value name (optional)
591 * @return string
593 public function getRadioSet( $params ) {
594 $params['controlName'] = $this->getName() . '_' . $params['var'];
595 $params['value'] = $this->getVar( $params['var'] );
597 return $this->parent->getRadioSet( $params );
601 * Convenience function to set variables based on form data.
602 * Assumes that variables containing "password" in the name are (potentially
603 * fake) passwords.
604 * @param array $varNames
605 * @return array
607 public function setVarsFromRequest( $varNames ) {
608 return $this->parent->setVarsFromRequest( $varNames, $this->getName() . '_' );
612 * Determine whether an existing installation of MediaWiki is present in
613 * the configured administrative connection. Returns true if there is
614 * such a wiki, false if the database doesn't exist.
616 * Traditionally, this is done by testing for the existence of either
617 * the revision table or the cur table.
619 * @return bool
621 public function needsUpgrade() {
622 $status = $this->getConnection();
623 if ( !$status->isOK() ) {
624 return false;
627 try {
628 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
629 } catch ( DBConnectionError $e ) {
630 // Don't catch DBConnectionError
631 throw $e;
632 } catch ( DBExpectedError $e ) {
633 return false;
636 return $this->db->tableExists( 'cur', __METHOD__ ) ||
637 $this->db->tableExists( 'revision', __METHOD__ );
641 * Get a standard install-user fieldset.
643 * @return string
645 public function getInstallUserBox() {
646 return Html::openElement( 'fieldset' ) .
647 Html::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
648 $this->getTextBox(
649 '_InstallUser',
650 'config-db-username',
651 [ 'dir' => 'ltr' ],
652 $this->parent->getHelpBox( 'config-db-install-username' )
654 $this->getPasswordBox(
655 '_InstallPassword',
656 'config-db-password',
657 [ 'dir' => 'ltr' ],
658 $this->parent->getHelpBox( 'config-db-install-password' )
660 Html::closeElement( 'fieldset' );
664 * Submit a standard install user fieldset.
665 * @return Status
667 public function submitInstallUserBox() {
668 $this->setVarsFromRequest( [ '_InstallUser', '_InstallPassword' ] );
670 return Status::newGood();
674 * Get a standard web-user fieldset
675 * @param string|bool $noCreateMsg Message to display instead of the creation checkbox.
676 * Set this to false to show a creation checkbox (default).
678 * @return string
680 public function getWebUserBox( $noCreateMsg = false ) {
681 $wrapperStyle = $this->getVar( '_SameAccount' ) ? 'display: none' : '';
682 $s = Html::openElement( 'fieldset' ) .
683 Html::element( 'legend', [], wfMessage( 'config-db-web-account' )->text() ) .
684 $this->getCheckBox(
685 '_SameAccount', 'config-db-web-account-same',
686 [ 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' ]
688 Html::openElement( 'div', [ 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ] ) .
689 $this->getTextBox( 'wgDBuser', 'config-db-username' ) .
690 $this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
691 $this->parent->getHelpBox( 'config-db-web-help' );
692 if ( $noCreateMsg ) {
693 $s .= Html::warningBox( wfMessage( $noCreateMsg )->plain(), 'config-warning-box' );
694 } else {
695 $s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
697 $s .= Html::closeElement( 'div' ) . Html::closeElement( 'fieldset' );
699 return $s;
703 * Submit the form from getWebUserBox().
705 * @return Status
707 public function submitWebUserBox() {
708 $this->setVarsFromRequest(
709 [ 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' ]
712 if ( $this->getVar( '_SameAccount' ) ) {
713 $this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
714 $this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
717 if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
718 return Status::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
721 return Status::newGood();
725 * Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
727 * @return Status
729 public function populateInterwikiTable() {
730 $status = $this->getConnection();
731 if ( !$status->isOK() ) {
732 return $status;
734 $this->db->selectDB( $this->getVar( 'wgDBname' ) );
736 if ( $this->db->selectRow( 'interwiki', '1', [], __METHOD__ ) ) {
737 $status->warning( 'config-install-interwiki-exists' );
739 return $status;
741 global $IP;
742 Wikimedia\suppressWarnings();
743 $rows = file( "$IP/maintenance/interwiki.list",
744 FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
745 Wikimedia\restoreWarnings();
746 $interwikis = [];
747 if ( !$rows ) {
748 return Status::newFatal( 'config-install-interwiki-list' );
750 foreach ( $rows as $row ) {
751 $row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
752 if ( $row == "" ) {
753 continue;
755 $row .= "|";
756 $interwikis[] = array_combine(
757 [ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
758 explode( '|', $row )
761 $this->db->insert( 'interwiki', $interwikis, __METHOD__ );
763 return Status::newGood();
766 public function outputHandler( $string ) {
767 return htmlspecialchars( $string );