rdbms: Avoid selectDB() call in LoadMonitor new connections
[mediawiki.git] / includes / installer / MysqlInstaller.php
blob0250b6f9c321cae9e27b038b02c0f1f85235c324
1 <?php
2 /**
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
20 * @file
21 * @ingroup Deployment
24 use Wikimedia\Rdbms\Database;
25 use Wikimedia\Rdbms\DBQueryError;
26 use Wikimedia\Rdbms\DBConnectionError;
28 /**
29 * Class for setting up the MediaWiki database using MySQL.
31 * @ingroup Deployment
32 * @since 1.17
34 class MysqlInstaller extends DatabaseInstaller {
36 protected $globalNames = [
37 'wgDBserver',
38 'wgDBname',
39 'wgDBuser',
40 'wgDBpassword',
41 'wgDBprefix',
42 'wgDBTableOptions',
43 'wgDBmysql5',
46 protected $internalDefaults = [
47 '_MysqlEngine' => 'InnoDB',
48 '_MysqlCharset' => 'binary',
49 '_InstallUser' => 'root',
52 public $supportedEngines = [ 'InnoDB', 'MyISAM' ];
54 public $minimumVersion = '5.5.8';
56 public $webUserPrivs = [
57 'DELETE',
58 'INSERT',
59 'SELECT',
60 'UPDATE',
61 'CREATE TEMPORARY TABLES',
64 /**
65 * @return string
67 public function getName() {
68 return 'mysql';
71 /**
72 * @return bool
74 public function isCompiled() {
75 return self::checkExtension( 'mysql' ) || self::checkExtension( 'mysqli' );
78 /**
79 * @return string
81 public function getConnectForm() {
82 return $this->getTextBox(
83 'wgDBserver',
84 'config-db-host',
85 [],
86 $this->parent->getHelpBox( 'config-db-host-help' )
87 ) .
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' ] );
102 // Validate them.
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() ) {
116 return $status;
119 // Submit user box
120 $status = $this->submitInstallUserBox();
121 if ( !$status->isOK() ) {
122 return $status;
125 // Try to connect
126 $status = $this->getConnection();
127 if ( !$status->isOK() ) {
128 return $status;
131 * @var $conn Database
133 $conn = $status->value;
135 // Check version
136 $version = $conn->getServerVersion();
137 if ( version_compare( $version, $this->minimumVersion ) < 0 ) {
138 return Status::newFatal( 'config-mysql-old', $this->minimumVersion, $version );
141 return $status;
145 * @return Status
147 public function openConnection() {
148 $status = Status::newGood();
149 try {
150 $db = Database::factory( 'mysql', [
151 'host' => $this->getVar( 'wgDBserver' ),
152 'user' => $this->getVar( '_InstallUser' ),
153 'password' => $this->getVar( '_InstallPassword' ),
154 'dbname' => false,
155 'flags' => 0,
156 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ] );
157 $status->value = $db;
158 } catch ( DBConnectionError $e ) {
159 $status->fatal( 'config-connection-error', $e->getMessage() );
162 return $status;
165 public function preUpgrade() {
166 global $wgDBuser, $wgDBpassword;
168 $status = $this->getConnection();
169 if ( !$status->isOK() ) {
170 $this->parent->showStatusError( $status );
172 return;
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 = $this->escapeLikeInternal( $this->getVar( 'wgDBprefix' ) . 'revision', '\\' );
183 $res = $conn->query( "SHOW TABLE STATUS LIKE '$revision'", __METHOD__ );
184 $row = $conn->fetchObject( $res );
185 if ( !$row ) {
186 $this->parent->showMessage( 'config-show-table-status' );
187 $existingSchema = false;
188 $existingEngine = false;
189 } else {
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';
196 } else {
197 $existingSchema = false;
198 $this->parent->showMessage( 'config-unknown-collation' );
200 if ( isset( $row->Engine ) ) {
201 $existingEngine = $row->Engine;
202 } else {
203 $existingEngine = $row->Type;
206 } else {
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 * @param string $s
226 * @return string
228 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
229 return str_replace( [ $escapeChar, '%', '_' ],
230 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
231 $s );
235 * Get a list of storage engines that are available and supported
237 * @return array
239 public function getEngines() {
240 $status = $this->getConnection();
243 * @var $conn Database
245 $conn = $status->value;
247 $engines = [];
248 $res = $conn->query( 'SHOW ENGINES', __METHOD__ );
249 foreach ( $res as $row ) {
250 if ( $row->Support == 'YES' || $row->Support == 'DEFAULT' ) {
251 $engines[] = $row->Engine;
254 $engines = array_intersect( $this->supportedEngines, $engines );
256 return $engines;
260 * Get a list of character sets that are available and supported
262 * @return array
264 public function getCharsets() {
265 return [ 'binary', 'utf8' ];
269 * Return true if the install user can create accounts
271 * @return bool
273 public function canCreateAccounts() {
274 $status = $this->getConnection();
275 if ( !$status->isOK() ) {
276 return false;
278 /** @var $conn Database */
279 $conn = $status->value;
281 // Get current account name
282 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__ );
283 $parts = explode( '@', $currentName );
284 if ( count( $parts ) != 2 ) {
285 return false;
287 $quotedUser = $conn->addQuotes( $parts[0] ) .
288 '@' . $conn->addQuotes( $parts[1] );
290 // The user needs to have INSERT on mysql.* to be able to CREATE USER
291 // The grantee will be double-quoted in this query, as required
292 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
293 [ 'GRANTEE' => $quotedUser ], __METHOD__ );
294 $insertMysql = false;
295 $grantOptions = array_flip( $this->webUserPrivs );
296 foreach ( $res as $row ) {
297 if ( $row->PRIVILEGE_TYPE == 'INSERT' ) {
298 $insertMysql = true;
300 if ( $row->IS_GRANTABLE ) {
301 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
305 // Check for DB-specific privs for mysql.*
306 if ( !$insertMysql ) {
307 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
309 'GRANTEE' => $quotedUser,
310 'TABLE_SCHEMA' => 'mysql',
311 'PRIVILEGE_TYPE' => 'INSERT',
312 ], __METHOD__ );
313 if ( $row ) {
314 $insertMysql = true;
318 if ( !$insertMysql ) {
319 return false;
322 // Check for DB-level grant options
323 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
325 'GRANTEE' => $quotedUser,
326 'IS_GRANTABLE' => 1,
327 ], __METHOD__ );
328 foreach ( $res as $row ) {
329 $regex = $this->likeToRegex( $row->TABLE_SCHEMA );
330 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
331 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
334 if ( count( $grantOptions ) ) {
335 // Can't grant everything
336 return false;
339 return true;
343 * Convert a wildcard (as used in LIKE) to a regex
344 * Slashes are escaped, slash terminators included
346 protected function likeToRegex( $wildcard ) {
347 $r = preg_quote( $wildcard, '/' );
348 $r = strtr( $r, [
349 '%' => '.*',
350 '_' => '.'
351 ] );
352 return "/$r/s";
356 * @return string
358 public function getSettingsForm() {
359 if ( $this->canCreateAccounts() ) {
360 $noCreateMsg = false;
361 } else {
362 $noCreateMsg = 'config-db-web-no-create-privs';
364 $s = $this->getWebUserBox( $noCreateMsg );
366 // Do engine selector
367 $engines = $this->getEngines();
368 // If the current default engine is not supported, use an engine that is
369 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
370 $this->setVar( '_MysqlEngine', reset( $engines ) );
373 $s .= Xml::openElement( 'div', [
374 'id' => 'dbMyisamWarning'
375 ] );
376 $myisamWarning = 'config-mysql-myisam-dep';
377 if ( count( $engines ) === 1 ) {
378 $myisamWarning = 'config-mysql-only-myisam-dep';
380 $s .= $this->parent->getWarningBox( wfMessage( $myisamWarning )->text() );
381 $s .= Xml::closeElement( 'div' );
383 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
384 $s .= Xml::openElement( 'script' );
385 $s .= '$(\'#dbMyisamWarning\').hide();';
386 $s .= Xml::closeElement( 'script' );
389 if ( count( $engines ) >= 2 ) {
390 // getRadioSet() builds a set of labeled radio buttons.
391 // For grep: The following messages are used as the item labels:
392 // config-mysql-innodb, config-mysql-myisam
393 $s .= $this->getRadioSet( [
394 'var' => '_MysqlEngine',
395 'label' => 'config-mysql-engine',
396 'itemLabelPrefix' => 'config-mysql-',
397 'values' => $engines,
398 'itemAttribs' => [
399 'MyISAM' => [
400 'class' => 'showHideRadio',
401 'rel' => 'dbMyisamWarning'
403 'InnoDB' => [
404 'class' => 'hideShowRadio',
405 'rel' => 'dbMyisamWarning'
408 ] );
409 $s .= $this->parent->getHelpBox( 'config-mysql-engine-help' );
412 // If the current default charset is not supported, use a charset that is
413 $charsets = $this->getCharsets();
414 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
415 $this->setVar( '_MysqlCharset', reset( $charsets ) );
418 // Do charset selector
419 if ( count( $charsets ) >= 2 ) {
420 // getRadioSet() builds a set of labeled radio buttons.
421 // For grep: The following messages are used as the item labels:
422 // config-mysql-binary, config-mysql-utf8
423 $s .= $this->getRadioSet( [
424 'var' => '_MysqlCharset',
425 'label' => 'config-mysql-charset',
426 'itemLabelPrefix' => 'config-mysql-',
427 'values' => $charsets
428 ] );
429 $s .= $this->parent->getHelpBox( 'config-mysql-charset-help' );
432 return $s;
436 * @return Status
438 public function submitSettingsForm() {
439 $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
440 $status = $this->submitWebUserBox();
441 if ( !$status->isOK() ) {
442 return $status;
445 // Validate the create checkbox
446 $canCreate = $this->canCreateAccounts();
447 if ( !$canCreate ) {
448 $this->setVar( '_CreateDBAccount', false );
449 $create = false;
450 } else {
451 $create = $this->getVar( '_CreateDBAccount' );
454 if ( !$create ) {
455 // Test the web account
456 try {
457 Database::factory( 'mysql', [
458 'host' => $this->getVar( 'wgDBserver' ),
459 'user' => $this->getVar( 'wgDBuser' ),
460 'password' => $this->getVar( 'wgDBpassword' ),
461 'dbname' => false,
462 'flags' => 0,
463 'tablePrefix' => $this->getVar( 'wgDBprefix' )
464 ] );
465 } catch ( DBConnectionError $e ) {
466 return Status::newFatal( 'config-connection-error', $e->getMessage() );
470 // Validate engines and charsets
471 // This is done pre-submit already so it's just for security
472 $engines = $this->getEngines();
473 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
474 $this->setVar( '_MysqlEngine', reset( $engines ) );
476 $charsets = $this->getCharsets();
477 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
478 $this->setVar( '_MysqlCharset', reset( $charsets ) );
481 return Status::newGood();
484 public function preInstall() {
485 # Add our user callback to installSteps, right before the tables are created.
486 $callback = [
487 'name' => 'user',
488 'callback' => [ $this, 'setupUser' ],
490 $this->parent->addInstallStep( $callback, 'tables' );
494 * @return Status
496 public function setupDatabase() {
497 $status = $this->getConnection();
498 if ( !$status->isOK() ) {
499 return $status;
501 /** @var Database $conn */
502 $conn = $status->value;
503 $dbName = $this->getVar( 'wgDBname' );
504 if ( !$conn->selectDB( $dbName ) ) {
505 $conn->query(
506 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
507 __METHOD__
509 $conn->selectDB( $dbName );
511 $this->setupSchemaVars();
513 return $status;
517 * @return Status
519 public function setupUser() {
520 $dbUser = $this->getVar( 'wgDBuser' );
521 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
522 return Status::newGood();
524 $status = $this->getConnection();
525 if ( !$status->isOK() ) {
526 return $status;
529 $this->setupSchemaVars();
530 $dbName = $this->getVar( 'wgDBname' );
531 $this->db->selectDB( $dbName );
532 $server = $this->getVar( 'wgDBserver' );
533 $password = $this->getVar( 'wgDBpassword' );
534 $grantableNames = [];
536 if ( $this->getVar( '_CreateDBAccount' ) ) {
537 // Before we blindly try to create a user that already has access,
538 try { // first attempt to connect to the database
539 Database::factory( 'mysql', [
540 'host' => $server,
541 'user' => $dbUser,
542 'password' => $password,
543 'dbname' => false,
544 'flags' => 0,
545 'tablePrefix' => $this->getVar( 'wgDBprefix' )
546 ] );
547 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
548 $tryToCreate = false;
549 } catch ( DBConnectionError $e ) {
550 $tryToCreate = true;
552 } else {
553 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
554 $tryToCreate = false;
557 if ( $tryToCreate ) {
558 $createHostList = [
559 $server,
560 'localhost',
561 'localhost.localdomain',
565 $createHostList = array_unique( $createHostList );
566 $escPass = $this->db->addQuotes( $password );
568 foreach ( $createHostList as $host ) {
569 $fullName = $this->buildFullUserName( $dbUser, $host );
570 if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
571 try {
572 $this->db->begin( __METHOD__ );
573 $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
574 $this->db->commit( __METHOD__ );
575 $grantableNames[] = $fullName;
576 } catch ( DBQueryError $dqe ) {
577 if ( $this->db->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
578 // User (probably) already exists
579 $this->db->rollback( __METHOD__ );
580 $status->warning( 'config-install-user-alreadyexists', $dbUser );
581 $grantableNames[] = $fullName;
582 break;
583 } else {
584 // If we couldn't create for some bizzare reason and the
585 // user probably doesn't exist, skip the grant
586 $this->db->rollback( __METHOD__ );
587 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getMessage() );
590 } else {
591 $status->warning( 'config-install-user-alreadyexists', $dbUser );
592 $grantableNames[] = $fullName;
593 break;
598 // Try to grant to all the users we know exist or we were able to create
599 $dbAllTables = $this->db->addIdentifierQuotes( $dbName ) . '.*';
600 foreach ( $grantableNames as $name ) {
601 try {
602 $this->db->begin( __METHOD__ );
603 $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
604 $this->db->commit( __METHOD__ );
605 } catch ( DBQueryError $dqe ) {
606 $this->db->rollback( __METHOD__ );
607 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getMessage() );
611 return $status;
615 * Return a formal 'User'@'Host' username for use in queries
616 * @param string $name Username, quotes will be added
617 * @param string $host Hostname, quotes will be added
618 * @return string
620 private function buildFullUserName( $name, $host ) {
621 return $this->db->addQuotes( $name ) . '@' . $this->db->addQuotes( $host );
625 * Try to see if the user account exists. Our "superuser" may not have
626 * access to mysql.user, so false means "no" or "maybe"
627 * @param string $host Hostname to check
628 * @param string $user Username to check
629 * @return bool
631 private function userDefinitelyExists( $host, $user ) {
632 try {
633 $res = $this->db->selectRow( 'mysql.user', [ 'Host', 'User' ],
634 [ 'Host' => $host, 'User' => $user ], __METHOD__ );
636 return (bool)$res;
637 } catch ( DBQueryError $dqe ) {
638 return false;
643 * Return any table options to be applied to all tables that don't
644 * override them.
646 * @return string
648 protected function getTableOptions() {
649 $options = [];
650 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
651 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
653 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
654 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
657 return implode( ', ', $options );
661 * Get variables to substitute into tables.sql and the SQL patch files.
663 * @return array
665 public function getSchemaVars() {
666 return [
667 'wgDBTableOptions' => $this->getTableOptions(),
668 'wgDBname' => $this->getVar( 'wgDBname' ),
669 'wgDBuser' => $this->getVar( 'wgDBuser' ),
670 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
674 public function getLocalSettings() {
675 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
676 $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
677 $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
679 return "# MySQL specific settings
680 \$wgDBprefix = \"{$prefix}\";
682 # MySQL table options to use during installation or update
683 \$wgDBTableOptions = \"{$tblOpts}\";
685 # Experimental charset support for MySQL 5.0.
686 \$wgDBmysql5 = {$dbmysql5};";