|
| 1 | +<?php |
| 2 | + |
| 3 | +header("Access-Control-Allow-Origin: *"); |
| 4 | + |
| 5 | +$pdo = new PDO("mysql:dbname=" . getenv('DB_NAME') . ";host=" . getenv('DB_HOST'), getenv('DB_USER'), getenv('DB_PASSWORD')); |
| 6 | +$method = $_SERVER['REQUEST_METHOD']; |
| 7 | +$slug = $_GET['slug'] ?? null; |
| 8 | +$dispatchCountOn = 50; |
| 9 | +$ip = $_SERVER["REMOTE_ADDR"]; |
| 10 | + |
| 11 | +if ($slug === null) { |
| 12 | + die; |
| 13 | +} |
| 14 | + |
| 15 | +if ($method === 'GET') { |
| 16 | + $query = $pdo->prepare('SELECT SUM(count) as count, position FROM votes WHERE slug = ? GROUP BY position'); |
| 17 | + $query->execute([$slug]); |
| 18 | + $result = $query->fetchAll(PDO::FETCH_ASSOC); |
| 19 | + |
| 20 | + echo json_encode($result); |
| 21 | + return; |
| 22 | +} |
| 23 | + |
| 24 | +if ($method === 'POST') { |
| 25 | + $position = $_POST['position'] ?? null; |
| 26 | + |
| 27 | + if ($position === null) { |
| 28 | + die; |
| 29 | + } |
| 30 | + |
| 31 | + $hashedIp = sha1($ip); |
| 32 | + $query = $pdo->prepare('SELECT * FROM logs WHERE ip = ?'); |
| 33 | + $query->execute([$hashedIp]); |
| 34 | + |
| 35 | + $result = $query->fetch(PDO::FETCH_ASSOC); |
| 36 | + |
| 37 | + if ($result === false) { |
| 38 | + $query = $pdo->prepare('INSERT INTO logs (ip, slugs) VALUES (?, ?);'); |
| 39 | + $query->execute([$hashedIp, json_encode([$slug])]); |
| 40 | + |
| 41 | + insertVote($pdo, $slug, $position, $dispatchCountOn); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + $alreadyVotedFor = json_decode($result['slugs'], true); |
| 46 | + $found = in_array($slug, $alreadyVotedFor); |
| 47 | + |
| 48 | + if (!$found) { |
| 49 | + array_push($alreadyVotedFor, $slug); |
| 50 | + |
| 51 | + insertVote($pdo, $slug, $position, $dispatchCountOn); |
| 52 | + $query = $pdo->prepare('UPDATE logs SET slugs = ? WHERE ip = ?;'); |
| 53 | + $query->execute([ |
| 54 | + json_encode($alreadyVotedFor), |
| 55 | + $hashedIp |
| 56 | + ]); |
| 57 | + } |
| 58 | + |
| 59 | + return; |
| 60 | +} |
| 61 | + |
| 62 | +function insertVote(PDO $pdo, string $slug, int $position, int $dispatchCountOn) |
| 63 | +{ |
| 64 | + $query = $pdo->prepare('INSERT INTO votes (slug, slot, count, position) VALUES (?, RAND() * '. $dispatchCountOn .', 1, ?) ON DUPLICATE KEY UPDATE count = count + 1;'); |
| 65 | + $query->execute([$slug, $position]); |
| 66 | +} |
0 commit comments