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