Debian Codegraph @

includes/installer/MysqlInstaller.php

raw symbols SCIP
1 <?php
2
3 /**
4 * MySQL-specific installer.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Installer
23 */
24
25 namespace MediaWiki\Installer;
26
27 use MediaWiki\Status\Status;
28 use Wikimedia\Rdbms\Database;
29 use Wikimedia\Rdbms\DatabaseFactory;
30 use Wikimedia\Rdbms\DatabaseMySQL;
31 use Wikimedia\Rdbms\DBConnectionError;
32 use Wikimedia\Rdbms\DBQueryError;
33 use Wikimedia\Rdbms\IDatabase;
34
35 /**
36 * Class for setting up the MediaWiki database using MySQL.
37 *
38 * @ingroup Installer
39 * @since 1.17
40 */
41 class MysqlInstaller extends DatabaseInstaller {
42
43 /** @inheritDoc */
44 protected $globalNames = [
45 'wgDBserver',
46 'wgDBname',
47 'wgDBuser',
48 'wgDBpassword',
49 'wgDBssl',
50 'wgDBprefix',
51 'wgDBTableOptions',
52 ];
53
54 /** @inheritDoc */
55 protected $internalDefaults = [
56 '_MysqlEngine' => 'InnoDB',
57 '_MysqlCharset' => 'binary',
58 '_InstallUser' => 'root',
59 ];
60
61 /** @var string[] */
62 public $supportedEngines = [ 'InnoDB' ];
63
64 private const MIN_VERSIONS = [
65 'MySQL' => '5.7.0',
66 'MariaDB' => '10.3',
67 ];
68 /** @inheritDoc */
69 public static $minimumVersion;
70 /** @inheritDoc */
71 protected static $notMinimumVersionMessage;
72
73 /** @var string[] */
74 public $webUserPrivs = [
75 'DELETE',
76 'INSERT',
77 'SELECT',
78 'UPDATE',
79 'CREATE TEMPORARY TABLES',
80 ];
81
82 /**
83 * @return string
84 */
85 public function getName() {
86 return 'mysql';
87 }
88
89 /**
90 * @return bool
91 */
92 public function isCompiled() {
93 return self::checkExtension( 'mysqli' );
94 }
95
96 public function getConnectForm( WebInstaller $webInstaller ): DatabaseConnectForm {
97 return new MysqlConnectForm( $webInstaller, $this );
98 }
99
100 public function getSettingsForm( WebInstaller $webInstaller ): DatabaseSettingsForm {
101 return new MysqlSettingsForm( $webInstaller, $this );
102 }
103
104 public static function meetsMinimumRequirement( IDatabase $conn ) {
105 $type = str_contains( $conn->getSoftwareLink(), 'MariaDB' ) ? 'MariaDB' : 'MySQL';
106 self::$minimumVersion = self::MIN_VERSIONS[$type];
107 // Used messages: config-mysql-old, config-mariadb-old
108 self::$notMinimumVersionMessage = 'config-' . strtolower( $type ) . '-old';
109 return parent::meetsMinimumRequirement( $conn );
110 }
111
112 /**
113 * @param string $type
114 * @return ConnectionStatus
115 */
116 protected function openConnection( string $type ) {
117 $status = new ConnectionStatus;
118 $dbName = $type === DatabaseInstaller::CONN_CREATE_DATABASE
119 ? null : $this->getVar( 'wgDBname' );
120 try {
121 /** @var DatabaseMySQL $db */
122 $db = ( new DatabaseFactory() )->create( 'mysql', [
123 'host' => $this->getVar( 'wgDBserver' ),
124 'user' => $this->getVar( '_InstallUser' ),
125 'password' => $this->getVar( '_InstallPassword' ),
126 'ssl' => $this->getVar( 'wgDBssl' ),
127 'dbname' => $dbName,
128 'flags' => 0,
129 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ] );
130 $status->setDB( $db );
131 } catch ( DBConnectionError $e ) {
132 $status->fatal( 'config-connection-error', $e->getMessage() );
133 }
134
135 return $status;
136 }
137
138 public function preUpgrade() {
139 global $wgDBuser, $wgDBpassword;
140
141 $status = $this->getConnection( self::CONN_CREATE_TABLES );
142 if ( !$status->isOK() ) {
143 $this->parent->showStatusMessage( $status );
144
145 return;
146 }
147 $conn = $status->getDB();
148 # Determine existing default character set
149 if ( $conn->tableExists( "revision", __METHOD__ ) ) {
150 $revision = $this->escapeLikeInternal( $this->getVar( 'wgDBprefix' ) . 'revision', '\\' );
151 $res = $conn->query( "SHOW TABLE STATUS LIKE '$revision'", __METHOD__ );
152 $row = $res->fetchObject();
153 if ( !$row ) {
154 $this->parent->showMessage( 'config-show-table-status' );
155 $existingSchema = false;
156 $existingEngine = false;
157 } else {
158 if ( preg_match( '/^latin1/', $row->Collation ) ) {
159 $existingSchema = 'latin1';
160 } elseif ( preg_match( '/^utf8/', $row->Collation ) ) {
161 $existingSchema = 'utf8';
162 } elseif ( preg_match( '/^binary/', $row->Collation ) ) {
163 $existingSchema = 'binary';
164 } else {
165 $existingSchema = false;
166 $this->parent->showMessage( 'config-unknown-collation' );
167 }
168 $existingEngine = $row->Engine ?? $row->Type;
169 }
170 } else {
171 $existingSchema = false;
172 $existingEngine = false;
173 }
174
175 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
176 $this->setVar( '_MysqlCharset', $existingSchema );
177 }
178 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
179 $this->setVar( '_MysqlEngine', $existingEngine );
180 }
181
182 # Normal user and password are selected after this step, so for now
183 # just copy these two
184 $wgDBuser = $this->getVar( '_InstallUser' );
185 $wgDBpassword = $this->getVar( '_InstallPassword' );
186 }
187
188 /**
189 * @param string $s
190 * @param string $escapeChar
191 * @return string
192 */
193 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
194 return str_replace( [ $escapeChar, '%', '_' ],
195 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
196 $s );
197 }
198
199 /**
200 * Get a list of storage engines that are available and supported
201 *
202 * @return array
203 */
204 public function getEngines() {
205 $status = $this->getConnection( self::CONN_CREATE_DATABASE );
206 $conn = $status->getDB();
207
208 $engines = [];
209 $res = $conn->query( 'SHOW ENGINES', __METHOD__ );
210 foreach ( $res as $row ) {
211 if ( $row->Support == 'YES' || $row->Support == 'DEFAULT' ) {
212 $engines[] = $row->Engine;
213 }
214 }
215 $engines = array_intersect( $this->supportedEngines, $engines );
216
217 return $engines;
218 }
219
220 /**
221 * Get a list of character sets that are available and supported
222 *
223 * @return array
224 */
225 public function getCharsets() {
226 return [ 'binary', 'utf8' ];
227 }
228
229 /**
230 * Return true if the install user can create accounts
231 *
232 * @return bool
233 */
234 public function canCreateAccounts() {
235 $status = $this->getConnection( self::CONN_CREATE_DATABASE );
236 if ( !$status->isOK() ) {
237 return false;
238 }
239 $conn = $status->getDB();
240
241 // Get current account name
242 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__ );
243 $parts = explode( '@', $currentName );
244 if ( count( $parts ) != 2 ) {
245 return false;
246 }
247 $quotedUser = $conn->addQuotes( $parts[0] ) .
248 '@' . $conn->addQuotes( $parts[1] );
249
250 // The user needs to have INSERT on mysql.* or (global) CREATE USER to be able to CREATE USER
251 // The grantee will be double-quoted in this query, as required
252 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
253 [ 'GRANTEE' => $quotedUser ], __METHOD__ );
254 $insertMysql = false;
255 // The user needs to have permission to GRANT all necessary permissions to the newly created user.
256 // This starts as a list of all necessary permissions and they are removed as they are found.
257 // If any are left in the list after checking for permissions, those are the missing permissions.
258 $missingGrantOptions = array_fill_keys( $this->webUserPrivs, true );
259 foreach ( $res as $row ) {
260 if ( $row->PRIVILEGE_TYPE == 'INSERT' ) {
261 $insertMysql = true;
262 } elseif ( $row->PRIVILEGE_TYPE == 'CREATE USER' ) {
263 $insertMysql = true;
264 }
265 if ( $row->IS_GRANTABLE === 'YES' ) {
266 unset( $missingGrantOptions[$row->PRIVILEGE_TYPE] );
267 }
268 }
269
270 // Check for DB-specific privs for mysql.*
271 if ( !$insertMysql ) {
272 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
273 [
274 'GRANTEE' => $quotedUser,
275 'TABLE_SCHEMA' => 'mysql',
276 'PRIVILEGE_TYPE' => 'INSERT',
277 ], __METHOD__ );
278 if ( $row ) {
279 $insertMysql = true;
280 }
281 }
282
283 if ( !$insertMysql ) {
284 return false;
285 }
286
287 // Check for DB-level grant options
288 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
289 [
290 'GRANTEE' => $quotedUser,
291 'IS_GRANTABLE' => 'YES',
292 ], __METHOD__ );
293 foreach ( $res as $row ) {
294 $regex = $this->likeToRegex( $row->TABLE_SCHEMA );
295 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
296 unset( $missingGrantOptions[$row->PRIVILEGE_TYPE] );
297 }
298 }
299 if ( count( $missingGrantOptions ) ) {
300 // Can't grant everything
301 return false;
302 }
303
304 return true;
305 }
306
307 /**
308 * Convert a wildcard (as used in LIKE) to a regex
309 * Slashes are escaped, slash terminators included
310 * @param string $wildcard
311 * @return string
312 */
313 protected function likeToRegex( $wildcard ) {
314 $r = preg_quote( $wildcard, '/' );
315 $r = strtr( $r, [
316 '%' => '.*',
317 '_' => '.'
318 ] );
319 return "/$r/s";
320 }
321
322 public function preInstall() {
323 # Add our user callback to installSteps, right before the tables are created.
324 $callback = [
325 'name' => 'user',
326 'callback' => [ $this, 'setupUser' ],
327 ];
328 $this->parent->addInstallStep( $callback, 'tables' );
329 }
330
331 /**
332 * @return Status
333 */
334 public function setupDatabase() {
335 $status = $this->getConnection( self::CONN_CREATE_DATABASE );
336 if ( !$status->isOK() ) {
337 return $status;
338 }
339 $conn = $status->getDB();
340 $dbName = $this->getVar( 'wgDBname' );
341 if ( !$this->databaseExists( $dbName ) ) {
342 $conn->query(
343 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
344 __METHOD__
345 );
346 }
347 $this->selectDatabase( $conn, $dbName );
348
349 return $status;
350 }
351
352 /**
353 * Try to see if a given database exists
354 * @param string $dbName Database name to check
355 * @return bool
356 */
357 private function databaseExists( $dbName ) {
358 return (bool)$this->definitelyGetConnection( self::CONN_CREATE_DATABASE )
359 ->newSelectQueryBuilder()
360 ->select( '1' )
361 ->from( 'information_schema.schemata' )
362 ->where( [ 'schema_name' => $dbName ] )
363 ->fetchRow();
364 }
365
366 /**
367 * @return Status
368 */
369 public function setupUser() {
370 $dbUser = $this->getVar( 'wgDBuser' );
371 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
372 return Status::newGood();
373 }
374 $status = $this->getConnection( self::CONN_CREATE_DATABASE );
375 if ( !$status->isOK() ) {
376 return $status;
377 }
378
379 $conn = $status->getDB();
380 $server = $this->getVar( 'wgDBserver' );
381 $password = $this->getVar( 'wgDBpassword' );
382 $grantableNames = [];
383
384 if ( $this->getVar( '_CreateDBAccount' ) ) {
385 // Before we blindly try to create a user that already has access,
386 try { // first attempt to connect to the database
387 ( new DatabaseFactory() )->create( 'mysql', [
388 'host' => $server,
389 'user' => $dbUser,
390 'password' => $password,
391 'ssl' => $this->getVar( 'wgDBssl' ),
392 'dbname' => null,
393 'flags' => 0,
394 'tablePrefix' => $this->getVar( 'wgDBprefix' )
395 ] );
396 $grantableNames[] = $this->buildFullUserName( $conn, $dbUser, $server );
397 $tryToCreate = false;
398 } catch ( DBConnectionError $e ) {
399 $tryToCreate = true;
400 }
401 } else {
402 $grantableNames[] = $this->buildFullUserName( $conn, $dbUser, $server );
403 $tryToCreate = false;
404 }
405
406 if ( $tryToCreate ) {
407 $createHostList = [
408 $server,
409 'localhost',
410 'localhost.localdomain',
411 '%'
412 ];
413
414 $createHostList = array_unique( $createHostList );
415 $escPass = $conn->addQuotes( $password );
416
417 foreach ( $createHostList as $host ) {
418 $fullName = $this->buildFullUserName( $conn, $dbUser, $host );
419 if ( !$this->userDefinitelyExists( $conn, $host, $dbUser ) ) {
420 try {
421 $conn->begin( __METHOD__ );
422 $conn->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
423 $conn->commit( __METHOD__ );
424 $grantableNames[] = $fullName;
425 } catch ( DBQueryError $dqe ) {
426 if ( $conn->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
427 // User (probably) already exists
428 $conn->rollback( __METHOD__ );
429 $status->warning( 'config-install-user-alreadyexists', $dbUser );
430 $grantableNames[] = $fullName;
431 break;
432 } else {
433 // If we couldn't create for some bizarre reason and the
434 // user probably doesn't exist, skip the grant
435 $conn->rollback( __METHOD__ );
436 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getMessage() );
437 }
438 }
439 } else {
440 $status->warning( 'config-install-user-alreadyexists', $dbUser );
441 $grantableNames[] = $fullName;
442 break;
443 }
444 }
445 }
446
447 // Try to grant to all the users we know exist or we were able to create
448 $dbAllTables = $conn->addIdentifierQuotes( $this->getVar( 'wgDBname' ) ) . '.*';
449 foreach ( $grantableNames as $name ) {
450 try {
451 $conn->begin( __METHOD__ );
452 $conn->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
453 $conn->commit( __METHOD__ );
454 } catch ( DBQueryError $dqe ) {
455 $conn->rollback( __METHOD__ );
456 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getMessage() );
457 }
458 }
459
460 return $status;
461 }
462
463 /**
464 * Return a formal 'User'@'Host' username for use in queries
465 * @param Database $conn
466 * @param string $name Username, quotes will be added
467 * @param string $host Hostname, quotes will be added
468 * @return string
469 */
470 private function buildFullUserName( $conn, $name, $host ) {
471 return $conn->addQuotes( $name ) . '@' . $conn->addQuotes( $host );
472 }
473
474 /**
475 * Try to see if the user account exists. Our "superuser" may not have
476 * access to mysql.user, so false means "no" or "maybe"
477 * @param Database $conn
478 * @param string $host Hostname to check
479 * @param string $user Username to check
480 * @return bool
481 */
482 private function userDefinitelyExists( $conn, $host, $user ) {
483 try {
484 $res = $conn->newSelectQueryBuilder()
485 ->select( [ 'Host', 'User' ] )
486 ->from( 'mysql.user' )
487 ->where( [ 'Host' => $host, 'User' => $user ] )
488 ->caller( __METHOD__ )->fetchRow();
489
490 return (bool)$res;
491 } catch ( DBQueryError $dqe ) {
492 return false;
493 }
494 }
495
496 /**
497 * Return any table options to be applied to all tables that don't
498 * override them.
499 *
500 * @return string
501 */
502 protected function getTableOptions() {
503 $options = [];
504 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
505 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
506 }
507 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
508 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
509 }
510
511 return implode( ', ', $options );
512 }
513
514 /**
515 * Get variables to substitute into tables.sql and the SQL patch files.
516 *
517 * @return array
518 */
519 public function getSchemaVars() {
520 return [
521 'wgDBTableOptions' => $this->getTableOptions(),
522 'wgDBname' => $this->getVar( 'wgDBname' ),
523 'wgDBuser' => $this->getVar( 'wgDBuser' ),
524 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
525 ];
526 }
527
528 public function getLocalSettings() {
529 $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
530 $useSsl = $this->getVar( 'wgDBssl' ) ? 'true' : 'false';
531 $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
532
533 return "# MySQL specific settings
534 \$wgDBprefix = \"{$prefix}\";
535 \$wgDBssl = {$useSsl};
536
537 # MySQL table options to use during installation or update
538 \$wgDBTableOptions = \"{$tblOpts}\";";
539 }
540 }