Merge "Typo fix"
[mediawiki.git] / includes / installer / MysqlInstaller.php
blobe0bf3d7ee7cf0f5ca60f5f3c23d910cd61a64db3
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 public function __construct( $parent ) {
68 parent::__construct( $parent );
71 /**
72 * @return Bool
74 public function isCompiled() {
75 return self::checkExtension( 'mysql' );
78 /**
79 * @return array
81 public function getGlobalDefaults() {
82 return array();
85 /**
86 * @return string
88 public function getConnectForm() {
89 return $this->getTextBox( 'wgDBserver', 'config-db-host', array(), $this->parent->getHelpBox( 'config-db-host-help' ) ) .
90 Html::openElement( 'fieldset' ) .
91 Html::element( 'legend', array(), wfMessage( 'config-db-wiki-settings' )->text() ) .
92 $this->getTextBox( 'wgDBname', 'config-db-name', array( 'dir' => 'ltr' ), $this->parent->getHelpBox( 'config-db-name-help' ) ) .
93 $this->getTextBox( 'wgDBprefix', 'config-db-prefix', array( 'dir' => 'ltr' ), $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( array( '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 DatabaseBase
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 = new DatabaseMysql(
151 $this->getVar( 'wgDBserver' ),
152 $this->getVar( '_InstallUser' ),
153 $this->getVar( '_InstallPassword' ),
154 false,
156 $this->getVar( 'wgDBprefix' )
158 $status->value = $db;
159 } catch ( DBConnectionError $e ) {
160 $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 );
171 return;
174 * @var $conn DatabaseBase
176 $conn = $status->value;
177 $conn->selectDB( $this->getVar( 'wgDBname' ) );
179 # Determine existing default character set
180 if ( $conn->tableExists( "revision", __METHOD__ ) ) {
181 $revision = $conn->buildLike( $this->getVar( 'wgDBprefix' ) . 'revision' );
182 $res = $conn->query( "SHOW TABLE STATUS $revision", __METHOD__ );
183 $row = $conn->fetchObject( $res );
184 if ( !$row ) {
185 $this->parent->showMessage( 'config-show-table-status' );
186 $existingSchema = false;
187 $existingEngine = false;
188 } else {
189 if ( preg_match( '/^latin1/', $row->Collation ) ) {
190 $existingSchema = 'latin1';
191 } elseif ( preg_match( '/^utf8/', $row->Collation ) ) {
192 $existingSchema = 'utf8';
193 } elseif ( preg_match( '/^binary/', $row->Collation ) ) {
194 $existingSchema = 'binary';
195 } else {
196 $existingSchema = false;
197 $this->parent->showMessage( 'config-unknown-collation' );
199 if ( isset( $row->Engine ) ) {
200 $existingEngine = $row->Engine;
201 } else {
202 $existingEngine = $row->Type;
205 } else {
206 $existingSchema = false;
207 $existingEngine = false;
210 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
211 $this->setVar( '_MysqlCharset', $existingSchema );
213 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
214 $this->setVar( '_MysqlEngine', $existingEngine );
217 # Normal user and password are selected after this step, so for now
218 # just copy these two
219 $wgDBuser = $this->getVar( '_InstallUser' );
220 $wgDBpassword = $this->getVar( '_InstallPassword' );
224 * Get a list of storage engines that are available and supported
226 * @return array
228 public function getEngines() {
229 $status = $this->getConnection();
232 * @var $conn DatabaseBase
234 $conn = $status->value;
236 $engines = array();
237 $res = $conn->query( 'SHOW ENGINES', __METHOD__ );
238 foreach ( $res as $row ) {
239 if ( $row->Support == 'YES' || $row->Support == 'DEFAULT' ) {
240 $engines[] = $row->Engine;
243 $engines = array_intersect( $this->supportedEngines, $engines );
244 return $engines;
248 * Get a list of character sets that are available and supported
250 * @return array
252 public function getCharsets() {
253 return array( 'binary', 'utf8' );
257 * Return true if the install user can create accounts
259 * @return bool
261 public function canCreateAccounts() {
262 $status = $this->getConnection();
263 if ( !$status->isOK() ) {
264 return false;
267 * @var $conn DatabaseBase
269 $conn = $status->value;
271 // Get current account name
272 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__ );
273 $parts = explode( '@', $currentName );
274 if ( count( $parts ) != 2 ) {
275 return false;
277 $quotedUser = $conn->addQuotes( $parts[0] ) .
278 '@' . $conn->addQuotes( $parts[1] );
280 // The user needs to have INSERT on mysql.* to be able to CREATE USER
281 // The grantee will be double-quoted in this query, as required
282 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
283 array( 'GRANTEE' => $quotedUser ), __METHOD__ );
284 $insertMysql = false;
285 $grantOptions = array_flip( $this->webUserPrivs );
286 foreach ( $res as $row ) {
287 if ( $row->PRIVILEGE_TYPE == 'INSERT' ) {
288 $insertMysql = true;
290 if ( $row->IS_GRANTABLE ) {
291 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
295 // Check for DB-specific privs for mysql.*
296 if ( !$insertMysql ) {
297 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
298 array(
299 'GRANTEE' => $quotedUser,
300 'TABLE_SCHEMA' => 'mysql',
301 'PRIVILEGE_TYPE' => 'INSERT',
302 ), __METHOD__ );
303 if ( $row ) {
304 $insertMysql = true;
308 if ( !$insertMysql ) {
309 return false;
312 // Check for DB-level grant options
313 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
314 array(
315 'GRANTEE' => $quotedUser,
316 'IS_GRANTABLE' => 1,
317 ), __METHOD__ );
318 foreach ( $res as $row ) {
319 $regex = $conn->likeToRegex( $row->TABLE_SCHEMA );
320 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
321 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
324 if ( count( $grantOptions ) ) {
325 // Can't grant everything
326 return false;
328 return true;
332 * @return string
334 public function getSettingsForm() {
335 if ( $this->canCreateAccounts() ) {
336 $noCreateMsg = false;
337 } else {
338 $noCreateMsg = 'config-db-web-no-create-privs';
340 $s = $this->getWebUserBox( $noCreateMsg );
342 // Do engine selector
343 $engines = $this->getEngines();
344 // If the current default engine is not supported, use an engine that is
345 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
346 $this->setVar( '_MysqlEngine', reset( $engines ) );
349 $s .= Xml::openElement( 'div', array(
350 'id' => 'dbMyisamWarning'
352 $myisamWarning = 'config-mysql-myisam-dep';
353 if ( count( $engines ) === 1 ) {
354 $myisamWarning = 'config-mysql-only-myisam-dep';
356 $s .= $this->parent->getWarningBox( wfMessage( $myisamWarning )->text() );
357 $s .= Xml::closeElement( 'div' );
359 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
360 $s .= Xml::openElement( 'script', array( 'type' => 'text/javascript' ) );
361 $s .= '$(\'#dbMyisamWarning\').hide();';
362 $s .= Xml::closeElement( 'script' );
365 if ( count( $engines ) >= 2 ) {
366 // getRadioSet() builds a set of labeled radio buttons.
367 // For grep: The following messages are used as the item labels:
368 // config-mysql-innodb, config-mysql-myisam
369 $s .= $this->getRadioSet( array(
370 'var' => '_MysqlEngine',
371 'label' => 'config-mysql-engine',
372 'itemLabelPrefix' => 'config-mysql-',
373 'values' => $engines,
374 'itemAttribs' => array(
375 'MyISAM' => array(
376 'class' => 'showHideRadio',
377 'rel' => 'dbMyisamWarning'
379 'InnoDB' => array(
380 'class' => 'hideShowRadio',
381 'rel' => 'dbMyisamWarning'
383 )));
384 $s .= $this->parent->getHelpBox( 'config-mysql-engine-help' );
387 // If the current default charset is not supported, use a charset that is
388 $charsets = $this->getCharsets();
389 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
390 $this->setVar( '_MysqlCharset', reset( $charsets ) );
393 // Do charset selector
394 if ( count( $charsets ) >= 2 ) {
395 // getRadioSet() builds a set of labeled radio buttons.
396 // For grep: The following messages are used as the item labels:
397 // config-mysql-binary, config-mysql-utf8
398 $s .= $this->getRadioSet( array(
399 'var' => '_MysqlCharset',
400 'label' => 'config-mysql-charset',
401 'itemLabelPrefix' => 'config-mysql-',
402 'values' => $charsets
404 $s .= $this->parent->getHelpBox( 'config-mysql-charset-help' );
407 return $s;
411 * @return Status
413 public function submitSettingsForm() {
414 $this->setVarsFromRequest( array( '_MysqlEngine', '_MysqlCharset' ) );
415 $status = $this->submitWebUserBox();
416 if ( !$status->isOK() ) {
417 return $status;
420 // Validate the create checkbox
421 $canCreate = $this->canCreateAccounts();
422 if ( !$canCreate ) {
423 $this->setVar( '_CreateDBAccount', false );
424 $create = false;
425 } else {
426 $create = $this->getVar( '_CreateDBAccount' );
429 if ( !$create ) {
430 // Test the web account
431 try {
432 new DatabaseMysql(
433 $this->getVar( 'wgDBserver' ),
434 $this->getVar( 'wgDBuser' ),
435 $this->getVar( 'wgDBpassword' ),
436 false,
438 $this->getVar( 'wgDBprefix' )
440 } catch ( DBConnectionError $e ) {
441 return Status::newFatal( 'config-connection-error', $e->getMessage() );
445 // Validate engines and charsets
446 // This is done pre-submit already so it's just for security
447 $engines = $this->getEngines();
448 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
449 $this->setVar( '_MysqlEngine', reset( $engines ) );
451 $charsets = $this->getCharsets();
452 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
453 $this->setVar( '_MysqlCharset', reset( $charsets ) );
455 return Status::newGood();
458 public function preInstall() {
459 # Add our user callback to installSteps, right before the tables are created.
460 $callback = array(
461 'name' => 'user',
462 'callback' => array( $this, 'setupUser' ),
464 $this->parent->addInstallStep( $callback, 'tables' );
468 * @return Status
470 public function setupDatabase() {
471 $status = $this->getConnection();
472 if ( !$status->isOK() ) {
473 return $status;
475 $conn = $status->value;
476 $dbName = $this->getVar( 'wgDBname' );
477 if ( !$conn->selectDB( $dbName ) ) {
478 $conn->query( "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ), __METHOD__ );
479 $conn->selectDB( $dbName );
481 $this->setupSchemaVars();
482 return $status;
486 * @return Status
488 public function setupUser() {
489 $dbUser = $this->getVar( 'wgDBuser' );
490 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
491 return Status::newGood();
493 $status = $this->getConnection();
494 if ( !$status->isOK() ) {
495 return $status;
498 $this->setupSchemaVars();
499 $dbName = $this->getVar( 'wgDBname' );
500 $this->db->selectDB( $dbName );
501 $server = $this->getVar( 'wgDBserver' );
502 $password = $this->getVar( 'wgDBpassword' );
503 $grantableNames = array();
505 if ( $this->getVar( '_CreateDBAccount' ) ) {
506 // Before we blindly try to create a user that already has access,
507 try { // first attempt to connect to the database
508 new DatabaseMysql(
509 $server,
510 $dbUser,
511 $password,
512 false,
514 $this->getVar( 'wgDBprefix' )
516 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
517 $tryToCreate = false;
518 } catch ( DBConnectionError $e ) {
519 $tryToCreate = true;
521 } else {
522 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
523 $tryToCreate = false;
526 if ( $tryToCreate ) {
527 $createHostList = array(
528 $server,
529 'localhost',
530 'localhost.localdomain',
534 $createHostList = array_unique( $createHostList );
535 $escPass = $this->db->addQuotes( $password );
537 foreach ( $createHostList as $host ) {
538 $fullName = $this->buildFullUserName( $dbUser, $host );
539 if ( !$this->userDefinitelyExists( $dbUser, $host ) ) {
540 try {
541 $this->db->begin( __METHOD__ );
542 $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
543 $this->db->commit( __METHOD__ );
544 $grantableNames[] = $fullName;
545 } catch ( DBQueryError $dqe ) {
546 if ( $this->db->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
547 // User (probably) already exists
548 $this->db->rollback( __METHOD__ );
549 $status->warning( 'config-install-user-alreadyexists', $dbUser );
550 $grantableNames[] = $fullName;
551 break;
552 } else {
553 // If we couldn't create for some bizzare reason and the
554 // user probably doesn't exist, skip the grant
555 $this->db->rollback( __METHOD__ );
556 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
559 } else {
560 $status->warning( 'config-install-user-alreadyexists', $dbUser );
561 $grantableNames[] = $fullName;
562 break;
567 // Try to grant to all the users we know exist or we were able to create
568 $dbAllTables = $this->db->addIdentifierQuotes( $dbName ) . '.*';
569 foreach ( $grantableNames as $name ) {
570 try {
571 $this->db->begin( __METHOD__ );
572 $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
573 $this->db->commit( __METHOD__ );
574 } catch ( DBQueryError $dqe ) {
575 $this->db->rollback( __METHOD__ );
576 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
580 return $status;
584 * Return a formal 'User'@'Host' username for use in queries
585 * @param string $name Username, quotes will be added
586 * @param string $host Hostname, quotes will be added
587 * @return String
589 private function buildFullUserName( $name, $host ) {
590 return $this->db->addQuotes( $name ) . '@' . $this->db->addQuotes( $host );
594 * Try to see if the user account exists. Our "superuser" may not have
595 * access to mysql.user, so false means "no" or "maybe"
596 * @param string $host Hostname to check
597 * @param string $user Username to check
598 * @return boolean
600 private function userDefinitelyExists( $host, $user ) {
601 try {
602 $res = $this->db->selectRow( 'mysql.user', array( 'Host', 'User' ),
603 array( 'Host' => $host, 'User' => $user ), __METHOD__ );
604 return (bool)$res;
605 } catch ( DBQueryError $dqe ) {
606 return false;
612 * Return any table options to be applied to all tables that don't
613 * override them.
615 * @return String
617 protected function getTableOptions() {
618 $options = array();
619 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
620 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
622 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
623 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
625 return implode( ', ', $options );
629 * Get variables to substitute into tables.sql and the SQL patch files.
631 * @return array
633 public function getSchemaVars() {
634 return array(
635 'wgDBTableOptions' => $this->getTableOptions(),
636 'wgDBname' => $this->getVar( 'wgDBname' ),
637 'wgDBuser' => $this->getVar( 'wgDBuser' ),
638 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
642 public function getLocalSettings() {
643 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
644 $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
645 $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
646 return
647 "# MySQL specific settings
648 \$wgDBprefix = \"{$prefix}\";
650 # MySQL table options to use during installation or update
651 \$wgDBTableOptions = \"{$tblOpts}\";
653 # Experimental charset support for MySQL 5.0.
654 \$wgDBmysql5 = {$dbmysql5};";