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' ),
93 $this->parent
->getHelpBox( 'config-db-name-help' ) ) .
94 $this->getTextBox( 'wgDBprefix', 'config-db-prefix', array( 'dir' => 'ltr' ),
95 $this->parent
->getHelpBox( 'config-db-prefix-help' ) ) .
96 Html
::closeElement( 'fieldset' ) .
97 $this->getInstallUserBox();
100 public function submitConnectForm() {
101 // Get variables from the request.
102 $newValues = $this->setVarsFromRequest( array( 'wgDBserver', 'wgDBname', 'wgDBprefix' ) );
105 $status = Status
::newGood();
106 if ( !strlen( $newValues['wgDBserver'] ) ) {
107 $status->fatal( 'config-missing-db-host' );
109 if ( !strlen( $newValues['wgDBname'] ) ) {
110 $status->fatal( 'config-missing-db-name' );
111 } elseif ( !preg_match( '/^[a-z0-9+_-]+$/i', $newValues['wgDBname'] ) ) {
112 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
114 if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
115 $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
117 if ( !$status->isOK() ) {
122 $status = $this->submitInstallUserBox();
123 if ( !$status->isOK() ) {
128 $status = $this->getConnection();
129 if ( !$status->isOK() ) {
133 * @var $conn DatabaseBase
135 $conn = $status->value
;
138 $version = $conn->getServerVersion();
139 if ( version_compare( $version, $this->minimumVersion
) < 0 ) {
140 return Status
::newFatal( 'config-mysql-old', $this->minimumVersion
, $version );
149 public function openConnection() {
150 $status = Status
::newGood();
152 $db = new DatabaseMysql(
153 $this->getVar( 'wgDBserver' ),
154 $this->getVar( '_InstallUser' ),
155 $this->getVar( '_InstallPassword' ),
158 $this->getVar( 'wgDBprefix' )
160 $status->value
= $db;
161 } catch ( DBConnectionError
$e ) {
162 $status->fatal( 'config-connection-error', $e->getMessage() );
167 public function preUpgrade() {
168 global $wgDBuser, $wgDBpassword;
170 $status = $this->getConnection();
171 if ( !$status->isOK() ) {
172 $this->parent
->showStatusError( $status );
176 * @var $conn DatabaseBase
178 $conn = $status->value
;
179 $conn->selectDB( $this->getVar( 'wgDBname' ) );
181 # Determine existing default character set
182 if ( $conn->tableExists( "revision", __METHOD__
) ) {
183 $revision = $conn->buildLike( $this->getVar( 'wgDBprefix' ) . 'revision' );
184 $res = $conn->query( "SHOW TABLE STATUS $revision", __METHOD__
);
185 $row = $conn->fetchObject( $res );
187 $this->parent
->showMessage( 'config-show-table-status' );
188 $existingSchema = false;
189 $existingEngine = false;
191 if ( preg_match( '/^latin1/', $row->Collation
) ) {
192 $existingSchema = 'latin1';
193 } elseif ( preg_match( '/^utf8/', $row->Collation
) ) {
194 $existingSchema = 'utf8';
195 } elseif ( preg_match( '/^binary/', $row->Collation
) ) {
196 $existingSchema = 'binary';
198 $existingSchema = false;
199 $this->parent
->showMessage( 'config-unknown-collation' );
201 if ( isset( $row->Engine
) ) {
202 $existingEngine = $row->Engine
;
204 $existingEngine = $row->Type
;
208 $existingSchema = false;
209 $existingEngine = false;
212 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
213 $this->setVar( '_MysqlCharset', $existingSchema );
215 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
216 $this->setVar( '_MysqlEngine', $existingEngine );
219 # Normal user and password are selected after this step, so for now
220 # just copy these two
221 $wgDBuser = $this->getVar( '_InstallUser' );
222 $wgDBpassword = $this->getVar( '_InstallPassword' );
226 * Get a list of storage engines that are available and supported
230 public function getEngines() {
231 $status = $this->getConnection();
234 * @var $conn DatabaseBase
236 $conn = $status->value
;
239 $res = $conn->query( 'SHOW ENGINES', __METHOD__
);
240 foreach ( $res as $row ) {
241 if ( $row->Support
== 'YES' ||
$row->Support
== 'DEFAULT' ) {
242 $engines[] = $row->Engine
;
245 $engines = array_intersect( $this->supportedEngines
, $engines );
250 * Get a list of character sets that are available and supported
254 public function getCharsets() {
255 return array( 'binary', 'utf8' );
259 * Return true if the install user can create accounts
263 public function canCreateAccounts() {
264 $status = $this->getConnection();
265 if ( !$status->isOK() ) {
269 * @var $conn DatabaseBase
271 $conn = $status->value
;
273 // Get current account name
274 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__
);
275 $parts = explode( '@', $currentName );
276 if ( count( $parts ) != 2 ) {
279 $quotedUser = $conn->addQuotes( $parts[0] ) .
280 '@' . $conn->addQuotes( $parts[1] );
282 // The user needs to have INSERT on mysql.* to be able to CREATE USER
283 // The grantee will be double-quoted in this query, as required
284 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
285 array( 'GRANTEE' => $quotedUser ), __METHOD__
);
286 $insertMysql = false;
287 $grantOptions = array_flip( $this->webUserPrivs
);
288 foreach ( $res as $row ) {
289 if ( $row->PRIVILEGE_TYPE
== 'INSERT' ) {
292 if ( $row->IS_GRANTABLE
) {
293 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
297 // Check for DB-specific privs for mysql.*
298 if ( !$insertMysql ) {
299 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
301 'GRANTEE' => $quotedUser,
302 'TABLE_SCHEMA' => 'mysql',
303 'PRIVILEGE_TYPE' => 'INSERT',
310 if ( !$insertMysql ) {
314 // Check for DB-level grant options
315 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
317 'GRANTEE' => $quotedUser,
320 foreach ( $res as $row ) {
321 $regex = $conn->likeToRegex( $row->TABLE_SCHEMA
);
322 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
323 unset( $grantOptions[$row->PRIVILEGE_TYPE
] );
326 if ( count( $grantOptions ) ) {
327 // Can't grant everything
336 public function getSettingsForm() {
337 if ( $this->canCreateAccounts() ) {
338 $noCreateMsg = false;
340 $noCreateMsg = 'config-db-web-no-create-privs';
342 $s = $this->getWebUserBox( $noCreateMsg );
344 // Do engine selector
345 $engines = $this->getEngines();
346 // If the current default engine is not supported, use an engine that is
347 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
348 $this->setVar( '_MysqlEngine', reset( $engines ) );
351 $s .= Xml
::openElement( 'div', array(
352 'id' => 'dbMyisamWarning'
354 $myisamWarning = 'config-mysql-myisam-dep';
355 if ( count( $engines ) === 1 ) {
356 $myisamWarning = 'config-mysql-only-myisam-dep';
358 $s .= $this->parent
->getWarningBox( wfMessage( $myisamWarning )->text() );
359 $s .= Xml
::closeElement( 'div' );
361 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
362 $s .= Xml
::openElement( 'script', array( 'type' => 'text/javascript' ) );
363 $s .= '$(\'#dbMyisamWarning\').hide();';
364 $s .= Xml
::closeElement( 'script' );
367 if ( count( $engines ) >= 2 ) {
368 // getRadioSet() builds a set of labeled radio buttons.
369 // For grep: The following messages are used as the item labels:
370 // config-mysql-innodb, config-mysql-myisam
371 $s .= $this->getRadioSet( array(
372 'var' => '_MysqlEngine',
373 'label' => 'config-mysql-engine',
374 'itemLabelPrefix' => 'config-mysql-',
375 'values' => $engines,
376 'itemAttribs' => array(
378 'class' => 'showHideRadio',
379 'rel' => 'dbMyisamWarning'
382 'class' => 'hideShowRadio',
383 'rel' => 'dbMyisamWarning'
386 $s .= $this->parent
->getHelpBox( 'config-mysql-engine-help' );
389 // If the current default charset is not supported, use a charset that is
390 $charsets = $this->getCharsets();
391 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
392 $this->setVar( '_MysqlCharset', reset( $charsets ) );
395 // Do charset selector
396 if ( count( $charsets ) >= 2 ) {
397 // getRadioSet() builds a set of labeled radio buttons.
398 // For grep: The following messages are used as the item labels:
399 // config-mysql-binary, config-mysql-utf8
400 $s .= $this->getRadioSet( array(
401 'var' => '_MysqlCharset',
402 'label' => 'config-mysql-charset',
403 'itemLabelPrefix' => 'config-mysql-',
404 'values' => $charsets
406 $s .= $this->parent
->getHelpBox( 'config-mysql-charset-help' );
415 public function submitSettingsForm() {
416 $this->setVarsFromRequest( array( '_MysqlEngine', '_MysqlCharset' ) );
417 $status = $this->submitWebUserBox();
418 if ( !$status->isOK() ) {
422 // Validate the create checkbox
423 $canCreate = $this->canCreateAccounts();
425 $this->setVar( '_CreateDBAccount', false );
428 $create = $this->getVar( '_CreateDBAccount' );
432 // Test the web account
435 $this->getVar( 'wgDBserver' ),
436 $this->getVar( 'wgDBuser' ),
437 $this->getVar( 'wgDBpassword' ),
440 $this->getVar( 'wgDBprefix' )
442 } catch ( DBConnectionError
$e ) {
443 return Status
::newFatal( 'config-connection-error', $e->getMessage() );
447 // Validate engines and charsets
448 // This is done pre-submit already so it's just for security
449 $engines = $this->getEngines();
450 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
451 $this->setVar( '_MysqlEngine', reset( $engines ) );
453 $charsets = $this->getCharsets();
454 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
455 $this->setVar( '_MysqlCharset', reset( $charsets ) );
457 return Status
::newGood();
460 public function preInstall() {
461 # Add our user callback to installSteps, right before the tables are created.
464 'callback' => array( $this, 'setupUser' ),
466 $this->parent
->addInstallStep( $callback, 'tables' );
472 public function setupDatabase() {
473 $status = $this->getConnection();
474 if ( !$status->isOK() ) {
477 $conn = $status->value
;
478 $dbName = $this->getVar( 'wgDBname' );
479 if ( !$conn->selectDB( $dbName ) ) {
480 $conn->query( "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8", __METHOD__
);
481 $conn->selectDB( $dbName );
483 $this->setupSchemaVars();
490 public function setupUser() {
491 $dbUser = $this->getVar( 'wgDBuser' );
492 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
493 return Status
::newGood();
495 $status = $this->getConnection();
496 if ( !$status->isOK() ) {
500 $this->setupSchemaVars();
501 $dbName = $this->getVar( 'wgDBname' );
502 $this->db
->selectDB( $dbName );
503 $server = $this->getVar( 'wgDBserver' );
504 $password = $this->getVar( 'wgDBpassword' );
505 $grantableNames = array();
507 if ( $this->getVar( '_CreateDBAccount' ) ) {
508 // Before we blindly try to create a user that already has access,
509 try { // first attempt to connect to the database
516 $this->getVar( 'wgDBprefix' )
518 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
519 $tryToCreate = false;
520 } catch ( DBConnectionError
$e ) {
524 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
525 $tryToCreate = false;
528 if ( $tryToCreate ) {
529 $createHostList = array(
532 'localhost.localdomain',
536 $createHostList = array_unique( $createHostList );
537 $escPass = $this->db
->addQuotes( $password );
539 foreach ( $createHostList as $host ) {
540 $fullName = $this->buildFullUserName( $dbUser, $host );
541 if ( !$this->userDefinitelyExists( $dbUser, $host ) ) {
543 $this->db
->begin( __METHOD__
);
544 $this->db
->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__
);
545 $this->db
->commit( __METHOD__
);
546 $grantableNames[] = $fullName;
547 } catch ( DBQueryError
$dqe ) {
548 if ( $this->db
->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
549 // User (probably) already exists
550 $this->db
->rollback( __METHOD__
);
551 $status->warning( 'config-install-user-alreadyexists', $dbUser );
552 $grantableNames[] = $fullName;
555 // If we couldn't create for some bizzare reason and the
556 // user probably doesn't exist, skip the grant
557 $this->db
->rollback( __METHOD__
);
558 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
562 $status->warning( 'config-install-user-alreadyexists', $dbUser );
563 $grantableNames[] = $fullName;
569 // Try to grant to all the users we know exist or we were able to create
570 $dbAllTables = $this->db
->addIdentifierQuotes( $dbName ) . '.*';
571 foreach ( $grantableNames as $name ) {
573 $this->db
->begin( __METHOD__
);
574 $this->db
->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__
);
575 $this->db
->commit( __METHOD__
);
576 } catch ( DBQueryError
$dqe ) {
577 $this->db
->rollback( __METHOD__
);
578 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
586 * Return a formal 'User'@'Host' username for use in queries
587 * @param string $name Username, quotes will be added
588 * @param string $host Hostname, quotes will be added
591 private function buildFullUserName( $name, $host ) {
592 return $this->db
->addQuotes( $name ) . '@' . $this->db
->addQuotes( $host );
596 * Try to see if the user account exists. Our "superuser" may not have
597 * access to mysql.user, so false means "no" or "maybe"
598 * @param string $host Hostname to check
599 * @param string $user Username to check
602 private function userDefinitelyExists( $host, $user ) {
604 $res = $this->db
->selectRow( 'mysql.user', array( 'Host', 'User' ),
605 array( 'Host' => $host, 'User' => $user ), __METHOD__
);
607 } catch ( DBQueryError
$dqe ) {
614 * Return any table options to be applied to all tables that don't
619 protected function getTableOptions() {
621 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
622 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
624 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
625 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
627 return implode( ', ', $options );
631 * Get variables to substitute into tables.sql and the SQL patch files.
635 public function getSchemaVars() {
637 'wgDBTableOptions' => $this->getTableOptions(),
638 'wgDBname' => $this->getVar( 'wgDBname' ),
639 'wgDBuser' => $this->getVar( 'wgDBuser' ),
640 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
644 public function getLocalSettings() {
645 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
646 $prefix = LocalSettingsGenerator
::escapePhpString( $this->getVar( 'wgDBprefix' ) );
647 $tblOpts = LocalSettingsGenerator
::escapePhpString( $this->getTableOptions() );
649 "# MySQL specific settings
650 \$wgDBprefix = \"{$prefix}\";
652 # MySQL table options to use during installation or update
653 \$wgDBTableOptions = \"{$tblOpts}\";
655 # Experimental charset support for MySQL 5.0.
656 \$wgDBmysql5 = {$dbmysql5};";