summaryrefslogtreecommitdiff
path: root/emotes/rate.php
blob: 2e862f9a50c99718852a2b3626a86dba040fbbfc (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
<?php
include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/alert.php";
include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/utils.php";
include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/config.php";
include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/accounts.php";

if (!CONFIG['rating']['enable']) {
    generate_alert("/404.php", "Emote ratings are disabled", 403);
    exit;
}

if (!authorize_user(true)) {
    exit;
}

if (isset($_SESSION["user_role"]) && !$_SESSION["user_role"]["permission_rate"]) {
    generate_alert("/404.php", "Not enough permissions", 403);
    exit;
}

$id = str_safe($_POST["id"] ?? "0", 32);
$rate = intval(str_safe($_POST["rate"] ?? "0", 2));

if ($id == 0 || $rate == 0) {
    generate_alert("/emotes" . (isset($_POST["id"]) ? "?id=" . $_POST["id"] : ""), "Not enough POST fields");
    exit;
}

$db = new PDO(CONFIG['database']['url'], CONFIG['database']['user'], CONFIG['database']['pass']);

// checking if emote exists
$stmt = $db->prepare("SELECT id FROM emotes WHERE id = ?");
$stmt->execute([$id]);
if ($stmt->rowCount() != 1) {
    generate_alert("/emotes", "Emote ID $id does not exist", 404);
    exit;
}

// checking if user has already given a rate
$stmt = $db->prepare("SELECT id FROM ratings WHERE user_id = ? AND emote_id = ?");
$stmt->execute([$_SESSION["user_id"], $id]);
if ($stmt->rowCount() != 0) {
    generate_alert("/emotes?id=$id", "You have already given a rate for this emote!", 403);
    exit;
}

// giving a rate
$stmt = $db->prepare("INSERT INTO ratings(user_id, emote_id, rate) VALUES (?, ?, ?)");
$stmt->execute([$_SESSION["user_id"], $id, clamp($rate, -2, 2)]);

if (CLIENT_REQUIRES_JSON) {
    $stmt = $db->prepare("SELECT * FROM ratings WHERE id = ?");
    $stmt->execute([$db->lastInsertId()]);

    json_response([
        "status_code" => 200,
        "message" => "Rated!",
        "data" => $stmt->fetch(PDO::FETCH_ASSOC)
    ]);
    exit;
}

generate_alert("/emotes?id=$id", "Rated!", 200);