PageRenderTime 65ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/classes/Server/Privileges.php

http://github.com/phpmyadmin/phpmyadmin
PHP | 3898 lines | 3136 code | 318 blank | 444 comment | 365 complexity | 304f267100282d8151c48a3d443ea6fe MD5 | raw file
Possible License(s): GPL-2.0, MIT, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * set of functions with the Privileges section in pma
  4. */
  5. declare(strict_types=1);
  6. namespace PhpMyAdmin\Server;
  7. use mysqli_stmt;
  8. use PhpMyAdmin\DatabaseInterface;
  9. use PhpMyAdmin\Html\Generator;
  10. use PhpMyAdmin\Html\MySQLDocumentation;
  11. use PhpMyAdmin\Message;
  12. use PhpMyAdmin\Query\Compatibility;
  13. use PhpMyAdmin\Relation;
  14. use PhpMyAdmin\RelationCleanup;
  15. use PhpMyAdmin\ResponseRenderer;
  16. use PhpMyAdmin\Template;
  17. use PhpMyAdmin\Url;
  18. use PhpMyAdmin\Util;
  19. use function __;
  20. use function array_map;
  21. use function array_merge;
  22. use function array_unique;
  23. use function count;
  24. use function explode;
  25. use function htmlspecialchars;
  26. use function implode;
  27. use function in_array;
  28. use function is_array;
  29. use function is_scalar;
  30. use function is_string;
  31. use function json_decode;
  32. use function ksort;
  33. use function max;
  34. use function mb_chr;
  35. use function mb_strpos;
  36. use function mb_strrpos;
  37. use function mb_strtolower;
  38. use function mb_strtoupper;
  39. use function mb_substr;
  40. use function preg_match;
  41. use function preg_replace;
  42. use function sprintf;
  43. use function str_contains;
  44. use function str_replace;
  45. use function strlen;
  46. use function trim;
  47. use function uksort;
  48. /**
  49. * Privileges class
  50. */
  51. class Privileges
  52. {
  53. /** @var Template */
  54. public $template;
  55. /** @var RelationCleanup */
  56. private $relationCleanup;
  57. /** @var DatabaseInterface */
  58. public $dbi;
  59. /** @var Relation */
  60. public $relation;
  61. /** @var Plugins */
  62. private $plugins;
  63. /**
  64. * @param Template $template Template object
  65. * @param DatabaseInterface $dbi DatabaseInterface object
  66. * @param Relation $relation Relation object
  67. * @param RelationCleanup $relationCleanup RelationCleanup object
  68. */
  69. public function __construct(
  70. Template $template,
  71. $dbi,
  72. Relation $relation,
  73. RelationCleanup $relationCleanup,
  74. Plugins $plugins
  75. ) {
  76. $this->template = $template;
  77. $this->dbi = $dbi;
  78. $this->relation = $relation;
  79. $this->relationCleanup = $relationCleanup;
  80. $this->plugins = $plugins;
  81. }
  82. /**
  83. * Escapes wildcard in a database+table specification
  84. * before using it in a GRANT statement.
  85. *
  86. * Escaping a wildcard character in a GRANT is only accepted at the global
  87. * or database level, not at table level; this is why I remove
  88. * the escaping character. Internally, in mysql.tables_priv.Db there are
  89. * no escaping (for example test_db) but in mysql.db you'll see test\_db
  90. * for a db-specific privilege.
  91. *
  92. * @param string $dbname Database name
  93. * @param string $tablename Table name
  94. *
  95. * @return string the escaped (if necessary) database.table
  96. */
  97. public function wildcardEscapeForGrant(string $dbname, string $tablename): string
  98. {
  99. if (strlen($dbname) === 0) {
  100. return '*.*';
  101. }
  102. if (strlen($tablename) > 0) {
  103. return Util::backquote(
  104. Util::unescapeMysqlWildcards($dbname)
  105. )
  106. . '.' . Util::backquote($tablename);
  107. }
  108. return Util::backquote($dbname) . '.*';
  109. }
  110. /**
  111. * Generates a condition on the user name
  112. *
  113. * @param string|null $initial the user's initial
  114. *
  115. * @return string the generated condition
  116. */
  117. public function rangeOfUsers($initial = '')
  118. {
  119. // strtolower() is used because the User field
  120. // might be BINARY, so LIKE would be case sensitive
  121. if ($initial === null || $initial === '') {
  122. return '';
  123. }
  124. return " WHERE `User` LIKE '"
  125. . $this->dbi->escapeString($initial) . "%'"
  126. . " OR `User` LIKE '"
  127. . $this->dbi->escapeString(mb_strtolower($initial))
  128. . "%'";
  129. }
  130. /**
  131. * Parses privileges into an array, it modifies the array
  132. *
  133. * @param array $row Results row from
  134. */
  135. public function fillInTablePrivileges(array &$row): void
  136. {
  137. $row1 = $this->dbi->fetchSingleRow('SHOW COLUMNS FROM `mysql`.`tables_priv` LIKE \'Table_priv\';', 'ASSOC');
  138. // note: in MySQL 5.0.3 we get "Create View', 'Show view';
  139. // the View for Create is spelled with uppercase V
  140. // the view for Show is spelled with lowercase v
  141. // and there is a space between the words
  142. $avGrants = explode(
  143. '\',\'',
  144. mb_substr(
  145. $row1['Type'],
  146. mb_strpos($row1['Type'], '(') + 2,
  147. mb_strpos($row1['Type'], ')')
  148. - mb_strpos($row1['Type'], '(') - 3
  149. )
  150. );
  151. $usersGrants = explode(',', $row['Table_priv']);
  152. foreach ($avGrants as $currentGrant) {
  153. $row[$currentGrant . '_priv'] = in_array($currentGrant, $usersGrants) ? 'Y' : 'N';
  154. }
  155. unset($row['Table_priv']);
  156. }
  157. /**
  158. * Extracts the privilege information of a priv table row
  159. *
  160. * @param array|null $row the row
  161. * @param bool $enableHTML add <dfn> tag with tooltips
  162. * @param bool $tablePrivs whether row contains table privileges
  163. *
  164. * @return array
  165. *
  166. * @global resource $user_link the database connection
  167. */
  168. public function extractPrivInfo($row = null, $enableHTML = false, $tablePrivs = false)
  169. {
  170. if ($tablePrivs) {
  171. $grants = $this->getTableGrantsArray();
  172. } else {
  173. $grants = $this->getGrantsArray();
  174. }
  175. if ($row !== null && isset($row['Table_priv'])) {
  176. $this->fillInTablePrivileges($row);
  177. }
  178. $privs = [];
  179. $allPrivileges = true;
  180. foreach ($grants as $currentGrant) {
  181. if (
  182. ($row === null || ! isset($row[$currentGrant[0]]))
  183. && ($row !== null || ! isset($GLOBALS[$currentGrant[0]]))
  184. ) {
  185. continue;
  186. }
  187. if (
  188. ($row !== null && $row[$currentGrant[0]] === 'Y')
  189. || ($row === null
  190. && ($GLOBALS[$currentGrant[0]] === 'Y'
  191. || (is_array($GLOBALS[$currentGrant[0]])
  192. && count($GLOBALS[$currentGrant[0]]) == $_REQUEST['column_count']
  193. && empty($GLOBALS[$currentGrant[0] . '_none']))))
  194. ) {
  195. if ($enableHTML) {
  196. $privs[] = '<dfn title="' . $currentGrant[2] . '">'
  197. . $currentGrant[1] . '</dfn>';
  198. } else {
  199. $privs[] = $currentGrant[1];
  200. }
  201. } elseif (
  202. ! empty($GLOBALS[$currentGrant[0]])
  203. && is_array($GLOBALS[$currentGrant[0]])
  204. && empty($GLOBALS[$currentGrant[0] . '_none'])
  205. ) {
  206. // Required for proper escaping of ` (backtick) in a column name
  207. $grantCols = array_map(
  208. /**
  209. * @param string $val
  210. *
  211. * @return string
  212. */
  213. static function ($val) {
  214. return Util::backquote($val);
  215. },
  216. $GLOBALS[$currentGrant[0]]
  217. );
  218. if ($enableHTML) {
  219. $privs[] = '<dfn title="' . $currentGrant[2] . '">'
  220. . $currentGrant[1] . '</dfn>'
  221. . ' (' . implode(', ', $grantCols) . ')';
  222. } else {
  223. $privs[] = $currentGrant[1]
  224. . ' (' . implode(', ', $grantCols) . ')';
  225. }
  226. } else {
  227. $allPrivileges = false;
  228. }
  229. }
  230. if (empty($privs)) {
  231. if ($enableHTML) {
  232. $privs[] = '<dfn title="' . __('No privileges.') . '">USAGE</dfn>';
  233. } else {
  234. $privs[] = 'USAGE';
  235. }
  236. } elseif ($allPrivileges && (! isset($_POST['grant_count']) || count($privs) == $_POST['grant_count'])) {
  237. if ($enableHTML) {
  238. $privs = [
  239. '<dfn title="'
  240. . __('Includes all privileges except GRANT.')
  241. . '">ALL PRIVILEGES</dfn>',
  242. ];
  243. } else {
  244. $privs = ['ALL PRIVILEGES'];
  245. }
  246. }
  247. return $privs;
  248. }
  249. /**
  250. * Returns an array of table grants and their descriptions
  251. *
  252. * @return array array of table grants
  253. */
  254. public function getTableGrantsArray()
  255. {
  256. return [
  257. [
  258. 'Delete',
  259. 'DELETE',
  260. __('Allows deleting data.'),
  261. ],
  262. [
  263. 'Create',
  264. 'CREATE',
  265. __('Allows creating new tables.'),
  266. ],
  267. [
  268. 'Drop',
  269. 'DROP',
  270. __('Allows dropping tables.'),
  271. ],
  272. [
  273. 'Index',
  274. 'INDEX',
  275. __('Allows creating and dropping indexes.'),
  276. ],
  277. [
  278. 'Alter',
  279. 'ALTER',
  280. __('Allows altering the structure of existing tables.'),
  281. ],
  282. [
  283. 'Create View',
  284. 'CREATE_VIEW',
  285. __('Allows creating new views.'),
  286. ],
  287. [
  288. 'Show view',
  289. 'SHOW_VIEW',
  290. __('Allows performing SHOW CREATE VIEW queries.'),
  291. ],
  292. [
  293. 'Trigger',
  294. 'TRIGGER',
  295. __('Allows creating and dropping triggers.'),
  296. ],
  297. ];
  298. }
  299. /**
  300. * Get the grants array which contains all the privilege types
  301. * and relevant grant messages
  302. *
  303. * @return array
  304. */
  305. public function getGrantsArray()
  306. {
  307. return [
  308. [
  309. 'Select_priv',
  310. 'SELECT',
  311. __('Allows reading data.'),
  312. ],
  313. [
  314. 'Insert_priv',
  315. 'INSERT',
  316. __('Allows inserting and replacing data.'),
  317. ],
  318. [
  319. 'Update_priv',
  320. 'UPDATE',
  321. __('Allows changing data.'),
  322. ],
  323. [
  324. 'Delete_priv',
  325. 'DELETE',
  326. __('Allows deleting data.'),
  327. ],
  328. [
  329. 'Create_priv',
  330. 'CREATE',
  331. __('Allows creating new databases and tables.'),
  332. ],
  333. [
  334. 'Drop_priv',
  335. 'DROP',
  336. __('Allows dropping databases and tables.'),
  337. ],
  338. [
  339. 'Reload_priv',
  340. 'RELOAD',
  341. __('Allows reloading server settings and flushing the server\'s caches.'),
  342. ],
  343. [
  344. 'Shutdown_priv',
  345. 'SHUTDOWN',
  346. __('Allows shutting down the server.'),
  347. ],
  348. [
  349. 'Process_priv',
  350. 'PROCESS',
  351. __('Allows viewing processes of all users.'),
  352. ],
  353. [
  354. 'File_priv',
  355. 'FILE',
  356. __('Allows importing data from and exporting data into files.'),
  357. ],
  358. [
  359. 'References_priv',
  360. 'REFERENCES',
  361. __('Has no effect in this MySQL version.'),
  362. ],
  363. [
  364. 'Index_priv',
  365. 'INDEX',
  366. __('Allows creating and dropping indexes.'),
  367. ],
  368. [
  369. 'Alter_priv',
  370. 'ALTER',
  371. __('Allows altering the structure of existing tables.'),
  372. ],
  373. [
  374. 'Show_db_priv',
  375. 'SHOW DATABASES',
  376. __('Gives access to the complete list of databases.'),
  377. ],
  378. [
  379. 'Super_priv',
  380. 'SUPER',
  381. __(
  382. 'Allows connecting, even if maximum number of connections '
  383. . 'is reached; required for most administrative operations '
  384. . 'like setting global variables or killing threads of other users.'
  385. ),
  386. ],
  387. [
  388. 'Create_tmp_table_priv',
  389. 'CREATE TEMPORARY TABLES',
  390. __('Allows creating temporary tables.'),
  391. ],
  392. [
  393. 'Lock_tables_priv',
  394. 'LOCK TABLES',
  395. __('Allows locking tables for the current thread.'),
  396. ],
  397. [
  398. 'Repl_slave_priv',
  399. 'REPLICATION SLAVE',
  400. __('Needed for the replication slaves.'),
  401. ],
  402. [
  403. 'Repl_client_priv',
  404. 'REPLICATION CLIENT',
  405. __('Allows the user to ask where the slaves / masters are.'),
  406. ],
  407. [
  408. 'Create_view_priv',
  409. 'CREATE VIEW',
  410. __('Allows creating new views.'),
  411. ],
  412. [
  413. 'Event_priv',
  414. 'EVENT',
  415. __('Allows to set up events for the event scheduler.'),
  416. ],
  417. [
  418. 'Trigger_priv',
  419. 'TRIGGER',
  420. __('Allows creating and dropping triggers.'),
  421. ],
  422. // for table privs:
  423. [
  424. 'Create View_priv',
  425. 'CREATE VIEW',
  426. __('Allows creating new views.'),
  427. ],
  428. [
  429. 'Show_view_priv',
  430. 'SHOW VIEW',
  431. __('Allows performing SHOW CREATE VIEW queries.'),
  432. ],
  433. // for table privs:
  434. [
  435. 'Show view_priv',
  436. 'SHOW VIEW',
  437. __('Allows performing SHOW CREATE VIEW queries.'),
  438. ],
  439. [
  440. 'Delete_history_priv',
  441. 'DELETE HISTORY',
  442. // phpcs:ignore Generic.Files.LineLength.TooLong
  443. /* l10n: https://mariadb.com/kb/en/library/grant/#table-privileges "Remove historical rows from a table using the DELETE HISTORY statement" */
  444. __('Allows deleting historical rows.'),
  445. ],
  446. [
  447. // This was finally removed in the following MariaDB versions
  448. // @see https://jira.mariadb.org/browse/MDEV-20382
  449. 'Delete versioning rows_priv',
  450. 'DELETE HISTORY',
  451. // phpcs:ignore Generic.Files.LineLength.TooLong
  452. /* l10n: https://mariadb.com/kb/en/library/grant/#table-privileges "Remove historical rows from a table using the DELETE HISTORY statement" */
  453. __('Allows deleting historical rows.'),
  454. ],
  455. [
  456. 'Create_routine_priv',
  457. 'CREATE ROUTINE',
  458. __('Allows creating stored routines.'),
  459. ],
  460. [
  461. 'Alter_routine_priv',
  462. 'ALTER ROUTINE',
  463. __('Allows altering and dropping stored routines.'),
  464. ],
  465. [
  466. 'Create_user_priv',
  467. 'CREATE USER',
  468. __('Allows creating, dropping and renaming user accounts.'),
  469. ],
  470. [
  471. 'Execute_priv',
  472. 'EXECUTE',
  473. __('Allows executing stored routines.'),
  474. ],
  475. ];
  476. }
  477. /**
  478. * Get sql query for display privileges table
  479. *
  480. * @param string $db the database
  481. * @param string $table the table
  482. * @param string $username username for database connection
  483. * @param string $hostname hostname for database connection
  484. *
  485. * @return string sql query
  486. */
  487. public function getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname)
  488. {
  489. if ($db === '*') {
  490. return 'SELECT * FROM `mysql`.`user`'
  491. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  492. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "';";
  493. }
  494. if ($table === '*') {
  495. return 'SELECT * FROM `mysql`.`db`'
  496. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  497. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "'"
  498. . " AND `Db` = '" . $this->dbi->escapeString($db) . "'";
  499. }
  500. return 'SELECT `Table_priv`'
  501. . ' FROM `mysql`.`tables_priv`'
  502. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  503. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "'"
  504. . " AND `Db` = '" . $this->dbi->escapeString(Util::unescapeMysqlWildcards($db)) . "'"
  505. . " AND `Table_name` = '" . $this->dbi->escapeString($table) . "';";
  506. }
  507. /**
  508. * Sets the user group from request values
  509. *
  510. * @param string $username username
  511. * @param string $userGroup user group to set
  512. */
  513. public function setUserGroup($username, $userGroup): void
  514. {
  515. $userGroup = $userGroup ?? '';
  516. $cfgRelation = $this->relation->getRelationsParam();
  517. if (empty($cfgRelation['db']) || empty($cfgRelation['users']) || empty($cfgRelation['usergroups'])) {
  518. return;
  519. }
  520. $userTable = Util::backquote($cfgRelation['db'])
  521. . '.' . Util::backquote($cfgRelation['users']);
  522. $sqlQuery = 'SELECT `usergroup` FROM ' . $userTable
  523. . " WHERE `username` = '" . $this->dbi->escapeString($username) . "'";
  524. $oldUserGroup = $this->dbi->fetchValue($sqlQuery, 0, 0, DatabaseInterface::CONNECT_CONTROL);
  525. if ($oldUserGroup === false) {
  526. $updQuery = 'INSERT INTO ' . $userTable . '(`username`, `usergroup`)'
  527. . " VALUES ('" . $this->dbi->escapeString($username) . "', "
  528. . "'" . $this->dbi->escapeString($userGroup) . "')";
  529. } else {
  530. if (empty($userGroup)) {
  531. $updQuery = 'DELETE FROM ' . $userTable
  532. . " WHERE `username`='" . $this->dbi->escapeString($username) . "'";
  533. } elseif ($oldUserGroup != $userGroup) {
  534. $updQuery = 'UPDATE ' . $userTable
  535. . " SET `usergroup`='" . $this->dbi->escapeString($userGroup) . "'"
  536. . " WHERE `username`='" . $this->dbi->escapeString($username) . "'";
  537. }
  538. }
  539. if (! isset($updQuery)) {
  540. return;
  541. }
  542. $this->relation->queryAsControlUser($updQuery);
  543. }
  544. /**
  545. * Displays the privileges form table
  546. *
  547. * @param string $db the database
  548. * @param string $table the table
  549. * @param bool $submit whether to display the submit button or not
  550. *
  551. * @return string html snippet
  552. *
  553. * @global array $cfg the phpMyAdmin configuration
  554. * @global resource $user_link the database connection
  555. */
  556. public function getHtmlToDisplayPrivilegesTable(
  557. $db = '*',
  558. $table = '*',
  559. $submit = true
  560. ) {
  561. $sqlQuery = '';
  562. if ($db === '*') {
  563. $table = '*';
  564. }
  565. $username = '';
  566. $hostname = '';
  567. $row = [];
  568. if (isset($GLOBALS['username'])) {
  569. $username = $GLOBALS['username'];
  570. $hostname = $GLOBALS['hostname'];
  571. $sqlQuery = $this->getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname);
  572. $row = $this->dbi->fetchSingleRow($sqlQuery);
  573. }
  574. if (empty($row)) {
  575. if ($table === '*' && $this->dbi->isSuperUser()) {
  576. $row = [];
  577. if ($db === '*') {
  578. $sqlQuery = 'SHOW COLUMNS FROM `mysql`.`user`;';
  579. } elseif ($table === '*') {
  580. $sqlQuery = 'SHOW COLUMNS FROM `mysql`.`db`;';
  581. }
  582. $res = $this->dbi->query($sqlQuery);
  583. while ($row1 = $this->dbi->fetchRow($res)) {
  584. if (mb_substr($row1[0], 0, 4) === 'max_') {
  585. $row[$row1[0]] = 0;
  586. } elseif (mb_substr($row1[0], 0, 5) === 'x509_' || mb_substr($row1[0], 0, 4) === 'ssl_') {
  587. $row[$row1[0]] = '';
  588. } else {
  589. $row[$row1[0]] = 'N';
  590. }
  591. }
  592. $this->dbi->freeResult($res);
  593. } elseif ($table === '*') {
  594. $row = [];
  595. } else {
  596. $row = ['Table_priv' => ''];
  597. }
  598. }
  599. if (isset($row['Table_priv'])) {
  600. $this->fillInTablePrivileges($row);
  601. // get columns
  602. $res = $this->dbi->tryQuery(
  603. 'SHOW COLUMNS FROM '
  604. . Util::backquote(
  605. Util::unescapeMysqlWildcards($db)
  606. )
  607. . '.' . Util::backquote($table) . ';'
  608. );
  609. $columns = [];
  610. if ($res) {
  611. while ($row1 = $this->dbi->fetchRow($res)) {
  612. $columns[$row1[0]] = [
  613. 'Select' => false,
  614. 'Insert' => false,
  615. 'Update' => false,
  616. 'References' => false,
  617. ];
  618. }
  619. $this->dbi->freeResult($res);
  620. }
  621. }
  622. if (! empty($columns)) {
  623. $res = $this->dbi->query(
  624. 'SELECT `Column_name`, `Column_priv`'
  625. . ' FROM `mysql`.`columns_priv`'
  626. . ' WHERE `User`'
  627. . ' = \'' . $this->dbi->escapeString($username) . "'"
  628. . ' AND `Host`'
  629. . ' = \'' . $this->dbi->escapeString($hostname) . "'"
  630. . ' AND `Db`'
  631. . ' = \'' . $this->dbi->escapeString(
  632. Util::unescapeMysqlWildcards($db)
  633. ) . "'"
  634. . ' AND `Table_name`'
  635. . ' = \'' . $this->dbi->escapeString($table) . '\';'
  636. );
  637. while ($row1 = $this->dbi->fetchRow($res)) {
  638. $row1[1] = explode(',', $row1[1]);
  639. foreach ($row1[1] as $current) {
  640. $columns[$row1[0]][$current] = true;
  641. }
  642. }
  643. $this->dbi->freeResult($res);
  644. }
  645. return $this->template->render('server/privileges/privileges_table', [
  646. 'is_global' => $db === '*',
  647. 'is_database' => $table === '*',
  648. 'row' => $row,
  649. 'columns' => $columns ?? [],
  650. 'has_submit' => $submit,
  651. 'supports_references_privilege' => Compatibility::supportsReferencesPrivilege($this->dbi),
  652. 'is_mariadb' => $this->dbi->isMariaDB(),
  653. ]);
  654. }
  655. /**
  656. * Get the HTML snippet for routine specific privileges
  657. *
  658. * @param string $username username for database connection
  659. * @param string $hostname hostname for database connection
  660. * @param string $db the database
  661. * @param string $routine the routine
  662. * @param string $urlDbname url encoded db name
  663. *
  664. * @return string
  665. */
  666. public function getHtmlForRoutineSpecificPrivileges(
  667. $username,
  668. $hostname,
  669. $db,
  670. $routine,
  671. $urlDbname
  672. ) {
  673. $privileges = $this->getRoutinePrivileges($username, $hostname, $db, $routine);
  674. return $this->template->render('server/privileges/edit_routine_privileges', [
  675. 'username' => $username,
  676. 'hostname' => $hostname,
  677. 'database' => $db,
  678. 'routine' => $routine,
  679. 'privileges' => $privileges,
  680. 'dbname' => $urlDbname,
  681. 'current_user' => $this->dbi->getCurrentUser(),
  682. ]);
  683. }
  684. /**
  685. * Displays the fields used by the "new user" form as well as the
  686. * "change login information / copy user" form.
  687. *
  688. * @param string $mode are we creating a new user or are we just
  689. * changing one? (allowed values: 'new', 'change')
  690. * @param string $user User name
  691. * @param string $host Host name
  692. *
  693. * @return string a HTML snippet
  694. */
  695. public function getHtmlForLoginInformationFields(
  696. $mode = 'new',
  697. $user = null,
  698. $host = null
  699. ) {
  700. global $pred_username, $pred_hostname, $username, $hostname, $new_username;
  701. [$usernameLength, $hostnameLength] = $this->getUsernameAndHostnameLength();
  702. if (isset($username) && strlen($username) === 0) {
  703. $pred_username = 'any';
  704. }
  705. $currentUser = $this->dbi->fetchValue('SELECT USER();');
  706. $thisHost = null;
  707. if (! empty($currentUser)) {
  708. $thisHost = str_replace(
  709. '\'',
  710. '',
  711. mb_substr(
  712. $currentUser,
  713. mb_strrpos($currentUser, '@') + 1
  714. )
  715. );
  716. }
  717. if (! isset($pred_hostname) && isset($hostname)) {
  718. switch (mb_strtolower($hostname)) {
  719. case 'localhost':
  720. case '127.0.0.1':
  721. $pred_hostname = 'localhost';
  722. break;
  723. case '%':
  724. $pred_hostname = 'any';
  725. break;
  726. default:
  727. $pred_hostname = 'userdefined';
  728. break;
  729. }
  730. }
  731. $serverVersion = $this->dbi->getVersion();
  732. $authPlugin = $this->getCurrentAuthenticationPlugin($mode, $user, $host);
  733. $isNew = (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50507)
  734. || (Compatibility::isMariaDb() && $serverVersion >= 50200);
  735. $activeAuthPlugins = ['mysql_native_password' => __('Native MySQL authentication')];
  736. if ($isNew) {
  737. $activeAuthPlugins = $this->plugins->getAuthentication();
  738. if (isset($activeAuthPlugins['mysql_old_password'])) {
  739. unset($activeAuthPlugins['mysql_old_password']);
  740. }
  741. }
  742. return $this->template->render('server/privileges/login_information_fields', [
  743. 'pred_username' => $pred_username ?? null,
  744. 'pred_hostname' => $pred_hostname ?? null,
  745. 'username_length' => $usernameLength,
  746. 'hostname_length' => $hostnameLength,
  747. 'username' => $username ?? null,
  748. 'new_username' => $new_username ?? null,
  749. 'hostname' => $hostname ?? null,
  750. 'this_host' => $thisHost,
  751. 'is_change' => $mode === 'change',
  752. 'auth_plugin' => $authPlugin,
  753. 'active_auth_plugins' => $activeAuthPlugins,
  754. 'is_new' => $isNew,
  755. ]);
  756. }
  757. /**
  758. * Get username and hostname length
  759. *
  760. * @return array username length and hostname length
  761. */
  762. public function getUsernameAndHostnameLength()
  763. {
  764. /* Fallback values */
  765. $usernameLength = 16;
  766. $hostnameLength = 41;
  767. /* Try to get real lengths from the database */
  768. $fieldsInfo = $this->dbi->fetchResult(
  769. 'SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH '
  770. . 'FROM information_schema.columns '
  771. . "WHERE table_schema = 'mysql' AND table_name = 'user' "
  772. . "AND COLUMN_NAME IN ('User', 'Host')"
  773. );
  774. foreach ($fieldsInfo as $val) {
  775. if ($val['COLUMN_NAME'] === 'User') {
  776. $usernameLength = $val['CHARACTER_MAXIMUM_LENGTH'];
  777. } elseif ($val['COLUMN_NAME'] === 'Host') {
  778. $hostnameLength = $val['CHARACTER_MAXIMUM_LENGTH'];
  779. }
  780. }
  781. return [
  782. $usernameLength,
  783. $hostnameLength,
  784. ];
  785. }
  786. /**
  787. * Get current authentication plugin in use - for a user or globally
  788. *
  789. * @param string $mode are we creating a new user or are we just
  790. * changing one? (allowed values: 'new', 'change')
  791. * @param string $username User name
  792. * @param string $hostname Host name
  793. *
  794. * @return string authentication plugin in use
  795. */
  796. public function getCurrentAuthenticationPlugin(
  797. $mode = 'new',
  798. $username = null,
  799. $hostname = null
  800. ) {
  801. global $dbi;
  802. /* Fallback (standard) value */
  803. $authenticationPlugin = 'mysql_native_password';
  804. $serverVersion = $this->dbi->getVersion();
  805. if (isset($username, $hostname) && $mode === 'change') {
  806. $row = $this->dbi->fetchSingleRow(
  807. 'SELECT `plugin` FROM `mysql`.`user` WHERE `User` = "'
  808. . $dbi->escapeString($username)
  809. . '" AND `Host` = "'
  810. . $dbi->escapeString($hostname)
  811. . '" LIMIT 1'
  812. );
  813. // Table 'mysql'.'user' may not exist for some previous
  814. // versions of MySQL - in that case consider fallback value
  815. if (is_array($row) && isset($row['plugin'])) {
  816. $authenticationPlugin = $row['plugin'];
  817. }
  818. } elseif ($mode === 'change') {
  819. [$username, $hostname] = $this->dbi->getCurrentUserAndHost();
  820. $row = $this->dbi->fetchSingleRow(
  821. 'SELECT `plugin` FROM `mysql`.`user` WHERE `User` = "'
  822. . $dbi->escapeString($username)
  823. . '" AND `Host` = "'
  824. . $dbi->escapeString($hostname)
  825. . '"'
  826. );
  827. if (is_array($row) && isset($row['plugin'])) {
  828. $authenticationPlugin = $row['plugin'];
  829. }
  830. } elseif ($serverVersion >= 50702) {
  831. $row = $this->dbi->fetchSingleRow('SELECT @@default_authentication_plugin');
  832. $authenticationPlugin = is_array($row) ? $row['@@default_authentication_plugin'] : null;
  833. }
  834. return $authenticationPlugin;
  835. }
  836. /**
  837. * Returns all the grants for a certain user on a certain host
  838. * Used in the export privileges for all users section
  839. *
  840. * @param string $user User name
  841. * @param string $host Host name
  842. *
  843. * @return string containing all the grants text
  844. */
  845. public function getGrants($user, $host)
  846. {
  847. $grants = $this->dbi->fetchResult(
  848. "SHOW GRANTS FOR '"
  849. . $this->dbi->escapeString($user) . "'@'"
  850. . $this->dbi->escapeString($host) . "'"
  851. );
  852. $response = '';
  853. foreach ($grants as $oneGrant) {
  854. $response .= $oneGrant . ";\n\n";
  855. }
  856. return $response;
  857. }
  858. /**
  859. * Update password and get message for password updating
  860. *
  861. * @param string $errorUrl error url
  862. * @param string $username username
  863. * @param string $hostname hostname
  864. *
  865. * @return Message success or error message after updating password
  866. */
  867. public function updatePassword($errorUrl, $username, $hostname)
  868. {
  869. global $dbi;
  870. // similar logic in /user-password
  871. $message = null;
  872. if (isset($_POST['pma_pw'], $_POST['pma_pw2']) && empty($_POST['nopass'])) {
  873. if ($_POST['pma_pw'] != $_POST['pma_pw2']) {
  874. $message = Message::error(__('The passwords aren\'t the same!'));
  875. } elseif (empty($_POST['pma_pw']) || empty($_POST['pma_pw2'])) {
  876. $message = Message::error(__('The password is empty!'));
  877. }
  878. }
  879. // here $nopass could be == 1
  880. if ($message === null) {
  881. $hashingFunction = 'PASSWORD';
  882. $serverVersion = $this->dbi->getVersion();
  883. $authenticationPlugin = ($_POST['authentication_plugin'] ?? $this->getCurrentAuthenticationPlugin(
  884. 'change',
  885. $username,
  886. $hostname
  887. ));
  888. // Use 'ALTER USER ...' syntax for MySQL 5.7.6+
  889. if (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50706) {
  890. if ($authenticationPlugin !== 'mysql_old_password') {
  891. $queryPrefix = "ALTER USER '"
  892. . $this->dbi->escapeString($username)
  893. . "'@'" . $this->dbi->escapeString($hostname) . "'"
  894. . ' IDENTIFIED WITH '
  895. . $authenticationPlugin
  896. . " BY '";
  897. } else {
  898. $queryPrefix = "ALTER USER '"
  899. . $this->dbi->escapeString($username)
  900. . "'@'" . $this->dbi->escapeString($hostname) . "'"
  901. . " IDENTIFIED BY '";
  902. }
  903. // in $sql_query which will be displayed, hide the password
  904. $sqlQuery = $queryPrefix . "*'";
  905. $localQuery = $queryPrefix
  906. . $this->dbi->escapeString($_POST['pma_pw']) . "'";
  907. } elseif (Compatibility::isMariaDb() && $serverVersion >= 10000) {
  908. // MariaDB uses "SET PASSWORD" syntax to change user password.
  909. // On Galera cluster only DDL queries are replicated, since
  910. // users are stored in MyISAM storage engine.
  911. $queryPrefix = "SET PASSWORD FOR '"
  912. . $this->dbi->escapeString($username)
  913. . "'@'" . $this->dbi->escapeString($hostname) . "'"
  914. . " = PASSWORD ('";
  915. $sqlQuery = $localQuery = $queryPrefix
  916. . $this->dbi->escapeString($_POST['pma_pw']) . "')";
  917. } elseif (Compatibility::isMariaDb() && $serverVersion >= 50200 && $this->dbi->isSuperUser()) {
  918. // Use 'UPDATE `mysql`.`user` ...' Syntax for MariaDB 5.2+
  919. if ($authenticationPlugin === 'mysql_native_password') {
  920. // Set the hashing method used by PASSWORD()
  921. // to be 'mysql_native_password' type
  922. $this->dbi->tryQuery('SET old_passwords = 0;');
  923. } elseif ($authenticationPlugin === 'sha256_password') {
  924. // Set the hashing method used by PASSWORD()
  925. // to be 'sha256_password' type
  926. $this->dbi->tryQuery('SET `old_passwords` = 2;');
  927. }
  928. $hashedPassword = $this->getHashedPassword($_POST['pma_pw']);
  929. $sqlQuery = 'SET PASSWORD FOR \''
  930. . $this->dbi->escapeString($username)
  931. . '\'@\'' . $this->dbi->escapeString($hostname) . '\' = '
  932. . ($_POST['pma_pw'] == ''
  933. ? '\'\''
  934. : $hashingFunction . '(\''
  935. . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
  936. $localQuery = 'UPDATE `mysql`.`user` SET '
  937. . " `authentication_string` = '" . $hashedPassword
  938. . "', `Password` = '', "
  939. . " `plugin` = '" . $authenticationPlugin . "'"
  940. . " WHERE `User` = '" . $dbi->escapeString($username)
  941. . "' AND Host = '" . $dbi->escapeString($hostname) . "';";
  942. } else {
  943. // USE 'SET PASSWORD ...' syntax for rest of the versions
  944. // Backup the old value, to be reset later
  945. $row = $this->dbi->fetchSingleRow('SELECT @@old_passwords;');
  946. $origValue = $row['@@old_passwords'];
  947. $updatePluginQuery = 'UPDATE `mysql`.`user` SET'
  948. . " `plugin` = '" . $authenticationPlugin . "'"
  949. . " WHERE `User` = '" . $dbi->escapeString($username)
  950. . "' AND Host = '" . $dbi->escapeString($hostname) . "';";
  951. // Update the plugin for the user
  952. if (! $this->dbi->tryQuery($updatePluginQuery)) {
  953. Generator::mysqlDie(
  954. $this->dbi->getError(),
  955. $updatePluginQuery,
  956. false,
  957. $errorUrl
  958. );
  959. }
  960. $this->dbi->tryQuery('FLUSH PRIVILEGES;');
  961. if ($authenticationPlugin === 'mysql_native_password') {
  962. // Set the hashing method used by PASSWORD()
  963. // to be 'mysql_native_password' type
  964. $this->dbi->tryQuery('SET old_passwords = 0;');
  965. } elseif ($authenticationPlugin === 'sha256_password') {
  966. // Set the hashing method used by PASSWORD()
  967. // to be 'sha256_password' type
  968. $this->dbi->tryQuery('SET `old_passwords` = 2;');
  969. }
  970. $sqlQuery = 'SET PASSWORD FOR \''
  971. . $this->dbi->escapeString($username)
  972. . '\'@\'' . $this->dbi->escapeString($hostname) . '\' = '
  973. . ($_POST['pma_pw'] == ''
  974. ? '\'\''
  975. : $hashingFunction . '(\''
  976. . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
  977. $localQuery = 'SET PASSWORD FOR \''
  978. . $this->dbi->escapeString($username)
  979. . '\'@\'' . $this->dbi->escapeString($hostname) . '\' = '
  980. . ($_POST['pma_pw'] == '' ? '\'\'' : $hashingFunction
  981. . '(\'' . $this->dbi->escapeString($_POST['pma_pw']) . '\')');
  982. }
  983. if (! $this->dbi->tryQuery($localQuery)) {
  984. Generator::mysqlDie(
  985. $this->dbi->getError(),
  986. $sqlQuery,
  987. false,
  988. $errorUrl
  989. );
  990. }
  991. // Flush privileges after successful password change
  992. $this->dbi->tryQuery('FLUSH PRIVILEGES;');
  993. $message = Message::success(
  994. __('The password for %s was changed successfully.')
  995. );
  996. $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
  997. if (isset($origValue)) {
  998. $this->dbi->tryQuery('SET `old_passwords` = ' . $origValue . ';');
  999. }
  1000. }
  1001. return $message;
  1002. }
  1003. /**
  1004. * Revokes privileges and get message and SQL query for privileges revokes
  1005. *
  1006. * @param string $dbname database name
  1007. * @param string $tablename table name
  1008. * @param string $username username
  1009. * @param string $hostname host name
  1010. * @param string $itemType item type
  1011. *
  1012. * @return array ($message, $sql_query)
  1013. */
  1014. public function getMessageAndSqlQueryForPrivilegesRevoke(
  1015. string $dbname,
  1016. string $tablename,
  1017. $username,
  1018. $hostname,
  1019. $itemType
  1020. ) {
  1021. $dbAndTable = $this->wildcardEscapeForGrant($dbname, $tablename);
  1022. $sqlQuery0 = 'REVOKE ALL PRIVILEGES ON ' . $itemType . ' ' . $dbAndTable
  1023. . ' FROM \''
  1024. . $this->dbi->escapeString($username) . '\'@\''
  1025. . $this->dbi->escapeString($hostname) . '\';';
  1026. $sqlQuery1 = 'REVOKE GRANT OPTION ON ' . $itemType . ' ' . $dbAndTable
  1027. . ' FROM \'' . $this->dbi->escapeString($username) . '\'@\''
  1028. . $this->dbi->escapeString($hostname) . '\';';
  1029. $this->dbi->query($sqlQuery0);
  1030. if (! $this->dbi->tryQuery($sqlQuery1)) {
  1031. // this one may fail, too...
  1032. $sqlQuery1 = '';
  1033. }
  1034. $sqlQuery = $sqlQuery0 . ' ' . $sqlQuery1;
  1035. $message = Message::success(
  1036. __('You have revoked the privileges for %s.')
  1037. );
  1038. $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
  1039. return [
  1040. $message,
  1041. $sqlQuery,
  1042. ];
  1043. }
  1044. /**
  1045. * Get REQUIRE clause
  1046. *
  1047. * @return string REQUIRE clause
  1048. */
  1049. public function getRequireClause()
  1050. {
  1051. $arr = isset($_POST['ssl_type']) ? $_POST : $GLOBALS;
  1052. if (isset($arr['ssl_type']) && $arr['ssl_type'] === 'SPECIFIED') {
  1053. $require = [];
  1054. if (! empty($arr['ssl_cipher'])) {
  1055. $require[] = "CIPHER '"
  1056. . $this->dbi->escapeString($arr['ssl_cipher']) . "'";
  1057. }
  1058. if (! empty($arr['x509_issuer'])) {
  1059. $require[] = "ISSUER '"
  1060. . $this->dbi->escapeString($arr['x509_issuer']) . "'";
  1061. }
  1062. if (! empty($arr['x509_subject'])) {
  1063. $require[] = "SUBJECT '"
  1064. . $this->dbi->escapeString($arr['x509_subject']) . "'";
  1065. }
  1066. if (count($require)) {
  1067. $requireClause = ' REQUIRE ' . implode(' AND ', $require);
  1068. } else {
  1069. $requireClause = ' REQUIRE NONE';
  1070. }
  1071. } elseif (isset($arr['ssl_type']) && $arr['ssl_type'] === 'X509') {
  1072. $requireClause = ' REQUIRE X509';
  1073. } elseif (isset($arr['ssl_type']) && $arr['ssl_type'] === 'ANY') {
  1074. $requireClause = ' REQUIRE SSL';
  1075. } else {
  1076. $requireClause = ' REQUIRE NONE';
  1077. }
  1078. return $requireClause;
  1079. }
  1080. /**
  1081. * Get a WITH clause for 'update privileges' and 'add user'
  1082. *
  1083. * @return string
  1084. */
  1085. public function getWithClauseForAddUserAndUpdatePrivs()
  1086. {
  1087. $sqlQuery = '';
  1088. if (
  1089. ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] === 'Y')
  1090. || (isset($GLOBALS['Grant_priv']) && $GLOBALS['Grant_priv'] === 'Y'))
  1091. && ! (Compatibility::isMySqlOrPerconaDb() && $this->dbi->getVersion() >= 80011)
  1092. ) {
  1093. $sqlQuery .= ' GRANT OPTION';
  1094. }
  1095. if (isset($_POST['max_questions']) || isset($GLOBALS['max_questions'])) {
  1096. $maxQuestions = isset($_POST['max_questions'])
  1097. ? (int) $_POST['max_questions'] : (int) $GLOBALS['max_questions'];
  1098. $maxQuestions = max(0, $maxQuestions);
  1099. $sqlQuery .= ' MAX_QUERIES_PER_HOUR ' . $maxQuestions;
  1100. }
  1101. if (isset($_POST['max_connections']) || isset($GLOBALS['max_connections'])) {
  1102. $maxConnections = isset($_POST['max_connections'])
  1103. ? (int) $_POST['max_connections'] : (int) $GLOBALS['max_connections'];
  1104. $maxConnections = max(0, $maxConnections);
  1105. $sqlQuery .= ' MAX_CONNECTIONS_PER_HOUR ' . $maxConnections;
  1106. }
  1107. if (isset($_POST['max_updates']) || isset($GLOBALS['max_updates'])) {
  1108. $maxUpdates = isset($_POST['max_updates'])
  1109. ? (int) $_POST['max_updates'] : (int) $GLOBALS['max_updates'];
  1110. $maxUpdates = max(0, $maxUpdates);
  1111. $sqlQuery .= ' MAX_UPDATES_PER_HOUR ' . $maxUpdates;
  1112. }
  1113. if (isset($_POST['max_user_connections']) || isset($GLOBALS['max_user_connections'])) {
  1114. $maxUserConnections = isset($_POST['max_user_connections'])
  1115. ? (int) $_POST['max_user_connections']
  1116. : (int) $GLOBALS['max_user_connections'];
  1117. $maxUserConnections = max(0, $maxUserConnections);
  1118. $sqlQuery .= ' MAX_USER_CONNECTIONS ' . $maxUserConnections;
  1119. }
  1120. return ! empty($sqlQuery) ? ' WITH' . $sqlQuery : '';
  1121. }
  1122. /**
  1123. * Get HTML for addUsersForm, This function call if isset($_GET['adduser'])
  1124. *
  1125. * @param string $dbname database name
  1126. *
  1127. * @return string HTML for addUserForm
  1128. */
  1129. public function getHtmlForAddUser($dbname)
  1130. {
  1131. $isGrantUser = $this->dbi->isGrantUser();
  1132. $loginInformationFieldsNew = $this->getHtmlForLoginInformationFields('new');
  1133. $privilegesTable = '';
  1134. if ($isGrantUser) {
  1135. $privilegesTable = $this->getHtmlToDisplayPrivilegesTable('*', '*', false);
  1136. }
  1137. return $this->template->render('server/privileges/add_user', [
  1138. 'database' => $dbname,
  1139. 'login_information_fields_new' => $loginInformationFieldsNew,
  1140. 'is_grant_user' => $isGrantUser,
  1141. 'privileges_table' => $privilegesTable,
  1142. ]);
  1143. }
  1144. /**
  1145. * @param string $db database name
  1146. * @param string $table table name
  1147. *
  1148. * @return array
  1149. */
  1150. public function getAllPrivileges(string $db, string $table = ''): array
  1151. {
  1152. $databasePrivileges = $this->getGlobalAndDatabasePrivileges($db);
  1153. $tablePrivileges = [];
  1154. if ($table !== '') {
  1155. $tablePrivileges = $this->getTablePrivileges($db, $table);
  1156. }
  1157. $routinePrivileges = $this->getRoutinesPrivileges($db);
  1158. $allPrivileges = array_merge($databasePrivileges, $tablePrivileges, $routinePrivileges);
  1159. $privileges = [];
  1160. foreach ($allPrivileges as $privilege) {
  1161. $userHost = $privilege['User'] . '@' . $privilege['Host'];
  1162. $privileges[$userHost] = $privileges[$userHost] ?? [];
  1163. $privileges[$userHost]['user'] = (string) $privilege['User'];
  1164. $privileges[$userHost]['host'] = (string) $privilege['Host'];
  1165. $privileges[$userHost]['privileges'] = $privileges[$userHost]['privileges'] ?? [];
  1166. $privileges[$userHost]['privileges'][] = $this->getSpecificPrivilege($privilege);
  1167. }
  1168. return $privileges;
  1169. }
  1170. /**
  1171. * @param array $row Array with user privileges
  1172. *
  1173. * @return array
  1174. */
  1175. private function getSpecificPrivilege(array $row): array
  1176. {
  1177. $privilege = [
  1178. 'type' => $row['Type'],
  1179. 'database' => $row['Db'],
  1180. ];
  1181. if ($row['Type'] === 'r') {
  1182. $privilege['routine'] = $row['Routine_name'];
  1183. $privilege['has_grant'] = str_contains($row['Proc_priv'], 'Grant');
  1184. $privilege['privileges'] = explode(',', $row['Proc_priv']);
  1185. } elseif ($row['Type'] === 't') {
  1186. $privilege['table'] = $row['Table_name'];
  1187. $privilege['has_grant'] = str_contains($row['Table_priv'], 'Grant');
  1188. $tablePrivs = explode(',', $row['Table_priv']);
  1189. $specificPrivileges = [];
  1190. $grantsArr = $this->getTableGrantsArray();
  1191. foreach ($grantsArr as $grant) {
  1192. $specificPrivileges[$grant[0]] = 'N';
  1193. foreach ($tablePrivs as $tablePriv) {
  1194. if ($grant[0] != $tablePriv) {
  1195. continue;
  1196. }
  1197. $specificPrivileges[$grant[0]] = 'Y';
  1198. }
  1199. }
  1200. $privilege['privileges'] = $this->extractPrivInfo($specificPrivileges, true, true);
  1201. } else {
  1202. $privilege['has_grant'] = $row['Grant_priv'] === 'Y';
  1203. $privilege['privileges'] = $this->extractPrivInfo($row, true);
  1204. }
  1205. return $privilege;
  1206. }
  1207. /**
  1208. * @param string $db database name
  1209. *
  1210. * @return array
  1211. */
  1212. private function getGlobalAndDatabasePrivileges(string $db): array
  1213. {
  1214. $listOfPrivileges = '`Select_priv`,
  1215. `Insert_priv`,
  1216. `Update_priv`,
  1217. `Delete_priv`,
  1218. `Create_priv`,
  1219. `Drop_priv`,
  1220. `Grant_priv`,
  1221. `Index_priv`,
  1222. `Alter_priv`,
  1223. `References_priv`,
  1224. `Create_tmp_table_priv`,
  1225. `Lock_tables_priv`,
  1226. `Create_view_priv`,
  1227. `Show_view_priv`,
  1228. `Create_routine_priv`,
  1229. `Alter_routine_priv`,
  1230. `Execute_priv`,
  1231. `Event_priv`,
  1232. `Trigger_priv`,';
  1233. $listOfComparedPrivileges = 'BINARY `Select_priv` = \'N\' AND
  1234. BINARY `Insert_priv` = \'N\' AND
  1235. BINARY `Update_priv` = \'N\' AND
  1236. BINARY `Delete_priv` = \'N\' AND
  1237. BINARY `Create_priv` = \'N\' AND
  1238. BINARY `Drop_priv` = \'N\' AND
  1239. BINARY `Grant_priv` = \'N\' AND
  1240. BINARY `References_priv` = \'N\' AND
  1241. BINARY `Create_tmp_table_priv` = \'N\' AND
  1242. BINARY `Lock_tables_priv` = \'N\' AND
  1243. BINARY `Create_view_priv` = \'N\' AND
  1244. BINARY `Show_view_priv` = \'N\' AND
  1245. BINARY `Create_routine_priv` = \'N\' AND
  1246. BINARY `Alter_routine_priv` = \'N\' AND
  1247. BINARY `Execute_priv` = \'N\' AND
  1248. BINARY `Event_priv` = \'N\' AND
  1249. BINARY `Trigger_priv` = \'N\'';
  1250. $query = '
  1251. (
  1252. SELECT `User`, `Host`, ' . $listOfPrivileges . ' \'*\' AS `Db`, \'g\' AS `Type`
  1253. FROM `mysql`.`user`
  1254. WHERE NOT (' . $listOfComparedPrivileges . ')
  1255. )
  1256. UNION
  1257. (
  1258. SELECT `User`, `Host`, ' . $listOfPrivileges . ' `Db`, \'d\' AS `Type`
  1259. FROM `mysql`.`db`
  1260. WHERE \'' . $this->dbi->escapeString($db) . '\' LIKE `Db` AND NOT (' . $listOfComparedPrivileges . ')
  1261. )
  1262. ORDER BY `User` ASC, `Host` ASC, `Db` ASC;
  1263. ';
  1264. $result = $this->dbi->query($query);
  1265. if ($result === false) {
  1266. return [];
  1267. }
  1268. $privileges = [];
  1269. while ($row = $this->dbi->fetchAssoc($result)) {
  1270. $privileges[] = $row;
  1271. }
  1272. return $privileges;
  1273. }
  1274. /**
  1275. * @param string $db database name
  1276. * @param string $table table name
  1277. *
  1278. * @return array
  1279. */
  1280. private function getTablePrivileges(string $db, string $table): array
  1281. {
  1282. $query = '
  1283. SELECT `User`, `Host`, `Db`, \'t\' AS `Type`, `Table_name`, `Table_priv`
  1284. FROM `mysql`.`tables_priv`
  1285. WHERE
  1286. ? LIKE `Db` AND
  1287. ? LIKE `Table_name` AND
  1288. NOT (`Table_priv` = \'\' AND Column_priv = \'\')
  1289. ORDER BY `User` ASC, `Host` ASC, `Db` ASC, `Table_priv` ASC;
  1290. ';
  1291. /** @var mysqli_stmt|false $statem…

Large files files are truncated, but you can click here to view the full file