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 getGlobalDefaults() {
84 public function getConnectForm() {
85 return $this->getTextBox(
89 $this->parent
->getHelpBox( 'config-db-host-help' )
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(
104 'wgDBserver', 'wgDBname', 'wgDBprefix', '_InstallUser', '_InstallPassword'
108 $status = Status
::newGood();
109 if ( !strlen( $newValues['wgDBserver'] ) ) {
110 $status->fatal( 'config-missing-db-host' );
112 if ( !strlen( $newValues['wgDBname'] ) ) {
113 $status->fatal( 'config-missing-db-name' );
114 } elseif ( !preg_match( '/^[a-z0-9+_-]+$/i', $newValues['wgDBname'] ) ) {
115 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
117 if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
118 $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
120 if ( !strlen( $newValues['_InstallUser'] ) ) {
121 $status->fatal( 'config-db-username-empty' );
123 if ( !strlen( $newValues['_InstallPassword'] ) ) {
124 $status->fatal( 'config-db-password-empty', $newValues['_InstallUser'] );
126 if ( !$status->isOK() ) {
131 $status = $this->submitInstallUserBox();
132 if ( !$status->isOK() ) {
137 $status = $this->getConnection();
138 if ( !$status->isOK() ) {
142 * @var $conn DatabaseBase
144 $conn = $status->value
;
147 $version = $conn->getServerVersion();
148 if ( version_compare( $version, $this->minimumVersion
) < 0 ) {
149 return Status
::newFatal( 'config-mysql-old', $this->minimumVersion
, $version );
158 public function openConnection() {
159 $status = Status
::newGood();
161 $db = DatabaseBase
::factory( 'mysql', array(
162 'host' => $this->getVar( 'wgDBserver' ),
163 'user' => $this->getVar( '_InstallUser' ),
164 'password' => $this->getVar( '_InstallPassword' ),
167 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ) );
168 $status->value
= $db;
169 } catch ( DBConnectionError
$e ) {
170 $status->fatal( 'config-connection-error', $e->getMessage() );
176 public function preUpgrade() {
177 global $wgDBuser, $wgDBpassword;
179 $status = $this->getConnection();
180 if ( !$status->isOK() ) {
181 $this->parent
->showStatusError( $status );
186 * @var $conn DatabaseBase
188 $conn = $status->value
;
189 $conn->selectDB( $this->getVar( 'wgDBname' ) );
191 # Determine existing default character set
192 if ( $conn->tableExists( "revision", __METHOD__
) ) {
193 $revision = $conn->buildLike( $this->getVar( 'wgDBprefix' ) . 'revision' );
194 $res = $conn->query( "SHOW TABLE STATUS $revision", __METHOD__
);
195 $row = $conn->fetchObject( $res );
197 $this->parent
->showMessage( 'config-show-table-status' );
198 $existingSchema = false;
199 $existingEngine = false;
201 if ( preg_match( '/^latin1/', $row->Collation
) ) {
202 $existingSchema = 'latin1';
203 } elseif ( preg_match( '/^utf8/', $row->Collation
) ) {
204 $existingSchema = 'utf8';
205 } elseif ( preg_match( '/^binary/', $row->Collation
) ) {
206 $existingSchema = 'binary';
208 $existingSchema = false;
209 $this->parent
->showMessage( 'config-unknown-collation' );
211 if ( isset( $row->Engine
) ) {
212 $existingEngine = $row->Engine
;
214 $existingEngine = $row->Type
;
218 $existingSchema = false;
219 $existingEngine = false;
222 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
223 $this->setVar( '_MysqlCharset', $existingSchema );
225 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
226 $this->setVar( '_MysqlEngine', $existingEngine );
229 # Normal user and password are selected after this step, so for now
230 # just copy these two
231 $wgDBuser = $this->getVar( '_InstallUser' );
232 $wgDBpassword = $this->getVar( '_InstallPassword' );
236 * Get a list of storage engines that are available and supported
240 public function getEngines() {
241 $status = $this->getConnection();
244 * @var $conn DatabaseBase
246 $conn = $status->value
;
249 $res = $conn->query( 'SHOW ENGINES', __METHOD__
);
250 foreach ( $res as $row ) {
251 if ( $row->Support
== 'YES' ||
$row->Support
== 'DEFAULT' ) {
252 $engines[] = $row->Engine
;
255 $engines = array_intersect( $this->supportedEngines
, $engines );
261 * Get a list of character sets that are available and supported
265 public function getCharsets() {
266 return array( 'binary', 'utf8' );
270 * Return true if the install user can create accounts
274 public function canCreateAccounts() {
275 $status = $this->getConnection();
276 if ( !$status->isOK() ) {
279 /** @var $conn DatabaseBase */
280 $conn = $status->value
;
282 // Get current account name
283 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__
);
284 $parts = explode( '@', $currentName );
285 if ( count( $parts ) != 2 ) {
288 $quotedUser = $conn->addQuotes( $parts[0] ) .
289 '@' . $conn->addQuotes( $parts[1] );
291 // The user needs to have INSERT on mysql.* to be able to CREATE USER
292 // The grantee will be double-quoted in this query, as required
293 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
294 array( 'GRANTEE' => $quotedUser ), __METHOD__
);
295 $insertMysql = false;
296 $grantOptions = array_flip( $this->webUserPrivs
);
297 foreach ( $res as $row ) {
298 if ( $row->PRIVILEGE_TYPE
== 'INSERT' ) {
301 if ( $row->IS_GRANTABLE
) {
302 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
306 // Check for DB-specific privs for mysql.*
307 if ( !$insertMysql ) {
308 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
310 'GRANTEE' => $quotedUser,
311 'TABLE_SCHEMA' => 'mysql',
312 'PRIVILEGE_TYPE' => 'INSERT',
319 if ( !$insertMysql ) {
323 // Check for DB-level grant options
324 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
326 'GRANTEE' => $quotedUser,
329 foreach ( $res as $row ) {
330 $regex = $conn->likeToRegex( $row->TABLE_SCHEMA
);
331 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
332 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
335 if ( count( $grantOptions ) ) {
336 // Can't grant everything
346 public function getSettingsForm() {
347 if ( $this->canCreateAccounts() ) {
348 $noCreateMsg = false;
350 $noCreateMsg = 'config-db-web-no-create-privs';
352 $s = $this->getWebUserBox( $noCreateMsg );
354 // Do engine selector
355 $engines = $this->getEngines();
356 // If the current default engine is not supported, use an engine that is
357 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
358 $this->setVar( '_MysqlEngine', reset( $engines ) );
361 $s .= Xml
::openElement( 'div', array(
362 'id' => 'dbMyisamWarning'
364 $myisamWarning = 'config-mysql-myisam-dep';
365 if ( count( $engines ) === 1 ) {
366 $myisamWarning = 'config-mysql-only-myisam-dep';
368 $s .= $this->parent
->getWarningBox( wfMessage( $myisamWarning )->text() );
369 $s .= Xml
::closeElement( 'div' );
371 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
372 $s .= Xml
::openElement( 'script', array( 'type' => 'text/javascript' ) );
373 $s .= '$(\'#dbMyisamWarning\').hide();';
374 $s .= Xml
::closeElement( 'script' );
377 if ( count( $engines ) >= 2 ) {
378 // getRadioSet() builds a set of labeled radio buttons.
379 // For grep: The following messages are used as the item labels:
380 // config-mysql-innodb, config-mysql-myisam
381 $s .= $this->getRadioSet( array(
382 'var' => '_MysqlEngine',
383 'label' => 'config-mysql-engine',
384 'itemLabelPrefix' => 'config-mysql-',
385 'values' => $engines,
386 'itemAttribs' => array(
388 'class' => 'showHideRadio',
389 'rel' => 'dbMyisamWarning'
392 'class' => 'hideShowRadio',
393 'rel' => 'dbMyisamWarning'
397 $s .= $this->parent
->getHelpBox( 'config-mysql-engine-help' );
400 // If the current default charset is not supported, use a charset that is
401 $charsets = $this->getCharsets();
402 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
403 $this->setVar( '_MysqlCharset', reset( $charsets ) );
406 // Do charset selector
407 if ( count( $charsets ) >= 2 ) {
408 // getRadioSet() builds a set of labeled radio buttons.
409 // For grep: The following messages are used as the item labels:
410 // config-mysql-binary, config-mysql-utf8
411 $s .= $this->getRadioSet( array(
412 'var' => '_MysqlCharset',
413 'label' => 'config-mysql-charset',
414 'itemLabelPrefix' => 'config-mysql-',
415 'values' => $charsets
417 $s .= $this->parent
->getHelpBox( 'config-mysql-charset-help' );
426 public function submitSettingsForm() {
427 $this->setVarsFromRequest( array( '_MysqlEngine', '_MysqlCharset' ) );
428 $status = $this->submitWebUserBox();
429 if ( !$status->isOK() ) {
433 // Validate the create checkbox
434 $canCreate = $this->canCreateAccounts();
436 $this->setVar( '_CreateDBAccount', false );
439 $create = $this->getVar( '_CreateDBAccount' );
443 // Test the web account
445 DatabaseBase
::factory( 'mysql', array(
446 'host' => $this->getVar( 'wgDBserver' ),
447 'user' => $this->getVar( 'wgDBuser' ),
448 'password' => $this->getVar( 'wgDBpassword' ),
451 'tablePrefix' => $this->getVar( 'wgDBprefix' )
453 } catch ( DBConnectionError
$e ) {
454 return Status
::newFatal( 'config-connection-error', $e->getMessage() );
458 // Validate engines and charsets
459 // This is done pre-submit already so it's just for security
460 $engines = $this->getEngines();
461 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
462 $this->setVar( '_MysqlEngine', reset( $engines ) );
464 $charsets = $this->getCharsets();
465 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
466 $this->setVar( '_MysqlCharset', reset( $charsets ) );
469 return Status
::newGood();
472 public function preInstall() {
473 # Add our user callback to installSteps, right before the tables are created.
476 'callback' => array( $this, 'setupUser' ),
478 $this->parent
->addInstallStep( $callback, 'tables' );
484 public function setupDatabase() {
485 $status = $this->getConnection();
486 if ( !$status->isOK() ) {
489 /** @var DatabaseBase $conn */
490 $conn = $status->value
;
491 $dbName = $this->getVar( 'wgDBname' );
492 if ( !$conn->selectDB( $dbName ) ) {
494 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
497 $conn->selectDB( $dbName );
499 $this->setupSchemaVars();
507 public function setupUser() {
508 $dbUser = $this->getVar( 'wgDBuser' );
509 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
510 return Status
::newGood();
512 $status = $this->getConnection();
513 if ( !$status->isOK() ) {
517 $this->setupSchemaVars();
518 $dbName = $this->getVar( 'wgDBname' );
519 $this->db
->selectDB( $dbName );
520 $server = $this->getVar( 'wgDBserver' );
521 $password = $this->getVar( 'wgDBpassword' );
522 $grantableNames = array();
524 if ( $this->getVar( '_CreateDBAccount' ) ) {
525 // Before we blindly try to create a user that already has access,
526 try { // first attempt to connect to the database
527 DatabaseBase
::factory( 'mysql', array(
530 'password' => $password,
533 'tablePrefix' => $this->getVar( 'wgDBprefix' )
535 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
536 $tryToCreate = false;
537 } catch ( DBConnectionError
$e ) {
541 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
542 $tryToCreate = false;
545 if ( $tryToCreate ) {
546 $createHostList = array(
549 'localhost.localdomain',
553 $createHostList = array_unique( $createHostList );
554 $escPass = $this->db
->addQuotes( $password );
556 foreach ( $createHostList as $host ) {
557 $fullName = $this->buildFullUserName( $dbUser, $host );
558 if ( !$this->userDefinitelyExists( $dbUser, $host ) ) {
560 $this->db
->begin( __METHOD__
);
561 $this->db
->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__
);
562 $this->db
->commit( __METHOD__
);
563 $grantableNames[] = $fullName;
564 } catch ( DBQueryError
$dqe ) {
565 if ( $this->db
->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
566 // User (probably) already exists
567 $this->db
->rollback( __METHOD__
);
568 $status->warning( 'config-install-user-alreadyexists', $dbUser );
569 $grantableNames[] = $fullName;
572 // If we couldn't create for some bizzare reason and the
573 // user probably doesn't exist, skip the grant
574 $this->db
->rollback( __METHOD__
);
575 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
579 $status->warning( 'config-install-user-alreadyexists', $dbUser );
580 $grantableNames[] = $fullName;
586 // Try to grant to all the users we know exist or we were able to create
587 $dbAllTables = $this->db
->addIdentifierQuotes( $dbName ) . '.*';
588 foreach ( $grantableNames as $name ) {
590 $this->db
->begin( __METHOD__
);
591 $this->db
->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__
);
592 $this->db
->commit( __METHOD__
);
593 } catch ( DBQueryError
$dqe ) {
594 $this->db
->rollback( __METHOD__
);
595 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
603 * Return a formal 'User'@'Host' username for use in queries
604 * @param string $name Username, quotes will be added
605 * @param string $host Hostname, quotes will be added
608 private function buildFullUserName( $name, $host ) {
609 return $this->db
->addQuotes( $name ) . '@' . $this->db
->addQuotes( $host );
613 * Try to see if the user account exists. Our "superuser" may not have
614 * access to mysql.user, so false means "no" or "maybe"
615 * @param string $host Hostname to check
616 * @param string $user Username to check
619 private function userDefinitelyExists( $host, $user ) {
621 $res = $this->db
->selectRow( 'mysql.user', array( 'Host', 'User' ),
622 array( 'Host' => $host, 'User' => $user ), __METHOD__
);
625 } catch ( DBQueryError
$dqe ) {
631 * Return any table options to be applied to all tables that don't
636 protected function getTableOptions() {
638 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
639 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
641 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
642 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
645 return implode( ', ', $options );
649 * Get variables to substitute into tables.sql and the SQL patch files.
653 public function getSchemaVars() {
655 'wgDBTableOptions' => $this->getTableOptions(),
656 'wgDBname' => $this->getVar( 'wgDBname' ),
657 'wgDBuser' => $this->getVar( 'wgDBuser' ),
658 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
662 public function getLocalSettings() {
663 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
664 $prefix = LocalSettingsGenerator
::escapePhpString( $this->getVar( 'wgDBprefix' ) );
665 $tblOpts = LocalSettingsGenerator
::escapePhpString( $this->getTableOptions() );
667 return "# MySQL specific settings
668 \$wgDBprefix = \"{$prefix}\";
670 # MySQL table options to use during installation or update
671 \$wgDBTableOptions = \"{$tblOpts}\";
673 # Experimental charset support for MySQL 5.0.
674 \$wgDBmysql5 = {$dbmysql5};";