-
Notifications
You must be signed in to change notification settings - Fork 16
/
interact_chirp.php
executable file
·80 lines (68 loc) · 2.76 KB
/
interact_chirp.php
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
<?php
session_start();
header('Content-Type: application/json');
// Check if user is signed in
if (!isset($_SESSION['user_id'])) {
echo json_encode(['success' => false, 'error' => 'not_signed_in']);
exit;
}
try {
// Connect to the SQLite database
$db = new PDO('sqlite:' . __DIR__ . '/../chirp.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Decode JSON input
$data = json_decode(file_get_contents('php://input'), true);
// Validate input data
if (empty($data['chirpId']) || empty($data['action'])) {
echo json_encode(['success' => false, 'error' => 'missing_data']);
exit;
}
// Sanitize and validate inputs
$chirpId = (int) $data['chirpId'];
$action = strtolower($data['action']);
$userId = $_SESSION['user_id'];
// Validate action and restrict table names
$validActions = ['like' => 'likes', 'rechirp' => 'rechirps'];
if (!array_key_exists($action, $validActions)) {
echo json_encode(['success' => false, 'error' => 'invalid_action']);
exit;
}
$table = $validActions[$action];
// Check if the user has already interacted
$stmt = $db->prepare("SELECT COUNT(*) FROM $table WHERE chirp_id = :chirpId AND user_id = :userId");
$stmt->bindParam(':chirpId', $chirpId, PDO::PARAM_INT);
$stmt->bindParam(':userId', $userId, PDO::PARAM_INT);
$stmt->execute();
$exists = $stmt->fetchColumn() > 0;
if ($exists) {
// Remove the user's interaction
$stmt = $db->prepare("DELETE FROM $table WHERE chirp_id = :chirpId AND user_id = :userId");
$stmt->bindParam(':chirpId', $chirpId, PDO::PARAM_INT);
$stmt->bindParam(':userId', $userId, PDO::PARAM_INT);
$stmt->execute();
$status = false;
} else {
// Add the user's interaction with current timestamp
$stmt = $db->prepare("INSERT INTO $table (chirp_id, user_id, timestamp) VALUES (:chirpId, :userId, :timestamp)");
$stmt->bindParam(':chirpId', $chirpId, PDO::PARAM_INT);
$stmt->bindParam(':userId', $userId, PDO::PARAM_INT);
$stmt->bindParam(':timestamp', time(), PDO::PARAM_INT);
$stmt->execute();
$status = true;
}
// Fetch updated count
$stmt = $db->prepare("SELECT COUNT(*) FROM $table WHERE chirp_id = :chirpId");
$stmt->bindParam(':chirpId', $chirpId, PDO::PARAM_INT);
$stmt->execute();
$count = $stmt->fetchColumn();
// Prepare response
$response = [
'success' => true,
$action => $status,
$action . '_count' => (int) $count
];
echo json_encode($response);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>