-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
1949 lines (1647 loc) · 71.1 KB
/
api.php
File metadata and controls
1949 lines (1647 loc) · 71.1 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// Comment System API
// Load config.php if it exists, otherwise use defaults
if (file_exists(__DIR__ . '/config.php')) {
require_once 'config.php';
}
// Define constants if not already defined by config.php
if (!defined('DB_PATH')) {
// Auto-detect environment
$isLocalhost = false;
if (getenv('COMMENT_ENV') === 'development') {
$isLocalhost = true;
} elseif (isset($_SERVER['HTTP_HOST'])) {
$host = $_SERVER['HTTP_HOST'];
$isLocalhost = (
strpos($host, 'localhost') !== false ||
strpos($host, '127.0.0.1') !== false ||
strpos($host, '.local') !== false ||
strpos($host, ':1313') !== false
);
} elseif (php_sapi_name() === 'cli-server') {
$isLocalhost = true;
}
define('DB_PATH', __DIR__ . ($isLocalhost ? '/db/comments-dev.db' : '/db/comments.db'));
}
if (!defined('ADMIN_TOKEN_COOKIE')) {
define('ADMIN_TOKEN_COOKIE', 'comment_admin_token');
}
if (!defined('SESSION_LIFETIME')) {
define('SESSION_LIFETIME', 3600 * 24 * 30); // 30 days
}
if (!defined('ALLOWED_ORIGINS')) {
// Default CORS - allow all origins (can be restricted in config.php)
define('ALLOWED_ORIGINS', ['*']);
}
// Set timezone if not already set
if (!ini_get('date.timezone')) {
date_default_timezone_set('UTC');
}
// Error logging setup
if (!ini_get('error_log')) {
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
$logsDir = __DIR__ . '/logs';
if (!is_dir($logsDir)) {
@mkdir($logsDir, 0755, true);
}
ini_set('error_log', $logsDir . '/php-errors.log');
}
require_once 'database.php';
header('Content-Type: application/json');
// Security headers
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'");
// Cache control - prevent caching of API responses
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Expires: 0');
// CORS headers
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array('*', ALLOWED_ORIGINS) || in_array($origin, ALLOWED_ORIGINS)) {
if (in_array('*', ALLOWED_ORIGINS)) {
header("Access-Control-Allow-Origin: *");
} else {
header("Access-Control-Allow-Origin: $origin");
header('Access-Control-Allow-Credentials: true');
}
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
}
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
$db = getDatabase();
if (!$db) {
http_response_code(500);
echo json_encode(['error' => 'Database connection failed']);
exit;
}
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
// Periodic housekeeping: prune rows that are no longer useful.
// Runs on ~1% of requests to avoid adding overhead to every call.
function periodicCleanup($db) {
// vote_log is only used for rate-limiting within a 60-second window
$db->exec("DELETE FROM vote_log WHERE created_at < datetime('now', '-2 hours')");
// login_attempts are checked within a 1-hour window
$db->exec("DELETE FROM login_attempts WHERE attempted_at < datetime('now', '-2 hours')");
// expired sessions
$db->exec("DELETE FROM sessions WHERE expires_at < datetime('now')");
// processed/failed email queue entries older than 30 days
if (tableExists($db, 'email_queue')) {
$db->exec("DELETE FROM email_queue WHERE status IN ('sent','failed') AND created_at < datetime('now', '-30 days')");
}
}
if (rand(1, 100) === 1) {
periodicCleanup($db);
}
function jsonResponse($data, $code = 200) {
http_response_code($code);
echo json_encode($data);
exit;
}
function getInput() {
return json_decode(file_get_contents('php://input'), true) ?? [];
}
function validateEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
function sanitizeUrl($url) {
if (empty($url)) return null;
return filter_var($url, FILTER_VALIDATE_URL) ? $url : null;
}
function isAdmin() {
if (isset($_COOKIE[ADMIN_TOKEN_COOKIE])) {
$token = $_COOKIE[ADMIN_TOKEN_COOKIE];
$db = getDatabase();
// Check if session exists and is not expired
$stmt = $db->prepare("
SELECT id FROM sessions
WHERE token = ? AND expires_at > datetime('now')
");
$stmt->execute([$token]);
$session = $stmt->fetch();
if ($session) {
// Update last activity timestamp
$updateStmt = $db->prepare("
UPDATE sessions SET last_activity = datetime('now') WHERE id = ?
");
$updateStmt->execute([$session['id']]);
return true;
}
// Fallback to old token system for backward compatibility
$stmt = $db->prepare("SELECT value FROM settings WHERE key = 'admin_token'");
$stmt->execute();
$result = $stmt->fetch();
return $result && hash_equals($result['value'], $token);
}
return false;
}
function generateCSRFToken() {
if (!isset($_COOKIE['csrf_token'])) {
$token = bin2hex(random_bytes(32));
$isSecure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443;
setcookie('csrf_token', $token, time() + SESSION_LIFETIME, '/comments/', '', $isSecure, false); // Not HTTPOnly - JS needs to read it
return $token;
}
return $_COOKIE['csrf_token'];
}
function validateCSRFToken($token) {
return isset($_COOKIE['csrf_token']) && hash_equals($_COOKIE['csrf_token'], $token);
}
function checkRateLimit($ipAddress, $email) {
// Skip rate limiting for logged-in admins (for testing)
if (isAdmin()) {
return ['limited' => false];
}
$db = getDatabase();
// Check IP-based rate limiting (5 comments per hour)
$stmt = $db->prepare("
SELECT COUNT(*) as count FROM comments
WHERE ip_address = ? AND created_at > datetime('now', '-1 hour')
");
$stmt->execute([$ipAddress]);
$result = $stmt->fetch();
if ($result['count'] >= 5) {
return ['limited' => true, 'reason' => 'Too many comments from your IP address. Please try again later.'];
}
// Check email-based rate limiting (3 comments per 10 minutes)
$stmt = $db->prepare("
SELECT COUNT(*) as count FROM comments
WHERE author_email = ? AND created_at > datetime('now', '-10 minutes')
");
$stmt->execute([$email]);
$result = $stmt->fetch();
if ($result['count'] >= 3) {
return ['limited' => true, 'reason' => 'Too many comments in a short time. Please wait a few minutes.'];
}
return ['limited' => false];
}
function detectSpam($content, $authorName, $authorEmail, $authorUrl) {
$spamScore = 0;
// Check for excessive links
$linkCount = preg_match_all('/(https?:\/\/|www\.)/i', $content);
if ($linkCount > 3) {
$spamScore += 2;
}
// Check for common spam keywords
$spamKeywords = ['viagra', 'cialis', 'pharmacy', 'poker', 'casino', 'loan', 'mortgage', 'seo services', 'buy now'];
foreach ($spamKeywords as $keyword) {
if (stripos($content, $keyword) !== false || stripos($authorName, $keyword) !== false) {
$spamScore += 3;
}
}
// Check for excessive capitalization
if (preg_match('/[A-Z]{10,}/', $content)) {
$spamScore += 1;
}
// Check for suspicious email domains
$suspiciousDomains = ['example.com', 'test.com', 'tempmail', 'disposable'];
foreach ($suspiciousDomains as $domain) {
if (stripos($authorEmail, $domain) !== false) {
$spamScore += 1;
}
}
// Check content length (too short or too long)
$contentLength = strlen($content);
if ($contentLength < 10) {
$spamScore += 1;
}
if ($contentLength > 4000) {
$spamScore += 1;
}
// If spam score is high, auto-mark as spam
return $spamScore >= 4;
}
function sanitizeEmailContent($input) {
// Remove characters that could be used for email header injection
// Strip newlines, carriage returns, and URL-encoded versions
return str_replace(["\r", "\n", "%0a", "%0d", "\x0A", "\x0D"], '', $input);
}
function queueEmail($commentId, $recipientEmail, $recipientName, $emailType, $subject, $body) {
try {
$db = getDatabase();
if (!$db) {
error_log("Failed to get database connection for email queue");
return false;
}
// Validate email address before queuing
if (!filter_var($recipientEmail, FILTER_VALIDATE_EMAIL)) {
error_log("Invalid email address, not queuing: $recipientEmail");
return false;
}
$stmt = $db->prepare("
INSERT INTO email_queue (comment_id, recipient_email, recipient_name, email_type, subject, body, status)
VALUES (?, ?, ?, ?, ?, ?, 'pending')
");
return $stmt->execute([$commentId, $recipientEmail, $recipientName, $emailType, $subject, $body]);
} catch (PDOException $e) {
error_log("Failed to queue email: " . $e->getMessage());
// Don't throw - just log and return false so comment posting can continue
return false;
}
}
function checkLoginRateLimit($ipAddress) {
$db = getDatabase();
// Allow 5 login attempts per hour per IP
$stmt = $db->prepare("
SELECT COUNT(*) as count FROM login_attempts
WHERE ip_address = ? AND attempted_at > datetime('now', '-1 hour')
");
$stmt->execute([$ipAddress]);
$result = $stmt->fetch();
if ($result['count'] >= 5) {
return ['limited' => true, 'reason' => 'Too many login attempts. Please try again later.'];
}
return ['limited' => false];
}
function recordLoginAttempt($ipAddress, $success) {
$db = getDatabase();
$stmt = $db->prepare("
INSERT INTO login_attempts (ip_address, success, attempted_at)
VALUES (?, ?, datetime('now'))
");
return $stmt->execute([$ipAddress, $success ? 1 : 0]);
}
function sendNotificationEmail($commentId, $pageUrl, $parentId, $authorName, $content, $authorEmail) {
$db = getDatabase();
// Check if notifications are enabled
$stmt = $db->prepare("SELECT value FROM settings WHERE key = 'enable_notifications'");
$stmt->execute();
$result = $stmt->fetch();
if (!$result || $result['value'] !== 'true') {
return; // Notifications disabled
}
// Sanitize all user input to prevent email header injection
$safeAuthorName = sanitizeEmailContent($authorName);
$safeContent = sanitizeEmailContent($content);
$safePageUrl = sanitizeEmailContent($pageUrl);
// Track who has been notified to prevent duplicates
$notifiedEmails = [];
// If this is a reply, notify the parent comment author first with personalized message
if ($parentId !== null) {
$stmt = $db->prepare("SELECT author_email, author_name FROM comments WHERE id = ?");
$stmt->execute([$parentId]);
$parent = $stmt->fetch();
if ($parent && $parent['author_email'] && $parent['author_email'] !== $authorEmail) {
$safeParentName = sanitizeEmailContent($parent['author_name']);
// Get unsubscribe token for parent
$stmt = $db->prepare("SELECT token FROM subscriptions WHERE page_url = ? AND email = ?");
$stmt->execute([$pageUrl, $parent['author_email']]);
$subData = $stmt->fetch();
$unsubscribeUrl = $subData ? "https://" . $_SERVER['HTTP_HOST'] . "/comments/unsubscribe.php?token=" . $subData['token'] : "";
$subject = "New reply to your comment";
$message = "Hello {$safeParentName},\n\n";
$message .= "{$safeAuthorName} replied to your comment on {$safePageUrl}:\n\n";
$message .= "{$safeContent}\n\n";
$message .= "View and reply: {$safePageUrl}#comment-{$commentId}\n\n";
if ($unsubscribeUrl) {
$message .= "---\n";
$message .= "To unsubscribe from notifications: {$unsubscribeUrl}\n";
}
// Queue email instead of sending immediately
queueEmail($commentId, $parent['author_email'], $safeParentName, 'parent_reply', $subject, $message);
// Mark this email as notified
$notifiedEmails[] = $parent['author_email'];
}
}
// Get all active subscribers for this page (excluding the comment author and those already notified)
$stmt = $db->prepare("
SELECT email, token FROM subscriptions
WHERE page_url = ? AND active = 1 AND email != ?
");
$stmt->execute([$pageUrl, $authorEmail]);
$subscribers = $stmt->fetchAll();
// Queue notification emails to all subscribers who haven't been notified yet
foreach ($subscribers as $subscriber) {
// Skip if already notified
if (in_array($subscriber['email'], $notifiedEmails)) {
continue;
}
$unsubscribeUrl = "https://" . $_SERVER['HTTP_HOST'] . "/comments/unsubscribe.php?token=" . $subscriber['token'];
$subject = "New comment on " . parse_url($pageUrl, PHP_URL_PATH);
$message = "Hello,\n\n";
$message .= "{$safeAuthorName} posted a new comment on {$safePageUrl}:\n\n";
$message .= "{$safeContent}\n\n";
$message .= "View and reply: {$safePageUrl}#comment-{$commentId}\n\n";
$message .= "---\n";
$message .= "To unsubscribe from notifications for this page: {$unsubscribeUrl}\n";
// Queue email instead of sending immediately
queueEmail($commentId, $subscriber['email'], '', 'subscriber', $subject, $message);
}
// Notify admin of new comment
$stmt = $db->prepare("SELECT value FROM settings WHERE key = 'admin_email'");
$stmt->execute();
$result = $stmt->fetch();
if ($result && !empty($result['value'])) {
$subject = "New comment on your site";
$message = "New comment from {$safeAuthorName} on {$safePageUrl}:\n\n";
$message .= "{$safeContent}\n\n";
$message .= "Manage comments: https://" . $_SERVER['HTTP_HOST'] . "/comments/admin.html\n";
// Queue admin email instead of sending immediately
queueEmail($commentId, $result['value'], 'Admin', 'admin', $subject, $message);
}
}
function sendPostReactionNotificationEmail($pageUrl, $reactionType) {
$db = getDatabase();
// Check if notifications are enabled
$stmt = $db->prepare("SELECT value FROM settings WHERE key = 'enable_notifications'");
$stmt->execute();
$result = $stmt->fetch();
if (!$result || $result['value'] !== 'true') {
return;
}
$stmt = $db->prepare("SELECT value FROM settings WHERE key = 'admin_email'");
$stmt->execute();
$result = $stmt->fetch();
if (!$result || empty($result['value'])) {
return;
}
$adminEmail = $result['value'];
$reactionLabels = [
'heart' => '♥ heart',
'thumbsup' => '👍 thumbs up',
'lightbulb' => '💡 lightbulb',
'funny' => '😄 laugh',
];
$reactionLabel = $reactionLabels[$reactionType] ?? $reactionType;
$fullPageUrl = "https://" . $_SERVER['HTTP_HOST'] . $pageUrl;
$safePageUrl = sanitizeEmailContent($fullPageUrl);
$subject = "New post reaction on your site";
$message = "Someone left a {$reactionLabel} reaction on {$safePageUrl}.\n\n";
$message .= "View post reactions: https://" . $_SERVER['HTTP_HOST'] . "/comments/admin-post-reactions.html\n";
queueEmail(null, $adminEmail, 'Admin', 'post_reaction', $subject, $message);
}
function sendReactionNotificationEmail($commentId, $pageUrl, $authorName, $authorEmail, $reactionType) {
if (empty($authorEmail)) {
return;
}
$db = getDatabase();
// Check if notifications are enabled
$stmt = $db->prepare("SELECT value FROM settings WHERE key = 'enable_notifications'");
$stmt->execute();
$result = $stmt->fetch();
if (!$result || $result['value'] !== 'true') {
return;
}
$reactionLabels = [
'heart' => '♥ heart',
'thumbsup' => '👍 thumbs up',
'lightbulb' => '💡 lightbulb',
'funny' => '😄 laugh',
];
$reactionLabel = $reactionLabels[$reactionType] ?? $reactionType;
$safeAuthorName = sanitizeEmailContent($authorName);
$fullPageUrl = "https://" . $_SERVER['HTTP_HOST'] . $pageUrl;
$safePageUrl = sanitizeEmailContent($fullPageUrl);
// Get unsubscribe token if they have a subscription
$stmt = $db->prepare("SELECT token FROM subscriptions WHERE page_url = ? AND email = ?");
$stmt->execute([$pageUrl, $authorEmail]);
$subData = $stmt->fetch();
$unsubscribeUrl = $subData ? "https://" . $_SERVER['HTTP_HOST'] . "/comments/unsubscribe.php?token=" . $subData['token'] : "";
$subject = "Someone reacted to your comment";
$message = "Hello {$safeAuthorName},\n\n";
$message .= "Someone left a {$reactionLabel} reaction on your comment at {$safePageUrl}.\n\n";
$message .= "View your comment: {$safePageUrl}#comment-{$commentId}\n\n";
if ($unsubscribeUrl) {
$message .= "---\n";
$message .= "To unsubscribe from notifications: {$unsubscribeUrl}\n";
}
queueEmail($commentId, $authorEmail, $safeAuthorName, 'reaction', $subject, $message);
}
// GET /api.php?action=comments&url=...
if ($method === 'GET' && $action === 'comments') {
$pageUrl = $_GET['url'] ?? '';
if (empty($pageUrl)) {
jsonResponse(['error' => 'URL is required'], 400);
}
// Add pagination support to prevent memory overflow with large comment counts
$limit = isset($_GET['limit']) ? min(max(1, (int)$_GET['limit']), 1000) : 500;
$offset = isset($_GET['offset']) ? max(0, (int)$_GET['offset']) : 0;
$status = isAdmin() ? ['pending', 'approved'] : ['approved'];
$placeholders = implode(',', array_fill(0, count($status), '?'));
// Get total count for pagination metadata
$countStmt = $db->prepare("
SELECT COUNT(*) as total FROM comments
WHERE page_url = ? AND status IN ($placeholders)
");
$countStmt->execute(array_merge([$pageUrl], $status));
$countResult = $countStmt->fetch();
$total = $countResult['total'];
$stmt = $db->prepare("
SELECT c.id, c.page_url, c.parent_id, c.author_name, c.author_email, c.author_url,
c.content, c.created_at, c.status,
COALESCE(v.votes_heart, 0) AS votes_heart,
COALESCE(v.votes_thumbsup, 0) AS votes_thumbsup,
COALESCE(v.votes_lightbulb, 0) AS votes_lightbulb,
COALESCE(v.votes_funny, 0) AS votes_funny
FROM comments c
LEFT JOIN (
SELECT comment_id,
SUM(reaction_type = 'heart') AS votes_heart,
SUM(reaction_type = 'thumbsup') AS votes_thumbsup,
SUM(reaction_type = 'lightbulb') AS votes_lightbulb,
SUM(reaction_type = 'funny') AS votes_funny
FROM votes
GROUP BY comment_id
) v ON v.comment_id = c.id
WHERE c.page_url = ? AND c.status IN ($placeholders)
ORDER BY c.created_at ASC
LIMIT ? OFFSET ?
");
$stmt->execute(array_merge([$pageUrl], $status, [$limit, $offset]));
$comments = $stmt->fetchAll();
// Build threaded structure
$threaded = [];
$lookup = [];
foreach ($comments as $comment) {
$comment['replies'] = [];
// Don't expose email to non-admins
if (!isAdmin()) {
unset($comment['author_email']);
}
$lookup[$comment['id']] = $comment;
}
foreach ($lookup as $id => $comment) {
if ($comment['parent_id'] === null) {
$threaded[] = &$lookup[$id];
} else if (isset($lookup[$comment['parent_id']])) {
$lookup[$comment['parent_id']]['replies'][] = &$lookup[$id];
}
}
// Fetch post-level reaction counts for this page (single query)
$postReactions = ['heart' => 0, 'thumbsup' => 0, 'lightbulb' => 0, 'funny' => 0];
$prStmt = $db->prepare("SELECT reaction_type, COUNT(*) as count FROM post_reactions WHERE page_url = ? GROUP BY reaction_type");
$prStmt->execute([$pageUrl]);
foreach ($prStmt->fetchAll() as $row) {
if (isset($postReactions[$row['reaction_type']])) {
$postReactions[$row['reaction_type']] = (int)$row['count'];
}
}
jsonResponse([
'comments' => $threaded,
'post_reactions' => $postReactions,
'pagination' => [
'total' => $total,
'limit' => $limit,
'offset' => $offset,
'hasMore' => ($offset + $limit) < $total
]
]);
}
// GET /api.php?action=recent&limit=10
// Public endpoint for displaying recent comments site-wide
if ($method === 'GET' && $action === 'recent') {
$limit = isset($_GET['limit']) ? min(max(1, (int)$_GET['limit']), 100) : 10;
$stmt = $db->prepare("
SELECT id, page_url, author_name, author_url,
content, created_at
FROM comments
WHERE status = 'approved'
ORDER BY created_at DESC
LIMIT ?
");
$stmt->execute([$limit]);
$comments = $stmt->fetchAll();
// Trim content to excerpt for display
foreach ($comments as &$comment) {
if (strlen($comment['content']) > 150) {
$comment['excerpt'] = substr($comment['content'], 0, 150) . '...';
} else {
$comment['excerpt'] = $comment['content'];
}
}
jsonResponse(['comments' => $comments]);
}
// POST /api.php?action=vote
// Toggle a reaction on a comment (one per IP address per reaction type)
if ($method === 'POST' && $action === 'vote') {
$input = getInput();
$commentId = isset($input['comment_id']) ? (int)$input['comment_id'] : 0;
if ($commentId <= 0) {
jsonResponse(['error' => 'Invalid comment ID'], 400);
}
$allowedTypes = ['heart', 'thumbsup', 'lightbulb', 'funny'];
$reactionType = $input['reaction_type'] ?? 'heart';
if (!in_array($reactionType, $allowedTypes)) {
jsonResponse(['error' => 'Invalid reaction type'], 400);
}
// Verify the comment exists and is approved
$checkStmt = $db->prepare("SELECT id, author_name, author_email, page_url FROM comments WHERE id = ? AND status = 'approved'");
$checkStmt->execute([$commentId]);
$comment = $checkStmt->fetch();
if (!$comment) {
jsonResponse(['error' => 'Comment not found'], 404);
}
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
// Rate limit: max 15 vote actions per IP per 60 seconds
$rateStmt = $db->prepare("SELECT COUNT(*) as count FROM vote_log WHERE ip_address = ? AND created_at > datetime('now', '-60 seconds')");
$rateStmt->execute([$ip]);
if ((int)$rateStmt->fetch()['count'] >= 15) {
jsonResponse(['error' => 'Too many reactions. Please slow down.'], 429);
}
// Check if this IP has already used this reaction on this comment
$existsStmt = $db->prepare("SELECT id FROM votes WHERE comment_id = ? AND ip_address = ? AND reaction_type = ?");
$existsStmt->execute([$commentId, $ip, $reactionType]);
$existing = $existsStmt->fetch();
if ($existing) {
// Already reacted — remove it (toggle off)
$db->prepare("DELETE FROM votes WHERE comment_id = ? AND ip_address = ? AND reaction_type = ?")->execute([$commentId, $ip, $reactionType]);
$voted = false;
} else {
// New reaction — insert it
$db->prepare("INSERT INTO votes (comment_id, ip_address, reaction_type) VALUES (?, ?, ?)")->execute([$commentId, $ip, $reactionType]);
$voted = true;
}
// Log this action for rate limiting
$db->prepare("INSERT INTO vote_log (ip_address) VALUES (?)")->execute([$ip]);
// Notify comment author of new reaction
if ($voted) {
sendReactionNotificationEmail($commentId, $comment['page_url'], $comment['author_name'], $comment['author_email'], $reactionType);
}
// Return per-type counts
$counts = [];
foreach ($allowedTypes as $type) {
$countStmt = $db->prepare("SELECT COUNT(*) as count FROM votes WHERE comment_id = ? AND reaction_type = ?");
$countStmt->execute([$commentId, $type]);
$counts[$type] = (int)$countStmt->fetch()['count'];
}
jsonResponse(['voted' => $voted, 'reaction_type' => $reactionType, 'counts' => $counts]);
}
// POST /api.php?action=post
if ($method === 'POST' && $action === 'post') {
$input = getInput();
$pageUrl = $input['page_url'] ?? '';
$parentId = $input['parent_id'] ?? null;
$authorName = trim($input['author_name'] ?? '');
$authorEmail = trim($input['author_email'] ?? '');
$authorUrl = sanitizeUrl($input['author_url'] ?? '');
$content = trim($input['content'] ?? '');
$subscribe = $input['subscribe'] ?? false;
$honeypot = $input['website'] ?? ''; // Honeypot field
// Honeypot check - if filled, it's likely a bot
if (!empty($honeypot)) {
jsonResponse(['error' => 'Invalid submission'], 400);
}
// Validation
$errors = [];
if (empty($pageUrl)) $errors[] = 'URL is required';
if (empty($authorName)) $errors[] = 'Name is required';
if (empty($authorEmail) || !validateEmail($authorEmail)) $errors[] = 'Valid email is required';
if (empty($content)) $errors[] = 'Comment content is required';
if (strlen($content) > 5000) $errors[] = 'Comment is too long';
if (!empty($errors)) {
jsonResponse(['error' => implode(', ', $errors)], 400);
}
$ipAddress = $_SERVER['REMOTE_ADDR'] ?? null;
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? null;
// Rate limiting
$rateLimitCheck = checkRateLimit($ipAddress, $authorEmail);
if ($rateLimitCheck['limited']) {
jsonResponse(['error' => $rateLimitCheck['reason']], 429);
}
// Spam detection
$isSpam = detectSpam($content, $authorName, $authorEmail, $authorUrl);
// Check if parent exists if specified
if ($parentId !== null) {
$stmt = $db->prepare("SELECT id FROM comments WHERE id = ?");
$stmt->execute([$parentId]);
if (!$stmt->fetch()) {
jsonResponse(['error' => 'Parent comment not found'], 404);
}
}
// Get moderation setting
$stmt = $db->prepare("SELECT value FROM settings WHERE key = 'require_moderation'");
$stmt->execute();
$moderation = $stmt->fetch();
// Check if this email has previously approved comments (trusted commenter)
$stmt = $db->prepare("
SELECT COUNT(*) as count FROM comments
WHERE author_email = ? AND status = 'approved'
");
$stmt->execute([$authorEmail]);
$result = $stmt->fetch();
$isTrustedCommenter = $result['count'] > 0;
// Determine status: spam > trusted > moderation > approved
if ($isSpam) {
$status = 'spam';
} else if ($isTrustedCommenter) {
$status = 'approved'; // Auto-approve trusted commenters
} else {
$status = ($moderation && $moderation['value'] === 'true') ? 'pending' : 'approved';
}
// Insert comment with explicit timestamp in configured timezone
$now = date('Y-m-d H:i:s');
$stmt = $db->prepare("
INSERT INTO comments (page_url, parent_id, author_name, author_email, author_url,
content, status, ip_address, user_agent, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$pageUrl, $parentId, $authorName, $authorEmail, $authorUrl,
$content, $status, $ipAddress, $userAgent, $now, $now
]);
$commentId = $db->lastInsertId();
// Handle subscription preference
if ($subscribe && $status !== 'spam') {
$token = bin2hex(random_bytes(32));
$subscribeTime = date('Y-m-d H:i:s');
$stmt = $db->prepare("
INSERT OR REPLACE INTO subscriptions (page_url, email, token, subscribed_at)
VALUES (?, ?, ?, ?)
");
$stmt->execute([$pageUrl, $authorEmail, $token, $subscribeTime]);
}
// If not spam and approved/pending, send notification
if ($status !== 'spam') {
// Send notification email (if enabled)
sendNotificationEmail($commentId, $pageUrl, $parentId, $authorName, $content, $authorEmail);
}
// Generate appropriate message
$message = 'Comment posted successfully';
if ($status === 'spam') {
$message = 'Comment marked as spam';
} else if ($status === 'pending') {
$message = 'Comment submitted for moderation';
} else if ($isTrustedCommenter) {
$message = 'Comment posted successfully (auto-approved)';
}
jsonResponse([
'success' => true,
'id' => $commentId,
'status' => $status,
'message' => $message,
'trusted' => $isTrustedCommenter
], 201);
}
// GET /api.php?action=csrf_token
if ($method === 'GET' && $action === 'csrf_token') {
$token = generateCSRFToken();
jsonResponse(['token' => $token]);
}
// POST /api.php?action=login (admin)
if ($method === 'POST' && $action === 'login') {
$ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
// Check login rate limiting
$rateLimit = checkLoginRateLimit($ipAddress);
if ($rateLimit['limited']) {
jsonResponse(['error' => $rateLimit['reason']], 429);
}
$input = getInput();
$password = $input['password'] ?? '';
$stmt = $db->prepare("SELECT value FROM settings WHERE key = 'admin_password_hash'");
$stmt->execute();
$result = $stmt->fetch();
if ($result && password_verify($password, $result['value'])) {
// Record successful login attempt
recordLoginAttempt($ipAddress, true);
$token = bin2hex(random_bytes(32));
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
// Create new session in sessions table
$stmt = $db->prepare("
INSERT INTO sessions (token, expires_at, ip_address, user_agent)
VALUES (?, datetime('now', '+30 days'), ?, ?)
");
$stmt->execute([$token, $ipAddress, $userAgent]);
// Also store in old settings table for backward compatibility
$stmt = $db->prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('admin_token', ?)");
$stmt->execute([$token]);
// Set secure cookie (HTTPS only in production)
$isSecure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443;
setcookie(ADMIN_TOKEN_COOKIE, $token, time() + SESSION_LIFETIME, '/comments/', '', $isSecure, true);
// Generate CSRF token for this session
$csrfToken = generateCSRFToken();
jsonResponse(['success' => true, 'message' => 'Logged in successfully', 'csrf_token' => $csrfToken]);
} else {
// Record failed login attempt
recordLoginAttempt($ipAddress, false);
jsonResponse(['error' => 'Invalid password'], 401);
}
}
// POST /api.php?action=logout (admin)
if ($method === 'POST' && $action === 'logout') {
if (isset($_COOKIE[ADMIN_TOKEN_COOKIE])) {
$token = $_COOKIE[ADMIN_TOKEN_COOKIE];
// Invalidate the session in the database
$stmt = $db->prepare("DELETE FROM sessions WHERE token = ?");
$stmt->execute([$token]);
// Clear the admin_token fallback too
$stmt = $db->prepare("DELETE FROM settings WHERE key = 'admin_token' AND value = ?");
$stmt->execute([$token]);
}
// Expire the cookie
$isSecure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443;
setcookie(ADMIN_TOKEN_COOKIE, '', time() - 3600, '/comments/', '', $isSecure, true);
setcookie('csrf_token', '', time() - 3600, '/comments/', '', $isSecure, false);
jsonResponse(['success' => true]);
}
// PUT /api.php?action=moderate&id=...
if ($method === 'PUT' && $action === 'moderate') {
if (!isAdmin()) {
jsonResponse(['error' => 'Unauthorized'], 401);
}
$input = getInput();
// Validate CSRF token
$csrfToken = $input['csrf_token'] ?? '';
if (!validateCSRFToken($csrfToken)) {
jsonResponse(['error' => 'Invalid CSRF token'], 403);
}
$id = $_GET['id'] ?? '';
$status = $input['status'] ?? '';
if (!in_array($status, ['approved', 'spam', 'deleted'])) {
jsonResponse(['error' => 'Invalid status'], 400);
}
$stmt = $db->prepare("UPDATE comments SET status = ? WHERE id = ?");
$stmt->execute([$status, $id]);
jsonResponse(['success' => true, 'message' => 'Comment updated']);
}
// DELETE /api.php?action=delete&id=...
if ($method === 'DELETE' && $action === 'delete') {
if (!isAdmin()) {
jsonResponse(['error' => 'Unauthorized'], 401);
}
// Validate CSRF token from query parameter (since DELETE can't have body)
$csrfToken = $_GET['csrf_token'] ?? '';
if (!validateCSRFToken($csrfToken)) {
jsonResponse(['error' => 'Invalid CSRF token'], 403);
}
$id = $_GET['id'] ?? '';
$stmt = $db->prepare("DELETE FROM comments WHERE id = ?");
$stmt->execute([$id]);
jsonResponse(['success' => true, 'message' => 'Comment deleted']);
}
// GET /api.php?action=pending (admin)
if ($method === 'GET' && $action === 'pending') {
if (!isAdmin()) {
jsonResponse(['error' => 'Unauthorized'], 401);
}
// Add pagination to prevent browser crashes with large datasets
$limit = isset($_GET['limit']) ? min(max(1, (int)$_GET['limit']), 10000) : 50;
$offset = isset($_GET['offset']) ? max(0, (int)$_GET['offset']) : 0;
// Get total count
$countStmt = $db->query("SELECT COUNT(*) as total FROM comments WHERE status = 'pending'");
$countResult = $countStmt->fetch();
$total = $countResult['total'];
$stmt = $db->prepare("
SELECT c.id, c.page_url, c.parent_id, c.author_name, c.author_email, c.author_url,
c.content, c.created_at, c.status, c.ip_address,
COALESCE((SELECT COUNT(*) FROM votes WHERE comment_id = c.id AND reaction_type = 'heart'), 0) AS votes_heart,
COALESCE((SELECT COUNT(*) FROM votes WHERE comment_id = c.id AND reaction_type = 'thumbsup'), 0) AS votes_thumbsup,
COALESCE((SELECT COUNT(*) FROM votes WHERE comment_id = c.id AND reaction_type = 'lightbulb'), 0) AS votes_lightbulb,
COALESCE((SELECT COUNT(*) FROM votes WHERE comment_id = c.id AND reaction_type = 'funny'), 0) AS votes_funny
FROM comments c
WHERE c.status = 'pending'
ORDER BY c.created_at DESC
LIMIT ? OFFSET ?
");
$stmt->execute([$limit, $offset]);
$comments = $stmt->fetchAll();
jsonResponse([
'comments' => $comments,
'pagination' => [
'total' => $total,
'limit' => $limit,
'offset' => $offset,
'hasMore' => ($offset + $limit) < $total
]
]);
}
// GET /api.php?action=all (admin)
if ($method === 'GET' && $action === 'all') {
if (!isAdmin()) {
jsonResponse(['error' => 'Unauthorized'], 401);
}
$limit = isset($_GET['limit']) ? min(max(1, (int)$_GET['limit']), 100) : 50;
$offset = isset($_GET['offset']) ? max(0, (int)$_GET['offset']) : 0;
$statusFilter = trim($_GET['status'] ?? 'all');
$search = trim($_GET['search'] ?? '');
// Build WHERE clause from filters
$where = [];
$params = [];
if ($statusFilter !== 'all' && in_array($statusFilter, ['pending', 'approved', 'spam', 'deleted'])) {
$where[] = 'c.status = ?';
$params[] = $statusFilter;
}
if ($search !== '') {
$where[] = '(c.author_name LIKE ? OR c.author_email LIKE ? OR c.page_url LIKE ? OR c.content LIKE ?)';