More escaping of username and password.
[phpmyadmin.git] / libraries / classes / Server / Privileges.php
bloba62d111606fad667d9d925571f8c16f28b304b7b
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * set of functions with the Privileges section in pma
6 * @package PhpMyAdmin
7 */
8 namespace PhpMyAdmin\Server;
10 use PhpMyAdmin\Core;
11 use PhpMyAdmin\DatabaseInterface;
12 use PhpMyAdmin\Display\ChangePassword;
13 use PhpMyAdmin\Message;
14 use PhpMyAdmin\Relation;
15 use PhpMyAdmin\RelationCleanup;
16 use PhpMyAdmin\Response;
17 use PhpMyAdmin\Template;
18 use PhpMyAdmin\Url;
19 use PhpMyAdmin\Util;
21 /**
22 * Privileges class
24 * @package PhpMyAdmin
26 class Privileges
28 /**
29 * Get Html for User Group Dialog
31 * @param string $username username
32 * @param bool $is_menuswork Is menuswork set in configuration
34 * @return string html
36 public static function getHtmlForUserGroupDialog($username, $is_menuswork)
38 $html = '';
39 if (! empty($_GET['edit_user_group_dialog']) && $is_menuswork) {
40 $dialog = self::getHtmlToChooseUserGroup($username);
41 $response = Response::getInstance();
42 if ($response->isAjax()) {
43 $response->addJSON('message', $dialog);
44 exit;
45 } else {
46 $html .= $dialog;
50 return $html;
53 /**
54 * Escapes wildcard in a database+table specification
55 * before using it in a GRANT statement.
57 * Escaping a wildcard character in a GRANT is only accepted at the global
58 * or database level, not at table level; this is why I remove
59 * the escaping character. Internally, in mysql.tables_priv.Db there are
60 * no escaping (for example test_db) but in mysql.db you'll see test\_db
61 * for a db-specific privilege.
63 * @param string $dbname Database name
64 * @param string $tablename Table name
66 * @return string the escaped (if necessary) database.table
68 public static function wildcardEscapeForGrant($dbname, $tablename)
70 if (strlen($dbname) === 0) {
71 $db_and_table = '*.*';
72 } else {
73 if (strlen($tablename) > 0) {
74 $db_and_table = Util::backquote(
75 Util::unescapeMysqlWildcards($dbname)
77 . '.' . Util::backquote($tablename);
78 } else {
79 $db_and_table = Util::backquote($dbname) . '.*';
82 return $db_and_table;
85 /**
86 * Generates a condition on the user name
88 * @param string $initial the user's initial
90 * @return string the generated condition
92 public static function rangeOfUsers($initial = '')
94 // strtolower() is used because the User field
95 // might be BINARY, so LIKE would be case sensitive
96 if ($initial === null || $initial === '') {
97 return '';
100 $ret = " WHERE `User` LIKE '"
101 . $GLOBALS['dbi']->escapeString($initial) . "%'"
102 . " OR `User` LIKE '"
103 . $GLOBALS['dbi']->escapeString(mb_strtolower($initial))
104 . "%'";
105 return $ret;
106 } // end function
109 * Formats privilege name for a display
111 * @param array $privilege Privilege information
112 * @param boolean $html Whether to use HTML
114 * @return string
116 public static function formatPrivilege(array $privilege, $html)
118 if ($html) {
119 return '<dfn title="' . $privilege[2] . '">'
120 . $privilege[1] . '</dfn>';
123 return $privilege[1];
127 * Parses privileges into an array, it modifies the array
129 * @param array &$row Results row from
131 * @return void
133 public static function fillInTablePrivileges(array &$row)
135 $row1 = $GLOBALS['dbi']->fetchSingleRow(
136 'SHOW COLUMNS FROM `mysql`.`tables_priv` LIKE \'Table_priv\';',
137 'ASSOC'
139 // note: in MySQL 5.0.3 we get "Create View', 'Show view';
140 // the View for Create is spelled with uppercase V
141 // the view for Show is spelled with lowercase v
142 // and there is a space between the words
144 $av_grants = explode(
145 '\',\'',
146 mb_substr(
147 $row1['Type'],
148 mb_strpos($row1['Type'], '(') + 2,
149 mb_strpos($row1['Type'], ')')
150 - mb_strpos($row1['Type'], '(') - 3
154 $users_grants = explode(',', $row['Table_priv']);
156 foreach ($av_grants as $current_grant) {
157 $row[$current_grant . '_priv']
158 = in_array($current_grant, $users_grants) ? 'Y' : 'N';
160 unset($row['Table_priv']);
165 * Extracts the privilege information of a priv table row
167 * @param array|null $row the row
168 * @param boolean $enableHTML add <dfn> tag with tooltips
169 * @param boolean $tablePrivs whether row contains table privileges
171 * @global resource $user_link the database connection
173 * @return array
175 public static function extractPrivInfo($row = null, $enableHTML = false, $tablePrivs = false)
177 if ($tablePrivs) {
178 $grants = self::getTableGrantsArray();
179 } else {
180 $grants = self::getGrantsArray();
183 if (! is_null($row) && isset($row['Table_priv'])) {
184 self::fillInTablePrivileges($row);
187 $privs = array();
188 $allPrivileges = true;
189 foreach ($grants as $current_grant) {
190 if ((! is_null($row) && isset($row[$current_grant[0]]))
191 || (is_null($row) && isset($GLOBALS[$current_grant[0]]))
193 if ((! is_null($row) && $row[$current_grant[0]] == 'Y')
194 || (is_null($row)
195 && ($GLOBALS[$current_grant[0]] == 'Y'
196 || (is_array($GLOBALS[$current_grant[0]])
197 && count($GLOBALS[$current_grant[0]]) == $_REQUEST['column_count']
198 && empty($GLOBALS[$current_grant[0] . '_none']))))
200 $privs[] = self::formatPrivilege($current_grant, $enableHTML);
201 } elseif (! empty($GLOBALS[$current_grant[0]])
202 && is_array($GLOBALS[$current_grant[0]])
203 && empty($GLOBALS[$current_grant[0] . '_none'])
205 // Required for proper escaping of ` (backtick) in a column name
206 $grant_cols = array_map(
207 function($val) {
208 return Util::backquote($val);
210 $GLOBALS[$current_grant[0]]
213 $privs[] = self::formatPrivilege($current_grant, $enableHTML)
214 . ' (' . join(', ', $grant_cols) . ')';
215 } else {
216 $allPrivileges = false;
220 if (empty($privs)) {
221 if ($enableHTML) {
222 $privs[] = '<dfn title="' . __('No privileges.') . '">USAGE</dfn>';
223 } else {
224 $privs[] = 'USAGE';
226 } elseif ($allPrivileges
227 && (! isset($_POST['grant_count']) || count($privs) == $_POST['grant_count'])
229 if ($enableHTML) {
230 $privs = array('<dfn title="'
231 . __('Includes all privileges except GRANT.')
232 . '">ALL PRIVILEGES</dfn>'
234 } else {
235 $privs = array('ALL PRIVILEGES');
238 return $privs;
239 } // end of the 'self::extractPrivInfo()' function
242 * Returns an array of table grants and their descriptions
244 * @return array array of table grants
246 public static function getTableGrantsArray()
248 return array(
249 array(
250 'Delete',
251 'DELETE',
252 $GLOBALS['strPrivDescDelete']
254 array(
255 'Create',
256 'CREATE',
257 $GLOBALS['strPrivDescCreateTbl']
259 array(
260 'Drop',
261 'DROP',
262 $GLOBALS['strPrivDescDropTbl']
264 array(
265 'Index',
266 'INDEX',
267 $GLOBALS['strPrivDescIndex']
269 array(
270 'Alter',
271 'ALTER',
272 $GLOBALS['strPrivDescAlter']
274 array(
275 'Create View',
276 'CREATE_VIEW',
277 $GLOBALS['strPrivDescCreateView']
279 array(
280 'Show view',
281 'SHOW_VIEW',
282 $GLOBALS['strPrivDescShowView']
284 array(
285 'Trigger',
286 'TRIGGER',
287 $GLOBALS['strPrivDescTrigger']
293 * Get the grants array which contains all the privilege types
294 * and relevant grant messages
296 * @return array
298 public static function getGrantsArray()
300 return array(
301 array(
302 'Select_priv',
303 'SELECT',
304 __('Allows reading data.')
306 array(
307 'Insert_priv',
308 'INSERT',
309 __('Allows inserting and replacing data.')
311 array(
312 'Update_priv',
313 'UPDATE',
314 __('Allows changing data.')
316 array(
317 'Delete_priv',
318 'DELETE',
319 __('Allows deleting data.')
321 array(
322 'Create_priv',
323 'CREATE',
324 __('Allows creating new databases and tables.')
326 array(
327 'Drop_priv',
328 'DROP',
329 __('Allows dropping databases and tables.')
331 array(
332 'Reload_priv',
333 'RELOAD',
334 __('Allows reloading server settings and flushing the server\'s caches.')
336 array(
337 'Shutdown_priv',
338 'SHUTDOWN',
339 __('Allows shutting down the server.')
341 array(
342 'Process_priv',
343 'PROCESS',
344 __('Allows viewing processes of all users.')
346 array(
347 'File_priv',
348 'FILE',
349 __('Allows importing data from and exporting data into files.')
351 array(
352 'References_priv',
353 'REFERENCES',
354 __('Has no effect in this MySQL version.')
356 array(
357 'Index_priv',
358 'INDEX',
359 __('Allows creating and dropping indexes.')
361 array(
362 'Alter_priv',
363 'ALTER',
364 __('Allows altering the structure of existing tables.')
366 array(
367 'Show_db_priv',
368 'SHOW DATABASES',
369 __('Gives access to the complete list of databases.')
371 array(
372 'Super_priv',
373 'SUPER',
375 'Allows connecting, even if maximum number of connections '
376 . 'is reached; required for most administrative operations '
377 . 'like setting global variables or killing threads of other users.'
380 array(
381 'Create_tmp_table_priv',
382 'CREATE TEMPORARY TABLES',
383 __('Allows creating temporary tables.')
385 array(
386 'Lock_tables_priv',
387 'LOCK TABLES',
388 __('Allows locking tables for the current thread.')
390 array(
391 'Repl_slave_priv',
392 'REPLICATION SLAVE',
393 __('Needed for the replication slaves.')
395 array(
396 'Repl_client_priv',
397 'REPLICATION CLIENT',
398 __('Allows the user to ask where the slaves / masters are.')
400 array(
401 'Create_view_priv',
402 'CREATE VIEW',
403 __('Allows creating new views.')
405 array(
406 'Event_priv',
407 'EVENT',
408 __('Allows to set up events for the event scheduler.')
410 array(
411 'Trigger_priv',
412 'TRIGGER',
413 __('Allows creating and dropping triggers.')
415 // for table privs:
416 array(
417 'Create View_priv',
418 'CREATE VIEW',
419 __('Allows creating new views.')
421 array(
422 'Show_view_priv',
423 'SHOW VIEW',
424 __('Allows performing SHOW CREATE VIEW queries.')
426 // for table privs:
427 array(
428 'Show view_priv',
429 'SHOW VIEW',
430 __('Allows performing SHOW CREATE VIEW queries.')
432 array(
433 'Delete_history_priv',
434 'DELETE HISTORY',
435 $GLOBALS['strPrivDescDeleteHistoricalRows']
437 array(
438 'Delete versioning rows_priv',
439 'DELETE HISTORY',
440 $GLOBALS['strPrivDescDeleteHistoricalRows']
442 array(
443 'Create_routine_priv',
444 'CREATE ROUTINE',
445 __('Allows creating stored routines.')
447 array(
448 'Alter_routine_priv',
449 'ALTER ROUTINE',
450 __('Allows altering and dropping stored routines.')
452 array(
453 'Create_user_priv',
454 'CREATE USER',
455 __('Allows creating, dropping and renaming user accounts.')
457 array(
458 'Execute_priv',
459 'EXECUTE',
460 __('Allows executing stored routines.')
466 * Displays on which column(s) a table-specific privilege is granted
468 * @param array $columns columns array
469 * @param array $row first row from result or boolean false
470 * @param string $name_for_select privilege types - Select_priv, Insert_priv
471 * Update_priv, References_priv
472 * @param string $priv_for_header privilege for header
473 * @param string $name privilege name: insert, select, update, references
474 * @param string $name_for_dfn name for dfn
475 * @param string $name_for_current name for current
477 * @return string $html_output html snippet
479 public static function getHtmlForColumnPrivileges(array $columns, array $row, $name_for_select,
480 $priv_for_header, $name, $name_for_dfn, $name_for_current
482 $data = array(
483 'columns' => $columns,
484 'row' => $row,
485 'name_for_select' => $name_for_select,
486 'priv_for_header' => $priv_for_header,
487 'name' => $name,
488 'name_for_dfn' => $name_for_dfn,
489 'name_for_current' => $name_for_current
492 $html_output = Template::get('privileges/column_privileges')
493 ->render($data);
495 return $html_output;
496 } // end function
499 * Get sql query for display privileges table
501 * @param string $db the database
502 * @param string $table the table
503 * @param string $username username for database connection
504 * @param string $hostname hostname for database connection
506 * @return string sql query
508 public static function getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname)
510 if ($db == '*') {
511 return "SELECT * FROM `mysql`.`user`"
512 . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username) . "'"
513 . " AND `Host` = '" . $GLOBALS['dbi']->escapeString($hostname) . "';";
514 } elseif ($table == '*') {
515 return "SELECT * FROM `mysql`.`db`"
516 . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username) . "'"
517 . " AND `Host` = '" . $GLOBALS['dbi']->escapeString($hostname) . "'"
518 . " AND '" . $GLOBALS['dbi']->escapeString(Util::unescapeMysqlWildcards($db)) . "'"
519 . " LIKE `Db`;";
521 return "SELECT `Table_priv`"
522 . " FROM `mysql`.`tables_priv`"
523 . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username) . "'"
524 . " AND `Host` = '" . $GLOBALS['dbi']->escapeString($hostname) . "'"
525 . " AND `Db` = '" . $GLOBALS['dbi']->escapeString(Util::unescapeMysqlWildcards($db)) . "'"
526 . " AND `Table_name` = '" . $GLOBALS['dbi']->escapeString($table) . "';";
530 * Displays a dropdown to select the user group
531 * with menu items configured to each of them.
533 * @param string $username username
535 * @return string html to select the user group
537 public static function getHtmlToChooseUserGroup($username)
539 $relation = new Relation();
540 $cfgRelation = $relation->getRelationsParam();
541 $groupTable = Util::backquote($cfgRelation['db'])
542 . "." . Util::backquote($cfgRelation['usergroups']);
543 $userTable = Util::backquote($cfgRelation['db'])
544 . "." . Util::backquote($cfgRelation['users']);
546 $userGroup = '';
547 if (isset($GLOBALS['username'])) {
548 $sql_query = "SELECT `usergroup` FROM " . $userTable
549 . " WHERE `username` = '" . $GLOBALS['dbi']->escapeString($username) . "'";
550 $userGroup = $GLOBALS['dbi']->fetchValue(
551 $sql_query, 0, 0, DatabaseInterface::CONNECT_CONTROL
555 $allUserGroups = array('' => '');
556 $sql_query = "SELECT DISTINCT `usergroup` FROM " . $groupTable;
557 $result = $relation->queryAsControlUser($sql_query, false);
558 if ($result) {
559 while ($row = $GLOBALS['dbi']->fetchRow($result)) {
560 $allUserGroups[$row[0]] = $row[0];
563 $GLOBALS['dbi']->freeResult($result);
565 // render the template
566 $data = array(
567 'all_user_groups' => $allUserGroups,
568 'user_group' => $userGroup,
569 'params' => array('username' => $username)
571 $html_output = Template::get('privileges/choose_user_group')
572 ->render($data);
574 return $html_output;
578 * Sets the user group from request values
580 * @param string $username username
581 * @param string $userGroup user group to set
583 * @return void
585 public static function setUserGroup($username, $userGroup)
587 $relation = new Relation();
588 $cfgRelation = $relation->getRelationsParam();
589 if (empty($cfgRelation['db']) || empty($cfgRelation['users']) || empty($cfgRelation['usergroups'])) {
590 return;
593 $userTable = Util::backquote($cfgRelation['db'])
594 . "." . Util::backquote($cfgRelation['users']);
596 $sql_query = "SELECT `usergroup` FROM " . $userTable
597 . " WHERE `username` = '" . $GLOBALS['dbi']->escapeString($username) . "'";
598 $oldUserGroup = $GLOBALS['dbi']->fetchValue(
599 $sql_query, 0, 0, DatabaseInterface::CONNECT_CONTROL
602 if ($oldUserGroup === false) {
603 $upd_query = "INSERT INTO " . $userTable . "(`username`, `usergroup`)"
604 . " VALUES ('" . $GLOBALS['dbi']->escapeString($username) . "', "
605 . "'" . $GLOBALS['dbi']->escapeString($userGroup) . "')";
606 } else {
607 if (empty($userGroup)) {
608 $upd_query = "DELETE FROM " . $userTable
609 . " WHERE `username`='" . $GLOBALS['dbi']->escapeString($username) . "'";
610 } elseif ($oldUserGroup != $userGroup) {
611 $upd_query = "UPDATE " . $userTable
612 . " SET `usergroup`='" . $GLOBALS['dbi']->escapeString($userGroup) . "'"
613 . " WHERE `username`='" . $GLOBALS['dbi']->escapeString($username) . "'";
616 if (isset($upd_query)) {
617 $relation->queryAsControlUser($upd_query);
622 * Displays the privileges form table
624 * @param string $db the database
625 * @param string $table the table
626 * @param boolean $submit whether to display the submit button or not
628 * @global array $cfg the phpMyAdmin configuration
629 * @global resource $user_link the database connection
631 * @return string html snippet
633 public static function getHtmlToDisplayPrivilegesTable($db = '*',
634 $table = '*', $submit = true
636 $html_output = '';
637 $sql_query = '';
639 if ($db == '*') {
640 $table = '*';
643 if (isset($GLOBALS['username'])) {
644 $username = $GLOBALS['username'];
645 $hostname = $GLOBALS['hostname'];
646 $sql_query = self::getSqlQueryForDisplayPrivTable(
647 $db, $table, $username, $hostname
649 $row = $GLOBALS['dbi']->fetchSingleRow($sql_query);
651 if (empty($row)) {
652 if ($table == '*' && $GLOBALS['dbi']->isSuperuser()) {
653 $row = array();
654 if ($db == '*') {
655 $sql_query = 'SHOW COLUMNS FROM `mysql`.`user`;';
656 } elseif ($table == '*') {
657 $sql_query = 'SHOW COLUMNS FROM `mysql`.`db`;';
659 $res = $GLOBALS['dbi']->query($sql_query);
660 while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
661 if (mb_substr($row1[0], 0, 4) == 'max_') {
662 $row[$row1[0]] = 0;
663 } elseif (mb_substr($row1[0], 0, 5) == 'x509_'
664 || mb_substr($row1[0], 0, 4) == 'ssl_'
666 $row[$row1[0]] = '';
667 } else {
668 $row[$row1[0]] = 'N';
671 $GLOBALS['dbi']->freeResult($res);
672 } elseif ($table == '*') {
673 $row = array();
674 } else {
675 $row = array('Table_priv' => '');
678 if (isset($row['Table_priv'])) {
679 self::fillInTablePrivileges($row);
681 // get columns
682 $res = $GLOBALS['dbi']->tryQuery(
683 'SHOW COLUMNS FROM '
684 . Util::backquote(
685 Util::unescapeMysqlWildcards($db)
687 . '.' . Util::backquote($table) . ';'
689 $columns = array();
690 if ($res) {
691 while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
692 $columns[$row1[0]] = array(
693 'Select' => false,
694 'Insert' => false,
695 'Update' => false,
696 'References' => false
699 $GLOBALS['dbi']->freeResult($res);
701 unset($res, $row1);
703 // table-specific privileges
704 if (! empty($columns)) {
705 $html_output .= self::getHtmlForTableSpecificPrivileges(
706 $username, $hostname, $db, $table, $columns, $row
708 } else {
709 // global or db-specific
710 $html_output .= self::getHtmlForGlobalOrDbSpecificPrivs($db, $table, $row);
712 $html_output .= '</fieldset>' . "\n";
713 if ($submit) {
714 $html_output .= '<fieldset id="fieldset_user_privtable_footer" '
715 . 'class="tblFooters">' . "\n"
716 . '<input type="hidden" name="update_privs" value="1" />' . "\n"
717 . '<input type="submit" value="' . __('Go') . '" />' . "\n"
718 . '</fieldset>' . "\n";
720 return $html_output;
721 } // end of the 'PMA_displayPrivTable()' function
724 * Get HTML for "Require"
726 * @param array $row privilege array
728 * @return string html snippet
730 public static function getHtmlForRequires(array $row)
732 $specified = (isset($row['ssl_type']) && $row['ssl_type'] == 'SPECIFIED');
733 $require_options = array(
734 array(
735 'name' => 'ssl_type',
736 'value' => 'NONE',
737 'description' => __(
738 'Does not require SSL-encrypted connections.'
740 'label' => 'REQUIRE NONE',
741 'checked' => ((isset($row['ssl_type'])
742 && ($row['ssl_type'] == 'NONE'
743 || $row['ssl_type'] == ''))
744 ? 'checked="checked"'
745 : ''
747 'disabled' => false,
748 'radio' => true
750 array(
751 'name' => 'ssl_type',
752 'value' => 'ANY',
753 'description' => __(
754 'Requires SSL-encrypted connections.'
756 'label' => 'REQUIRE SSL',
757 'checked' => (isset($row['ssl_type']) && ($row['ssl_type'] == 'ANY')
758 ? 'checked="checked"'
759 : ''
761 'disabled' => false,
762 'radio' => true
764 array(
765 'name' => 'ssl_type',
766 'value' => 'X509',
767 'description' => __(
768 'Requires a valid X509 certificate.'
770 'label' => 'REQUIRE X509',
771 'checked' => (isset($row['ssl_type']) && ($row['ssl_type'] == 'X509')
772 ? 'checked="checked"'
773 : ''
775 'disabled' => false,
776 'radio' => true
778 array(
779 'name' => 'ssl_type',
780 'value' => 'SPECIFIED',
781 'description' => '',
782 'label' => 'SPECIFIED',
783 'checked' => ($specified ? 'checked="checked"' : ''),
784 'disabled' => false,
785 'radio' => true
787 array(
788 'name' => 'ssl_cipher',
789 'value' => (isset($row['ssl_cipher'])
790 ? htmlspecialchars($row['ssl_cipher']) : ''
792 'description' => __(
793 'Requires that a specific cipher method be used for a connection.'
795 'label' => 'REQUIRE CIPHER',
796 'checked' => '',
797 'disabled' => ! $specified,
798 'radio' => false
800 array(
801 'name' => 'x509_issuer',
802 'value' => (isset($row['x509_issuer'])
803 ? htmlspecialchars($row['x509_issuer']) : ''
805 'description' => __(
806 'Requires that a valid X509 certificate issued by this CA be presented.'
808 'label' => 'REQUIRE ISSUER',
809 'checked' => '',
810 'disabled' => ! $specified,
811 'radio' => false
813 array(
814 'name' => 'x509_subject',
815 'value' => (isset($row['x509_subject'])
816 ? htmlspecialchars($row['x509_subject']) : ''
818 'description' => __(
819 'Requires that a valid X509 certificate with this subject be presented.'
821 'label' => 'REQUIRE SUBJECT',
822 'checked' => '',
823 'disabled' => ! $specified,
824 'radio' => false
828 $html_output = Template::get('privileges/require_options')
829 ->render(array('require_options' => $require_options));
831 return $html_output;
835 * Get HTML for "Resource limits"
837 * @param array $row first row from result or boolean false
839 * @return string html snippet
841 public static function getHtmlForResourceLimits(array $row)
843 $limits = array(
844 array(
845 'input_name' => 'max_questions',
846 'name_main' => 'MAX QUERIES PER HOUR',
847 'value' => (isset($row['max_questions']) ? $row['max_questions'] : '0'),
848 'description' => __(
849 'Limits the number of queries the user may send to the server per hour.'
852 array(
853 'input_name' => 'max_updates',
854 'name_main' => 'MAX UPDATES PER HOUR',
855 'value' => (isset($row['max_updates']) ? $row['max_updates'] : '0'),
856 'description' => __(
857 'Limits the number of commands that change any table '
858 . 'or database the user may execute per hour.'
861 array(
862 'input_name' => 'max_connections',
863 'name_main' => 'MAX CONNECTIONS PER HOUR',
864 'value' => (isset($row['max_connections']) ? $row['max_connections'] : '0'),
865 'description' => __(
866 'Limits the number of new connections the user may open per hour.'
869 array(
870 'input_name' => 'max_user_connections',
871 'name_main' => 'MAX USER_CONNECTIONS',
872 'value' => (isset($row['max_user_connections']) ?
873 $row['max_user_connections'] : '0'),
874 'description' => __(
875 'Limits the number of simultaneous connections '
876 . 'the user may have.'
881 return Template::get('privileges/resource_limits')
882 ->render(array('limits' => $limits));
886 * Get the HTML snippet for routine specific privileges
888 * @param string $username username for database connection
889 * @param string $hostname hostname for database connection
890 * @param string $db the database
891 * @param string $routine the routine
892 * @param string $url_dbname url encoded db name
894 * @return string $html_output
896 public static function getHtmlForRoutineSpecificPrivileges(
897 $username, $hostname, $db, $routine, $url_dbname
899 $header = self::getHtmlHeaderForUserProperties(
900 false, $url_dbname, $db, $username, $hostname,
901 $routine, 'routine'
904 $sql = "SELECT `Proc_priv`"
905 . " FROM `mysql`.`procs_priv`"
906 . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username) . "'"
907 . " AND `Host` = '" . $GLOBALS['dbi']->escapeString($hostname) . "'"
908 . " AND `Db` = '"
909 . $GLOBALS['dbi']->escapeString(Util::unescapeMysqlWildcards($db)) . "'"
910 . " AND `Routine_name` LIKE '" . $GLOBALS['dbi']->escapeString($routine) . "';";
911 $res = $GLOBALS['dbi']->fetchValue($sql);
913 $privs = self::parseProcPriv($res);
915 $routineArray = array(self::getTriggerPrivilegeTable());
916 $privTableNames = array(__('Routine'));
917 $privCheckboxes = self::getHtmlForGlobalPrivTableWithCheckboxes(
918 $routineArray, $privTableNames, $privs
921 $data = array(
922 'username' => $username,
923 'hostname' => $hostname,
924 'database' => $db,
925 'routine' => $routine,
926 'grant_count' => count($privs),
927 'priv_checkboxes' => $privCheckboxes,
928 'header' => $header,
930 $html_output = Template::get('privileges/edit_routine_privileges')
931 ->render($data);
933 return $html_output;
937 * Get routine privilege table as an array
939 * @return privilege type array
941 public static function getTriggerPrivilegeTable()
943 $routinePrivTable = array(
944 array(
945 'Grant',
946 'GRANT',
948 'Allows user to give to other users or remove from other users '
949 . 'privileges that user possess on this routine.'
952 array(
953 'Alter_routine',
954 'ALTER ROUTINE',
955 __('Allows altering and dropping this routine.')
957 array(
958 'Execute',
959 'EXECUTE',
960 __('Allows executing this routine.')
963 return $routinePrivTable;
967 * Get the HTML snippet for table specific privileges
969 * @param string $username username for database connection
970 * @param string $hostname hostname for database connection
971 * @param string $db the database
972 * @param string $table the table
973 * @param array $columns columns array
974 * @param array $row current privileges row
976 * @return string $html_output
978 public static function getHtmlForTableSpecificPrivileges(
979 $username, $hostname, $db, $table, array $columns, array $row
981 $res = $GLOBALS['dbi']->query(
982 'SELECT `Column_name`, `Column_priv`'
983 . ' FROM `mysql`.`columns_priv`'
984 . ' WHERE `User`'
985 . ' = \'' . $GLOBALS['dbi']->escapeString($username) . "'"
986 . ' AND `Host`'
987 . ' = \'' . $GLOBALS['dbi']->escapeString($hostname) . "'"
988 . ' AND `Db`'
989 . ' = \'' . $GLOBALS['dbi']->escapeString(
990 Util::unescapeMysqlWildcards($db)
991 ) . "'"
992 . ' AND `Table_name`'
993 . ' = \'' . $GLOBALS['dbi']->escapeString($table) . '\';'
996 while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
997 $row1[1] = explode(',', $row1[1]);
998 foreach ($row1[1] as $current) {
999 $columns[$row1[0]][$current] = true;
1002 $GLOBALS['dbi']->freeResult($res);
1003 unset($res, $row1, $current);
1005 $html_output = '<input type="hidden" name="grant_count" '
1006 . 'value="' . count($row) . '" />' . "\n"
1007 . '<input type="hidden" name="column_count" '
1008 . 'value="' . count($columns) . '" />' . "\n"
1009 . '<fieldset id="fieldset_user_priv">' . "\n"
1010 . '<legend data-submenu-label="' . __('Table') . '">' . __('Table-specific privileges')
1011 . '</legend>'
1012 . '<p><small><i>'
1013 . __('Note: MySQL privilege names are expressed in English.')
1014 . '</i></small></p>';
1016 // privs that are attached to a specific column
1017 $html_output .= self::getHtmlForAttachedPrivilegesToTableSpecificColumn(
1018 $columns, $row
1021 // privs that are not attached to a specific column
1022 $html_output .= '<div class="item">' . "\n"
1023 . self::getHtmlForNotAttachedPrivilegesToTableSpecificColumn($row)
1024 . '</div>' . "\n";
1026 // for Safari 2.0.2
1027 $html_output .= '<div class="clearfloat"></div>' . "\n";
1029 return $html_output;
1033 * Get HTML snippet for privileges that are attached to a specific column
1035 * @param array $columns columns array
1036 * @param array $row first row from result or boolean false
1038 * @return string $html_output
1040 public static function getHtmlForAttachedPrivilegesToTableSpecificColumn(array $columns, array $row)
1042 $html_output = self::getHtmlForColumnPrivileges(
1043 $columns, $row, 'Select_priv', 'SELECT',
1044 'select', __('Allows reading data.'), 'Select'
1047 $html_output .= self::getHtmlForColumnPrivileges(
1048 $columns, $row, 'Insert_priv', 'INSERT',
1049 'insert', __('Allows inserting and replacing data.'), 'Insert'
1052 $html_output .= self::getHtmlForColumnPrivileges(
1053 $columns, $row, 'Update_priv', 'UPDATE',
1054 'update', __('Allows changing data.'), 'Update'
1057 $html_output .= self::getHtmlForColumnPrivileges(
1058 $columns, $row, 'References_priv', 'REFERENCES', 'references',
1059 __('Has no effect in this MySQL version.'), 'References'
1061 return $html_output;
1065 * Get HTML for privileges that are not attached to a specific column
1067 * @param array $row first row from result or boolean false
1069 * @return string $html_output
1071 public static function getHtmlForNotAttachedPrivilegesToTableSpecificColumn(array $row)
1073 $html_output = '';
1075 foreach ($row as $current_grant => $current_grant_value) {
1076 $grant_type = substr($current_grant, 0, -5);
1077 if (in_array($grant_type, array('Select', 'Insert', 'Update', 'References'))
1079 continue;
1081 // make a substitution to match the messages variables;
1082 // also we must substitute the grant we get, because we can't generate
1083 // a form variable containing blanks (those would get changed to
1084 // an underscore when receiving the POST)
1085 if ($current_grant == 'Create View_priv') {
1086 $tmp_current_grant = 'CreateView_priv';
1087 $current_grant = 'Create_view_priv';
1088 } elseif ($current_grant == 'Show view_priv') {
1089 $tmp_current_grant = 'ShowView_priv';
1090 $current_grant = 'Show_view_priv';
1091 } elseif ($current_grant == 'Delete versioning rows_priv') {
1092 $tmp_current_grant = 'DeleteHistoricalRows_priv';
1093 $current_grant = 'Delete_history_priv';
1094 } else {
1095 $tmp_current_grant = $current_grant;
1098 $html_output .= '<div class="item">' . "\n"
1099 . '<input type="checkbox"'
1100 . ' name="' . $current_grant . '" id="checkbox_' . $current_grant
1101 . '" value="Y" '
1102 . ($current_grant_value == 'Y' ? 'checked="checked" ' : '')
1103 . 'title="';
1105 $privGlobalName = 'strPrivDesc'
1106 . mb_substr(
1107 $tmp_current_grant,
1109 (mb_strlen($tmp_current_grant) - 5)
1111 $html_output .= (isset($GLOBALS[$privGlobalName])
1112 ? $GLOBALS[$privGlobalName]
1113 : $GLOBALS[$privGlobalName . 'Tbl']
1115 . '"/>' . "\n";
1117 $privGlobalName1 = 'strPrivDesc'
1118 . mb_substr(
1119 $tmp_current_grant,
1123 $html_output .= '<label for="checkbox_' . $current_grant
1124 . '"><code><dfn title="'
1125 . (isset($GLOBALS[$privGlobalName1])
1126 ? $GLOBALS[$privGlobalName1]
1127 : $GLOBALS[$privGlobalName1 . 'Tbl']
1129 . '">'
1130 . mb_strtoupper(
1131 mb_substr(
1132 $current_grant,
1137 . '</dfn></code></label>' . "\n"
1138 . '</div>' . "\n";
1139 } // end foreach ()
1140 return $html_output;
1144 * Get HTML for global or database specific privileges
1146 * @param string $db the database
1147 * @param string $table the table
1148 * @param array $row first row from result or boolean false
1150 * @return string $html_output
1152 public static function getHtmlForGlobalOrDbSpecificPrivs($db, $table, array $row)
1154 $privTable_names = array(0 => __('Data'),
1155 1 => __('Structure'),
1156 2 => __('Administration')
1158 $privTable = array();
1159 // d a t a
1160 $privTable[0] = self::getDataPrivilegeTable($db);
1162 // s t r u c t u r e
1163 $privTable[1] = self::getStructurePrivilegeTable($table, $row);
1165 // a d m i n i s t r a t i o n
1166 $privTable[2] = self::getAdministrationPrivilegeTable($db);
1168 $html_output = '<input type="hidden" name="grant_count" value="'
1169 . (count($privTable[0])
1170 + count($privTable[1])
1171 + count($privTable[2])
1172 - (isset($row['Grant_priv']) ? 1 : 0)
1174 . '" />';
1175 if ($db == '*') {
1176 $legend = __('Global privileges');
1177 $menu_label = __('Global');
1178 } elseif ($table == '*') {
1179 $legend = __('Database-specific privileges');
1180 $menu_label = __('Database');
1181 } else {
1182 $legend = __('Table-specific privileges');
1183 $menu_label = __('Table');
1185 $html_output .= '<fieldset id="fieldset_user_global_rights">'
1186 . '<legend data-submenu-label="' . $menu_label . '">' . $legend
1187 . '<input type="checkbox" id="addUsersForm_checkall" '
1188 . 'class="checkall_box" title="' . __('Check all') . '" /> '
1189 . '<label for="addUsersForm_checkall">' . __('Check all') . '</label> '
1190 . '</legend>'
1191 . '<p><small><i>'
1192 . __('Note: MySQL privilege names are expressed in English.')
1193 . '</i></small></p>';
1195 // Output the Global privilege tables with checkboxes
1196 $html_output .= self::getHtmlForGlobalPrivTableWithCheckboxes(
1197 $privTable, $privTable_names, $row
1200 // The "Resource limits" box is not displayed for db-specific privs
1201 if ($db == '*') {
1202 $html_output .= self::getHtmlForResourceLimits($row);
1203 $html_output .= self::getHtmlForRequires($row);
1205 // for Safari 2.0.2
1206 $html_output .= '<div class="clearfloat"></div>';
1208 return $html_output;
1212 * Get data privilege table as an array
1214 * @param string $db the database
1216 * @return string data privilege table
1218 public static function getDataPrivilegeTable($db)
1220 $data_privTable = array(
1221 array('Select', 'SELECT', __('Allows reading data.')),
1222 array('Insert', 'INSERT', __('Allows inserting and replacing data.')),
1223 array('Update', 'UPDATE', __('Allows changing data.')),
1224 array('Delete', 'DELETE', __('Allows deleting data.'))
1226 if ($db == '*') {
1227 $data_privTable[]
1228 = array('File',
1229 'FILE',
1230 __('Allows importing data from and exporting data into files.')
1233 return $data_privTable;
1237 * Get structure privilege table as an array
1239 * @param string $table the table
1240 * @param array $row first row from result or boolean false
1242 * @return string structure privilege table
1244 public static function getStructurePrivilegeTable($table, array $row)
1246 $structure_privTable = array(
1247 array('Create',
1248 'CREATE',
1249 ($table == '*'
1250 ? __('Allows creating new databases and tables.')
1251 : __('Allows creating new tables.')
1254 array('Alter',
1255 'ALTER',
1256 __('Allows altering the structure of existing tables.')
1258 array('Index', 'INDEX', __('Allows creating and dropping indexes.')),
1259 array('Drop',
1260 'DROP',
1261 ($table == '*'
1262 ? __('Allows dropping databases and tables.')
1263 : __('Allows dropping tables.')
1266 array('Create_tmp_table',
1267 'CREATE TEMPORARY TABLES',
1268 __('Allows creating temporary tables.')
1270 array('Show_view',
1271 'SHOW VIEW',
1272 __('Allows performing SHOW CREATE VIEW queries.')
1274 array('Create_routine',
1275 'CREATE ROUTINE',
1276 __('Allows creating stored routines.')
1278 array('Alter_routine',
1279 'ALTER ROUTINE',
1280 __('Allows altering and dropping stored routines.')
1282 array('Execute', 'EXECUTE', __('Allows executing stored routines.')),
1284 // this one is for a db-specific priv: Create_view_priv
1285 if (isset($row['Create_view_priv'])) {
1286 $structure_privTable[] = array('Create_view',
1287 'CREATE VIEW',
1288 __('Allows creating new views.')
1291 // this one is for a table-specific priv: Create View_priv
1292 if (isset($row['Create View_priv'])) {
1293 $structure_privTable[] = array('Create View',
1294 'CREATE VIEW',
1295 __('Allows creating new views.')
1298 if (isset($row['Event_priv'])) {
1299 // MySQL 5.1.6
1300 $structure_privTable[] = array('Event',
1301 'EVENT',
1302 __('Allows to set up events for the event scheduler.')
1304 $structure_privTable[] = array('Trigger',
1305 'TRIGGER',
1306 __('Allows creating and dropping triggers.')
1309 return $structure_privTable;
1313 * Get administration privilege table as an array
1315 * @param string $db the table
1317 * @return string administration privilege table
1319 public static function getAdministrationPrivilegeTable($db)
1321 if ($db == '*') {
1322 $adminPrivTable = array(
1323 array('Grant',
1324 'GRANT',
1326 'Allows adding users and privileges '
1327 . 'without reloading the privilege tables.'
1331 $adminPrivTable[] = array('Super',
1332 'SUPER',
1334 'Allows connecting, even if maximum number '
1335 . 'of connections is reached; required for '
1336 . 'most administrative operations like '
1337 . 'setting global variables or killing threads of other users.'
1340 $adminPrivTable[] = array('Process',
1341 'PROCESS',
1342 __('Allows viewing processes of all users.')
1344 $adminPrivTable[] = array('Reload',
1345 'RELOAD',
1346 __('Allows reloading server settings and flushing the server\'s caches.')
1348 $adminPrivTable[] = array('Shutdown',
1349 'SHUTDOWN',
1350 __('Allows shutting down the server.')
1352 $adminPrivTable[] = array('Show_db',
1353 'SHOW DATABASES',
1354 __('Gives access to the complete list of databases.')
1357 else {
1358 $adminPrivTable = array(
1359 array('Grant',
1360 'GRANT',
1362 'Allows user to give to other users or remove from other'
1363 . ' users the privileges that user possess yourself.'
1368 $adminPrivTable[] = array('Lock_tables',
1369 'LOCK TABLES',
1370 __('Allows locking tables for the current thread.')
1372 $adminPrivTable[] = array('References',
1373 'REFERENCES',
1374 __('Has no effect in this MySQL version.')
1376 if ($db == '*') {
1377 $adminPrivTable[] = array('Repl_client',
1378 'REPLICATION CLIENT',
1379 __('Allows the user to ask where the slaves / masters are.')
1381 $adminPrivTable[] = array('Repl_slave',
1382 'REPLICATION SLAVE',
1383 __('Needed for the replication slaves.')
1385 $adminPrivTable[] = array('Create_user',
1386 'CREATE USER',
1387 __('Allows creating, dropping and renaming user accounts.')
1390 return $adminPrivTable;
1394 * Get HTML snippet for global privileges table with check boxes
1396 * @param array $privTable privileges table array
1397 * @param array $privTableNames names of the privilege tables
1398 * (Data, Structure, Administration)
1399 * @param array $row first row from result or boolean false
1401 * @return string $html_output
1403 public static function getHtmlForGlobalPrivTableWithCheckboxes(
1404 array $privTable, array $privTableNames, array $row
1406 return Template::get('privileges/global_priv_table')->render(array(
1407 'priv_table' => $privTable,
1408 'priv_table_names' => $privTableNames,
1409 'row' => $row,
1414 * Gets the currently active authentication plugins
1416 * @param string $orig_auth_plugin Default Authentication plugin
1417 * @param string $mode are we creating a new user or are we just
1418 * changing one?
1419 * (allowed values: 'new', 'edit', 'change_pw')
1420 * @param string $versions Is MySQL version newer or older than 5.5.7
1422 * @return string $html_output
1424 public static function getHtmlForAuthPluginsDropdown(
1425 $orig_auth_plugin,
1426 $mode = 'new',
1427 $versions = 'new'
1429 $select_id = 'select_authentication_plugin'
1430 . ($mode =='change_pw' ? '_cp' : '');
1432 if ($versions == 'new') {
1433 $active_auth_plugins = self::getActiveAuthPlugins();
1435 if (isset($active_auth_plugins['mysql_old_password'])) {
1436 unset($active_auth_plugins['mysql_old_password']);
1438 } else {
1439 $active_auth_plugins = array(
1440 'mysql_native_password' => __('Native MySQL authentication')
1444 $html_output = Util::getDropdown(
1445 'authentication_plugin',
1446 $active_auth_plugins,
1447 $orig_auth_plugin,
1448 $select_id
1451 return $html_output;
1455 * Gets the currently active authentication plugins
1457 * @return array $result array of plugin names and descriptions
1459 public static function getActiveAuthPlugins()
1461 $get_plugins_query = "SELECT `PLUGIN_NAME`, `PLUGIN_DESCRIPTION`"
1462 . " FROM `information_schema`.`PLUGINS` "
1463 . "WHERE `PLUGIN_TYPE` = 'AUTHENTICATION';";
1464 $resultset = $GLOBALS['dbi']->query($get_plugins_query);
1466 $result = array();
1468 while ($row = $GLOBALS['dbi']->fetchAssoc($resultset)) {
1469 // if description is known, enable its translation
1470 if ('mysql_native_password' == $row['PLUGIN_NAME']) {
1471 $row['PLUGIN_DESCRIPTION'] = __('Native MySQL authentication');
1472 } elseif ('sha256_password' == $row['PLUGIN_NAME']) {
1473 $row['PLUGIN_DESCRIPTION'] = __('SHA256 password authentication');
1476 $result[$row['PLUGIN_NAME']] = $row['PLUGIN_DESCRIPTION'];
1479 return $result;
1483 * Displays the fields used by the "new user" form as well as the
1484 * "change login information / copy user" form.
1486 * @param string $mode are we creating a new user or are we just
1487 * changing one? (allowed values: 'new', 'change')
1488 * @param string $username User name
1489 * @param string $hostname Host name
1491 * @global array $cfg the phpMyAdmin configuration
1492 * @global resource $user_link the database connection
1494 * @return string $html_output a HTML snippet
1496 public static function getHtmlForLoginInformationFields(
1497 $mode = 'new',
1498 $username = null,
1499 $hostname = null
1501 list($username_length, $hostname_length) = self::getUsernameAndHostnameLength();
1503 if (isset($GLOBALS['username']) && strlen($GLOBALS['username']) === 0) {
1504 $GLOBALS['pred_username'] = 'any';
1506 $html_output = '<fieldset id="fieldset_add_user_login">' . "\n"
1507 . '<legend>' . __('Login Information') . '</legend>' . "\n"
1508 . '<div class="item">' . "\n"
1509 . '<label for="select_pred_username">' . "\n"
1510 . ' ' . __('User name:') . "\n"
1511 . '</label>' . "\n"
1512 . '<span class="options">' . "\n";
1514 $html_output .= '<select name="pred_username" id="select_pred_username" '
1515 . 'title="' . __('User name') . '">' . "\n";
1517 $html_output .= '<option value="any"'
1518 . ((isset($GLOBALS['pred_username']) && $GLOBALS['pred_username'] == 'any')
1519 ? ' selected="selected"'
1520 : '') . '>'
1521 . __('Any user')
1522 . '</option>' . "\n";
1524 $html_output .= '<option value="userdefined"'
1525 . ((! isset($GLOBALS['pred_username'])
1526 || $GLOBALS['pred_username'] == 'userdefined'
1528 ? ' selected="selected"'
1529 : '') . '>'
1530 . __('Use text field')
1531 . ':</option>' . "\n";
1533 $html_output .= '</select>' . "\n"
1534 . '</span>' . "\n";
1536 $html_output .= '<input type="text" name="username" id="pma_username" class="autofocus"'
1537 . ' maxlength="' . $username_length . '" title="' . __('User name') . '"'
1538 . (empty($GLOBALS['username'])
1539 ? ''
1540 : ' value="' . htmlspecialchars(
1541 isset($GLOBALS['new_username'])
1542 ? $GLOBALS['new_username']
1543 : $GLOBALS['username']
1544 ) . '"'
1546 . ((! isset($GLOBALS['pred_username'])
1547 || $GLOBALS['pred_username'] == 'userdefined'
1549 ? 'required="required"'
1550 : '') . ' />' . "\n";
1552 $html_output .= '<div id="user_exists_warning"'
1553 . ' name="user_exists_warning" class="hide">'
1554 . Message::notice(
1556 'An account already exists with the same username '
1557 . 'but possibly a different hostname.'
1559 )->getDisplay()
1560 . '</div>';
1561 $html_output .= '</div>';
1563 $html_output .= '<div class="item">' . "\n"
1564 . '<label for="select_pred_hostname">' . "\n"
1565 . ' ' . __('Host name:') . "\n"
1566 . '</label>' . "\n";
1568 $html_output .= '<span class="options">' . "\n"
1569 . ' <select name="pred_hostname" id="select_pred_hostname" '
1570 . 'title="' . __('Host name') . '"' . "\n";
1571 $_current_user = $GLOBALS['dbi']->fetchValue('SELECT USER();');
1572 if (! empty($_current_user)) {
1573 $thishost = str_replace(
1574 "'",
1576 mb_substr(
1577 $_current_user,
1578 (mb_strrpos($_current_user, '@') + 1)
1581 if ($thishost != 'localhost' && $thishost != '127.0.0.1') {
1582 $html_output .= ' data-thishost="' . htmlspecialchars($thishost) . '" ';
1583 } else {
1584 unset($thishost);
1587 $html_output .= '>' . "\n";
1588 unset($_current_user);
1590 // when we start editing a user, $GLOBALS['pred_hostname'] is not defined
1591 if (! isset($GLOBALS['pred_hostname']) && isset($GLOBALS['hostname'])) {
1592 switch (mb_strtolower($GLOBALS['hostname'])) {
1593 case 'localhost':
1594 case '127.0.0.1':
1595 $GLOBALS['pred_hostname'] = 'localhost';
1596 break;
1597 case '%':
1598 $GLOBALS['pred_hostname'] = 'any';
1599 break;
1600 default:
1601 $GLOBALS['pred_hostname'] = 'userdefined';
1602 break;
1605 $html_output .= '<option value="any"'
1606 . ((isset($GLOBALS['pred_hostname'])
1607 && $GLOBALS['pred_hostname'] == 'any'
1609 ? ' selected="selected"'
1610 : '') . '>'
1611 . __('Any host')
1612 . '</option>' . "\n"
1613 . '<option value="localhost"'
1614 . ((isset($GLOBALS['pred_hostname'])
1615 && $GLOBALS['pred_hostname'] == 'localhost'
1617 ? ' selected="selected"'
1618 : '') . '>'
1619 . __('Local')
1620 . '</option>' . "\n";
1621 if (! empty($thishost)) {
1622 $html_output .= '<option value="thishost"'
1623 . ((isset($GLOBALS['pred_hostname'])
1624 && $GLOBALS['pred_hostname'] == 'thishost'
1626 ? ' selected="selected"'
1627 : '') . '>'
1628 . __('This Host')
1629 . '</option>' . "\n";
1631 unset($thishost);
1632 $html_output .= '<option value="hosttable"'
1633 . ((isset($GLOBALS['pred_hostname'])
1634 && $GLOBALS['pred_hostname'] == 'hosttable'
1636 ? ' selected="selected"'
1637 : '') . '>'
1638 . __('Use Host Table')
1639 . '</option>' . "\n";
1641 $html_output .= '<option value="userdefined"'
1642 . ((isset($GLOBALS['pred_hostname'])
1643 && $GLOBALS['pred_hostname'] == 'userdefined'
1645 ? ' selected="selected"'
1646 : '') . '>'
1647 . __('Use text field:') . '</option>' . "\n"
1648 . '</select>' . "\n"
1649 . '</span>' . "\n";
1651 $html_output .= '<input type="text" name="hostname" id="pma_hostname" maxlength="'
1652 . $hostname_length . '" value="'
1653 // use default value of '%' to match with the default 'Any host'
1654 . htmlspecialchars(isset($GLOBALS['hostname']) ? $GLOBALS['hostname'] : '%')
1655 . '" title="' . __('Host name') . '" '
1656 . ((isset($GLOBALS['pred_hostname'])
1657 && $GLOBALS['pred_hostname'] == 'userdefined'
1659 ? 'required="required"'
1660 : '')
1661 . ' />' . "\n"
1662 . Util::showHint(
1664 'When Host table is used, this field is ignored '
1665 . 'and values stored in Host table are used instead.'
1668 . '</div>' . "\n";
1670 $html_output .= '<div class="item">' . "\n"
1671 . '<label for="select_pred_password">' . "\n"
1672 . ' ' . __('Password:') . "\n"
1673 . '</label>' . "\n"
1674 . '<span class="options">' . "\n"
1675 . '<select name="pred_password" id="select_pred_password" title="'
1676 . __('Password') . '">' . "\n"
1677 . ($mode == 'change' ? '<option value="keep" selected="selected">'
1678 . __('Do not change the password')
1679 . '</option>' . "\n" : '')
1680 . '<option value="none"';
1682 if (isset($GLOBALS['username']) && $mode != 'change') {
1683 $html_output .= ' selected="selected"';
1685 $html_output .= '>' . __('No Password') . '</option>' . "\n"
1686 . '<option value="userdefined"'
1687 . (isset($GLOBALS['username']) ? '' : ' selected="selected"') . '>'
1688 . __('Use text field')
1689 . ':</option>' . "\n"
1690 . '</select>' . "\n"
1691 . '</span>' . "\n"
1692 . '<input type="password" id="text_pma_pw" name="pma_pw" '
1693 . 'title="' . __('Password') . '" '
1694 . (isset($GLOBALS['username']) ? '' : 'required="required"')
1695 . '/>' . "\n"
1696 . '<span>Strength:</span> '
1697 . '<meter max="4" id="password_strength_meter" name="pw_meter"></meter> '
1698 . '<span id="password_strength" name="pw_strength"></span>' . "\n"
1699 . '</div>' . "\n";
1701 $html_output .= '<div class="item" '
1702 . 'id="div_element_before_generate_password">' . "\n"
1703 . '<label for="text_pma_pw2">' . "\n"
1704 . ' ' . __('Re-type:') . "\n"
1705 . '</label>' . "\n"
1706 . '<span class="options">&nbsp;</span>' . "\n"
1707 . '<input type="password" name="pma_pw2" id="text_pma_pw2" '
1708 . 'title="' . __('Re-type') . '" '
1709 . (isset($GLOBALS['username']) ? '' : 'required="required"')
1710 . '/>' . "\n"
1711 . '</div>' . "\n"
1712 . '<div class="item" id="authentication_plugin_div">'
1713 . '<label for="select_authentication_plugin" >';
1715 $serverType = Util::getServerType();
1716 $serverVersion = $GLOBALS['dbi']->getVersion();
1717 $orig_auth_plugin = self::getCurrentAuthenticationPlugin(
1718 $mode,
1719 $username,
1720 $hostname
1723 if (($serverType == 'MySQL'
1724 && $serverVersion >= 50507)
1725 || ($serverType == 'MariaDB'
1726 && $serverVersion >= 50200)
1728 $html_output .= __('Authentication Plugin')
1729 . '</label><span class="options">&nbsp;</span>' . "\n";
1731 $auth_plugin_dropdown = self::getHtmlForAuthPluginsDropdown(
1732 $orig_auth_plugin, $mode, 'new'
1734 } else {
1735 $html_output .= __('Password Hashing Method')
1736 . '</label><span class="options">&nbsp;</span>' . "\n";
1737 $auth_plugin_dropdown = self::getHtmlForAuthPluginsDropdown(
1738 $orig_auth_plugin, $mode, 'old'
1741 $html_output .= $auth_plugin_dropdown;
1743 $html_output .= '<div'
1744 . ($orig_auth_plugin != 'sha256_password' ? ' class="hide"' : '')
1745 . ' id="ssl_reqd_warning">'
1746 . Message::notice(
1748 'This method requires using an \'<i>SSL connection</i>\' '
1749 . 'or an \'<i>unencrypted connection that encrypts the password '
1750 . 'using RSA</i>\'; while connecting to the server.'
1752 . Util::showMySQLDocu('sha256-authentication-plugin')
1754 ->getDisplay()
1755 . '</div>';
1757 $html_output .= '</div>' . "\n"
1758 // Generate password added here via jQuery
1759 . '</fieldset>' . "\n";
1761 return $html_output;
1762 } // end of the 'self::getHtmlForLoginInformationFields()' function
1765 * Get username and hostname length
1767 * @return array username length and hostname length
1769 public static function getUsernameAndHostnameLength()
1771 /* Fallback values */
1772 $username_length = 16;
1773 $hostname_length = 41;
1775 /* Try to get real lengths from the database */
1776 $fields_info = $GLOBALS['dbi']->fetchResult(
1777 'SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH '
1778 . 'FROM information_schema.columns '
1779 . "WHERE table_schema = 'mysql' AND table_name = 'user' "
1780 . "AND COLUMN_NAME IN ('User', 'Host')"
1782 foreach ($fields_info as $val) {
1783 if ($val['COLUMN_NAME'] == 'User') {
1784 $username_length = $val['CHARACTER_MAXIMUM_LENGTH'];
1785 } elseif ($val['COLUMN_NAME'] == 'Host') {
1786 $hostname_length = $val['CHARACTER_MAXIMUM_LENGTH'];
1789 return array($username_length, $hostname_length);
1793 * Get current authentication plugin in use - for a user or globally
1795 * @param string $mode are we creating a new user or are we just
1796 * changing one? (allowed values: 'new', 'change')
1797 * @param string $username User name
1798 * @param string $hostname Host name
1800 * @return string authentication plugin in use
1802 public static function getCurrentAuthenticationPlugin(
1803 $mode = 'new',
1804 $username = null,
1805 $hostname = null
1807 /* Fallback (standard) value */
1808 $authentication_plugin = 'mysql_native_password';
1809 $serverVersion = $GLOBALS['dbi']->getVersion();
1811 if (isset($username) && isset($hostname)
1812 && $mode == 'change'
1814 $row = $GLOBALS['dbi']->fetchSingleRow(
1815 'SELECT `plugin` FROM `mysql`.`user` WHERE `User` = "'
1816 . $GLOBALS['dbi']->escapeString($username)
1817 . '" AND `Host` = "'
1818 . $GLOBALS['dbi']->escapeString($hostname)
1819 . '" LIMIT 1'
1821 // Table 'mysql'.'user' may not exist for some previous
1822 // versions of MySQL - in that case consider fallback value
1823 if (isset($row) && $row) {
1824 $authentication_plugin = $row['plugin'];
1826 } elseif ($mode == 'change') {
1827 list($username, $hostname) = $GLOBALS['dbi']->getCurrentUserAndHost();
1829 $row = $GLOBALS['dbi']->fetchSingleRow(
1830 'SELECT `plugin` FROM `mysql`.`user` WHERE `User` = "'
1831 . $GLOBALS['dbi']->escapeString($username)
1832 . '" AND `Host` = "'
1833 . $GLOBALS['dbi']->escapeString($hostname)
1834 . '"'
1836 if (isset($row) && $row && ! empty($row['plugin'])) {
1837 $authentication_plugin = $row['plugin'];
1839 } elseif ($serverVersion >= 50702) {
1840 $row = $GLOBALS['dbi']->fetchSingleRow(
1841 'SELECT @@default_authentication_plugin'
1843 $authentication_plugin = is_array($row) ? $row['@@default_authentication_plugin'] : null;
1846 return $authentication_plugin;
1850 * Returns all the grants for a certain user on a certain host
1851 * Used in the export privileges for all users section
1853 * @param string $user User name
1854 * @param string $host Host name
1856 * @return string containing all the grants text
1858 public static function getGrants($user, $host)
1860 $grants = $GLOBALS['dbi']->fetchResult(
1861 "SHOW GRANTS FOR '"
1862 . $GLOBALS['dbi']->escapeString($user) . "'@'"
1863 . $GLOBALS['dbi']->escapeString($host) . "'"
1865 $response = '';
1866 foreach ($grants as $one_grant) {
1867 $response .= $one_grant . ";\n\n";
1869 return $response;
1870 } // end of the 'self::getGrants()' function
1873 * Update password and get message for password updating
1875 * @param string $err_url error url
1876 * @param string $username username
1877 * @param string $hostname hostname
1879 * @return string $message success or error message after updating password
1881 public static function updatePassword($err_url, $username, $hostname)
1883 // similar logic in user_password.php
1884 $message = '';
1886 if (empty($_POST['nopass'])
1887 && isset($_POST['pma_pw'])
1888 && isset($_POST['pma_pw2'])
1890 if ($_POST['pma_pw'] != $_POST['pma_pw2']) {
1891 $message = Message::error(__('The passwords aren\'t the same!'));
1892 } elseif (empty($_POST['pma_pw']) || empty($_POST['pma_pw2'])) {
1893 $message = Message::error(__('The password is empty!'));
1897 // here $nopass could be == 1
1898 if (empty($message)) {
1899 $hashing_function = 'PASSWORD';
1900 $serverType = Util::getServerType();
1901 $serverVersion = $GLOBALS['dbi']->getVersion();
1902 $authentication_plugin
1903 = (isset($_POST['authentication_plugin'])
1904 ? $_POST['authentication_plugin']
1905 : self::getCurrentAuthenticationPlugin(
1906 'change',
1907 $username,
1908 $hostname
1911 // Use 'ALTER USER ...' syntax for MySQL 5.7.6+
1912 if ($serverType == 'MySQL'
1913 && $serverVersion >= 50706
1915 if ($authentication_plugin != 'mysql_old_password') {
1916 $query_prefix = "ALTER USER '"
1917 . $GLOBALS['dbi']->escapeString($username)
1918 . "'@'" . $GLOBALS['dbi']->escapeString($hostname) . "'"
1919 . " IDENTIFIED WITH "
1920 . $authentication_plugin
1921 . " BY '";
1922 } else {
1923 $query_prefix = "ALTER USER '"
1924 . $GLOBALS['dbi']->escapeString($username)
1925 . "'@'" . $GLOBALS['dbi']->escapeString($hostname) . "'"
1926 . " IDENTIFIED BY '";
1929 // in $sql_query which will be displayed, hide the password
1930 $sql_query = $query_prefix . "*'";
1932 $local_query = $query_prefix
1933 . $GLOBALS['dbi']->escapeString($_POST['pma_pw']) . "'";
1934 } elseif ($serverType == 'MariaDB' && $serverVersion >= 10000) {
1935 // MariaDB uses "SET PASSWORD" syntax to change user password.
1936 // On Galera cluster only DDL queries are replicated, since
1937 // users are stored in MyISAM storage engine.
1938 $query_prefix = "SET PASSWORD FOR '"
1939 . $GLOBALS['dbi']->escapeString($username)
1940 . "'@'" . $GLOBALS['dbi']->escapeString($hostname) . "'"
1941 . " = PASSWORD ('";
1942 $sql_query = $local_query = $query_prefix
1943 . $GLOBALS['dbi']->escapeString($_POST['pma_pw']) . "')";
1944 } elseif ($serverType == 'MariaDB'
1945 && $serverVersion >= 50200
1946 && $GLOBALS['dbi']->isSuperuser()
1948 // Use 'UPDATE `mysql`.`user` ...' Syntax for MariaDB 5.2+
1949 if ($authentication_plugin == 'mysql_native_password') {
1950 // Set the hashing method used by PASSWORD()
1951 // to be 'mysql_native_password' type
1952 $GLOBALS['dbi']->tryQuery('SET old_passwords = 0;');
1954 } elseif ($authentication_plugin == 'sha256_password') {
1955 // Set the hashing method used by PASSWORD()
1956 // to be 'sha256_password' type
1957 $GLOBALS['dbi']->tryQuery('SET `old_passwords` = 2;');
1960 $hashedPassword = self::getHashedPassword($_POST['pma_pw']);
1962 $sql_query = 'SET PASSWORD FOR \''
1963 . $GLOBALS['dbi']->escapeString($username)
1964 . '\'@\'' . $GLOBALS['dbi']->escapeString($hostname) . '\' = '
1965 . (($_POST['pma_pw'] == '')
1966 ? '\'\''
1967 : $hashing_function . '(\''
1968 . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
1970 $local_query = "UPDATE `mysql`.`user` SET "
1971 . " `authentication_string` = '" . $hashedPassword
1972 . "', `Password` = '', "
1973 . " `plugin` = '" . $authentication_plugin . "'"
1974 . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username)
1975 . "' AND Host = '" . $GLOBALS['dbi']->escapeString($hostname) . "';";
1976 } else {
1977 // USE 'SET PASSWORD ...' syntax for rest of the versions
1978 // Backup the old value, to be reset later
1979 $row = $GLOBALS['dbi']->fetchSingleRow(
1980 'SELECT @@old_passwords;'
1982 $orig_value = $row['@@old_passwords'];
1983 $update_plugin_query = "UPDATE `mysql`.`user` SET"
1984 . " `plugin` = '" . $authentication_plugin . "'"
1985 . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username)
1986 . "' AND Host = '" . $GLOBALS['dbi']->escapeString($hostname) . "';";
1988 // Update the plugin for the user
1989 if (!($GLOBALS['dbi']->tryQuery($update_plugin_query))) {
1990 Util::mysqlDie(
1991 $GLOBALS['dbi']->getError(),
1992 $update_plugin_query,
1993 false, $err_url
1996 $GLOBALS['dbi']->tryQuery("FLUSH PRIVILEGES;");
1998 if ($authentication_plugin == 'mysql_native_password') {
1999 // Set the hashing method used by PASSWORD()
2000 // to be 'mysql_native_password' type
2001 $GLOBALS['dbi']->tryQuery('SET old_passwords = 0;');
2002 } elseif ($authentication_plugin == 'sha256_password') {
2003 // Set the hashing method used by PASSWORD()
2004 // to be 'sha256_password' type
2005 $GLOBALS['dbi']->tryQuery('SET `old_passwords` = 2;');
2007 $sql_query = 'SET PASSWORD FOR \''
2008 . $GLOBALS['dbi']->escapeString($username)
2009 . '\'@\'' . $GLOBALS['dbi']->escapeString($hostname) . '\' = '
2010 . (($_POST['pma_pw'] == '')
2011 ? '\'\''
2012 : $hashing_function . '(\''
2013 . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
2015 $local_query = 'SET PASSWORD FOR \''
2016 . $GLOBALS['dbi']->escapeString($username)
2017 . '\'@\'' . $GLOBALS['dbi']->escapeString($hostname) . '\' = '
2018 . (($_POST['pma_pw'] == '') ? '\'\'' : $hashing_function
2019 . '(\'' . $GLOBALS['dbi']->escapeString($_POST['pma_pw']) . '\')');
2022 if (!($GLOBALS['dbi']->tryQuery($local_query))) {
2023 Util::mysqlDie(
2024 $GLOBALS['dbi']->getError(), $sql_query, false, $err_url
2027 // Flush privileges after successful password change
2028 $GLOBALS['dbi']->tryQuery("FLUSH PRIVILEGES;");
2030 $message = Message::success(
2031 __('The password for %s was changed successfully.')
2033 $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
2034 if (isset($orig_value)) {
2035 $GLOBALS['dbi']->tryQuery(
2036 'SET `old_passwords` = ' . $orig_value . ';'
2040 return $message;
2044 * Revokes privileges and get message and SQL query for privileges revokes
2046 * @param string $dbname database name
2047 * @param string $tablename table name
2048 * @param string $username username
2049 * @param string $hostname host name
2050 * @param string $itemType item type
2052 * @return array ($message, $sql_query)
2054 public static function getMessageAndSqlQueryForPrivilegesRevoke($dbname,
2055 $tablename, $username, $hostname, $itemType
2057 $db_and_table = self::wildcardEscapeForGrant($dbname, $tablename);
2059 $sql_query0 = 'REVOKE ALL PRIVILEGES ON ' . $itemType . ' ' . $db_and_table
2060 . ' FROM \''
2061 . $GLOBALS['dbi']->escapeString($username) . '\'@\''
2062 . $GLOBALS['dbi']->escapeString($hostname) . '\';';
2064 $sql_query1 = 'REVOKE GRANT OPTION ON ' . $itemType . ' ' . $db_and_table
2065 . ' FROM \'' . $GLOBALS['dbi']->escapeString($username) . '\'@\''
2066 . $GLOBALS['dbi']->escapeString($hostname) . '\';';
2068 $GLOBALS['dbi']->query($sql_query0);
2069 if (! $GLOBALS['dbi']->tryQuery($sql_query1)) {
2070 // this one may fail, too...
2071 $sql_query1 = '';
2073 $sql_query = $sql_query0 . ' ' . $sql_query1;
2074 $message = Message::success(
2075 __('You have revoked the privileges for %s.')
2077 $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
2079 return array($message, $sql_query);
2083 * Get REQUIRE cluase
2085 * @return string REQUIRE clause
2087 public static function getRequireClause()
2089 $arr = isset($_POST['ssl_type']) ? $_POST : $GLOBALS;
2090 if (isset($arr['ssl_type']) && $arr['ssl_type'] == 'SPECIFIED') {
2091 $require = array();
2092 if (! empty($arr['ssl_cipher'])) {
2093 $require[] = "CIPHER '"
2094 . $GLOBALS['dbi']->escapeString($arr['ssl_cipher']) . "'";
2096 if (! empty($arr['x509_issuer'])) {
2097 $require[] = "ISSUER '"
2098 . $GLOBALS['dbi']->escapeString($arr['x509_issuer']) . "'";
2100 if (! empty($arr['x509_subject'])) {
2101 $require[] = "SUBJECT '"
2102 . $GLOBALS['dbi']->escapeString($arr['x509_subject']) . "'";
2104 if (count($require)) {
2105 $require_clause = " REQUIRE " . implode(" AND ", $require);
2106 } else {
2107 $require_clause = " REQUIRE NONE";
2109 } elseif (isset($arr['ssl_type']) && $arr['ssl_type'] == 'X509') {
2110 $require_clause = " REQUIRE X509";
2111 } elseif (isset($arr['ssl_type']) && $arr['ssl_type'] == 'ANY') {
2112 $require_clause = " REQUIRE SSL";
2113 } else {
2114 $require_clause = " REQUIRE NONE";
2117 return $require_clause;
2121 * Get a WITH clause for 'update privileges' and 'add user'
2123 * @return string $sql_query
2125 public static function getWithClauseForAddUserAndUpdatePrivs()
2127 $sql_query = '';
2128 if (((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
2129 || (isset($GLOBALS['Grant_priv']) && $GLOBALS['Grant_priv'] == 'Y'))
2130 && ! ((Util::getServerType() == 'MySQL' || Util::getServerType() == 'Percona Server')
2131 && $GLOBALS['dbi']->getVersion() >= 80011)
2133 $sql_query .= ' GRANT OPTION';
2135 if (isset($_POST['max_questions']) || isset($GLOBALS['max_questions'])) {
2136 $max_questions = isset($_POST['max_questions'])
2137 ? (int)$_POST['max_questions'] : (int)$GLOBALS['max_questions'];
2138 $max_questions = max(0, $max_questions);
2139 $sql_query .= ' MAX_QUERIES_PER_HOUR ' . $max_questions;
2141 if (isset($_POST['max_connections']) || isset($GLOBALS['max_connections'])) {
2142 $max_connections = isset($_POST['max_connections'])
2143 ? (int)$_POST['max_connections'] : (int)$GLOBALS['max_connections'];
2144 $max_connections = max(0, $max_connections);
2145 $sql_query .= ' MAX_CONNECTIONS_PER_HOUR ' . $max_connections;
2147 if (isset($_POST['max_updates']) || isset($GLOBALS['max_updates'])) {
2148 $max_updates = isset($_POST['max_updates'])
2149 ? (int)$_POST['max_updates'] : (int)$GLOBALS['max_updates'];
2150 $max_updates = max(0, $max_updates);
2151 $sql_query .= ' MAX_UPDATES_PER_HOUR ' . $max_updates;
2153 if (isset($_POST['max_user_connections'])
2154 || isset($GLOBALS['max_user_connections'])
2156 $max_user_connections = isset($_POST['max_user_connections'])
2157 ? (int)$_POST['max_user_connections']
2158 : (int)$GLOBALS['max_user_connections'];
2159 $max_user_connections = max(0, $max_user_connections);
2160 $sql_query .= ' MAX_USER_CONNECTIONS ' . $max_user_connections;
2162 return ((!empty($sql_query)) ? ' WITH' . $sql_query : '');
2166 * Get HTML for addUsersForm, This function call if isset($_GET['adduser'])
2168 * @param string $dbname database name
2170 * @return string HTML for addUserForm
2172 public static function getHtmlForAddUser($dbname)
2174 $html_output = '<h2>' . "\n"
2175 . Util::getIcon('b_usradd') . __('Add user account') . "\n"
2176 . '</h2>' . "\n"
2177 . '<form name="usersForm" id="addUsersForm"'
2178 . ' onsubmit="return checkAddUser(this);"'
2179 . ' action="server_privileges.php" method="post" autocomplete="off" >' . "\n"
2180 . Url::getHiddenInputs('', '')
2181 . self::getHtmlForLoginInformationFields('new');
2183 $html_output .= '<fieldset id="fieldset_add_user_database">' . "\n"
2184 . '<legend>' . __('Database for user account') . '</legend>' . "\n";
2186 $html_output .= Template::get('checkbox')
2187 ->render(
2188 array(
2189 'html_field_name' => 'createdb-1',
2190 'label' => __('Create database with same name and grant all privileges.'),
2191 'checked' => false,
2192 'onclick' => false,
2193 'html_field_id' => 'createdb-1',
2196 $html_output .= '<br />' . "\n";
2197 $html_output .= Template::get('checkbox')
2198 ->render(
2199 array(
2200 'html_field_name' => 'createdb-2',
2201 'label' => __('Grant all privileges on wildcard name (username\\_%).'),
2202 'checked' => false,
2203 'onclick' => false,
2204 'html_field_id' => 'createdb-2',
2207 $html_output .= '<br />' . "\n";
2209 if (! empty($dbname) ) {
2210 $html_output .= Template::get('checkbox')
2211 ->render(
2212 array(
2213 'html_field_name' => 'createdb-3',
2214 'label' => sprintf(__('Grant all privileges on database %s.'), htmlspecialchars($dbname)),
2215 'checked' => true,
2216 'onclick' => false,
2217 'html_field_id' => 'createdb-3',
2220 $html_output .= '<input type="hidden" name="dbname" value="'
2221 . htmlspecialchars($dbname) . '" />' . "\n";
2222 $html_output .= '<br />' . "\n";
2225 $html_output .= '</fieldset>' . "\n";
2226 if ($GLOBALS['is_grantuser']) {
2227 $html_output .= self::getHtmlToDisplayPrivilegesTable('*', '*', false);
2229 $html_output .= '<fieldset id="fieldset_add_user_footer" class="tblFooters">'
2230 . "\n"
2231 . '<input type="hidden" name="adduser_submit" value="1" />' . "\n"
2232 . '<input type="submit" id="adduser_submit" value="' . __('Go') . '" />'
2233 . "\n"
2234 . '</fieldset>' . "\n"
2235 . '</form>' . "\n";
2237 return $html_output;
2241 * Get the list of privileges and list of compared privileges as strings
2242 * and return a array that contains both strings
2244 * @return array $list_of_privileges, $list_of_compared_privileges
2246 public static function getListOfPrivilegesAndComparedPrivileges()
2248 $list_of_privileges
2249 = '`User`, '
2250 . '`Host`, '
2251 . '`Select_priv`, '
2252 . '`Insert_priv`, '
2253 . '`Update_priv`, '
2254 . '`Delete_priv`, '
2255 . '`Create_priv`, '
2256 . '`Drop_priv`, '
2257 . '`Grant_priv`, '
2258 . '`Index_priv`, '
2259 . '`Alter_priv`, '
2260 . '`References_priv`, '
2261 . '`Create_tmp_table_priv`, '
2262 . '`Lock_tables_priv`, '
2263 . '`Create_view_priv`, '
2264 . '`Show_view_priv`, '
2265 . '`Create_routine_priv`, '
2266 . '`Alter_routine_priv`, '
2267 . '`Execute_priv`';
2269 $listOfComparedPrivs
2270 = '`Select_priv` = \'N\''
2271 . ' AND `Insert_priv` = \'N\''
2272 . ' AND `Update_priv` = \'N\''
2273 . ' AND `Delete_priv` = \'N\''
2274 . ' AND `Create_priv` = \'N\''
2275 . ' AND `Drop_priv` = \'N\''
2276 . ' AND `Grant_priv` = \'N\''
2277 . ' AND `References_priv` = \'N\''
2278 . ' AND `Create_tmp_table_priv` = \'N\''
2279 . ' AND `Lock_tables_priv` = \'N\''
2280 . ' AND `Create_view_priv` = \'N\''
2281 . ' AND `Show_view_priv` = \'N\''
2282 . ' AND `Create_routine_priv` = \'N\''
2283 . ' AND `Alter_routine_priv` = \'N\''
2284 . ' AND `Execute_priv` = \'N\'';
2286 $list_of_privileges .=
2287 ', `Event_priv`, '
2288 . '`Trigger_priv`';
2289 $listOfComparedPrivs .=
2290 ' AND `Event_priv` = \'N\''
2291 . ' AND `Trigger_priv` = \'N\'';
2292 return array($list_of_privileges, $listOfComparedPrivs);
2296 * Get the HTML for routine based privileges
2298 * @param string $db database name
2299 * @param string $index_checkbox starting index for rows to be added
2301 * @return string $html_output
2303 public static function getHtmlTableBodyForSpecificDbRoutinePrivs($db, $index_checkbox)
2305 $sql_query = 'SELECT * FROM `mysql`.`procs_priv` WHERE Db = \'' . $GLOBALS['dbi']->escapeString($db) . '\';';
2306 $res = $GLOBALS['dbi']->query($sql_query);
2307 $html_output = '';
2308 while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
2310 $html_output .= '<tr>';
2312 $html_output .= '<td';
2313 $value = htmlspecialchars($row['User'] . '&amp;#27;' . $row['Host']);
2314 $html_output .= '>';
2315 $html_output .= '<input type="checkbox" class="checkall" '
2316 . 'name="selected_usr[]" '
2317 . 'id="checkbox_sel_users_' . ($index_checkbox++) . '" '
2318 . 'value="' . $value . '" /></td>';
2320 $html_output .= '<td>' . htmlspecialchars($row['User'])
2321 . '</td>'
2322 . '<td>' . htmlspecialchars($row['Host'])
2323 . '</td>'
2324 . '<td>' . 'routine'
2325 . '</td>'
2326 . '<td>' . '<code>' . htmlspecialchars($row['Routine_name']) . '</code>'
2327 . '</td>'
2328 . '<td>' . 'Yes'
2329 . '</td>';
2330 $current_user = $row['User'];
2331 $current_host = $row['Host'];
2332 $routine = $row['Routine_name'];
2333 $html_output .= '<td>';
2334 if ($GLOBALS['is_grantuser']) {
2335 $specific_db = (isset($row['Db']) && $row['Db'] != '*')
2336 ? $row['Db'] : '';
2337 $specific_table = (isset($row['Table_name'])
2338 && $row['Table_name'] != '*')
2339 ? $row['Table_name'] : '';
2340 $html_output .= self::getUserLink(
2341 'edit',
2342 $current_user,
2343 $current_host,
2344 $specific_db,
2345 $specific_table,
2346 $routine
2349 $html_output .= '</td>';
2350 $html_output .= '<td>';
2351 $html_output .= self::getUserLink(
2352 'export',
2353 $current_user,
2354 $current_host,
2355 $specific_db,
2356 $specific_table,
2357 $routine
2359 $html_output .= '</td>';
2361 $html_output .= '</tr>';
2364 return $html_output;
2368 * Get the HTML for user form and check the privileges for a particular database.
2370 * @param string $db database name
2372 * @return string $html_output
2374 public static function getHtmlForSpecificDbPrivileges($db)
2376 $html_output = '';
2378 if ($GLOBALS['dbi']->isSuperuser()) {
2379 // check the privileges for a particular database.
2380 $html_output = '<form id="usersForm" action="server_privileges.php">';
2381 $html_output .= Url::getHiddenInputs($db);
2382 $html_output .= '<div class="width100">';
2383 $html_output .= '<fieldset>';
2384 $html_output .= '<legend>' . "\n"
2385 . Util::getIcon('b_usrcheck')
2386 . ' '
2387 . sprintf(
2388 __('Users having access to "%s"'),
2389 '<a href="' . Util::getScriptNameForOption(
2390 $GLOBALS['cfg']['DefaultTabDatabase'], 'database'
2392 . Url::getCommon(array('db' => $db)) . '">'
2393 . htmlspecialchars($db)
2394 . '</a>'
2396 . "\n"
2397 . '</legend>' . "\n";
2399 $html_output .= '<div class="responsivetable jsresponsive">';
2400 $html_output .= '<table id="dbspecificuserrights" class="data">';
2401 $html_output .= self::getHtmlForPrivsTableHead();
2402 $privMap = self::getPrivMap($db);
2403 $html_output .= self::getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db);
2404 $html_output .= '</table>';
2405 $html_output .= '</div>';
2407 $html_output .= '<div class="floatleft">';
2408 $html_output .= Template::get('select_all')
2409 ->render(
2410 array(
2411 'pma_theme_image' => $GLOBALS['pmaThemeImage'],
2412 'text_dir' => $GLOBALS['text_dir'],
2413 'form_name' => "usersForm",
2416 $html_output .= Util::getButtonOrImage(
2417 'submit_mult', 'mult_submit',
2418 __('Export'), 'b_tblexport', 'export'
2421 $html_output .= '</fieldset>';
2422 $html_output .= '</div>';
2423 $html_output .= '</form>';
2424 } else {
2425 $html_output .= self::getHtmlForViewUsersError();
2428 $response = Response::getInstance();
2429 if ($response->isAjax() == true
2430 && empty($_REQUEST['ajax_page_request'])
2432 $message = Message::success(__('User has been added.'));
2433 $response->addJSON('message', $message);
2434 $response->addJSON('user_form', $html_output);
2435 exit;
2436 } else {
2437 // Offer to create a new user for the current database
2438 $html_output .= self::getAddUserHtmlFieldset($db);
2440 return $html_output;
2444 * Get the HTML for user form and check the privileges for a particular table.
2446 * @param string $db database name
2447 * @param string $table table name
2449 * @return string $html_output
2451 public static function getHtmlForSpecificTablePrivileges($db, $table)
2453 $html_output = '';
2454 if ($GLOBALS['dbi']->isSuperuser()) {
2455 // check the privileges for a particular table.
2456 $html_output = '<form id="usersForm" action="server_privileges.php">';
2457 $html_output .= Url::getHiddenInputs($db, $table);
2458 $html_output .= '<fieldset>';
2459 $html_output .= '<legend>'
2460 . Util::getIcon('b_usrcheck')
2461 . sprintf(
2462 __('Users having access to "%s"'),
2463 '<a href="' . Util::getScriptNameForOption(
2464 $GLOBALS['cfg']['DefaultTabTable'], 'table'
2466 . Url::getCommon(
2467 array(
2468 'db' => $db,
2469 'table' => $table,
2471 ) . '">'
2472 . htmlspecialchars($db) . '.' . htmlspecialchars($table)
2473 . '</a>'
2475 . '</legend>';
2477 $html_output .= '<div class="responsivetable jsresponsive">';
2478 $html_output .= '<table id="tablespecificuserrights" class="data">';
2479 $html_output .= self::getHtmlForPrivsTableHead();
2480 $privMap = self::getPrivMap($db);
2481 $sql_query = "SELECT `User`, `Host`, `Db`,"
2482 . " 't' AS `Type`, `Table_name`, `Table_priv`"
2483 . " FROM `mysql`.`tables_priv`"
2484 . " WHERE '" . $GLOBALS['dbi']->escapeString($db) . "' LIKE `Db`"
2485 . " AND '" . $GLOBALS['dbi']->escapeString($table) . "' LIKE `Table_name`"
2486 . " AND NOT (`Table_priv` = '' AND Column_priv = '')"
2487 . " ORDER BY `User` ASC, `Host` ASC, `Db` ASC, `Table_priv` ASC;";
2488 $res = $GLOBALS['dbi']->query($sql_query);
2489 self::mergePrivMapFromResult($privMap, $res);
2490 $html_output .= self::getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db);
2491 $html_output .= '</table></div>';
2493 $html_output .= '<div class="floatleft">';
2494 $html_output .= Template::get('select_all')
2495 ->render(
2496 array(
2497 'pma_theme_image' => $GLOBALS['pmaThemeImage'],
2498 'text_dir' => $GLOBALS['text_dir'],
2499 'form_name' => "usersForm",
2502 $html_output .= Util::getButtonOrImage(
2503 'submit_mult', 'mult_submit',
2504 __('Export'), 'b_tblexport', 'export'
2507 $html_output .= '</fieldset>';
2508 $html_output .= '</form>';
2509 } else {
2510 $html_output .= self::getHtmlForViewUsersError();
2512 // Offer to create a new user for the current database
2513 $html_output .= self::getAddUserHtmlFieldset($db, $table);
2514 return $html_output;
2518 * gets privilege map
2520 * @param string $db the database
2522 * @return array $privMap the privilege map
2524 public static function getPrivMap($db)
2526 list($listOfPrivs, $listOfComparedPrivs)
2527 = self::getListOfPrivilegesAndComparedPrivileges();
2528 $sql_query
2529 = "("
2530 . " SELECT " . $listOfPrivs . ", '*' AS `Db`, 'g' AS `Type`"
2531 . " FROM `mysql`.`user`"
2532 . " WHERE NOT (" . $listOfComparedPrivs . ")"
2533 . ")"
2534 . " UNION "
2535 . "("
2536 . " SELECT " . $listOfPrivs . ", `Db`, 'd' AS `Type`"
2537 . " FROM `mysql`.`db`"
2538 . " WHERE '" . $GLOBALS['dbi']->escapeString($db) . "' LIKE `Db`"
2539 . " AND NOT (" . $listOfComparedPrivs . ")"
2540 . ")"
2541 . " ORDER BY `User` ASC, `Host` ASC, `Db` ASC;";
2542 $res = $GLOBALS['dbi']->query($sql_query);
2543 $privMap = array();
2544 self::mergePrivMapFromResult($privMap, $res);
2545 return $privMap;
2549 * merge privilege map and rows from resultset
2551 * @param array &$privMap the privilege map reference
2552 * @param object $result the resultset of query
2554 * @return void
2556 public static function mergePrivMapFromResult(array &$privMap, $result)
2558 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
2559 $user = $row['User'];
2560 $host = $row['Host'];
2561 if (! isset($privMap[$user])) {
2562 $privMap[$user] = array();
2564 if (! isset($privMap[$user][$host])) {
2565 $privMap[$user][$host] = array();
2567 $privMap[$user][$host][] = $row;
2572 * Get HTML snippet for privileges table head
2574 * @return string $html_output
2576 public static function getHtmlForPrivsTableHead()
2578 return '<thead>'
2579 . '<tr>'
2580 . '<th></th>'
2581 . '<th>' . __('User name') . '</th>'
2582 . '<th>' . __('Host name') . '</th>'
2583 . '<th>' . __('Type') . '</th>'
2584 . '<th>' . __('Privileges') . '</th>'
2585 . '<th>' . __('Grant') . '</th>'
2586 . '<th colspan="2">' . __('Action') . '</th>'
2587 . '</tr>'
2588 . '</thead>';
2592 * Get HTML error for View Users form
2593 * For non superusers such as grant/create users
2595 * @return string $html_output
2597 public static function getHtmlForViewUsersError()
2599 return Message::error(
2600 __('Not enough privilege to view users.')
2601 )->getDisplay();
2605 * Get HTML snippet for table body of specific database or table privileges
2607 * @param array $privMap privilege map
2608 * @param string $db database
2610 * @return string $html_output
2612 public static function getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db)
2614 $html_output = '<tbody>';
2615 $index_checkbox = 0;
2616 if (empty($privMap)) {
2617 $html_output .= '<tr>'
2618 . '<td colspan="6">'
2619 . __('No user found.')
2620 . '</td>'
2621 . '</tr>'
2622 . '</tbody>';
2623 return $html_output;
2626 foreach ($privMap as $current_user => $val) {
2627 foreach ($val as $current_host => $current_privileges) {
2628 $nbPrivileges = count($current_privileges);
2629 $html_output .= '<tr>';
2631 $value = htmlspecialchars($current_user . '&amp;#27;' . $current_host);
2632 $html_output .= '<td';
2633 if ($nbPrivileges > 1) {
2634 $html_output .= ' rowspan="' . $nbPrivileges . '"';
2636 $html_output .= '>';
2637 $html_output .= '<input type="checkbox" class="checkall" '
2638 . 'name="selected_usr[]" '
2639 . 'id="checkbox_sel_users_' . ($index_checkbox++) . '" '
2640 . 'value="' . $value . '" /></td>' . "\n";
2642 // user
2643 $html_output .= '<td';
2644 if ($nbPrivileges > 1) {
2645 $html_output .= ' rowspan="' . $nbPrivileges . '"';
2647 $html_output .= '>';
2648 if (empty($current_user)) {
2649 $html_output .= '<span style="color: #FF0000">'
2650 . __('Any') . '</span>';
2651 } else {
2652 $html_output .= htmlspecialchars($current_user);
2654 $html_output .= '</td>';
2656 // host
2657 $html_output .= '<td';
2658 if ($nbPrivileges > 1) {
2659 $html_output .= ' rowspan="' . $nbPrivileges . '"';
2661 $html_output .= '>';
2662 $html_output .= htmlspecialchars($current_host);
2663 $html_output .= '</td>';
2665 $html_output .= self::getHtmlListOfPrivs(
2666 $db, $current_privileges, $current_user,
2667 $current_host
2672 //For fetching routine based privileges
2673 $html_output .= self::getHtmlTableBodyForSpecificDbRoutinePrivs($db, $index_checkbox);
2674 $html_output .= '</tbody>';
2676 return $html_output;
2680 * Get HTML to display privileges
2682 * @param string $db Database name
2683 * @param array $current_privileges List of privileges
2684 * @param string $current_user Current user
2685 * @param string $current_host Current host
2687 * @return string HTML to display privileges
2689 public static function getHtmlListOfPrivs(
2690 $db, array $current_privileges, $current_user,
2691 $current_host
2693 $nbPrivileges = count($current_privileges);
2694 $html_output = null;
2695 for ($i = 0; $i < $nbPrivileges; $i++) {
2696 $current = $current_privileges[$i];
2698 // type
2699 $html_output .= '<td>';
2700 if ($current['Type'] == 'g') {
2701 $html_output .= __('global');
2702 } elseif ($current['Type'] == 'd') {
2703 if ($current['Db'] == Util::escapeMysqlWildcards($db)) {
2704 $html_output .= __('database-specific');
2705 } else {
2706 $html_output .= __('wildcard') . ': '
2707 . '<code>'
2708 . htmlspecialchars($current['Db'])
2709 . '</code>';
2711 } elseif ($current['Type'] == 't') {
2712 $html_output .= __('table-specific');
2714 $html_output .= '</td>';
2716 // privileges
2717 $html_output .= '<td>';
2718 if (isset($current['Table_name'])) {
2719 $privList = explode(',', $current['Table_priv']);
2720 $privs = array();
2721 $grantsArr = self::getTableGrantsArray();
2722 foreach ($grantsArr as $grant) {
2723 $privs[$grant[0]] = 'N';
2724 foreach ($privList as $priv) {
2725 if ($grant[0] == $priv) {
2726 $privs[$grant[0]] = 'Y';
2730 $html_output .= '<code>'
2731 . join(
2732 ',',
2733 self::extractPrivInfo($privs, true, true)
2735 . '</code>';
2736 } else {
2737 $html_output .= '<code>'
2738 . join(
2739 ',',
2740 self::extractPrivInfo($current, true, false)
2742 . '</code>';
2744 $html_output .= '</td>';
2746 // grant
2747 $html_output .= '<td>';
2748 $containsGrant = false;
2749 if (isset($current['Table_name'])) {
2750 $privList = explode(',', $current['Table_priv']);
2751 foreach ($privList as $priv) {
2752 if ($priv == 'Grant') {
2753 $containsGrant = true;
2756 } else {
2757 $containsGrant = $current['Grant_priv'] == 'Y';
2759 $html_output .= ($containsGrant ? __('Yes') : __('No'));
2760 $html_output .= '</td>';
2762 // action
2763 $html_output .= '<td>';
2764 $specific_db = (isset($current['Db']) && $current['Db'] != '*')
2765 ? $current['Db'] : '';
2766 $specific_table = (isset($current['Table_name'])
2767 && $current['Table_name'] != '*')
2768 ? $current['Table_name'] : '';
2769 if ($GLOBALS['is_grantuser']) {
2770 $html_output .= self::getUserLink(
2771 'edit',
2772 $current_user,
2773 $current_host,
2774 $specific_db,
2775 $specific_table
2778 $html_output .= '</td>';
2779 $html_output .= '<td class="center">'
2780 . self::getUserLink(
2781 'export',
2782 $current_user,
2783 $current_host,
2784 $specific_db,
2785 $specific_table
2787 . '</td>';
2789 $html_output .= '</tr>';
2790 if (($i + 1) < $nbPrivileges) {
2791 $html_output .= '<tr class="noclick">';
2794 return $html_output;
2798 * Returns edit, revoke or export link for a user.
2800 * @param string $linktype The link type (edit | revoke | export)
2801 * @param string $username User name
2802 * @param string $hostname Host name
2803 * @param string $dbname Database name
2804 * @param string $tablename Table name
2805 * @param string $routinename Routine name
2806 * @param string $initial Initial value
2808 * @return string HTML code with link
2810 public static function getUserLink(
2811 $linktype, $username, $hostname, $dbname = '',
2812 $tablename = '', $routinename = '', $initial = ''
2814 $html = '<a';
2815 switch($linktype) {
2816 case 'edit':
2817 $html .= ' class="edit_user_anchor"';
2818 break;
2819 case 'export':
2820 $html .= ' class="export_user_anchor ajax"';
2821 break;
2823 $params = array(
2824 'username' => $username,
2825 'hostname' => $hostname
2827 switch($linktype) {
2828 case 'edit':
2829 $params['dbname'] = $dbname;
2830 $params['tablename'] = $tablename;
2831 $params['routinename'] = $routinename;
2832 break;
2833 case 'revoke':
2834 $params['dbname'] = $dbname;
2835 $params['tablename'] = $tablename;
2836 $params['routinename'] = $routinename;
2837 $params['revokeall'] = 1;
2838 break;
2839 case 'export':
2840 $params['initial'] = $initial;
2841 $params['export'] = 1;
2842 break;
2845 $html .= ' href="server_privileges.php';
2846 if ($linktype == 'revoke') {
2847 $html .= '" data-post="' . Url::getCommon($params, '');
2848 } else {
2849 $html .= Url::getCommon($params);
2851 $html .= '">';
2853 switch($linktype) {
2854 case 'edit':
2855 $html .= Util::getIcon('b_usredit', __('Edit privileges'));
2856 break;
2857 case 'revoke':
2858 $html .= Util::getIcon('b_usrdrop', __('Revoke'));
2859 break;
2860 case 'export':
2861 $html .= Util::getIcon('b_tblexport', __('Export'));
2862 break;
2864 $html .= '</a>';
2866 return $html;
2870 * Returns user group edit link
2872 * @param string $username User name
2874 * @return string HTML code with link
2876 public static function getUserGroupEditLink($username)
2878 return '<a class="edit_user_group_anchor ajax"'
2879 . ' href="server_privileges.php'
2880 . Url::getCommon(array('username' => $username))
2881 . '">'
2882 . Util::getIcon('b_usrlist', __('Edit user group'))
2883 . '</a>';
2887 * Returns number of defined user groups
2889 * @return integer $user_group_count
2891 public static function getUserGroupCount()
2893 $relation = new Relation();
2894 $cfgRelation = $relation->getRelationsParam();
2895 $user_group_table = Util::backquote($cfgRelation['db'])
2896 . '.' . Util::backquote($cfgRelation['usergroups']);
2897 $sql_query = 'SELECT COUNT(*) FROM ' . $user_group_table;
2898 $user_group_count = $GLOBALS['dbi']->fetchValue(
2899 $sql_query, 0, 0, DatabaseInterface::CONNECT_CONTROL
2902 return $user_group_count;
2906 * Returns name of user group that user is part of
2908 * @param string $username User name
2910 * @return mixed usergroup if found or null if not found
2912 public static function getUserGroupForUser($username)
2914 $relation = new Relation();
2915 $cfgRelation = $relation->getRelationsParam();
2917 if (empty($cfgRelation['db'])
2918 || empty($cfgRelation['users'])
2920 return null;
2923 $user_table = Util::backquote($cfgRelation['db'])
2924 . '.' . Util::backquote($cfgRelation['users']);
2925 $sql_query = 'SELECT `usergroup` FROM ' . $user_table
2926 . ' WHERE `username` = \'' . $username . '\''
2927 . ' LIMIT 1';
2929 $usergroup = $GLOBALS['dbi']->fetchValue(
2930 $sql_query, 0, 0, DatabaseInterface::CONNECT_CONTROL
2933 if ($usergroup === false) {
2934 return null;
2937 return $usergroup;
2941 * This function return the extra data array for the ajax behavior
2943 * @param string $password password
2944 * @param string $sql_query sql query
2945 * @param string $hostname hostname
2946 * @param string $username username
2948 * @return array $extra_data
2950 public static function getExtraDataForAjaxBehavior(
2951 $password, $sql_query, $hostname, $username
2953 $relation = new Relation();
2954 if (isset($GLOBALS['dbname'])) {
2955 //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
2956 if (preg_match('/(?<!\\\\)(?:_|%)/i', $GLOBALS['dbname'])) {
2957 $dbname_is_wildcard = true;
2958 } else {
2959 $dbname_is_wildcard = false;
2963 $user_group_count = 0;
2964 if ($GLOBALS['cfgRelation']['menuswork']) {
2965 $user_group_count = self::getUserGroupCount();
2968 $extra_data = array();
2969 if (strlen($sql_query) > 0) {
2970 $extra_data['sql_query'] = Util::getMessage(null, $sql_query);
2973 if (isset($_POST['change_copy'])) {
2975 * generate html on the fly for the new user that was just created.
2977 $new_user_string = '<tr>' . "\n"
2978 . '<td> <input type="checkbox" name="selected_usr[]" '
2979 . 'id="checkbox_sel_users_"'
2980 . 'value="'
2981 . htmlspecialchars($username)
2982 . '&amp;#27;' . htmlspecialchars($hostname) . '" />'
2983 . '</td>' . "\n"
2984 . '<td><label for="checkbox_sel_users_">'
2985 . (empty($_POST['username'])
2986 ? '<span style="color: #FF0000">' . __('Any') . '</span>'
2987 : htmlspecialchars($username) ) . '</label></td>' . "\n"
2988 . '<td>' . htmlspecialchars($hostname) . '</td>' . "\n";
2990 $new_user_string .= '<td>';
2992 if (! empty($password) || isset($_POST['pma_pw'])) {
2993 $new_user_string .= __('Yes');
2994 } else {
2995 $new_user_string .= '<span style="color: #FF0000">'
2996 . __('No')
2997 . '</span>';
3000 $new_user_string .= '</td>' . "\n";
3001 $new_user_string .= '<td>'
3002 . '<code>' . join(', ', self::extractPrivInfo(null, true)) . '</code>'
3003 . '</td>'; //Fill in privileges here
3005 // if $cfg['Servers'][$i]['users'] and $cfg['Servers'][$i]['usergroups'] are
3006 // enabled
3007 $cfgRelation = $relation->getRelationsParam();
3008 if (!empty($cfgRelation['users']) && !empty($cfgRelation['usergroups'])) {
3009 $new_user_string .= '<td class="usrGroup"></td>';
3012 $new_user_string .= '<td>';
3013 if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')) {
3014 $new_user_string .= __('Yes');
3015 } else {
3016 $new_user_string .= __('No');
3018 $new_user_string .='</td>';
3020 if ($GLOBALS['is_grantuser']) {
3021 $new_user_string .= '<td>'
3022 . self::getUserLink('edit', $username, $hostname)
3023 . '</td>' . "\n";
3026 if ($cfgRelation['menuswork'] && $user_group_count > 0) {
3027 $new_user_string .= '<td>'
3028 . self::getUserGroupEditLink($username)
3029 . '</td>' . "\n";
3032 $new_user_string .= '<td>'
3033 . self::getUserLink(
3034 'export',
3035 $username,
3036 $hostname,
3040 isset($_GET['initial']) ? $_GET['initial'] : ''
3042 . '</td>' . "\n";
3044 $new_user_string .= '</tr>';
3046 $extra_data['new_user_string'] = $new_user_string;
3049 * Generate the string for this alphabet's initial, to update the user
3050 * pagination
3052 $new_user_initial = mb_strtoupper(
3053 mb_substr($username, 0, 1)
3055 $newUserInitialString = '<a href="server_privileges.php'
3056 . Url::getCommon(array('initial' => $new_user_initial)) . '">'
3057 . $new_user_initial . '</a>';
3058 $extra_data['new_user_initial'] = $new_user_initial;
3059 $extra_data['new_user_initial_string'] = $newUserInitialString;
3062 if (isset($_POST['update_privs'])) {
3063 $extra_data['db_specific_privs'] = false;
3064 $extra_data['db_wildcard_privs'] = false;
3065 if (isset($dbname_is_wildcard)) {
3066 $extra_data['db_specific_privs'] = ! $dbname_is_wildcard;
3067 $extra_data['db_wildcard_privs'] = $dbname_is_wildcard;
3069 $new_privileges = join(', ', self::extractPrivInfo(null, true));
3071 $extra_data['new_privileges'] = $new_privileges;
3074 if (isset($_GET['validate_username'])) {
3075 $sql_query = "SELECT * FROM `mysql`.`user` WHERE `User` = '"
3076 . $GLOBALS['dbi']->escapeString($_GET['username']) . "';";
3077 $res = $GLOBALS['dbi']->query($sql_query);
3078 $row = $GLOBALS['dbi']->fetchRow($res);
3079 if (empty($row)) {
3080 $extra_data['user_exists'] = false;
3081 } else {
3082 $extra_data['user_exists'] = true;
3086 return $extra_data;
3090 * Get the HTML snippet for change user login information
3092 * @param string $username username
3093 * @param string $hostname host name
3095 * @return string HTML snippet
3097 public static function getChangeLoginInformationHtmlForm($username, $hostname)
3099 $choices = array(
3100 '4' => __('… keep the old one.'),
3101 '1' => __('… delete the old one from the user tables.'),
3102 '2' => __(
3103 '… revoke all active privileges from '
3104 . 'the old one and delete it afterwards.'
3106 '3' => __(
3107 '… delete the old one from the user tables '
3108 . 'and reload the privileges afterwards.'
3112 $html_output = '<form action="server_privileges.php" '
3113 . 'onsubmit="return checkAddUser(this);" '
3114 . 'method="post" class="copyUserForm submenu-item">' . "\n"
3115 . Url::getHiddenInputs('', '')
3116 . '<input type="hidden" name="old_username" '
3117 . 'value="' . htmlspecialchars($username) . '" />' . "\n"
3118 . '<input type="hidden" name="old_hostname" '
3119 . 'value="' . htmlspecialchars($hostname) . '" />' . "\n";
3121 $usergroup = self::getUserGroupForUser($username);
3122 if ($usergroup !== null) {
3123 $html_output .= '<input type="hidden" name="old_usergroup" '
3124 . 'value="' . htmlspecialchars($usergroup) . '" />' . "\n";
3127 $html_output .= '<fieldset id="fieldset_change_copy_user">' . "\n"
3128 . '<legend data-submenu-label="' . __('Login Information') . '">' . "\n"
3129 . __('Change login information / Copy user account')
3130 . '</legend>' . "\n"
3131 . self::getHtmlForLoginInformationFields('change', $username, $hostname);
3133 $html_output .= '<fieldset id="fieldset_mode">' . "\n"
3134 . ' <legend>'
3135 . __('Create a new user account with the same privileges and …')
3136 . '</legend>' . "\n";
3137 $html_output .= Util::getRadioFields(
3138 'mode', $choices, '4', true
3140 $html_output .= '</fieldset>' . "\n"
3141 . '</fieldset>' . "\n";
3143 $html_output .= '<fieldset id="fieldset_change_copy_user_footer" '
3144 . 'class="tblFooters">' . "\n"
3145 . '<input type="hidden" name="change_copy" value="1" />' . "\n"
3146 . '<input type="submit" value="' . __('Go') . '" />' . "\n"
3147 . '</fieldset>' . "\n"
3148 . '</form>' . "\n";
3150 return $html_output;
3154 * Provide a line with links to the relevant database and table
3156 * @param string $url_dbname url database name that urlencode() string
3157 * @param string $dbname database name
3158 * @param string $tablename table name
3160 * @return string HTML snippet
3162 public static function getLinkToDbAndTable($url_dbname, $dbname, $tablename)
3164 $html_output = '[ ' . __('Database')
3165 . ' <a href="' . Util::getScriptNameForOption(
3166 $GLOBALS['cfg']['DefaultTabDatabase'], 'database'
3168 . Url::getCommon(
3169 array(
3170 'db' => $url_dbname,
3171 'reload' => 1
3174 . '">'
3175 . htmlspecialchars(Util::unescapeMysqlWildcards($dbname)) . ': '
3176 . Util::getTitleForTarget(
3177 $GLOBALS['cfg']['DefaultTabDatabase']
3179 . "</a> ]\n";
3181 if (strlen($tablename) > 0) {
3182 $html_output .= ' [ ' . __('Table') . ' <a href="'
3183 . Util::getScriptNameForOption(
3184 $GLOBALS['cfg']['DefaultTabTable'], 'table'
3186 . Url::getCommon(
3187 array(
3188 'db' => $url_dbname,
3189 'table' => $tablename,
3190 'reload' => 1,
3193 . '">' . htmlspecialchars($tablename) . ': '
3194 . Util::getTitleForTarget(
3195 $GLOBALS['cfg']['DefaultTabTable']
3197 . "</a> ]\n";
3199 return $html_output;
3203 * no db name given, so we want all privs for the given user
3204 * db name was given, so we want all user specific rights for this db
3205 * So this function returns user rights as an array
3207 * @param string $username username
3208 * @param string $hostname host name
3209 * @param string $type database or table
3210 * @param string $dbname database name
3212 * @return array $db_rights database rights
3214 public static function getUserSpecificRights($username, $hostname, $type, $dbname = '')
3216 $user_host_condition = " WHERE `User`"
3217 . " = '" . $GLOBALS['dbi']->escapeString($username) . "'"
3218 . " AND `Host`"
3219 . " = '" . $GLOBALS['dbi']->escapeString($hostname) . "'";
3221 if ($type == 'database') {
3222 $tables_to_search_for_users = array(
3223 'tables_priv', 'columns_priv', 'procs_priv'
3225 $dbOrTableName = 'Db';
3226 } elseif ($type == 'table') {
3227 $user_host_condition .= " AND `Db` LIKE '"
3228 . $GLOBALS['dbi']->escapeString($dbname) . "'";
3229 $tables_to_search_for_users = array('columns_priv',);
3230 $dbOrTableName = 'Table_name';
3231 } else { // routine
3232 $user_host_condition .= " AND `Db` LIKE '"
3233 . $GLOBALS['dbi']->escapeString($dbname) . "'";
3234 $tables_to_search_for_users = array('procs_priv',);
3235 $dbOrTableName = 'Routine_name';
3238 // we also want privileges for this user not in table `db` but in other table
3239 $tables = $GLOBALS['dbi']->fetchResult('SHOW TABLES FROM `mysql`;');
3241 $db_rights_sqls = array();
3242 foreach ($tables_to_search_for_users as $table_search_in) {
3243 if (in_array($table_search_in, $tables)) {
3244 $db_rights_sqls[] = '
3245 SELECT DISTINCT `' . $dbOrTableName . '`
3246 FROM `mysql`.' . Util::backquote($table_search_in)
3247 . $user_host_condition;
3251 $user_defaults = array(
3252 $dbOrTableName => '',
3253 'Grant_priv' => 'N',
3254 'privs' => array('USAGE'),
3255 'Column_priv' => true,
3258 // for the rights
3259 $db_rights = array();
3261 $db_rights_sql = '(' . implode(') UNION (', $db_rights_sqls) . ')'
3262 . ' ORDER BY `' . $dbOrTableName . '` ASC';
3264 $db_rights_result = $GLOBALS['dbi']->query($db_rights_sql);
3266 while ($db_rights_row = $GLOBALS['dbi']->fetchAssoc($db_rights_result)) {
3267 $db_rights_row = array_merge($user_defaults, $db_rights_row);
3268 if ($type == 'database') {
3269 // only Db names in the table `mysql`.`db` uses wildcards
3270 // as we are in the db specific rights display we want
3271 // all db names escaped, also from other sources
3272 $db_rights_row['Db'] = Util::escapeMysqlWildcards(
3273 $db_rights_row['Db']
3276 $db_rights[$db_rights_row[$dbOrTableName]] = $db_rights_row;
3279 $GLOBALS['dbi']->freeResult($db_rights_result);
3281 if ($type == 'database') {
3282 $sql_query = 'SELECT * FROM `mysql`.`db`'
3283 . $user_host_condition . ' ORDER BY `Db` ASC';
3284 } elseif ($type == 'table') {
3285 $sql_query = 'SELECT `Table_name`,'
3286 . ' `Table_priv`,'
3287 . ' IF(`Column_priv` = _latin1 \'\', 0, 1)'
3288 . ' AS \'Column_priv\''
3289 . ' FROM `mysql`.`tables_priv`'
3290 . $user_host_condition
3291 . ' ORDER BY `Table_name` ASC;';
3292 } else {
3293 $sql_query = "SELECT `Routine_name`, `Proc_priv`"
3294 . " FROM `mysql`.`procs_priv`"
3295 . $user_host_condition
3296 . " ORDER BY `Routine_name`";
3300 $result = $GLOBALS['dbi']->query($sql_query);
3302 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
3303 if (isset($db_rights[$row[$dbOrTableName]])) {
3304 $db_rights[$row[$dbOrTableName]]
3305 = array_merge($db_rights[$row[$dbOrTableName]], $row);
3306 } else {
3307 $db_rights[$row[$dbOrTableName]] = $row;
3309 if ($type == 'database') {
3310 // there are db specific rights for this user
3311 // so we can drop this db rights
3312 $db_rights[$row['Db']]['can_delete'] = true;
3315 $GLOBALS['dbi']->freeResult($result);
3316 return $db_rights;
3320 * Parses Proc_priv data
3322 * @param string $privs Proc_priv
3324 * @return array
3326 public static function parseProcPriv($privs)
3328 $result = array(
3329 'Alter_routine_priv' => 'N',
3330 'Execute_priv' => 'N',
3331 'Grant_priv' => 'N',
3333 foreach (explode(',', $privs) as $priv) {
3334 if ($priv == 'Alter Routine') {
3335 $result['Alter_routine_priv'] = 'Y';
3336 } else {
3337 $result[$priv . '_priv'] = 'Y';
3340 return $result;
3344 * Get a HTML table for display user's tabel specific or database specific rights
3346 * @param string $username username
3347 * @param string $hostname host name
3348 * @param string $type database, table or routine
3349 * @param string $dbname database name
3351 * @return array $html_output
3353 public static function getHtmlForAllTableSpecificRights(
3354 $username, $hostname, $type, $dbname = ''
3356 $uiData = array(
3357 'database' => array(
3358 'form_id' => 'database_specific_priv',
3359 'sub_menu_label' => __('Database'),
3360 'legend' => __('Database-specific privileges'),
3361 'type_label' => __('Database'),
3363 'table' => array(
3364 'form_id' => 'table_specific_priv',
3365 'sub_menu_label' => __('Table'),
3366 'legend' => __('Table-specific privileges'),
3367 'type_label' => __('Table'),
3369 'routine' => array(
3370 'form_id' => 'routine_specific_priv',
3371 'sub_menu_label' => __('Routine'),
3372 'legend' => __('Routine-specific privileges'),
3373 'type_label' => __('Routine'),
3378 * no db name given, so we want all privs for the given user
3379 * db name was given, so we want all user specific rights for this db
3381 $db_rights = self::getUserSpecificRights($username, $hostname, $type, $dbname);
3382 ksort($db_rights);
3384 $foundRows = array();
3385 $privileges = array();
3386 foreach ($db_rights as $row) {
3387 $onePrivilege = array();
3389 $paramTableName = '';
3390 $paramRoutineName = '';
3392 if ($type == 'database') {
3393 $name = $row['Db'];
3394 $onePrivilege['grant'] = $row['Grant_priv'] == 'Y';
3395 $onePrivilege['table_privs'] = ! empty($row['Table_priv'])
3396 || ! empty($row['Column_priv']);
3397 $onePrivilege['privileges'] = join(',', self::extractPrivInfo($row, true));
3399 $paramDbName = $row['Db'];
3401 } elseif ($type == 'table') {
3402 $name = $row['Table_name'];
3403 $onePrivilege['grant'] = in_array(
3404 'Grant',
3405 explode(',', $row['Table_priv'])
3407 $onePrivilege['column_privs'] = ! empty($row['Column_priv']);
3408 $onePrivilege['privileges'] = join(',', self::extractPrivInfo($row, true));
3410 $paramDbName = $dbname;
3411 $paramTableName = $row['Table_name'];
3413 } else { // routine
3414 $name = $row['Routine_name'];
3415 $onePrivilege['grant'] = in_array(
3416 'Grant',
3417 explode(',', $row['Proc_priv'])
3420 $privs = self::parseProcPriv($row['Proc_priv']);
3421 $onePrivilege['privileges'] = join(
3422 ',',
3423 self::extractPrivInfo($privs, true)
3426 $paramDbName = $dbname;
3427 $paramRoutineName = $row['Routine_name'];
3430 $foundRows[] = $name;
3431 $onePrivilege['name'] = $name;
3433 $onePrivilege['edit_link'] = '';
3434 if ($GLOBALS['is_grantuser']) {
3435 $onePrivilege['edit_link'] = self::getUserLink(
3436 'edit',
3437 $username,
3438 $hostname,
3439 $paramDbName,
3440 $paramTableName,
3441 $paramRoutineName
3445 $onePrivilege['revoke_link'] = '';
3446 if ($type != 'database' || ! empty($row['can_delete'])) {
3447 $onePrivilege['revoke_link'] = self::getUserLink(
3448 'revoke',
3449 $username,
3450 $hostname,
3451 $paramDbName,
3452 $paramTableName,
3453 $paramRoutineName
3457 $privileges[] = $onePrivilege;
3460 $data = $uiData[$type];
3461 $data['privileges'] = $privileges;
3462 $data['username'] = $username;
3463 $data['hostname'] = $hostname;
3464 $data['database'] = $dbname;
3465 $data['type'] = $type;
3467 if ($type == 'database') {
3469 // we already have the list of databases from libraries/common.inc.php
3470 // via $pma = new PMA;
3471 $pred_db_array = $GLOBALS['dblist']->databases;
3472 $databases_to_skip = array('information_schema', 'performance_schema');
3474 $databases = array();
3475 if (! empty($pred_db_array)) {
3476 foreach ($pred_db_array as $current_db) {
3477 if (in_array($current_db, $databases_to_skip)) {
3478 continue;
3480 $current_db_escaped = Util::escapeMysqlWildcards($current_db);
3481 // cannot use array_diff() once, outside of the loop,
3482 // because the list of databases has special characters
3483 // already escaped in $foundRows,
3484 // contrary to the output of SHOW DATABASES
3485 if (! in_array($current_db_escaped, $foundRows)) {
3486 $databases[] = $current_db;
3490 $data['databases'] = $databases;
3492 } elseif ($type == 'table') {
3493 $result = @$GLOBALS['dbi']->tryQuery(
3494 "SHOW TABLES FROM " . Util::backquote($dbname),
3495 DatabaseInterface::CONNECT_USER,
3496 DatabaseInterface::QUERY_STORE
3499 $tables = array();
3500 if ($result) {
3501 while ($row = $GLOBALS['dbi']->fetchRow($result)) {
3502 if (! in_array($row[0], $foundRows)) {
3503 $tables[] = $row[0];
3506 $GLOBALS['dbi']->freeResult($result);
3508 $data['tables'] = $tables;
3510 } else { // routine
3511 $routineData = $GLOBALS['dbi']->getRoutines($dbname);
3513 $routines = array();
3514 foreach ($routineData as $routine) {
3515 if (! in_array($routine['name'], $foundRows)) {
3516 $routines[] = $routine['name'];
3519 $data['routines'] = $routines;
3522 $html_output = Template::get('privileges/privileges_summary')
3523 ->render($data);
3525 return $html_output;
3529 * Get HTML for display the users overview
3530 * (if less than 50 users, display them immediately)
3532 * @param array $result ran sql query
3533 * @param array $db_rights user's database rights array
3534 * @param string $pmaThemeImage a image source link
3535 * @param string $text_dir text directory
3537 * @return string HTML snippet
3539 public static function getUsersOverview($result, array $db_rights, $pmaThemeImage, $text_dir)
3541 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
3542 $row['privs'] = self::extractPrivInfo($row, true);
3543 $db_rights[$row['User']][$row['Host']] = $row;
3545 $GLOBALS['dbi']->freeResult($result);
3546 $user_group_count = 0;
3547 if ($GLOBALS['cfgRelation']['menuswork']) {
3548 $user_group_count = self::getUserGroupCount();
3551 $html_output
3552 = '<form name="usersForm" id="usersForm" action="server_privileges.php" '
3553 . 'method="post">' . "\n"
3554 . Url::getHiddenInputs('', '')
3555 . '<div class="responsivetable">'
3556 . '<table id="tableuserrights" class="data">' . "\n"
3557 . '<thead>' . "\n"
3558 . '<tr><th></th>' . "\n"
3559 . '<th>' . __('User name') . '</th>' . "\n"
3560 . '<th>' . __('Host name') . '</th>' . "\n"
3561 . '<th>' . __('Password') . '</th>' . "\n"
3562 . '<th>' . __('Global privileges') . ' '
3563 . Util::showHint(
3564 __('Note: MySQL privilege names are expressed in English.')
3566 . '</th>' . "\n";
3567 if ($GLOBALS['cfgRelation']['menuswork']) {
3568 $html_output .= '<th>' . __('User group') . '</th>' . "\n";
3570 $html_output .= '<th>' . __('Grant') . '</th>' . "\n"
3571 . '<th colspan="' . ($user_group_count > 0 ? '3' : '2') . '">'
3572 . __('Action') . '</th>' . "\n"
3573 . '</tr>' . "\n"
3574 . '</thead>' . "\n";
3576 $html_output .= '<tbody>' . "\n";
3577 $html_output .= self::getHtmlTableBodyForUserRights($db_rights);
3578 $html_output .= '</tbody>'
3579 . '</table></div>' . "\n";
3581 $html_output .= '<div class="floatleft">'
3582 . Template::get('select_all')
3583 ->render(
3584 array(
3585 'pma_theme_image' => $pmaThemeImage,
3586 'text_dir' => $text_dir,
3587 'form_name' => 'usersForm',
3589 ) . "\n";
3590 $html_output .= Util::getButtonOrImage(
3591 'submit_mult', 'mult_submit',
3592 __('Export'), 'b_tblexport', 'export'
3594 $html_output .= '<input type="hidden" name="initial" '
3595 . 'value="' . (isset($_GET['initial']) ? htmlspecialchars($_GET['initial']) : '') . '" />';
3596 $html_output .= '</div>'
3597 . '<div class="clearfloat"></div>';
3599 // add/delete user fieldset
3600 $html_output .= self::getFieldsetForAddDeleteUser();
3601 $html_output .= '</form>' . "\n";
3603 return $html_output;
3607 * Get table body for 'tableuserrights' table in userform
3609 * @param array $db_rights user's database rights array
3611 * @return string HTML snippet
3613 public static function getHtmlTableBodyForUserRights(array $db_rights)
3615 $relation = new Relation();
3616 $cfgRelation = $relation->getRelationsParam();
3617 if ($cfgRelation['menuswork']) {
3618 $users_table = Util::backquote($cfgRelation['db'])
3619 . "." . Util::backquote($cfgRelation['users']);
3620 $sql_query = 'SELECT * FROM ' . $users_table;
3621 $result = $relation->queryAsControlUser($sql_query, false);
3622 $group_assignment = array();
3623 if ($result) {
3624 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
3625 $group_assignment[$row['username']] = $row['usergroup'];
3628 $GLOBALS['dbi']->freeResult($result);
3630 $user_group_count = self::getUserGroupCount();
3633 $index_checkbox = 0;
3634 $html_output = '';
3635 foreach ($db_rights as $user) {
3636 ksort($user);
3637 foreach ($user as $host) {
3638 $index_checkbox++;
3639 $html_output .= '<tr>'
3640 . "\n";
3641 $html_output .= '<td>'
3642 . '<input type="checkbox" class="checkall" name="selected_usr[]" '
3643 . 'id="checkbox_sel_users_'
3644 . $index_checkbox . '" value="'
3645 . htmlspecialchars($host['User'] . '&amp;#27;' . $host['Host'])
3646 . '"'
3647 . ' /></td>' . "\n";
3649 $html_output .= '<td><label '
3650 . 'for="checkbox_sel_users_' . $index_checkbox . '">'
3651 . (empty($host['User'])
3652 ? '<span style="color: #FF0000">' . __('Any') . '</span>'
3653 : htmlspecialchars($host['User'])) . '</label></td>' . "\n"
3654 . '<td>' . htmlspecialchars($host['Host']) . '</td>' . "\n";
3656 $html_output .= '<td>';
3658 $password_column = 'Password';
3660 $check_plugin_query = "SELECT * FROM `mysql`.`user` WHERE "
3661 . "`User` = '" . $host['User'] . "' AND `Host` = '"
3662 . $host['Host'] . "'";
3663 $res = $GLOBALS['dbi']->fetchSingleRow($check_plugin_query);
3665 if ((isset($res['authentication_string'])
3666 && ! empty($res['authentication_string']))
3667 || (isset($res['Password'])
3668 && ! empty($res['Password']))
3670 $host[$password_column] = 'Y';
3671 } else {
3672 $host[$password_column] = 'N';
3675 switch ($host[$password_column]) {
3676 case 'Y':
3677 $html_output .= __('Yes');
3678 break;
3679 case 'N':
3680 $html_output .= '<span style="color: #FF0000">' . __('No')
3681 . '</span>';
3682 break;
3683 // this happens if this is a definition not coming from mysql.user
3684 default:
3685 $html_output .= '--'; // in future version, replace by "not present"
3686 break;
3687 } // end switch
3689 if (! isset($host['Select_priv'])) {
3690 $html_output .= Util::showHint(
3691 __('The selected user was not found in the privilege table.')
3695 $html_output .= '</td>' . "\n";
3697 $html_output .= '<td><code>' . "\n"
3698 . '' . implode(',' . "\n" . ' ', $host['privs']) . "\n"
3699 . '</code></td>' . "\n";
3700 if ($cfgRelation['menuswork']) {
3701 $html_output .= '<td class="usrGroup">' . "\n"
3702 . (isset($group_assignment[$host['User']])
3703 ? htmlspecialchars($group_assignment[$host['User']])
3704 : ''
3706 . '</td>' . "\n";
3708 $html_output .= '<td>'
3709 . ($host['Grant_priv'] == 'Y' ? __('Yes') : __('No'))
3710 . '</td>' . "\n";
3712 if ($GLOBALS['is_grantuser']) {
3713 $html_output .= '<td class="center">'
3714 . self::getUserLink(
3715 'edit',
3716 $host['User'],
3717 $host['Host']
3719 . '</td>';
3721 if ($cfgRelation['menuswork'] && $user_group_count > 0) {
3722 if (empty($host['User'])) {
3723 $html_output .= '<td class="center"></td>';
3724 } else {
3725 $html_output .= '<td class="center">'
3726 . self::getUserGroupEditLink($host['User'])
3727 . '</td>';
3730 $html_output .= '<td class="center">'
3731 . self::getUserLink(
3732 'export',
3733 $host['User'],
3734 $host['Host'],
3738 isset($_GET['initial']) ? $_GET['initial'] : ''
3740 . '</td>';
3741 $html_output .= '</tr>';
3744 return $html_output;
3748 * Get HTML fieldset for Add/Delete user
3750 * @return string HTML snippet
3752 public static function getFieldsetForAddDeleteUser()
3754 $html_output = self::getAddUserHtmlFieldset();
3756 $html_output .= Template::get('privileges/delete_user_fieldset')
3757 ->render(array());
3759 return $html_output;
3763 * Get HTML for Displays the initials
3765 * @param array $array_initials array for all initials, even non A-Z
3767 * @return string HTML snippet
3769 public static function getHtmlForInitials(array $array_initials)
3771 // initialize to false the letters A-Z
3772 for ($letter_counter = 1; $letter_counter < 27; $letter_counter++) {
3773 if (! isset($array_initials[mb_chr($letter_counter + 64)])) {
3774 $array_initials[mb_chr($letter_counter + 64)] = false;
3778 $initials = $GLOBALS['dbi']->tryQuery(
3779 'SELECT DISTINCT UPPER(LEFT(`User`,1)) FROM `user`'
3780 . ' ORDER BY UPPER(LEFT(`User`,1)) ASC',
3781 DatabaseInterface::CONNECT_USER,
3782 DatabaseInterface::QUERY_STORE
3784 if ($initials) {
3785 while (list($tmp_initial) = $GLOBALS['dbi']->fetchRow($initials)) {
3786 $array_initials[$tmp_initial] = true;
3790 // Display the initials, which can be any characters, not
3791 // just letters. For letters A-Z, we add the non-used letters
3792 // as greyed out.
3794 uksort($array_initials, "strnatcasecmp");
3796 $html_output = Template::get('privileges/initials_row')
3797 ->render(
3798 array(
3799 'array_initials' => $array_initials,
3800 'initial' => isset($_GET['initial']) ? $_GET['initial'] : null,
3804 return $html_output;
3808 * Get the database rights array for Display user overview
3810 * @return array $db_rights database rights array
3812 public static function getDbRightsForUserOverview()
3814 // we also want users not in table `user` but in other table
3815 $tables = $GLOBALS['dbi']->fetchResult('SHOW TABLES FROM `mysql`;');
3817 $tablesSearchForUsers = array(
3818 'user', 'db', 'tables_priv', 'columns_priv', 'procs_priv',
3821 $db_rights_sqls = array();
3822 foreach ($tablesSearchForUsers as $table_search_in) {
3823 if (in_array($table_search_in, $tables)) {
3824 $db_rights_sqls[] = 'SELECT DISTINCT `User`, `Host` FROM `mysql`.`'
3825 . $table_search_in . '` '
3826 . (isset($_GET['initial'])
3827 ? self::rangeOfUsers($_GET['initial'])
3828 : '');
3831 $user_defaults = array(
3832 'User' => '',
3833 'Host' => '%',
3834 'Password' => '?',
3835 'Grant_priv' => 'N',
3836 'privs' => array('USAGE'),
3839 // for the rights
3840 $db_rights = array();
3842 $db_rights_sql = '(' . implode(') UNION (', $db_rights_sqls) . ')'
3843 . ' ORDER BY `User` ASC, `Host` ASC';
3845 $db_rights_result = $GLOBALS['dbi']->query($db_rights_sql);
3847 while ($db_rights_row = $GLOBALS['dbi']->fetchAssoc($db_rights_result)) {
3848 $db_rights_row = array_merge($user_defaults, $db_rights_row);
3849 $db_rights[$db_rights_row['User']][$db_rights_row['Host']]
3850 = $db_rights_row;
3852 $GLOBALS['dbi']->freeResult($db_rights_result);
3853 ksort($db_rights);
3855 return $db_rights;
3859 * Delete user and get message and sql query for delete user in privileges
3861 * @param array $queries queries
3863 * @return array Message
3865 public static function deleteUser(array $queries)
3867 $sql_query = '';
3868 if (empty($queries)) {
3869 $message = Message::error(__('No users selected for deleting!'));
3870 } else {
3871 if ($_POST['mode'] == 3) {
3872 $queries[] = '# ' . __('Reloading the privileges') . ' …';
3873 $queries[] = 'FLUSH PRIVILEGES;';
3875 $drop_user_error = '';
3876 foreach ($queries as $sql_query) {
3877 if ($sql_query[0] != '#') {
3878 if (! $GLOBALS['dbi']->tryQuery($sql_query)) {
3879 $drop_user_error .= $GLOBALS['dbi']->getError() . "\n";
3883 // tracking sets this, causing the deleted db to be shown in navi
3884 unset($GLOBALS['db']);
3886 $sql_query = join("\n", $queries);
3887 if (! empty($drop_user_error)) {
3888 $message = Message::rawError($drop_user_error);
3889 } else {
3890 $message = Message::success(
3891 __('The selected users have been deleted successfully.')
3895 return array($sql_query, $message);
3899 * Update the privileges and return the success or error message
3901 * @param string $username username
3902 * @param string $hostname host name
3903 * @param string $tablename table name
3904 * @param string $dbname database name
3905 * @param string $itemType item type
3907 * @return Message success message or error message for update
3909 public static function updatePrivileges($username, $hostname, $tablename, $dbname, $itemType)
3911 $db_and_table = self::wildcardEscapeForGrant($dbname, $tablename);
3913 $sql_query0 = 'REVOKE ALL PRIVILEGES ON ' . $itemType . ' ' . $db_and_table
3914 . ' FROM \'' . $GLOBALS['dbi']->escapeString($username)
3915 . '\'@\'' . $GLOBALS['dbi']->escapeString($hostname) . '\';';
3917 if (! isset($_POST['Grant_priv']) || $_POST['Grant_priv'] != 'Y') {
3918 $sql_query1 = 'REVOKE GRANT OPTION ON ' . $itemType . ' ' . $db_and_table
3919 . ' FROM \'' . $GLOBALS['dbi']->escapeString($username) . '\'@\''
3920 . $GLOBALS['dbi']->escapeString($hostname) . '\';';
3921 } else {
3922 $sql_query1 = '';
3925 // Should not do a GRANT USAGE for a table-specific privilege, it
3926 // causes problems later (cannot revoke it)
3927 if (! (strlen($tablename) > 0
3928 && 'USAGE' == implode('', self::extractPrivInfo()))
3930 $sql_query2 = 'GRANT ' . join(', ', self::extractPrivInfo())
3931 . ' ON ' . $itemType . ' ' . $db_and_table
3932 . ' TO \'' . $GLOBALS['dbi']->escapeString($username) . '\'@\''
3933 . $GLOBALS['dbi']->escapeString($hostname) . '\'';
3935 if (strlen($dbname) === 0) {
3936 // add REQUIRE clause
3937 $sql_query2 .= self::getRequireClause();
3940 if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
3941 || (strlen($dbname) === 0
3942 && (isset($_POST['max_questions']) || isset($_POST['max_connections'])
3943 || isset($_POST['max_updates'])
3944 || isset($_POST['max_user_connections'])))
3946 $sql_query2 .= self::getWithClauseForAddUserAndUpdatePrivs();
3948 $sql_query2 .= ';';
3950 if (! $GLOBALS['dbi']->tryQuery($sql_query0)) {
3951 // This might fail when the executing user does not have
3952 // ALL PRIVILEGES himself.
3953 // See https://github.com/phpmyadmin/phpmyadmin/issues/9673
3954 $sql_query0 = '';
3956 if (! empty($sql_query1) && ! $GLOBALS['dbi']->tryQuery($sql_query1)) {
3957 // this one may fail, too...
3958 $sql_query1 = '';
3960 if (! empty($sql_query2)) {
3961 $GLOBALS['dbi']->query($sql_query2);
3962 } else {
3963 $sql_query2 = '';
3965 $sql_query = $sql_query0 . ' ' . $sql_query1 . ' ' . $sql_query2;
3966 $message = Message::success(__('You have updated the privileges for %s.'));
3967 $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
3969 return array($sql_query, $message);
3973 * Get List of information: Changes / copies a user
3975 * @return array
3977 public static function getDataForChangeOrCopyUser()
3979 $queries = null;
3980 $password = null;
3982 if (isset($_POST['change_copy'])) {
3983 $user_host_condition = ' WHERE `User` = '
3984 . "'" . $GLOBALS['dbi']->escapeString($_POST['old_username']) . "'"
3985 . ' AND `Host` = '
3986 . "'" . $GLOBALS['dbi']->escapeString($_POST['old_hostname']) . "';";
3987 $row = $GLOBALS['dbi']->fetchSingleRow(
3988 'SELECT * FROM `mysql`.`user` ' . $user_host_condition
3990 if (! $row) {
3991 $response = Response::getInstance();
3992 $response->addHTML(
3993 Message::notice(__('No user found.'))->getDisplay()
3995 unset($_POST['change_copy']);
3996 } else {
3997 extract($row, EXTR_OVERWRITE);
3998 foreach ($row as $key => $value) {
3999 $GLOBALS[$key] = $value;
4001 $serverVersion = $GLOBALS['dbi']->getVersion();
4002 // Recent MySQL versions have the field "Password" in mysql.user,
4003 // so the previous extract creates $Password but this script
4004 // uses $password
4005 if (! isset($password) && isset($Password)) {
4006 $password = $Password;
4008 if (Util::getServerType() == 'MySQL'
4009 && $serverVersion >= 50606
4010 && $serverVersion < 50706
4011 && ((isset($authentication_string)
4012 && empty($password))
4013 || (isset($plugin)
4014 && $plugin == 'sha256_password'))
4016 $password = $authentication_string;
4019 if (Util::getServerType() == 'MariaDB'
4020 && $serverVersion >= 50500
4021 && isset($authentication_string)
4022 && empty($password)
4024 $password = $authentication_string;
4027 // Always use 'authentication_string' column
4028 // for MySQL 5.7.6+ since it does not have
4029 // the 'password' column at all
4030 if (in_array(Util::getServerType(), array('MySQL', 'Percona Server'))
4031 && $serverVersion >= 50706
4032 && isset($authentication_string)
4034 $password = $authentication_string;
4037 $queries = array();
4041 return array($queries, $password);
4045 * Update Data for information: Deletes users
4047 * @param array $queries queries array
4049 * @return array
4051 public static function getDataForDeleteUsers($queries)
4053 if (isset($_POST['change_copy'])) {
4054 $selected_usr = array(
4055 $_POST['old_username'] . '&amp;#27;' . $_POST['old_hostname']
4057 } else {
4058 $selected_usr = $_POST['selected_usr'];
4059 $queries = array();
4062 // this happens, was seen in https://reports.phpmyadmin.net/reports/view/17146
4063 if (! is_array($selected_usr)) {
4064 return array();
4067 foreach ($selected_usr as $each_user) {
4068 list($this_user, $this_host) = explode('&amp;#27;', $each_user);
4069 $queries[] = '# '
4070 . sprintf(
4071 __('Deleting %s'),
4072 '\'' . $this_user . '\'@\'' . $this_host . '\''
4074 . ' ...';
4075 $queries[] = 'DROP USER \''
4076 . $GLOBALS['dbi']->escapeString($this_user)
4077 . '\'@\'' . $GLOBALS['dbi']->escapeString($this_host) . '\';';
4078 RelationCleanup::user($this_user);
4080 if (isset($_POST['drop_users_db'])) {
4081 $queries[] = 'DROP DATABASE IF EXISTS '
4082 . Util::backquote($this_user) . ';';
4083 $GLOBALS['reload'] = true;
4086 return $queries;
4090 * update Message For Reload
4092 * @return array
4094 public static function updateMessageForReload()
4096 $message = null;
4097 if (isset($_GET['flush_privileges'])) {
4098 $sql_query = 'FLUSH PRIVILEGES;';
4099 $GLOBALS['dbi']->query($sql_query);
4100 $message = Message::success(
4101 __('The privileges were reloaded successfully.')
4105 if (isset($_GET['validate_username'])) {
4106 $message = Message::success();
4109 return $message;
4113 * update Data For Queries from queries_for_display
4115 * @param array $queries queries array
4116 * @param array|null $queries_for_display queries array for display
4118 * @return null
4120 public static function getDataForQueries(array $queries, $queries_for_display)
4122 $tmp_count = 0;
4123 foreach ($queries as $sql_query) {
4124 if ($sql_query[0] != '#') {
4125 $GLOBALS['dbi']->query($sql_query);
4127 // when there is a query containing a hidden password, take it
4128 // instead of the real query sent
4129 if (isset($queries_for_display[$tmp_count])) {
4130 $queries[$tmp_count] = $queries_for_display[$tmp_count];
4132 $tmp_count++;
4135 return $queries;
4139 * update Data for information: Adds a user
4141 * @param string $dbname db name
4142 * @param string $username user name
4143 * @param string $hostname host name
4144 * @param string $password password
4145 * @param bool $is_menuwork is_menuwork set?
4147 * @return array
4149 public static function addUser(
4150 $dbname, $username, $hostname,
4151 $password, $is_menuwork
4153 $_add_user_error = false;
4154 $message = null;
4155 $queries = null;
4156 $queries_for_display = null;
4157 $sql_query = null;
4159 if (!isset($_POST['adduser_submit']) && !isset($_POST['change_copy'])) {
4160 return array(
4161 $message, $queries, $queries_for_display, $sql_query, $_add_user_error
4165 $sql_query = '';
4166 if ($_POST['pred_username'] == 'any') {
4167 $username = '';
4169 switch ($_POST['pred_hostname']) {
4170 case 'any':
4171 $hostname = '%';
4172 break;
4173 case 'localhost':
4174 $hostname = 'localhost';
4175 break;
4176 case 'hosttable':
4177 $hostname = '';
4178 break;
4179 case 'thishost':
4180 $_user_name = $GLOBALS['dbi']->fetchValue('SELECT USER()');
4181 $hostname = mb_substr(
4182 $_user_name,
4183 (mb_strrpos($_user_name, '@') + 1)
4185 unset($_user_name);
4186 break;
4188 $sql = "SELECT '1' FROM `mysql`.`user`"
4189 . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username) . "'"
4190 . " AND `Host` = '" . $GLOBALS['dbi']->escapeString($hostname) . "';";
4191 if ($GLOBALS['dbi']->fetchValue($sql) == 1) {
4192 $message = Message::error(__('The user %s already exists!'));
4193 $message->addParam('[em]\'' . $username . '\'@\'' . $hostname . '\'[/em]');
4194 $_GET['adduser'] = true;
4195 $_add_user_error = true;
4197 return array(
4198 $message,
4199 $queries,
4200 $queries_for_display,
4201 $sql_query,
4202 $_add_user_error
4206 list(
4207 $create_user_real, $create_user_show, $real_sql_query, $sql_query,
4208 $password_set_real, $password_set_show,
4209 $alter_real_sql_query,
4210 $alter_sql_query
4211 ) = self::getSqlQueriesForDisplayAndAddUser(
4212 $username, $hostname, (isset($password) ? $password : '')
4215 if (empty($_POST['change_copy'])) {
4216 $_error = false;
4218 if (isset($create_user_real)) {
4219 if (!$GLOBALS['dbi']->tryQuery($create_user_real)) {
4220 $_error = true;
4222 if (isset($password_set_real) && !empty($password_set_real)
4223 && isset($_POST['authentication_plugin'])
4225 self::setProperPasswordHashing(
4226 $_POST['authentication_plugin']
4228 if ($GLOBALS['dbi']->tryQuery($password_set_real)) {
4229 $sql_query .= $password_set_show;
4232 $sql_query = $create_user_show . $sql_query;
4235 list($sql_query, $message) = self::addUserAndCreateDatabase(
4236 $_error,
4237 $real_sql_query,
4238 $sql_query,
4239 $username,
4240 $hostname,
4241 isset($dbname) ? $dbname : null,
4242 $alter_real_sql_query,
4243 $alter_sql_query
4245 if (!empty($_POST['userGroup']) && $is_menuwork) {
4246 self::setUserGroup($GLOBALS['username'], $_POST['userGroup']);
4249 return array(
4250 $message,
4251 $queries,
4252 $queries_for_display,
4253 $sql_query,
4254 $_add_user_error
4258 // Copy the user group while copying a user
4259 $old_usergroup =
4260 isset($_POST['old_usergroup']) ? $_POST['old_usergroup'] : null;
4261 self::setUserGroup($_POST['username'], $old_usergroup);
4263 if (isset($create_user_real)) {
4264 $queries[] = $create_user_real;
4266 $queries[] = $real_sql_query;
4268 if (isset($password_set_real) && ! empty($password_set_real)
4269 && isset($_POST['authentication_plugin'])
4271 self::setProperPasswordHashing(
4272 $_POST['authentication_plugin']
4275 $queries[] = $password_set_real;
4277 // we put the query containing the hidden password in
4278 // $queries_for_display, at the same position occupied
4279 // by the real query in $queries
4280 $tmp_count = count($queries);
4281 if (isset($create_user_real)) {
4282 $queries_for_display[$tmp_count - 2] = $create_user_show;
4284 if (isset($password_set_real) && ! empty($password_set_real)) {
4285 $queries_for_display[$tmp_count - 3] = $create_user_show;
4286 $queries_for_display[$tmp_count - 2] = $sql_query;
4287 $queries_for_display[$tmp_count - 1] = $password_set_show;
4288 } else {
4289 $queries_for_display[$tmp_count - 1] = $sql_query;
4292 return array(
4293 $message, $queries, $queries_for_display, $sql_query, $_add_user_error
4298 * Sets proper value of `old_passwords` according to
4299 * the authentication plugin selected
4301 * @param string $auth_plugin authentication plugin selected
4303 * @return void
4305 public static function setProperPasswordHashing($auth_plugin)
4307 // Set the hashing method used by PASSWORD()
4308 // to be of type depending upon $authentication_plugin
4309 if ($auth_plugin == 'sha256_password') {
4310 $GLOBALS['dbi']->tryQuery('SET `old_passwords` = 2;');
4311 } elseif ($auth_plugin == 'mysql_old_password') {
4312 $GLOBALS['dbi']->tryQuery('SET `old_passwords` = 1;');
4313 } else {
4314 $GLOBALS['dbi']->tryQuery('SET `old_passwords` = 0;');
4319 * Update DB information: DB, Table, isWildcard
4321 * @return array
4323 public static function getDataForDBInfo()
4325 $username = null;
4326 $hostname = null;
4327 $dbname = null;
4328 $tablename = null;
4329 $routinename = null;
4330 $dbname_is_wildcard = null;
4332 if (isset($_REQUEST['username'])) {
4333 $username = $_REQUEST['username'];
4335 if (isset($_REQUEST['hostname'])) {
4336 $hostname = $_REQUEST['hostname'];
4339 * Checks if a dropdown box has been used for selecting a database / table
4341 if (Core::isValid($_POST['pred_tablename'])) {
4342 $tablename = $_POST['pred_tablename'];
4343 } elseif (Core::isValid($_REQUEST['tablename'])) {
4344 $tablename = $_REQUEST['tablename'];
4345 } else {
4346 unset($tablename);
4349 if (Core::isValid($_POST['pred_routinename'])) {
4350 $routinename = $_POST['pred_routinename'];
4351 } elseif (Core::isValid($_REQUEST['routinename'])) {
4352 $routinename = $_REQUEST['routinename'];
4353 } else {
4354 unset($routinename);
4357 if (isset($_POST['pred_dbname'])) {
4358 $is_valid_pred_dbname = true;
4359 foreach ($_POST['pred_dbname'] as $key => $db_name) {
4360 if (! Core::isValid($db_name)) {
4361 $is_valid_pred_dbname = false;
4362 break;
4367 if (isset($_REQUEST['dbname'])) {
4368 $is_valid_dbname = true;
4369 if (is_array($_REQUEST['dbname'])) {
4370 foreach ($_REQUEST['dbname'] as $key => $db_name) {
4371 if (! Core::isValid($db_name)) {
4372 $is_valid_dbname = false;
4373 break;
4376 } else {
4377 if (! Core::isValid($_REQUEST['dbname'])) {
4378 $is_valid_dbname = false;
4383 if (isset($is_valid_pred_dbname) && $is_valid_pred_dbname) {
4384 $dbname = $_POST['pred_dbname'];
4385 // If dbname contains only one database.
4386 if (count($dbname) == 1) {
4387 $dbname = $dbname[0];
4389 } elseif (isset($is_valid_dbname) && $is_valid_dbname) {
4390 $dbname = $_REQUEST['dbname'];
4391 } else {
4392 unset($dbname);
4393 unset($tablename);
4396 if (isset($dbname)) {
4397 if (is_array($dbname)) {
4398 $db_and_table = $dbname;
4399 foreach ($db_and_table as $key => $db_name) {
4400 $db_and_table[$key] .= '.';
4402 } else {
4403 $unescaped_db = Util::unescapeMysqlWildcards($dbname);
4404 $db_and_table = Util::backquote($unescaped_db) . '.';
4406 if (isset($tablename)) {
4407 $db_and_table .= Util::backquote($tablename);
4408 } else {
4409 if (is_array($db_and_table)) {
4410 foreach ($db_and_table as $key => $db_name) {
4411 $db_and_table[$key] .= '*';
4413 } else {
4414 $db_and_table .= '*';
4417 } else {
4418 $db_and_table = '*.*';
4421 // check if given $dbname is a wildcard or not
4422 if (isset($dbname)) {
4423 //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
4424 if (! is_array($dbname) && preg_match('/(?<!\\\\)(?:_|%)/i', $dbname)) {
4425 $dbname_is_wildcard = true;
4426 } else {
4427 $dbname_is_wildcard = false;
4431 return array(
4432 $username, $hostname,
4433 isset($dbname)? $dbname : null,
4434 isset($tablename)? $tablename : null,
4435 isset($routinename) ? $routinename : null,
4436 $db_and_table,
4437 $dbname_is_wildcard,
4442 * Get title and textarea for export user definition in Privileges
4444 * @param string $username username
4445 * @param string $hostname host name
4447 * @return array ($title, $export)
4449 public static function getListForExportUserDefinition($username, $hostname)
4451 $export = '<textarea class="export" cols="60" rows="15">';
4453 if (isset($_POST['selected_usr'])) {
4454 // export privileges for selected users
4455 $title = __('Privileges');
4457 //For removing duplicate entries of users
4458 $_POST['selected_usr'] = array_unique($_POST['selected_usr']);
4460 foreach ($_POST['selected_usr'] as $export_user) {
4461 $export_username = mb_substr(
4462 $export_user, 0, mb_strpos($export_user, '&')
4464 $export_hostname = mb_substr(
4465 $export_user, mb_strrpos($export_user, ';') + 1
4467 $export .= '# '
4468 . sprintf(
4469 __('Privileges for %s'),
4470 '`' . htmlspecialchars($export_username)
4471 . '`@`' . htmlspecialchars($export_hostname) . '`'
4473 . "\n\n";
4474 $export .= self::getGrants($export_username, $export_hostname) . "\n";
4476 } else {
4477 // export privileges for a single user
4478 $title = __('User') . ' `' . htmlspecialchars($username)
4479 . '`@`' . htmlspecialchars($hostname) . '`';
4480 $export .= self::getGrants($username, $hostname);
4482 // remove trailing whitespace
4483 $export = trim($export);
4485 $export .= '</textarea>';
4487 return array($title, $export);
4491 * Get HTML for display Add userfieldset
4493 * @param string $db the database
4494 * @param string $table the table name
4496 * @return string html output
4498 public static function getAddUserHtmlFieldset($db = '', $table = '')
4500 if (!$GLOBALS['is_createuser']) {
4501 return '';
4503 $rel_params = array();
4504 $url_params = array(
4505 'adduser' => 1
4507 if (!empty($db)) {
4508 $url_params['dbname']
4509 = $rel_params['checkprivsdb']
4510 = $db;
4512 if (!empty($table)) {
4513 $url_params['tablename']
4514 = $rel_params['checkprivstable']
4515 = $table;
4518 return Template::get('privileges/add_user_fieldset')
4519 ->render(
4520 array(
4521 'url_params' => $url_params,
4522 'rel_params' => $rel_params
4528 * Get HTML header for display User's properties
4530 * @param boolean $dbname_is_wildcard whether database name is wildcard or not
4531 * @param string $url_dbname url database name that urlencode() string
4532 * @param string $dbname database name
4533 * @param string $username username
4534 * @param string $hostname host name
4535 * @param string $entity_name entity (table or routine) name
4536 * @param string $entity_type optional, type of entity ('table' or 'routine')
4538 * @return string $html_output
4540 public static function getHtmlHeaderForUserProperties(
4541 $dbname_is_wildcard, $url_dbname, $dbname,
4542 $username, $hostname, $entity_name, $entity_type='table'
4544 $html_output = '<h2>' . "\n"
4545 . Util::getIcon('b_usredit')
4546 . __('Edit privileges:') . ' '
4547 . __('User account');
4549 if (! empty($dbname)) {
4550 $html_output .= ' <i><a class="edit_user_anchor"'
4551 . ' href="server_privileges.php'
4552 . Url::getCommon(
4553 array(
4554 'username' => $username,
4555 'hostname' => $hostname,
4556 'dbname' => '',
4557 'tablename' => '',
4560 . '">\'' . htmlspecialchars($username)
4561 . '\'@\'' . htmlspecialchars($hostname)
4562 . '\'</a></i>' . "\n";
4564 $html_output .= ' - ';
4565 $html_output .= ($dbname_is_wildcard
4566 || is_array($dbname) && count($dbname) > 1)
4567 ? __('Databases') : __('Database');
4568 if (! empty($entity_name) && $entity_type === 'table') {
4569 $html_output .= ' <i><a href="server_privileges.php'
4570 . Url::getCommon(
4571 array(
4572 'username' => $username,
4573 'hostname' => $hostname,
4574 'dbname' => $url_dbname,
4575 'tablename' => '',
4578 . '">' . htmlspecialchars($dbname)
4579 . '</a></i>';
4581 $html_output .= ' - ' . __('Table')
4582 . ' <i>' . htmlspecialchars($entity_name) . '</i>';
4583 } elseif (! empty($entity_name)) {
4584 $html_output .= ' <i><a href="server_privileges.php'
4585 . Url::getCommon(
4586 array(
4587 'username' => $username,
4588 'hostname' => $hostname,
4589 'dbname' => $url_dbname,
4590 'routinename' => '',
4593 . '">' . htmlspecialchars($dbname)
4594 . '</a></i>';
4596 $html_output .= ' - ' . __('Routine')
4597 . ' <i>' . htmlspecialchars($entity_name) . '</i>';
4598 } else {
4599 if (! is_array($dbname)) {
4600 $dbname = array($dbname);
4602 $html_output .= ' <i>'
4603 . htmlspecialchars(implode(', ', $dbname))
4604 . '</i>';
4607 } else {
4608 $html_output .= ' <i>\'' . htmlspecialchars($username)
4609 . '\'@\'' . htmlspecialchars($hostname)
4610 . '\'</i>' . "\n";
4613 $html_output .= '</h2>' . "\n";
4614 $cur_user = $GLOBALS['dbi']->getCurrentUser();
4615 $user = $username . '@' . $hostname;
4616 // Add a short notice for the user
4617 // to remind him that he is editing his own privileges
4618 if ($user === $cur_user) {
4619 $html_output .= Message::notice(
4621 'Note: You are attempting to edit privileges of the '
4622 . 'user with which you are currently logged in.'
4624 )->getDisplay();
4626 return $html_output;
4630 * Get HTML snippet for display user overview page
4632 * @param string $pmaThemeImage a image source link
4633 * @param string $text_dir text directory
4635 * @return string $html_output
4637 public static function getHtmlForUserOverview($pmaThemeImage, $text_dir)
4639 $html_output = '<h2>' . "\n"
4640 . Util::getIcon('b_usrlist')
4641 . __('User accounts overview') . "\n"
4642 . '</h2>' . "\n";
4644 $password_column = 'Password';
4645 $server_type = Util::getServerType();
4646 $serverVersion = $GLOBALS['dbi']->getVersion();
4647 if (($server_type == 'MySQL' || $server_type == 'Percona Server')
4648 && $serverVersion >= 50706
4650 $password_column = 'authentication_string';
4652 // $sql_query is for the initial-filtered,
4653 // $sql_query_all is for counting the total no. of users
4655 $sql_query = $sql_query_all = 'SELECT *,' .
4656 " IF(`" . $password_column . "` = _latin1 '', 'N', 'Y') AS 'Password'" .
4657 ' FROM `mysql`.`user`';
4659 $sql_query .= (isset($_GET['initial'])
4660 ? self::rangeOfUsers($_GET['initial'])
4661 : '');
4663 $sql_query .= ' ORDER BY `User` ASC, `Host` ASC;';
4664 $sql_query_all .= ' ;';
4666 $res = $GLOBALS['dbi']->tryQuery(
4667 $sql_query,
4668 DatabaseInterface::CONNECT_USER,
4669 DatabaseInterface::QUERY_STORE
4671 $res_all = $GLOBALS['dbi']->tryQuery(
4672 $sql_query_all,
4673 DatabaseInterface::CONNECT_USER,
4674 DatabaseInterface::QUERY_STORE
4677 if (! $res) {
4678 // the query failed! This may have two reasons:
4679 // - the user does not have enough privileges
4680 // - the privilege tables use a structure of an earlier version.
4681 // so let's try a more simple query
4683 $GLOBALS['dbi']->freeResult($res);
4684 $GLOBALS['dbi']->freeResult($res_all);
4685 $sql_query = 'SELECT * FROM `mysql`.`user`';
4686 $res = $GLOBALS['dbi']->tryQuery(
4687 $sql_query,
4688 DatabaseInterface::CONNECT_USER,
4689 DatabaseInterface::QUERY_STORE
4692 if (! $res) {
4693 $html_output .= self::getHtmlForViewUsersError();
4694 $html_output .= self::getAddUserHtmlFieldset();
4695 } else {
4696 // This message is hardcoded because I will replace it by
4697 // a automatic repair feature soon.
4698 $raw = 'Your privilege table structure seems to be older than'
4699 . ' this MySQL version!<br />'
4700 . 'Please run the <code>mysql_upgrade</code> command'
4701 . ' that should be included in your MySQL server distribution'
4702 . ' to solve this problem!';
4703 $html_output .= Message::rawError($raw)->getDisplay();
4705 $GLOBALS['dbi']->freeResult($res);
4706 } else {
4707 $db_rights = self::getDbRightsForUserOverview();
4708 // for all initials, even non A-Z
4709 $array_initials = array();
4711 foreach ($db_rights as $right) {
4712 foreach ($right as $account) {
4713 if (empty($account['User']) && $account['Host'] == 'localhost') {
4714 $html_output .= Message::notice(
4716 'A user account allowing any user from localhost to '
4717 . 'connect is present. This will prevent other users '
4718 . 'from connecting if the host part of their account '
4719 . 'allows a connection from any (%) host.'
4721 . Util::showMySQLDocu('problems-connecting')
4722 )->getDisplay();
4723 break 2;
4729 * Displays the initials
4730 * Also not necessary if there is less than 20 privileges
4732 if ($GLOBALS['dbi']->numRows($res_all) > 20) {
4733 $html_output .= self::getHtmlForInitials($array_initials);
4737 * Display the user overview
4738 * (if less than 50 users, display them immediately)
4740 if (isset($_GET['initial'])
4741 || isset($_GET['showall'])
4742 || $GLOBALS['dbi']->numRows($res) < 50
4744 $html_output .= self::getUsersOverview(
4745 $res, $db_rights, $pmaThemeImage, $text_dir
4747 } else {
4748 $html_output .= self::getAddUserHtmlFieldset();
4749 } // end if (display overview)
4751 $response = Response::getInstance();
4752 if (! $response->isAjax()
4753 || ! empty($_REQUEST['ajax_page_request'])
4755 if ($GLOBALS['is_reload_priv']) {
4756 $flushnote = new Message(
4758 'Note: phpMyAdmin gets the users’ privileges directly '
4759 . 'from MySQL’s privilege tables. The content of these '
4760 . 'tables may differ from the privileges the server uses, '
4761 . 'if they have been changed manually. In this case, '
4762 . 'you should %sreload the privileges%s before you continue.'
4764 Message::NOTICE
4766 $flushnote->addParamHtml(
4767 '<a href="server_privileges.php'
4768 . Url::getCommon(array('flush_privileges' => 1))
4769 . '" id="reload_privileges_anchor">'
4771 $flushnote->addParamHtml('</a>');
4772 } else {
4773 $flushnote = new Message(
4775 'Note: phpMyAdmin gets the users’ privileges directly '
4776 . 'from MySQL’s privilege tables. The content of these '
4777 . 'tables may differ from the privileges the server uses, '
4778 . 'if they have been changed manually. In this case, '
4779 . 'the privileges have to be reloaded but currently, you '
4780 . 'don\'t have the RELOAD privilege.'
4782 . Util::showMySQLDocu(
4783 'privileges-provided',
4784 false,
4785 'priv_reload'
4787 Message::NOTICE
4790 $html_output .= $flushnote->getDisplay();
4794 return $html_output;
4798 * Get HTML snippet for display user properties
4800 * @param boolean $dbname_is_wildcard whether database name is wildcard or not
4801 * @param string $url_dbname url database name that urlencode() string
4802 * @param string $username username
4803 * @param string $hostname host name
4804 * @param string $dbname database name
4805 * @param string $tablename table name
4807 * @return string $html_output
4809 public static function getHtmlForUserProperties($dbname_is_wildcard, $url_dbname,
4810 $username, $hostname, $dbname, $tablename
4812 $html_output = '<div id="edit_user_dialog">';
4813 $html_output .= self::getHtmlHeaderForUserProperties(
4814 $dbname_is_wildcard, $url_dbname, $dbname, $username, $hostname,
4815 $tablename, 'table'
4818 $sql = "SELECT '1' FROM `mysql`.`user`"
4819 . " WHERE `User` = '" . $GLOBALS['dbi']->escapeString($username) . "'"
4820 . " AND `Host` = '" . $GLOBALS['dbi']->escapeString($hostname) . "';";
4822 $user_does_not_exists = (bool) ! $GLOBALS['dbi']->fetchValue($sql);
4824 if ($user_does_not_exists) {
4825 $html_output .= Message::error(
4826 __('The selected user was not found in the privilege table.')
4827 )->getDisplay();
4828 $html_output .= self::getHtmlForLoginInformationFields();
4831 $_params = array(
4832 'username' => $username,
4833 'hostname' => $hostname,
4835 if (! is_array($dbname) && strlen($dbname) > 0) {
4836 $_params['dbname'] = $dbname;
4837 if (strlen($tablename) > 0) {
4838 $_params['tablename'] = $tablename;
4840 } else {
4841 $_params['dbname'] = $dbname;
4844 $html_output .= '<form class="submenu-item" name="usersForm" '
4845 . 'id="addUsersForm" action="server_privileges.php" method="post">' . "\n";
4846 $html_output .= Url::getHiddenInputs($_params);
4847 $html_output .= self::getHtmlToDisplayPrivilegesTable(
4848 // If $dbname is an array, pass any one db as all have same privs.
4849 Core::ifSetOr($dbname, (is_array($dbname)) ? $dbname[0] : '*', 'length'),
4850 Core::ifSetOr($tablename, '*', 'length')
4853 $html_output .= '</form>' . "\n";
4855 if (! is_array($dbname) && strlen($tablename) === 0
4856 && empty($dbname_is_wildcard)
4858 // no table name was given, display all table specific rights
4859 // but only if $dbname contains no wildcards
4860 if (strlen($dbname) === 0) {
4861 $html_output .= self::getHtmlForAllTableSpecificRights(
4862 $username, $hostname, 'database'
4864 } else {
4865 // unescape wildcards in dbname at table level
4866 $unescaped_db = Util::unescapeMysqlWildcards($dbname);
4868 $html_output .= self::getHtmlForAllTableSpecificRights(
4869 $username, $hostname, 'table', $unescaped_db
4871 $html_output .= self::getHtmlForAllTableSpecificRights(
4872 $username, $hostname, 'routine', $unescaped_db
4877 // Provide a line with links to the relevant database and table
4878 if (! is_array($dbname) && strlen($dbname) > 0 && empty($dbname_is_wildcard)) {
4879 $html_output .= self::getLinkToDbAndTable($url_dbname, $dbname, $tablename);
4883 if (! is_array($dbname) && strlen($dbname) === 0 && ! $user_does_not_exists) {
4884 //change login information
4885 $html_output .= ChangePassword::getHtml(
4886 'edit_other',
4887 $username,
4888 $hostname
4890 $html_output .= self::getChangeLoginInformationHtmlForm($username, $hostname);
4892 $html_output .= '</div>';
4894 return $html_output;
4898 * Get queries for Table privileges to change or copy user
4900 * @param string $user_host_condition user host condition to
4901 * select relevant table privileges
4902 * @param array $queries queries array
4903 * @param string $username username
4904 * @param string $hostname host name
4906 * @return array $queries
4908 public static function getTablePrivsQueriesForChangeOrCopyUser($user_host_condition,
4909 array $queries, $username, $hostname
4911 $res = $GLOBALS['dbi']->query(
4912 'SELECT `Db`, `Table_name`, `Table_priv` FROM `mysql`.`tables_priv`'
4913 . $user_host_condition,
4914 DatabaseInterface::CONNECT_USER,
4915 DatabaseInterface::QUERY_STORE
4917 while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
4919 $res2 = $GLOBALS['dbi']->query(
4920 'SELECT `Column_name`, `Column_priv`'
4921 . ' FROM `mysql`.`columns_priv`'
4922 . ' WHERE `User`'
4923 . ' = \'' . $GLOBALS['dbi']->escapeString($_POST['old_username']) . "'"
4924 . ' AND `Host`'
4925 . ' = \'' . $GLOBALS['dbi']->escapeString($_POST['old_username']) . '\''
4926 . ' AND `Db`'
4927 . ' = \'' . $GLOBALS['dbi']->escapeString($row['Db']) . "'"
4928 . ' AND `Table_name`'
4929 . ' = \'' . $GLOBALS['dbi']->escapeString($row['Table_name']) . "'"
4930 . ';',
4931 DatabaseInterface::CONNECT_USER,
4932 DatabaseInterface::QUERY_STORE
4935 $tmp_privs1 = self::extractPrivInfo($row);
4936 $tmp_privs2 = array(
4937 'Select' => array(),
4938 'Insert' => array(),
4939 'Update' => array(),
4940 'References' => array()
4943 while ($row2 = $GLOBALS['dbi']->fetchAssoc($res2)) {
4944 $tmp_array = explode(',', $row2['Column_priv']);
4945 if (in_array('Select', $tmp_array)) {
4946 $tmp_privs2['Select'][] = $row2['Column_name'];
4948 if (in_array('Insert', $tmp_array)) {
4949 $tmp_privs2['Insert'][] = $row2['Column_name'];
4951 if (in_array('Update', $tmp_array)) {
4952 $tmp_privs2['Update'][] = $row2['Column_name'];
4954 if (in_array('References', $tmp_array)) {
4955 $tmp_privs2['References'][] = $row2['Column_name'];
4958 if (count($tmp_privs2['Select']) > 0 && ! in_array('SELECT', $tmp_privs1)) {
4959 $tmp_privs1[] = 'SELECT (`' . join('`, `', $tmp_privs2['Select']) . '`)';
4961 if (count($tmp_privs2['Insert']) > 0 && ! in_array('INSERT', $tmp_privs1)) {
4962 $tmp_privs1[] = 'INSERT (`' . join('`, `', $tmp_privs2['Insert']) . '`)';
4964 if (count($tmp_privs2['Update']) > 0 && ! in_array('UPDATE', $tmp_privs1)) {
4965 $tmp_privs1[] = 'UPDATE (`' . join('`, `', $tmp_privs2['Update']) . '`)';
4967 if (count($tmp_privs2['References']) > 0
4968 && ! in_array('REFERENCES', $tmp_privs1)
4970 $tmp_privs1[]
4971 = 'REFERENCES (`' . join('`, `', $tmp_privs2['References']) . '`)';
4974 $queries[] = 'GRANT ' . join(', ', $tmp_privs1)
4975 . ' ON ' . Util::backquote($row['Db']) . '.'
4976 . Util::backquote($row['Table_name'])
4977 . ' TO \'' . $GLOBALS['dbi']->escapeString($username)
4978 . '\'@\'' . $GLOBALS['dbi']->escapeString($hostname) . '\''
4979 . (in_array('Grant', explode(',', $row['Table_priv']))
4980 ? ' WITH GRANT OPTION;'
4981 : ';');
4983 return $queries;
4987 * Get queries for database specific privileges for change or copy user
4989 * @param array $queries queries array with string
4990 * @param string $username username
4991 * @param string $hostname host name
4993 * @return array $queries
4995 public static function getDbSpecificPrivsQueriesForChangeOrCopyUser(
4996 array $queries, $username, $hostname
4998 $user_host_condition = ' WHERE `User`'
4999 . ' = \'' . $GLOBALS['dbi']->escapeString($_POST['old_username']) . "'"
5000 . ' AND `Host`'
5001 . ' = \'' . $GLOBALS['dbi']->escapeString($_POST['old_hostname']) . '\';';
5003 $res = $GLOBALS['dbi']->query(
5004 'SELECT * FROM `mysql`.`db`' . $user_host_condition
5007 while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
5008 $queries[] = 'GRANT ' . join(', ', self::extractPrivInfo($row))
5009 . ' ON ' . Util::backquote($row['Db']) . '.*'
5010 . ' TO \'' . $GLOBALS['dbi']->escapeString($username)
5011 . '\'@\'' . $GLOBALS['dbi']->escapeString($hostname) . '\''
5012 . ($row['Grant_priv'] == 'Y' ? ' WITH GRANT OPTION;' : ';');
5014 $GLOBALS['dbi']->freeResult($res);
5016 $queries = self::getTablePrivsQueriesForChangeOrCopyUser(
5017 $user_host_condition, $queries, $username, $hostname
5020 return $queries;
5024 * Prepares queries for adding users and
5025 * also create database and return query and message
5027 * @param boolean $_error whether user create or not
5028 * @param string $real_sql_query SQL query for add a user
5029 * @param string $sql_query SQL query to be displayed
5030 * @param string $username username
5031 * @param string $hostname host name
5032 * @param string $dbname database name
5033 * @param string $alter_real_sql_query SQL query for ALTER USER
5034 * @param string $alter_sql_query SQL query for ALTER USER to be displayed
5036 * @return array $sql_query, $message
5038 public static function addUserAndCreateDatabase(
5039 $_error,
5040 $real_sql_query,
5041 $sql_query,
5042 $username,
5043 $hostname,
5044 $dbname,
5045 $alter_real_sql_query,
5046 $alter_sql_query
5048 if ($_error || (!empty($real_sql_query)
5049 && !$GLOBALS['dbi']->tryQuery($real_sql_query))
5051 $_POST['createdb-1'] = $_POST['createdb-2']
5052 = $_POST['createdb-3'] = null;
5053 $message = Message::rawError($GLOBALS['dbi']->getError());
5054 } elseif ($alter_real_sql_query !== '' && !$GLOBALS['dbi']->tryQuery($alter_real_sql_query)) {
5055 $_POST['createdb-1'] = $_POST['createdb-2']
5056 = $_POST['createdb-3'] = null;
5057 $message = Message::rawError($GLOBALS['dbi']->getError());
5058 } else {
5059 $sql_query .= $alter_sql_query;
5060 $message = Message::success(__('You have added a new user.'));
5063 if (isset($_POST['createdb-1'])) {
5064 // Create database with same name and grant all privileges
5065 $q = 'CREATE DATABASE IF NOT EXISTS '
5066 . Util::backquote(
5067 $GLOBALS['dbi']->escapeString($username)
5068 ) . ';';
5069 $sql_query .= $q;
5070 if (! $GLOBALS['dbi']->tryQuery($q)) {
5071 $message = Message::rawError($GLOBALS['dbi']->getError());
5075 * Reload the navigation
5077 $GLOBALS['reload'] = true;
5078 $GLOBALS['db'] = $username;
5080 $q = 'GRANT ALL PRIVILEGES ON '
5081 . Util::backquote(
5082 Util::escapeMysqlWildcards(
5083 $GLOBALS['dbi']->escapeString($username)
5085 ) . '.* TO \''
5086 . $GLOBALS['dbi']->escapeString($username)
5087 . '\'@\'' . $GLOBALS['dbi']->escapeString($hostname) . '\';';
5088 $sql_query .= $q;
5089 if (! $GLOBALS['dbi']->tryQuery($q)) {
5090 $message = Message::rawError($GLOBALS['dbi']->getError());
5094 if (isset($_POST['createdb-2'])) {
5095 // Grant all privileges on wildcard name (username\_%)
5096 $q = 'GRANT ALL PRIVILEGES ON '
5097 . Util::backquote(
5098 Util::escapeMysqlWildcards(
5099 $GLOBALS['dbi']->escapeString($username)
5100 ) . '\_%'
5101 ) . '.* TO \''
5102 . $GLOBALS['dbi']->escapeString($username)
5103 . '\'@\'' . $GLOBALS['dbi']->escapeString($hostname) . '\';';
5104 $sql_query .= $q;
5105 if (! $GLOBALS['dbi']->tryQuery($q)) {
5106 $message = Message::rawError($GLOBALS['dbi']->getError());
5110 if (isset($_POST['createdb-3'])) {
5111 // Grant all privileges on the specified database to the new user
5112 $q = 'GRANT ALL PRIVILEGES ON '
5113 . Util::backquote(
5114 $GLOBALS['dbi']->escapeString($dbname)
5115 ) . '.* TO \''
5116 . $GLOBALS['dbi']->escapeString($username)
5117 . '\'@\'' . $GLOBALS['dbi']->escapeString($hostname) . '\';';
5118 $sql_query .= $q;
5119 if (! $GLOBALS['dbi']->tryQuery($q)) {
5120 $message = Message::rawError($GLOBALS['dbi']->getError());
5123 return array($sql_query, $message);
5127 * Get the hashed string for password
5129 * @param string $password password
5131 * @return string $hashedPassword
5133 public static function getHashedPassword($password)
5135 $password = $GLOBALS['dbi']->escapeString($password);
5136 $result = $GLOBALS['dbi']->fetchSingleRow(
5137 "SELECT PASSWORD('" . $password . "') AS `password`;"
5140 $hashedPassword = $result['password'];
5142 return $hashedPassword;
5146 * Check if MariaDB's 'simple_password_check'
5147 * OR 'cracklib_password_check' is ACTIVE
5149 * @return boolean if atleast one of the plugins is ACTIVE
5151 public static function checkIfMariaDBPwdCheckPluginActive()
5153 $serverVersion = $GLOBALS['dbi']->getVersion();
5154 if (!(Util::getServerType() == 'MariaDB' && $serverVersion >= 100002)) {
5155 return false;
5158 $result = $GLOBALS['dbi']->tryQuery(
5159 'SHOW PLUGINS SONAME LIKE \'%_password_check%\''
5162 /* Plugins are not working, for example directory does not exists */
5163 if ($result === false) {
5164 return false;
5167 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
5168 if ($row['Status'] === 'ACTIVE') {
5169 return true;
5173 return false;
5178 * Get SQL queries for Display and Add user
5180 * @param string $username username
5181 * @param string $hostname host name
5182 * @param string $password password
5184 * @return array ($create_user_real, $create_user_show, $real_sql_query, $sql_query
5185 * $password_set_real, $password_set_show, $alter_real_sql_query, $alter_sql_query)
5187 public static function getSqlQueriesForDisplayAndAddUser($username, $hostname, $password)
5189 $slashedUsername = $GLOBALS['dbi']->escapeString($username);
5190 $slashedHostname = $GLOBALS['dbi']->escapeString($hostname);
5191 $slashedPassword = $GLOBALS['dbi']->escapeString($password);
5192 $serverType = Util::getServerType();
5193 $serverVersion = $GLOBALS['dbi']->getVersion();
5195 $create_user_stmt = sprintf(
5196 'CREATE USER \'%s\'@\'%s\'',
5197 $slashedUsername,
5198 $slashedHostname
5200 $isMariaDBPwdPluginActive = self::checkIfMariaDBPwdCheckPluginActive();
5202 // See https://github.com/phpmyadmin/phpmyadmin/pull/11560#issuecomment-147158219
5203 // for details regarding details of syntax usage for various versions
5205 // 'IDENTIFIED WITH auth_plugin'
5206 // is supported by MySQL 5.5.7+
5207 if (($serverType == 'MySQL' || $serverType == 'Percona Server')
5208 && $serverVersion >= 50507
5209 && isset($_POST['authentication_plugin'])
5211 $create_user_stmt .= ' IDENTIFIED WITH '
5212 . $_POST['authentication_plugin'];
5215 // 'IDENTIFIED VIA auth_plugin'
5216 // is supported by MariaDB 5.2+
5217 if ($serverType == 'MariaDB'
5218 && $serverVersion >= 50200
5219 && isset($_POST['authentication_plugin'])
5220 && ! $isMariaDBPwdPluginActive
5222 $create_user_stmt .= ' IDENTIFIED VIA '
5223 . $_POST['authentication_plugin'];
5226 $create_user_real = $create_user_show = $create_user_stmt;
5228 $password_set_stmt = 'SET PASSWORD FOR \'%s\'@\'%s\' = \'%s\'';
5229 $password_set_show = sprintf(
5230 $password_set_stmt,
5231 $slashedUsername,
5232 $slashedHostname,
5233 '***'
5236 $sql_query_stmt = sprintf(
5237 'GRANT %s ON *.* TO \'%s\'@\'%s\'',
5238 join(', ', self::extractPrivInfo()),
5239 $slashedUsername,
5240 $slashedHostname
5242 $real_sql_query = $sql_query = $sql_query_stmt;
5244 // Set the proper hashing method
5245 if (isset($_POST['authentication_plugin'])) {
5246 self::setProperPasswordHashing(
5247 $_POST['authentication_plugin']
5251 // Use 'CREATE USER ... WITH ... AS ..' syntax for
5252 // newer MySQL versions
5253 // and 'CREATE USER ... VIA .. USING ..' syntax for
5254 // newer MariaDB versions
5255 if ((($serverType == 'MySQL' || $serverType == 'Percona Server')
5256 && $serverVersion >= 50706)
5257 || ($serverType == 'MariaDB'
5258 && $serverVersion >= 50200)
5260 $password_set_real = null;
5262 // Required for binding '%' with '%s'
5263 $create_user_stmt = str_replace(
5264 '%', '%%', $create_user_stmt
5267 // MariaDB uses 'USING' whereas MySQL uses 'AS'
5268 // but MariaDB with validation plugin needs cleartext password
5269 if ($serverType == 'MariaDB'
5270 && ! $isMariaDBPwdPluginActive
5272 $create_user_stmt .= ' USING \'%s\'';
5273 } elseif ($serverType == 'MariaDB') {
5274 $create_user_stmt .= ' IDENTIFIED BY \'%s\'';
5275 } elseif (($serverType == 'MySQL' || $serverType == 'Percona Server') && $serverVersion >= 80011) {
5276 $create_user_stmt .= ' BY \'%s\'';
5277 } else {
5278 $create_user_stmt .= ' AS \'%s\'';
5281 if ($_POST['pred_password'] == 'keep') {
5282 $create_user_real = sprintf(
5283 $create_user_stmt,
5284 $slashedPassword
5286 $create_user_show = sprintf(
5287 $create_user_stmt,
5288 '***'
5290 } elseif ($_POST['pred_password'] == 'none') {
5291 $create_user_real = sprintf(
5292 $create_user_stmt,
5293 null
5295 $create_user_show = sprintf(
5296 $create_user_stmt,
5297 '***'
5299 } else {
5300 if (! (($serverType == 'MariaDB' && $isMariaDBPwdPluginActive)
5301 || ($serverType == 'MySQL' || $serverType == 'Percona Server') && $serverVersion >= 80011)) {
5302 $hashedPassword = self::getHashedPassword($_POST['pma_pw']);
5303 } else {
5304 // MariaDB with validation plugin needs cleartext password
5305 $hashedPassword = $_POST['pma_pw'];
5307 $create_user_real = sprintf(
5308 $create_user_stmt,
5309 $hashedPassword
5311 $create_user_show = sprintf(
5312 $create_user_stmt,
5313 '***'
5316 } else {
5317 // Use 'SET PASSWORD' syntax for pre-5.7.6 MySQL versions
5318 // and pre-5.2.0 MariaDB versions
5319 if ($_POST['pred_password'] == 'keep') {
5320 $password_set_real = sprintf(
5321 $password_set_stmt,
5322 $slashedUsername,
5323 $slashedHostname,
5324 $slashedPassword
5326 } elseif ($_POST['pred_password'] == 'none') {
5327 $password_set_real = sprintf(
5328 $password_set_stmt,
5329 $slashedUsername,
5330 $slashedHostname,
5331 null
5333 } else {
5334 $hashedPassword = self::getHashedPassword($_POST['pma_pw']);
5335 $password_set_real = sprintf(
5336 $password_set_stmt,
5337 $slashedUsername,
5338 $slashedHostname,
5339 $hashedPassword
5344 $alter_real_sql_query = '';
5345 $alter_sql_query = '';
5346 if (($serverType == 'MySQL' || $serverType == 'Percona Server') && $serverVersion >= 80011) {
5347 $sql_query_stmt = '';
5348 if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
5349 || (isset($GLOBALS['Grant_priv']) && $GLOBALS['Grant_priv'] == 'Y')
5351 $sql_query_stmt = ' WITH GRANT OPTION';
5353 $real_sql_query .= $sql_query_stmt;
5354 $sql_query .= $sql_query_stmt;
5356 $alter_sql_query_stmt = sprintf(
5357 'ALTER USER \'%s\'@\'%s\'',
5358 $slashedUsername,
5359 $slashedHostname
5361 $alter_real_sql_query = $alter_sql_query_stmt;
5362 $alter_sql_query = $alter_sql_query_stmt;
5365 // add REQUIRE clause
5366 $require_clause = self::getRequireClause();
5367 $with_clause = self::getWithClauseForAddUserAndUpdatePrivs();
5369 if (($serverType == 'MySQL' || $serverType == 'Percona Server') && $serverVersion >= 80011) {
5370 $alter_real_sql_query .= $require_clause;
5371 $alter_sql_query .= $require_clause;
5372 $alter_real_sql_query .= $with_clause;
5373 $alter_sql_query .= $with_clause;
5374 } else {
5375 $real_sql_query .= $require_clause;
5376 $sql_query .= $require_clause;
5377 $real_sql_query .= $with_clause;
5378 $sql_query .= $with_clause;
5381 if (isset($create_user_real)) {
5382 $create_user_real .= ';';
5383 $create_user_show .= ';';
5385 if ($alter_real_sql_query !== '') {
5386 $alter_real_sql_query .= ';';
5387 $alter_sql_query .= ';';
5389 $real_sql_query .= ';';
5390 $sql_query .= ';';
5391 // No Global GRANT_OPTION privilege
5392 if (!$GLOBALS['is_grantuser']) {
5393 $real_sql_query = '';
5394 $sql_query = '';
5397 // Use 'SET PASSWORD' for pre-5.7.6 MySQL versions
5398 // and pre-5.2.0 MariaDB
5399 if (($serverType == 'MySQL'
5400 && $serverVersion >= 50706)
5401 || ($serverType == 'MariaDB'
5402 && $serverVersion >= 50200)
5404 $password_set_real = null;
5405 $password_set_show = null;
5406 } else {
5407 if ($password_set_real !== null) {
5408 $password_set_real .= ";";
5410 $password_set_show .= ";";
5413 return array(
5414 $create_user_real,
5415 $create_user_show,
5416 $real_sql_query,
5417 $sql_query,
5418 $password_set_real,
5419 $password_set_show,
5420 $alter_real_sql_query,
5421 $alter_sql_query
5426 * Returns the type ('PROCEDURE' or 'FUNCTION') of the routine
5428 * @param string $dbname database
5429 * @param string $routineName routine
5431 * @return string type
5433 public static function getRoutineType($dbname, $routineName)
5435 $routineData = $GLOBALS['dbi']->getRoutines($dbname);
5437 foreach ($routineData as $routine) {
5438 if ($routine['name'] === $routineName) {
5439 return $routine['type'];
5442 return '';