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