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