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

session_start();

if (!FILE_DELETION) {
    generate_alert(
        '/',
        "File deletion is not allowed",
        403
    );
    exit();
}

$file_id = $_GET['f'] ?? null;
$password = $_GET['key'] ?? null;

if (!isset($file_id)) {
    generate_alert(
        '/',
        "File ID must be set!",
        400
    );
    exit();
}

$file_id = explode('.', $file_id);
$file_ext = $file_id[1];
$file_id = $file_id[0];

if (!preg_match('/^[a-zA-Z0-9_-]+$/', $file_id) || !preg_match('/^[a-zA-Z0-9]+$/', $file_ext)) {
    generate_alert(
        '/',
        "Invalid file ID or extension",
        400
    );
    exit();
}

$db = new PDO(DB_URL, DB_USER, DB_PASS);
$stmt = $db->prepare('SELECT password FROM files WHERE id = ? AND extension = ?');
$stmt->execute([$file_id, $file_ext]);

$file = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

if (!$file) {
    generate_alert(
        "/",
        "File $file_id not found",
        404
    );
    exit();
}

if (!isset($_SESSION['is_moderator']) && !isset($file['password'])) {
    generate_alert(
        "/$file_id.$file_ext",
        "File $file_id does not have a password. File cannot be deleted!",
        400
    );
    exit();
}

if (!isset($_SESSION['is_moderator']) && !isset($password)) {
    generate_alert(
        "/$file_id.$file_ext",
        "Field 'key' must be set!",
        400
    );
    exit();
}

if (!isset($_SESSION['is_moderator']) && !password_verify($password, $file['password'])) {
    generate_alert(
        "/$file_id.$file_ext",
        'Unauthorized',
        401
    );
    exit();
}

if (!delete_file($file_id, $file_ext, $db)) {
    generate_alert(
        "/$file_id.$file_ext",
        'Failed to remove files. Try again later',
        500
    );
    exit();
}

generate_alert(
    $_GET['r'] ?? '/',
    'Successfully deleted the file',
    200,
    [
        'id' => $file_id,
        'extension' => $file_ext
    ]
);