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 static $minimumVersion = '5.5.8';
55 protected static $notMiniumumVerisonMessage = 'config-mysql-old';
57 public $webUserPrivs = [
62 'CREATE TEMPORARY TABLES',
68 public function getName() {
75 public function isCompiled() {
76 return self
::checkExtension( 'mysqli' );
82 public function getConnectForm() {
83 return $this->getTextBox(
87 $this->parent
->getHelpBox( 'config-db-host-help' )
89 Html
::openElement( 'fieldset' ) .
90 Html
::element( 'legend', [], wfMessage( 'config-db-wiki-settings' )->text() ) .
91 $this->getTextBox( 'wgDBname', 'config-db-name', [ 'dir' => 'ltr' ],
92 $this->parent
->getHelpBox( 'config-db-name-help' ) ) .
93 $this->getTextBox( 'wgDBprefix', 'config-db-prefix', [ 'dir' => 'ltr' ],
94 $this->parent
->getHelpBox( 'config-db-prefix-help' ) ) .
95 Html
::closeElement( 'fieldset' ) .
96 $this->getInstallUserBox();
99 public function submitConnectForm() {
100 // Get variables from the request.
101 $newValues = $this->setVarsFromRequest( [ 'wgDBserver', 'wgDBname', 'wgDBprefix' ] );
104 $status = Status
::newGood();
105 if ( !strlen( $newValues['wgDBserver'] ) ) {
106 $status->fatal( 'config-missing-db-host' );
108 if ( !strlen( $newValues['wgDBname'] ) ) {
109 $status->fatal( 'config-missing-db-name' );
110 } elseif ( !preg_match( '/^[a-z0-9+_-]+$/i', $newValues['wgDBname'] ) ) {
111 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
113 if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
114 $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
116 if ( !$status->isOK() ) {
121 $status = $this->submitInstallUserBox();
122 if ( !$status->isOK() ) {
127 $status = $this->getConnection();
128 if ( !$status->isOK() ) {
132 * @var $conn Database
134 $conn = $status->value
;
137 return static::meetsMinimumRequirement( $conn->getServerVersion() );
143 public function openConnection() {
144 $status = Status
::newGood();
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
->showStatusError( $status );
171 * @var $conn Database
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 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' );
222 * @param string $escapeChar
225 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
226 return str_replace( [ $escapeChar, '%', '_' ],
227 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
232 * Get a list of storage engines that are available and supported
236 public function getEngines() {
237 $status = $this->getConnection();
240 * @var $conn Database
242 $conn = $status->value
;
245 $res = $conn->query( 'SHOW ENGINES', __METHOD__
);
246 foreach ( $res as $row ) {
247 if ( $row->Support
== 'YES' ||
$row->Support
== 'DEFAULT' ) {
248 $engines[] = $row->Engine
;
251 $engines = array_intersect( $this->supportedEngines
, $engines );
257 * Get a list of character sets that are available and supported
261 public function getCharsets() {
262 return [ 'binary', 'utf8' ];
266 * Return true if the install user can create accounts
270 public function canCreateAccounts() {
271 $status = $this->getConnection();
272 if ( !$status->isOK() ) {
275 /** @var Database $conn */
276 $conn = $status->value
;
278 // Get current account name
279 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__
);
280 $parts = explode( '@', $currentName );
281 if ( count( $parts ) != 2 ) {
284 $quotedUser = $conn->addQuotes( $parts[0] ) .
285 '@' . $conn->addQuotes( $parts[1] );
287 // The user needs to have INSERT on mysql.* to be able to CREATE USER
288 // The grantee will be double-quoted in this query, as required
289 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
290 [ 'GRANTEE' => $quotedUser ], __METHOD__
);
291 $insertMysql = false;
292 $grantOptions = array_flip( $this->webUserPrivs
);
293 foreach ( $res as $row ) {
294 if ( $row->PRIVILEGE_TYPE
== 'INSERT' ) {
297 if ( $row->IS_GRANTABLE
) {
298 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
302 // Check for DB-specific privs for mysql.*
303 if ( !$insertMysql ) {
304 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
306 'GRANTEE' => $quotedUser,
307 'TABLE_SCHEMA' => 'mysql',
308 'PRIVILEGE_TYPE' => 'INSERT',
315 if ( !$insertMysql ) {
319 // Check for DB-level grant options
320 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
322 'GRANTEE' => $quotedUser,
325 foreach ( $res as $row ) {
326 $regex = $this->likeToRegex( $row->TABLE_SCHEMA
);
327 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
328 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
331 if ( count( $grantOptions ) ) {
332 // Can't grant everything
340 * Convert a wildcard (as used in LIKE) to a regex
341 * Slashes are escaped, slash terminators included
342 * @param string $wildcard
345 protected function likeToRegex( $wildcard ) {
346 $r = preg_quote( $wildcard, '/' );
357 public function getSettingsForm() {
358 if ( $this->canCreateAccounts() ) {
359 $noCreateMsg = false;
361 $noCreateMsg = 'config-db-web-no-create-privs';
363 $s = $this->getWebUserBox( $noCreateMsg );
365 // Do engine selector
366 $engines = $this->getEngines();
367 // If the current default engine is not supported, use an engine that is
368 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
369 $this->setVar( '_MysqlEngine', reset( $engines ) );
372 $s .= Xml
::openElement( 'div', [
373 'id' => 'dbMyisamWarning'
375 $myisamWarning = 'config-mysql-myisam-dep';
376 if ( count( $engines ) === 1 ) {
377 $myisamWarning = 'config-mysql-only-myisam-dep';
379 $s .= $this->parent
->getWarningBox( wfMessage( $myisamWarning )->text() );
380 $s .= Xml
::closeElement( 'div' );
382 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
383 $s .= Xml
::openElement( 'script' );
384 $s .= '$(\'#dbMyisamWarning\').hide();';
385 $s .= Xml
::closeElement( 'script' );
388 if ( count( $engines ) >= 2 ) {
389 // getRadioSet() builds a set of labeled radio buttons.
390 // For grep: The following messages are used as the item labels:
391 // config-mysql-innodb, config-mysql-myisam
392 $s .= $this->getRadioSet( [
393 'var' => '_MysqlEngine',
394 'label' => 'config-mysql-engine',
395 'itemLabelPrefix' => 'config-mysql-',
396 'values' => $engines,
399 'class' => 'showHideRadio',
400 'rel' => 'dbMyisamWarning'
403 'class' => 'hideShowRadio',
404 'rel' => 'dbMyisamWarning'
408 $s .= $this->parent
->getHelpBox( 'config-mysql-engine-help' );
411 // If the current default charset is not supported, use a charset that is
412 $charsets = $this->getCharsets();
413 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
414 $this->setVar( '_MysqlCharset', reset( $charsets ) );
417 // Do charset selector
418 if ( count( $charsets ) >= 2 ) {
419 // getRadioSet() builds a set of labeled radio buttons.
420 // For grep: The following messages are used as the item labels:
421 // config-mysql-binary, config-mysql-utf8
422 $s .= $this->getRadioSet( [
423 'var' => '_MysqlCharset',
424 'label' => 'config-mysql-charset',
425 'itemLabelPrefix' => 'config-mysql-',
426 'values' => $charsets
428 $s .= $this->parent
->getHelpBox( 'config-mysql-charset-help' );
437 public function submitSettingsForm() {
438 $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
439 $status = $this->submitWebUserBox();
440 if ( !$status->isOK() ) {
444 // Validate the create checkbox
445 $canCreate = $this->canCreateAccounts();
447 $this->setVar( '_CreateDBAccount', false );
450 $create = $this->getVar( '_CreateDBAccount' );
454 // Test the web account
456 Database
::factory( 'mysql', [
457 'host' => $this->getVar( 'wgDBserver' ),
458 'user' => $this->getVar( 'wgDBuser' ),
459 'password' => $this->getVar( 'wgDBpassword' ),
462 'tablePrefix' => $this->getVar( 'wgDBprefix' )
464 } catch ( DBConnectionError
$e ) {
465 return Status
::newFatal( 'config-connection-error', $e->getMessage() );
469 // Validate engines and charsets
470 // This is done pre-submit already so it's just for security
471 $engines = $this->getEngines();
472 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
473 $this->setVar( '_MysqlEngine', reset( $engines ) );
475 $charsets = $this->getCharsets();
476 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
477 $this->setVar( '_MysqlCharset', reset( $charsets ) );
480 return Status
::newGood();
483 public function preInstall() {
484 # Add our user callback to installSteps, right before the tables are created.
487 'callback' => [ $this, 'setupUser' ],
489 $this->parent
->addInstallStep( $callback, 'tables' );
495 public function setupDatabase() {
496 $status = $this->getConnection();
497 if ( !$status->isOK() ) {
500 /** @var Database $conn */
501 $conn = $status->value
;
502 $dbName = $this->getVar( 'wgDBname' );
503 if ( !$conn->selectDB( $dbName ) ) {
505 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
508 $conn->selectDB( $dbName );
510 $this->setupSchemaVars();
518 public function setupUser() {
519 $dbUser = $this->getVar( 'wgDBuser' );
520 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
521 return Status
::newGood();
523 $status = $this->getConnection();
524 if ( !$status->isOK() ) {
528 $this->setupSchemaVars();
529 $dbName = $this->getVar( 'wgDBname' );
530 $this->db
->selectDB( $dbName );
531 $server = $this->getVar( 'wgDBserver' );
532 $password = $this->getVar( 'wgDBpassword' );
533 $grantableNames = [];
535 if ( $this->getVar( '_CreateDBAccount' ) ) {
536 // Before we blindly try to create a user that already has access,
537 try { // first attempt to connect to the database
538 Database
::factory( 'mysql', [
541 'password' => $password,
544 'tablePrefix' => $this->getVar( 'wgDBprefix' )
546 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
547 $tryToCreate = false;
548 } catch ( DBConnectionError
$e ) {
552 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
553 $tryToCreate = false;
556 if ( $tryToCreate ) {
560 'localhost.localdomain',
564 $createHostList = array_unique( $createHostList );
565 $escPass = $this->db
->addQuotes( $password );
567 foreach ( $createHostList as $host ) {
568 $fullName = $this->buildFullUserName( $dbUser, $host );
569 if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
571 $this->db
->begin( __METHOD__
);
572 $this->db
->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__
);
573 $this->db
->commit( __METHOD__
);
574 $grantableNames[] = $fullName;
575 } catch ( DBQueryError
$dqe ) {
576 if ( $this->db
->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
577 // User (probably) already exists
578 $this->db
->rollback( __METHOD__
);
579 $status->warning( 'config-install-user-alreadyexists', $dbUser );
580 $grantableNames[] = $fullName;
583 // If we couldn't create for some bizzare reason and the
584 // user probably doesn't exist, skip the grant
585 $this->db
->rollback( __METHOD__
);
586 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getMessage() );
590 $status->warning( 'config-install-user-alreadyexists', $dbUser );
591 $grantableNames[] = $fullName;
597 // Try to grant to all the users we know exist or we were able to create
598 $dbAllTables = $this->db
->addIdentifierQuotes( $dbName ) . '.*';
599 foreach ( $grantableNames as $name ) {
601 $this->db
->begin( __METHOD__
);
602 $this->db
->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__
);
603 $this->db
->commit( __METHOD__
);
604 } catch ( DBQueryError
$dqe ) {
605 $this->db
->rollback( __METHOD__
);
606 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getMessage() );
614 * Return a formal 'User'@'Host' username for use in queries
615 * @param string $name Username, quotes will be added
616 * @param string $host Hostname, quotes will be added
619 private function buildFullUserName( $name, $host ) {
620 return $this->db
->addQuotes( $name ) . '@' . $this->db
->addQuotes( $host );
624 * Try to see if the user account exists. Our "superuser" may not have
625 * access to mysql.user, so false means "no" or "maybe"
626 * @param string $host Hostname to check
627 * @param string $user Username to check
630 private function userDefinitelyExists( $host, $user ) {
632 $res = $this->db
->selectRow( 'mysql.user', [ 'Host', 'User' ],
633 [ 'Host' => $host, 'User' => $user ], __METHOD__
);
636 } catch ( DBQueryError
$dqe ) {
642 * Return any table options to be applied to all tables that don't
647 protected function getTableOptions() {
649 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
650 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
652 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
653 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
656 return implode( ', ', $options );
660 * Get variables to substitute into tables.sql and the SQL patch files.
664 public function getSchemaVars() {
666 'wgDBTableOptions' => $this->getTableOptions(),
667 'wgDBname' => $this->getVar( 'wgDBname' ),
668 'wgDBuser' => $this->getVar( 'wgDBuser' ),
669 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
673 public function getLocalSettings() {
674 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
675 $prefix = LocalSettingsGenerator
::escapePhpString( $this->getVar( 'wgDBprefix' ) );
676 $tblOpts = LocalSettingsGenerator
::escapePhpString( $this->getTableOptions() );
678 return "# MySQL specific settings
679 \$wgDBprefix = \"{$prefix}\";
681 # MySQL table options to use during installation or update
682 \$wgDBTableOptions = \"{$tblOpts}\";
684 # Experimental charset support for MySQL 5.0.
685 \$wgDBmysql5 = {$dbmysql5};";