Remove support for PHP extension 'mysql' (not mysqli!)
[lhc/web/wiklou.git] / includes / installer / MysqlInstaller.php
1 <?php
2 /**
3 * MySQL-specific installer.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Deployment
22 */
23
24 use Wikimedia\Rdbms\Database;
25 use Wikimedia\Rdbms\DBQueryError;
26 use Wikimedia\Rdbms\DBConnectionError;
27
28 /**
29 * Class for setting up the MediaWiki database using MySQL.
30 *
31 * @ingroup Deployment
32 * @since 1.17
33 */
34 class MysqlInstaller extends DatabaseInstaller {
35
36 protected $globalNames = [
37 'wgDBserver',
38 'wgDBname',
39 'wgDBuser',
40 'wgDBpassword',
41 'wgDBprefix',
42 'wgDBTableOptions',
43 'wgDBmysql5',
44 ];
45
46 protected $internalDefaults = [
47 '_MysqlEngine' => 'InnoDB',
48 '_MysqlCharset' => 'binary',
49 '_InstallUser' => 'root',
50 ];
51
52 public $supportedEngines = [ 'InnoDB', 'MyISAM' ];
53
54 public static $minimumVersion = '5.5.8';
55 protected static $notMiniumumVerisonMessage = 'config-mysql-old';
56
57 public $webUserPrivs = [
58 'DELETE',
59 'INSERT',
60 'SELECT',
61 'UPDATE',
62 'CREATE TEMPORARY TABLES',
63 ];
64
65 /**
66 * @return string
67 */
68 public function getName() {
69 return 'mysql';
70 }
71
72 /**
73 * @return bool
74 */
75 public function isCompiled() {
76 return self::checkExtension( 'mysqli' );
77 }
78
79 /**
80 * @return string
81 */
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 }
131 /**
132 * @var $conn Database
133 */
134 $conn = $status->value;
135
136 // Check version
137 return static::meetsMinimumRequirement( $conn->getServerVersion() );
138 }
139
140 /**
141 * @return Status
142 */
143 public function openConnection() {
144 $status = Status::newGood();
145 try {
146 $db = Database::factory( 'mysql', [
147 'host' => $this->getVar( 'wgDBserver' ),
148 'user' => $this->getVar( '_InstallUser' ),
149 'password' => $this->getVar( '_InstallPassword' ),
150 'dbname' => false,
151 'flags' => 0,
152 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ] );
153 $status->value = $db;
154 } catch ( DBConnectionError $e ) {
155 $status->fatal( 'config-connection-error', $e->getMessage() );
156 }
157
158 return $status;
159 }
160
161 public function preUpgrade() {
162 global $wgDBuser, $wgDBpassword;
163
164 $status = $this->getConnection();
165 if ( !$status->isOK() ) {
166 $this->parent->showStatusError( $status );
167
168 return;
169 }
170 /**
171 * @var $conn Database
172 */
173 $conn = $status->value;
174 $conn->selectDB( $this->getVar( 'wgDBname' ) );
175
176 # Determine existing default character set
177 if ( $conn->tableExists( "revision", __METHOD__ ) ) {
178 $revision = $this->escapeLikeInternal( $this->getVar( 'wgDBprefix' ) . 'revision', '\\' );
179 $res = $conn->query( "SHOW TABLE STATUS LIKE '$revision'", __METHOD__ );
180 $row = $conn->fetchObject( $res );
181 if ( !$row ) {
182 $this->parent->showMessage( 'config-show-table-status' );
183 $existingSchema = false;
184 $existingEngine = false;
185 } else {
186 if ( preg_match( '/^latin1/', $row->Collation ) ) {
187 $existingSchema = 'latin1';
188 } elseif ( preg_match( '/^utf8/', $row->Collation ) ) {
189 $existingSchema = 'utf8';
190 } elseif ( preg_match( '/^binary/', $row->Collation ) ) {
191 $existingSchema = 'binary';
192 } else {
193 $existingSchema = false;
194 $this->parent->showMessage( 'config-unknown-collation' );
195 }
196 if ( isset( $row->Engine ) ) {
197 $existingEngine = $row->Engine;
198 } else {
199 $existingEngine = $row->Type;
200 }
201 }
202 } else {
203 $existingSchema = false;
204 $existingEngine = false;
205 }
206
207 if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
208 $this->setVar( '_MysqlCharset', $existingSchema );
209 }
210 if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
211 $this->setVar( '_MysqlEngine', $existingEngine );
212 }
213
214 # Normal user and password are selected after this step, so for now
215 # just copy these two
216 $wgDBuser = $this->getVar( '_InstallUser' );
217 $wgDBpassword = $this->getVar( '_InstallPassword' );
218 }
219
220 /**
221 * @param string $s
222 * @param string $escapeChar
223 * @return string
224 */
225 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
226 return str_replace( [ $escapeChar, '%', '_' ],
227 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
228 $s );
229 }
230
231 /**
232 * Get a list of storage engines that are available and supported
233 *
234 * @return array
235 */
236 public function getEngines() {
237 $status = $this->getConnection();
238
239 /**
240 * @var $conn Database
241 */
242 $conn = $status->value;
243
244 $engines = [];
245 $res = $conn->query( 'SHOW ENGINES', __METHOD__ );
246 foreach ( $res as $row ) {
247 if ( $row->Support == 'YES' || $row->Support == 'DEFAULT' ) {
248 $engines[] = $row->Engine;
249 }
250 }
251 $engines = array_intersect( $this->supportedEngines, $engines );
252
253 return $engines;
254 }
255
256 /**
257 * Get a list of character sets that are available and supported
258 *
259 * @return array
260 */
261 public function getCharsets() {
262 return [ 'binary', 'utf8' ];
263 }
264
265 /**
266 * Return true if the install user can create accounts
267 *
268 * @return bool
269 */
270 public function canCreateAccounts() {
271 $status = $this->getConnection();
272 if ( !$status->isOK() ) {
273 return false;
274 }
275 /** @var Database $conn */
276 $conn = $status->value;
277
278 // Get current account name
279 $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__ );
280 $parts = explode( '@', $currentName );
281 if ( count( $parts ) != 2 ) {
282 return false;
283 }
284 $quotedUser = $conn->addQuotes( $parts[0] ) .
285 '@' . $conn->addQuotes( $parts[1] );
286
287 // The user needs to have INSERT on mysql.* to be able to CREATE USER
288 // The grantee will be double-quoted in this query, as required
289 $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
290 [ 'GRANTEE' => $quotedUser ], __METHOD__ );
291 $insertMysql = false;
292 $grantOptions = array_flip( $this->webUserPrivs );
293 foreach ( $res as $row ) {
294 if ( $row->PRIVILEGE_TYPE == 'INSERT' ) {
295 $insertMysql = true;
296 }
297 if ( $row->IS_GRANTABLE ) {
298 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
299 }
300 }
301
302 // Check for DB-specific privs for mysql.*
303 if ( !$insertMysql ) {
304 $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
305 [
306 'GRANTEE' => $quotedUser,
307 'TABLE_SCHEMA' => 'mysql',
308 'PRIVILEGE_TYPE' => 'INSERT',
309 ], __METHOD__ );
310 if ( $row ) {
311 $insertMysql = true;
312 }
313 }
314
315 if ( !$insertMysql ) {
316 return false;
317 }
318
319 // Check for DB-level grant options
320 $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
321 [
322 'GRANTEE' => $quotedUser,
323 'IS_GRANTABLE' => 1,
324 ], __METHOD__ );
325 foreach ( $res as $row ) {
326 $regex = $this->likeToRegex( $row->TABLE_SCHEMA );
327 if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
328 unset( $grantOptions[$row->PRIVILEGE_TYPE] );
329 }
330 }
331 if ( count( $grantOptions ) ) {
332 // Can't grant everything
333 return false;
334 }
335
336 return true;
337 }
338
339 /**
340 * Convert a wildcard (as used in LIKE) to a regex
341 * Slashes are escaped, slash terminators included
342 * @param string $wildcard
343 * @return string
344 */
345 protected function likeToRegex( $wildcard ) {
346 $r = preg_quote( $wildcard, '/' );
347 $r = strtr( $r, [
348 '%' => '.*',
349 '_' => '.'
350 ] );
351 return "/$r/s";
352 }
353
354 /**
355 * @return string
356 */
357 public function getSettingsForm() {
358 if ( $this->canCreateAccounts() ) {
359 $noCreateMsg = false;
360 } else {
361 $noCreateMsg = 'config-db-web-no-create-privs';
362 }
363 $s = $this->getWebUserBox( $noCreateMsg );
364
365 // Do engine selector
366 $engines = $this->getEngines();
367 // If the current default engine is not supported, use an engine that is
368 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
369 $this->setVar( '_MysqlEngine', reset( $engines ) );
370 }
371
372 $s .= Xml::openElement( 'div', [
373 'id' => 'dbMyisamWarning'
374 ] );
375 $myisamWarning = 'config-mysql-myisam-dep';
376 if ( count( $engines ) === 1 ) {
377 $myisamWarning = 'config-mysql-only-myisam-dep';
378 }
379 $s .= $this->parent->getWarningBox( wfMessage( $myisamWarning )->text() );
380 $s .= Xml::closeElement( 'div' );
381
382 if ( $this->getVar( '_MysqlEngine' ) != 'MyISAM' ) {
383 $s .= Xml::openElement( 'script' );
384 $s .= '$(\'#dbMyisamWarning\').hide();';
385 $s .= Xml::closeElement( 'script' );
386 }
387
388 if ( count( $engines ) >= 2 ) {
389 // getRadioSet() builds a set of labeled radio buttons.
390 // For grep: The following messages are used as the item labels:
391 // config-mysql-innodb, config-mysql-myisam
392 $s .= $this->getRadioSet( [
393 'var' => '_MysqlEngine',
394 'label' => 'config-mysql-engine',
395 'itemLabelPrefix' => 'config-mysql-',
396 'values' => $engines,
397 'itemAttribs' => [
398 'MyISAM' => [
399 'class' => 'showHideRadio',
400 'rel' => 'dbMyisamWarning'
401 ],
402 'InnoDB' => [
403 'class' => 'hideShowRadio',
404 'rel' => 'dbMyisamWarning'
405 ]
406 ]
407 ] );
408 $s .= $this->parent->getHelpBox( 'config-mysql-engine-help' );
409 }
410
411 // If the current default charset is not supported, use a charset that is
412 $charsets = $this->getCharsets();
413 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
414 $this->setVar( '_MysqlCharset', reset( $charsets ) );
415 }
416
417 // Do charset selector
418 if ( count( $charsets ) >= 2 ) {
419 // getRadioSet() builds a set of labeled radio buttons.
420 // For grep: The following messages are used as the item labels:
421 // config-mysql-binary, config-mysql-utf8
422 $s .= $this->getRadioSet( [
423 'var' => '_MysqlCharset',
424 'label' => 'config-mysql-charset',
425 'itemLabelPrefix' => 'config-mysql-',
426 'values' => $charsets
427 ] );
428 $s .= $this->parent->getHelpBox( 'config-mysql-charset-help' );
429 }
430
431 return $s;
432 }
433
434 /**
435 * @return Status
436 */
437 public function submitSettingsForm() {
438 $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
439 $status = $this->submitWebUserBox();
440 if ( !$status->isOK() ) {
441 return $status;
442 }
443
444 // Validate the create checkbox
445 $canCreate = $this->canCreateAccounts();
446 if ( !$canCreate ) {
447 $this->setVar( '_CreateDBAccount', false );
448 $create = false;
449 } else {
450 $create = $this->getVar( '_CreateDBAccount' );
451 }
452
453 if ( !$create ) {
454 // Test the web account
455 try {
456 Database::factory( 'mysql', [
457 'host' => $this->getVar( 'wgDBserver' ),
458 'user' => $this->getVar( 'wgDBuser' ),
459 'password' => $this->getVar( 'wgDBpassword' ),
460 'dbname' => false,
461 'flags' => 0,
462 'tablePrefix' => $this->getVar( 'wgDBprefix' )
463 ] );
464 } catch ( DBConnectionError $e ) {
465 return Status::newFatal( 'config-connection-error', $e->getMessage() );
466 }
467 }
468
469 // Validate engines and charsets
470 // This is done pre-submit already so it's just for security
471 $engines = $this->getEngines();
472 if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
473 $this->setVar( '_MysqlEngine', reset( $engines ) );
474 }
475 $charsets = $this->getCharsets();
476 if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
477 $this->setVar( '_MysqlCharset', reset( $charsets ) );
478 }
479
480 return Status::newGood();
481 }
482
483 public function preInstall() {
484 # Add our user callback to installSteps, right before the tables are created.
485 $callback = [
486 'name' => 'user',
487 'callback' => [ $this, 'setupUser' ],
488 ];
489 $this->parent->addInstallStep( $callback, 'tables' );
490 }
491
492 /**
493 * @return Status
494 */
495 public function setupDatabase() {
496 $status = $this->getConnection();
497 if ( !$status->isOK() ) {
498 return $status;
499 }
500 /** @var Database $conn */
501 $conn = $status->value;
502 $dbName = $this->getVar( 'wgDBname' );
503 if ( !$conn->selectDB( $dbName ) ) {
504 $conn->query(
505 "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
506 __METHOD__
507 );
508 $conn->selectDB( $dbName );
509 }
510 $this->setupSchemaVars();
511
512 return $status;
513 }
514
515 /**
516 * @return Status
517 */
518 public function setupUser() {
519 $dbUser = $this->getVar( 'wgDBuser' );
520 if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
521 return Status::newGood();
522 }
523 $status = $this->getConnection();
524 if ( !$status->isOK() ) {
525 return $status;
526 }
527
528 $this->setupSchemaVars();
529 $dbName = $this->getVar( 'wgDBname' );
530 $this->db->selectDB( $dbName );
531 $server = $this->getVar( 'wgDBserver' );
532 $password = $this->getVar( 'wgDBpassword' );
533 $grantableNames = [];
534
535 if ( $this->getVar( '_CreateDBAccount' ) ) {
536 // Before we blindly try to create a user that already has access,
537 try { // first attempt to connect to the database
538 Database::factory( 'mysql', [
539 'host' => $server,
540 'user' => $dbUser,
541 'password' => $password,
542 'dbname' => false,
543 'flags' => 0,
544 'tablePrefix' => $this->getVar( 'wgDBprefix' )
545 ] );
546 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
547 $tryToCreate = false;
548 } catch ( DBConnectionError $e ) {
549 $tryToCreate = true;
550 }
551 } else {
552 $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
553 $tryToCreate = false;
554 }
555
556 if ( $tryToCreate ) {
557 $createHostList = [
558 $server,
559 'localhost',
560 'localhost.localdomain',
561 '%'
562 ];
563
564 $createHostList = array_unique( $createHostList );
565 $escPass = $this->db->addQuotes( $password );
566
567 foreach ( $createHostList as $host ) {
568 $fullName = $this->buildFullUserName( $dbUser, $host );
569 if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
570 try {
571 $this->db->begin( __METHOD__ );
572 $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
573 $this->db->commit( __METHOD__ );
574 $grantableNames[] = $fullName;
575 } catch ( DBQueryError $dqe ) {
576 if ( $this->db->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
577 // User (probably) already exists
578 $this->db->rollback( __METHOD__ );
579 $status->warning( 'config-install-user-alreadyexists', $dbUser );
580 $grantableNames[] = $fullName;
581 break;
582 } else {
583 // If we couldn't create for some bizzare reason and the
584 // user probably doesn't exist, skip the grant
585 $this->db->rollback( __METHOD__ );
586 $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getMessage() );
587 }
588 }
589 } else {
590 $status->warning( 'config-install-user-alreadyexists', $dbUser );
591 $grantableNames[] = $fullName;
592 break;
593 }
594 }
595 }
596
597 // Try to grant to all the users we know exist or we were able to create
598 $dbAllTables = $this->db->addIdentifierQuotes( $dbName ) . '.*';
599 foreach ( $grantableNames as $name ) {
600 try {
601 $this->db->begin( __METHOD__ );
602 $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
603 $this->db->commit( __METHOD__ );
604 } catch ( DBQueryError $dqe ) {
605 $this->db->rollback( __METHOD__ );
606 $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getMessage() );
607 }
608 }
609
610 return $status;
611 }
612
613 /**
614 * Return a formal 'User'@'Host' username for use in queries
615 * @param string $name Username, quotes will be added
616 * @param string $host Hostname, quotes will be added
617 * @return string
618 */
619 private function buildFullUserName( $name, $host ) {
620 return $this->db->addQuotes( $name ) . '@' . $this->db->addQuotes( $host );
621 }
622
623 /**
624 * Try to see if the user account exists. Our "superuser" may not have
625 * access to mysql.user, so false means "no" or "maybe"
626 * @param string $host Hostname to check
627 * @param string $user Username to check
628 * @return bool
629 */
630 private function userDefinitelyExists( $host, $user ) {
631 try {
632 $res = $this->db->selectRow( 'mysql.user', [ 'Host', 'User' ],
633 [ 'Host' => $host, 'User' => $user ], __METHOD__ );
634
635 return (bool)$res;
636 } catch ( DBQueryError $dqe ) {
637 return false;
638 }
639 }
640
641 /**
642 * Return any table options to be applied to all tables that don't
643 * override them.
644 *
645 * @return string
646 */
647 protected function getTableOptions() {
648 $options = [];
649 if ( $this->getVar( '_MysqlEngine' ) !== null ) {
650 $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
651 }
652 if ( $this->getVar( '_MysqlCharset' ) !== null ) {
653 $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
654 }
655
656 return implode( ', ', $options );
657 }
658
659 /**
660 * Get variables to substitute into tables.sql and the SQL patch files.
661 *
662 * @return array
663 */
664 public function getSchemaVars() {
665 return [
666 'wgDBTableOptions' => $this->getTableOptions(),
667 'wgDBname' => $this->getVar( 'wgDBname' ),
668 'wgDBuser' => $this->getVar( 'wgDBuser' ),
669 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
670 ];
671 }
672
673 public function getLocalSettings() {
674 $dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
675 $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
676 $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
677
678 return "# MySQL specific settings
679 \$wgDBprefix = \"{$prefix}\";
680
681 # MySQL table options to use during installation or update
682 \$wgDBTableOptions = \"{$tblOpts}\";
683
684 # Experimental charset support for MySQL 5.0.
685 \$wgDBmysql5 = {$dbmysql5};";
686 }
687 }