summaryrefslogtreecommitdiff
path: root/lib/file.php
blob: fc3e38a49f9e2c326a540cf3216ecee791549c8b (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
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/../config.php';

function verify_mimetype(string $file_path, string $mimetype): bool
{
    $path = escapeshellarg($file_path);

    if (str_starts_with($mimetype, 'image/')) {
        $output = shell_exec("identify -quiet -ping $path");
        return !empty($output);
    } else if (str_starts_with($mimetype, 'video/') || str_starts_with($mimetype, 'audio/')) {
        $output = [];
        $exitCode = 0;
        $cmd = "ffprobe -v error -i $path 2>&1";
        exec($cmd, $output, $exitCode);
        return $exitCode === 0;
    }

    throw new RuntimeException("Illegal type for MIME verifications: $mimetype");
}

function delete_file(string $file_id, string $file_extension, PDO|null $db = null): bool
{
    $paths = [
        FILE_UPLOAD_DIRECTORY . "/{$file_id}.{$file_extension}",
        FILE_THUMBNAIL_DIRECTORY . "/{$file_id}.webp"
    ];

    foreach ($paths as $path) {
        if (is_file($path) && !unlink($path)) {
            return false;
        }
    }

    if ($db) {
        $db->prepare('DELETE FROM files WHERE id = ? AND extension = ?')->execute([$file_id, $file_extension]);
    }

    return true;
}

function strip_exif(string $file_path)
{
    $file_path = escapeshellarg($file_path);
    $output = shell_exec("exiftool -q -EXIF= $file_path $file_path");
    return empty($output);
}