public static function currentUserHasPrivilege($priv, $db = null, $tbl = null)
{
// Get the username for the current user in the format
// required to use in the information schema database.
list($user, $host) = $GLOBALS['dbi']->getCurrentUserAndHost();
if ($user === '') {
// MySQL is started with --skip-grant-tables
return true;
}
$username = "''";
$username .= str_replace("'", "''", $user);
$username .= "''@''";
$username .= str_replace("'", "''", $host);
$username .= "''";
// Prepare the query
$query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` " . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
// Check global privileges first.
$user_privileges = $GLOBALS['dbi']->fetchValue(sprintf($query, 'USER_PRIVILEGES', $username, $priv));
if ($user_privileges) {
return true;
}
// If a database name was provided and user does not have the
// required global privilege, try database-wise permissions.
if ($db !== null) {
$query .= " AND '%s' LIKE `TABLE_SCHEMA`";
$schema_privileges = $GLOBALS['dbi']->fetchValue(sprintf($query, 'SCHEMA_PRIVILEGES', $username, $priv, $GLOBALS['dbi']->escapeString($db)));
if ($schema_privileges) {
return true;
}
} else {
// There was no database name provided and the user
// does not have the correct global privilege.
return false;
}
// If a table name was also provided and we still didn't
// find any valid privileges, try table-wise privileges.
if ($tbl !== null) {
// need to escape wildcards in db and table names, see bug #3518484
$tbl = str_replace(array('%', '_'), array('\\%', '\\_'), $tbl);
$query .= " AND TABLE_NAME='%s'";
$table_privileges = $GLOBALS['dbi']->fetchValue(sprintf($query, 'TABLE_PRIVILEGES', $username, $priv, $GLOBALS['dbi']->escapeString($db), $GLOBALS['dbi']->escapeString($tbl)));
if ($table_privileges) {
return true;
}
}
// If we reached this point, the user does not
// have even valid table-wise privileges.
return false;
}