1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
|
<?php
/**
* DBMS-specific installation helper.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Installer
*/
use Wikimedia\Rdbms\Database;
use Wikimedia\Rdbms\DBConnectionError;
use Wikimedia\Rdbms\DBExpectedError;
use Wikimedia\Rdbms\IDatabase;
use Wikimedia\Rdbms\LBFactorySingle;
/**
* Base class for DBMS-specific installation helper classes.
*
* @stable to extend
* @ingroup Installer
* @since 1.17
*/
abstract class DatabaseInstaller {
/**
* The Installer object.
*
* @var WebInstaller
*/
public $parent;
/**
* @var string Set by subclasses
*/
public static $minimumVersion;
/**
* @var string Set by subclasses
*/
protected static $notMinimumVersionMessage;
/**
* The database connection.
*
* @var Database
*/
public $db = null;
/**
* Internal variables for installation.
*
* @var array
*/
protected $internalDefaults = [];
/**
* Array of MW configuration globals this class uses.
*
* @var array
*/
protected $globalNames = [];
/**
* Whether the provided version meets the necessary requirements for this type
*
* @param string $serverVersion Output of Database::getServerVersion()
* @return Status
* @since 1.30
*/
public static function meetsMinimumRequirement( $serverVersion ) {
if ( version_compare( $serverVersion, static::$minimumVersion ) < 0 ) {
return Status::newFatal(
static::$notMinimumVersionMessage, static::$minimumVersion, $serverVersion
);
}
return Status::newGood();
}
/**
* Return the internal name, e.g. 'mysql', or 'sqlite'.
*/
abstract public function getName();
/**
* @return bool Returns true if the client library is compiled in.
*/
abstract public function isCompiled();
/**
* Checks for installation prerequisites other than those checked by isCompiled()
* @stable to override
* @since 1.19
* @return Status
*/
public function checkPrerequisites() {
return Status::newGood();
}
/**
* Get HTML for a web form that configures this database. Configuration
* at this time should be the minimum needed to connect and test
* whether install or upgrade is required.
*
* If this is called, $this->parent can be assumed to be a WebInstaller.
*/
abstract public function getConnectForm();
/**
* Set variables based on the request array, assuming it was submitted
* via the form returned by getConnectForm(). Validate the connection
* settings by attempting to connect with them.
*
* If this is called, $this->parent can be assumed to be a WebInstaller.
*
* @return Status
*/
abstract public function submitConnectForm();
/**
* Get HTML for a web form that retrieves settings used for installation.
* $this->parent can be assumed to be a WebInstaller.
* If the DB type has no settings beyond those already configured with
* getConnectForm(), this should return false.
* @stable to override
* @return string|bool
*/
public function getSettingsForm() {
return false;
}
/**
* Set variables based on the request array, assuming it was submitted via
* the form return by getSettingsForm().
* @stable to override
*
* @return Status
*/
public function submitSettingsForm() {
return Status::newGood();
}
/**
* Open a connection to the database using the administrative user/password
* currently defined in the session, without any caching. Returns a status
* object. On success, the status object will contain a Database object in
* its value member.
*
* @return Status
*/
abstract public function openConnection();
/**
* Create the database and return a Status object indicating success or
* failure.
*
* @return Status
*/
abstract public function setupDatabase();
/**
* Connect to the database using the administrative user/password currently
* defined in the session. Returns a status object. On success, the status
* object will contain a Database object in its value member.
*
* This will return a cached connection if one is available.
*
* @stable to override
* @return Status
* @suppress PhanUndeclaredMethod
*/
public function getConnection() {
if ( $this->db ) {
return Status::newGood( $this->db );
}
$status = $this->openConnection();
if ( $status->isOK() ) {
$this->db = $status->value;
// Enable autocommit
$this->db->clearFlag( DBO_TRX );
$this->db->commit( __METHOD__ );
}
return $status;
}
/**
* Apply a SQL source file to the database as part of running an installation step.
*
* @param string $sourceFileMethod
* @param string $stepName
* @param bool $archiveTableMustNotExist
* @return Status
*/
private function stepApplySourceFile(
$sourceFileMethod,
$stepName,
$archiveTableMustNotExist = false
) {
$status = $this->getConnection();
if ( !$status->isOK() ) {
return $status;
}
$this->db->selectDB( $this->getVar( 'wgDBname' ) );
if ( $archiveTableMustNotExist && $this->db->tableExists( 'archive', __METHOD__ ) ) {
$status->warning( "config-$stepName-tables-exist" );
$this->enableLB();
return $status;
}
$this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
$this->db->begin( __METHOD__ );
$error = $this->db->sourceFile(
call_user_func( [ $this, $sourceFileMethod ], $this->db )
);
if ( $error !== true ) {
$this->db->reportQueryError( $error, 0, '', __METHOD__ );
$this->db->rollback( __METHOD__ );
$status->fatal( "config-$stepName-tables-failed", $error );
} else {
$this->db->commit( __METHOD__ );
}
// Resume normal operations
if ( $status->isOK() ) {
$this->enableLB();
}
return $status;
}
/**
* Create database tables from scratch from the automatically generated file
* @stable to override
*
* @return Status
*/
public function createTables() {
return $this->stepApplySourceFile( 'getGeneratedSchemaPath', 'install', true );
}
/**
* Create database tables from scratch.
* @stable to override
*
* @return Status
*/
public function createManualTables() {
// TODO: Set "archiveTableMustNotExist" to "false" when archive table is migrated to tables.json
return $this->stepApplySourceFile( 'getSchemaPath', 'install-manual', true );
}
/**
* Insert update keys into table to prevent running unneded updates.
* @stable to override
*
* @return Status
*/
public function insertUpdateKeys() {
return $this->stepApplySourceFile( 'getUpdateKeysPath', 'updates', false );
}
/**
* Return a path to the DBMS-specific SQL file if it exists,
* otherwise default SQL file
*
* @param IDatabase $db
* @param string $filename
* @return string
*/
private function getSqlFilePath( $db, $filename ) {
global $IP;
$dbmsSpecificFilePath = "$IP/maintenance/" . $db->getType() . "/$filename";
if ( file_exists( $dbmsSpecificFilePath ) ) {
return $dbmsSpecificFilePath;
} else {
return "$IP/maintenance/$filename";
}
}
/**
* Return a path to the DBMS-specific schema file,
* otherwise default to tables.sql
* @stable to override
*
* @param IDatabase $db
* @return string
*/
public function getSchemaPath( $db ) {
return $this->getSqlFilePath( $db, 'tables.sql' );
}
/**
* Return a path to the DBMS-specific automatically generated schema file.
* @stable to override
*
* @param IDatabase $db
* @return string
*/
public function getGeneratedSchemaPath( $db ) {
return $this->getSqlFilePath( $db, 'tables-generated.sql' );
}
/**
* Return a path to the DBMS-specific update key file,
* otherwise default to update-keys.sql
* @stable to override
*
* @param IDatabase $db
* @return string
*/
public function getUpdateKeysPath( $db ) {
return $this->getSqlFilePath( $db, 'update-keys.sql' );
}
/**
* Create the tables for each extension the user enabled
* @stable to override
* @return Status
*/
public function createExtensionTables() {
$status = $this->getConnection();
if ( !$status->isOK() ) {
return $status;
}
// Now run updates to create tables for old extensions
$updater = DatabaseUpdater::newForDB( $this->db );
$updater->setAutoExtensionHookContainer( $this->parent->getAutoExtensionHookContainer() );
$updater->doUpdates( [ 'extensions' ] );
return $status;
}
/**
* Get the DBMS-specific options for LocalSettings.php generation.
*
* @return string
*/
abstract public function getLocalSettings();
/**
* Override this to provide DBMS-specific schema variables, to be
* substituted into tables.sql and other schema files.
* @stable to override
* @return array
*/
public function getSchemaVars() {
return [];
}
/**
* Set appropriate schema variables in the current database connection.
*
* This should be called after any request data has been imported, but before
* any write operations to the database.
*
* @stable to override
*/
public function setupSchemaVars() {
$status = $this->getConnection();
if ( $status->isOK() ) {
// @phan-suppress-next-line PhanUndeclaredMethod
$status->value->setSchemaVars( $this->getSchemaVars() );
} else {
$msg = __METHOD__ . ': unexpected error while establishing'
. ' a database connection with message: '
. $status->getMessage()->plain();
throw new MWException( $msg );
}
}
/**
* Set up LBFactory so that wfGetDB() etc. works.
* We set up a special LBFactory instance which returns the current
* installer connection.
*/
public function enableLB() {
$status = $this->getConnection();
if ( !$status->isOK() ) {
throw new MWException( __METHOD__ . ': unexpected DB connection error' );
}
$connection = $status->value;
$this->parent->resetMediaWikiServices( null, [
'DBLoadBalancerFactory' => function () use ( $connection ) {
return LBFactorySingle::newFromConnection( $connection );
}
] );
}
/**
* Perform database upgrades
*
* @suppress SecurityCheck-XSS Escaping provided by $this->outputHandler
* @return bool
*/
public function doUpgrade() {
$this->setupSchemaVars();
$this->enableLB();
$ret = true;
ob_start( [ $this, 'outputHandler' ] );
$up = DatabaseUpdater::newForDB( $this->db );
try {
$up->doUpdates();
$up->purgeCache();
} catch ( MWException $e ) {
echo "\nAn error occurred:\n";
echo $e->getText();
$ret = false;
} catch ( Exception $e ) {
echo "\nAn error occurred:\n";
echo $e->getMessage();
$ret = false;
}
ob_end_flush();
return $ret;
}
/**
* Allow DB installers a chance to make last-minute changes before installation
* occurs. This happens before setupDatabase() or createTables() is called, but
* long after the constructor. Helpful for things like modifying setup steps :)
* @stable to override
*/
public function preInstall() {
}
/**
* Allow DB installers a chance to make checks before upgrade.
* @stable to override
*/
public function preUpgrade() {
}
/**
* Get an array of MW configuration globals that will be configured by this class.
* @stable to override
* @return array
*/
public function getGlobalNames() {
return $this->globalNames;
}
/**
* Construct and initialise parent.
* This is typically only called from Installer::getDBInstaller()
* @stable to call
* @param WebInstaller $parent
*/
public function __construct( $parent ) {
$this->parent = $parent;
}
/**
* Convenience function.
* Check if a named extension is present.
*
* @param string $name
* @return bool
*/
protected static function checkExtension( $name ) {
return extension_loaded( $name );
}
/**
* Get the internationalised name for this DBMS.
* @stable to override
* @return string
*/
public function getReadableName() {
// Messages: config-type-mysql, config-type-postgres, config-type-sqlite
return wfMessage( 'config-type-' . $this->getName() )->text();
}
/**
* Get a name=>value map of MW configuration globals for the default values.
* @stable to override
* @return array
*/
public function getGlobalDefaults() {
$defaults = [];
foreach ( $this->getGlobalNames() as $var ) {
if ( isset( $GLOBALS[$var] ) ) {
$defaults[$var] = $GLOBALS[$var];
}
}
return $defaults;
}
/**
* Get a name=>value map of internal variables used during installation.
* @return array
*/
public function getInternalDefaults() {
return $this->internalDefaults;
}
/**
* Get a variable, taking local defaults into account.
* @param string $var
* @param mixed|null $default
* @return mixed
*/
public function getVar( $var, $default = null ) {
$defaults = $this->getGlobalDefaults();
$internal = $this->getInternalDefaults();
if ( isset( $defaults[$var] ) ) {
$default = $defaults[$var];
} elseif ( isset( $internal[$var] ) ) {
$default = $internal[$var];
}
return $this->parent->getVar( $var, $default );
}
/**
* Convenience alias for $this->parent->setVar()
* @param string $name
* @param mixed $value
*/
public function setVar( $name, $value ) {
$this->parent->setVar( $name, $value );
}
/**
* Get a labelled text box to configure a local variable.
*
* @param string $var
* @param string $label
* @param array $attribs
* @param string $helpData
* @return string
*/
public function getTextBox( $var, $label, $attribs = [], $helpData = "" ) {
$name = $this->getName() . '_' . $var;
$value = $this->getVar( $var );
if ( !isset( $attribs ) ) {
$attribs = [];
}
return $this->parent->getTextBox( [
'var' => $var,
'label' => $label,
'attribs' => $attribs,
'controlName' => $name,
'value' => $value,
'help' => $helpData
] );
}
/**
* Get a labelled password box to configure a local variable.
* Implements password hiding.
*
* @param string $var
* @param string $label
* @param array $attribs
* @param string $helpData
* @return string
*/
public function getPasswordBox( $var, $label, $attribs = [], $helpData = "" ) {
$name = $this->getName() . '_' . $var;
$value = $this->getVar( $var );
if ( !isset( $attribs ) ) {
$attribs = [];
}
return $this->parent->getPasswordBox( [
'var' => $var,
'label' => $label,
'attribs' => $attribs,
'controlName' => $name,
'value' => $value,
'help' => $helpData
] );
}
/**
* Get a labelled checkbox to configure a local boolean variable.
*
* @param string $var
* @param string $label
* @param array $attribs Optional.
* @param string $helpData Optional.
* @return string
*/
public function getCheckBox( $var, $label, $attribs = [], $helpData = "" ) {
$name = $this->getName() . '_' . $var;
$value = $this->getVar( $var );
return $this->parent->getCheckBox( [
'var' => $var,
'label' => $label,
'attribs' => $attribs,
'controlName' => $name,
'value' => $value,
'help' => $helpData
] );
}
/**
* Get a set of labelled radio buttons.
*
* @param array $params Parameters are:
* var: The variable to be configured (required)
* label: The message name for the label (required)
* itemLabelPrefix: The message name prefix for the item labels (required)
* values: List of allowed values (required)
* itemAttribs Array of attribute arrays, outer key is the value name (optional)
*
* @return string
*/
public function getRadioSet( $params ) {
$params['controlName'] = $this->getName() . '_' . $params['var'];
$params['value'] = $this->getVar( $params['var'] );
return $this->parent->getRadioSet( $params );
}
/**
* Convenience function to set variables based on form data.
* Assumes that variables containing "password" in the name are (potentially
* fake) passwords.
* @param array $varNames
* @return array
*/
public function setVarsFromRequest( $varNames ) {
return $this->parent->setVarsFromRequest( $varNames, $this->getName() . '_' );
}
/**
* Determine whether an existing installation of MediaWiki is present in
* the configured administrative connection. Returns true if there is
* such a wiki, false if the database doesn't exist.
*
* Traditionally, this is done by testing for the existence of either
* the revision table or the cur table.
*
* @stable to override
* @return bool
*/
public function needsUpgrade() {
$status = $this->getConnection();
if ( !$status->isOK() ) {
return false;
}
try {
$this->db->selectDB( $this->getVar( 'wgDBname' ) );
} catch ( DBConnectionError $e ) {
// Don't catch DBConnectionError
throw $e;
} catch ( DBExpectedError $e ) {
return false;
}
return $this->db->tableExists( 'cur', __METHOD__ ) ||
$this->db->tableExists( 'revision', __METHOD__ );
}
/**
* Get a standard install-user fieldset.
*
* @return string
*/
public function getInstallUserBox() {
return Html::openElement( 'fieldset' ) .
Html::element( 'legend', [], wfMessage( 'config-db-install-account' )->text() ) .
$this->getTextBox(
'_InstallUser',
'config-db-username',
[ 'dir' => 'ltr' ],
$this->parent->getHelpBox( 'config-db-install-username' )
) .
$this->getPasswordBox(
'_InstallPassword',
'config-db-password',
[ 'dir' => 'ltr' ],
$this->parent->getHelpBox( 'config-db-install-password' )
) .
Html::closeElement( 'fieldset' );
}
/**
* Submit a standard install user fieldset.
* @return Status
*/
public function submitInstallUserBox() {
$this->setVarsFromRequest( [ '_InstallUser', '_InstallPassword' ] );
return Status::newGood();
}
/**
* Get a standard web-user fieldset
* @param string|bool $noCreateMsg Message to display instead of the creation checkbox.
* Set this to false to show a creation checkbox (default).
*
* @return string
*/
public function getWebUserBox( $noCreateMsg = false ) {
$wrapperStyle = $this->getVar( '_SameAccount' ) ? 'display: none' : '';
$s = Html::openElement( 'fieldset' ) .
Html::element( 'legend', [], wfMessage( 'config-db-web-account' )->text() ) .
$this->getCheckBox(
'_SameAccount', 'config-db-web-account-same',
[ 'class' => 'hideShowRadio', 'rel' => 'dbOtherAccount' ]
) .
Html::openElement( 'div', [ 'id' => 'dbOtherAccount', 'style' => $wrapperStyle ] ) .
$this->getTextBox( 'wgDBuser', 'config-db-username' ) .
$this->getPasswordBox( 'wgDBpassword', 'config-db-password' ) .
$this->parent->getHelpBox( 'config-db-web-help' );
if ( $noCreateMsg ) {
$s .= Html::warningBox( wfMessage( $noCreateMsg )->plain(), 'config-warning-box' );
} else {
$s .= $this->getCheckBox( '_CreateDBAccount', 'config-db-web-create' );
}
$s .= Html::closeElement( 'div' ) . Html::closeElement( 'fieldset' );
return $s;
}
/**
* Submit the form from getWebUserBox().
*
* @return Status
*/
public function submitWebUserBox() {
$this->setVarsFromRequest(
[ 'wgDBuser', 'wgDBpassword', '_SameAccount', '_CreateDBAccount' ]
);
if ( $this->getVar( '_SameAccount' ) ) {
$this->setVar( 'wgDBuser', $this->getVar( '_InstallUser' ) );
$this->setVar( 'wgDBpassword', $this->getVar( '_InstallPassword' ) );
}
if ( $this->getVar( '_CreateDBAccount' ) && strval( $this->getVar( 'wgDBpassword' ) ) == '' ) {
return Status::newFatal( 'config-db-password-empty', $this->getVar( 'wgDBuser' ) );
}
return Status::newGood();
}
/**
* Common function for databases that don't understand the MySQLish syntax of interwiki.sql.
* @stable to override
*
* @return Status
*/
public function populateInterwikiTable() {
$status = $this->getConnection();
if ( !$status->isOK() ) {
return $status;
}
$this->db->selectDB( $this->getVar( 'wgDBname' ) );
if ( $this->db->selectRow( 'interwiki', '1', [], __METHOD__ ) ) {
$status->warning( 'config-install-interwiki-exists' );
return $status;
}
global $IP;
Wikimedia\suppressWarnings();
$rows = file( "$IP/maintenance/interwiki.list",
FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
Wikimedia\restoreWarnings();
$interwikis = [];
if ( !$rows ) {
return Status::newFatal( 'config-install-interwiki-list' );
}
foreach ( $rows as $row ) {
$row = preg_replace( '/^\s*([^#]*?)\s*(#.*)?$/', '\\1', $row ); // strip comments - whee
if ( $row == "" ) {
continue;
}
$row .= "|";
$interwikis[] = array_combine(
[ 'iw_prefix', 'iw_url', 'iw_local', 'iw_api', 'iw_wikiid' ],
explode( '|', $row )
);
}
$this->db->insert( 'interwiki', $interwikis, __METHOD__ );
return Status::newGood();
}
public function outputHandler( $string ) {
return htmlspecialchars( $string );
}
}
|