MysqlInstaller.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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. use Wikimedia\Rdbms\Database;
  24. use Wikimedia\Rdbms\DBQueryError;
  25. use Wikimedia\Rdbms\DBConnectionError;
  26. /**
  27. * Class for setting up the MediaWiki database using MySQL.
  28. *
  29. * @ingroup Deployment
  30. * @since 1.17
  31. */
  32. class MysqlInstaller extends DatabaseInstaller {
  33. protected $globalNames = [
  34. 'wgDBserver',
  35. 'wgDBname',
  36. 'wgDBuser',
  37. 'wgDBpassword',
  38. 'wgDBprefix',
  39. 'wgDBTableOptions',
  40. ];
  41. protected $internalDefaults = [
  42. '_MysqlEngine' => 'InnoDB',
  43. '_MysqlCharset' => 'binary',
  44. '_InstallUser' => 'root',
  45. ];
  46. public $supportedEngines = [ 'InnoDB' ];
  47. public static $minimumVersion = '5.5.8';
  48. protected static $notMinimumVersionMessage = 'config-mysql-old';
  49. public $webUserPrivs = [
  50. 'DELETE',
  51. 'INSERT',
  52. 'SELECT',
  53. 'UPDATE',
  54. 'CREATE TEMPORARY TABLES',
  55. ];
  56. /**
  57. * @return string
  58. */
  59. public function getName() {
  60. return 'mysql';
  61. }
  62. /**
  63. * @return bool
  64. */
  65. public function isCompiled() {
  66. return self::checkExtension( 'mysqli' );
  67. }
  68. /**
  69. * @return string
  70. */
  71. public function getConnectForm() {
  72. return $this->getTextBox(
  73. 'wgDBserver',
  74. 'config-db-host',
  75. [],
  76. $this->parent->getHelpBox( 'config-db-host-help' )
  77. ) .
  78. Html::openElement( 'fieldset' ) .
  79. Html::element( 'legend', [], wfMessage( 'config-db-wiki-settings' )->text() ) .
  80. $this->getTextBox( 'wgDBname', 'config-db-name', [ 'dir' => 'ltr' ],
  81. $this->parent->getHelpBox( 'config-db-name-help' ) ) .
  82. $this->getTextBox( 'wgDBprefix', 'config-db-prefix', [ 'dir' => 'ltr' ],
  83. $this->parent->getHelpBox( 'config-db-prefix-help' ) ) .
  84. Html::closeElement( 'fieldset' ) .
  85. $this->getInstallUserBox();
  86. }
  87. public function submitConnectForm() {
  88. // Get variables from the request.
  89. $newValues = $this->setVarsFromRequest( [ 'wgDBserver', 'wgDBname', 'wgDBprefix' ] );
  90. // Validate them.
  91. $status = Status::newGood();
  92. if ( !strlen( $newValues['wgDBserver'] ) ) {
  93. $status->fatal( 'config-missing-db-host' );
  94. }
  95. if ( !strlen( $newValues['wgDBname'] ) ) {
  96. $status->fatal( 'config-missing-db-name' );
  97. } elseif ( !preg_match( '/^[a-z0-9+_-]+$/i', $newValues['wgDBname'] ) ) {
  98. $status->fatal( 'config-invalid-db-name', $newValues['wgDBname'] );
  99. }
  100. if ( !preg_match( '/^[a-z0-9_-]*$/i', $newValues['wgDBprefix'] ) ) {
  101. $status->fatal( 'config-invalid-db-prefix', $newValues['wgDBprefix'] );
  102. }
  103. if ( !$status->isOK() ) {
  104. return $status;
  105. }
  106. // Submit user box
  107. $status = $this->submitInstallUserBox();
  108. if ( !$status->isOK() ) {
  109. return $status;
  110. }
  111. // Try to connect
  112. $status = $this->getConnection();
  113. if ( !$status->isOK() ) {
  114. return $status;
  115. }
  116. /**
  117. * @var Database $conn
  118. */
  119. $conn = $status->value;
  120. '@phan-var Database $conn';
  121. // Check version
  122. return static::meetsMinimumRequirement( $conn->getServerVersion() );
  123. }
  124. /**
  125. * @return Status
  126. */
  127. public function openConnection() {
  128. $status = Status::newGood();
  129. try {
  130. /** @var DatabaseMysqlBase $db */
  131. $db = Database::factory( 'mysql', [
  132. 'host' => $this->getVar( 'wgDBserver' ),
  133. 'user' => $this->getVar( '_InstallUser' ),
  134. 'password' => $this->getVar( '_InstallPassword' ),
  135. 'dbname' => false,
  136. 'flags' => 0,
  137. 'tablePrefix' => $this->getVar( 'wgDBprefix' ) ] );
  138. $status->value = $db;
  139. } catch ( DBConnectionError $e ) {
  140. $status->fatal( 'config-connection-error', $e->getMessage() );
  141. }
  142. return $status;
  143. }
  144. public function preUpgrade() {
  145. global $wgDBuser, $wgDBpassword;
  146. $status = $this->getConnection();
  147. if ( !$status->isOK() ) {
  148. $this->parent->showStatusMessage( $status );
  149. return;
  150. }
  151. /**
  152. * @var Database $conn
  153. */
  154. $conn = $status->value;
  155. $conn->selectDB( $this->getVar( 'wgDBname' ) );
  156. # Determine existing default character set
  157. if ( $conn->tableExists( "revision", __METHOD__ ) ) {
  158. $revision = $this->escapeLikeInternal( $this->getVar( 'wgDBprefix' ) . 'revision', '\\' );
  159. $res = $conn->query( "SHOW TABLE STATUS LIKE '$revision'", __METHOD__ );
  160. $row = $conn->fetchObject( $res );
  161. if ( !$row ) {
  162. $this->parent->showMessage( 'config-show-table-status' );
  163. $existingSchema = false;
  164. $existingEngine = false;
  165. } else {
  166. if ( preg_match( '/^latin1/', $row->Collation ) ) {
  167. $existingSchema = 'latin1';
  168. } elseif ( preg_match( '/^utf8/', $row->Collation ) ) {
  169. $existingSchema = 'utf8';
  170. } elseif ( preg_match( '/^binary/', $row->Collation ) ) {
  171. $existingSchema = 'binary';
  172. } else {
  173. $existingSchema = false;
  174. $this->parent->showMessage( 'config-unknown-collation' );
  175. }
  176. $existingEngine = $row->Engine ?? $row->Type;
  177. }
  178. } else {
  179. $existingSchema = false;
  180. $existingEngine = false;
  181. }
  182. if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
  183. $this->setVar( '_MysqlCharset', $existingSchema );
  184. }
  185. if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
  186. $this->setVar( '_MysqlEngine', $existingEngine );
  187. }
  188. # Normal user and password are selected after this step, so for now
  189. # just copy these two
  190. $wgDBuser = $this->getVar( '_InstallUser' );
  191. $wgDBpassword = $this->getVar( '_InstallPassword' );
  192. }
  193. /**
  194. * @param string $s
  195. * @param string $escapeChar
  196. * @return string
  197. */
  198. protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
  199. return str_replace( [ $escapeChar, '%', '_' ],
  200. [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
  201. $s );
  202. }
  203. /**
  204. * Get a list of storage engines that are available and supported
  205. *
  206. * @return array
  207. */
  208. public function getEngines() {
  209. $status = $this->getConnection();
  210. /**
  211. * @var Database $conn
  212. */
  213. $conn = $status->value;
  214. $engines = [];
  215. $res = $conn->query( 'SHOW ENGINES', __METHOD__ );
  216. foreach ( $res as $row ) {
  217. if ( $row->Support == 'YES' || $row->Support == 'DEFAULT' ) {
  218. $engines[] = $row->Engine;
  219. }
  220. }
  221. $engines = array_intersect( $this->supportedEngines, $engines );
  222. return $engines;
  223. }
  224. /**
  225. * Get a list of character sets that are available and supported
  226. *
  227. * @return array
  228. */
  229. public function getCharsets() {
  230. return [ 'binary', 'utf8' ];
  231. }
  232. /**
  233. * Return true if the install user can create accounts
  234. *
  235. * @return bool
  236. */
  237. public function canCreateAccounts() {
  238. $status = $this->getConnection();
  239. if ( !$status->isOK() ) {
  240. return false;
  241. }
  242. /** @var Database $conn */
  243. $conn = $status->value;
  244. // Get current account name
  245. $currentName = $conn->selectField( '', 'CURRENT_USER()', '', __METHOD__ );
  246. $parts = explode( '@', $currentName );
  247. if ( count( $parts ) != 2 ) {
  248. return false;
  249. }
  250. $quotedUser = $conn->addQuotes( $parts[0] ) .
  251. '@' . $conn->addQuotes( $parts[1] );
  252. // The user needs to have INSERT on mysql.* to be able to CREATE USER
  253. // The grantee will be double-quoted in this query, as required
  254. $res = $conn->select( 'INFORMATION_SCHEMA.USER_PRIVILEGES', '*',
  255. [ 'GRANTEE' => $quotedUser ], __METHOD__ );
  256. $insertMysql = false;
  257. $grantOptions = array_flip( $this->webUserPrivs );
  258. foreach ( $res as $row ) {
  259. if ( $row->PRIVILEGE_TYPE == 'INSERT' ) {
  260. $insertMysql = true;
  261. }
  262. if ( $row->IS_GRANTABLE ) {
  263. unset( $grantOptions[$row->PRIVILEGE_TYPE] );
  264. }
  265. }
  266. // Check for DB-specific privs for mysql.*
  267. if ( !$insertMysql ) {
  268. $row = $conn->selectRow( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
  269. [
  270. 'GRANTEE' => $quotedUser,
  271. 'TABLE_SCHEMA' => 'mysql',
  272. 'PRIVILEGE_TYPE' => 'INSERT',
  273. ], __METHOD__ );
  274. if ( $row ) {
  275. $insertMysql = true;
  276. }
  277. }
  278. if ( !$insertMysql ) {
  279. return false;
  280. }
  281. // Check for DB-level grant options
  282. $res = $conn->select( 'INFORMATION_SCHEMA.SCHEMA_PRIVILEGES', '*',
  283. [
  284. 'GRANTEE' => $quotedUser,
  285. 'IS_GRANTABLE' => 1,
  286. ], __METHOD__ );
  287. foreach ( $res as $row ) {
  288. $regex = $this->likeToRegex( $row->TABLE_SCHEMA );
  289. if ( preg_match( $regex, $this->getVar( 'wgDBname' ) ) ) {
  290. unset( $grantOptions[$row->PRIVILEGE_TYPE] );
  291. }
  292. }
  293. if ( count( $grantOptions ) ) {
  294. // Can't grant everything
  295. return false;
  296. }
  297. return true;
  298. }
  299. /**
  300. * Convert a wildcard (as used in LIKE) to a regex
  301. * Slashes are escaped, slash terminators included
  302. * @param string $wildcard
  303. * @return string
  304. */
  305. protected function likeToRegex( $wildcard ) {
  306. $r = preg_quote( $wildcard, '/' );
  307. $r = strtr( $r, [
  308. '%' => '.*',
  309. '_' => '.'
  310. ] );
  311. return "/$r/s";
  312. }
  313. /**
  314. * @return string
  315. */
  316. public function getSettingsForm() {
  317. if ( $this->canCreateAccounts() ) {
  318. $noCreateMsg = false;
  319. } else {
  320. $noCreateMsg = 'config-db-web-no-create-privs';
  321. }
  322. $s = $this->getWebUserBox( $noCreateMsg );
  323. // Do engine selector
  324. $engines = $this->getEngines();
  325. // If the current default engine is not supported, use an engine that is
  326. if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
  327. $this->setVar( '_MysqlEngine', reset( $engines ) );
  328. }
  329. // If the current default charset is not supported, use a charset that is
  330. $charsets = $this->getCharsets();
  331. if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
  332. $this->setVar( '_MysqlCharset', reset( $charsets ) );
  333. }
  334. return $s;
  335. }
  336. /**
  337. * @return Status
  338. */
  339. public function submitSettingsForm() {
  340. $this->setVarsFromRequest( [ '_MysqlEngine', '_MysqlCharset' ] );
  341. $status = $this->submitWebUserBox();
  342. if ( !$status->isOK() ) {
  343. return $status;
  344. }
  345. // Validate the create checkbox
  346. $canCreate = $this->canCreateAccounts();
  347. if ( !$canCreate ) {
  348. $this->setVar( '_CreateDBAccount', false );
  349. $create = false;
  350. } else {
  351. $create = $this->getVar( '_CreateDBAccount' );
  352. }
  353. if ( !$create ) {
  354. // Test the web account
  355. try {
  356. Database::factory( 'mysql', [
  357. 'host' => $this->getVar( 'wgDBserver' ),
  358. 'user' => $this->getVar( 'wgDBuser' ),
  359. 'password' => $this->getVar( 'wgDBpassword' ),
  360. 'dbname' => false,
  361. 'flags' => 0,
  362. 'tablePrefix' => $this->getVar( 'wgDBprefix' )
  363. ] );
  364. } catch ( DBConnectionError $e ) {
  365. return Status::newFatal( 'config-connection-error', $e->getMessage() );
  366. }
  367. }
  368. // Validate engines and charsets
  369. // This is done pre-submit already so it's just for security
  370. $engines = $this->getEngines();
  371. if ( !in_array( $this->getVar( '_MysqlEngine' ), $engines ) ) {
  372. $this->setVar( '_MysqlEngine', reset( $engines ) );
  373. }
  374. $charsets = $this->getCharsets();
  375. if ( !in_array( $this->getVar( '_MysqlCharset' ), $charsets ) ) {
  376. $this->setVar( '_MysqlCharset', reset( $charsets ) );
  377. }
  378. return Status::newGood();
  379. }
  380. public function preInstall() {
  381. # Add our user callback to installSteps, right before the tables are created.
  382. $callback = [
  383. 'name' => 'user',
  384. 'callback' => [ $this, 'setupUser' ],
  385. ];
  386. $this->parent->addInstallStep( $callback, 'tables' );
  387. }
  388. /**
  389. * @return Status
  390. */
  391. public function setupDatabase() {
  392. $status = $this->getConnection();
  393. if ( !$status->isOK() ) {
  394. return $status;
  395. }
  396. /** @var Database $conn */
  397. $conn = $status->value;
  398. $dbName = $this->getVar( 'wgDBname' );
  399. if ( !$this->databaseExists( $dbName ) ) {
  400. $conn->query(
  401. "CREATE DATABASE " . $conn->addIdentifierQuotes( $dbName ) . "CHARACTER SET utf8",
  402. __METHOD__
  403. );
  404. }
  405. $conn->selectDB( $dbName );
  406. $this->setupSchemaVars();
  407. return $status;
  408. }
  409. /**
  410. * Try to see if a given database exists
  411. * @param string $dbName Database name to check
  412. * @return bool
  413. */
  414. private function databaseExists( $dbName ) {
  415. $encDatabase = $this->db->addQuotes( $dbName );
  416. return $this->db->query(
  417. "SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = $encDatabase",
  418. __METHOD__
  419. )->numRows() > 0;
  420. }
  421. /**
  422. * @return Status
  423. */
  424. public function setupUser() {
  425. $dbUser = $this->getVar( 'wgDBuser' );
  426. if ( $dbUser == $this->getVar( '_InstallUser' ) ) {
  427. return Status::newGood();
  428. }
  429. $status = $this->getConnection();
  430. if ( !$status->isOK() ) {
  431. return $status;
  432. }
  433. $this->setupSchemaVars();
  434. $dbName = $this->getVar( 'wgDBname' );
  435. $this->db->selectDB( $dbName );
  436. $server = $this->getVar( 'wgDBserver' );
  437. $password = $this->getVar( 'wgDBpassword' );
  438. $grantableNames = [];
  439. if ( $this->getVar( '_CreateDBAccount' ) ) {
  440. // Before we blindly try to create a user that already has access,
  441. try { // first attempt to connect to the database
  442. Database::factory( 'mysql', [
  443. 'host' => $server,
  444. 'user' => $dbUser,
  445. 'password' => $password,
  446. 'dbname' => false,
  447. 'flags' => 0,
  448. 'tablePrefix' => $this->getVar( 'wgDBprefix' )
  449. ] );
  450. $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
  451. $tryToCreate = false;
  452. } catch ( DBConnectionError $e ) {
  453. $tryToCreate = true;
  454. }
  455. } else {
  456. $grantableNames[] = $this->buildFullUserName( $dbUser, $server );
  457. $tryToCreate = false;
  458. }
  459. if ( $tryToCreate ) {
  460. $createHostList = [
  461. $server,
  462. 'localhost',
  463. 'localhost.localdomain',
  464. '%'
  465. ];
  466. $createHostList = array_unique( $createHostList );
  467. $escPass = $this->db->addQuotes( $password );
  468. foreach ( $createHostList as $host ) {
  469. $fullName = $this->buildFullUserName( $dbUser, $host );
  470. if ( !$this->userDefinitelyExists( $host, $dbUser ) ) {
  471. try {
  472. $this->db->begin( __METHOD__ );
  473. $this->db->query( "CREATE USER $fullName IDENTIFIED BY $escPass", __METHOD__ );
  474. $this->db->commit( __METHOD__ );
  475. $grantableNames[] = $fullName;
  476. } catch ( DBQueryError $dqe ) {
  477. if ( $this->db->lastErrno() == 1396 /* ER_CANNOT_USER */ ) {
  478. // User (probably) already exists
  479. $this->db->rollback( __METHOD__ );
  480. $status->warning( 'config-install-user-alreadyexists', $dbUser );
  481. $grantableNames[] = $fullName;
  482. break;
  483. } else {
  484. // If we couldn't create for some bizzare reason and the
  485. // user probably doesn't exist, skip the grant
  486. $this->db->rollback( __METHOD__ );
  487. $status->warning( 'config-install-user-create-failed', $dbUser, $dqe->getMessage() );
  488. }
  489. }
  490. } else {
  491. $status->warning( 'config-install-user-alreadyexists', $dbUser );
  492. $grantableNames[] = $fullName;
  493. break;
  494. }
  495. }
  496. }
  497. // Try to grant to all the users we know exist or we were able to create
  498. $dbAllTables = $this->db->addIdentifierQuotes( $dbName ) . '.*';
  499. foreach ( $grantableNames as $name ) {
  500. try {
  501. $this->db->begin( __METHOD__ );
  502. $this->db->query( "GRANT ALL PRIVILEGES ON $dbAllTables TO $name", __METHOD__ );
  503. $this->db->commit( __METHOD__ );
  504. } catch ( DBQueryError $dqe ) {
  505. $this->db->rollback( __METHOD__ );
  506. $status->fatal( 'config-install-user-grant-failed', $dbUser, $dqe->getMessage() );
  507. }
  508. }
  509. return $status;
  510. }
  511. /**
  512. * Return a formal 'User'@'Host' username for use in queries
  513. * @param string $name Username, quotes will be added
  514. * @param string $host Hostname, quotes will be added
  515. * @return string
  516. */
  517. private function buildFullUserName( $name, $host ) {
  518. return $this->db->addQuotes( $name ) . '@' . $this->db->addQuotes( $host );
  519. }
  520. /**
  521. * Try to see if the user account exists. Our "superuser" may not have
  522. * access to mysql.user, so false means "no" or "maybe"
  523. * @param string $host Hostname to check
  524. * @param string $user Username to check
  525. * @return bool
  526. */
  527. private function userDefinitelyExists( $host, $user ) {
  528. try {
  529. $res = $this->db->selectRow( 'mysql.user', [ 'Host', 'User' ],
  530. [ 'Host' => $host, 'User' => $user ], __METHOD__ );
  531. return (bool)$res;
  532. } catch ( DBQueryError $dqe ) {
  533. return false;
  534. }
  535. }
  536. /**
  537. * Return any table options to be applied to all tables that don't
  538. * override them.
  539. *
  540. * @return string
  541. */
  542. protected function getTableOptions() {
  543. $options = [];
  544. if ( $this->getVar( '_MysqlEngine' ) !== null ) {
  545. $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
  546. }
  547. if ( $this->getVar( '_MysqlCharset' ) !== null ) {
  548. $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
  549. }
  550. return implode( ', ', $options );
  551. }
  552. /**
  553. * Get variables to substitute into tables.sql and the SQL patch files.
  554. *
  555. * @return array
  556. */
  557. public function getSchemaVars() {
  558. return [
  559. 'wgDBTableOptions' => $this->getTableOptions(),
  560. 'wgDBname' => $this->getVar( 'wgDBname' ),
  561. 'wgDBuser' => $this->getVar( 'wgDBuser' ),
  562. 'wgDBpassword' => $this->getVar( 'wgDBpassword' ),
  563. ];
  564. }
  565. public function getLocalSettings() {
  566. $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
  567. $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
  568. return "# MySQL specific settings
  569. \$wgDBprefix = \"{$prefix}\";
  570. # MySQL table options to use during installation or update
  571. \$wgDBTableOptions = \"{$tblOpts}\";";
  572. }
  573. }