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