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 = [
45 protected $internalDefaults = [
46 '_MysqlEngine' => 'InnoDB',
47 '_MysqlCharset' => 'binary',
48 '_InstallUser' => 'root',
51 public $supportedEngines = [ 'InnoDB' ];
53 public static $minimumVersion = '5.5.8';
54 protected static $notMinimumVersionMessage = 'config-mysql-old';
56 public $webUserPrivs = [
61 'CREATE TEMPORARY TABLES',
67 public function getName() {
74 public function isCompiled() {
75 return 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 Database $conn
133 $conn = $status->value
;
136 return static::meetsMinimumRequirement( $conn->getServerVersion() );
142 public function openConnection() {
143 $status = Status
::newGood();
145 /** @var DatabaseMysqlBase $db */
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
->showStatusMessage( $status );
171 * @var Database $conn
173 $conn = $status->value
;
174 $conn->selectDB( $this->getVar( 'wgDBname' ) );
176 # Determine existing default character set
177 if ( $conn->tableExists( "revision", __METHOD__
) ) {
178 $revision = $this->escapeLikeInternal( $this->getVar( 'wgDBprefix' ) . 'revision', '\\' );
179 $res = $conn->query( "SHOW TABLE STATUS LIKE '$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 $existingEngine = $row->Engine ??
$row->Type
;
199 $existingSchema = false;
200 $existingEngine = false;
203 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
204 $this->setVar( '_MysqlCharset', $existingSchema );
206 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
207 $this->setVar( '_MysqlEngine', $existingEngine );
210 # Normal user and password are selected after this step, so for now
211 # just copy these two
212 $wgDBuser = $this->getVar( '_InstallUser' );
213 $wgDBpassword = $this->getVar( '_InstallPassword' );
218 * @param string $escapeChar
221 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
222 return str_replace( [ $escapeChar, '%', '_' ],
223 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
228 * Get a list of storage engines that are available and supported
232 public function getEngines() {
233 $status = $this->getConnection();
236 * @var Database $conn
238 $conn = $status->value
;
241 $res = $conn->query( 'SHOW ENGINES', __METHOD__
);
242 foreach ( $res as $row ) {
243 if ( $row->Support
== 'YES' ||
$row->Support
== 'DEFAULT' ) {
244 $engines[] = $row->Engine
;
247 $engines = array_intersect( $this->supportedEngines
, $engines );
253 * Get a list of character sets that are available and supported
257 public function getCharsets() {
258 return [ 'binary', 'utf8' ];
262 * Return true if the install user can create accounts
266 public function canCreateAccounts() {
267 $status = $this->getConnection();
268 if ( !$status->isOK() ) {
271 /** @var Database $conn */
272 $conn = $status->value
;
274 // Get current account name
275 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__
);
276 $parts = explode( '@', $currentName );
277 if ( count( $parts ) != 2 ) {
280 $quotedUser = $conn->addQuotes( $parts[0] ) .
281 '@' . $conn->addQuotes( $parts[1] );
283 // The user needs to have INSERT on mysql.* to be able to CREATE USER
284 // The grantee will be double-quoted in this query, as required
285 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
286 [ 'GRANTEE' => $quotedUser ], __METHOD__
);
287 $insertMysql = false;
288 $grantOptions = array_flip( $this->webUserPrivs
);
289 foreach ( $res as $row ) {
290 if ( $row->PRIVILEGE_TYPE
== 'INSERT' ) {
293 if ( $row->IS_GRANTABLE
) {
294 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
298 // Check for DB-specific privs for mysql.*
299 if ( !$insertMysql ) {
300 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
302 'GRANTEE' => $quotedUser,
303 'TABLE_SCHEMA' => 'mysql',
304 'PRIVILEGE_TYPE' => 'INSERT',
311 if ( !$insertMysql ) {
315 // Check for DB-level grant options
316 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
318 'GRANTEE' => $quotedUser,
321 foreach ( $res as $row ) {
322 $regex = $this->likeToRegex( $row->TABLE_SCHEMA
);
323 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
324 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
327 if ( count( $grantOptions ) ) {
328 // Can't grant everything
336 * Convert a wildcard (as used in LIKE) to a regex
337 * Slashes are escaped, slash terminators included
338 * @param string $wildcard
341 protected function likeToRegex( $wildcard ) {
342 $r = preg_quote( $wildcard, '/' );
353 public function getSettingsForm() {
354 if ( $this->canCreateAccounts() ) {
355 $noCreateMsg = false;
357 $noCreateMsg = 'config-db-web-no-create-privs';
359 $s = $this->getWebUserBox( $noCreateMsg );
361 // Do engine selector
362 $engines = $this->getEngines();
363 // If the current default engine is not supported, use an engine that is
364 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
365 $this->setVar( '_MysqlEngine', reset( $engines ) );
368 // If the current default charset is not supported, use a charset that is
369 $charsets = $this->getCharsets();
370 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
371 $this->setVar( '_MysqlCharset', reset( $charsets ) );
380 public function submitSettingsForm() {
381 $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
382 $status = $this->submitWebUserBox();
383 if ( !$status->isOK() ) {
387 // Validate the create checkbox
388 $canCreate = $this->canCreateAccounts();
390 $this->setVar( '_CreateDBAccount', false );
393 $create = $this->getVar( '_CreateDBAccount' );
397 // Test the web account
399 Database
::factory( 'mysql', [
400 'host' => $this->getVar( 'wgDBserver' ),
401 'user' => $this->getVar( 'wgDBuser' ),
402 'password' => $this->getVar( 'wgDBpassword' ),
405 'tablePrefix' => $this->getVar( 'wgDBprefix' )
407 } catch ( DBConnectionError
$e ) {
408 return Status
::newFatal( 'config-connection-error', $e->getMessage() );
412 // Validate engines and charsets
413 // This is done pre-submit already so it's just for security
414 $engines = $this->getEngines();
415 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
416 $this->setVar( '_MysqlEngine', reset( $engines ) );
418 $charsets = $this->getCharsets();
419 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
420 $this->setVar( '_MysqlCharset', reset( $charsets ) );
423 return Status
::newGood();
426 public function preInstall() {
427 # Add our user callback to installSteps, right before the tables are created.
430 'callback' => [ $this, 'setupUser' ],
432 $this->parent
->addInstallStep( $callback, 'tables' );
438 public function setupDatabase() {
439 $status = $this->getConnection();
440 if ( !$status->isOK() ) {
443 /** @var Database $conn */
444 $conn = $status->value
;
445 $dbName = $this->getVar( 'wgDBname' );
446 if ( !$this->databaseExists( $dbName ) ) {
448 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
452 $conn->selectDB( $dbName );
453 $this->setupSchemaVars();
459 * Try to see if a given database exists
460 * @param string $dbName Database name to check
463 private function databaseExists( $dbName ) {
464 $encDatabase = $this->db
->addQuotes( $dbName );
466 return $this->db
->query(
467 "SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = $encDatabase",
475 public function setupUser() {
476 $dbUser = $this->getVar( 'wgDBuser' );
477 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
478 return Status
::newGood();
480 $status = $this->getConnection();
481 if ( !$status->isOK() ) {
485 $this->setupSchemaVars();
486 $dbName = $this->getVar( 'wgDBname' );
487 $this->db
->selectDB( $dbName );
488 $server = $this->getVar( 'wgDBserver' );
489 $password = $this->getVar( 'wgDBpassword' );
490 $grantableNames = [];
492 if ( $this->getVar( '_CreateDBAccount' ) ) {
493 // Before we blindly try to create a user that already has access,
494 try { // first attempt to connect to the database
495 Database
::factory( 'mysql', [
498 'password' => $password,
501 'tablePrefix' => $this->getVar( 'wgDBprefix' )
503 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
504 $tryToCreate = false;
505 } catch ( DBConnectionError
$e ) {
509 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
510 $tryToCreate = false;
513 if ( $tryToCreate ) {
517 'localhost.localdomain',
521 $createHostList = array_unique( $createHostList );
522 $escPass = $this->db
->addQuotes( $password );
524 foreach ( $createHostList as $host ) {
525 $fullName = $this->buildFullUserName( $dbUser, $host );
526 if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
528 $this->db
->begin( __METHOD__
);
529 $this->db
->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__
);
530 $this->db
->commit( __METHOD__
);
531 $grantableNames[] = $fullName;
532 } catch ( DBQueryError
$dqe ) {
533 if ( $this->db
->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
534 // User (probably) already exists
535 $this->db
->rollback( __METHOD__
);
536 $status->warning( 'config-install-user-alreadyexists', $dbUser );
537 $grantableNames[] = $fullName;
540 // If we couldn't create for some bizzare reason and the
541 // user probably doesn't exist, skip the grant
542 $this->db
->rollback( __METHOD__
);
543 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getMessage() );
547 $status->warning( 'config-install-user-alreadyexists', $dbUser );
548 $grantableNames[] = $fullName;
554 // Try to grant to all the users we know exist or we were able to create
555 $dbAllTables = $this->db
->addIdentifierQuotes( $dbName ) . '.*';
556 foreach ( $grantableNames as $name ) {
558 $this->db
->begin( __METHOD__
);
559 $this->db
->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__
);
560 $this->db
->commit( __METHOD__
);
561 } catch ( DBQueryError
$dqe ) {
562 $this->db
->rollback( __METHOD__
);
563 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getMessage() );
571 * Return a formal 'User'@'Host' username for use in queries
572 * @param string $name Username, quotes will be added
573 * @param string $host Hostname, quotes will be added
576 private function buildFullUserName( $name, $host ) {
577 return $this->db
->addQuotes( $name ) . '@' . $this->db
->addQuotes( $host );
581 * Try to see if the user account exists. Our "superuser" may not have
582 * access to mysql.user, so false means "no" or "maybe"
583 * @param string $host Hostname to check
584 * @param string $user Username to check
587 private function userDefinitelyExists( $host, $user ) {
589 $res = $this->db
->selectRow( 'mysql.user', [ 'Host', 'User' ],
590 [ 'Host' => $host, 'User' => $user ], __METHOD__
);
593 } catch ( DBQueryError
$dqe ) {
599 * Return any table options to be applied to all tables that don't
604 protected function getTableOptions() {
606 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
607 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
609 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
610 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
613 return implode( ', ', $options );
617 * Get variables to substitute into tables.sql and the SQL patch files.
621 public function getSchemaVars() {
623 'wgDBTableOptions' => $this->getTableOptions(),
624 'wgDBname' => $this->getVar( 'wgDBname' ),
625 'wgDBuser' => $this->getVar( 'wgDBuser' ),
626 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
630 public function getLocalSettings() {
631 $prefix = LocalSettingsGenerator
::escapePhpString( $this->getVar( 'wgDBprefix' ) );
632 $tblOpts = LocalSettingsGenerator
::escapePhpString( $this->getTableOptions() );
634 return "# MySQL specific settings
635 \$wgDBprefix = \"{$prefix}\";
637 # MySQL table options to use during installation or update
638 \$wgDBTableOptions = \"{$tblOpts}\";";