<?php
require_once('config.php');

function parseGrant($grant) {
    if (preg_match("/GRANT (.*?) ON `(.*?)`\.`(.*?)`(?: \((.*?)\))?/", $grant, $matches)) {
        $permissions = trim($matches[1]);
        
        // Új elágazás az oszlopok kezelésére
        if (preg_match("/(\w+) \((.*?)\)/", $permissions, $permMatches)) {
            $permissions = trim($permMatches[1]);
            $columns = array_map('htmlspecialchars', array_map('trim', explode(',', $permMatches[2])));
        } else {
            $columns = ["*"];
        }
        
        $database = htmlspecialchars($matches[2]);
        $table = htmlspecialchars($matches[3]);
        return [$permissions, $database, $table, $columns];
    } elseif (preg_match("/GRANT (.*?) ON `(.*?)`\.\*/", $grant, $matches)) {
        $permissions = trim($matches[1]);
        $database = htmlspecialchars($matches[2]);
        return [$permissions, $database, "Minden tábla", ["Minden oszlop"]];
    }
    return ["Ismeretlen", "-", "-", ["-"]];
}




?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <?php if(!isset($_POST["user"])) {
        echo "Térj vissza az előző oldalra, és adj meg egy ténlyeges felhasználót!";
    ?>
        
    
    <?php    } else {
        $sql = "SHOW GRANTS FOR ".$_POST["user"].";";

        $result = $conn->query($sql);
        
        if ($result) {
            echo "<table border='1'>";
            echo "<tr><th>Felhasználó</th><th>Jogosultság</th><th>Adatbázis</th><th>Tábla</th><th>Oszlop</th></tr>";
            
            while ($row = $result->fetch_array(MYSQLI_NUM)) {
                foreach ($row as $grant) {
                    list($permissions, $database, $table, $columns) = parseGrant($grant);
                    echo "<tr>";
                    echo "<td>" . htmlspecialchars($_POST["user"]) . "</td>";
                    echo "<td>" . htmlspecialchars($permissions) . "</td>";
                    echo "<td>" . htmlspecialchars($database) . "</td>";
                    echo "<td>" . htmlspecialchars($table) . "</td>";
                    echo "<td>" . htmlspecialchars(implode(", ", $columns)) . "</td>";
                    echo "</tr>";
                }
            }
            
            echo "</table>";
        } else {
            echo "Hiba a lekérdezésben: " . $conn->error;
        }
        
        $conn->close();
        
        
    }
    ?>
    
</body>
</html>