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