<?php
/**
 * 日期：2026-11-09
 * 名称：File share
 * 版本：v0.4-test5
 * 项目简介：文字、视频、图片、文件临时共享
 * 项目地址：https://cp.6dsa.com
 * 搭建环境：宝塔面板 + PHP 8.0
 * 源码／备份地址：https://github.com/lieying8/codex/tree/main/file-share
 * 本次更新：保留发布区新标题；并发发布全部结束后再刷新，避免中断文件上传。
 * 核心功能不依赖 JavaScript，复制、粘贴按钮为可选增强；数据存于网站目录之外。
 */
declare(strict_types=1);
ini_set('display_errors', '0');
umask(0077);

$config = [
    'storage_dir' => '', // 空值沿用原版的站外 PHP 临时目录。可填站外可写绝对路径。
    'ttl' => 24 * 3600,
    'max_file' => 100 * 1024 * 1024,
    'max_text' => 10 * 1024 * 1024,
    'max_total' => 1024 * 1024 * 1024,
    'max_items' => 200,
    'min_free' => 64 * 1024 * 1024,
];

final class RelayError extends RuntimeException
{
    public int $status;
    public function __construct(string $message, int $status = 400)
    {
        parent::__construct($message);
        $this->status = $status;
    }
}

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

function iniBytes(string $value): int
{
    $value = trim($value);
    if ($value === '' || $value === '0' || $value === '-1') return PHP_INT_MAX;
    $number = (float)$value;
    switch (strtolower(substr($value, -1))) {
        case 'g': $number *= 1024;
        case 'm': $number *= 1024;
        case 'k': $number *= 1024;
    }
    return (int)min($number, PHP_INT_MAX);
}

function isInside(string $path, string $root): bool
{
    $root = rtrim($root, DIRECTORY_SEPARATOR);
    return $path === $root || str_starts_with($path, $root . DIRECTORY_SEPARATOR);
}

function storageDir(array $config): string
{
    // 与旧版使用同一算法：在原路径覆盖 index.php 可以继续使用原来的数据。
    $path = $config['storage_dir'] ?: rtrim(sys_get_temp_dir(), '/\\') . '/php-relay-' . substr(hash('sha256', __FILE__), 0, 20);
    if (!is_dir($path) && !is_link($path)) @mkdir($path, 0700, true);
    // 首次并发访问时，另一请求可能刚刚创建了目录；以最终状态判断。
    if (is_link($path) || !is_dir($path)) {
        throw new RelayError('无法创建私有临时目录。请检查 PHP 临时目录权限，或将 storage_dir 设置为网站目录外、PHP 允许访问的可写绝对路径。', 503);
    }
    $real = realpath($path);
    $webRoot = !empty($_SERVER['DOCUMENT_ROOT']) ? realpath($_SERVER['DOCUMENT_ROOT']) : false;
    if ($real === false || isInside($real, __DIR__) || ($webRoot !== false && isInside($real, $webRoot))) {
        throw new RelayError('存储目录必须放在网站根目录之外，请修改 storage_dir；不要关闭服务器目录限制。', 503);
    }
    @chmod($real, 0700);
    if (!is_writable($real)) throw new RelayError('私有临时目录不可写，请检查目录权限和 PHP 目录限制。', 503);
    return $real;
}

function validId(mixed $id): bool
{
    return is_string($id) && preg_match('/\A[a-f0-9]{32}\z/D', $id) === 1;
}

function saveIndex(string $dir, array $db): void
{
    $temp = $dir . '/index-' . bin2hex(random_bytes(8)) . '.tmp';
    try {
        $json = json_encode($db, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR);
        if (@file_put_contents($temp, $json) !== strlen($json) || !@rename($temp, $dir . '/index.json')) {
            throw new RelayError('保存失败，请检查磁盘空间和目录权限。', 507);
        }
    } finally {
        if (is_file($temp)) @unlink($temp);
    }
}

function locked(string $dir, callable $operation): mixed
{
    $lock = @fopen($dir . '/store.lock', 'c');
    if ($lock === false) throw new RelayError('存储暂时不可用，请稍后重试。', 503);
    if (!flock($lock, LOCK_EX)) {
        fclose($lock);
        throw new RelayError('存储暂时不可用，请稍后重试。', 503);
    }
    try {
        $db = ['items' => [], 'rates' => []];
        if (is_file($dir . '/index.json')) {
            $raw = file_get_contents($dir . '/index.json');
            $db = json_decode($raw === false ? '' : $raw, true, 512, JSON_THROW_ON_ERROR);
            unset($raw);
            if (!is_array($db) || !isset($db['items'], $db['rates']) || !is_array($db['items']) || !is_array($db['rates'])) {
                throw new RelayError('存储索引损坏，请由网站维护者检查。', 503);
            }
        }
        $now = time();
        $changed = false;
        foreach ($db['items'] as $id => $item) {
            if (!validId($id) || !is_array($item) || !isset($item['kind'], $item['expires_at'])) {
                throw new RelayError('存储索引格式不正确。', 503);
            }
            if ($item['expires_at'] <= $now) {
                $suffix = $item['kind'] === 'file' ? '.bin' : (!empty($item['text_file']) ? '.txt' : '');
                $file = $suffix !== '' ? $dir . '/' . $id . $suffix : '';
                if ($file !== '' && is_file($file) && !@unlink($file)) continue;
                unset($db['items'][$id]);
                $changed = true;
            }
        }
        foreach ($db['rates'] as $key => $rate) {
            if ($rate['until'] <= $now) { unset($db['rates'][$key]); $changed = true; }
        }
        if (($db['last_sweep'] ?? 0) < $now - 300) {
            foreach (array_merge(glob($dir . '/*.bin') ?: [], glob($dir . '/*.txt') ?: []) as $path) {
                $suffix = substr($path, -4);
                $id = basename($path, $suffix);
                $item = $db['items'][$id] ?? null;
                $referenced = $item && (($suffix === '.bin' && $item['kind'] === 'file') ||
                    ($suffix === '.txt' && $item['kind'] === 'text' && !empty($item['text_file'])));
                if (validId($id) && !$referenced && filemtime($path) < $now - 3600) @unlink($path);
            }
            foreach (glob($dir . '/index-*.tmp') ?: [] as $path) {
                if (filemtime($path) < $now - 3600) @unlink($path);
            }
            $db['last_sweep'] = $now;
            $changed = true;
        }
        if ($changed) saveIndex($dir, $db);
        return $operation($db);
    } finally {
        flock($lock, LOCK_UN);
        fclose($lock);
    }
}

function publicItems(array $db): array
{
    $items = array_values(array_filter($db['items'], fn($item) => $item['expires_at'] > time()));
    usort($items, fn($a, $b) => $b['created_at'] <=> $a['created_at'] ?: strcmp($b['id'], $a['id']));
    return $items;
}

function usage(array $db): int
{
    return (int)array_sum(array_column($db['items'], 'size'));
}

function consumeRate(string $dir, array &$db): void
{
    // 不信任客户端提供的 X-Forwarded-For。限制不能替代服务器流量防护。
    $key = hash('sha256', ($_SERVER['REMOTE_ADDR'] ?? '') . ':' . gmdate('Y-m-d') . ':' . $dir);
    $rate = $db['rates'][$key] ?? ['count' => 0, 'until' => time() + 60];
    if ($rate['count'] >= 30 || (!isset($db['rates'][$key]) && count($db['rates']) >= 5000)) {
        header('Retry-After: 60');
        throw new RelayError('操作太频繁，请一分钟后再试。', 429);
    }
    $rate['count']++;
    $db['rates'][$key] = $rate;
    saveIndex($dir, $db);
}

function checkQuota(array $db, array $config, string $dir, int $size): void
{
    if (count($db['items']) >= $config['max_items'] || usage($db) + $size > $config['max_total']) {
        throw new RelayError('中转站已满，请删除一些内容后重试。', 507);
    }
    $free = @disk_free_space($dir);
    if ($free !== false && $free < $size + $config['min_free']) throw new RelayError('服务器磁盘空间不足。', 507);
}

// 不使用会话文件：一个站点密钥存在原索引里，每个浏览器只有一个随机 Cookie。
// 表单的签名 token 同时绑定 Cookie 和过期时间，不依赖 JavaScript / SameSite 支持。
function prepareCsrf(string $secret): string
{
    global $cookieName;
    $browser = $_COOKIE[$cookieName] ?? '';
    if (!is_string($browser) || preg_match('/\A[a-f0-9]{64}\z/D', $browser) !== 1) {
        $browser = bin2hex(random_bytes(32));
        setcookie($cookieName, $browser, [
            'expires' => 0, 'path' => scriptPath(),
            'secure' => !empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off',
            'httponly' => true, 'samesite' => 'Lax',
        ]);
    }
    $expires = (string)(time() + 24 * 3600);
    return $expires . '.' . hash_hmac('sha256', $browser . ':' . $expires, $secret);
}

