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