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