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 DatabaseBase
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 = DatabaseBase
::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 DatabaseBase
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 DatabaseBase
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 DatabaseBase */
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 = $conn->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
331 public function getSettingsForm() {
332 if ( $this->canCreateAccounts() ) {
333 $noCreateMsg = false;
335 $noCreateMsg = 'config-db-web-no-create-privs';
337 $s = $this->getWebUserBox( $noCreateMsg );
339 // Do engine selector
340 $engines = $this->getEngines();
341 // If the current default engine is not supported, use an engine that is
342 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
343 $this->setVar( '_MysqlEngine', reset( $engines ) );
346 $s .= Xml
::openElement( 'div', [
347 'id' => 'dbMyisamWarning'
349 $myisamWarning = 'config-mysql-myisam-dep';
350 if ( count( $engines ) === 1 ) {
351 $myisamWarning = 'config-mysql-only-myisam-dep';
353 $s .= $this->parent
->getWarningBox( wfMessage( $myisamWarning )->text() );
354 $s .= Xml
::closeElement( 'div' );
356 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
357 $s .= Xml
::openElement( 'script' );
358 $s .= '$(\'#dbMyisamWarning\').hide();';
359 $s .= Xml
::closeElement( 'script' );
362 if ( count( $engines ) >= 2 ) {
363 // getRadioSet() builds a set of labeled radio buttons.
364 // For grep: The following messages are used as the item labels:
365 // config-mysql-innodb, config-mysql-myisam
366 $s .= $this->getRadioSet( [
367 'var' => '_MysqlEngine',
368 'label' => 'config-mysql-engine',
369 'itemLabelPrefix' => 'config-mysql-',
370 'values' => $engines,
373 'class' => 'showHideRadio',
374 'rel' => 'dbMyisamWarning'
377 'class' => 'hideShowRadio',
378 'rel' => 'dbMyisamWarning'
382 $s .= $this->parent
->getHelpBox( 'config-mysql-engine-help' );
385 // If the current default charset is not supported, use a charset that is
386 $charsets = $this->getCharsets();
387 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
388 $this->setVar( '_MysqlCharset', reset( $charsets ) );
391 // Do charset selector
392 if ( count( $charsets ) >= 2 ) {
393 // getRadioSet() builds a set of labeled radio buttons.
394 // For grep: The following messages are used as the item labels:
395 // config-mysql-binary, config-mysql-utf8
396 $s .= $this->getRadioSet( [
397 'var' => '_MysqlCharset',
398 'label' => 'config-mysql-charset',
399 'itemLabelPrefix' => 'config-mysql-',
400 'values' => $charsets
402 $s .= $this->parent
->getHelpBox( 'config-mysql-charset-help' );
411 public function submitSettingsForm() {
412 $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
413 $status = $this->submitWebUserBox();
414 if ( !$status->isOK() ) {
418 // Validate the create checkbox
419 $canCreate = $this->canCreateAccounts();
421 $this->setVar( '_CreateDBAccount', false );
424 $create = $this->getVar( '_CreateDBAccount' );
428 // Test the web account
430 DatabaseBase
::factory( 'mysql', [
431 'host' => $this->getVar( 'wgDBserver' ),
432 'user' => $this->getVar( 'wgDBuser' ),
433 'password' => $this->getVar( 'wgDBpassword' ),
436 'tablePrefix' => $this->getVar( 'wgDBprefix' )
438 } catch ( DBConnectionError
$e ) {
439 return Status
::newFatal( 'config-connection-error', $e->getMessage() );
443 // Validate engines and charsets
444 // This is done pre-submit already so it's just for security
445 $engines = $this->getEngines();
446 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
447 $this->setVar( '_MysqlEngine', reset( $engines ) );
449 $charsets = $this->getCharsets();
450 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
451 $this->setVar( '_MysqlCharset', reset( $charsets ) );
454 return Status
::newGood();
457 public function preInstall() {
458 # Add our user callback to installSteps, right before the tables are created.
461 'callback' => [ $this, 'setupUser' ],
463 $this->parent
->addInstallStep( $callback, 'tables' );
469 public function setupDatabase() {
470 $status = $this->getConnection();
471 if ( !$status->isOK() ) {
474 /** @var DatabaseBase $conn */
475 $conn = $status->value
;
476 $dbName = $this->getVar( 'wgDBname' );
477 if ( !$conn->selectDB( $dbName ) ) {
479 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
482 $conn->selectDB( $dbName );
484 $this->setupSchemaVars();
492 public function setupUser() {
493 $dbUser = $this->getVar( 'wgDBuser' );
494 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
495 return Status
::newGood();
497 $status = $this->getConnection();
498 if ( !$status->isOK() ) {
502 $this->setupSchemaVars();
503 $dbName = $this->getVar( 'wgDBname' );
504 $this->db
->selectDB( $dbName );
505 $server = $this->getVar( 'wgDBserver' );
506 $password = $this->getVar( 'wgDBpassword' );
507 $grantableNames = [];
509 if ( $this->getVar( '_CreateDBAccount' ) ) {
510 // Before we blindly try to create a user that already has access,
511 try { // first attempt to connect to the database
512 DatabaseBase
::factory( 'mysql', [
515 'password' => $password,
518 'tablePrefix' => $this->getVar( 'wgDBprefix' )
520 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
521 $tryToCreate = false;
522 } catch ( DBConnectionError
$e ) {
526 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
527 $tryToCreate = false;
530 if ( $tryToCreate ) {
534 'localhost.localdomain',
538 $createHostList = array_unique( $createHostList );
539 $escPass = $this->db
->addQuotes( $password );
541 foreach ( $createHostList as $host ) {
542 $fullName = $this->buildFullUserName( $dbUser, $host );
543 if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
545 $this->db
->begin( __METHOD__
);
546 $this->db
->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__
);
547 $this->db
->commit( __METHOD__
);
548 $grantableNames[] = $fullName;
549 } catch ( DBQueryError
$dqe ) {
550 if ( $this->db
->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
551 // User (probably) already exists
552 $this->db
->rollback( __METHOD__
);
553 $status->warning( 'config-install-user-alreadyexists', $dbUser );
554 $grantableNames[] = $fullName;
557 // If we couldn't create for some bizzare reason and the
558 // user probably doesn't exist, skip the grant
559 $this->db
->rollback( __METHOD__
);
560 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
564 $status->warning( 'config-install-user-alreadyexists', $dbUser );
565 $grantableNames[] = $fullName;
571 // Try to grant to all the users we know exist or we were able to create
572 $dbAllTables = $this->db
->addIdentifierQuotes( $dbName ) . '.*';
573 foreach ( $grantableNames as $name ) {
575 $this->db
->begin( __METHOD__
);
576 $this->db
->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__
);
577 $this->db
->commit( __METHOD__
);
578 } catch ( DBQueryError
$dqe ) {
579 $this->db
->rollback( __METHOD__
);
580 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
588 * Return a formal 'User'@'Host' username for use in queries
589 * @param string $name Username, quotes will be added
590 * @param string $host Hostname, quotes will be added
593 private function buildFullUserName( $name, $host ) {
594 return $this->db
->addQuotes( $name ) . '@' . $this->db
->addQuotes( $host );
598 * Try to see if the user account exists. Our "superuser" may not have
599 * access to mysql.user, so false means "no" or "maybe"
600 * @param string $host Hostname to check
601 * @param string $user Username to check
604 private function userDefinitelyExists( $host, $user ) {
606 $res = $this->db
->selectRow( 'mysql.user', [ 'Host', 'User' ],
607 [ 'Host' => $host, 'User' => $user ], __METHOD__
);
610 } catch ( DBQueryError
$dqe ) {
616 * Return any table options to be applied to all tables that don't
621 protected function getTableOptions() {
623 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
624 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
626 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
627 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
630 return implode( ', ', $options );
634 * Get variables to substitute into tables.sql and the SQL patch files.
638 public function getSchemaVars() {
640 'wgDBTableOptions' => $this->getTableOptions(),
641 'wgDBname' => $this->getVar( 'wgDBname' ),
642 'wgDBuser' => $this->getVar( 'wgDBuser' ),
643 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
647 public function getLocalSettings() {
648 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
649 $prefix = LocalSettingsGenerator
::escapePhpString( $this->getVar( 'wgDBprefix' ) );
650 $tblOpts = LocalSettingsGenerator
::escapePhpString( $this->getTableOptions() );
652 return "# MySQL specific settings
653 \$wgDBprefix = \"{$prefix}\";
655 # MySQL table options to use during installation or update
656 \$wgDBTableOptions = \"{$tblOpts}\";
658 # Experimental charset support for MySQL 5.0.
659 \$wgDBmysql5 = {$dbmysql5};";