<?php
declare(strict_types=1);

/*
 * Minimal read-only file repository.
 * Put this file in the public "repo" directory.
 * Store repository files in this same directory (or its subdirectories).
 */

const REPO_TITLE = 'File Repository';
const SHOW_FILE_SIZE = true;
const SHOW_MODIFIED_TIME = true;

$base = realpath(__DIR__);
if ($base === false) {
    http_response_code(500);
    exit('Repository unavailable.');
}

function fail(int $status, string $message): never
{
    http_response_code($status);
    header('Content-Type: text/plain; charset=UTF-8');
    exit($message);
}

function cleanRelativePath(string $input): string
{
    if (str_contains($input, "\0") || str_contains($input, '\\')) {
        fail(400, 'Invalid path.');
    }

    $parts = explode('/', $input);
    $clean = [];

    foreach ($parts as $part) {
        if ($part === '' || $part === '.') {
            continue;
        }
        if ($part === '..' || str_starts_with($part, '.')) {
            fail(404, 'Not found.');
        }
        if (preg_match('/[\x00-\x1F\x7F]/', $part)) {
            fail(400, 'Invalid path.');
        }
        $clean[] = $part;
    }

    return implode(DIRECTORY_SEPARATOR, $clean);
}

function resolveInside(string $base, string $relative): string
{
    $candidate = $base . ($relative !== '' ? DIRECTORY_SEPARATOR . $relative : '');
    $resolved = realpath($candidate);

    if ($resolved === false) {
        fail(404, 'Not found.');
    }

    $prefix = rtrim($base, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
    if ($resolved !== $base && !str_starts_with($resolved, $prefix)) {
        fail(404, 'Not found.');
    }

    // Do not follow symlinks anywhere in the requested path.
    $cursor = $base;
    if ($relative !== '') {
        foreach (explode(DIRECTORY_SEPARATOR, $relative) as $part) {
            $cursor .= DIRECTORY_SEPARATOR . $part;
            if (is_link($cursor)) {
                fail(404, 'Not found.');
            }
        }
    }

    return $resolved;
}

function h(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function encodedRelative(string $relative): string
{
    if ($relative === '') {
        return '';
    }
    return implode('/', array_map('rawurlencode', explode(DIRECTORY_SEPARATOR, $relative)));
}

function formatSize(int $bytes): string
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $size = (float)$bytes;
    $unit = 0;
    while ($size >= 1024 && $unit < count($units) - 1) {
        $size /= 1024;
        $unit++;
    }
    return number_format($size, $unit === 0 ? 0 : 1) . ' ' . $units[$unit];
}

$relative = cleanRelativePath((string)($_GET['path'] ?? ''));
$target = resolveInside($base, $relative);

/* Files are delivered by PHP as attachments, never executed as PHP scripts. */
if (isset($_GET['download'])) {
    $downloadRelative = cleanRelativePath((string)$_GET['download']);
    $file = resolveInside($base, $downloadRelative);

    if (!is_file($file) || !is_readable($file)) {
        fail(404, 'Not found.');
    }

    $name = basename($file);
    if ($name === '' || str_starts_with($name, '.')) {
        fail(404, 'Not found.');
    }

    header('X-Content-Type-Options: nosniff');
    header('Content-Type: application/octet-stream');
    header('Content-Length: ' . (string)filesize($file));
    header("Content-Disposition: attachment; filename=\"download\"; filename*=UTF-8''" . rawurlencode($name));
    header('Cache-Control: private, no-store');
    readfile($file);
    exit;
}

if (!is_dir($target) || !is_readable($target)) {
    fail(404, 'Not found.');
}

$items = [];
$scan = scandir($target);
if ($scan === false) {
    fail(500, 'Unable to read repository.');
}

foreach ($scan as $name) {
	if ($name === 'index.php') {
		continue;
	}
    if ($name === '.' || $name === '..' || str_starts_with($name, '.')) {
        continue;
    }

    // Avoid symlinks and special files.
    $full = $target . DIRECTORY_SEPARATOR . $name;
    if (is_link($full) || (!is_dir($full) && !is_file($full))) {
        continue;
    }

    $items[] = [
        'name' => $name,
        'dir' => is_dir($full),
        'size' => is_file($full) ? (int)filesize($full) : 0,
        'mtime' => (int)filemtime($full),
        'relative' => $relative === '' ? $name : $relative . DIRECTORY_SEPARATOR . $name,
    ];
}

usort($items, static function (array $a, array $b): int {
    if ($a['dir'] !== $b['dir']) {
        return $a['dir'] ? -1 : 1;
    }
    return strnatcasecmp($a['name'], $b['name']);
});

$currentUrl = encodedRelative($relative);
$parent = '';
if ($relative !== '') {
    $parent = dirname($relative);
    if ($parent === '.') {
        $parent = '';
    }
}
?>
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title><?= h(REPO_TITLE) ?></title>
<style>
:root{color-scheme:dark;--bg:#0b1020;--panel:#111a2e;--line:#26334d;--text:#e8eefc;--muted:#9aa9c4;--accent:#83b7ff}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:15px system-ui,-apple-system,Segoe UI,sans-serif}
main{max-width:900px;margin:7vh auto;padding:0 18px}.head{margin-bottom:22px}.head h1{font-size:24px;margin:0 0 7px}.crumb{color:var(--muted);overflow-wrap:anywhere}
.panel{background:var(--panel);border:1px solid var(--line);border-radius:14px;overflow:hidden}
.row{display:grid;grid-template-columns:minmax(0,1fr) 110px 170px;gap:14px;align-items:center;padding:13px 17px;border-bottom:1px solid var(--line)}
.row:last-child{border-bottom:0}.name{min-width:0;overflow-wrap:anywhere}.name a{color:var(--text);text-decoration:none}.name a:hover{color:var(--accent)}
.meta{color:var(--muted);font-size:13px;text-align:right}.icon{display:inline-block;width:25px;color:var(--accent)}
.parent{color:var(--muted)!important}.empty{padding:24px;color:var(--muted);text-align:center}
@media(max-width:600px){.row{grid-template-columns:minmax(0,1fr) auto}.meta:last-child{display:none}.meta{text-align:right}}
</style>
</head>
<body>
<main>
  <header class="head">
    <h1><?= h(REPO_TITLE) ?></h1>
    <div class="crumb">/<?= h($relative) ?><?= $relative !== '' ? '/' : '' ?></div>
  </header>
  <section class="panel" aria-label="Repository files">
    <?php if ($relative !== ''): ?>
      <div class="row">
        <div class="name"><span class="icon">↩</span><a class="parent" href="?path=<?= rawurlencode($parent) ?>">..</a></div>
        <div class="meta">Папка</div><div class="meta"></div>
      </div>
    <?php endif; ?>

    <?php if ($items === []): ?>
      <div class="empty">Эта папка пуста.</div>
    <?php else: ?>
      <?php foreach ($items as $item): ?>
        <?php
          $encoded = encodedRelative($item['relative']);
          $href = $item['dir']
              ? '?path=' . rawurlencode($item['relative'])
              : '?download=' . rawurlencode($item['relative']);
        ?>
        <div class="row">
          <div class="name">
            <span class="icon"><?= $item['dir'] ? '📁' : '📄' ?></span>
            <a href="<?= h($href) ?>"><?= h($item['name']) ?></a>
          </div>
          <div class="meta"><?= $item['dir'] ? 'Папка' : (SHOW_FILE_SIZE ? h(formatSize($item['size'])) : 'Файл') ?></div>
          <div class="meta"><?= SHOW_MODIFIED_TIME ? h(date('Y-m-d H:i', $item['mtime'])) : '' ?></div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </section>
</main>
</body>
</html>
