Slight improvements to FormSpecialPage behavior.
[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 $s .= $this->parent->getWarningBox( wfMessage( 'config-mysql-myisam-dep' )->text() );
354 $s .= Xml::closeElement( 'div' );
355
356 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
357 $s .= Xml::openElement( 'script', array( 'type' => 'text/javascript' ) );
358 $s .= '$(\'#dbMyisamWarning\').hide();';
359 $s .= Xml::closeElement( 'script' );
360 }
361
362 if ( count( $engines ) >= 2 ) {
363 // getRadioSet() builds a set of labeled radio buttons.
364 // For grep: The following messages are used as the item labels:
365 // config-mysql-innodb, config-mysql-myisam
366 $s .= $this->getRadioSet( array(
367 'var' => '_MysqlEngine',
368 'label' => 'config-mysql-engine',
369 'itemLabelPrefix' => 'config-mysql-',
370 'values' => $engines,
371 'itemAttribs' => array(
372 'MyISAM' => array(
373 'class' => 'showHideRadio',
374 'rel' => 'dbMyisamWarning'
375 ),
376 'InnoDB' => array(
377 'class' => 'hideShowRadio',
378 'rel' => 'dbMyisamWarning'
379 )
380 )));
381 $s .= $this->parent->getHelpBox( 'config-mysql-engine-help' );
382 }
383
384 // If the current default charset is not supported, use a charset that is
385 $charsets = $this->getCharsets();
386 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
387 $this->setVar( '_MysqlCharset', reset( $charsets ) );
388 }
389
390 // Do charset selector
391 if ( count( $charsets ) >= 2 ) {
392 // getRadioSet() builds a set of labeled radio buttons.
393 // For grep: The following messages are used as the item labels:
394 // config-mysql-binary, config-mysql-utf8
395 $s .= $this->getRadioSet( array(
396 'var' => '_MysqlCharset',
397 'label' => 'config-mysql-charset',
398 'itemLabelPrefix' => 'config-mysql-',
399 'values' => $charsets
400 ));
401 $s .= $this->parent->getHelpBox( 'config-mysql-charset-help' );
402 }
403
404 return $s;
405 }
406
407 /**
408 * @return Status
409 */
410 public function submitSettingsForm() {
411 $this->setVarsFromRequest( array( '_MysqlEngine', '_MysqlCharset' ) );
412 $status = $this->submitWebUserBox();
413 if ( !$status->isOK() ) {
414 return $status;
415 }
416
417 // Validate the create checkbox
418 $canCreate = $this->canCreateAccounts();
419 if ( !$canCreate ) {
420 $this->setVar( '_CreateDBAccount', false );
421 $create = false;
422 } else {
423 $create = $this->getVar( '_CreateDBAccount' );
424 }
425
426 if ( !$create ) {
427 // Test the web account
428 try {
429 new DatabaseMysql(
430 $this->getVar( 'wgDBserver' ),
431 $this->getVar( 'wgDBuser' ),
432 $this->getVar( 'wgDBpassword' ),
433 false,
434 false,
435 0,
436 $this->getVar( 'wgDBprefix' )
437 );
438 } catch ( DBConnectionError $e ) {
439 return Status::newFatal( 'config-connection-error', $e->getMessage() );
440 }
441 }
442
443 // Validate engines and charsets
444 // This is done pre-submit already so it's just for security
445 $engines = $this->getEngines();
446 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
447 $this->setVar( '_MysqlEngine', reset( $engines ) );
448 }
449 $charsets = $this->getCharsets();
450 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
451 $this->setVar( '_MysqlCharset', reset( $charsets ) );
452 }
453 return Status::newGood();
454 }
455
456 public function preInstall() {
457 # Add our user callback to installSteps, right before the tables are created.
458 $callback = array(
459 'name' => 'user',
460 'callback' => array( $this, 'setupUser' ),
461 );
462 $this->parent->addInstallStep( $callback, 'tables' );
463 }
464
465 /**
466 * @return Status
467 */
468 public function setupDatabase() {
469 $status = $this->getConnection();
470 if ( !$status->isOK() ) {
471 return $status;
472 }
473 $conn = $status->value;
474 $dbName = $this->getVar( 'wgDBname' );
475 if ( !$conn->selectDB( $dbName ) ) {
476 $conn->query( "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ), __METHOD__ );
477 $conn->selectDB( $dbName );
478 }
479 $this->setupSchemaVars();
480 return $status;
481 }
482
483 /**
484 * @return Status
485 */
486 public function setupUser() {
487 $dbUser = $this->getVar( 'wgDBuser' );
488 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
489 return Status::newGood();
490 }
491 $status = $this->getConnection();
492 if ( !$status->isOK() ) {
493 return $status;
494 }
495
496 $this->setupSchemaVars();
497 $dbName = $this->getVar( 'wgDBname' );
498 $this->db->selectDB( $dbName );
499 $server = $this->getVar( 'wgDBserver' );
500 $password = $this->getVar( 'wgDBpassword' );
501 $grantableNames = array();
502
503 if ( $this->getVar( '_CreateDBAccount' ) ) {
504 // Before we blindly try to create a user that already has access,
505 try { // first attempt to connect to the database
506 new DatabaseMysql(
507 $server,
508 $dbUser,
509 $password,
510 false,
511 false,
512 0,
513 $this->getVar( 'wgDBprefix' )
514 );
515 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
516 $tryToCreate = false;
517 } catch ( DBConnectionError $e ) {
518 $tryToCreate = true;
519 }
520 } else {
521 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
522 $tryToCreate = false;
523 }
524
525 if ( $tryToCreate ) {
526 $createHostList = array(
527 $server,
528 'localhost',
529 'localhost.localdomain',
530 '%'
531 );
532
533 $createHostList = array_unique( $createHostList );
534 $escPass = $this->db->addQuotes( $password );
535
536 foreach ( $createHostList as $host ) {
537 $fullName = $this->buildFullUserName( $dbUser, $host );
538 if ( !$this->userDefinitelyExists( $dbUser, $host ) ) {
539 try{
540 $this->db->begin( __METHOD__ );
541 $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
542 $this->db->commit( __METHOD__ );
543 $grantableNames[] = $fullName;
544 } catch( DBQueryError $dqe ) {
545 if ( $this->db->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
546 // User (probably) already exists
547 $this->db->rollback( __METHOD__ );
548 $status->warning( 'config-install-user-alreadyexists', $dbUser );
549 $grantableNames[] = $fullName;
550 break;
551 } else {
552 // If we couldn't create for some bizzare reason and the
553 // user probably doesn't exist, skip the grant
554 $this->db->rollback( __METHOD__ );
555 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
556 }
557 }
558 } else {
559 $status->warning( 'config-install-user-alreadyexists', $dbUser );
560 $grantableNames[] = $fullName;
561 break;
562 }
563 }
564 }
565
566 // Try to grant to all the users we know exist or we were able to create
567 $dbAllTables = $this->db->addIdentifierQuotes( $dbName ) . '.*';
568 foreach ( $grantableNames as $name ) {
569 try {
570 $this->db->begin( __METHOD__ );
571 $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
572 $this->db->commit( __METHOD__ );
573 } catch( DBQueryError $dqe ) {
574 $this->db->rollback( __METHOD__ );
575 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
576 }
577 }
578
579 return $status;
580 }
581
582 /**
583 * Return a formal 'User'@'Host' username for use in queries
584 * @param string $name Username, quotes will be added
585 * @param string $host Hostname, quotes will be added
586 * @return String
587 */
588 private function buildFullUserName( $name, $host ) {
589 return $this->db->addQuotes( $name ) . '@' . $this->db->addQuotes( $host );
590 }
591
592 /**
593 * Try to see if the user account exists. Our "superuser" may not have
594 * access to mysql.user, so false means "no" or "maybe"
595 * @param string $host Hostname to check
596 * @param string $user Username to check
597 * @return boolean
598 */
599 private function userDefinitelyExists( $host, $user ) {
600 try {
601 $res = $this->db->selectRow( 'mysql.user', array( 'Host', 'User' ),
602 array( 'Host' => $host, 'User' => $user ), __METHOD__ );
603 return (bool)$res;
604 } catch( DBQueryError $dqe ) {
605 return false;
606 }
607
608 }
609
610 /**
611 * Return any table options to be applied to all tables that don't
612 * override them.
613 *
614 * @return String
615 */
616 protected function getTableOptions() {
617 $options = array();
618 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
619 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
620 }
621 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
622 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
623 }
624 return implode( ', ', $options );
625 }
626
627 /**
628 * Get variables to substitute into tables.sql and the SQL patch files.
629 *
630 * @return array
631 */
632 public function getSchemaVars() {
633 return array(
634 'wgDBTableOptions' => $this->getTableOptions(),
635 'wgDBname' => $this->getVar( 'wgDBname' ),
636 'wgDBuser' => $this->getVar( 'wgDBuser' ),
637 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
638 );
639 }
640
641 public function getLocalSettings() {
642 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
643 $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
644 $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
645 return
646 "# MySQL specific settings
647 \$wgDBprefix = \"{$prefix}\";
648
649 # MySQL table options to use during installation or update
650 \$wgDBTableOptions = \"{$tblOpts}\";
651
652 # Experimental charset support for MySQL 5.0.
653 \$wgDBmysql5 = {$dbmysql5};";
654 }
655 }