-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathchat.php
More file actions
306 lines (245 loc) · 9.21 KB
/
chat.php
File metadata and controls
306 lines (245 loc) · 9.21 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
<?php
require_once 'config.php';
// Get or create chat between two users
function getOrCreateChat($user1Id, $user2Id) {
$pdo = getDB();
// Ensure user1Id is always smaller for consistency
if ($user1Id > $user2Id) {
list($user1Id, $user2Id) = [$user2Id, $user1Id];
}
// Check if chat exists
$stmt = $pdo->prepare("SELECT id FROM chats WHERE user1_id = ? AND user2_id = ?");
$stmt->execute([$user1Id, $user2Id]);
$chat = $stmt->fetch();
if ($chat) {
return $chat['id'];
}
// Create new chat
$stmt = $pdo->prepare("INSERT INTO chats (user1_id, user2_id) VALUES (?, ?)");
$stmt->execute([$user1Id, $user2Id]);
return $pdo->lastInsertId();
}
// Get all chats for a user
function getUserChats($userId) {
$pdo = getDB();
$stmt = $pdo->prepare("
SELECT
c.id AS chat_id,
c.updated_at,
CASE
WHEN c.user1_id = ? THEN c.user2_id
ELSE c.user1_id
END AS other_user_id,
u.username,
u.display_name,
u.avatar,
u.is_online,
u.last_seen,
(SELECT message FROM messages WHERE chat_id = c.id ORDER BY created_at DESC LIMIT 1) AS last_message,
(SELECT message_type FROM messages WHERE chat_id = c.id ORDER BY created_at DESC LIMIT 1) AS last_message_type,
(SELECT created_at FROM messages WHERE chat_id = c.id ORDER BY created_at DESC LIMIT 1) AS last_message_time,
(SELECT COUNT(*) FROM messages WHERE chat_id = c.id AND receiver_id = ? AND is_read = 0) AS unread_count
FROM chats c
INNER JOIN users u ON u.id = CASE
WHEN c.user1_id = ? THEN c.user2_id
ELSE c.user1_id
END
WHERE c.user1_id = ? OR c.user2_id = ?
ORDER BY c.updated_at DESC
");
$stmt->execute([$userId, $userId, $userId, $userId, $userId]);
return $stmt->fetchAll();
}
// Send message
function sendMessage($chatId, $senderId, $receiverId, $message, $messageType = 'text', $filePath = null, $fileName = null, $fileSize = null, $selfDestructTimer = null) {
$pdo = getDB();
// Calculate destruct time if timer is set
$destructAt = null;
if ($selfDestructTimer) {
$destructAt = date('Y-m-d H:i:s', time() + $selfDestructTimer);
}
$stmt = $pdo->prepare("
INSERT INTO messages (chat_id, sender_id, receiver_id, message, message_type, file_path, file_name, file_size, self_destruct_timer, destruct_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$chatId,
$senderId,
$receiverId,
$message,
$messageType,
$filePath,
$fileName,
$fileSize,
$selfDestructTimer,
$destructAt
]);
$messageId = $pdo->lastInsertId();
// Update chat timestamp
$stmt = $pdo->prepare("UPDATE chats SET updated_at = NOW() WHERE id = ?");
$stmt->execute([$chatId]);
return $messageId;
}
// Get messages for a chat
function getChatMessages($chatId, $userId, $limit = 50, $offset = 0) {
$pdo = getDB();
$stmt = $pdo->prepare("
SELECT
m.*,
s.username AS sender_username,
s.display_name AS sender_display_name,
s.avatar AS sender_avatar
FROM messages m
INNER JOIN users s ON s.id = m.sender_id
WHERE m.chat_id = ?
ORDER BY m.created_at DESC
LIMIT ? OFFSET ?
");
$stmt->execute([$chatId, $limit, $offset]);
$messages = $stmt->fetchAll();
// Mark messages as read
$stmt = $pdo->prepare("UPDATE messages SET is_read = 1 WHERE chat_id = ? AND receiver_id = ? AND is_read = 0");
$stmt->execute([$chatId, $userId]);
return array_reverse($messages);
}
// Get new messages (for polling)
function getNewMessages($chatId, $lastMessageId, $userId) {
$pdo = getDB();
$stmt = $pdo->prepare("
SELECT
m.*,
s.username AS sender_username,
s.display_name AS sender_display_name,
s.avatar AS sender_avatar
FROM messages m
INNER JOIN users s ON s.id = m.sender_id
WHERE m.chat_id = ? AND m.id > ?
ORDER BY m.created_at ASC
");
$stmt->execute([$chatId, $lastMessageId]);
$messages = $stmt->fetchAll();
// Mark new messages as read
if (!empty($messages)) {
$stmt = $pdo->prepare("UPDATE messages SET is_read = 1 WHERE chat_id = ? AND receiver_id = ? AND id > ? AND is_read = 0");
$stmt->execute([$chatId, $userId, $lastMessageId]);
}
return $messages;
}
// Delete message (single side or both)
function deleteMessage($messageId, $userId) {
$pdo = getDB();
// Get message details
$stmt = $pdo->prepare("SELECT * FROM messages WHERE id = ?");
$stmt->execute([$messageId]);
$message = $stmt->fetch();
if (!$message) {
return false;
}
// Delete file if exists
if ($message['file_path']) {
$filePath = UPLOAD_DIR . '/' . $message['file_path'];
if (file_exists($filePath)) {
unlink($filePath);
}
// Delete file storage record
$stmt = $pdo->prepare("DELETE FROM file_storage WHERE message_id = ?");
$stmt->execute([$messageId]);
}
// Delete message
$stmt = $pdo->prepare("DELETE FROM messages WHERE id = ?");
$stmt->execute([$messageId]);
// Log deletion
$stmt = $pdo->prepare("INSERT INTO deleted_logs (message_id, deleted_by, deletion_type) VALUES (?, ?, 'message')");
$stmt->execute([$messageId, $userId]);
return true;
}
// Delete entire chat (both sides)
function deleteChat($chatId, $userId) {
$pdo = getDB();
// Get all messages with files
$stmt = $pdo->prepare("SELECT id, file_path FROM messages WHERE chat_id = ? AND file_path IS NOT NULL");
$stmt->execute([$chatId]);
$messages = $stmt->fetchAll();
// Delete all files
foreach ($messages as $message) {
$filePath = UPLOAD_DIR . '/' . $message['file_path'];
if (file_exists($filePath)) {
unlink($filePath);
}
}
// Delete file storage records
$stmt = $pdo->prepare("DELETE FROM file_storage WHERE message_id IN (SELECT id FROM messages WHERE chat_id = ?)");
$stmt->execute([$chatId]);
// Delete all messages
$stmt = $pdo->prepare("DELETE FROM messages WHERE chat_id = ?");
$stmt->execute([$chatId]);
// Delete chat
$stmt = $pdo->prepare("DELETE FROM chats WHERE id = ?");
$stmt->execute([$chatId]);
// Log deletion
$stmt = $pdo->prepare("INSERT INTO deleted_logs (chat_id, deleted_by, deletion_type) VALUES (?, ?, 'chat')");
$stmt->execute([$chatId, $userId]);
return true;
}
// Auto-delete expired messages (run via CRON)
function cleanupExpiredMessages() {
$pdo = getDB();
// Get expired messages
$stmt = $pdo->query("SELECT id, file_path FROM messages WHERE destruct_at IS NOT NULL AND destruct_at <= NOW()");
$messages = $stmt->fetchAll();
foreach ($messages as $message) {
// Delete file if exists
if ($message['file_path']) {
$filePath = UPLOAD_DIR . '/' . $message['file_path'];
if (file_exists($filePath)) {
unlink($filePath);
}
}
// Delete message
$stmt = $pdo->prepare("DELETE FROM messages WHERE id = ?");
$stmt->execute([$message['id']]);
// Log deletion
$stmt = $pdo->prepare("INSERT INTO deleted_logs (message_id, deleted_by, deletion_type) VALUES (?, 0, 'auto_destruct')");
$stmt->execute([$message['id']]);
}
// Clean up file tokens
$stmt = $pdo->query("DELETE FROM file_tokens WHERE expires_at <= NOW()");
return count($messages);
}
// Set typing status
function setTypingStatus($chatId, $userId, $isTyping) {
$pdo = getDB();
$stmt = $pdo->prepare("
INSERT INTO typing_status (chat_id, user_id, is_typing)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE is_typing = ?, updated_at = NOW()
");
$stmt->execute([$chatId, $userId, $isTyping ? 1 : 0, $isTyping ? 1 : 0]);
}
// Get typing status
function getTypingStatus($chatId, $otherUserId) {
$pdo = getDB();
$stmt = $pdo->prepare("
SELECT is_typing
FROM typing_status
WHERE chat_id = ? AND user_id = ? AND updated_at >= DATE_SUB(NOW(), INTERVAL 5 SECOND)
");
$stmt->execute([$chatId, $otherUserId]);
$result = $stmt->fetch();
return $result ? (bool)$result['is_typing'] : false;
}
// Get unread message count for user
function getUnreadCount($userId) {
$pdo = getDB();
$stmt = $pdo->prepare("SELECT COUNT(*) as count FROM messages WHERE receiver_id = ? AND is_read = 0");
$stmt->execute([$userId]);
$result = $stmt->fetch();
return $result['count'];
}
// Check if user has access to chat
function userHasAccessToChat($chatId, $userId) {
$pdo = getDB();
$stmt = $pdo->prepare("SELECT id FROM chats WHERE id = ? AND (user1_id = ? OR user2_id = ?)");
$stmt->execute([$chatId, $userId, $userId]);
return $stmt->fetch() !== false;
}