Merge "Localisation updates from https://translatewiki.net."
[mediawiki.git] / includes / installer / MysqlInstaller.php
blob2d433244ae62a573dae78061dbebd54e31848d5e
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 = array(
33 'wgDBserver',
34 'wgDBname',
35 'wgDBuser',
36 'wgDBpassword',
37 'wgDBprefix',
38 'wgDBTableOptions',
39 'wgDBmysql5',
42 protected $internalDefaults = array(
43 '_MysqlEngine' => 'InnoDB',
44 '_MysqlCharset' => 'binary',
45 '_InstallUser' => 'root',
48 public $supportedEngines = array( 'InnoDB', 'MyISAM' );
50 public $minimumVersion = '5.0.2';
52 public $webUserPrivs = array(
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 array
77 public function getGlobalDefaults() {
78 return array();
81 /**
82 * @return string
84 public function getConnectForm() {
85 return $this->getTextBox(
86 'wgDBserver',
87 'config-db-host',
88 array(),
89 $this->parent->getHelpBox( 'config-db-host-help' )
90 ) .
91 Html::openElement( 'fieldset' ) .
92 Html::element( 'legend', array(), wfMessage( 'config-db-wiki-settings' )->text() ) .
93 $this->getTextBox( 'wgDBname', 'config-db-name', array( 'dir' => 'ltr' ),
94 $this->parent->getHelpBox( 'config-db-name-help' ) ) .
95 $this->getTextBox( 'wgDBprefix', 'config-db-prefix', array( 'dir' => 'ltr' ),
96 $this->parent->getHelpBox( 'config-db-prefix-help' ) ) .
97 Html::closeElement( 'fieldset' ) .
98 $this->getInstallUserBox();
101 public function submitConnectForm() {
102 // Get variables from the request.
103 $newValues = $this->setVarsFromRequest( array( 'wgDBserver', 'wgDBname', 'wgDBprefix' ) );
105 // Validate them.
106 $status = Status::newGood();
107 if ( !strlen( $newValues['wgDBserver'] ) ) {
108 $status->fatal( 'config-missing-db-host' );
110 if ( !strlen( $newValues['wgDBname'] ) ) {
111 $status->fatal( 'config-missing-db-name' );
112 } elseif ( !preg_match( '/^[a-z0-9+_-]+$/i', $newValues['wgDBname'] ) ) {
113 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
115 if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
116 $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
118 if ( !$status->isOK() ) {
119 return $status;
122 // Submit user box
123 $status = $this->submitInstallUserBox();
124 if ( !$status->isOK() ) {
125 return $status;
128 // Try to connect
129 $status = $this->getConnection();
130 if ( !$status->isOK() ) {
131 return $status;
134 * @var $conn DatabaseBase
136 $conn = $status->value;
138 // Check version
139 $version = $conn->getServerVersion();
140 if ( version_compare( $version, $this->minimumVersion ) < 0 ) {
141 return Status::newFatal( 'config-mysql-old', $this->minimumVersion, $version );
144 return $status;
148 * @return Status
150 public function openConnection() {
151 $status = Status::newGood();
152 try {
153 $db = DatabaseBase::factory( 'mysql', array(
154 'host' => $this->getVar( 'wgDBserver' ),
155 'user' => $this->getVar( '_InstallUser' ),
156 'password' => $this->getVar( '_InstallPassword' ),
157 'dbname' => false,
158 'flags' => 0,
159 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ) );
160 $status->value = $db;
161 } catch ( DBConnectionError $e ) {
162 $status->fatal( 'config-connection-error', $e->getMessage() );
165 return $status;
168 public function preUpgrade() {
169 global $wgDBuser, $wgDBpassword;
171 $status = $this->getConnection();
172 if ( !$status->isOK() ) {
173 $this->parent->showStatusError( $status );
175 return;
178 * @var $conn DatabaseBase
180 $conn = $status->value;
181 $conn->selectDB( $this->getVar( 'wgDBname' ) );
183 # Determine existing default character set
184 if ( $conn->tableExists( "revision", __METHOD__ ) ) {
185 $revision = $conn->buildLike( $this->getVar( 'wgDBprefix' ) . 'revision' );
186 $res = $conn->query( "SHOW TABLE STATUS $revision", __METHOD__ );
187 $row = $conn->fetchObject( $res );
188 if ( !$row ) {
189 $this->parent->showMessage( 'config-show-table-status' );
190 $existingSchema = false;
191 $existingEngine = false;
192 } else {
193 if ( preg_match( '/^latin1/', $row->Collation ) ) {
194 $existingSchema = 'latin1';
195 } elseif ( preg_match( '/^utf8/', $row->Collation ) ) {
196 $existingSchema = 'utf8';
197 } elseif ( preg_match( '/^binary/', $row->Collation ) ) {
198 $existingSchema = 'binary';
199 } else {
200 $existingSchema = false;
201 $this->parent->showMessage( 'config-unknown-collation' );
203 if ( isset( $row->Engine ) ) {
204 $existingEngine = $row->Engine;
205 } else {
206 $existingEngine = $row->Type;
209 } else {
210 $existingSchema = false;
211 $existingEngine = false;
214 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
215 $this->setVar( '_MysqlCharset', $existingSchema );
217 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
218 $this->setVar( '_MysqlEngine', $existingEngine );
221 # Normal user and password are selected after this step, so for now
222 # just copy these two
223 $wgDBuser = $this->getVar( '_InstallUser' );
224 $wgDBpassword = $this->getVar( '_InstallPassword' );
228 * Get a list of storage engines that are available and supported
230 * @return array
232 public function getEngines() {
233 $status = $this->getConnection();
236 * @var $conn DatabaseBase
238 $conn = $status->value;
240 $engines = array();
241 $res = $conn->query( 'SHOW ENGINES', __METHOD__ );
242 foreach ( $res as $row ) {
243 if ( $row->Support == 'YES' || $row->Support == 'DEFAULT' ) {
244 $engines[] = $row->Engine;
247 $engines = array_intersect( $this->supportedEngines, $engines );
249 return $engines;
253 * Get a list of character sets that are available and supported
255 * @return array
257 public function getCharsets() {
258 return array( 'binary', 'utf8' );
262 * Return true if the install user can create accounts
264 * @return bool
266 public function canCreateAccounts() {
267 $status = $this->getConnection();
268 if ( !$status->isOK() ) {
269 return false;
271 /** @var $conn DatabaseBase */
272 $conn = $status->value;
274 // Get current account name
275 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__ );
276 $parts = explode( '@', $currentName );
277 if ( count( $parts ) != 2 ) {
278 return false;
280 $quotedUser = $conn->addQuotes( $parts[0] ) .
281 '@' . $conn->addQuotes( $parts[1] );
283 // The user needs to have INSERT on mysql.* to be able to CREATE USER
284 // The grantee will be double-quoted in this query, as required
285 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
286 array( 'GRANTEE' => $quotedUser ), __METHOD__ );
287 $insertMysql = false;
288 $grantOptions = array_flip( $this->webUserPrivs );
289 foreach ( $res as $row ) {
290 if ( $row->PRIVILEGE_TYPE == 'INSERT' ) {
291 $insertMysql = true;
293 if ( $row->IS_GRANTABLE ) {
294 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
298 // Check for DB-specific privs for mysql.*
299 if ( !$insertMysql ) {
300 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
301 array(
302 'GRANTEE' => $quotedUser,
303 'TABLE_SCHEMA' => 'mysql',
304 'PRIVILEGE_TYPE' => 'INSERT',
305 ), __METHOD__ );
306 if ( $row ) {
307 $insertMysql = true;
311 if ( !$insertMysql ) {
312 return false;
315 // Check for DB-level grant options
316 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
317 array(
318 'GRANTEE' => $quotedUser,
319 'IS_GRANTABLE' => 1,
320 ), __METHOD__ );
321 foreach ( $res as $row ) {
322 $regex = $conn->likeToRegex( $row->TABLE_SCHEMA );
323 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
324 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
327 if ( count( $grantOptions ) ) {
328 // Can't grant everything
329 return false;
332 return true;
336 * @return string
338 public function getSettingsForm() {
339 if ( $this->canCreateAccounts() ) {
340 $noCreateMsg = false;
341 } else {
342 $noCreateMsg = 'config-db-web-no-create-privs';
344 $s = $this->getWebUserBox( $noCreateMsg );
346 // Do engine selector
347 $engines = $this->getEngines();
348 // If the current default engine is not supported, use an engine that is
349 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
350 $this->setVar( '_MysqlEngine', reset( $engines ) );
353 $s .= Xml::openElement( 'div', array(
354 'id' => 'dbMyisamWarning'
355 ) );
356 $myisamWarning = 'config-mysql-myisam-dep';
357 if ( count( $engines ) === 1 ) {
358 $myisamWarning = 'config-mysql-only-myisam-dep';
360 $s .= $this->parent->getWarningBox( wfMessage( $myisamWarning )->text() );
361 $s .= Xml::closeElement( 'div' );
363 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
364 $s .= Xml::openElement( 'script', array( 'type' => 'text/javascript' ) );
365 $s .= '$(\'#dbMyisamWarning\').hide();';
366 $s .= Xml::closeElement( 'script' );
369 if ( count( $engines ) >= 2 ) {
370 // getRadioSet() builds a set of labeled radio buttons.
371 // For grep: The following messages are used as the item labels:
372 // config-mysql-innodb, config-mysql-myisam
373 $s .= $this->getRadioSet( array(
374 'var' => '_MysqlEngine',
375 'label' => 'config-mysql-engine',
376 'itemLabelPrefix' => 'config-mysql-',
377 'values' => $engines,
378 'itemAttribs' => array(
379 'MyISAM' => array(
380 'class' => 'showHideRadio',
381 'rel' => 'dbMyisamWarning'
383 'InnoDB' => array(
384 'class' => 'hideShowRadio',
385 'rel' => 'dbMyisamWarning'
388 ) );
389 $s .= $this->parent->getHelpBox( 'config-mysql-engine-help' );
392 // If the current default charset is not supported, use a charset that is
393 $charsets = $this->getCharsets();
394 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
395 $this->setVar( '_MysqlCharset', reset( $charsets ) );
398 // Do charset selector
399 if ( count( $charsets ) >= 2 ) {
400 // getRadioSet() builds a set of labeled radio buttons.
401 // For grep: The following messages are used as the item labels:
402 // config-mysql-binary, config-mysql-utf8
403 $s .= $this->getRadioSet( array(
404 'var' => '_MysqlCharset',
405 'label' => 'config-mysql-charset',
406 'itemLabelPrefix' => 'config-mysql-',
407 'values' => $charsets
408 ) );
409 $s .= $this->parent->getHelpBox( 'config-mysql-charset-help' );
412 return $s;
416 * @return Status
418 public function submitSettingsForm() {
419 $this->setVarsFromRequest( array( '_MysqlEngine', '_MysqlCharset' ) );
420 $status = $this->submitWebUserBox();
421 if ( !$status->isOK() ) {
422 return $status;
425 // Validate the create checkbox
426 $canCreate = $this->canCreateAccounts();
427 if ( !$canCreate ) {
428 $this->setVar( '_CreateDBAccount', false );
429 $create = false;
430 } else {
431 $create = $this->getVar( '_CreateDBAccount' );
434 if ( !$create ) {
435 // Test the web account
436 try {
437 DatabaseBase::factory( 'mysql', array(
438 'host' => $this->getVar( 'wgDBserver' ),
439 'user' => $this->getVar( 'wgDBuser' ),
440 'password' => $this->getVar( 'wgDBpassword' ),
441 'dbname' => false,
442 'flags' => 0,
443 'tablePrefix' => $this->getVar( 'wgDBprefix' )
444 ) );
445 } catch ( DBConnectionError $e ) {
446 return Status::newFatal( 'config-connection-error', $e->getMessage() );
450 // Validate engines and charsets
451 // This is done pre-submit already so it's just for security
452 $engines = $this->getEngines();
453 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
454 $this->setVar( '_MysqlEngine', reset( $engines ) );
456 $charsets = $this->getCharsets();
457 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
458 $this->setVar( '_MysqlCharset', reset( $charsets ) );
461 return Status::newGood();
464 public function preInstall() {
465 # Add our user callback to installSteps, right before the tables are created.
466 $callback = array(
467 'name' => 'user',
468 'callback' => array( $this, 'setupUser' ),
470 $this->parent->addInstallStep( $callback, 'tables' );
474 * @return Status
476 public function setupDatabase() {
477 $status = $this->getConnection();
478 if ( !$status->isOK() ) {
479 return $status;
481 /** @var DatabaseBase $conn */
482 $conn = $status->value;
483 $dbName = $this->getVar( 'wgDBname' );
484 if ( !$conn->selectDB( $dbName ) ) {
485 $conn->query(
486 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
487 __METHOD__
489 $conn->selectDB( $dbName );
491 $this->setupSchemaVars();
493 return $status;
497 * @return Status
499 public function setupUser() {
500 $dbUser = $this->getVar( 'wgDBuser' );
501 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
502 return Status::newGood();
504 $status = $this->getConnection();
505 if ( !$status->isOK() ) {
506 return $status;
509 $this->setupSchemaVars();
510 $dbName = $this->getVar( 'wgDBname' );
511 $this->db->selectDB( $dbName );
512 $server = $this->getVar( 'wgDBserver' );
513 $password = $this->getVar( 'wgDBpassword' );
514 $grantableNames = array();
516 if ( $this->getVar( '_CreateDBAccount' ) ) {
517 // Before we blindly try to create a user that already has access,
518 try { // first attempt to connect to the database
519 DatabaseBase::factory( 'mysql', array(
520 'host' => $server,
521 'user' => $dbUser,
522 'password' => $password,
523 'dbname' => false,
524 'flags' => 0,
525 'tablePrefix' => $this->getVar( 'wgDBprefix' )
526 ) );
527 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
528 $tryToCreate = false;
529 } catch ( DBConnectionError $e ) {
530 $tryToCreate = true;
532 } else {
533 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
534 $tryToCreate = false;
537 if ( $tryToCreate ) {
538 $createHostList = array(
539 $server,
540 'localhost',
541 'localhost.localdomain',
545 $createHostList = array_unique( $createHostList );
546 $escPass = $this->db->addQuotes( $password );
548 foreach ( $createHostList as $host ) {
549 $fullName = $this->buildFullUserName( $dbUser, $host );
550 if ( !$this->userDefinitelyExists( $dbUser, $host ) ) {
551 try {
552 $this->db->begin( __METHOD__ );
553 $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
554 $this->db->commit( __METHOD__ );
555 $grantableNames[] = $fullName;
556 } catch ( DBQueryError $dqe ) {
557 if ( $this->db->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
558 // User (probably) already exists
559 $this->db->rollback( __METHOD__ );
560 $status->warning( 'config-install-user-alreadyexists', $dbUser );
561 $grantableNames[] = $fullName;
562 break;
563 } else {
564 // If we couldn't create for some bizzare reason and the
565 // user probably doesn't exist, skip the grant
566 $this->db->rollback( __METHOD__ );
567 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
570 } else {
571 $status->warning( 'config-install-user-alreadyexists', $dbUser );
572 $grantableNames[] = $fullName;
573 break;
578 // Try to grant to all the users we know exist or we were able to create
579 $dbAllTables = $this->db->addIdentifierQuotes( $dbName ) . '.*';
580 foreach ( $grantableNames as $name ) {
581 try {
582 $this->db->begin( __METHOD__ );
583 $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
584 $this->db->commit( __METHOD__ );
585 } catch ( DBQueryError $dqe ) {
586 $this->db->rollback( __METHOD__ );
587 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
591 return $status;
595 * Return a formal 'User'@'Host' username for use in queries
596 * @param string $name Username, quotes will be added
597 * @param string $host Hostname, quotes will be added
598 * @return String
600 private function buildFullUserName( $name, $host ) {
601 return $this->db->addQuotes( $name ) . '@' . $this->db->addQuotes( $host );
605 * Try to see if the user account exists. Our "superuser" may not have
606 * access to mysql.user, so false means "no" or "maybe"
607 * @param string $host Hostname to check
608 * @param string $user Username to check
609 * @return boolean
611 private function userDefinitelyExists( $host, $user ) {
612 try {
613 $res = $this->db->selectRow( 'mysql.user', array( 'Host', 'User' ),
614 array( 'Host' => $host, 'User' => $user ), __METHOD__ );
616 return (bool)$res;
617 } catch ( DBQueryError $dqe ) {
618 return false;
623 * Return any table options to be applied to all tables that don't
624 * override them.
626 * @return String
628 protected function getTableOptions() {
629 $options = array();
630 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
631 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
633 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
634 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
637 return implode( ', ', $options );
641 * Get variables to substitute into tables.sql and the SQL patch files.
643 * @return array
645 public function getSchemaVars() {
646 return array(
647 'wgDBTableOptions' => $this->getTableOptions(),
648 'wgDBname' => $this->getVar( 'wgDBname' ),
649 'wgDBuser' => $this->getVar( 'wgDBuser' ),
650 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
654 public function getLocalSettings() {
655 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
656 $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
657 $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
659 return "# MySQL specific settings
660 \$wgDBprefix = \"{$prefix}\";
662 # MySQL table options to use during installation or update
663 \$wgDBTableOptions = \"{$tblOpts}\";
665 # Experimental charset support for MySQL 5.0.
666 \$wgDBmysql5 = {$dbmysql5};";