3 * MySQL-specific installer.
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
24 use Wikimedia\Rdbms\Database
;
25 use Wikimedia\Rdbms\DBQueryError
;
26 use Wikimedia\Rdbms\DBConnectionError
;
29 * Class for setting up the MediaWiki database using MySQL.
34 class MysqlInstaller
extends DatabaseInstaller
{
36 protected $globalNames = [
46 protected $internalDefaults = [
47 '_MysqlEngine' => 'InnoDB',
48 '_MysqlCharset' => 'binary',
49 '_InstallUser' => 'root',
52 public $supportedEngines = [ 'InnoDB', 'MyISAM' ];
54 public $minimumVersion = '5.0.3';
56 public $webUserPrivs = [
61 'CREATE TEMPORARY TABLES',
67 public function getName() {
74 public function isCompiled() {
75 return self
::checkExtension( 'mysql' ) || self
::checkExtension( 'mysqli' );
81 public function getConnectForm() {
82 return $this->getTextBox(
86 $this->parent
->getHelpBox( 'config-db-host-help' )
88 Html
::openElement( 'fieldset' ) .
89 Html
::element( 'legend', [], wfMessage( 'config-db-wiki-settings' )->text() ) .
90 $this->getTextBox( 'wgDBname', 'config-db-name', [ 'dir' => 'ltr' ],
91 $this->parent
->getHelpBox( 'config-db-name-help' ) ) .
92 $this->getTextBox( 'wgDBprefix', 'config-db-prefix', [ 'dir' => 'ltr' ],
93 $this->parent
->getHelpBox( 'config-db-prefix-help' ) ) .
94 Html
::closeElement( 'fieldset' ) .
95 $this->getInstallUserBox();
98 public function submitConnectForm() {
99 // Get variables from the request.
100 $newValues = $this->setVarsFromRequest( [ 'wgDBserver', 'wgDBname', 'wgDBprefix' ] );
103 $status = Status
::newGood();
104 if ( !strlen( $newValues['wgDBserver'] ) ) {
105 $status->fatal( 'config-missing-db-host' );
107 if ( !strlen( $newValues['wgDBname'] ) ) {
108 $status->fatal( 'config-missing-db-name' );
109 } elseif ( !preg_match( '/^[a-z0-9+_-]+$/i', $newValues['wgDBname'] ) ) {
110 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
112 if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
113 $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
115 if ( !$status->isOK() ) {
120 $status = $this->submitInstallUserBox();
121 if ( !$status->isOK() ) {
126 $status = $this->getConnection();
127 if ( !$status->isOK() ) {
131 * @var $conn Database
133 $conn = $status->value
;
136 $version = $conn->getServerVersion();
137 if ( version_compare( $version, $this->minimumVersion
) < 0 ) {
138 return Status
::newFatal( 'config-mysql-old', $this->minimumVersion
, $version );
147 public function openConnection() {
148 $status = Status
::newGood();
150 $db = Database
::factory( 'mysql', [
151 'host' => $this->getVar( 'wgDBserver' ),
152 'user' => $this->getVar( '_InstallUser' ),
153 'password' => $this->getVar( '_InstallPassword' ),
156 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ] );
157 $status->value
= $db;
158 } catch ( DBConnectionError
$e ) {
159 $status->fatal( 'config-connection-error', $e->getMessage() );
165 public function preUpgrade() {
166 global $wgDBuser, $wgDBpassword;
168 $status = $this->getConnection();
169 if ( !$status->isOK() ) {
170 $this->parent
->showStatusError( $status );
175 * @var $conn Database
177 $conn = $status->value
;
178 $conn->selectDB( $this->getVar( 'wgDBname' ) );
180 # Determine existing default character set
181 if ( $conn->tableExists( "revision", __METHOD__
) ) {
182 $revision = $conn->buildLike( $this->getVar( 'wgDBprefix' ) . 'revision' );
183 $res = $conn->query( "SHOW TABLE STATUS $revision", __METHOD__
);
184 $row = $conn->fetchObject( $res );
186 $this->parent
->showMessage( 'config-show-table-status' );
187 $existingSchema = false;
188 $existingEngine = false;
190 if ( preg_match( '/^latin1/', $row->Collation
) ) {
191 $existingSchema = 'latin1';
192 } elseif ( preg_match( '/^utf8/', $row->Collation
) ) {
193 $existingSchema = 'utf8';
194 } elseif ( preg_match( '/^binary/', $row->Collation
) ) {
195 $existingSchema = 'binary';
197 $existingSchema = false;
198 $this->parent
->showMessage( 'config-unknown-collation' );
200 if ( isset( $row->Engine
) ) {
201 $existingEngine = $row->Engine
;
203 $existingEngine = $row->Type
;
207 $existingSchema = false;
208 $existingEngine = false;
211 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
212 $this->setVar( '_MysqlCharset', $existingSchema );
214 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
215 $this->setVar( '_MysqlEngine', $existingEngine );
218 # Normal user and password are selected after this step, so for now
219 # just copy these two
220 $wgDBuser = $this->getVar( '_InstallUser' );
221 $wgDBpassword = $this->getVar( '_InstallPassword' );
225 * Get a list of storage engines that are available and supported
229 public function getEngines() {
230 $status = $this->getConnection();
233 * @var $conn Database
235 $conn = $status->value
;
238 $res = $conn->query( 'SHOW ENGINES', __METHOD__
);
239 foreach ( $res as $row ) {
240 if ( $row->Support
== 'YES' ||
$row->Support
== 'DEFAULT' ) {
241 $engines[] = $row->Engine
;
244 $engines = array_intersect( $this->supportedEngines
, $engines );
250 * Get a list of character sets that are available and supported
254 public function getCharsets() {
255 return [ 'binary', 'utf8' ];
259 * Return true if the install user can create accounts
263 public function canCreateAccounts() {
264 $status = $this->getConnection();
265 if ( !$status->isOK() ) {
268 /** @var $conn Database */
269 $conn = $status->value
;
271 // Get current account name
272 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__
);
273 $parts = explode( '@', $currentName );
274 if ( count( $parts ) != 2 ) {
277 $quotedUser = $conn->addQuotes( $parts[0] ) .
278 '@' . $conn->addQuotes( $parts[1] );
280 // The user needs to have INSERT on mysql.* to be able to CREATE USER
281 // The grantee will be double-quoted in this query, as required
282 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
283 [ 'GRANTEE' => $quotedUser ], __METHOD__
);
284 $insertMysql = false;
285 $grantOptions = array_flip( $this->webUserPrivs
);
286 foreach ( $res as $row ) {
287 if ( $row->PRIVILEGE_TYPE
== 'INSERT' ) {
290 if ( $row->IS_GRANTABLE
) {
291 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
295 // Check for DB-specific privs for mysql.*
296 if ( !$insertMysql ) {
297 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
299 'GRANTEE' => $quotedUser,
300 'TABLE_SCHEMA' => 'mysql',
301 'PRIVILEGE_TYPE' => 'INSERT',
308 if ( !$insertMysql ) {
312 // Check for DB-level grant options
313 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
315 'GRANTEE' => $quotedUser,
318 foreach ( $res as $row ) {
319 $regex = $this->likeToRegex( $row->TABLE_SCHEMA
);
320 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
321 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
324 if ( count( $grantOptions ) ) {
325 // Can't grant everything
333 * Convert a wildcard (as used in LIKE) to a regex
334 * Slashes are escaped, slash terminators included
336 protected function likeToRegex( $wildcard ) {
337 $r = preg_quote( $wildcard, '/' );
348 public function getSettingsForm() {
349 if ( $this->canCreateAccounts() ) {
350 $noCreateMsg = false;
352 $noCreateMsg = 'config-db-web-no-create-privs';
354 $s = $this->getWebUserBox( $noCreateMsg );
356 // Do engine selector
357 $engines = $this->getEngines();
358 // If the current default engine is not supported, use an engine that is
359 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
360 $this->setVar( '_MysqlEngine', reset( $engines ) );
363 $s .= Xml
::openElement( 'div', [
364 'id' => 'dbMyisamWarning'
366 $myisamWarning = 'config-mysql-myisam-dep';
367 if ( count( $engines ) === 1 ) {
368 $myisamWarning = 'config-mysql-only-myisam-dep';
370 $s .= $this->parent
->getWarningBox( wfMessage( $myisamWarning )->text() );
371 $s .= Xml
::closeElement( 'div' );
373 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
374 $s .= Xml
::openElement( 'script' );
375 $s .= '$(\'#dbMyisamWarning\').hide();';
376 $s .= Xml
::closeElement( 'script' );
379 if ( count( $engines ) >= 2 ) {
380 // getRadioSet() builds a set of labeled radio buttons.
381 // For grep: The following messages are used as the item labels:
382 // config-mysql-innodb, config-mysql-myisam
383 $s .= $this->getRadioSet( [
384 'var' => '_MysqlEngine',
385 'label' => 'config-mysql-engine',
386 'itemLabelPrefix' => 'config-mysql-',
387 'values' => $engines,
390 'class' => 'showHideRadio',
391 'rel' => 'dbMyisamWarning'
394 'class' => 'hideShowRadio',
395 'rel' => 'dbMyisamWarning'
399 $s .= $this->parent
->getHelpBox( 'config-mysql-engine-help' );
402 // If the current default charset is not supported, use a charset that is
403 $charsets = $this->getCharsets();
404 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
405 $this->setVar( '_MysqlCharset', reset( $charsets ) );
408 // Do charset selector
409 if ( count( $charsets ) >= 2 ) {
410 // getRadioSet() builds a set of labeled radio buttons.
411 // For grep: The following messages are used as the item labels:
412 // config-mysql-binary, config-mysql-utf8
413 $s .= $this->getRadioSet( [
414 'var' => '_MysqlCharset',
415 'label' => 'config-mysql-charset',
416 'itemLabelPrefix' => 'config-mysql-',
417 'values' => $charsets
419 $s .= $this->parent
->getHelpBox( 'config-mysql-charset-help' );
428 public function submitSettingsForm() {
429 $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
430 $status = $this->submitWebUserBox();
431 if ( !$status->isOK() ) {
435 // Validate the create checkbox
436 $canCreate = $this->canCreateAccounts();
438 $this->setVar( '_CreateDBAccount', false );
441 $create = $this->getVar( '_CreateDBAccount' );
445 // Test the web account
447 Database
::factory( 'mysql', [
448 'host' => $this->getVar( 'wgDBserver' ),
449 'user' => $this->getVar( 'wgDBuser' ),
450 'password' => $this->getVar( 'wgDBpassword' ),
453 'tablePrefix' => $this->getVar( 'wgDBprefix' )
455 } catch ( DBConnectionError
$e ) {
456 return Status
::newFatal( 'config-connection-error', $e->getMessage() );
460 // Validate engines and charsets
461 // This is done pre-submit already so it's just for security
462 $engines = $this->getEngines();
463 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
464 $this->setVar( '_MysqlEngine', reset( $engines ) );
466 $charsets = $this->getCharsets();
467 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
468 $this->setVar( '_MysqlCharset', reset( $charsets ) );
471 return Status
::newGood();
474 public function preInstall() {
475 # Add our user callback to installSteps, right before the tables are created.
478 'callback' => [ $this, 'setupUser' ],
480 $this->parent
->addInstallStep( $callback, 'tables' );
486 public function setupDatabase() {
487 $status = $this->getConnection();
488 if ( !$status->isOK() ) {
491 /** @var Database $conn */
492 $conn = $status->value
;
493 $dbName = $this->getVar( 'wgDBname' );
494 if ( !$conn->selectDB( $dbName ) ) {
496 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
499 $conn->selectDB( $dbName );
501 $this->setupSchemaVars();
509 public function setupUser() {
510 $dbUser = $this->getVar( 'wgDBuser' );
511 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
512 return Status
::newGood();
514 $status = $this->getConnection();
515 if ( !$status->isOK() ) {
519 $this->setupSchemaVars();
520 $dbName = $this->getVar( 'wgDBname' );
521 $this->db
->selectDB( $dbName );
522 $server = $this->getVar( 'wgDBserver' );
523 $password = $this->getVar( 'wgDBpassword' );
524 $grantableNames = [];
526 if ( $this->getVar( '_CreateDBAccount' ) ) {
527 // Before we blindly try to create a user that already has access,
528 try { // first attempt to connect to the database
529 Database
::factory( 'mysql', [
532 'password' => $password,
535 'tablePrefix' => $this->getVar( 'wgDBprefix' )
537 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
538 $tryToCreate = false;
539 } catch ( DBConnectionError
$e ) {
543 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
544 $tryToCreate = false;
547 if ( $tryToCreate ) {
551 'localhost.localdomain',
555 $createHostList = array_unique( $createHostList );
556 $escPass = $this->db
->addQuotes( $password );
558 foreach ( $createHostList as $host ) {
559 $fullName = $this->buildFullUserName( $dbUser, $host );
560 if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
562 $this->db
->begin( __METHOD__
);
563 $this->db
->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__
);
564 $this->db
->commit( __METHOD__
);
565 $grantableNames[] = $fullName;
566 } catch ( DBQueryError
$dqe ) {
567 if ( $this->db
->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
568 // User (probably) already exists
569 $this->db
->rollback( __METHOD__
);
570 $status->warning( 'config-install-user-alreadyexists', $dbUser );
571 $grantableNames[] = $fullName;
574 // If we couldn't create for some bizzare reason and the
575 // user probably doesn't exist, skip the grant
576 $this->db
->rollback( __METHOD__
);
577 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
581 $status->warning( 'config-install-user-alreadyexists', $dbUser );
582 $grantableNames[] = $fullName;
588 // Try to grant to all the users we know exist or we were able to create
589 $dbAllTables = $this->db
->addIdentifierQuotes( $dbName ) . '.*';
590 foreach ( $grantableNames as $name ) {
592 $this->db
->begin( __METHOD__
);
593 $this->db
->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__
);
594 $this->db
->commit( __METHOD__
);
595 } catch ( DBQueryError
$dqe ) {
596 $this->db
->rollback( __METHOD__
);
597 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
605 * Return a formal 'User'@'Host' username for use in queries
606 * @param string $name Username, quotes will be added
607 * @param string $host Hostname, quotes will be added
610 private function buildFullUserName( $name, $host ) {
611 return $this->db
->addQuotes( $name ) . '@' . $this->db
->addQuotes( $host );
615 * Try to see if the user account exists. Our "superuser" may not have
616 * access to mysql.user, so false means "no" or "maybe"
617 * @param string $host Hostname to check
618 * @param string $user Username to check
621 private function userDefinitelyExists( $host, $user ) {
623 $res = $this->db
->selectRow( 'mysql.user', [ 'Host', 'User' ],
624 [ 'Host' => $host, 'User' => $user ], __METHOD__
);
627 } catch ( DBQueryError
$dqe ) {
633 * Return any table options to be applied to all tables that don't
638 protected function getTableOptions() {
640 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
641 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
643 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
644 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
647 return implode( ', ', $options );
651 * Get variables to substitute into tables.sql and the SQL patch files.
655 public function getSchemaVars() {
657 'wgDBTableOptions' => $this->getTableOptions(),
658 'wgDBname' => $this->getVar( 'wgDBname' ),
659 'wgDBuser' => $this->getVar( 'wgDBuser' ),
660 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
664 public function getLocalSettings() {
665 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
666 $prefix = LocalSettingsGenerator
::escapePhpString( $this->getVar( 'wgDBprefix' ) );
667 $tblOpts = LocalSettingsGenerator
::escapePhpString( $this->getTableOptions() );
669 return "# MySQL specific settings
670 \$wgDBprefix = \"{$prefix}\";
672 # MySQL table options to use during installation or update
673 \$wgDBTableOptions = \"{$tblOpts}\";
675 # Experimental charset support for MySQL 5.0.
676 \$wgDBmysql5 = {$dbmysql5};";