function mutationGuard(string $secret): void
{
    global $cookieName;
    if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') throw new RelayError('此操作需要使用表单提交。', 405);
    $browser = $_COOKIE[$cookieName] ?? '';
    $token = $_POST['csrf'] ?? '';
    if (!is_string($browser) || preg_match('/\A[a-f0-9]{64}\z/D', $browser) !== 1 ||
        !is_string($token) || preg_match('/\A([0-9]{10,12})\.([a-f0-9]{64})\z/D', $token, $parts) !== 1 ||
        (int)$parts[1] <= time() || (int)$parts[1] > time() + 24 * 3600 + 60 ||
        !hash_equals(hash_hmac('sha256', $browser . ':' . $parts[1], $secret), $parts[2])) {
        throw new RelayError('表单校验失败或页面已过期。请允许本站 Cookie，刷新页面后重新提交。', 403);
    }
    // 旧浏览器可以不提供这些头；提供时再检查。
    $site = $_SERVER['HTTP_SEC_FETCH_SITE'] ?? '';
    if ($site !== '' && !in_array($site, ['same-origin', 'none'], true)) throw new RelayError('不接受跨站提交。', 403);
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        $origin = parse_url($_SERVER['HTTP_ORIGIN']);
        if (!is_array($origin) || !isset($origin['scheme'], $origin['host']) || !in_array($origin['scheme'], ['http', 'https'], true)) {
            throw new RelayError('请求来源不正确。', 403);
        }
        $host = $origin['host'] . (isset($origin['port']) ? ':' . $origin['port'] : '');
        if (strtolower($host) !== strtolower($_SERVER['HTTP_HOST'] ?? '')) throw new RelayError('不接受跨站提交。', 403);
    }
}

function isAvif(string $path): bool
{
    $head = @file_get_contents($path, false, null, 0, 4096);
    if (!is_string($head) || strlen($head) < 16 || substr($head, 4, 4) !== 'ftyp') return false;
    $box = unpack('Nsize', substr($head, 0, 4));
    $length = $box['size'];
    if ($length < 16 || $length > strlen($head) || $length % 4 !== 0) return false;
    $brands = substr($head, 8, 4) . substr($head, 16, $length - 16);
    for ($offset = 0; $offset < strlen($brands); $offset += 4) {
        if (in_array(substr($brands, $offset, 4), ['avif', 'avis'], true)) return true;
    }
    return false;
}

function safeMime(string $path): string
{
    if (isAvif($path)) return 'image/avif';
    if (!class_exists('finfo')) return '';
    $mime = (new finfo(FILEINFO_MIME_TYPE))->file($path);
    if ($mime === 'image/avif') return 'image/avif';
    if (in_array($mime, ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], true)) {
        $info = @getimagesize($path);
        return is_array($info) && ($info['mime'] ?? '') === $mime ? $mime : '';
    }
    return in_array($mime, ['video/mp4', 'video/webm'], true) ? $mime : '';
}

function sendContent(string $dir, string $id, bool $preview): void
{
    [$item, $handle] = locked($dir, function (array &$db) use ($dir, $id, $preview) {
        $item = $db['items'][$id] ?? null;
        if (!$item || $item['kind'] !== 'file' || $item['expires_at'] <= time()) throw new RelayError('文件不存在或已过期。', 404);
        if ($preview && $item['preview_mime'] === '') throw new RelayError('此格式不支持安全预览，请下载查看。', 415);
        $handle = @fopen($dir . '/' . $id . '.bin', 'rb');
        if ($handle === false) throw new RelayError('文件已不可用。', 404);
        return [$item, $handle];
    });
    // 打开后立刻释放全局文件锁，慢速下载不会锁住其他用户的发布操作。
    $size = (int)fstat($handle)['size'];
    $start = 0;
    $end = $size - 1;
    if (isset($_SERVER['HTTP_RANGE'])) {
        $range = $_SERVER['HTTP_RANGE'];
        if ($size === 0 || !preg_match('/\Abytes=(\d*)-(\d*)\z/D', $range, $match) || ($match[1] === '' && $match[2] === '')) {
            fclose($handle);
            header('Content-Range: bytes */' . $size);
            throw new RelayError('不支持此下载范围。', 416);
        }
        if ($match[1] === '') {
            if ((int)$match[2] === 0) { fclose($handle); header('Content-Range: bytes */' . $size); throw new RelayError('下载范围无效。', 416); }
            $start = max(0, $size - (int)$match[2]);
        } else {
            $start = (int)$match[1];
            if ($match[2] !== '') $end = min($end, (int)$match[2]);
        }
        if ($start > $end || $start >= $size) {
            fclose($handle);
            header('Content-Range: bytes */' . $size);
            throw new RelayError('下载范围超出文件大小。', 416);
        }
        http_response_code(206);
        header("Content-Range: bytes $start-$end/$size");
    }
    $fallback = substr((string)preg_replace('/[^A-Za-z0-9._-]/', '_', $item['name']), 0, 120);
    if (trim($fallback, '._-') === '') $fallback = 'download';
    header('Content-Type: ' . ($preview ? $item['preview_mime'] : 'application/octet-stream'));
    header('Content-Disposition: ' . ($preview ? 'inline' : 'attachment') . '; filename="' . $fallback . '"; filename*=UTF-8\'\'' . rawurlencode($item['name']));
    header("Content-Security-Policy: sandbox; default-src 'none'");
    header('Accept-Ranges: bytes');
    header('Content-Length: ' . max(0, $end - $start + 1));
    if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'HEAD') {
        @set_time_limit(0);
        fseek($handle, $start);
        $left = max(0, $end - $start + 1);
        while ($left > 0 && !feof($handle) && !connection_aborted()) {
            $chunk = fread($handle, min(65536, $left));
            if ($chunk === false || $chunk === '') break;
            echo $chunk;
            $left -= strlen($chunk);
        }
    }
    fclose($handle);
    exit;
}

function scriptPath(): string
{
    $path = $_SERVER['SCRIPT_NAME'] ?? '/index.php';
    return preg_match('/[\x00-\x20\x7f]/', $path) || substr($path, 0, 1) !== '/' || substr($path, 0, 2) === '//' ? '/index.php' : $path;
}

