<?php

//  * @LastEditors: Swk(葫芦侠:陌南尘。)
//  * @hitokoto: 先谋杀全世界的噪音 再审判心跳的供词.

ob_clean();
// 配置文件
require_once 'config.php';

// 会话管理
session_start();

// 验证登录状态
function isLoggedIn() {
    return isset($_SESSION['authenticated']) && $_SESSION['authenticated'] === true;
}

// 登录处理
if (isset($_POST['login'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    if ($username === USERNAME && password_verify($password, PASSWORD_HASH)) {
        $_SESSION['authenticated'] = true;
        header('Location: index.php');
        exit;
    } else {
        $loginError = '用户名或密码错误';
    }
}

// 登出处理
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: index.php');
    exit;
}

// 如果未登录，显示登录页面
if (!isLoggedIn()) {
    include 'login.php';
    exit;
}

// 文件管理功能
// 获取当前路径
// 获取当前路径
function getCurrentPath() {
    $path = isset($_GET['path']) ? $_GET['path'] : '';
    $path = urldecode($path);
    $path = UPLOAD_DIR . '/' . ltrim($path, '/');
    
    // 安全检查：确保路径在上传目录内
    if (strpos(realpath($path), realpath(UPLOAD_DIR)) !== 0) {
        return UPLOAD_DIR;
    }
    
    return $path;
}
// 获取相对路径
function getRelativePath($path) {
    $uploadDir = realpath(UPLOAD_DIR);
    $realPath = realpath($path);
    
    if (strpos($realPath, $uploadDir) === 0) {
        return substr($realPath, strlen($uploadDir) + 1);
    }
    
    return '';
}

// 创建文件夹
if (isset($_POST['create_folder'])) {
    $folderName = $_POST['folder_name'];
    $currentPath = getCurrentPath();
    $newFolderPath = $currentPath . '/' . $folderName;
    
    if (!file_exists($newFolderPath)) {
        if (mkdir($newFolderPath, 0777, true)) {
            $successMessage = '文件夹创建成功';
        } else {
            $errorMessage = '文件夹创建失败';
        }
    } else {
        $errorMessage = '文件夹已存在';
    }
}

// 重命名文件夹
if (isset($_POST['rename_folder'])) {
    $oldName = $_POST['old_name'];
    $newName = $_POST['new_name'];
    $currentPath = getCurrentPath();
    
    $oldPath = $currentPath . '/' . $oldName;
    $newPath = $currentPath . '/' . $newName;
    
    if (file_exists($oldPath) && !file_exists($newPath)) {
        if (rename($oldPath, $newPath)) {
            $successMessage = '文件夹重命名成功';
        } else {
            $errorMessage = '文件夹重命名失败';
        }
    } else {
        $errorMessage = '操作失败，可能源文件夹不存在或目标文件夹已存在';
    }
}

// 删除文件夹
if (isset($_POST['delete_folder'])) {
    $folderName = $_POST['folder_name'];
    $currentPath = getCurrentPath();
    $folderPath = $currentPath . '/' . $folderName;
    
    if (is_dir($folderPath)) {
        // 递归删除文件夹
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($folderPath, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );
        
        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        
        if (rmdir($folderPath)) {
            $successMessage = '文件夹删除成功';
        } else {
            $errorMessage = '文件夹删除失败';
        }
    } else {
        $errorMessage = '文件夹不存在';
    }
}



// index.php

// 批量删除文件
if (isset($_POST['delete_selected_files'])) {
    $selectedFiles = $_POST['selected_files'];
    $currentPath = getCurrentPath();

    $successCount = 0;
    foreach ($selectedFiles as $filePath) {
        $fileName = basename($filePath);
        $currentFilePath = $currentPath . '/' . $fileName;

        if (file_exists($currentFilePath)) {
            if (unlink($currentFilePath)) {
                $successCount++;
            }
        }
    }

    if ($successCount > 0) {
        $successMessage = "成功删除 {$successCount} 个文件";
    } else {
        $errorMessage = '文件删除失败，请检查权限';
    }
}


// 重命名文件
if (isset($_POST['rename_file'])) {
    $oldName = $_POST['old_name'];
    $newName = $_POST['new_name'];
    $currentPath = getCurrentPath();
    
    $oldPath = $currentPath . '/' . $oldName;
    $newPath = $currentPath . '/' . $newName;
    
    if (file_exists($oldPath) && !file_exists($newPath)) {
        if (rename($oldPath, $newPath)) {
            $successMessage = '文件重命名成功';
        } else {
            $errorMessage = '文件重命名失败';
        }
    } else {
        $errorMessage = '操作失败，可能源文件不存在或目标文件已存在';
    }
}

// 删除文件
if (isset($_POST['delete_file'])) {
    $fileName = $_POST['file_name'];
    $currentPath = getCurrentPath();
    $filePath = $currentPath . '/' . $fileName;
    
    if (file_exists($filePath)) {
        if (unlink($filePath)) {
            $successMessage = '文件删除成功';
        } else {
            $errorMessage = '文件删除失败';
        }
    } else {
        $errorMessage = '文件不存在';
    }
}

// 移动文件
if (isset($_POST['move_file'])) {
    $fileName = $_POST['file_name'];
    $targetFolder = $_POST['target_folder'];
    $currentPath = getCurrentPath();
    $filePath = $currentPath . '/' . $fileName;
    
    // 构建目标路径
    $targetFolder = ltrim($targetFolder, '/');
    $targetDir = UPLOAD_DIR . '/' . $targetFolder;
    $targetPath = $targetDir . '/' . $fileName;
    
    // 确保目标目录存在
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }
    
    // 安全检查：验证目标路径是否在上传目录内
    $uploadDirReal = realpath(UPLOAD_DIR);
    $targetDirReal = realpath(dirname($targetPath));
    
    if (!$uploadDirReal || !$targetDirReal) {
        $errorMessage = '路径解析失败，请检查目录权限';
    } else {
        // 不区分大小写的路径验证（适用于Windows）
        $isSubDir = stripos($targetDirReal, $uploadDirReal) === 0;
        
        if (!$isSubDir) {
            $errorMessage = '目标路径不在上传目录内，操作被拒绝';
        } elseif (file_exists($filePath) && !file_exists($targetPath)) {
            if (rename($filePath, $targetPath)) {
                $successMessage = '文件移动成功';
            } else {
                $errorMessage = '文件移动失败，请检查权限';
            }
        } else {
            $errorMessage = '操作失败，可能源文件不存在或目标文件已存在';
        }
    }
}

