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