Merge "Type hint against LinkTarget in WatchedItemStore"
[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' ];
52
53 public static $minimumVersion = '5.5.8';
54 protected static $notMinimumVersionMessage = '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 Database $conn
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 /** @var DatabaseMysqlBase $db */
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->showStatusMessage( $status );
167
168 return;
169 }
170 /**
171 * @var Database $conn
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 $existingEngine = $row->Engine ?? $row->Type;
197 }
198 } else {
199 $existingSchema = false;
200 $existingEngine = false;
201 }
202
203 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
204 $this->setVar( '_MysqlCharset', $existingSchema );
205 }
206 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
207 $this->setVar( '_MysqlEngine', $existingEngine );
208 }
209
210 # Normal user and password are selected after this step, so for now
211 # just copy these two
212 $wgDBuser = $this->getVar( '_InstallUser' );
213 $wgDBpassword = $this->getVar( '_InstallPassword' );
214 }
215
216 /**
217 * @param string $s
218 * @param string $escapeChar
219 * @return string
220 */
221 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
222 return str_replace( [ $escapeChar, '%', '_' ],
223 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
224 $s );
225 }
226
227 /**
228 * Get a list of storage engines that are available and supported
229 *
230 * @return array
231 */
232 public function getEngines() {
233 $status = $this->getConnection();
234
235 /**
236 * @var Database $conn
237 */
238 $conn = $status->value;
239
240 $engines = [];
241 $res = $conn->query( 'SHOW ENGINES', __METHOD__ );
242 foreach ( $res as $row ) {
243 if ( $row->Support == 'YES' || $row->Support == 'DEFAULT' ) {
244 $engines[] = $row->Engine;
245 }
246 }
247 $engines = array_intersect( $this->supportedEngines, $engines );
248
249 return $engines;
250 }
251
252 /**
253 * Get a list of character sets that are available and supported
254 *
255 * @return array
256 */
257 public function getCharsets() {
258 return [ 'binary', 'utf8' ];
259 }
260
261 /**
262 * Return true if the install user can create accounts
263 *
264 * @return bool
265 */
266 public function canCreateAccounts() {
267 $status = $this->getConnection();
268 if ( !$status->isOK() ) {
269 return false;
270 }
271 /** @var Database $conn */
272 $conn = $status->value;
273
274 // Get current account name
275 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__ );
276 $parts = explode( '@', $currentName );
277 if ( count( $parts ) != 2 ) {
278 return false;
279 }
280 $quotedUser = $conn->addQuotes( $parts[0] ) .
281 '@' . $conn->addQuotes( $parts[1] );
282
283 // The user needs to have INSERT on mysql.* to be able to CREATE USER
284 // The grantee will be double-quoted in this query, as required
285 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
286 [ 'GRANTEE' => $quotedUser ], __METHOD__ );
287 $insertMysql = false;
288 $grantOptions = array_flip( $this->webUserPrivs );
289 foreach ( $res as $row ) {
290 if ( $row->PRIVILEGE_TYPE == 'INSERT' ) {
291 $insertMysql = true;
292 }
293 if ( $row->IS_GRANTABLE ) {
294 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
295 }
296 }
297
298 // Check for DB-specific privs for mysql.*
299 if ( !$insertMysql ) {
300 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
301 [
302 'GRANTEE' => $quotedUser,
303 'TABLE_SCHEMA' => 'mysql',
304 'PRIVILEGE_TYPE' => 'INSERT',
305 ], __METHOD__ );
306 if ( $row ) {
307 $insertMysql = true;
308 }
309 }
310
311 if ( !$insertMysql ) {
312 return false;
313 }
314
315 // Check for DB-level grant options
316 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
317 [
318 'GRANTEE' => $quotedUser,
319 'IS_GRANTABLE' => 1,
320 ], __METHOD__ );
321 foreach ( $res as $row ) {
322 $regex = $this->likeToRegex( $row->TABLE_SCHEMA );
323 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
324 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
325 }
326 }
327 if ( count( $grantOptions ) ) {
328 // Can't grant everything
329 return false;
330 }
331
332 return true;
333 }
334
335 /**
336 * Convert a wildcard (as used in LIKE) to a regex
337 * Slashes are escaped, slash terminators included
338 * @param string $wildcard
339 * @return string
340 */
341 protected function likeToRegex( $wildcard ) {
342 $r = preg_quote( $wildcard, '/' );
343 $r = strtr( $r, [
344 '%' => '.*',
345 '_' => '.'
346 ] );
347 return "/$r/s";
348 }
349
350 /**
351 * @return string
352 */
353 public function getSettingsForm() {
354 if ( $this->canCreateAccounts() ) {
355 $noCreateMsg = false;
356 } else {
357 $noCreateMsg = 'config-db-web-no-create-privs';
358 }
359 $s = $this->getWebUserBox( $noCreateMsg );
360
361 // Do engine selector
362 $engines = $this->getEngines();
363 // If the current default engine is not supported, use an engine that is
364 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
365 $this->setVar( '_MysqlEngine', reset( $engines ) );
366 }
367
368 // If the current default charset is not supported, use a charset that is
369 $charsets = $this->getCharsets();
370 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
371 $this->setVar( '_MysqlCharset', reset( $charsets ) );
372 }
373
374 return $s;
375 }
376
377 /**
378 * @return Status
379 */
380 public function submitSettingsForm() {
381 $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
382 $status = $this->submitWebUserBox();
383 if ( !$status->isOK() ) {
384 return $status;
385 }
386
387 // Validate the create checkbox
388 $canCreate = $this->canCreateAccounts();
389 if ( !$canCreate ) {
390 $this->setVar( '_CreateDBAccount', false );
391 $create = false;
392 } else {
393 $create = $this->getVar( '_CreateDBAccount' );
394 }
395
396 if ( !$create ) {
397 // Test the web account
398 try {
399 Database::factory( 'mysql', [
400 'host' => $this->getVar( 'wgDBserver' ),
401 'user' => $this->getVar( 'wgDBuser' ),
402 'password' => $this->getVar( 'wgDBpassword' ),
403 'dbname' => false,
404 'flags' => 0,
405 'tablePrefix' => $this->getVar( 'wgDBprefix' )
406 ] );
407 } catch ( DBConnectionError $e ) {
408 return Status::newFatal( 'config-connection-error', $e->getMessage() );
409 }
410 }
411
412 // Validate engines and charsets
413 // This is done pre-submit already so it's just for security
414 $engines = $this->getEngines();
415 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
416 $this->setVar( '_MysqlEngine', reset( $engines ) );
417 }
418 $charsets = $this->getCharsets();
419 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
420 $this->setVar( '_MysqlCharset', reset( $charsets ) );
421 }
422
423 return Status::newGood();
424 }
425
426 public function preInstall() {
427 # Add our user callback to installSteps, right before the tables are created.
428 $callback = [
429 'name' => 'user',
430 'callback' => [ $this, 'setupUser' ],
431 ];
432 $this->parent->addInstallStep( $callback, 'tables' );
433 }
434
435 /**
436 * @return Status
437 */
438 public function setupDatabase() {
439 $status = $this->getConnection();
440 if ( !$status->isOK() ) {
441 return $status;
442 }
443 /** @var Database $conn */
444 $conn = $status->value;
445 $dbName = $this->getVar( 'wgDBname' );
446 if ( !$this->databaseExists( $dbName ) ) {
447 $conn->query(
448 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
449 __METHOD__
450 );
451 }
452 $conn->selectDB( $dbName );
453 $this->setupSchemaVars();
454
455 return $status;
456 }
457
458 /**
459 * Try to see if a given database exists
460 * @param string $dbName Database name to check
461 * @return bool
462 */
463 private function databaseExists( $dbName ) {
464 $encDatabase = $this->db->addQuotes( $dbName );
465
466 return $this->db->query(
467 "SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = $encDatabase",
468 __METHOD__
469 )->numRows() > 0;
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 = [];
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 Database::factory( 'mysql', [
496 'host' => $server,
497 'user' => $dbUser,
498 'password' => $password,
499 'dbname' => false,
500 'flags' => 0,
501 'tablePrefix' => $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 = [
515 $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( $host, $dbUser ) ) {
527 try {
528 $this->db->begin( __METHOD__ );
529 $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
530 $this->db->commit( __METHOD__ );
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( __METHOD__ );
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( __METHOD__ );
543 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getMessage() );
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( __METHOD__ );
559 $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
560 $this->db->commit( __METHOD__ );
561 } catch ( DBQueryError $dqe ) {
562 $this->db->rollback( __METHOD__ );
563 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getMessage() );
564 }
565 }
566
567 return $status;
568 }
569
570 /**
571 * Return a formal 'User'@'Host' username for use in queries
572 * @param string $name Username, quotes will be added
573 * @param string $host 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 string $host Hostname to check
584 * @param string $user Username to check
585 * @return bool
586 */
587 private function userDefinitelyExists( $host, $user ) {
588 try {
589 $res = $this->db->selectRow( 'mysql.user', [ 'Host', 'User' ],
590 [ 'Host' => $host, 'User' => $user ], __METHOD__ );
591
592 return (bool)$res;
593 } catch ( DBQueryError $dqe ) {
594 return false;
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 = [];
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
613 return implode( ', ', $options );
614 }
615
616 /**
617 * Get variables to substitute into tables.sql and the SQL patch files.
618 *
619 * @return array
620 */
621 public function getSchemaVars() {
622 return [
623 'wgDBTableOptions' => $this->getTableOptions(),
624 'wgDBname' => $this->getVar( 'wgDBname' ),
625 'wgDBuser' => $this->getVar( 'wgDBuser' ),
626 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
627 ];
628 }
629
630 public function getLocalSettings() {
631 $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
632 $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
633
634 return "# MySQL specific settings
635 \$wgDBprefix = \"{$prefix}\";
636
637 # MySQL table options to use during installation or update
638 \$wgDBTableOptions = \"{$tblOpts}\";";
639 }
640 }