// 批量文件上传处理
// 批量文件上传处理
if (isset($_FILES['files'])) {
    $currentPath = getCurrentPath(); // 获取当前路径
    $uploadedFiles = $_FILES['files'];
    $totalFiles = count($uploadedFiles['name']);
    $successCount = 0;

    for ($i = 0; $i < $totalFiles; $i++) {
        $fileName = $uploadedFiles['name'][$i];
        $fileTmpName = $uploadedFiles['tmp_name'][$i];
        $fileSize = $uploadedFiles['size'][$i];
        $fileError = $uploadedFiles['error'][$i];

        if ($fileError === 0) {
            $filePath = $currentPath . '/' . $fileName;

            // 检查文件是否已存在
            if (file_exists($filePath)) {
                // 自动重命名文件
                $fileNameInfo = pathinfo($fileName);
                $baseName = $fileNameInfo['filename'];
                $extension = isset($fileNameInfo['extension']) ? '.' . $fileNameInfo['extension'] : '';
                $counter = 1;

                while (file_exists($currentPath . '/' . $baseName . '_' . $counter . $extension)) {
                    $counter++;
                }

                $fileName = $baseName . '_' . $counter . $extension;
                $filePath = $currentPath . '/' . $fileName;
            }

            if (move_uploaded_file($fileTmpName, $filePath)) {
                $successCount++;
            }
        }
    }

    if ($successCount > 0) {
        $_SESSION['successMessage'] = "成功上传 {$successCount} 个文件";
    } else {
        $_SESSION['errorMessage'] = '文件上传失败，请检查目录权限';
    }

    // 刷新页面
    header('Location: ' . $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET));
    exit;
}


