Files
laysense.cn/app/Content/Media.php

136 lines
6.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMXPath;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RuntimeException;
use Throwable;
use Webman\Http\UploadFile;
final class Media
{
public const MAX_BYTES = 64 * 1024 * 1024;
private const EXTENSIONS = [
'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp',
'image/avif' => 'avif', 'image/x-icon' => 'ico', 'image/vnd.microsoft.icon' => 'ico', 'image/svg+xml' => 'svg',
'video/mp4' => 'mp4', 'video/webm' => 'webm', 'video/quicktime' => 'mov',
'audio/mpeg' => 'mp3', 'audio/ogg' => 'ogg', 'audio/wav' => 'wav',
'application/pdf' => 'pdf', 'font/woff' => 'woff', 'font/woff2' => 'woff2',
];
public static function all(bool $includeArchived = false): array
{
$query = 'SELECT name, label, mime, size, created_at, archived FROM media' . ($includeArchived ? '' : ' WHERE archived = 0');
$files = Database::connect()->query($query . ' ORDER BY created_at DESC, name')->fetchAll();
foreach ($files as &$file) {
$file['url'] = '/assets/uploads/' . $file['name'];
}
unset($file);
$root = dirname(__DIR__, 2) . '/public/assets';
$builtIn = [];
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root)) as $file) {
if (!$file->isFile() || $file->isLink() || str_starts_with($file->getFilename(), '.')) {
continue;
}
$path = str_replace(DIRECTORY_SEPARATOR, '/', substr($file->getPathname(), strlen($root) + 1));
$label = $file->getFilename();
$type = array_search(strtolower($file->getExtension()), self::EXTENSIONS, true) ?: 'application/octet-stream';
$builtIn[] = ['label' => $label, 'name' => '', 'mime' => $type, 'size' => $file->getSize(),
'url' => '/assets/' . $path, 'archived' => 0];
}
usort($builtIn, static fn (array $left, array $right): int => strnatcasecmp($left['url'], $right['url']));
return [...$files, ...$builtIn];
}
public static function upload(UploadFile $file, string $label): void
{
if (!$file->isValid() || ($size = $file->getSize()) < 1 || $size > self::MAX_BYTES) {
throw new RuntimeException('请选择大小不超过 64 MB 的有效文件。');
}
$source = $file->getPathname();
$mime = (new \finfo(FILEINFO_MIME_TYPE))->file($source);
$extension = self::EXTENSIONS[$mime] ?? null;
if ($extension === null) {
throw new RuntimeException('文件类型不受支持。');
}
$content = $mime === 'image/svg+xml' ? self::safeSvg($source, $size) : null;
$name = bin2hex(random_bytes(16)) . '.' . $extension;
$directory = self::directory();
if (!is_dir($directory) && !mkdir($directory, 0750, true) && !is_dir($directory)) {
throw new RuntimeException('资源目录无法创建。');
}
$path = $directory . '/' . $name;
try {
$written = $content === null ? copy($source, $path) : file_put_contents($path, $content) === strlen($content);
if (!$written) {
throw new RuntimeException('文件写入失败。');
}
$query = Database::connect()->prepare('INSERT INTO media (name, label, mime, size, created_at) VALUES (?, ?, ?, ?, ?)');
$query->execute([$name, $label, $mime, $content === null ? $size : strlen($content), gmdate('c')]);
} catch (Throwable $error) {
if (is_file($path)) {
unlink($path);
}
throw $error;
}
}
public static function find(string $name): ?array
{
$query = Database::connect()->prepare('SELECT * FROM media WHERE name = ?');
$query->execute([$name]);
return $query->fetch() ?: null;
}
public static function update(string $name, string $label, bool $archived): void
{
Database::connect()->prepare('UPDATE media SET label = ?, archived = ? WHERE name = ?')
->execute([$label, (int) $archived, $name]);
}
public static function directory(): string
{
return rtrim(getenv('LAYSENSE_MEDIA_DIR') ?: dirname(__DIR__, 2) . '/storage/media', '/');
}
private static function safeSvg(string $source, int $size): string
{
if ($size > 512 * 1024) {
throw new RuntimeException('SVG 图标最大支持 512 KB。');
}
$svg = new DOMDocument();
if (!$svg->loadXML(file_get_contents($source), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) || $svg->doctype
|| $svg->documentElement?->namespaceURI !== 'http://www.w3.org/2000/svg' || $svg->documentElement->localName !== 'svg') {
throw new RuntimeException('SVG 图标格式无效。');
}
$tags = ['svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'title', 'desc'];
$attributes = ['viewBox', 'width', 'height', 'fill', 'fill-rule', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-linecap',
'stroke-linejoin', 'stroke-dasharray', 'stroke-opacity', 'curve', 'clip-rule', 'opacity', 'd', 'x', 'y',
'rx', 'ry', 'cx', 'cy', 'r', 'x1', 'x2', 'y1', 'y2', 'points', 'transform'];
foreach ((new DOMXPath($svg))->query('//*') as $element) {
if (!$element instanceof DOMElement || $element->namespaceURI !== 'http://www.w3.org/2000/svg'
|| !in_array($element->localName, $tags, true)) {
throw new RuntimeException('SVG 仅支持基础矢量元素。');
}
foreach ($element->attributes as $attribute) {
if ($attribute->namespaceURI !== null || !in_array($attribute->localName, $attributes, true)
|| !preg_match('/^[a-z0-9#.,%\s()+-]*$/iD', $attribute->value) || preg_match('/url\s*\(/i', $attribute->value)) {
throw new RuntimeException('SVG 包含不支持的属性或外部引用。');
}
}
}
return $svg->saveXML($svg->documentElement);
}
}