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