MediaWiki REL1_39
MysqlInstaller.php
Go to the documentation of this file.
1<?php
29
37
38 protected $globalNames = [
39 'wgDBserver',
40 'wgDBname',
41 'wgDBuser',
42 'wgDBpassword',
43 'wgDBssl',
44 'wgDBprefix',
45 'wgDBTableOptions',
46 ];
47
48 protected $internalDefaults = [
49 '_MysqlEngine' => 'InnoDB',
50 '_MysqlCharset' => 'binary',
51 '_InstallUser' => 'root',
52 ];
53
54 public $supportedEngines = [ 'InnoDB' ];
55
56 private const MIN_VERSIONS = [
57 'MySQL' => '5.7.0',
58 'MariaDB' => '10.3',
59 ];
60 public static $minimumVersion;
61 protected static $notMinimumVersionMessage;
62
63 public $webUserPrivs = [
64 'DELETE',
65 'INSERT',
66 'SELECT',
67 'UPDATE',
68 'CREATE TEMPORARY TABLES',
69 ];
70
74 public function getName() {
75 return 'mysql';
76 }
77
81 public function isCompiled() {
82 return self::checkExtension( 'mysqli' );
83 }
84
88 public function getConnectForm() {
89 return $this->getTextBox(
90 'wgDBserver',
91 'config-db-host',
92 [],
93 $this->parent->getHelpBox( 'config-db-host-help' )
94 ) .
95 $this->getCheckBox( 'wgDBssl', 'config-db-ssl' ) .
96 Html::openElement( 'fieldset' ) .
97 Html::element( 'legend', [], wfMessage( 'config-db-wiki-settings' )->text() ) .
98 $this->getTextBox( 'wgDBname', 'config-db-name', [ 'dir' => 'ltr' ],
99 $this->parent->getHelpBox( 'config-db-name-help' ) ) .
100 $this->getTextBox( 'wgDBprefix', 'config-db-prefix', [ 'dir' => 'ltr' ],
101 $this->parent->getHelpBox( 'config-db-prefix-help' ) ) .
102 Html::closeElement( 'fieldset' ) .
103 $this->getInstallUserBox();
104 }
105
106 public function submitConnectForm() {
107 // Get variables from the request.
108 $newValues = $this->setVarsFromRequest( [ 'wgDBserver', 'wgDBname', 'wgDBprefix', 'wgDBssl' ] );
109
110 // Validate them.
111 $status = Status::newGood();
112 if ( !strlen( $newValues['wgDBserver'] ) ) {
113 $status->fatal( 'config-missing-db-host' );
114 }
115 if ( !strlen( $newValues['wgDBname'] ) ) {
116 $status->fatal( 'config-missing-db-name' );
117 } elseif ( !preg_match( '/^[a-z0-9+_-]+$/i', $newValues['wgDBname'] ) ) {
118 $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
119 }
120 if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
121 $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
122 }
123 if ( !$status->isOK() ) {
124 return $status;
125 }
126
127 // Submit user box
128 $status = $this->submitInstallUserBox();
129 if ( !$status->isOK() ) {
130 return $status;
131 }
132
133 // Try to connect
134 $status = $this->getConnection();
135 if ( !$status->isOK() ) {
136 return $status;
137 }
141 $conn = $status->value;
142 '@phan-var Database $conn';
143
144 // Check version
145 return static::meetsMinimumRequirement( $conn );
146 }
147
148 public static function meetsMinimumRequirement( IDatabase $conn ) {
149 $type = str_contains( $conn->getSoftwareLink(), 'MariaDB' ) ? 'MariaDB' : 'MySQL';
150 self::$minimumVersion = self::MIN_VERSIONS[$type];
151 // Used messages: config-mysql-old, config-mariadb-old
152 self::$notMinimumVersionMessage = 'config-' . strtolower( $type ) . '-old';
153 return parent::meetsMinimumRequirement( $conn );
154 }
155
159 public function openConnection() {
160 $status = Status::newGood();
161 try {
163 $db = Database::factory( 'mysql', [
164 'host' => $this->getVar( 'wgDBserver' ),
165 'user' => $this->getVar( '_InstallUser' ),
166 'password' => $this->getVar( '_InstallPassword' ),
167 'ssl' => $this->getVar( 'wgDBssl' ),
168 'dbname' => false,
169 'flags' => 0,
170 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ] );
171 $status->value = $db;
172 } catch ( DBConnectionError $e ) {
173 $status->fatal( 'config-connection-error', $e->getMessage() );
174 }
175
176 return $status;
177 }
178
179 public function preUpgrade() {
180 global $wgDBuser, $wgDBpassword;
181
182 $status = $this->getConnection();
183 if ( !$status->isOK() ) {
184 $this->parent->showStatusMessage( $status );
185
186 return;
187 }
191 $conn = $status->value;
192 $conn->selectDB( $this->getVar( 'wgDBname' ) );
193
194 # Determine existing default character set
195 if ( $conn->tableExists( "revision", __METHOD__ ) ) {
196 $revision = $this->escapeLikeInternal( $this->getVar( 'wgDBprefix' ) . 'revision', '\\' );
197 $res = $conn->query( "SHOW TABLE STATUS LIKE '$revision'", __METHOD__ );
198 $row = $res->fetchObject();
199 if ( !$row ) {
200 $this->parent->showMessage( 'config-show-table-status' );
201 $existingSchema = false;
202 $existingEngine = false;
203 } else {
204 if ( preg_match( '/^latin1/', $row->Collation ) ) {
205 $existingSchema = 'latin1';
206 } elseif ( preg_match( '/^utf8/', $row->Collation ) ) {
207 $existingSchema = 'utf8';
208 } elseif ( preg_match( '/^binary/', $row->Collation ) ) {
209 $existingSchema = 'binary';
210 } else {
211 $existingSchema = false;
212 $this->parent->showMessage( 'config-unknown-collation' );
213 }
214 $existingEngine = $row->Engine ?? $row->Type;
215 }
216 } else {
217 $existingSchema = false;
218 $existingEngine = false;
219 }
220
221 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
222 $this->setVar( '_MysqlCharset', $existingSchema );
223 }
224 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
225 $this->setVar( '_MysqlEngine', $existingEngine );
226 }
227
228 # Normal user and password are selected after this step, so for now
229 # just copy these two
230 $wgDBuser = $this->getVar( '_InstallUser' );
231 $wgDBpassword = $this->getVar( '_InstallPassword' );
232 }
233
239 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
240 return str_replace( [ $escapeChar, '%', '_' ],
241 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
242 $s );
243 }
244
250 public function getEngines() {
251 $status = $this->getConnection();
252
256 $conn = $status->value;
257
258 $engines = [];
259 $res = $conn->query( 'SHOW ENGINES', __METHOD__ );
260 foreach ( $res as $row ) {
261 if ( $row->Support == 'YES' || $row->Support == 'DEFAULT' ) {
262 $engines[] = $row->Engine;
263 }
264 }
265 $engines = array_intersect( $this->supportedEngines, $engines );
266
267 return $engines;
268 }
269
275 public function getCharsets() {
276 return [ 'binary', 'utf8' ];
277 }
278
284 public function canCreateAccounts() {
285 $status = $this->getConnection();
286 if ( !$status->isOK() ) {
287 return false;
288 }
290 $conn = $status->value;
291
292 // Get current account name
293 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__ );
294 $parts = explode( '@', $currentName );
295 if ( count( $parts ) != 2 ) {
296 return false;
297 }
298 $quotedUser = $conn->addQuotes( $parts[0] ) .
299 '@' . $conn->addQuotes( $parts[1] );
300
301 // The user needs to have INSERT on mysql.* to be able to CREATE USER
302 // The grantee will be double-quoted in this query, as required
303 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
304 [ 'GRANTEE' => $quotedUser ], __METHOD__ );
305 $insertMysql = false;
306 $grantOptions = array_fill_keys( $this->webUserPrivs, true );
307 foreach ( $res as $row ) {
308 if ( $row->PRIVILEGE_TYPE == 'INSERT' ) {
309 $insertMysql = true;
310 }
311 if ( $row->IS_GRANTABLE ) {
312 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
313 }
314 }
315
316 // Check for DB-specific privs for mysql.*
317 if ( !$insertMysql ) {
318 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
319 [
320 'GRANTEE' => $quotedUser,
321 'TABLE_SCHEMA' => 'mysql',
322 'PRIVILEGE_TYPE' => 'INSERT',
323 ], __METHOD__ );
324 if ( $row ) {
325 $insertMysql = true;
326 }
327 }
328
329 if ( !$insertMysql ) {
330 return false;
331 }
332
333 // Check for DB-level grant options
334 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
335 [
336 'GRANTEE' => $quotedUser,
337 'IS_GRANTABLE' => 1,
338 ], __METHOD__ );
339 foreach ( $res as $row ) {
340 $regex = $this->likeToRegex( $row->TABLE_SCHEMA );
341 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
342 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
343 }
344 }
345 if ( count( $grantOptions ) ) {
346 // Can't grant everything
347 return false;
348 }
349
350 return true;
351 }
352
359 protected function likeToRegex( $wildcard ) {
360 $r = preg_quote( $wildcard, '/' );
361 $r = strtr( $r, [
362 '%' => '.*',
363 '_' => '.'
364 ] );
365 return "/$r/s";
366 }
367
371 public function getSettingsForm() {
372 if ( $this->canCreateAccounts() ) {
373 $noCreateMsg = false;
374 } else {
375 $noCreateMsg = 'config-db-web-no-create-privs';
376 }
377 $s = $this->getWebUserBox( $noCreateMsg );
378
379 // Do engine selector
380 $engines = $this->getEngines();
381 // If the current default engine is not supported, use an engine that is
382 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
383 $this->setVar( '_MysqlEngine', reset( $engines ) );
384 }
385
386 // If the current default charset is not supported, use a charset that is
387 $charsets = $this->getCharsets();
388 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
389 $this->setVar( '_MysqlCharset', reset( $charsets ) );
390 }
391
392 return $s;
393 }
394
398 public function submitSettingsForm() {
399 $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
400 $status = $this->submitWebUserBox();
401 if ( !$status->isOK() ) {
402 return $status;
403 }
404
405 // Validate the create checkbox
406 $canCreate = $this->canCreateAccounts();
407 if ( !$canCreate ) {
408 $this->setVar( '_CreateDBAccount', false );
409 $create = false;
410 } else {
411 $create = $this->getVar( '_CreateDBAccount' );
412 }
413
414 if ( !$create ) {
415 // Test the web account
416 try {
417 MediaWikiServices::getInstance()->getDatabaseFactory()->create( 'mysql', [
418 'host' => $this->getVar( 'wgDBserver' ),
419 'user' => $this->getVar( 'wgDBuser' ),
420 'password' => $this->getVar( 'wgDBpassword' ),
421 'ssl' => $this->getVar( 'wgDBssl' ),
422 'dbname' => false,
423 'flags' => 0,
424 'tablePrefix' => $this->getVar( 'wgDBprefix' )
425 ] );
426 } catch ( DBConnectionError $e ) {
427 return Status::newFatal( 'config-connection-error', $e->getMessage() );
428 }
429 }
430
431 // Validate engines and charsets
432 // This is done pre-submit already so it's just for security
433 $engines = $this->getEngines();
434 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
435 $this->setVar( '_MysqlEngine', reset( $engines ) );
436 }
437 $charsets = $this->getCharsets();
438 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
439 $this->setVar( '_MysqlCharset', reset( $charsets ) );
440 }
441
442 return Status::newGood();
443 }
444
445 public function preInstall() {
446 # Add our user callback to installSteps, right before the tables are created.
447 $callback = [
448 'name' => 'user',
449 'callback' => [ $this, 'setupUser' ],
450 ];
451 $this->parent->addInstallStep( $callback, 'tables' );
452 }
453
457 public function setupDatabase() {
458 $status = $this->getConnection();
459 if ( !$status->isOK() ) {
460 return $status;
461 }
463 $conn = $status->value;
464 $dbName = $this->getVar( 'wgDBname' );
465 if ( !$this->databaseExists( $dbName ) ) {
466 $conn->query(
467 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
468 __METHOD__
469 );
470 }
471 $conn->selectDB( $dbName );
472 $this->setupSchemaVars();
473
474 return $status;
475 }
476
482 private function databaseExists( $dbName ) {
483 $encDatabase = $this->db->addQuotes( $dbName );
484
485 return $this->db->query(
486 "SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = $encDatabase",
487 __METHOD__
488 )->numRows() > 0;
489 }
490
494 public function setupUser() {
495 $dbUser = $this->getVar( 'wgDBuser' );
496 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
497 return Status::newGood();
498 }
499 $status = $this->getConnection();
500 if ( !$status->isOK() ) {
501 return $status;
502 }
503
504 $this->setupSchemaVars();
505 $dbName = $this->getVar( 'wgDBname' );
506 $this->db->selectDB( $dbName );
507 $server = $this->getVar( 'wgDBserver' );
508 $password = $this->getVar( 'wgDBpassword' );
509 $grantableNames = [];
510
511 if ( $this->getVar( '_CreateDBAccount' ) ) {
512 // Before we blindly try to create a user that already has access,
513 try { // first attempt to connect to the database
514 Database::factory( 'mysql', [
515 'host' => $server,
516 'user' => $dbUser,
517 'password' => $password,
518 'ssl' => $this->getVar( 'wgDBssl' ),
519 'dbname' => false,
520 'flags' => 0,
521 'tablePrefix' => $this->getVar( 'wgDBprefix' )
522 ] );
523 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
524 $tryToCreate = false;
525 } catch ( DBConnectionError $e ) {
526 $tryToCreate = true;
527 }
528 } else {
529 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
530 $tryToCreate = false;
531 }
532
533 if ( $tryToCreate ) {
534 $createHostList = [
535 $server,
536 'localhost',
537 'localhost.localdomain',
538 '%'
539 ];
540
541 $createHostList = array_unique( $createHostList );
542 $escPass = $this->db->addQuotes( $password );
543
544 foreach ( $createHostList as $host ) {
545 $fullName = $this->buildFullUserName( $dbUser, $host );
546 if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
547 try {
548 $this->db->begin( __METHOD__ );
549 $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
550 $this->db->commit( __METHOD__ );
551 $grantableNames[] = $fullName;
552 } catch ( DBQueryError $dqe ) {
553 if ( $this->db->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
554 // User (probably) already exists
555 $this->db->rollback( __METHOD__ );
556 $status->warning( 'config-install-user-alreadyexists', $dbUser );
557 $grantableNames[] = $fullName;
558 break;
559 } else {
560 // If we couldn't create for some bizarre reason and the
561 // user probably doesn't exist, skip the grant
562 $this->db->rollback( __METHOD__ );
563 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getMessage() );
564 }
565 }
566 } else {
567 $status->warning( 'config-install-user-alreadyexists', $dbUser );
568 $grantableNames[] = $fullName;
569 break;
570 }
571 }
572 }
573
574 // Try to grant to all the users we know exist or we were able to create
575 $dbAllTables = $this->db->addIdentifierQuotes( $dbName ) . '.*';
576 foreach ( $grantableNames as $name ) {
577 try {
578 $this->db->begin( __METHOD__ );
579 $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
580 $this->db->commit( __METHOD__ );
581 } catch ( DBQueryError $dqe ) {
582 $this->db->rollback( __METHOD__ );
583 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getMessage() );
584 }
585 }
586
587 return $status;
588 }
589
596 private function buildFullUserName( $name, $host ) {
597 return $this->db->addQuotes( $name ) . '@' . $this->db->addQuotes( $host );
598 }
599
607 private function userDefinitelyExists( $host, $user ) {
608 try {
609 $res = $this->db->selectRow( 'mysql.user', [ 'Host', 'User' ],
610 [ 'Host' => $host, 'User' => $user ], __METHOD__ );
611
612 return (bool)$res;
613 } catch ( DBQueryError $dqe ) {
614 return false;
615 }
616 }
617
624 protected function getTableOptions() {
625 $options = [];
626 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
627 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
628 }
629 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
630 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
631 }
632
633 return implode( ', ', $options );
634 }
635
641 public function getSchemaVars() {
642 return [
643 'wgDBTableOptions' => $this->getTableOptions(),
644 'wgDBname' => $this->getVar( 'wgDBname' ),
645 'wgDBuser' => $this->getVar( 'wgDBuser' ),
646 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
647 ];
648 }
649
650 public function getLocalSettings() {
651 $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
652 $useSsl = $this->getVar( 'wgDBssl' ) ? 'true' : 'false';
653 $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
654
655 return "# MySQL specific settings
656\$wgDBprefix = \"{$prefix}\";
657\$wgDBssl = {$useSsl};
658
659# MySQL table options to use during installation or update
660\$wgDBTableOptions = \"{$tblOpts}\";";
661 }
662}
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Base class for DBMS-specific installation helper classes.
getWebUserBox( $noCreateMsg=false)
Get a standard web-user fieldset.
submitWebUserBox()
Submit the form from getWebUserBox().
static checkExtension( $name)
Convenience function.
Database $db
The database connection.
setVarsFromRequest( $varNames)
Convenience function to set variables based on form data.
getCheckBox( $var, $label, $attribs=[], $helpData="")
Get a labelled checkbox to configure a local boolean variable.
getConnection()
Connect to the database using the administrative user/password currently defined in the session.
getVar( $var, $default=null)
Get a variable, taking local defaults into account.
getTextBox( $var, $label, $attribs=[], $helpData="")
Get a labelled text box to configure a local variable.
setVar( $name, $value)
Convenience alias for $this->parent->setVar()
submitInstallUserBox()
Submit a standard install user fieldset.
getInstallUserBox()
Get a standard install-user fieldset.
setupSchemaVars()
Set appropriate schema variables in the current database connection.
Service locator for MediaWiki core services.
Class for setting up the MediaWiki database using MySQL.
likeToRegex( $wildcard)
Convert a wildcard (as used in LIKE) to a regex Slashes are escaped, slash terminators included.
escapeLikeInternal( $s, $escapeChar='`')
static meetsMinimumRequirement(IDatabase $conn)
Whether the provided version meets the necessary requirements for this type.
getSchemaVars()
Get variables to substitute into tables.sql and the SQL patch files.
preInstall()
Allow DB installers a chance to make last-minute changes before installation occurs.
getEngines()
Get a list of storage engines that are available and supported.
canCreateAccounts()
Return true if the install user can create accounts.
preUpgrade()
Allow DB installers a chance to make checks before upgrade.
getTableOptions()
Return any table options to be applied to all tables that don't override them.
getCharsets()
Get a list of character sets that are available and supported.
static $notMinimumVersionMessage
submitConnectForm()
Set variables based on the request array, assuming it was submitted via the form returned by getConne...
getLocalSettings()
Get the DBMS-specific options for LocalSettings.php generation.
$wgDBuser
Config variable stub for the DBuser setting, for use by phpdoc and IDEs.
$wgDBpassword
Config variable stub for the DBpassword setting, for use by phpdoc and IDEs.
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:39
getSoftwareLink()
Returns a wikitext style link to the DB's website (e.g.
foreach( $mmfl['setupFiles'] as $fileName) if($queue) if(empty( $mmfl['quiet'])) $s