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