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
25 * Class for setting up the MediaWiki database using MySQL.
30 class MysqlInstaller
extends DatabaseInstaller
{
32 protected $globalNames = array(
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(
57 'CREATE TEMPORARY TABLES',
63 public function getName() {
67 public function __construct( $parent ) {
68 parent
::__construct( $parent );
74 public function isCompiled() {
75 return self
::checkExtension( 'mysql' );
81 public function getGlobalDefaults() {
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' ) );
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 DatabaseBase
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 = new DatabaseMysql(
151 $this->getVar( 'wgDBserver' ),
152 $this->getVar( '_InstallUser' ),
153 $this->getVar( '_InstallPassword' ),
156 $this->getVar( 'wgDBprefix' )
158 $status->value
= $db;
159 } catch ( DBConnectionError
$e ) {
160 $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 );
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 );
185 $this->parent
->showMessage( 'config-show-table-status' );
186 $existingSchema = false;
187 $existingEngine = false;
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';
196 $existingSchema = false;
197 $this->parent
->showMessage( 'config-unknown-collation' );
199 if ( isset( $row->Engine
) ) {
200 $existingEngine = $row->Engine
;
202 $existingEngine = $row->Type
;
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
228 public function getEngines() {
229 $status = $this->getConnection();
232 * @var $conn DatabaseBase
234 $conn = $status->value
;
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 );
248 * Get a list of character sets that are available and supported
252 public function getCharsets() {
253 return array( 'binary', 'utf8' );
257 * Return true if the install user can create accounts
261 public function canCreateAccounts() {
262 $status = $this->getConnection();
263 if ( !$status->isOK() ) {
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 ) {
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' ) {
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', '*',
299 'GRANTEE' => $quotedUser,
300 'TABLE_SCHEMA' => 'mysql',
301 'PRIVILEGE_TYPE' => 'INSERT',
308 if ( !$insertMysql ) {
312 // Check for DB-level grant options
313 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
315 'GRANTEE' => $quotedUser,
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
334 public function getSettingsForm() {
335 if ( $this->canCreateAccounts() ) {
336 $noCreateMsg = false;
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(
376 'class' => 'showHideRadio',
377 'rel' => 'dbMyisamWarning'
380 'class' => 'hideShowRadio',
381 'rel' => 'dbMyisamWarning'
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' );
413 public function submitSettingsForm() {
414 $this->setVarsFromRequest( array( '_MysqlEngine', '_MysqlCharset' ) );
415 $status = $this->submitWebUserBox();
416 if ( !$status->isOK() ) {
420 // Validate the create checkbox
421 $canCreate = $this->canCreateAccounts();
423 $this->setVar( '_CreateDBAccount', false );
426 $create = $this->getVar( '_CreateDBAccount' );
430 // Test the web account
433 $this->getVar( 'wgDBserver' ),
434 $this->getVar( 'wgDBuser' ),
435 $this->getVar( 'wgDBpassword' ),
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.
462 'callback' => array( $this, 'setupUser' ),
464 $this->parent
->addInstallStep( $callback, 'tables' );
470 public function setupDatabase() {
471 $status = $this->getConnection();
472 if ( !$status->isOK() ) {
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();
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() ) {
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
514 $this->getVar( 'wgDBprefix' )
516 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
517 $tryToCreate = false;
518 } catch ( DBConnectionError
$e ) {
522 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
523 $tryToCreate = false;
526 if ( $tryToCreate ) {
527 $createHostList = array(
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 ) ) {
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;
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() );
560 $status->warning( 'config-install-user-alreadyexists', $dbUser );
561 $grantableNames[] = $fullName;
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 ) {
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() );
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
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
600 private function userDefinitelyExists( $host, $user ) {
602 $res = $this->db
->selectRow( 'mysql.user', array( 'Host', 'User' ),
603 array( 'Host' => $host, 'User' => $user ), __METHOD__
);
605 } catch ( DBQueryError
$dqe ) {
612 * Return any table options to be applied to all tables that don't
617 protected function getTableOptions() {
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.
633 public function getSchemaVars() {
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() );
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};";