Added release notes for 'ContentHandler::runLegacyHooks' removal
[mediawiki.git] / includes / installer / MysqlInstaller.php
blob72697739c887ae78f012574f1a7276ee579771f7
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 /**
25 * Class for setting up the MediaWiki database using MySQL.
27 * @ingroup Deployment
28 * @since 1.17
30 class MysqlInstaller extends DatabaseInstaller {
32 protected $globalNames = [
33 'wgDBserver',
34 'wgDBname',
35 'wgDBuser',
36 'wgDBpassword',
37 'wgDBprefix',
38 'wgDBTableOptions',
39 'wgDBmysql5',
42 protected $internalDefaults = [
43 '_MysqlEngine' => 'InnoDB',
44 '_MysqlCharset' => 'binary',
45 '_InstallUser' => 'root',
48 public $supportedEngines = [ 'InnoDB', 'MyISAM' ];
50 public $minimumVersion = '5.0.3';
52 public $webUserPrivs = [
53 'DELETE',
54 'INSERT',
55 'SELECT',
56 'UPDATE',
57 'CREATE TEMPORARY TABLES',
60 /**
61 * @return string
63 public function getName() {
64 return 'mysql';
67 /**
68 * @return bool
70 public function isCompiled() {
71 return self::checkExtension( 'mysql' ) || self::checkExtension( 'mysqli' );
74 /**
75 * @return string
77 public function getConnectForm() {
78 return $this->getTextBox(
79 'wgDBserver',
80 'config-db-host',
81 [],
82 $this->parent->getHelpBox( 'config-db-host-help' )
83 ) .
84 Html::openElement( 'fieldset' ) .
85 Html::element( 'legend', [], wfMessage( 'config-db-wiki-settings' )->text() ) .
86 $this->getTextBox( 'wgDBname', 'config-db-name', [ 'dir' => 'ltr' ],
87 $this->parent->getHelpBox( 'config-db-name-help' ) ) .
88 $this->getTextBox( 'wgDBprefix', 'config-db-prefix', [ 'dir' => 'ltr' ],
89 $this->parent->getHelpBox( 'config-db-prefix-help' ) ) .
90 Html::closeElement( 'fieldset' ) .
91 $this->getInstallUserBox();
94 public function submitConnectForm() {
95 // Get variables from the request.
96 $newValues = $this->setVarsFromRequest( [ 'wgDBserver', 'wgDBname', 'wgDBprefix' ] );
98 // Validate them.
99 $status = Status::newGood();
100 if ( !strlen( $newValues['wgDBserver'] ) ) {
101 $status->fatal( 'config-missing-db-host' );
103 if ( !strlen( $newValues['wgDBname'] ) ) {
104 $status->fatal( 'config-missing-db-name' );
105 } elseif ( !preg_match( '/^[a-z0-9+_-]+$/i', $newValues['wgDBname'] ) ) {
106 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
108 if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
109 $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
111 if ( !$status->isOK() ) {
112 return $status;
115 // Submit user box
116 $status = $this->submitInstallUserBox();
117 if ( !$status->isOK() ) {
118 return $status;
121 // Try to connect
122 $status = $this->getConnection();
123 if ( !$status->isOK() ) {
124 return $status;
127 * @var $conn Database
129 $conn = $status->value;
131 // Check version
132 $version = $conn->getServerVersion();
133 if ( version_compare( $version, $this->minimumVersion ) < 0 ) {
134 return Status::newFatal( 'config-mysql-old', $this->minimumVersion, $version );
137 return $status;
141 * @return Status
143 public function openConnection() {
144 $status = Status::newGood();
145 try {
146 $db = Database::factory( 'mysql', [
147 'host' => $this->getVar( 'wgDBserver' ),
148 'user' => $this->getVar( '_InstallUser' ),
149 'password' => $this->getVar( '_InstallPassword' ),
150 'dbname' => false,
151 'flags' => 0,
152 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ] );
153 $status->value = $db;
154 } catch ( DBConnectionError $e ) {
155 $status->fatal( 'config-connection-error', $e->getMessage() );
158 return $status;
161 public function preUpgrade() {
162 global $wgDBuser, $wgDBpassword;
164 $status = $this->getConnection();
165 if ( !$status->isOK() ) {
166 $this->parent->showStatusError( $status );
168 return;
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 = $conn->buildLike( $this->getVar( 'wgDBprefix' ) . 'revision' );
179 $res = $conn->query( "SHOW TABLE STATUS $revision", __METHOD__ );
180 $row = $conn->fetchObject( $res );
181 if ( !$row ) {
182 $this->parent->showMessage( 'config-show-table-status' );
183 $existingSchema = false;
184 $existingEngine = false;
185 } else {
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';
192 } else {
193 $existingSchema = false;
194 $this->parent->showMessage( 'config-unknown-collation' );
196 if ( isset( $row->Engine ) ) {
197 $existingEngine = $row->Engine;
198 } else {
199 $existingEngine = $row->Type;
202 } else {
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' );
221 * Get a list of storage engines that are available and supported
223 * @return array
225 public function getEngines() {
226 $status = $this->getConnection();
229 * @var $conn Database
231 $conn = $status->value;
233 $engines = [];
234 $res = $conn->query( 'SHOW ENGINES', __METHOD__ );
235 foreach ( $res as $row ) {
236 if ( $row->Support == 'YES' || $row->Support == 'DEFAULT' ) {
237 $engines[] = $row->Engine;
240 $engines = array_intersect( $this->supportedEngines, $engines );
242 return $engines;
246 * Get a list of character sets that are available and supported
248 * @return array
250 public function getCharsets() {
251 return [ 'binary', 'utf8' ];
255 * Return true if the install user can create accounts
257 * @return bool
259 public function canCreateAccounts() {
260 $status = $this->getConnection();
261 if ( !$status->isOK() ) {
262 return false;
264 /** @var $conn Database */
265 $conn = $status->value;
267 // Get current account name
268 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__ );
269 $parts = explode( '@', $currentName );
270 if ( count( $parts ) != 2 ) {
271 return false;
273 $quotedUser = $conn->addQuotes( $parts[0] ) .
274 '@' . $conn->addQuotes( $parts[1] );
276 // The user needs to have INSERT on mysql.* to be able to CREATE USER
277 // The grantee will be double-quoted in this query, as required
278 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
279 [ 'GRANTEE' => $quotedUser ], __METHOD__ );
280 $insertMysql = false;
281 $grantOptions = array_flip( $this->webUserPrivs );
282 foreach ( $res as $row ) {
283 if ( $row->PRIVILEGE_TYPE == 'INSERT' ) {
284 $insertMysql = true;
286 if ( $row->IS_GRANTABLE ) {
287 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
291 // Check for DB-specific privs for mysql.*
292 if ( !$insertMysql ) {
293 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
295 'GRANTEE' => $quotedUser,
296 'TABLE_SCHEMA' => 'mysql',
297 'PRIVILEGE_TYPE' => 'INSERT',
298 ], __METHOD__ );
299 if ( $row ) {
300 $insertMysql = true;
304 if ( !$insertMysql ) {
305 return false;
308 // Check for DB-level grant options
309 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
311 'GRANTEE' => $quotedUser,
312 'IS_GRANTABLE' => 1,
313 ], __METHOD__ );
314 foreach ( $res as $row ) {
315 $regex = $this->likeToRegex( $row->TABLE_SCHEMA );
316 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
317 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
320 if ( count( $grantOptions ) ) {
321 // Can't grant everything
322 return false;
325 return true;
329 * Convert a wildcard (as used in LIKE) to a regex
330 * Slashes are escaped, slash terminators included
332 protected function likeToRegex( $wildcard ) {
333 $r = preg_quote( $wildcard, '/' );
334 $r = strtr( $r, [
335 '%' => '.*',
336 '_' => '.'
337 ] );
338 return "/$r/s";
342 * @return string
344 public function getSettingsForm() {
345 if ( $this->canCreateAccounts() ) {
346 $noCreateMsg = false;
347 } else {
348 $noCreateMsg = 'config-db-web-no-create-privs';
350 $s = $this->getWebUserBox( $noCreateMsg );
352 // Do engine selector
353 $engines = $this->getEngines();
354 // If the current default engine is not supported, use an engine that is
355 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
356 $this->setVar( '_MysqlEngine', reset( $engines ) );
359 $s .= Xml::openElement( 'div', [
360 'id' => 'dbMyisamWarning'
361 ] );
362 $myisamWarning = 'config-mysql-myisam-dep';
363 if ( count( $engines ) === 1 ) {
364 $myisamWarning = 'config-mysql-only-myisam-dep';
366 $s .= $this->parent->getWarningBox( wfMessage( $myisamWarning )->text() );
367 $s .= Xml::closeElement( 'div' );
369 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
370 $s .= Xml::openElement( 'script' );
371 $s .= '$(\'#dbMyisamWarning\').hide();';
372 $s .= Xml::closeElement( 'script' );
375 if ( count( $engines ) >= 2 ) {
376 // getRadioSet() builds a set of labeled radio buttons.
377 // For grep: The following messages are used as the item labels:
378 // config-mysql-innodb, config-mysql-myisam
379 $s .= $this->getRadioSet( [
380 'var' => '_MysqlEngine',
381 'label' => 'config-mysql-engine',
382 'itemLabelPrefix' => 'config-mysql-',
383 'values' => $engines,
384 'itemAttribs' => [
385 'MyISAM' => [
386 'class' => 'showHideRadio',
387 'rel' => 'dbMyisamWarning'
389 'InnoDB' => [
390 'class' => 'hideShowRadio',
391 'rel' => 'dbMyisamWarning'
394 ] );
395 $s .= $this->parent->getHelpBox( 'config-mysql-engine-help' );
398 // If the current default charset is not supported, use a charset that is
399 $charsets = $this->getCharsets();
400 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
401 $this->setVar( '_MysqlCharset', reset( $charsets ) );
404 // Do charset selector
405 if ( count( $charsets ) >= 2 ) {
406 // getRadioSet() builds a set of labeled radio buttons.
407 // For grep: The following messages are used as the item labels:
408 // config-mysql-binary, config-mysql-utf8
409 $s .= $this->getRadioSet( [
410 'var' => '_MysqlCharset',
411 'label' => 'config-mysql-charset',
412 'itemLabelPrefix' => 'config-mysql-',
413 'values' => $charsets
414 ] );
415 $s .= $this->parent->getHelpBox( 'config-mysql-charset-help' );
418 return $s;
422 * @return Status
424 public function submitSettingsForm() {
425 $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
426 $status = $this->submitWebUserBox();
427 if ( !$status->isOK() ) {
428 return $status;
431 // Validate the create checkbox
432 $canCreate = $this->canCreateAccounts();
433 if ( !$canCreate ) {
434 $this->setVar( '_CreateDBAccount', false );
435 $create = false;
436 } else {
437 $create = $this->getVar( '_CreateDBAccount' );
440 if ( !$create ) {
441 // Test the web account
442 try {
443 Database::factory( 'mysql', [
444 'host' => $this->getVar( 'wgDBserver' ),
445 'user' => $this->getVar( 'wgDBuser' ),
446 'password' => $this->getVar( 'wgDBpassword' ),
447 'dbname' => false,
448 'flags' => 0,
449 'tablePrefix' => $this->getVar( 'wgDBprefix' )
450 ] );
451 } catch ( DBConnectionError $e ) {
452 return Status::newFatal( 'config-connection-error', $e->getMessage() );
456 // Validate engines and charsets
457 // This is done pre-submit already so it's just for security
458 $engines = $this->getEngines();
459 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
460 $this->setVar( '_MysqlEngine', reset( $engines ) );
462 $charsets = $this->getCharsets();
463 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
464 $this->setVar( '_MysqlCharset', reset( $charsets ) );
467 return Status::newGood();
470 public function preInstall() {
471 # Add our user callback to installSteps, right before the tables are created.
472 $callback = [
473 'name' => 'user',
474 'callback' => [ $this, 'setupUser' ],
476 $this->parent->addInstallStep( $callback, 'tables' );
480 * @return Status
482 public function setupDatabase() {
483 $status = $this->getConnection();
484 if ( !$status->isOK() ) {
485 return $status;
487 /** @var Database $conn */
488 $conn = $status->value;
489 $dbName = $this->getVar( 'wgDBname' );
490 if ( !$conn->selectDB( $dbName ) ) {
491 $conn->query(
492 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
493 __METHOD__
495 $conn->selectDB( $dbName );
497 $this->setupSchemaVars();
499 return $status;
503 * @return Status
505 public function setupUser() {
506 $dbUser = $this->getVar( 'wgDBuser' );
507 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
508 return Status::newGood();
510 $status = $this->getConnection();
511 if ( !$status->isOK() ) {
512 return $status;
515 $this->setupSchemaVars();
516 $dbName = $this->getVar( 'wgDBname' );
517 $this->db->selectDB( $dbName );
518 $server = $this->getVar( 'wgDBserver' );
519 $password = $this->getVar( 'wgDBpassword' );
520 $grantableNames = [];
522 if ( $this->getVar( '_CreateDBAccount' ) ) {
523 // Before we blindly try to create a user that already has access,
524 try { // first attempt to connect to the database
525 Database::factory( 'mysql', [
526 'host' => $server,
527 'user' => $dbUser,
528 'password' => $password,
529 'dbname' => false,
530 'flags' => 0,
531 'tablePrefix' => $this->getVar( 'wgDBprefix' )
532 ] );
533 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
534 $tryToCreate = false;
535 } catch ( DBConnectionError $e ) {
536 $tryToCreate = true;
538 } else {
539 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
540 $tryToCreate = false;
543 if ( $tryToCreate ) {
544 $createHostList = [
545 $server,
546 'localhost',
547 'localhost.localdomain',
551 $createHostList = array_unique( $createHostList );
552 $escPass = $this->db->addQuotes( $password );
554 foreach ( $createHostList as $host ) {
555 $fullName = $this->buildFullUserName( $dbUser, $host );
556 if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
557 try {
558 $this->db->begin( __METHOD__ );
559 $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
560 $this->db->commit( __METHOD__ );
561 $grantableNames[] = $fullName;
562 } catch ( DBQueryError $dqe ) {
563 if ( $this->db->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
564 // User (probably) already exists
565 $this->db->rollback( __METHOD__ );
566 $status->warning( 'config-install-user-alreadyexists', $dbUser );
567 $grantableNames[] = $fullName;
568 break;
569 } else {
570 // If we couldn't create for some bizzare reason and the
571 // user probably doesn't exist, skip the grant
572 $this->db->rollback( __METHOD__ );
573 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
576 } else {
577 $status->warning( 'config-install-user-alreadyexists', $dbUser );
578 $grantableNames[] = $fullName;
579 break;
584 // Try to grant to all the users we know exist or we were able to create
585 $dbAllTables = $this->db->addIdentifierQuotes( $dbName ) . '.*';
586 foreach ( $grantableNames as $name ) {
587 try {
588 $this->db->begin( __METHOD__ );
589 $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
590 $this->db->commit( __METHOD__ );
591 } catch ( DBQueryError $dqe ) {
592 $this->db->rollback( __METHOD__ );
593 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
597 return $status;
601 * Return a formal 'User'@'Host' username for use in queries
602 * @param string $name Username, quotes will be added
603 * @param string $host Hostname, quotes will be added
604 * @return string
606 private function buildFullUserName( $name, $host ) {
607 return $this->db->addQuotes( $name ) . '@' . $this->db->addQuotes( $host );
611 * Try to see if the user account exists. Our "superuser" may not have
612 * access to mysql.user, so false means "no" or "maybe"
613 * @param string $host Hostname to check
614 * @param string $user Username to check
615 * @return bool
617 private function userDefinitelyExists( $host, $user ) {
618 try {
619 $res = $this->db->selectRow( 'mysql.user', [ 'Host', 'User' ],
620 [ 'Host' => $host, 'User' => $user ], __METHOD__ );
622 return (bool)$res;
623 } catch ( DBQueryError $dqe ) {
624 return false;
629 * Return any table options to be applied to all tables that don't
630 * override them.
632 * @return string
634 protected function getTableOptions() {
635 $options = [];
636 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
637 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
639 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
640 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
643 return implode( ', ', $options );
647 * Get variables to substitute into tables.sql and the SQL patch files.
649 * @return array
651 public function getSchemaVars() {
652 return [
653 'wgDBTableOptions' => $this->getTableOptions(),
654 'wgDBname' => $this->getVar( 'wgDBname' ),
655 'wgDBuser' => $this->getVar( 'wgDBuser' ),
656 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
660 public function getLocalSettings() {
661 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
662 $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
663 $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
665 return "# MySQL specific settings
666 \$wgDBprefix = \"{$prefix}\";
668 # MySQL table options to use during installation or update
669 \$wgDBTableOptions = \"{$tblOpts}\";
671 # Experimental charset support for MySQL 5.0.
672 \$wgDBmysql5 = {$dbmysql5};";