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 = [
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 = [
61 'CREATE TEMPORARY TABLES',
67 public function getName() {
74 public function isCompiled() {
75 return self
::checkExtension( 'mysql' ) || 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 $conn Database
133 $conn = $status->value
;
136 $version = $conn->getServerVersion();
137 if ( version_compare( $version, $this->minimumVersion
) < 0 ) {
138 return Status
::newFatal( 'config-mysql-old', $this->minimumVersion
, $version );
147 public function openConnection() {
148 $status = Status
::newGood();
150 $db = Database
::factory( 'mysql', [
151 'host' => $this->getVar( 'wgDBserver' ),
152 'user' => $this->getVar( '_InstallUser' ),
153 'password' => $this->getVar( '_InstallPassword' ),
156 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ] );
157 $status->value
= $db;
158 } catch ( DBConnectionError
$e ) {
159 $status->fatal( 'config-connection-error', $e->getMessage() );
165 public function preUpgrade() {
166 global $wgDBuser, $wgDBpassword;
168 $status = $this->getConnection();
169 if ( !$status->isOK() ) {
170 $this->parent
->showStatusError( $status );
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 );
186 $this->parent
->showMessage( 'config-show-table-status' );
187 $existingSchema = false;
188 $existingEngine = false;
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';
197 $existingSchema = false;
198 $this->parent
->showMessage( 'config-unknown-collation' );
200 if ( isset( $row->Engine
) ) {
201 $existingEngine = $row->Engine
;
203 $existingEngine = $row->Type
;
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' );
226 * @param string $escapeChar
229 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
230 return str_replace( [ $escapeChar, '%', '_' ],
231 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
236 * Get a list of storage engines that are available and supported
240 public function getEngines() {
241 $status = $this->getConnection();
244 * @var $conn Database
246 $conn = $status->value
;
249 $res = $conn->query( 'SHOW ENGINES', __METHOD__
);
250 foreach ( $res as $row ) {
251 if ( $row->Support
== 'YES' ||
$row->Support
== 'DEFAULT' ) {
252 $engines[] = $row->Engine
;
255 $engines = array_intersect( $this->supportedEngines
, $engines );
261 * Get a list of character sets that are available and supported
265 public function getCharsets() {
266 return [ 'binary', 'utf8' ];
270 * Return true if the install user can create accounts
274 public function canCreateAccounts() {
275 $status = $this->getConnection();
276 if ( !$status->isOK() ) {
279 /** @var Database $conn */
280 $conn = $status->value
;
282 // Get current account name
283 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__
);
284 $parts = explode( '@', $currentName );
285 if ( count( $parts ) != 2 ) {
288 $quotedUser = $conn->addQuotes( $parts[0] ) .
289 '@' . $conn->addQuotes( $parts[1] );
291 // The user needs to have INSERT on mysql.* to be able to CREATE USER
292 // The grantee will be double-quoted in this query, as required
293 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
294 [ 'GRANTEE' => $quotedUser ], __METHOD__
);
295 $insertMysql = false;
296 $grantOptions = array_flip( $this->webUserPrivs
);
297 foreach ( $res as $row ) {
298 if ( $row->PRIVILEGE_TYPE
== 'INSERT' ) {
301 if ( $row->IS_GRANTABLE
) {
302 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
306 // Check for DB-specific privs for mysql.*
307 if ( !$insertMysql ) {
308 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
310 'GRANTEE' => $quotedUser,
311 'TABLE_SCHEMA' => 'mysql',
312 'PRIVILEGE_TYPE' => 'INSERT',
319 if ( !$insertMysql ) {
323 // Check for DB-level grant options
324 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
326 'GRANTEE' => $quotedUser,
329 foreach ( $res as $row ) {
330 $regex = $this->likeToRegex( $row->TABLE_SCHEMA
);
331 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
332 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
335 if ( count( $grantOptions ) ) {
336 // Can't grant everything
344 * Convert a wildcard (as used in LIKE) to a regex
345 * Slashes are escaped, slash terminators included
346 * @param string $wildcard
349 protected function likeToRegex( $wildcard ) {
350 $r = preg_quote( $wildcard, '/' );
361 public function getSettingsForm() {
362 if ( $this->canCreateAccounts() ) {
363 $noCreateMsg = false;
365 $noCreateMsg = 'config-db-web-no-create-privs';
367 $s = $this->getWebUserBox( $noCreateMsg );
369 // Do engine selector
370 $engines = $this->getEngines();
371 // If the current default engine is not supported, use an engine that is
372 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
373 $this->setVar( '_MysqlEngine', reset( $engines ) );
376 $s .= Xml
::openElement( 'div', [
377 'id' => 'dbMyisamWarning'
379 $myisamWarning = 'config-mysql-myisam-dep';
380 if ( count( $engines ) === 1 ) {
381 $myisamWarning = 'config-mysql-only-myisam-dep';
383 $s .= $this->parent
->getWarningBox( wfMessage( $myisamWarning )->text() );
384 $s .= Xml
::closeElement( 'div' );
386 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
387 $s .= Xml
::openElement( 'script' );
388 $s .= '$(\'#dbMyisamWarning\').hide();';
389 $s .= Xml
::closeElement( 'script' );
392 if ( count( $engines ) >= 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-innodb, config-mysql-myisam
396 $s .= $this->getRadioSet( [
397 'var' => '_MysqlEngine',
398 'label' => 'config-mysql-engine',
399 'itemLabelPrefix' => 'config-mysql-',
400 'values' => $engines,
403 'class' => 'showHideRadio',
404 'rel' => 'dbMyisamWarning'
407 'class' => 'hideShowRadio',
408 'rel' => 'dbMyisamWarning'
412 $s .= $this->parent
->getHelpBox( 'config-mysql-engine-help' );
415 // If the current default charset is not supported, use a charset that is
416 $charsets = $this->getCharsets();
417 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
418 $this->setVar( '_MysqlCharset', reset( $charsets ) );
421 // Do charset selector
422 if ( count( $charsets ) >= 2 ) {
423 // getRadioSet() builds a set of labeled radio buttons.
424 // For grep: The following messages are used as the item labels:
425 // config-mysql-binary, config-mysql-utf8
426 $s .= $this->getRadioSet( [
427 'var' => '_MysqlCharset',
428 'label' => 'config-mysql-charset',
429 'itemLabelPrefix' => 'config-mysql-',
430 'values' => $charsets
432 $s .= $this->parent
->getHelpBox( 'config-mysql-charset-help' );
441 public function submitSettingsForm() {
442 $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
443 $status = $this->submitWebUserBox();
444 if ( !$status->isOK() ) {
448 // Validate the create checkbox
449 $canCreate = $this->canCreateAccounts();
451 $this->setVar( '_CreateDBAccount', false );
454 $create = $this->getVar( '_CreateDBAccount' );
458 // Test the web account
460 Database
::factory( 'mysql', [
461 'host' => $this->getVar( 'wgDBserver' ),
462 'user' => $this->getVar( 'wgDBuser' ),
463 'password' => $this->getVar( 'wgDBpassword' ),
466 'tablePrefix' => $this->getVar( 'wgDBprefix' )
468 } catch ( DBConnectionError
$e ) {
469 return Status
::newFatal( 'config-connection-error', $e->getMessage() );
473 // Validate engines and charsets
474 // This is done pre-submit already so it's just for security
475 $engines = $this->getEngines();
476 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
477 $this->setVar( '_MysqlEngine', reset( $engines ) );
479 $charsets = $this->getCharsets();
480 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
481 $this->setVar( '_MysqlCharset', reset( $charsets ) );
484 return Status
::newGood();
487 public function preInstall() {
488 # Add our user callback to installSteps, right before the tables are created.
491 'callback' => [ $this, 'setupUser' ],
493 $this->parent
->addInstallStep( $callback, 'tables' );
499 public function setupDatabase() {
500 $status = $this->getConnection();
501 if ( !$status->isOK() ) {
504 /** @var Database $conn */
505 $conn = $status->value
;
506 $dbName = $this->getVar( 'wgDBname' );
507 if ( !$conn->selectDB( $dbName ) ) {
509 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
512 $conn->selectDB( $dbName );
514 $this->setupSchemaVars();
522 public function setupUser() {
523 $dbUser = $this->getVar( 'wgDBuser' );
524 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
525 return Status
::newGood();
527 $status = $this->getConnection();
528 if ( !$status->isOK() ) {
532 $this->setupSchemaVars();
533 $dbName = $this->getVar( 'wgDBname' );
534 $this->db
->selectDB( $dbName );
535 $server = $this->getVar( 'wgDBserver' );
536 $password = $this->getVar( 'wgDBpassword' );
537 $grantableNames = [];
539 if ( $this->getVar( '_CreateDBAccount' ) ) {
540 // Before we blindly try to create a user that already has access,
541 try { // first attempt to connect to the database
542 Database
::factory( 'mysql', [
545 'password' => $password,
548 'tablePrefix' => $this->getVar( 'wgDBprefix' )
550 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
551 $tryToCreate = false;
552 } catch ( DBConnectionError
$e ) {
556 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
557 $tryToCreate = false;
560 if ( $tryToCreate ) {
564 'localhost.localdomain',
568 $createHostList = array_unique( $createHostList );
569 $escPass = $this->db
->addQuotes( $password );
571 foreach ( $createHostList as $host ) {
572 $fullName = $this->buildFullUserName( $dbUser, $host );
573 if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
575 $this->db
->begin( __METHOD__
);
576 $this->db
->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__
);
577 $this->db
->commit( __METHOD__
);
578 $grantableNames[] = $fullName;
579 } catch ( DBQueryError
$dqe ) {
580 if ( $this->db
->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
581 // User (probably) already exists
582 $this->db
->rollback( __METHOD__
);
583 $status->warning( 'config-install-user-alreadyexists', $dbUser );
584 $grantableNames[] = $fullName;
587 // If we couldn't create for some bizzare reason and the
588 // user probably doesn't exist, skip the grant
589 $this->db
->rollback( __METHOD__
);
590 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getMessage() );
594 $status->warning( 'config-install-user-alreadyexists', $dbUser );
595 $grantableNames[] = $fullName;
601 // Try to grant to all the users we know exist or we were able to create
602 $dbAllTables = $this->db
->addIdentifierQuotes( $dbName ) . '.*';
603 foreach ( $grantableNames as $name ) {
605 $this->db
->begin( __METHOD__
);
606 $this->db
->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__
);
607 $this->db
->commit( __METHOD__
);
608 } catch ( DBQueryError
$dqe ) {
609 $this->db
->rollback( __METHOD__
);
610 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getMessage() );
618 * Return a formal 'User'@'Host' username for use in queries
619 * @param string $name Username, quotes will be added
620 * @param string $host Hostname, quotes will be added
623 private function buildFullUserName( $name, $host ) {
624 return $this->db
->addQuotes( $name ) . '@' . $this->db
->addQuotes( $host );
628 * Try to see if the user account exists. Our "superuser" may not have
629 * access to mysql.user, so false means "no" or "maybe"
630 * @param string $host Hostname to check
631 * @param string $user Username to check
634 private function userDefinitelyExists( $host, $user ) {
636 $res = $this->db
->selectRow( 'mysql.user', [ 'Host', 'User' ],
637 [ 'Host' => $host, 'User' => $user ], __METHOD__
);
640 } catch ( DBQueryError
$dqe ) {
646 * Return any table options to be applied to all tables that don't
651 protected function getTableOptions() {
653 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
654 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
656 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
657 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
660 return implode( ', ', $options );
664 * Get variables to substitute into tables.sql and the SQL patch files.
668 public function getSchemaVars() {
670 'wgDBTableOptions' => $this->getTableOptions(),
671 'wgDBname' => $this->getVar( 'wgDBname' ),
672 'wgDBuser' => $this->getVar( 'wgDBuser' ),
673 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
677 public function getLocalSettings() {
678 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
679 $prefix = LocalSettingsGenerator
::escapePhpString( $this->getVar( 'wgDBprefix' ) );
680 $tblOpts = LocalSettingsGenerator
::escapePhpString( $this->getTableOptions() );
682 return "# MySQL specific settings
683 \$wgDBprefix = \"{$prefix}\";
685 # MySQL table options to use during installation or update
686 \$wgDBTableOptions = \"{$tblOpts}\";
688 # Experimental charset support for MySQL 5.0.
689 \$wgDBmysql5 = {$dbmysql5};";