function url(array $params = []): string
{
    return scriptPath() . ($params ? '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986) : '');
}

function formatBytes(int $bytes): string
{
    if ($bytes < 1024) return $bytes . ' B';
    if ($bytes < 1024 * 1024) return round($bytes / 1024, 1) . ' KB';
    if ($bytes < 1024 * 1024 * 1024) return round($bytes / 1024 / 1024, 1) . ' MB';
    return round($bytes / 1024 / 1024 / 1024, 1) . ' GB';
}

function excerpt(string $text, int $limit = 100): string
{
    // 不需要 mbstring；只把文本分成 UTF-8 字符，避免截断汉字。
    preg_match('/\A.{0,' . $limit . '}/us', $text, $match);
    $short = $match[0] ?? '';
    return $short . (strlen($short) < strlen($text) ? '…' : '');
}

// 返回不截断 UTF-8 字符的前缀长度。输入来自已校验的 UTF-8 文字。
function utf8PrefixLength(string $text, int $limit): int
{
    $length = strlen($text);
    if ($limit >= $length) return $length;
    while ($limit > 0 && (ord($text[$limit]) & 0xc0) === 0x80) $limit--;
    return $limit > 0 ? $limit : min($length, 1);
}

function textIsLong(string $text): bool
{
    // UTF-8 每字符至多四字节；大文本无需扫描全部换行或构造匹配数组。
    return strlen($text) > 480 || excerpt($text, 120) !== $text || preg_match_all('/\r\n|\r|\n/', $text) >= 3;
}

function textPreview(string $text): string
{
    $offset = strspn($text, " \t\n\r\0\x0b");
    // 只保留约 1 KB 的有界前缀，避免对 10 MB 的密集换行文字执行全量 preg_split。
    $piece = substr($text, $offset, 1028);
    $prefix = substr($piece, 0, utf8PrefixLength($piece, 1024));
    $lines = preg_split('/\r\n|\r|\n/', $prefix, 4);
    $preview = rtrim(excerpt(implode("\n", array_slice($lines, 0, 3)), 120));
    if (($offset + strlen($prefix) < strlen($text) || count($lines) > 3) && !str_ends_with($preview, '…')) $preview .= '…';
    return $preview;
}

function echoEscapedText(string $text): void
{
    $length = strlen($text);
    for ($offset = 0; $offset < $length;) {
        $size = min(8192, $length - $offset);
        // 在下一字符开头截断，保留跨块的中文和 emoji。
        if ($offset + $size < $length) {
            while ($size > 0 && (ord($text[$offset + $size]) & 0xc0) === 0x80) $size--;
        }
        if ($size === 0) $size = min(8192, $length - $offset);
        echo h(substr($text, $offset, $size));
        $offset += $size;
    }
}

function echoItemText(array $item, string $dir): void
{
    if (isset($item['text']) && is_string($item['text'])) {
        echoEscapedText($item['text']);
        return;
    }
    $id = $item['id'] ?? null;
    if (!validId($id) || empty($item['text_file'])) throw new RelayError('文字内容不可用。', 404);
    // 在锁内重新检查到期和删除状态并打开，传输时不再占用全局锁。
    $handle = locked($dir, function (array &$db) use ($id, $dir) {
        $current = $db['items'][$id] ?? null;
        if (!$current || $current['kind'] !== 'text' || empty($current['text_file']) || $current['expires_at'] <= time()) {
            throw new RelayError('文字不存在或已过期。', 404);
        }
        $path = $dir . '/' . $id . '.txt';
        if (is_link($path)) throw new RelayError('文字内容不可用。', 404);
        $handle = @fopen($path, 'rb');
        if ($handle === false) throw new RelayError('文字内容不可用。', 404);
        return $handle;
    });
    try {
        $buffer = '';
        while (!feof($handle) && !connection_aborted()) {
            $chunk = fread($handle, 8192);
            if ($chunk === false) throw new RelayError('读取文字失败，请刷新重试。', 503);
            if ($chunk === '') break;
            $buffer .= $chunk;
            if (strlen($buffer) > 8192) {
                $size = utf8PrefixLength($buffer, 8192);
                echo h(substr($buffer, 0, $size));
                $buffer = substr($buffer, $size);
            }
        }
        if ($buffer !== '') echo h($buffer);
    } finally {
        fclose($handle);
    }
}

function saveTextFile(string $dir, string $id, string $text): string
{
    $path = $dir . '/' . $id . '.txt';
    $handle = @fopen($path, 'xb');
    if ($handle === false) throw new RelayError('无法保存文字，请检查磁盘空间和目录权限。', 507);
    $complete = false;
    try {
        $length = strlen($text);
        for ($offset = 0; $offset < $length;) {
            $written = @fwrite($handle, substr($text, $offset, 16384));
            if ($written === false || $written === 0) throw new RelayError('无法保存文字，请检查磁盘空间和目录权限。', 507);
            $offset += $written;
        }
        @chmod($path, 0600);
        $complete = true;
    } finally {
        fclose($handle);
        if (!$complete) @unlink($path);
    }
    return $path;
}

function csrfInput(): void
{
    global $csrfToken;
    echo '<input type="hidden" name="csrf" value="' . h($csrfToken) . '">';
}

function deleteReturnUrl(): string
{
    $params = ['notice' => 'deleted'];
    if (($_POST['return_view'] ?? '') === 'list') {
        $params['action'] = 'list';
        if (($_POST['return_refresh'] ?? '') === '1') $params['refresh'] = 1;
    }
    $page = $_POST['return_page'] ?? '1';
    if (is_string($page) && preg_match('/\A[1-9][0-9]{0,5}\z/D', $page)) $params['page'] = (int)$page;
    return url($params) . '#content-list';
}

function jsonReply(array $data, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR);
    exit;
}

function renderDeleteForm(string $id, int $page = 1, bool $confirmFile = false): void
{
    global $view, $autoRefresh;
    if ($confirmFile) echo '<details class="file-delete-control"><summary class="delete-button">删除</summary>';
    ?><form class="delete-form" method="post" action="<?= h(url(['action' => 'delete'])) ?>" data-delete-id="<?= h($id) ?>" data-confirm-file="<?= $confirmFile ? '1' : '0' ?>" accept-charset="UTF-8">
<?php csrfInput(); ?><input type="hidden" name="id" value="<?= h($id) ?>">
<input type="hidden" name="return_page" value="<?= $page ?>"><input type="hidden" name="return_view" value="<?= $view === 'list' ? 'list' : 'home' ?>"><input type="hidden" name="return_refresh" value="<?= $autoRefresh ? '1' : '0' ?>">
<button class="delete-button" type="submit"><?= $confirmFile ? '确认删除' : '删除' ?></button></form><?php
    if ($confirmFile) echo '</details>';
}

function refreshUrl(): string
{
    global $action, $id, $autoRefresh;
    $params = [];
    if (is_string($action) && in_array($action, ['view', 'delete', 'preview', 'list'], true)) $params['action'] = $action;
    if (validId($id)) $params['id'] = $id;
    if ($autoRefresh) $params['refresh'] = 1;
    $page = $_GET['page'] ?? '';
    if (is_string($page) && preg_match('/\A[1-9][0-9]{0,5}\z/D', $page)) $params['page'] = $page;
    $params['r'] = time() . '-' . bin2hex(random_bytes(4));
    return url($params);
}

function sendSiteQrCode(): void
{
    // 固定站点二维码，构建时生成并独立解码验证；PHP 无需扩展或第三方依赖。
    $png = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAQgAAAEICAAAAACGnTUjAAADWElEQVR4nO3dwWrcMBRA0Unp//9yu7mzMQjpeZy2lHN2aScTcxFY2LL89evF6/V6/fjbB/CvECJCRIgIESEiRISIEBEiQkSICBEhIkSEiBARIkJEiAgRISJEhIgQESJCRIgIESEiRH7uPvB184vf6y6+Lj9fv/f03586nhUjIkJEiAgRISJEhMh2HvF2uh7zep5fzRNWP6++7/o9d49nxYiIEBEiQkSICBEhcjyPeFudl3fXD07P+9PnR6bHs2JERIgIESEiRISIEBnPI6ZW5/PVdYrrvONPPZdqRESICBEhIkSEiBD59nnE2+q6wXXecHf9w6eMiAgRISJEhIgQESLjecRT9x2m9ztWnrpeYUREiAgRISJEhIgQOZ5HfHqdYPX8xunzGbv1mp8yIiJEhIgQESJCRIh8/an1B6frIZ9aNzllRESICBEhIkSEiBA53j9iev3gbfW85nVd5dVuvcTp/hOn90+MiAgRISJEhIgQESLj+xrT+xPT+w+7758e3ykjIkJEiAgRISJEhMjtfahO5xOn5/XpfYvT9RT2oRoSIkJEiAgRISJEtusjPj3/P33/Yfp3ThkRESJCRIgIESEiRB5/7nO3nuH6Paef3x3Pp/tpGhERIkJEiAgRISJEtvOI6f2Du8937s7z0/sU1kfcJESEiBARIkJEiHz8vs+n7k+cPu85fU7E+oghISJEhIgQESJCZLx/xOl6iel7P+/+3urvTxkRESJCRIgIESEiRMbrLJ/aV/Lp/Sl36zh3jIgIESEiRISIEBEit9dHnP7/U+/hOr2fcf28dZZDQkSICBEhIkSEyMfrI1Z21xtO3w+++72nGBERIkJEiAgRISJEbu9DtbJb9/Dp/lF3j2PHiIgQESJCRIgIESEy3j/iqfdoTc/zT7/f88qIiBARIkJEiAgRITKeR3zq9DnRu9cddutCV4yICBEhIkSEiBARIt8+j7i7b9T0/V+r+Yl1lkNCRIgIESEiRITI4/tin37+7j7Zp/thTo/TiIgQESJCRIgIESEyfm/41He/X3z1d3b/fmVERIgIESEiRISIEBnvZ/m/MiIiRISIEBEiQkSICBEhIkSEiBARIkJEiAgRISJEhIgQESJCRIgIESEiRISIEBEiQkSI/AaMv3sxcNjiQgAAAABJRU5ErkJggg==', true);
    header('Content-Type: image/png');
    header('Content-Length: ' . strlen($png));
    if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'HEAD') echo $png;
    exit;
}

