aboutsummaryrefslogtreecommitdiff
path: root/lib/uploads.php
blob: 7540f11321ac49d50ae0794cee2857a93bdc2b88 (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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
<?php

const UPLOADS_ALLOWED_EXTENSIONS = [
    'jpg', 'png', 'git', 'mp4', 'mp3', 'ogg', 'diff', 'txt', 'gz', 'tar',
    'icc', 'icm', 'patch', 'zip', 'brd', 'pdf', 'lua', 'xpi', 'rar', '7z',
    'tgz', 'bin', 'py', 'pac', 'yaml', 'toml', 'xml', 'json', 'yml',
];

class uploads {

    static function getCount(): int {
        $db = DB();
        return (int)$db->result($db->query("SELECT COUNT(*) FROM uploads"));
    }

    static function isExtensionAllowed(string $ext): bool {
        return in_array($ext, UPLOADS_ALLOWED_EXTENSIONS);
    }

    static function add(string $tmp_name, string $name, string $note): ?int {
        global $config;

        $name = sanitize_filename($name);
        if (!$name)
            $name = 'file';

        $random_id = self::_getNewUploadRandomId();
        $size = filesize($tmp_name);
        $is_image = detect_image_type($tmp_name) !== false;
        $image_w = 0;
        $image_h = 0;
        if ($is_image) {
            list($image_w, $image_h) = getimagesize($tmp_name);
        }

        $db = DB();
        if (!$db->insert('uploads', [
            'random_id' => $random_id,
            'ts' => time(),
            'name' => $name,
            'size' => $size,
            'image' => (int)$is_image,
            'image_w' => $image_w,
            'image_h' => $image_h,
            'note' => $note,
            'downloads' => 0,
        ])) {
            return null;
        }

        $id = $db->insertId();

        $dir = $config['uploads_dir'].'/'.$random_id;
        $path = $dir.'/'.$name;

        mkdir($dir);
        chmod($dir, 0775); // g+w

        rename($tmp_name, $path);
        chmod($path, 0664); // g+w

        return $id;
    }

    static function delete(int $id): bool {
        $upload = self::get($id);
        if (!$upload)
            return false;

        $db = DB();
        $db->query("DELETE FROM uploads WHERE id=?", $id);

        rrmdir($upload->getDirectory());
        return true;
    }

    /**
     * @return Upload[]
     */
    static function getAllUploads(): array {
        $db = DB();
        $q = $db->query("SELECT * FROM uploads ORDER BY id DESC");
        return array_map('Upload::create_instance', $db->fetchAll($q));
    }

    static function get(int $id): ?Upload {
        $db = DB();
        $q = $db->query("SELECT * FROM uploads WHERE id=?", $id);
        if ($db->numRows($q)) {
            return new Upload($db->fetch($q));
        } else {
            return null;
        }
    }

    /**
     * @param string[] $ids
     * @param bool $flat
     * @return Upload[]
     */
    static function getUploadsByRandomId(array $ids, bool $flat = false): array {
        if (empty($ids)) {
            return [];
        }

        $db = DB();
        $uploads = array_fill_keys($ids, null);

        $q = $db->query("SELECT * FROM uploads WHERE random_id IN('".implode('\',\'', array_map([$db, 'escape'], $ids))."')");

        while ($row = $db->fetch($q)) {
            $uploads[$row['random_id']] = new Upload($row);
        }

        if ($flat) {
            $list = [];
            foreach ($ids as $id) {
                $list[] = $uploads[$id];
            }
            unset($uploads);
            return $list;
        }

        return $uploads;
    }

    static function getUploadByRandomId(string $random_id): ?Upload {
        $db = DB();
        $q = $db->query("SELECT * FROM uploads WHERE random_id=? LIMIT 1", $random_id);
        if ($db->numRows($q)) {
            return new Upload($db->fetch($q));
        } else {
            return null;
        }
    }

    static function _getNewUploadRandomId(): string {
        $db = DB();
        do {
            $random_id = strgen(8);
        } while ($db->numRows($db->query("SELECT id FROM uploads WHERE random_id=?", $random_id)) > 0);
        return $random_id;
    }   

}


class Upload extends model {

    const DB_TABLE = 'uploads';

    public static array $ImageExtensions = ['jpg', 'jpeg', 'png', 'gif'];
    public static array $VideoExtensions = ['mp4', 'ogg'];

    public int $id;
    public string $randomId;
    public int $ts;
    public string $name;
    public int $size;
    public int $downloads;
    public int $image; // TODO: remove
    public int $imageW;
    public int $imageH;
    public string $note;

    function getDirectory(): string {
        global $config;
        return $config['uploads_dir'].'/'.$this->randomId;
    }

    function getDirectUrl(): string {
        global $config;
        return 'https://'.$config['uploads_host'].'/'.$this->randomId.'/'.$this->name;
    }

    function getDirectPreviewUrl(int $w, int $h, bool $retina = false): string {
        global $config;
        if ($w == $this->imageW && $this->imageH == $h)
            return $this->getDirectUrl();

        if ($retina) {
            $w *= 2;
            $h *= 2;
        }

        $prefix = $this->imageMayHaveAlphaChannel() ? 'a' : 'p';
        return 'https://'.$config['uploads_host'].'/'.$this->randomId.'/'.$prefix.$w.'x'.$h.'.jpg';
    }

    // TODO remove?
    function incrementDownloads() {
        $db = DB();
        $db->query("UPDATE uploads SET downloads=downloads+1 WHERE id=?", $this->id);
        $this->downloads++;
    }

    function getSize(): string {
        return sizeString($this->size);
    }

    function getMarkdown(): string {
        if ($this->isImage()) {
            $md = '{image:'.$this->randomId.',w='.$this->imageW.',h='.$this->imageH.'}{/image}';
        } else if ($this->isVideo()) {
            $md = '{video:'.$this->randomId.'}{/video}';
        } else {
            $md = '{fileAttach:'.$this->randomId.'}{/fileAttach}';
        }
        $md .= ' <!-- '.$this->name.' -->';
        return $md;
    }

    function setNote(string $note) {
        $db = DB();
        $db->query("UPDATE uploads SET note=? WHERE id=?", $note, $this->id);
    }

    function isImage(): bool {
        return in_array(extension($this->name), self::$ImageExtensions);
    }

    // assume all png images have alpha channel
    // i know this is wrong, but anyway
    function imageMayHaveAlphaChannel(): bool {
        return strtolower(extension($this->name)) == 'png';
    }

    function isVideo(): bool {
        return in_array(extension($this->name), self::$VideoExtensions);
    }

    function getImageRatio(): float {
        return $this->imageW / $this->imageH;
    }

    function getImagePreviewSize(?int $w = null, ?int $h = null): array {
        if (is_null($w) && is_null($h))
            throw new Exception(__METHOD__.': both width and height can\'t be null');

        if (is_null($h))
            $h = round($w / $this->getImageRatio());

        if (is_null($w))
            $w = round($h * $this->getImageRatio());

        return [$w, $h];
    }

    function createImagePreview(?int $w = null,
                                       ?int $h = null,
                                       bool $force_update = false,
                                       bool $may_have_alpha = false): bool {
        global $config;

        $orig = $config['uploads_dir'].'/'.$this->randomId.'/'.$this->name;
        $updated = false;

        foreach (themes::getThemes() as $theme) {
            if (!$may_have_alpha && $theme == 'dark')
                continue;

            for ($mult = 1; $mult <= 2; $mult++) {
                $dw = $w * $mult;
                $dh = $h * $mult;

                $prefix = $may_have_alpha ? 'a' : 'p';
                $dst = $config['uploads_dir'].'/'.$this->randomId.'/'.$prefix.$dw.'x'.$dh.($theme == 'dark' ? '_dark' : '').'.jpg';

                if (file_exists($dst)) {
                    if (!$force_update)
                        continue;
                    unlink($dst);
                }

                $img = imageopen($orig);
                imageresize($img, $dw, $dh, themes::getThemeAlphaColorAsRGB($theme));
                imagejpeg($img, $dst, $mult == 1 ? 93 : 67);
                imagedestroy($img);

                setperm($dst);
                $updated = true;
            }
        }

        return $updated;
    }

    /**
     * @return int  Number of deleted files
     */
    function deleteAllImagePreviews(): int {
        global $config;
        $dir = $config['uploads_dir'].'/'.$this->randomId;
        $files = scandir($dir);
        $deleted = 0;
        foreach ($files as $f) {
            if (preg_match('/^[ap](\d+)x(\d+)(?:_dark)?\.jpg$/', $f)) {
                if (is_file($dir.'/'.$f))
                    unlink($dir.'/'.$f);
                else
                    logError(__METHOD__.': '.$dir.'/'.$f.' is not a file!');
                $deleted++;
            }
        }
        return $deleted;
    }

}