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() {
70 public function isCompiled() {
71 return self
::checkExtension( 'mysql' ) || self
::checkExtension( 'mysqli' );
77 public function getConnectForm() {
78 return $this->getTextBox(
82 $this->parent
->getHelpBox( 'config-db-host-help' )
84 Html
::openElement( 'fieldset' ) .
85 Html
::element( 'legend', array(), wfMessage( 'config-db-wiki-settings' )->text() ) .
86 $this->getTextBox( 'wgDBname', 'config-db-name', array( 'dir' => 'ltr' ),
87 $this->parent
->getHelpBox( 'config-db-name-help' ) ) .
88 $this->getTextBox( 'wgDBprefix', 'config-db-prefix', array( '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( array(
97 'wgDBserver', 'wgDBname', 'wgDBprefix', '_InstallUser', '_InstallPassword'
101 $status = Status
::newGood();
102 if ( !strlen( $newValues['wgDBserver'] ) ) {
103 $status->fatal( 'config-missing-db-host' );
105 if ( !strlen( $newValues['wgDBname'] ) ) {
106 $status->fatal( 'config-missing-db-name' );
107 } elseif ( !preg_match( '/^[a-z0-9+_-]+$/i', $newValues['wgDBname'] ) ) {
108 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
110 if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
111 $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
113 if ( !strlen( $newValues['_InstallUser'] ) ) {
114 $status->fatal( 'config-db-username-empty' );
116 if ( !strlen( $newValues['_InstallPassword'] ) ) {
117 $status->fatal( 'config-db-password-empty', $newValues['_InstallUser'] );
119 if ( !$status->isOK() ) {
124 $status = $this->submitInstallUserBox();
125 if ( !$status->isOK() ) {
130 $status = $this->getConnection();
131 if ( !$status->isOK() ) {
135 * @var $conn DatabaseBase
137 $conn = $status->value
;
140 $version = $conn->getServerVersion();
141 if ( version_compare( $version, $this->minimumVersion
) < 0 ) {
142 return Status
::newFatal( 'config-mysql-old', $this->minimumVersion
, $version );
151 public function openConnection() {
152 $status = Status
::newGood();
154 $db = DatabaseBase
::factory( 'mysql', array(
155 'host' => $this->getVar( 'wgDBserver' ),
156 'user' => $this->getVar( '_InstallUser' ),
157 'password' => $this->getVar( '_InstallPassword' ),
160 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ) );
161 $status->value
= $db;
162 } catch ( DBConnectionError
$e ) {
163 $status->fatal( 'config-connection-error', $e->getMessage() );
169 public function preUpgrade() {
170 global $wgDBuser, $wgDBpassword;
172 $status = $this->getConnection();
173 if ( !$status->isOK() ) {
174 $this->parent
->showStatusError( $status );
179 * @var $conn DatabaseBase
181 $conn = $status->value
;
182 $conn->selectDB( $this->getVar( 'wgDBname' ) );
184 # Determine existing default character set
185 if ( $conn->tableExists( "revision", __METHOD__
) ) {
186 $revision = $conn->buildLike( $this->getVar( 'wgDBprefix' ) . 'revision' );
187 $res = $conn->query( "SHOW TABLE STATUS $revision", __METHOD__
);
188 $row = $conn->fetchObject( $res );
190 $this->parent
->showMessage( 'config-show-table-status' );
191 $existingSchema = false;
192 $existingEngine = false;
194 if ( preg_match( '/^latin1/', $row->Collation
) ) {
195 $existingSchema = 'latin1';
196 } elseif ( preg_match( '/^utf8/', $row->Collation
) ) {
197 $existingSchema = 'utf8';
198 } elseif ( preg_match( '/^binary/', $row->Collation
) ) {
199 $existingSchema = 'binary';
201 $existingSchema = false;
202 $this->parent
->showMessage( 'config-unknown-collation' );
204 if ( isset( $row->Engine
) ) {
205 $existingEngine = $row->Engine
;
207 $existingEngine = $row->Type
;
211 $existingSchema = false;
212 $existingEngine = false;
215 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
216 $this->setVar( '_MysqlCharset', $existingSchema );
218 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
219 $this->setVar( '_MysqlEngine', $existingEngine );
222 # Normal user and password are selected after this step, so for now
223 # just copy these two
224 $wgDBuser = $this->getVar( '_InstallUser' );
225 $wgDBpassword = $this->getVar( '_InstallPassword' );
229 * Get a list of storage engines that are available and supported
233 public function getEngines() {
234 $status = $this->getConnection();
237 * @var $conn DatabaseBase
239 $conn = $status->value
;
242 $res = $conn->query( 'SHOW ENGINES', __METHOD__
);
243 foreach ( $res as $row ) {
244 if ( $row->Support
== 'YES' ||
$row->Support
== 'DEFAULT' ) {
245 $engines[] = $row->Engine
;
248 $engines = array_intersect( $this->supportedEngines
, $engines );
254 * Get a list of character sets that are available and supported
258 public function getCharsets() {
259 return array( 'binary', 'utf8' );
263 * Return true if the install user can create accounts
267 public function canCreateAccounts() {
268 $status = $this->getConnection();
269 if ( !$status->isOK() ) {
272 /** @var $conn DatabaseBase */
273 $conn = $status->value
;
275 // Get current account name
276 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__
);
277 $parts = explode( '@', $currentName );
278 if ( count( $parts ) != 2 ) {
281 $quotedUser = $conn->addQuotes( $parts[0] ) .
282 '@' . $conn->addQuotes( $parts[1] );
284 // The user needs to have INSERT on mysql.* to be able to CREATE USER
285 // The grantee will be double-quoted in this query, as required
286 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
287 array( 'GRANTEE' => $quotedUser ), __METHOD__
);
288 $insertMysql = false;
289 $grantOptions = array_flip( $this->webUserPrivs
);
290 foreach ( $res as $row ) {
291 if ( $row->PRIVILEGE_TYPE
== 'INSERT' ) {
294 if ( $row->IS_GRANTABLE
) {
295 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
299 // Check for DB-specific privs for mysql.*
300 if ( !$insertMysql ) {
301 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
303 'GRANTEE' => $quotedUser,
304 'TABLE_SCHEMA' => 'mysql',
305 'PRIVILEGE_TYPE' => 'INSERT',
312 if ( !$insertMysql ) {
316 // Check for DB-level grant options
317 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
319 'GRANTEE' => $quotedUser,
322 foreach ( $res as $row ) {
323 $regex = $conn->likeToRegex( $row->TABLE_SCHEMA
);
324 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
325 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
328 if ( count( $grantOptions ) ) {
329 // Can't grant everything
339 public function getSettingsForm() {
340 if ( $this->canCreateAccounts() ) {
341 $noCreateMsg = false;
343 $noCreateMsg = 'config-db-web-no-create-privs';
345 $s = $this->getWebUserBox( $noCreateMsg );
347 // Do engine selector
348 $engines = $this->getEngines();
349 // If the current default engine is not supported, use an engine that is
350 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
351 $this->setVar( '_MysqlEngine', reset( $engines ) );
354 $s .= Xml
::openElement( 'div', array(
355 'id' => 'dbMyisamWarning'
357 $myisamWarning = 'config-mysql-myisam-dep';
358 if ( count( $engines ) === 1 ) {
359 $myisamWarning = 'config-mysql-only-myisam-dep';
361 $s .= $this->parent
->getWarningBox( wfMessage( $myisamWarning )->text() );
362 $s .= Xml
::closeElement( 'div' );
364 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
365 $s .= Xml
::openElement( 'script', array( 'type' => 'text/javascript' ) );
366 $s .= '$(\'#dbMyisamWarning\').hide();';
367 $s .= Xml
::closeElement( 'script' );
370 if ( count( $engines ) >= 2 ) {
371 // getRadioSet() builds a set of labeled radio buttons.
372 // For grep: The following messages are used as the item labels:
373 // config-mysql-innodb, config-mysql-myisam
374 $s .= $this->getRadioSet( array(
375 'var' => '_MysqlEngine',
376 'label' => 'config-mysql-engine',
377 'itemLabelPrefix' => 'config-mysql-',
378 'values' => $engines,
379 'itemAttribs' => array(
381 'class' => 'showHideRadio',
382 'rel' => 'dbMyisamWarning'
385 'class' => 'hideShowRadio',
386 'rel' => 'dbMyisamWarning'
390 $s .= $this->parent
->getHelpBox( 'config-mysql-engine-help' );
393 // If the current default charset is not supported, use a charset that is
394 $charsets = $this->getCharsets();
395 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
396 $this->setVar( '_MysqlCharset', reset( $charsets ) );
399 // Do charset selector
400 if ( count( $charsets ) >= 2 ) {
401 // getRadioSet() builds a set of labeled radio buttons.
402 // For grep: The following messages are used as the item labels:
403 // config-mysql-binary, config-mysql-utf8
404 $s .= $this->getRadioSet( array(
405 'var' => '_MysqlCharset',
406 'label' => 'config-mysql-charset',
407 'itemLabelPrefix' => 'config-mysql-',
408 'values' => $charsets
410 $s .= $this->parent
->getHelpBox( 'config-mysql-charset-help' );
419 public function submitSettingsForm() {
420 $this->setVarsFromRequest( array( '_MysqlEngine', '_MysqlCharset' ) );
421 $status = $this->submitWebUserBox();
422 if ( !$status->isOK() ) {
426 // Validate the create checkbox
427 $canCreate = $this->canCreateAccounts();
429 $this->setVar( '_CreateDBAccount', false );
432 $create = $this->getVar( '_CreateDBAccount' );
436 // Test the web account
438 DatabaseBase
::factory( 'mysql', array(
439 'host' => $this->getVar( 'wgDBserver' ),
440 'user' => $this->getVar( 'wgDBuser' ),
441 'password' => $this->getVar( 'wgDBpassword' ),
444 'tablePrefix' => $this->getVar( 'wgDBprefix' )
446 } catch ( DBConnectionError
$e ) {
447 return Status
::newFatal( 'config-connection-error', $e->getMessage() );
451 // Validate engines and charsets
452 // This is done pre-submit already so it's just for security
453 $engines = $this->getEngines();
454 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
455 $this->setVar( '_MysqlEngine', reset( $engines ) );
457 $charsets = $this->getCharsets();
458 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
459 $this->setVar( '_MysqlCharset', reset( $charsets ) );
462 return Status
::newGood();
465 public function preInstall() {
466 # Add our user callback to installSteps, right before the tables are created.
469 'callback' => array( $this, 'setupUser' ),
471 $this->parent
->addInstallStep( $callback, 'tables' );
477 public function setupDatabase() {
478 $status = $this->getConnection();
479 if ( !$status->isOK() ) {
482 /** @var DatabaseBase $conn */
483 $conn = $status->value
;
484 $dbName = $this->getVar( 'wgDBname' );
485 if ( !$conn->selectDB( $dbName ) ) {
487 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
490 $conn->selectDB( $dbName );
492 $this->setupSchemaVars();
500 public function setupUser() {
501 $dbUser = $this->getVar( 'wgDBuser' );
502 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
503 return Status
::newGood();
505 $status = $this->getConnection();
506 if ( !$status->isOK() ) {
510 $this->setupSchemaVars();
511 $dbName = $this->getVar( 'wgDBname' );
512 $this->db
->selectDB( $dbName );
513 $server = $this->getVar( 'wgDBserver' );
514 $password = $this->getVar( 'wgDBpassword' );
515 $grantableNames = array();
517 if ( $this->getVar( '_CreateDBAccount' ) ) {
518 // Before we blindly try to create a user that already has access,
519 try { // first attempt to connect to the database
520 DatabaseBase
::factory( 'mysql', array(
523 'password' => $password,
526 'tablePrefix' => $this->getVar( 'wgDBprefix' )
528 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
529 $tryToCreate = false;
530 } catch ( DBConnectionError
$e ) {
534 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
535 $tryToCreate = false;
538 if ( $tryToCreate ) {
539 $createHostList = array(
542 'localhost.localdomain',
546 $createHostList = array_unique( $createHostList );
547 $escPass = $this->db
->addQuotes( $password );
549 foreach ( $createHostList as $host ) {
550 $fullName = $this->buildFullUserName( $dbUser, $host );
551 if ( !$this->userDefinitelyExists( $dbUser, $host ) ) {
553 $this->db
->begin( __METHOD__
);
554 $this->db
->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__
);
555 $this->db
->commit( __METHOD__
);
556 $grantableNames[] = $fullName;
557 } catch ( DBQueryError
$dqe ) {
558 if ( $this->db
->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
559 // User (probably) already exists
560 $this->db
->rollback( __METHOD__
);
561 $status->warning( 'config-install-user-alreadyexists', $dbUser );
562 $grantableNames[] = $fullName;
565 // If we couldn't create for some bizzare reason and the
566 // user probably doesn't exist, skip the grant
567 $this->db
->rollback( __METHOD__
);
568 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
572 $status->warning( 'config-install-user-alreadyexists', $dbUser );
573 $grantableNames[] = $fullName;
579 // Try to grant to all the users we know exist or we were able to create
580 $dbAllTables = $this->db
->addIdentifierQuotes( $dbName ) . '.*';
581 foreach ( $grantableNames as $name ) {
583 $this->db
->begin( __METHOD__
);
584 $this->db
->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__
);
585 $this->db
->commit( __METHOD__
);
586 } catch ( DBQueryError
$dqe ) {
587 $this->db
->rollback( __METHOD__
);
588 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
596 * Return a formal 'User'@'Host' username for use in queries
597 * @param string $name Username, quotes will be added
598 * @param string $host Hostname, quotes will be added
601 private function buildFullUserName( $name, $host ) {
602 return $this->db
->addQuotes( $name ) . '@' . $this->db
->addQuotes( $host );
606 * Try to see if the user account exists. Our "superuser" may not have
607 * access to mysql.user, so false means "no" or "maybe"
608 * @param string $host Hostname to check
609 * @param string $user Username to check
612 private function userDefinitelyExists( $host, $user ) {
614 $res = $this->db
->selectRow( 'mysql.user', array( 'Host', 'User' ),
615 array( 'Host' => $host, 'User' => $user ), __METHOD__
);
618 } catch ( DBQueryError
$dqe ) {
624 * Return any table options to be applied to all tables that don't
629 protected function getTableOptions() {
631 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
632 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
634 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
635 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
638 return implode( ', ', $options );
642 * Get variables to substitute into tables.sql and the SQL patch files.
646 public function getSchemaVars() {
648 'wgDBTableOptions' => $this->getTableOptions(),
649 'wgDBname' => $this->getVar( 'wgDBname' ),
650 'wgDBuser' => $this->getVar( 'wgDBuser' ),
651 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
655 public function getLocalSettings() {
656 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
657 $prefix = LocalSettingsGenerator
::escapePhpString( $this->getVar( 'wgDBprefix' ) );
658 $tblOpts = LocalSettingsGenerator
::escapePhpString( $this->getTableOptions() );
660 return "# MySQL specific settings
661 \$wgDBprefix = \"{$prefix}\";
663 # MySQL table options to use during installation or update
664 \$wgDBTableOptions = \"{$tblOpts}\";
666 # Experimental charset support for MySQL 5.0.
667 \$wgDBmysql5 = {$dbmysql5};";