Files
phpfilebrowser/index.php
T
Johann a8f78536f0 refactor: extract configuration into config.php
- New config.php.example template (tracked)
- config.php git-ignored
- index.php loads config.php if present, falls back to defaults
2026-06-09 17:19:46 +02:00

1349 lines
47 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* phpfilebrowser — Single-file PHP file browser
* No external dependencies. Modern dark theme. Responsive.
*/
// ── Configuration ──────────────────────────────────────────────────────────
// Load config.php if present, otherwise use defaults
if (file_exists(__DIR__ . '/config.php')) {
require __DIR__ . '/config.php';
}
if (!defined('ENTRY_POINT')) {
define('ENTRY_POINT', '/tmp');
}
// ── Helpers ────────────────────────────────────────────────────────────────
function isMediaFile(string $path): bool
{
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$imageTypes = ['jpg','jpeg','png','gif','webp','svg','bmp','ico','tiff','avif'];
$audioTypes = ['mp3','ogg','wav','flac','aac','wma','opus','m4a'];
$videoTypes = ['mp4','webm','ogg','mov','avi','mkv','m4v'];
return in_array($ext, $imageTypes)
|| in_array($ext, $audioTypes)
|| in_array($ext, $videoTypes);
}
function isImageFile(string $path): bool
{
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
return in_array($ext, ['jpg','jpeg','png','gif','webp','svg','bmp','ico','tiff','avif']);
}
function formatSize(int|float $bytes): string
{
if ($bytes === 0) return '—';
$units = ['B','KB','MB','GB','TB'];
$i = 0;
while ($bytes >= 1024 && $i < count($units) - 1) {
$bytes /= 1024;
$i++;
}
return round($bytes, 2) . ' ' . $units[$i];
}
function formatDateTime(string $datetime): string
{
try {
$ts = strtotime($datetime);
if ($ts === false) return $datetime;
return date('d.m.Y H:i', $ts);
} catch (\Exception $e) {
return $datetime;
}
}
function encodePath(string $path): string
{
return rawurlencode($path);
}
function getRelativePath(string $fullPath): string
{
$entry = ENTRY_POINT;
if ($fullPath === $entry) return '/';
if (strpos($fullPath, $entry . '/') === 0) {
$rel = substr($fullPath, strlen($entry) + 1);
return $rel === '' ? '/' : '/' . $rel;
}
return $fullPath;
}
function getBreadcrumbs(string $path): array
{
$entry = ENTRY_POINT;
$parts = [];
if ($path === $entry) {
return [['label' => '/', 'path' => $entry]];
}
// Root segment
$parts[] = ['label' => '/', 'path' => $entry];
$rel = substr($path, strlen($entry) + 1);
$segments = explode('/', $rel);
$current = $entry;
foreach ($segments as $segment) {
if ($segment === '') continue;
$current .= '/' . $segment;
$parts[] = ['label' => $segment, 'path' => $current];
}
return $parts;
}
// ── API: Directory Listing ─────────────────────────────────────────────────
function handleList(): void
{
$rawPath = $_GET['path'] ?? '';
$currentPath = $rawPath === '' ? ENTRY_POINT : ENTRY_POINT . '/' . urldecode($rawPath);
// Resolve to absolute path inside ENTRY_POINT
$currentPath = realpath($currentPath);
if ($currentPath === false || strpos($currentPath, ENTRY_POINT) !== 0) {
http_response_code(404);
echo json_encode(['error' => 'Directory not found']);
return;
}
$items = [];
if ($dh = opendir($currentPath)) {
while (($entry = readdir($dh)) !== false) {
if ($entry === '.' || $entry === '..') continue;
$fullPath = $currentPath . '/' . $entry;
$stat = stat($fullPath);
$items[] = [
'name' => $entry,
'type' => is_dir($fullPath) ? 'dir' : 'file',
'size' => is_dir($fullPath) ? null : ($stat !== false ? $stat['size'] : 0),
'modified' => $stat !== false ? date('Y-m-d H:i:s', $stat['mtime']) : '',
'path' => $fullPath,
];
}
closedir($dh);
}
echo json_encode($items);
}
// ── API: File Download ─────────────────────────────────────────────────────
function handleDownload(): void
{
$rawFile = $_GET['file'] ?? '';
$filePath = ENTRY_POINT . '/' . urldecode($rawFile);
if (!is_file($filePath)) {
http_response_code(404);
echo 'File not found';
return;
}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Content-Length: ' . filesize($filePath));
header('Cache-Control: no-cache');
header('Pragma: no-cache');
readfile($filePath);
exit;
}
// ── MIME-Type Mapping ────────────────────────────────────────────
function getMimeType(string $filePath): string
{
// Try finfo first (most accurate)
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $filePath);
finfo_close($finfo);
if ($mime && $mime !== 'application/octet-stream') {
return $mime;
}
}
// Fallback: extension-based mapping
$ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
$mimes = [
// Images
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp',
'svg' => 'image/svg+xml',
'bmp' => 'image/bmp',
'ico' => 'image/x-icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'avif' => 'image/avif',
// Audio
'mp3' => 'audio/mpeg',
'ogg' => 'audio/ogg',
'wav' => 'audio/wav',
'flac' => 'audio/flac',
'aac' => 'audio/aac',
'wma' => 'audio/x-ms-wma',
'opus' => 'audio/opus',
'm4a' => 'audio/mp4',
// Video
'mp4' => 'video/mp4',
'webm' => 'video/webm',
'ogg' => 'video/ogg',
'mov' => 'video/quicktime',
'avi' => 'video/x-msvideo',
'mkv' => 'video/x-matroska',
'm4v' => 'video/x-m4v',
];
return $mimes[$ext] ?? 'application/octet-stream';
}
// ── API: File Stream (for media playback) ──────────────────────────
function handleStream(): void
{
$rawFile = $_GET['file'] ?? '';
$filePath = ENTRY_POINT . '/' . urldecode($rawFile);
if (!is_file($filePath)) {
http_response_code(404);
echo 'File not found';
return;
}
$mime = getMimeType($filePath);
$size = filesize($filePath);
// Handle Range requests (seeking support)
$rangeHeader = $_SERVER['HTTP_RANGE'] ?? '';
if (!empty($rangeHeader)) {
// Parse Range header (format: bytes=start-end)
if (preg_match('/bytes=(\d+)-(\d+)?/', $rangeHeader, $matches)) {
$start = (int)$matches[1];
$end = isset($matches[2]) && $matches[2] !== '' ? (int)$matches[2] : $size - 1;
$length = $end - $start + 1;
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
header('Accept-Ranges: bytes');
header('Content-Length: ' . $length);
header('Content-Type: ' . $mime);
header('Cache-Control: public, max-age=3600');
$fp = fopen($filePath, 'rb');
fseek($fp, $start);
$remaining = $length;
while ($remaining > 0 && !feof($fp)) {
$chunk = min(8192, $remaining);
echo fread($fp, $chunk);
$remaining -= $chunk;
}
fclose($fp);
exit;
}
}
// Full file response
header('HTTP/1.1 200 OK');
header('Content-Type: ' . $mime);
header('Content-Length: ' . $size);
header('Accept-Ranges: bytes');
header('Cache-Control: public, max-age=3600');
readfile($filePath);
exit;
}
// ── API Router ─────────────────────────────────────────────────────
if (isset($_GET['action'])) {
header('Content-Type: application/json');
if ($_GET['action'] === 'list') {
handleList();
exit;
}
if ($_GET['action'] === 'download') {
header('Content-Type: application/octet-stream');
handleDownload();
exit;
}
if ($_GET['action'] === 'stream') {
handleStream();
exit;
}
}
// ── HTML Output ────────────────────────────────────────────────────────────
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Browser</title>
<style>
/* ── CSS Variables ────────────────────────────────────────────── */
:root {
--bg-primary: #0d1117;
--bg-secondary: #161b22;
--bg-tertiary: #21262d;
--bg-hover: #30363d;
--border-color: #30363d;
--text-primary: #e6edf3;
--text-secondary: #8b949e;
--text-muted: #6e7681;
--accent: #58a6ff;
--accent-hover: #79b8ff;
--success: #3fb950;
--warning: #d29922;
--danger: #f85149;
--radius: 8px;
--radius-sm: 4px;
--transition: 0.2s ease;
--shadow: 0 8px 32px rgba(0,0,0,0.4);
--shadow-lg: 0 16px 64px rgba(0,0,0,0.6);
}
/* ── Reset & Base ─────────────────────────────────────────────── */
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html, body {
height: 100%;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
font-size: 14px;
line-height: 1.5;
color: var(--text-primary);
background: var(--bg-primary);
-webkit-font-smoothing: antialiased;
}
body {
display: flex;
flex-direction: column;
overflow: hidden;
}
/* ── Header / Toolbar ─────────────────────────────────────────── */
.toolbar {
display: flex;
align-items: center;
gap: 10px;
padding: 12px 16px;
background: var(--bg-secondary);
border-bottom: 1px solid var(--border-color);
flex-shrink: 0;
flex-wrap: wrap;
}
.toolbar-group {
display: flex;
align-items: center;
gap: 6px;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
padding: 6px 12px;
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
background: var(--bg-tertiary);
color: var(--text-primary);
font-size: 13px;
cursor: pointer;
transition: all var(--transition);
text-decoration: none;
white-space: nowrap;
min-width: 36px;
height: 34px;
}
.btn:hover {
background: var(--bg-hover);
border-color: var(--text-muted);
}
.btn:active {
transform: scale(0.97);
}
.btn:disabled {
opacity: 0.4;
cursor: not-allowed;
transform: none;
}
.btn-nav {
padding: 6px 10px;
}
.btn-accent {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
.btn-accent:hover {
background: var(--accent-hover);
border-color: var(--accent-hover);
}
/* ── Breadcrumb ───────────────────────────────────────────────── */
.breadcrumb {
display: flex;
align-items: center;
gap: 4px;
overflow-x: auto;
flex: 1;
min-width: 0;
padding: 0 8px;
scrollbar-width: none;
}
.breadcrumb::-webkit-scrollbar { display: none; }
.breadcrumb-item {
color: var(--text-secondary);
text-decoration: none;
padding: 4px 8px;
border-radius: var(--radius-sm);
font-size: 13px;
white-space: nowrap;
transition: all var(--transition);
}
.breadcrumb-item:hover {
color: var(--text-primary);
background: var(--bg-tertiary);
}
.breadcrumb-separator {
color: var(--text-muted);
font-size: 11px;
user-select: none;
}
.breadcrumb-item.active {
color: var(--text-primary);
font-weight: 600;
}
/* ── Filter ───────────────────────────────────────────────────── */
.filter-input {
width: 220px;
padding: 6px 12px;
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
background: var(--bg-primary);
color: var(--text-primary);
font-size: 13px;
transition: all var(--transition);
}
.filter-input:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(88, 166, 255, 0.15);
}
.filter-input::placeholder {
color: var(--text-muted);
}
/* ── Sort Indicator ───────────────────────────────────────────── */
.sort-indicator {
font-size: 10px;
margin-left: 2px;
opacity: 0.6;
}
.sort-indicator.active {
opacity: 1;
color: var(--accent);
}
/* ── File List Container ──────────────────────────────────────── */
.file-container {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
padding: 8px 0;
}
/* ── Table ────────────────────────────────────────────────────── */
.file-table {
width: 100%;
border-collapse: collapse;
}
.file-table thead {
position: sticky;
top: 0;
z-index: 10;
}
.file-table th {
padding: 10px 16px;
text-align: left;
font-weight: 600;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-secondary);
background: var(--bg-secondary);
border-bottom: 2px solid var(--border-color);
cursor: pointer;
user-select: none;
transition: color var(--transition);
white-space: nowrap;
}
.file-table th:hover {
color: var(--text-primary);
}
.file-table th.sorted {
color: var(--accent);
}
.file-table th .sort-arrow {
display: inline-block;
margin-left: 4px;
font-size: 10px;
}
.file-table td {
padding: 8px 16px;
border-bottom: 1px solid var(--border-color);
vertical-align: middle;
}
.file-table tbody tr {
transition: background var(--transition);
cursor: pointer;
}
.file-table tbody tr:hover {
background: var(--bg-hover);
}
.file-table tbody tr.selected {
background: rgba(88, 166, 255, 0.1);
border-left: 3px solid var(--accent);
}
/* ── File Icon ────────────────────────────────────────────────── */
.file-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
margin-right: 10px;
flex-shrink: 0;
}
.file-icon svg {
width: 20px;
height: 20px;
}
.icon-dir { color: var(--accent); }
.icon-image { color: #f778ba; }
.icon-audio { color: #79c0ff; }
.icon-video { color: #ffa657; }
.icon-file { color: var(--text-secondary); }
/* ── File Name Cell ───────────────────────────────────────────── */
.file-name-cell {
display: flex;
align-items: center;
}
.file-name {
font-weight: 500;
word-break: break-all;
}
.file-name.dir {
color: var(--accent);
font-weight: 600;
}
/* ── Meta Cells ───────────────────────────────────────────────── */
.file-date,
.file-size {
color: var(--text-secondary);
font-size: 13px;
white-space: nowrap;
}
/* ── Empty State ──────────────────────────────────────────────── */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 60px 20px;
color: var(--text-muted);
text-align: center;
}
.empty-state svg {
width: 64px;
height: 64px;
margin-bottom: 16px;
opacity: 0.3;
}
.empty-state p {
font-size: 15px;
}
/* ── Overlay ──────────────────────────────────────────────────── */
.overlay {
display: none;
position: fixed;
inset: 0;
z-index: 1000;
background: rgba(0, 0, 0, 0.85);
backdrop-filter: blur(8px);
align-items: center;
justify-content: center;
padding: 24px;
animation: fadeIn 0.15s ease;
}
.overlay.active {
display: flex;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideUp {
from { opacity: 0; transform: translateY(20px) scale(0.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.overlay-content {
position: relative;
max-width: 90vw;
max-height: 90vh;
display: flex;
align-items: center;
justify-content: center;
animation: slideUp 0.2s ease;
}
.overlay-content img {
max-width: 100%;
max-height: 85vh;
border-radius: var(--radius);
box-shadow: var(--shadow-lg);
object-fit: contain;
}
.overlay-content audio,
.overlay-content video {
max-width: 90vw;
max-height: 85vh;
border-radius: var(--radius);
box-shadow: var(--shadow-lg);
outline: none;
}
.overlay-content audio {
width: 500px;
max-width: 90vw;
}
.overlay-close {
position: absolute;
top: -40px;
right: -8px;
width: 36px;
height: 36px;
border: none;
border-radius: 50%;
background: var(--bg-tertiary);
color: var(--text-primary);
font-size: 18px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all var(--transition);
border: 1px solid var(--border-color);
}
.overlay-close:hover {
background: var(--danger);
border-color: var(--danger);
}
/* ── Loading State ────────────────────────────────────────────── */
.loading {
display: none;
text-align: center;
padding: 40px;
color: var(--text-muted);
}
.loading.visible {
display: block;
}
.spinner {
width: 32px;
height: 32px;
border: 3px solid var(--border-color);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.8s linear infinite;
margin: 0 auto 12px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* ── Responsive ───────────────────────────────────────────────── */
@media (max-width: 768px) {
.toolbar {
padding: 8px 12px;
gap: 6px;
}
.filter-input {
width: 100%;
order: 10;
}
.toolbar-group.nav-group {
order: 1;
}
.toolbar-group.filter-group {
width: 100%;
order: 10;
}
.toolbar-group.filter-group .filter-input {
width: 100%;
}
.file-table th:nth-child(3),
.file-table td:nth-child(3) {
display: none;
}
.breadcrumb {
font-size: 12px;
}
.breadcrumb-item {
padding: 3px 6px;
font-size: 12px;
}
.file-table th,
.file-table td {
padding: 8px 10px;
}
.overlay {
padding: 12px;
}
.overlay-close {
top: -36px;
right: 0;
width: 32px;
height: 32px;
}
}
@media (max-width: 480px) {
.file-table th:nth-child(2),
.file-table td:nth-child(2) {
display: none;
}
}
/* ── Scrollbar ────────────────────────────────────────────────── */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg-primary);
}
::-webkit-scrollbar-thumb {
background: var(--bg-tertiary);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--bg-hover);
}
/* ── Selection highlight (filter match) ───────────────────────── */
mark {
background: rgba(88, 166, 255, 0.25);
color: var(--text-primary);
border-radius: 2px;
padding: 0 1px;
}
/* ── File count badge ─────────────────────────────────────────── */
.file-count {
font-size: 12px;
color: var(--text-muted);
padding: 6px 16px;
border-bottom: 1px solid var(--border-color);
background: var(--bg-secondary);
}
</style>
</head>
<body>
<!-- ── Toolbar ──────────────────────────────────────────────────── -->
<div class="toolbar">
<div class="toolbar-group nav-group">
<button class="btn btn-nav" id="btn-back" title="Zurück" disabled>
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
<path d="M7.78 12.53a.75.75 0 0 1-1.06 0L2.47 8.28a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 1.06L4.81 7h8.44a.75.75 0 0 1 0 1.5H4.81l2.97 2.97a.75.75 0 0 1 0 1.06z"/>
</svg>
</button>
<button class="btn btn-nav" id="btn-forward" title="Vorwärts" disabled>
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
<path d="M8.22 3.47a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06-1.06l2.97-2.97H3.75a.75.75 0 0 1 0-1.5h7.44L8.22 4.53a.75.75 0 0 1 0-1.06z"/>
</svg>
</button>
</div>
<nav class="breadcrumb" id="breadcrumb"></nav>
<div class="toolbar-group filter-group">
<input type="text" class="filter-input" id="filter-input" placeholder="🔍 Filter…" autocomplete="off">
</div>
<div class="toolbar-group">
<select class="filter-input" id="sort-select" style="width:160px;">
<option value="name:asc">Name ↑</option>
<option value="name:desc">Name ↓</option>
<option value="date:asc">Datum ↑</option>
<option value="date:desc">Datum ↓</option>
<option value="size:asc">Größe ↑</option>
<option value="size:desc">Größe ↓</option>
</select>
</div>
</div>
<!-- ── File List ────────────────────────────────────────────────── -->
<div class="loading" id="loading">
<div class="spinner"></div>
<p>Lade Dateien…</p>
</div>
<div class="file-container" id="file-container" style="display:none;">
<div class="file-count" id="file-count"></div>
<table class="file-table" id="file-table">
<thead>
<tr>
<th data-sort="name" class="sorted">
Dateiname <span class="sort-arrow" id="arrow-name">▲</span>
</th>
<th data-sort="date">
Änderungsdatum <span class="sort-arrow" id="arrow-date">▲</span>
</th>
<th data-sort="size">
Größe <span class="sort-arrow" id="arrow-size">▲</span>
</th>
</tr>
</thead>
<tbody id="file-tbody"></tbody>
</table>
</div>
<div class="empty-state" id="empty-state" style="display:none;">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M19.5 6l-7.5-4.5L4.5 6H3a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h18a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1h-1.5zm-1.5 1H5V7h13v0zm0 2H5v1h13v-1zM5 13h13v1H5v-1zm0 3h13v1H5v-1z"/>
</svg>
<p id="empty-message">Keine Dateien in diesem Verzeichnis</p>
</div>
<!-- ── Media Overlay ───────────────────────────────────────────── -->
<div class="overlay" id="overlay">
<div class="overlay-content" id="overlay-content">
<button class="overlay-close" id="overlay-close" title="Schließen">
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
<path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.75.75 0 1 1 1.06 1.06L9.06 8l3.22 3.22a.75.75 0 1 1-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 0 1-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06z"/>
</svg>
</button>
</div>
</div>
<script>
(() => {
'use strict';
// ── State ──────────────────────────────────────────────────────
let currentPath = window.location.search.includes('path=')
? decodeURIComponent(new URLSearchParams(window.location.search).get('path') || '')
: '';
let currentFiles = [];
let sortColumn = 'name';
let sortDir = 'asc';
let filterText = '';
let historyStack = [''];
let historyIndex = 0;
// ── DOM Elements ───────────────────────────────────────────────
const $ = (sel) => document.querySelector(sel);
const btnBack = $('#btn-back');
const btnForward = $('#btn-forward');
const breadcrumb = $('#breadcrumb');
const filterInput = $('#filter-input');
const sortSelect = $('#sort-select');
const loading = $('#loading');
const fileContainer = $('#file-container');
const fileTable = $('#file-tbody');
const fileCount = $('#file-count');
const emptyState = $('#empty-state');
const emptyMessage = $('#empty-message');
const overlay = $('#overlay');
const overlayContent = $('#overlay-content');
const overlayClose = $('#overlay-close');
// ── SVG Icons ──────────────────────────────────────────────────
const icons = {
dir: `<svg viewBox="0 0 24 24" fill="currentColor"><path d="M10 4H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2z"/></svg>`,
image: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="M21 15l-5-5L5 21"/></svg>`,
audio: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>`,
video: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="4" width="15" height="16" rx="2"/><path d="M17 8l5-3v14l-5-3"/></svg>`,
file: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`,
};
function getFileIcon(file) {
if (file.type === 'dir') return icons.dir;
const ext = file.name.split('.').pop().toLowerCase();
const imgExts = ['jpg','jpeg','png','gif','webp','svg','bmp','ico','tiff','avif'];
const audioExts = ['mp3','ogg','wav','flac','aac','wma','opus','m4a'];
const videoExts = ['mp4','webm','ogg','mov','avi','mkv','m4v'];
if (imgExts.includes(ext)) return icons.image;
if (audioExts.includes(ext)) return icons.audio;
if (videoExts.includes(ext)) return icons.video;
return icons.file;
}
// ── Navigation ─────────────────────────────────────────────────
function navigateTo(path) {
currentPath = path;
// Update history
historyStack = historyStack.slice(0, historyIndex + 1);
historyStack.push(path);
historyIndex = historyStack.length - 1;
updateURL();
loadDirectory();
updateNavButtons();
}
function goBack() {
if (historyIndex > 0) {
historyIndex--;
currentPath = historyStack[historyIndex];
updateURL();
loadDirectory();
updateNavButtons();
}
}
function goForward() {
if (historyIndex < historyStack.length - 1) {
historyIndex++;
currentPath = historyStack[historyIndex];
updateURL();
loadDirectory();
updateNavButtons();
}
}
function updateURL() {
const params = new URLSearchParams();
if (currentPath) params.set('path', currentPath);
const url = 'index.php' + (params.toString() ? '?' + params.toString() : '');
history.pushState({ path: currentPath }, '', url);
}
function updateNavButtons() {
btnBack.disabled = historyIndex <= 0;
btnForward.disabled = historyIndex >= historyStack.length - 1;
}
// ── Breadcrumb ─────────────────────────────────────────────────
function renderBreadcrumb(path) {
// Build breadcrumbs from path segments
let crumbs = [{ label: '/', path: '' }];
if (path) {
const segments = path.split('/').filter(Boolean);
let accumulated = '';
for (const seg of segments) {
accumulated += (accumulated ? '/' : '') + seg;
crumbs.push({ label: seg, path: accumulated });
}
}
breadcrumb.innerHTML = crumbs.map((crumb, i) => {
const isActive = i === crumbs.length - 1;
return `<a href="#" class="breadcrumb-item${isActive ? ' active' : ''}" data-path="${crumb.path}">${crumb.label}</a>${i < crumbs.length - 1 ? '<span class="breadcrumb-separator">›</span>' : ''}`;
}).join('');
}
// ── Data Loading ───────────────────────────────────────────────
async function loadDirectory() {
loading.classList.add('visible');
fileContainer.style.display = 'none';
emptyState.style.display = 'none';
try {
const url = `index.php?action=list${currentPath ? '&path=' + encodeURIComponent(currentPath) : ''}`;
const resp = await fetch(url);
if (!resp.ok) throw new Error('Network error');
const files = await resp.json();
currentFiles = files;
renderBreadcrumb(currentPath);
renderTable();
} catch (err) {
console.error('Failed to load directory:', err);
emptyMessage.textContent = 'Fehler beim Laden des Verzeichnisses';
emptyState.style.display = 'flex';
} finally {
loading.classList.remove('visible');
}
}
// ── Table Rendering ────────────────────────────────────────────
function getSortedAndFiltered() {
let items = [...currentFiles];
// Filter
if (filterText) {
const query = filterText.toLowerCase();
items = items.filter(f => f.name.toLowerCase().includes(query));
}
// Sort: dirs first, then by column
items.sort((a, b) => {
// Directories always first
if (a.type !== b.type) return a.type === 'dir' ? -1 : 1;
let cmp = 0;
if (sortColumn === 'name') {
cmp = a.name.localeCompare(b.name, 'de');
} else if (sortColumn === 'date') {
cmp = a.modified.localeCompare(b.modified);
} else if (sortColumn === 'size') {
cmp = (a.size || 0) - (b.size || 0);
}
return sortDir === 'desc' ? -cmp : cmp;
});
return items;
}
function renderTable() {
const items = getSortedAndFiltered();
fileTable.innerHTML = '';
fileCount.textContent = `${items.length} Eintrag${items.length !== 1 ? 'e' : ''}`;
if (items.length === 0) {
emptyState.style.display = 'flex';
emptyMessage.textContent = currentFiles.length === 0
? 'Dieses Verzeichnis ist leer'
: 'Keine Dateien entsprechen dem Filter';
fileContainer.style.display = 'none';
return;
}
emptyState.style.display = 'none';
fileContainer.style.display = 'block';
items.forEach(file => {
const tr = document.createElement('tr');
tr.dataset.path = file.path || '';
tr.dataset.type = file.type;
// Cell: Name
const tdName = document.createElement('td');
const nameCell = document.createElement('div');
nameCell.className = 'file-name-cell';
const iconSpan = document.createElement('span');
iconSpan.className = `file-icon icon-${file.type === 'dir' ? 'dir' : getFileTypeClass(file.name)}`;
iconSpan.innerHTML = getFileIcon(file);
const nameSpan = document.createElement('span');
nameSpan.className = 'file-name' + (file.type === 'dir' ? ' dir' : '');
nameSpan.textContent = file.name;
nameCell.appendChild(iconSpan);
nameCell.appendChild(nameSpan);
tdName.appendChild(nameCell);
// Cell: Date
const tdDate = document.createElement('td');
tdDate.className = 'file-date';
tdDate.textContent = file.modified || '—';
// Cell: Size
const tdSize = document.createElement('td');
tdSize.className = 'file-size';
tdSize.textContent = file.type === 'dir' ? '—' : formatSize(file.size);
tr.appendChild(tdName);
tr.appendChild(tdDate);
tr.appendChild(tdSize);
// Click handler
tr.addEventListener('click', () => handleFileClick(file));
fileTable.appendChild(tr);
});
updateSortIndicators();
}
function getFileTypeClass(filename) {
const ext = filename.split('.').pop().toLowerCase();
const imgExts = ['jpg','jpeg','png','gif','webp','svg','bmp','ico','tiff','avif'];
const audioExts = ['mp3','ogg','wav','flac','aac','wma','opus','m4a'];
const videoExts = ['mp4','webm','ogg','mov','avi','mkv','m4v'];
if (imgExts.includes(ext)) return 'image';
if (audioExts.includes(ext)) return 'audio';
if (videoExts.includes(ext)) return 'video';
return 'file';
}
function formatSize(bytes) {
if (bytes === 0 || bytes == null) return '—';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
let val = bytes;
while (val >= 1024 && i < units.length - 1) {
val /= 1024;
i++;
}
return (val < 10 ? val.toFixed(1) : Math.round(val)) + ' ' + units[i];
}
function updateSortIndicators() {
document.querySelectorAll('.file-table th').forEach(th => {
const col = th.dataset.sort;
const arrow = th.querySelector('.sort-arrow');
if (col === sortColumn) {
th.classList.add('sorted');
arrow.textContent = sortDir === 'asc' ? '▲' : '▼';
} else {
th.classList.remove('sorted');
arrow.textContent = '▲';
}
});
}
// ── File Click Handler ─────────────────────────────────────────
function handleFileClick(file) {
if (file.type === 'dir') {
// Navigate into directory
navigateTo(currentPath ? currentPath + '/' + file.name : file.name);
return;
}
// It's a file — check if media
const ext = file.name.split('.').pop().toLowerCase();
const isImage = ['jpg','jpeg','png','gif','webp','svg','bmp','ico','tiff','avif'].includes(ext);
const isAudio = ['mp3','ogg','wav','flac','aac','wma','opus','m4a'].includes(ext);
const isVideo = ['mp4','webm','ogg','mov','avi','mkv','m4v'].includes(ext);
if (isImage) {
showMediaOverlay(file.name, 'image');
} else if (isAudio) {
showMediaOverlay(file.name, 'audio');
} else if (isVideo) {
showMediaOverlay(file.name, 'video');
} else {
// Download
triggerDownload(file.name);
}
}
// ── Media Overlay ──────────────────────────────────────────────
function showMediaOverlay(filename, type) {
const src = `index.php?action=stream&file=${encodeURIComponent(currentPath ? currentPath + '/' + filename : filename)}`;
// Remove existing content (except close button)
const existingMedia = overlayContent.querySelector('img, audio, video');
if (existingMedia) existingMedia.remove();
let media;
if (type === 'image') {
media = document.createElement('img');
media.src = src;
media.alt = filename;
media.loading = 'eager';
} else if (type === 'audio') {
media = document.createElement('audio');
media.src = src;
media.controls = true;
media.autoplay = true;
media.preload = 'auto';
} else if (type === 'video') {
media = document.createElement('video');
media.src = src;
media.controls = true;
media.autoplay = true;
media.preload = 'auto';
}
if (media) {
overlayContent.insertBefore(media, overlayClose);
overlay.classList.add('active');
document.body.style.overflow = 'hidden';
}
}
function closeOverlay() {
overlay.classList.remove('active');
document.body.style.overflow = '';
// Stop media playback
const media = overlayContent.querySelector('audio, video');
if (media) {
media.pause();
media.src = '';
}
// Remove media element
const img = overlayContent.querySelector('img');
if (img) img.remove();
}
// ── Download ───────────────────────────────────────────────────
function triggerDownload(filename) {
const fileParam = currentPath ? currentPath + '/' + filename : filename;
const url = `index.php?action=download&file=${encodeURIComponent(fileParam)}`;
const a = document.createElement('a');
a.href = url;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
// ── Event Listeners ────────────────────────────────────────────
// Navigation buttons
btnBack.addEventListener('click', goBack);
btnForward.addEventListener('click', goForward);
// Browser back/forward
window.addEventListener('popstate', (e) => {
if (e.state && e.state.path !== undefined) {
currentPath = e.state.path;
historyStack = [e.state.path];
historyIndex = 0;
renderBreadcrumb(currentPath);
loadDirectory();
updateNavButtons();
}
});
// Breadcrumb clicks
breadcrumb.addEventListener('click', (e) => {
const link = e.target.closest('.breadcrumb-item');
if (link && !link.classList.contains('active')) {
e.preventDefault();
const path = link.dataset.path;
navigateTo(path);
}
});
// Filter
let filterTimeout;
filterInput.addEventListener('input', () => {
clearTimeout(filterTimeout);
filterTimeout = setTimeout(() => {
filterText = filterInput.value.trim();
renderTable();
}, 150);
});
// Sort
sortSelect.addEventListener('change', () => {
const [col, dir] = sortSelect.value.split(':');
sortColumn = col;
sortDir = dir;
renderTable();
});
// Sort header clicks
document.querySelectorAll('.file-table th[data-sort]').forEach(th => {
th.addEventListener('click', () => {
const col = th.dataset.sort;
if (sortColumn === col) {
sortDir = sortDir === 'asc' ? 'desc' : 'asc';
} else {
sortColumn = col;
sortDir = 'asc';
}
sortSelect.value = `${sortColumn}:${sortDir}`;
renderTable();
});
});
// Overlay
overlayClose.addEventListener('click', closeOverlay);
overlay.addEventListener('click', (e) => {
if (e.target === overlay) closeOverlay();
});
// Escape to close overlay
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && overlay.classList.contains('active')) {
closeOverlay();
}
});
// ── Initial Load ───────────────────────────────────────────────
loadDirectory();
updateNavButtons();
})();
</script>
</body>
</html>