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
25 * Class for setting up the MediaWiki database using MySQL.
30 class MysqlInstaller
extends DatabaseInstaller
{
32 protected $globalNames = [
42 protected $internalDefaults = [
43 '_MysqlEngine' => 'InnoDB',
44 '_MysqlCharset' => 'binary',
45 '_InstallUser' => 'root',
48 public $supportedEngines = [ 'InnoDB', 'MyISAM' ];
50 public $minimumVersion = '5.0.3';
52 public $webUserPrivs = [
57 'CREATE TEMPORARY TABLES',
63 public function getName() {
70 public function isCompiled() {
71 return self
::checkExtension( 'mysql' ) || self
::checkExtension( 'mysqli' );
77 public function getConnectForm() {
78 return $this->getTextBox(
82 $this->parent
->getHelpBox( 'config-db-host-help' )
84 Html
::openElement( 'fieldset' ) .
85 Html
::element( 'legend', [], wfMessage( 'config-db-wiki-settings' )->text() ) .
86 $this->getTextBox( 'wgDBname', 'config-db-name', [ 'dir' => 'ltr' ],
87 $this->parent
->getHelpBox( 'config-db-name-help' ) ) .
88 $this->getTextBox( 'wgDBprefix', 'config-db-prefix', [ 'dir' => 'ltr' ],
89 $this->parent
->getHelpBox( 'config-db-prefix-help' ) ) .
90 Html
::closeElement( 'fieldset' ) .
91 $this->getInstallUserBox();
94 public function submitConnectForm() {
95 // Get variables from the request.
96 $newValues = $this->setVarsFromRequest( [ 'wgDBserver', 'wgDBname', 'wgDBprefix' ] );
99 $status = Status
::newGood();
100 if ( !strlen( $newValues['wgDBserver'] ) ) {
101 $status->fatal( 'config-missing-db-host' );
103 if ( !strlen( $newValues['wgDBname'] ) ) {
104 $status->fatal( 'config-missing-db-name' );
105 } elseif ( !preg_match( '/^[a-z0-9+_-]+$/i', $newValues['wgDBname'] ) ) {
106 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
108 if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
109 $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
111 if ( !$status->isOK() ) {
116 $status = $this->submitInstallUserBox();
117 if ( !$status->isOK() ) {
122 $status = $this->getConnection();
123 if ( !$status->isOK() ) {
127 * @var $conn Database
129 $conn = $status->value
;
132 $version = $conn->getServerVersion();
133 if ( version_compare( $version, $this->minimumVersion
) < 0 ) {
134 return Status
::newFatal( 'config-mysql-old', $this->minimumVersion
, $version );
143 public function openConnection() {
144 $status = Status
::newGood();
146 $db = Database
::factory( 'mysql', [
147 'host' => $this->getVar( 'wgDBserver' ),
148 'user' => $this->getVar( '_InstallUser' ),
149 'password' => $this->getVar( '_InstallPassword' ),
152 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ] );
153 $status->value
= $db;
154 } catch ( DBConnectionError
$e ) {
155 $status->fatal( 'config-connection-error', $e->getMessage() );
161 public function preUpgrade() {
162 global $wgDBuser, $wgDBpassword;
164 $status = $this->getConnection();
165 if ( !$status->isOK() ) {
166 $this->parent
->showStatusError( $status );
171 * @var $conn Database
173 $conn = $status->value
;
174 $conn->selectDB( $this->getVar( 'wgDBname' ) );
176 # Determine existing default character set
177 if ( $conn->tableExists( "revision", __METHOD__
) ) {
178 $revision = $conn->buildLike( $this->getVar( 'wgDBprefix' ) . 'revision' );
179 $res = $conn->query( "SHOW TABLE STATUS $revision", __METHOD__
);
180 $row = $conn->fetchObject( $res );
182 $this->parent
->showMessage( 'config-show-table-status' );
183 $existingSchema = false;
184 $existingEngine = false;
186 if ( preg_match( '/^latin1/', $row->Collation
) ) {
187 $existingSchema = 'latin1';
188 } elseif ( preg_match( '/^utf8/', $row->Collation
) ) {
189 $existingSchema = 'utf8';
190 } elseif ( preg_match( '/^binary/', $row->Collation
) ) {
191 $existingSchema = 'binary';
193 $existingSchema = false;
194 $this->parent
->showMessage( 'config-unknown-collation' );
196 if ( isset( $row->Engine
) ) {
197 $existingEngine = $row->Engine
;
199 $existingEngine = $row->Type
;
203 $existingSchema = false;
204 $existingEngine = false;
207 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
208 $this->setVar( '_MysqlCharset', $existingSchema );
210 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
211 $this->setVar( '_MysqlEngine', $existingEngine );
214 # Normal user and password are selected after this step, so for now
215 # just copy these two
216 $wgDBuser = $this->getVar( '_InstallUser' );
217 $wgDBpassword = $this->getVar( '_InstallPassword' );
221 * Get a list of storage engines that are available and supported
225 public function getEngines() {
226 $status = $this->getConnection();
229 * @var $conn Database
231 $conn = $status->value
;
234 $res = $conn->query( 'SHOW ENGINES', __METHOD__
);
235 foreach ( $res as $row ) {
236 if ( $row->Support
== 'YES' ||
$row->Support
== 'DEFAULT' ) {
237 $engines[] = $row->Engine
;
240 $engines = array_intersect( $this->supportedEngines
, $engines );
246 * Get a list of character sets that are available and supported
250 public function getCharsets() {
251 return [ 'binary', 'utf8' ];
255 * Return true if the install user can create accounts
259 public function canCreateAccounts() {
260 $status = $this->getConnection();
261 if ( !$status->isOK() ) {
264 /** @var $conn Database */
265 $conn = $status->value
;
267 // Get current account name
268 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__
);
269 $parts = explode( '@', $currentName );
270 if ( count( $parts ) != 2 ) {
273 $quotedUser = $conn->addQuotes( $parts[0] ) .
274 '@' . $conn->addQuotes( $parts[1] );
276 // The user needs to have INSERT on mysql.* to be able to CREATE USER
277 // The grantee will be double-quoted in this query, as required
278 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
279 [ 'GRANTEE' => $quotedUser ], __METHOD__
);
280 $insertMysql = false;
281 $grantOptions = array_flip( $this->webUserPrivs
);
282 foreach ( $res as $row ) {
283 if ( $row->PRIVILEGE_TYPE
== 'INSERT' ) {
286 if ( $row->IS_GRANTABLE
) {
287 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
291 // Check for DB-specific privs for mysql.*
292 if ( !$insertMysql ) {
293 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
295 'GRANTEE' => $quotedUser,
296 'TABLE_SCHEMA' => 'mysql',
297 'PRIVILEGE_TYPE' => 'INSERT',
304 if ( !$insertMysql ) {
308 // Check for DB-level grant options
309 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
311 'GRANTEE' => $quotedUser,
314 foreach ( $res as $row ) {
315 $regex = $this->likeToRegex( $row->TABLE_SCHEMA
);
316 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
317 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
320 if ( count( $grantOptions ) ) {
321 // Can't grant everything
329 * Convert a wildcard (as used in LIKE) to a regex
330 * Slashes are escaped, slash terminators included
332 protected function likeToRegex( $wildcard ) {
333 $r = preg_quote( $wildcard, '/' );
344 public function getSettingsForm() {
345 if ( $this->canCreateAccounts() ) {
346 $noCreateMsg = false;
348 $noCreateMsg = 'config-db-web-no-create-privs';
350 $s = $this->getWebUserBox( $noCreateMsg );
352 // Do engine selector
353 $engines = $this->getEngines();
354 // If the current default engine is not supported, use an engine that is
355 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
356 $this->setVar( '_MysqlEngine', reset( $engines ) );
359 $s .= Xml
::openElement( 'div', [
360 'id' => 'dbMyisamWarning'
362 $myisamWarning = 'config-mysql-myisam-dep';
363 if ( count( $engines ) === 1 ) {
364 $myisamWarning = 'config-mysql-only-myisam-dep';
366 $s .= $this->parent
->getWarningBox( wfMessage( $myisamWarning )->text() );
367 $s .= Xml
::closeElement( 'div' );
369 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
370 $s .= Xml
::openElement( 'script' );
371 $s .= '$(\'#dbMyisamWarning\').hide();';
372 $s .= Xml
::closeElement( 'script' );
375 if ( count( $engines ) >= 2 ) {
376 // getRadioSet() builds a set of labeled radio buttons.
377 // For grep: The following messages are used as the item labels:
378 // config-mysql-innodb, config-mysql-myisam
379 $s .= $this->getRadioSet( [
380 'var' => '_MysqlEngine',
381 'label' => 'config-mysql-engine',
382 'itemLabelPrefix' => 'config-mysql-',
383 'values' => $engines,
386 'class' => 'showHideRadio',
387 'rel' => 'dbMyisamWarning'
390 'class' => 'hideShowRadio',
391 'rel' => 'dbMyisamWarning'
395 $s .= $this->parent
->getHelpBox( 'config-mysql-engine-help' );
398 // If the current default charset is not supported, use a charset that is
399 $charsets = $this->getCharsets();
400 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
401 $this->setVar( '_MysqlCharset', reset( $charsets ) );
404 // Do charset selector
405 if ( count( $charsets ) >= 2 ) {
406 // getRadioSet() builds a set of labeled radio buttons.
407 // For grep: The following messages are used as the item labels:
408 // config-mysql-binary, config-mysql-utf8
409 $s .= $this->getRadioSet( [
410 'var' => '_MysqlCharset',
411 'label' => 'config-mysql-charset',
412 'itemLabelPrefix' => 'config-mysql-',
413 'values' => $charsets
415 $s .= $this->parent
->getHelpBox( 'config-mysql-charset-help' );
424 public function submitSettingsForm() {
425 $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
426 $status = $this->submitWebUserBox();
427 if ( !$status->isOK() ) {
431 // Validate the create checkbox
432 $canCreate = $this->canCreateAccounts();
434 $this->setVar( '_CreateDBAccount', false );
437 $create = $this->getVar( '_CreateDBAccount' );
441 // Test the web account
443 Database
::factory( 'mysql', [
444 'host' => $this->getVar( 'wgDBserver' ),
445 'user' => $this->getVar( 'wgDBuser' ),
446 'password' => $this->getVar( 'wgDBpassword' ),
449 'tablePrefix' => $this->getVar( 'wgDBprefix' )
451 } catch ( DBConnectionError
$e ) {
452 return Status
::newFatal( 'config-connection-error', $e->getMessage() );
456 // Validate engines and charsets
457 // This is done pre-submit already so it's just for security
458 $engines = $this->getEngines();
459 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
460 $this->setVar( '_MysqlEngine', reset( $engines ) );
462 $charsets = $this->getCharsets();
463 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
464 $this->setVar( '_MysqlCharset', reset( $charsets ) );
467 return Status
::newGood();
470 public function preInstall() {
471 # Add our user callback to installSteps, right before the tables are created.
474 'callback' => [ $this, 'setupUser' ],
476 $this->parent
->addInstallStep( $callback, 'tables' );
482 public function setupDatabase() {
483 $status = $this->getConnection();
484 if ( !$status->isOK() ) {
487 /** @var Database $conn */
488 $conn = $status->value
;
489 $dbName = $this->getVar( 'wgDBname' );
490 if ( !$conn->selectDB( $dbName ) ) {
492 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
495 $conn->selectDB( $dbName );
497 $this->setupSchemaVars();
505 public function setupUser() {
506 $dbUser = $this->getVar( 'wgDBuser' );
507 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
508 return Status
::newGood();
510 $status = $this->getConnection();
511 if ( !$status->isOK() ) {
515 $this->setupSchemaVars();
516 $dbName = $this->getVar( 'wgDBname' );
517 $this->db
->selectDB( $dbName );
518 $server = $this->getVar( 'wgDBserver' );
519 $password = $this->getVar( 'wgDBpassword' );
520 $grantableNames = [];
522 if ( $this->getVar( '_CreateDBAccount' ) ) {
523 // Before we blindly try to create a user that already has access,
524 try { // first attempt to connect to the database
525 Database
::factory( 'mysql', [
528 'password' => $password,
531 'tablePrefix' => $this->getVar( 'wgDBprefix' )
533 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
534 $tryToCreate = false;
535 } catch ( DBConnectionError
$e ) {
539 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
540 $tryToCreate = false;
543 if ( $tryToCreate ) {
547 'localhost.localdomain',
551 $createHostList = array_unique( $createHostList );
552 $escPass = $this->db
->addQuotes( $password );
554 foreach ( $createHostList as $host ) {
555 $fullName = $this->buildFullUserName( $dbUser, $host );
556 if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
558 $this->db
->begin( __METHOD__
);
559 $this->db
->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__
);
560 $this->db
->commit( __METHOD__
);
561 $grantableNames[] = $fullName;
562 } catch ( DBQueryError
$dqe ) {
563 if ( $this->db
->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
564 // User (probably) already exists
565 $this->db
->rollback( __METHOD__
);
566 $status->warning( 'config-install-user-alreadyexists', $dbUser );
567 $grantableNames[] = $fullName;
570 // If we couldn't create for some bizzare reason and the
571 // user probably doesn't exist, skip the grant
572 $this->db
->rollback( __METHOD__
);
573 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
577 $status->warning( 'config-install-user-alreadyexists', $dbUser );
578 $grantableNames[] = $fullName;
584 // Try to grant to all the users we know exist or we were able to create
585 $dbAllTables = $this->db
->addIdentifierQuotes( $dbName ) . '.*';
586 foreach ( $grantableNames as $name ) {
588 $this->db
->begin( __METHOD__
);
589 $this->db
->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__
);
590 $this->db
->commit( __METHOD__
);
591 } catch ( DBQueryError
$dqe ) {
592 $this->db
->rollback( __METHOD__
);
593 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
601 * Return a formal 'User'@'Host' username for use in queries
602 * @param string $name Username, quotes will be added
603 * @param string $host Hostname, quotes will be added
606 private function buildFullUserName( $name, $host ) {
607 return $this->db
->addQuotes( $name ) . '@' . $this->db
->addQuotes( $host );
611 * Try to see if the user account exists. Our "superuser" may not have
612 * access to mysql.user, so false means "no" or "maybe"
613 * @param string $host Hostname to check
614 * @param string $user Username to check
617 private function userDefinitelyExists( $host, $user ) {
619 $res = $this->db
->selectRow( 'mysql.user', [ 'Host', 'User' ],
620 [ 'Host' => $host, 'User' => $user ], __METHOD__
);
623 } catch ( DBQueryError
$dqe ) {
629 * Return any table options to be applied to all tables that don't
634 protected function getTableOptions() {
636 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
637 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
639 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
640 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
643 return implode( ', ', $options );
647 * Get variables to substitute into tables.sql and the SQL patch files.
651 public function getSchemaVars() {
653 'wgDBTableOptions' => $this->getTableOptions(),
654 'wgDBname' => $this->getVar( 'wgDBname' ),
655 'wgDBuser' => $this->getVar( 'wgDBuser' ),
656 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
660 public function getLocalSettings() {
661 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
662 $prefix = LocalSettingsGenerator
::escapePhpString( $this->getVar( 'wgDBprefix' ) );
663 $tblOpts = LocalSettingsGenerator
::escapePhpString( $this->getTableOptions() );
665 return "# MySQL specific settings
666 \$wgDBprefix = \"{$prefix}\";
668 # MySQL table options to use during installation or update
669 \$wgDBTableOptions = \"{$tblOpts}\";
671 # Experimental charset support for MySQL 5.0.
672 \$wgDBmysql5 = {$dbmysql5};";