Translated using Weblate (Armenian)
[phpmyadmin.git] / libraries / server_privileges.lib.php
blobc173799ea64781849a95c7ca4cd844b457023618
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 */
9 if (! defined('PHPMYADMIN')) {
10 exit;
13 /**
14 * Get Html for User Group Dialog
16 * @param string $username username
17 * @param bool $is_menuswork Is menuswork set in configuration
19 * @return string html
21 function PMA_getHtmlForUserGroupDialog($username, $is_menuswork)
23 $html = '';
24 if (! empty($_REQUEST['edit_user_group_dialog']) && $is_menuswork) {
25 $dialog = PMA_getHtmlToChooseUserGroup($username);
26 $response = PMA_Response::getInstance();
27 if ($GLOBALS['is_ajax_request']) {
28 $response->addJSON('message', $dialog);
29 exit;
30 } else {
31 $html .= $dialog;
35 return $html;
38 /**
39 * Escapes wildcard in a database+table specification
40 * before using it in a GRANT statement.
42 * Escaping a wildcard character in a GRANT is only accepted at the global
43 * or database level, not at table level; this is why I remove
44 * the escaping character. Internally, in mysql.tables_priv.Db there are
45 * no escaping (for example test_db) but in mysql.db you'll see test\_db
46 * for a db-specific privilege.
48 * @param string $dbname Database name
49 * @param string $tablename Table name
51 * @return string the escaped (if necessary) database.table
53 function PMA_wildcardEscapeForGrant($dbname, $tablename)
55 if (!/*overload*/mb_strlen($dbname)) {
56 $db_and_table = '*.*';
57 } else {
58 if (/*overload*/mb_strlen($tablename)) {
59 $db_and_table = PMA_Util::backquote(
60 PMA_Util::unescapeMysqlWildcards($dbname)
62 . '.' . PMA_Util::backquote($tablename);
63 } else {
64 $db_and_table = PMA_Util::backquote($dbname) . '.*';
67 return $db_and_table;
70 /**
71 * Generates a condition on the user name
73 * @param string $initial the user's initial
75 * @return string the generated condition
77 function PMA_rangeOfUsers($initial = '')
79 // strtolower() is used because the User field
80 // might be BINARY, so LIKE would be case sensitive
81 if ($initial === null || $initial === '') {
82 return '';
85 $ret = " WHERE `User` LIKE '"
86 . PMA_Util::sqlAddSlashes($initial, true) . "%'"
87 . " OR `User` LIKE '"
88 . PMA_Util::sqlAddSlashes(/*overload*/mb_strtolower($initial), true)
89 . "%'";
90 return $ret;
91 } // end function
93 /**
94 * Formats privilege name for a display
96 * @param array $privilege Privilege information
97 * @param boolean $html Whether to use HTML
99 * @return string
101 function PMA_formatPrivilege($privilege, $html)
103 if ($html) {
104 return '<dfn title="' . $privilege[2] . '">'
105 . $privilege[1] . '</dfn>';
106 } else {
107 return $privilege[1];
112 * Parses privileges into an array, it modifies the array
114 * @param array &$row Results row from
116 * @return void
118 function PMA_fillInTablePrivileges(&$row)
120 $row1 = $GLOBALS['dbi']->fetchSingleRow(
121 'SHOW COLUMNS FROM `mysql`.`tables_priv` LIKE \'Table_priv\';',
122 'ASSOC', $GLOBALS['userlink']
124 // note: in MySQL 5.0.3 we get "Create View', 'Show view';
125 // the View for Create is spelled with uppercase V
126 // the view for Show is spelled with lowercase v
127 // and there is a space between the words
129 $av_grants = explode(
130 '\',\'',
131 /*overload*/mb_substr(
132 $row1['Type'],
133 /*overload*/mb_strpos($row1['Type'], '(') + 2,
134 /*overload*/mb_strpos($row1['Type'], ')')
135 - /*overload*/mb_strpos($row1['Type'], '(') - 3
139 $users_grants = explode(',', $row['Table_priv']);
141 foreach ($av_grants as $current_grant) {
142 $row[$current_grant . '_priv']
143 = in_array($current_grant, $users_grants) ? 'Y' : 'N';
145 unset($row['Table_priv']);
150 * Extracts the privilege information of a priv table row
152 * @param array|null $row the row
153 * @param boolean $enableHTML add <dfn> tag with tooltips
154 * @param boolean $tablePrivs whether row contains table privileges
156 * @global resource $user_link the database connection
158 * @return array
160 function PMA_extractPrivInfo($row = null, $enableHTML = false, $tablePrivs = false)
162 if ($tablePrivs) {
163 $grants = PMA_getTableGrantsArray();
164 } else {
165 $grants = PMA_getGrantsArray();
168 if (! is_null($row) && isset($row['Table_priv'])) {
169 PMA_fillInTablePrivileges($row);
172 $privs = array();
173 $allPrivileges = true;
174 foreach ($grants as $current_grant) {
175 if ((! is_null($row) && isset($row[$current_grant[0]]))
176 || (is_null($row) && isset($GLOBALS[$current_grant[0]]))
178 if ((! is_null($row) && $row[$current_grant[0]] == 'Y')
179 || (is_null($row)
180 && ($GLOBALS[$current_grant[0]] == 'Y'
181 || (is_array($GLOBALS[$current_grant[0]])
182 && count($GLOBALS[$current_grant[0]]) == $_REQUEST['column_count']
183 && empty($GLOBALS[$current_grant[0] . '_none']))))
185 $privs[] = PMA_formatPrivilege($current_grant, $enableHTML);
186 } elseif (! empty($GLOBALS[$current_grant[0]])
187 && is_array($GLOBALS[$current_grant[0]])
188 && empty($GLOBALS[$current_grant[0] . '_none'])
190 $privs[] = PMA_formatPrivilege($current_grant, $enableHTML)
191 . ' (`' . join('`, `', $GLOBALS[$current_grant[0]]) . '`)';
192 } else {
193 $allPrivileges = false;
197 if (empty($privs)) {
198 if ($enableHTML) {
199 $privs[] = '<dfn title="' . __('No privileges.') . '">USAGE</dfn>';
200 } else {
201 $privs[] = 'USAGE';
203 } elseif ($allPrivileges
204 && (! isset($_POST['grant_count']) || count($privs) == $_POST['grant_count'])
206 if ($enableHTML) {
207 $privs = array('<dfn title="'
208 . __('Includes all privileges except GRANT.')
209 . '">ALL PRIVILEGES</dfn>'
211 } else {
212 $privs = array('ALL PRIVILEGES');
215 return $privs;
216 } // end of the 'PMA_extractPrivInfo()' function
219 * Returns an array of table grants and their descriptions
221 * @return array array of table grants
223 function PMA_getTableGrantsArray()
225 return array(
226 array(
227 'Delete',
228 'DELETE',
229 $GLOBALS['strPrivDescDelete']
231 array(
232 'Create',
233 'CREATE',
234 $GLOBALS['strPrivDescCreateTbl']
236 array(
237 'Drop',
238 'DROP',
239 $GLOBALS['strPrivDescDropTbl']
241 array(
242 'Index',
243 'INDEX',
244 $GLOBALS['strPrivDescIndex']
246 array(
247 'Alter',
248 'ALTER',
249 $GLOBALS['strPrivDescAlter']
251 array(
252 'Create View',
253 'CREATE_VIEW',
254 $GLOBALS['strPrivDescCreateView']
256 array(
257 'Show view',
258 'SHOW_VIEW',
259 $GLOBALS['strPrivDescShowView']
261 array(
262 'Trigger',
263 'TRIGGER',
264 $GLOBALS['strPrivDescTrigger']
270 * Get the grants array which contains all the privilege types
271 * and relevant grant messages
273 * @return array
275 function PMA_getGrantsArray()
277 return array(
278 array(
279 'Select_priv',
280 'SELECT',
281 __('Allows reading data.')
283 array(
284 'Insert_priv',
285 'INSERT',
286 __('Allows inserting and replacing data.')
288 array(
289 'Update_priv',
290 'UPDATE',
291 __('Allows changing data.')
293 array(
294 'Delete_priv',
295 'DELETE',
296 __('Allows deleting data.')
298 array(
299 'Create_priv',
300 'CREATE',
301 __('Allows creating new databases and tables.')
303 array(
304 'Drop_priv',
305 'DROP',
306 __('Allows dropping databases and tables.')
308 array(
309 'Reload_priv',
310 'RELOAD',
311 __('Allows reloading server settings and flushing the server\'s caches.')
313 array(
314 'Shutdown_priv',
315 'SHUTDOWN',
316 __('Allows shutting down the server.')
318 array(
319 'Process_priv',
320 'PROCESS',
321 __('Allows viewing processes of all users.')
323 array(
324 'File_priv',
325 'FILE',
326 __('Allows importing data from and exporting data into files.')
328 array(
329 'References_priv',
330 'REFERENCES',
331 __('Has no effect in this MySQL version.')
333 array(
334 'Index_priv',
335 'INDEX',
336 __('Allows creating and dropping indexes.')
338 array(
339 'Alter_priv',
340 'ALTER',
341 __('Allows altering the structure of existing tables.')
343 array(
344 'Show_db_priv',
345 'SHOW DATABASES',
346 __('Gives access to the complete list of databases.')
348 array(
349 'Super_priv',
350 'SUPER',
352 'Allows connecting, even if maximum number of connections '
353 . 'is reached; required for most administrative operations '
354 . 'like setting global variables or killing threads of other users.'
357 array(
358 'Create_tmp_table_priv',
359 'CREATE TEMPORARY TABLES',
360 __('Allows creating temporary tables.')
362 array(
363 'Lock_tables_priv',
364 'LOCK TABLES',
365 __('Allows locking tables for the current thread.')
367 array(
368 'Repl_slave_priv',
369 'REPLICATION SLAVE',
370 __('Needed for the replication slaves.')
372 array(
373 'Repl_client_priv',
374 'REPLICATION CLIENT',
375 __('Allows the user to ask where the slaves / masters are.')
377 array(
378 'Create_view_priv',
379 'CREATE VIEW',
380 __('Allows creating new views.')
382 array(
383 'Event_priv',
384 'EVENT',
385 __('Allows to set up events for the event scheduler.')
387 array(
388 'Trigger_priv',
389 'TRIGGER',
390 __('Allows creating and dropping triggers.')
392 // for table privs:
393 array(
394 'Create View_priv',
395 'CREATE VIEW',
396 __('Allows creating new views.')
398 array(
399 'Show_view_priv',
400 'SHOW VIEW',
401 __('Allows performing SHOW CREATE VIEW queries.')
403 // for table privs:
404 array(
405 'Show view_priv',
406 'SHOW VIEW',
407 __('Allows performing SHOW CREATE VIEW queries.')
409 array(
410 'Create_routine_priv',
411 'CREATE ROUTINE',
412 __('Allows creating stored routines.')
414 array(
415 'Alter_routine_priv',
416 'ALTER ROUTINE',
417 __('Allows altering and dropping stored routines.')
419 array(
420 'Create_user_priv',
421 'CREATE USER',
422 __('Allows creating, dropping and renaming user accounts.')
424 array(
425 'Execute_priv',
426 'EXECUTE',
427 __('Allows executing stored routines.')
433 * Displays on which column(s) a table-specific privilege is granted
435 * @param array $columns columns array
436 * @param array $row first row from result or boolean false
437 * @param string $name_for_select privilege types - Select_priv, Insert_priv
438 * Update_priv, References_priv
439 * @param string $priv_for_header privilege for header
440 * @param string $name privilege name: insert, select, update, references
441 * @param string $name_for_dfn name for dfn
442 * @param string $name_for_current name for current
444 * @return string $html_output html snippet
446 function PMA_getHtmlForColumnPrivileges($columns, $row, $name_for_select,
447 $priv_for_header, $name, $name_for_dfn, $name_for_current
449 $html_output = '<div class="item" id="div_item_' . $name . '">' . "\n"
450 . '<label for="select_' . $name . '_priv">' . "\n"
451 . '<code><dfn title="' . $name_for_dfn . '">'
452 . $priv_for_header . '</dfn></code>' . "\n"
453 . '</label><br />' . "\n"
454 . '<select id="select_' . $name . '_priv" name="'
455 . $name_for_select . '[]" multiple="multiple" size="8">' . "\n";
457 foreach ($columns as $currCol => $currColPrivs) {
458 $html_output .= '<option '
459 . 'value="' . htmlspecialchars($currCol) . '"';
460 if ($row[$name_for_select] == 'Y'
461 || $currColPrivs[$name_for_current]
463 $html_output .= ' selected="selected"';
465 $html_output .= '>'
466 . htmlspecialchars($currCol) . '</option>' . "\n";
469 $html_output .= '</select>' . "\n"
470 . '<i>' . __('Or') . '</i>' . "\n"
471 . '<label for="checkbox_' . $name_for_select
472 . '_none"><input type="checkbox"'
473 . ' name="' . $name_for_select . '_none" id="checkbox_'
474 . $name_for_select . '_none" title="'
475 . _pgettext('None privileges', 'None') . '" />'
476 . _pgettext('None privileges', 'None') . '</label>' . "\n"
477 . '</div>' . "\n";
478 return $html_output;
479 } // end function
482 * Get sql query for display privileges table
484 * @param string $db the database
485 * @param string $table the table
486 * @param string $username username for database connection
487 * @param string $hostname hostname for database connection
489 * @return string sql query
491 function PMA_getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname)
493 if ($db == '*') {
494 return "SELECT * FROM `mysql`.`user`"
495 . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
496 . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "';";
497 } elseif ($table == '*') {
498 return "SELECT * FROM `mysql`.`db`"
499 . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
500 . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "'"
501 . " AND '" . PMA_Util::unescapeMysqlWildcards($db) . "'"
502 . " LIKE `Db`;";
504 return "SELECT `Table_priv`"
505 . " FROM `mysql`.`tables_priv`"
506 . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
507 . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "'"
508 . " AND `Db` = '" . PMA_Util::unescapeMysqlWildcards($db) . "'"
509 . " AND `Table_name` = '" . PMA_Util::sqlAddSlashes($table) . "';";
513 * Displays a dropdown to select the user group
514 * with menu items configured to each of them.
516 * @param string $username username
518 * @return string html to select the user group
520 function PMA_getHtmlToChooseUserGroup($username)
522 $html_output = '<form class="ajax" id="changeUserGroupForm"'
523 . ' action="server_privileges.php" method="post">';
524 $params = array('username' => $username);
525 $html_output .= PMA_URL_getHiddenInputs($params);
526 $html_output .= '<fieldset id="fieldset_user_group_selection">';
527 $html_output .= '<legend>' . __('User group') . '</legend>';
529 $cfgRelation = PMA_getRelationsParam();
530 $groupTable = PMA_Util::backquote($cfgRelation['db'])
531 . "." . PMA_Util::backquote($cfgRelation['usergroups']);
532 $userTable = PMA_Util::backquote($cfgRelation['db'])
533 . "." . PMA_Util::backquote($cfgRelation['users']);
535 $userGroups = array();
536 $sql_query = "SELECT DISTINCT `usergroup` FROM " . $groupTable;
537 $result = PMA_queryAsControlUser($sql_query, false);
538 if ($result) {
539 while ($row = $GLOBALS['dbi']->fetchRow($result)) {
540 $userGroups[] = $row[0];
543 $GLOBALS['dbi']->freeResult($result);
545 $userGroup = '';
546 if (isset($GLOBALS['username'])) {
547 $sql_query = "SELECT `usergroup` FROM " . $userTable
548 . " WHERE `username` = '" . PMA_Util::sqlAddSlashes($username) . "'";
549 $userGroup = $GLOBALS['dbi']->fetchValue(
550 $sql_query, 0, 0, $GLOBALS['controllink']
554 $html_output .= __('User group') . ': ';
555 $html_output .= '<select name="userGroup">';
556 $html_output .= '<option value=""></option>';
557 foreach ($userGroups as $oneUserGroup) {
558 $html_output .= '<option value="' . htmlspecialchars($oneUserGroup) . '"'
559 . ($oneUserGroup == $userGroup ? ' selected="selected"' : '')
560 . '>'
561 . htmlspecialchars($oneUserGroup)
562 . '</option>';
564 $html_output .= '</select>';
565 $html_output .= '<input type="hidden" name="changeUserGroup" value="1">';
566 $html_output .= '</fieldset>';
567 $html_output .= '</form>';
568 return $html_output;
572 * Sets the user group from request values
574 * @param string $username username
575 * @param string $userGroup user group to set
577 * @return void
579 function PMA_setUserGroup($username, $userGroup)
581 $cfgRelation = PMA_getRelationsParam();
582 $userTable = PMA_Util::backquote($cfgRelation['db'])
583 . "." . PMA_Util::backquote($cfgRelation['users']);
585 $sql_query = "SELECT `usergroup` FROM " . $userTable
586 . " WHERE `username` = '" . PMA_Util::sqlAddSlashes($username) . "'";
587 $oldUserGroup = $GLOBALS['dbi']->fetchValue(
588 $sql_query, 0, 0, $GLOBALS['controllink']
591 if ($oldUserGroup === false) {
592 $upd_query = "INSERT INTO " . $userTable . "(`username`, `usergroup`)"
593 . " VALUES ('" . PMA_Util::sqlAddSlashes($username) . "', "
594 . "'" . PMA_Util::sqlAddSlashes($userGroup) . "')";
595 } else {
596 if (empty($userGroup)) {
597 $upd_query = "DELETE FROM " . $userTable
598 . " WHERE `username`='" . PMA_Util::sqlAddSlashes($username) . "'";
599 } elseif ($oldUserGroup != $userGroup) {
600 $upd_query = "UPDATE " . $userTable
601 . " SET `usergroup`='" . PMA_Util::sqlAddSlashes($userGroup) . "'"
602 . " WHERE `username`='" . PMA_Util::sqlAddSlashes($username) . "'";
605 if (isset($upd_query)) {
606 PMA_queryAsControlUser($upd_query);
611 * Displays the privileges form table
613 * @param string $db the database
614 * @param string $table the table
615 * @param boolean $submit whether to display the submit button or not
617 * @global array $cfg the phpMyAdmin configuration
618 * @global resource $user_link the database connection
620 * @return string html snippet
622 function PMA_getHtmlToDisplayPrivilegesTable($db = '*',
623 $table = '*', $submit = true
625 $html_output = '';
626 $sql_query = '';
628 if ($db == '*') {
629 $table = '*';
632 if (isset($GLOBALS['username'])) {
633 $username = $GLOBALS['username'];
634 $hostname = $GLOBALS['hostname'];
635 $sql_query = PMA_getSqlQueryForDisplayPrivTable(
636 $db, $table, $username, $hostname
638 $row = $GLOBALS['dbi']->fetchSingleRow($sql_query);
640 if (empty($row)) {
641 if ($table == '*' && $GLOBALS['is_superuser']) {
642 if ($db == '*') {
643 $sql_query = 'SHOW COLUMNS FROM `mysql`.`user`;';
644 } elseif ($table == '*') {
645 $sql_query = 'SHOW COLUMNS FROM `mysql`.`db`;';
647 $res = $GLOBALS['dbi']->query($sql_query);
648 while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
649 if (mb_substr($row1[0], 0, 4) == 'max_') {
650 $row[$row1[0]] = 0;
651 } elseif (mb_substr($row1[0], 0, 5) == 'x509_'
652 || mb_substr($row1[0], 0, 4) == 'ssl_'
654 $row[$row1[0]] = '';
655 } else {
656 $row[$row1[0]] = 'N';
659 $GLOBALS['dbi']->freeResult($res);
660 } elseif ($table == '*') {
661 $row = array();
662 } else {
663 $row = array('Table_priv' => '');
666 if (isset($row['Table_priv'])) {
667 PMA_fillInTablePrivileges($row);
669 // get columns
670 $res = $GLOBALS['dbi']->tryQuery(
671 'SHOW COLUMNS FROM '
672 . PMA_Util::backquote(
673 PMA_Util::unescapeMysqlWildcards($db)
675 . '.' . PMA_Util::backquote($table) . ';'
677 $columns = array();
678 if ($res) {
679 while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
680 $columns[$row1[0]] = array(
681 'Select' => false,
682 'Insert' => false,
683 'Update' => false,
684 'References' => false
687 $GLOBALS['dbi']->freeResult($res);
689 unset($res, $row1);
691 // table-specific privileges
692 if (! empty($columns)) {
693 $html_output .= PMA_getHtmlForTableSpecificPrivileges(
694 $username, $hostname, $db, $table, $columns, $row
696 } else {
697 // global or db-specific
698 $html_output .= PMA_getHtmlForGlobalOrDbSpecificPrivs($db, $table, $row);
700 $html_output .= '</fieldset>' . "\n";
701 if ($submit) {
702 $html_output .= '<fieldset id="fieldset_user_privtable_footer" '
703 . 'class="tblFooters">' . "\n"
704 . '<input type="hidden" name="update_privs" value="1" />' . "\n"
705 . '<input type="submit" value="' . __('Go') . '" />' . "\n"
706 . '</fieldset>' . "\n";
708 return $html_output;
709 } // end of the 'PMA_displayPrivTable()' function
712 * Get HTML for "Require"
714 * @param array $row privilege array
716 * @return string html snippet
718 function PMA_getHtmlForRequires($row)
720 $html_output = '<fieldset>';
722 $html_output .= '<legend>';
723 $html_output .= '<input type="checkbox" name="SSL_priv" id="checkbox_SSL_priv"'
724 . ' value="Y" title="'
725 . __(
726 'Requires SSL-encrypted connections.'
728 . '"'
729 . ((isset($row['ssl_type']) && $row['ssl_type'] != '')
730 ? ' checked="checked"'
731 : ''
733 . '/>';
734 $html_output .= __('Require SSL') . '</legend>';
735 $html_output .= '<div id="require_ssl_div">';
737 // Specified
738 $html_output .= '<div class="item">';
739 $html_output .= '<input type="radio" name="ssl_type" id="ssl_type_specified"'
740 . ' value="specified"'
741 . ((isset($row['ssl_type']) && $row['ssl_type'] == 'SPECIFIED')
742 ? ' checked="checked"'
743 : ''
745 . '/>';
747 $html_output .= '<label for="ssl_type_speified"><code>'
748 . 'SPECIFIED'
749 . '</code></label>';
750 $html_output .= '</div>';
752 $html_output .= '<div id="specified_div" style="padding-left:20px;">';
754 // REQUIRE CIPHER
755 $html_output .= '<div class="item">';
756 $html_output .= '<label for="text_ssl_cipher">'
757 . '<code><dfn title="'
758 . __(
759 'Requires that a specific cipher method be used for a connection.'
761 . '">'
762 . 'REQUIRE CIPHER'
763 . '</dfn></code></label>';
764 $html_output .= '<input type="text" name="ssl_cipher" id="text_ssl_cipher" '
765 . 'value="' . (isset($row['ssl_cipher']) ? $row['ssl_cipher'] : '') . '" '
766 . 'size=80" title="'
767 . __(
768 'Requires that a specific cipher method be used for a connection.'
770 . '" />';
771 $html_output .= '</div>';
773 // REQUIRE ISSUER
774 $html_output .= '<div class="item">';
775 $html_output .= '<label for="text_x509_issuer">'
776 . '<code><dfn title="'
777 . __(
778 'Requires that a valid X509 certificate issued by this CA be presented.'
780 . '">'
781 . 'REQUIRE ISSUER'
782 . '</dfn></code></label>';
783 $html_output .= '<input type="text" name="x509_issuer" id="text_x509_issuer" '
784 . 'value="' . (isset($row['x509_issuer']) ? $row['x509_issuer'] : '') . '" '
785 . 'size=80" title="'
786 . __(
787 'Requires that a valid X509 certificate issued by this CA be presented.'
789 . '" />';
790 $html_output .= '</div>';
792 // REQUIRE SUBJECT
793 $html_output .= '<div class="item">';
794 $html_output .= '<label for="text_x509_subject">'
795 . '<code><dfn title="'
796 . __(
797 'Requires that a valid X509 certificate with this subject be presented.'
799 . '">'
800 . 'REQUIRE SUBJECT'
801 . '</dfn></code></label>';
802 $html_output .= '<input type="text" name="x509_subject" id="text_x509_subject" '
803 . 'value="' . (isset($row['x509_subject']) ? $row['x509_subject'] : '')
804 . '" size=80" title="'
805 . __(
806 'Requires that a valid X509 certificate with this subject be presented.'
808 . '" />';
809 $html_output .= '</div>';
811 $html_output .= '</div>';
813 // REQUIRE X509
814 $html_output .= '<div class="item">';
815 $html_output .= '<input type="radio" name="ssl_type" id="ssl_type_X509"'
816 . ' value="X509" title="'
817 . __(
818 'Requires a valid X509 certificate.'
820 . '"'
821 . ((isset($row['ssl_type']) && $row['ssl_type'] == 'X509')
822 ? ' checked="checked"'
823 : ''
825 . '/>';
827 $html_output .= '<label for="radio_X509_priv"><code>'
828 . 'REQUIRE X509'
829 . '</code></label>';
830 $html_output .= '</div>';
832 // REQUIRE SSL
833 $html_output .= '<div class="item">';
834 $html_output .= '<input type="radio" name="ssl_type" id="ssl_type_ANY"'
835 . ' value="ANY" title="'
836 . __(
837 'Requires SSL-encrypted connections.'
839 . '"'
840 . ((isset($row['ssl_type'])
841 && ($row['ssl_type'] == 'ANY'
842 || $row['ssl_type'] == ''))
843 ? ' checked="checked"'
844 : ''
846 . '/>';
848 $html_output .= '<label for="ssl_type_ANY"><code>'
849 . 'REQUIRE SSL'
850 . '</code></label>';
851 $html_output .= '</div>';
853 $html_output .= '</div>';
854 $html_output .= '</fieldset>';
856 return $html_output;
860 * Get HTML for "Resource limits"
862 * @param array $row first row from result or boolean false
864 * @return string html snippet
866 function PMA_getHtmlForResourceLimits($row)
868 $html_output = '<fieldset>' . "\n"
869 . '<legend>' . __('Resource limits') . '</legend>' . "\n"
870 . '<p><small>'
871 . '<i>' . __('Note: Setting these options to 0 (zero) removes the limit.')
872 . '</i></small></p>' . "\n";
874 $html_output .= '<div class="item">' . "\n"
875 . '<label for="text_max_questions">'
876 . '<code><dfn title="'
877 . __(
878 'Limits the number of queries the user may send to the server per hour.'
880 . '">'
881 . 'MAX QUERIES PER HOUR'
882 . '</dfn></code></label>' . "\n"
883 . '<input type="number" name="max_questions" id="text_max_questions" '
884 . 'value="'
885 . (isset($row['max_questions']) ? $row['max_questions'] : '0')
886 . '" min="0" '
887 . 'title="'
888 . __(
889 'Limits the number of queries the user may send to the server per hour.'
891 . '" />' . "\n"
892 . '</div>' . "\n";
894 $html_output .= '<div class="item">' . "\n"
895 . '<label for="text_max_updates">'
896 . '<code><dfn title="'
897 . __(
898 'Limits the number of commands that change any table '
899 . 'or database the user may execute per hour.'
900 ) . '">'
901 . 'MAX UPDATES PER HOUR'
902 . '</dfn></code></label>' . "\n"
903 . '<input type="number" name="max_updates" id="text_max_updates" '
904 . 'value="'
905 . (isset($row['max_updates']) ? $row['max_updates'] : '0')
906 . '" min="0" '
907 . 'title="'
908 . __(
909 'Limits the number of commands that change any table '
910 . 'or database the user may execute per hour.'
912 . '" />' . "\n"
913 . '</div>' . "\n";
915 $html_output .= '<div class="item">' . "\n"
916 . '<label for="text_max_connections">'
917 . '<code><dfn title="'
918 . __(
919 'Limits the number of new connections the user may open per hour.'
920 ) . '">'
921 . 'MAX CONNECTIONS PER HOUR'
922 . '</dfn></code></label>' . "\n"
923 . '<input type="number" name="max_connections" id="text_max_connections" '
924 . 'value="'
925 . (isset($row['max_connections']) ? $row['max_connections'] : '0')
926 . '" min="0" '
927 . 'title="' . __(
928 'Limits the number of new connections the user may open per hour.'
930 . '" />' . "\n"
931 . '</div>' . "\n";
933 $html_output .= '<div class="item">' . "\n"
934 . '<label for="text_max_user_connections">'
935 . '<code><dfn title="'
936 . __('Limits the number of simultaneous connections the user may have.')
937 . '">'
938 . 'MAX USER_CONNECTIONS'
939 . '</dfn></code></label>' . "\n"
940 . '<input type="number" name="max_user_connections" '
941 . 'id="text_max_user_connections" '
942 . 'value="'
943 . (isset($row['max_user_connections']) ? $row['max_user_connections'] : '0')
944 . '" '
945 . 'title="'
946 . __('Limits the number of simultaneous connections the user may have.')
947 . '" />' . "\n"
948 . '</div>' . "\n";
950 $html_output .= '</fieldset>' . "\n";
952 return $html_output;
956 * Get the HTML snippet for table specific privileges
958 * @param string $username username for database connection
959 * @param string $hostname hostname for database connection
960 * @param string $db the database
961 * @param string $table the table
962 * @param array $columns columns array
963 * @param array $row current privileges row
965 * @return string $html_output
967 function PMA_getHtmlForTableSpecificPrivileges(
968 $username, $hostname, $db, $table, $columns, $row
970 $res = $GLOBALS['dbi']->query(
971 'SELECT `Column_name`, `Column_priv`'
972 . ' FROM `mysql`.`columns_priv`'
973 . ' WHERE `User`'
974 . ' = \'' . PMA_Util::sqlAddSlashes($username) . "'"
975 . ' AND `Host`'
976 . ' = \'' . PMA_Util::sqlAddSlashes($hostname) . "'"
977 . ' AND `Db`'
978 . ' = \'' . PMA_Util::sqlAddSlashes(
979 PMA_Util::unescapeMysqlWildcards($db)
980 ) . "'"
981 . ' AND `Table_name`'
982 . ' = \'' . PMA_Util::sqlAddSlashes($table) . '\';'
985 while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
986 $row1[1] = explode(',', $row1[1]);
987 foreach ($row1[1] as $current) {
988 $columns[$row1[0]][$current] = true;
991 $GLOBALS['dbi']->freeResult($res);
992 unset($res, $row1, $current);
994 $html_output = '<input type="hidden" name="grant_count" '
995 . 'value="' . count($row) . '" />' . "\n"
996 . '<input type="hidden" name="column_count" '
997 . 'value="' . count($columns) . '" />' . "\n"
998 . '<fieldset id="fieldset_user_priv">' . "\n"
999 . '<legend data-submenu-label="Table">' . __('Table-specific privileges')
1000 . PMA_Util::showHint(
1001 __('Note: MySQL privilege names are expressed in English.')
1003 . '</legend>' . "\n";
1005 // privs that are attached to a specific column
1006 $html_output .= PMA_getHtmlForAttachedPrivilegesToTableSpecificColumn(
1007 $columns, $row
1010 // privs that are not attached to a specific column
1011 $html_output .= '<div class="item">' . "\n"
1012 . PMA_getHtmlForNotAttachedPrivilegesToTableSpecificColumn($row)
1013 . '</div>' . "\n";
1015 // for Safari 2.0.2
1016 $html_output .= '<div class="clearfloat"></div>' . "\n";
1018 return $html_output;
1022 * Get HTML snippet for privileges that are attached to a specific column
1024 * @param array $columns columns array
1025 * @param array $row first row from result or boolean false
1027 * @return string $html_output
1029 function PMA_getHtmlForAttachedPrivilegesToTableSpecificColumn($columns, $row)
1031 $html_output = PMA_getHtmlForColumnPrivileges(
1032 $columns, $row, 'Select_priv', 'SELECT',
1033 'select', __('Allows reading data.'), 'Select'
1036 $html_output .= PMA_getHtmlForColumnPrivileges(
1037 $columns, $row, 'Insert_priv', 'INSERT',
1038 'insert', __('Allows inserting and replacing data.'), 'Insert'
1041 $html_output .= PMA_getHtmlForColumnPrivileges(
1042 $columns, $row, 'Update_priv', 'UPDATE',
1043 'update', __('Allows changing data.'), 'Update'
1046 $html_output .= PMA_getHtmlForColumnPrivileges(
1047 $columns, $row, 'References_priv', 'REFERENCES', 'references',
1048 __('Has no effect in this MySQL version.'), 'References'
1050 return $html_output;
1054 * Get HTML for privileges that are not attached to a specific column
1056 * @param array $row first row from result or boolean false
1058 * @return string $html_output
1060 function PMA_getHtmlForNotAttachedPrivilegesToTableSpecificColumn($row)
1062 $html_output = '';
1064 foreach ($row as $current_grant => $current_grant_value) {
1065 $grant_type = substr($current_grant, 0, -5);
1066 if (in_array($grant_type, array('Select', 'Insert', 'Update', 'References'))
1068 continue;
1070 // make a substitution to match the messages variables;
1071 // also we must substitute the grant we get, because we can't generate
1072 // a form variable containing blanks (those would get changed to
1073 // an underscore when receiving the POST)
1074 if ($current_grant == 'Create View_priv') {
1075 $tmp_current_grant = 'CreateView_priv';
1076 $current_grant = 'Create_view_priv';
1077 } elseif ($current_grant == 'Show view_priv') {
1078 $tmp_current_grant = 'ShowView_priv';
1079 $current_grant = 'Show_view_priv';
1080 } else {
1081 $tmp_current_grant = $current_grant;
1084 $html_output .= '<div class="item">' . "\n"
1085 . '<input type="checkbox"'
1086 . ' name="' . $current_grant . '" id="checkbox_' . $current_grant
1087 . '" value="Y" '
1088 . ($current_grant_value == 'Y' ? 'checked="checked" ' : '')
1089 . 'title="';
1091 $privGlobalName = 'strPrivDesc'
1092 . /*overload*/mb_substr(
1093 $tmp_current_grant,
1095 (/*overload*/mb_strlen($tmp_current_grant) - 5)
1097 $html_output .= (isset($GLOBALS[$privGlobalName])
1098 ? $GLOBALS[$privGlobalName]
1099 : $GLOBALS[$privGlobalName . 'Tbl']
1101 . '"/>' . "\n";
1103 $privGlobalName1 = 'strPrivDesc'
1104 . /*overload*/mb_substr(
1105 $tmp_current_grant,
1109 $html_output .= '<label for="checkbox_' . $current_grant
1110 . '"><code><dfn title="'
1111 . (isset($GLOBALS[$privGlobalName1])
1112 ? $GLOBALS[$privGlobalName1]
1113 : $GLOBALS[$privGlobalName1 . 'Tbl']
1115 . '">'
1116 . /*overload*/mb_strtoupper(
1117 /*overload*/mb_substr(
1118 $current_grant,
1123 . '</dfn></code></label>' . "\n"
1124 . '</div>' . "\n";
1125 } // end foreach ()
1126 return $html_output;
1130 * Get HTML for global or database specific privileges
1132 * @param string $db the database
1133 * @param string $table the table
1134 * @param array $row first row from result or boolean false
1136 * @return string $html_output
1138 function PMA_getHtmlForGlobalOrDbSpecificPrivs($db, $table, $row)
1140 $privTable_names = array(0 => __('Data'),
1141 1 => __('Structure'),
1142 2 => __('Administration')
1144 $privTable = array();
1145 // d a t a
1146 $privTable[0] = PMA_getDataPrivilegeTable($db);
1148 // s t r u c t u r e
1149 $privTable[1] = PMA_getStructurePrivilegeTable($table, $row);
1151 // a d m i n i s t r a t i o n
1152 $privTable[2] = PMA_getAdministrationPrivilegeTable($db);
1154 $html_output = '<input type="hidden" name="grant_count" value="'
1155 . (count($privTable[0])
1156 + count($privTable[1])
1157 + count($privTable[2])
1158 - (isset($row['Grant_priv']) ? 1 : 0)
1160 . '" />';
1161 if ($db == '*') {
1162 $legend = __('Global privileges');
1163 $menu_label = __('Global');
1164 } else if ($table == '*') {
1165 $legend = __('Database-specific privileges');
1166 $menu_label = __('Database');
1167 } else {
1168 $legend = __('Table-specific privileges');
1169 $menu_label = __('Table');
1171 $html_output .= '<fieldset id="fieldset_user_global_rights">'
1172 . '<legend data-submenu-label="' . $menu_label . '">' . $legend
1173 . '<input type="checkbox" id="addUsersForm_checkall" '
1174 . 'class="checkall_box" title="' . __('Check All') . '" /> '
1175 . '<label for="addUsersForm_checkall">' . __('Check All') . '</label> '
1176 . '</legend>'
1177 . '<p><small><i>'
1178 . __('Note: MySQL privilege names are expressed in English.')
1179 . '</i></small></p>';
1181 // Output the Global privilege tables with checkboxes
1182 $html_output .= PMA_getHtmlForGlobalPrivTableWithCheckboxes(
1183 $privTable, $privTable_names, $row
1186 // The "Resource limits" box is not displayed for db-specific privs
1187 if ($db == '*') {
1188 $html_output .= PMA_getHtmlForResourceLimits($row);
1189 $html_output .= PMA_getHtmlForRequires($row);
1191 // for Safari 2.0.2
1192 $html_output .= '<div class="clearfloat"></div>';
1194 return $html_output;
1198 * Get data privilege table as an array
1200 * @param string $db the database
1202 * @return string data privilege table
1204 function PMA_getDataPrivilegeTable($db)
1206 $data_privTable = array(
1207 array('Select', 'SELECT', __('Allows reading data.')),
1208 array('Insert', 'INSERT', __('Allows inserting and replacing data.')),
1209 array('Update', 'UPDATE', __('Allows changing data.')),
1210 array('Delete', 'DELETE', __('Allows deleting data.'))
1212 if ($db == '*') {
1213 $data_privTable[]
1214 = array('File',
1215 'FILE',
1216 __('Allows importing data from and exporting data into files.')
1219 return $data_privTable;
1223 * Get structure privilege table as an array
1225 * @param string $table the table
1226 * @param array $row first row from result or boolean false
1228 * @return string structure privilege table
1230 function PMA_getStructurePrivilegeTable($table, $row)
1232 $structure_privTable = array(
1233 array('Create',
1234 'CREATE',
1235 ($table == '*'
1236 ? __('Allows creating new databases and tables.')
1237 : __('Allows creating new tables.')
1240 array('Alter',
1241 'ALTER',
1242 __('Allows altering the structure of existing tables.')
1244 array('Index', 'INDEX', __('Allows creating and dropping indexes.')),
1245 array('Drop',
1246 'DROP',
1247 ($table == '*'
1248 ? __('Allows dropping databases and tables.')
1249 : __('Allows dropping tables.')
1252 array('Create_tmp_table',
1253 'CREATE TEMPORARY TABLES',
1254 __('Allows creating temporary tables.')
1256 array('Show_view',
1257 'SHOW VIEW',
1258 __('Allows performing SHOW CREATE VIEW queries.')
1260 array('Create_routine',
1261 'CREATE ROUTINE',
1262 __('Allows creating stored routines.')
1264 array('Alter_routine',
1265 'ALTER ROUTINE',
1266 __('Allows altering and dropping stored routines.')
1268 array('Execute', 'EXECUTE', __('Allows executing stored routines.')),
1270 // this one is for a db-specific priv: Create_view_priv
1271 if (isset($row['Create_view_priv'])) {
1272 $structure_privTable[] = array('Create_view',
1273 'CREATE VIEW',
1274 __('Allows creating new views.')
1277 // this one is for a table-specific priv: Create View_priv
1278 if (isset($row['Create View_priv'])) {
1279 $structure_privTable[] = array('Create View',
1280 'CREATE VIEW',
1281 __('Allows creating new views.')
1284 if (isset($row['Event_priv'])) {
1285 // MySQL 5.1.6
1286 $structure_privTable[] = array('Event',
1287 'EVENT',
1288 __('Allows to set up events for the event scheduler.')
1290 $structure_privTable[] = array('Trigger',
1291 'TRIGGER',
1292 __('Allows creating and dropping triggers.')
1295 return $structure_privTable;
1299 * Get administration privilege table as an array
1301 * @param string $db the table
1303 * @return string administration privilege table
1305 function PMA_getAdministrationPrivilegeTable($db)
1307 $adminPrivTable = array(
1308 array('Grant',
1309 'GRANT',
1311 'Allows adding users and privileges '
1312 . 'without reloading the privilege tables.'
1316 if ($db == '*') {
1317 $adminPrivTable[] = array('Super',
1318 'SUPER',
1320 'Allows connecting, even if maximum number '
1321 . 'of connections is reached; required for '
1322 . 'most administrative operations like '
1323 . 'setting global variables or killing threads of other users.'
1326 $adminPrivTable[] = array('Process',
1327 'PROCESS',
1328 __('Allows viewing processes of all users.')
1330 $adminPrivTable[] = array('Reload',
1331 'RELOAD',
1332 __('Allows reloading server settings and flushing the server\'s caches.')
1334 $adminPrivTable[] = array('Shutdown',
1335 'SHUTDOWN',
1336 __('Allows shutting down the server.')
1338 $adminPrivTable[] = array('Show_db',
1339 'SHOW DATABASES',
1340 __('Gives access to the complete list of databases.')
1343 $adminPrivTable[] = array('Lock_tables',
1344 'LOCK TABLES',
1345 __('Allows locking tables for the current thread.')
1347 $adminPrivTable[] = array('References',
1348 'REFERENCES',
1349 __('Has no effect in this MySQL version.')
1351 if ($db == '*') {
1352 $adminPrivTable[] = array('Repl_client',
1353 'REPLICATION CLIENT',
1354 __('Allows the user to ask where the slaves / masters are.')
1356 $adminPrivTable[] = array('Repl_slave',
1357 'REPLICATION SLAVE',
1358 __('Needed for the replication slaves.')
1360 $adminPrivTable[] = array('Create_user',
1361 'CREATE USER',
1362 __('Allows creating, dropping and renaming user accounts.')
1365 return $adminPrivTable;
1369 * Get HTML snippet for global privileges table with check boxes
1371 * @param array $privTable privileges table array
1372 * @param array $privTable_names names of the privilege tables
1373 * (Data, Structure, Administration)
1374 * @param array $row first row from result or boolean false
1376 * @return string $html_output
1378 function PMA_getHtmlForGlobalPrivTableWithCheckboxes(
1379 $privTable, $privTable_names, $row
1381 $html_output = '';
1382 foreach ($privTable as $i => $table) {
1383 $html_output .= '<fieldset>' . "\n"
1384 . '<legend>' . "\n"
1385 . '<input type="checkbox" class="sub_checkall_box"'
1386 . ' id="checkall_' . $privTable_names[$i] . '_priv"'
1387 . ' title="' . __('Check All') . '"/>'
1388 . '<label for="checkall_' . $privTable_names[$i] . '_priv">'
1389 . $privTable_names[$i] . '</label>' . "\n"
1390 . '</legend>' . "\n";
1391 foreach ($table as $priv) {
1392 $html_output .= '<div class="item">' . "\n"
1393 . '<input type="checkbox" class="checkall"'
1394 . ' name="' . $priv[0] . '_priv" '
1395 . 'id="checkbox_' . $priv[0] . '_priv"'
1396 . ' value="Y" title="' . $priv[2] . '"'
1397 . ((isset($row[$priv[0] . '_priv'])
1398 && $row[$priv[0] . '_priv'] == 'Y')
1399 ? ' checked="checked"'
1400 : ''
1402 . '/>' . "\n"
1403 . '<label for="checkbox_' . $priv[0] . '_priv">'
1404 . '<code>'
1405 . PMA_formatPrivilege($priv, true)
1406 . '</code></label>' . "\n"
1407 . '</div>' . "\n";
1409 $html_output .= '</fieldset>' . "\n";
1411 return $html_output;
1415 * Displays the fields used by the "new user" form as well as the
1416 * "change login information / copy user" form.
1418 * @param string $mode are we creating a new user or are we just
1419 * changing one? (allowed values: 'new', 'change')
1421 * @global array $cfg the phpMyAdmin configuration
1422 * @global resource $user_link the database connection
1424 * @return string $html_output a HTML snippet
1426 function PMA_getHtmlForLoginInformationFields($mode = 'new')
1428 list($username_length, $hostname_length) = PMA_getUsernameAndHostnameLength();
1430 if (isset($GLOBALS['username'])
1431 && /*overload*/mb_strlen($GLOBALS['username']) === 0
1433 $GLOBALS['pred_username'] = 'any';
1435 $html_output = '<fieldset id="fieldset_add_user_login">' . "\n"
1436 . '<legend>' . __('Login Information') . '</legend>' . "\n"
1437 . '<div class="item">' . "\n"
1438 . '<label for="select_pred_username">' . "\n"
1439 . ' ' . __('User name:') . "\n"
1440 . '</label>' . "\n"
1441 . '<span class="options">' . "\n";
1443 $html_output .= '<select name="pred_username" id="select_pred_username" '
1444 . 'title="' . __('User name') . '"' . "\n";
1446 $html_output .= ' onchange="'
1447 . 'if (this.value == \'any\') {'
1448 . ' username.value = \'\'; '
1449 . ' user_exists_warning.style.display = \'none\'; '
1450 . ' username.required = false; '
1451 . '} else if (this.value == \'userdefined\') {'
1452 . ' username.focus(); username.select(); '
1453 . ' username.required = true; '
1454 . '}">' . "\n";
1456 $html_output .= '<option value="any"'
1457 . ((isset($GLOBALS['pred_username']) && $GLOBALS['pred_username'] == 'any')
1458 ? ' selected="selected"'
1459 : '') . '>'
1460 . __('Any user')
1461 . '</option>' . "\n";
1463 $html_output .= '<option value="userdefined"'
1464 . ((! isset($GLOBALS['pred_username'])
1465 || $GLOBALS['pred_username'] == 'userdefined'
1467 ? ' selected="selected"'
1468 : '') . '>'
1469 . __('Use text field')
1470 . ':</option>' . "\n";
1472 $html_output .= '</select>' . "\n"
1473 . '</span>' . "\n";
1475 $html_output .= '<input type="text" name="username" class="autofocus"'
1476 . ' maxlength="' . $username_length . '" title="' . __('User name') . '"'
1477 . (empty($GLOBALS['username'])
1478 ? ''
1479 : ' value="' . htmlspecialchars(
1480 isset($GLOBALS['new_username'])
1481 ? $GLOBALS['new_username']
1482 : $GLOBALS['username']
1483 ) . '"'
1485 . ' onchange="pred_username.value = \'userdefined\'; this.required = true;" '
1486 . ((! isset($GLOBALS['pred_username'])
1487 || $GLOBALS['pred_username'] == 'userdefined'
1489 ? 'required="required"'
1490 : '') . ' />' . "\n";
1492 $html_output .= '<div id="user_exists_warning"'
1493 . ' name="user_exists_warning" style="display:none;">'
1494 . PMA_Message::notice(
1496 'An account already exists with the same username '
1497 . 'but possibly a different hostname.'
1499 )->getDisplay()
1500 . '</div>';
1501 $html_output .= '</div>';
1503 $html_output .= '<div class="item">' . "\n"
1504 . '<label for="select_pred_hostname">' . "\n"
1505 . ' ' . __('Host name:') . "\n"
1506 . '</label>' . "\n";
1508 $html_output .= '<span class="options">' . "\n"
1509 . ' <select name="pred_hostname" id="select_pred_hostname" '
1510 . 'title="' . __('Host name') . '"' . "\n";
1511 $_current_user = $GLOBALS['dbi']->fetchValue('SELECT USER();');
1512 if (! empty($_current_user)) {
1513 $thishost = str_replace(
1514 "'",
1516 /*overload*/mb_substr(
1517 $_current_user,
1518 (/*overload*/mb_strrpos($_current_user, '@') + 1)
1521 if ($thishost == 'localhost' || $thishost == '127.0.0.1') {
1522 unset($thishost);
1525 $html_output .= ' onchange="'
1526 . 'if (this.value == \'any\') { '
1527 . ' hostname.value = \'%\'; '
1528 . '} else if (this.value == \'localhost\') { '
1529 . ' hostname.value = \'localhost\'; '
1530 . '} '
1531 . (empty($thishost)
1532 ? ''
1533 : 'else if (this.value == \'thishost\') { '
1534 . ' hostname.value = \'' . addslashes(htmlspecialchars($thishost))
1535 . '\'; '
1536 . '} '
1538 . 'else if (this.value == \'hosttable\') { '
1539 . ' hostname.value = \'\'; '
1540 . ' hostname.required = false; '
1541 . '} else if (this.value == \'userdefined\') {'
1542 . ' hostname.focus(); hostname.select(); '
1543 . ' hostname.required = true; '
1544 . '}">' . "\n";
1545 unset($_current_user);
1547 // when we start editing a user, $GLOBALS['pred_hostname'] is not defined
1548 if (! isset($GLOBALS['pred_hostname']) && isset($GLOBALS['hostname'])) {
1549 switch (/*overload*/mb_strtolower($GLOBALS['hostname'])) {
1550 case 'localhost':
1551 case '127.0.0.1':
1552 $GLOBALS['pred_hostname'] = 'localhost';
1553 break;
1554 case '%':
1555 $GLOBALS['pred_hostname'] = 'any';
1556 break;
1557 default:
1558 $GLOBALS['pred_hostname'] = 'userdefined';
1559 break;
1562 $html_output .= '<option value="any"'
1563 . ((isset($GLOBALS['pred_hostname'])
1564 && $GLOBALS['pred_hostname'] == 'any'
1566 ? ' selected="selected"'
1567 : '') . '>'
1568 . __('Any host')
1569 . '</option>' . "\n"
1570 . '<option value="localhost"'
1571 . ((isset($GLOBALS['pred_hostname'])
1572 && $GLOBALS['pred_hostname'] == 'localhost'
1574 ? ' selected="selected"'
1575 : '') . '>'
1576 . __('Local')
1577 . '</option>' . "\n";
1578 if (! empty($thishost)) {
1579 $html_output .= '<option value="thishost"'
1580 . ((isset($GLOBALS['pred_hostname'])
1581 && $GLOBALS['pred_hostname'] == 'thishost'
1583 ? ' selected="selected"'
1584 : '') . '>'
1585 . __('This Host')
1586 . '</option>' . "\n";
1588 unset($thishost);
1589 $html_output .= '<option value="hosttable"'
1590 . ((isset($GLOBALS['pred_hostname'])
1591 && $GLOBALS['pred_hostname'] == 'hosttable'
1593 ? ' selected="selected"'
1594 : '') . '>'
1595 . __('Use Host Table')
1596 . '</option>' . "\n";
1598 $html_output .= '<option value="userdefined"'
1599 . ((isset($GLOBALS['pred_hostname'])
1600 && $GLOBALS['pred_hostname'] == 'userdefined'
1602 ? ' selected="selected"'
1603 : '') . '>'
1604 . __('Use text field:') . '</option>' . "\n"
1605 . '</select>' . "\n"
1606 . '</span>' . "\n";
1608 $html_output .= '<input type="text" name="hostname" maxlength="'
1609 . $hostname_length . '" value="'
1610 // use default value of '%' to match with the default 'Any host'
1611 . htmlspecialchars(isset($GLOBALS['hostname']) ? $GLOBALS['hostname'] : '%')
1612 . '" title="' . __('Host name')
1613 . '" onchange="pred_hostname.value = \'userdefined\'; '
1614 . 'this.required = true;" '
1615 . ((isset($GLOBALS['pred_hostname'])
1616 && $GLOBALS['pred_hostname'] == 'userdefined'
1618 ? 'required="required"'
1619 : '')
1620 . ' />' . "\n"
1621 . PMA_Util::showHint(
1623 'When Host table is used, this field is ignored '
1624 . 'and values stored in Host table are used instead.'
1627 . '</div>' . "\n";
1629 $html_output .= '<div class="item">' . "\n"
1630 . '<label for="select_pred_password">' . "\n"
1631 . ' ' . __('Password:') . "\n"
1632 . '</label>' . "\n"
1633 . '<span class="options">' . "\n"
1634 . '<select name="pred_password" id="select_pred_password" title="'
1635 . __('Password') . '"' . "\n";
1637 $html_output .= ' onchange="'
1638 . 'if (this.value == \'none\') { '
1639 . ' pma_pw.value = \'\'; pma_pw2.value = \'\'; '
1640 . ' pma_pw.required = false; pma_pw2.required = false; '
1641 . '} else if (this.value == \'userdefined\') { '
1642 . ' pma_pw.focus(); pma_pw.select(); '
1643 . ' pma_pw.required = true; pma_pw2.required = true; '
1644 . '} else { '
1645 . ' pma_pw.required = false; pma_pw2.required = false; '
1646 . '}">' . "\n"
1647 . ($mode == 'change' ? '<option value="keep" selected="selected">'
1648 . __('Do not change the password')
1649 . '</option>' . "\n" : '')
1650 . '<option value="none"';
1652 if (isset($GLOBALS['username']) && $mode != 'change') {
1653 $html_output .= ' selected="selected"';
1655 $html_output .= '>' . __('No Password') . '</option>' . "\n"
1656 . '<option value="userdefined"'
1657 . (isset($GLOBALS['username']) ? '' : ' selected="selected"') . '>'
1658 . __('Use text field')
1659 . ':</option>' . "\n"
1660 . '</select>' . "\n"
1661 . '</span>' . "\n"
1662 . '<input type="password" id="text_pma_pw" name="pma_pw" '
1663 . 'title="' . __('Password') . '" '
1664 . 'onchange="pred_password.value = \'userdefined\'; this.required = true; '
1665 . 'pma_pw2.required = true;" '
1666 . (isset($GLOBALS['username']) ? '' : 'required="required"')
1667 . '/>' . "\n"
1668 . '</div>' . "\n";
1670 $html_output .= '<div class="item" '
1671 . 'id="div_element_before_generate_password">' . "\n"
1672 . '<label for="text_pma_pw2">' . "\n"
1673 . ' ' . __('Re-type:') . "\n"
1674 . '</label>' . "\n"
1675 . '<span class="options">&nbsp;</span>' . "\n"
1676 . '<input type="password" name="pma_pw2" id="text_pma_pw2" '
1677 . 'title="' . __('Re-type') . '" '
1678 . 'onchange="pred_password.value = \'userdefined\'; this.required = true; '
1679 . 'pma_pw.required = true;" '
1680 . (isset($GLOBALS['username']) ? '' : 'required="required"')
1681 . '/>' . "\n"
1682 . '</div>' . "\n"
1683 // Generate password added here via jQuery
1684 . '</fieldset>' . "\n";
1686 return $html_output;
1687 } // end of the 'PMA_displayUserAndHostFields()' function
1690 * Get username and hostname length
1692 * @return array username length and hostname length
1694 function PMA_getUsernameAndHostnameLength()
1696 /* Fallback values */
1697 $username_length = 16;
1698 $hostname_length = 41;
1700 /* Try to get real lengths from the database */
1701 $fields_info = $GLOBALS['dbi']->fetchResult(
1702 'SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH '
1703 . 'FROM information_schema.columns '
1704 . "WHERE table_schema = 'mysql' AND table_name = 'user' "
1705 . "AND COLUMN_NAME IN ('User', 'Host')"
1707 foreach ($fields_info as $val) {
1708 if ($val['COLUMN_NAME'] == 'User') {
1709 $username_length = $val['CHARACTER_MAXIMUM_LENGTH'];
1710 } elseif ($val['COLUMN_NAME'] == 'Host') {
1711 $hostname_length = $val['CHARACTER_MAXIMUM_LENGTH'];
1714 return array($username_length, $hostname_length);
1718 * Returns all the grants for a certain user on a certain host
1719 * Used in the export privileges for all users section
1721 * @param string $user User name
1722 * @param string $host Host name
1724 * @return string containing all the grants text
1726 function PMA_getGrants($user, $host)
1728 $grants = $GLOBALS['dbi']->fetchResult(
1729 "SHOW GRANTS FOR '"
1730 . PMA_Util::sqlAddSlashes($user) . "'@'"
1731 . PMA_Util::sqlAddSlashes($host) . "'"
1733 $response = '';
1734 foreach ($grants as $one_grant) {
1735 $response .= $one_grant . ";\n\n";
1737 return $response;
1738 } // end of the 'PMA_getGrants()' function
1741 * Update password and get message for password updating
1743 * @param string $err_url error url
1744 * @param string $username username
1745 * @param string $hostname hostname
1747 * @return string $message success or error message after updating password
1749 function PMA_updatePassword($err_url, $username, $hostname)
1751 // similar logic in user_password.php
1752 $message = '';
1754 if (empty($_REQUEST['nopass'])
1755 && isset($_POST['pma_pw'])
1756 && isset($_POST['pma_pw2'])
1758 if ($_POST['pma_pw'] != $_POST['pma_pw2']) {
1759 $message = PMA_Message::error(__('The passwords aren\'t the same!'));
1760 } elseif (empty($_POST['pma_pw']) || empty($_POST['pma_pw2'])) {
1761 $message = PMA_Message::error(__('The password is empty!'));
1765 // here $nopass could be == 1
1766 if (empty($message)) {
1767 if (PMA_Util::getServerType() == 'MySQL'
1768 && PMA_MYSQL_INT_VERSION >= 50706
1770 $query_prefix = "ALTER USER '"
1771 . PMA_Util::sqlAddSlashes($username)
1772 . "'@'" . PMA_Util::sqlAddSlashes($hostname) . "'"
1773 . " IDENTIFIED BY '";
1775 // in $sql_query which will be displayed, hide the password
1776 $sql_query = $query_prefix . "*'";
1778 $local_query = $query_prefix
1779 . PMA_Util::sqlAddSlashes($_POST['pma_pw']) . "'";
1780 } else {
1781 if (! empty($_REQUEST['pw_hash']) && $_REQUEST['pw_hash'] == 'old') {
1782 $hashing_function = 'OLD_PASSWORD';
1783 } else {
1784 $hashing_function = 'PASSWORD';
1787 $sql_query = 'SET PASSWORD FOR \''
1788 . PMA_Util::sqlAddSlashes($username)
1789 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\' = '
1790 . (($_POST['pma_pw'] == '')
1791 ? '\'\''
1792 : $hashing_function . '(\''
1793 . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
1795 $local_query = 'SET PASSWORD FOR \''
1796 . PMA_Util::sqlAddSlashes($username)
1797 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\' = '
1798 . (($_POST['pma_pw'] == '') ? '\'\'' : $hashing_function
1799 . '(\'' . PMA_Util::sqlAddSlashes($_POST['pma_pw']) . '\')');
1802 $GLOBALS['dbi']->tryQuery($local_query)
1803 or PMA_Util::mysqlDie(
1804 $GLOBALS['dbi']->getError(), $sql_query, false, $err_url
1806 $message = PMA_Message::success(
1807 __('The password for %s was changed successfully.')
1809 $message->addParam(
1810 '\'' . htmlspecialchars($username)
1811 . '\'@\'' . htmlspecialchars($hostname) . '\''
1814 return $message;
1818 * Revokes privileges and get message and SQL query for privileges revokes
1820 * @param string $dbname database name
1821 * @param string $tablename table name
1822 * @param string $username username
1823 * @param string $hostname host name
1825 * @return array ($message, $sql_query)
1827 function PMA_getMessageAndSqlQueryForPrivilegesRevoke($dbname,
1828 $tablename, $username, $hostname
1830 $db_and_table = PMA_wildcardEscapeForGrant($dbname, $tablename);
1832 $sql_query0 = 'REVOKE ALL PRIVILEGES ON ' . $db_and_table
1833 . ' FROM \''
1834 . PMA_Util::sqlAddSlashes($username) . '\'@\''
1835 . PMA_Util::sqlAddSlashes($hostname) . '\';';
1837 $sql_query1 = 'REVOKE GRANT OPTION ON ' . $db_and_table
1838 . ' FROM \'' . PMA_Util::sqlAddSlashes($username) . '\'@\''
1839 . PMA_Util::sqlAddSlashes($hostname) . '\';';
1841 $GLOBALS['dbi']->query($sql_query0);
1842 if (! $GLOBALS['dbi']->tryQuery($sql_query1)) {
1843 // this one may fail, too...
1844 $sql_query1 = '';
1846 $sql_query = $sql_query0 . ' ' . $sql_query1;
1847 $message = PMA_Message::success(
1848 __('You have revoked the privileges for %s.')
1850 $message->addParam(
1851 '\'' . htmlspecialchars($username)
1852 . '\'@\'' . htmlspecialchars($hostname) . '\''
1855 return array($message, $sql_query);
1859 * Get REQUIRE cluase
1861 * @return stirng REQUIRE clause
1863 function PMA_getRequireClause()
1865 $require_clause = "";
1866 if (isset($_POST['SSL_priv']) && $_POST['SSL_priv'] == 'Y') {
1867 if (isset($_POST['ssl_type']) && $_POST['ssl_type'] == 'specified') {
1868 $require = array();
1869 if (! empty($_POST['ssl_cipher'])) {
1870 $require[] = "CIPHER '"
1871 . PMA_Util::sqlAddSlashes($_POST['ssl_cipher']) . "'";
1873 if (! empty($_POST['x509_issuer'])) {
1874 $require[] = "ISSUER '"
1875 . PMA_Util::sqlAddSlashes($_POST['x509_issuer']) . "'";
1877 if (! empty($_POST['x509_subject'])) {
1878 $require[] = "SUBJECT '"
1879 . PMA_Util::sqlAddSlashes($_POST['x509_subject']) . "'";
1881 if (count($require)) {
1882 $require_clause = " REQUIRE " . implode(" AND ", $require);
1883 } else {
1884 $require_clause = " REQUIRE NONE";
1886 } elseif (isset($_POST['ssl_type']) && $_POST['ssl_type'] == 'X509') {
1887 $require_clause = " REQUIRE X509";
1888 } elseif (isset($_POST['ssl_type']) && $_POST['ssl_type'] == 'ANY') {
1889 $require_clause = " REQUIRE SSL";
1891 } else {
1892 $require_clause = " REQUIRE NONE";
1895 return $require_clause;
1899 * Get a WITH clause for 'update privileges' and 'add user'
1901 * @return string $sql_query
1903 function PMA_getWithClauseForAddUserAndUpdatePrivs()
1905 $sql_query = '';
1906 if (isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y') {
1907 $sql_query .= ' GRANT OPTION';
1909 if (isset($_POST['max_questions'])) {
1910 $max_questions = max(0, (int)$_POST['max_questions']);
1911 $sql_query .= ' MAX_QUERIES_PER_HOUR ' . $max_questions;
1913 if (isset($_POST['max_connections'])) {
1914 $max_connections = max(0, (int)$_POST['max_connections']);
1915 $sql_query .= ' MAX_CONNECTIONS_PER_HOUR ' . $max_connections;
1917 if (isset($_POST['max_updates'])) {
1918 $max_updates = max(0, (int)$_POST['max_updates']);
1919 $sql_query .= ' MAX_UPDATES_PER_HOUR ' . $max_updates;
1921 if (isset($_POST['max_user_connections'])) {
1922 $max_user_connections = max(0, (int)$_POST['max_user_connections']);
1923 $sql_query .= ' MAX_USER_CONNECTIONS ' . $max_user_connections;
1925 return ((!empty($sql_query)) ? ' WITH' . $sql_query : '');
1929 * Get HTML for addUsersForm, This function call if isset($_REQUEST['adduser'])
1931 * @param string $dbname database name
1933 * @return string HTML for addUserForm
1935 function PMA_getHtmlForAddUser($dbname)
1937 $html_output = '<h2>' . "\n"
1938 . PMA_Util::getIcon('b_usradd.png') . __('Add user account') . "\n"
1939 . '</h2>' . "\n"
1940 . '<form name="usersForm" id="addUsersForm"'
1941 . ' onsubmit="return checkAddUser(this);"'
1942 . ' action="server_privileges.php" method="post" autocomplete="off" >' . "\n"
1943 . PMA_URL_getHiddenInputs('', '')
1944 . PMA_getHtmlForLoginInformationFields('new');
1946 $html_output .= '<fieldset id="fieldset_add_user_database">' . "\n"
1947 . '<legend>' . __('Database for user account') . '</legend>' . "\n";
1949 $html_output .= PMA_Util::getCheckbox(
1950 'createdb-1',
1951 __('Create database with same name and grant all privileges.'),
1952 false, false, 'createdb-1'
1954 $html_output .= '<br />' . "\n";
1955 $html_output .= PMA_Util::getCheckbox(
1956 'createdb-2',
1957 __('Grant all privileges on wildcard name (username\\_%).'),
1958 false, false, 'createdb-2'
1960 $html_output .= '<br />' . "\n";
1962 if (! empty($dbname) ) {
1963 $html_output .= PMA_Util::getCheckbox(
1964 'createdb-3',
1965 sprintf(
1966 __('Grant all privileges on database "%s".'),
1967 htmlspecialchars($dbname)
1969 true,
1970 false,
1971 'createdb-3'
1973 $html_output .= '<input type="hidden" name="dbname" value="'
1974 . htmlspecialchars($dbname) . '" />' . "\n";
1975 $html_output .= '<br />' . "\n";
1978 $html_output .= '</fieldset>' . "\n";
1979 if ($GLOBALS['is_grantuser']) {
1980 $html_output .= PMA_getHtmlToDisplayPrivilegesTable('*', '*', false);
1982 $html_output .= '<fieldset id="fieldset_add_user_footer" class="tblFooters">'
1983 . "\n"
1984 . '<input type="hidden" name="adduser_submit" value="1" />' . "\n"
1985 . '<input type="submit" id="adduser_submit" value="' . __('Go') . '" />'
1986 . "\n"
1987 . '</fieldset>' . "\n"
1988 . '</form>' . "\n";
1990 return $html_output;
1994 * Get the list of privileges and list of compared privileges as strings
1995 * and return a array that contains both strings
1997 * @return array $list_of_privileges, $list_of_compared_privileges
1999 function PMA_getListOfPrivilegesAndComparedPrivileges()
2001 $list_of_privileges
2002 = '`User`, '
2003 . '`Host`, '
2004 . '`Select_priv`, '
2005 . '`Insert_priv`, '
2006 . '`Update_priv`, '
2007 . '`Delete_priv`, '
2008 . '`Create_priv`, '
2009 . '`Drop_priv`, '
2010 . '`Grant_priv`, '
2011 . '`Index_priv`, '
2012 . '`Alter_priv`, '
2013 . '`References_priv`, '
2014 . '`Create_tmp_table_priv`, '
2015 . '`Lock_tables_priv`, '
2016 . '`Create_view_priv`, '
2017 . '`Show_view_priv`, '
2018 . '`Create_routine_priv`, '
2019 . '`Alter_routine_priv`, '
2020 . '`Execute_priv`';
2022 $listOfComparedPrivs
2023 = '`Select_priv` = \'N\''
2024 . ' AND `Insert_priv` = \'N\''
2025 . ' AND `Update_priv` = \'N\''
2026 . ' AND `Delete_priv` = \'N\''
2027 . ' AND `Create_priv` = \'N\''
2028 . ' AND `Drop_priv` = \'N\''
2029 . ' AND `Grant_priv` = \'N\''
2030 . ' AND `References_priv` = \'N\''
2031 . ' AND `Create_tmp_table_priv` = \'N\''
2032 . ' AND `Lock_tables_priv` = \'N\''
2033 . ' AND `Create_view_priv` = \'N\''
2034 . ' AND `Show_view_priv` = \'N\''
2035 . ' AND `Create_routine_priv` = \'N\''
2036 . ' AND `Alter_routine_priv` = \'N\''
2037 . ' AND `Execute_priv` = \'N\'';
2039 $list_of_privileges .=
2040 ', `Event_priv`, '
2041 . '`Trigger_priv`';
2042 $listOfComparedPrivs .=
2043 ' AND `Event_priv` = \'N\''
2044 . ' AND `Trigger_priv` = \'N\'';
2045 return array($list_of_privileges, $listOfComparedPrivs);
2049 * Get the HTML for user form and check the privileges for a particular database.
2051 * @param string $db database name
2053 * @return string $html_output
2055 function PMA_getHtmlForSpecificDbPrivileges($db)
2057 $html_output = '';
2058 if ($GLOBALS['is_superuser']) {
2059 // check the privileges for a particular database.
2060 $html_output = '<form id="usersForm" action="server_privileges.php">';
2061 $html_output .= PMA_URL_getHiddenInputs($db);
2062 $html_output .= '<fieldset>';
2063 $html_output .= '<legend>' . "\n"
2064 . PMA_Util::getIcon('b_usrcheck.png')
2065 . ' '
2066 . sprintf(
2067 __('Users having access to "%s"'),
2068 '<a href="' . PMA_Util::getScriptNameForOption(
2069 $GLOBALS['cfg']['DefaultTabDatabase'], 'database'
2071 . PMA_URL_getCommon(array('db' => $db)) . '">'
2072 . htmlspecialchars($db)
2073 . '</a>'
2075 . "\n"
2076 . '</legend>' . "\n";
2078 $html_output .= '<table id="dbspecificuserrights" class="data">';
2079 $html_output .= PMA_getHtmlForPrivsTableHead();
2080 $privMap = PMA_getPrivMap($db);
2081 $html_output .= PMA_getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db);
2082 $html_output .= '</table>';
2084 $html_output .= '<div class="floatleft">';
2085 $html_output .= PMA_Util::getWithSelected(
2086 $GLOBALS['pmaThemeImage'], $GLOBALS['text_dir'], "usersForm"
2088 $html_output .= PMA_Util::getButtonOrImage(
2089 'submit_mult', 'mult_submit', 'submit_mult_export',
2090 __('Export'), 'b_tblexport.png', 'export'
2093 $html_output .= '</fieldset>';
2094 $html_output .= '</form>';
2095 } else {
2096 $html_output .= PMA_getHtmlForViewUsersError();
2099 if ($GLOBALS['is_ajax_request'] == true
2100 && empty($_REQUEST['ajax_page_request'])
2102 $message = PMA_Message::success(__('User has been added.'));
2103 $response = PMA_Response::getInstance();
2104 $response->addJSON('message', $message);
2105 $response->addJSON('user_form', $html_output);
2106 exit;
2107 } else {
2108 // Offer to create a new user for the current database
2109 $html_output .= PMA_getAddUserHtmlFieldset($db);
2111 return $html_output;
2115 * Get the HTML for user form and check the privileges for a particular table.
2117 * @param string $db database name
2118 * @param string $table table name
2120 * @return string $html_output
2122 function PMA_getHtmlForSpecificTablePrivileges($db, $table)
2124 $html_output = '';
2125 if ($GLOBALS['is_superuser']) {
2126 // check the privileges for a particular table.
2127 $html_output = '<form id="usersForm" action="server_privileges.php">';
2128 $html_output .= PMA_URL_getHiddenInputs($db, $table);
2129 $html_output .= '<fieldset>';
2130 $html_output .= '<legend>'
2131 . PMA_Util::getIcon('b_usrcheck.png')
2132 . sprintf(
2133 __('Users having access to "%s"'),
2134 '<a href="' . PMA_Util::getScriptNameForOption(
2135 $GLOBALS['cfg']['DefaultTabTable'], 'table'
2137 . PMA_URL_getCommon(
2138 array(
2139 'db' => $db,
2140 'table' => $table,
2142 ) . '">'
2143 . htmlspecialchars($db) . '.' . htmlspecialchars($table)
2144 . '</a>'
2146 . '</legend>';
2148 $html_output .= '<table id="tablespecificuserrights" class="data">';
2149 $html_output .= PMA_getHtmlForPrivsTableHead();
2150 $privMap = PMA_getPrivMap($db);
2151 $sql_query = "SELECT `User`, `Host`, `Db`,"
2152 . " 't' AS `Type`, `Table_name`, `Table_priv`"
2153 . " FROM `mysql`.`tables_priv`"
2154 . " WHERE '" . PMA_Util::sqlAddSlashes($db) . "' LIKE `Db`"
2155 . " AND '" . PMA_Util::sqlAddSlashes($table) . "' LIKE `Table_name`"
2156 . " AND NOT (`Table_priv` = '' AND Column_priv = '')"
2157 . " ORDER BY `User` ASC, `Host` ASC, `Db` ASC, `Table_priv` ASC;";
2158 $res = $GLOBALS['dbi']->query($sql_query);
2159 PMA_mergePrivMapFromResult($privMap, $res);
2160 $html_output .= PMA_getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db);
2161 $html_output .= '</table>';
2163 $html_output .= '<div class="floatleft">';
2164 $html_output .= PMA_Util::getWithSelected(
2165 $GLOBALS['pmaThemeImage'], $GLOBALS['text_dir'], "usersForm"
2167 $html_output .= PMA_Util::getButtonOrImage(
2168 'submit_mult', 'mult_submit', 'submit_mult_export',
2169 __('Export'), 'b_tblexport.png', 'export'
2172 $html_output .= '</fieldset>';
2173 $html_output .= '</form>';
2174 } else {
2175 $html_output .= PMA_getHtmlForViewUsersError();
2177 // Offer to create a new user for the current database
2178 $html_output .= PMA_getAddUserHtmlFieldset($db, $table);
2179 return $html_output;
2183 * gets privilege map
2185 * @param string $db the database
2187 * @return array $privMap the privilege map
2189 function PMA_getPrivMap($db)
2191 list($listOfPrivs, $listOfComparedPrivs)
2192 = PMA_getListOfPrivilegesAndComparedPrivileges();
2193 $sql_query
2194 = "("
2195 . " SELECT " . $listOfPrivs . ", '*' AS `Db`, 'g' AS `Type`"
2196 . " FROM `mysql`.`user`"
2197 . " WHERE NOT (" . $listOfComparedPrivs . ")"
2198 . ")"
2199 . " UNION "
2200 . "("
2201 . " SELECT " . $listOfPrivs . ", `Db`, 'd' AS `Type`"
2202 . " FROM `mysql`.`db`"
2203 . " WHERE '" . PMA_Util::sqlAddSlashes($db) . "' LIKE `Db`"
2204 . " AND NOT (" . $listOfComparedPrivs . ")"
2205 . ")"
2206 . " ORDER BY `User` ASC, `Host` ASC, `Db` ASC;";
2207 $res = $GLOBALS['dbi']->query($sql_query);
2208 $privMap = array();
2209 PMA_mergePrivMapFromResult($privMap, $res);
2210 return $privMap;
2214 * merge privilege map and rows from resultset
2216 * @param array &$privMap the privilege map reference
2217 * @param object $result the resultset of query
2219 * @return void
2221 function PMA_mergePrivMapFromResult(&$privMap, $result)
2223 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
2224 $user = $row['User'];
2225 $host = $row['Host'];
2226 if (! isset($privMap[$user])) {
2227 $privMap[$user] = array();
2229 if (! isset($privMap[$user][$host])) {
2230 $privMap[$user][$host] = array();
2232 $privMap[$user][$host][] = $row;
2237 * Get HTML snippet for privileges table head
2239 * @return string $html_output
2241 function PMA_getHtmlForPrivsTableHead()
2243 return '<thead>'
2244 . '<tr>'
2245 . '<th></th>'
2246 . '<th>' . __('User name') . '</th>'
2247 . '<th>' . __('Host name') . '</th>'
2248 . '<th>' . __('Type') . '</th>'
2249 . '<th>' . __('Privileges') . '</th>'
2250 . '<th>' . __('Grant') . '</th>'
2251 . '<th>' . __('Action') . '</th>'
2252 . '</tr>'
2253 . '</thead>';
2257 * Get HTML error for View Users form
2258 * For non superusers such as grant/create users
2260 * @return string $html_output
2262 function PMA_getHtmlForViewUsersError()
2264 return PMA_Message::error(
2265 __('Not enough privilege to view users.')
2266 )->getDisplay();
2270 * Get HTML snippet for table body of specific database or table privileges
2272 * @param array $privMap privilege map
2273 * @param string $db database
2275 * @return string $html_output
2277 function PMA_getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db)
2279 $html_output = '<tbody>';
2280 $index_checkbox = 0;
2281 $odd_row = true;
2282 if (empty($privMap)) {
2283 $html_output .= '<tr class="odd">'
2284 . '<td colspan="6">'
2285 . __('No user found.')
2286 . '</td>'
2287 . '</tr>'
2288 . '</tbody>';
2289 return $html_output;
2292 foreach ($privMap as $current_user => $val) {
2293 foreach ($val as $current_host => $current_privileges) {
2294 $nbPrivileges = count($current_privileges);
2295 $html_output .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">';
2297 $value = htmlspecialchars($current_user . '&amp;#27;' . $current_host);
2298 $html_output .= '<td';
2299 if ($nbPrivileges > 1) {
2300 $html_output .= ' rowspan="' . $nbPrivileges . '"';
2302 $html_output .= '>';
2303 $html_output .= '<input type="checkbox" class="checkall" '
2304 . 'name="selected_usr[]" '
2305 . 'id="checkbox_sel_users_' . ($index_checkbox++) . '" '
2306 . 'value="' . $value . '" /></td>' . "\n";
2308 // user
2309 $html_output .= '<td';
2310 if ($nbPrivileges > 1) {
2311 $html_output .= ' rowspan="' . $nbPrivileges . '"';
2313 $html_output .= '>';
2314 if (empty($current_user)) {
2315 $html_output .= '<span style="color: #FF0000">'
2316 . __('Any') . '</span>';
2317 } else {
2318 $html_output .= htmlspecialchars($current_user);
2320 $html_output .= '</td>';
2322 // host
2323 $html_output .= '<td';
2324 if ($nbPrivileges > 1) {
2325 $html_output .= ' rowspan="' . $nbPrivileges . '"';
2327 $html_output .= '>';
2328 $html_output .= htmlspecialchars($current_host);
2329 $html_output .= '</td>';
2331 $html_output .= PMA_getHtmlListOfPrivs(
2332 $db, $current_privileges, $current_user,
2333 $current_host, $odd_row
2336 $odd_row = ! $odd_row;
2339 $html_output .= '</tbody>';
2341 return $html_output;
2345 * Get HTML to display privileges
2347 * @param string $db Database name
2348 * @param array $current_privileges List of privileges
2349 * @param string $current_user Current user
2350 * @param string $current_host Current host
2351 * @param boolean $odd_row Current row is odd
2353 * @return string HTML to display privileges
2355 function PMA_getHtmlListOfPrivs(
2356 $db, $current_privileges, $current_user,
2357 $current_host, $odd_row
2359 $nbPrivileges = count($current_privileges);
2360 $html_output = null;
2361 for ($i = 0; $i < $nbPrivileges; $i++) {
2362 $current = $current_privileges[$i];
2364 // type
2365 $html_output .= '<td>';
2366 if ($current['Type'] == 'g') {
2367 $html_output .= __('global');
2368 } elseif ($current['Type'] == 'd') {
2369 if ($current['Db'] == PMA_Util::escapeMysqlWildcards($db)) {
2370 $html_output .= __('database-specific');
2371 } else {
2372 $html_output .= __('wildcard') . ': '
2373 . '<code>'
2374 . htmlspecialchars($current['Db'])
2375 . '</code>';
2377 } elseif ($current['Type'] == 't') {
2378 $html_output .= __('table-specific');
2380 $html_output .= '</td>';
2382 // privileges
2383 $html_output .= '<td>';
2384 if (isset($current['Table_name'])) {
2385 $privList = explode(',', $current['Table_priv']);
2386 $privs = array();
2387 $grantsArr = PMA_getTableGrantsArray();
2388 foreach ($grantsArr as $grant) {
2389 $privs[$grant[0]] = 'N';
2390 foreach ($privList as $priv) {
2391 if ($grant[0] == $priv) {
2392 $privs[$grant[0]] = 'Y';
2396 $html_output .= '<code>'
2397 . join(
2398 ',',
2399 PMA_extractPrivInfo($privs, true, true)
2401 . '</code>';
2402 } else {
2403 $html_output .= '<code>'
2404 . join(
2405 ',',
2406 PMA_extractPrivInfo($current, true, false)
2408 . '</code>';
2410 $html_output .= '</td>';
2412 // grant
2413 $html_output .= '<td>';
2414 $containsGrant = false;
2415 if (isset($current['Table_name'])) {
2416 $privList = explode(',', $current['Table_priv']);
2417 foreach ($privList as $priv) {
2418 if ($priv == 'Grant') {
2419 $containsGrant = true;
2422 } else {
2423 $containsGrant = $current['Grant_priv'] == 'Y';
2425 $html_output .= ($containsGrant ? __('Yes') : __('No'));
2426 $html_output .= '</td>';
2428 // action
2429 $html_output .= '<td>';
2430 if ($GLOBALS['is_grantuser']) {
2431 $specific_db = (isset($current['Db']) && $current['Db'] != '*')
2432 ? $current['Db'] : '';
2433 $specific_table = (isset($current['Table_name'])
2434 && $current['Table_name'] != '*')
2435 ? $current['Table_name'] : '';
2436 $html_output .= PMA_getUserLink(
2437 'edit',
2438 $current_user,
2439 $current_host,
2440 $specific_db,
2441 $specific_table
2444 $html_output .= '</td>';
2446 $html_output .= '</tr>';
2447 if (($i + 1) < $nbPrivileges) {
2448 $html_output .= '<tr class="noclick '
2449 . ($odd_row ? 'odd' : 'even') . '">';
2452 return $html_output;
2456 * Returns edit, revoke or export link for a user.
2458 * @param string $linktype The link type (edit | revoke | export)
2459 * @param string $username User name
2460 * @param string $hostname Host name
2461 * @param string $dbname Database name
2462 * @param string $tablename Table name
2463 * @param string $initial Initial value
2465 * @return string HTML code with link
2467 function PMA_getUserLink(
2468 $linktype, $username, $hostname, $dbname = '', $tablename = '', $initial = ''
2470 $html = '<a';
2471 switch($linktype) {
2472 case 'edit':
2473 $html .= ' class="edit_user_anchor"';
2474 break;
2475 case 'export':
2476 $html .= ' class="export_user_anchor ajax"';
2477 break;
2479 $params = array(
2480 'username' => $username,
2481 'hostname' => $hostname
2483 switch($linktype) {
2484 case 'edit':
2485 $params['dbname'] = $dbname;
2486 $params['tablename'] = $tablename;
2487 break;
2488 case 'revoke':
2489 $params['dbname'] = $dbname;
2490 $params['tablename'] = $tablename;
2491 $params['revokeall'] = 1;
2492 break;
2493 case 'export':
2494 $params['initial'] = $initial;
2495 $params['export'] = 1;
2496 break;
2499 $html .= ' href="server_privileges.php'
2500 . PMA_URL_getCommon($params)
2501 . '">';
2503 switch($linktype) {
2504 case 'edit':
2505 $html .= PMA_Util::getIcon('b_usredit.png', __('Edit Privileges'));
2506 break;
2507 case 'revoke':
2508 $html .= PMA_Util::getIcon('b_usrdrop.png', __('Revoke'));
2509 break;
2510 case 'export':
2511 $html .= PMA_Util::getIcon('b_tblexport.png', __('Export'));
2512 break;
2514 $html .= '</a>';
2516 return $html;
2520 * Returns user group edit link
2522 * @param string $username User name
2524 * @return HTML code with link
2526 function PMA_getUserGroupEditLink($username)
2528 return '<a class="edit_user_group_anchor ajax"'
2529 . ' href="server_privileges.php'
2530 . PMA_URL_getCommon(array('username' => $username))
2531 . '">'
2532 . PMA_Util::getIcon('b_usrlist.png', __('Edit user group'))
2533 . '</a>';
2537 * Returns number of defined user groups
2539 * @return integer $user_group_count
2541 function PMA_getUserGroupCount()
2543 $cfgRelation = PMA_getRelationsParam();
2544 $user_group_table = PMA_Util::backquote($cfgRelation['db'])
2545 . '.' . PMA_Util::backquote($cfgRelation['usergroups']);
2546 $sql_query = 'SELECT COUNT(*) FROM ' . $user_group_table;
2547 $user_group_count = $GLOBALS['dbi']->fetchValue(
2548 $sql_query, 0, 0, $GLOBALS['controllink']
2551 return $user_group_count;
2555 * This function return the extra data array for the ajax behavior
2557 * @param string $password password
2558 * @param string $sql_query sql query
2559 * @param string $hostname hostname
2560 * @param string $username username
2562 * @return array $extra_data
2564 function PMA_getExtraDataForAjaxBehavior(
2565 $password, $sql_query, $hostname, $username
2567 if (isset($GLOBALS['dbname'])) {
2568 //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
2569 if (preg_match('/(?<!\\\\)(?:_|%)/i', $GLOBALS['dbname'])) {
2570 $dbname_is_wildcard = true;
2571 } else {
2572 $dbname_is_wildcard = false;
2576 $user_group_count = 0;
2577 if ($GLOBALS['cfgRelation']['menuswork']) {
2578 $user_group_count = PMA_getUserGroupCount();
2581 $extra_data = array();
2582 if (/*overload*/mb_strlen($sql_query)) {
2583 $extra_data['sql_query'] = PMA_Util::getMessage(null, $sql_query);
2586 if (isset($_REQUEST['change_copy'])) {
2588 * generate html on the fly for the new user that was just created.
2590 $new_user_string = '<tr>' . "\n"
2591 . '<td> <input type="checkbox" name="selected_usr[]" '
2592 . 'id="checkbox_sel_users_"'
2593 . 'value="'
2594 . htmlspecialchars($username)
2595 . '&amp;#27;' . htmlspecialchars($hostname) . '" />'
2596 . '</td>' . "\n"
2597 . '<td><label for="checkbox_sel_users_">'
2598 . (empty($_REQUEST['username'])
2599 ? '<span style="color: #FF0000">' . __('Any') . '</span>'
2600 : htmlspecialchars($username) ) . '</label></td>' . "\n"
2601 . '<td>' . htmlspecialchars($hostname) . '</td>' . "\n";
2603 $new_user_string .= '<td>';
2605 if (! empty($password) || isset($_POST['pma_pw'])) {
2606 $new_user_string .= __('Yes');
2607 } else {
2608 $new_user_string .= '<span style="color: #FF0000">'
2609 . __('No')
2610 . '</span>';
2613 $new_user_string .= '</td>' . "\n";
2614 $new_user_string .= '<td>'
2615 . '<code>' . join(', ', PMA_extractPrivInfo(null, true)) . '</code>'
2616 . '</td>'; //Fill in privileges here
2618 // if $cfg['Servers'][$i]['users'] and $cfg['Servers'][$i]['usergroups'] are
2619 // enabled
2620 $cfgRelation = PMA_getRelationsParam();
2621 if (isset($cfgRelation['users']) && isset($cfgRelation['usergroups'])) {
2622 $new_user_string .= '<td class="usrGroup"></td>';
2625 $new_user_string .= '<td>';
2626 if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')) {
2627 $new_user_string .= __('Yes');
2628 } else {
2629 $new_user_string .= __('No');
2631 $new_user_string .='</td>';
2633 if ($GLOBALS['is_grantuser']) {
2634 $new_user_string .= '<td>'
2635 . PMA_getUserLink('edit', $username, $hostname)
2636 . '</td>' . "\n";
2639 if ($cfgRelation['menuswork'] && $user_group_count > 0) {
2640 $new_user_string .= '<td>'
2641 . PMA_getUserGroupEditLink($username)
2642 . '</td>' . "\n";
2645 $new_user_string .= '<td>'
2646 . PMA_getUserLink(
2647 'export',
2648 $username,
2649 $hostname,
2652 isset($_GET['initial']) ? $_GET['initial'] : ''
2654 . '</td>' . "\n";
2656 $new_user_string .= '</tr>';
2658 $extra_data['new_user_string'] = $new_user_string;
2661 * Generate the string for this alphabet's initial, to update the user
2662 * pagination
2664 $new_user_initial = /*overload*/mb_strtoupper(
2665 /*overload*/mb_substr($username, 0, 1)
2667 $newUserInitialString = '<a href="server_privileges.php'
2668 . PMA_URL_getCommon(array('initial' => $new_user_initial)) . '">'
2669 . $new_user_initial . '</a>';
2670 $extra_data['new_user_initial'] = $new_user_initial;
2671 $extra_data['new_user_initial_string'] = $newUserInitialString;
2674 if (isset($_POST['update_privs'])) {
2675 $extra_data['db_specific_privs'] = false;
2676 $extra_data['db_wildcard_privs'] = false;
2677 if (isset($dbname_is_wildcard)) {
2678 $extra_data['db_specific_privs'] = ! $dbname_is_wildcard;
2679 $extra_data['db_wildcard_privs'] = $dbname_is_wildcard;
2681 $new_privileges = join(', ', PMA_extractPrivInfo(null, true));
2683 $extra_data['new_privileges'] = $new_privileges;
2686 if (isset($_REQUEST['validate_username'])) {
2687 $sql_query = "SELECT * FROM `mysql`.`user` WHERE `User` = '"
2688 . $_REQUEST['username'] . "';";
2689 $res = $GLOBALS['dbi']->query($sql_query);
2690 $row = $GLOBALS['dbi']->fetchRow($res);
2691 if (empty($row)) {
2692 $extra_data['user_exists'] = false;
2693 } else {
2694 $extra_data['user_exists'] = true;
2698 return $extra_data;
2702 * Get the HTML snippet for change user login information
2704 * @param string $username username
2705 * @param string $hostname host name
2707 * @return string HTML snippet
2709 function PMA_getChangeLoginInformationHtmlForm($username, $hostname)
2711 $choices = array(
2712 '4' => __('… keep the old one.'),
2713 '1' => __('… delete the old one from the user tables.'),
2714 '2' => __(
2715 '… revoke all active privileges from '
2716 . 'the old one and delete it afterwards.'
2718 '3' => __(
2719 '… delete the old one from the user tables '
2720 . 'and reload the privileges afterwards.'
2724 $html_output = '<form action="server_privileges.php" '
2725 . 'onsubmit="return checkAddUser(this);" '
2726 . 'method="post" class="copyUserForm submenu-item">' . "\n"
2727 . PMA_URL_getHiddenInputs('', '')
2728 . '<input type="hidden" name="old_username" '
2729 . 'value="' . htmlspecialchars($username) . '" />' . "\n"
2730 . '<input type="hidden" name="old_hostname" '
2731 . 'value="' . htmlspecialchars($hostname) . '" />' . "\n"
2732 . '<fieldset id="fieldset_change_copy_user">' . "\n"
2733 . '<legend data-submenu-label="' . __('Login Information') . '">' . "\n"
2734 . __('Change login information / Copy user account')
2735 . '</legend>' . "\n"
2736 . PMA_getHtmlForLoginInformationFields('change');
2738 $html_output .= '<fieldset id="fieldset_mode">' . "\n"
2739 . ' <legend>'
2740 . __('Create a new user account with the same privileges and …')
2741 . '</legend>' . "\n";
2742 $html_output .= PMA_Util::getRadioFields(
2743 'mode', $choices, '4', true
2745 $html_output .= '</fieldset>' . "\n"
2746 . '</fieldset>' . "\n";
2748 $html_output .= '<fieldset id="fieldset_change_copy_user_footer" '
2749 . 'class="tblFooters">' . "\n"
2750 . '<input type="hidden" name="change_copy" value="1" />' . "\n"
2751 . '<input type="submit" value="' . __('Go') . '" />' . "\n"
2752 . '</fieldset>' . "\n"
2753 . '</form>' . "\n";
2755 return $html_output;
2759 * Provide a line with links to the relevant database and table
2761 * @param string $url_dbname url database name that urlencode() string
2762 * @param string $dbname database name
2763 * @param string $tablename table name
2765 * @return string HTML snippet
2767 function PMA_getLinkToDbAndTable($url_dbname, $dbname, $tablename)
2769 $html_output = '[ ' . __('Database')
2770 . ' <a href="' . PMA_Util::getScriptNameForOption(
2771 $GLOBALS['cfg']['DefaultTabDatabase'], 'database'
2773 . PMA_URL_getCommon(
2774 array(
2775 'db' => $url_dbname,
2776 'reload' => 1
2779 . '">'
2780 . htmlspecialchars($dbname) . ': '
2781 . PMA_Util::getTitleForTarget(
2782 $GLOBALS['cfg']['DefaultTabDatabase']
2784 . "</a> ]\n";
2786 if (/*overload*/mb_strlen($tablename)) {
2787 $html_output .= ' [ ' . __('Table') . ' <a href="'
2788 . PMA_Util::getScriptNameForOption(
2789 $GLOBALS['cfg']['DefaultTabTable'], 'table'
2791 . PMA_URL_getCommon(
2792 array(
2793 'db' => $url_dbname,
2794 'table' => $tablename,
2795 'reload' => 1,
2798 . '">' . htmlspecialchars($tablename) . ': '
2799 . PMA_Util::getTitleForTarget(
2800 $GLOBALS['cfg']['DefaultTabTable']
2802 . "</a> ]\n";
2804 return $html_output;
2808 * no db name given, so we want all privs for the given user
2809 * db name was given, so we want all user specific rights for this db
2810 * So this function returns user rights as an array
2812 * @param array $tables tables
2813 * @param string $user_host_condition a where clause that contained user's host
2814 * condition
2815 * @param string $dbname database name
2817 * @return array $db_rights database rights
2819 function PMA_getUserSpecificRights($tables, $user_host_condition, $dbname)
2821 if (!/*overload*/mb_strlen($dbname)) {
2822 $tables_to_search_for_users = array(
2823 'tables_priv', 'columns_priv',
2825 $dbOrTableName = 'Db';
2826 } else {
2827 $user_host_condition .=
2828 ' AND `Db`'
2829 . ' LIKE \''
2830 . PMA_Util::sqlAddSlashes($dbname, true) . "'";
2831 $tables_to_search_for_users = array('columns_priv',);
2832 $dbOrTableName = 'Table_name';
2835 $db_rights_sqls = array();
2836 foreach ($tables_to_search_for_users as $table_search_in) {
2837 if (in_array($table_search_in, $tables)) {
2838 $db_rights_sqls[] = '
2839 SELECT DISTINCT `' . $dbOrTableName . '`
2840 FROM `mysql`.' . PMA_Util::backquote($table_search_in)
2841 . $user_host_condition;
2845 $user_defaults = array(
2846 $dbOrTableName => '',
2847 'Grant_priv' => 'N',
2848 'privs' => array('USAGE'),
2849 'Column_priv' => true,
2852 // for the rights
2853 $db_rights = array();
2855 $db_rights_sql = '(' . implode(') UNION (', $db_rights_sqls) . ')'
2856 . ' ORDER BY `' . $dbOrTableName . '` ASC';
2858 $db_rights_result = $GLOBALS['dbi']->query($db_rights_sql);
2860 while ($db_rights_row = $GLOBALS['dbi']->fetchAssoc($db_rights_result)) {
2861 $db_rights_row = array_merge($user_defaults, $db_rights_row);
2862 if (!/*overload*/mb_strlen($dbname)) {
2863 // only Db names in the table `mysql`.`db` uses wildcards
2864 // as we are in the db specific rights display we want
2865 // all db names escaped, also from other sources
2866 $db_rights_row['Db'] = PMA_Util::escapeMysqlWildcards(
2867 $db_rights_row['Db']
2870 $db_rights[$db_rights_row[$dbOrTableName]] = $db_rights_row;
2873 $GLOBALS['dbi']->freeResult($db_rights_result);
2875 if (!/*overload*/mb_strlen($dbname)) {
2876 $sql_query = 'SELECT * FROM `mysql`.`db`'
2877 . $user_host_condition . ' ORDER BY `Db` ASC';
2878 } else {
2879 $sql_query = 'SELECT `Table_name`,'
2880 . ' `Table_priv`,'
2881 . ' IF(`Column_priv` = _latin1 \'\', 0, 1)'
2882 . ' AS \'Column_priv\''
2883 . ' FROM `mysql`.`tables_priv`'
2884 . $user_host_condition
2885 . ' ORDER BY `Table_name` ASC;';
2888 $result = $GLOBALS['dbi']->query($sql_query);
2890 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
2891 if (isset($db_rights[$row[$dbOrTableName]])) {
2892 $db_rights[$row[$dbOrTableName]]
2893 = array_merge($db_rights[$row[$dbOrTableName]], $row);
2894 } else {
2895 $db_rights[$row[$dbOrTableName]] = $row;
2897 if (!/*overload*/mb_strlen($dbname)) {
2898 // there are db specific rights for this user
2899 // so we can drop this db rights
2900 $db_rights[$row['Db']]['can_delete'] = true;
2903 $GLOBALS['dbi']->freeResult($result);
2904 return $db_rights;
2908 * Display user rights in table rows(Table specific or database specific privs)
2910 * @param array $db_rights user's database rights array
2911 * @param string $dbname database name
2912 * @param string $hostname host name
2913 * @param string $username username
2915 * @return array $found_rows, $html_output
2917 function PMA_getHtmlForUserRights($db_rights, $dbname,
2918 $hostname, $username
2920 $html_output = '';
2921 $found_rows = array();
2923 // display rows
2924 if (count($db_rights) < 1) {
2925 $html_output .= '<tr class="odd">' . "\n"
2926 . '<td colspan="6"><center><i>' . __('None') . '</i></center></td>' . "\n"
2927 . '</tr>' . "\n";
2928 return array($found_rows, $html_output);
2931 $odd_row = true;
2932 //while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
2933 foreach ($db_rights as $row) {
2934 $dbNameLength = /*overload*/mb_strlen($dbname);
2935 $found_rows[] = (!$dbNameLength)
2936 ? $row['Db']
2937 : $row['Table_name'];
2939 $html_output .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">' . "\n"
2940 . '<td>'
2941 . htmlspecialchars(
2942 (!$dbNameLength)
2943 ? $row['Db']
2944 : $row['Table_name']
2946 . '</td>' . "\n"
2947 . '<td><code>' . "\n"
2948 . ' '
2949 . join(
2950 ',' . "\n" . ' ',
2951 PMA_extractPrivInfo($row, true)
2952 ) . "\n"
2953 . '</code></td>' . "\n"
2954 . '<td>'
2955 . ((((!$dbNameLength) && $row['Grant_priv'] == 'Y')
2956 || ($dbNameLength
2957 && in_array('Grant', explode(',', $row['Table_priv']))))
2958 ? __('Yes')
2959 : __('No'))
2960 . '</td>' . "\n"
2961 . '<td>';
2962 if (! empty($row['Table_privs']) || ! empty ($row['Column_priv'])) {
2963 $html_output .= __('Yes');
2964 } else {
2965 $html_output .= __('No');
2967 $html_output .= '</td>';
2969 $html_output .= '<td>';
2970 if ($GLOBALS['is_grantuser']) {
2971 $html_output .= PMA_getUserLink(
2972 'edit',
2973 $username,
2974 $hostname,
2975 (!$dbNameLength) ? $row['Db'] : $dbname,
2976 (!$dbNameLength) ? '' : $row['Table_name']
2979 $html_output .= '</td>';
2981 $html_output .= '<td>';
2982 if (! empty($row['can_delete'])
2983 || isset($row['Table_name'])
2984 && /*overload*/mb_strlen($row['Table_name'])
2986 $html_output .= PMA_getUserLink(
2987 'revoke',
2988 $username,
2989 $hostname,
2990 (!$dbNameLength) ? $row['Db'] : $dbname,
2991 (!$dbNameLength) ? '' : $row['Table_name']
2994 $html_output .= '</td>' . "\n"
2995 . '</tr>' . "\n";
2996 $odd_row = ! $odd_row;
2997 } // end while
2999 return array($found_rows, $html_output);
3003 * Get a HTML table for display user's tabel specific or database specific rights
3005 * @param string $username username
3006 * @param string $hostname host name
3007 * @param string $dbname database name
3009 * @return array $html_output, $found_rows
3011 function PMA_getHtmlForAllTableSpecificRights(
3012 $username, $hostname, $dbname
3014 // table header
3015 $html_output = PMA_URL_getHiddenInputs('', '')
3016 . '<input type="hidden" name="username" '
3017 . 'value="' . htmlspecialchars($username) . '" />' . "\n"
3018 . '<input type="hidden" name="hostname" '
3019 . 'value="' . htmlspecialchars($hostname) . '" />' . "\n"
3020 . '<fieldset>' . "\n"
3021 . '<legend data-submenu-label="'
3022 . (!/*overload*/mb_strlen($dbname)
3023 ? __('Database')
3024 : __('Table')
3026 . '">'
3027 . (!/*overload*/mb_strlen($dbname)
3028 ? __('Database-specific privileges')
3029 : __('Table-specific privileges')
3031 . '</legend>' . "\n"
3032 . '<table class="data">' . "\n"
3033 . '<thead>' . "\n"
3034 . '<tr><th>'
3035 . (!/*overload*/mb_strlen($dbname) ? __('Database') : __('Table'))
3036 . '</th>' . "\n"
3037 . '<th>' . __('Privileges') . '</th>' . "\n"
3038 . '<th>' . __('Grant') . '</th>' . "\n"
3039 . '<th>'
3040 . (!/*overload*/mb_strlen($dbname)
3041 ? __('Table-specific privileges')
3042 : __('Column-specific privileges')
3044 . '</th>' . "\n"
3045 . '<th colspan="2">' . __('Action') . '</th>' . "\n"
3046 . '</tr>' . "\n"
3047 . '</thead>' . "\n";
3049 $user_host_condition = ' WHERE `User`'
3050 . ' = \'' . PMA_Util::sqlAddSlashes($username) . "'"
3051 . ' AND `Host`'
3052 . ' = \'' . PMA_Util::sqlAddSlashes($hostname) . "'";
3054 // table body
3055 // get data
3057 // we also want privileges for this user not in table `db` but in other table
3058 $tables = $GLOBALS['dbi']->fetchResult('SHOW TABLES FROM `mysql`;');
3061 * no db name given, so we want all privs for the given user
3062 * db name was given, so we want all user specific rights for this db
3064 $db_rights = PMA_getUserSpecificRights($tables, $user_host_condition, $dbname);
3066 ksort($db_rights);
3068 $html_output .= '<tbody>' . "\n";
3069 // display rows
3070 list ($found_rows, $html_out) = PMA_getHtmlForUserRights(
3071 $db_rights, $dbname, $hostname, $username
3074 $html_output .= $html_out;
3075 $html_output .= '</tbody>' . "\n";
3076 $html_output .='</table>' . "\n";
3078 return array($html_output, $found_rows);
3082 * Get HTML for display select db
3084 * @param array $found_rows isset($dbname)) ? $row['Db'] : $row['Table_name']
3086 * @return string HTML snippet
3088 function PMA_getHtmlForSelectDbInEditPrivs($found_rows)
3090 // we already have the list of databases from libraries/common.inc.php
3091 // via $pma = new PMA;
3092 $pred_db_array = $GLOBALS['pma']->databases;
3094 $databases_to_skip = array('information_schema', 'performance_schema');
3096 $html_output = '<label for="text_dbname">'
3097 . __('Add privileges on the following database(s):') . '</label>' . "\n";
3098 if (! empty($pred_db_array)) {
3099 $html_output .= '<select name="pred_dbname[]" multiple="multiple">' . "\n";
3100 foreach ($pred_db_array as $current_db) {
3101 if (in_array($current_db, $databases_to_skip)) {
3102 continue;
3104 $current_db_show = $current_db;
3105 $current_db = PMA_Util::escapeMysqlWildcards($current_db);
3106 // cannot use array_diff() once, outside of the loop,
3107 // because the list of databases has special characters
3108 // already escaped in $found_rows,
3109 // contrary to the output of SHOW DATABASES
3110 if (empty($found_rows) || ! in_array($current_db, $found_rows)) {
3111 $html_output .= '<option value="'
3112 . htmlspecialchars($current_db) . '">'
3113 . htmlspecialchars($current_db_show) . '</option>' . "\n";
3116 $html_output .= '</select>' . "\n";
3118 $html_output .= '<input type="text" id="text_dbname" name="dbname" />'
3119 . "\n"
3120 . PMA_Util::showHint(
3121 __('Wildcards % and _ should be escaped with a \ to use them literally.')
3123 return $html_output;
3127 * Get HTML for display table in edit privilege
3129 * @param string $dbname database naame
3130 * @param array $found_rows isset($dbname)) ? $row['Db'] : $row['Table_name']
3132 * @return string HTML snippet
3134 function PMA_displayTablesInEditPrivs($dbname, $found_rows)
3136 $html_output = '<input type="hidden" name="dbname"
3137 ' . 'value="' . htmlspecialchars($dbname) . '"/>' . "\n";
3138 $html_output .= '<label for="text_tablename">'
3139 . __('Add privileges on the following table:') . '</label>' . "\n";
3141 $result = @$GLOBALS['dbi']->tryQuery(
3142 'SHOW TABLES FROM ' . PMA_Util::backquote(
3143 PMA_Util::unescapeMysqlWildcards($dbname)
3144 ) . ';',
3145 null,
3146 PMA_DatabaseInterface::QUERY_STORE
3149 if ($result) {
3150 $pred_tbl_array = array();
3151 while ($row = $GLOBALS['dbi']->fetchRow($result)) {
3152 if (! isset($found_rows) || ! in_array($row[0], $found_rows)) {
3153 $pred_tbl_array[] = $row[0];
3156 $GLOBALS['dbi']->freeResult($result);
3158 if (! empty($pred_tbl_array)) {
3159 $html_output .= '<select name="pred_tablename" '
3160 . 'class="autosubmit">' . "\n"
3161 . '<option value="" selected="selected">' . __('Use text field')
3162 . ':</option>' . "\n";
3163 foreach ($pred_tbl_array as $current_table) {
3164 $html_output .= '<option '
3165 . 'value="' . htmlspecialchars($current_table) . '">'
3166 . htmlspecialchars($current_table)
3167 . '</option>' . "\n";
3169 $html_output .= '</select>' . "\n";
3172 $html_output .= '<input type="text" id="text_tablename" name="tablename" />'
3173 . "\n";
3175 return $html_output;
3179 * Get HTML for display the users overview
3180 * (if less than 50 users, display them immediately)
3182 * @param array $result ran sql query
3183 * @param array $db_rights user's database rights array
3184 * @param string $pmaThemeImage a image source link
3185 * @param string $text_dir text directory
3187 * @return string HTML snippet
3189 function PMA_getUsersOverview($result, $db_rights, $pmaThemeImage, $text_dir)
3191 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
3192 $row['privs'] = PMA_extractPrivInfo($row, true);
3193 $db_rights[$row['User']][$row['Host']] = $row;
3195 @$GLOBALS['dbi']->freeResult($result);
3196 $user_group_count = 0;
3197 if ($GLOBALS['cfgRelation']['menuswork']) {
3198 $user_group_count = PMA_getUserGroupCount();
3201 $html_output
3202 = '<form name="usersForm" id="usersForm" action="server_privileges.php" '
3203 . 'method="post">' . "\n"
3204 . PMA_URL_getHiddenInputs('', '')
3205 . '<table id="tableuserrights" class="data">' . "\n"
3206 . '<thead>' . "\n"
3207 . '<tr><th></th>' . "\n"
3208 . '<th>' . __('User name') . '</th>' . "\n"
3209 . '<th>' . __('Host name') . '</th>' . "\n"
3210 . '<th>' . __('Password') . '</th>' . "\n"
3211 . '<th>' . __('Global privileges') . ' '
3212 . PMA_Util::showHint(
3213 __('Note: MySQL privilege names are expressed in English.')
3215 . '</th>' . "\n";
3216 if ($GLOBALS['cfgRelation']['menuswork']) {
3217 $html_output .= '<th>' . __('User group') . '</th>' . "\n";
3219 $html_output .= '<th>' . __('Grant') . '</th>' . "\n"
3220 . '<th colspan="' . ($user_group_count > 0 ? '3' : '2') . '">'
3221 . __('Action') . '</th>' . "\n"
3222 . '</tr>' . "\n"
3223 . '</thead>' . "\n";
3225 $html_output .= '<tbody>' . "\n";
3226 $html_output .= PMA_getHtmlTableBodyForUserRights($db_rights);
3227 $html_output .= '</tbody>'
3228 . '</table>' . "\n";
3230 $html_output .= '<div class="floatleft">'
3231 . PMA_Util::getWithSelected($pmaThemeImage, $text_dir, "usersForm") . "\n";
3233 $html_output .= PMA_Util::getButtonOrImage(
3234 'submit_mult', 'mult_submit', 'submit_mult_export',
3235 __('Export'), 'b_tblexport.png', 'export'
3237 $html_output .= '<input type="hidden" name="initial" '
3238 . 'value="' . (isset($_GET['initial']) ? $_GET['initial'] : '') . '" />';
3239 $html_output .= '</div>'
3240 . '<div class="clear_both" style="clear:both"></div>';
3242 // add/delete user fieldset
3243 $html_output .= PMA_getFieldsetForAddDeleteUser();
3244 $html_output .= '</form>' . "\n";
3246 return $html_output;
3250 * Get table body for 'tableuserrights' table in userform
3252 * @param array $db_rights user's database rights array
3254 * @return string HTML snippet
3256 function PMA_getHtmlTableBodyForUserRights($db_rights)
3258 $cfgRelation = PMA_getRelationsParam();
3259 if ($cfgRelation['menuswork']) {
3260 $users_table = PMA_Util::backquote($cfgRelation['db'])
3261 . "." . PMA_Util::backquote($cfgRelation['users']);
3262 $sql_query = 'SELECT * FROM ' . $users_table;
3263 $result = PMA_queryAsControlUser($sql_query, false);
3264 $group_assignment = array();
3265 if ($result) {
3266 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
3267 $group_assignment[$row['username']] = $row['usergroup'];
3270 $GLOBALS['dbi']->freeResult($result);
3272 $user_group_count = PMA_getUserGroupCount();
3275 $odd_row = true;
3276 $index_checkbox = 0;
3277 $html_output = '';
3278 foreach ($db_rights as $user) {
3279 ksort($user);
3280 foreach ($user as $host) {
3281 $index_checkbox++;
3282 $html_output .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">'
3283 . "\n";
3284 $html_output .= '<td>'
3285 . '<input type="checkbox" class="checkall" name="selected_usr[]" '
3286 . 'id="checkbox_sel_users_'
3287 . $index_checkbox . '" value="'
3288 . htmlspecialchars($host['User'] . '&amp;#27;' . $host['Host'])
3289 . '"'
3290 . ' /></td>' . "\n";
3292 $html_output .= '<td><label '
3293 . 'for="checkbox_sel_users_' . $index_checkbox . '">'
3294 . (empty($host['User'])
3295 ? '<span style="color: #FF0000">' . __('Any') . '</span>'
3296 : htmlspecialchars($host['User'])) . '</label></td>' . "\n"
3297 . '<td>' . htmlspecialchars($host['Host']) . '</td>' . "\n";
3299 $html_output .= '<td>';
3300 switch ($host['Password']) {
3301 case 'Y':
3302 $html_output .= __('Yes');
3303 break;
3304 case 'N':
3305 $html_output .= '<span style="color: #FF0000">' . __('No')
3306 . '</span>';
3307 break;
3308 // this happens if this is a definition not coming from mysql.user
3309 default:
3310 $html_output .= '--'; // in future version, replace by "not present"
3311 break;
3312 } // end switch
3313 $html_output .= '</td>' . "\n";
3315 $html_output .= '<td><code>' . "\n"
3316 . '' . implode(',' . "\n" . ' ', $host['privs']) . "\n"
3317 . '</code></td>' . "\n";
3318 if ($cfgRelation['menuswork']) {
3319 $html_output .= '<td class="usrGroup">' . "\n"
3320 . (isset($group_assignment[$host['User']])
3321 ? $group_assignment[$host['User']]
3322 : ''
3324 . '</td>' . "\n";
3326 $html_output .= '<td>'
3327 . ($host['Grant_priv'] == 'Y' ? __('Yes') : __('No'))
3328 . '</td>' . "\n";
3330 if ($GLOBALS['is_grantuser']) {
3331 $html_output .= '<td class="center">'
3332 . PMA_getUserLink(
3333 'edit',
3334 $host['User'],
3335 $host['Host']
3337 . '</td>';
3339 if ($cfgRelation['menuswork'] && $user_group_count > 0) {
3340 if (empty($host['User'])) {
3341 $html_output .= '<td class="center"></td>';
3342 } else {
3343 $html_output .= '<td class="center">'
3344 . PMA_getUserGroupEditLink($host['User'])
3345 . '</td>';
3348 $html_output .= '<td class="center">'
3349 . PMA_getUserLink(
3350 'export',
3351 $host['User'],
3352 $host['Host'],
3355 isset($_GET['initial']) ? $_GET['initial'] : ''
3357 . '</td>';
3358 $html_output .= '</tr>';
3359 $odd_row = ! $odd_row;
3362 return $html_output;
3366 * Get HTML fieldset for Add/Delete user
3368 * @return string HTML snippet
3370 function PMA_getFieldsetForAddDeleteUser()
3372 $html_output = PMA_getAddUserHtmlFieldset();
3373 $html_output .= '<fieldset id="fieldset_delete_user">'
3374 . '<legend>' . "\n"
3375 . PMA_Util::getIcon('b_usrdrop.png')
3376 . ' ' . __('Remove selected user accounts') . '' . "\n"
3377 . '</legend>' . "\n";
3379 $html_output .= '<input type="hidden" name="mode" value="2" />' . "\n"
3380 . '('
3381 . __(
3382 'Revoke all active privileges from the users '
3383 . 'and delete them afterwards.'
3385 . ')'
3386 . '<br />' . "\n";
3388 $html_output .= '<input type="checkbox" '
3389 . 'title="'
3390 . __('Drop the databases that have the same names as the users.')
3391 . '" '
3392 . 'name="drop_users_db" id="checkbox_drop_users_db" />' . "\n";
3394 $html_output .= '<label for="checkbox_drop_users_db" '
3395 . 'title="'
3396 . __('Drop the databases that have the same names as the users.')
3397 . '">' . "\n"
3398 . ' '
3399 . __('Drop the databases that have the same names as the users.')
3400 . "\n"
3401 . '</label>' . "\n"
3402 . '</fieldset>' . "\n";
3404 $html_output .= '<fieldset id="fieldset_delete_user_footer" class="tblFooters">'
3405 . "\n";
3406 $html_output .= '<input type="submit" name="delete" '
3407 . 'value="' . __('Go') . '" id="buttonGo" '
3408 . 'class="ajax"/>' . "\n";
3410 $html_output .= '</fieldset>' . "\n";
3412 return $html_output;
3416 * Get HTML for Displays the initials
3418 * @param array $array_initials array for all initials, even non A-Z
3420 * @return string HTML snippet
3422 function PMA_getHtmlForInitials($array_initials)
3424 // initialize to false the letters A-Z
3425 for ($letter_counter = 1; $letter_counter < 27; $letter_counter++) {
3426 if (! isset($array_initials[/*overload*/mb_chr($letter_counter + 64)])) {
3427 $array_initials[/*overload*/mb_chr($letter_counter + 64)] = false;
3431 $initials = $GLOBALS['dbi']->tryQuery(
3432 'SELECT DISTINCT UPPER(LEFT(`User`,1)) FROM `user` ORDER BY `User` ASC',
3433 null,
3434 PMA_DatabaseInterface::QUERY_STORE
3436 while (list($tmp_initial) = $GLOBALS['dbi']->fetchRow($initials)) {
3437 $array_initials[$tmp_initial] = true;
3440 // Display the initials, which can be any characters, not
3441 // just letters. For letters A-Z, we add the non-used letters
3442 // as greyed out.
3444 uksort($array_initials, "strnatcasecmp");
3446 $html_output = '<table id="initials_table" cellspacing="5">'
3447 . '<tr>';
3448 foreach ($array_initials as $tmp_initial => $initial_was_found) {
3449 if ($tmp_initial === null) {
3450 continue;
3453 if (!$initial_was_found) {
3454 $html_output .= '<td>' . $tmp_initial . '</td>';
3455 continue;
3458 $html_output .= '<td>'
3459 . '<a class="ajax'
3460 . ((isset($_REQUEST['initial'])
3461 && $_REQUEST['initial'] === $tmp_initial
3462 ) ? ' active' : '')
3463 . '" href="server_privileges.php'
3464 . PMA_URL_getCommon(array('initial' => $tmp_initial))
3465 . '">' . $tmp_initial
3466 . '</a>'
3467 . '</td>' . "\n";
3469 $html_output .= '<td>'
3470 . '<a href="server_privileges.php'
3471 . PMA_URL_getCommon(array('showall' => 1))
3472 . '" class="nowrap">' . __('Show all') . '</a></td>' . "\n";
3473 $html_output .= '</tr></table>';
3475 return $html_output;
3479 * Get the database rights array for Display user overview
3481 * @return array $db_rights database rights array
3483 function PMA_getDbRightsForUserOverview()
3485 // we also want users not in table `user` but in other table
3486 $tables = $GLOBALS['dbi']->fetchResult('SHOW TABLES FROM `mysql`;');
3488 $tablesSearchForUsers = array(
3489 'user', 'db', 'tables_priv', 'columns_priv', 'procs_priv',
3492 $db_rights_sqls = array();
3493 foreach ($tablesSearchForUsers as $table_search_in) {
3494 if (in_array($table_search_in, $tables)) {
3495 $db_rights_sqls[] = 'SELECT DISTINCT `User`, `Host` FROM `mysql`.`'
3496 . $table_search_in . '` '
3497 . (isset($_GET['initial'])
3498 ? PMA_rangeOfUsers($_GET['initial'])
3499 : '');
3502 $user_defaults = array(
3503 'User' => '',
3504 'Host' => '%',
3505 'Password' => '?',
3506 'Grant_priv' => 'N',
3507 'privs' => array('USAGE'),
3510 // for the rights
3511 $db_rights = array();
3513 $db_rights_sql = '(' . implode(') UNION (', $db_rights_sqls) . ')'
3514 . ' ORDER BY `User` ASC, `Host` ASC';
3516 $db_rights_result = $GLOBALS['dbi']->query($db_rights_sql);
3518 while ($db_rights_row = $GLOBALS['dbi']->fetchAssoc($db_rights_result)) {
3519 $db_rights_row = array_merge($user_defaults, $db_rights_row);
3520 $db_rights[$db_rights_row['User']][$db_rights_row['Host']]
3521 = $db_rights_row;
3523 $GLOBALS['dbi']->freeResult($db_rights_result);
3524 ksort($db_rights);
3526 return $db_rights;
3530 * Delete user and get message and sql query for delete user in privileges
3532 * @param array $queries queries
3534 * @return array PMA_message
3536 function PMA_deleteUser($queries)
3538 $sql_query = '';
3539 if (empty($queries)) {
3540 $message = PMA_Message::error(__('No users selected for deleting!'));
3541 } else {
3542 if ($_REQUEST['mode'] == 3) {
3543 $queries[] = '# ' . __('Reloading the privileges') . ' …';
3544 $queries[] = 'FLUSH PRIVILEGES;';
3546 $drop_user_error = '';
3547 foreach ($queries as $sql_query) {
3548 if ($sql_query{0} != '#') {
3549 if (! $GLOBALS['dbi']->tryQuery($sql_query, $GLOBALS['userlink'])) {
3550 $drop_user_error .= $GLOBALS['dbi']->getError() . "\n";
3554 // tracking sets this, causing the deleted db to be shown in navi
3555 unset($GLOBALS['db']);
3557 $sql_query = join("\n", $queries);
3558 if (! empty($drop_user_error)) {
3559 $message = PMA_Message::rawError($drop_user_error);
3560 } else {
3561 $message = PMA_Message::success(
3562 __('The selected users have been deleted successfully.')
3566 return array($sql_query, $message);
3570 * Update the privileges and return the success or error message
3572 * @param string $username username
3573 * @param string $hostname host name
3574 * @param string $tablename table name
3575 * @param string $dbname database name
3577 * @return PMA_message success message or error message for update
3579 function PMA_updatePrivileges($username, $hostname, $tablename, $dbname)
3581 $db_and_table = PMA_wildcardEscapeForGrant($dbname, $tablename);
3583 $sql_query0 = 'REVOKE ALL PRIVILEGES ON ' . $db_and_table
3584 . ' FROM \'' . PMA_Util::sqlAddSlashes($username)
3585 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
3587 if (! isset($_POST['Grant_priv']) || $_POST['Grant_priv'] != 'Y') {
3588 $sql_query1 = 'REVOKE GRANT OPTION ON ' . $db_and_table
3589 . ' FROM \'' . PMA_Util::sqlAddSlashes($username) . '\'@\''
3590 . PMA_Util::sqlAddSlashes($hostname) . '\';';
3591 } else {
3592 $sql_query1 = '';
3595 // Should not do a GRANT USAGE for a table-specific privilege, it
3596 // causes problems later (cannot revoke it)
3597 if (! (/*overload*/mb_strlen($tablename)
3598 && 'USAGE' == implode('', PMA_extractPrivInfo()))
3600 $sql_query2 = 'GRANT ' . join(', ', PMA_extractPrivInfo())
3601 . ' ON ' . $db_and_table
3602 . ' TO \'' . PMA_Util::sqlAddSlashes($username) . '\'@\''
3603 . PMA_Util::sqlAddSlashes($hostname) . '\'';
3605 if (! /*overload*/mb_strlen($dbname)) {
3606 // add REQUIRE clause
3607 $sql_query2 .= PMA_getRequireClause();
3610 if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
3611 || (! /*overload*/mb_strlen($dbname)
3612 && (isset($_POST['max_questions']) || isset($_POST['max_connections'])
3613 || isset($_POST['max_updates'])
3614 || isset($_POST['max_user_connections'])))
3616 $sql_query2 .= PMA_getWithClauseForAddUserAndUpdatePrivs();
3618 $sql_query2 .= ';';
3620 if (! $GLOBALS['dbi']->tryQuery($sql_query0)) {
3621 // This might fail when the executing user does not have
3622 // ALL PRIVILEGES himself.
3623 // See https://sourceforge.net/p/phpmyadmin/bugs/3270/
3624 $sql_query0 = '';
3626 if (! empty($sql_query1) && ! $GLOBALS['dbi']->tryQuery($sql_query1)) {
3627 // this one may fail, too...
3628 $sql_query1 = '';
3630 if (! empty($sql_query2)) {
3631 $GLOBALS['dbi']->query($sql_query2);
3632 } else {
3633 $sql_query2 = '';
3635 $sql_query = $sql_query0 . ' ' . $sql_query1 . ' ' . $sql_query2;
3636 $message = PMA_Message::success(__('You have updated the privileges for %s.'));
3637 $message->addParam(
3638 '\'' . htmlspecialchars($username)
3639 . '\'@\'' . htmlspecialchars($hostname) . '\''
3642 return array($sql_query, $message);
3646 * Get List of information: Changes / copies a user
3648 * @return array
3650 function PMA_getDataForChangeOrCopyUser()
3652 $queries = null;
3653 $password = null;
3655 if (isset($_REQUEST['change_copy'])) {
3656 $user_host_condition = ' WHERE `User` = '
3657 . "'" . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'"
3658 . ' AND `Host` = '
3659 . "'" . PMA_Util::sqlAddSlashes($_REQUEST['old_hostname']) . "';";
3660 $row = $GLOBALS['dbi']->fetchSingleRow(
3661 'SELECT * FROM `mysql`.`user` ' . $user_host_condition
3663 if (! $row) {
3664 $response = PMA_Response::getInstance();
3665 $response->addHTML(
3666 PMA_Message::notice(__('No user found.'))->getDisplay()
3668 unset($_REQUEST['change_copy']);
3669 } else {
3670 extract($row, EXTR_OVERWRITE);
3671 // Recent MySQL versions have the field "Password" in mysql.user,
3672 // so the previous extract creates $Password but this script
3673 // uses $password
3674 if (! isset($password) && isset($Password)) {
3675 $password = $Password;
3677 $queries = array();
3681 return array($queries, $password);
3685 * Update Data for information: Deletes users
3687 * @param array $queries queries array
3689 * @return array
3691 function PMA_getDataForDeleteUsers($queries)
3693 if (isset($_REQUEST['change_copy'])) {
3694 $selected_usr = array(
3695 $_REQUEST['old_username'] . '&amp;#27;' . $_REQUEST['old_hostname']
3697 } else {
3698 $selected_usr = $_REQUEST['selected_usr'];
3699 $queries = array();
3701 foreach ($selected_usr as $each_user) {
3702 list($this_user, $this_host) = explode('&amp;#27;', $each_user);
3703 $queries[] = '# '
3704 . sprintf(
3705 __('Deleting %s'),
3706 '\'' . $this_user . '\'@\'' . $this_host . '\''
3708 . ' ...';
3709 $queries[] = 'DROP USER \''
3710 . PMA_Util::sqlAddSlashes($this_user)
3711 . '\'@\'' . PMA_Util::sqlAddSlashes($this_host) . '\';';
3712 PMA_relationsCleanupUser($this_user);
3714 if (isset($_REQUEST['drop_users_db'])) {
3715 $queries[] = 'DROP DATABASE IF EXISTS '
3716 . PMA_Util::backquote($this_user) . ';';
3717 $GLOBALS['reload'] = true;
3720 return $queries;
3724 * update Message For Reload
3726 * @return array
3728 function PMA_updateMessageForReload()
3730 $message = null;
3731 if (isset($_REQUEST['flush_privileges'])) {
3732 $sql_query = 'FLUSH PRIVILEGES;';
3733 $GLOBALS['dbi']->query($sql_query);
3734 $message = PMA_Message::success(
3735 __('The privileges were reloaded successfully.')
3739 if (isset($_REQUEST['validate_username'])) {
3740 $message = PMA_Message::success();
3743 return $message;
3747 * update Data For Queries from queries_for_display
3749 * @param array $queries queries array
3750 * @param array|null $queries_for_display queries array for display
3752 * @return null
3754 function PMA_getDataForQueries($queries, $queries_for_display)
3756 $tmp_count = 0;
3757 foreach ($queries as $sql_query) {
3758 if ($sql_query{0} != '#') {
3759 $GLOBALS['dbi']->query($sql_query);
3761 // when there is a query containing a hidden password, take it
3762 // instead of the real query sent
3763 if (isset($queries_for_display[$tmp_count])) {
3764 $queries[$tmp_count] = $queries_for_display[$tmp_count];
3766 $tmp_count++;
3769 return $queries;
3773 * update Data for information: Adds a user
3775 * @param string $dbname db name
3776 * @param string $username user name
3777 * @param string $hostname host name
3778 * @param string $password password
3779 * @param bool $is_menuwork is_menuwork set?
3781 * @return array
3783 function PMA_addUser(
3784 $dbname, $username, $hostname,
3785 $password, $is_menuwork
3787 $_add_user_error = false;
3788 $message = null;
3789 $queries = null;
3790 $queries_for_display = null;
3791 $sql_query = null;
3793 if (isset($_REQUEST['adduser_submit']) || isset($_REQUEST['change_copy'])) {
3794 $sql_query = '';
3795 if ($_POST['pred_username'] == 'any') {
3796 $username = '';
3798 switch ($_POST['pred_hostname']) {
3799 case 'any':
3800 $hostname = '%';
3801 break;
3802 case 'localhost':
3803 $hostname = 'localhost';
3804 break;
3805 case 'hosttable':
3806 $hostname = '';
3807 break;
3808 case 'thishost':
3809 $_user_name = $GLOBALS['dbi']->fetchValue('SELECT USER()');
3810 $hostname = /*overload*/mb_substr(
3811 $_user_name,
3812 (/*overload*/mb_strrpos($_user_name, '@') + 1)
3814 unset($_user_name);
3815 break;
3817 $sql = "SELECT '1' FROM `mysql`.`user`"
3818 . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
3819 . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "';";
3820 if ($GLOBALS['dbi']->fetchValue($sql) == 1) {
3821 $message = PMA_Message::error(__('The user %s already exists!'));
3822 $message->addParam(
3823 '[em]\'' . $username . '\'@\'' . $hostname . '\'[/em]'
3825 $_REQUEST['adduser'] = true;
3826 $_add_user_error = true;
3827 } else {
3828 list($create_user_real, $create_user_show, $real_sql_query, $sql_query)
3829 = PMA_getSqlQueriesForDisplayAndAddUser(
3830 $username, $hostname, (isset ($password) ? $password : '')
3833 if (empty($_REQUEST['change_copy'])) {
3834 $_error = false;
3836 if (isset($create_user_real)) {
3837 if (! $GLOBALS['dbi']->tryQuery($create_user_real)) {
3838 $_error = true;
3840 $sql_query = $create_user_show . $sql_query;
3842 list($sql_query, $message) = PMA_addUserAndCreateDatabase(
3843 $_error, $real_sql_query, $sql_query, $username, $hostname,
3844 isset($dbname) ? $dbname : null
3846 if (! empty($_REQUEST['userGroup']) && $is_menuwork) {
3847 PMA_setUserGroup($GLOBALS['username'], $_REQUEST['userGroup']);
3850 } else {
3851 if (isset($create_user_real)) {
3852 $queries[] = $create_user_real;
3854 $queries[] = $real_sql_query;
3855 // we put the query containing the hidden password in
3856 // $queries_for_display, at the same position occupied
3857 // by the real query in $queries
3858 $tmp_count = count($queries);
3859 if (isset($create_user_real)) {
3860 $queries_for_display[$tmp_count - 2] = $create_user_show;
3862 $queries_for_display[$tmp_count - 1] = $sql_query;
3864 unset($real_sql_query);
3868 return array(
3869 $message, $queries, $queries_for_display, $sql_query, $_add_user_error
3874 * Update DB information: DB, Table, isWildcard
3876 * @return array
3878 function PMA_getDataForDBInfo()
3880 $username = null;
3881 $hostname = null;
3882 $dbname = null;
3883 $tablename = null;
3884 $dbname_is_wildcard = null;
3886 if (isset ($_REQUEST['username'])) {
3887 $username = $_REQUEST['username'];
3889 if (isset ($_REQUEST['hostname'])) {
3890 $hostname = $_REQUEST['hostname'];
3893 * Checks if a dropdown box has been used for selecting a database / table
3895 if (PMA_isValid($_REQUEST['pred_tablename'])) {
3896 $tablename = $_REQUEST['pred_tablename'];
3897 } elseif (PMA_isValid($_REQUEST['tablename'])) {
3898 $tablename = $_REQUEST['tablename'];
3899 } else {
3900 unset($tablename);
3903 if (isset($_REQUEST['pred_dbname'])) {
3904 $is_valid_pred_dbname = true;
3905 foreach ($_REQUEST['pred_dbname'] as $key => $db_name) {
3906 if (! PMA_isValid($db_name)) {
3907 $is_valid_pred_dbname = false;
3908 break;
3913 if (isset($_REQUEST['dbname'])) {
3914 $is_valid_dbname = true;
3915 if (is_array($_REQUEST['dbname'])) {
3916 foreach ($_REQUEST['dbname'] as $key => $db_name) {
3917 if (! PMA_isValid($db_name)) {
3918 $is_valid_dbname = false;
3919 break;
3922 } else {
3923 if (! PMA_isValid($_REQUEST['dbname'])) {
3924 $is_valid_dbname = false;
3929 if (isset($is_valid_pred_dbname) && $is_valid_pred_dbname) {
3930 $dbname = $_REQUEST['pred_dbname'];
3931 // If dbname contains only one database.
3932 if (count($dbname) == 1) {
3933 $dbname = $dbname[0];
3935 } elseif (isset($is_valid_dbname) && $is_valid_dbname) {
3936 $dbname = $_REQUEST['dbname'];
3937 } else {
3938 unset($dbname);
3939 unset($tablename);
3942 if (isset($dbname)) {
3943 if (is_array($dbname)) {
3944 $db_and_table = $dbname;
3945 foreach ($db_and_table as $key => $db_name) {
3946 $db_and_table[$key] .= '.';
3948 } else {
3949 $unescaped_db = PMA_Util::unescapeMysqlWildcards($dbname);
3950 $db_and_table = PMA_Util::backquote($unescaped_db) . '.';
3952 if (isset($tablename)) {
3953 $db_and_table .= PMA_Util::backquote($tablename);
3954 } else {
3955 if (is_array($db_and_table)) {
3956 foreach ($db_and_table as $key => $db_name) {
3957 $db_and_table[$key] .= '*';
3959 } else {
3960 $db_and_table .= '*';
3963 } else {
3964 $db_and_table = '*.*';
3967 // check if given $dbname is a wildcard or not
3968 if (isset($dbname)) {
3969 //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
3970 if (! is_array($dbname) && preg_match('/(?<!\\\\)(?:_|%)/i', $dbname)) {
3971 $dbname_is_wildcard = true;
3972 } else {
3973 $dbname_is_wildcard = false;
3977 return array(
3978 $username, $hostname,
3979 isset($dbname)? $dbname : null,
3980 isset($tablename)? $tablename : null,
3981 $db_and_table,
3982 $dbname_is_wildcard,
3987 * Get title and textarea for export user definition in Privileges
3989 * @param string $username username
3990 * @param string $hostname host name
3992 * @return array ($title, $export)
3994 function PMA_getListForExportUserDefinition($username, $hostname)
3996 $export = '<textarea class="export" cols="60" rows="15">';
3998 if (isset($_REQUEST['selected_usr'])) {
3999 // export privileges for selected users
4000 $title = __('Privileges');
4002 foreach ($_REQUEST['selected_usr'] as $export_user) {
4003 $export_username = /*overload*/mb_substr(
4004 $export_user, 0, /*overload*/mb_strpos($export_user, '&')
4006 $export_hostname = /*overload*/mb_substr(
4007 $export_user, /*overload*/mb_strrpos($export_user, ';') + 1
4009 $export .= '# '
4010 . sprintf(
4011 __('Privileges for %s'),
4012 '`' . htmlspecialchars($export_username)
4013 . '`@`' . htmlspecialchars($export_hostname) . '`'
4015 . "\n\n";
4016 $export .= PMA_getGrants($export_username, $export_hostname) . "\n";
4018 } else {
4019 // export privileges for a single user
4020 $title = __('User') . ' `' . htmlspecialchars($username)
4021 . '`@`' . htmlspecialchars($hostname) . '`';
4022 $export .= PMA_getGrants($username, $hostname);
4024 // remove trailing whitespace
4025 $export = trim($export);
4027 $export .= '</textarea>';
4029 return array($title, $export);
4033 * Get HTML for display Add userfieldset
4035 * @param string $db the database
4036 * @param string $table the table name
4038 * @return string html output
4040 function PMA_getAddUserHtmlFieldset($db = '', $table = '')
4042 if (!$GLOBALS['is_createuser']) {
4043 return '';
4045 $rel_params = array();
4046 $url_params = array(
4047 'adduser' => 1
4049 if (!empty($db)) {
4050 $url_params['dbname']
4051 = $rel_params['checkprivsdb']
4052 = $db;
4054 if (!empty($table)) {
4055 $url_params['tablename']
4056 = $rel_params['checkprivstable']
4057 = $table;
4060 return '<fieldset id="fieldset_add_user">' . "\n"
4061 . '<legend>' . _pgettext('Create new user', 'New') . '</legend>'
4062 . '<a id="add_user_anchor" href="server_privileges.php'
4063 . PMA_URL_getCommon($url_params) . '" '
4064 . (!empty($rel_params)
4065 ? ('rel="' . PMA_URL_getCommon($rel_params) . '" ')
4066 : '')
4067 . '>' . "\n"
4068 . PMA_Util::getIcon('b_usradd.png')
4069 . ' ' . __('Add user account') . '</a>' . "\n"
4070 . '</fieldset>' . "\n";
4074 * Get HTML header for display User's properties
4076 * @param boolean $dbname_is_wildcard whether database name is wildcard or not
4077 * @param string $url_dbname url database name that urlencode() string
4078 * @param string $dbname database name
4079 * @param string $username username
4080 * @param string $hostname host name
4081 * @param string $tablename table name
4083 * @return string $html_output
4085 function PMA_getHtmlHeaderForUserProperties(
4086 $dbname_is_wildcard, $url_dbname, $dbname, $username, $hostname, $tablename
4088 $html_output = '<h2>' . "\n"
4089 . PMA_Util::getIcon('b_usredit.png')
4090 . __('Edit privileges:') . ' '
4091 . __('User account');
4093 if (! empty($dbname)) {
4094 $html_output .= ' <i><a class="edit_user_anchor"'
4095 . ' href="server_privileges.php'
4096 . PMA_URL_getCommon(
4097 array(
4098 'username' => $username,
4099 'hostname' => $hostname,
4100 'dbname' => '',
4101 'tablename' => '',
4104 . '">\'' . htmlspecialchars($username)
4105 . '\'@\'' . htmlspecialchars($hostname)
4106 . '\'</a></i>' . "\n";
4108 $html_output .= ' - ';
4109 $html_output .= ($dbname_is_wildcard
4110 || is_array($dbname) && count($dbname) > 1)
4111 ? __('Databases') : __('Database');
4112 if (! empty($_REQUEST['tablename'])) {
4113 $html_output .= ' <i><a href="server_privileges.php'
4114 . PMA_URL_getCommon(
4115 array(
4116 'username' => $username,
4117 'hostname' => $hostname,
4118 'dbname' => $url_dbname,
4119 'tablename' => '',
4122 . '">' . htmlspecialchars($dbname)
4123 . '</a></i>';
4125 $html_output .= ' - ' . __('Table')
4126 . ' <i>' . htmlspecialchars($tablename) . '</i>';
4127 } else {
4128 if (! is_array($dbname)) {
4129 $dbname = array($dbname);
4131 $html_output .= ' <i>'
4132 . htmlspecialchars(implode(', ', $dbname))
4133 . '</i>';
4136 } else {
4137 $html_output .= ' <i>\'' . htmlspecialchars($username)
4138 . '\'@\'' . htmlspecialchars($hostname)
4139 . '\'</i>' . "\n";
4142 $html_output .= '</h2>' . "\n";
4143 $cur_user = htmlspecialchars($GLOBALS['dbi']->getCurrentUser());
4144 $user = htmlspecialchars($username . '@' . $hostname);
4145 // Add a short notice for the user
4146 // to remind him that he is editing his own privileges
4147 if ($user === $cur_user) {
4148 $html_output .= PMA_Message::notice(
4150 'Note: You are attempting to edit privileges of the '
4151 . 'user with which you are currently logged in.'
4153 )->getDisplay();
4155 return $html_output;
4159 * Get HTML snippet for display user overview page
4161 * @param string $pmaThemeImage a image source link
4162 * @param string $text_dir text directory
4164 * @return string $html_output
4166 function PMA_getHtmlForUserOverview($pmaThemeImage, $text_dir)
4168 $html_output = '<h2>' . "\n"
4169 . PMA_Util::getIcon('b_usrlist.png')
4170 . __('User accounts overview') . "\n"
4171 . '</h2>' . "\n";
4173 $password_column = 'Password';
4174 if (PMA_Util::getServerType() == 'MySQL'
4175 && PMA_MYSQL_INT_VERSION >= 50706
4177 $password_column = 'authentication_string';
4179 // $sql_query is for the initial-filtered,
4180 // $sql_query_all is for counting the total no. of users
4182 $sql_query = $sql_query_all = 'SELECT *,' .
4183 " IF(`" . $password_column . "` = _latin1 '', 'N', 'Y') AS 'Password'" .
4184 ' FROM `mysql`.`user`';
4186 $sql_query .= (isset($_REQUEST['initial'])
4187 ? PMA_rangeOfUsers($_REQUEST['initial'])
4188 : '');
4190 $sql_query .= ' ORDER BY `User` ASC, `Host` ASC;';
4191 $sql_query_all .= ' ;';
4193 $res = $GLOBALS['dbi']->tryQuery(
4194 $sql_query, null, PMA_DatabaseInterface::QUERY_STORE
4196 $res_all = $GLOBALS['dbi']->tryQuery(
4197 $sql_query_all, null, PMA_DatabaseInterface::QUERY_STORE
4200 if (! $res) {
4201 // the query failed! This may have two reasons:
4202 // - the user does not have enough privileges
4203 // - the privilege tables use a structure of an earlier version.
4204 // so let's try a more simple query
4206 $GLOBALS['dbi']->freeResult($res);
4207 $GLOBALS['dbi']->freeResult($res_all);
4208 $sql_query = 'SELECT * FROM `mysql`.`user`';
4209 $res = $GLOBALS['dbi']->tryQuery(
4210 $sql_query, null, PMA_DatabaseInterface::QUERY_STORE
4213 if (! $res) {
4214 $html_output .= PMA_getHtmlForViewUsersError();
4215 $html_output .= PMA_getAddUserHtmlFieldset();
4216 } else {
4217 // This message is hardcoded because I will replace it by
4218 // a automatic repair feature soon.
4219 $raw = 'Your privilege table structure seems to be older than'
4220 . ' this MySQL version!<br />'
4221 . 'Please run the <code>mysql_upgrade</code> command'
4222 . '(<code>mysql_fix_privilege_tables</code> on older systems)'
4223 . ' that should be included in your MySQL server distribution'
4224 . ' to solve this problem!';
4225 $html_output .= PMA_Message::rawError($raw)->getDisplay();
4227 $GLOBALS['dbi']->freeResult($res);
4228 } else {
4229 $db_rights = PMA_getDbRightsForUserOverview();
4230 // for all initials, even non A-Z
4231 $array_initials = array();
4233 foreach ($db_rights as $right) {
4234 foreach ($right as $account) {
4235 if (empty($account['User']) && $account['Host'] == 'localhost') {
4236 $html_output .= PMA_Message::notice(
4238 'A user account allowing any user from localhost to '
4239 . 'connect is present. This will prevent other users '
4240 . 'from connecting if the host part of their account '
4241 . 'allows a connection from any (%) host.'
4243 . PMA_Util::showMySQLDocu('problems-connecting')
4244 )->getDisplay();
4245 break 2;
4251 * Displays the initials
4252 * Also not necessary if there is less than 20 privileges
4254 if ($GLOBALS['dbi']->numRows($res_all) > 20) {
4255 $html_output .= PMA_getHtmlForInitials($array_initials);
4259 * Display the user overview
4260 * (if less than 50 users, display them immediately)
4262 if (isset($_REQUEST['initial'])
4263 || isset($_REQUEST['showall'])
4264 || $GLOBALS['dbi']->numRows($res) < 50
4266 $html_output .= PMA_getUsersOverview(
4267 $res, $db_rights, $pmaThemeImage, $text_dir
4269 } else {
4270 $html_output .= PMA_getAddUserHtmlFieldset();
4271 } // end if (display overview)
4273 if (! $GLOBALS['is_ajax_request']
4274 || ! empty($_REQUEST['ajax_page_request'])
4276 $flushnote = new PMA_Message(
4278 'Note: phpMyAdmin gets the users\' privileges directly '
4279 . 'from MySQL\'s privilege tables. The content of these tables '
4280 . 'may differ from the privileges the server uses, '
4281 . 'if they have been changed manually. In this case, '
4282 . 'you should %sreload the privileges%s before you continue.'
4284 PMA_Message::NOTICE
4286 $flushLink = '<a href="server_privileges.php'
4287 . PMA_URL_getCommon(array('flush_privileges' => 1))
4288 . '" id="reload_privileges_anchor">';
4289 $flushnote->addParam(
4290 $flushLink,
4291 false
4293 $flushnote->addParam('</a>', false);
4294 $html_output .= $flushnote->getDisplay();
4298 return $html_output;
4302 * Get HTML snippet for display user properties
4304 * @param boolean $dbname_is_wildcard whether database name is wildcard or not
4305 * @param string $url_dbname url database name that urlencode() string
4306 * @param string $username username
4307 * @param string $hostname host name
4308 * @param string $dbname database name
4309 * @param string $tablename table name
4311 * @return string $html_output
4313 function PMA_getHtmlForUserProperties($dbname_is_wildcard,$url_dbname,
4314 $username, $hostname, $dbname, $tablename
4316 $html_output = '<div id="edit_user_dialog">';
4317 $html_output .= PMA_getHtmlHeaderForUserProperties(
4318 $dbname_is_wildcard, $url_dbname, $dbname, $username, $hostname, $tablename
4321 $sql = "SELECT '1' FROM `mysql`.`user`"
4322 . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
4323 . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "';";
4325 $user_does_not_exists = (bool) ! $GLOBALS['dbi']->fetchValue($sql);
4327 if ($user_does_not_exists) {
4328 $html_output .= PMA_Message::error(
4329 __('The selected user was not found in the privilege table.')
4330 )->getDisplay();
4331 $html_output .= PMA_getHtmlForLoginInformationFields();
4332 //exit;
4335 $_params = array(
4336 'username' => $username,
4337 'hostname' => $hostname,
4339 if (! is_array($dbname) && /*overload*/mb_strlen($dbname)) {
4340 $_params['dbname'] = $dbname;
4341 if (/*overload*/mb_strlen($tablename)) {
4342 $_params['tablename'] = $tablename;
4344 } else {
4345 $_params['dbname'] = $dbname;
4348 $html_output .= '<form class="submenu-item" name="usersForm" '
4349 . 'id="addUsersForm" action="server_privileges.php" method="post">' . "\n";
4350 $html_output .= PMA_URL_getHiddenInputs($_params);
4351 $html_output .= PMA_getHtmlToDisplayPrivilegesTable(
4352 // If $dbname is an array, pass any one db as all have same privs.
4353 PMA_ifSetOr($dbname, (is_array($dbname)) ? $dbname[0] : '*', 'length'),
4354 PMA_ifSetOr($tablename, '*', 'length')
4357 $html_output .= '</form>' . "\n";
4359 if (! is_array($dbname) && ! /*overload*/mb_strlen($tablename)
4360 && empty($dbname_is_wildcard)
4363 // no table name was given, display all table specific rights
4364 // but only if $dbname contains no wildcards
4366 $html_output .= '<form class="submenu-item" action="server_privileges.php" '
4367 . 'id="db_or_table_specific_priv" method="post">' . "\n";
4369 // unescape wildcards in dbname at table level
4370 $unescaped_db = PMA_Util::unescapeMysqlWildcards($dbname);
4371 list($html_rightsTable, $found_rows)
4372 = PMA_getHtmlForAllTableSpecificRights(
4373 $username, $hostname, $unescaped_db
4375 $html_output .= $html_rightsTable;
4377 if (! /*overload*/mb_strlen($dbname)) {
4378 // no database name was given, display select db
4379 $html_output .= PMA_getHtmlForSelectDbInEditPrivs($found_rows);
4381 } else {
4382 $html_output .= PMA_displayTablesInEditPrivs($dbname, $found_rows);
4384 $html_output .= '</fieldset>' . "\n";
4386 $html_output .= '<fieldset class="tblFooters">' . "\n"
4387 . ' <input type="submit" value="' . __('Go') . '" />'
4388 . '</fieldset>' . "\n"
4389 . '</form>' . "\n";
4392 // Provide a line with links to the relevant database and table
4393 if (! is_array($dbname) && /*overload*/mb_strlen($dbname)
4394 && empty($dbname_is_wildcard)
4396 $html_output .= PMA_getLinkToDbAndTable($url_dbname, $dbname, $tablename);
4400 if (! is_array($dbname) && ! /*overload*/mb_strlen($dbname)
4401 && ! $user_does_not_exists
4403 //change login information
4404 $html_output .= PMA_getHtmlForChangePassword($username, $hostname);
4405 $html_output .= PMA_getChangeLoginInformationHtmlForm($username, $hostname);
4407 $html_output .= '</div>';
4409 return $html_output;
4413 * Get queries for Table privileges to change or copy user
4415 * @param string $user_host_condition user host condition to
4416 * select relevant table privileges
4417 * @param array $queries queries array
4418 * @param string $username username
4419 * @param string $hostname host name
4421 * @return array $queries
4423 function PMA_getTablePrivsQueriesForChangeOrCopyUser($user_host_condition,
4424 $queries, $username, $hostname
4426 $res = $GLOBALS['dbi']->query(
4427 'SELECT `Db`, `Table_name`, `Table_priv` FROM `mysql`.`tables_priv`'
4428 . $user_host_condition,
4429 $GLOBALS['userlink'],
4430 PMA_DatabaseInterface::QUERY_STORE
4432 while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
4434 $res2 = $GLOBALS['dbi']->query(
4435 'SELECT `Column_name`, `Column_priv`'
4436 . ' FROM `mysql`.`columns_priv`'
4437 . ' WHERE `User`'
4438 . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'"
4439 . ' AND `Host`'
4440 . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . '\''
4441 . ' AND `Db`'
4442 . ' = \'' . PMA_Util::sqlAddSlashes($row['Db']) . "'"
4443 . ' AND `Table_name`'
4444 . ' = \'' . PMA_Util::sqlAddSlashes($row['Table_name']) . "'"
4445 . ';',
4446 null,
4447 PMA_DatabaseInterface::QUERY_STORE
4450 $tmp_privs1 = PMA_extractPrivInfo($row);
4451 $tmp_privs2 = array(
4452 'Select' => array(),
4453 'Insert' => array(),
4454 'Update' => array(),
4455 'References' => array()
4458 while ($row2 = $GLOBALS['dbi']->fetchAssoc($res2)) {
4459 $tmp_array = explode(',', $row2['Column_priv']);
4460 if (in_array('Select', $tmp_array)) {
4461 $tmp_privs2['Select'][] = $row2['Column_name'];
4463 if (in_array('Insert', $tmp_array)) {
4464 $tmp_privs2['Insert'][] = $row2['Column_name'];
4466 if (in_array('Update', $tmp_array)) {
4467 $tmp_privs2['Update'][] = $row2['Column_name'];
4469 if (in_array('References', $tmp_array)) {
4470 $tmp_privs2['References'][] = $row2['Column_name'];
4473 if (count($tmp_privs2['Select']) > 0 && ! in_array('SELECT', $tmp_privs1)) {
4474 $tmp_privs1[] = 'SELECT (`' . join('`, `', $tmp_privs2['Select']) . '`)';
4476 if (count($tmp_privs2['Insert']) > 0 && ! in_array('INSERT', $tmp_privs1)) {
4477 $tmp_privs1[] = 'INSERT (`' . join('`, `', $tmp_privs2['Insert']) . '`)';
4479 if (count($tmp_privs2['Update']) > 0 && ! in_array('UPDATE', $tmp_privs1)) {
4480 $tmp_privs1[] = 'UPDATE (`' . join('`, `', $tmp_privs2['Update']) . '`)';
4482 if (count($tmp_privs2['References']) > 0
4483 && ! in_array('REFERENCES', $tmp_privs1)
4485 $tmp_privs1[]
4486 = 'REFERENCES (`' . join('`, `', $tmp_privs2['References']) . '`)';
4489 $queries[] = 'GRANT ' . join(', ', $tmp_privs1)
4490 . ' ON ' . PMA_Util::backquote($row['Db']) . '.'
4491 . PMA_Util::backquote($row['Table_name'])
4492 . ' TO \'' . PMA_Util::sqlAddSlashes($username)
4493 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\''
4494 . (in_array('Grant', explode(',', $row['Table_priv']))
4495 ? ' WITH GRANT OPTION;'
4496 : ';');
4498 return $queries;
4502 * Get queries for database specific privileges for change or copy user
4504 * @param array $queries queries array with string
4505 * @param string $username username
4506 * @param string $hostname host name
4508 * @return array $queries
4510 function PMA_getDbSpecificPrivsQueriesForChangeOrCopyUser(
4511 $queries, $username, $hostname
4513 $user_host_condition = ' WHERE `User`'
4514 . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'"
4515 . ' AND `Host`'
4516 . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_hostname']) . '\';';
4518 $res = $GLOBALS['dbi']->query(
4519 'SELECT * FROM `mysql`.`db`' . $user_host_condition
4522 while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
4523 $queries[] = 'GRANT ' . join(', ', PMA_extractPrivInfo($row))
4524 . ' ON ' . PMA_Util::backquote($row['Db']) . '.*'
4525 . ' TO \'' . PMA_Util::sqlAddSlashes($username)
4526 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\''
4527 . ($row['Grant_priv'] == 'Y' ? ' WITH GRANT OPTION;' : ';');
4529 $GLOBALS['dbi']->freeResult($res);
4531 $queries = PMA_getTablePrivsQueriesForChangeOrCopyUser(
4532 $user_host_condition, $queries, $username, $hostname
4535 return $queries;
4539 * Prepares queries for adding users and
4540 * also create database and return query and message
4542 * @param boolean $_error whether user create or not
4543 * @param string $real_sql_query SQL query for add a user
4544 * @param string $sql_query SQL query to be displayed
4545 * @param string $username username
4546 * @param string $hostname host name
4547 * @param string $dbname database name
4549 * @return array $sql_query, $message
4551 function PMA_addUserAndCreateDatabase($_error, $real_sql_query, $sql_query,
4552 $username, $hostname, $dbname
4554 if ($_error || (!empty($real_sql_query)
4555 && !$GLOBALS['dbi']->tryQuery($real_sql_query))
4557 $_REQUEST['createdb-1'] = $_REQUEST['createdb-2']
4558 = $_REQUEST['createdb-3'] = null;
4559 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
4560 } else {
4561 $message = PMA_Message::success(__('You have added a new user.'));
4564 if (isset($_REQUEST['createdb-1'])) {
4565 // Create database with same name and grant all privileges
4566 $q = 'CREATE DATABASE IF NOT EXISTS '
4567 . PMA_Util::backquote(
4568 PMA_Util::sqlAddSlashes($username)
4569 ) . ';';
4570 $sql_query .= $q;
4571 if (! $GLOBALS['dbi']->tryQuery($q)) {
4572 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
4576 * Reload the navigation
4578 $GLOBALS['reload'] = true;
4579 $GLOBALS['db'] = $username;
4581 $q = 'GRANT ALL PRIVILEGES ON '
4582 . PMA_Util::backquote(
4583 PMA_Util::escapeMysqlWildcards(
4584 PMA_Util::sqlAddSlashes($username)
4586 ) . '.* TO \''
4587 . PMA_Util::sqlAddSlashes($username)
4588 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
4589 $sql_query .= $q;
4590 if (! $GLOBALS['dbi']->tryQuery($q)) {
4591 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
4595 if (isset($_REQUEST['createdb-2'])) {
4596 // Grant all privileges on wildcard name (username\_%)
4597 $q = 'GRANT ALL PRIVILEGES ON '
4598 . PMA_Util::backquote(
4599 PMA_Util::sqlAddSlashes($username) . '\_%'
4600 ) . '.* TO \''
4601 . PMA_Util::sqlAddSlashes($username)
4602 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
4603 $sql_query .= $q;
4604 if (! $GLOBALS['dbi']->tryQuery($q)) {
4605 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
4609 if (isset($_REQUEST['createdb-3'])) {
4610 // Grant all privileges on the specified database to the new user
4611 $q = 'GRANT ALL PRIVILEGES ON '
4612 . PMA_Util::backquote(
4613 PMA_Util::sqlAddSlashes($dbname)
4614 ) . '.* TO \''
4615 . PMA_Util::sqlAddSlashes($username)
4616 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
4617 $sql_query .= $q;
4618 if (! $GLOBALS['dbi']->tryQuery($q)) {
4619 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
4622 return array($sql_query, $message);
4626 * Get SQL queries for Display and Add user
4628 * @param string $username username
4629 * @param string $hostname host name
4630 * @param string $password password
4632 * @return array ($create_user_real, $create_user_show,$real_sql_query, $sql_query)
4634 function PMA_getSqlQueriesForDisplayAndAddUser($username, $hostname, $password)
4636 $create_user_real = 'CREATE USER \''
4637 . PMA_Util::sqlAddSlashes($username) . '\'@\''
4638 . PMA_Util::sqlAddSlashes($hostname) . '\'';
4640 $real_sql_query = 'GRANT ' . join(', ', PMA_extractPrivInfo()) . ' ON *.* TO \''
4641 . PMA_Util::sqlAddSlashes($username) . '\'@\''
4642 . PMA_Util::sqlAddSlashes($hostname) . '\'';
4644 if ($_POST['pred_password'] != 'none' && $_POST['pred_password'] != 'keep') {
4645 $sql_query = $real_sql_query;
4646 // Requires SELECT privilege on mysql database
4647 // for using this with GRANT queries. It can be skipped.
4648 if ($GLOBALS['is_superuser']) {
4649 $sql_query .= ' IDENTIFIED BY \'***\'';
4650 $real_sql_query .= ' IDENTIFIED BY \''
4651 . PMA_Util::sqlAddSlashes($_POST['pma_pw']) . '\'';
4653 if (isset($create_user_real)) {
4654 $create_user_show = $create_user_real . ' IDENTIFIED BY \'***\'';
4655 $create_user_real .= ' IDENTIFIED BY \''
4656 . PMA_Util::sqlAddSlashes($_POST['pma_pw']) . '\'';
4658 } else {
4659 if ($_POST['pred_password'] == 'keep' && ! empty($password)) {
4660 $real_sql_query .= ' IDENTIFIED BY PASSWORD \'' . $password . '\'';
4661 if (isset($create_user_real)) {
4662 $create_user_real .= ' IDENTIFIED BY PASSWORD \'' . $password . '\'';
4665 $sql_query = $real_sql_query;
4666 if (isset($create_user_real)) {
4667 $create_user_show = $create_user_real;
4671 // add REQUIRE clause
4672 $require_clause = PMA_getRequireClause();
4673 $real_sql_query .= $require_clause;
4674 $sql_query .= $require_clause;
4676 if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
4677 || (isset($_POST['max_questions']) || isset($_POST['max_connections'])
4678 || isset($_POST['max_updates']) || isset($_POST['max_user_connections']))
4680 $with_clause = PMA_getWithClauseForAddUserAndUpdatePrivs();
4681 $real_sql_query .= $with_clause;
4682 $sql_query .= $with_clause;
4685 if (isset($create_user_real)) {
4686 $create_user_real .= ';';
4687 $create_user_show .= ';';
4689 $real_sql_query .= ';';
4690 $sql_query .= ';';
4691 // No Global GRANT_OPTION privilege
4692 if (!$GLOBALS['is_grantuser']) {
4693 $real_sql_query = '';
4694 $sql_query = '';
4697 return array($create_user_real,
4698 $create_user_show,
4699 $real_sql_query,
4700 $sql_query