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