-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.php
More file actions
2473 lines (2350 loc) · 144 KB
/
Copy pathindex.php
File metadata and controls
2473 lines (2350 loc) · 144 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
// --- Configuration ---
define('DB_FILE', __DIR__ . '/board.db'); // Database file
define('UPLOADS_DIR', __DIR__ . '/uploads'); // Base Uploads directory
define('UPLOADS_URL_PATH', 'uploads'); // Relative web path base
define('MAX_FILE_SIZE', 20 * 1024 * 1024); // 20 MB
define('ALLOWED_EXTENSIONS', ['jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'webm', 'mp3', 'wav', 'ogg', 'avi', 'mov', 'flv', 'wmv']);
define('VIDEO_EXTENSIONS', ['mp4', 'webm', 'avi', 'mov', 'flv', 'wmv']);
define('AUDIO_EXTENSIONS', ['mp3', 'wav', 'ogg']);
// Define allowed channels (UNCHANGED - Keep your existing list)
define('ALLOWED_CHANNELS', [ /* ... Your full list of channels ... */
// Original
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'gif', 'h', 'hr', 'k', 'm', 'o', 'p', 'r', 's', 't', 'u', 'v',
'vg', 'vm', 'vmg', 'vr', 'vrpg', 'vst', 'w', 'wg', 'i', 'ic', 'r9k', 's4s', 'vip', 'qa', 'cm',
'hm', 'lgbt', 'mlp', 'news', 'out', 'po', 'pw', 'qst', 'sp', 'trv', 'tv', 'vp', 'wsg', 'wsr',
'x', 'y', '3', 'aco', 'adv', 'an', 'bant', 'biz', 'cgl', 'ck', 'co', 'diy', 'fa', 'fit', 'gd',
'hc', 'his', 'int', 'jp', 'lit', 'mu', 'n', 'pol', 'sci', 'soc', 'tg', 'toy', 'vt', 'xs',
// New 40 Channels
'art', 'tech', 'food', 'movies', 'music', 'books', 'news2', 'dev', 'meta', 'diy2', 'crypto', 'learn',
'lang', 'travel2', 'health', 'cars', 'bikes', 'space', 'scifi', 'fantasy', 'hist2', 'phil', 'eco',
'game', 'mobi', 'prog', 'web', 'desk', 'serv', 'net', 'sec', 'ai', 'ml', 'data', 'vr2', 'ar',
'robot', 'drone', '3dp', 'hobby'
]);
define('CHANNEL_NAMES', [ /* ... Your full list of channel names ... */
// Original
'a' => 'Anime & Manga', 'b' => 'Random', 'c' => 'Anime/Cute', 'd' => 'Hentai/Alternative', 'e' => 'Ecchi',
'f' => 'Flash', 'g' => 'Technology', 'gif' => 'Animated GIF', 'h' => 'Hentai', 'hr' => 'High Resolution',
'k' => 'Weapons', 'm' => 'Mecha', 'o' => 'Auto', 'p' => 'Photography', 'r' => 'Adult Requests',
's' => 'Sexy Beautiful Women', 't' => 'Torrents', 'u' => 'Yuri', 'v' => 'Video Games', 'vg' => 'Video Game Generals',
'vm' => 'Video Games/Mobile', 'vmg' => 'Video Games/Mobile Generals', 'vr' => 'Retro Games',
'vrpg' => 'Video Games/RPG', 'vst' => 'Video Games/Strategy', 'w' => 'Anime/Wallpapers',
'wg' => 'Wallpapers/General', 'i' => 'Oekaki', 'ic' => 'Artwork/Critique', 'r9k' => 'ROBOT9001',
's4s' => 'Shit 4chan Says', 'vip' => 'Very Important Posts', 'qa' => 'Question & Answer', 'cm' => 'Cute/Male',
'hm' => 'Handsome Men', 'lgbt' => 'LGBT', 'mlp' => 'My Little Pony', 'news' => 'Current News',
'out' => 'Outdoors', 'po' => 'Papercraft & Origami', 'pw' => 'Professional Wrestling',
'qst' => 'Quests', 'sp' => 'Sports', 'trv' => 'Travel', 'tv' => 'Television & Film',
'vp' => 'Pokemon', 'wsg' => 'Worksafe GIF', 'wsr' => 'Worksafe Requests', 'x' => 'Paranormal',
'y' => 'Yaoi', '3' => '3DCG', 'aco' => 'Adult Cartoons', 'adv' => 'Advice', 'an' => 'Animals & Nature',
'bant' => 'International/Random', 'biz' => 'Business & Finance', 'cgl' => 'Cosplay & EGL',
'ck' => 'Food & Cooking', 'co' => 'Comics & Cartoons', 'diy' => 'Do-It-Yourself', 'fa' => 'Fashion',
'fit' => 'Fitness', 'gd' => 'Graphic Design', 'hc' => 'Hardcore', 'his' => 'History & Humanities',
'int' => 'International', 'jp' => 'Otaku Culture', 'lit' => 'Literature', 'mu' => 'Music',
'n' => 'Transportation', 'pol' => 'Politically Incorrect', 'sci' => 'Science & Math', 'soc' => 'Social',
'tg' => 'Traditional Games', 'toy' => 'Toys', 'vt' => 'Virtual YouTubers', 'xs' => 'Extreme Sports',
// New 40 Channels
'art' => 'Art General', 'tech' => 'Technology General', 'food' => 'Food General', 'movies' => 'Movies General',
'music' => 'Music General', 'books' => 'Books General', 'news2' => 'News General', 'dev' => 'Development',
'meta' => 'Meta/Board Talk', 'diy2' => 'DIY General', 'crypto' => 'Cryptocurrency', 'learn' => 'Learning & Education',
'lang' => 'Languages', 'travel2' => 'Travel General', 'health' => 'Health & Wellness', 'cars' => 'Cars & Vehicles',
'bikes' => 'Motorcycles', 'space' => 'Space & Astronomy', 'scifi' => 'Sci-Fi', 'fantasy' => 'Fantasy',
'hist2' => 'History General', 'phil' => 'Philosophy', 'eco' => 'Economics', 'game' => 'Gaming General',
'mobi' => 'Mobile Tech', 'prog' => 'Programming', 'web' => 'Web Development', 'desk' => 'Desktop Customization',
'serv' => 'Servers & Hosting', 'net' => 'Networking', 'sec' => 'Security', 'ai' => 'Artificial Intelligence',
'ml' => 'Machine Learning', 'data' => 'Data Science', 'vr2' => 'Virtual Reality General', 'ar' => 'Augmented Reality',
'robot' => 'Robotics', 'drone' => 'Drones', '3dp' => '3D Printing', 'hobby' => 'Hobbies General'
]);
define('NSFW_CHANNELS', [ /* ... Your list ... */
// Original
'b', 'd', 'gif', 'h', 'hr', 'r9k', 's', 'soc', 'x', 'y', 'aco', 'bant', 'hc', 'hm', 'pol', 'r', 's4s', 'lgbt',
// New (Add any relevant new ones here)
'art', // Art can sometimes be NSFW
'meta', // Meta discussions might touch on NSFW rules/topics
'hist2', // History can contain sensitive/graphic content
]);
$channel_categories = [ /* ... Your categories ... */
'Japanese Culture' => ['a', 'c', 'e', 'h', 'jp', 'm', 'u', 'w', 'vt'],
'Video Games' => ['v', 'vg', 'vm', 'vmg', 'vr', 'vrpg', 'vst', 'vp', 'game'],
'Creative' => ['i', 'ic', 'p', 'po', 'gd', 'diy', 'diy2', 'art', 'music', 'mu', 'lit', 'books', '3dp'],
'Technology' => ['g', 'f', 'tech', 'dev', 'prog', 'web', 'serv', 'net', 'sec', 'ai', 'ml', 'data', 'mobi', 'crypto', 'sci', 'vr2', 'ar', 'robot', 'drone', 'space'],
'Interests & Hobbies' => ['o', 'k', 'out', 'ck', 'food', 'sp', 'toy', 'n', 'cars', 'bikes', 'hobby', 'xs', 'trv', 'travel2', 'health', 'fit', 'fa', 'cgl', 'mlp', 'co', 'tv', 'movies', 'lang', 'learn'],
'Adult (18+)' => ['s', 'd', 'gif', 'hr', 'r', 'wsr', 'y', '3', 'aco', 'hc', 'hm', 'cm'], // Use with caution & check local laws
'Random & Community' => ['b', 'r9k', 's4s', 'vip', 'qa', 'adv', 'an', 'bant', 'int', 'news', 'news2', 'pol', 'soc', 'his', 'hist2', 'phil', 'eco', 'biz', 'lgbt', 'pw', 'qst', 'wsg', 'x', 'meta', 'desk'],
];
define('THREADS_PER_PAGE', 10);
define('REPLIES_PREVIEW_COUNT', 6);
define('COMMENT_PREVIEW_LENGTH', 1000);
define('USERNAME_MAX_LENGTH', 50);
define('PASSWORD_MIN_LENGTH', 8); // Increased for better security
// User Roles
define('ROLE_USER', 'user');
define('ROLE_JANITOR', 'janitor');
define('ROLE_MODERATOR', 'moderator');
define('ROLE_ADMIN', 'admin');
$roles = [ROLE_USER, ROLE_JANITOR, ROLE_MODERATOR, ROLE_ADMIN];
$role_hierarchy = [
ROLE_USER => 1,
ROLE_JANITOR => 2,
ROLE_MODERATOR => 3,
ROLE_ADMIN => 4
];
// User Statuses
define('STATUS_ACTIVE', 'active');
define('STATUS_BANNED', 'banned');
$statuses = [STATUS_ACTIVE, STATUS_BANNED];
// --- Initialization & DB Setup ---
ini_set('display_errors', 0); // Hide errors from users
error_reporting(E_ALL);
// Configure session settings for better security
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
ini_set('session.cookie_secure', 1);
}
ini_set('session.cookie_samesite', 'Lax'); // Prevent CSRF via cross-site cookies
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['session_started_time'])) {
$_SESSION['session_started_time'] = time();
}
if (!isset($_SESSION['last_regen']) || time() - $_SESSION['last_regen'] > (15 * 60)) {
session_regenerate_id(true);
$_SESSION['last_regen'] = time();
}
// CSRF Token
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];
// --- Access Denied Page ---
if (isset($_GET['access']) && $_GET['access'] === 'denied') {
http_response_code(403);
echo <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Access Denied</title>
<link rel="icon" type="image/png" href="/HDBoard.png">
<style>
body { background-color: #1a1a1a; color: #e0e0e0; font-family: sans-serif; text-align: center; padding-top: 50px; }
.container { max-width: 600px; margin: auto; background-color: #282828; padding: 30px; border: 1px solid #444; border-radius: 5px; }
h1 { color: #f7768e; }
a { color: #7aa2f7; }
a:hover { color: #c0caf5; }
</style>
</head>
<body>
<div class="container">
<h1>Access Denied</h1>
<p>You do not have permission to perform this action or access this resource.</p>
<p><a href="./">Return to Board Index</a></p>
</div>
</body>
</html>
HTML;
exit;
}
// --- Uploads Directory Check ---
if (!is_dir(UPLOADS_DIR)) {
if (!mkdir(UPLOADS_DIR, 0755, true)) { die("Error: Could not create base uploads directory."); }
}
if (!is_writable(UPLOADS_DIR)) { die("Error: The base uploads directory is not writable."); }
// --- Database Connection and Schema Update ---
try {
$db = new PDO('sqlite:' . DB_FILE);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->exec('PRAGMA foreign_keys = ON;');
// --- Users Table ---
$db->exec("CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT '" . ROLE_USER . "',
status TEXT NOT NULL DEFAULT '" . STATUS_ACTIVE . "',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
CHECK(role IN ('" . implode("','", $roles) . "')),
CHECK(status IN ('" . implode("','", $statuses) . "'))
)");
// --- Threads Table ---
$db->exec("CREATE TABLE IF NOT EXISTS threads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel TEXT NOT NULL,
user_id INTEGER DEFAULT NULL,
username TEXT DEFAULT NULL,
password_hash TEXT DEFAULT NULL,
subject TEXT,
comment TEXT NOT NULL,
image TEXT,
image_orig_name TEXT,
image_w INTEGER,
image_h INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_reply_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
)");
// --- Replies Table ---
$db->exec("CREATE TABLE IF NOT EXISTS replies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
thread_id INTEGER NOT NULL,
user_id INTEGER DEFAULT NULL,
username TEXT DEFAULT NULL,
password_hash TEXT DEFAULT NULL,
comment TEXT NOT NULL,
image TEXT,
image_orig_name TEXT,
image_w INTEGER,
image_h INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
)");
function addColumnIfNotExists(PDO $db, string $tableName, string $columnName, string $columnDefinition) {
try {
$stmt = $db->query("PRAGMA table_info($tableName)");
$columns = $stmt->fetchAll(PDO::FETCH_COLUMN, 1);
if (!in_array($columnName, $columns)) {
$db->exec("ALTER TABLE $tableName ADD COLUMN $columnName $columnDefinition");
}
} catch (PDOException $e) {
error_log("Schema Update Error (Table: $tableName, Column: $columnName): " . $e->getMessage());
}
}
addColumnIfNotExists($db, 'threads', 'user_id', 'INTEGER DEFAULT NULL REFERENCES users(id) ON DELETE SET NULL');
addColumnIfNotExists($db, 'replies', 'user_id', 'INTEGER DEFAULT NULL REFERENCES users(id) ON DELETE SET NULL');
addColumnIfNotExists($db, 'threads', 'username', 'TEXT DEFAULT NULL');
addColumnIfNotExists($db, 'threads', 'password_hash', 'TEXT DEFAULT NULL');
addColumnIfNotExists($db, 'replies', 'username', 'TEXT DEFAULT NULL');
addColumnIfNotExists($db, 'replies', 'password_hash', 'TEXT DEFAULT NULL');
addColumnIfNotExists($db, 'users', 'role', "TEXT NOT NULL DEFAULT '" . ROLE_USER . "' CHECK(role IN ('" . implode("','", $roles) . "'))");
addColumnIfNotExists($db, 'users', 'status', "TEXT NOT NULL DEFAULT '" . STATUS_ACTIVE . "' CHECK(status IN ('" . implode("','", $statuses) . "'))");
} catch (PDOException $e) {
error_log("Database Connection/Setup Error: " . $e->getMessage());
die("A critical error occurred with the database connection. Please check server logs.");
}
// --- AJAX Endpoint: Load More Replies ---
if (isset($_GET['action']) && $_GET['action'] === 'load_more_replies') {
header('Content-Type: application/json');
$thread_id = filter_input(INPUT_GET, 'thread_id', FILTER_VALIDATE_INT);
$offset = filter_input(INPUT_GET, 'offset', FILTER_VALIDATE_INT) ?: 25;
if (!$thread_id) {
echo json_encode(['success' => false, 'error' => 'Invalid Thread ID']);
exit;
}
try {
$stmt = $db->prepare("SELECT * FROM replies WHERE thread_id = ? ORDER BY created_at ASC LIMIT 25 OFFSET ?");
$stmt->bindValue(1, $thread_id, PDO::PARAM_INT);
$stmt->bindValue(2, $offset, PDO::PARAM_INT);
$stmt->execute();
$replies = $stmt->fetchAll();
// Fetch associated users to render roles safely
$user_ids = array_unique(array_filter(array_column($replies, 'user_id')));
$users_data = [];
if (!empty($user_ids)) {
$placeholders = implode(',', array_fill(0, count($user_ids), '?'));
$user_stmt = $db->prepare("SELECT id, username, role, status FROM users WHERE id IN ($placeholders)");
$user_stmt->execute(array_values($user_ids));
while ($row = $user_stmt->fetch()) {
$users_data[$row['id']] = $row;
}
}
$current_user = get_session_user();
$html = '';
foreach ($replies as $reply) {
$reply_id = $reply['id'];
$reply_element_id_prefix = 'post-' . $reply_id;
$reply_user_info = (!empty($reply['user_id']) && isset($users_data[$reply['user_id']])) ? $users_data[$reply['user_id']] : null;
$reply_display_name = $reply_user_info ? h($reply_user_info['username']) : ($reply['username'] ? h($reply['username']) : 'Anonymous');
$reply_display_role = $reply_user_info ? $reply_user_info['role'] : null;
$reply_display_status = $reply_user_info ? $reply_user_info['status'] : null;
$reply_is_legacy_anon = !$reply_user_info && !empty($reply['username']) && !empty($reply['password_hash']);
$can_edit_reply = ($current_user && $reply_user_info && $current_user['id'] === $reply_user_info['id']) || user_has_role(ROLE_MODERATOR);
$can_delete_reply = ($current_user && $reply_user_info && $current_user['id'] === $reply_user_info['id']) || user_has_role(ROLE_JANITOR);
$show_ban_button_for_reply = $current_user && $reply_user_info && $reply_user_info['id'] !== $current_user['id'] && user_has_role(ROLE_JANITOR) && ($role_hierarchy[$current_user['role']] > $role_hierarchy[$reply_user_info['role']] || $current_user['role'] === ROLE_ADMIN);
$reply_uploaded_media_html = generate_uploaded_media_html($reply, $reply_element_id_prefix);
$reply_link_media_result = process_comment_media_links($reply['comment'], $reply_element_id_prefix);
$reply_linked_media_html = $reply_link_media_result['media_html'];
$reply_formatted_comment = format_comment($reply_link_media_result['cleaned_text']);
$html .= "
<div class='reply' id='{$reply_element_id_prefix}'>
<p class='post-info'>
<span class='name'>{$reply_display_name}</span>";
if ($reply_display_role) {
$html .= " <span class='role role-" . h($reply_display_role) . "'>( " . ucfirst(h($reply_display_role)) . " )</span>";
}
if ($reply_display_status === STATUS_BANNED) {
$html .= " <span class='status-banned'>[Banned]</span>";
}
if ($reply_is_legacy_anon) {
$html .= " <span class='role'>(Legacy)</span>";
}
$html .= "
<span class='time'>" . date('Y/m/d(D) H:i:s', strtotime($reply['created_at'])) . "</span>
<span class='post-id'>No.{$reply_id}</span>
<a href='#{$reply_element_id_prefix}' class='reply-link' title='Link to post'>▶</a>";
if ($can_edit_reply) {
$html .= " <span class='action-link'>[<a href='./?action=show_edit_form&type=reply&id={$reply_id}'>Edit</a>]</span>";
}
if ($can_delete_reply) {
$html .= " <span class='action-link'>[<a href='./?action=confirm_delete&type=reply&id={$reply_id}'>Delete</a>]</span>";
}
if ($show_ban_button_for_reply) {
$html .= "
<span class='action-link'>
<form action='./' method='post' style='display: inline;'>
<input type='hidden' name='action' value='" . ($reply_display_status === STATUS_BANNED ? 'unban_user' : 'ban_user') . "'>
<input type='hidden' name='user_id' value='{$reply_user_info['id']}'>
<input type='hidden' name='csrf_token' value='{$csrf_token}'>
<button type='submit'>[" . ($reply_display_status === STATUS_BANNED ? 'Unban' : 'Ban') . "]</button>
</form>
</span>";
}
$html .= "
</p>
{$reply_uploaded_media_html}
{$reply_linked_media_html}
<div class='comment'>{$reply_formatted_comment}</div>
</div>";
}
echo json_encode([
'success' => true,
'html' => $html,
'count' => count($replies)
]);
exit;
} catch (Exception $e) {
echo json_encode(['success' => false, 'error' => 'Database error']);
exit;
}
}
// --- Helper Functions ---
function is_logged_in(): bool {
return isset($_SESSION['user_id']);
}
// XSS Sanitization Helper
function h(?string $str): string {
return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8');
}
function get_session_user(): ?array {
if (!is_logged_in() || !isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['role'], $_SESSION['status'])) {
return null;
}
return [
'id' => $_SESSION['user_id'],
'username' => $_SESSION['username'],
'role' => $_SESSION['role'],
'status' => $_SESSION['status'],
];
}
function logout_user() {
$_SESSION = [];
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
}
function user_has_role(string $required_role): bool {
global $role_hierarchy;
$user = get_session_user();
if (!$user || !isset($role_hierarchy[$user['role']], $role_hierarchy[$required_role])) {
return false;
}
return $role_hierarchy[$user['role']] >= $role_hierarchy[$required_role];
}
function verify_legacy_user_password(PDO $db, string $raw_username, string $submitted_password): bool {
if (empty($raw_username) || empty($submitted_password)) {
return false;
}
try {
$stmt_check = $db->prepare("
SELECT password_hash FROM (
SELECT password_hash, created_at FROM threads WHERE username = ? COLLATE NOCASE AND password_hash IS NOT NULL AND user_id IS NULL
UNION ALL
SELECT password_hash, created_at FROM replies WHERE username = ? COLLATE NOCASE AND password_hash IS NOT NULL AND user_id IS NULL
) AS user_posts
ORDER BY created_at ASC
LIMIT 1
");
$stmt_check->execute([$raw_username, $raw_username]);
$result = $stmt_check->fetch();
$existing_hash = $result['password_hash'] ?? null;
if ($existing_hash === null) return false;
return password_verify($submitted_password, $existing_hash);
} catch (PDOException $e) {
error_log("Legacy password verification DB error for '{$raw_username}': " . $e->getMessage());
return false;
}
}
function get_user_by_username(PDO $db, string $username): ?array {
try {
$stmt = $db->prepare("SELECT * FROM users WHERE username = ? COLLATE NOCASE");
$stmt->execute([$username]);
return $stmt->fetch() ?: null;
} catch (PDOException $e) {
error_log("Error fetching user by username '{$username}': " . $e->getMessage());
return null;
}
}
function get_user_by_id(PDO $db, int $user_id): ?array {
try {
$stmt = $db->prepare("SELECT id, username, role, status, created_at FROM users WHERE id = ?");
$stmt->execute([$user_id]);
return $stmt->fetch() ?: null;
} catch (PDOException $e) {
error_log("Error fetching user by ID '{$user_id}': " . $e->getMessage());
return null;
}
}
function delete_post_file(?string $image_relative_path): bool {
if (empty($image_relative_path)) {
return true;
}
if (strpos($image_relative_path, '..') !== false) {
error_log("Attempted deletion with traversal path: " . $image_relative_path);
return false;
}
$full_path = UPLOADS_DIR . DIRECTORY_SEPARATOR . $image_relative_path;
$base_dir = realpath(UPLOADS_DIR);
$real_file_path = realpath($full_path);
if ($real_file_path === false || strpos($real_file_path, $base_dir) !== 0) {
error_log("Attempted to delete invalid or non-existent file (path check failed): " . $full_path);
return false;
}
if (is_writable($real_file_path)) {
if (@unlink($real_file_path)) {
return true;
}
error_log("Failed to delete file: " . $real_file_path);
} else {
error_log("File not writable, cannot delete: " . $real_file_path);
}
return false;
}
function handle_upload($file_input_name) {
if (!isset($_FILES[$file_input_name]) || $_FILES[$file_input_name]['error'] === UPLOAD_ERR_NO_FILE) {
return ['success' => false];
}
$file = $_FILES[$file_input_name];
if ($file['error'] !== UPLOAD_ERR_OK) {
$errors = [
UPLOAD_ERR_INI_SIZE => 'File is too large (Server limit).',
UPLOAD_ERR_FORM_SIZE => 'File is too large (Form limit).',
UPLOAD_ERR_PARTIAL => 'File was only partially uploaded.',
UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder.',
UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the upload.'
];
return ['error' => $errors[$file['error']] ?? 'Unknown upload error (Code: ' . $file['error'] . ').'];
}
if ($file['size'] > MAX_FILE_SIZE) {
return ['error' => 'File is too large (Max: ' . (MAX_FILE_SIZE / 1024 / 1024) . ' MB).'];
}
$file_info = pathinfo($file['name']);
$extension = strtolower($file_info['extension'] ?? '');
if (!in_array($extension, ALLOWED_EXTENSIONS)) {
return ['error' => 'Invalid file extension.'];
}
$img_w = null; $img_h = null;
if (in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
$image_size = @getimagesize($file['tmp_name']);
if ($image_size !== false) {
$img_w = $image_size[0] ?? null;
$img_h = $image_size[1] ?? null;
}
}
$relative_dir_path = date('Y/m/d');
$target_dir = UPLOADS_DIR . '/' . $relative_dir_path;
if (!is_dir($target_dir)) {
if (!mkdir($target_dir, 0755, true)) {
error_log("Error: Could not create dated upload directory: " . $target_dir);
return ['error' => 'Server error: Could not create upload directory.'];
}
}
if (!is_writable($target_dir)) {
error_log("Error: Dated upload directory is not writable: " . $target_dir);
return ['error' => 'Server error: Upload directory is not writable.'];
}
$new_filename = uniqid('', true) . '.' . $extension;
$relative_path_for_db = $relative_dir_path . '/' . $new_filename;
$destination = $target_dir . '/' . $new_filename;
if (move_uploaded_file($file['tmp_name'], $destination)) {
if (!file_exists($destination)) {
error_log("Failed to confirm uploaded file existence: " . $destination);
return ['error' => 'Failed to confirm file after move.'];
}
return [ 'success' => true, 'filename' => $relative_path_for_db, 'orig_name' => basename($file['name']), 'width' => $img_w, 'height' => $img_h ];
}
error_log("Failed to move uploaded file to " . $destination);
return ['error' => 'Failed to save uploaded file.'];
}
function get_render_media_type($url_or_filename) {
if (!$url_or_filename) return 'unknown';
$is_url = preg_match('/^(https?|ftp):\/\//i', $url_or_filename);
if ($is_url) {
$youtube_regex = '/^https?:\/\/(?:www\.)?(?:m\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|v\/|shorts\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})(?:[?&].*)?$/i';
if (preg_match($youtube_regex, $url_or_filename)) { return 'youtube'; }
}
$path_part = $is_url ? parse_url($url_or_filename, PHP_URL_PATH) : $url_or_filename;
$extension = strtolower(pathinfo($path_part ?: '', PATHINFO_EXTENSION));
if (in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) return 'image';
if (in_array($extension, VIDEO_EXTENSIONS)) return 'video';
if (in_array($extension, AUDIO_EXTENSIONS)) return 'audio';
return 'unknown';
}
function format_comment($comment) {
$comment = (string) ($comment ?? '');
$comment = htmlspecialchars($comment, ENT_QUOTES, 'UTF-8');
$comment = preg_replace('/\[b\](.*?)\[\/b\]/is', '<strong>$1</strong>', $comment);
$comment = preg_replace('/\[i\](.*?)\[\/i\]/is', '<em>$1</em>', $comment);
$comment = preg_replace('/\[u\](.*?)\[\/u\]/is', '<u>$1</u>', $comment);
$comment = preg_replace('/\[s\](.*?)\[\/s\]/is', '<del>$1</del>', $comment);
$comment = preg_replace('/\[spoiler\](.*?)\[\/spoiler\]/is', '<span class="spoiler">$1</span>', $comment);
$comment = preg_replace_callback('/\[code\](.*?)\[\/code\]/is', function ($matches) {
$code_content = htmlspecialchars($matches[1], ENT_QUOTES, 'UTF-8');
return '<pre class="code-block"><code>' . $code_content . '</code></pre>';
}, $comment);
$comment = preg_replace('/\[quote\](.*?)\[\/quote\]/is', '<blockquote class="quote-block">$1</blockquote>', $comment);
$comment = preg_replace_callback('/\[quote=(?:")?(.*?)(?:")?\](.*?)\[\/quote\]/is', function ($matches) {
$cite_attr = htmlspecialchars($matches[1], ENT_QUOTES, 'UTF-8');
return '<blockquote class="quote-block"><cite>Quote from ' . $cite_attr . ':</cite>' . $matches[2] . '</blockquote>';
}, $comment);
$comment = preg_replace_callback(
'/(?<!["\'>=])\b(https?|ftp):\/\/([^\s<>"\'`]+)/i',
function ($matches) {
$url = $matches[0];
$display_path = htmlspecialchars_decode($matches[2], ENT_QUOTES);
$display_url = (mb_strlen($display_path) > 50) ? mb_substr($display_path, 0, 47) . '...' : $display_path;
$safe_url = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
$safe_display_url = htmlspecialchars($matches[1] . '://' . $display_url, ENT_QUOTES, 'UTF-8');
return '<a href="' . $safe_url . '" target="_blank" rel="noopener noreferrer">' . $safe_display_url . '</a>';
},
$comment
);
$comment = nl2br($comment, false);
$comment = preg_replace_callback('/(<pre(?:.*?)>)(.*?)(<\/pre>)/is', fn($m) => $m[1] . str_replace('<br />', '', $m[2]) . $m[3], $comment);
$comment = preg_replace_callback('/(<blockquote(?:.*?)>)(.*?)(<\/blockquote>)/is', fn($m) => $m[1] . str_replace('<br />', '', $m[2]) . $m[3], $comment);
$comment = preg_replace('/(^<br\s*\/?>|^)(>[^<].*?)(?=<br\s*\/?>|\n|$)/m', '$1<span class="greentext">$2</span>', $comment);
$comment = preg_replace('/^(>[^<].*?)(?=<br\s*\/?>|\n|$)/m', '<span class="greentext">$1</span>', $comment);
$comment = preg_replace('/>>(\d+)/', '<a href="#post-$1" class="reply-mention">>>$1</a>', $comment);
return $comment;
}
function generate_uploaded_media_html(array $post_data, string $post_element_id_prefix): string {
if (empty($post_data['image'])) return '';
$relative_path = $post_data['image'];
$media_url = UPLOADS_URL_PATH . '/' . $relative_path;
$safe_media_url = htmlspecialchars($media_url, ENT_QUOTES, 'UTF-8');
$safe_orig_name = htmlspecialchars($post_data['image_orig_name'] ?? basename($relative_path), ENT_QUOTES, 'UTF-8');
$media_type = get_render_media_type($relative_path);
$media_id = $post_element_id_prefix . '-uploaded-media';
$details = "File: <a href='{$safe_media_url}' target='_blank' rel='noopener noreferrer'>{$safe_orig_name}</a>";
if (!empty($post_data['image_w']) && !empty($post_data['image_h'])) {
$details .= " ({$post_data['image_w']}x{$post_data['image_h']})";
}
$full_file_path = UPLOADS_DIR . '/' . $relative_path;
if (file_exists($full_file_path)) {
$file_size = @filesize($full_file_path);
if ($file_size !== false) {
$details .= ' (' . round($file_size / 1024, 2) . ' KB)';
}
}
$button_text_map = ['image' => 'View Image', 'video' => 'View Video', 'audio' => 'View Audio'];
$button_text = $button_text_map[$media_type] ?? 'View Media';
$html = "<div class='file-info uploaded-file-info'>";
$html .= "<div class='media-toggle'><button class='show-media-btn' data-media-id='{$media_id}' data-media-url='{$safe_media_url}' data-media-type='{$media_type}'>{$button_text}</button></div>";
$html .= "<span class='file-details'>{$details}</span>";
$html .= "</div>";
$html .= "<div id='media-container-{$media_id}' class='media-container' style='display:none;'></div>";
return $html;
}
function process_comment_media_links($text, $post_element_id_prefix) {
$media_html = '';
$cleaned_text = $text;
$link_counter = 0;
$url_regex = '/(?<!href=["\'])(?<!src=["\'])(?<!data-media-url=["\'])(?<!>)\b(https?|ftp):\/\/([^\s<>"\'`]+)/i';
if (preg_match_all($url_regex, $text, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
$matches_reversed = array_reverse($matches);
$media_items_to_append = [];
foreach ($matches_reversed as $match) {
$url = $match[0][0];
$offset = $match[0][1];
$render_type = get_render_media_type($url);
if ($render_type !== 'unknown') {
$media_items_to_append[] = ['url' => $url, 'render_type' => $render_type];
$cleaned_text = mb_substr($cleaned_text, 0, $offset, 'UTF-8') . mb_substr($cleaned_text, $offset + mb_strlen($url, 'UTF-8'), null, 'UTF-8');
}
}
foreach (array_reverse($media_items_to_append) as $item) {
$link_counter++;
$media_id = $post_element_id_prefix . '-link-' . $link_counter;
$safe_url = htmlspecialchars($item['url'], ENT_QUOTES, 'UTF-8');
$render_type = $item['render_type'];
$button_text_map = ['image' => 'View Image', 'video' => 'View Video', 'audio' => 'View Audio', 'youtube' => 'View YouTube'];
$button_text = $button_text_map[$render_type] ?? 'View Media';
$media_html .= "<div class='file-info comment-link-info'>";
$media_html .= "<div class='media-toggle'><button class='show-media-btn' data-media-id='{$media_id}' data-media-url='{$safe_url}' data-media-type='{$render_type}'>{$button_text}</button></div>";
$safe_display_link = htmlspecialchars($item['url'], ENT_QUOTES, 'UTF-8');
$media_html .= "<span class='file-details'>Link: <a href='{$safe_url}' target='_blank' rel='noopener noreferrer'>{$safe_display_link}</a></span>";
$media_html .= "</div>";
$media_html .= "<div id='media-container-{$media_id}' class='media-container' style='display:none;'></div>";
}
}
return ['cleaned_text' => trim($cleaned_text), 'media_html' => $media_html];
}
// --- Determine Current View & Parse Search Queries ---
$show_board_index = true;
$current_channel_code = null;
$current_channel_display_name = 'Board Index';
$search_query = trim($_GET['search'] ?? '');
$requested_channel = $_GET['channel'] ?? null;
if ($requested_channel !== null && in_array($requested_channel, ALLOWED_CHANNELS)) {
$current_channel_code = $requested_channel;
$current_channel_display_name = CHANNEL_NAMES[$current_channel_code] ?? $current_channel_code;
$show_board_index = false;
}
if ($search_query !== '') {
$show_board_index = false;
}
$viewing_thread_id = null;
if (!$show_board_index && $search_query === '') {
$viewing_thread_id = filter_input(INPUT_GET, 'thread', FILTER_VALIDATE_INT);
if ($viewing_thread_id === false || $viewing_thread_id === null) { $viewing_thread_id = null; }
}
$show_login_form = isset($_GET['action']) && $_GET['action'] === 'login';
$show_register_form = isset($_GET['action']) && $_GET['action'] === 'register';
// --- Global Variables for Actions/Messages ---
$action_error = null; $action_success = null; $auth_error = null; $auth_success = null;
$show_action_form = null; $post_data_for_form = null;
// --- Handle AUTH Actions (Login, Logout, Register, Ban/Unban) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
$action = $_POST['action'];
$submitted_csrf = $_POST['csrf_token'] ?? null;
if (!isset($submitted_csrf) || !hash_equals($_SESSION['csrf_token'], $submitted_csrf)) {
$temp_error = "Invalid form submission. Please try again.";
if (in_array($action, ['dologin', 'doregister', 'logout'])) $auth_error = $temp_error;
else $action_error = $temp_error;
$action = null;
error_log("CSRF token mismatch for action: " . ($_POST['action'] ?? 'UNKNOWN'));
}
if ($action !== null) {
switch ($action) {
case 'dologin':
$_SESSION['login_attempts'] = ($_SESSION['login_attempts'] ?? 0) + 1;
if ($_SESSION['login_attempts'] > 5 && (time() - ($_SESSION['last_login_attempt'] ?? 0)) < 300) {
$auth_error = "Too many failed login attempts. Please wait 5 minutes.";
} else {
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';
if (empty($username) || empty($password)) {
$auth_error = "Username and password are required.";
} else {
$user = get_user_by_username($db, $username);
if ($user && password_verify($password, $user['password_hash'])) {
if ($user['status'] === STATUS_BANNED) {
$auth_error = "This account is banned.";
} else {
unset($_SESSION['login_attempts'], $_SESSION['last_login_attempt']);
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['role'] = $user['role'];
$_SESSION['status'] = $user['status'];
$_SESSION['last_regen'] = time();
header("Location: ./");
exit;
}
} else {
$_SESSION['last_login_attempt'] = time();
$auth_error = "Invalid username or password.";
}
}
}
$show_login_form = true;
break;
case 'doregister':
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';
$password_confirm = $_POST['password_confirm'] ?? '';
if (empty($username) || empty($password) || empty($password_confirm)) {
$auth_error = "All fields are required for registration.";
} elseif ($password !== $password_confirm) {
$auth_error = "Passwords do not match.";
} elseif (mb_strlen($password) < PASSWORD_MIN_LENGTH) {
$auth_error = "Password must be at least " . PASSWORD_MIN_LENGTH . " characters long.";
} elseif (mb_strlen($username) > USERNAME_MAX_LENGTH) {
$auth_error = "Username is too long (max " . USERNAME_MAX_LENGTH . " characters).";
} elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
$auth_error = "Username can only contain letters, numbers, and underscores.";
} else {
$existing_user = get_user_by_username($db, $username);
if ($existing_user) {
$auth_error = "Username already taken. Please choose another.";
} else {
$password_hash = password_hash($password, PASSWORD_DEFAULT);
if ($password_hash === false) {
$auth_error = "Error processing password.";
error_log("password_hash failed for registration attempt: " . $username);
} else {
try {
$stmt = $db->prepare("INSERT INTO users (username, password_hash) VALUES (?, ?)");
$stmt->execute([$username, $password_hash]);
$user_id = $db->lastInsertId();
session_regenerate_id(true);
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['role'] = ROLE_USER;
$_SESSION['status'] = STATUS_ACTIVE;
$_SESSION['last_regen'] = time();
header("Location: ./");
exit;
} catch (PDOException $e) {
if (str_contains($e->getMessage(), 'UNIQUE constraint failed')) {
$auth_error = "Username already taken.";
} else {
$auth_error = "Database error during registration.";
error_log("Registration DB error for '{$username}': " . $e->getMessage());
}
}
}
}
}
if ($auth_error) $show_register_form = true;
break;
case 'logout':
logout_user();
header("Location: ./?loggedout=1");
exit;
case 'ban_user':
case 'unban_user':
$current_user = get_session_user();
if (!$current_user || !user_has_role(ROLE_JANITOR)) {
$action_error = "Permission denied.";
} else {
$user_id_to_modify = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);
if (!$user_id_to_modify) {
$action_error = "Invalid user ID specified.";
} else {
$target_user = get_user_by_id($db, $user_id_to_modify);
if (!$target_user) {
$action_error = "User to modify not found.";
} elseif ($target_user['id'] === $current_user['id']) {
$action_error = "You cannot modify yourself.";
} else {
$current_user_level = $role_hierarchy[$current_user['role']];
$target_user_level = $role_hierarchy[$target_user['role']];
if ($current_user_level <= $target_user_level && $current_user['role'] !== ROLE_ADMIN) {
$action_error = "Permission denied: You cannot modify a user with an equal or higher role.";
} else {
$new_status = ($action === 'ban_user') ? STATUS_BANNED : STATUS_ACTIVE;
$action_verb = ($action === 'ban_user') ? 'banned' : 'unbanned';
try {
$stmt = $db->prepare("UPDATE users SET status = ? WHERE id = ?");
$stmt->execute([$new_status, $user_id_to_modify]);
$safe_username = urlencode($target_user['username']);
header("Location: ./?user_{$action_verb}={$safe_username}");
exit;
} catch (PDOException $e) {
$action_error = "Database error updating user status.";
error_log("Error {$action_verb} user {$user_id_to_modify}: " . $e->getMessage());
}
}
}
}
}
break;
case 'delete':
case 'edit':
case 'save_edit':
break;
}
}
}
// --- Handle GET Actions (Confirm Delete, Show Edit Form) & POST (Delete, Edit, Save) ---
if (isset($_REQUEST['action']) && !in_array($_REQUEST['action'], ['login', 'register', 'dologin', 'doregister', 'logout', 'ban_user', 'unban_user'])) {
$action = $_REQUEST['action'];
$post_type = in_array($_REQUEST['type'] ?? null, ['thread', 'reply']) ? $_REQUEST['type'] : null;
$post_id = filter_var($_REQUEST['id'] ?? null, FILTER_VALIDATE_INT);
$submitted_password = $_POST['password'] ?? null;
$current_user = get_session_user();
if (!$post_type || !$post_id) {
$action_error = $action_error ?? "Invalid request parameters.";
} else {
try {
if ($post_type === 'thread') {
$stmt = $db->prepare("SELECT t.*, u.username as registered_username, u.role as user_role, u.status as user_status
FROM threads t LEFT JOIN users u ON t.user_id = u.id WHERE t.id = ?");
} else {
$stmt = $db->prepare("SELECT r.*, t.channel, u.username as registered_username, u.role as user_role, u.status as user_status
FROM replies r JOIN threads t ON r.thread_id = t.id LEFT JOIN users u ON r.user_id = u.id WHERE r.id = ?");
}
$stmt->execute([$post_id]);
$post_data = $stmt->fetch();
} catch (PDOException $e) {
error_log("DB Error fetching post for action {$action}: " . $e->getMessage());
$action_error = $action_error ?? "Database error fetching post.";
}
if (!$post_data) {
$action_error = $action_error ?? ucfirst($post_type) . " not found.";
} elseif ($action_error === null) {
$is_own_post = $current_user && isset($post_data['user_id']) && $post_data['user_id'] == $current_user['id'];
$can_delete_this_post = $is_own_post || user_has_role(ROLE_JANITOR);
$can_edit_this_post = $is_own_post || user_has_role(ROLE_MODERATOR);
$post_legacy_username = !$post_data['user_id'] ? ($post_data['username'] ?? null) : null;
$require_password = $post_legacy_username && !$current_user && !empty($post_data['password_hash']);
$post_channel = $post_data['channel'] ?? null;
if (!$post_channel && $post_type === 'reply' && $post_data['thread_id']) {
try {
$stmt_chan = $db->prepare("SELECT channel FROM threads WHERE id = ?");
$stmt_chan->execute([$post_data['thread_id']]);
$post_channel = $stmt_chan->fetchColumn();
} catch (PDOException $e) { error_log("Failed to fetch channel for reply {$post_id}: " . $e->getMessage()); }
}
$redirect_url_base = $post_channel ? "./?channel=" . urlencode($post_channel) : './';
$redirect_url_thread = ($post_type === 'reply' && isset($post_data['thread_id'])) ? $redirect_url_base . "&thread=" . $post_data['thread_id'] : $redirect_url_base;
switch ($action) {
case 'confirm_delete':
if (!$can_delete_this_post) { header("Location: ./?access=denied"); exit; }
$show_action_form = 'delete_confirm';
$post_data_for_form = ['type' => $post_type, 'id' => $post_id, 'require_password' => $require_password] + $post_data;
break;
case 'delete':
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header("Location: ./?access=denied"); exit; }
if (!$can_delete_this_post) { header("Location: ./?access=denied"); exit; }
$password_ok = !$require_password || verify_legacy_user_password($db, $post_legacy_username, $submitted_password);
if ($password_ok) {
try {
$db->beginTransaction();
delete_post_file($post_data['image'] ?? null);
if ($post_type === 'thread') {
$stmt_get_reply_images = $db->prepare("SELECT image FROM replies WHERE thread_id = ? AND image IS NOT NULL");
$stmt_get_reply_images->execute([$post_id]);
while ($reply_image = $stmt_get_reply_images->fetchColumn()) delete_post_file($reply_image);
$db->prepare("DELETE FROM replies WHERE thread_id = ?")->execute([$post_id]);
$db->prepare("DELETE FROM threads WHERE id = ?")->execute([$post_id]);
} else {
$db->prepare("DELETE FROM replies WHERE id = ?")->execute([$post_id]);
}
$db->commit();
$separator = (strpos($redirect_url_thread, '?') !== false) ? '&' : '?';
header("Location: " . $redirect_url_thread . $separator . "deleted=" . $post_id); exit;
} catch (PDOException $e) {
if ($db->inTransaction()) $db->rollBack();
error_log("DB Error deleting {$post_type} ID {$post_id}: " . $e->getMessage());
$action_error = "Database error during deletion.";
}
} else {
$action_error = "Incorrect password for legacy post deletion.";
$show_action_form = 'delete_confirm';
$post_data_for_form = ['type' => $post_type, 'id' => $post_id, 'require_password' => true] + $post_data;
}
break;
case 'show_edit_form':
if (!$can_edit_this_post) { header("Location: ./?access=denied"); exit; }
if ($require_password) {
$show_action_form = 'edit_confirm';
} else {
$_SESSION['edit_verified'] = ['type' => $post_type, 'id' => $post_id, 'time' => time()];
$show_action_form = 'edit_fields';
}
$post_data_for_form = ['type' => $post_type, 'id' => $post_id] + $post_data;
break;
case 'edit':
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header("Location: ./?access=denied"); exit; }
if (!$can_edit_this_post || !$require_password) { header("Location: ./?access=denied"); exit; }
if (verify_legacy_user_password($db, $post_legacy_username, $submitted_password)) {
$_SESSION['edit_verified'] = ['type' => $post_type, 'id' => $post_id, 'time' => time()];
$show_action_form = 'edit_fields';
} else {
$action_error = "Incorrect password for legacy post edit.";
$show_action_form = 'edit_confirm';
}
$post_data_for_form = ['type' => $post_type, 'id' => $post_id] + $post_data;
break;
case 'save_edit':
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header("Location: ./?access=denied"); exit; }
if (empty($_SESSION['edit_verified']) || $_SESSION['edit_verified']['type'] !== $post_type || $_SESSION['edit_verified']['id'] !== $post_id || (time() - $_SESSION['edit_verified']['time'] > 300)) {
unset($_SESSION['edit_verified']);
$action_error = "Edit session invalid or timed out. Please try again.";
} elseif (!$can_edit_this_post) {
unset($_SESSION['edit_verified']);
header("Location: ./?access=denied"); exit;
} else {
$new_comment = trim($_POST['comment'] ?? '');
if (empty($new_comment) || mb_strlen($new_comment) > 4000) {
$action_error = empty($new_comment) ? "Comment cannot be empty." : "Comment is too long.";
$show_action_form = 'edit_fields';
$post_data_for_form = ['type' => $post_type, 'id' => $post_id, 'comment_attempt' => $new_comment] + $post_data;
if ($post_type === 'thread') $post_data_for_form['subject_attempt'] = trim($_POST['subject'] ?? '');
} else {
try {
if ($post_type === 'thread') {
$stmt_update = $db->prepare("UPDATE threads SET subject = ?, comment = ? WHERE id = ?");
$stmt_update->execute([trim($_POST['subject'] ?? ''), $new_comment, $post_id]);
} else {
$stmt_update = $db->prepare("UPDATE replies SET comment = ? WHERE id = ?");
$stmt_update->execute([$new_comment, $post_id]);
}
unset($_SESSION['edit_verified']);
$separator = (strpos($redirect_url_thread, '?') !== false) ? '&' : '?';
header("Location: " . $redirect_url_thread . $separator . "edited=" . $post_id . "#post-" . $post_id); exit;
} catch (PDOException $e) {
unset($_SESSION['edit_verified']);
error_log("DB Error updating {$post_type} ID {$post_id}: " . $e->getMessage());
$action_error = "Database error during update.";
}
}
}
break;
}
}
}
}
// --- Handle Post Request (New Thread/Reply) ---
$post_error = null;
$post_success = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['action']) && !$show_board_index && isset($_POST['comment']) && empty($action_error) && empty($show_action_form) && !$show_login_form && !$show_register_form) {
$submitted_csrf = $_POST['csrf_token'] ?? null;
if (!isset($submitted_csrf) || !hash_equals($_SESSION['csrf_token'], $submitted_csrf)) {
$post_error = "Invalid form submission. Please try again.";
} else {
$comment_raw = trim($_POST['comment'] ?? '');
$thread_id = filter_input(INPUT_POST, 'thread_id', FILTER_VALIDATE_INT);
$current_user = get_session_user();
if (($current_user && $current_user['status'] === STATUS_BANNED) || ($_POST['channel'] ?? '') !== $current_channel_code) {
$post_error = ($current_user && $current_user['status'] === STATUS_BANNED) ? "Your account is banned." : "Invalid channel for post.";
}
$post_user_id = null; $post_username = null; $post_password_hash = null;
if ($post_error === null) {