Simplify the check to make it more understandable
[mediawiki.git] / includes / installer / MysqlInstaller.php
blob7585fe7a5949c34bce465bfce53f76ea1d367b1c
1 <?php
2 /**
3 * MySQL-specific installer.
5 * @file
6 * @ingroup Deployment
7 */
9 /**
10 * Class for setting up the MediaWiki database using MySQL.
12 * @ingroup Deployment
13 * @since 1.17
15 class MysqlInstaller extends DatabaseInstaller {
17 protected $globalNames = array(
18 'wgDBserver',
19 'wgDBname',
20 'wgDBuser',
21 'wgDBpassword',
22 'wgDBprefix',
23 'wgDBTableOptions',
24 'wgDBmysql5',
27 protected $internalDefaults = array(
28 '_MysqlEngine' => 'InnoDB',
29 '_MysqlCharset' => 'binary',
30 '_InstallUser' => 'root',
33 public $supportedEngines = array( 'InnoDB', 'MyISAM' );
35 public $minimumVersion = '5.0.2';
37 public $webUserPrivs = array(
38 'DELETE',
39 'INSERT',
40 'SELECT',
41 'UPDATE',
42 'CREATE TEMPORARY TABLES',
45 /**
46 * @return string
48 public function getName() {
49 return 'mysql';
52 public function __construct( $parent ) {
53 parent::__construct( $parent );
56 /**
57 * @return Bool
59 public function isCompiled() {
60 return self::checkExtension( 'mysql' );
63 /**
64 * @return array
66 public function getGlobalDefaults() {
67 return array();
70 /**
71 * @return string
73 public function getConnectForm() {
74 return
75 $this->getTextBox( 'wgDBserver', 'config-db-host', array(), $this->parent->getHelpBox( 'config-db-host-help' ) ) .
76 Html::openElement( 'fieldset' ) .
77 Html::element( 'legend', array(), wfMsg( 'config-db-wiki-settings' ) ) .
78 $this->getTextBox( 'wgDBname', 'config-db-name', array( 'dir' => 'ltr' ), $this->parent->getHelpBox( 'config-db-name-help' ) ) .
79 $this->getTextBox( 'wgDBprefix', 'config-db-prefix', array( 'dir' => 'ltr' ), $this->parent->getHelpBox( 'config-db-prefix-help' ) ) .
80 Html::closeElement( 'fieldset' ) .
81 $this->getInstallUserBox();
84 public function submitConnectForm() {
85 // Get variables from the request.
86 $newValues = $this->setVarsFromRequest( array( 'wgDBserver', 'wgDBname', 'wgDBprefix' ) );
88 // Validate them.
89 $status = Status::newGood();
90 if ( !strlen( $newValues['wgDBserver'] ) ) {
91 $status->fatal( 'config-missing-db-host' );
93 if ( !strlen( $newValues['wgDBname'] ) ) {
94 $status->fatal( 'config-missing-db-name' );
95 } elseif ( !preg_match( '/^[a-z0-9_-]+$/i', $newValues['wgDBname'] ) ) {
96 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
98 if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
99 $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
101 if ( !$status->isOK() ) {
102 return $status;
105 // Submit user box
106 $status = $this->submitInstallUserBox();
107 if ( !$status->isOK() ) {
108 return $status;
111 // Try to connect
112 $status = $this->getConnection();
113 if ( !$status->isOK() ) {
114 return $status;
117 * @var $conn DatabaseBase
119 $conn = $status->value;
121 // Check version
122 $version = $conn->getServerVersion();
123 if ( version_compare( $version, $this->minimumVersion ) < 0 ) {
124 return Status::newFatal( 'config-mysql-old', $this->minimumVersion, $version );
127 return $status;
131 * @return Status
133 public function openConnection() {
134 $status = Status::newGood();
135 try {
136 $db = new DatabaseMysql(
137 $this->getVar( 'wgDBserver' ),
138 $this->getVar( '_InstallUser' ),
139 $this->getVar( '_InstallPassword' ),
140 false,
141 false,
143 $this->getVar( 'wgDBprefix' )
145 $status->value = $db;
146 } catch ( DBConnectionError $e ) {
147 $status->fatal( 'config-connection-error', $e->getMessage() );
149 return $status;
152 public function preUpgrade() {
153 global $wgDBuser, $wgDBpassword;
155 $status = $this->getConnection();
156 if ( !$status->isOK() ) {
157 $this->parent->showStatusError( $status );
158 return;
161 * @var $conn DatabaseBase
163 $conn = $status->value;
164 $conn->selectDB( $this->getVar( 'wgDBname' ) );
166 # Determine existing default character set
167 if ( $conn->tableExists( "revision", __METHOD__ ) ) {
168 $revision = $conn->buildLike( $this->getVar( 'wgDBprefix' ) . 'revision' );
169 $res = $conn->query( "SHOW TABLE STATUS $revision", __METHOD__ );
170 $row = $conn->fetchObject( $res );
171 if ( !$row ) {
172 $this->parent->showMessage( 'config-show-table-status' );
173 $existingSchema = false;
174 $existingEngine = false;
175 } else {
176 if ( preg_match( '/^latin1/', $row->Collation ) ) {
177 $existingSchema = 'latin1';
178 } elseif ( preg_match( '/^utf8/', $row->Collation ) ) {
179 $existingSchema = 'utf8';
180 } elseif ( preg_match( '/^binary/', $row->Collation ) ) {
181 $existingSchema = 'binary';
182 } else {
183 $existingSchema = false;
184 $this->parent->showMessage( 'config-unknown-collation' );
186 if ( isset( $row->Engine ) ) {
187 $existingEngine = $row->Engine;
188 } else {
189 $existingEngine = $row->Type;
192 } else {
193 $existingSchema = false;
194 $existingEngine = false;
197 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
198 $this->setVar( '_MysqlCharset', $existingSchema );
200 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
201 $this->setVar( '_MysqlEngine', $existingEngine );
204 # Normal user and password are selected after this step, so for now
205 # just copy these two
206 $wgDBuser = $this->getVar( '_InstallUser' );
207 $wgDBpassword = $this->getVar( '_InstallPassword' );
211 * Get a list of storage engines that are available and supported
213 * @return array
215 public function getEngines() {
216 $status = $this->getConnection();
219 * @var $conn DatabaseBase
221 $conn = $status->value;
223 $engines = array();
224 $res = $conn->query( 'SHOW ENGINES', __METHOD__ );
225 foreach ( $res as $row ) {
226 if ( $row->Support == 'YES' || $row->Support == 'DEFAULT' ) {
227 $engines[] = $row->Engine;
230 $engines = array_intersect( $this->supportedEngines, $engines );
231 return $engines;
235 * Get a list of character sets that are available and supported
237 * @return array
239 public function getCharsets() {
240 return array( 'binary', 'utf8' );
244 * Return true if the install user can create accounts
246 * @return bool
248 public function canCreateAccounts() {
249 $status = $this->getConnection();
250 if ( !$status->isOK() ) {
251 return false;
254 * @var $conn DatabaseBase
256 $conn = $status->value;
258 // Get current account name
259 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__ );
260 $parts = explode( '@', $currentName );
261 if ( count( $parts ) != 2 ) {
262 return false;
264 $quotedUser = $conn->addQuotes( $parts[0] ) .
265 '@' . $conn->addQuotes( $parts[1] );
267 // The user needs to have INSERT on mysql.* to be able to CREATE USER
268 // The grantee will be double-quoted in this query, as required
269 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
270 array( 'GRANTEE' => $quotedUser ), __METHOD__ );
271 $insertMysql = false;
272 $grantOptions = array_flip( $this->webUserPrivs );
273 foreach ( $res as $row ) {
274 if ( $row->PRIVILEGE_TYPE == 'INSERT' ) {
275 $insertMysql = true;
277 if ( $row->IS_GRANTABLE ) {
278 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
282 // Check for DB-specific privs for mysql.*
283 if ( !$insertMysql ) {
284 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
285 array(
286 'GRANTEE' => $quotedUser,
287 'TABLE_SCHEMA' => 'mysql',
288 'PRIVILEGE_TYPE' => 'INSERT',
289 ), __METHOD__ );
290 if ( $row ) {
291 $insertMysql = true;
295 if ( !$insertMysql ) {
296 return false;
299 // Check for DB-level grant options
300 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
301 array(
302 'GRANTEE' => $quotedUser,
303 'IS_GRANTABLE' => 1,
304 ), __METHOD__ );
305 foreach ( $res as $row ) {
306 $regex = $conn->likeToRegex( $row->TABLE_SCHEMA );
307 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
308 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
311 if ( count( $grantOptions ) ) {
312 // Can't grant everything
313 return false;
315 return true;
319 * @return string
321 public function getSettingsForm() {
322 if ( $this->canCreateAccounts() ) {
323 $noCreateMsg = false;
324 } else {
325 $noCreateMsg = 'config-db-web-no-create-privs';
327 $s = $this->getWebUserBox( $noCreateMsg );
329 // Do engine selector
330 $engines = $this->getEngines();
331 // If the current default engine is not supported, use an engine that is
332 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
333 $this->setVar( '_MysqlEngine', reset( $engines ) );
336 $s .= Xml::openElement( 'div', array(
337 'id' => 'dbMyisamWarning'
339 $s .= $this->parent->getWarningBox( wfMsg( 'config-mysql-myisam-dep' ) );
340 $s .= Xml::closeElement( 'div' );
342 if( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
343 $s .= Xml::openElement( 'script', array( 'type' => 'text/javascript' ) );
344 $s .= '$(\'#dbMyisamWarning\').hide();';
345 $s .= Xml::closeElement( 'script' );
348 if ( count( $engines ) >= 2 ) {
349 $s .= $this->getRadioSet( array(
350 'var' => '_MysqlEngine',
351 'label' => 'config-mysql-engine',
352 'itemLabelPrefix' => 'config-mysql-',
353 'values' => $engines,
354 'itemAttribs' => array(
355 'MyISAM' => array(
356 'class' => 'showHideRadio',
357 'rel' => 'dbMyisamWarning'),
358 'InnoDB' => array(
359 'class' => 'hideShowRadio',
360 'rel' => 'dbMyisamWarning')
361 )));
362 $s .= $this->parent->getHelpBox( 'config-mysql-engine-help' );
365 // If the current default charset is not supported, use a charset that is
366 $charsets = $this->getCharsets();
367 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
368 $this->setVar( '_MysqlCharset', reset( $charsets ) );
371 // Do charset selector
372 if ( count( $charsets ) >= 2 ) {
373 $s .= $this->getRadioSet( array(
374 'var' => '_MysqlCharset',
375 'label' => 'config-mysql-charset',
376 'itemLabelPrefix' => 'config-mysql-',
377 'values' => $charsets
379 $s .= $this->parent->getHelpBox( 'config-mysql-charset-help' );
382 return $s;
386 * @return Status
388 public function submitSettingsForm() {
389 $this->setVarsFromRequest( array( '_MysqlEngine', '_MysqlCharset' ) );
390 $status = $this->submitWebUserBox();
391 if ( !$status->isOK() ) {
392 return $status;
395 // Validate the create checkbox
396 $canCreate = $this->canCreateAccounts();
397 if ( !$canCreate ) {
398 $this->setVar( '_CreateDBAccount', false );
399 $create = false;
400 } else {
401 $create = $this->getVar( '_CreateDBAccount' );
404 if ( !$create ) {
405 // Test the web account
406 try {
407 new DatabaseMysql(
408 $this->getVar( 'wgDBserver' ),
409 $this->getVar( 'wgDBuser' ),
410 $this->getVar( 'wgDBpassword' ),
411 false,
412 false,
414 $this->getVar( 'wgDBprefix' )
416 } catch ( DBConnectionError $e ) {
417 return Status::newFatal( 'config-connection-error', $e->getMessage() );
421 // Validate engines and charsets
422 // This is done pre-submit already so it's just for security
423 $engines = $this->getEngines();
424 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
425 $this->setVar( '_MysqlEngine', reset( $engines ) );
427 $charsets = $this->getCharsets();
428 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
429 $this->setVar( '_MysqlCharset', reset( $charsets ) );
431 return Status::newGood();
434 public function preInstall() {
435 # Add our user callback to installSteps, right before the tables are created.
436 $callback = array(
437 'name' => 'user',
438 'callback' => array( $this, 'setupUser' ),
440 $this->parent->addInstallStep( $callback, 'tables' );
444 * @return Status
446 public function setupDatabase() {
447 $status = $this->getConnection();
448 if ( !$status->isOK() ) {
449 return $status;
451 $conn = $status->value;
452 $dbName = $this->getVar( 'wgDBname' );
453 if( !$conn->selectDB( $dbName ) ) {
454 $conn->query( "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ), __METHOD__ );
455 $conn->selectDB( $dbName );
457 $this->setupSchemaVars();
458 return $status;
462 * @return Status
464 public function setupUser() {
465 $dbUser = $this->getVar( 'wgDBuser' );
466 if( $dbUser == $this->getVar( '_InstallUser' ) ) {
467 return Status::newGood();
469 $status = $this->getConnection();
470 if ( !$status->isOK() ) {
471 return $status;
474 $this->setupSchemaVars();
475 $dbName = $this->getVar( 'wgDBname' );
476 $this->db->selectDB( $dbName );
477 $server = $this->getVar( 'wgDBserver' );
478 $password = $this->getVar( 'wgDBpassword' );
479 $grantableNames = array();
481 if ( $this->getVar( '_CreateDBAccount' ) ) {
482 // Before we blindly try to create a user that already has access,
483 try { // first attempt to connect to the database
484 new DatabaseMysql(
485 $server,
486 $dbUser,
487 $password,
488 false,
489 false,
491 $this->getVar( 'wgDBprefix' )
493 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
494 $tryToCreate = false;
495 } catch ( DBConnectionError $e ) {
496 $tryToCreate = true;
498 } else {
499 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
500 $tryToCreate = false;
503 if( $tryToCreate ) {
504 $createHostList = array($server,
505 'localhost',
506 'localhost.localdomain',
510 $createHostList = array_unique( $createHostList );
511 $escPass = $this->db->addQuotes( $password );
513 foreach( $createHostList as $host ) {
514 $fullName = $this->buildFullUserName( $dbUser, $host );
515 if( !$this->userDefinitelyExists( $dbUser, $host ) ) {
516 try{
517 $this->db->begin();
518 $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
519 $this->db->commit();
520 $grantableNames[] = $fullName;
521 } catch( DBQueryError $dqe ) {
522 if( $this->db->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
523 // User (probably) already exists
524 $this->db->rollback();
525 $status->warning( 'config-install-user-alreadyexists', $dbUser );
526 $grantableNames[] = $fullName;
527 break;
528 } else {
529 // If we couldn't create for some bizzare reason and the
530 // user probably doesn't exist, skip the grant
531 $this->db->rollback();
532 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
535 } else {
536 $status->warning( 'config-install-user-alreadyexists', $dbUser );
537 $grantableNames[] = $fullName;
538 break;
543 // Try to grant to all the users we know exist or we were able to create
544 $dbAllTables = $this->db->addIdentifierQuotes( $dbName ) . '.*';
545 foreach( $grantableNames as $name ) {
546 try {
547 $this->db->begin();
548 $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
549 $this->db->commit();
550 } catch( DBQueryError $dqe ) {
551 $this->db->rollback();
552 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
556 return $status;
560 * Return a formal 'User'@'Host' username for use in queries
561 * @param $name String Username, quotes will be added
562 * @param $host String Hostname, quotes will be added
563 * @return String
565 private function buildFullUserName( $name, $host ) {
566 return $this->db->addQuotes( $name ) . '@' . $this->db->addQuotes( $host );
570 * Try to see if the user account exists. Our "superuser" may not have
571 * access to mysql.user, so false means "no" or "maybe"
572 * @param $host String Hostname to check
573 * @param $user String Username to check
574 * @return boolean
576 private function userDefinitelyExists( $host, $user ) {
577 try {
578 $res = $this->db->selectRow( 'mysql.user', array( 'Host', 'User' ),
579 array( 'Host' => $host, 'User' => $user ), __METHOD__ );
580 return (bool)$res;
581 } catch( DBQueryError $dqe ) {
582 return false;
588 * Return any table options to be applied to all tables that don't
589 * override them.
591 * @return String
593 protected function getTableOptions() {
594 $options = array();
595 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
596 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
598 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
599 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
601 return implode( ', ', $options );
605 * Get variables to substitute into tables.sql and the SQL patch files.
607 * @return array
609 public function getSchemaVars() {
610 return array(
611 'wgDBTableOptions' => $this->getTableOptions(),
612 'wgDBname' => $this->getVar( 'wgDBname' ),
613 'wgDBuser' => $this->getVar( 'wgDBuser' ),
614 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
618 public function getLocalSettings() {
619 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
620 $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
621 $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
622 return
623 "# MySQL specific settings
624 \$wgDBprefix = \"{$prefix}\";
626 # MySQL table options to use during installation or update
627 \$wgDBTableOptions = \"{$tblOpts}\";
629 # Experimental charset support for MySQL 5.0.
630 \$wgDBmysql5 = {$dbmysql5};";