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