Patch for Bug #28669, “Scream bloody murder when user chooses MyISAM and InnoDB is...
[lhc/web/wiklou.git] / includes / installer / MysqlInstaller.php
1 <?php
2 /**
3 * MySQL-specific installer.
4 *
5 * @file
6 * @ingroup Deployment
7 */
8
9 /**
10 * Class for setting up the MediaWiki database using MySQL.
11 *
12 * @ingroup Deployment
13 * @since 1.17
14 */
15 class MysqlInstaller extends DatabaseInstaller {
16
17 protected $globalNames = array(
18 'wgDBserver',
19 'wgDBname',
20 'wgDBuser',
21 'wgDBpassword',
22 'wgDBprefix',
23 'wgDBTableOptions',
24 'wgDBmysql5',
25 );
26
27 protected $internalDefaults = array(
28 '_MysqlEngine' => 'InnoDB',
29 '_MysqlCharset' => 'binary',
30 );
31
32 public $supportedEngines = array( 'InnoDB', 'MyISAM' );
33
34 public $minimumVersion = '4.0.14';
35
36 public $webUserPrivs = array(
37 'DELETE',
38 'INSERT',
39 'SELECT',
40 'UPDATE',
41 'CREATE TEMPORARY TABLES',
42 );
43
44 public function getName() {
45 return 'mysql';
46 }
47
48 public function __construct( $parent ) {
49 parent::__construct( $parent );
50 }
51
52 public function isCompiled() {
53 return self::checkExtension( 'mysql' );
54 }
55
56 public function getGlobalDefaults() {
57 return array();
58 }
59
60 public function getConnectForm() {
61 return
62 $this->getTextBox( 'wgDBserver', 'config-db-host', array(), $this->parent->getHelpBox( 'config-db-host-help' ) ) .
63 Html::openElement( 'fieldset' ) .
64 Html::element( 'legend', array(), wfMsg( 'config-db-wiki-settings' ) ) .
65 $this->getTextBox( 'wgDBname', 'config-db-name', array(), $this->parent->getHelpBox( 'config-db-name-help' ) ) .
66 $this->getTextBox( 'wgDBprefix', 'config-db-prefix', array(), $this->parent->getHelpBox( 'config-db-prefix-help' ) ) .
67 Html::closeElement( 'fieldset' ) .
68 $this->getInstallUserBox();
69 }
70
71 public function submitConnectForm() {
72 // Get variables from the request.
73 $newValues = $this->setVarsFromRequest( array( 'wgDBserver', 'wgDBname', 'wgDBprefix' ) );
74
75 // Validate them.
76 $status = Status::newGood();
77 if ( !strlen( $newValues['wgDBserver'] ) ) {
78 $status->fatal( 'config-missing-db-host' );
79 }
80 if ( !strlen( $newValues['wgDBname'] ) ) {
81 $status->fatal( 'config-missing-db-name' );
82 } elseif ( !preg_match( '/^[a-z0-9_-]+$/i', $newValues['wgDBname'] ) ) {
83 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
84 }
85 if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
86 $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
87 }
88 if ( !$status->isOK() ) {
89 return $status;
90 }
91
92 // Submit user box
93 $status = $this->submitInstallUserBox();
94 if ( !$status->isOK() ) {
95 return $status;
96 }
97
98 // Try to connect
99 $status = $this->getConnection();
100 if ( !$status->isOK() ) {
101 return $status;
102 }
103 $conn = $status->value;
104
105 // Check version
106 $version = $conn->getServerVersion();
107 if ( version_compare( $version, $this->minimumVersion ) < 0 ) {
108 return Status::newFatal( 'config-mysql-old', $this->minimumVersion, $version );
109 }
110
111 return $status;
112 }
113
114 public function openConnection() {
115 $status = Status::newGood();
116 try {
117 $db = new DatabaseMysql(
118 $this->getVar( 'wgDBserver' ),
119 $this->getVar( '_InstallUser' ),
120 $this->getVar( '_InstallPassword' ),
121 false,
122 false,
123 0,
124 $this->getVar( 'wgDBprefix' )
125 );
126 $status->value = $db;
127 } catch ( DBConnectionError $e ) {
128 $status->fatal( 'config-connection-error', $e->getMessage() );
129 }
130 return $status;
131 }
132
133 public function preUpgrade() {
134 global $wgDBuser, $wgDBpassword;
135
136 $status = $this->getConnection();
137 if ( !$status->isOK() ) {
138 $this->parent->showStatusError( $status );
139 return;
140 }
141 $conn = $status->value;
142 $conn->selectDB( $this->getVar( 'wgDBname' ) );
143
144 # Determine existing default character set
145 if ( $conn->tableExists( "revision" ) ) {
146 $revision = $conn->buildLike( $this->getVar( 'wgDBprefix' ) . 'revision' );
147 $res = $conn->query( "SHOW TABLE STATUS $revision", __METHOD__ );
148 $row = $conn->fetchObject( $res );
149 if ( !$row ) {
150 $this->parent->showMessage( 'config-show-table-status' );
151 $existingSchema = false;
152 $existingEngine = false;
153 } else {
154 if ( preg_match( '/^latin1/', $row->Collation ) ) {
155 $existingSchema = 'mysql4';
156 } elseif ( preg_match( '/^utf8/', $row->Collation ) ) {
157 $existingSchema = 'utf8';
158 } elseif ( preg_match( '/^binary/', $row->Collation ) ) {
159 $existingSchema = 'binary';
160 } else {
161 $existingSchema = false;
162 $this->parent->showMessage( 'config-unknown-collation' );
163 }
164 if ( isset( $row->Engine ) ) {
165 $existingEngine = $row->Engine;
166 } else {
167 $existingEngine = $row->Type;
168 }
169 }
170 } else {
171 $existingSchema = false;
172 $existingEngine = false;
173 }
174
175 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
176 $this->setVar( '_MysqlCharset', $existingSchema );
177 }
178 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
179 $this->setVar( '_MysqlEngine', $existingEngine );
180 }
181
182 # Normal user and password are selected after this step, so for now
183 # just copy these two
184 $wgDBuser = $this->getVar( '_InstallUser' );
185 $wgDBpassword = $this->getVar( '_InstallPassword' );
186 }
187
188 /**
189 * Get a list of storage engines that are available and supported
190 */
191 public function getEngines() {
192 $engines = array( 'InnoDB', 'MyISAM' );
193 $status = $this->getConnection();
194 if ( !$status->isOK() ) {
195 return $engines;
196 }
197 $conn = $status->value;
198
199 $version = $conn->getServerVersion();
200 if ( version_compare( $version, "4.1.2", "<" ) ) {
201 // No SHOW ENGINES in this version
202 return $engines;
203 }
204
205 $engines = array();
206 $res = $conn->query( 'SHOW ENGINES', __METHOD__ );
207 foreach ( $res as $row ) {
208 if ( $row->Support == 'YES' || $row->Support == 'DEFAULT' ) {
209 $engines[] = $row->Engine;
210 }
211 }
212 $engines = array_intersect( $this->supportedEngines, $engines );
213 return $engines;
214 }
215
216 /**
217 * Get a list of character sets that are available and supported
218 */
219 public function getCharsets() {
220 $status = $this->getConnection();
221 $mysql5 = array( 'binary', 'utf8' );
222 $mysql4 = array( 'mysql4' );
223 if ( !$status->isOK() ) {
224 return $mysql5;
225 }
226 if ( version_compare( $status->value->getServerVersion(), '4.1.0', '>=' ) ) {
227 return $mysql5;
228 }
229 return $mysql4;
230 }
231
232 /**
233 * Return true if the install user can create accounts
234 */
235 public function canCreateAccounts() {
236 $status = $this->getConnection();
237 if ( !$status->isOK() ) {
238 return false;
239 }
240 $conn = $status->value;
241
242 // Check version, need INFORMATION_SCHEMA and CREATE USER
243 if ( version_compare( $conn->getServerVersion(), '5.0.2', '<' ) ) {
244 return false;
245 }
246
247 // Get current account name
248 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__ );
249 $parts = explode( '@', $currentName );
250 if ( count( $parts ) != 2 ) {
251 return false;
252 }
253 $quotedUser = $conn->addQuotes( $parts[0] ) .
254 '@' . $conn->addQuotes( $parts[1] );
255
256 // The user needs to have INSERT on mysql.* to be able to CREATE USER
257 // The grantee will be double-quoted in this query, as required
258 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
259 array( 'GRANTEE' => $quotedUser ), __METHOD__ );
260 $insertMysql = false;
261 $grantOptions = array_flip( $this->webUserPrivs );
262 foreach ( $res as $row ) {
263 if ( $row->PRIVILEGE_TYPE == 'INSERT' ) {
264 $insertMysql = true;
265 }
266 if ( $row->IS_GRANTABLE ) {
267 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
268 }
269 }
270
271 // Check for DB-specific privs for mysql.*
272 if ( !$insertMysql ) {
273 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
274 array(
275 'GRANTEE' => $quotedUser,
276 'TABLE_SCHEMA' => 'mysql',
277 'PRIVILEGE_TYPE' => 'INSERT',
278 ), __METHOD__ );
279 if ( $row ) {
280 $insertMysql = true;
281 }
282 }
283
284 if ( !$insertMysql ) {
285 return false;
286 }
287
288 // Check for DB-level grant options
289 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
290 array(
291 'GRANTEE' => $quotedUser,
292 'IS_GRANTABLE' => 1,
293 ), __METHOD__ );
294 foreach ( $res as $row ) {
295 $regex = $conn->likeToRegex( $row->TABLE_SCHEMA );
296 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
297 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
298 }
299 }
300 if ( count( $grantOptions ) ) {
301 // Can't grant everything
302 return false;
303 }
304 return true;
305 }
306
307 public function getSettingsForm() {
308 if ( $this->canCreateAccounts() ) {
309 $noCreateMsg = false;
310 } else {
311 $noCreateMsg = 'config-db-web-no-create-privs';
312 }
313 $s = $this->getWebUserBox( $noCreateMsg );
314
315 // Do engine selector
316 $engines = $this->getEngines();
317 // If the current default engine is not supported, use an engine that is
318 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
319 $this->setVar( '_MysqlEngine', reset( $engines ) );
320 }
321
322 $s .= Xml::openElement( 'div', array(
323 'id' => 'dbMyisamWarning'
324 ));
325 $s .= $this->parent->getWarningBox( wfMsg( 'config-mysql-myisam-dep' ) );
326 $s .= Xml::closeElement( 'div' );
327
328 if( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
329 $s .= Xml::openElement( 'script', array( 'type' => 'text/javascript' ) );
330 $s .= '$(\'#dbMyisamWarning\').hide();';
331 $s .= Xml::closeElement( 'script' );
332 }
333
334 if ( count( $engines ) >= 2 ) {
335 $s .= $this->getRadioSet( array(
336 'var' => '_MysqlEngine',
337 'label' => 'config-mysql-engine',
338 'itemLabelPrefix' => 'config-mysql-',
339 'values' => $engines,
340 'itemAttribs' => array(
341 'MyISAM' => array(
342 'class' => 'showHideRadio',
343 'rel' => 'dbMyisamWarning'),
344 'InnoDB' => array(
345 'class' => 'hideShowRadio',
346 'rel' => 'dbMyisamWarning')
347 )));
348 $s .= $this->parent->getHelpBox( 'config-mysql-engine-help' );
349 }
350
351 // If the current default charset is not supported, use a charset that is
352 $charsets = $this->getCharsets();
353 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
354 $this->setVar( '_MysqlCharset', reset( $charsets ) );
355 }
356
357 // Do charset selector
358 if ( count( $charsets ) >= 2 ) {
359 $s .= $this->getRadioSet( array(
360 'var' => '_MysqlCharset',
361 'label' => 'config-mysql-charset',
362 'itemLabelPrefix' => 'config-mysql-',
363 'values' => $charsets
364 ));
365 $s .= $this->parent->getHelpBox( 'config-mysql-charset-help' );
366 }
367
368 return $s;
369 }
370
371 public function submitSettingsForm() {
372 $this->setVarsFromRequest( array( '_MysqlEngine', '_MysqlCharset' ) );
373 $status = $this->submitWebUserBox();
374 if ( !$status->isOK() ) {
375 return $status;
376 }
377
378 // Validate the create checkbox
379 $canCreate = $this->canCreateAccounts();
380 if ( !$canCreate ) {
381 $this->setVar( '_CreateDBAccount', false );
382 $create = false;
383 } else {
384 $create = $this->getVar( '_CreateDBAccount' );
385 }
386
387 if ( !$create ) {
388 // Test the web account
389 try {
390 new DatabaseMysql(
391 $this->getVar( 'wgDBserver' ),
392 $this->getVar( 'wgDBuser' ),
393 $this->getVar( 'wgDBpassword' ),
394 false,
395 false,
396 0,
397 $this->getVar( 'wgDBprefix' )
398 );
399 } catch ( DBConnectionError $e ) {
400 return Status::newFatal( 'config-connection-error', $e->getMessage() );
401 }
402 }
403
404 // Validate engines and charsets
405 // This is done pre-submit already so it's just for security
406 $engines = $this->getEngines();
407 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
408 $this->setVar( '_MysqlEngine', reset( $engines ) );
409 }
410 $charsets = $this->getCharsets();
411 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
412 $this->setVar( '_MysqlCharset', reset( $charsets ) );
413 }
414 return Status::newGood();
415 }
416
417 public function preInstall() {
418 # Add our user callback to installSteps, right before the tables are created.
419 $callback = array(
420 'name' => 'user',
421 'callback' => array( $this, 'setupUser' ),
422 );
423 $this->parent->addInstallStep( $callback, 'tables' );
424 }
425
426 public function setupDatabase() {
427 $status = $this->getConnection();
428 if ( !$status->isOK() ) {
429 return $status;
430 }
431 $conn = $status->value;
432 $dbName = $this->getVar( 'wgDBname' );
433 if( !$conn->selectDB( $dbName ) ) {
434 $conn->query( "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ), __METHOD__ );
435 $conn->selectDB( $dbName );
436 }
437 $this->setupSchemaVars();
438 return $status;
439 }
440
441 public function setupUser() {
442 $dbUser = $this->getVar( 'wgDBuser' );
443 if( $dbUser == $this->getVar( '_InstallUser' ) ) {
444 return Status::newGood();
445 }
446 $status = $this->getConnection();
447 if ( !$status->isOK() ) {
448 return $status;
449 }
450
451 $this->setupSchemaVars();
452 $dbName = $this->getVar( 'wgDBname' );
453 $this->db->selectDB( $dbName );
454 $server = $this->getVar( 'wgDBserver' );
455 $password = $this->getVar( 'wgDBpassword' );
456 $grantableNames = array();
457
458 if ( $this->getVar( '_CreateDBAccount' ) ) {
459 // Before we blindly try to create a user that already has access,
460 try { // first attempt to connect to the database
461 new DatabaseMysql(
462 $server,
463 $dbUser,
464 $password,
465 false,
466 false,
467 0,
468 $this->getVar( 'wgDBprefix' )
469 );
470 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
471 $tryToCreate = false;
472 } catch ( DBConnectionError $e ) {
473 $tryToCreate = true;
474 }
475 } else {
476 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
477 $tryToCreate = false;
478 }
479
480 if( $tryToCreate ) {
481 $createHostList = array($server,
482 'localhost',
483 'localhost.localdomain',
484 '%'
485 );
486
487 $createHostList = array_unique( $createHostList );
488 $escPass = $this->db->addQuotes( $password );
489
490 foreach( $createHostList as $host ) {
491 $fullName = $this->buildFullUserName( $dbUser, $host );
492 if( !$this->userDefinitelyExists( $dbUser, $host ) ) {
493 try{
494 $this->db->begin();
495 $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
496 $this->db->commit();
497 $grantableNames[] = $fullName;
498 } catch( DBQueryError $dqe ) {
499 if( $this->db->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
500 // User (probably) already exists
501 $this->db->rollback();
502 $status->warning( 'config-install-user-alreadyexists', $dbUser );
503 $grantableNames[] = $fullName;
504 break;
505 } else {
506 // If we couldn't create for some bizzare reason and the
507 // user probably doesn't exist, skip the grant
508 $this->db->rollback();
509 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
510 }
511 }
512 } else {
513 $status->warning( 'config-install-user-alreadyexists', $dbUser );
514 $grantableNames[] = $fullName;
515 break;
516 }
517 }
518 }
519
520 // Try to grant to all the users we know exist or we were able to create
521 $dbAllTables = $this->db->addIdentifierQuotes( $dbName ) . '.*';
522 foreach( $grantableNames as $name ) {
523 try {
524 $this->db->begin();
525 $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
526 $this->db->commit();
527 } catch( DBQueryError $dqe ) {
528 $this->db->rollback();
529 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
530 }
531 }
532
533 return $status;
534 }
535
536 /**
537 * Return a formal 'User'@'Host' username for use in queries
538 * @param $name String Username, quotes will be added
539 * @param $host String Hostname, quotes will be added
540 * @return String
541 */
542 private function buildFullUserName( $name, $host ) {
543 return $this->db->addQuotes( $name ) . '@' . $this->db->addQuotes( $host );
544 }
545
546 /**
547 * Try to see if the user account exists. Our "superuser" may not have
548 * access to mysql.user, so false means "no" or "maybe"
549 * @param $host String Hostname to check
550 * @param $user String Username to check
551 * @return boolean
552 */
553 private function userDefinitelyExists( $host, $user ) {
554 try {
555 $res = $this->db->selectRow( 'mysql.user', array( 'Host', 'User' ),
556 array( 'Host' => $host, 'User' => $user ), __METHOD__ );
557 return (bool)$res;
558 } catch( DBQueryError $dqe ) {
559 return false;
560 }
561
562 }
563
564 /**
565 * Return any table options to be applied to all tables that don't
566 * override them.
567 *
568 * @return String
569 */
570 protected function getTableOptions() {
571 $options = array();
572 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
573 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
574 }
575 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
576 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
577 }
578 return implode( ', ', $options );
579 }
580
581 /**
582 * Get variables to substitute into tables.sql and the SQL patch files.
583 */
584 public function getSchemaVars() {
585 return array(
586 'wgDBTableOptions' => $this->getTableOptions(),
587 'wgDBname' => $this->getVar( 'wgDBname' ),
588 'wgDBuser' => $this->getVar( 'wgDBuser' ),
589 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
590 );
591 }
592
593 public function getLocalSettings() {
594 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
595 $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
596 $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
597 return
598 "# MySQL specific settings
599 \$wgDBprefix = \"{$prefix}\";
600
601 # MySQL table options to use during installation or update
602 \$wgDBTableOptions = \"{$tblOpts}\";
603
604 # Experimental charset support for MySQL 4.1/5.0.
605 \$wgDBmysql5 = {$dbmysql5};";
606 }
607 }