Converted referrals_report.php to standard security model, take 2.
[openemr.git] / phpmyadmin / libraries / server_privileges.lib.php
blob9ad749a177fe99ec218839cf749011e64244677e
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * set of functions with the Privileges section in pma
6 * @package PhpMyAdmin
7 */
9 if (! defined('PHPMYADMIN')) {
10 exit;
13 /**
14 * Get Html for User Group Dialog
16 * @param string $username username
17 * @param bool $is_menuswork Is menuswork set in configuration
19 * @return string html
21 function PMA_getHtmlForUserGroupDialog($username, $is_menuswork)
23 $html = '';
24 if (! empty($_REQUEST['edit_user_group_dialog']) && $is_menuswork) {
25 $dialog = PMA_getHtmlToChooseUserGroup($username);
26 $response = PMA_Response::getInstance();
27 if ($GLOBALS['is_ajax_request']) {
28 $response->addJSON('message', $dialog);
29 exit;
30 } else {
31 $html .= $dialog;
35 return $html;
38 /**
39 * Escapes wildcard in a database+table specification
40 * before using it in a GRANT statement.
42 * Escaping a wildcard character in a GRANT is only accepted at the global
43 * or database level, not at table level; this is why I remove
44 * the escaping character. Internally, in mysql.tables_priv.Db there are
45 * no escaping (for example test_db) but in mysql.db you'll see test\_db
46 * for a db-specific privilege.
48 * @param string $dbname Database name
49 * @param string $tablename Table name
51 * @return string the escaped (if necessary) database.table
53 function PMA_wildcardEscapeForGrant($dbname, $tablename)
55 if (!/*overload*/mb_strlen($dbname)) {
56 $db_and_table = '*.*';
57 } else {
58 if (/*overload*/mb_strlen($tablename)) {
59 $db_and_table = PMA_Util::backquote(
60 PMA_Util::unescapeMysqlWildcards($dbname)
62 . '.' . PMA_Util::backquote($tablename);
63 } else {
64 $db_and_table = PMA_Util::backquote($dbname) . '.*';
67 return $db_and_table;
70 /**
71 * Generates a condition on the user name
73 * @param string $initial the user's initial
75 * @return string the generated condition
77 function PMA_rangeOfUsers($initial = '')
79 // strtolower() is used because the User field
80 // might be BINARY, so LIKE would be case sensitive
81 if ($initial === null || $initial === '') {
82 return '';
85 $ret = " WHERE `User` LIKE '"
86 . PMA_Util::sqlAddSlashes($initial, true) . "%'"
87 . " OR `User` LIKE '"
88 . PMA_Util::sqlAddSlashes(/*overload*/mb_strtolower($initial), true)
89 . "%'";
90 return $ret;
91 } // end function
93 /**
94 * Formats privilege name for a display
96 * @param array $privilege Privilege information
97 * @param boolean $html Whether to use HTML
99 * @return string
101 function PMA_formatPrivilege($privilege, $html)
103 if ($html) {
104 return '<dfn title="' . $privilege[2] . '">'
105 . $privilege[1] . '</dfn>';
106 } else {
107 return $privilege[1];
112 * Parses privileges into an array, it modifies the array
114 * @param array &$row Results row from
116 * @return void
118 function PMA_fillInTablePrivileges(&$row)
120 $row1 = $GLOBALS['dbi']->fetchSingleRow(
121 'SHOW COLUMNS FROM `mysql`.`tables_priv` LIKE \'Table_priv\';',
122 'ASSOC', $GLOBALS['userlink']
124 // note: in MySQL 5.0.3 we get "Create View', 'Show view';
125 // the View for Create is spelled with uppercase V
126 // the view for Show is spelled with lowercase v
127 // and there is a space between the words
129 $av_grants = explode(
130 '\',\'',
131 /*overload*/mb_substr(
132 $row1['Type'],
133 /*overload*/mb_strpos($row1['Type'], '(') + 2,
134 /*overload*/mb_strpos($row1['Type'], ')')
135 - /*overload*/mb_strpos($row1['Type'], '(') - 3
139 $users_grants = explode(',', $row['Table_priv']);
141 foreach ($av_grants as $current_grant) {
142 $row[$current_grant . '_priv']
143 = in_array($current_grant, $users_grants) ? 'Y' : 'N';
145 unset($row['Table_priv']);
150 * Extracts the privilege information of a priv table row
152 * @param array|null $row the row
153 * @param boolean $enableHTML add <dfn> tag with tooltips
154 * @param boolean $tablePrivs whether row contains table privileges
156 * @global resource $user_link the database connection
158 * @return array
160 function PMA_extractPrivInfo($row = null, $enableHTML = false, $tablePrivs = false)
162 if ($tablePrivs) {
163 $grants = PMA_getTableGrantsArray();
164 } else {
165 $grants = PMA_getGrantsArray();
168 if (! is_null($row) && isset($row['Table_priv'])) {
169 PMA_fillInTablePrivileges($row);
172 $privs = array();
173 $allPrivileges = true;
174 foreach ($grants as $current_grant) {
175 if ((! is_null($row) && isset($row[$current_grant[0]]))
176 || (is_null($row) && isset($GLOBALS[$current_grant[0]]))
178 if ((! is_null($row) && $row[$current_grant[0]] == 'Y')
179 || (is_null($row)
180 && ($GLOBALS[$current_grant[0]] == 'Y'
181 || (is_array($GLOBALS[$current_grant[0]])
182 && count($GLOBALS[$current_grant[0]]) == $_REQUEST['column_count']
183 && empty($GLOBALS[$current_grant[0] . '_none']))))
185 $privs[] = PMA_formatPrivilege($current_grant, $enableHTML);
186 } elseif (! empty($GLOBALS[$current_grant[0]])
187 && is_array($GLOBALS[$current_grant[0]])
188 && empty($GLOBALS[$current_grant[0] . '_none'])
190 $privs[] = PMA_formatPrivilege($current_grant, $enableHTML)
191 . ' (`' . join('`, `', $GLOBALS[$current_grant[0]]) . '`)';
192 } else {
193 $allPrivileges = false;
197 if (empty($privs)) {
198 if ($enableHTML) {
199 $privs[] = '<dfn title="' . __('No privileges.') . '">USAGE</dfn>';
200 } else {
201 $privs[] = 'USAGE';
203 } elseif ($allPrivileges
204 && (! isset($_POST['grant_count']) || count($privs) == $_POST['grant_count'])
206 if ($enableHTML) {
207 $privs = array('<dfn title="'
208 . __('Includes all privileges except GRANT.')
209 . '">ALL PRIVILEGES</dfn>'
211 } else {
212 $privs = array('ALL PRIVILEGES');
215 return $privs;
216 } // end of the 'PMA_extractPrivInfo()' function
219 * Returns an array of table grants and their descriptions
221 * @return array array of table grants
223 function PMA_getTableGrantsArray()
225 return array(
226 array(
227 'Delete',
228 'DELETE',
229 $GLOBALS['strPrivDescDelete']
231 array(
232 'Create',
233 'CREATE',
234 $GLOBALS['strPrivDescCreateTbl']
236 array(
237 'Drop',
238 'DROP',
239 $GLOBALS['strPrivDescDropTbl']
241 array(
242 'Index',
243 'INDEX',
244 $GLOBALS['strPrivDescIndex']
246 array(
247 'Alter',
248 'ALTER',
249 $GLOBALS['strPrivDescAlter']
251 array(
252 'Create View',
253 'CREATE_VIEW',
254 $GLOBALS['strPrivDescCreateView']
256 array(
257 'Show view',
258 'SHOW_VIEW',
259 $GLOBALS['strPrivDescShowView']
261 array(
262 'Trigger',
263 'TRIGGER',
264 $GLOBALS['strPrivDescTrigger']
270 * Get the grants array which contains all the privilege types
271 * and relevant grant messages
273 * @return array
275 function PMA_getGrantsArray()
277 return array(
278 array(
279 'Select_priv',
280 'SELECT',
281 __('Allows reading data.')
283 array(
284 'Insert_priv',
285 'INSERT',
286 __('Allows inserting and replacing data.')
288 array(
289 'Update_priv',
290 'UPDATE',
291 __('Allows changing data.')
293 array(
294 'Delete_priv',
295 'DELETE',
296 __('Allows deleting data.')
298 array(
299 'Create_priv',
300 'CREATE',
301 __('Allows creating new databases and tables.')
303 array(
304 'Drop_priv',
305 'DROP',
306 __('Allows dropping databases and tables.')
308 array(
309 'Reload_priv',
310 'RELOAD',
311 __('Allows reloading server settings and flushing the server\'s caches.')
313 array(
314 'Shutdown_priv',
315 'SHUTDOWN',
316 __('Allows shutting down the server.')
318 array(
319 'Process_priv',
320 'PROCESS',
321 __('Allows viewing processes of all users.')
323 array(
324 'File_priv',
325 'FILE',
326 __('Allows importing data from and exporting data into files.')
328 array(
329 'References_priv',
330 'REFERENCES',
331 __('Has no effect in this MySQL version.')
333 array(
334 'Index_priv',
335 'INDEX',
336 __('Allows creating and dropping indexes.')
338 array(
339 'Alter_priv',
340 'ALTER',
341 __('Allows altering the structure of existing tables.')
343 array(
344 'Show_db_priv',
345 'SHOW DATABASES',
346 __('Gives access to the complete list of databases.')
348 array(
349 'Super_priv',
350 'SUPER',
352 'Allows connecting, even if maximum number of connections '
353 . 'is reached; required for most administrative operations '
354 . 'like setting global variables or killing threads of other users.'
357 array(
358 'Create_tmp_table_priv',
359 'CREATE TEMPORARY TABLES',
360 __('Allows creating temporary tables.')
362 array(
363 'Lock_tables_priv',
364 'LOCK TABLES',
365 __('Allows locking tables for the current thread.')
367 array(
368 'Repl_slave_priv',
369 'REPLICATION SLAVE',
370 __('Needed for the replication slaves.')
372 array(
373 'Repl_client_priv',
374 'REPLICATION CLIENT',
375 __('Allows the user to ask where the slaves / masters are.')
377 array(
378 'Create_view_priv',
379 'CREATE VIEW',
380 __('Allows creating new views.')
382 array(
383 'Event_priv',
384 'EVENT',
385 __('Allows to set up events for the event scheduler.')
387 array(
388 'Trigger_priv',
389 'TRIGGER',
390 __('Allows creating and dropping triggers.')
392 // for table privs:
393 array(
394 'Create View_priv',
395 'CREATE VIEW',
396 __('Allows creating new views.')
398 array(
399 'Show_view_priv',
400 'SHOW VIEW',
401 __('Allows performing SHOW CREATE VIEW queries.')
403 // for table privs:
404 array(
405 'Show view_priv',
406 'SHOW VIEW',
407 __('Allows performing SHOW CREATE VIEW queries.')
409 array(
410 'Create_routine_priv',
411 'CREATE ROUTINE',
412 __('Allows creating stored routines.')
414 array(
415 'Alter_routine_priv',
416 'ALTER ROUTINE',
417 __('Allows altering and dropping stored routines.')
419 array(
420 'Create_user_priv',
421 'CREATE USER',
422 __('Allows creating, dropping and renaming user accounts.')
424 array(
425 'Execute_priv',
426 'EXECUTE',
427 __('Allows executing stored routines.')
433 * Displays on which column(s) a table-specific privilege is granted
435 * @param array $columns columns array
436 * @param array $row first row from result or boolean false
437 * @param string $name_for_select privilege types - Select_priv, Insert_priv
438 * Update_priv, References_priv
439 * @param string $priv_for_header privilege for header
440 * @param string $name privilege name: insert, select, update, references
441 * @param string $name_for_dfn name for dfn
442 * @param string $name_for_current name for current
444 * @return string $html_output html snippet
446 function PMA_getHtmlForColumnPrivileges($columns, $row, $name_for_select,
447 $priv_for_header, $name, $name_for_dfn, $name_for_current
449 $html_output = '<div class="item" id="div_item_' . $name . '">' . "\n"
450 . '<label for="select_' . $name . '_priv">' . "\n"
451 . '<code><dfn title="' . $name_for_dfn . '">'
452 . $priv_for_header . '</dfn></code>' . "\n"
453 . '</label><br />' . "\n"
454 . '<select id="select_' . $name . '_priv" name="'
455 . $name_for_select . '[]" multiple="multiple" size="8">' . "\n";
457 foreach ($columns as $currCol => $currColPrivs) {
458 $html_output .= '<option '
459 . 'value="' . htmlspecialchars($currCol) . '"';
460 if ($row[$name_for_select] == 'Y'
461 || $currColPrivs[$name_for_current]
463 $html_output .= ' selected="selected"';
465 $html_output .= '>'
466 . htmlspecialchars($currCol) . '</option>' . "\n";
469 $html_output .= '</select>' . "\n"
470 . '<i>' . __('Or') . '</i>' . "\n"
471 . '<label for="checkbox_' . $name_for_select
472 . '_none"><input type="checkbox"'
473 . ' name="' . $name_for_select . '_none" id="checkbox_'
474 . $name_for_select . '_none" title="'
475 . _pgettext('None privileges', 'None') . '" />'
476 . _pgettext('None privileges', 'None') . '</label>' . "\n"
477 . '</div>' . "\n";
478 return $html_output;
479 } // end function
482 * Get sql query for display privileges table
484 * @param string $db the database
485 * @param string $table the table
486 * @param string $username username for database connection
487 * @param string $hostname hostname for database connection
489 * @return string sql query
491 function PMA_getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname)
493 if ($db == '*') {
494 return "SELECT * FROM `mysql`.`user`"
495 . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
496 . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "';";
497 } elseif ($table == '*') {
498 return "SELECT * FROM `mysql`.`db`"
499 . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
500 . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "'"
501 . " AND '" . PMA_Util::unescapeMysqlWildcards($db) . "'"
502 . " LIKE `Db`;";
504 return "SELECT `Table_priv`"
505 . " FROM `mysql`.`tables_priv`"
506 . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
507 . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "'"
508 . " AND `Db` = '" . PMA_Util::unescapeMysqlWildcards($db) . "'"
509 . " AND `Table_name` = '" . PMA_Util::sqlAddSlashes($table) . "';";
513 * Displays a dropdown to select the user group
514 * with menu items configured to each of them.
516 * @param string $username username
518 * @return string html to select the user group
520 function PMA_getHtmlToChooseUserGroup($username)
522 $html_output = '<form class="ajax" id="changeUserGroupForm"'
523 . ' action="server_privileges.php" method="post">';
524 $params = array('username' => $username);
525 $html_output .= PMA_URL_getHiddenInputs($params);
526 $html_output .= '<fieldset id="fieldset_user_group_selection">';
527 $html_output .= '<legend>' . __('User group') . '</legend>';
529 $cfgRelation = PMA_getRelationsParam();
530 $groupTable = PMA_Util::backquote($cfgRelation['db'])
531 . "." . PMA_Util::backquote($cfgRelation['usergroups']);
532 $userTable = PMA_Util::backquote($cfgRelation['db'])
533 . "." . PMA_Util::backquote($cfgRelation['users']);
535 $userGroups = array();
536 $sql_query = "SELECT DISTINCT `usergroup` FROM " . $groupTable;
537 $result = PMA_queryAsControlUser($sql_query, false);
538 if ($result) {
539 while ($row = $GLOBALS['dbi']->fetchRow($result)) {
540 $userGroups[] = $row[0];
543 $GLOBALS['dbi']->freeResult($result);
545 $userGroup = '';
546 if (isset($GLOBALS['username'])) {
547 $sql_query = "SELECT `usergroup` FROM " . $userTable
548 . " WHERE `username` = '" . PMA_Util::sqlAddSlashes($username) . "'";
549 $userGroup = $GLOBALS['dbi']->fetchValue(
550 $sql_query, 0, 0, $GLOBALS['controllink']
554 $html_output .= __('User group') . ': ';
555 $html_output .= '<select name="userGroup">';
556 $html_output .= '<option value=""></option>';
557 foreach ($userGroups as $oneUserGroup) {
558 $html_output .= '<option value="' . htmlspecialchars($oneUserGroup) . '"'
559 . ($oneUserGroup == $userGroup ? ' selected="selected"' : '')
560 . '>'
561 . htmlspecialchars($oneUserGroup)
562 . '</option>';
564 $html_output .= '</select>';
565 $html_output .= '<input type="hidden" name="changeUserGroup" value="1">';
566 $html_output .= '</fieldset>';
567 $html_output .= '</form>';
568 return $html_output;
572 * Sets the user group from request values
574 * @param string $username username
575 * @param string $userGroup user group to set
577 * @return void
579 function PMA_setUserGroup($username, $userGroup)
581 $cfgRelation = PMA_getRelationsParam();
582 $userTable = PMA_Util::backquote($cfgRelation['db'])
583 . "." . PMA_Util::backquote($cfgRelation['users']);
585 $sql_query = "SELECT `usergroup` FROM " . $userTable
586 . " WHERE `username` = '" . PMA_Util::sqlAddSlashes($username) . "'";
587 $oldUserGroup = $GLOBALS['dbi']->fetchValue(
588 $sql_query, 0, 0, $GLOBALS['controllink']
591 if ($oldUserGroup === false) {
592 $upd_query = "INSERT INTO " . $userTable . "(`username`, `usergroup`)"
593 . " VALUES ('" . PMA_Util::sqlAddSlashes($username) . "', "
594 . "'" . PMA_Util::sqlAddSlashes($userGroup) . "')";
595 } else {
596 if (empty($userGroup)) {
597 $upd_query = "DELETE FROM " . $userTable
598 . " WHERE `username`='" . PMA_Util::sqlAddSlashes($username) . "'";
599 } elseif ($oldUserGroup != $userGroup) {
600 $upd_query = "UPDATE " . $userTable
601 . " SET `usergroup`='" . PMA_Util::sqlAddSlashes($userGroup) . "'"
602 . " WHERE `username`='" . PMA_Util::sqlAddSlashes($username) . "'";
605 if (isset($upd_query)) {
606 PMA_queryAsControlUser($upd_query);
611 * Displays the privileges form table
613 * @param string $db the database
614 * @param string $table the table
615 * @param boolean $submit whether to display the submit button or not
617 * @global array $cfg the phpMyAdmin configuration
618 * @global resource $user_link the database connection
620 * @return string html snippet
622 function PMA_getHtmlToDisplayPrivilegesTable($db = '*',
623 $table = '*', $submit = true
625 $html_output = '';
626 $sql_query = '';
628 if ($db == '*') {
629 $table = '*';
632 if (isset($GLOBALS['username'])) {
633 $username = $GLOBALS['username'];
634 $hostname = $GLOBALS['hostname'];
635 $sql_query = PMA_getSqlQueryForDisplayPrivTable(
636 $db, $table, $username, $hostname
638 $row = $GLOBALS['dbi']->fetchSingleRow($sql_query);
640 if (empty($row)) {
641 if ($table == '*' && $GLOBALS['is_superuser']) {
642 if ($db == '*') {
643 $sql_query = 'SHOW COLUMNS FROM `mysql`.`user`;';
644 } elseif ($table == '*') {
645 $sql_query = 'SHOW COLUMNS FROM `mysql`.`db`;';
647 $res = $GLOBALS['dbi']->query($sql_query);
648 while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
649 if (mb_substr($row1[0], 0, 4) == 'max_') {
650 $row[$row1[0]] = 0;
651 } elseif (mb_substr($row1[0], 0, 5) == 'x509_'
652 || mb_substr($row1[0], 0, 4) == 'ssl_'
654 $row[$row1[0]] = '';
655 } else {
656 $row[$row1[0]] = 'N';
659 $GLOBALS['dbi']->freeResult($res);
660 } elseif ($table == '*') {
661 $row = array();
662 } else {
663 $row = array('Table_priv' => '');
666 if (isset($row['Table_priv'])) {
667 PMA_fillInTablePrivileges($row);
669 // get columns
670 $res = $GLOBALS['dbi']->tryQuery(
671 'SHOW COLUMNS FROM '
672 . PMA_Util::backquote(
673 PMA_Util::unescapeMysqlWildcards($db)
675 . '.' . PMA_Util::backquote($table) . ';'
677 $columns = array();
678 if ($res) {
679 while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
680 $columns[$row1[0]] = array(
681 'Select' => false,
682 'Insert' => false,
683 'Update' => false,
684 'References' => false
687 $GLOBALS['dbi']->freeResult($res);
689 unset($res, $row1);
691 // table-specific privileges
692 if (! empty($columns)) {
693 $html_output .= PMA_getHtmlForTableSpecificPrivileges(
694 $username, $hostname, $db, $table, $columns, $row
696 } else {
697 // global or db-specific
698 $html_output .= PMA_getHtmlForGlobalOrDbSpecificPrivs($db, $table, $row);
700 $html_output .= '</fieldset>' . "\n";
701 if ($submit) {
702 $html_output .= '<fieldset id="fieldset_user_privtable_footer" '
703 . 'class="tblFooters">' . "\n"
704 . '<input type="hidden" name="update_privs" value="1" />' . "\n"
705 . '<input type="submit" value="' . __('Go') . '" />' . "\n"
706 . '</fieldset>' . "\n";
708 return $html_output;
709 } // end of the 'PMA_displayPrivTable()' function
712 * Get HTML for "Require"
714 * @param array $row privilege array
716 * @return string html snippet
718 function PMA_getHtmlForRequires($row)
720 $html_output = '<fieldset>';
722 $html_output .= '<legend>';
723 $html_output .= '<input type="checkbox" name="SSL_priv" id="checkbox_SSL_priv"'
724 . ' value="Y" title="'
725 . __(
726 'Requires SSL-encrypted connections.'
728 . '"'
729 . ((isset($row['ssl_type']) && $row['ssl_type'] != '')
730 ? ' checked="checked"'
731 : ''
733 . '/>';
734 $html_output .= __('Require SSL') . '</legend>';
735 $html_output .= '<div id="require_ssl_div">';
737 // Specified
738 $html_output .= '<div class="item">';
739 $html_output .= '<input type="radio" name="ssl_type" id="ssl_type_specified"'
740 . ' value="specified"'
741 . ((isset($row['ssl_type']) && $row['ssl_type'] == 'SPECIFIED')
742 ? ' checked="checked"'
743 : ''
745 . '/>';
747 $html_output .= '<label for="ssl_type_speified"><code>'
748 . 'SPECIFIED'
749 . '</code></label>';
750 $html_output .= '</div>';
752 $html_output .= '<div id="specified_div" style="padding-left:20px;">';
754 // REQUIRE CIPHER
755 $html_output .= '<div class="item">';
756 $html_output .= '<label for="text_ssl_cipher">'
757 . '<code><dfn title="'
758 . __(
759 'Requires that a specific cipher method be used for a connection.'
761 . '">'
762 . 'REQUIRE CIPHER'
763 . '</dfn></code></label>';
764 $html_output .= '<input type="text" name="ssl_cipher" id="text_ssl_cipher" '
765 . 'value="' . (isset($row['ssl_cipher']) ? $row['ssl_cipher'] : '') . '" '
766 . 'size=80" title="'
767 . __(
768 'Requires that a specific cipher method be used for a connection.'
770 . '" />';
771 $html_output .= '</div>';
773 // REQUIRE ISSUER
774 $html_output .= '<div class="item">';
775 $html_output .= '<label for="text_x509_issuer">'
776 . '<code><dfn title="'
777 . __(
778 'Requires that a valid X509 certificate issued by this CA be presented.'
780 . '">'
781 . 'REQUIRE ISSUER'
782 . '</dfn></code></label>';
783 $html_output .= '<input type="text" name="x509_issuer" id="text_x509_issuer" '
784 . 'value="' . (isset($row['x509_issuer']) ? $row['x509_issuer'] : '') . '" '
785 . 'size=80" title="'
786 . __(
787 'Requires that a valid X509 certificate issued by this CA be presented.'
789 . '" />';
790 $html_output .= '</div>';
792 // REQUIRE SUBJECT
793 $html_output .= '<div class="item">';
794 $html_output .= '<label for="text_x509_subject">'
795 . '<code><dfn title="'
796 . __(
797 'Requires that a valid X509 certificate with this subject be presented.'
799 . '">'
800 . 'REQUIRE SUBJECT'
801 . '</dfn></code></label>';
802 $html_output .= '<input type="text" name="x509_subject" id="text_x509_subject" '
803 . 'value="' . (isset($row['x509_subject']) ? $row['x509_subject'] : '')
804 . '" size=80" title="'
805 . __(
806 'Requires that a valid X509 certificate with this subject be presented.'
808 . '" />';
809 $html_output .= '</div>';
811 $html_output .= '</div>';
813 // REQUIRE X509
814 $html_output .= '<div class="item">';
815 $html_output .= '<input type="radio" name="ssl_type" id="ssl_type_X509"'
816 . ' value="X509" title="'
817 . __(
818 'Requires a valid X509 certificate.'
820 . '"'
821 . ((isset($row['ssl_type']) && $row['ssl_type'] == 'X509')
822 ? ' checked="checked"'
823 : ''
825 . '/>';
827 $html_output .= '<label for="radio_X509_priv"><code>'
828 . 'REQUIRE X509'
829 . '</code></label>';
830 $html_output .= '</div>';
832 // REQUIRE SSL
833 $html_output .= '<div class="item">';
834 $html_output .= '<input type="radio" name="ssl_type" id="ssl_type_ANY"'
835 . ' value="ANY" title="'
836 . __(
837 'Requires SSL-encrypted connections.'
839 . '"'
840 . ((isset($row['ssl_type'])
841 && ($row['ssl_type'] == 'ANY'
842 || $row['ssl_type'] == ''))
843 ? ' checked="checked"'
844 : ''
846 . '/>';
848 $html_output .= '<label for="ssl_type_ANY"><code>'
849 . 'REQUIRE SSL'
850 . '</code></label>';
851 $html_output .= '</div>';
853 $html_output .= '</div>';
854 $html_output .= '</fieldset>';
856 return $html_output;
860 * Get HTML for "Resource limits"
862 * @param array $row first row from result or boolean false
864 * @return string html snippet
866 function PMA_getHtmlForResourceLimits($row)
868 $html_output = '<fieldset>' . "\n"
869 . '<legend>' . __('Resource limits') . '</legend>' . "\n"
870 . '<p><small>'
871 . '<i>' . __('Note: Setting these options to 0 (zero) removes the limit.')
872 . '</i></small></p>' . "\n";
874 $html_output .= '<div class="item">' . "\n"
875 . '<label for="text_max_questions">'
876 . '<code><dfn title="'
877 . __(
878 'Limits the number of queries the user may send to the server per hour.'
880 . '">'
881 . 'MAX QUERIES PER HOUR'
882 . '</dfn></code></label>' . "\n"
883 . '<input type="number" name="max_questions" id="text_max_questions" '
884 . 'value="'
885 . (isset($row['max_questions']) ? $row['max_questions'] : '0')
886 . '" min="0" '
887 . 'title="'
888 . __(
889 'Limits the number of queries the user may send to the server per hour.'
891 . '" />' . "\n"
892 . '</div>' . "\n";
894 $html_output .= '<div class="item">' . "\n"
895 . '<label for="text_max_updates">'
896 . '<code><dfn title="'
897 . __(
898 'Limits the number of commands that change any table '
899 . 'or database the user may execute per hour.'
900 ) . '">'
901 . 'MAX UPDATES PER HOUR'
902 . '</dfn></code></label>' . "\n"
903 . '<input type="number" name="max_updates" id="text_max_updates" '
904 . 'value="'
905 . (isset($row['max_updates']) ? $row['max_updates'] : '0')
906 . '" min="0" '
907 . 'title="'
908 . __(
909 'Limits the number of commands that change any table '
910 . 'or database the user may execute per hour.'
912 . '" />' . "\n"
913 . '</div>' . "\n";
915 $html_output .= '<div class="item">' . "\n"
916 . '<label for="text_max_connections">'
917 . '<code><dfn title="'
918 . __(
919 'Limits the number of new connections the user may open per hour.'
920 ) . '">'
921 . 'MAX CONNECTIONS PER HOUR'
922 . '</dfn></code></label>' . "\n"
923 . '<input type="number" name="max_connections" id="text_max_connections" '
924 . 'value="'
925 . (isset($row['max_connections']) ? $row['max_connections'] : '0')
926 . '" min="0" '
927 . 'title="' . __(
928 'Limits the number of new connections the user may open per hour.'
930 . '" />' . "\n"
931 . '</div>' . "\n";
933 $html_output .= '<div class="item">' . "\n"
934 . '<label for="text_max_user_connections">'
935 . '<code><dfn title="'
936 . __('Limits the number of simultaneous connections the user may have.')
937 . '">'
938 . 'MAX USER_CONNECTIONS'
939 . '</dfn></code></label>' . "\n"
940 . '<input type="number" name="max_user_connections" '
941 . 'id="text_max_user_connections" '
942 . 'value="'
943 . (isset($row['max_user_connections']) ? $row['max_user_connections'] : '0')
944 . '" '
945 . 'title="'
946 . __('Limits the number of simultaneous connections the user may have.')
947 . '" />' . "\n"
948 . '</div>' . "\n";
950 $html_output .= '</fieldset>' . "\n";
952 return $html_output;
956 * Get the HTML snippet for table specific privileges
958 * @param string $username username for database connection
959 * @param string $hostname hostname for database connection
960 * @param string $db the database
961 * @param string $table the table
962 * @param array $columns columns array
963 * @param array $row current privileges row
965 * @return string $html_output
967 function PMA_getHtmlForTableSpecificPrivileges(
968 $username, $hostname, $db, $table, $columns, $row
970 $res = $GLOBALS['dbi']->query(
971 'SELECT `Column_name`, `Column_priv`'
972 . ' FROM `mysql`.`columns_priv`'
973 . ' WHERE `User`'
974 . ' = \'' . PMA_Util::sqlAddSlashes($username) . "'"
975 . ' AND `Host`'
976 . ' = \'' . PMA_Util::sqlAddSlashes($hostname) . "'"
977 . ' AND `Db`'
978 . ' = \'' . PMA_Util::sqlAddSlashes(
979 PMA_Util::unescapeMysqlWildcards($db)
980 ) . "'"
981 . ' AND `Table_name`'
982 . ' = \'' . PMA_Util::sqlAddSlashes($table) . '\';'
985 while ($row1 = $GLOBALS['dbi']->fetchRow($res)) {
986 $row1[1] = explode(',', $row1[1]);
987 foreach ($row1[1] as $current) {
988 $columns[$row1[0]][$current] = true;
991 $GLOBALS['dbi']->freeResult($res);
992 unset($res, $row1, $current);
994 $html_output = '<input type="hidden" name="grant_count" '
995 . 'value="' . count($row) . '" />' . "\n"
996 . '<input type="hidden" name="column_count" '
997 . 'value="' . count($columns) . '" />' . "\n"
998 . '<fieldset id="fieldset_user_priv">' . "\n"
999 . '<legend data-submenu-label="Table">' . __('Table-specific privileges')
1000 . PMA_Util::showHint(
1001 __('Note: MySQL privilege names are expressed in English.')
1003 . '</legend>' . "\n";
1005 // privs that are attached to a specific column
1006 $html_output .= PMA_getHtmlForAttachedPrivilegesToTableSpecificColumn(
1007 $columns, $row
1010 // privs that are not attached to a specific column
1011 $html_output .= '<div class="item">' . "\n"
1012 . PMA_getHtmlForNotAttachedPrivilegesToTableSpecificColumn($row)
1013 . '</div>' . "\n";
1015 // for Safari 2.0.2
1016 $html_output .= '<div class="clearfloat"></div>' . "\n";
1018 return $html_output;
1022 * Get HTML snippet for privileges that are attached to a specific column
1024 * @param array $columns columns array
1025 * @param array $row first row from result or boolean false
1027 * @return string $html_output
1029 function PMA_getHtmlForAttachedPrivilegesToTableSpecificColumn($columns, $row)
1031 $html_output = PMA_getHtmlForColumnPrivileges(
1032 $columns, $row, 'Select_priv', 'SELECT',
1033 'select', __('Allows reading data.'), 'Select'
1036 $html_output .= PMA_getHtmlForColumnPrivileges(
1037 $columns, $row, 'Insert_priv', 'INSERT',
1038 'insert', __('Allows inserting and replacing data.'), 'Insert'
1041 $html_output .= PMA_getHtmlForColumnPrivileges(
1042 $columns, $row, 'Update_priv', 'UPDATE',
1043 'update', __('Allows changing data.'), 'Update'
1046 $html_output .= PMA_getHtmlForColumnPrivileges(
1047 $columns, $row, 'References_priv', 'REFERENCES', 'references',
1048 __('Has no effect in this MySQL version.'), 'References'
1050 return $html_output;
1054 * Get HTML for privileges that are not attached to a specific column
1056 * @param array $row first row from result or boolean false
1058 * @return string $html_output
1060 function PMA_getHtmlForNotAttachedPrivilegesToTableSpecificColumn($row)
1062 $html_output = '';
1064 foreach ($row as $current_grant => $current_grant_value) {
1065 $grant_type = substr($current_grant, 0, -5);
1066 if (in_array($grant_type, array('Select', 'Insert', 'Update', 'References'))
1068 continue;
1070 // make a substitution to match the messages variables;
1071 // also we must substitute the grant we get, because we can't generate
1072 // a form variable containing blanks (those would get changed to
1073 // an underscore when receiving the POST)
1074 if ($current_grant == 'Create View_priv') {
1075 $tmp_current_grant = 'CreateView_priv';
1076 $current_grant = 'Create_view_priv';
1077 } elseif ($current_grant == 'Show view_priv') {
1078 $tmp_current_grant = 'ShowView_priv';
1079 $current_grant = 'Show_view_priv';
1080 } else {
1081 $tmp_current_grant = $current_grant;
1084 $html_output .= '<div class="item">' . "\n"
1085 . '<input type="checkbox"'
1086 . ' name="' . $current_grant . '" id="checkbox_' . $current_grant
1087 . '" value="Y" '
1088 . ($current_grant_value == 'Y' ? 'checked="checked" ' : '')
1089 . 'title="';
1091 $privGlobalName = 'strPrivDesc'
1092 . /*overload*/mb_substr(
1093 $tmp_current_grant,
1095 (/*overload*/mb_strlen($tmp_current_grant) - 5)
1097 $html_output .= (isset($GLOBALS[$privGlobalName])
1098 ? $GLOBALS[$privGlobalName]
1099 : $GLOBALS[$privGlobalName . 'Tbl']
1101 . '"/>' . "\n";
1103 $privGlobalName1 = 'strPrivDesc'
1104 . /*overload*/mb_substr(
1105 $tmp_current_grant,
1109 $html_output .= '<label for="checkbox_' . $current_grant
1110 . '"><code><dfn title="'
1111 . (isset($GLOBALS[$privGlobalName1])
1112 ? $GLOBALS[$privGlobalName1]
1113 : $GLOBALS[$privGlobalName1 . 'Tbl']
1115 . '">'
1116 . /*overload*/mb_strtoupper(
1117 /*overload*/mb_substr(
1118 $current_grant,
1123 . '</dfn></code></label>' . "\n"
1124 . '</div>' . "\n";
1125 } // end foreach ()
1126 return $html_output;
1130 * Get HTML for global or database specific privileges
1132 * @param string $db the database
1133 * @param string $table the table
1134 * @param array $row first row from result or boolean false
1136 * @return string $html_output
1138 function PMA_getHtmlForGlobalOrDbSpecificPrivs($db, $table, $row)
1140 $privTable_names = array(0 => __('Data'),
1141 1 => __('Structure'),
1142 2 => __('Administration')
1144 $privTable = array();
1145 // d a t a
1146 $privTable[0] = PMA_getDataPrivilegeTable($db);
1148 // s t r u c t u r e
1149 $privTable[1] = PMA_getStructurePrivilegeTable($table, $row);
1151 // a d m i n i s t r a t i o n
1152 $privTable[2] = PMA_getAdministrationPrivilegeTable($db);
1154 $html_output = '<input type="hidden" name="grant_count" value="'
1155 . (count($privTable[0])
1156 + count($privTable[1])
1157 + count($privTable[2])
1158 - (isset($row['Grant_priv']) ? 1 : 0)
1160 . '" />';
1161 if ($db == '*') {
1162 $legend = __('Global privileges');
1163 $menu_label = __('Global');
1164 } else if ($table == '*') {
1165 $legend = __('Database-specific privileges');
1166 $menu_label = __('Database');
1167 } else {
1168 $legend = __('Table-specific privileges');
1169 $menu_label = __('Table');
1171 $html_output .= '<fieldset id="fieldset_user_global_rights">'
1172 . '<legend data-submenu-label="' . $menu_label . '">' . $legend
1173 . '<input type="checkbox" id="addUsersForm_checkall" '
1174 . 'class="checkall_box" title="' . __('Check all') . '" /> '
1175 . '<label for="addUsersForm_checkall">' . __('Check all') . '</label> '
1176 . '</legend>'
1177 . '<p><small><i>'
1178 . __('Note: MySQL privilege names are expressed in English.')
1179 . '</i></small></p>';
1181 // Output the Global privilege tables with checkboxes
1182 $html_output .= PMA_getHtmlForGlobalPrivTableWithCheckboxes(
1183 $privTable, $privTable_names, $row
1186 // The "Resource limits" box is not displayed for db-specific privs
1187 if ($db == '*') {
1188 $html_output .= PMA_getHtmlForResourceLimits($row);
1189 $html_output .= PMA_getHtmlForRequires($row);
1191 // for Safari 2.0.2
1192 $html_output .= '<div class="clearfloat"></div>';
1194 return $html_output;
1198 * Get data privilege table as an array
1200 * @param string $db the database
1202 * @return string data privilege table
1204 function PMA_getDataPrivilegeTable($db)
1206 $data_privTable = array(
1207 array('Select', 'SELECT', __('Allows reading data.')),
1208 array('Insert', 'INSERT', __('Allows inserting and replacing data.')),
1209 array('Update', 'UPDATE', __('Allows changing data.')),
1210 array('Delete', 'DELETE', __('Allows deleting data.'))
1212 if ($db == '*') {
1213 $data_privTable[]
1214 = array('File',
1215 'FILE',
1216 __('Allows importing data from and exporting data into files.')
1219 return $data_privTable;
1223 * Get structure privilege table as an array
1225 * @param string $table the table
1226 * @param array $row first row from result or boolean false
1228 * @return string structure privilege table
1230 function PMA_getStructurePrivilegeTable($table, $row)
1232 $structure_privTable = array(
1233 array('Create',
1234 'CREATE',
1235 ($table == '*'
1236 ? __('Allows creating new databases and tables.')
1237 : __('Allows creating new tables.')
1240 array('Alter',
1241 'ALTER',
1242 __('Allows altering the structure of existing tables.')
1244 array('Index', 'INDEX', __('Allows creating and dropping indexes.')),
1245 array('Drop',
1246 'DROP',
1247 ($table == '*'
1248 ? __('Allows dropping databases and tables.')
1249 : __('Allows dropping tables.')
1252 array('Create_tmp_table',
1253 'CREATE TEMPORARY TABLES',
1254 __('Allows creating temporary tables.')
1256 array('Show_view',
1257 'SHOW VIEW',
1258 __('Allows performing SHOW CREATE VIEW queries.')
1260 array('Create_routine',
1261 'CREATE ROUTINE',
1262 __('Allows creating stored routines.')
1264 array('Alter_routine',
1265 'ALTER ROUTINE',
1266 __('Allows altering and dropping stored routines.')
1268 array('Execute', 'EXECUTE', __('Allows executing stored routines.')),
1270 // this one is for a db-specific priv: Create_view_priv
1271 if (isset($row['Create_view_priv'])) {
1272 $structure_privTable[] = array('Create_view',
1273 'CREATE VIEW',
1274 __('Allows creating new views.')
1277 // this one is for a table-specific priv: Create View_priv
1278 if (isset($row['Create View_priv'])) {
1279 $structure_privTable[] = array('Create View',
1280 'CREATE VIEW',
1281 __('Allows creating new views.')
1284 if (isset($row['Event_priv'])) {
1285 // MySQL 5.1.6
1286 $structure_privTable[] = array('Event',
1287 'EVENT',
1288 __('Allows to set up events for the event scheduler.')
1290 $structure_privTable[] = array('Trigger',
1291 'TRIGGER',
1292 __('Allows creating and dropping triggers.')
1295 return $structure_privTable;
1299 * Get administration privilege table as an array
1301 * @param string $db the table
1303 * @return string administration privilege table
1305 function PMA_getAdministrationPrivilegeTable($db)
1307 $adminPrivTable = array(
1308 array('Grant',
1309 'GRANT',
1311 'Allows adding users and privileges '
1312 . 'without reloading the privilege tables.'
1316 if ($db == '*') {
1317 $adminPrivTable[] = array('Super',
1318 'SUPER',
1320 'Allows connecting, even if maximum number '
1321 . 'of connections is reached; required for '
1322 . 'most administrative operations like '
1323 . 'setting global variables or killing threads of other users.'
1326 $adminPrivTable[] = array('Process',
1327 'PROCESS',
1328 __('Allows viewing processes of all users.')
1330 $adminPrivTable[] = array('Reload',
1331 'RELOAD',
1332 __('Allows reloading server settings and flushing the server\'s caches.')
1334 $adminPrivTable[] = array('Shutdown',
1335 'SHUTDOWN',
1336 __('Allows shutting down the server.')
1338 $adminPrivTable[] = array('Show_db',
1339 'SHOW DATABASES',
1340 __('Gives access to the complete list of databases.')
1343 $adminPrivTable[] = array('Lock_tables',
1344 'LOCK TABLES',
1345 __('Allows locking tables for the current thread.')
1347 $adminPrivTable[] = array('References',
1348 'REFERENCES',
1349 __('Has no effect in this MySQL version.')
1351 if ($db == '*') {
1352 $adminPrivTable[] = array('Repl_client',
1353 'REPLICATION CLIENT',
1354 __('Allows the user to ask where the slaves / masters are.')
1356 $adminPrivTable[] = array('Repl_slave',
1357 'REPLICATION SLAVE',
1358 __('Needed for the replication slaves.')
1360 $adminPrivTable[] = array('Create_user',
1361 'CREATE USER',
1362 __('Allows creating, dropping and renaming user accounts.')
1365 return $adminPrivTable;
1369 * Get HTML snippet for global privileges table with check boxes
1371 * @param array $privTable privileges table array
1372 * @param array $privTable_names names of the privilege tables
1373 * (Data, Structure, Administration)
1374 * @param array $row first row from result or boolean false
1376 * @return string $html_output
1378 function PMA_getHtmlForGlobalPrivTableWithCheckboxes(
1379 $privTable, $privTable_names, $row
1381 $html_output = '';
1382 foreach ($privTable as $i => $table) {
1383 $html_output .= '<fieldset>' . "\n"
1384 . '<legend>' . "\n"
1385 . '<input type="checkbox" class="sub_checkall_box"'
1386 . ' id="checkall_' . $privTable_names[$i] . '_priv"'
1387 . ' title="' . __('Check all') . '"/>'
1388 . '<label for="checkall_' . $privTable_names[$i] . '_priv">'
1389 . $privTable_names[$i] . '</label>' . "\n"
1390 . '</legend>' . "\n";
1391 foreach ($table as $priv) {
1392 $html_output .= '<div class="item">' . "\n"
1393 . '<input type="checkbox" class="checkall"'
1394 . ' name="' . $priv[0] . '_priv" '
1395 . 'id="checkbox_' . $priv[0] . '_priv"'
1396 . ' value="Y" title="' . $priv[2] . '"'
1397 . ((isset($row[$priv[0] . '_priv'])
1398 && $row[$priv[0] . '_priv'] == 'Y')
1399 ? ' checked="checked"'
1400 : ''
1402 . '/>' . "\n"
1403 . '<label for="checkbox_' . $priv[0] . '_priv">'
1404 . '<code>'
1405 . PMA_formatPrivilege($priv, true)
1406 . '</code></label>' . "\n"
1407 . '</div>' . "\n";
1409 $html_output .= '</fieldset>' . "\n";
1411 return $html_output;
1415 * Gets the currently active authentication plugins
1417 * @param string $username User name
1418 * @param string $hostname Host name
1419 * @param string $orig_auth_plugin Default Authentication plugin
1420 * @param string $mode are we creating a new user or are we just
1421 * changing one?
1422 * (allowed values: 'new', 'edit', 'change_pw')
1423 * @param string $versions Is MySQL version newer or older than 5.5.7
1425 * @return string $html_output
1427 function PMA_getHtmlForAuthPluginsDropdown(
1428 $username,
1429 $hostname,
1430 $orig_auth_plugin,
1431 $mode = 'new',
1432 $versions = 'new'
1434 $html_output = '<select '
1435 . 'id="select_authentication_plugin'
1436 . ($mode =='change_pw' ? '_cp' : '') . '" '
1437 . 'name="authentication_plugin" >';
1438 if ($versions == 'new') {
1439 $active_auth_plugins = PMA_getActiveAuthPlugins();
1441 foreach ($active_auth_plugins as $plugin) {
1442 if ($plugin['PLUGIN_NAME'] == 'mysql_old_password') {
1443 continue;
1445 // if description is known, enable its translation
1446 if ('Native MySQL authentication' == $plugin['PLUGIN_DESCRIPTION']) {
1447 $description = __('Native MySQL authentication');
1448 } elseif ('SHA256 password authentication' == $plugin['PLUGIN_DESCRIPTION']) {
1449 $description = __('SHA256 password authentication');
1450 } else {
1451 // but there can be other auth plugins, see
1452 // https://github.com/phpmyadmin/phpmyadmin/issues/11561
1453 $description = $plugin['PLUGIN_DESCRIPTION'];
1456 $html_output .= '<option value="' . $plugin['PLUGIN_NAME'] . '"'
1457 . ($orig_auth_plugin == $plugin['PLUGIN_NAME'] ? 'selected ' : '')
1458 . '>' . $description . '</option>';
1460 $html_output .= '</select>';
1461 } else {
1462 $html_output .= '<option value="mysql_native_password" >'
1463 . __('Native MySQL Authentication') . '</option>'
1464 . '</select>';
1467 return $html_output;
1470 * Gets the currently active authentication plugins
1472 * @return array $result array of plugin names and descriptions
1474 function PMA_getActiveAuthPlugins()
1476 $get_plugins_query = "SELECT `PLUGIN_NAME`, `PLUGIN_DESCRIPTION`"
1477 . " FROM `information_schema`.`PLUGINS` "
1478 . "WHERE `PLUGIN_TYPE` = 'AUTHENTICATION';";
1479 $resultset = $GLOBALS['dbi']->query($get_plugins_query);
1481 $result = array();
1483 while ($row = $GLOBALS['dbi']->fetchAssoc($resultset)) {
1484 $result[] = $row;
1487 return $result;
1491 * Displays the fields used by the "new user" form as well as the
1492 * "change login information / copy user" form.
1494 * @param string $mode are we creating a new user or are we just
1495 * changing one? (allowed values: 'new', 'change')
1496 * @param string $username User name
1497 * @param string $hostname Host name
1499 * @global array $cfg the phpMyAdmin configuration
1500 * @global resource $user_link the database connection
1502 * @return string $html_output a HTML snippet
1504 function PMA_getHtmlForLoginInformationFields(
1505 $mode = 'new',
1506 $username = null,
1507 $hostname = null
1509 list($username_length, $hostname_length) = PMA_getUsernameAndHostnameLength();
1511 if (isset($GLOBALS['username'])
1512 && /*overload*/mb_strlen($GLOBALS['username']) === 0
1514 $GLOBALS['pred_username'] = 'any';
1516 $html_output = '<fieldset id="fieldset_add_user_login">' . "\n"
1517 . '<legend>' . __('Login Information') . '</legend>' . "\n"
1518 . '<div class="item">' . "\n"
1519 . '<label for="select_pred_username">' . "\n"
1520 . ' ' . __('User name:') . "\n"
1521 . '</label>' . "\n"
1522 . '<span class="options">' . "\n";
1524 $html_output .= '<select name="pred_username" id="select_pred_username" '
1525 . 'title="' . __('User name') . '"' . "\n";
1527 $html_output .= ' onchange="'
1528 . 'if (this.value == \'any\') {'
1529 . ' username.value = \'\'; '
1530 . ' user_exists_warning.style.display = \'none\'; '
1531 . ' username.required = false; '
1532 . '} else if (this.value == \'userdefined\') {'
1533 . ' username.focus(); username.select(); '
1534 . ' username.required = true; '
1535 . '}">' . "\n";
1537 $html_output .= '<option value="any"'
1538 . ((isset($GLOBALS['pred_username']) && $GLOBALS['pred_username'] == 'any')
1539 ? ' selected="selected"'
1540 : '') . '>'
1541 . __('Any user')
1542 . '</option>' . "\n";
1544 $html_output .= '<option value="userdefined"'
1545 . ((! isset($GLOBALS['pred_username'])
1546 || $GLOBALS['pred_username'] == 'userdefined'
1548 ? ' selected="selected"'
1549 : '') . '>'
1550 . __('Use text field')
1551 . ':</option>' . "\n";
1553 $html_output .= '</select>' . "\n"
1554 . '</span>' . "\n";
1556 $html_output .= '<input type="text" name="username" class="autofocus"'
1557 . ' maxlength="' . $username_length . '" title="' . __('User name') . '"'
1558 . (empty($GLOBALS['username'])
1559 ? ''
1560 : ' value="' . htmlspecialchars(
1561 isset($GLOBALS['new_username'])
1562 ? $GLOBALS['new_username']
1563 : $GLOBALS['username']
1564 ) . '"'
1566 . ' onchange="pred_username.value = \'userdefined\'; this.required = true;" '
1567 . ((! isset($GLOBALS['pred_username'])
1568 || $GLOBALS['pred_username'] == 'userdefined'
1570 ? 'required="required"'
1571 : '') . ' />' . "\n";
1573 $html_output .= '<div id="user_exists_warning"'
1574 . ' name="user_exists_warning" style="display:none;">'
1575 . PMA_Message::notice(
1577 'An account already exists with the same username '
1578 . 'but possibly a different hostname.'
1580 )->getDisplay()
1581 . '</div>';
1582 $html_output .= '</div>';
1584 $html_output .= '<div class="item">' . "\n"
1585 . '<label for="select_pred_hostname">' . "\n"
1586 . ' ' . __('Host name:') . "\n"
1587 . '</label>' . "\n";
1589 $html_output .= '<span class="options">' . "\n"
1590 . ' <select name="pred_hostname" id="select_pred_hostname" '
1591 . 'title="' . __('Host name') . '"' . "\n";
1592 $_current_user = $GLOBALS['dbi']->fetchValue('SELECT USER();');
1593 if (! empty($_current_user)) {
1594 $thishost = str_replace(
1595 "'",
1597 /*overload*/mb_substr(
1598 $_current_user,
1599 (/*overload*/mb_strrpos($_current_user, '@') + 1)
1602 if ($thishost == 'localhost' || $thishost == '127.0.0.1') {
1603 unset($thishost);
1606 $html_output .= ' onchange="'
1607 . 'if (this.value == \'any\') { '
1608 . ' hostname.value = \'%\'; '
1609 . '} else if (this.value == \'localhost\') { '
1610 . ' hostname.value = \'localhost\'; '
1611 . '} '
1612 . (empty($thishost)
1613 ? ''
1614 : 'else if (this.value == \'thishost\') { '
1615 . ' hostname.value = \'' . addslashes(htmlspecialchars($thishost))
1616 . '\'; '
1617 . '} '
1619 . 'else if (this.value == \'hosttable\') { '
1620 . ' hostname.value = \'\'; '
1621 . ' hostname.required = false; '
1622 . '} else if (this.value == \'userdefined\') {'
1623 . ' hostname.focus(); hostname.select(); '
1624 . ' hostname.required = true; '
1625 . '}">' . "\n";
1626 unset($_current_user);
1628 // when we start editing a user, $GLOBALS['pred_hostname'] is not defined
1629 if (! isset($GLOBALS['pred_hostname']) && isset($GLOBALS['hostname'])) {
1630 switch (/*overload*/mb_strtolower($GLOBALS['hostname'])) {
1631 case 'localhost':
1632 case '127.0.0.1':
1633 $GLOBALS['pred_hostname'] = 'localhost';
1634 break;
1635 case '%':
1636 $GLOBALS['pred_hostname'] = 'any';
1637 break;
1638 default:
1639 $GLOBALS['pred_hostname'] = 'userdefined';
1640 break;
1643 $html_output .= '<option value="any"'
1644 . ((isset($GLOBALS['pred_hostname'])
1645 && $GLOBALS['pred_hostname'] == 'any'
1647 ? ' selected="selected"'
1648 : '') . '>'
1649 . __('Any host')
1650 . '</option>' . "\n"
1651 . '<option value="localhost"'
1652 . ((isset($GLOBALS['pred_hostname'])
1653 && $GLOBALS['pred_hostname'] == 'localhost'
1655 ? ' selected="selected"'
1656 : '') . '>'
1657 . __('Local')
1658 . '</option>' . "\n";
1659 if (! empty($thishost)) {
1660 $html_output .= '<option value="thishost"'
1661 . ((isset($GLOBALS['pred_hostname'])
1662 && $GLOBALS['pred_hostname'] == 'thishost'
1664 ? ' selected="selected"'
1665 : '') . '>'
1666 . __('This Host')
1667 . '</option>' . "\n";
1669 unset($thishost);
1670 $html_output .= '<option value="hosttable"'
1671 . ((isset($GLOBALS['pred_hostname'])
1672 && $GLOBALS['pred_hostname'] == 'hosttable'
1674 ? ' selected="selected"'
1675 : '') . '>'
1676 . __('Use Host Table')
1677 . '</option>' . "\n";
1679 $html_output .= '<option value="userdefined"'
1680 . ((isset($GLOBALS['pred_hostname'])
1681 && $GLOBALS['pred_hostname'] == 'userdefined'
1683 ? ' selected="selected"'
1684 : '') . '>'
1685 . __('Use text field:') . '</option>' . "\n"
1686 . '</select>' . "\n"
1687 . '</span>' . "\n";
1689 $html_output .= '<input type="text" name="hostname" maxlength="'
1690 . $hostname_length . '" value="'
1691 // use default value of '%' to match with the default 'Any host'
1692 . htmlspecialchars(isset($GLOBALS['hostname']) ? $GLOBALS['hostname'] : '%')
1693 . '" title="' . __('Host name')
1694 . '" onchange="pred_hostname.value = \'userdefined\'; '
1695 . 'this.required = true;" '
1696 . ((isset($GLOBALS['pred_hostname'])
1697 && $GLOBALS['pred_hostname'] == 'userdefined'
1699 ? 'required="required"'
1700 : '')
1701 . ' />' . "\n"
1702 . PMA_Util::showHint(
1704 'When Host table is used, this field is ignored '
1705 . 'and values stored in Host table are used instead.'
1708 . '</div>' . "\n";
1710 $html_output .= '<div class="item">' . "\n"
1711 . '<label for="select_pred_password">' . "\n"
1712 . ' ' . __('Password:') . "\n"
1713 . '</label>' . "\n"
1714 . '<span class="options">' . "\n"
1715 . '<select name="pred_password" id="select_pred_password" title="'
1716 . __('Password') . '"' . "\n";
1718 $html_output .= ' onchange="'
1719 . 'if (this.value == \'none\') { '
1720 . ' pma_pw.value = \'\'; pma_pw2.value = \'\'; '
1721 . ' pma_pw.required = false; pma_pw2.required = false; '
1722 . '} else if (this.value == \'userdefined\') { '
1723 . ' pma_pw.focus(); pma_pw.select(); '
1724 . ' pma_pw.required = true; pma_pw2.required = true; '
1725 . '} else { '
1726 . ' pma_pw.required = false; pma_pw2.required = false; '
1727 . '}">' . "\n"
1728 . ($mode == 'change' ? '<option value="keep" selected="selected">'
1729 . __('Do not change the password')
1730 . '</option>' . "\n" : '')
1731 . '<option value="none"';
1733 if (isset($GLOBALS['username']) && $mode != 'change') {
1734 $html_output .= ' selected="selected"';
1736 $html_output .= '>' . __('No Password') . '</option>' . "\n"
1737 . '<option value="userdefined"'
1738 . (isset($GLOBALS['username']) ? '' : ' selected="selected"') . '>'
1739 . __('Use text field')
1740 . ':</option>' . "\n"
1741 . '</select>' . "\n"
1742 . '</span>' . "\n"
1743 . '<input type="password" id="text_pma_pw" name="pma_pw" '
1744 . 'title="' . __('Password') . '" '
1745 . 'onchange="pred_password.value = \'userdefined\'; this.required = true; '
1746 . 'pma_pw2.required = true;" '
1747 . (isset($GLOBALS['username']) ? '' : 'required="required"')
1748 . '/>' . "\n"
1749 . '</div>' . "\n";
1751 $html_output .= '<div class="item" '
1752 . 'id="div_element_before_generate_password">' . "\n"
1753 . '<label for="text_pma_pw2">' . "\n"
1754 . ' ' . __('Re-type:') . "\n"
1755 . '</label>' . "\n"
1756 . '<span class="options">&nbsp;</span>' . "\n"
1757 . '<input type="password" name="pma_pw2" id="text_pma_pw2" '
1758 . 'title="' . __('Re-type') . '" '
1759 . 'onchange="pred_password.value = \'userdefined\'; this.required = true; '
1760 . 'pma_pw.required = true;" '
1761 . (isset($GLOBALS['username']) ? '' : 'required="required"')
1762 . '/>' . "\n"
1763 . '</div>' . "\n"
1764 . '<div class="item" id="authentication_plugin_div">'
1765 . '<label for="select_authentication_plugin" >';
1767 $serverType = PMA_Util::getServerType();
1768 $auth_plugin_dropdown = '';
1769 $orig_auth_plugin = PMA_getCurrentAuthenticationPlugin(
1770 $mode,
1771 $username,
1772 $hostname
1775 if (($serverType == 'MySQL'
1776 && PMA_MYSQL_INT_VERSION >= 50507)
1777 || ($serverType == 'MariaDB'
1778 && PMA_MYSQL_INT_VERSION >= 50200)
1780 $html_output .= __('Authentication Plugin')
1781 . '</label><span class="options">&nbsp;</span>' . "\n";
1783 $auth_plugin_dropdown = PMA_getHtmlForAuthPluginsDropdown(
1784 $username, $hostname, $orig_auth_plugin, $mode, 'new'
1786 } else {
1787 $html_output .= __('Password Hashing Method')
1788 . '</label><span class="options">&nbsp;</span>' . "\n";
1789 $auth_plugin_dropdown = PMA_getHtmlForAuthPluginsDropdown(
1790 $username, $hostname, $orig_auth_plugin, $mode, 'old'
1793 $html_output .= $auth_plugin_dropdown;
1795 $html_output .= '<div '
1796 . ($orig_auth_plugin != 'sha256_password' ? 'style="display:none"' : '')
1797 . ' id="ssl_reqd_warning">'
1798 . PMA_Message::notice(
1800 'This method requires using an \'<i>SSL connection</i>\' '
1801 . 'or an \'<i>unencrypted connection that encrypts the password '
1802 . 'using RSA</i>\'; while connecting to the server.'
1804 . PMA_Util::showMySQLDocu('sha256-authentication-plugin')
1806 ->getDisplay()
1807 . '</div>';
1809 $html_output .= '</div>' . "\n"
1810 // Generate password added here via jQuery
1811 . '</fieldset>' . "\n";
1813 return $html_output;
1814 } // end of the 'PMA_getHtmlForLoginInformationFields()' function
1817 * Get username and hostname length
1819 * @return array username length and hostname length
1821 function PMA_getUsernameAndHostnameLength()
1823 /* Fallback values */
1824 $username_length = 16;
1825 $hostname_length = 41;
1827 /* Try to get real lengths from the database */
1828 $fields_info = $GLOBALS['dbi']->fetchResult(
1829 'SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH '
1830 . 'FROM information_schema.columns '
1831 . "WHERE table_schema = 'mysql' AND table_name = 'user' "
1832 . "AND COLUMN_NAME IN ('User', 'Host')"
1834 foreach ($fields_info as $val) {
1835 if ($val['COLUMN_NAME'] == 'User') {
1836 $username_length = $val['CHARACTER_MAXIMUM_LENGTH'];
1837 } elseif ($val['COLUMN_NAME'] == 'Host') {
1838 $hostname_length = $val['CHARACTER_MAXIMUM_LENGTH'];
1841 return array($username_length, $hostname_length);
1845 * Get current authentication plugin in use - for a user or globally
1847 * @param string $mode are we creating a new user or are we just
1848 * changing one? (allowed values: 'new', 'change')
1849 * @param string $username User name
1850 * @param string $hostname Host name
1852 * @return string authentication plugin in use
1854 function PMA_getCurrentAuthenticationPlugin(
1855 $mode = 'new',
1856 $username = null,
1857 $hostname = null
1859 /* Fallback (standard) value */
1860 $authentication_plugin = 'mysql_native_password';
1862 if (isset($username) && isset($hostname)
1863 && $mode == 'change'
1865 $row = $GLOBALS['dbi']->fetchSingleRow(
1866 'SELECT `plugin` FROM `mysql`.`user` WHERE '
1867 . '`User` = "' . $username . '" AND `Host` = "' . $hostname . '" LIMIT 1'
1869 // Table 'mysql'.'user' may not exist for some previous
1870 // versions of MySQL - in that case consider fallback value
1871 if (isset($row) && $row) {
1872 $authentication_plugin = $row['plugin'];
1874 } elseif ($mode == 'change') {
1875 $row = $GLOBALS['dbi']->fetchSingleRow(
1876 'SELECT CURRENT_USER() as user;'
1878 if (isset($row) && $row) {
1879 list($username, $hostname) = explode('@', $row['user']);
1882 $row = $GLOBALS['dbi']->fetchSingleRow(
1883 'SELECT `plugin` FROM `mysql`.`user` WHERE '
1884 . '`User` = "' . $username . '" AND `Host` = "' . $hostname . '"'
1886 if (isset($row) && $row && ! empty($row['plugin'])) {
1887 $authentication_plugin = $row['plugin'];
1889 } elseif (PMA_MYSQL_INT_VERSION >= 50702) {
1890 $row = $GLOBALS['dbi']->fetchSingleRow(
1891 'SELECT @@default_authentication_plugin'
1893 $authentication_plugin = $row['@@default_authentication_plugin'];
1896 return $authentication_plugin;
1900 * Returns all the grants for a certain user on a certain host
1901 * Used in the export privileges for all users section
1903 * @param string $user User name
1904 * @param string $host Host name
1906 * @return string containing all the grants text
1908 function PMA_getGrants($user, $host)
1910 $grants = $GLOBALS['dbi']->fetchResult(
1911 "SHOW GRANTS FOR '"
1912 . PMA_Util::sqlAddSlashes($user) . "'@'"
1913 . PMA_Util::sqlAddSlashes($host) . "'"
1915 $response = '';
1916 foreach ($grants as $one_grant) {
1917 $response .= $one_grant . ";\n\n";
1919 return $response;
1920 } // end of the 'PMA_getGrants()' function
1923 * Update password and get message for password updating
1925 * @param string $err_url error url
1926 * @param string $username username
1927 * @param string $hostname hostname
1929 * @return string $message success or error message after updating password
1931 function PMA_updatePassword($err_url, $username, $hostname)
1933 // similar logic in user_password.php
1934 $message = '';
1935 $is_superuser = $GLOBALS['dbi']->isSuperuser();
1937 if (empty($_REQUEST['nopass'])
1938 && isset($_POST['pma_pw'])
1939 && isset($_POST['pma_pw2'])
1941 if ($_POST['pma_pw'] != $_POST['pma_pw2']) {
1942 $message = PMA_Message::error(__('The passwords aren\'t the same!'));
1943 } elseif (empty($_POST['pma_pw']) || empty($_POST['pma_pw2'])) {
1944 $message = PMA_Message::error(__('The password is empty!'));
1948 // here $nopass could be == 1
1949 if (empty($message)) {
1950 $hashing_function = 'PASSWORD';
1951 $serverType = PMA_Util::getServerType();
1952 $authentication_plugin =
1953 (isset($_REQUEST['authentication_plugin'])
1954 ? $_REQUEST['authentication_plugin']
1955 : PMA_getCurrentAuthenticationPlugin(
1956 'change',
1957 $username,
1958 $hostname
1961 // Use 'ALTER USER ...' syntax for MySQL 5.7.6+
1962 if ($serverType == 'MySQL'
1963 && PMA_MYSQL_INT_VERSION >= 50706
1965 if ($authentication_plugin != 'mysql_old_password') {
1966 $query_prefix = "ALTER USER '"
1967 . PMA_Util::sqlAddSlashes($username)
1968 . "'@'" . PMA_Util::sqlAddSlashes($hostname) . "'"
1969 . " IDENTIFIED WITH "
1970 . $authentication_plugin
1971 . " BY '";
1972 } else {
1973 $query_prefix = "ALTER USER '"
1974 . PMA_Util::sqlAddSlashes($username)
1975 . "'@'" . PMA_Util::sqlAddSlashes($hostname) . "'"
1976 . " IDENTIFIED BY '";
1979 // in $sql_query which will be displayed, hide the password
1980 $sql_query = $query_prefix . "*'";
1982 $local_query = $query_prefix
1983 . PMA_Util::sqlAddSlashes($_POST['pma_pw']) . "'";
1984 } else if ($serverType == 'MariaDB'
1985 && PMA_MYSQL_INT_VERSION >= 50200
1986 && $is_superuser
1988 // Use 'UPDATE `mysql`.`user` ...' Syntax for MariaDB 5.2+
1989 if ($authentication_plugin == 'mysql_native_password') {
1990 // Set the hashing method used by PASSWORD()
1991 // to be 'mysql_native_password' type
1992 $GLOBALS['dbi']->tryQuery('SET old_passwords = 0;');
1994 } else if ($authentication_plugin == 'sha256_password') {
1995 // Set the hashing method used by PASSWORD()
1996 // to be 'sha256_password' type
1997 $GLOBALS['dbi']->tryQuery('SET `old_passwords` = 2;');
2000 $hashedPassword = PMA_getHashedPassword($_POST['pma_pw']);
2002 $sql_query = 'SET PASSWORD FOR \''
2003 . PMA_Util::sqlAddSlashes($username)
2004 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\' = '
2005 . (($_POST['pma_pw'] == '')
2006 ? '\'\''
2007 : $hashing_function . '(\''
2008 . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
2010 $local_query = "UPDATE `mysql`.`user` SET "
2011 . " `authentication_string` = '" . $hashedPassword
2012 . "', `Password` = '', "
2013 . " `plugin` = '" . $authentication_plugin . "'"
2014 . " WHERE `User` = '" . $username . "' AND Host = '"
2015 . $hostname . "';";
2017 $GLOBALS['dbi']->tryQuery("FLUSH PRIVILEGES;");
2018 } else {
2019 // USE 'SET PASSWORD ...' syntax for rest of the versions
2020 // Backup the old value, to be reset later
2021 $row = $GLOBALS['dbi']->fetchSingleRow(
2022 'SELECT @@old_passwords;'
2024 $orig_value = $row['@@old_passwords'];
2025 $update_plugin_query = "UPDATE `mysql`.`user` SET"
2026 . " `plugin` = '" . $authentication_plugin . "'"
2027 . " WHERE `User` = '" . $username . "' AND Host = '"
2028 . $hostname . "';";
2030 // Update the plugin for the user
2031 $GLOBALS['dbi']->tryQuery($update_plugin_query)
2032 or PMA_Util::mysqlDie(
2033 $GLOBALS['dbi']->getError(),
2034 $update_plugin_query,
2035 false, $err_url
2037 $GLOBALS['dbi']->tryQuery("FLUSH PRIVILEGES;");
2038 if ($authentication_plugin == 'mysql_native_password') {
2039 // Set the hashing method used by PASSWORD()
2040 // to be 'mysql_native_password' type
2041 $GLOBALS['dbi']->tryQuery('SET old_passwords = 0;');
2042 } else if ($authentication_plugin == 'sha256_password') {
2043 // Set the hashing method used by PASSWORD()
2044 // to be 'sha256_password' type
2045 $GLOBALS['dbi']->tryQuery('SET `old_passwords` = 2;');
2047 $sql_query = 'SET PASSWORD FOR \''
2048 . PMA_Util::sqlAddSlashes($username)
2049 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\' = '
2050 . (($_POST['pma_pw'] == '')
2051 ? '\'\''
2052 : $hashing_function . '(\''
2053 . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
2054 $local_query = 'SET PASSWORD FOR \''
2055 . PMA_Util::sqlAddSlashes($username)
2056 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\' = '
2057 . (($_POST['pma_pw'] == '') ? '\'\'' : $hashing_function
2058 . '(\'' . PMA_Util::sqlAddSlashes($_POST['pma_pw']) . '\')');
2061 $GLOBALS['dbi']->tryQuery($local_query)
2062 or PMA_Util::mysqlDie(
2063 $GLOBALS['dbi']->getError(), $sql_query, false, $err_url
2065 $message = PMA_Message::success(
2066 __('The password for %s was changed successfully.')
2068 $message->addParam(
2069 '\'' . htmlspecialchars($username)
2070 . '\'@\'' . htmlspecialchars($hostname) . '\''
2072 if (isset($orig_value)) {
2073 $GLOBALS['dbi']->tryQuery(
2074 'SET `old_passwords` = ' . $orig_value . ';'
2078 return $message;
2082 * Revokes privileges and get message and SQL query for privileges revokes
2084 * @param string $dbname database name
2085 * @param string $tablename table name
2086 * @param string $username username
2087 * @param string $hostname host name
2089 * @return array ($message, $sql_query)
2091 function PMA_getMessageAndSqlQueryForPrivilegesRevoke($dbname,
2092 $tablename, $username, $hostname
2094 $db_and_table = PMA_wildcardEscapeForGrant($dbname, $tablename);
2096 $sql_query0 = 'REVOKE ALL PRIVILEGES ON ' . $db_and_table
2097 . ' FROM \''
2098 . PMA_Util::sqlAddSlashes($username) . '\'@\''
2099 . PMA_Util::sqlAddSlashes($hostname) . '\';';
2101 $sql_query1 = 'REVOKE GRANT OPTION ON ' . $db_and_table
2102 . ' FROM \'' . PMA_Util::sqlAddSlashes($username) . '\'@\''
2103 . PMA_Util::sqlAddSlashes($hostname) . '\';';
2105 $GLOBALS['dbi']->query($sql_query0);
2106 if (! $GLOBALS['dbi']->tryQuery($sql_query1)) {
2107 // this one may fail, too...
2108 $sql_query1 = '';
2110 $sql_query = $sql_query0 . ' ' . $sql_query1;
2111 $message = PMA_Message::success(
2112 __('You have revoked the privileges for %s.')
2114 $message->addParam(
2115 '\'' . htmlspecialchars($username)
2116 . '\'@\'' . htmlspecialchars($hostname) . '\''
2119 return array($message, $sql_query);
2123 * Get REQUIRE cluase
2125 * @return string REQUIRE clause
2127 function PMA_getRequireClause()
2129 $require_clause = "";
2130 if (isset($_POST['SSL_priv']) && $_POST['SSL_priv'] == 'Y') {
2131 if (isset($_POST['ssl_type']) && $_POST['ssl_type'] == 'specified') {
2132 $require = array();
2133 if (! empty($_POST['ssl_cipher'])) {
2134 $require[] = "CIPHER '"
2135 . PMA_Util::sqlAddSlashes($_POST['ssl_cipher']) . "'";
2137 if (! empty($_POST['x509_issuer'])) {
2138 $require[] = "ISSUER '"
2139 . PMA_Util::sqlAddSlashes($_POST['x509_issuer']) . "'";
2141 if (! empty($_POST['x509_subject'])) {
2142 $require[] = "SUBJECT '"
2143 . PMA_Util::sqlAddSlashes($_POST['x509_subject']) . "'";
2145 if (count($require)) {
2146 $require_clause = " REQUIRE " . implode(" AND ", $require);
2147 } else {
2148 $require_clause = " REQUIRE NONE";
2150 } elseif (isset($_POST['ssl_type']) && $_POST['ssl_type'] == 'X509') {
2151 $require_clause = " REQUIRE X509";
2152 } elseif (isset($_POST['ssl_type']) && $_POST['ssl_type'] == 'ANY') {
2153 $require_clause = " REQUIRE SSL";
2155 } else {
2156 $require_clause = " REQUIRE NONE";
2159 return $require_clause;
2163 * Get a WITH clause for 'update privileges' and 'add user'
2165 * @return string $sql_query
2167 function PMA_getWithClauseForAddUserAndUpdatePrivs()
2169 $sql_query = '';
2170 if (isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y') {
2171 $sql_query .= ' GRANT OPTION';
2173 if (isset($_POST['max_questions'])) {
2174 $max_questions = max(0, (int)$_POST['max_questions']);
2175 $sql_query .= ' MAX_QUERIES_PER_HOUR ' . $max_questions;
2177 if (isset($_POST['max_connections'])) {
2178 $max_connections = max(0, (int)$_POST['max_connections']);
2179 $sql_query .= ' MAX_CONNECTIONS_PER_HOUR ' . $max_connections;
2181 if (isset($_POST['max_updates'])) {
2182 $max_updates = max(0, (int)$_POST['max_updates']);
2183 $sql_query .= ' MAX_UPDATES_PER_HOUR ' . $max_updates;
2185 if (isset($_POST['max_user_connections'])) {
2186 $max_user_connections = max(0, (int)$_POST['max_user_connections']);
2187 $sql_query .= ' MAX_USER_CONNECTIONS ' . $max_user_connections;
2189 return ((!empty($sql_query)) ? ' WITH' . $sql_query : '');
2193 * Get HTML for addUsersForm, This function call if isset($_REQUEST['adduser'])
2195 * @param string $dbname database name
2197 * @return string HTML for addUserForm
2199 function PMA_getHtmlForAddUser($dbname)
2201 $html_output = '<h2>' . "\n"
2202 . PMA_Util::getIcon('b_usradd.png') . __('Add user account') . "\n"
2203 . '</h2>' . "\n"
2204 . '<form name="usersForm" id="addUsersForm"'
2205 . ' onsubmit="return checkAddUser(this);"'
2206 . ' action="server_privileges.php" method="post" autocomplete="off" >' . "\n"
2207 . PMA_URL_getHiddenInputs('', '')
2208 . PMA_getHtmlForLoginInformationFields('new');
2210 $html_output .= '<fieldset id="fieldset_add_user_database">' . "\n"
2211 . '<legend>' . __('Database for user account') . '</legend>' . "\n";
2213 $html_output .= PMA_Util::getCheckbox(
2214 'createdb-1',
2215 __('Create database with same name and grant all privileges.'),
2216 false, false, 'createdb-1'
2218 $html_output .= '<br />' . "\n";
2219 $html_output .= PMA_Util::getCheckbox(
2220 'createdb-2',
2221 __('Grant all privileges on wildcard name (username\\_%).'),
2222 false, false, 'createdb-2'
2224 $html_output .= '<br />' . "\n";
2226 if (! empty($dbname) ) {
2227 $html_output .= PMA_Util::getCheckbox(
2228 'createdb-3',
2229 sprintf(
2230 __('Grant all privileges on database "%s".'),
2231 htmlspecialchars($dbname)
2233 true,
2234 false,
2235 'createdb-3'
2237 $html_output .= '<input type="hidden" name="dbname" value="'
2238 . htmlspecialchars($dbname) . '" />' . "\n";
2239 $html_output .= '<br />' . "\n";
2242 $html_output .= '</fieldset>' . "\n";
2243 if ($GLOBALS['is_grantuser']) {
2244 $html_output .= PMA_getHtmlToDisplayPrivilegesTable('*', '*', false);
2246 $html_output .= '<fieldset id="fieldset_add_user_footer" class="tblFooters">'
2247 . "\n"
2248 . '<input type="hidden" name="adduser_submit" value="1" />' . "\n"
2249 . '<input type="submit" id="adduser_submit" value="' . __('Go') . '" />'
2250 . "\n"
2251 . '</fieldset>' . "\n"
2252 . '</form>' . "\n";
2254 return $html_output;
2258 * Get the list of privileges and list of compared privileges as strings
2259 * and return a array that contains both strings
2261 * @return array $list_of_privileges, $list_of_compared_privileges
2263 function PMA_getListOfPrivilegesAndComparedPrivileges()
2265 $list_of_privileges
2266 = '`User`, '
2267 . '`Host`, '
2268 . '`Select_priv`, '
2269 . '`Insert_priv`, '
2270 . '`Update_priv`, '
2271 . '`Delete_priv`, '
2272 . '`Create_priv`, '
2273 . '`Drop_priv`, '
2274 . '`Grant_priv`, '
2275 . '`Index_priv`, '
2276 . '`Alter_priv`, '
2277 . '`References_priv`, '
2278 . '`Create_tmp_table_priv`, '
2279 . '`Lock_tables_priv`, '
2280 . '`Create_view_priv`, '
2281 . '`Show_view_priv`, '
2282 . '`Create_routine_priv`, '
2283 . '`Alter_routine_priv`, '
2284 . '`Execute_priv`';
2286 $listOfComparedPrivs
2287 = '`Select_priv` = \'N\''
2288 . ' AND `Insert_priv` = \'N\''
2289 . ' AND `Update_priv` = \'N\''
2290 . ' AND `Delete_priv` = \'N\''
2291 . ' AND `Create_priv` = \'N\''
2292 . ' AND `Drop_priv` = \'N\''
2293 . ' AND `Grant_priv` = \'N\''
2294 . ' AND `References_priv` = \'N\''
2295 . ' AND `Create_tmp_table_priv` = \'N\''
2296 . ' AND `Lock_tables_priv` = \'N\''
2297 . ' AND `Create_view_priv` = \'N\''
2298 . ' AND `Show_view_priv` = \'N\''
2299 . ' AND `Create_routine_priv` = \'N\''
2300 . ' AND `Alter_routine_priv` = \'N\''
2301 . ' AND `Execute_priv` = \'N\'';
2303 $list_of_privileges .=
2304 ', `Event_priv`, '
2305 . '`Trigger_priv`';
2306 $listOfComparedPrivs .=
2307 ' AND `Event_priv` = \'N\''
2308 . ' AND `Trigger_priv` = \'N\'';
2309 return array($list_of_privileges, $listOfComparedPrivs);
2313 * Get the HTML for user form and check the privileges for a particular database.
2315 * @param string $db database name
2317 * @return string $html_output
2319 function PMA_getHtmlForSpecificDbPrivileges($db)
2321 $html_output = '';
2322 if ($GLOBALS['is_superuser']) {
2323 // check the privileges for a particular database.
2324 $html_output = '<form id="usersForm" action="server_privileges.php">';
2325 $html_output .= PMA_URL_getHiddenInputs($db);
2326 $html_output .= '<fieldset>';
2327 $html_output .= '<legend>' . "\n"
2328 . PMA_Util::getIcon('b_usrcheck.png')
2329 . ' '
2330 . sprintf(
2331 __('Users having access to "%s"'),
2332 '<a href="' . PMA_Util::getScriptNameForOption(
2333 $GLOBALS['cfg']['DefaultTabDatabase'], 'database'
2335 . PMA_URL_getCommon(array('db' => $db)) . '">'
2336 . htmlspecialchars($db)
2337 . '</a>'
2339 . "\n"
2340 . '</legend>' . "\n";
2342 $html_output .= '<table id="dbspecificuserrights" class="data">';
2343 $html_output .= PMA_getHtmlForPrivsTableHead();
2344 $privMap = PMA_getPrivMap($db);
2345 $html_output .= PMA_getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db);
2346 $html_output .= '</table>';
2348 $html_output .= '<div class="floatleft">';
2349 $html_output .= PMA_Util::getWithSelected(
2350 $GLOBALS['pmaThemeImage'], $GLOBALS['text_dir'], "usersForm"
2352 $html_output .= PMA_Util::getButtonOrImage(
2353 'submit_mult', 'mult_submit', 'submit_mult_export',
2354 __('Export'), 'b_tblexport.png', 'export'
2357 $html_output .= '</fieldset>';
2358 $html_output .= '</form>';
2359 } else {
2360 $html_output .= PMA_getHtmlForViewUsersError();
2363 if ($GLOBALS['is_ajax_request'] == true
2364 && empty($_REQUEST['ajax_page_request'])
2366 $message = PMA_Message::success(__('User has been added.'));
2367 $response = PMA_Response::getInstance();
2368 $response->addJSON('message', $message);
2369 $response->addJSON('user_form', $html_output);
2370 exit;
2371 } else {
2372 // Offer to create a new user for the current database
2373 $html_output .= PMA_getAddUserHtmlFieldset($db);
2375 return $html_output;
2379 * Get the HTML for user form and check the privileges for a particular table.
2381 * @param string $db database name
2382 * @param string $table table name
2384 * @return string $html_output
2386 function PMA_getHtmlForSpecificTablePrivileges($db, $table)
2388 $html_output = '';
2389 if ($GLOBALS['is_superuser']) {
2390 // check the privileges for a particular table.
2391 $html_output = '<form id="usersForm" action="server_privileges.php">';
2392 $html_output .= PMA_URL_getHiddenInputs($db, $table);
2393 $html_output .= '<fieldset>';
2394 $html_output .= '<legend>'
2395 . PMA_Util::getIcon('b_usrcheck.png')
2396 . sprintf(
2397 __('Users having access to "%s"'),
2398 '<a href="' . PMA_Util::getScriptNameForOption(
2399 $GLOBALS['cfg']['DefaultTabTable'], 'table'
2401 . PMA_URL_getCommon(
2402 array(
2403 'db' => $db,
2404 'table' => $table,
2406 ) . '">'
2407 . htmlspecialchars($db) . '.' . htmlspecialchars($table)
2408 . '</a>'
2410 . '</legend>';
2412 $html_output .= '<table id="tablespecificuserrights" class="data">';
2413 $html_output .= PMA_getHtmlForPrivsTableHead();
2414 $privMap = PMA_getPrivMap($db);
2415 $sql_query = "SELECT `User`, `Host`, `Db`,"
2416 . " 't' AS `Type`, `Table_name`, `Table_priv`"
2417 . " FROM `mysql`.`tables_priv`"
2418 . " WHERE '" . PMA_Util::sqlAddSlashes($db) . "' LIKE `Db`"
2419 . " AND '" . PMA_Util::sqlAddSlashes($table) . "' LIKE `Table_name`"
2420 . " AND NOT (`Table_priv` = '' AND Column_priv = '')"
2421 . " ORDER BY `User` ASC, `Host` ASC, `Db` ASC, `Table_priv` ASC;";
2422 $res = $GLOBALS['dbi']->query($sql_query);
2423 PMA_mergePrivMapFromResult($privMap, $res);
2424 $html_output .= PMA_getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db);
2425 $html_output .= '</table>';
2427 $html_output .= '<div class="floatleft">';
2428 $html_output .= PMA_Util::getWithSelected(
2429 $GLOBALS['pmaThemeImage'], $GLOBALS['text_dir'], "usersForm"
2431 $html_output .= PMA_Util::getButtonOrImage(
2432 'submit_mult', 'mult_submit', 'submit_mult_export',
2433 __('Export'), 'b_tblexport.png', 'export'
2436 $html_output .= '</fieldset>';
2437 $html_output .= '</form>';
2438 } else {
2439 $html_output .= PMA_getHtmlForViewUsersError();
2441 // Offer to create a new user for the current database
2442 $html_output .= PMA_getAddUserHtmlFieldset($db, $table);
2443 return $html_output;
2447 * gets privilege map
2449 * @param string $db the database
2451 * @return array $privMap the privilege map
2453 function PMA_getPrivMap($db)
2455 list($listOfPrivs, $listOfComparedPrivs)
2456 = PMA_getListOfPrivilegesAndComparedPrivileges();
2457 $sql_query
2458 = "("
2459 . " SELECT " . $listOfPrivs . ", '*' AS `Db`, 'g' AS `Type`"
2460 . " FROM `mysql`.`user`"
2461 . " WHERE NOT (" . $listOfComparedPrivs . ")"
2462 . ")"
2463 . " UNION "
2464 . "("
2465 . " SELECT " . $listOfPrivs . ", `Db`, 'd' AS `Type`"
2466 . " FROM `mysql`.`db`"
2467 . " WHERE '" . PMA_Util::sqlAddSlashes($db) . "' LIKE `Db`"
2468 . " AND NOT (" . $listOfComparedPrivs . ")"
2469 . ")"
2470 . " ORDER BY `User` ASC, `Host` ASC, `Db` ASC;";
2471 $res = $GLOBALS['dbi']->query($sql_query);
2472 $privMap = array();
2473 PMA_mergePrivMapFromResult($privMap, $res);
2474 return $privMap;
2478 * merge privilege map and rows from resultset
2480 * @param array &$privMap the privilege map reference
2481 * @param object $result the resultset of query
2483 * @return void
2485 function PMA_mergePrivMapFromResult(&$privMap, $result)
2487 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
2488 $user = $row['User'];
2489 $host = $row['Host'];
2490 if (! isset($privMap[$user])) {
2491 $privMap[$user] = array();
2493 if (! isset($privMap[$user][$host])) {
2494 $privMap[$user][$host] = array();
2496 $privMap[$user][$host][] = $row;
2501 * Get HTML snippet for privileges table head
2503 * @return string $html_output
2505 function PMA_getHtmlForPrivsTableHead()
2507 return '<thead>'
2508 . '<tr>'
2509 . '<th></th>'
2510 . '<th>' . __('User name') . '</th>'
2511 . '<th>' . __('Host name') . '</th>'
2512 . '<th>' . __('Type') . '</th>'
2513 . '<th>' . __('Privileges') . '</th>'
2514 . '<th>' . __('Grant') . '</th>'
2515 . '<th>' . __('Action') . '</th>'
2516 . '</tr>'
2517 . '</thead>';
2521 * Get HTML error for View Users form
2522 * For non superusers such as grant/create users
2524 * @return string $html_output
2526 function PMA_getHtmlForViewUsersError()
2528 return PMA_Message::error(
2529 __('Not enough privilege to view users.')
2530 )->getDisplay();
2534 * Get HTML snippet for table body of specific database or table privileges
2536 * @param array $privMap privilege map
2537 * @param string $db database
2539 * @return string $html_output
2541 function PMA_getHtmlTableBodyForSpecificDbOrTablePrivs($privMap, $db)
2543 $html_output = '<tbody>';
2544 $index_checkbox = 0;
2545 $odd_row = true;
2546 if (empty($privMap)) {
2547 $html_output .= '<tr class="odd">'
2548 . '<td colspan="6">'
2549 . __('No user found.')
2550 . '</td>'
2551 . '</tr>'
2552 . '</tbody>';
2553 return $html_output;
2556 foreach ($privMap as $current_user => $val) {
2557 foreach ($val as $current_host => $current_privileges) {
2558 $nbPrivileges = count($current_privileges);
2559 $html_output .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">';
2561 $value = htmlspecialchars($current_user . '&amp;#27;' . $current_host);
2562 $html_output .= '<td';
2563 if ($nbPrivileges > 1) {
2564 $html_output .= ' rowspan="' . $nbPrivileges . '"';
2566 $html_output .= '>';
2567 $html_output .= '<input type="checkbox" class="checkall" '
2568 . 'name="selected_usr[]" '
2569 . 'id="checkbox_sel_users_' . ($index_checkbox++) . '" '
2570 . 'value="' . $value . '" /></td>' . "\n";
2572 // user
2573 $html_output .= '<td';
2574 if ($nbPrivileges > 1) {
2575 $html_output .= ' rowspan="' . $nbPrivileges . '"';
2577 $html_output .= '>';
2578 if (empty($current_user)) {
2579 $html_output .= '<span style="color: #FF0000">'
2580 . __('Any') . '</span>';
2581 } else {
2582 $html_output .= htmlspecialchars($current_user);
2584 $html_output .= '</td>';
2586 // host
2587 $html_output .= '<td';
2588 if ($nbPrivileges > 1) {
2589 $html_output .= ' rowspan="' . $nbPrivileges . '"';
2591 $html_output .= '>';
2592 $html_output .= htmlspecialchars($current_host);
2593 $html_output .= '</td>';
2595 $html_output .= PMA_getHtmlListOfPrivs(
2596 $db, $current_privileges, $current_user,
2597 $current_host, $odd_row
2600 $odd_row = ! $odd_row;
2603 $html_output .= '</tbody>';
2605 return $html_output;
2609 * Get HTML to display privileges
2611 * @param string $db Database name
2612 * @param array $current_privileges List of privileges
2613 * @param string $current_user Current user
2614 * @param string $current_host Current host
2615 * @param boolean $odd_row Current row is odd
2617 * @return string HTML to display privileges
2619 function PMA_getHtmlListOfPrivs(
2620 $db, $current_privileges, $current_user,
2621 $current_host, $odd_row
2623 $nbPrivileges = count($current_privileges);
2624 $html_output = null;
2625 for ($i = 0; $i < $nbPrivileges; $i++) {
2626 $current = $current_privileges[$i];
2628 // type
2629 $html_output .= '<td>';
2630 if ($current['Type'] == 'g') {
2631 $html_output .= __('global');
2632 } elseif ($current['Type'] == 'd') {
2633 if ($current['Db'] == PMA_Util::escapeMysqlWildcards($db)) {
2634 $html_output .= __('database-specific');
2635 } else {
2636 $html_output .= __('wildcard') . ': '
2637 . '<code>'
2638 . htmlspecialchars($current['Db'])
2639 . '</code>';
2641 } elseif ($current['Type'] == 't') {
2642 $html_output .= __('table-specific');
2644 $html_output .= '</td>';
2646 // privileges
2647 $html_output .= '<td>';
2648 if (isset($current['Table_name'])) {
2649 $privList = explode(',', $current['Table_priv']);
2650 $privs = array();
2651 $grantsArr = PMA_getTableGrantsArray();
2652 foreach ($grantsArr as $grant) {
2653 $privs[$grant[0]] = 'N';
2654 foreach ($privList as $priv) {
2655 if ($grant[0] == $priv) {
2656 $privs[$grant[0]] = 'Y';
2660 $html_output .= '<code>'
2661 . join(
2662 ',',
2663 PMA_extractPrivInfo($privs, true, true)
2665 . '</code>';
2666 } else {
2667 $html_output .= '<code>'
2668 . join(
2669 ',',
2670 PMA_extractPrivInfo($current, true, false)
2672 . '</code>';
2674 $html_output .= '</td>';
2676 // grant
2677 $html_output .= '<td>';
2678 $containsGrant = false;
2679 if (isset($current['Table_name'])) {
2680 $privList = explode(',', $current['Table_priv']);
2681 foreach ($privList as $priv) {
2682 if ($priv == 'Grant') {
2683 $containsGrant = true;
2686 } else {
2687 $containsGrant = $current['Grant_priv'] == 'Y';
2689 $html_output .= ($containsGrant ? __('Yes') : __('No'));
2690 $html_output .= '</td>';
2692 // action
2693 $html_output .= '<td>';
2694 if ($GLOBALS['is_grantuser']) {
2695 $specific_db = (isset($current['Db']) && $current['Db'] != '*')
2696 ? $current['Db'] : '';
2697 $specific_table = (isset($current['Table_name'])
2698 && $current['Table_name'] != '*')
2699 ? $current['Table_name'] : '';
2700 $html_output .= PMA_getUserLink(
2701 'edit',
2702 $current_user,
2703 $current_host,
2704 $specific_db,
2705 $specific_table
2708 $html_output .= '</td>';
2710 $html_output .= '</tr>';
2711 if (($i + 1) < $nbPrivileges) {
2712 $html_output .= '<tr class="noclick '
2713 . ($odd_row ? 'odd' : 'even') . '">';
2716 return $html_output;
2720 * Returns edit, revoke or export link for a user.
2722 * @param string $linktype The link type (edit | revoke | export)
2723 * @param string $username User name
2724 * @param string $hostname Host name
2725 * @param string $dbname Database name
2726 * @param string $tablename Table name
2727 * @param string $initial Initial value
2729 * @return string HTML code with link
2731 function PMA_getUserLink(
2732 $linktype, $username, $hostname, $dbname = '', $tablename = '', $initial = ''
2734 $html = '<a';
2735 switch($linktype) {
2736 case 'edit':
2737 $html .= ' class="edit_user_anchor"';
2738 break;
2739 case 'export':
2740 $html .= ' class="export_user_anchor ajax"';
2741 break;
2743 $params = array(
2744 'username' => $username,
2745 'hostname' => $hostname
2747 switch($linktype) {
2748 case 'edit':
2749 $params['dbname'] = $dbname;
2750 $params['tablename'] = $tablename;
2751 break;
2752 case 'revoke':
2753 $params['dbname'] = $dbname;
2754 $params['tablename'] = $tablename;
2755 $params['revokeall'] = 1;
2756 break;
2757 case 'export':
2758 $params['initial'] = $initial;
2759 $params['export'] = 1;
2760 break;
2763 $html .= ' href="server_privileges.php'
2764 . PMA_URL_getCommon($params)
2765 . '">';
2767 switch($linktype) {
2768 case 'edit':
2769 $html .= PMA_Util::getIcon('b_usredit.png', __('Edit privileges'));
2770 break;
2771 case 'revoke':
2772 $html .= PMA_Util::getIcon('b_usrdrop.png', __('Revoke'));
2773 break;
2774 case 'export':
2775 $html .= PMA_Util::getIcon('b_tblexport.png', __('Export'));
2776 break;
2778 $html .= '</a>';
2780 return $html;
2784 * Returns user group edit link
2786 * @param string $username User name
2788 * @return string HTML code with link
2790 function PMA_getUserGroupEditLink($username)
2792 return '<a class="edit_user_group_anchor ajax"'
2793 . ' href="server_privileges.php'
2794 . PMA_URL_getCommon(array('username' => $username))
2795 . '">'
2796 . PMA_Util::getIcon('b_usrlist.png', __('Edit user group'))
2797 . '</a>';
2801 * Returns number of defined user groups
2803 * @return integer $user_group_count
2805 function PMA_getUserGroupCount()
2807 $cfgRelation = PMA_getRelationsParam();
2808 $user_group_table = PMA_Util::backquote($cfgRelation['db'])
2809 . '.' . PMA_Util::backquote($cfgRelation['usergroups']);
2810 $sql_query = 'SELECT COUNT(*) FROM ' . $user_group_table;
2811 $user_group_count = $GLOBALS['dbi']->fetchValue(
2812 $sql_query, 0, 0, $GLOBALS['controllink']
2815 return $user_group_count;
2819 * This function return the extra data array for the ajax behavior
2821 * @param string $password password
2822 * @param string $sql_query sql query
2823 * @param string $hostname hostname
2824 * @param string $username username
2826 * @return array $extra_data
2828 function PMA_getExtraDataForAjaxBehavior(
2829 $password, $sql_query, $hostname, $username
2831 if (isset($GLOBALS['dbname'])) {
2832 //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
2833 if (preg_match('/(?<!\\\\)(?:_|%)/i', $GLOBALS['dbname'])) {
2834 $dbname_is_wildcard = true;
2835 } else {
2836 $dbname_is_wildcard = false;
2840 $user_group_count = 0;
2841 if ($GLOBALS['cfgRelation']['menuswork']) {
2842 $user_group_count = PMA_getUserGroupCount();
2845 $extra_data = array();
2846 if (/*overload*/mb_strlen($sql_query)) {
2847 $extra_data['sql_query'] = PMA_Util::getMessage(null, $sql_query);
2850 if (isset($_REQUEST['change_copy'])) {
2852 * generate html on the fly for the new user that was just created.
2854 $new_user_string = '<tr>' . "\n"
2855 . '<td> <input type="checkbox" name="selected_usr[]" '
2856 . 'id="checkbox_sel_users_"'
2857 . 'value="'
2858 . htmlspecialchars($username)
2859 . '&amp;#27;' . htmlspecialchars($hostname) . '" />'
2860 . '</td>' . "\n"
2861 . '<td><label for="checkbox_sel_users_">'
2862 . (empty($_REQUEST['username'])
2863 ? '<span style="color: #FF0000">' . __('Any') . '</span>'
2864 : htmlspecialchars($username) ) . '</label></td>' . "\n"
2865 . '<td>' . htmlspecialchars($hostname) . '</td>' . "\n";
2867 $new_user_string .= '<td>';
2869 if (! empty($password) || isset($_POST['pma_pw'])) {
2870 $new_user_string .= __('Yes');
2871 } else {
2872 $new_user_string .= '<span style="color: #FF0000">'
2873 . __('No')
2874 . '</span>';
2877 $new_user_string .= '</td>' . "\n";
2878 $new_user_string .= '<td>'
2879 . '<code>' . join(', ', PMA_extractPrivInfo(null, true)) . '</code>'
2880 . '</td>'; //Fill in privileges here
2882 // if $cfg['Servers'][$i]['users'] and $cfg['Servers'][$i]['usergroups'] are
2883 // enabled
2884 $cfgRelation = PMA_getRelationsParam();
2885 if (isset($cfgRelation['users']) && isset($cfgRelation['usergroups'])) {
2886 $new_user_string .= '<td class="usrGroup"></td>';
2889 $new_user_string .= '<td>';
2890 if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')) {
2891 $new_user_string .= __('Yes');
2892 } else {
2893 $new_user_string .= __('No');
2895 $new_user_string .='</td>';
2897 if ($GLOBALS['is_grantuser']) {
2898 $new_user_string .= '<td>'
2899 . PMA_getUserLink('edit', $username, $hostname)
2900 . '</td>' . "\n";
2903 if ($cfgRelation['menuswork'] && $user_group_count > 0) {
2904 $new_user_string .= '<td>'
2905 . PMA_getUserGroupEditLink($username)
2906 . '</td>' . "\n";
2909 $new_user_string .= '<td>'
2910 . PMA_getUserLink(
2911 'export',
2912 $username,
2913 $hostname,
2916 isset($_GET['initial']) ? $_GET['initial'] : ''
2918 . '</td>' . "\n";
2920 $new_user_string .= '</tr>';
2922 $extra_data['new_user_string'] = $new_user_string;
2925 * Generate the string for this alphabet's initial, to update the user
2926 * pagination
2928 $new_user_initial = /*overload*/mb_strtoupper(
2929 /*overload*/mb_substr($username, 0, 1)
2931 $newUserInitialString = '<a href="server_privileges.php'
2932 . PMA_URL_getCommon(array('initial' => $new_user_initial)) . '">'
2933 . $new_user_initial . '</a>';
2934 $extra_data['new_user_initial'] = $new_user_initial;
2935 $extra_data['new_user_initial_string'] = $newUserInitialString;
2938 if (isset($_POST['update_privs'])) {
2939 $extra_data['db_specific_privs'] = false;
2940 $extra_data['db_wildcard_privs'] = false;
2941 if (isset($dbname_is_wildcard)) {
2942 $extra_data['db_specific_privs'] = ! $dbname_is_wildcard;
2943 $extra_data['db_wildcard_privs'] = $dbname_is_wildcard;
2945 $new_privileges = join(', ', PMA_extractPrivInfo(null, true));
2947 $extra_data['new_privileges'] = $new_privileges;
2950 if (isset($_REQUEST['validate_username'])) {
2951 $sql_query = "SELECT * FROM `mysql`.`user` WHERE `User` = '"
2952 . $_REQUEST['username'] . "';";
2953 $res = $GLOBALS['dbi']->query($sql_query);
2954 $row = $GLOBALS['dbi']->fetchRow($res);
2955 if (empty($row)) {
2956 $extra_data['user_exists'] = false;
2957 } else {
2958 $extra_data['user_exists'] = true;
2962 return $extra_data;
2966 * Get the HTML snippet for change user login information
2968 * @param string $username username
2969 * @param string $hostname host name
2971 * @return string HTML snippet
2973 function PMA_getChangeLoginInformationHtmlForm($username, $hostname)
2975 $choices = array(
2976 '4' => __('… keep the old one.'),
2977 '1' => __('… delete the old one from the user tables.'),
2978 '2' => __(
2979 '… revoke all active privileges from '
2980 . 'the old one and delete it afterwards.'
2982 '3' => __(
2983 '… delete the old one from the user tables '
2984 . 'and reload the privileges afterwards.'
2988 $html_output = '<form action="server_privileges.php" '
2989 . 'onsubmit="return checkAddUser(this);" '
2990 . 'method="post" class="copyUserForm submenu-item">' . "\n"
2991 . PMA_URL_getHiddenInputs('', '')
2992 . '<input type="hidden" name="old_username" '
2993 . 'value="' . htmlspecialchars($username) . '" />' . "\n"
2994 . '<input type="hidden" name="old_hostname" '
2995 . 'value="' . htmlspecialchars($hostname) . '" />' . "\n"
2996 . '<fieldset id="fieldset_change_copy_user">' . "\n"
2997 . '<legend data-submenu-label="' . __('Login Information') . '">' . "\n"
2998 . __('Change login information / Copy user account')
2999 . '</legend>' . "\n"
3000 . PMA_getHtmlForLoginInformationFields('change', $username, $hostname);
3002 $html_output .= '<fieldset id="fieldset_mode">' . "\n"
3003 . ' <legend>'
3004 . __('Create a new user account with the same privileges and …')
3005 . '</legend>' . "\n";
3006 $html_output .= PMA_Util::getRadioFields(
3007 'mode', $choices, '4', true
3009 $html_output .= '</fieldset>' . "\n"
3010 . '</fieldset>' . "\n";
3012 $html_output .= '<fieldset id="fieldset_change_copy_user_footer" '
3013 . 'class="tblFooters">' . "\n"
3014 . '<input type="hidden" name="change_copy" value="1" />' . "\n"
3015 . '<input type="submit" value="' . __('Go') . '" />' . "\n"
3016 . '</fieldset>' . "\n"
3017 . '</form>' . "\n";
3019 return $html_output;
3023 * Provide a line with links to the relevant database and table
3025 * @param string $url_dbname url database name that urlencode() string
3026 * @param string $dbname database name
3027 * @param string $tablename table name
3029 * @return string HTML snippet
3031 function PMA_getLinkToDbAndTable($url_dbname, $dbname, $tablename)
3033 $html_output = '[ ' . __('Database')
3034 . ' <a href="' . PMA_Util::getScriptNameForOption(
3035 $GLOBALS['cfg']['DefaultTabDatabase'], 'database'
3037 . PMA_URL_getCommon(
3038 array(
3039 'db' => $url_dbname,
3040 'reload' => 1
3043 . '">'
3044 . htmlspecialchars($dbname) . ': '
3045 . PMA_Util::getTitleForTarget(
3046 $GLOBALS['cfg']['DefaultTabDatabase']
3048 . "</a> ]\n";
3050 if (/*overload*/mb_strlen($tablename)) {
3051 $html_output .= ' [ ' . __('Table') . ' <a href="'
3052 . PMA_Util::getScriptNameForOption(
3053 $GLOBALS['cfg']['DefaultTabTable'], 'table'
3055 . PMA_URL_getCommon(
3056 array(
3057 'db' => $url_dbname,
3058 'table' => $tablename,
3059 'reload' => 1,
3062 . '">' . htmlspecialchars($tablename) . ': '
3063 . PMA_Util::getTitleForTarget(
3064 $GLOBALS['cfg']['DefaultTabTable']
3066 . "</a> ]\n";
3068 return $html_output;
3072 * no db name given, so we want all privs for the given user
3073 * db name was given, so we want all user specific rights for this db
3074 * So this function returns user rights as an array
3076 * @param array $tables tables
3077 * @param string $user_host_condition a where clause that contained user's host
3078 * condition
3079 * @param string $dbname database name
3081 * @return array $db_rights database rights
3083 function PMA_getUserSpecificRights($tables, $user_host_condition, $dbname)
3085 if (!/*overload*/mb_strlen($dbname)) {
3086 $tables_to_search_for_users = array(
3087 'tables_priv', 'columns_priv',
3089 $dbOrTableName = 'Db';
3090 } else {
3091 $user_host_condition .=
3092 ' AND `Db`'
3093 . ' LIKE \''
3094 . PMA_Util::sqlAddSlashes($dbname, true) . "'";
3095 $tables_to_search_for_users = array('columns_priv',);
3096 $dbOrTableName = 'Table_name';
3099 $db_rights_sqls = array();
3100 foreach ($tables_to_search_for_users as $table_search_in) {
3101 if (in_array($table_search_in, $tables)) {
3102 $db_rights_sqls[] = '
3103 SELECT DISTINCT `' . $dbOrTableName . '`
3104 FROM `mysql`.' . PMA_Util::backquote($table_search_in)
3105 . $user_host_condition;
3109 $user_defaults = array(
3110 $dbOrTableName => '',
3111 'Grant_priv' => 'N',
3112 'privs' => array('USAGE'),
3113 'Column_priv' => true,
3116 // for the rights
3117 $db_rights = array();
3119 $db_rights_sql = '(' . implode(') UNION (', $db_rights_sqls) . ')'
3120 . ' ORDER BY `' . $dbOrTableName . '` ASC';
3122 $db_rights_result = $GLOBALS['dbi']->query($db_rights_sql);
3124 while ($db_rights_row = $GLOBALS['dbi']->fetchAssoc($db_rights_result)) {
3125 $db_rights_row = array_merge($user_defaults, $db_rights_row);
3126 if (!/*overload*/mb_strlen($dbname)) {
3127 // only Db names in the table `mysql`.`db` uses wildcards
3128 // as we are in the db specific rights display we want
3129 // all db names escaped, also from other sources
3130 $db_rights_row['Db'] = PMA_Util::escapeMysqlWildcards(
3131 $db_rights_row['Db']
3134 $db_rights[$db_rights_row[$dbOrTableName]] = $db_rights_row;
3137 $GLOBALS['dbi']->freeResult($db_rights_result);
3139 if (!/*overload*/mb_strlen($dbname)) {
3140 $sql_query = 'SELECT * FROM `mysql`.`db`'
3141 . $user_host_condition . ' ORDER BY `Db` ASC';
3142 } else {
3143 $sql_query = 'SELECT `Table_name`,'
3144 . ' `Table_priv`,'
3145 . ' IF(`Column_priv` = _latin1 \'\', 0, 1)'
3146 . ' AS \'Column_priv\''
3147 . ' FROM `mysql`.`tables_priv`'
3148 . $user_host_condition
3149 . ' ORDER BY `Table_name` ASC;';
3152 $result = $GLOBALS['dbi']->query($sql_query);
3154 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
3155 if (isset($db_rights[$row[$dbOrTableName]])) {
3156 $db_rights[$row[$dbOrTableName]]
3157 = array_merge($db_rights[$row[$dbOrTableName]], $row);
3158 } else {
3159 $db_rights[$row[$dbOrTableName]] = $row;
3161 if (!/*overload*/mb_strlen($dbname)) {
3162 // there are db specific rights for this user
3163 // so we can drop this db rights
3164 $db_rights[$row['Db']]['can_delete'] = true;
3167 $GLOBALS['dbi']->freeResult($result);
3168 return $db_rights;
3172 * Display user rights in table rows(Table specific or database specific privs)
3174 * @param array $db_rights user's database rights array
3175 * @param string $dbname database name
3176 * @param string $hostname host name
3177 * @param string $username username
3179 * @return array $found_rows, $html_output
3181 function PMA_getHtmlForUserRights($db_rights, $dbname,
3182 $hostname, $username
3184 $html_output = '';
3185 $found_rows = array();
3187 // display rows
3188 if (count($db_rights) < 1) {
3189 $html_output .= '<tr class="odd">' . "\n"
3190 . '<td colspan="6"><center><i>' . __('None') . '</i></center></td>' . "\n"
3191 . '</tr>' . "\n";
3192 return array($found_rows, $html_output);
3195 $odd_row = true;
3196 //while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
3197 foreach ($db_rights as $row) {
3198 $dbNameLength = /*overload*/mb_strlen($dbname);
3199 $found_rows[] = (!$dbNameLength)
3200 ? $row['Db']
3201 : $row['Table_name'];
3203 $html_output .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">' . "\n"
3204 . '<td>'
3205 . htmlspecialchars(
3206 (!$dbNameLength)
3207 ? $row['Db']
3208 : $row['Table_name']
3210 . '</td>' . "\n"
3211 . '<td><code>' . "\n"
3212 . ' '
3213 . join(
3214 ',' . "\n" . ' ',
3215 PMA_extractPrivInfo($row, true)
3216 ) . "\n"
3217 . '</code></td>' . "\n"
3218 . '<td>'
3219 . ((((!$dbNameLength) && $row['Grant_priv'] == 'Y')
3220 || ($dbNameLength
3221 && in_array('Grant', explode(',', $row['Table_priv']))))
3222 ? __('Yes')
3223 : __('No'))
3224 . '</td>' . "\n"
3225 . '<td>';
3226 if (!empty($row['Table_privs']) || !empty($row['Column_priv'])) {
3227 $html_output .= __('Yes');
3228 } else {
3229 $html_output .= __('No');
3231 $html_output .= '</td>';
3233 $html_output .= '<td>';
3234 if ($GLOBALS['is_grantuser']) {
3235 $html_output .= PMA_getUserLink(
3236 'edit',
3237 $username,
3238 $hostname,
3239 (!$dbNameLength) ? $row['Db'] : $dbname,
3240 (!$dbNameLength) ? '' : $row['Table_name']
3243 $html_output .= '</td>';
3245 $html_output .= '<td>';
3246 if (! empty($row['can_delete'])
3247 || isset($row['Table_name'])
3248 && /*overload*/mb_strlen($row['Table_name'])
3250 $html_output .= PMA_getUserLink(
3251 'revoke',
3252 $username,
3253 $hostname,
3254 (!$dbNameLength) ? $row['Db'] : $dbname,
3255 (!$dbNameLength) ? '' : $row['Table_name']
3258 $html_output .= '</td>' . "\n"
3259 . '</tr>' . "\n";
3260 $odd_row = ! $odd_row;
3261 } // end while
3263 return array($found_rows, $html_output);
3267 * Get a HTML table for display user's tabel specific or database specific rights
3269 * @param string $username username
3270 * @param string $hostname host name
3271 * @param string $dbname database name
3273 * @return array $html_output, $found_rows
3275 function PMA_getHtmlForAllTableSpecificRights(
3276 $username, $hostname, $dbname
3278 // table header
3279 $html_output = PMA_URL_getHiddenInputs('', '')
3280 . '<input type="hidden" name="username" '
3281 . 'value="' . htmlspecialchars($username) . '" />' . "\n"
3282 . '<input type="hidden" name="hostname" '
3283 . 'value="' . htmlspecialchars($hostname) . '" />' . "\n"
3284 . '<fieldset>' . "\n"
3285 . '<legend data-submenu-label="'
3286 . (!/*overload*/mb_strlen($dbname)
3287 ? __('Database')
3288 : __('Table')
3290 . '">'
3291 . (!/*overload*/mb_strlen($dbname)
3292 ? __('Database-specific privileges')
3293 : __('Table-specific privileges')
3295 . '</legend>' . "\n"
3296 . '<table class="data">' . "\n"
3297 . '<thead>' . "\n"
3298 . '<tr><th>'
3299 . (!/*overload*/mb_strlen($dbname) ? __('Database') : __('Table'))
3300 . '</th>' . "\n"
3301 . '<th>' . __('Privileges') . '</th>' . "\n"
3302 . '<th>' . __('Grant') . '</th>' . "\n"
3303 . '<th>'
3304 . (!/*overload*/mb_strlen($dbname)
3305 ? __('Table-specific privileges')
3306 : __('Column-specific privileges')
3308 . '</th>' . "\n"
3309 . '<th colspan="2">' . __('Action') . '</th>' . "\n"
3310 . '</tr>' . "\n"
3311 . '</thead>' . "\n";
3313 $user_host_condition = ' WHERE `User`'
3314 . ' = \'' . PMA_Util::sqlAddSlashes($username) . "'"
3315 . ' AND `Host`'
3316 . ' = \'' . PMA_Util::sqlAddSlashes($hostname) . "'";
3318 // table body
3319 // get data
3321 // we also want privileges for this user not in table `db` but in other table
3322 $tables = $GLOBALS['dbi']->fetchResult('SHOW TABLES FROM `mysql`;');
3325 * no db name given, so we want all privs for the given user
3326 * db name was given, so we want all user specific rights for this db
3328 $db_rights = PMA_getUserSpecificRights($tables, $user_host_condition, $dbname);
3330 ksort($db_rights);
3332 $html_output .= '<tbody>' . "\n";
3333 // display rows
3334 list ($found_rows, $html_out) = PMA_getHtmlForUserRights(
3335 $db_rights, $dbname, $hostname, $username
3338 $html_output .= $html_out;
3339 $html_output .= '</tbody>' . "\n";
3340 $html_output .='</table>' . "\n";
3342 return array($html_output, $found_rows);
3346 * Get HTML for display select db
3348 * @param array $found_rows isset($dbname)) ? $row['Db'] : $row['Table_name']
3350 * @return string HTML snippet
3352 function PMA_getHtmlForSelectDbInEditPrivs($found_rows)
3354 // we already have the list of databases from libraries/common.inc.php
3355 // via $pma = new PMA;
3356 $pred_db_array = $GLOBALS['pma']->databases;
3358 $databases_to_skip = array('information_schema', 'performance_schema');
3360 $html_output = '<label for="text_dbname">'
3361 . __('Add privileges on the following database(s):') . '</label>' . "\n";
3362 if (! empty($pred_db_array)) {
3363 $html_output .= '<select name="pred_dbname[]" multiple="multiple">' . "\n";
3364 foreach ($pred_db_array as $current_db) {
3365 if (in_array($current_db, $databases_to_skip)) {
3366 continue;
3368 $current_db_show = $current_db;
3369 $current_db = PMA_Util::escapeMysqlWildcards($current_db);
3370 // cannot use array_diff() once, outside of the loop,
3371 // because the list of databases has special characters
3372 // already escaped in $found_rows,
3373 // contrary to the output of SHOW DATABASES
3374 if (empty($found_rows) || ! in_array($current_db, $found_rows)) {
3375 $html_output .= '<option value="'
3376 . htmlspecialchars($current_db) . '">'
3377 . htmlspecialchars($current_db_show) . '</option>' . "\n";
3380 $html_output .= '</select>' . "\n";
3382 $html_output .= '<input type="text" id="text_dbname" name="dbname" />'
3383 . "\n"
3384 . PMA_Util::showHint(
3385 __('Wildcards % and _ should be escaped with a \ to use them literally.')
3387 return $html_output;
3391 * Get HTML for display table in edit privilege
3393 * @param string $dbname database naame
3394 * @param array $found_rows isset($dbname)) ? $row['Db'] : $row['Table_name']
3396 * @return string HTML snippet
3398 function PMA_displayTablesInEditPrivs($dbname, $found_rows)
3400 $html_output = '<input type="hidden" name="dbname"
3401 ' . 'value="' . htmlspecialchars($dbname) . '"/>' . "\n";
3402 $html_output .= '<label for="text_tablename">'
3403 . __('Add privileges on the following table:') . '</label>' . "\n";
3405 $result = @$GLOBALS['dbi']->tryQuery(
3406 'SHOW TABLES FROM ' . PMA_Util::backquote(
3407 PMA_Util::unescapeMysqlWildcards($dbname)
3408 ) . ';',
3409 null,
3410 PMA_DatabaseInterface::QUERY_STORE
3413 if ($result) {
3414 $pred_tbl_array = array();
3415 while ($row = $GLOBALS['dbi']->fetchRow($result)) {
3416 if (! isset($found_rows) || ! in_array($row[0], $found_rows)) {
3417 $pred_tbl_array[] = $row[0];
3420 $GLOBALS['dbi']->freeResult($result);
3422 if (! empty($pred_tbl_array)) {
3423 $html_output .= '<select name="pred_tablename" '
3424 . 'class="autosubmit">' . "\n"
3425 . '<option value="" selected="selected">' . __('Use text field')
3426 . ':</option>' . "\n";
3427 foreach ($pred_tbl_array as $current_table) {
3428 $html_output .= '<option '
3429 . 'value="' . htmlspecialchars($current_table) . '">'
3430 . htmlspecialchars($current_table)
3431 . '</option>' . "\n";
3433 $html_output .= '</select>' . "\n";
3436 $html_output .= '<input type="text" id="text_tablename" name="tablename" />'
3437 . "\n";
3439 return $html_output;
3443 * Get HTML for display the users overview
3444 * (if less than 50 users, display them immediately)
3446 * @param array $result ran sql query
3447 * @param array $db_rights user's database rights array
3448 * @param string $pmaThemeImage a image source link
3449 * @param string $text_dir text directory
3451 * @return string HTML snippet
3453 function PMA_getUsersOverview($result, $db_rights, $pmaThemeImage, $text_dir)
3455 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
3456 $row['privs'] = PMA_extractPrivInfo($row, true);
3457 $db_rights[$row['User']][$row['Host']] = $row;
3459 @$GLOBALS['dbi']->freeResult($result);
3460 $user_group_count = 0;
3461 if ($GLOBALS['cfgRelation']['menuswork']) {
3462 $user_group_count = PMA_getUserGroupCount();
3465 $html_output
3466 = '<form name="usersForm" id="usersForm" action="server_privileges.php" '
3467 . 'method="post">' . "\n"
3468 . PMA_URL_getHiddenInputs('', '')
3469 . '<table id="tableuserrights" class="data">' . "\n"
3470 . '<thead>' . "\n"
3471 . '<tr><th></th>' . "\n"
3472 . '<th>' . __('User name') . '</th>' . "\n"
3473 . '<th>' . __('Host name') . '</th>' . "\n"
3474 . '<th>' . __('Password') . '</th>' . "\n"
3475 . '<th>' . __('Global privileges') . ' '
3476 . PMA_Util::showHint(
3477 __('Note: MySQL privilege names are expressed in English.')
3479 . '</th>' . "\n";
3480 if ($GLOBALS['cfgRelation']['menuswork']) {
3481 $html_output .= '<th>' . __('User group') . '</th>' . "\n";
3483 $html_output .= '<th>' . __('Grant') . '</th>' . "\n"
3484 . '<th colspan="' . ($user_group_count > 0 ? '3' : '2') . '">'
3485 . __('Action') . '</th>' . "\n"
3486 . '</tr>' . "\n"
3487 . '</thead>' . "\n";
3489 $html_output .= '<tbody>' . "\n";
3490 $html_output .= PMA_getHtmlTableBodyForUserRights($db_rights);
3491 $html_output .= '</tbody>'
3492 . '</table>' . "\n";
3494 $html_output .= '<div class="floatleft">'
3495 . PMA_Util::getWithSelected($pmaThemeImage, $text_dir, "usersForm") . "\n";
3497 $html_output .= PMA_Util::getButtonOrImage(
3498 'submit_mult', 'mult_submit', 'submit_mult_export',
3499 __('Export'), 'b_tblexport.png', 'export'
3501 $html_output .= '<input type="hidden" name="initial" '
3502 . 'value="' . (isset($_GET['initial']) ? $_GET['initial'] : '') . '" />';
3503 $html_output .= '</div>'
3504 . '<div class="clear_both" style="clear:both"></div>';
3506 // add/delete user fieldset
3507 $html_output .= PMA_getFieldsetForAddDeleteUser();
3508 $html_output .= '</form>' . "\n";
3510 return $html_output;
3514 * Get table body for 'tableuserrights' table in userform
3516 * @param array $db_rights user's database rights array
3518 * @return string HTML snippet
3520 function PMA_getHtmlTableBodyForUserRights($db_rights)
3522 $cfgRelation = PMA_getRelationsParam();
3523 if ($cfgRelation['menuswork']) {
3524 $users_table = PMA_Util::backquote($cfgRelation['db'])
3525 . "." . PMA_Util::backquote($cfgRelation['users']);
3526 $sql_query = 'SELECT * FROM ' . $users_table;
3527 $result = PMA_queryAsControlUser($sql_query, false);
3528 $group_assignment = array();
3529 if ($result) {
3530 while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
3531 $group_assignment[$row['username']] = $row['usergroup'];
3534 $GLOBALS['dbi']->freeResult($result);
3536 $user_group_count = PMA_getUserGroupCount();
3539 $odd_row = true;
3540 $index_checkbox = 0;
3541 $html_output = '';
3542 foreach ($db_rights as $user) {
3543 ksort($user);
3544 foreach ($user as $host) {
3545 $index_checkbox++;
3546 $html_output .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">'
3547 . "\n";
3548 $html_output .= '<td>'
3549 . '<input type="checkbox" class="checkall" name="selected_usr[]" '
3550 . 'id="checkbox_sel_users_'
3551 . $index_checkbox . '" value="'
3552 . htmlspecialchars($host['User'] . '&amp;#27;' . $host['Host'])
3553 . '"'
3554 . ' /></td>' . "\n";
3556 $html_output .= '<td><label '
3557 . 'for="checkbox_sel_users_' . $index_checkbox . '">'
3558 . (empty($host['User'])
3559 ? '<span style="color: #FF0000">' . __('Any') . '</span>'
3560 : htmlspecialchars($host['User'])) . '</label></td>' . "\n"
3561 . '<td>' . htmlspecialchars($host['Host']) . '</td>' . "\n";
3563 $html_output .= '<td>';
3565 $password_column = 'Password';
3567 $check_plugin_query = "SELECT * FROM `mysql`.`user` WHERE "
3568 . "`User` = '" . $host['User'] . "' AND `Host` = '"
3569 . $host['Host'] . "'";
3570 $res = $GLOBALS['dbi']->fetchSingleRow($check_plugin_query);
3572 if ((isset($res['authentication_string'])
3573 && ! empty($res['authentication_string']))
3574 || (isset($res['Password'])
3575 && ! empty($res['Password']))
3577 $host[$password_column] = 'Y';
3578 } else {
3579 $host[$password_column] = 'N';
3582 switch ($host[$password_column]) {
3583 case 'Y':
3584 $html_output .= __('Yes');
3585 break;
3586 case 'N':
3587 $html_output .= '<span style="color: #FF0000">' . __('No')
3588 . '</span>';
3589 break;
3590 // this happens if this is a definition not coming from mysql.user
3591 default:
3592 $html_output .= '--'; // in future version, replace by "not present"
3593 break;
3594 } // end switch
3596 $html_output .= '</td>' . "\n";
3598 $html_output .= '<td><code>' . "\n"
3599 . '' . implode(',' . "\n" . ' ', $host['privs']) . "\n"
3600 . '</code></td>' . "\n";
3601 if ($cfgRelation['menuswork']) {
3602 $html_output .= '<td class="usrGroup">' . "\n"
3603 . (isset($group_assignment[$host['User']])
3604 ? $group_assignment[$host['User']]
3605 : ''
3607 . '</td>' . "\n";
3609 $html_output .= '<td>'
3610 . ($host['Grant_priv'] == 'Y' ? __('Yes') : __('No'))
3611 . '</td>' . "\n";
3613 if ($GLOBALS['is_grantuser']) {
3614 $html_output .= '<td class="center">'
3615 . PMA_getUserLink(
3616 'edit',
3617 $host['User'],
3618 $host['Host']
3620 . '</td>';
3622 if ($cfgRelation['menuswork'] && $user_group_count > 0) {
3623 if (empty($host['User'])) {
3624 $html_output .= '<td class="center"></td>';
3625 } else {
3626 $html_output .= '<td class="center">'
3627 . PMA_getUserGroupEditLink($host['User'])
3628 . '</td>';
3631 $html_output .= '<td class="center">'
3632 . PMA_getUserLink(
3633 'export',
3634 $host['User'],
3635 $host['Host'],
3638 isset($_GET['initial']) ? $_GET['initial'] : ''
3640 . '</td>';
3641 $html_output .= '</tr>';
3642 $odd_row = ! $odd_row;
3645 return $html_output;
3649 * Get HTML fieldset for Add/Delete user
3651 * @return string HTML snippet
3653 function PMA_getFieldsetForAddDeleteUser()
3655 $html_output = PMA_getAddUserHtmlFieldset();
3656 $html_output .= '<fieldset id="fieldset_delete_user">'
3657 . '<legend>' . "\n"
3658 . PMA_Util::getIcon('b_usrdrop.png')
3659 . ' ' . __('Remove selected user accounts') . '' . "\n"
3660 . '</legend>' . "\n";
3662 $html_output .= '<input type="hidden" name="mode" value="2" />' . "\n"
3663 . '('
3664 . __(
3665 'Revoke all active privileges from the users '
3666 . 'and delete them afterwards.'
3668 . ')'
3669 . '<br />' . "\n";
3671 $html_output .= '<input type="checkbox" '
3672 . 'title="'
3673 . __('Drop the databases that have the same names as the users.')
3674 . '" '
3675 . 'name="drop_users_db" id="checkbox_drop_users_db" />' . "\n";
3677 $html_output .= '<label for="checkbox_drop_users_db" '
3678 . 'title="'
3679 . __('Drop the databases that have the same names as the users.')
3680 . '">' . "\n"
3681 . ' '
3682 . __('Drop the databases that have the same names as the users.')
3683 . "\n"
3684 . '</label>' . "\n"
3685 . '</fieldset>' . "\n";
3687 $html_output .= '<fieldset id="fieldset_delete_user_footer" class="tblFooters">'
3688 . "\n";
3689 $html_output .= '<input type="submit" name="delete" '
3690 . 'value="' . __('Go') . '" id="buttonGo" '
3691 . 'class="ajax"/>' . "\n";
3693 $html_output .= '</fieldset>' . "\n";
3695 return $html_output;
3699 * Get HTML for Displays the initials
3701 * @param array $array_initials array for all initials, even non A-Z
3703 * @return string HTML snippet
3705 function PMA_getHtmlForInitials($array_initials)
3707 // initialize to false the letters A-Z
3708 for ($letter_counter = 1; $letter_counter < 27; $letter_counter++) {
3709 if (! isset($array_initials[/*overload*/mb_chr($letter_counter + 64)])) {
3710 $array_initials[/*overload*/mb_chr($letter_counter + 64)] = false;
3714 $initials = $GLOBALS['dbi']->tryQuery(
3715 'SELECT DISTINCT UPPER(LEFT(`User`,1)) FROM `user` ORDER BY `User` ASC',
3716 null,
3717 PMA_DatabaseInterface::QUERY_STORE
3719 if ($initials) {
3720 while (list($tmp_initial) = $GLOBALS['dbi']->fetchRow($initials)) {
3721 $array_initials[$tmp_initial] = true;
3725 // Display the initials, which can be any characters, not
3726 // just letters. For letters A-Z, we add the non-used letters
3727 // as greyed out.
3729 uksort($array_initials, "strnatcasecmp");
3731 $html_output = '<table id="initials_table" cellspacing="5">'
3732 . '<tr>';
3733 foreach ($array_initials as $tmp_initial => $initial_was_found) {
3734 if ($tmp_initial === null) {
3735 continue;
3738 if (!$initial_was_found) {
3739 $html_output .= '<td>' . $tmp_initial . '</td>';
3740 continue;
3743 $html_output .= '<td>'
3744 . '<a class="ajax'
3745 . ((isset($_REQUEST['initial'])
3746 && $_REQUEST['initial'] === $tmp_initial
3747 ) ? ' active' : '')
3748 . '" href="server_privileges.php'
3749 . PMA_URL_getCommon(array('initial' => $tmp_initial))
3750 . '">' . $tmp_initial
3751 . '</a>'
3752 . '</td>' . "\n";
3754 $html_output .= '<td>'
3755 . '<a href="server_privileges.php'
3756 . PMA_URL_getCommon(array('showall' => 1))
3757 . '" class="nowrap">' . __('Show all') . '</a></td>' . "\n";
3758 $html_output .= '</tr></table>';
3760 return $html_output;
3764 * Get the database rights array for Display user overview
3766 * @return array $db_rights database rights array
3768 function PMA_getDbRightsForUserOverview()
3770 // we also want users not in table `user` but in other table
3771 $tables = $GLOBALS['dbi']->fetchResult('SHOW TABLES FROM `mysql`;');
3773 $tablesSearchForUsers = array(
3774 'user', 'db', 'tables_priv', 'columns_priv', 'procs_priv',
3777 $db_rights_sqls = array();
3778 foreach ($tablesSearchForUsers as $table_search_in) {
3779 if (in_array($table_search_in, $tables)) {
3780 $db_rights_sqls[] = 'SELECT DISTINCT `User`, `Host` FROM `mysql`.`'
3781 . $table_search_in . '` '
3782 . (isset($_GET['initial'])
3783 ? PMA_rangeOfUsers($_GET['initial'])
3784 : '');
3787 $user_defaults = array(
3788 'User' => '',
3789 'Host' => '%',
3790 'Password' => '?',
3791 'Grant_priv' => 'N',
3792 'privs' => array('USAGE'),
3795 // for the rights
3796 $db_rights = array();
3798 $db_rights_sql = '(' . implode(') UNION (', $db_rights_sqls) . ')'
3799 . ' ORDER BY `User` ASC, `Host` ASC';
3801 $db_rights_result = $GLOBALS['dbi']->query($db_rights_sql);
3803 while ($db_rights_row = $GLOBALS['dbi']->fetchAssoc($db_rights_result)) {
3804 $db_rights_row = array_merge($user_defaults, $db_rights_row);
3805 $db_rights[$db_rights_row['User']][$db_rights_row['Host']]
3806 = $db_rights_row;
3808 $GLOBALS['dbi']->freeResult($db_rights_result);
3809 ksort($db_rights);
3811 return $db_rights;
3815 * Delete user and get message and sql query for delete user in privileges
3817 * @param array $queries queries
3819 * @return array PMA_message
3821 function PMA_deleteUser($queries)
3823 $sql_query = '';
3824 if (empty($queries)) {
3825 $message = PMA_Message::error(__('No users selected for deleting!'));
3826 } else {
3827 if ($_REQUEST['mode'] == 3) {
3828 $queries[] = '# ' . __('Reloading the privileges') . ' …';
3829 $queries[] = 'FLUSH PRIVILEGES;';
3831 $drop_user_error = '';
3832 foreach ($queries as $sql_query) {
3833 if ($sql_query{0} != '#') {
3834 if (! $GLOBALS['dbi']->tryQuery($sql_query, $GLOBALS['userlink'])) {
3835 $drop_user_error .= $GLOBALS['dbi']->getError() . "\n";
3839 // tracking sets this, causing the deleted db to be shown in navi
3840 unset($GLOBALS['db']);
3842 $sql_query = join("\n", $queries);
3843 if (! empty($drop_user_error)) {
3844 $message = PMA_Message::rawError($drop_user_error);
3845 } else {
3846 $message = PMA_Message::success(
3847 __('The selected users have been deleted successfully.')
3851 return array($sql_query, $message);
3855 * Update the privileges and return the success or error message
3857 * @param string $username username
3858 * @param string $hostname host name
3859 * @param string $tablename table name
3860 * @param string $dbname database name
3862 * @return PMA_message success message or error message for update
3864 function PMA_updatePrivileges($username, $hostname, $tablename, $dbname)
3866 $db_and_table = PMA_wildcardEscapeForGrant($dbname, $tablename);
3868 $sql_query0 = 'REVOKE ALL PRIVILEGES ON ' . $db_and_table
3869 . ' FROM \'' . PMA_Util::sqlAddSlashes($username)
3870 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
3872 if (! isset($_POST['Grant_priv']) || $_POST['Grant_priv'] != 'Y') {
3873 $sql_query1 = 'REVOKE GRANT OPTION ON ' . $db_and_table
3874 . ' FROM \'' . PMA_Util::sqlAddSlashes($username) . '\'@\''
3875 . PMA_Util::sqlAddSlashes($hostname) . '\';';
3876 } else {
3877 $sql_query1 = '';
3880 // Should not do a GRANT USAGE for a table-specific privilege, it
3881 // causes problems later (cannot revoke it)
3882 if (! (/*overload*/mb_strlen($tablename)
3883 && 'USAGE' == implode('', PMA_extractPrivInfo()))
3885 $sql_query2 = 'GRANT ' . join(', ', PMA_extractPrivInfo())
3886 . ' ON ' . $db_and_table
3887 . ' TO \'' . PMA_Util::sqlAddSlashes($username) . '\'@\''
3888 . PMA_Util::sqlAddSlashes($hostname) . '\'';
3890 if (! /*overload*/mb_strlen($dbname)) {
3891 // add REQUIRE clause
3892 $sql_query2 .= PMA_getRequireClause();
3895 if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
3896 || (! /*overload*/mb_strlen($dbname)
3897 && (isset($_POST['max_questions']) || isset($_POST['max_connections'])
3898 || isset($_POST['max_updates'])
3899 || isset($_POST['max_user_connections'])))
3901 $sql_query2 .= PMA_getWithClauseForAddUserAndUpdatePrivs();
3903 $sql_query2 .= ';';
3905 if (! $GLOBALS['dbi']->tryQuery($sql_query0)) {
3906 // This might fail when the executing user does not have
3907 // ALL PRIVILEGES himself.
3908 // See https://sourceforge.net/p/phpmyadmin/bugs/3270/
3909 $sql_query0 = '';
3911 if (! empty($sql_query1) && ! $GLOBALS['dbi']->tryQuery($sql_query1)) {
3912 // this one may fail, too...
3913 $sql_query1 = '';
3915 if (! empty($sql_query2)) {
3916 $GLOBALS['dbi']->query($sql_query2);
3917 } else {
3918 $sql_query2 = '';
3920 $sql_query = $sql_query0 . ' ' . $sql_query1 . ' ' . $sql_query2;
3921 $message = PMA_Message::success(__('You have updated the privileges for %s.'));
3922 $message->addParam(
3923 '\'' . htmlspecialchars($username)
3924 . '\'@\'' . htmlspecialchars($hostname) . '\''
3927 return array($sql_query, $message);
3931 * Get List of information: Changes / copies a user
3933 * @return array
3935 function PMA_getDataForChangeOrCopyUser()
3937 $queries = null;
3938 $password = null;
3940 if (isset($_REQUEST['change_copy'])) {
3941 $user_host_condition = ' WHERE `User` = '
3942 . "'" . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'"
3943 . ' AND `Host` = '
3944 . "'" . PMA_Util::sqlAddSlashes($_REQUEST['old_hostname']) . "';";
3945 $row = $GLOBALS['dbi']->fetchSingleRow(
3946 'SELECT * FROM `mysql`.`user` ' . $user_host_condition
3948 if (! $row) {
3949 $response = PMA_Response::getInstance();
3950 $response->addHTML(
3951 PMA_Message::notice(__('No user found.'))->getDisplay()
3953 unset($_REQUEST['change_copy']);
3954 } else {
3955 extract($row, EXTR_OVERWRITE);
3956 // Recent MySQL versions have the field "Password" in mysql.user,
3957 // so the previous extract creates $Password but this script
3958 // uses $password
3959 if (! isset($password) && isset($Password)) {
3960 $password = $Password;
3962 if (PMA_Util::getServerType() == 'MySQL'
3963 && PMA_MYSQL_INT_VERSION >= 50606
3964 && PMA_MYSQL_INT_VERSION < 50706
3965 && ((isset($authentication_string)
3966 && empty($password))
3967 || (isset($plugin)
3968 && $plugin == 'sha256_password'))
3970 $password = $authentication_string;
3973 if (PMA_Util::getServerType() == 'MariaDB'
3974 && PMA_MYSQL_INT_VERSION >= 50500
3975 && isset($authentication_string)
3976 && empty($password)
3978 $password = $authentication_string;
3981 // Always use 'authentication_string' column
3982 // for MySQL 5.7.6+ since it does not have
3983 // the 'password' column at all
3984 if (PMA_Util::getServerType() == 'MySQL'
3985 && PMA_MYSQL_INT_VERSION >= 50706
3986 && isset($authentication_string)
3988 $password = $authentication_string;
3991 $queries = array();
3995 return array($queries, $password);
3999 * Update Data for information: Deletes users
4001 * @param array $queries queries array
4003 * @return array
4005 function PMA_getDataForDeleteUsers($queries)
4007 if (isset($_REQUEST['change_copy'])) {
4008 $selected_usr = array(
4009 $_REQUEST['old_username'] . '&amp;#27;' . $_REQUEST['old_hostname']
4011 } else {
4012 $selected_usr = $_REQUEST['selected_usr'];
4013 $queries = array();
4016 // this happens, was seen in https://reports.phpmyadmin.net/reports/view/17146
4017 if (! is_array($selected_usr)) {
4018 return array();
4021 foreach ($selected_usr as $each_user) {
4022 list($this_user, $this_host) = explode('&amp;#27;', $each_user);
4023 $queries[] = '# '
4024 . sprintf(
4025 __('Deleting %s'),
4026 '\'' . $this_user . '\'@\'' . $this_host . '\''
4028 . ' ...';
4029 $queries[] = 'DROP USER \''
4030 . PMA_Util::sqlAddSlashes($this_user)
4031 . '\'@\'' . PMA_Util::sqlAddSlashes($this_host) . '\';';
4032 PMA_relationsCleanupUser($this_user);
4034 if (isset($_REQUEST['drop_users_db'])) {
4035 $queries[] = 'DROP DATABASE IF EXISTS '
4036 . PMA_Util::backquote($this_user) . ';';
4037 $GLOBALS['reload'] = true;
4040 return $queries;
4044 * update Message For Reload
4046 * @return array
4048 function PMA_updateMessageForReload()
4050 $message = null;
4051 if (isset($_REQUEST['flush_privileges'])) {
4052 $sql_query = 'FLUSH PRIVILEGES;';
4053 $GLOBALS['dbi']->query($sql_query);
4054 $message = PMA_Message::success(
4055 __('The privileges were reloaded successfully.')
4059 if (isset($_REQUEST['validate_username'])) {
4060 $message = PMA_Message::success();
4063 return $message;
4067 * update Data For Queries from queries_for_display
4069 * @param array $queries queries array
4070 * @param array|null $queries_for_display queries array for display
4072 * @return null
4074 function PMA_getDataForQueries($queries, $queries_for_display)
4076 $tmp_count = 0;
4077 foreach ($queries as $sql_query) {
4078 if ($sql_query{0} != '#') {
4079 $GLOBALS['dbi']->query($sql_query);
4081 // when there is a query containing a hidden password, take it
4082 // instead of the real query sent
4083 if (isset($queries_for_display[$tmp_count])) {
4084 $queries[$tmp_count] = $queries_for_display[$tmp_count];
4086 $tmp_count++;
4089 return $queries;
4093 * update Data for information: Adds a user
4095 * @param string $dbname db name
4096 * @param string $username user name
4097 * @param string $hostname host name
4098 * @param string $password password
4099 * @param bool $is_menuwork is_menuwork set?
4101 * @return array
4103 function PMA_addUser(
4104 $dbname, $username, $hostname,
4105 $password, $is_menuwork
4107 $_add_user_error = false;
4108 $message = null;
4109 $queries = null;
4110 $queries_for_display = null;
4111 $sql_query = null;
4113 if (!isset($_REQUEST['adduser_submit']) && !isset($_REQUEST['change_copy'])) {
4114 return array(
4115 $message, $queries, $queries_for_display, $sql_query, $_add_user_error
4119 if (!isset($_REQUEST['adduser_submit']) && !isset($_REQUEST['change_copy'])) {
4120 return array(
4121 $message,
4122 $queries,
4123 $queries_for_display,
4124 $sql_query,
4125 $_add_user_error
4129 $sql_query = '';
4130 if ($_POST['pred_username'] == 'any') {
4131 $username = '';
4133 switch ($_POST['pred_hostname']) {
4134 case 'any':
4135 $hostname = '%';
4136 break;
4137 case 'localhost':
4138 $hostname = 'localhost';
4139 break;
4140 case 'hosttable':
4141 $hostname = '';
4142 break;
4143 case 'thishost':
4144 $_user_name = $GLOBALS['dbi']->fetchValue('SELECT USER()');
4145 $hostname = /*overload*/mb_substr(
4146 $_user_name,
4147 (/*overload*/mb_strrpos($_user_name, '@') + 1)
4149 unset($_user_name);
4150 break;
4152 $sql = "SELECT '1' FROM `mysql`.`user`"
4153 . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
4154 . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "';";
4155 if ($GLOBALS['dbi']->fetchValue($sql) == 1) {
4156 $message = PMA_Message::error(__('The user %s already exists!'));
4157 $message->addParam(
4158 '[em]\'' . $username . '\'@\'' . $hostname . '\'[/em]'
4160 $_REQUEST['adduser'] = true;
4161 $_add_user_error = true;
4163 return array(
4164 $message,
4165 $queries,
4166 $queries_for_display,
4167 $sql_query,
4168 $_add_user_error
4172 list(
4173 $create_user_real, $create_user_show, $real_sql_query, $sql_query,
4174 $password_set_real, $password_set_show
4175 ) = PMA_getSqlQueriesForDisplayAndAddUser(
4176 $username, $hostname, (isset($password) ? $password : '')
4179 if (empty($_REQUEST['change_copy'])) {
4180 $_error = false;
4182 if (isset($create_user_real)) {
4183 if (!$GLOBALS['dbi']->tryQuery($create_user_real)) {
4184 $_error = true;
4186 if (isset($password_set_real) && !empty($password_set_real)
4187 && isset($_REQUEST['authentication_plugin'])
4189 PMA_setProperPasswordHashing(
4190 $_REQUEST['authentication_plugin']
4192 if ($GLOBALS['dbi']->tryQuery($password_set_real)) {
4193 $sql_query .= $password_set_show;
4196 $sql_query = $create_user_show . $sql_query;
4199 list($sql_query, $message) = PMA_addUserAndCreateDatabase(
4200 $_error,
4201 $real_sql_query,
4202 $sql_query,
4203 $username,
4204 $hostname,
4205 isset($dbname) ? $dbname : null
4207 if (!empty($_REQUEST['userGroup']) && $is_menuwork) {
4208 PMA_setUserGroup($GLOBALS['username'], $_REQUEST['userGroup']);
4211 return array(
4212 $message,
4213 $queries,
4214 $queries_for_display,
4215 $sql_query,
4216 $_add_user_error
4220 if (isset($create_user_real)) {
4221 $queries[] = $create_user_real;
4223 $queries[] = $real_sql_query;
4225 if (isset($password_set_real) && ! empty($password_set_real)
4226 && isset($_REQUEST['authentication_plugin'])
4228 PMA_setProperPasswordHashing(
4229 $_REQUEST['authentication_plugin']
4232 $queries[] = $password_set_real;
4234 // we put the query containing the hidden password in
4235 // $queries_for_display, at the same position occupied
4236 // by the real query in $queries
4237 $tmp_count = count($queries);
4238 if (isset($create_user_real)) {
4239 $queries_for_display[$tmp_count - 2] = $create_user_show;
4241 if (isset($password_set_real) && ! empty($password_set_real)) {
4242 $queries_for_display[$tmp_count - 3] = $create_user_show;
4243 $queries_for_display[$tmp_count - 2] = $sql_query;
4244 $queries_for_display[$tmp_count - 1] = $password_set_show;
4245 } else {
4246 $queries_for_display[$tmp_count - 1] = $sql_query;
4249 return array(
4250 $message, $queries, $queries_for_display, $sql_query, $_add_user_error
4255 * Sets proper value of `old_passwords` according to
4256 * the authentication plugin selected
4258 * @param string $auth_plugin authentication plugin selected
4260 * @return void
4262 function PMA_setProperPasswordHashing($auth_plugin)
4264 // Set the hashing method used by PASSWORD()
4265 // to be of type depending upon $authentication_plugin
4266 if ($auth_plugin == 'sha256_password') {
4267 $GLOBALS['dbi']->tryQuery('SET `old_passwords` = 2');
4268 } else if ($auth_plugin == 'mysql_old_password') {
4269 $GLOBALS['dbi']->tryQuery('SET `old_passwords` = 1');
4270 } else {
4271 $GLOBALS['dbi']->tryQuery('SET `old_passwords` = 0');
4276 * Update DB information: DB, Table, isWildcard
4278 * @return array
4280 function PMA_getDataForDBInfo()
4282 $username = null;
4283 $hostname = null;
4284 $dbname = null;
4285 $tablename = null;
4286 $dbname_is_wildcard = null;
4288 if (isset($_REQUEST['username'])) {
4289 $username = $_REQUEST['username'];
4291 if (isset($_REQUEST['hostname'])) {
4292 $hostname = $_REQUEST['hostname'];
4295 * Checks if a dropdown box has been used for selecting a database / table
4297 if (PMA_isValid($_REQUEST['pred_tablename'])) {
4298 $tablename = $_REQUEST['pred_tablename'];
4299 } elseif (PMA_isValid($_REQUEST['tablename'])) {
4300 $tablename = $_REQUEST['tablename'];
4301 } else {
4302 unset($tablename);
4305 if (isset($_REQUEST['pred_dbname'])) {
4306 $is_valid_pred_dbname = true;
4307 foreach ($_REQUEST['pred_dbname'] as $key => $db_name) {
4308 if (! PMA_isValid($db_name)) {
4309 $is_valid_pred_dbname = false;
4310 break;
4315 if (isset($_REQUEST['dbname'])) {
4316 $is_valid_dbname = true;
4317 if (is_array($_REQUEST['dbname'])) {
4318 foreach ($_REQUEST['dbname'] as $key => $db_name) {
4319 if (! PMA_isValid($db_name)) {
4320 $is_valid_dbname = false;
4321 break;
4324 } else {
4325 if (! PMA_isValid($_REQUEST['dbname'])) {
4326 $is_valid_dbname = false;
4331 if (isset($is_valid_pred_dbname) && $is_valid_pred_dbname) {
4332 $dbname = $_REQUEST['pred_dbname'];
4333 // If dbname contains only one database.
4334 if (count($dbname) == 1) {
4335 $dbname = $dbname[0];
4337 } elseif (isset($is_valid_dbname) && $is_valid_dbname) {
4338 $dbname = $_REQUEST['dbname'];
4339 } else {
4340 unset($dbname);
4341 unset($tablename);
4344 if (isset($dbname)) {
4345 if (is_array($dbname)) {
4346 $db_and_table = $dbname;
4347 foreach ($db_and_table as $key => $db_name) {
4348 $db_and_table[$key] .= '.';
4350 } else {
4351 $unescaped_db = PMA_Util::unescapeMysqlWildcards($dbname);
4352 $db_and_table = PMA_Util::backquote($unescaped_db) . '.';
4354 if (isset($tablename)) {
4355 $db_and_table .= PMA_Util::backquote($tablename);
4356 } else {
4357 if (is_array($db_and_table)) {
4358 foreach ($db_and_table as $key => $db_name) {
4359 $db_and_table[$key] .= '*';
4361 } else {
4362 $db_and_table .= '*';
4365 } else {
4366 $db_and_table = '*.*';
4369 // check if given $dbname is a wildcard or not
4370 if (isset($dbname)) {
4371 //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
4372 if (! is_array($dbname) && preg_match('/(?<!\\\\)(?:_|%)/i', $dbname)) {
4373 $dbname_is_wildcard = true;
4374 } else {
4375 $dbname_is_wildcard = false;
4379 return array(
4380 $username, $hostname,
4381 isset($dbname)? $dbname : null,
4382 isset($tablename)? $tablename : null,
4383 $db_and_table,
4384 $dbname_is_wildcard,
4389 * Get title and textarea for export user definition in Privileges
4391 * @param string $username username
4392 * @param string $hostname host name
4394 * @return array ($title, $export)
4396 function PMA_getListForExportUserDefinition($username, $hostname)
4398 $export = '<textarea class="export" cols="60" rows="15">';
4400 if (isset($_REQUEST['selected_usr'])) {
4401 // export privileges for selected users
4402 $title = __('Privileges');
4404 foreach ($_REQUEST['selected_usr'] as $export_user) {
4405 $export_username = /*overload*/mb_substr(
4406 $export_user, 0, /*overload*/mb_strpos($export_user, '&')
4408 $export_hostname = /*overload*/mb_substr(
4409 $export_user, /*overload*/mb_strrpos($export_user, ';') + 1
4411 $export .= '# '
4412 . sprintf(
4413 __('Privileges for %s'),
4414 '`' . htmlspecialchars($export_username)
4415 . '`@`' . htmlspecialchars($export_hostname) . '`'
4417 . "\n\n";
4418 $export .= PMA_getGrants($export_username, $export_hostname) . "\n";
4420 } else {
4421 // export privileges for a single user
4422 $title = __('User') . ' `' . htmlspecialchars($username)
4423 . '`@`' . htmlspecialchars($hostname) . '`';
4424 $export .= PMA_getGrants($username, $hostname);
4426 // remove trailing whitespace
4427 $export = trim($export);
4429 $export .= '</textarea>';
4431 return array($title, $export);
4435 * Get HTML for display Add userfieldset
4437 * @param string $db the database
4438 * @param string $table the table name
4440 * @return string html output
4442 function PMA_getAddUserHtmlFieldset($db = '', $table = '')
4444 if (!$GLOBALS['is_createuser']) {
4445 return '';
4447 $rel_params = array();
4448 $url_params = array(
4449 'adduser' => 1
4451 if (!empty($db)) {
4452 $url_params['dbname']
4453 = $rel_params['checkprivsdb']
4454 = $db;
4456 if (!empty($table)) {
4457 $url_params['tablename']
4458 = $rel_params['checkprivstable']
4459 = $table;
4462 return '<fieldset id="fieldset_add_user">' . "\n"
4463 . '<legend>' . _pgettext('Create new user', 'New') . '</legend>'
4464 . '<a id="add_user_anchor" href="server_privileges.php'
4465 . PMA_URL_getCommon($url_params) . '" '
4466 . (!empty($rel_params)
4467 ? ('rel="' . PMA_URL_getCommon($rel_params) . '" ')
4468 : '')
4469 . '>' . "\n"
4470 . PMA_Util::getIcon('b_usradd.png')
4471 . ' ' . __('Add user account') . '</a>' . "\n"
4472 . '</fieldset>' . "\n";
4476 * Get HTML header for display User's properties
4478 * @param boolean $dbname_is_wildcard whether database name is wildcard or not
4479 * @param string $url_dbname url database name that urlencode() string
4480 * @param string $dbname database name
4481 * @param string $username username
4482 * @param string $hostname host name
4483 * @param string $tablename table name
4485 * @return string $html_output
4487 function PMA_getHtmlHeaderForUserProperties(
4488 $dbname_is_wildcard, $url_dbname, $dbname, $username, $hostname, $tablename
4490 $html_output = '<h2>' . "\n"
4491 . PMA_Util::getIcon('b_usredit.png')
4492 . __('Edit privileges:') . ' '
4493 . __('User account');
4495 if (! empty($dbname)) {
4496 $html_output .= ' <i><a class="edit_user_anchor"'
4497 . ' href="server_privileges.php'
4498 . PMA_URL_getCommon(
4499 array(
4500 'username' => $username,
4501 'hostname' => $hostname,
4502 'dbname' => '',
4503 'tablename' => '',
4506 . '">\'' . htmlspecialchars($username)
4507 . '\'@\'' . htmlspecialchars($hostname)
4508 . '\'</a></i>' . "\n";
4510 $html_output .= ' - ';
4511 $html_output .= ($dbname_is_wildcard
4512 || is_array($dbname) && count($dbname) > 1)
4513 ? __('Databases') : __('Database');
4514 if (! empty($_REQUEST['tablename'])) {
4515 $html_output .= ' <i><a href="server_privileges.php'
4516 . PMA_URL_getCommon(
4517 array(
4518 'username' => $username,
4519 'hostname' => $hostname,
4520 'dbname' => $url_dbname,
4521 'tablename' => '',
4524 . '">' . htmlspecialchars($dbname)
4525 . '</a></i>';
4527 $html_output .= ' - ' . __('Table')
4528 . ' <i>' . htmlspecialchars($tablename) . '</i>';
4529 } else {
4530 if (! is_array($dbname)) {
4531 $dbname = array($dbname);
4533 $html_output .= ' <i>'
4534 . htmlspecialchars(implode(', ', $dbname))
4535 . '</i>';
4538 } else {
4539 $html_output .= ' <i>\'' . htmlspecialchars($username)
4540 . '\'@\'' . htmlspecialchars($hostname)
4541 . '\'</i>' . "\n";
4544 $html_output .= '</h2>' . "\n";
4545 $cur_user = htmlspecialchars($GLOBALS['dbi']->getCurrentUser());
4546 $user = htmlspecialchars($username . '@' . $hostname);
4547 // Add a short notice for the user
4548 // to remind him that he is editing his own privileges
4549 if ($user === $cur_user) {
4550 $html_output .= PMA_Message::notice(
4552 'Note: You are attempting to edit privileges of the '
4553 . 'user with which you are currently logged in.'
4555 )->getDisplay();
4557 return $html_output;
4561 * Get HTML snippet for display user overview page
4563 * @param string $pmaThemeImage a image source link
4564 * @param string $text_dir text directory
4566 * @return string $html_output
4568 function PMA_getHtmlForUserOverview($pmaThemeImage, $text_dir)
4570 $html_output = '<h2>' . "\n"
4571 . PMA_Util::getIcon('b_usrlist.png')
4572 . __('User accounts overview') . "\n"
4573 . '</h2>' . "\n";
4575 $password_column = 'Password';
4576 if (PMA_Util::getServerType() == 'MySQL'
4577 && PMA_MYSQL_INT_VERSION >= 50706
4579 $password_column = 'authentication_string';
4581 // $sql_query is for the initial-filtered,
4582 // $sql_query_all is for counting the total no. of users
4584 $sql_query = $sql_query_all = 'SELECT *,' .
4585 " IF(`" . $password_column . "` = _latin1 '', 'N', 'Y') AS 'Password'" .
4586 ' FROM `mysql`.`user`';
4588 $sql_query .= (isset($_REQUEST['initial'])
4589 ? PMA_rangeOfUsers($_REQUEST['initial'])
4590 : '');
4592 $sql_query .= ' ORDER BY `User` ASC, `Host` ASC;';
4593 $sql_query_all .= ' ;';
4595 $res = $GLOBALS['dbi']->tryQuery(
4596 $sql_query, null, PMA_DatabaseInterface::QUERY_STORE
4598 $res_all = $GLOBALS['dbi']->tryQuery(
4599 $sql_query_all, null, PMA_DatabaseInterface::QUERY_STORE
4602 if (! $res) {
4603 // the query failed! This may have two reasons:
4604 // - the user does not have enough privileges
4605 // - the privilege tables use a structure of an earlier version.
4606 // so let's try a more simple query
4608 $GLOBALS['dbi']->freeResult($res);
4609 $GLOBALS['dbi']->freeResult($res_all);
4610 $sql_query = 'SELECT * FROM `mysql`.`user`';
4611 $res = $GLOBALS['dbi']->tryQuery(
4612 $sql_query, null, PMA_DatabaseInterface::QUERY_STORE
4615 if (! $res) {
4616 $html_output .= PMA_getHtmlForViewUsersError();
4617 $html_output .= PMA_getAddUserHtmlFieldset();
4618 } else {
4619 // This message is hardcoded because I will replace it by
4620 // a automatic repair feature soon.
4621 $raw = 'Your privilege table structure seems to be older than'
4622 . ' this MySQL version!<br />'
4623 . 'Please run the <code>mysql_upgrade</code> command'
4624 . '(<code>mysql_fix_privilege_tables</code> on older systems)'
4625 . ' that should be included in your MySQL server distribution'
4626 . ' to solve this problem!';
4627 $html_output .= PMA_Message::rawError($raw)->getDisplay();
4629 $GLOBALS['dbi']->freeResult($res);
4630 } else {
4631 $db_rights = PMA_getDbRightsForUserOverview();
4632 // for all initials, even non A-Z
4633 $array_initials = array();
4635 foreach ($db_rights as $right) {
4636 foreach ($right as $account) {
4637 if (empty($account['User']) && $account['Host'] == 'localhost') {
4638 $html_output .= PMA_Message::notice(
4640 'A user account allowing any user from localhost to '
4641 . 'connect is present. This will prevent other users '
4642 . 'from connecting if the host part of their account '
4643 . 'allows a connection from any (%) host.'
4645 . PMA_Util::showMySQLDocu('problems-connecting')
4646 )->getDisplay();
4647 break 2;
4653 * Displays the initials
4654 * Also not necessary if there is less than 20 privileges
4656 if ($GLOBALS['dbi']->numRows($res_all) > 20) {
4657 $html_output .= PMA_getHtmlForInitials($array_initials);
4661 * Display the user overview
4662 * (if less than 50 users, display them immediately)
4664 if (isset($_REQUEST['initial'])
4665 || isset($_REQUEST['showall'])
4666 || $GLOBALS['dbi']->numRows($res) < 50
4668 $html_output .= PMA_getUsersOverview(
4669 $res, $db_rights, $pmaThemeImage, $text_dir
4671 } else {
4672 $html_output .= PMA_getAddUserHtmlFieldset();
4673 } // end if (display overview)
4675 if (! $GLOBALS['is_ajax_request']
4676 || ! empty($_REQUEST['ajax_page_request'])
4678 if ($GLOBALS['is_reload_priv']) {
4679 $flushnote = new PMA_Message(
4681 'Note: phpMyAdmin gets the users\' privileges directly '
4682 . 'from MySQL\'s privilege tables. The content of these '
4683 . 'tables may differ from the privileges the server uses, '
4684 . 'if they have been changed manually. In this case, '
4685 . 'you should %sreload the privileges%s before you continue.'
4687 PMA_Message::NOTICE
4689 $flushLink = '<a href="server_privileges.php'
4690 . PMA_URL_getCommon(array('flush_privileges' => 1))
4691 . '" id="reload_privileges_anchor">';
4692 $flushnote->addParam(
4693 $flushLink,
4694 false
4696 $flushnote->addParam('</a>', false);
4697 } else {
4698 $flushnote = new PMA_Message(
4700 'Note: phpMyAdmin gets the users\' privileges directly '
4701 . 'from MySQL\'s privilege tables. The content of these '
4702 . 'tables may differ from the privileges the server uses, '
4703 . 'if they have been changed manually. In this case, '
4704 . 'the privileges have to be reloaded but currently, you '
4705 . 'don\'t have the RELOAD privilege.'
4707 . PMA_Util::showMySQLDocu(
4708 'privileges-provided',
4709 false,
4710 'priv_reload'
4712 PMA_Message::NOTICE
4715 $html_output .= $flushnote->getDisplay();
4719 return $html_output;
4723 * Get HTML snippet for display user properties
4725 * @param boolean $dbname_is_wildcard whether database name is wildcard or not
4726 * @param string $url_dbname url database name that urlencode() string
4727 * @param string $username username
4728 * @param string $hostname host name
4729 * @param string $dbname database name
4730 * @param string $tablename table name
4732 * @return string $html_output
4734 function PMA_getHtmlForUserProperties($dbname_is_wildcard,$url_dbname,
4735 $username, $hostname, $dbname, $tablename
4737 $html_output = '<div id="edit_user_dialog">';
4738 $html_output .= PMA_getHtmlHeaderForUserProperties(
4739 $dbname_is_wildcard, $url_dbname, $dbname, $username, $hostname, $tablename
4742 $sql = "SELECT '1' FROM `mysql`.`user`"
4743 . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'"
4744 . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "';";
4746 $user_does_not_exists = (bool) ! $GLOBALS['dbi']->fetchValue($sql);
4748 if ($user_does_not_exists) {
4749 $html_output .= PMA_Message::error(
4750 __('The selected user was not found in the privilege table.')
4751 )->getDisplay();
4752 $html_output .= PMA_getHtmlForLoginInformationFields();
4755 $_params = array(
4756 'username' => $username,
4757 'hostname' => $hostname,
4759 if (! is_array($dbname) && /*overload*/mb_strlen($dbname)) {
4760 $_params['dbname'] = $dbname;
4761 if (/*overload*/mb_strlen($tablename)) {
4762 $_params['tablename'] = $tablename;
4764 } else {
4765 $_params['dbname'] = $dbname;
4768 $html_output .= '<form class="submenu-item" name="usersForm" '
4769 . 'id="addUsersForm" action="server_privileges.php" method="post">' . "\n";
4770 $html_output .= PMA_URL_getHiddenInputs($_params);
4771 $html_output .= PMA_getHtmlToDisplayPrivilegesTable(
4772 // If $dbname is an array, pass any one db as all have same privs.
4773 PMA_ifSetOr($dbname, (is_array($dbname)) ? $dbname[0] : '*', 'length'),
4774 PMA_ifSetOr($tablename, '*', 'length')
4777 $html_output .= '</form>' . "\n";
4779 if (! is_array($dbname) && ! /*overload*/mb_strlen($tablename)
4780 && empty($dbname_is_wildcard)
4783 // no table name was given, display all table specific rights
4784 // but only if $dbname contains no wildcards
4786 $html_output .= '<form class="submenu-item" action="server_privileges.php" '
4787 . 'id="db_or_table_specific_priv" method="post">' . "\n";
4789 // unescape wildcards in dbname at table level
4790 $unescaped_db = PMA_Util::unescapeMysqlWildcards($dbname);
4791 list($html_rightsTable, $found_rows)
4792 = PMA_getHtmlForAllTableSpecificRights(
4793 $username, $hostname, $unescaped_db
4795 $html_output .= $html_rightsTable;
4797 if (! /*overload*/mb_strlen($dbname)) {
4798 // no database name was given, display select db
4799 $html_output .= PMA_getHtmlForSelectDbInEditPrivs($found_rows);
4801 } else {
4802 $html_output .= PMA_displayTablesInEditPrivs($dbname, $found_rows);
4804 $html_output .= '</fieldset>' . "\n";
4806 $html_output .= '<fieldset class="tblFooters">' . "\n"
4807 . ' <input type="submit" value="' . __('Go') . '" />'
4808 . '</fieldset>' . "\n"
4809 . '</form>' . "\n";
4812 // Provide a line with links to the relevant database and table
4813 if (! is_array($dbname) && /*overload*/mb_strlen($dbname)
4814 && empty($dbname_is_wildcard)
4816 $html_output .= PMA_getLinkToDbAndTable($url_dbname, $dbname, $tablename);
4820 if (! is_array($dbname) && ! /*overload*/mb_strlen($dbname)
4821 && ! $user_does_not_exists
4823 //change login information
4824 $html_output .= PMA_getHtmlForChangePassword('edit_other', $username, $hostname);
4825 $html_output .= PMA_getChangeLoginInformationHtmlForm($username, $hostname);
4827 $html_output .= '</div>';
4829 return $html_output;
4833 * Get queries for Table privileges to change or copy user
4835 * @param string $user_host_condition user host condition to
4836 * select relevant table privileges
4837 * @param array $queries queries array
4838 * @param string $username username
4839 * @param string $hostname host name
4841 * @return array $queries
4843 function PMA_getTablePrivsQueriesForChangeOrCopyUser($user_host_condition,
4844 $queries, $username, $hostname
4846 $res = $GLOBALS['dbi']->query(
4847 'SELECT `Db`, `Table_name`, `Table_priv` FROM `mysql`.`tables_priv`'
4848 . $user_host_condition,
4849 $GLOBALS['userlink'],
4850 PMA_DatabaseInterface::QUERY_STORE
4852 while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
4854 $res2 = $GLOBALS['dbi']->query(
4855 'SELECT `Column_name`, `Column_priv`'
4856 . ' FROM `mysql`.`columns_priv`'
4857 . ' WHERE `User`'
4858 . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'"
4859 . ' AND `Host`'
4860 . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . '\''
4861 . ' AND `Db`'
4862 . ' = \'' . PMA_Util::sqlAddSlashes($row['Db']) . "'"
4863 . ' AND `Table_name`'
4864 . ' = \'' . PMA_Util::sqlAddSlashes($row['Table_name']) . "'"
4865 . ';',
4866 null,
4867 PMA_DatabaseInterface::QUERY_STORE
4870 $tmp_privs1 = PMA_extractPrivInfo($row);
4871 $tmp_privs2 = array(
4872 'Select' => array(),
4873 'Insert' => array(),
4874 'Update' => array(),
4875 'References' => array()
4878 while ($row2 = $GLOBALS['dbi']->fetchAssoc($res2)) {
4879 $tmp_array = explode(',', $row2['Column_priv']);
4880 if (in_array('Select', $tmp_array)) {
4881 $tmp_privs2['Select'][] = $row2['Column_name'];
4883 if (in_array('Insert', $tmp_array)) {
4884 $tmp_privs2['Insert'][] = $row2['Column_name'];
4886 if (in_array('Update', $tmp_array)) {
4887 $tmp_privs2['Update'][] = $row2['Column_name'];
4889 if (in_array('References', $tmp_array)) {
4890 $tmp_privs2['References'][] = $row2['Column_name'];
4893 if (count($tmp_privs2['Select']) > 0 && ! in_array('SELECT', $tmp_privs1)) {
4894 $tmp_privs1[] = 'SELECT (`' . join('`, `', $tmp_privs2['Select']) . '`)';
4896 if (count($tmp_privs2['Insert']) > 0 && ! in_array('INSERT', $tmp_privs1)) {
4897 $tmp_privs1[] = 'INSERT (`' . join('`, `', $tmp_privs2['Insert']) . '`)';
4899 if (count($tmp_privs2['Update']) > 0 && ! in_array('UPDATE', $tmp_privs1)) {
4900 $tmp_privs1[] = 'UPDATE (`' . join('`, `', $tmp_privs2['Update']) . '`)';
4902 if (count($tmp_privs2['References']) > 0
4903 && ! in_array('REFERENCES', $tmp_privs1)
4905 $tmp_privs1[]
4906 = 'REFERENCES (`' . join('`, `', $tmp_privs2['References']) . '`)';
4909 $queries[] = 'GRANT ' . join(', ', $tmp_privs1)
4910 . ' ON ' . PMA_Util::backquote($row['Db']) . '.'
4911 . PMA_Util::backquote($row['Table_name'])
4912 . ' TO \'' . PMA_Util::sqlAddSlashes($username)
4913 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\''
4914 . (in_array('Grant', explode(',', $row['Table_priv']))
4915 ? ' WITH GRANT OPTION;'
4916 : ';');
4918 return $queries;
4922 * Get queries for database specific privileges for change or copy user
4924 * @param array $queries queries array with string
4925 * @param string $username username
4926 * @param string $hostname host name
4928 * @return array $queries
4930 function PMA_getDbSpecificPrivsQueriesForChangeOrCopyUser(
4931 $queries, $username, $hostname
4933 $user_host_condition = ' WHERE `User`'
4934 . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'"
4935 . ' AND `Host`'
4936 . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_hostname']) . '\';';
4938 $res = $GLOBALS['dbi']->query(
4939 'SELECT * FROM `mysql`.`db`' . $user_host_condition
4942 while ($row = $GLOBALS['dbi']->fetchAssoc($res)) {
4943 $queries[] = 'GRANT ' . join(', ', PMA_extractPrivInfo($row))
4944 . ' ON ' . PMA_Util::backquote($row['Db']) . '.*'
4945 . ' TO \'' . PMA_Util::sqlAddSlashes($username)
4946 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\''
4947 . ($row['Grant_priv'] == 'Y' ? ' WITH GRANT OPTION;' : ';');
4949 $GLOBALS['dbi']->freeResult($res);
4951 $queries = PMA_getTablePrivsQueriesForChangeOrCopyUser(
4952 $user_host_condition, $queries, $username, $hostname
4955 return $queries;
4959 * Prepares queries for adding users and
4960 * also create database and return query and message
4962 * @param boolean $_error whether user create or not
4963 * @param string $real_sql_query SQL query for add a user
4964 * @param string $sql_query SQL query to be displayed
4965 * @param string $username username
4966 * @param string $hostname host name
4967 * @param string $dbname database name
4969 * @return array $sql_query, $message
4971 function PMA_addUserAndCreateDatabase($_error, $real_sql_query, $sql_query,
4972 $username, $hostname, $dbname
4974 if ($_error || (!empty($real_sql_query)
4975 && !$GLOBALS['dbi']->tryQuery($real_sql_query))
4977 $_REQUEST['createdb-1'] = $_REQUEST['createdb-2']
4978 = $_REQUEST['createdb-3'] = null;
4979 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
4980 } else {
4981 $message = PMA_Message::success(__('You have added a new user.'));
4984 if (isset($_REQUEST['createdb-1'])) {
4985 // Create database with same name and grant all privileges
4986 $q = 'CREATE DATABASE IF NOT EXISTS '
4987 . PMA_Util::backquote(
4988 PMA_Util::sqlAddSlashes($username)
4989 ) . ';';
4990 $sql_query .= $q;
4991 if (! $GLOBALS['dbi']->tryQuery($q)) {
4992 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
4996 * Reload the navigation
4998 $GLOBALS['reload'] = true;
4999 $GLOBALS['db'] = $username;
5001 $q = 'GRANT ALL PRIVILEGES ON '
5002 . PMA_Util::backquote(
5003 PMA_Util::escapeMysqlWildcards(
5004 PMA_Util::sqlAddSlashes($username)
5006 ) . '.* TO \''
5007 . PMA_Util::sqlAddSlashes($username)
5008 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
5009 $sql_query .= $q;
5010 if (! $GLOBALS['dbi']->tryQuery($q)) {
5011 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
5015 if (isset($_REQUEST['createdb-2'])) {
5016 // Grant all privileges on wildcard name (username\_%)
5017 $q = 'GRANT ALL PRIVILEGES ON '
5018 . PMA_Util::backquote(
5019 PMA_Util::sqlAddSlashes($username) . '\_%'
5020 ) . '.* TO \''
5021 . PMA_Util::sqlAddSlashes($username)
5022 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
5023 $sql_query .= $q;
5024 if (! $GLOBALS['dbi']->tryQuery($q)) {
5025 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
5029 if (isset($_REQUEST['createdb-3'])) {
5030 // Grant all privileges on the specified database to the new user
5031 $q = 'GRANT ALL PRIVILEGES ON '
5032 . PMA_Util::backquote(
5033 PMA_Util::sqlAddSlashes($dbname)
5034 ) . '.* TO \''
5035 . PMA_Util::sqlAddSlashes($username)
5036 . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\';';
5037 $sql_query .= $q;
5038 if (! $GLOBALS['dbi']->tryQuery($q)) {
5039 $message = PMA_Message::rawError($GLOBALS['dbi']->getError());
5042 return array($sql_query, $message);
5046 * Get the hashed string for password
5048 * @param string $password password
5050 * @return string $hashedPassword
5052 function PMA_getHashedPassword($password)
5054 $result = $GLOBALS['dbi']->fetchSingleRow(
5055 "SELECT PASSWORD('" . $password . "') AS `password`;"
5058 $hashedPassword = $result['password'];
5060 return $hashedPassword;
5065 * Get SQL queries for Display and Add user
5067 * @param string $username username
5068 * @param string $hostname host name
5069 * @param string $password password
5071 * @return array ($create_user_real, $create_user_show,$real_sql_query, $sql_query
5072 * $password_set_real, $password_set_show)
5074 function PMA_getSqlQueriesForDisplayAndAddUser($username, $hostname, $password)
5076 $slashedUsername = PMA_Util::sqlAddSlashes($username);
5077 $slashedHostname = PMA_Util::sqlAddSlashes($hostname);
5078 $slashedPassword = PMA_Util::sqlAddSlashes($password);
5079 $serverType = PMA_Util::getServerType();
5081 $create_user_stmt = sprintf(
5082 'CREATE USER \'%s\'@\'%s\'',
5083 $slashedUsername,
5084 $slashedHostname
5087 // See https://github.com/phpmyadmin/phpmyadmin/pull/11560#issuecomment-147158219
5088 // for details regarding details of syntax usage for various versions
5090 // 'IDENTIFIED WITH auth_plugin'
5091 // is supported by MySQL 5.5.7+
5092 if (($serverType == 'MySQL' || $serverType == 'Percona Server')
5093 && PMA_MYSQL_INT_VERSION >= 50507
5094 && isset($_REQUEST['authentication_plugin'])
5096 $create_user_stmt .= ' IDENTIFIED WITH '
5097 . $_REQUEST['authentication_plugin'];
5100 // 'IDENTIFIED VIA auth_plugin'
5101 // is supported by MariaDB 5.2+
5102 if ($serverType == 'MariaDB'
5103 && PMA_MYSQL_INT_VERSION >= 50200
5104 && isset($_REQUEST['authentication_plugin'])
5106 $create_user_stmt .= ' IDENTIFIED VIA '
5107 . $_REQUEST['authentication_plugin'];
5110 $create_user_real = $create_user_show = $create_user_stmt;
5112 $password_set_stmt = 'SET PASSWORD FOR \'%s\'@\'%s\' = \'%s\'';
5113 $password_set_show = sprintf(
5114 $password_set_stmt,
5115 $slashedUsername,
5116 $slashedHostname,
5117 '***'
5119 $password_set_real = null;
5121 $sql_query_stmt = sprintf(
5122 'GRANT %s ON *.* TO \'%s\'@\'%s\'',
5123 join(', ', PMA_extractPrivInfo()),
5124 $slashedUsername,
5125 $slashedHostname
5127 $real_sql_query = $sql_query = $sql_query_stmt;
5129 // Set the proper hashing method
5130 if (isset($_REQUEST['authentication_plugin'])) {
5131 PMA_setProperPasswordHashing(
5132 $_REQUEST['authentication_plugin']
5135 // Use 'CREATE USER ... WITH ... AS ..' syntax for
5136 // newer MySQL versions
5137 // and 'CREATE USER ... USING .. VIA ..' syntax for
5138 // newer MariaDB versions
5139 if ((($serverType == 'MySQL' || $serverType == 'Percona Server')
5140 && PMA_MYSQL_INT_VERSION >= 50706)
5141 || ($serverType == 'MariaDB'
5142 && PMA_MYSQL_INT_VERSION >= 50200)
5144 $password_set_real = null;
5146 // Required for binding '%' with '%s'
5147 $create_user_stmt = str_replace(
5148 '%', '%%', $create_user_stmt
5151 // MariaDB uses 'USING' whereas MySQL uses 'AS'
5152 if ($serverType == 'MariaDB') {
5153 $create_user_stmt .= ' USING \'%s\'';
5154 } else {
5155 $create_user_stmt .= ' AS \'%s\'';
5158 $create_user_real = $create_user_show = $create_user_stmt;
5160 if ($_POST['pred_password'] == 'keep') {
5161 $create_user_real = sprintf(
5162 $create_user_stmt,
5163 $slashedPassword
5165 $create_user_show = sprintf(
5166 $create_user_stmt,
5167 '***'
5169 } else if ($_POST['pred_password'] == 'none') {
5170 $create_user_real = sprintf(
5171 $create_user_stmt,
5172 null
5174 $create_user_show = sprintf(
5175 $create_user_stmt,
5176 '***'
5178 } else {
5179 $hashedPassword = PMA_getHashedPassword($_POST['pma_pw']);
5180 $create_user_real = sprintf(
5181 $create_user_stmt,
5182 $hashedPassword
5184 $create_user_show = sprintf(
5185 $create_user_stmt,
5186 '***'
5189 } else {
5190 // Use 'SET PASSWORD' syntax for pre-5.7.6 MySQL versions
5191 // and pre-5.2.0 MariaDB versions
5192 if ($_POST['pred_password'] == 'keep') {
5193 $password_set_real = sprintf(
5194 $password_set_stmt,
5195 $slashedUsername,
5196 $slashedHostname,
5197 $slashedPassword
5199 } else if ($_POST['pred_password'] == 'none') {
5200 $password_set_real = sprintf(
5201 $password_set_stmt,
5202 $slashedUsername,
5203 $slashedHostname,
5204 null
5206 } else {
5207 $hashedPassword = PMA_getHashedPassword($_POST['pma_pw']);
5208 $password_set_real = sprintf(
5209 $password_set_stmt,
5210 $slashedUsername,
5211 $slashedHostname,
5212 $hashedPassword
5217 // add REQUIRE clause
5218 $require_clause = PMA_getRequireClause();
5219 $real_sql_query .= $require_clause;
5220 $sql_query .= $require_clause;
5222 if ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] == 'Y')
5223 || (isset($_POST['max_questions']) || isset($_POST['max_connections'])
5224 || isset($_POST['max_updates']) || isset($_POST['max_user_connections']))
5226 $with_clause = PMA_getWithClauseForAddUserAndUpdatePrivs();
5227 $real_sql_query .= $with_clause;
5228 $sql_query .= $with_clause;
5231 if (isset($create_user_real)) {
5232 $create_user_real .= ';';
5233 $create_user_show .= ';';
5235 $real_sql_query .= ';';
5236 $sql_query .= ';';
5237 // No Global GRANT_OPTION privilege
5238 if (!$GLOBALS['is_grantuser']) {
5239 $real_sql_query = '';
5240 $sql_query = '';
5243 // Use 'SET PASSWORD' for pre-5.7.6 MySQL versions
5244 // and pre-5.2.0 MariaDB
5245 if (($serverType == 'MySQL'
5246 && PMA_MYSQL_INT_VERSION >= 50706)
5247 || ($serverType == 'MariaDB'
5248 && PMA_MYSQL_INT_VERSION >= 50200)
5250 $password_set_real = null;
5251 $password_set_show = null;
5252 } else {
5253 $password_set_real .= ";";
5254 $password_set_show .= ";";
5257 return array($create_user_real,
5258 $create_user_show,
5259 $real_sql_query,
5260 $sql_query,
5261 $password_set_real,
5262 $password_set_show