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