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