Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.55% covered (success)
91.55%
65 / 71
66.67% covered (warning)
66.67%
4 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
Ingest
91.55% covered (success)
91.55%
65 / 71
66.67% covered (warning)
66.67%
4 / 6
24.35
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 ingest
90.00% covered (success)
90.00%
36 / 40
0.00% covered (danger)
0.00%
0 / 1
6.04
 validate
89.47% covered (warning)
89.47%
17 / 19
0.00% covered (danger)
0.00%
0 / 1
11.14
 imageDimensions
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 safeFilename
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 sanitizeSvgMarkup
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3declare(strict_types=1);
4
5namespace Cosray\Assets;
6
7use Celema\Quma\Database;
8use Cosray\Actor;
9use Cosray\Config;
10use Cosray\Exception\IngestError;
11use Cosray\Exception\RuntimeException;
12use Cosray\Storage\Storage;
13use Cosray\Uid;
14use enshrined\svgSanitize\Sanitizer;
15use finfo;
16use Throwable;
17
18/**
19 * Catalogs raw bytes as an asset: validation, SVG sanitising, hash dedup,
20 * the storage write, and the catalog row. The upload controller and
21 * importers share this one pipeline.
22 */
23final class Ingest
24{
25    private readonly Storage $storage;
26
27    public function __construct(
28        private readonly Config $config,
29        private readonly Database $db,
30    ) {
31        $this->storage = new Storage($config);
32    }
33
34    public function ingest(
35        string $contents,
36        string $filename,
37        string $mediatype,
38        ?Actor $actor = null,
39        array $meta = [],
40    ): IngestResult {
41        $filename = self::safeFilename($filename);
42        $mime = $this->validate($contents, $filename, $mediatype);
43
44        // SVGs are served inline, so a stored `<script>`/`onload` would run
45        // in the site origin. Clean the markup before it lands in the pool;
46        // hash and byte count are taken from the sanitized bytes.
47        if (strtolower(pathinfo($filename, PATHINFO_EXTENSION)) === 'svg') {
48            $clean = self::sanitizeSvgMarkup($contents);
49
50            if ($clean === null) {
51                throw IngestError::unsafeSvg();
52            }
53
54            $contents = $clean;
55        }
56
57        $hash = hash('sha256', $contents);
58        $existing = $this->db
59            ->assets
60            ->byHash([
61                'hash' => $hash,
62                'disk' => $this->storage->disk,
63            ])
64            ->first();
65
66        if ($existing) {
67            return new IngestResult($existing, created: false);
68        }
69
70        [$width, $height] = $this->imageDimensions($mediatype, $contents);
71        $uidConfig = $this->config->uid;
72        $uid = new Uid($uidConfig->alphabet, $uidConfig->length)->generate();
73        $key = Storage::key($uid, $filename);
74        $this->storage->write($key, $contents);
75
76        $row = [
77            'uid' => $uid,
78            'disk' => $this->storage->disk,
79            'key' => $key,
80            'filename' => $filename,
81            'mime' => $mime,
82            'bytes' => strlen($contents),
83            'width' => $width,
84            'height' => $height,
85            'hash' => $hash,
86            'meta' => $meta === [] ? '{}' : json_encode($meta),
87            'creator' => ($actor ?? Actor::system())->id,
88        ];
89
90        try {
91            $this->db->assets->create($row)->one();
92        } catch (Throwable $e) {
93            $this->storage->delete($key);
94
95            throw $e;
96        }
97
98        return new IngestResult($row, created: true);
99    }
100
101    /** @return string the detected mime type */
102    private function validate(string $contents, string $filename, string $mediatype): string
103    {
104        $upload = $this->config->upload;
105        $mimeTypes = match ($mediatype) {
106            'file' => $upload->file,
107            'image' => $upload->image,
108            'video' => $upload->video,
109            default => throw new RuntimeException('Media type not supported: ' . $mediatype),
110        };
111
112        if ($filename === '') {
113            throw IngestError::unknownFilename();
114        }
115
116        if (strlen($contents) > $upload->maxSize) {
117            throw IngestError::tooLarge(strlen($contents), $upload->maxSize);
118        }
119
120        $mime = (string) new finfo(FILEINFO_MIME_TYPE)->buffer($contents);
121        $allowedExtensions = $mimeTypes[$mime] ?? null;
122
123        if (!$allowedExtensions) {
124            throw IngestError::disallowedType($mime);
125        }
126
127        $ext = pathinfo($filename, PATHINFO_EXTENSION) ?: null;
128
129        if (!$ext || !in_array(strtolower($ext), $allowedExtensions, true)) {
130            throw IngestError::wrongExtension($ext, $allowedExtensions, $mime);
131        }
132
133        return $mime;
134    }
135
136    /** @return array{0: ?int, 1: ?int} */
137    private function imageDimensions(string $mediatype, string $contents): array
138    {
139        if ($mediatype !== 'image') {
140            return [null, null];
141        }
142
143        // getimagesizefromstring warns on undecodable input (e.g. SVG bytes);
144        // unreadable dimensions are an expected outcome here, not an error.
145        set_error_handler(static fn(): bool => true);
146
147        try {
148            $info = getimagesizefromstring($contents);
149        } finally {
150            restore_error_handler();
151        }
152
153        return $info === false ? [null, null] : [$info[0], $info[1]];
154    }
155
156    /**
157     * Reduce a client-supplied upload name to a safe on-disk basename:
158     * strip every directory component (and any `../`), drop control
159     * characters, and trim leading/trailing dots and spaces.
160     */
161    public static function safeFilename(string $name): string
162    {
163        $name = basename($name);
164        $name = preg_replace('/[\x00-\x1F\x7F]/', '', $name) ?? '';
165
166        return trim($name, ' .');
167    }
168
169    /**
170     * Strip scripts, event handlers and remote references from SVG markup.
171     * Returns null when the sanitizer rejects the markup as malformed.
172     */
173    public static function sanitizeSvgMarkup(string $svg): ?string
174    {
175        $clean = new Sanitizer()->sanitize($svg);
176
177        return $clean === false ? null : $clean;
178    }
179}