UPDATE 4.4.0.0
[phpmyadmin.git] / libraries / server_privileges.lib.php
blobc056f8e4e6cea42959bd0bb27d8f44da7a997cf4
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 cetrificate.'
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']) && ($row['ssl_type'] == 'ANY' || $row['ssl_type'] == ''))
841 ? ' checked="checked"'
842 : ''
844 . '/>';
846 $html_output .= '<label for="ssl_type_ANY"><code>'
847 . 'REQUIRE SSL'
848 . '</code></label>';
849 $html_output .= '</div>';
851 $html_output .= '</div>';
852 $html_output .= '</fieldset>';
854 return $html_output;
858 * Get HTML for "Resource limits"
860 * @param array $row first row from result or boolean false
862 * @return string html snippet
864 function PMA_getHtmlForResourceLimits($row)
866 $html_output = '<fieldset>' . "\n"
867 . '<legend>' . __('Resource limits') . '</legend>' . "\n"
868 . '<p><small>'
869 . '<i>' . __('Note: Setting these options to 0 (zero) removes the limit.')
870 . '</i></small></p>' . "\n";
872 $html_output .= '<div class="item">' . "\n"
873 . '<label for="text_max_questions">'
874 . '<code><dfn title="'
875 . __(
876 'Limits the number of queries the user may send to the server per hour.'
878 . '">'
879 . 'MAX QUERIES PER HOUR'
880 . '</dfn></code></label>' . "\n"
881 . '<input type="number" name="max_questions" id="text_max_questions" '
882 . 'value="'
883 . (isset($row['max_questions']) ? $row['max_questions'] : '0')
884 . '" min="0" '
885 . 'title="'
886 . __(
887 'Limits the number of queries the user may send to the server per hour.'
889 . '" />' . "\n"
890 . '</div>' . "\n";
892 $html_output .= '<div class="item">' . "\n"
893 . '<label for="text_max_updates">'
894 . '<code><dfn title="'
895 . __(
896 'Limits the number of commands that change any table '
897 . 'or database the user may execute per hour.'
898 ) . '">'
899 . 'MAX UPDATES PER HOUR'
900 . '</dfn></code></label>' . "\n"
901 . '<input type="number" name="max_updates" id="text_max_updates" '
902 . 'value="'
903 . (isset($row['max_updates']) ? $row['max_updates'] : '0')
904 . '" min="0" '
905 . 'title="'
906 . __(
907 'Limits the number of commands that change any table '
908 . 'or database the user may execute per hour.'
910 . '" />' . "\n"
911 . '</div>' . "\n";
913 $html_output .= '<div class="item">' . "\n"
914 . '<label for="text_max_connections">'
915 . '<code><dfn title="'
916 . __(
917 'Limits the number of new connections the user may open per hour.'
918 ) . '">'
919 . 'MAX CONNECTIONS PER HOUR'
920 . '</dfn></code></label>' . "\n"
921 . '<input type="number" name="max_connections" id="text_max_connections" '
922 . 'value="'
923 . (isset($row['max_connections']) ? $row['max_connections'] : '0')
924 . '" min="0" '
925 . 'title="' . __(
926 'Limits the number of new connections the user may open per hour.'
928 . '" />' . "\n"
929 . '</div>' . "\n";
931 $html_output .= '<div class="item">' . "\n"
932 . '<label for="text_max_user_connections">'
933 . '<code><dfn title="'
934 . __('Limits the number of simultaneous connections the user may have.')
935 . '">'
936 . 'MAX USER_CONNECTIONS'
937 . '</dfn></code></label>' . "\n"
938 . '<input type="number" name="max_user_connections" '
939 . 'id="text_max_user_connections" '
940 . 'value="'
941 . (isset($row['max_user_connections']) ? $row['max_user_connections'] : '0')
942 . '" '
943 . 'title="'
944 . __('Limits the number of simultaneous connections the user may have.')
945 . '" />' . "\n"
946 . '</div>' . "\n";
948 $html_output .= '</fieldset>' . "\n";
950 return $html_output;
954 * Get the HTML snippet for table specific privileges
956 * @param string $username username for database connection
957 * @param string $hostname hostname for database connection
958 * @param string $db the database
959 * @param string $table the table
960 * @param array $columns columns array
961 * @param array $row current privileges row
963 * @return string $html_output
965 function PMA_getHtmlForTableSpecificPrivileges(
966 $username, $hostname, $db, $table, $columns, $row
968 $res = $GLOBALS['dbi']->query(
969 'SELECT `Column_name`, `Column_priv`'
970 . ' FROM `mysql`.`columns_priv`'
971 . ' WHERE `User`'
972 . ' = \'' . PMA_Util::sqlAddSlashes($username) . "'"
973 . ' AND `Host`'
974 . ' = \'' . PMA_Util::sqlAddSlashes($hostname) . "'"
975 . ' AND `Db`'
976 . ' = \'' . PMA_Util::sqlAddSlashes(
977 PMA_Util::unescapeMysqlWildcards($db)
978 ) . "'"
979 . ' AND `Table_name`'
980 . ' = \'' . PMA_Util::sqlAddSlashes($table) . '\';'
983 while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
984 $row1[1] = explode(',', $row1[1]);
985 foreach ($row1[1] as $current) {
986 $columns[$row1[0]][$current] = true;
989 $GLOBALS['dbi']->freeResult($res);
990 unset($res, $row1, $current);
992 $html_output = '<input type="hidden" name="grant_count" '
993 . 'value="' . count($row) . '" />' . "\n"
994 . '<input type="hidden" name="column_count" '
995 . 'value="' . count($columns) . '" />' . "\n"
996 . '<fieldset id="fieldset_user_priv">' . "\n"
997 . '<legend data-submenu-label="Table">' . __('Table-specific privileges')
998 . PMA_Util::showHint(
999 __('Note: MySQL privilege names are expressed in English.')
1001 . '</legend>' . "\n";
1003 // privs that are attached to a specific column
1004 $html_output .= PMA_getHtmlForAttachedPrivilegesToTableSpecificColumn(
1005 $columns, $row
1008 // privs that are not attached to a specific column
1009 $html_output .= '<div class="item">' . "\n"
1010 . PMA_getHtmlForNotAttachedPrivilegesToTableSpecificColumn($row)
1011 . '</div>' . "\n";
1013 // for Safari 2.0.2
1014 $html_output .= '<div class="clearfloat"></div>' . "\n";
1016 return $html_output;
1020 * Get HTML snippet for privileges that are attached to a specific column
1022 * @param array $columns columns array
1023 * @param array $row first row from result or boolean false
1025 * @return string $html_output
1027 function PMA_getHtmlForAttachedPrivilegesToTableSpecificColumn($columns, $row)
1029 $html_output = PMA_getHtmlForColumnPrivileges(
1030 $columns, $row, 'Select_priv', 'SELECT',
1031 'select', __('Allows reading data.'), 'Select'
1034 $html_output .= PMA_getHtmlForColumnPrivileges(
1035 $columns, $row, 'Insert_priv', 'INSERT',
1036 'insert', __('Allows inserting and replacing data.'), 'Insert'
1039 $html_output .= PMA_getHtmlForColumnPrivileges(
1040 $columns, $row, 'Update_priv', 'UPDATE',
1041 'update', __('Allows changing data.'), 'Update'
1044 $html_output .= PMA_getHtmlForColumnPrivileges(
1045 $columns, $row, 'References_priv', 'REFERENCES', 'references',
1046 __('Has no effect in this MySQL version.'), 'References'
1048 return $html_output;
1052 * Get HTML for privileges that are not attached to a specific column
1054 * @param array $row first row from result or boolean false
1056 * @return string $html_output
1058 function PMA_getHtmlForNotAttachedPrivilegesToTableSpecificColumn($row)
1060 $html_output = '';
1062 foreach ($row as $current_grant => $current_grant_value) {
1063 $grant_type = substr($current_grant, 0, -5);
1064 if (in_array($grant_type, array('Select', 'Insert', 'Update', 'References'))
1066 continue;
1068 // make a substitution to match the messages variables;
1069 // also we must substitute the grant we get, because we can't generate
1070 // a form variable containing blanks (those would get changed to
1071 // an underscore when receiving the POST)
1072 if ($current_grant == 'Create View_priv') {
1073 $tmp_current_grant = 'CreateView_priv';
1074 $current_grant = 'Create_view_priv';
1075 } elseif ($current_grant == 'Show view_priv') {
1076 $tmp_current_grant = 'ShowView_priv';
1077 $current_grant = 'Show_view_priv';
1078 } else {
1079 $tmp_current_grant = $current_grant;
1082 $html_output .= '<div class="item">' . "\n"
1083 . '<input type="checkbox"'
1084 . ' name="' . $current_grant . '" id="checkbox_' . $current_grant
1085 . '" value="Y" '
1086 . ($current_grant_value == 'Y' ? 'checked="checked" ' : '')
1087 . 'title="';
1089 $html_output .= (isset($GLOBALS[
1090 'strPrivDesc' . /*overload*/mb_substr(
1091 $tmp_current_grant,
1093 (/*overload*/mb_strlen($tmp_current_grant) - 5)
1096 ? $GLOBALS[
1097 'strPrivDesc' . /*overload*/mb_substr(
1098 $tmp_current_grant,
1100 (/*overload*/mb_strlen($tmp_current_grant) - 5)
1103 : $GLOBALS[
1104 'strPrivDesc' . /*overload*/mb_substr(
1105 $tmp_current_grant,
1107 (/*overload*/mb_strlen($tmp_current_grant) - 5)
1108 ) . 'Tbl'
1111 . '"/>' . "\n";
1113 $html_output .= '<label for="checkbox_' . $current_grant
1114 . '"><code><dfn title="'
1115 . (isset($GLOBALS[
1116 'strPrivDesc' . /*overload*/mb_substr(
1117 $tmp_current_grant,
1122 ? $GLOBALS[
1123 'strPrivDesc' . /*overload*/mb_substr(
1124 $tmp_current_grant,
1129 : $GLOBALS[
1130 'strPrivDesc' . /*overload*/mb_substr(
1131 $tmp_current_grant,
1134 ) . 'Tbl'
1137 . '">'
1138 . /*overload*/mb_strtoupper(
1139 /*overload*/mb_substr(
1140 $current_grant,
1145 . '</dfn></code></label>' . "\n"
1146 . '</div>' . "\n";
1147 } // end foreach ()
1148 return $html_output;
1152 * Get HTML for global or database specific privileges
1154 * @param string $db the database
1155 * @param string $table the table
1156 * @param string $row first row from result or boolean false
1158 * @return string $html_output
1160 function PMA_getHtmlForGlobalOrDbSpecificPrivs($db, $table, $row)
1162 $privTable_names = array(0 => __('Data'),
1163 1 => __('Structure'),
1164 2 => __('Administration')
1166 $privTable = array();
1167 // d a t a
1168 $privTable[0] = PMA_getDataPrivilegeTable($db);
1170 // s t r u c t u r e
1171 $privTable[1] = PMA_getStructurePrivilegeTable($table, $row);
1173 // a d m i n i s t r a t i o n
1174 $privTable[2] = PMA_getAdministrationPrivilegeTable($db);
1176 $html_output = '<input type="hidden" name="grant_count" value="'
1177 . (count($privTable[0])
1178 + count($privTable[1])
1179 + count($privTable[2])
1180 - (isset($row['Grant_priv']) ? 1 : 0)
1182 . '" />';
1183 if ($db == '*') {
1184 $legend = __('Global privileges');
1185 $menu_label = __('Global');
1186 } else if ($table == '*') {
1187 $legend = __('Database-specific privileges');
1188 $menu_label = __('Database');
1189 } else {
1190 $legend = __('Table-specific privileges');
1191 $menu_label = __('Table');
1193 $html_output .= '<fieldset id="fieldset_user_global_rights">'
1194 . '<legend data-submenu-label="' . $menu_label . '">' . $legend
1195 . '<input type="checkbox" id="addUsersForm_checkall" '
1196 . 'class="checkall_box" title="' . __('Check All') . '" /> '
1197 . '<label for="addUsersForm_checkall">' . __('Check All') . '</label> '
1198 . '</legend>'
1199 . '<p><small><i>'
1200 . __('Note: MySQL privilege names are expressed in English.')
1201 . '</i></small></p>';
1203 // Output the Global privilege tables with checkboxes
1204 $html_output .= PMA_getHtmlForGlobalPrivTableWithCheckboxes(
1205 $privTable, $privTable_names, $row
1208 // The "Resource limits" box is not displayed for db-specific privs
1209 if ($db == '*') {
1210 $html_output .= PMA_getHtmlForResourceLimits($row);
1211 $html_output .= PMA_getHtmlForRequires($row);
1213 // for Safari 2.0.2
1214 $html_output .= '<div class="clearfloat"></div>';
1216 return $html_output;
1220 * Get data privilege table as an array
1222 * @param string $db the database
1224 * @return string data privilege table
1226 function PMA_getDataPrivilegeTable($db)
1228 $data_privTable = array(
1229 array('Select', 'SELECT', __('Allows reading data.')),
1230 array('Insert', 'INSERT', __('Allows inserting and replacing data.')),
1231 array('Update', 'UPDATE', __('Allows changing data.')),
1232 array('Delete', 'DELETE', __('Allows deleting data.'))
1234 if ($db == '*') {
1235 $data_privTable[]
1236 = array('File',
1237 'FILE',
1238 __('Allows importing data from and exporting data into files.')
1241 return $data_privTable;
1245 * Get structure privilege table as an array
1247 * @param string $table the table
1248 * @param array $row first row from result or boolean false
1250 * @return string structure privilege table
1252 function PMA_getStructurePrivilegeTable($table, $row)
1254 $structure_privTable = array(
1255 array('Create',
1256 'CREATE',
1257 ($table == '*'
1258 ? __('Allows creating new databases and tables.')
1259 : __('Allows creating new tables.')
1262 array('Alter',
1263 'ALTER',
1264 __('Allows altering the structure of existing tables.')
1266 array('Index', 'INDEX', __('Allows creating and dropping indexes.')),
1267 array('Drop',
1268 'DROP',
1269 ($table == '*'
1270 ? __('Allows dropping databases and tables.')
1271 : __('Allows dropping tables.')
1274 array('Create_tmp_table',
1275 'CREATE TEMPORARY TABLES',
1276 __('Allows creating temporary tables.')
1278 array('Show_view',
1279 'SHOW VIEW',
1280 __('Allows performing SHOW CREATE VIEW queries.')
1282 array('Create_routine',
1283 'CREATE ROUTINE',
1284 __('Allows creating stored routines.')
1286 array('Alter_routine',
1287 'ALTER ROUTINE',
1288 __('Allows altering and dropping stored routines.')
1290 array('Execute', 'EXECUTE', __('Allows executing stored routines.')),
1292 // this one is for a db-specific priv: Create_view_priv
1293 if (isset($row['Create_view_priv'])) {
1294 $structure_privTable[] = array('Create_view',
1295 'CREATE VIEW',
1296 __('Allows creating new views.')
1299 // this one is for a table-specific priv: Create View_priv
1300 if (isset($row['Create View_priv'])) {
1301 $structure_privTable[] = array('Create View',
1302 'CREATE VIEW',
1303 __('Allows creating new views.')
1306 if (isset($row['Event_priv'])) {
1307 // MySQL 5.1.6
1308 $structure_privTable[] = array('Event',
1309 'EVENT',
1310 __('Allows to set up events for the event scheduler.')
1312 $structure_privTable[] = array('Trigger',
1313 'TRIGGER',
1314 __('Allows creating and dropping triggers.')
1317 return $structure_privTable;
1321 * Get administration privilege table as an array
1323 * @param string $db the table
1325 * @return string administration privilege table
1327 function PMA_getAdministrationPrivilegeTable($db)
1329 $adminPrivTable = array(
1330 array('Grant',
1331 'GRANT',
1333 'Allows adding users and privileges '
1334 . 'without reloading the privilege tables.'
1338 if ($db == '*') {
1339 $adminPrivTable[] = array('Super',
1340 'SUPER',
1342 'Allows connecting, even if maximum number '
1343 . 'of connections is reached; required for '
1344 . 'most administrative operations like '
1345 . 'setting global variables or killing threads of other users.'
1348 $adminPrivTable[] = array('Process',
1349 'PROCESS',
1350 __('Allows viewing processes of all users.')
1352 $adminPrivTable[] = array('Reload',
1353 'RELOAD',
1354 __('Allows reloading server settings and flushing the server\'s caches.')
1356 $adminPrivTable[] = array('Shutdown',
1357 'SHUTDOWN',
1358 __('Allows shutting down the server.')
1360 $adminPrivTable[] = array('Show_db',
1361 'SHOW DATABASES',
1362 __('Gives access to the complete list of databases.')
1365 $adminPrivTable[] = array('Lock_tables',
1366 'LOCK TABLES',
1367 __('Allows locking tables for the current thread.')
1369 $adminPrivTable[] = array('References',
1370 'REFERENCES',
1371 __('Has no effect in this MySQL version.')
1373 if ($db == '*') {
1374 $adminPrivTable[] = array('Repl_client',
1375 'REPLICATION CLIENT',
1376 __('Allows the user to ask where the slaves / masters are.')
1378 $adminPrivTable[] = array('Repl_slave',
1379 'REPLICATION SLAVE',
1380 __('Needed for the replication slaves.')
1382 $adminPrivTable[] = array('Create_user',
1383 'CREATE USER',
1384 __('Allows creating, dropping and renaming user accounts.')
1387 return $adminPrivTable;
1391 * Get HTML snippet for global privileges table with check boxes
1393 * @param array $privTable privileges table array
1394 * @param array $privTable_names names of the privilege tables
1395 * (Data, Structure, Administration)
1396 * @param array $row first row from result or boolean false
1398 * @return string $html_output
1400 function PMA_getHtmlForGlobalPrivTableWithCheckboxes(
1401 $privTable, $privTable_names, $row
1403 $html_output = '';
1404 foreach ($privTable as $i => $table) {
1405 $html_output .= '<fieldset>' . "\n"
1406 . '<legend>' . $privTable_names[$i] . '</legend>' . "\n";
1407 foreach ($table as $priv) {
1408 $html_output .= '<div class="item">' . "\n"
1409 . '<input type="checkbox" class="checkall"'
1410 . ' name="' . $priv[0] . '_priv" '
1411 . 'id="checkbox_' . $priv[0] . '_priv"'
1412 . ' value="Y" title="' . $priv[2] . '"'
1413 . ((isset($row[$priv[0] . '_priv'])
1414 && $row[$priv[0] . '_priv'] == 'Y')
1415 ? ' checked="checked"'
1416 : ''
1418 . '/>' . "\n"
1419 . '<label for="checkbox_' . $priv[0] . '_priv">'
1420 . '<code>'
1421 . PMA_formatPrivilege($priv, true)
1422 . '</code></label>' . "\n"
1423 . '</div>' . "\n";
1425 $html_output .= '</fieldset>' . "\n";
1427 return $html_output;
1431 * Displays the fields used by the "new user" form as well as the
1432 * "change login information / copy user" form.
1434 * @param string $mode are we creating a new user or are we just
1435 * changing one? (allowed values: 'new', 'change')
1437 * @global array $cfg the phpMyAdmin configuration
1438 * @global resource $user_link the database connection
1440 * @return string $html_output a HTML snippet
1442 function PMA_getHtmlForLoginInformationFields($mode = 'new')
1444 list($username_length, $hostname_length) = PMA_getUsernameAndHostnameLength();
1446 if (isset($GLOBALS['username'])
1447 && /*overload*/mb_strlen($GLOBALS['username']) === 0
1449 $GLOBALS['pred_username'] = 'any';
1451 $html_output = '<fieldset id="fieldset_add_user_login">' . "\n"
1452 . '<legend>' . __('Login Information') . '</legend>' . "\n"
1453 . '<div class="item">' . "\n"
1454 . '<label for="select_pred_username">' . "\n"
1455 . ' ' . __('User name:') . "\n"
1456 . '</label>' . "\n"
1457 . '<span class="options">' . "\n";
1459 $html_output .= '<select name="pred_username" id="select_pred_username" '
1460 . 'title="' . __('User name') . '"' . "\n";
1462 $html_output .= ' onchange="'
1463 . 'if (this.value == \'any\') {'
1464 . ' username.value = \'\'; '
1465 . ' user_exists_warning.style.display = \'none\'; '
1466 . ' username.required = false; '
1467 . '} else if (this.value == \'userdefined\') {'
1468 . ' username.focus(); username.select(); '
1469 . ' username.required = true; '
1470 . '}">' . "\n";
1472 $html_output .= '<option value="any"'
1473 . ((isset($GLOBALS['pred_username']) && $GLOBALS['pred_username'] == 'any')
1474 ? ' selected="selected"'
1475 : '') . '>'
1476 . __('Any user')
1477 . '</option>' . "\n";
1479 $html_output .= '<option value="userdefined"'
1480 . ((! isset($GLOBALS['pred_username'])
1481 || $GLOBALS['pred_username'] == 'userdefined'
1483 ? ' selected="selected"'
1484 : '') . '>'
1485 . __('Use text field')
1486 . ':</option>' . "\n";
1488 $html_output .= '</select>' . "\n"
1489 . '</span>' . "\n";
1491 $html_output .= '<input type="text" name="username" class="autofocus"'
1492 . ' maxlength="' . $username_length . '" title="' . __('User name') . '"'
1493 . (empty($GLOBALS['username'])
1494 ? ''
1495 : ' value="' . htmlspecialchars(
1496 isset($GLOBALS['new_username'])
1497 ? $GLOBALS['new_username']
1498 : $GLOBALS['username']
1499 ) . '"'
1501 . ' onchange="pred_username.value = \'userdefined\'; this.required = true;" '
1502 . ((! isset($GLOBALS['pred_username'])
1503 || $GLOBALS['pred_username'] == 'userdefined'
1505 ? 'required="required"'
1506 : '') . ' />' . "\n";
1508 $html_output .= '<div id="user_exists_warning"'
1509 . ' name="user_exists_warning" style="display:none;">'
1510 . PMA_Message::notice(
1512 'An account already exists with the same username '
1513 . 'but possibly a different hostname.'
1515 )->getDisplay()
1516 . '</div>';
1517 $html_output .= '</div>';
1519 $html_output .= '<div class="item">' . "\n"
1520 . '<label for="select_pred_hostname">' . "\n"
1521 . ' ' . __('Host:') . "\n"
1522 . '</label>' . "\n";
1524 $html_output .= '<span class="options">' . "\n"
1525 . ' <select name="pred_hostname" id="select_pred_hostname" '
1526 . 'title="' . __('Host') . '"' . "\n";
1527 $_current_user = $GLOBALS['dbi']->fetchValue('SELECT USER();');
1528 if (! empty($_current_user)) {
1529 $thishost = str_replace(
1530 "'",
1532 /*overload*/mb_substr(
1533 $_current_user,
1534 (/*overload*/mb_strrpos($_current_user, '@') + 1)
1537 if ($thishost == 'localhost' || $thishost == '127.0.0.1') {
1538 unset($thishost);
1541 $html_output .= ' onchange="'
1542 . 'if (this.value == \'any\') { '
1543 . ' hostname.value = \'%\'; '
1544 . '} else if (this.value == \'localhost\') { '
1545 . ' hostname.value = \'localhost\'; '
1546 . '} '
1547 . (empty($thishost)
1548 ? ''
1549 : 'else if (this.value == \'thishost\') { '
1550 . ' hostname.value = \'' . addslashes(htmlspecialchars($thishost))
1551 . '\'; '
1552 . '} '
1554 . 'else if (this.value == \'hosttable\') { '
1555 . ' hostname.value = \'\'; '
1556 . ' hostname.required = false; '
1557 . '} else if (this.value == \'userdefined\') {'
1558 . ' hostname.focus(); hostname.select(); '
1559 . ' hostname.required = true; '
1560 . '}">' . "\n";
1561 unset($_current_user);
1563 // when we start editing a user, $GLOBALS['pred_hostname'] is not defined
1564 if (! isset($GLOBALS['pred_hostname']) && isset($GLOBALS['hostname'])) {
1565 switch (/*overload*/mb_strtolower($GLOBALS['hostname'])) {
1566 case 'localhost':
1567 case '127.0.0.1':
1568 $GLOBALS['pred_hostname'] = 'localhost';
1569 break;
1570 case '%':
1571 $GLOBALS['pred_hostname'] = 'any';
1572 break;
1573 default:
1574 $GLOBALS['pred_hostname'] = 'userdefined';
1575 break;
1578 $html_output .= '<option value="any"'
1579 . ((isset($GLOBALS['pred_hostname'])
1580 && $GLOBALS['pred_hostname'] == 'any'
1582 ? ' selected="selected"'
1583 : '') . '>'
1584 . __('Any host')
1585 . '</option>' . "\n"
1586 . '<option value="localhost"'
1587 . ((isset($GLOBALS['pred_hostname'])
1588 && $GLOBALS['pred_hostname'] == 'localhost'
1590 ? ' selected="selected"'
1591 : '') . '>'
1592 . __('Local')
1593 . '</option>' . "\n";
1594 if (! empty($thishost)) {
1595 $html_output .= '<option value="thishost"'
1596 . ((isset($GLOBALS['pred_hostname'])
1597 && $GLOBALS['pred_hostname'] == 'thishost'
1599 ? ' selected="selected"'
1600 : '') . '>'
1601 . __('This Host')
1602 . '</option>' . "\n";
1604 unset($thishost);
1605 $html_output .= '<option value="hosttable"'
1606 . ((isset($GLOBALS['pred_hostname'])
1607 && $GLOBALS['pred_hostname'] == 'hosttable'
1609 ? ' selected="selected"'
1610 : '') . '>'
1611 . __('Use Host Table')
1612 . '</option>' . "\n";
1614 $html_output .= '<option value="userdefined"'
1615 . ((isset($GLOBALS['pred_hostname'])
1616 && $GLOBALS['pred_hostname'] == 'userdefined'
1618 ? ' selected="selected"'
1619 : '') . '>'
1620 . __('Use text field:') . '</option>' . "\n"
1621 . '</select>' . "\n"
1622 . '</span>' . "\n";
1624 $html_output .= '<input type="text" name="hostname" maxlength="'
1625 . $hostname_length . '" value="'
1626 // use default value of '%' to match with the default 'Any host'
1627 . htmlspecialchars(isset($GLOBALS['hostname']) ? $GLOBALS['hostname'] : '%')
1628 . '" title="' . __('Host')
1629 . '" onchange="pred_hostname.value = \'userdefined\'; this.required = true;" '
1630 . ((isset($GLOBALS['pred_hostname'])
1631 && $GLOBALS['pred_hostname'] == 'userdefined'
1633 ? 'required="required"'
1634 : '')
1635 . ' />' . "\n"
1636 . PMA_Util::showHint(
1638 'When Host table is used, this field is ignored '
1639 . 'and values stored in Host table are used instead.'
1642 . '</div>' . "\n";
1644 $html_output .= '<div class="item">' . "\n"
1645 . '<label for="select_pred_password">' . "\n"
1646 . ' ' . __('Password:') . "\n"
1647 . '</label>' . "\n"
1648 . '<span class="options">' . "\n"
1649 . '<select name="pred_password" id="select_pred_password" title="'
1650 . __('Password') . '"' . "\n";
1652 $html_output .= ' onchange="'
1653 . 'if (this.value == \'none\') { '
1654 . ' pma_pw.value = \'\'; pma_pw2.value = \'\'; '
1655 . ' pma_pw.required = false; pma_pw2.required = false; '
1656 . '} else if (this.value == \'userdefined\') { '
1657 . ' pma_pw.focus(); pma_pw.select(); '
1658 . ' pma_pw.required = true; pma_pw2.required = true; '
1659 . '} else { '
1660 . ' pma_pw.required = false; pma_pw2.required = false; '
1661 . '}">' . "\n"
1662 . ($mode == 'change' ? '<option value="keep" selected="selected">'
1663 . __('Do not change the password')
1664 . '</option>' . "\n" : '')
1665 . '<option value="none"';
1667 if (isset($GLOBALS['username']) && $mode != 'change') {
1668 $html_output .= ' selected="selected"';
1670 $html_output .= '>' . __('No Password') . '</option>' . "\n"
1671 . '<option value="userdefined"'
1672 . (isset($GLOBALS['username']) ? '' : ' selected="selected"') . '>'
1673 . __('Use text field')
1674 . ':</option>' . "\n"
1675 . '</select>' . "\n"
1676 . '</span>' . "\n"
1677 . '<input type="password" id="text_pma_pw" name="pma_pw" '
1678 . 'title="' . __('Password') . '" '
1679 . 'onchange="pred_password.value = \'userdefined\'; this.required = true; pma_pw2.required = true;" '
1680 . (isset($GLOBALS['username']) ? '' : 'required="required"')
1681 . '/>' . "\n"
1682 . '</div>' . "\n";
1684 $html_output .= '<div class="item" '
1685 . 'id="div_element_before_generate_password">' . "\n"
1686 . '<label for="text_pma_pw2">' . "\n"
1687 . ' ' . __('Re-type:') . "\n"
1688 . '</label>' . "\n"
1689 . '<span class="options">&nbsp;</span>' . "\n"
1690 . '<input type="password" name="pma_pw2" id="text_pma_pw2" '
1691 . 'title="' . __('Re-type') . '" '
1692 . 'onchange="pred_password.value = \'userdefined\'; this.required = true; pma_pw.required = true;" '
1693 . (isset($GLOBALS['username']) ? '' : 'required="required"')
1694 . '/>' . "\n"
1695 . '</div>' . "\n"
1696 // Generate password added here via jQuery
1697 . '</fieldset>' . "\n";
1699 return $html_output;
1700 } // end of the 'PMA_displayUserAndHostFields()' function
1703 * Get username and hostname length
1705 * @return array username length and hostname length
1707 function PMA_getUsernameAndHostnameLength()
1709 /* Fallback values */
1710 $username_length = 16;
1711 $hostname_length = 41;
1713 /* Try to get real lengths from the database */
1714 $fields_info = $GLOBALS['dbi']->fetchResult(
1715 'SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH '
1716 . 'FROM information_schema.columns '
1717 . "WHERE table_schema = 'mysql' AND table_name = 'user' "
1718 . "AND COLUMN_NAME IN ('User', 'Host')"
1720 foreach ($fields_info as $val) {
1721 if ($val['COLUMN_NAME'] == 'User') {
1722 $username_length = $val['CHARACTER_MAXIMUM_LENGTH'];
1723 } elseif ($val['COLUMN_NAME'] == 'Host') {
1724 $hostname_length = $val['CHARACTER_MAXIMUM_LENGTH'];
1727 return array($username_length, $hostname_length);
1731 * Returns all the grants for a certain user on a certain host
1732 * Used in the export privileges for all users section
1734 * @param string $user User name
1735 * @param string $host Host name
1737 * @return string containing all the grants text
1739 function PMA_getGrants($user, $host)
1741 $grants = $GLOBALS['dbi']->fetchResult(
1742 "SHOW GRANTS FOR '"
1743 . PMA_Util::sqlAddSlashes($user) . "'@'"
1744 . PMA_Util::sqlAddSlashes($host) . "'"
1746 $response = '';
1747 foreach ($grants as $one_grant) {
1748 $response .= $one_grant . ";\n\n";
1750 return $response;
1751 } // end of the 'PMA_getGrants()' function
1754 * Update password and get message for password updating
1756 * @param string $err_url error url
1757 * @param string $username username
1758 * @param string $hostname hostname
1760 * @return string $message success or error message after updating password
1762 function PMA_updatePassword($err_url, $username, $hostname)
1764 // similar logic in user_password.php
1765 $message = '';
1767 if (empty($_REQUEST['nopass'])
1768 && isset($_POST['pma_pw'])
1769 && isset($_POST['pma_pw2'])
1771 if ($_POST['pma_pw'] != $_POST['pma_pw2']) {
1772 $message = PMA_Message::error(__('The passwords aren\'t the same!'));
1773 } elseif (empty($_POST['pma_pw']) || empty($_POST['pma_pw2'])) {
1774 $message = PMA_Message::error(__('The password is empty!'));
1778 // here $nopass could be == 1
1779 if (empty($message)) {
1781 $hashing_function
1782 = (! empty($_REQUEST['pw_hash']) && $_REQUEST['pw_hash'] == 'old'
1783 ? 'OLD_'
1784 : ''
1786 . 'PASSWORD';
1788 // in $sql_query which will be displayed, hide the password
1789 $sql_query = 'SET PASSWORD FOR \''
1790 . PMA_Util::sqlAddSlashes($username)
1791 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\' = '
1792 . (($_POST['pma_pw'] == '')
1793 ? '\'\''
1794 : $hashing_function . '(\''
1795 . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
1797 $local_query = 'SET PASSWORD FOR \''
1798 . PMA_Util::sqlAddSlashes($username)
1799 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\' = '
1800 . (($_POST['pma_pw'] == '') ? '\'\'' : $hashing_function
1801 . '(\'' . PMA_Util::sqlAddSlashes($_POST['pma_pw']) . '\')');
1803 $GLOBALS['dbi']->tryQuery($local_query)
1804 or PMA_Util::mysqlDie(
1805 $GLOBALS['dbi']->getError(), $sql_query, false, $err_url
1807 $message = PMA_Message::success(
1808 __('The password for %s was changed successfully.')
1810 $message->addParam(
1811 '\'' . htmlspecialchars($username)
1812 . '\'@\'' . htmlspecialchars($hostname) . '\''
1815 return $message;
1819 * Revokes privileges and get message and SQL query for privileges revokes
1821 * @param string $dbname database name
1822 * @param string $tablename table name
1823 * @param string $username username
1824 * @param string $hostname host name
1826 * @return array ($message, $sql_query)
1828 function PMA_getMessageAndSqlQueryForPrivilegesRevoke($dbname,
1829 $tablename, $username, $hostname
1831 $db_and_table = PMA_wildcardEscapeForGrant($dbname, $tablename);
1833 $sql_query0 = 'REVOKE ALL PRIVILEGES ON ' . $db_and_table
1834 . ' FROM \''
1835 . PMA_Util::sqlAddSlashes($username) . '\'@\''
1836 . PMA_Util::sqlAddSlashes($hostname) . '\';';
1838 $sql_query1 = 'REVOKE GRANT OPTION ON ' . $db_and_table
1839 . ' FROM \'' . PMA_Util::sqlAddSlashes($username) . '\'@\''
1840 . PMA_Util::sqlAddSlashes($hostname) . '\';';
1842 $GLOBALS['dbi']->query($sql_query0);
1843 if (! $GLOBALS['dbi']->tryQuery($sql_query1)) {
1844 // this one may fail, too...
1845 $sql_query1 = '';
1847 $sql_query = $sql_query0 . ' ' . $sql_query1;
1848 $message = PMA_Message::success(
1849 __('You have revoked the privileges for %s.')
1851 $message->addParam(
1852 '\'' . htmlspecialchars($username)
1853 . '\'@\'' . htmlspecialchars($hostname) . '\''
1856 return array($message, $sql_query);
1860 * Get REQUIRE cluase
1862 * @return stirng REQUIRE clause
1864 function PMA_getRequireClause()
1866 $require_clause = "";
1867 if (isset($_POST['SSL_priv']) && $_POST['SSL_priv'] == 'Y') {
1868 if (isset($_POST['ssl_type']) && $_POST['ssl_type'] == 'specified') {
1869 $require = array();
1870 if (! empty($_POST['ssl_cipher'])) {
1871 $require[] = "CIPHER '"
1872 . PMA_Util::sqlAddSlashes($_POST['ssl_cipher']) . "'";
1874 if (! empty($_POST['x509_issuer'])) {
1875 $require[] = "ISSUER '"
1876 . PMA_Util::sqlAddSlashes($_POST['x509_issuer']) . "'";
1878 if (! empty($_POST['x509_subject'])) {
1879 $require[] = "SUBJECT '"
1880 . PMA_Util::sqlAddSlashes($_POST['x509_subject']) . "'";
1882 if (count($require)) {
1883 $require_clause = " REQUIRE " . implode(" AND ", $require);
1884 } else {
1885 $require_clause = " REQUIRE NONE";
1887 } elseif (isset($_POST['ssl_type']) && $_POST['ssl_type'] == 'X509') {
1888 $require_clause = " REQUIRE X509";
1889 } elseif (isset($_POST['ssl_type']) && $_POST['ssl_type'] == 'ANY') {
1890 $require_clause = " REQUIRE SSL";
1892 } else {
1893 $require_clause = " REQUIRE NONE";
1896 return $require_clause;
1900 * Get a WITH clause for 'update privileges' and 'add user'
1902 * @return string $sql_query
1904 function PMA_getWithClauseForAddUserAndUpdatePrivs()
1906 $sql_query = '';
1907 if (isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y') {
1908 $sql_query .= ' GRANT OPTION';
1910 if (isset($_POST['max_questions'])) {
1911 $max_questions = max(0, (int)$_POST['max_questions']);
1912 $sql_query .= ' MAX_QUERIES_PER_HOUR ' . $max_questions;
1914 if (isset($_POST['max_connections'])) {
1915 $max_connections = max(0, (int)$_POST['max_connections']);
1916 $sql_query .= ' MAX_CONNECTIONS_PER_HOUR ' . $max_connections;
1918 if (isset($_POST['max_updates'])) {
1919 $max_updates = max(0, (int)$_POST['max_updates']);
1920 $sql_query .= ' MAX_UPDATES_PER_HOUR ' . $max_updates;
1922 if (isset($_POST['max_user_connections'])) {
1923 $max_user_connections = max(0, (int)$_POST['max_user_connections']);
1924 $sql_query .= ' MAX_USER_CONNECTIONS ' . $max_user_connections;
1926 return ((!empty($sql_query)) ? ' WITH' . $sql_query : '');
1930 * Get HTML for addUsersForm, This function call if isset($_REQUEST['adduser'])
1932 * @param string $dbname database name
1934 * @return string HTML for addUserForm
1936 function PMA_getHtmlForAddUser($dbname)
1938 $html_output = '<h2>' . "\n"
1939 . PMA_Util::getIcon('b_usradd.png') . __('Add user') . "\n"
1940 . '</h2>' . "\n"
1941 . '<form name="usersForm" id="addUsersForm"'
1942 . ' onsubmit="return checkAddUser(this);"'
1943 . ' action="server_privileges.php" method="post" autocomplete="off" >' . "\n"
1944 . PMA_URL_getHiddenInputs('', '')
1945 . PMA_getHtmlForLoginInformationFields('new');
1947 $html_output .= '<fieldset id="fieldset_add_user_database">' . "\n"
1948 . '<legend>' . __('Database for user') . '</legend>' . "\n";
1950 $html_output .= PMA_Util::getCheckbox(
1951 'createdb-1',
1952 __('Create database with same name and grant all privileges.'),
1953 false, false, 'createdb-1'
1955 $html_output .= '<br />' . "\n";
1956 $html_output .= PMA_Util::getCheckbox(
1957 'createdb-2',
1958 __('Grant all privileges on wildcard name (username\\_%).'),
1959 false, false, 'createdb-2'
1961 $html_output .= '<br />' . "\n";
1963 if (! empty($dbname) ) {
1964 $html_output .= PMA_Util::getCheckbox(
1965 'createdb-3',
1966 sprintf(
1967 __('Grant all privileges on database "%s".'),
1968 htmlspecialchars($dbname)
1970 true,
1971 false,
1972 'createdb-3'
1974 $html_output .= '<input type="hidden" name="dbname" value="'
1975 . htmlspecialchars($dbname) . '" />' . "\n";
1976 $html_output .= '<br />' . "\n";
1979 $html_output .= '</fieldset>' . "\n";
1980 if ($GLOBALS['is_grantuser']) {
1981 $html_output .= PMA_getHtmlToDisplayPrivilegesTable('*', '*', false);
1983 $html_output .= '<fieldset id="fieldset_add_user_footer" class="tblFooters">'
1984 . "\n"
1985 . '<input type="hidden" name="adduser_submit" value="1" />' . "\n"
1986 . '<input type="submit" id="adduser_submit" value="' . __('Go') . '" />'
1987 . "\n"
1988 . '</fieldset>' . "\n"
1989 . '</form>' . "\n";
1991 return $html_output;
1995 * Get the list of privileges and list of compared privileges as strings
1996 * and return a array that contains both strings
1998 * @return array $list_of_privileges, $list_of_compared_privileges
2000 function PMA_getListOfPrivilegesAndComparedPrivileges()
2002 $list_of_privileges
2003 = '`User`, '
2004 . '`Host`, '
2005 . '`Select_priv`, '
2006 . '`Insert_priv`, '
2007 . '`Update_priv`, '
2008 . '`Delete_priv`, '
2009 . '`Create_priv`, '
2010 . '`Drop_priv`, '
2011 . '`Grant_priv`, '
2012 . '`Index_priv`, '
2013 . '`Alter_priv`, '
2014 . '`References_priv`, '
2015 . '`Create_tmp_table_priv`, '
2016 . '`Lock_tables_priv`, '
2017 . '`Create_view_priv`, '
2018 . '`Show_view_priv`, '
2019 . '`Create_routine_priv`, '
2020 . '`Alter_routine_priv`, '
2021 . '`Execute_priv`';
2023 $listOfComparedPrivs
2024 = '`Select_priv` = \'N\''
2025 . ' AND `Insert_priv` = \'N\''
2026 . ' AND `Update_priv` = \'N\''
2027 . ' AND `Delete_priv` = \'N\''
2028 . ' AND `Create_priv` = \'N\''
2029 . ' AND `Drop_priv` = \'N\''
2030 . ' AND `Grant_priv` = \'N\''
2031 . ' AND `References_priv` = \'N\''
2032 . ' AND `Create_tmp_table_priv` = \'N\''
2033 . ' AND `Lock_tables_priv` = \'N\''
2034 . ' AND `Create_view_priv` = \'N\''
2035 . ' AND `Show_view_priv` = \'N\''
2036 . ' AND `Create_routine_priv` = \'N\''
2037 . ' AND `Alter_routine_priv` = \'N\''
2038 . ' AND `Execute_priv` = \'N\'';
2040 $list_of_privileges .=
2041 ', `Event_priv`, '
2042 . '`Trigger_priv`';
2043 $listOfComparedPrivs .=
2044 ' AND `Event_priv` = \'N\''
2045 . ' AND `Trigger_priv` = \'N\'';
2046 return array($list_of_privileges, $listOfComparedPrivs);
2050 * Get the HTML for user form and check the privileges for a particular database.
2052 * @param string $db database name
2054 * @return string $html_output
2056 function PMA_getHtmlForSpecificDbPrivileges($db)
2058 $html_output = '';
2059 if ($GLOBALS['is_superuser']) {
2060 // check the privileges for a particular database.
2061 $html_output = '<form id="usersForm" action="server_privileges.php">';
2062 $html_output .= PMA_URL_getHiddenInputs($db);
2063 $html_output .= '<fieldset>';
2064 $html_output .= '<legend>' . "\n"
2065 . PMA_Util::getIcon('b_usrcheck.png')
2066 . ' '
2067 . sprintf(
2068 __('Users having access to "%s"'),
2069 '<a href="' . $GLOBALS['cfg']['DefaultTabDatabase']
2070 . PMA_URL_getCommon(array('db' => $db)) . '">'
2071 . htmlspecialchars($db)
2072 . '</a>'
2074 . "\n"
2075 . '</legend>' . "\n";
2077 $html_output .= '<table id="dbspecificuserrights" class="data">';
2078 $html_output .= PMA_getHtmlForPrivsTableHead();
2079 $privMap = PMA_getPrivMap($db);
2080 $html_output .= PMA_getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db);
2081 $html_output .= '</table>';
2083 $html_output .= '<div style="float:left;">';
2084 $html_output .= PMA_Util::getWithSelected(
2085 $GLOBALS['pmaThemeImage'], $GLOBALS['text_dir'], "usersForm"
2087 $html_output .= PMA_Util::getButtonOrImage(
2088 'submit_mult', 'mult_submit', 'submit_mult_export',
2089 __('Export'), 'b_tblexport.png', 'export'
2092 $html_output .= '</fieldset>';
2093 $html_output .= '</form>';
2094 } else {
2095 $html_output .= PMA_getHtmlForViewUsersError();
2098 if ($GLOBALS['is_ajax_request'] == true
2099 && empty($_REQUEST['ajax_page_request'])
2101 $message = PMA_Message::success(__('User has been added.'));
2102 $response = PMA_Response::getInstance();
2103 $response->addJSON('message', $message);
2104 $response->addJSON('user_form', $html_output);
2105 exit;
2106 } else {
2107 // Offer to create a new user for the current database
2108 $html_output .= PMA_getAddUserHtmlFieldset($db);
2110 return $html_output;
2114 * Get the HTML for user form and check the privileges for a particular table.
2116 * @param string $db database name
2117 * @param string $table table name
2119 * @return string $html_output
2121 function PMA_getHtmlForSpecificTablePrivileges($db, $table)
2123 $html_output = '';
2124 if ($GLOBALS['is_superuser']) {
2125 // check the privileges for a particular table.
2126 $html_output = '<form id="usersForm" action="server_privileges.php">';
2127 $html_output .= PMA_URL_getHiddenInputs($db, $table);
2128 $html_output .= '<fieldset>';
2129 $html_output .= '<legend>'
2130 . PMA_Util::getIcon('b_usrcheck.png')
2131 . sprintf(
2132 __('Users having access to "%s"'),
2133 '<a href="' . $GLOBALS['cfg']['DefaultTabTable']
2134 . PMA_URL_getCommon(
2135 array(
2136 'db' => $db,
2137 'table' => $table,
2139 ) . '">'
2140 . htmlspecialchars($db) . '.' . htmlspecialchars($table)
2141 . '</a>'
2143 . '</legend>';
2145 $html_output .= '<table id="tablespecificuserrights" class="data">';
2146 $html_output .= PMA_getHtmlForPrivsTableHead();
2147 $privMap = PMA_getPrivMap($db);
2148 $sql_query = "SELECT `User`, `Host`, `Db`,"
2149 . " 't' AS `Type`, `Table_name`, `Table_priv`"
2150 . " FROM `mysql`.`tables_priv`"
2151 . " WHERE '" . PMA_Util::sqlAddSlashes($db) . "' LIKE `Db`"
2152 . " AND '" . PMA_Util::sqlAddSlashes($table) . "' LIKE `Table_name`"
2153 . " AND NOT (`Table_priv` = '' AND Column_priv = '')"
2154 . " ORDER BY `User` ASC, `Host` ASC, `Db` ASC, `Table_priv` ASC;";
2155 $res = $GLOBALS['dbi']->query($sql_query);
2156 PMA_mergePrivMapFromResult($privMap, $res);
2157 $html_output .= PMA_getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db);
2158 $html_output .= '</table>';
2160 $html_output .= '<div style="float:left;">';
2161 $html_output .= PMA_Util::getWithSelected(
2162 $GLOBALS['pmaThemeImage'], $GLOBALS['text_dir'], "usersForm"
2164 $html_output .= PMA_Util::getButtonOrImage(
2165 'submit_mult', 'mult_submit', 'submit_mult_export',
2166 __('Export'), 'b_tblexport.png', 'export'
2169 $html_output .= '</fieldset>';
2170 $html_output .= '</form>';
2171 } else {
2172 $html_output .= PMA_getHtmlForViewUsersError();
2174 // Offer to create a new user for the current database
2175 $html_output .= PMA_getAddUserHtmlFieldset($db, $table);
2176 return $html_output;
2180 * gets privilege map
2182 * @param string $db the database
2184 * @return array $privMap the privilege map
2186 function PMA_getPrivMap($db)
2188 list($listOfPrivs, $listOfComparedPrivs)
2189 = PMA_getListOfPrivilegesAndComparedPrivileges();
2190 $sql_query
2191 = "("
2192 . " SELECT " . $listOfPrivs . ", '*' AS `Db`, 'g' AS `Type`"
2193 . " FROM `mysql`.`user`"
2194 . " WHERE NOT (" . $listOfComparedPrivs . ")"
2195 . ")"
2196 . " UNION "
2197 . "("
2198 . " SELECT " . $listOfPrivs . ", `Db`, 'd' AS `Type`"
2199 . " FROM `mysql`.`db`"
2200 . " WHERE '" . PMA_Util::sqlAddSlashes($db) . "' LIKE `Db`"
2201 . " AND NOT (" . $listOfComparedPrivs . ")"
2202 . ")"
2203 . " ORDER BY `User` ASC, `Host` ASC, `Db` ASC;";
2204 $res = $GLOBALS['dbi']->query($sql_query);
2205 $privMap = array();
2206 PMA_mergePrivMapFromResult($privMap, $res);
2207 return $privMap;
2211 * merge privilege map and rows from resultset
2213 * @param array &$privMap the privilege map reference
2214 * @param object $result the resultset of query
2216 * @return void
2218 function PMA_mergePrivMapFromResult(&$privMap, $result)
2220 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
2221 $user = $row['User'];
2222 $host = $row['Host'];
2223 if (! isset($privMap[$user])) {
2224 $privMap[$user] = array();
2226 if (! isset($privMap[$user][$host])) {
2227 $privMap[$user][$host] = array();
2229 $privMap[$user][$host][] = $row;
2234 * Get HTML snippet for privileges table head
2236 * @return string $html_output
2238 function PMA_getHtmlForPrivsTableHead()
2240 return '<thead>'
2241 . '<tr>'
2242 . '<th></th>'
2243 . '<th>' . __('User') . '</th>'
2244 . '<th>' . __('Host') . '</th>'
2245 . '<th>' . __('Type') . '</th>'
2246 . '<th>' . __('Privileges') . '</th>'
2247 . '<th>' . __('Grant') . '</th>'
2248 . '<th>' . __('Action') . '</th>'
2249 . '</tr>'
2250 . '</thead>';
2254 * Get HTML error for View Users form
2255 * For non superusers such as grant/create users
2257 * @return string $html_output
2259 function PMA_getHtmlForViewUsersError()
2261 return PMA_Message::error(
2262 __('Not enough privilege to view users.')
2263 )->getDisplay();
2267 * Get HTML snippet for table body of specific database or table privileges
2269 * @param array $privMap privilege map
2270 * @param string $db database
2272 * @return string $html_output
2274 function PMA_getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db)
2276 $html_output = '<tbody>';
2277 $index_checkbox = 0;
2278 $odd_row = true;
2279 if (empty($privMap)) {
2280 $html_output .= '<tr class="odd">'
2281 . '<td colspan="6">'
2282 . __('No user found.')
2283 . '</td>'
2284 . '</tr>'
2285 . '</tbody>';
2286 return $html_output;
2289 foreach ($privMap as $current_user => $val) {
2290 foreach ($val as $current_host => $current_privileges) {
2291 $nbPrivileges = count($current_privileges);
2292 $html_output .= '<tr class="noclick '
2293 . ($odd_row ? 'odd' : 'even') . '">';
2295 $value = htmlspecialchars($current_user . '&amp;#27;' . $current_host);
2296 $html_output .= '<td';
2297 if ($nbPrivileges > 1) {
2298 $html_output .= ' rowspan="' . $nbPrivileges . '"';
2300 $html_output .= '>';
2301 $html_output .= '<input type="checkbox" class="checkall" name="selected_usr[]" '
2302 . 'id="checkbox_sel_users_' . ($index_checkbox++) . '" '
2303 . 'value="' . $value . '" /></td>' . "\n";
2305 // user
2306 $html_output .= '<td';
2307 if ($nbPrivileges > 1) {
2308 $html_output .= ' rowspan="' . $nbPrivileges . '"';
2310 $html_output .= '>';
2311 if (empty($current_user)) {
2312 $html_output .= '<span style="color: #FF0000">'
2313 . __('Any') . '</span>';
2314 } else {
2315 $html_output .= htmlspecialchars($current_user);
2317 $html_output .= '</td>';
2319 // host
2320 $html_output .= '<td';
2321 if ($nbPrivileges > 1) {
2322 $html_output .= ' rowspan="' . $nbPrivileges . '"';
2324 $html_output .= '>';
2325 $html_output .= htmlspecialchars($current_host);
2326 $html_output .= '</td>';
2328 $html_output .= PMA_getHtmlListOfPrivs(
2329 $db, $current_privileges, $current_user,
2330 $current_host, $odd_row
2333 $odd_row = ! $odd_row;
2336 $html_output .= '</tbody>';
2338 return $html_output;
2342 * Get HTML to display privileges
2344 * @param string $db Database name
2345 * @param array $current_privileges List of privileges
2346 * @param string $current_user Current user
2347 * @param string $current_host Current host
2348 * @param boolean $odd_row Current row is odd
2350 * @return string HTML to display privileges
2352 function PMA_getHtmlListOfPrivs(
2353 $db, $current_privileges, $current_user,
2354 $current_host, $odd_row
2356 $nbPrivileges = count($current_privileges);
2357 $html_output = null;
2358 for ($i = 0; $i < $nbPrivileges; $i++) {
2359 $current = $current_privileges[$i];
2361 // type
2362 $html_output .= '<td>';
2363 if ($current['Type'] == 'g') {
2364 $html_output .= __('global');
2365 } elseif ($current['Type'] == 'd') {
2366 if ($current['Db'] == PMA_Util::escapeMysqlWildcards($db)) {
2367 $html_output .= __('database-specific');
2368 } else {
2369 $html_output .= __('wildcard') . ': '
2370 . '<code>'
2371 . htmlspecialchars($current['Db'])
2372 . '</code>';
2374 } elseif ($current['Type'] == 't') {
2375 $html_output .= __('table-specific');
2377 $html_output .= '</td>';
2379 // privileges
2380 $html_output .= '<td>';
2381 if (isset($current['Table_name'])) {
2382 $privList = explode(',', $current['Table_priv']);
2383 $privs = array();
2384 $grantsArr = PMA_getTableGrantsArray();
2385 foreach ($grantsArr as $grant) {
2386 $privs[$grant[0]] = 'N';
2387 foreach ($privList as $priv) {
2388 if ($grant[0] == $priv) {
2389 $privs[$grant[0]] = 'Y';
2393 $html_output .= '<code>'
2394 . join(
2395 ',',
2396 PMA_extractPrivInfo($privs, true, true)
2398 . '</code>';
2399 } else {
2400 $html_output .= '<code>'
2401 . join(
2402 ',',
2403 PMA_extractPrivInfo($current, true, false)
2405 . '</code>';
2407 $html_output .= '</td>';
2409 // grant
2410 $html_output .= '<td>';
2411 $containsGrant = false;
2412 if (isset($current['Table_name'])) {
2413 $privList = explode(',', $current['Table_priv']);
2414 foreach ($privList as $priv) {
2415 if ($priv == 'Grant') {
2416 $containsGrant = true;
2419 } else {
2420 $containsGrant = $current['Grant_priv'] == 'Y';
2422 $html_output .= ($containsGrant ? __('Yes') : __('No'));
2423 $html_output .= '</td>';
2425 // action
2426 $html_output .= '<td>';
2427 if ($GLOBALS['is_grantuser']) {
2428 $specific_db = (isset($current['Db']) && $current['Db'] != '*')
2429 ? $current['Db'] : '';
2430 $specific_table = (isset($current['Table_name'])
2431 && $current['Table_name'] != '*')
2432 ? $current['Table_name'] : '';
2433 $html_output .= PMA_getUserLink(
2434 'edit',
2435 $current_user,
2436 $current_host,
2437 $specific_db,
2438 $specific_table
2441 $html_output .= '</td>';
2443 $html_output .= '</tr>';
2444 if (($i + 1) < $nbPrivileges) {
2445 $html_output .= '<tr class="noclick '
2446 . ($odd_row ? 'odd' : 'even') . '">';
2449 return $html_output;
2453 * Returns edit, revoke or export link for a user.
2455 * @param string $linktype The link type (edit | revoke | export)
2456 * @param string $username User name
2457 * @param string $hostname Host name
2458 * @param string $dbname Database name
2459 * @param string $tablename Table name
2460 * @param string $initial Initial value
2462 * @return string HTML code with link
2464 function PMA_getUserLink(
2465 $linktype, $username, $hostname, $dbname = '', $tablename = '', $initial = ''
2467 $html = '<a';
2468 switch($linktype) {
2469 case 'edit':
2470 $html .= ' class="edit_user_anchor"';
2471 break;
2472 case 'export':
2473 $html .= ' class="export_user_anchor ajax"';
2474 break;
2476 $params = array(
2477 'username' => $username,
2478 'hostname' => $hostname
2480 switch($linktype) {
2481 case 'edit':
2482 $params['dbname'] = $dbname;
2483 $params['tablename'] = $tablename;
2484 break;
2485 case 'revoke':
2486 $params['dbname'] = $dbname;
2487 $params['tablename'] = $tablename;
2488 $params['revokeall'] = 1;
2489 break;
2490 case 'export':
2491 $params['initial'] = $initial;
2492 $params['export'] = 1;
2493 break;
2496 $html .= ' href="server_privileges.php'
2497 . PMA_URL_getCommon($params)
2498 . '">';
2500 switch($linktype) {
2501 case 'edit':
2502 $html .= PMA_Util::getIcon('b_usredit.png', __('Edit Privileges'));
2503 break;
2504 case 'revoke':
2505 $html .= PMA_Util::getIcon('b_usrdrop.png', __('Revoke'));
2506 break;
2507 case 'export':
2508 $html .= PMA_Util::getIcon('b_tblexport.png', __('Export'));
2509 break;
2511 $html . '</a>';
2513 return $html;
2517 * Returns user group edit link
2519 * @param string $username User name
2521 * @return HTML code with link
2523 function PMA_getUserGroupEditLink($username)
2525 return '<a class="edit_user_group_anchor ajax"'
2526 . ' href="server_privileges.php'
2527 . PMA_URL_getCommon(array('username' => $username))
2528 . '">'
2529 . PMA_Util::getIcon('b_usrlist.png', __('Edit user group'))
2530 . '</a>';
2534 * Returns number of defined user groups
2536 * @return integer $user_group_count
2538 function PMA_getUserGroupCount()
2540 $cfgRelation = PMA_getRelationsParam();
2541 $user_group_table = PMA_Util::backquote($cfgRelation['db'])
2542 . '.' . PMA_Util::backquote($cfgRelation['usergroups']);
2543 $sql_query = 'SELECT COUNT(*) FROM ' . $user_group_table;
2544 $user_group_count = $GLOBALS['dbi']->fetchValue(
2545 $sql_query, 0, 0, $GLOBALS['controllink']
2548 return $user_group_count;
2552 * This function return the extra data array for the ajax behavior
2554 * @param string $password password
2555 * @param string $sql_query sql query
2556 * @param string $hostname hostname
2557 * @param string $username username
2559 * @return array $extra_data
2561 function PMA_getExtraDataForAjaxBehavior(
2562 $password, $sql_query, $hostname, $username
2564 if (isset($GLOBALS['dbname'])) {
2565 //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
2566 if (preg_match('/(?<!\\\\)(?:_|%)/i', $GLOBALS['dbname'])) {
2567 $dbname_is_wildcard = true;
2568 } else {
2569 $dbname_is_wildcard = false;
2573 $user_group_count = 0;
2574 if ($GLOBALS['cfgRelation']['menuswork']) {
2575 $user_group_count = PMA_getUserGroupCount();
2578 $extra_data = array();
2579 if (/*overload*/mb_strlen($sql_query)) {
2580 $extra_data['sql_query'] = PMA_Util::getMessage(null, $sql_query);
2583 if (isset($_REQUEST['change_copy'])) {
2585 * generate html on the fly for the new user that was just created.
2587 $new_user_string = '<tr>' . "\n"
2588 . '<td> <input type="checkbox" name="selected_usr[]" '
2589 . 'id="checkbox_sel_users_"'
2590 . 'value="'
2591 . htmlspecialchars($username)
2592 . '&amp;#27;' . htmlspecialchars($hostname) . '" />'
2593 . '</td>' . "\n"
2594 . '<td><label for="checkbox_sel_users_">'
2595 . (empty($_REQUEST['username'])
2596 ? '<span style="color: #FF0000">' . __('Any') . '</span>'
2597 : htmlspecialchars($username) ) . '</label></td>' . "\n"
2598 . '<td>' . htmlspecialchars($hostname) . '</td>' . "\n";
2600 $new_user_string .= '<td>';
2602 if (! empty($password) || isset($_POST['pma_pw'])) {
2603 $new_user_string .= __('Yes');
2604 } else {
2605 $new_user_string .= '<span style="color: #FF0000">'
2606 . __('No')
2607 . '</span>';
2610 $new_user_string .= '</td>' . "\n";
2611 $new_user_string .= '<td>'
2612 . '<code>' . join(', ', PMA_extractPrivInfo(null, true)) . '</code>'
2613 . '</td>'; //Fill in privileges here
2615 // if $cfg['Servers'][$i]['users'] and $cfg['Servers'][$i]['usergroups'] are
2616 // enabled
2617 $cfgRelation = PMA_getRelationsParam();
2618 if (isset($cfgRelation['users']) && isset($cfgRelation['usergroups'])) {
2619 $new_user_string .= '<td class="usrGroup"></td>';
2622 $new_user_string .= '<td>';
2623 if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')) {
2624 $new_user_string .= __('Yes');
2625 } else {
2626 $new_user_string .= __('No');
2628 $new_user_string .='</td>';
2630 if ($GLOBALS['is_grantuser']) {
2631 $new_user_string .= '<td>'
2632 . PMA_getUserLink('edit', $username, $hostname)
2633 . '</td>' . "\n";
2636 if (isset($cfgRelation['menuswork']) && $user_group_count > 0) {
2637 $new_user_string .= '<td>'
2638 . PMA_getUserGroupEditLink($username)
2639 . '</td>' . "\n";
2642 $new_user_string .= '<td>'
2643 . PMA_getUserLink(
2644 'export',
2645 $username,
2646 $hostname,
2649 isset($_GET['initial']) ? $_GET['initial'] : ''
2651 . '</td>' . "\n";
2653 $new_user_string .= '</tr>';
2655 $extra_data['new_user_string'] = $new_user_string;
2658 * Generate the string for this alphabet's initial, to update the user
2659 * pagination
2661 $new_user_initial = /*overload*/mb_strtoupper(
2662 /*overload*/mb_substr($username, 0, 1)
2664 $newUserInitialString = '<a href="server_privileges.php'
2665 . PMA_URL_getCommon(array('initial' => $new_user_initial)) . '">'
2666 . $new_user_initial . '</a>';
2667 $extra_data['new_user_initial'] = $new_user_initial;
2668 $extra_data['new_user_initial_string'] = $newUserInitialString;
2671 if (isset($_POST['update_privs'])) {
2672 $extra_data['db_specific_privs'] = false;
2673 $extra_data['db_wildcard_privs'] = false;
2674 if (isset($dbname_is_wildcard)) {
2675 $extra_data['db_specific_privs'] = ! $dbname_is_wildcard;
2676 $extra_data['db_wildcard_privs'] = $dbname_is_wildcard;
2678 $new_privileges = join(', ', PMA_extractPrivInfo(null, true));
2680 $extra_data['new_privileges'] = $new_privileges;
2683 if (isset($_REQUEST['validate_username'])) {
2684 $sql_query = "SELECT * FROM `mysql`.`user` WHERE `User` = '"
2685 . $_REQUEST['username'] . "';";
2686 $res = $GLOBALS['dbi']->query($sql_query);
2687 $row = $GLOBALS['dbi']->fetchRow($res);
2688 if (empty($row)) {
2689 $extra_data['user_exists'] = false;
2690 } else {
2691 $extra_data['user_exists'] = true;
2695 return $extra_data;
2699 * Get the HTML snippet for change user login information
2701 * @param string $username username
2702 * @param string $hostname host name
2704 * @return string HTML snippet
2706 function PMA_getChangeLoginInformationHtmlForm($username, $hostname)
2708 $choices = array(
2709 '4' => __('… keep the old one.'),
2710 '1' => __('… delete the old one from the user tables.'),
2711 '2' => __(
2712 '… revoke all active privileges from '
2713 . 'the old one and delete it afterwards.'
2715 '3' => __(
2716 '… delete the old one from the user tables '
2717 . 'and reload the privileges afterwards.'
2721 $html_output = '<form action="server_privileges.php" '
2722 . 'onsubmit="return checkAddUser(this);" '
2723 . 'method="post" class="copyUserForm submenu-item">' . "\n"
2724 . PMA_URL_getHiddenInputs('', '')
2725 . '<input type="hidden" name="old_username" '
2726 . 'value="' . htmlspecialchars($username) . '" />' . "\n"
2727 . '<input type="hidden" name="old_hostname" '
2728 . 'value="' . htmlspecialchars($hostname) . '" />' . "\n"
2729 . '<fieldset id="fieldset_change_copy_user">' . "\n"
2730 . '<legend data-submenu-label="' . __('Login Information') . '">' . "\n"
2731 . __('Change Login Information / Copy User')
2732 . '</legend>' . "\n"
2733 . PMA_getHtmlForLoginInformationFields('change');
2735 $html_output .= '<fieldset id="fieldset_mode">' . "\n"
2736 . ' <legend>'
2737 . __('Create a new user with the same privileges and …')
2738 . '</legend>' . "\n";
2739 $html_output .= PMA_Util::getRadioFields(
2740 'mode', $choices, '4', true
2742 $html_output .= '</fieldset>' . "\n"
2743 . '</fieldset>' . "\n";
2745 $html_output .= '<fieldset id="fieldset_change_copy_user_footer" '
2746 . 'class="tblFooters">' . "\n"
2747 . '<input type="hidden" name="change_copy" value="1" />' . "\n"
2748 . '<input type="submit" value="' . __('Go') . '" />' . "\n"
2749 . '</fieldset>' . "\n"
2750 . '</form>' . "\n";
2752 return $html_output;
2756 * Provide a line with links to the relevant database and table
2758 * @param string $url_dbname url database name that urlencode() string
2759 * @param string $dbname database name
2760 * @param string $tablename table name
2762 * @return string HTML snippet
2764 function PMA_getLinkToDbAndTable($url_dbname, $dbname, $tablename)
2766 $html_output = '[ ' . __('Database')
2767 . ' <a href="' . $GLOBALS['cfg']['DefaultTabDatabase']
2768 . PMA_URL_getCommon(
2769 array(
2770 'db' => $url_dbname,
2771 'reload' => 1
2774 . '">'
2775 . htmlspecialchars($dbname) . ': '
2776 . PMA_Util::getTitleForTarget(
2777 $GLOBALS['cfg']['DefaultTabDatabase']
2779 . "</a> ]\n";
2781 if (/*overload*/mb_strlen($tablename)) {
2782 $html_output .= ' [ ' . __('Table') . ' <a href="'
2783 . $GLOBALS['cfg']['DefaultTabTable']
2784 . PMA_URL_getCommon(
2785 array(
2786 'db' => $url_dbname,
2787 'table' => $tablename,
2788 'reload' => 1,
2791 . '">' . htmlspecialchars($tablename) . ': '
2792 . PMA_Util::getTitleForTarget(
2793 $GLOBALS['cfg']['DefaultTabTable']
2795 . "</a> ]\n";
2797 return $html_output;
2801 * no db name given, so we want all privs for the given user
2802 * db name was given, so we want all user specific rights for this db
2803 * So this function returns user rights as an array
2805 * @param array $tables tables
2806 * @param string $user_host_condition a where clause that contained user's host
2807 * condition
2808 * @param string $dbname database name
2810 * @return array $db_rights database rights
2812 function PMA_getUserSpecificRights($tables, $user_host_condition, $dbname)
2814 if (!/*overload*/mb_strlen($dbname)) {
2815 $tables_to_search_for_users = array(
2816 'tables_priv', 'columns_priv',
2818 $dbOrTableName = 'Db';
2819 } else {
2820 $user_host_condition .=
2821 ' AND `Db`'
2822 . ' LIKE \''
2823 . PMA_Util::sqlAddSlashes($dbname, true) . "'";
2824 $tables_to_search_for_users = array('columns_priv',);
2825 $dbOrTableName = 'Table_name';
2828 $db_rights_sqls = array();
2829 foreach ($tables_to_search_for_users as $table_search_in) {
2830 if (in_array($table_search_in, $tables)) {
2831 $db_rights_sqls[] = '
2832 SELECT DISTINCT `' . $dbOrTableName . '`
2833 FROM `mysql`.' . PMA_Util::backquote($table_search_in)
2834 . $user_host_condition;
2838 $user_defaults = array(
2839 $dbOrTableName => '',
2840 'Grant_priv' => 'N',
2841 'privs' => array('USAGE'),
2842 'Column_priv' => true,
2845 // for the rights
2846 $db_rights = array();
2848 $db_rights_sql = '(' . implode(') UNION (', $db_rights_sqls) . ')'
2849 . ' ORDER BY `' . $dbOrTableName . '` ASC';
2851 $db_rights_result = $GLOBALS['dbi']->query($db_rights_sql);
2853 while ($db_rights_row = $GLOBALS['dbi']->fetchAssoc($db_rights_result)) {
2854 $db_rights_row = array_merge($user_defaults, $db_rights_row);
2855 if (!/*overload*/mb_strlen($dbname)) {
2856 // only Db names in the table `mysql`.`db` uses wildcards
2857 // as we are in the db specific rights display we want
2858 // all db names escaped, also from other sources
2859 $db_rights_row['Db'] = PMA_Util::escapeMysqlWildcards(
2860 $db_rights_row['Db']
2863 $db_rights[$db_rights_row[$dbOrTableName]] = $db_rights_row;
2866 $GLOBALS['dbi']->freeResult($db_rights_result);
2868 if (!/*overload*/mb_strlen($dbname)) {
2869 $sql_query = 'SELECT * FROM `mysql`.`db`'
2870 . $user_host_condition . ' ORDER BY `Db` ASC';
2871 } else {
2872 $sql_query = 'SELECT `Table_name`,'
2873 . ' `Table_priv`,'
2874 . ' IF(`Column_priv` = _latin1 \'\', 0, 1)'
2875 . ' AS \'Column_priv\''
2876 . ' FROM `mysql`.`tables_priv`'
2877 . $user_host_condition
2878 . ' ORDER BY `Table_name` ASC;';
2881 $result = $GLOBALS['dbi']->query($sql_query);
2883 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
2884 if (isset($db_rights[$row[$dbOrTableName]])) {
2885 $db_rights[$row[$dbOrTableName]]
2886 = array_merge($db_rights[$row[$dbOrTableName]], $row);
2887 } else {
2888 $db_rights[$row[$dbOrTableName]] = $row;
2890 if (!/*overload*/mb_strlen($dbname)) {
2891 // there are db specific rights for this user
2892 // so we can drop this db rights
2893 $db_rights[$row['Db']]['can_delete'] = true;
2896 $GLOBALS['dbi']->freeResult($result);
2897 return $db_rights;
2901 * Display user rights in table rows(Table specific or database specific privs)
2903 * @param array $db_rights user's database rights array
2904 * @param string $dbname database name
2905 * @param string $hostname host name
2906 * @param string $username username
2908 * @return array $found_rows, $html_output
2910 function PMA_getHtmlForUserRights($db_rights, $dbname,
2911 $hostname, $username
2913 $html_output = '';
2914 $found_rows = array();
2916 // display rows
2917 if (count($db_rights) < 1) {
2918 $html_output .= '<tr class="odd">' . "\n"
2919 . '<td colspan="6"><center><i>' . __('None') . '</i></center></td>' . "\n"
2920 . '</tr>' . "\n";
2921 return array($found_rows, $html_output);
2924 $odd_row = true;
2925 //while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
2926 foreach ($db_rights as $row) {
2927 $dbNameLength = /*overload*/mb_strlen($dbname);
2928 $found_rows[] = (!$dbNameLength)
2929 ? $row['Db']
2930 : $row['Table_name'];
2932 $html_output .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">' . "\n"
2933 . '<td>'
2934 . htmlspecialchars(
2935 (!$dbNameLength)
2936 ? $row['Db']
2937 : $row['Table_name']
2939 . '</td>' . "\n"
2940 . '<td><code>' . "\n"
2941 . ' '
2942 . join(
2943 ',' . "\n" . ' ',
2944 PMA_extractPrivInfo($row, true)
2945 ) . "\n"
2946 . '</code></td>' . "\n"
2947 . '<td>'
2948 . ((((!$dbNameLength) && $row['Grant_priv'] == 'Y')
2949 || ($dbNameLength
2950 && in_array('Grant', explode(',', $row['Table_priv']))))
2951 ? __('Yes')
2952 : __('No'))
2953 . '</td>' . "\n"
2954 . '<td>';
2955 if (! empty($row['Table_privs']) || ! empty ($row['Column_priv'])) {
2956 $html_output .= __('Yes');
2957 } else {
2958 $html_output .= __('No');
2960 $html_output .= '</td>';
2962 $html_output .= '<td>';
2963 if ($GLOBALS['is_grantuser']) {
2964 $html_output .= PMA_getUserLink(
2965 'edit',
2966 $username,
2967 $hostname,
2968 (!$dbNameLength) ? $row['Db'] : $dbname,
2969 (!$dbNameLength) ? '' : $row['Table_name']
2972 $html_output .= '</td>';
2974 $html_output .= '<td>';
2975 if (! empty($row['can_delete'])
2976 || isset($row['Table_name'])
2977 && /*overload*/mb_strlen($row['Table_name'])
2979 $html_output .= PMA_getUserLink(
2980 'revoke',
2981 $username,
2982 $hostname,
2983 (!$dbNameLength) ? $row['Db'] : $dbname,
2984 (!$dbNameLength) ? '' : $row['Table_name']
2987 $html_output .= '</td>' . "\n"
2988 . '</tr>' . "\n";
2989 $odd_row = ! $odd_row;
2990 } // end while
2992 return array($found_rows, $html_output);
2996 * Get a HTML table for display user's tabel specific or database specific rights
2998 * @param string $username username
2999 * @param string $hostname host name
3000 * @param string $dbname database name
3002 * @return array $html_output, $found_rows
3004 function PMA_getHtmlForAllTableSpecificRights(
3005 $username, $hostname, $dbname
3007 // table header
3008 $html_output = PMA_URL_getHiddenInputs('', '')
3009 . '<input type="hidden" name="username" '
3010 . 'value="' . htmlspecialchars($username) . '" />' . "\n"
3011 . '<input type="hidden" name="hostname" '
3012 . 'value="' . htmlspecialchars($hostname) . '" />' . "\n"
3013 . '<fieldset>' . "\n"
3014 . '<legend data-submenu-label="'
3015 . (!/*overload*/mb_strlen($dbname)
3016 ? __('Database')
3017 : __('Table')
3019 . '">'
3020 . (!/*overload*/mb_strlen($dbname)
3021 ? __('Database-specific privileges')
3022 : __('Table-specific privileges')
3024 . '</legend>' . "\n"
3025 . '<table class="data">' . "\n"
3026 . '<thead>' . "\n"
3027 . '<tr><th>'
3028 . (!/*overload*/mb_strlen($dbname) ? __('Database') : __('Table'))
3029 . '</th>' . "\n"
3030 . '<th>' . __('Privileges') . '</th>' . "\n"
3031 . '<th>' . __('Grant') . '</th>' . "\n"
3032 . '<th>'
3033 . (!/*overload*/mb_strlen($dbname)
3034 ? __('Table-specific privileges')
3035 : __('Column-specific privileges')
3037 . '</th>' . "\n"
3038 . '<th colspan="2">' . __('Action') . '</th>' . "\n"
3039 . '</tr>' . "\n"
3040 . '</thead>' . "\n";
3042 $user_host_condition = ' WHERE `User`'
3043 . ' = \'' . PMA_Util::sqlAddSlashes($username) . "'"
3044 . ' AND `Host`'
3045 . ' = \'' . PMA_Util::sqlAddSlashes($hostname) . "'";
3047 // table body
3048 // get data
3050 // we also want privileges for this user not in table `db` but in other table
3051 $tables = $GLOBALS['dbi']->fetchResult('SHOW TABLES FROM `mysql`;');
3054 * no db name given, so we want all privs for the given user
3055 * db name was given, so we want all user specific rights for this db
3057 $db_rights = PMA_getUserSpecificRights($tables, $user_host_condition, $dbname);
3059 ksort($db_rights);
3061 $html_output .= '<tbody>' . "\n";
3062 // display rows
3063 list ($found_rows, $html_out) = PMA_getHtmlForUserRights(
3064 $db_rights, $dbname, $hostname, $username
3067 $html_output .= $html_out;
3068 $html_output .= '</tbody>' . "\n";
3069 $html_output .='</table>' . "\n";
3071 return array($html_output, $found_rows);
3075 * Get HTML for display select db
3077 * @param array $found_rows isset($dbname)) ? $row['Db'] : $row['Table_name']
3079 * @return string HTML snippet
3081 function PMA_getHtmlForSelectDbInEditPrivs($found_rows)
3083 // we already have the list of databases from libraries/common.inc.php
3084 // via $pma = new PMA;
3085 $pred_db_array = $GLOBALS['pma']->databases;
3087 $databases_to_skip = array('information_schema', 'performance_schema');
3089 $html_output = '<label for="text_dbname">'
3090 . __('Add privileges on the following database(s):') . '</label>' . "\n";
3091 if (! empty($pred_db_array)) {
3092 $html_output .= '<select name="pred_dbname[]" multiple="multiple">' . "\n";
3093 foreach ($pred_db_array as $current_db) {
3094 if (in_array($current_db, $databases_to_skip)) {
3095 continue;
3097 $current_db_show = $current_db;
3098 $current_db = PMA_Util::escapeMysqlWildcards($current_db);
3099 // cannot use array_diff() once, outside of the loop,
3100 // because the list of databases has special characters
3101 // already escaped in $found_rows,
3102 // contrary to the output of SHOW DATABASES
3103 if (empty($found_rows) || ! in_array($current_db, $found_rows)) {
3104 $html_output .= '<option value="'
3105 . htmlspecialchars($current_db) . '">'
3106 . htmlspecialchars($current_db_show) . '</option>' . "\n";
3109 $html_output .= '</select>' . "\n";
3111 $html_output .= '<input type="text" id="text_dbname" name="dbname" />'
3112 . "\n"
3113 . PMA_Util::showHint(
3114 __('Wildcards % and _ should be escaped with a \ to use them literally.')
3116 return $html_output;
3120 * Get HTML for display table in edit privilege
3122 * @param string $dbname database naame
3123 * @param array $found_rows isset($dbname)) ? $row['Db'] : $row['Table_name']
3125 * @return string HTML snippet
3127 function PMA_displayTablesInEditPrivs($dbname, $found_rows)
3129 $html_output = '<input type="hidden" name="dbname"
3130 ' . 'value="' . htmlspecialchars($dbname) . '"/>' . "\n";
3131 $html_output .= '<label for="text_tablename">'
3132 . __('Add privileges on the following table:') . '</label>' . "\n";
3134 $result = @$GLOBALS['dbi']->tryQuery(
3135 'SHOW TABLES FROM ' . PMA_Util::backquote(
3136 PMA_Util::unescapeMysqlWildcards($dbname)
3137 ) . ';',
3138 null,
3139 PMA_DatabaseInterface::QUERY_STORE
3142 if ($result) {
3143 $pred_tbl_array = array();
3144 while ($row = $GLOBALS['dbi']->fetchRow($result)) {
3145 if (! isset($found_rows) || ! in_array($row[0], $found_rows)) {
3146 $pred_tbl_array[] = $row[0];
3149 $GLOBALS['dbi']->freeResult($result);
3151 if (! empty($pred_tbl_array)) {
3152 $html_output .= '<select name="pred_tablename" '
3153 . 'class="autosubmit">' . "\n"
3154 . '<option value="" selected="selected">' . __('Use text field')
3155 . ':</option>' . "\n";
3156 foreach ($pred_tbl_array as $current_table) {
3157 $html_output .= '<option '
3158 . 'value="' . htmlspecialchars($current_table) . '">'
3159 . htmlspecialchars($current_table)
3160 . '</option>' . "\n";
3162 $html_output .= '</select>' . "\n";
3165 $html_output .= '<input type="text" id="text_tablename" name="tablename" />'
3166 . "\n";
3168 return $html_output;
3172 * Get HTML for display the users overview
3173 * (if less than 50 users, display them immediately)
3175 * @param array $result ran sql query
3176 * @param array $db_rights user's database rights array
3177 * @param string $pmaThemeImage a image source link
3178 * @param string $text_dir text directory
3180 * @return string HTML snippet
3182 function PMA_getUsersOverview($result, $db_rights, $pmaThemeImage, $text_dir)
3184 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
3185 $row['privs'] = PMA_extractPrivInfo($row, true);
3186 $db_rights[$row['User']][$row['Host']] = $row;
3188 @$GLOBALS['dbi']->freeResult($result);
3189 $user_group_count = 0;
3190 if ($GLOBALS['cfgRelation']['menuswork']) {
3191 $user_group_count = PMA_getUserGroupCount();
3194 $html_output
3195 = '<form name="usersForm" id="usersForm" action="server_privileges.php" '
3196 . 'method="post">' . "\n"
3197 . PMA_URL_getHiddenInputs('', '')
3198 . '<table id="tableuserrights" class="data">' . "\n"
3199 . '<thead>' . "\n"
3200 . '<tr><th></th>' . "\n"
3201 . '<th>' . __('User') . '</th>' . "\n"
3202 . '<th>' . __('Host') . '</th>' . "\n"
3203 . '<th>' . __('Password') . '</th>' . "\n"
3204 . '<th>' . __('Global privileges') . ' '
3205 . PMA_Util::showHint(
3206 __('Note: MySQL privilege names are expressed in English.')
3208 . '</th>' . "\n";
3209 if ($GLOBALS['cfgRelation']['menuswork']) {
3210 $html_output .= '<th>' . __('User group') . '</th>' . "\n";
3212 $html_output .= '<th>' . __('Grant') . '</th>' . "\n"
3213 . '<th colspan="' . ($user_group_count > 0 ? '3' : '2') . '">'
3214 . __('Action') . '</th>' . "\n"
3215 . '</tr>' . "\n"
3216 . '</thead>' . "\n";
3218 $html_output .= '<tbody>' . "\n";
3219 $html_output .= PMA_getHtmlTableBodyForUserRights($db_rights);
3220 $html_output .= '</tbody>'
3221 . '</table>' . "\n";
3223 $html_output .= '<div style="float:left;">'
3224 . PMA_Util::getWithSelected($pmaThemeImage, $text_dir, "usersForm") . "\n";
3226 $html_output .= PMA_Util::getButtonOrImage(
3227 'submit_mult', 'mult_submit', 'submit_mult_export',
3228 __('Export'), 'b_tblexport.png', 'export'
3230 $html_output .= '<input type="hidden" name="initial" '
3231 . 'value="' . (isset($_GET['initial']) ? $_GET['initial'] : '') . '" />';
3232 $html_output .= '</div>'
3233 . '<div class="clear_both" style="clear:both"></div>';
3235 // add/delete user fieldset
3236 $html_output .= PMA_getFieldsetForAddDeleteUser();
3237 $html_output .= '</form>' . "\n";
3239 return $html_output;
3243 * Get table body for 'tableuserrights' table in userform
3245 * @param array $db_rights user's database rights array
3247 * @return string HTML snippet
3249 function PMA_getHtmlTableBodyForUserRights($db_rights)
3251 $cfgRelation = PMA_getRelationsParam();
3252 if ($cfgRelation['menuswork']) {
3253 $users_table = PMA_Util::backquote($cfgRelation['db'])
3254 . "." . PMA_Util::backquote($cfgRelation['users']);
3255 $sql_query = 'SELECT * FROM ' . $users_table;
3256 $result = PMA_queryAsControlUser($sql_query, false);
3257 $group_assignment = array();
3258 if ($result) {
3259 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
3260 $group_assignment[$row['username']] = $row['usergroup'];
3263 $GLOBALS['dbi']->freeResult($result);
3265 $user_group_count = PMA_getUserGroupCount();
3268 $odd_row = true;
3269 $index_checkbox = 0;
3270 $html_output = '';
3271 foreach ($db_rights as $user) {
3272 ksort($user);
3273 foreach ($user as $host) {
3274 $index_checkbox++;
3275 $html_output .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">'
3276 . "\n";
3277 $html_output .= '<td>'
3278 . '<input type="checkbox" class="checkall" name="selected_usr[]" '
3279 . 'id="checkbox_sel_users_'
3280 . $index_checkbox . '" value="'
3281 . htmlspecialchars($host['User'] . '&amp;#27;' . $host['Host'])
3282 . '"'
3283 . ' /></td>' . "\n";
3285 $html_output .= '<td><label '
3286 . 'for="checkbox_sel_users_' . $index_checkbox . '">'
3287 . (empty($host['User'])
3288 ? '<span style="color: #FF0000">' . __('Any') . '</span>'
3289 : htmlspecialchars($host['User'])) . '</label></td>' . "\n"
3290 . '<td>' . htmlspecialchars($host['Host']) . '</td>' . "\n";
3292 $html_output .= '<td>';
3293 switch ($host['Password']) {
3294 case 'Y':
3295 $html_output .= __('Yes');
3296 break;
3297 case 'N':
3298 $html_output .= '<span style="color: #FF0000">' . __('No')
3299 . '</span>';
3300 break;
3301 // this happens if this is a definition not coming from mysql.user
3302 default:
3303 $html_output .= '--'; // in future version, replace by "not present"
3304 break;
3305 } // end switch
3306 $html_output .= '</td>' . "\n";
3308 $html_output .= '<td><code>' . "\n"
3309 . '' . implode(',' . "\n" . ' ', $host['privs']) . "\n"
3310 . '</code></td>' . "\n";
3311 if ($cfgRelation['menuswork']) {
3312 $html_output .= '<td class="usrGroup">' . "\n"
3313 . (isset($group_assignment[$host['User']])
3314 ? $group_assignment[$host['User']]
3315 : ''
3317 . '</td>' . "\n";
3319 $html_output .= '<td>'
3320 . ($host['Grant_priv'] == 'Y' ? __('Yes') : __('No'))
3321 . '</td>' . "\n";
3323 if ($GLOBALS['is_grantuser']) {
3324 $html_output .= '<td class="center">'
3325 . PMA_getUserLink(
3326 'edit',
3327 $host['User'],
3328 $host['Host']
3330 . '</td>';
3332 if ($cfgRelation['menuswork'] && $user_group_count > 0) {
3333 if (empty($host['User'])) {
3334 $html_output .= '<td class="center"></td>';
3335 } else {
3336 $html_output .= '<td class="center">'
3337 . PMA_getUserGroupEditLink($host['User'])
3338 . '</td>';
3341 $html_output .= '<td class="center">'
3342 . PMA_getUserLink(
3343 'export',
3344 $host['User'],
3345 $host['Host'],
3348 isset($_GET['initial']) ? $_GET['initial'] : ''
3350 . '</td>';
3351 $html_output .= '</tr>';
3352 $odd_row = ! $odd_row;
3355 return $html_output;
3359 * Get HTML fieldset for Add/Delete user
3361 * @return string HTML snippet
3363 function PMA_getFieldsetForAddDeleteUser()
3365 $html_output = PMA_getAddUserHtmlFieldset();
3366 $html_output .= '<fieldset id="fieldset_delete_user">'
3367 . '<legend>' . "\n"
3368 . PMA_Util::getIcon('b_usrdrop.png')
3369 . ' ' . __('Remove selected users') . '' . "\n"
3370 . '</legend>' . "\n";
3372 $html_output .= '<input type="hidden" name="mode" value="2" />' . "\n"
3373 . '('
3374 . __(
3375 'Revoke all active privileges from the users '
3376 . 'and delete them afterwards.'
3378 . ')'
3379 . '<br />' . "\n";
3381 $html_output .= '<input type="checkbox" '
3382 . 'title="'
3383 . __('Drop the databases that have the same names as the users.')
3384 . '" '
3385 . 'name="drop_users_db" id="checkbox_drop_users_db" />' . "\n";
3387 $html_output .= '<label for="checkbox_drop_users_db" '
3388 . 'title="'
3389 . __('Drop the databases that have the same names as the users.')
3390 . '">' . "\n"
3391 . ' '
3392 . __('Drop the databases that have the same names as the users.')
3393 . "\n"
3394 . '</label>' . "\n"
3395 . '</fieldset>' . "\n";
3397 $html_output .= '<fieldset id="fieldset_delete_user_footer" class="tblFooters">'
3398 . "\n";
3399 $html_output .= '<input type="submit" name="delete" '
3400 . 'value="' . __('Go') . '" id="buttonGo" '
3401 . 'class="ajax"/>' . "\n";
3403 $html_output .= '</fieldset>' . "\n";
3405 return $html_output;
3409 * Get HTML for Displays the initials
3411 * @param array $array_initials array for all initials, even non A-Z
3413 * @return string HTML snippet
3415 function PMA_getHtmlForInitials($array_initials)
3417 // initialize to false the letters A-Z
3418 for ($letter_counter = 1; $letter_counter < 27; $letter_counter++) {
3419 if (! isset($array_initials[/*overload*/mb_chr($letter_counter + 64)])) {
3420 $array_initials[/*overload*/mb_chr($letter_counter + 64)] = false;
3424 $initials = $GLOBALS['dbi']->tryQuery(
3425 'SELECT DISTINCT UPPER(LEFT(`User`,1)) FROM `user` ORDER BY `User` ASC',
3426 null,
3427 PMA_DatabaseInterface::QUERY_STORE
3429 while (list($tmp_initial) = $GLOBALS['dbi']->fetchRow($initials)) {
3430 $array_initials[$tmp_initial] = true;
3433 // Display the initials, which can be any characters, not
3434 // just letters. For letters A-Z, we add the non-used letters
3435 // as greyed out.
3437 uksort($array_initials, "strnatcasecmp");
3439 $html_output = '<table id="initials_table" cellspacing="5">'
3440 . '<tr>';
3441 foreach ($array_initials as $tmp_initial => $initial_was_found) {
3442 if ($tmp_initial === null) {
3443 continue;
3446 if (!$initial_was_found) {
3447 $html_output .= '<td>' . $tmp_initial . '</td>';
3448 continue;
3451 $html_output .= '<td>'
3452 . '<a class="ajax'
3453 . ((isset($_REQUEST['initial'])
3454 && $_REQUEST['initial'] === $tmp_initial
3455 ) ? ' active' : '')
3456 . '" href="server_privileges.php'
3457 . PMA_URL_getCommon(array('initial' => $tmp_initial))
3458 . '">' . $tmp_initial
3459 . '</a>'
3460 . '</td>' . "\n";
3462 $html_output .= '<td>'
3463 . '<a href="server_privileges.php'
3464 . PMA_URL_getCommon(array('showall' => 1))
3465 . '" class="nowrap">' . __('Show all') . '</a></td>' . "\n";
3466 $html_output .= '</tr></table>';
3468 return $html_output;
3472 * Get the database rights array for Display user overview
3474 * @return array $db_rights database rights array
3476 function PMA_getDbRightsForUserOverview()
3478 // we also want users not in table `user` but in other table
3479 $tables = $GLOBALS['dbi']->fetchResult('SHOW TABLES FROM `mysql`;');
3481 $tablesSearchForUsers = array(
3482 'user', 'db', 'tables_priv', 'columns_priv', 'procs_priv',
3485 $db_rights_sqls = array();
3486 foreach ($tablesSearchForUsers as $table_search_in) {
3487 if (in_array($table_search_in, $tables)) {
3488 $db_rights_sqls[] = 'SELECT DISTINCT `User`, `Host` FROM `mysql`.`'
3489 . $table_search_in . '` '
3490 . (isset($_GET['initial'])
3491 ? PMA_rangeOfUsers($_GET['initial'])
3492 : '');
3495 $user_defaults = array(
3496 'User' => '',
3497 'Host' => '%',
3498 'Password' => '?',
3499 'Grant_priv' => 'N',
3500 'privs' => array('USAGE'),
3503 // for the rights
3504 $db_rights = array();
3506 $db_rights_sql = '(' . implode(') UNION (', $db_rights_sqls) . ')'
3507 . ' ORDER BY `User` ASC, `Host` ASC';
3509 $db_rights_result = $GLOBALS['dbi']->query($db_rights_sql);
3511 while ($db_rights_row = $GLOBALS['dbi']->fetchAssoc($db_rights_result)) {
3512 $db_rights_row = array_merge($user_defaults, $db_rights_row);
3513 $db_rights[$db_rights_row['User']][$db_rights_row['Host']]
3514 = $db_rights_row;
3516 $GLOBALS['dbi']->freeResult($db_rights_result);
3517 ksort($db_rights);
3519 return $db_rights;
3523 * Delete user and get message and sql query for delete user in privileges
3525 * @param array $queries queries
3527 * @return array PMA_message
3529 function PMA_deleteUser($queries)
3531 $sql_query = '';
3532 if (empty($queries)) {
3533 $message = PMA_Message::error(__('No users selected for deleting!'));
3534 } else {
3535 if ($_REQUEST['mode'] == 3) {
3536 $queries[] = '# ' . __('Reloading the privileges') . ' …';
3537 $queries[] = 'FLUSH PRIVILEGES;';
3539 $drop_user_error = '';
3540 foreach ($queries as $sql_query) {
3541 if ($sql_query{0} != '#') {
3542 if (! $GLOBALS['dbi']->tryQuery($sql_query, $GLOBALS['userlink'])) {
3543 $drop_user_error .= $GLOBALS['dbi']->getError() . "\n";
3547 // tracking sets this, causing the deleted db to be shown in navi
3548 unset($GLOBALS['db']);
3550 $sql_query = join("\n", $queries);
3551 if (! empty($drop_user_error)) {
3552 $message = PMA_Message::rawError($drop_user_error);
3553 } else {
3554 $message = PMA_Message::success(
3555 __('The selected users have been deleted successfully.')
3559 return array($sql_query, $message);
3563 * Update the privileges and return the success or error message
3565 * @param string $username username
3566 * @param string $hostname host name
3567 * @param string $tablename table name
3568 * @param string $dbname database name
3570 * @return PMA_message success message or error message for update
3572 function PMA_updatePrivileges($username, $hostname, $tablename, $dbname)
3574 $db_and_table = PMA_wildcardEscapeForGrant($dbname, $tablename);
3576 $sql_query0 = 'REVOKE ALL PRIVILEGES ON ' . $db_and_table
3577 . ' FROM \'' . PMA_Util::sqlAddSlashes($username)
3578 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
3580 if (! isset($_POST['Grant_priv']) || $_POST['Grant_priv'] != 'Y') {
3581 $sql_query1 = 'REVOKE GRANT OPTION ON ' . $db_and_table
3582 . ' FROM \'' . PMA_Util::sqlAddSlashes($username) . '\'@\''
3583 . PMA_Util::sqlAddSlashes($hostname) . '\';';
3584 } else {
3585 $sql_query1 = '';
3588 // Should not do a GRANT USAGE for a table-specific privilege, it
3589 // causes problems later (cannot revoke it)
3590 if (! (/*overload*/mb_strlen($tablename)
3591 && 'USAGE' == implode('', PMA_extractPrivInfo()))
3593 $sql_query2 = 'GRANT ' . join(', ', PMA_extractPrivInfo())
3594 . ' ON ' . $db_and_table
3595 . ' TO \'' . PMA_Util::sqlAddSlashes($username) . '\'@\''
3596 . PMA_Util::sqlAddSlashes($hostname) . '\'';
3598 if (! /*overload*/mb_strlen($dbname)) {
3599 // add REQUIRE clause
3600 $sql_query2 .= PMA_getRequireClause();
3603 if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
3604 || (! /*overload*/mb_strlen($dbname)
3605 && (isset($_POST['max_questions']) || isset($_POST['max_connections'])
3606 || isset($_POST['max_updates'])
3607 || isset($_POST['max_user_connections'])))
3609 $sql_query2 .= PMA_getWithClauseForAddUserAndUpdatePrivs();
3611 $sql_query2 .= ';';
3613 if (! $GLOBALS['dbi']->tryQuery($sql_query0)) {
3614 // This might fail when the executing user does not have
3615 // ALL PRIVILEGES himself.
3616 // See https://sourceforge.net/p/phpmyadmin/bugs/3270/
3617 $sql_query0 = '';
3619 if (! empty($sql_query1) && ! $GLOBALS['dbi']->tryQuery($sql_query1)) {
3620 // this one may fail, too...
3621 $sql_query1 = '';
3623 if (! empty($sql_query2)) {
3624 $GLOBALS['dbi']->query($sql_query2);
3625 } else {
3626 $sql_query2 = '';
3628 $sql_query = $sql_query0 . ' ' . $sql_query1 . ' ' . $sql_query2;
3629 $message = PMA_Message::success(__('You have updated the privileges for %s.'));
3630 $message->addParam(
3631 '\'' . htmlspecialchars($username)
3632 . '\'@\'' . htmlspecialchars($hostname) . '\''
3635 return array($sql_query, $message);
3639 * Get List of information: Changes / copies a user
3641 * @return array
3643 function PMA_getDataForChangeOrCopyUser()
3645 $queries = null;
3646 $password = null;
3648 if (isset($_REQUEST['change_copy'])) {
3649 $user_host_condition = ' WHERE `User` = '
3650 . "'" . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'"
3651 . ' AND `Host` = '
3652 . "'" . PMA_Util::sqlAddSlashes($_REQUEST['old_hostname']) . "';";
3653 $row = $GLOBALS['dbi']->fetchSingleRow(
3654 'SELECT * FROM `mysql`.`user` ' . $user_host_condition
3656 if (! $row) {
3657 $response = PMA_Response::getInstance();
3658 $response->addHTML(
3659 PMA_Message::notice(__('No user found.'))->getDisplay()
3661 unset($_REQUEST['change_copy']);
3662 } else {
3663 extract($row, EXTR_OVERWRITE);
3664 // Recent MySQL versions have the field "Password" in mysql.user,
3665 // so the previous extract creates $Password but this script
3666 // uses $password
3667 if (! isset($password) && isset($Password)) {
3668 $password = $Password;
3670 $queries = array();
3674 return array($queries, $password);
3678 * Update Data for information: Deletes users
3680 * @param array $queries queries array
3682 * @return array
3684 function PMA_getDataForDeleteUsers($queries)
3686 if (isset($_REQUEST['change_copy'])) {
3687 $selected_usr = array(
3688 $_REQUEST['old_username'] . '&amp;#27;' . $_REQUEST['old_hostname']
3690 } else {
3691 $selected_usr = $_REQUEST['selected_usr'];
3692 $queries = array();
3694 foreach ($selected_usr as $each_user) {
3695 list($this_user, $this_host) = explode('&amp;#27;', $each_user);
3696 $queries[] = '# '
3697 . sprintf(
3698 __('Deleting %s'),
3699 '\'' . $this_user . '\'@\'' . $this_host . '\''
3701 . ' ...';
3702 $queries[] = 'DROP USER \''
3703 . PMA_Util::sqlAddSlashes($this_user)
3704 . '\'@\'' . PMA_Util::sqlAddSlashes($this_host) . '\';';
3706 if (isset($_REQUEST['drop_users_db'])) {
3707 $queries[] = 'DROP DATABASE IF EXISTS '
3708 . PMA_Util::backquote($this_user) . ';';
3709 $GLOBALS['reload'] = true;
3712 return $queries;
3716 * update Message For Reload
3718 * @return array
3720 function PMA_updateMessageForReload()
3722 $message = null;
3723 if (isset($_REQUEST['flush_privileges'])) {
3724 $sql_query = 'FLUSH PRIVILEGES;';
3725 $GLOBALS['dbi']->query($sql_query);
3726 $message = PMA_Message::success(
3727 __('The privileges were reloaded successfully.')
3731 if (isset($_REQUEST['validate_username'])) {
3732 $message = PMA_Message::success();
3735 return $message;
3739 * update Data For Queries from queries_for_display
3741 * @param array $queries queries array
3742 * @param array|null $queries_for_display queries array for display
3744 * @return null
3746 function PMA_getDataForQueries($queries, $queries_for_display)
3748 $tmp_count = 0;
3749 foreach ($queries as $sql_query) {
3750 if ($sql_query{0} != '#') {
3751 $GLOBALS['dbi']->query($sql_query);
3753 // when there is a query containing a hidden password, take it
3754 // instead of the real query sent
3755 if (isset($queries_for_display[$tmp_count])) {
3756 $queries[$tmp_count] = $queries_for_display[$tmp_count];
3758 $tmp_count++;
3761 return $queries;
3765 * update Data for information: Adds a user
3767 * @param string $dbname db name
3768 * @param string $username user name
3769 * @param string $hostname host name
3770 * @param string $password password
3771 * @param bool $is_menuwork is_menuwork set?
3773 * @return array
3775 function PMA_addUser(
3776 $dbname, $username, $hostname,
3777 $password, $is_menuwork
3779 $_add_user_error = false;
3780 $message = null;
3781 $queries = null;
3782 $queries_for_display = null;
3783 $sql_query = null;
3785 if (isset($_REQUEST['adduser_submit']) || isset($_REQUEST['change_copy'])) {
3786 $sql_query = '';
3787 if ($_POST['pred_username'] == 'any') {
3788 $username = '';
3790 switch ($_POST['pred_hostname']) {
3791 case 'any':
3792 $hostname = '%';
3793 break;
3794 case 'localhost':
3795 $hostname = 'localhost';
3796 break;
3797 case 'hosttable':
3798 $hostname = '';
3799 break;
3800 case 'thishost':
3801 $_user_name = $GLOBALS['dbi']->fetchValue('SELECT USER()');
3802 $hostname = /*overload*/mb_substr(
3803 $_user_name,
3804 (/*overload*/mb_strrpos($_user_name, '@') + 1)
3806 unset($_user_name);
3807 break;
3809 $sql = "SELECT '1' FROM `mysql`.`user`"
3810 . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
3811 . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "';";
3812 if ($GLOBALS['dbi']->fetchValue($sql) == 1) {
3813 $message = PMA_Message::error(__('The user %s already exists!'));
3814 $message->addParam(
3815 '[em]\'' . $username . '\'@\'' . $hostname . '\'[/em]'
3817 $_REQUEST['adduser'] = true;
3818 $_add_user_error = true;
3819 } else {
3820 list($create_user_real, $create_user_show, $real_sql_query, $sql_query)
3821 = PMA_getSqlQueriesForDisplayAndAddUser(
3822 $username, $hostname, (isset ($password) ? $password : '')
3825 if (empty($_REQUEST['change_copy'])) {
3826 $_error = false;
3828 if (isset($create_user_real)) {
3829 if (! $GLOBALS['dbi']->tryQuery($create_user_real)) {
3830 $_error = true;
3832 $sql_query = $create_user_show . $sql_query;
3834 list($sql_query, $message) = PMA_addUserAndCreateDatabase(
3835 $_error, $real_sql_query, $sql_query, $username, $hostname,
3836 isset($dbname) ? $dbname : null
3838 if (! empty($_REQUEST['userGroup']) && $is_menuwork) {
3839 PMA_setUserGroup($GLOBALS['username'], $_REQUEST['userGroup']);
3842 } else {
3843 if (isset($create_user_real)) {
3844 $queries[] = $create_user_real;
3846 $queries[] = $real_sql_query;
3847 // we put the query containing the hidden password in
3848 // $queries_for_display, at the same position occupied
3849 // by the real query in $queries
3850 $tmp_count = count($queries);
3851 if (isset($create_user_real)) {
3852 $queries_for_display[$tmp_count - 2] = $create_user_show;
3854 $queries_for_display[$tmp_count - 1] = $sql_query;
3856 unset($real_sql_query);
3860 return array(
3861 $message, $queries, $queries_for_display, $sql_query, $_add_user_error
3866 * Update DB information: DB, Table, isWildcard
3868 * @return array
3870 function PMA_getDataForDBInfo()
3872 $username = null;
3873 $hostname = null;
3874 $dbname = null;
3875 $tablename = null;
3876 $dbname_is_wildcard = null;
3878 if (isset ($_REQUEST['username'])) {
3879 $username = $_REQUEST['username'];
3881 if (isset ($_REQUEST['hostname'])) {
3882 $hostname = $_REQUEST['hostname'];
3885 * Checks if a dropdown box has been used for selecting a database / table
3887 if (PMA_isValid($_REQUEST['pred_tablename'])) {
3888 $tablename = $_REQUEST['pred_tablename'];
3889 } elseif (PMA_isValid($_REQUEST['tablename'])) {
3890 $tablename = $_REQUEST['tablename'];
3891 } else {
3892 unset($tablename);
3895 if (isset($_REQUEST['pred_dbname'])) {
3896 $is_valid_pred_dbname = true;
3897 foreach ($_REQUEST['pred_dbname'] as $key => $db_name) {
3898 if (! PMA_isValid($db_name)) {
3899 $is_valid_pred_dbname = false;
3900 break;
3905 if (isset($_REQUEST['dbname'])) {
3906 $is_valid_dbname = true;
3907 if (is_array($_REQUEST['dbname'])) {
3908 foreach ($_REQUEST['dbname'] as $key => $db_name) {
3909 if (! PMA_isValid($db_name)) {
3910 $is_valid_dbname = false;
3911 break;
3914 } else {
3915 if (! PMA_isValid($_REQUEST['dbname'])) {
3916 $is_valid_dbname = false;
3921 if (isset($is_valid_pred_dbname) && $is_valid_pred_dbname) {
3922 $dbname = $_REQUEST['pred_dbname'];
3923 // If dbname contains only one database.
3924 if (count($dbname) == 1) {
3925 $dbname = $dbname[0];
3927 } elseif (isset($is_valid_dbname) && $is_valid_dbname) {
3928 $dbname = $_REQUEST['dbname'];
3929 } else {
3930 unset($dbname);
3931 unset($tablename);
3934 if (isset($dbname)) {
3935 if (is_array($dbname)) {
3936 $db_and_table = $dbname;
3937 foreach ($db_and_table as $key => $db_name) {
3938 $db_and_table[$key] .= '.';
3940 } else {
3941 $unescaped_db = PMA_Util::unescapeMysqlWildcards($dbname);
3942 $db_and_table = PMA_Util::backquote($unescaped_db) . '.';
3944 if (isset($tablename)) {
3945 $db_and_table .= PMA_Util::backquote($tablename);
3946 } else {
3947 if (is_array($db_and_table)) {
3948 foreach ($db_and_table as $key => $db_name) {
3949 $db_and_table[$key] .= '*';
3951 } else {
3952 $db_and_table .= '*';
3955 } else {
3956 $db_and_table = '*.*';
3959 // check if given $dbname is a wildcard or not
3960 if (isset($dbname)) {
3961 //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
3962 if (! is_array($dbname) && preg_match('/(?<!\\\\)(?:_|%)/i', $dbname)) {
3963 $dbname_is_wildcard = true;
3964 } else {
3965 $dbname_is_wildcard = false;
3969 return array(
3970 $username, $hostname,
3971 isset($dbname)? $dbname : null,
3972 isset($tablename)? $tablename : null,
3973 $db_and_table,
3974 $dbname_is_wildcard,
3979 * Get title and textarea for export user definition in Privileges
3981 * @param string $username username
3982 * @param string $hostname host name
3984 * @return array ($title, $export)
3986 function PMA_getListForExportUserDefinition($username, $hostname)
3988 $export = '<textarea class="export" cols="' . $GLOBALS['cfg']['TextareaCols']
3989 . '" rows="' . $GLOBALS['cfg']['TextareaRows'] . '">';
3991 if (isset($_REQUEST['selected_usr'])) {
3992 // export privileges for selected users
3993 $title = __('Privileges');
3995 foreach ($_REQUEST['selected_usr'] as $export_user) {
3996 $export_username = /*overload*/mb_substr(
3997 $export_user, 0, /*overload*/mb_strpos($export_user, '&')
3999 $export_hostname = /*overload*/mb_substr(
4000 $export_user, /*overload*/mb_strrpos($export_user, ';') + 1
4002 $export .= '# '
4003 . sprintf(
4004 __('Privileges for %s'),
4005 '`' . htmlspecialchars($export_username)
4006 . '`@`' . htmlspecialchars($export_hostname) . '`'
4008 . "\n\n";
4009 $export .= PMA_getGrants($export_username, $export_hostname) . "\n";
4011 } else {
4012 // export privileges for a single user
4013 $title = __('User') . ' `' . htmlspecialchars($username)
4014 . '`@`' . htmlspecialchars($hostname) . '`';
4015 $export .= PMA_getGrants($username, $hostname);
4017 // remove trailing whitespace
4018 $export = trim($export);
4020 $export .= '</textarea>';
4022 return array($title, $export);
4026 * Get HTML for display Add userfieldset
4028 * @param string $db the database
4029 * @param string $table the table name
4031 * @return string html output
4033 function PMA_getAddUserHtmlFieldset($db = '', $table = '')
4035 if (!$GLOBALS['is_createuser']) {
4036 return '';
4038 $rel_params = array();
4039 $url_params = array(
4040 'adduser' => 1
4042 if (!empty($db)) {
4043 $url_params['dbname']
4044 = $rel_params['checkprivsdb']
4045 = $db;
4047 if (!empty($table)) {
4048 $url_params['tablename']
4049 = $rel_params['checkprivstable']
4050 = $table;
4053 return '<fieldset id="fieldset_add_user">' . "\n"
4054 . '<legend>' . _pgettext('Create new user', 'New') . '</legend>'
4055 . '<a id="add_user_anchor" href="server_privileges.php'
4056 . PMA_URL_getCommon($url_params) . '" '
4057 . (!empty($rel_params)
4058 ? ('rel="' . PMA_URL_getCommon($rel_params) . '" ')
4059 : '')
4060 . '>' . "\n"
4061 . PMA_Util::getIcon('b_usradd.png')
4062 . ' ' . __('Add user') . '</a>' . "\n"
4063 . '</fieldset>' . "\n";
4067 * Get HTML header for display User's properties
4069 * @param boolean $dbname_is_wildcard whether database name is wildcard or not
4070 * @param string $url_dbname url database name that urlencode() string
4071 * @param string $dbname database name
4072 * @param string $username username
4073 * @param string $hostname host name
4074 * @param string $tablename table name
4076 * @return string $html_output
4078 function PMA_getHtmlHeaderForUserProperties(
4079 $dbname_is_wildcard, $url_dbname, $dbname, $username, $hostname, $tablename
4081 $html_output = '<h2>' . "\n"
4082 . PMA_Util::getIcon('b_usredit.png')
4083 . __('Edit Privileges:') . ' '
4084 . __('User');
4086 if (! empty($dbname)) {
4087 $html_output .= ' <i><a class="edit_user_anchor"'
4088 . ' href="server_privileges.php'
4089 . PMA_URL_getCommon(
4090 array(
4091 'username' => $username,
4092 'hostname' => $hostname,
4093 'dbname' => '',
4094 'tablename' => '',
4097 . '">\'' . htmlspecialchars($username)
4098 . '\'@\'' . htmlspecialchars($hostname)
4099 . '\'</a></i>' . "\n";
4101 $html_output .= ' - ';
4102 $html_output .= ($dbname_is_wildcard
4103 || is_array($dbname) && count($dbname) > 1)
4104 ? __('Databases') : __('Database');
4105 if (! empty($_REQUEST['tablename'])) {
4106 $html_output .= ' <i><a href="server_privileges.php'
4107 . PMA_URL_getCommon(
4108 array(
4109 'username' => $username,
4110 'hostname' => $hostname,
4111 'dbname' => $url_dbname,
4112 'tablename' => '',
4115 . '">' . htmlspecialchars($dbname)
4116 . '</a></i>';
4118 $html_output .= ' - ' . __('Table')
4119 . ' <i>' . htmlspecialchars($tablename) . '</i>';
4120 } else {
4121 if (! is_array($dbname)) {
4122 $dbname = array($dbname);
4124 $html_output .= ' <i>'
4125 . htmlspecialchars(implode(', ', $dbname))
4126 . '</i>';
4129 } else {
4130 $html_output .= ' <i>\'' . htmlspecialchars($username)
4131 . '\'@\'' . htmlspecialchars($hostname)
4132 . '\'</i>' . "\n";
4135 $html_output .= '</h2>' . "\n";
4136 $cur_user = htmlspecialchars($GLOBALS['dbi']->getCurrentUser());
4137 $user = htmlspecialchars($username . '@' . $hostname);
4138 // Add a short notice for the user
4139 // to remind him that he is editing his own privileges
4140 if ($user === $cur_user) {
4141 $html_output .= PMA_Message::notice(
4143 'Note: You are attempting to edit privileges of the '
4144 . 'user with which you are currently logged in.'
4146 )->getDisplay();
4148 return $html_output;
4152 * Get HTML snippet for display user overview page
4154 * @param string $pmaThemeImage a image source link
4155 * @param string $text_dir text directory
4157 * @return string $html_output
4159 function PMA_getHtmlForUserOverview($pmaThemeImage, $text_dir)
4161 $html_output = '<h2>' . "\n"
4162 . PMA_Util::getIcon('b_usrlist.png')
4163 . __('Users overview') . "\n"
4164 . '</h2>' . "\n";
4166 // $sql_query is for the initial-filtered,
4167 // $sql_query_all is for counting the total no. of users
4169 $sql_query = $sql_query_all = 'SELECT *,' .
4170 " IF(`Password` = _latin1 '', 'N', 'Y') AS 'Password'" .
4171 ' FROM `mysql`.`user`';
4173 $sql_query .= (isset($_REQUEST['initial'])
4174 ? PMA_rangeOfUsers($_REQUEST['initial'])
4175 : '');
4177 $sql_query .= ' ORDER BY `User` ASC, `Host` ASC;';
4178 $sql_query_all .= ' ;';
4180 $res = $GLOBALS['dbi']->tryQuery(
4181 $sql_query, null, PMA_DatabaseInterface::QUERY_STORE
4183 $res_all = $GLOBALS['dbi']->tryQuery(
4184 $sql_query_all, null, PMA_DatabaseInterface::QUERY_STORE
4187 if (! $res) {
4188 // the query failed! This may have two reasons:
4189 // - the user does not have enough privileges
4190 // - the privilege tables use a structure of an earlier version.
4191 // so let's try a more simple query
4193 $GLOBALS['dbi']->freeResult($res);
4194 $GLOBALS['dbi']->freeResult($res_all);
4195 $sql_query = 'SELECT * FROM `mysql`.`user`';
4196 $res = $GLOBALS['dbi']->tryQuery(
4197 $sql_query, null, PMA_DatabaseInterface::QUERY_STORE
4200 if (! $res) {
4201 $html_output .= PMA_getHtmlForViewUsersError();
4202 $html_output .= PMA_getAddUserHtmlFieldset();
4203 } else {
4204 // This message is hardcoded because I will replace it by
4205 // a automatic repair feature soon.
4206 $raw = 'Your privilege table structure seems to be older than'
4207 . ' this MySQL version!<br />'
4208 . 'Please run the <code>mysql_upgrade</code> command'
4209 . '(<code>mysql_fix_privilege_tables</code> on older systems)'
4210 . ' that should be included in your MySQL server distribution'
4211 . ' to solve this problem!';
4212 $html_output .= PMA_Message::rawError($raw)->getDisplay();
4214 $GLOBALS['dbi']->freeResult($res);
4215 } else {
4216 $db_rights = PMA_getDbRightsForUserOverview();
4217 // for all initials, even non A-Z
4218 $array_initials = array();
4221 * Displays the initials
4222 * Also not necessary if there is less than 20 privileges
4224 if ($GLOBALS['dbi']->numRows($res_all) > 20) {
4225 $html_output .= PMA_getHtmlForInitials($array_initials);
4229 * Display the user overview
4230 * (if less than 50 users, display them immediately)
4232 if (isset($_REQUEST['initial'])
4233 || isset($_REQUEST['showall'])
4234 || $GLOBALS['dbi']->numRows($res) < 50
4236 $html_output .= PMA_getUsersOverview(
4237 $res, $db_rights, $pmaThemeImage, $text_dir
4239 } else {
4240 $html_output .= PMA_getAddUserHtmlFieldset();
4241 } // end if (display overview)
4243 if (! $GLOBALS['is_ajax_request']
4244 || ! empty($_REQUEST['ajax_page_request'])
4246 $flushnote = new PMA_Message(
4248 'Note: phpMyAdmin gets the users\' privileges directly '
4249 . 'from MySQL\'s privilege tables. The content of these tables '
4250 . 'may differ from the privileges the server uses, '
4251 . 'if they have been changed manually. In this case, '
4252 . 'you should %sreload the privileges%s before you continue.'
4254 PMA_Message::NOTICE
4256 $flushLink = '<a href="server_privileges.php'
4257 . PMA_URL_getCommon(array('flush_privileges' => 1))
4258 . '" id="reload_privileges_anchor">';
4259 $flushnote->addParam(
4260 $flushLink,
4261 false
4263 $flushnote->addParam('</a>', false);
4264 $html_output .= $flushnote->getDisplay();
4268 return $html_output;
4272 * Get HTML snippet for display user properties
4274 * @param boolean $dbname_is_wildcard whether database name is wildcard or not
4275 * @param string $url_dbname url database name that urlencode() string
4276 * @param string $username username
4277 * @param string $hostname host name
4278 * @param string $dbname database name
4279 * @param string $tablename table name
4281 * @return string $html_output
4283 function PMA_getHtmlForUserProperties($dbname_is_wildcard,$url_dbname,
4284 $username, $hostname, $dbname, $tablename
4286 $html_output = '<div id="edit_user_dialog">';
4287 $html_output .= PMA_getHtmlHeaderForUserProperties(
4288 $dbname_is_wildcard, $url_dbname, $dbname, $username, $hostname, $tablename
4291 $sql = "SELECT '1' FROM `mysql`.`user`"
4292 . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
4293 . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "';";
4295 $user_does_not_exists = (bool) ! $GLOBALS['dbi']->fetchValue($sql);
4297 if ($user_does_not_exists) {
4298 $html_output .= PMA_Message::error(
4299 __('The selected user was not found in the privilege table.')
4300 )->getDisplay();
4301 $html_output .= PMA_getHtmlForLoginInformationFields();
4302 //exit;
4305 $_params = array(
4306 'username' => $username,
4307 'hostname' => $hostname,
4309 if (! is_array($dbname) && /*overload*/mb_strlen($dbname)) {
4310 $_params['dbname'] = $dbname;
4311 if (/*overload*/mb_strlen($tablename)) {
4312 $_params['tablename'] = $tablename;
4314 } else {
4315 $_params['dbname'] = $dbname;
4318 $html_output .= '<form class="submenu-item" name="usersForm" '
4319 . 'id="addUsersForm" action="server_privileges.php" method="post">' . "\n";
4320 $html_output .= PMA_URL_getHiddenInputs($_params);
4321 $html_output .= PMA_getHtmlToDisplayPrivilegesTable(
4322 // If $dbname is an array, pass any one db as all have same privs.
4323 PMA_ifSetOr($dbname, (is_array($dbname)) ? $dbname[0] : '*', 'length'),
4324 PMA_ifSetOr($tablename, '*', 'length')
4327 $html_output .= '</form>' . "\n";
4329 if (! is_array($dbname) && ! /*overload*/mb_strlen($tablename)
4330 && empty($dbname_is_wildcard)
4333 // no table name was given, display all table specific rights
4334 // but only if $dbname contains no wildcards
4336 $html_output .= '<form class="submenu-item" action="server_privileges.php" '
4337 . 'id="db_or_table_specific_priv" method="post">' . "\n";
4339 // unescape wildcards in dbname at table level
4340 $unescaped_db = PMA_Util::unescapeMysqlWildcards($dbname);
4341 list($html_rightsTable, $found_rows)
4342 = PMA_getHtmlForAllTableSpecificRights(
4343 $username, $hostname, $unescaped_db
4345 $html_output .= $html_rightsTable;
4347 if (! /*overload*/mb_strlen($dbname)) {
4348 // no database name was given, display select db
4349 $html_output .= PMA_getHtmlForSelectDbInEditPrivs($found_rows);
4351 } else {
4352 $html_output .= PMA_displayTablesInEditPrivs($dbname, $found_rows);
4354 $html_output .= '</fieldset>' . "\n";
4356 $html_output .= '<fieldset class="tblFooters">' . "\n"
4357 . ' <input type="submit" value="' . __('Go') . '" />'
4358 . '</fieldset>' . "\n"
4359 . '</form>' . "\n";
4362 // Provide a line with links to the relevant database and table
4363 if (! is_array($dbname) && /*overload*/mb_strlen($dbname)
4364 && empty($dbname_is_wildcard)
4366 $html_output .= PMA_getLinkToDbAndTable($url_dbname, $dbname, $tablename);
4370 if (! is_array($dbname) && ! /*overload*/mb_strlen($dbname)
4371 && ! $user_does_not_exists
4373 //change login information
4374 $html_output .= PMA_getHtmlForChangePassword($username, $hostname);
4375 $html_output .= PMA_getChangeLoginInformationHtmlForm($username, $hostname);
4377 $html_output .= '</div>';
4379 return $html_output;
4383 * Get queries for Table privileges to change or copy user
4385 * @param string $user_host_condition user host condition to
4386 * select relevant table privileges
4387 * @param array $queries queries array
4388 * @param string $username username
4389 * @param string $hostname host name
4391 * @return array $queries
4393 function PMA_getTablePrivsQueriesForChangeOrCopyUser($user_host_condition,
4394 $queries, $username, $hostname
4396 $res = $GLOBALS['dbi']->query(
4397 'SELECT `Db`, `Table_name`, `Table_priv` FROM `mysql`.`tables_priv`'
4398 . $user_host_condition,
4399 $GLOBALS['userlink'],
4400 PMA_DatabaseInterface::QUERY_STORE
4402 while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
4404 $res2 = $GLOBALS['dbi']->query(
4405 'SELECT `Column_name`, `Column_priv`'
4406 . ' FROM `mysql`.`columns_priv`'
4407 . ' WHERE `User`'
4408 . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'"
4409 . ' AND `Host`'
4410 . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . '\''
4411 . ' AND `Db`'
4412 . ' = \'' . PMA_Util::sqlAddSlashes($row['Db']) . "'"
4413 . ' AND `Table_name`'
4414 . ' = \'' . PMA_Util::sqlAddSlashes($row['Table_name']) . "'"
4415 . ';',
4416 null,
4417 PMA_DatabaseInterface::QUERY_STORE
4420 $tmp_privs1 = PMA_extractPrivInfo($row);
4421 $tmp_privs2 = array(
4422 'Select' => array(),
4423 'Insert' => array(),
4424 'Update' => array(),
4425 'References' => array()
4428 while ($row2 = $GLOBALS['dbi']->fetchAssoc($res2)) {
4429 $tmp_array = explode(',', $row2['Column_priv']);
4430 if (in_array('Select', $tmp_array)) {
4431 $tmp_privs2['Select'][] = $row2['Column_name'];
4433 if (in_array('Insert', $tmp_array)) {
4434 $tmp_privs2['Insert'][] = $row2['Column_name'];
4436 if (in_array('Update', $tmp_array)) {
4437 $tmp_privs2['Update'][] = $row2['Column_name'];
4439 if (in_array('References', $tmp_array)) {
4440 $tmp_privs2['References'][] = $row2['Column_name'];
4443 if (count($tmp_privs2['Select']) > 0 && ! in_array('SELECT', $tmp_privs1)) {
4444 $tmp_privs1[] = 'SELECT (`' . join('`, `', $tmp_privs2['Select']) . '`)';
4446 if (count($tmp_privs2['Insert']) > 0 && ! in_array('INSERT', $tmp_privs1)) {
4447 $tmp_privs1[] = 'INSERT (`' . join('`, `', $tmp_privs2['Insert']) . '`)';
4449 if (count($tmp_privs2['Update']) > 0 && ! in_array('UPDATE', $tmp_privs1)) {
4450 $tmp_privs1[] = 'UPDATE (`' . join('`, `', $tmp_privs2['Update']) . '`)';
4452 if (count($tmp_privs2['References']) > 0
4453 && ! in_array('REFERENCES', $tmp_privs1)
4455 $tmp_privs1[]
4456 = 'REFERENCES (`' . join('`, `', $tmp_privs2['References']) . '`)';
4459 $queries[] = 'GRANT ' . join(', ', $tmp_privs1)
4460 . ' ON ' . PMA_Util::backquote($row['Db']) . '.'
4461 . PMA_Util::backquote($row['Table_name'])
4462 . ' TO \'' . PMA_Util::sqlAddSlashes($username)
4463 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\''
4464 . (in_array('Grant', explode(',', $row['Table_priv']))
4465 ? ' WITH GRANT OPTION;'
4466 : ';');
4468 return $queries;
4472 * Get queries for database specific privileges for change or copy user
4474 * @param array $queries queries array with string
4475 * @param string $username username
4476 * @param string $hostname host name
4478 * @return array $queries
4480 function PMA_getDbSpecificPrivsQueriesForChangeOrCopyUser(
4481 $queries, $username, $hostname
4483 $user_host_condition = ' WHERE `User`'
4484 . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'"
4485 . ' AND `Host`'
4486 . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_hostname']) . '\';';
4488 $res = $GLOBALS['dbi']->query(
4489 'SELECT * FROM `mysql`.`db`' . $user_host_condition
4492 while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
4493 $queries[] = 'GRANT ' . join(', ', PMA_extractPrivInfo($row))
4494 . ' ON ' . PMA_Util::backquote($row['Db']) . '.*'
4495 . ' TO \'' . PMA_Util::sqlAddSlashes($username)
4496 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\''
4497 . ($row['Grant_priv'] == 'Y' ? ' WITH GRANT OPTION;' : ';');
4499 $GLOBALS['dbi']->freeResult($res);
4501 $queries = PMA_getTablePrivsQueriesForChangeOrCopyUser(
4502 $user_host_condition, $queries, $username, $hostname
4505 return $queries;
4509 * Prepares queries for adding users and
4510 * also create database and return query and message
4512 * @param boolean $_error whether user create or not
4513 * @param string $real_sql_query SQL query for add a user
4514 * @param string $sql_query SQL query to be displayed
4515 * @param string $username username
4516 * @param string $hostname host name
4517 * @param string $dbname database name
4519 * @return array $sql_query, $message
4521 function PMA_addUserAndCreateDatabase($_error, $real_sql_query, $sql_query,
4522 $username, $hostname, $dbname
4524 if ($_error || (!empty($real_sql_query)
4525 && !$GLOBALS['dbi']->tryQuery($real_sql_query))
4527 $_REQUEST['createdb-1'] = $_REQUEST['createdb-2']
4528 = $_REQUEST['createdb-3'] = null;
4529 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
4530 } else {
4531 $message = PMA_Message::success(__('You have added a new user.'));
4534 if (isset($_REQUEST['createdb-1'])) {
4535 // Create database with same name and grant all privileges
4536 $q = 'CREATE DATABASE IF NOT EXISTS '
4537 . PMA_Util::backquote(
4538 PMA_Util::sqlAddSlashes($username)
4539 ) . ';';
4540 $sql_query .= $q;
4541 if (! $GLOBALS['dbi']->tryQuery($q)) {
4542 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
4546 * Reload the navigation
4548 $GLOBALS['reload'] = true;
4549 $GLOBALS['db'] = $username;
4551 $q = 'GRANT ALL PRIVILEGES ON '
4552 . PMA_Util::backquote(
4553 PMA_Util::escapeMysqlWildcards(
4554 PMA_Util::sqlAddSlashes($username)
4556 ) . '.* TO \''
4557 . PMA_Util::sqlAddSlashes($username)
4558 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
4559 $sql_query .= $q;
4560 if (! $GLOBALS['dbi']->tryQuery($q)) {
4561 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
4565 if (isset($_REQUEST['createdb-2'])) {
4566 // Grant all privileges on wildcard name (username\_%)
4567 $q = 'GRANT ALL PRIVILEGES ON '
4568 . PMA_Util::backquote(
4569 PMA_Util::sqlAddSlashes($username) . '\_%'
4570 ) . '.* TO \''
4571 . PMA_Util::sqlAddSlashes($username)
4572 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
4573 $sql_query .= $q;
4574 if (! $GLOBALS['dbi']->tryQuery($q)) {
4575 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
4579 if (isset($_REQUEST['createdb-3'])) {
4580 // Grant all privileges on the specified database to the new user
4581 $q = 'GRANT ALL PRIVILEGES ON '
4582 . PMA_Util::backquote(
4583 PMA_Util::sqlAddSlashes($dbname)
4584 ) . '.* TO \''
4585 . PMA_Util::sqlAddSlashes($username)
4586 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
4587 $sql_query .= $q;
4588 if (! $GLOBALS['dbi']->tryQuery($q)) {
4589 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
4592 return array($sql_query, $message);
4596 * Get SQL queries for Display and Add user
4598 * @param string $username username
4599 * @param string $hostname host name
4600 * @param string $password password
4602 * @return array ($create_user_real, $create_user_show,$real_sql_query, $sql_query)
4604 function PMA_getSqlQueriesForDisplayAndAddUser($username, $hostname, $password)
4606 $create_user_real = 'CREATE USER \''
4607 . PMA_Util::sqlAddSlashes($username) . '\'@\''
4608 . PMA_Util::sqlAddSlashes($hostname) . '\'';
4610 $real_sql_query = 'GRANT ' . join(', ', PMA_extractPrivInfo()) . ' ON *.* TO \''
4611 . PMA_Util::sqlAddSlashes($username) . '\'@\''
4612 . PMA_Util::sqlAddSlashes($hostname) . '\'';
4614 if ($_POST['pred_password'] != 'none' && $_POST['pred_password'] != 'keep') {
4615 $sql_query = $real_sql_query;
4616 // Requires SELECT privilege on mysql database
4617 // for using this with GRANT queries. It can be skipped.
4618 if ($GLOBALS['is_superuser']) {
4619 $sql_query .= ' IDENTIFIED BY \'***\'';
4620 $real_sql_query .= ' IDENTIFIED BY \''
4621 . PMA_Util::sqlAddSlashes($_POST['pma_pw']) . '\'';
4623 if (isset($create_user_real)) {
4624 $create_user_show = $create_user_real . ' IDENTIFIED BY \'***\'';
4625 $create_user_real .= ' IDENTIFIED BY \''
4626 . PMA_Util::sqlAddSlashes($_POST['pma_pw']) . '\'';
4628 } else {
4629 if ($_POST['pred_password'] == 'keep' && ! empty($password)) {
4630 $real_sql_query .= ' IDENTIFIED BY PASSWORD \'' . $password . '\'';
4631 if (isset($create_user_real)) {
4632 $create_user_real .= ' IDENTIFIED BY PASSWORD \'' . $password . '\'';
4635 $sql_query = $real_sql_query;
4636 if (isset($create_user_real)) {
4637 $create_user_show = $create_user_real;
4641 // add REQUIRE clause
4642 $require_clause = PMA_getRequireClause();
4643 $real_sql_query .= $require_clause;
4644 $sql_query .= $require_clause;
4646 if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
4647 || (isset($_POST['max_questions']) || isset($_POST['max_connections'])
4648 || isset($_POST['max_updates']) || isset($_POST['max_user_connections']))
4650 $with_clause = PMA_getWithClauseForAddUserAndUpdatePrivs();
4651 $real_sql_query .= $with_clause;
4652 $sql_query .= $with_clause;
4655 if (isset($create_user_real)) {
4656 $create_user_real .= ';';
4657 $create_user_show .= ';';
4659 $real_sql_query .= ';';
4660 $sql_query .= ';';
4661 // No Global GRANT_OPTION privilege
4662 if (!$GLOBALS['is_grantuser']) {
4663 $real_sql_query = '';
4664 $sql_query = '';
4667 return array($create_user_real,
4668 $create_user_show,
4669 $real_sql_query,
4670 $sql_query