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
;
134 '@phan-var Database $conn';
137 return static::meetsMinimumRequirement( $conn->getServerVersion() );
143 public function openConnection() {
144 $status = Status
::newGood();
146 /** @var DatabaseMysqlBase $db */
147 $db = Database
::factory( 'mysql', [
148 'host' => $this->getVar( 'wgDBserver' ),
149 'user' => $this->getVar( '_InstallUser' ),
150 'password' => $this->getVar( '_InstallPassword' ),
153 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ] );
154 $status->value
= $db;
155 } catch ( DBConnectionError
$e ) {
156 $status->fatal( 'config-connection-error', $e->getMessage() );
162 public function preUpgrade() {
163 global $wgDBuser, $wgDBpassword;
165 $status = $this->getConnection();
166 if ( !$status->isOK() ) {
167 $this->parent
->showStatusMessage( $status );
172 * @var Database $conn
174 $conn = $status->value
;
175 $conn->selectDB( $this->getVar( 'wgDBname' ) );
177 # Determine existing default character set
178 if ( $conn->tableExists( "revision", __METHOD__
) ) {
179 $revision = $this->escapeLikeInternal( $this->getVar( 'wgDBprefix' ) . 'revision', '\\' );
180 $res = $conn->query( "SHOW TABLE STATUS LIKE '$revision'", __METHOD__
);
181 $row = $conn->fetchObject( $res );
183 $this->parent
->showMessage( 'config-show-table-status' );
184 $existingSchema = false;
185 $existingEngine = false;
187 if ( preg_match( '/^latin1/', $row->Collation
) ) {
188 $existingSchema = 'latin1';
189 } elseif ( preg_match( '/^utf8/', $row->Collation
) ) {
190 $existingSchema = 'utf8';
191 } elseif ( preg_match( '/^binary/', $row->Collation
) ) {
192 $existingSchema = 'binary';
194 $existingSchema = false;
195 $this->parent
->showMessage( 'config-unknown-collation' );
197 $existingEngine = $row->Engine ??
$row->Type
;
200 $existingSchema = false;
201 $existingEngine = false;
204 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
205 $this->setVar( '_MysqlCharset', $existingSchema );
207 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
208 $this->setVar( '_MysqlEngine', $existingEngine );
211 # Normal user and password are selected after this step, so for now
212 # just copy these two
213 $wgDBuser = $this->getVar( '_InstallUser' );
214 $wgDBpassword = $this->getVar( '_InstallPassword' );
219 * @param string $escapeChar
222 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
223 return str_replace( [ $escapeChar, '%', '_' ],
224 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
229 * Get a list of storage engines that are available and supported
233 public function getEngines() {
234 $status = $this->getConnection();
237 * @var Database $conn
239 $conn = $status->value
;
242 $res = $conn->query( 'SHOW ENGINES', __METHOD__
);
243 foreach ( $res as $row ) {
244 if ( $row->Support
== 'YES' ||
$row->Support
== 'DEFAULT' ) {
245 $engines[] = $row->Engine
;
248 $engines = array_intersect( $this->supportedEngines
, $engines );
254 * Get a list of character sets that are available and supported
258 public function getCharsets() {
259 return [ 'binary', 'utf8' ];
263 * Return true if the install user can create accounts
267 public function canCreateAccounts() {
268 $status = $this->getConnection();
269 if ( !$status->isOK() ) {
272 /** @var Database $conn */
273 $conn = $status->value
;
275 // Get current account name
276 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__
);
277 $parts = explode( '@', $currentName );
278 if ( count( $parts ) != 2 ) {
281 $quotedUser = $conn->addQuotes( $parts[0] ) .
282 '@' . $conn->addQuotes( $parts[1] );
284 // The user needs to have INSERT on mysql.* to be able to CREATE USER
285 // The grantee will be double-quoted in this query, as required
286 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
287 [ 'GRANTEE' => $quotedUser ], __METHOD__
);
288 $insertMysql = false;
289 $grantOptions = array_flip( $this->webUserPrivs
);
290 foreach ( $res as $row ) {
291 if ( $row->PRIVILEGE_TYPE
== 'INSERT' ) {
294 if ( $row->IS_GRANTABLE
) {
295 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
299 // Check for DB-specific privs for mysql.*
300 if ( !$insertMysql ) {
301 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
303 'GRANTEE' => $quotedUser,
304 'TABLE_SCHEMA' => 'mysql',
305 'PRIVILEGE_TYPE' => 'INSERT',
312 if ( !$insertMysql ) {
316 // Check for DB-level grant options
317 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
319 'GRANTEE' => $quotedUser,
322 foreach ( $res as $row ) {
323 $regex = $this->likeToRegex( $row->TABLE_SCHEMA
);
324 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
325 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
328 if ( count( $grantOptions ) ) {
329 // Can't grant everything
337 * Convert a wildcard (as used in LIKE) to a regex
338 * Slashes are escaped, slash terminators included
339 * @param string $wildcard
342 protected function likeToRegex( $wildcard ) {
343 $r = preg_quote( $wildcard, '/' );
354 public function getSettingsForm() {
355 if ( $this->canCreateAccounts() ) {
356 $noCreateMsg = false;
358 $noCreateMsg = 'config-db-web-no-create-privs';
360 $s = $this->getWebUserBox( $noCreateMsg );
362 // Do engine selector
363 $engines = $this->getEngines();
364 // If the current default engine is not supported, use an engine that is
365 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
366 $this->setVar( '_MysqlEngine', reset( $engines ) );
369 // If the current default charset is not supported, use a charset that is
370 $charsets = $this->getCharsets();
371 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
372 $this->setVar( '_MysqlCharset', reset( $charsets ) );
381 public function submitSettingsForm() {
382 $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
383 $status = $this->submitWebUserBox();
384 if ( !$status->isOK() ) {
388 // Validate the create checkbox
389 $canCreate = $this->canCreateAccounts();
391 $this->setVar( '_CreateDBAccount', false );
394 $create = $this->getVar( '_CreateDBAccount' );
398 // Test the web account
400 Database
::factory( 'mysql', [
401 'host' => $this->getVar( 'wgDBserver' ),
402 'user' => $this->getVar( 'wgDBuser' ),
403 'password' => $this->getVar( 'wgDBpassword' ),
406 'tablePrefix' => $this->getVar( 'wgDBprefix' )
408 } catch ( DBConnectionError
$e ) {
409 return Status
::newFatal( 'config-connection-error', $e->getMessage() );
413 // Validate engines and charsets
414 // This is done pre-submit already so it's just for security
415 $engines = $this->getEngines();
416 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
417 $this->setVar( '_MysqlEngine', reset( $engines ) );
419 $charsets = $this->getCharsets();
420 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
421 $this->setVar( '_MysqlCharset', reset( $charsets ) );
424 return Status
::newGood();
427 public function preInstall() {
428 # Add our user callback to installSteps, right before the tables are created.
431 'callback' => [ $this, 'setupUser' ],
433 $this->parent
->addInstallStep( $callback, 'tables' );
439 public function setupDatabase() {
440 $status = $this->getConnection();
441 if ( !$status->isOK() ) {
444 /** @var Database $conn */
445 $conn = $status->value
;
446 $dbName = $this->getVar( 'wgDBname' );
447 if ( !$this->databaseExists( $dbName ) ) {
449 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
453 $conn->selectDB( $dbName );
454 $this->setupSchemaVars();
460 * Try to see if a given database exists
461 * @param string $dbName Database name to check
464 private function databaseExists( $dbName ) {
465 $encDatabase = $this->db
->addQuotes( $dbName );
467 return $this->db
->query(
468 "SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = $encDatabase",
476 public function setupUser() {
477 $dbUser = $this->getVar( 'wgDBuser' );
478 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
479 return Status
::newGood();
481 $status = $this->getConnection();
482 if ( !$status->isOK() ) {
486 $this->setupSchemaVars();
487 $dbName = $this->getVar( 'wgDBname' );
488 $this->db
->selectDB( $dbName );
489 $server = $this->getVar( 'wgDBserver' );
490 $password = $this->getVar( 'wgDBpassword' );
491 $grantableNames = [];
493 if ( $this->getVar( '_CreateDBAccount' ) ) {
494 // Before we blindly try to create a user that already has access,
495 try { // first attempt to connect to the database
496 Database
::factory( 'mysql', [
499 'password' => $password,
502 'tablePrefix' => $this->getVar( 'wgDBprefix' )
504 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
505 $tryToCreate = false;
506 } catch ( DBConnectionError
$e ) {
510 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
511 $tryToCreate = false;
514 if ( $tryToCreate ) {
518 'localhost.localdomain',
522 $createHostList = array_unique( $createHostList );
523 $escPass = $this->db
->addQuotes( $password );
525 foreach ( $createHostList as $host ) {
526 $fullName = $this->buildFullUserName( $dbUser, $host );
527 if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
529 $this->db
->begin( __METHOD__
);
530 $this->db
->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__
);
531 $this->db
->commit( __METHOD__
);
532 $grantableNames[] = $fullName;
533 } catch ( DBQueryError
$dqe ) {
534 if ( $this->db
->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
535 // User (probably) already exists
536 $this->db
->rollback( __METHOD__
);
537 $status->warning( 'config-install-user-alreadyexists', $dbUser );
538 $grantableNames[] = $fullName;
541 // If we couldn't create for some bizzare reason and the
542 // user probably doesn't exist, skip the grant
543 $this->db
->rollback( __METHOD__
);
544 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getMessage() );
548 $status->warning( 'config-install-user-alreadyexists', $dbUser );
549 $grantableNames[] = $fullName;
555 // Try to grant to all the users we know exist or we were able to create
556 $dbAllTables = $this->db
->addIdentifierQuotes( $dbName ) . '.*';
557 foreach ( $grantableNames as $name ) {
559 $this->db
->begin( __METHOD__
);
560 $this->db
->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__
);
561 $this->db
->commit( __METHOD__
);
562 } catch ( DBQueryError
$dqe ) {
563 $this->db
->rollback( __METHOD__
);
564 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getMessage() );
572 * Return a formal 'User'@'Host' username for use in queries
573 * @param string $name Username, quotes will be added
574 * @param string $host Hostname, quotes will be added
577 private function buildFullUserName( $name, $host ) {
578 return $this->db
->addQuotes( $name ) . '@' . $this->db
->addQuotes( $host );
582 * Try to see if the user account exists. Our "superuser" may not have
583 * access to mysql.user, so false means "no" or "maybe"
584 * @param string $host Hostname to check
585 * @param string $user Username to check
588 private function userDefinitelyExists( $host, $user ) {
590 $res = $this->db
->selectRow( 'mysql.user', [ 'Host', 'User' ],
591 [ 'Host' => $host, 'User' => $user ], __METHOD__
);
594 } catch ( DBQueryError
$dqe ) {
600 * Return any table options to be applied to all tables that don't
605 protected function getTableOptions() {
607 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
608 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
610 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
611 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
614 return implode( ', ', $options );
618 * Get variables to substitute into tables.sql and the SQL patch files.
622 public function getSchemaVars() {
624 'wgDBTableOptions' => $this->getTableOptions(),
625 'wgDBname' => $this->getVar( 'wgDBname' ),
626 'wgDBuser' => $this->getVar( 'wgDBuser' ),
627 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
631 public function getLocalSettings() {
632 $prefix = LocalSettingsGenerator
::escapePhpString( $this->getVar( 'wgDBprefix' ) );
633 $tblOpts = LocalSettingsGenerator
::escapePhpString( $this->getTableOptions() );
635 return "# MySQL specific settings
636 \$wgDBprefix = \"{$prefix}\";
638 # MySQL table options to use during installation or update
639 \$wgDBTableOptions = \"{$tblOpts}\";";