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