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