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