// 获取文件列表
$currentPath = getCurrentPath();
$relativePath = getRelativePath($currentPath);
$directory = new DirectoryIterator($currentPath);

// 搜索功能
$searchTerm = isset($_GET['search']) ? trim($_GET['search']) : '';

// 排序功能
$sortBy = isset($_GET['sort']) ? $_GET['sort'] : 'name';
$sortOrder = isset($_GET['order']) ? $_GET['order'] : 'asc';

// 分页功能
$itemsPerPage = 10;
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$currentPage = max(1, $currentPage);

// 收集文件夹和文件
$folders = [];
$files = [];

foreach ($directory as $item) {
    if ($item->isDot()) continue;
    
    // 搜索过滤
    if (!empty($searchTerm) && stripos($item->getFilename(), $searchTerm) === false) {
        continue;
    }
    
    $itemPath = $item->getPathname();
    $itemRelativePath = getRelativePath($itemPath);
    
    if ($item->isDir()) {
        $folders[] = [
            'name' => $item->getFilename(),
            'path' => $itemRelativePath,
            'time' => $item->getMTime(),
            'type' => 'folder'
        ];
    } else {
        $files[] = [
            'name' => $item->getFilename(),
            'path' => $itemRelativePath,
            'time' => $item->getMTime(),
            'size' => $item->getSize(),
            'type' => mime_content_type($itemPath)
        ];
    }
}

// 排序
usort($files, function($a, $b) use ($sortBy, $sortOrder) {
    if ($sortBy === 'name') {
        $result = strcasecmp($a['name'], $b['name']);
    } elseif ($sortBy === 'time') {
        $result = $a['time'] - $b['time'];
    } elseif ($sortBy === 'size') {
        $result = $a['size'] - $b['size'];
    } elseif ($sortBy === 'type') {
        $result = strcasecmp($a['type'], $b['type']);
    } else {
        $result = 0;
    }
    
    return ($sortOrder === 'desc') ? -$result : $result;
});

// 分页
$totalFiles = count($files);
$totalPages = ceil($totalFiles / $itemsPerPage);
$currentPage = min($currentPage, $totalPages);
$offset = ($currentPage - 1) * $itemsPerPage;
$paginatedFiles = array_slice($files, $offset, $itemsPerPage);

// 获取所有文件夹用于移动操作
$allFolders = [];
function scanFolders($dir, &$result, $baseDir) {
    $directory = new DirectoryIterator($dir);
    foreach ($directory as $item) {
        if ($item->isDot()) continue;
        if ($item->isDir()) {
            $relativePath = substr($item->getPathname(), strlen($baseDir) + 1);
            $result[] = [
                'name' => $item->getFilename(),
                'relativePath' => $relativePath
            ];
            scanFolders($item->getPathname(), $result, $baseDir);
        }
    }
}
scanFolders(UPLOAD_DIR, $allFolders, UPLOAD_DIR);