function pageStart(string $title): void
{
    global $autoRefresh, $view;
    ?><!DOCTYPE html>
<html lang="zh-CN"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Pragma" content="no-cache">
<?php if ($autoRefresh): ?><meta http-equiv="refresh" content="60;url=<?= h(listPageUrl(currentListPage())) ?>"><?php endif; ?>
<title><?= h($title === 'File share' ? $title : $title . ' - File share') ?></title>
<style type="text/css">
body{margin:0;padding:8px;background:#f3f5f8;color:#2c3542;font-family:Arial,"PingFang SC","Microsoft YaHei",sans-serif;font-size:16px;line-height:1.7}
.page{max-width:760px;margin:6px auto;padding:12px 14px;background:#fff;border:1px solid #d8dfe9;border-radius:6px}
h1{margin:0 0 16px;padding-bottom:12px;border-bottom:2px solid #466b9d;font-size:28px;line-height:1.4}
h2{margin:20px 0 8px;font-size:20px;color:#344964}
.list-heading{overflow:hidden;margin:10px 0 6px}
.list-heading h2{display:inline-block;margin:0 8px 0 0}
.list-refresh{float:right;padding:4px 9px;border:1px solid #d5deeb;border-radius:3px;background:#f1f5fb;font-size:14px}
a{color:#315f99;text-decoration:none}
a:hover{color:#224575}
p{margin:6px 0}
.nav{margin:0 0 6px}
.nav a{display:inline-block;margin:0 6px 4px 0;padding:4px 10px;border:1px solid #d5deeb;border-radius:4px;background:#f1f5fb;font-size:15px}
.nav a:hover{background:#e5edf8}
.note{margin:12px 0 0;padding:11px 14px;border-left:3px solid #7e94b4;background:#f2f5fa;color:#526177;font-size:14px}
.error,.success{padding:12px 14px;border:1px solid;border-radius:4px}
.error{color:#8a3427;background:#fff3ee;border-color:#e5c2b7}
.success{color:#31547f;background:#eef4fc;border-color:#c8d8ed}
.submit-status,.upload-status{margin-left:8px;padding:0;border:0;background:transparent;color:#31547f;font-size:14px}
.upload-progress{display:none;margin:6px 0 2px}
.upload-progress.is-complete{display:block}
.upload-track{height:6px;background:#e5ebf4;border:1px solid #d5deeb}
.upload-fill{width:0;height:6px;background:#466b9d}
.upload-progress.is-complete .upload-fill{width:100%}
.upload-status{display:block;margin:3px 0 0}
.qr-entry{display:inline-block;vertical-align:top;margin-right:6px}
.nav a{vertical-align:top}
.qr-entry > summary{display:inline-block;list-style:none;cursor:pointer;padding:4px 10px;border:1px solid #d5deeb;border-radius:4px;background:#f1f5fb;color:#315f99;font-size:15px}
.qr-entry > summary::-webkit-details-marker,.publish-toggle > summary::-webkit-details-marker{display:none}
.qr-footer{text-align:center;margin:14px 0 4px}
.qr-footer img{display:inline-block;width:99px;height:99px;vertical-align:top}
.publish-toggle{margin:8px 0;border:1px solid #d5deeb;border-radius:4px;background:#fcfdff}
.publish-toggle > summary{display:block;padding:7px 8px;cursor:pointer;list-style:none;font-size:16px;color:#365c8e}
.toggle-open{display:none}
.publish-toggle[open] > summary .toggle-closed{display:none}
.publish-toggle[open] > summary .toggle-open{display:inline}
.publish-toggle fieldset{margin:4px 6px 8px}
fieldset{min-width:0;margin:10px 0;padding:6px 10px;border:1px solid #d5deeb;border-radius:4px;background:#fcfdff}
.upload-panel{padding:4px 10px}
.upload-panel p{margin:4px 0}
.upload-controls input[type=file]{width:62%;max-width:360px;margin-right:6px;vertical-align:middle}
.upload-controls input[type=submit]{vertical-align:middle}
legend{padding:0 6px;color:#365c8e;font-size:14px;font-weight:bold}
label{color:#414f63}
textarea{width:94%;padding:8px 2%;border:1px solid #bccadd;border-radius:4px;background:#fff;color:#2d3b50;font-family:Arial,"PingFang SC","Microsoft YaHei",sans-serif;font-size:16px;line-height:1.6}
#text{padding:4px 2%;line-height:1.5}
input,button{font-family:Arial,"PingFang SC","Microsoft YaHei",sans-serif;font-size:16px}
input[type=submit]{-webkit-appearance:none;padding:4px 12px;border:1px solid #2e5484;border-radius:4px;background:#3c6599;color:#fff;line-height:1.5;font-weight:bold;cursor:pointer}
input[type=submit]:hover{background:#2e5484}
.clipboard-action{display:none;margin:0 0 0 6px;padding:4px 12px;border:1px solid #bccadd;border-radius:4px;background:#f1f5fb;color:#315f99;line-height:1.5;cursor:pointer}
.clipboard-status{display:none;color:#435b7d;font-size:14px}
input[type=file]{max-width:100%;color:#414f63}
.table-wrap{overflow:auto;margin:8px 0 12px;border:1px solid #d8dfe9;border-radius:4px}
table{width:100%;border-collapse:collapse;font-size:15px}
th,td{padding:10px 8px;border-bottom:1px solid #e1e6ef;text-align:left;vertical-align:top}
th{background:#edf2f9;color:#435b7d;font-size:14px;font-weight:bold}
td{word-wrap:break-word;overflow-wrap:break-word}
tbody tr:nth-child(even){background:#f8fafd}
.name{width:50%;word-break:break-all}
details,summary{display:block}
.text-content,.text-preview{color:#2c3542;white-space:pre-wrap;word-wrap:break-word;overflow-wrap:break-word;word-break:normal}
.text-details summary{cursor:pointer;list-style:none}
.text-details summary::-webkit-details-marker{display:none}
.text-preview{display:block;margin-bottom:8px}
.text-more,.text-less{display:inline-block;padding:4px 9px;border:1px solid #d5deeb;border-radius:3px;background:#f1f5fb;color:#315f99;font-size:14px}
.text-less{display:none}
.text-details[open] .text-preview,.text-details[open] .text-more{display:none}
.text-details[open] .text-less{display:inline-block}
.inline-copy{display:block;margin:10px 0 0}
.short-copy{display:none}
.ops{width:28%}
.row-actions{display:table;width:100%}
.primary-actions{display:table-cell;vertical-align:top}
.primary-actions a,.primary-actions .clipboard-action{white-space:nowrap}
.delete-form{display:inline-block;margin:0}
.row-actions .delete-form{display:table-cell;vertical-align:top;text-align:right;padding-left:4px;white-space:nowrap}
.file-delete-control{display:inline-block;text-align:right}
.row-actions .file-delete-control{display:table-cell;vertical-align:top;padding-left:4px;white-space:nowrap}
.file-delete-control summary{list-style:none;cursor:pointer}
.file-delete-control summary::-webkit-details-marker{display:none}
.file-delete-control .delete-form{display:block;padding:4px 0 0;white-space:normal}
.file-delete-control button.delete-button{font-size:13px;padding:3px 4px}
.ops a,.ops .clipboard-action,.delete-button{display:inline-block;margin:0 4px 4px 0;padding:3px 6px;border:1px solid #d5deeb;border-radius:3px;background:#fff;font-size:14px;color:#315f99;line-height:1.7;vertical-align:top}
.ops .clipboard-action{display:none}
.ops a:hover{background:#edf3fc}
.delete-button{-webkit-appearance:none;margin-right:0;color:#8b4639;cursor:pointer}
.delete-button:disabled{cursor:default;opacity:.6}
.delete-result{display:block;color:#8b4639;font-size:13px}
.copy-result{display:block;color:#596779;font-size:13px}
.small{font-size:14px;color:#596779}
pre{padding:14px;border:1px solid #d5deeb;border-radius:4px;background:#f7f9fc;white-space:pre-wrap;word-wrap:break-word;overflow:auto}
img,video{max-width:100%;height:auto}
hr{margin:16px 0;border:0;border-top:1px solid #e1e6ef}
.pagination{margin:10px 0;font-size:14px;color:#596779}
.pagination a{display:inline-block;margin-right:10px;padding:4px 8px;border:1px solid #d5deeb;border-radius:3px;background:#f1f5fb}
/* 不支持媒体查询的浏览器仍使用上方普通块布局和表格。 */
@media screen and (max-width:600px){
    body{padding:4px}
    .page{margin:0;padding:10px 8px;border-radius:4px}
    h1{font-size:25px}
    .list-heading h2{font-size:18px}
    .nav a{margin-right:4px;padding:4px 8px;font-size:14px}
    fieldset{padding:4px 6px}
    th,td{padding:8px 6px}
    .ops a,.ops .clipboard-action,.delete-button{margin-right:0;padding:4px 6px}
}
</style></head><body><div class="page">
<?php if (!in_array($view, ['home', 'list'], true)): ?><h1><?= h($title) ?></h1><?php endif; ?>
<div class="nav"><a href="<?= h(url()) ?>">首页</a><?php if (!in_array($view, ['home', 'list'], true)): ?><a href="<?= h(refreshUrl()) ?>">手动刷新本页</a><?php endif; ?></div>
<?php
}

function pageEnd(): void
{
    global $config, $scriptNonce;
    ?><hr><p class="note">公开中转站：所有人都能查看、下载和删除。默认 <?= (int)ceil($config['ttl'] / 3600) ?> 小时后过期，请勿上传敏感资料。</p><div class="qr-footer"><img src="<?= h(url(['action' => 'qr-code'])) ?>" width="99" height="99" alt="网站二维码"></div></div>
<script nonce="<?= h($scriptNonce) ?>">
// 复制、粘贴及列表内删除的可选增强；所有核心操作都有无脚本路径。
(function () {
    function putText(node, text) {
        if ('textContent' in node) node.textContent = text;
        else node.innerText = text;
    }
    function say(text, button) {
        var status = document.getElementById('clipboard-status');
        if (status) { putText(status, text); status.style.display = 'block'; }
        if (button) {
            var result = document.getElementById('copy-result-' + button.getAttribute('data-copy-id'));
            if (result) putText(result, text);
        }
    }
    function selectField(field) {
        try { field.focus(); field.select(); if (field.setSelectionRange) field.setSelectionRange(0, field.value.length); } catch (ignore) {}
    }
    function manualCopy(field, button) {
        var parent = field.parentNode;
        while (parent && parent.nodeType === 1) {
            if (parent.tagName.toLowerCase() === 'details') parent.setAttribute('open', 'open');
            parent = parent.parentNode;
        }
        field.style.display = 'block';
        selectField(field);
        say('请选择文字后复制，或按 Ctrl+C / Command+C。', button);
    }
    function legacyCopy(text) {
        var field = document.createElement('textarea');
        var active = document.activeElement;
        var start = active && typeof active.selectionStart === 'number' ? active.selectionStart : null;
        var end = active && typeof active.selectionEnd === 'number' ? active.selectionEnd : null;
        var ok = false;
        field.value = text;
        field.readOnly = true;
        field.style.position = 'absolute';
        field.style.left = '-10000px';
        field.style.top = '0';
        field.style.fontSize = '16px';
        document.body.appendChild(field);
        selectField(field);
        try { ok = !!(document.execCommand && document.execCommand('copy')); } catch (ignore) {}
        document.body.removeChild(field);
        try {
            if (active && active.focus) active.focus();
            if (start !== null && active.setSelectionRange) active.setSelectionRange(start, end);
        } catch (ignore) {}
        return ok;
    }
    function copyText(button) {
        var field = document.getElementById('copy-' + button.getAttribute('data-copy-id'));
        if (!field) return;
        // 大文本不再克隆到离屏 textarea：旧式选取会触发巨量换行布局。
        // 支持时直接写入剪贴板，否则使用已存在的完整文本框手动选取。
        if (field.value.length <= 65536 && legacyCopy(field.value)) { say('已复制。', button); return; }
        if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
            try {
                var pending = navigator.clipboard.writeText(field.value);
                if (pending && typeof pending.then === 'function') {
                    pending.then(function () { say('已复制。', button); }, function () { manualCopy(field, button); });
                    return;
                }
            } catch (ignore) {}
        }
        manualCopy(field, button);
    }
    var paste = document.getElementById('paste-button');
    var input = document.getElementById('text');
    if (paste && input) {
        paste.onclick = function () {
            var before = input.value;
            var start = typeof input.selectionStart === 'number' ? input.selectionStart : before.length;
            var end = typeof input.selectionEnd === 'number' ? input.selectionEnd : before.length;
            function manualPaste() {
                input.focus();
                say('浏览器未允许读取剪贴板，请长按输入框或按 Ctrl+V / Command+V 粘贴。');
            }
            function insert(text) {
                if (typeof text !== 'string' || text === '') { input.focus(); say('剪贴板没有文字，请手动粘贴。'); return; }
                if (input.value !== before) start = end = input.value.length;
                input.value = input.value.substring(0, start) + text + input.value.substring(end);
                input.focus();
                try { if (input.setSelectionRange) input.setSelectionRange(start + text.length, start + text.length); } catch (ignore) {}
                say('已粘贴。');
            }
            if (navigator.clipboard && typeof navigator.clipboard.readText === 'function') {
                try {
                    var pending = navigator.clipboard.readText();
                    if (pending && typeof pending.then === 'function') { pending.then(insert, manualPaste); return false; }
                } catch (ignore) {}
            } else if (window.clipboardData && window.clipboardData.getData) {
                try { insert(window.clipboardData.getData('Text')); return false; } catch (ignore) {}
            }
            manualPaste();
            return false;
        };
        paste.style.display = 'inline-block';
    }
    var buttons = document.getElementsByTagName('button');
    for (var i = 0; i < buttons.length; i++) {
        if (/(^|\s)copy-button(\s|$)/.test(buttons[i].className)) {
            buttons[i].onclick = function () { copyText(this); return false; };
            buttons[i].style.display = 'inline-block';
        }
    }
    function deleteStatus(form, text) {
        var result = document.getElementById('delete-result-' + form.getAttribute('data-delete-id'));
        if (result) putText(result, text);
    }
    function removeDeletedRow(form, button) {
        var row = form.parentNode;
        while (row && row.nodeType === 1 && row.tagName.toLowerCase() !== 'tr') row = row.parentNode;
        if (row && row.nodeType === 1) {
            var body = row.parentNode;
            body.removeChild(row);
            if (!body.getElementsByTagName('tr').length) {
                var emptyRow = document.createElement('tr');
                var cell = document.createElement('td');
                cell.colSpan = 3;
                putText(cell, '本页暂无内容。');
                emptyRow.appendChild(cell);
                body.appendChild(emptyRow);
            }
        } else {
            button.disabled = true;
            deleteStatus(form, '内容已删除。');
        }
    }
    function submitDelete(form) {
        if (form._deleting) return false;
        if (form.getAttribute('data-confirm-file') === '1' && !window.confirm('确定删除这条内容吗？删除后无法恢复。')) return false;
        if (!window.XMLHttpRequest || !window.JSON || !window.JSON.parse) return true;
        var request;
        try {
            request = new window.XMLHttpRequest();
            request.open('POST', form.action, true);
            request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
            request.setRequestHeader('Accept', 'application/json');
            request.setRequestHeader('X-Relay-Request', '1');
        } catch (ignore) { return true; }
        var button = form.getElementsByTagName('button')[0];
        var fields = [];
        for (var j = 0; j < form.elements.length; j++) {
            var field = form.elements[j];
            if (field.name && !field.disabled) fields.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value));
        }
        fields.push('response=json');
        form._deleting = true;
        button.disabled = true;
        deleteStatus(form, '正在删除…');
        var finished = false;
        function failed(message) {
            if (finished) return;
            finished = true;
            form._deleting = false;
            button.disabled = false;
            deleteStatus(form, message);
        }
        request.onreadystatechange = function () {
            if (request.readyState !== 4 || finished) return;
            var data = null;
            var status = 0;
            try { data = window.JSON.parse(request.responseText); } catch (ignore) {}
            try { status = request.status; } catch (ignore) {}
            if (status >= 200 && status < 300 && data && data.ok === true) {
                finished = true;
                removeDeletedRow(form, button);
            } else failed(data && typeof data.error === 'string' ? data.error : '删除结果未确认，请手动刷新列表后再试。');
        };
        request.onerror = function () { failed('网络中断，删除结果未确认，请手动刷新列表后再试。'); };
        request.ontimeout = function () { failed('请求超时，删除结果未确认，请手动刷新列表后再试。'); };
        try { request.timeout = 15000; } catch (ignore) {}
        // 请求发出后不自动重发，以免网络故障造成重复操作。
        try { request.send(fields.join('&')); }
        catch (ignore) { failed('请求未完成，请手动刷新列表后再试。'); }
        return false;
    }
    var forms = document.getElementsByTagName('form');
    for (var k = 0; k < forms.length; k++) {
        if (/(^|\s)delete-form(\s|$)/.test(forms[k].className)) {
            forms[k].onsubmit = function () { return submitDelete(this); };
            if (forms[k].getAttribute('data-confirm-file') === '1') {
                (function (form) {
                    var summary = form.parentNode.getElementsByTagName('summary')[0];
                    if (summary) summary.onclick = function () {
                        if (submitDelete(form)) form.submit();
                        return false;
                    };
                }(forms[k]));
            }
        }
    }
    var activeSubmissions = 0;
    var pendingRedirect = '';
    var submissionFailed = false;
    function finishSubmission(success, redirect) {
        if (success) pendingRedirect = redirect;
        else submissionFailed = true;
        activeSubmissions--;
        if (activeSubmissions === 0 && pendingRedirect && !submissionFailed) window.location.assign(pendingRedirect);
    }
    function installSubmissionProgress(upload, fileInput, prefix) {
    if (upload && window.FormData && window.XMLHttpRequest && window.JSON && window.JSON.parse) {
        upload.onsubmit = function () {
            if (upload._uploading) return false;
            var request;
            var data;
            try {
                request = new window.XMLHttpRequest();
                if (!request.upload) return true;
                data = new window.FormData(upload);
                data.append('response', 'json');
                request.open('POST', upload.action, true);
                request.setRequestHeader('Accept', 'application/json');
                request.setRequestHeader('X-Relay-Request', '1');
            } catch (ignore) { return true; }
            var panel = document.getElementById(prefix + '-progress');
            var fill = document.getElementById(prefix + '-fill');
            var result = document.getElementById(prefix === 'text' ? 'text-result' : 'upload-result');
            var resultClass = prefix === 'text' ? 'submit-status' : 'upload-status';
            var label = prefix === 'text' ? '提交' : '上传';
            var button = upload.querySelector ? upload.querySelector('input[type=submit]') : upload.getElementsByTagName('input')[upload.getElementsByTagName('input').length - 1];
            panel.style.display = 'block';
            result.className = resultClass;
            fill.style.width = '0%';
            panel.setAttribute('aria-valuenow', '0');
            if (fileInput && !fileInput.value) { putText(result, '请先选择文件。'); return false; }
            if (activeSubmissions === 0) {
                pendingRedirect = '';
                submissionFailed = false;
            }
            upload._uploading = true;
            activeSubmissions++;
            button.disabled = true;
            putText(result, label + '中 0%');
            var finished = false;
            function failed(message) {
                if (finished) return;
                finished = true;
                upload._uploading = false;
                button.disabled = false;
                putText(result, message);
                finishSubmission(false, '');
            }
            request.upload.onprogress = function (event) {
                if (finished) return;
                if (!event.lengthComputable || !event.total) {
                    panel.removeAttribute('aria-valuenow');
                    putText(result, label + '中…');
                    return;
                }
                var percent = Math.min(100, Math.floor(event.loaded / event.total * 100));
                fill.style.width = percent + '%';
                panel.setAttribute('aria-valuenow', String(percent));
                putText(result, percent === 100 ? '100% · 正在保存…' : label + '中 ' + percent + '%');
            };
            request.onreadystatechange = function () {
                if (finished || request.readyState !== 4) return;
                var reply = null;
                var status = 0;
                try { reply = window.JSON.parse(request.responseText); } catch (ignore) {}
                try { status = request.status; } catch (ignore) {}
                if (status >= 200 && status < 300 && reply && reply.ok === true && typeof reply.redirect === 'string') {
                    finished = true;
                    fill.style.width = '100%';
                    panel.setAttribute('aria-valuenow', '100');
                    putText(result, '成功');
                    result.className = resultClass + ' success';
                    // 等本页已开始的其他发布请求也结束后，再用 GET 更新列表，避免刷新中断并行上传。
                    finishSubmission(true, reply.redirect);
                } else failed(reply && typeof reply.error === 'string' ? reply.error : label + '结果未确认（' + status + '），请手动刷新列表核实后重试。');
            };
            request.onerror = function () { failed('网络中断，请先核实列表，勿重复提交。'); };
            request.ontimeout = function () { failed(label + '超时，请先核实列表，勿重复提交。'); };
            try { request.send(data); } catch (ignore) { failed(label + '未完成，请核实列表后重试。'); }
            return false;
        };
    }
    }
    installSubmissionProgress(document.getElementById('text-form'), null, 'text');
    installSubmissionProgress(document.getElementById('upload-form'), document.getElementById('file'), 'upload');
}());
</script></body></html><?php
}

function renderTextValue(array $item): void
{
    global $dir;
    try { echoItemText($item, $dir); }
    catch (Throwable $error) {
        echoEscapedText('文字暂时不可用，可能已被删除或已过期，请刷新重试。');
        if (!($error instanceof RelayError)) error_log('PHP relay text: ' . $error->getMessage());
    }
}

function renderInlineText(array $item): void
{
    $text = isset($item['text']) && is_string($item['text']) ? $item['text'] : '';
    $long = !empty($item['text_file']) || textIsLong($text);
    if (!$long) {
        echo '<div class="text-content">' . h($text) . '</div>';
        echo '<textarea class="inline-copy short-copy" id="copy-' . h($item['id']) . '" data-item-id="' . h($item['id']) . '" rows="4" cols="30" readonly="readonly" aria-label="完整文字，可选取复制">' . "\n" . h($text) . '</textarea>';
        return;
    }
    $preview = !empty($item['text_file']) ? (string)($item['text_preview'] ?? '') : textPreview($text);
    // 折叠交给浏览器本身。不认识 details 的旧浏览器会直接显示完整文本框。
    // 不使用 CSS 隐藏全文，不依赖 JavaScript 或单独的查看页面。
    ?><details class="text-details">
<summary><span class="text-preview"><?= h($preview) ?></span><span class="text-more">显示更多</span><span class="text-less">收起</span></summary>
<textarea class="inline-copy" id="copy-<?= h($item['id']) ?>" data-item-id="<?= h($item['id']) ?>" rows="8" cols="30" readonly="readonly" aria-label="完整文字，可选取复制"><?php echo "\n"; renderTextValue($item); ?></textarea>
</details><?php
}

function currentListPage(): int
{
    $value = $_GET['page'] ?? '1';
    return is_string($value) && preg_match('/\A[1-9][0-9]{0,5}\z/D', $value) ? (int)$value : 1;
}

function listPageUrl(int $page): string
{
    global $view, $autoRefresh;
    $params = ['page' => max(1, $page)];
    if ($view === 'list') $params['action'] = 'list';
    if ($autoRefresh) $params['refresh'] = 1;
    return url($params);
}

function renderPagination(int $page, int $count): void
{
    if ($count <= 1) return;
    echo '<p class="pagination">第 ' . $page . ' / ' . $count . ' 页　';
    if ($page > 1) echo '<a href="' . h(listPageUrl($page - 1)) . '">上一页</a>';
    if ($page < $count) echo '<a href="' . h(listPageUrl($page + 1)) . '">下一页</a>';
    echo '</p>';
}

function renderList(array $items, int $used): void
{
    global $config;
    $pages = [];
    $group = [];
    $bytes = 0;
    foreach ($items as $entry) {
        $size = $entry['kind'] === 'text' ? (int)$entry['size'] : 0;
        if ($group && (count($group) >= 20 || $bytes + $size > 10 * 1024 * 1024)) {
            $pages[] = $group;
            $group = [];
            $bytes = 0;
        }
        $group[] = $entry;
        $bytes += $size;
    }
    if ($group || !$pages) $pages[] = $group;
    $page = min(currentListPage(), count($pages));
    $items = $pages[$page - 1];
    ?><div class="list-heading" id="content-list"><a class="list-refresh" href="<?= h(refreshUrl()) ?>">手动刷新本页</a></div>
<?php renderPagination($page, count($pages)); ?>
<div class="table-wrap"><table cellspacing="0" cellpadding="6"><thead><tr><th scope="col">名称 / 内容</th><th scope="col">大小 / 剩余时间</th><th scope="col">操作</th></tr></thead><tbody>
<?php if (!$items): ?><tr><td colspan="3">暂无内容。</td></tr><?php endif; ?>
<?php foreach ($items as $item): $file = $item['kind'] === 'file'; ?>
<tr id="item-<?= h($item['id']) ?>"><td class="name"><?php if ($file): ?><a href="<?= h(url(['action' => 'download', 'id' => $item['id']])) ?>"><?= h($item['name']) ?></a><?php else: renderInlineText($item); endif; ?></td>
<td class="small"><?= h(formatBytes((int)$item['size'])) ?><br>约 <?= max(1, (int)ceil(($item['expires_at'] - time()) / 60)) ?> 分钟后过期</td>
<td class="ops"><div class="row-actions"><span class="primary-actions"><?php if ($file): ?><a href="<?= h(url(['action' => 'download', 'id' => $item['id']])) ?>">下载</a><?php if ($item['preview_mime'] !== ''): ?><a href="<?= h(url(['action' => 'preview', 'id' => $item['id']])) ?>">预览</a><?php endif; ?><?php else: ?><button class="clipboard-action copy-button" type="button" data-copy-id="<?= h($item['id']) ?>">复制</button><?php endif; ?></span><?php renderDeleteForm($item['id'], $page, true); ?></div><?php if (!$file): ?><span class="copy-result" id="copy-result-<?= h($item['id']) ?>" role="status"></span><?php endif; ?><span class="delete-result" id="delete-result-<?= h($item['id']) ?>" role="status"></span></td></tr>
<?php endforeach; ?></tbody></table></div><?php renderPagination($page, count($pages));
}

function renderForms(string $oldText = ''): void
{
    global $fileLimit, $pageError;
    $notice = $pageError === '' ? ($_GET['notice'] ?? '') : '';
    $textSuccess = $notice === 'text-posted';
    $uploadSuccess = $notice === 'upload-posted';
    $open = $pageError !== '' || $textSuccess || $uploadSuccess || $oldText !== '';
    ?><details class="publish-toggle" id="publish-group"<?= $open ? ' open="open"' : '' ?>><summary><span class="toggle-closed" aria-hidden="true">▸ </span><span class="toggle-open" aria-hidden="true">▾ </span>点击发布（文字、图片、视频、文件）</summary><fieldset id="publish"><legend>文字 / 网址</legend>
<form id="text-form" method="post" enctype="multipart/form-data" action="<?= h(url(['action' => 'text'])) ?>" accept-charset="UTF-8">
<?php csrfInput(); ?>
<p><textarea id="text" name="text" rows="2" cols="50" aria-label="要发布的文字或网址"><?php echo "\n"; echoEscapedText($oldText); ?></textarea></p>
<p><input type="submit" value="发布文字"><button class="clipboard-action" type="button" id="paste-button">粘贴</button><span id="text-result" class="submit-status<?= $textSuccess ? ' success' : '' ?>" role="status" aria-live="polite"><?= $textSuccess ? '成功' : '' ?></span></p><div id="text-progress" class="upload-progress<?= $textSuccess ? ' is-complete' : '' ?>" role="progressbar" aria-label="文字提交进度" aria-valuemin="0" aria-valuemax="100" aria-valuenow="<?= $textSuccess ? '100' : '0' ?>"><div class="upload-track"><div id="text-fill" class="upload-fill"></div></div></div><p id="clipboard-status" class="clipboard-status" role="status" aria-live="polite"></p></form></fieldset>
<fieldset class="upload-panel"><legend>上传文件</legend>
<?php if ($fileLimit > 0): ?><form id="upload-form" method="post" enctype="multipart/form-data" action="<?= h(url(['action' => 'upload'])) ?>" accept-charset="UTF-8">
<?php csrfInput(); ?><input type="hidden" name="MAX_FILE_SIZE" value="<?= $fileLimit ?>">
<p class="upload-controls"><input type="file" id="file" name="file" aria-label="选择上传文件"> <input type="submit" value="上传文件"></p>
<div id="upload-progress" class="upload-progress<?= $uploadSuccess ? ' is-complete' : '' ?>" role="progressbar" aria-label="文件上传进度" aria-valuemin="0" aria-valuemax="100" aria-valuenow="<?= $uploadSuccess ? '100' : '0' ?>"><div class="upload-track"><div id="upload-fill" class="upload-fill"></div></div><span id="upload-result" class="upload-status<?= $uploadSuccess ? ' success' : '' ?>" role="status"><?= $uploadSuccess ? '成功' : '' ?></span></div>
</form><?php else: ?><p>当前 PHP 设置不允许上传文件；文字功能仍可使用。</p><?php endif; ?>
</fieldset></details><?php
}

// 所有响应（包括下载、错误和重定向）禁止缓存。
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
// 原生表单 POST 需要保留本站来源；no-referrer 会让部分浏览器发送 Origin: null。
header('Referrer-Policy: same-origin');
header('Cross-Origin-Resource-Policy: same-origin');
header('X-Robots-Tag: noindex, nofollow, noarchive');
$scriptNonce = base64_encode(random_bytes(18));
header("Content-Security-Policy: default-src 'none'; script-src 'nonce-$scriptNonce'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self'; media-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'");

$cookieName = 'relay_' . substr(hash('sha256', __FILE__), 0, 12);
$action = $_GET['action'] ?? '';
$id = $_GET['id'] ?? '';
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$ajaxDelete = $action === 'delete' && ($_POST['response'] ?? '') === 'json' && ($_SERVER['HTTP_X_RELAY_REQUEST'] ?? '') === '1';
$ajaxUpload = $action === 'upload' && ($_POST['response'] ?? '') === 'json' && ($_SERVER['HTTP_X_RELAY_REQUEST'] ?? '') === '1';
$ajaxText = $action === 'text' && ($_POST['response'] ?? '') === 'json' && ($_SERVER['HTTP_X_RELAY_REQUEST'] ?? '') === '1';
$csrfToken = '';
$fileLimit = 0;
$items = [];
$used = 0;
$item = null;
$pageError = '';
$autoRefresh = false;
$view = 'home';
try {
    if (!is_string($action) || !is_string($id)) throw new RelayError('请求格式不正确。');
    if ($action === 'qr-code') {
        if (!in_array($method, ['GET', 'HEAD'], true)) throw new RelayError('不支持此请求方式。', 405);
        sendSiteQrCode();
    }
    $dir = storageDir($config);
    $postLimit = iniBytes((string)ini_get('post_max_size'));
    $fileLimit = min($config['max_file'], iniBytes((string)ini_get('upload_max_filesize')), max(0, $postLimit - 65536));
    if (!filter_var(ini_get('file_uploads'), FILTER_VALIDATE_BOOLEAN)) $fileLimit = 0;
    if ($action === 'download' || $action === 'media') {
        if (!in_array($method, ['GET', 'HEAD'], true)) throw new RelayError('此操作只支持查看或下载。', 405);
        if (!validId($id)) throw new RelayError('文件不存在。', 404);
        sendContent($dir, $id, $action === 'media');
    }
    $snapshot = locked($dir, function (array &$db) use ($dir) {
        if (!isset($db['csrf_secret'])) {
            $db['csrf_secret'] = bin2hex(random_bytes(32));
            saveIndex($dir, $db);
        }
        if (!is_string($db['csrf_secret']) || preg_match('/\A[a-f0-9]{64}\z/D', $db['csrf_secret']) !== 1) {
            throw new RelayError('表单校验密钥损坏，请由网站维护者检查存储索引。', 503);
        }
        return ['items' => publicItems($db), 'used' => usage($db), 'secret' => $db['csrf_secret']];
    });
    $items = $snapshot['items'];
    $used = $snapshot['used'];
    $csrfToken = prepareCsrf($snapshot['secret']);
    if ($method === 'POST') {
        if (!in_array($action, ['text', 'upload', 'delete'], true)) throw new RelayError('接口不存在。', 404);
        // PHP 超过 post_max_size 时会清空 POST/FILES，先给出真正原因再验证表单。
        if ((int)($_SERVER['CONTENT_LENGTH'] ?? 0) > $postLimit) throw new RelayError('超过 PHP 提交大小限制，请选择更小的文件。', 413);
        mutationGuard($snapshot['secret']);
        $createdId = locked($dir, function (array &$db) use ($action, $dir, $config, $fileLimit) {
            consumeRate($dir, $db);
            if ($action === 'delete') {
                $target = $_POST['id'] ?? null;
                if (!validId($target) || !isset($db['items'][$target]) || $db['items'][$target]['expires_at'] <= time()) throw new RelayError('内容不存在或已过期。', 404);
                $targetItem = $db['items'][$target];
                if ($targetItem['kind'] === 'file' || !empty($targetItem['text_file'])) {
                    $path = $dir . '/' . $target . ($targetItem['kind'] === 'file' ? '.bin' : '.txt');
                    if (is_file($path) && !@unlink($path)) throw new RelayError('文件删除失败，请稍后重试。', 503);
                }
                unset($db['items'][$target]);
                saveIndex($dir, $db);
                return '';
            }
            $newId = bin2hex(random_bytes(16));
            $newItem = ['id' => $newId, 'kind' => $action === 'text' ? 'text' : 'file', 'created_at' => time(), 'expires_at' => time() + $config['ttl']];
            if ($action === 'text') {
                $text = $_POST['text'] ?? '';
                if (!is_string($text)) throw new RelayError('请输入有效的文字。');
                if (strlen($text) > $config['max_text']) throw new RelayError('文字过长，最多 ' . formatBytes($config['max_text']) . '。', 413);
                if (trim($text) === '' || preg_match('//u', $text) !== 1) throw new RelayError('请输入有效的文字。');
                if (preg_match('/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/', $text)) throw new RelayError('请提交纯文本，不要包含二进制控制字符。');
                checkQuota($db, $config, $dir, strlen($text));
                $newItem['size'] = strlen($text);
                if (strlen($text) > 64 * 1024) {
                    $path = saveTextFile($dir, $newId, $text);
                    $newItem += ['text_file' => true, 'text_preview' => textPreview($text)];
                } else {
                    $newItem['text'] = $text;
                }
            } else {
                if ($fileLimit <= 0) throw new RelayError('当前 PHP 设置不允许文件上传。', 413);
                $file = $_FILES['file'] ?? null;
                if (!is_array($file) || !isset($file['error']) || !is_int($file['error'])) throw new RelayError('请选择一个文件，也请检查 PHP 上传限制。');
                if ($file['error'] !== UPLOAD_ERR_OK) {
                    $large = in_array($file['error'], [UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE], true);
                    throw new RelayError($large ? '文件超过 PHP 上传大小限制。' : '上传未完成，请重新选择文件。', $large ? 413 : 400);
                }
                if (!is_string($file['tmp_name'] ?? null) || !is_uploaded_file($file['tmp_name'])) throw new RelayError('不是有效的上传文件。');
                $size = filesize($file['tmp_name']);
                if ($size === false || $size > $fileLimit) throw new RelayError('文件超过当前可上传大小。', 413);
                checkQuota($db, $config, $dir, $size);
                $name = is_string($file['name'] ?? null) ? basename(str_replace('\\', '/', $file['name'])) : 'download.bin';
                $name = trim((string)preg_replace('/[\x00-\x1f\x7f]/', '', $name));
                if ($name === '' || $name === '.' || $name === '..' || preg_match('//u', $name) !== 1) $name = 'download.bin';
                if (strlen($name) > 240) throw new RelayError('文件名过长，请重命名后上传。');
                $newItem += ['name' => $name, 'size' => $size, 'preview_mime' => safeMime($file['tmp_name'])];
                $path = $dir . '/' . $newId . '.bin';
                if (!move_uploaded_file($file['tmp_name'], $path)) throw new RelayError('无法保存文件，请检查磁盘空间和目录权限。', 507);
                @chmod($path, 0600);
            }
            $db['items'][$newId] = $newItem;
            try { saveIndex($dir, $db); }
            catch (Throwable $error) { if (isset($path)) @unlink($path); throw $error; }
            return $newId;
        });
        if ($action === 'delete' && $ajaxDelete) jsonReply(['ok' => true]);
        $successUrl = url(['notice' => $action === 'text' ? 'text-posted' : 'upload-posted', 'id' => $createdId]);
        if ($ajaxUpload || $ajaxText) jsonReply(['ok' => true, 'redirect' => $successUrl]);
        header('Location: ' . ($action === 'delete' ? deleteReturnUrl() : $successUrl), true, 303);
        exit;
    }
    if (!in_array($method, ['GET', 'HEAD'], true)) throw new RelayError('不支持此请求方式。', 405);
    if (in_array($action, ['view', 'delete', 'preview'], true)) {
        if (!validId($id)) throw new RelayError('内容不存在。', 404);
        foreach ($items as $candidate) { if ($candidate['id'] === $id) { $item = $candidate; break; } }
        if (!$item) throw new RelayError('内容不存在或已过期。', 404);
        if ($action === 'view' && $item['kind'] !== 'text') throw new RelayError('请使用文件的下载入口。', 400);
        if ($action === 'preview' && ($item['kind'] !== 'file' || $item['preview_mime'] === '')) throw new RelayError('此格式不支持安全预览，请下载查看。', 415);
        $view = $action;
    } elseif ($action === 'list') {
        $view = 'list';
        $autoRefresh = ($_GET['refresh'] ?? '') === '1';
    } elseif ($action === 'text' || $action === 'upload') {
        throw new RelayError('请返回首页，通过表单提交。', 405);
    } elseif ($action !== '') {
        throw new RelayError('页面不存在。', 404);
    }
} catch (Throwable $error) {
    $status = $error instanceof RelayError ? $error->status : 503;
    http_response_code($status);
    $pageError = $error instanceof RelayError ? $error->getMessage() : '存储暂时不可用，请检查 PHP 目录权限、磁盘空间及服务器错误日志。';
    if (!($error instanceof RelayError)) error_log('PHP relay: ' . $error->getMessage());
    if ($ajaxDelete || $ajaxUpload || $ajaxText) jsonReply(['error' => $pageError], $status);
    $view = 'error';
    $autoRefresh = false;
}

header('Content-Type: text/html; charset=UTF-8');
if ($method === 'HEAD') exit;
$titles = ['home' => 'File share', 'list' => '内容列表', 'view' => '查看 / 复制文字', 'delete' => '确认删除', 'preview' => '文件预览', 'error' => '操作未完成'];
pageStart($titles[$view]);
if ($view === 'error') {
    echo '<p class="error">' . h($pageError) . '</p><p><a href="' . h(url()) . '">返回首页重试</a></p>';
    if ($action === 'text' && $csrfToken !== '') {
        $oldText = $_POST['text'] ?? '';
        if (is_string($oldText)) {
            // 超出限制时仍保留一段可编辑原文，避免小幅超限就丢失输入。
            $retain = max($config['max_text'], 64 * 1024);
            if (strlen($oldText) > $retain) echo '<p>输入过长，下面仅保留前 ' . h(formatBytes($retain)) . '，请缩短后重新提交。</p>';
            renderForms(substr($oldText, 0, $retain));
        }
    }
} elseif ($view === 'home' || $view === 'list') {
    $notice = $_GET['notice'] ?? '';
    if ($notice === 'deleted') echo '<p class="success">内容已删除。</p>';
    if ($view === 'home') renderForms();
    if ($view === 'list') {
        echo $autoRefresh ? '<p>自动刷新已开启：每 60 秒更新此列表。<a href="' . h(url(['action' => 'list'])) . '">关闭自动刷新</a></p>' : '<p><a href="' . h(url(['action' => 'list', 'refresh' => 1])) . '">开启每 60 秒自动刷新</a>（仅此只读列表页）</p>';
    }
    renderList($items, $used);
} elseif ($view === 'view') {
    ?><p><label for="copy-text">长按文字选择并复制；电脑可点入文本框，按 Ctrl+A / Command+A，再复制。</label></p>
<p><textarea id="copy-text" rows="12" cols="60" readonly="readonly"><?php echo "\n"; renderTextValue($item); ?></textarea></p>
<?php renderDeleteForm($id); ?><span class="delete-result" id="delete-result-<?= h($id) ?>" role="status"></span><?php
} elseif ($view === 'delete') {
    ?><p class="error">确认删除下面的内容？删除后所有访客都将无法再获取它。</p>
<pre><?php if ($item['kind'] === 'text') renderTextValue($item); else echo h($item['name']); ?></pre>
<form method="post" action="<?= h(url(['action' => 'delete'])) ?>" accept-charset="UTF-8">
<?php csrfInput(); ?><input type="hidden" name="id" value="<?= h($id) ?>">
<p><input type="submit" value="确认删除">　<a href="<?= h(url()) ?>">取消 / 返回首页</a></p></form><?php
} elseif ($view === 'preview') {
    ?><h2><?= h($item['name']) ?></h2><p><a href="<?= h(url(['action' => 'download', 'id' => $id])) ?>">下载原文件</a>　旧浏览器无法预览时，请下载后打开。</p>
<?php if (str_starts_with($item['preview_mime'], 'image/')): ?>
<p><img src="<?= h(url(['action' => 'media', 'id' => $id])) ?>" alt="<?= h($item['name']) ?>"></p>
<?php else: ?>
<p><video controls="controls" preload="none" src="<?= h(url(['action' => 'media', 'id' => $id])) ?>">此浏览器不支持视频预览，请使用上方下载链接。</video></p>
<?php endif; renderDeleteForm($id, 1, true); ?><span class="delete-result" id="delete-result-<?= h($id) ?>" role="status"></span><?php
}
pageEnd();
