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