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