aboutsummaryrefslogtreecommitdiff
path: root/src/Models/Attachment.php
blob: bbd8fc4192aeb190614149d57ada9bb3d8f797b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
<?php


namespace Micropoly\Models;


use InvalidArgumentException;
use Micropoly\BoundVal;
use Micropoly\DbQuery;
use RuntimeException;
use SQLite3;

class Attachment
{
    public const HASH_ALGO = "sha3-256";

    private const HASH_PREFIX_LEN = 2;

    private string $id;
    private string $noteId;
    private string $hash;
    private ?string $fileName;
    private string $mime;

    private function __construct() {}

    /**
     * @param string $hash
     * @return string[]
     */
    private static function splitHash(string $hash): array
    {
        if (strlen($hash) <= self::HASH_PREFIX_LEN+1) { // +1 so $tail won't be empty
            throw new InvalidArgumentException("Invalid hash '$hash' given");
        }

        $head = substr($hash, 0, self::HASH_PREFIX_LEN);
        $tail = substr($hash, self::HASH_PREFIX_LEN);
        return [$head, $tail];
    }

    private static function relativeFilePathFromHash(string $hash): string
    {
        [$head, $tail] = self::splitHash($hash);

        return $head . DIRECTORY_SEPARATOR . $tail;
    }

    /**
     * @param string $attachmentPath
     * @param string $hash
     * @return string
     */
    private static function fullFilePathFromHash(string $attachmentPath, string $hash): string
    {
        return $attachmentPath . DIRECTORY_SEPARATOR . self::relativeFilePathFromHash($hash);
    }

    private static function deleteFileByHash(string $attachmentPath, string $hash): void
    {
        @unlink(self::fullFilePathFromHash($attachmentPath, $hash));
    }

