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