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