Merge "Add wgRevisionId variable to ResourceLoader"
[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' ),
93 $this->parent->getHelpBox( 'config-db-name-help' ) ) .
94 $this->getTextBox( 'wgDBprefix', 'config-db-prefix', array( 'dir' => 'ltr' ),
95 $this->parent->getHelpBox( 'config-db-prefix-help' ) ) .
96 Html::closeElement( 'fieldset' ) .
97 $this->getInstallUserBox();
98 }
99
100 public function submitConnectForm() {
101 // Get variables from the request.
102 $newValues = $this->setVarsFromRequest( array( 'wgDBserver', 'wgDBname', 'wgDBprefix' ) );
103
104 // Validate them.
105 $status = Status::newGood();
106 if ( !strlen( $newValues['wgDBserver'] ) ) {
107 $status->fatal( 'config-missing-db-host' );
108 }
109 if ( !strlen( $newValues['wgDBname'] ) ) {
110 $status->fatal( 'config-missing-db-name' );
111 } elseif ( !preg_match( '/^[a-z0-9+_-]+$/i', $newValues['wgDBname'] ) ) {
112 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
113 }
114 if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
115 $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
116 }
117 if ( !$status->isOK() ) {
118 return $status;
119 }
120
121 // Submit user box
122 $status = $this->submitInstallUserBox();
123 if ( !$status->isOK() ) {
124 return $status;
125 }
126
127 // Try to connect
128 $status = $this->getConnection();
129 if ( !$status->isOK() ) {
130 return $status;
131 }
132 /**
133 * @var $conn DatabaseBase
134 */
135 $conn = $status->value;
136
137 // Check version
138 $version = $conn->getServerVersion();
139 if ( version_compare( $version, $this->minimumVersion ) < 0 ) {
140 return Status::newFatal( 'config-mysql-old', $this->minimumVersion, $version );
141 }
142
143 return $status;
144 }
145
146 /**
147 * @return Status
148 */
149 public function openConnection() {
150 $status = Status::newGood();
151 try {
152 $db = new DatabaseMysql(
153 $this->getVar( 'wgDBserver' ),
154 $this->getVar( '_InstallUser' ),
155 $this->getVar( '_InstallPassword' ),
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 $myisamWarning = 'config-mysql-myisam-dep';
355 if ( count( $engines ) === 1 ) {
356 $myisamWarning = 'config-mysql-only-myisam-dep';
357 }
358 $s .= $this->parent->getWarningBox( wfMessage( $myisamWarning )->text() );
359 $s .= Xml::closeElement( 'div' );
360
361 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
362 $s .= Xml::openElement( 'script', array( 'type' => 'text/javascript' ) );
363 $s .= '$(\'#dbMyisamWarning\').hide();';
364 $s .= Xml::closeElement( 'script' );
365 }
366
367 if ( count( $engines ) >= 2 ) {
368 // getRadioSet() builds a set of labeled radio buttons.
369 // For grep: The following messages are used as the item labels:
370 // config-mysql-innodb, config-mysql-myisam
371 $s .= $this->getRadioSet( array(
372 'var' => '_MysqlEngine',
373 'label' => 'config-mysql-engine',
374 'itemLabelPrefix' => 'config-mysql-',
375 'values' => $engines,
376 'itemAttribs' => array(
377 'MyISAM' => array(
378 'class' => 'showHideRadio',
379 'rel' => 'dbMyisamWarning'
380 ),
381 'InnoDB' => array(
382 'class' => 'hideShowRadio',
383 'rel' => 'dbMyisamWarning'
384 )
385 )));
386 $s .= $this->parent->getHelpBox( 'config-mysql-engine-help' );
387 }
388
389 // If the current default charset is not supported, use a charset that is
390 $charsets = $this->getCharsets();
391 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
392 $this->setVar( '_MysqlCharset', reset( $charsets ) );
393 }
394
395 // Do charset selector
396 if ( count( $charsets ) >= 2 ) {
397 // getRadioSet() builds a set of labeled radio buttons.
398 // For grep: The following messages are used as the item labels:
399 // config-mysql-binary, config-mysql-utf8
400 $s .= $this->getRadioSet( array(
401 'var' => '_MysqlCharset',
402 'label' => 'config-mysql-charset',
403 'itemLabelPrefix' => 'config-mysql-',
404 'values' => $charsets
405 ));
406 $s .= $this->parent->getHelpBox( 'config-mysql-charset-help' );
407 }
408
409 return $s;
410 }
411
412 /**
413 * @return Status
414 */
415 public function submitSettingsForm() {
416 $this->setVarsFromRequest( array( '_MysqlEngine', '_MysqlCharset' ) );
417 $status = $this->submitWebUserBox();
418 if ( !$status->isOK() ) {
419 return $status;
420 }
421
422 // Validate the create checkbox
423 $canCreate = $this->canCreateAccounts();
424 if ( !$canCreate ) {
425 $this->setVar( '_CreateDBAccount', false );
426 $create = false;
427 } else {
428 $create = $this->getVar( '_CreateDBAccount' );
429 }
430
431 if ( !$create ) {
432 // Test the web account
433 try {
434 new DatabaseMysql(
435 $this->getVar( 'wgDBserver' ),
436 $this->getVar( 'wgDBuser' ),
437 $this->getVar( 'wgDBpassword' ),
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 ) . "CHARACTER SET utf8", __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 0,
516 $this->getVar( 'wgDBprefix' )
517 );
518 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
519 $tryToCreate = false;
520 } catch ( DBConnectionError $e ) {
521 $tryToCreate = true;
522 }
523 } else {
524 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
525 $tryToCreate = false;
526 }
527
528 if ( $tryToCreate ) {
529 $createHostList = array(
530 $server,
531 'localhost',
532 'localhost.localdomain',
533 '%'
534 );
535
536 $createHostList = array_unique( $createHostList );
537 $escPass = $this->db->addQuotes( $password );
538
539 foreach ( $createHostList as $host ) {
540 $fullName = $this->buildFullUserName( $dbUser, $host );
541 if ( !$this->userDefinitelyExists( $dbUser, $host ) ) {
542 try {
543 $this->db->begin( __METHOD__ );
544 $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
545 $this->db->commit( __METHOD__ );
546 $grantableNames[] = $fullName;
547 } catch ( DBQueryError $dqe ) {
548 if ( $this->db->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
549 // User (probably) already exists
550 $this->db->rollback( __METHOD__ );
551 $status->warning( 'config-install-user-alreadyexists', $dbUser );
552 $grantableNames[] = $fullName;
553 break;
554 } else {
555 // If we couldn't create for some bizzare reason and the
556 // user probably doesn't exist, skip the grant
557 $this->db->rollback( __METHOD__ );
558 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getText() );
559 }
560 }
561 } else {
562 $status->warning( 'config-install-user-alreadyexists', $dbUser );
563 $grantableNames[] = $fullName;
564 break;
565 }
566 }
567 }
568
569 // Try to grant to all the users we know exist or we were able to create
570 $dbAllTables = $this->db->addIdentifierQuotes( $dbName ) . '.*';
571 foreach ( $grantableNames as $name ) {
572 try {
573 $this->db->begin( __METHOD__ );
574 $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
575 $this->db->commit( __METHOD__ );
576 } catch ( DBQueryError $dqe ) {
577 $this->db->rollback( __METHOD__ );
578 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getText() );
579 }
580 }
581
582 return $status;
583 }
584
585 /**
586 * Return a formal 'User'@'Host' username for use in queries
587 * @param string $name Username, quotes will be added
588 * @param string $host Hostname, quotes will be added
589 * @return String
590 */
591 private function buildFullUserName( $name, $host ) {
592 return $this->db->addQuotes( $name ) . '@' . $this->db->addQuotes( $host );
593 }
594
595 /**
596 * Try to see if the user account exists. Our "superuser" may not have
597 * access to mysql.user, so false means "no" or "maybe"
598 * @param string $host Hostname to check
599 * @param string $user Username to check
600 * @return boolean
601 */
602 private function userDefinitelyExists( $host, $user ) {
603 try {
604 $res = $this->db->selectRow( 'mysql.user', array( 'Host', 'User' ),
605 array( 'Host' => $host, 'User' => $user ), __METHOD__ );
606 return (bool)$res;
607 } catch ( DBQueryError $dqe ) {
608 return false;
609 }
610
611 }
612
613 /**
614 * Return any table options to be applied to all tables that don't
615 * override them.
616 *
617 * @return String
618 */
619 protected function getTableOptions() {
620 $options = array();
621 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
622 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
623 }
624 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
625 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
626 }
627 return implode( ', ', $options );
628 }
629
630 /**
631 * Get variables to substitute into tables.sql and the SQL patch files.
632 *
633 * @return array
634 */
635 public function getSchemaVars() {
636 return array(
637 'wgDBTableOptions' => $this->getTableOptions(),
638 'wgDBname' => $this->getVar( 'wgDBname' ),
639 'wgDBuser' => $this->getVar( 'wgDBuser' ),
640 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
641 );
642 }
643
644 public function getLocalSettings() {
645 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
646 $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
647 $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
648 return
649 "# MySQL specific settings
650 \$wgDBprefix = \"{$prefix}\";
651
652 # MySQL table options to use during installation or update
653 \$wgDBTableOptions = \"{$tblOpts}\";
654
655 # Experimental charset support for MySQL 5.0.
656 \$wgDBmysql5 = {$dbmysql5};";
657 }
658 }