    public function clearAbandoned(SQLite3 $db, string $attachmentPath): void
    {
        $db->exec("BEGIN");
        foreach ((new DbQuery("
            SELECT a.hash
            FROM attachments a
            LEFT JOIN note_attachments na
                ON na.hash = a.hash
            WHERE na.id IS NULL
        "))->fetchValues($db) as $hash) {
            self::deleteFileByHash($attachmentPath, $hash);
        }

        $db->exec("
            DELETE FROM attachments
            WHERE hash NOT IN (
                SELECT hash
                FROM note_attachments
            )
        ");
        $db->exec("COMMIT");
    }

    private static function fromRow(array $row): self
    {
        $out = new self();

        $out->id = $row["id"];
        $out->noteId = $row["note_id"];
        $out->hash = $row["hash"];
        $out->fileName = $row["file_name"];
        $out->mime = $row["mime"];

        return $out;
    }

    /**
     * @param SQLite3 $db
     * @param DbQuery $query
     * @return self[] Indexed by id
     */
    private static function byQuery(SQLite3 $db, DbQuery $query): array
    {
        return array_map([self::class, "fromRow"], $query->fetchIndexedRows($db, "id"));
    }

    /**
     * @param SQLite3 $db
     * @param string[] $ids
     * @return self[] Indexed by id
     */
    public static function byIds(SQLite3 $db, array $ids): array
    {
        $ids = array_map("trim", $ids);
        $ids = array_filter($ids);

        if (empty($ids))
            return [];

        return self::byQuery(
            $db,
            (new DbQuery("
                SELECT id, note_id, hash, file_name, mime
                FROM note_attachments
                WHERE id IN (" . DbQuery::valueListPlaceholders($ids) . ")
            "))
                ->bindMultiText($ids)
        );
    }

    public static function byId(SQLite3 $db, string $id): ?self
    {
        return self::byIds($db, [$id])[$id] ?? null;
    }

    /**
     * @param SQLite3 $db
     * @param string $noteId
     * @return self[] Indexed by id
     */
    public static function byNoteId(SQLite3 $db, string $noteId): array
    {
        return self::byQuery(
            $db,
            (new DbQuery("
                SELECT id, note_id, hash, file_name, mime
                FROM note_attachments
                WHERE note_id = ?
            "))
                ->bind(1, BoundVal::ofText($noteId))
        );
    }

    private static function transposeUploadsArray(array $uploads): array
    {
        $out = [];
        foreach ($uploads as $key => $values) {
            if (!is_array($values))
                $values = [$values];

            foreach ($values as $i => $v)
                $out[$i][$key] = $v;
        }

        return $out;
    }

    private static function hasHash(SQLite3 $db, string $hash): bool
    {
        return (new DbQuery("SELECT COUNT(*) FROM attachments WHERE hash = ?"))
                ->bind(1, BoundVal::ofText($hash))
                ->fetchRow($db)[0] > 0;
    }

    private static function mkUploadDir(string $attachmentPath, string $hash): void
    {
        [$head] = self::splitHash($hash);
        $dir = $attachmentPath . DIRECTORY_SEPARATOR . $head;

        if (!is_dir($dir))
            if (!mkdir($dir))
                throw new RuntimeException("Failed creating upload dir '$dir'");
    }

    /**
     * @param SQLite3 $db
     * @param string $attachmentPath
     * @param Note $note
     * @param array $uploads a $_FILES[$name] like array.
     *                       Can be populated by multiple files, like
     *                       {@see https://www.php.net/manual/en/features.file-upload.multiple.php} describes it.
     * @return self[]
     */
    public static function createFromUploads(SQLite3 $db, string $attachmentPath, Note $note, array $uploads): array
    {
        $out = [];
        $inserts = [];

        foreach (self::transposeUploadsArray($uploads) as $upload) {
            if ($upload["error"] !== UPLOAD_ERR_OK)
                continue;

            $hash = hash_file(self::HASH_ALGO, $upload["tmp_name"]);
            if (self::hasHash($db, $hash)) {
                unlink($upload["tmp_name"]);
            } else {
                self::mkUploadDir($attachmentPath, $hash);
                if (!move_uploaded_file($upload["tmp_name"], self::fullFilePathFromHash($attachmentPath, $hash))) {
                    throw new RuntimeException("Failed uploading file '{$upload["tmp_name"]}', original name was: '{$upload["name"]}'");
                }
                DbQuery::insertKV($db, "attachments", ["hash" => BoundVal::ofText($hash)]);
            }

            $obj = new self();

            $obj->id = uniqid("", true);
            $obj->noteId = $note->getId();
            $obj->hash = $hash;
            $obj->fileName = $upload["name"] ?? null;
            $obj->mime = (string)($upload["type"] ?? "application/octet-stream");

            $out[] = $obj;
            $inserts[] = $obj->buildInsertValues();
        }

        DbQuery::insert($db, "note_attachments", ["id", "note_id", "hash", "file_name", "mime"], $inserts);

        return $out;
    }

    private function buildInsertValues()
    {
        return [
            BoundVal::ofText($this->id),
            BoundVal::ofText($this->noteId),
            BoundVal::ofText($this->hash),
            $this->fileName === null ? BoundVal::ofNull() : BoundVal::ofText($this->fileName),
            BoundVal::ofText($this->mime),
        ];
    }

    public function delete(SQLite3 $db, string $attachmentPath): void
    {
        (new DbQuery("DELETE FROM note_attachments WHERE id = ?"))->bind(1, BoundVal::ofText($this->id))->exec($db);
        self::clearAbandoned($db, $attachmentPath);
    }

    public function getId(): string { return $this->id; }
    public function getNoteId(): string { return $this->noteId; }
    public function getHash(): string { return $this->hash; }
    public function getFileName(): ?string { return $this->fileName; }
    public function getMime(): string { return $this->mime; }

    public function getFilePath(string $attachmentPath): string
    {
        return self::fullFilePathFromHash($attachmentPath, $this->hash);
    }
}