MediaWiki  master
MysqlInstaller.php
Go to the documentation of this file.
1 <?php
28 
36 
37  protected $globalNames = [
38  'wgDBserver',
39  'wgDBname',
40  'wgDBuser',
41  'wgDBpassword',
42  'wgDBprefix',
43  'wgDBTableOptions',
44  ];
45 
46  protected $internalDefaults = [
47  '_MysqlEngine' => 'InnoDB',
48  '_MysqlCharset' => 'binary',
49  '_InstallUser' => 'root',
50  ];
51 
52  public $supportedEngines = [ 'InnoDB' ];
53 
54  public static $minimumVersion = '5.7.0';
55  protected static $notMinimumVersionMessage = 'config-mysql-old';
56 
57  public $webUserPrivs = [
58  'DELETE',
59  'INSERT',
60  'SELECT',
61  'UPDATE',
62  'CREATE TEMPORARY TABLES',
63  ];
64 
68  public function getName() {
69  return 'mysql';
70  }
71 
75  public function isCompiled() {
76  return self::checkExtension( 'mysqli' );
77  }
78 
82  public function getConnectForm() {
83  return $this->getTextBox(
84  'wgDBserver',
85  'config-db-host',
86  [],
87  $this->parent->getHelpBox( 'config-db-host-help' )
88  ) .
89  Html::openElement( 'fieldset' ) .
90  Html::element( 'legend', [], wfMessage( 'config-db-wiki-settings' )->text() ) .
91  $this->getTextBox( 'wgDBname', 'config-db-name', [ 'dir' => 'ltr' ],
92  $this->parent->getHelpBox( 'config-db-name-help' ) ) .
93  $this->getTextBox( 'wgDBprefix', 'config-db-prefix', [ 'dir' => 'ltr' ],
94  $this->parent->getHelpBox( 'config-db-prefix-help' ) ) .
95  Html::closeElement( 'fieldset' ) .
96  $this->getInstallUserBox();
97  }
98 
99  public function submitConnectForm() {
100  // Get variables from the request.
101  $newValues = $this->setVarsFromRequest( [ 'wgDBserver', 'wgDBname', 'wgDBprefix' ] );
102 
103  // Validate them.
104  $status = Status::newGood();
105  if ( !strlen( $newValues['wgDBserver'] ) ) {
106  $status->fatal( 'config-missing-db-host' );
107  }
108  if ( !strlen( $newValues['wgDBname'] ) ) {
109  $status->fatal( 'config-missing-db-name' );
110  } elseif ( !preg_match( '/^[a-z0-9+_-]+$/i', $newValues['wgDBname'] ) ) {
111  $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
112  }
113  if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
114  $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
115  }
116  if ( !$status->isOK() ) {
117  return $status;
118  }
119 
120  // Submit user box
121  $status = $this->submitInstallUserBox();
122  if ( !$status->isOK() ) {
123  return $status;
124  }
125 
126  // Try to connect
127  $status = $this->getConnection();
128  if ( !$status->isOK() ) {
129  return $status;
130  }
134  $conn = $status->value;
135  '@phan-var Database $conn';
136 
137  // Check version
138  return static::meetsMinimumRequirement( $conn->getServerVersion() );
139  }
140 
144  public function openConnection() {
145  $status = Status::newGood();
146  try {
148  $db = Database::factory( 'mysql', [
149  'host' => $this->getVar( 'wgDBserver' ),
150  'user' => $this->getVar( '_InstallUser' ),
151  'password' => $this->getVar( '_InstallPassword' ),
152  'dbname' => false,
153  'flags' => 0,
154  'tablePrefix' => $this->getVar( 'wgDBprefix' ) ] );
155  $status->value = $db;
156  } catch ( DBConnectionError $e ) {
157  $status->fatal( 'config-connection-error', $e->getMessage() );
158  }
159 
160  return $status;
161  }
162 
163  public function preUpgrade() {
164  global $wgDBuser, $wgDBpassword;
165 
166  $status = $this->getConnection();
167  if ( !$status->isOK() ) {
168  $this->parent->showStatusMessage( $status );
169 
170  return;
171  }
175  $conn = $status->value;
176  $conn->selectDB( $this->getVar( 'wgDBname' ) );
177 
178  # Determine existing default character set
179  if ( $conn->tableExists( "revision", __METHOD__ ) ) {
180  $revision = $this->escapeLikeInternal( $this->getVar( 'wgDBprefix' ) . 'revision', '\\' );
181  $res = $conn->query( "SHOW TABLE STATUS LIKE '$revision'", __METHOD__ );
182  $row = $res->fetchObject();
183  if ( !$row ) {
184  $this->parent->showMessage( 'config-show-table-status' );
185  $existingSchema = false;
186  $existingEngine = false;
187  } else {
188  if ( preg_match( '/^latin1/', $row->Collation ) ) {
189  $existingSchema = 'latin1';
190  } elseif ( preg_match( '/^utf8/', $row->Collation ) ) {
191  $existingSchema = 'utf8';
192  } elseif ( preg_match( '/^binary/', $row->Collation ) ) {
193  $existingSchema = 'binary';
194  } else {
195  $existingSchema = false;
196  $this->parent->showMessage( 'config-unknown-collation' );
197  }
198  $existingEngine = $row->Engine ?? $row->Type;
199  }
200  } else {
201  $existingSchema = false;
202  $existingEngine = false;
203  }
204 
205  if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
206  $this->setVar( '_MysqlCharset', $existingSchema );
207  }
208  if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
209  $this->setVar( '_MysqlEngine', $existingEngine );
210  }
211 
212  # Normal user and password are selected after this step, so for now
213  # just copy these two
214  $wgDBuser = $this->getVar( '_InstallUser' );
215  $wgDBpassword = $this->getVar( '_InstallPassword' );
216  }
217 
223  protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
224  return str_replace( [ $escapeChar, '%', '_' ],
225  [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
226  $s );
227  }
228 
234  public function getEngines() {
235  $status = $this->getConnection();
236 
240  $conn = $status->value;
241 
242  $engines = [];
243  $res = $conn->query( 'SHOW ENGINES', __METHOD__ );
244  foreach ( $res as $row ) {
245  if ( $row->Support == 'YES' || $row->Support == 'DEFAULT' ) {
246  $engines[] = $row->Engine;
247  }
248  }
249  $engines = array_intersect( $this->supportedEngines, $engines );
250 
251  return $engines;
252  }
253 
259  public function getCharsets() {
260  return [ 'binary', 'utf8' ];
261  }
262 
268  public function canCreateAccounts() {
269  $status = $this->getConnection();
270  if ( !$status->isOK() ) {
271  return false;
272  }
274  $conn = $status->value;
275 
276  // Get current account name
277  $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__ );
278  $parts = explode( '@', $currentName );
279  if ( count( $parts ) != 2 ) {
280  return false;
281  }
282  $quotedUser = $conn->addQuotes( $parts[0] ) .
283  '@' . $conn->addQuotes( $parts[1] );
284 
285  // The user needs to have INSERT on mysql.* to be able to CREATE USER
286  // The grantee will be double-quoted in this query, as required
287  $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
288  [ 'GRANTEE' => $quotedUser ], __METHOD__ );
289  $insertMysql = false;
290  $grantOptions = array_fill_keys( $this->webUserPrivs, true );
291  foreach ( $res as $row ) {
292  if ( $row->PRIVILEGE_TYPE == 'INSERT' ) {
293  $insertMysql = true;
294  }
295  if ( $row->IS_GRANTABLE ) {
296  unset( $grantOptions[$row->PRIVILEGE_TYPE] );
297  }
298  }
299 
300  // Check for DB-specific privs for mysql.*
301  if ( !$insertMysql ) {
302  $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
303  [
304  'GRANTEE' => $quotedUser,
305  'TABLE_SCHEMA' => 'mysql',
306  'PRIVILEGE_TYPE' => 'INSERT',
307  ], __METHOD__ );
308  if ( $row ) {
309  $insertMysql = true;
310  }
311  }
312 
313  if ( !$insertMysql ) {
314  return false;
315  }
316 
317  // Check for DB-level grant options
318  $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
319  [
320  'GRANTEE' => $quotedUser,
321  'IS_GRANTABLE' => 1,
322  ], __METHOD__ );
323  foreach ( $res as $row ) {
324  $regex = $this->likeToRegex( $row->TABLE_SCHEMA );
325  if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
326  unset( $grantOptions[$row->PRIVILEGE_TYPE] );
327  }
328  }
329  if ( count( $grantOptions ) ) {
330  // Can't grant everything
331  return false;
332  }
333 
334  return true;
335  }
336 
343  protected function likeToRegex( $wildcard ) {
344  $r = preg_quote( $wildcard, '/' );
345  $r = strtr( $r, [
346  '%' => '.*',
347  '_' => '.'
348  ] );
349  return "/$r/s";
350  }
351 
355  public function getSettingsForm() {
356  if ( $this->canCreateAccounts() ) {
357  $noCreateMsg = false;
358  } else {
359  $noCreateMsg = 'config-db-web-no-create-privs';
360  }
361  $s = $this->getWebUserBox( $noCreateMsg );
362 
363  // Do engine selector
364  $engines = $this->getEngines();
365  // If the current default engine is not supported, use an engine that is
366  if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
367  $this->setVar( '_MysqlEngine', reset( $engines ) );
368  }
369 
370  // If the current default charset is not supported, use a charset that is
371  $charsets = $this->getCharsets();
372  if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
373  $this->setVar( '_MysqlCharset', reset( $charsets ) );
374  }
375 
376  return $s;
377  }
378 
382  public function submitSettingsForm() {
383  $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
384  $status = $this->submitWebUserBox();
385  if ( !$status->isOK() ) {
386  return $status;
387  }
388 
389  // Validate the create checkbox
390  $canCreate = $this->canCreateAccounts();
391  if ( !$canCreate ) {
392  $this->setVar( '_CreateDBAccount', false );
393  $create = false;
394  } else {
395  $create = $this->getVar( '_CreateDBAccount' );
396  }
397 
398  if ( !$create ) {
399  // Test the web account
400  try {
401  MediaWikiServices::getInstance()->getDatabaseFactory()->create( 'mysql', [
402  'host' => $this->getVar( 'wgDBserver' ),
403  'user' => $this->getVar( 'wgDBuser' ),
404  'password' => $this->getVar( 'wgDBpassword' ),
405  'dbname' => false,
406  'flags' => 0,
407  'tablePrefix' => $this->getVar( 'wgDBprefix' )
408  ] );
409  } catch ( DBConnectionError $e ) {
410  return Status::newFatal( 'config-connection-error', $e->getMessage() );
411  }
412  }
413 
414  // Validate engines and charsets
415  // This is done pre-submit already so it's just for security
416  $engines = $this->getEngines();
417  if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
418  $this->setVar( '_MysqlEngine', reset( $engines ) );
419  }
420  $charsets = $this->getCharsets();
421  if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
422  $this->setVar( '_MysqlCharset', reset( $charsets ) );
423  }
424 
425  return Status::newGood();
426  }
427 
428  public function preInstall() {
429  # Add our user callback to installSteps, right before the tables are created.
430  $callback = [
431  'name' => 'user',
432  'callback' => [ $this, 'setupUser' ],
433  ];
434  $this->parent->addInstallStep( $callback, 'tables' );
435  }
436 
440  public function setupDatabase() {
441  $status = $this->getConnection();
442  if ( !$status->isOK() ) {
443  return $status;
444  }
446  $conn = $status->value;
447  $dbName = $this->getVar( 'wgDBname' );
448  if ( !$this->databaseExists( $dbName ) ) {
449  $conn->query(
450  "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
451  __METHOD__
452  );
453  }
454  $conn->selectDB( $dbName );
455  $this->setupSchemaVars();
456 
457  return $status;
458  }
459 
465  private function databaseExists( $dbName ) {
466  $encDatabase = $this->db->addQuotes( $dbName );
467 
468  return $this->db->query(
469  "SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = $encDatabase",
470  __METHOD__
471  )->numRows() > 0;
472  }
473 
477  public function setupUser() {
478  $dbUser = $this->getVar( 'wgDBuser' );
479  if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
480  return Status::newGood();
481  }
482  $status = $this->getConnection();
483  if ( !$status->isOK() ) {
484  return $status;
485  }
486 
487  $this->setupSchemaVars();
488  $dbName = $this->getVar( 'wgDBname' );
489  $this->db->selectDB( $dbName );
490  $server = $this->getVar( 'wgDBserver' );
491  $password = $this->getVar( 'wgDBpassword' );
492  $grantableNames = [];
493 
494  if ( $this->getVar( '_CreateDBAccount' ) ) {
495  // Before we blindly try to create a user that already has access,
496  try { // first attempt to connect to the database
497  Database::factory( 'mysql', [
498  'host' => $server,
499  'user' => $dbUser,
500  'password' => $password,
501  'dbname' => false,
502  'flags' => 0,
503  'tablePrefix' => $this->getVar( 'wgDBprefix' )
504  ] );
505  $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
506  $tryToCreate = false;
507  } catch ( DBConnectionError $e ) {
508  $tryToCreate = true;
509  }
510  } else {
511  $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
512  $tryToCreate = false;
513  }
514 
515  if ( $tryToCreate ) {
516  $createHostList = [
517  $server,
518  'localhost',
519  'localhost.localdomain',
520  '%'
521  ];
522 
523  $createHostList = array_unique( $createHostList );
524  $escPass = $this->db->addQuotes( $password );
525 
526  foreach ( $createHostList as $host ) {
527  $fullName = $this->buildFullUserName( $dbUser, $host );
528  if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
529  try {
530  $this->db->begin( __METHOD__ );
531  $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
532  $this->db->commit( __METHOD__ );
533  $grantableNames[] = $fullName;
534  } catch ( DBQueryError $dqe ) {
535  if ( $this->db->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
536  // User (probably) already exists
537  $this->db->rollback( __METHOD__ );
538  $status->warning( 'config-install-user-alreadyexists', $dbUser );
539  $grantableNames[] = $fullName;
540  break;
541  } else {
542  // If we couldn't create for some bizarre reason and the
543  // user probably doesn't exist, skip the grant
544  $this->db->rollback( __METHOD__ );
545  $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getMessage() );
546  }
547  }
548  } else {
549  $status->warning( 'config-install-user-alreadyexists', $dbUser );
550  $grantableNames[] = $fullName;
551  break;
552  }
553  }
554  }
555 
556  // Try to grant to all the users we know exist or we were able to create
557  $dbAllTables = $this->db->addIdentifierQuotes( $dbName ) . '.*';
558  foreach ( $grantableNames as $name ) {
559  try {
560  $this->db->begin( __METHOD__ );
561  $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
562  $this->db->commit( __METHOD__ );
563  } catch ( DBQueryError $dqe ) {
564  $this->db->rollback( __METHOD__ );
565  $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getMessage() );
566  }
567  }
568 
569  return $status;
570  }
571 
578  private function buildFullUserName( $name, $host ) {
579  return $this->db->addQuotes( $name ) . '@' . $this->db->addQuotes( $host );
580  }
581 
589  private function userDefinitelyExists( $host, $user ) {
590  try {
591  $res = $this->db->selectRow( 'mysql.user', [ 'Host', 'User' ],
592  [ 'Host' => $host, 'User' => $user ], __METHOD__ );
593 
594  return (bool)$res;
595  } catch ( DBQueryError $dqe ) {
596  return false;
597  }
598  }
599 
606  protected function getTableOptions() {
607  $options = [];
608  if ( $this->getVar( '_MysqlEngine' ) !== null ) {
609  $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
610  }
611  if ( $this->getVar( '_MysqlCharset' ) !== null ) {
612  $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
613  }
614 
615  return implode( ', ', $options );
616  }
617 
623  public function getSchemaVars() {
624  return [
625  'wgDBTableOptions' => $this->getTableOptions(),
626  'wgDBname' => $this->getVar( 'wgDBname' ),
627  'wgDBuser' => $this->getVar( 'wgDBuser' ),
628  'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
629  ];
630  }
631 
632  public function getLocalSettings() {
633  $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
635 
636  return "# MySQL specific settings
637 \$wgDBprefix = \"{$prefix}\";
638 
639 # MySQL table options to use during installation or update
640 \$wgDBTableOptions = \"{$tblOpts}\";";
641  }
642 }
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.
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.
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:236
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:256
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:320
static escapePhpString( $string)
Returns the escaped version of a string of php code.
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='`')
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.
static $minimumVersion
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.
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:73
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:85
$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.
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s