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