// 批量移动文件
if (isset($_POST['move_selected_files'])) {
    $selectedFiles = $_POST['selected_files'];
    $targetFolder = $_POST['target_folder'];
    $currentPath = getCurrentPath();

    // 构建目标路径
    $targetFolder = ltrim($targetFolder, '/');
    $targetDir = UPLOAD_DIR . '/' . $targetFolder;

    // 确保目标目录存在
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    // 安全检查：验证目标路径是否在上传目录内
    $uploadDirReal = realpath(UPLOAD_DIR);
    $targetDirReal = realpath(dirname($targetDir));

    if (!$uploadDirReal || !$targetDirReal) {
        $_SESSION['errorMessage'] = '路径解析失败，请检查目录权限';
        header('Location: ' . $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET));
        exit;
    } else {
        // 不区分大小写的路径验证（适用于Windows）
        $isSubDir = stripos($targetDirReal, $uploadDirReal) === 0;

        if (!$isSubDir) {
            $_SESSION['errorMessage'] = '目标路径不在上传目录内，操作被拒绝';
            header('Location: ' . $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET));
            exit;
        } else {
            $successCount = 0;
            foreach ($selectedFiles as $filePath) {
                $fileName = basename($filePath);
                $currentFilePath = $currentPath . '/' . $fileName;
                $targetFilePath = $targetDir . '/' . $fileName;

                if (file_exists($currentFilePath) && !file_exists($targetFilePath)) {
                    if (rename($currentFilePath, $targetFilePath)) {
                        $successCount++;
                    }
                }
            }

            if ($successCount > 0) {
                $_SESSION['successMessage'] = "成功移动 {$successCount} 个文件";
                header('Location: ' . $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET));
                exit;
            } else {
                $_SESSION['errorMessage'] = '文件移动失败，请检查权限';
                header('Location: ' . $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET));
                exit;
            }
        }
    }
}

















// index.php 文件中，添加以下代码
// 单个文件下载

if (isset($_GET['download_file'])) {
    $filePath = UPLOAD_DIR . '/' . $_GET['file'];
    if (file_exists($filePath) && is_file($filePath)) {
        // 清除输出缓冲区
        ob_clean(); 
        flush();

        // 设置头部信息
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filePath));

        // 打开文件
        $file = fopen($filePath, 'rb');
        if ($file) {
            // 读取并输出文件内容
            while (!feof($file)) {
                print(fread($file, 1024*8));
                ob_flush();
                flush();
            }
            fclose($file);
        } else {
            $errorMessage = '无法打开文件';
        }
        exit;
    } else {
        $errorMessage = '文件不存在';
    }
}


// index.php 文件中，批量文件下载部分

if (isset($_GET['download_selected_files'])) {
    $selectedFiles = explode(',', $_GET['files']);
    $zip = new ZipArchive();
    $zipFileName = 'download_' . time() . '.zip';

    // 清除输出缓冲区
    ob_clean(); 
    flush();

    if ($zip->open($zipFileName, ZipArchive::CREATE) === TRUE) {
        foreach ($selectedFiles as $file) {
            $filePath = UPLOAD_DIR . '/' . $file;
            if (file_exists($filePath) && is_file($filePath)) {
                $zip->addFile($filePath, basename($filePath));
            }
        }
        $zip->close();

        if (file_exists($zipFileName)) {
            // 设置头部信息
            header('Content-Description: File Transfer');
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="' . $zipFileName . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($zipFileName));

            // 打开文件
            $file = fopen($zipFileName, 'rb');
            if ($file) {
                // 读取并输出文件内容
                while (!feof($file)) {
                    print(fread($file, 1024*8));
                    ob_flush();
                    flush();
                }
                fclose($file);
            } else {
                $errorMessage = '无法打开压缩文件';
            }

            // 删除临时 zip 文件
            unlink($zipFileName); 
        } else {
            $errorMessage = '压缩文件创建失败';
        }
    } else {
        $errorMessage = '无法创建压缩文件';
    }
}


// 获取存储使用情况
function formatSize($bytes) {
    if ($bytes === 0) return '0 Bytes';
    
    $sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    $i = floor(log($bytes, 1024));
    
    return round($bytes / pow(1024, $i), 2) . ' ' . $sizes[$i];
}

$totalSpace = disk_total_space(UPLOAD_DIR);
$freeSpace = disk_free_space(UPLOAD_DIR);
$usedSpace = $totalSpace - $freeSpace;
$spaceUsagePercent = ($totalSpace > 0) ? ($usedSpace / $totalSpace) * 100 : 0;

include 'template.php';
?>    