-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
1063 lines (1010 loc) · 67.1 KB
/
Copy pathindex.php
File metadata and controls
1063 lines (1010 loc) · 67.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
session_start();
$db = new PDO('sqlite:' . __DIR__ . '/social.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach ([
"CREATE TABLE IF NOT EXISTS u(id INTEGER PRIMARY KEY,name TEXT UNIQUE COLLATE NOCASE,pw TEXT,bio TEXT DEFAULT'',ts INT,admin INT DEFAULT 0)",
"CREATE TABLE IF NOT EXISTS p(id INTEGER PRIMARY KEY,uid INT,txt TEXT,ts INT)",
"CREATE TABLE IF NOT EXISTS f(a INT,b INT,PRIMARY KEY(a,b))",
"CREATE TABLE IF NOT EXISTS l(uid INT,pid INT,PRIMARY KEY(uid,pid))",
"CREATE TABLE IF NOT EXISTS c(id INTEGER PRIMARY KEY,pid INT,uid INT,txt TEXT,ts INT)",
"CREATE TABLE IF NOT EXISTS rl(sid TEXT PRIMARY KEY,cnt INT,ts INT)",
"CREATE TABLE IF NOT EXISTS bl(a INT,b INT,ts INT,PRIMARY KEY(a,b))",
"CREATE TABLE IF NOT EXISTS bu(uid INT PRIMARY KEY,until_ts INT,ts INT)",
"CREATE TABLE IF NOT EXISTS bip(ip TEXT PRIMARY KEY,until_ts INT,ts INT)",
"CREATE TABLE IF NOT EXISTS uip(uid INT PRIMARY KEY,ip TEXT,ts INT)",
"CREATE INDEX IF NOT EXISTS idx_pts ON p(ts)"
] as $s) $db->exec($s);
$POST_MAX = 280;
$BIO_MAX = 160;
$h = fn($s) => htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8');
$me = fn() => (int)($_SESSION['u'] ?? 0);
$tk = fn() => $_SESSION['t'] ??= bin2hex(random_bytes(16));
$err = $_SESSION['err'] ?? null;
unset($_SESSION['err']);
function q($sql, $p = []) { global $db; $s = $db->prepare($sql); $s->execute($p); return $s; }
function usr($id) { return $id ? q("SELECT * FROM u WHERE id=?", [$id])->fetch(PDO::FETCH_ASSOC) : null; }
function getPost($id) { return $id ? q("SELECT * FROM p WHERE id=?", [$id])->fetch(PDO::FETCH_ASSOC) : null; }
function now() { return time(); }
function ipAddr() { return $_SERVER['REMOTE_ADDR'] ?? ''; }
function isAdmin($uid) { $u = usr($uid); return (int)($u['admin'] ?? 0); }
function banUntilUser($uid) { return $uid ? (int)(q("SELECT until_ts FROM bu WHERE uid=?", [$uid])->fetchColumn() ?: 0) : 0; }
function banUntilIp($ip) { return $ip ? (int)(q("SELECT until_ts FROM bip WHERE ip=?", [$ip])->fetchColumn() ?: 0) : 0; }
function isBannedUser($uid) { $u = banUntilUser($uid); return $u === 0 ? false : $u > now(); }
function isBannedIp($ip) { $u = banUntilIp($ip); return $u === 0 ? false : $u > now(); }
function isBlocked($a, $b) { return $a && $b ? (bool)q("SELECT 1 FROM bl WHERE a=? AND b=?", [$a, $b])->fetch() : false; }
function isEitherBlocked($a, $b) { return $a && $b ? (bool)q("SELECT 1 FROM bl WHERE (a=? AND b=?) OR (a=? AND b=?)", [$a, $b, $b, $a])->fetch() : false; }
function touchUserIp($uid) { if (!$uid) return; $ip = ipAddr(); if (!$ip) return; q("INSERT OR REPLACE INTO uip(uid,ip,ts) VALUES(?,?,?)", [$uid, $ip, now()]); }
function lastUserIp($uid) { return $uid ? (string)(q("SELECT ip FROM uip WHERE uid=?", [$uid])->fetchColumn() ?: '') : ''; }
function checkRate($sid, $max = 60, $window = 60) {
$now = now(); $r = q("SELECT cnt,ts FROM rl WHERE sid=?", [$sid])->fetch(PDO::FETCH_ASSOC);
if (!$r || ($now - $r['ts']) >= $window) { q("INSERT OR REPLACE INTO rl(sid,cnt,ts) VALUES(?,1,?)", [$sid, $now]); return true; }
if ($r['cnt'] >= $max) return false;
q("UPDATE rl SET cnt=cnt+1 WHERE sid=?", [$sid]); return true;
}
function svg($d, $f = 'none', $sw = '2') {
$a = $sw ? " stroke=\"currentColor\" stroke-width=\"$sw\"" : '';
return "<svg viewBox=\"0 0 24 24\" fill=\"$f\"$a>$d</svg>";
}
$icons = [
'home' => svg('<path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>'),
'globe' => svg('<circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10 15.3 15.3 0 014-10z"/>'),
'user' => svg('<path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/>'),
'search' => svg('<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>'),
'heart' => svg('<path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/>'),
'heartF' => svg('<path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/>', 'currentColor'),
'comment' => svg('<path d="M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z"/>'),
'x' => svg('<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>'),
'send' => svg('<line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>'),
'gear' => svg('<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.6 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.6a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/>'),
'logout' => svg('<path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>'),
'trash' => svg('<polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/>'),
'plus' => svg('<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>', 'none', '2.5'),
'more' => svg('<circle cx="12" cy="6" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="12" cy="18" r="1.5"/>', 'currentColor', ''),
'copy' => svg('<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>'),
'share' => svg('<path d="M4 12v8a2 2 0 002 2h12a2 2 0 002-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/>'),
'back' => svg('<line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/>'),
'shield' => svg('<path d="M12 2l7 4v6c0 5-3 9-7 10-4-1-7-5-7-10V6l7-4z"/>'),
'lock' => svg('<rect x="5" y="11" width="14" height="11" rx="2"/><path d="M8 11V8a4 4 0 018 0v3"/>')
];
function postHtml($p, $single = false) {
global $icons, $me, $tk, $h;
if ($me() && isEitherBlocked($me(), (int)$p['uid'])) return '';
$u = usr($p['uid']);
$lc = q("SELECT COUNT(*) FROM l WHERE pid=?", [$p['id']])->fetchColumn();
$liked = $me() && q("SELECT 1 FROM l WHERE uid=? AND pid=?", [$me(), $p['id']])->fetch();
$cc = q("SELECT COUNT(*) FROM c WHERE pid=?", [$p['id']])->fetchColumn();
$canDel = $me() && ($p['uid'] == $me() || (usr($me())['admin'] ?? 0));
$cls = $single ? ' single' : '';
$clk = $single ? '' : " onclick=\"postClick(event,{$p['id']})\"";
ob_start(); ?>
<article class="post<?= $cls ?>"<?= $clk ?>>
<div class="avatar av-m"><?= strtoupper($u['name'][0]) ?></div>
<div class="post-body">
<div class="post-head">
<a href="?v=u&id=<?= $p['uid'] ?>" class="post-author"><?= $h($u['name']) ?></a>
<span class="meta">· <?= date('M j', $p['ts']) ?></span>
<div class="post-menu">
<button class="btn-icon" onclick="event.stopPropagation();toggleMenu(this)"><?= $icons['more'] ?></button>
<div class="dropdown">
<button onclick="copyText(this)" data-text="<?= $h($p['txt']) ?>"><?= $icons['copy'] ?> Copy text</button>
<button onclick="sharePost(<?= $p['id'] ?>)"><?= $icons['share'] ?> Share</button>
<?php if ($canDel): ?>
<form method="post"><input type="hidden" name="t" value="<?= $tk() ?>">
<input type="hidden" name="a" value="del"><input type="hidden" name="pid" value="<?= $p['id'] ?>">
<button class="danger" onclick="return confirm('Delete?')"><?= $icons['trash'] ?> Delete</button></form>
<?php endif ?>
</div>
</div>
</div>
<p class="post-text"><?= nl2br($h($p['txt'])) ?></p>
<div class="post-actions">
<form method="post" class="inline" onclick="event.stopPropagation()"><input type="hidden" name="t" value="<?= $tk() ?>">
<input type="hidden" name="a" value="like"><input type="hidden" name="pid" value="<?= $p['id'] ?>">
<button class="btn-action<?= $liked ? ' liked' : '' ?>"<?= $me() ? '' : ' disabled' ?>><?= $liked ? $icons['heartF'] : $icons['heart'] ?><span><?= $lc ?></span></button></form>
<a href="?v=p&id=<?= $p['id'] ?>" class="btn-action" onclick="event.stopPropagation()"><?= $icons['comment'] ?><span><?= $cc ?></span></a>
</div>
</div></article>
<?php return ob_get_clean(); }
/* ── API ── */
if (isset($_GET['api'])) {
header('Content-Type: application/json');
$ip = ipAddr();
if (isBannedIp($ip) || ($me() && isBannedUser($me()))) { http_response_code(403); echo json_encode(['error' => 'Banned']); exit; }
if ($_GET['api'] === 'posts') {
$off = (int)($_GET['offset'] ?? 0); $lim = 10;
$vw = $_GET['view'] ?? 'home'; $uid = (int)($_GET['uid'] ?? 0);
$blk = $me() ? " AND NOT EXISTS(SELECT 1 FROM bl WHERE (a=? AND b=p.uid) OR (a=p.uid AND b=?))" : "";
if ($vw === 'feed' && $me())
$rows = q("SELECT p.* FROM p JOIN f ON p.uid=f.b WHERE f.a=?$blk UNION SELECT * FROM p WHERE uid=?$blk ORDER BY ts DESC LIMIT ? OFFSET ?",
$me() ? [$me(), $me(), $me(), $me(), $me(), $lim, $off] : [$me(), $me(), $lim, $off]);
elseif ($vw === 'user' && $uid)
$rows = q("SELECT * FROM p WHERE uid=?".($me() ? " AND NOT EXISTS(SELECT 1 FROM bl WHERE (a=? AND b=?) OR (a=? AND b=?))" : "")." ORDER BY ts DESC LIMIT ? OFFSET ?",
$me() ? [$uid, $me(), $uid, $uid, $me(), $lim, $off] : [$uid, $lim, $off]);
else
$rows = q("SELECT * FROM p".($me() ? " WHERE NOT EXISTS(SELECT 1 FROM bl WHERE (a=? AND b=p.uid) OR (a=p.uid AND b=?))" : "")." ORDER BY ts DESC LIMIT ? OFFSET ?",
$me() ? [$me(), $me(), $lim, $off] : [$lim, $off]);
$posts = $rows->fetchAll(PDO::FETCH_ASSOC);
$html = ''; foreach ($posts as $p) $html .= postHtml($p);
echo json_encode(['html' => $html, 'hasMore' => count($posts) === $lim]);
} elseif ($_GET['api'] === 'search') {
$raw = trim($_GET['q'] ?? ''); $type = $_GET['type'] ?? 'all';
$lim = ($_GET['full'] ?? '') ? 20 : 5;
if (strlen($raw) < 2) { echo json_encode(['users' => [], 'posts' => []]); exit; }
$sq = "%$raw%";
$users = $type !== 'posts'
? q("SELECT id,name,bio FROM u WHERE name LIKE ?".($me() ? " AND NOT EXISTS(SELECT 1 FROM bl WHERE (a=? AND b=u.id) OR (a=u.id AND b=?))" : "")." LIMIT ?",
$me() ? [$sq, $me(), $me(), $lim] : [$sq, $lim])->fetchAll(PDO::FETCH_ASSOC) : [];
$posts = $type !== 'users'
? q("SELECT p.id,p.txt,u.name FROM p JOIN u ON p.uid=u.id WHERE p.txt LIKE ?".($me() ? " AND NOT EXISTS(SELECT 1 FROM bl WHERE (a=? AND b=p.uid) OR (a=p.uid AND b=?))" : "")." ORDER BY p.ts DESC LIMIT ?",
$me() ? [$sq, $me(), $me(), $lim] : [$sq, $lim])->fetchAll(PDO::FETCH_ASSOC) : [];
echo json_encode([
'users' => array_map(fn($u) => ['id' => $u['id'], 'name' => $h($u['name']), 'bio' => $h($u['bio'])], $users),
'posts' => array_map(fn($p) => ['id' => $p['id'], 'txt' => $h(mb_substr($p['txt'], 0, 80)), 'name' => $h($p['name'])], $posts)
]);
} elseif ($_GET['api'] === 'rels') {
$off = (int)($_GET['offset'] ?? 0); $lim = 20;
$uid = (int)($_GET['uid'] ?? 0);
$type = $_GET['type'] ?? 'followers';
if (!$uid || !in_array($type, ['followers','following'], true)) { echo json_encode(['html' => '', 'hasMore' => false]); exit; }
$meId = $me();
$blk = $meId ? " AND NOT EXISTS(SELECT 1 FROM bl WHERE (a=? AND b=u.id) OR (a=u.id AND b=?))" : "";
if ($type === 'followers') {
$sql = "SELECT u.id,u.name,u.bio," . ($meId ? " EXISTS(SELECT 1 FROM f fx WHERE fx.a=? AND fx.b=u.id) AS isFollowing" : " 0 AS isFollowing") .
" FROM f JOIN u ON u.id=f.a WHERE f.b=?$blk ORDER BY u.name COLLATE NOCASE LIMIT ? OFFSET ?";
$p = $meId ? [$meId, $uid, $meId, $meId, $lim, $off] : [$uid, $lim, $off];
} else {
$sql = "SELECT u.id,u.name,u.bio," . ($meId ? " EXISTS(SELECT 1 FROM f fx WHERE fx.a=? AND fx.b=u.id) AS isFollowing" : " 0 AS isFollowing") .
" FROM f JOIN u ON u.id=f.b WHERE f.a=?$blk ORDER BY u.name COLLATE NOCASE LIMIT ? OFFSET ?";
$p = $meId ? [$meId, $uid, $meId, $meId, $lim, $off] : [$uid, $lim, $off];
}
$rows = q($sql, $p)->fetchAll(PDO::FETCH_ASSOC);
$html = '';
foreach ($rows as $ru) {
$isMe = $meId && ((int)$ru['id'] === $meId);
$canFollow = $meId && !$isMe;
$followed = (int)($ru['isFollowing'] ?? 0);
$html .= '<div class="rel-item" onclick="location.href=\'?v=u&id=' . (int)$ru['id'] . '\'">';
$html .= '<div class="avatar av-m">' . strtoupper($h($ru['name'])[0] ?? 'U') . '</div>';
$html .= '<div class="rel-body"><div class="rel-name">' . $h($ru['name']) . '</div>';
$bio = trim((string)($ru['bio'] ?? ''));
$html .= '<div class="rel-bio">' . ($bio ? $h($bio) : 'No bio yet') . '</div></div>';
if ($canFollow) {
$html .= '<form method="post" onclick="event.stopPropagation()" data-rel-follow="1">';
$html .= '<input type="hidden" name="t" value="' . $tk() . '"><input type="hidden" name="a" value="fol">';
$html .= '<input type="hidden" name="tid" value="' . (int)$ru['id'] . '">';
$html .= '<input type="hidden" name="ajax" value="1">';
$html .= '<button class="btn' . ($followed ? ' btn-outline' : '') . '">' . ($followed ? 'Following' : 'Follow') . '</button></form>';
}
$html .= '</div>';
}
echo json_encode(['html' => $html, 'hasMore' => count($rows) === $lim]);
}
exit;
}
/* ── POST Actions ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (($_POST['t'] ?? '') !== $tk()) die('Invalid token');
if (!checkRate(session_id())) { http_response_code(429); die('Rate limit exceeded'); }
$ip = ipAddr();
if (isBannedIp($ip) || ($me() && isBannedUser($me()))) { http_response_code(403); die('Banned'); }
$a = $_POST['a'] ?? '';
if ($a === 'reg') {
if (isBannedIp($ip)) { $_SESSION['err'] = 'Access denied'; }
$n = trim($_POST['n'] ?? ''); $pw = $_POST['pw'] ?? '';
if (strlen($n) >= 2 && strlen($n) <= 20 && preg_match('/^\w+$/', $n) && strlen($pw) >= 4) {
if (q("SELECT 1 FROM u WHERE name=? COLLATE NOCASE", [$n])->fetch())
$_SESSION['err'] = 'Username already taken';
else {
$first = !q("SELECT 1 FROM u")->fetch();
q("INSERT INTO u(name,pw,ts,admin) VALUES(?,?,?,?)", [$n, password_hash($pw, PASSWORD_DEFAULT), now(), $first ? 1 : 0]);
$_SESSION['u'] = $db->lastInsertId();
touchUserIp($_SESSION['u']);
}
} else $_SESSION['err'] = 'Invalid username or password too short';
}
if ($a === 'log') {
$r = q("SELECT * FROM u WHERE name=? COLLATE NOCASE", [$_POST['n'] ?? ''])->fetch(PDO::FETCH_ASSOC);
if ($r && password_verify($_POST['pw'] ?? '', $r['pw'])) {
if (isBannedIp($ip) || isBannedUser((int)$r['id'])) $_SESSION['err'] = 'Access denied';
else { $_SESSION['u'] = $r['id']; touchUserIp($_SESSION['u']); }
} else $_SESSION['err'] = 'Invalid username or password';
}
if ($a === 'out') { session_destroy(); header('Location: ?'); exit; }
if ($a === 'post' && $me() && ($txt = trim($_POST['txt'] ?? '')))
q("INSERT INTO p(uid,txt,ts) VALUES(?,?,?)", [$me(), mb_substr($txt, 0, $POST_MAX), now()]);
if ($a === 'cmt' && $me() && ($txt = trim($_POST['txt'] ?? '')) && ($pid = (int)($_POST['pid'] ?? 0)))
q("INSERT INTO c(pid,uid,txt,ts) VALUES(?,?,?,?)", [$pid, $me(), mb_substr($txt, 0, 200), now()]);
if ($a === 'like' && $me() && ($pid = (int)($_POST['pid'] ?? 0))) {
$e = q("SELECT 1 FROM l WHERE uid=? AND pid=?", [$me(), $pid])->fetch();
q($e ? "DELETE FROM l WHERE uid=? AND pid=?" : "INSERT INTO l VALUES(?,?)", [$me(), $pid]);
}
if ($a === 'fol' && $me() && ($tid = (int)($_POST['tid'] ?? 0)) && $tid !== $me()) {
$e = q("SELECT 1 FROM f WHERE a=? AND b=?", [$me(), $tid])->fetch();
q($e ? "DELETE FROM f WHERE a=? AND b=?" : "INSERT INTO f VALUES(?,?)", [$me(), $tid]);
if (!empty($_POST['ajax'])) {
header('Content-Type: application/json');
echo json_encode(['following' => $e ? false : true]);
exit;
}
}
if ($a === 'bio' && $me()) {
q("UPDATE u SET bio=? WHERE id=?", [mb_substr(trim($_POST['bio'] ?? ''), 0, $BIO_MAX), $me()]);
$_SESSION['bio_updated'] = time();
}
if ($a === 'del' && $me() && ($pid = (int)($_POST['pid'] ?? 0))) {
$p = q("SELECT uid FROM p WHERE id=?", [$pid])->fetch(PDO::FETCH_ASSOC);
if ($p && ($p['uid'] == $me() || (usr($me())['admin'] ?? 0))) {
q("DELETE FROM c WHERE pid=?", [$pid]); q("DELETE FROM l WHERE pid=?", [$pid]); q("DELETE FROM p WHERE id=?", [$pid]);
}
}
if ($a === 'delu' && $me() && (usr($me())['admin'] ?? 0) && ($tid = (int)($_POST['tid'] ?? 0)) && $tid !== $me()) {
foreach (['c','l','p'] as $t) q("DELETE FROM $t WHERE uid=?", [$tid]);
q("DELETE FROM f WHERE a=? OR b=?", [$tid, $tid]); q("DELETE FROM u WHERE id=?", [$tid]);
}
if ($a === 'delme' && $me()) {
$tid = $me();
foreach (['c','l','p'] as $t) q("DELETE FROM $t WHERE uid=?", [$tid]);
q("DELETE FROM f WHERE a=? OR b=?", [$tid, $tid]);
q("DELETE FROM bl WHERE a=? OR b=?", [$tid, $tid]);
q("DELETE FROM bu WHERE uid=?", [$tid]);
q("DELETE FROM uip WHERE uid=?", [$tid]);
q("DELETE FROM u WHERE id=?", [$tid]);
session_destroy(); header('Location: ?'); exit;
}
if ($a === 'chname' && $me()) {
$n = trim($_POST['n'] ?? '');
if (strlen($n) >= 2 && strlen($n) <= 20 && preg_match('/^\w+$/', $n)) {
if (q("SELECT 1 FROM u WHERE name=? COLLATE NOCASE AND id<>?", [$n, $me()])->fetch()) $_SESSION['err'] = 'Username already taken';
else q("UPDATE u SET name=? WHERE id=?", [$n, $me()]);
} else $_SESSION['err'] = 'Invalid username';
}
if ($a === 'chpw' && $me()) {
$cur = $_POST['cur'] ?? ''; $pw = $_POST['pw'] ?? '';
$r = usr($me());
if (!$r || !password_verify($cur, $r['pw'])) $_SESSION['err'] = 'Current password is incorrect';
elseif (strlen($pw) < 4) $_SESSION['err'] = 'Password too short';
else q("UPDATE u SET pw=? WHERE id=?", [password_hash($pw, PASSWORD_DEFAULT), $me()]);
}
if ($a === 'blk' && $me() && ($tid = (int)($_POST['tid'] ?? 0)) && $tid !== $me()) {
$e = q("SELECT 1 FROM bl WHERE a=? AND b=?", [$me(), $tid])->fetch();
if ($e) q("DELETE FROM bl WHERE a=? AND b=?", [$me(), $tid]);
else q("INSERT INTO bl(a,b,ts) VALUES(?,?,?)", [$me(), $tid, now()]);
}
if ($a === 'ban' && $me() && (usr($me())['admin'] ?? 0) && ($tid = (int)($_POST['tid'] ?? 0)) && $tid !== $me()) {
$dur = $_POST['dur'] ?? '1d';
$perma = !empty($_POST['perma']);
$secs = ['1h'=>3600,'1d'=>86400,'7d'=>604800,'30d'=>2592000][$dur] ?? 86400;
$until = $perma ? (now() + 10*365*86400) : (now() + $secs);
q("INSERT OR REPLACE INTO bu(uid,until_ts,ts) VALUES(?,?,?)", [$tid, $until, now()]);
if (!empty($_POST['ipban'])) {
$uip = lastUserIp($tid);
if ($uip) q("INSERT OR REPLACE INTO bip(ip,until_ts,ts) VALUES(?,?,?)", [$uip, $until, now()]);
}
}
$base = strtok($_SERVER['REQUEST_URI'], '?');
$redir = $base . (isset($_GET['v']) ? '?v=' . $_GET['v'] . (isset($_GET['id']) ? '&id=' . $_GET['id'] : '') : '');
if (isset($_SESSION['err'])) $redir .= (str_contains($redir, '?') ? '&' : '?') . 'auth=1';
header('Location:' . $redir); exit;
}
$v = $_GET['v'] ?? 'home';
$self = usr($me());
$ip = ipAddr();
$banned = isBannedIp($ip) || ($me() && isBannedUser($me()));
$showAuth = isset($_GET['auth']) && $err;
$titles = ['home'=>'Home','explore'=>'Explore','feed'=>'Your Feed','u'=>'Profile','admin'=>'Admin','search'=>'Search','terms'=>'Terms','privacy'=>'Privacy','guidelines'=>'Guidelines'];
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>μSocial</title>
<style>
:root{--bg:#e8e4e0;--surface:#fff;--border:#d5d0cb;--text:#2d2d2d;--text2:#6b7280;--accent:#51344D;--accent-lt:#6b4765;--danger:#dc2626;--radius:16px;--shadow:0 2px 8px rgba(0,0,0,.08)}
*{box-sizing:border-box;margin:0;padding:0}
body{font:16px/1.6 'Trebuchet MS',Avenir,'Segoe UI',sans-serif;background:var(--bg);color:var(--text);min-height:100vh}
a{color:var(--accent);text-decoration:none} a:hover{text-decoration:underline}
/* Layout */
.layout{display:flex;justify-content:center;min-height:100vh;gap:24px;padding:0 16px}
.sidebar-left{width:68px;position:sticky;top:0;height:100vh;padding:16px 0;display:flex;flex-direction:column;align-items:center}
.sidebar-right{width:300px;min-width:300px;position:sticky;top:0;height:100vh;padding:20px 0;display:flex;flex-direction:column}
.main-col{display:flex;flex-direction:column;gap:16px;width:100%;max-width:580px;margin-top:16px;margin-bottom:16px}
.welcome-container{position:relative;border-radius:var(--radius);padding:32px 24px;box-shadow:var(--shadow);background:url('assets/banner.png') center/cover no-repeat,#000;color:#f9fafb;display:flex;align-items:flex-end;min-height:260px;overflow:hidden}
.welcome-container::after{content:'';position:absolute;inset:0;background:linear-gradient(180deg,rgba(0,0,0,0) 0,rgba(0,0,0,.65) 100%);pointer-events:none}
.welcome-inner{position:relative;z-index:1}
.welcome-container h2{margin:0 0 4px;font-size:22px;font-weight:700;color:#f9fafb}
.welcome-container p{margin:0;color:rgba(249,250,251,.85);font-size:15px;line-height:1.5;font-weight:700}
.main{width:100%;min-height:100vh;background:var(--surface);border-radius:var(--radius);padding-bottom:24px;box-shadow:var(--shadow)}
/* Shared: Avatars */
.avatar{border-radius:50%;background:var(--accent);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;flex-shrink:0}
.av-s{width:32px;height:32px;font-size:12px}
.av-m{width:44px;height:44px;font-size:15px}
.av-l{width:80px;height:80px;font-size:32px}
/* Shared: Dropdowns */
.dropdown{position:absolute;background:var(--surface);border-radius:12px;box-shadow:0 4px 20px rgba(0,0,0,.15);padding:6px;display:none;min-width:150px;z-index:50}
.dropdown.active{display:block}
.dropdown button,.dropdown a{width:100%;display:flex;align-items:center;gap:10px;padding:10px 12px;border:none;background:transparent;color:var(--text);cursor:pointer;border-radius:8px;font:inherit;font-size:14px;text-align:left;text-decoration:none}
.dropdown button:hover,.dropdown a:hover{background:var(--bg);text-decoration:none}
.dropdown .danger{color:var(--danger)} .dropdown .danger:hover{background:#fef2f2}
.dropdown svg{width:16px;height:16px;flex-shrink:0} .dropdown form{margin:0}
.dropdown.icon-only{min-width:auto;padding:6px;gap:6px}
.dropdown.icon-only.active{display:flex}
.dropdown.icon-only button,.dropdown.icon-only a{width:38px;height:38px;justify-content:center;padding:0;gap:0}
.dropdown.icon-only svg{width:18px;height:18px}
/* Shared: Tabs */
.tabs{display:flex;border-bottom:1px solid var(--border)}
.tab{flex:1;padding:14px;text-align:center;cursor:pointer;border:none;border-bottom:3px solid transparent;font-weight:600;color:var(--text2);background:none;font:inherit;transition:all .2s}
.tab:hover{background:var(--bg)} .tab.active{border-bottom-color:var(--accent);color:var(--accent)}
/* Nav */
.logo{font-size:24px;font-weight:800;color:var(--accent);margin-bottom:24px;text-decoration:none}
.logo:hover{text-decoration:none}
.nav{display:flex;flex-direction:column;gap:8px;align-items:center}
.nav-item{width:48px;height:48px;display:flex;align-items:center;justify-content:center;border-radius:50%;color:var(--text);transition:all .2s;border:none;background:transparent;cursor:pointer}
.nav-item:hover{background:var(--surface);color:var(--accent);text-decoration:none;box-shadow:var(--shadow)}
.nav-item.active{background:var(--accent);color:#fff} .nav-item.active:hover{background:var(--accent-lt)}
.nav-item svg{width:24px;height:24px}
/* Header */
.header{padding:20px;font-size:20px;font-weight:700;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:16px}
.btn-back{width:36px;height:36px;border-radius:50%;display:flex;align-items:center;justify-content:center;color:var(--text);transition:background .2s}
.btn-back:hover{background:var(--bg);text-decoration:none} .btn-back svg{width:20px;height:20px}
.btn-icon{width:32px;height:32px;border-radius:50%;background:transparent;border:none;color:var(--text2);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .2s}
.btn-icon:hover{background:var(--bg);color:var(--text)} .btn-icon svg{width:18px;height:18px}
/* Composer */
.composer{padding:16px 20px;border-bottom:1px solid var(--border);display:flex;gap:12px}
.composer-input{flex:1;display:flex;flex-direction:column;gap:12px}
.composer textarea{background:transparent;border:none;color:var(--text);font-size:17px;resize:none;min-height:60px;outline:none;font-family:inherit}
.composer textarea::placeholder{color:var(--text2)}
.composer-actions{display:flex;justify-content:flex-end}
.char-count{margin-right:12px;color:var(--text2);font-weight:700;font-size:14px;align-self:center;min-width:36px;text-align:right;visibility:hidden}
.char-count.show{visibility:visible}
.char-count.over{color:var(--danger)}
/* Posts */
.post{display:flex;gap:12px;padding:16px 20px;border-bottom:1px solid var(--border);transition:background .2s;cursor:pointer}
.post:hover{background:rgba(0,0,0,.02)}
.post.single{cursor:default} .post.single:hover{background:transparent}
.post-body{flex:1;min-width:0}
.post-head{display:flex;align-items:center;gap:6px;margin-bottom:4px}
.post-author{font-weight:700;color:var(--text)} .post-author:hover{color:var(--accent);text-decoration:underline}
.meta{color:var(--text2);font-size:14px}
.post-menu{margin-left:auto;position:relative} .post-menu .dropdown{top:100%;right:0}
.profile-menu .dropdown{top:100%;right:0;margin-top:8px}
.post-text{white-space:pre-wrap;word-break:break-word;line-height:1.5}
.post-actions{display:flex;gap:32px;margin-top:12px;align-items:center}
.btn-action{background:none;border:none;color:var(--text2);cursor:pointer;display:flex;align-items:center;gap:6px;padding:6px 10px;margin:-6px -10px;border-radius:20px;transition:all .2s;font-size:14px;text-decoration:none;line-height:1}
.btn-action:hover{color:var(--accent);background:rgba(81,52,77,.1);text-decoration:none}
.btn-action.liked{color:var(--danger)} .btn-action.liked:hover{background:rgba(220,38,38,.1)}
.btn-action svg{width:18px;height:18px} .btn-action:disabled{opacity:.4;cursor:not-allowed}
.inline{display:contents}
/* Comments */
.comments-section{border-top:1px solid var(--border)}
.comments-section h3{padding:16px 20px;font-size:16px;border-bottom:1px solid var(--border)}
.comment{padding:12px 20px;border-bottom:1px solid var(--border);display:flex;gap:10px}
.comment-body{flex:1;min-width:0}
.comment-author{font-weight:600;color:var(--text)}
.comment-text{color:var(--text);margin-top:2px} .comment-time{font-size:12px;color:var(--text2);margin-top:4px}
.comment-form{padding:16px 20px;display:flex;gap:10px;border-bottom:1px solid var(--border)}
.comment-form input{flex:1;background:var(--bg);border:1px solid var(--border);border-radius:20px;padding:10px 16px;color:var(--text);font-size:14px;outline:none;font-family:inherit}
.comment-form input:focus{border-color:var(--accent)}
.btn-send{width:40px;height:40px;border-radius:50%;background:var(--accent);color:#fff;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0}
.btn-send:hover{background:var(--accent-lt)} .btn-send svg{width:18px;height:18px}
/* Search */
.search-box{position:relative}
.search-box input{width:100%;background:var(--surface);border:1px solid var(--border);border-radius:24px;padding:12px 16px 12px 44px;color:var(--text);font-size:15px;outline:none;font-family:inherit}
.search-box input:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(81,52,77,.1)}
.search-box>svg{position:absolute;left:16px;top:50%;transform:translateY(-50%);width:18px;height:18px;color:var(--text2);pointer-events:none}
.search-results{position:absolute;top:100%;left:0;right:0;background:var(--surface);border:1px solid var(--border);border-radius:16px;margin-top:8px;max-height:400px;overflow-y:auto;display:none;z-index:100;box-shadow:0 4px 20px rgba(0,0,0,.12)}
.search-results.active{display:block}
.search-section{padding:12px} .search-section+.search-section{border-top:1px solid var(--border)}
.search-label{font-size:12px;font-weight:600;color:var(--text2);text-transform:uppercase;letter-spacing:.05em;margin-bottom:8px;padding:0 10px}
.search-item{display:flex;align-items:center;gap:12px;padding:10px;border-radius:10px;cursor:pointer;transition:background .2s;text-decoration:none;color:var(--text)}
.search-item:hover{background:var(--bg);text-decoration:none}
.si-text{min-width:0;flex:1} .si-name{font-weight:600}
.si-sub{font-size:13px;color:var(--text2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.search-page-empty{padding:60px 20px;text-align:center;color:var(--text2)}
/* Profile */
.profile-header{padding:24px 20px;border-bottom:1px solid var(--border);position:relative}
.profile-menu{position:absolute;top:20px;right:20px}
.profile-name{font-size:22px;font-weight:700;margin-top:16px}
.profile-bio{color:var(--text2);margin:8px 0}
.profile-stats{display:flex;gap:20px;margin:12px 0;font-size:15px}
.profile-stats b{color:var(--text)} .profile-stats span{color:var(--text2)}
.profile-stats button{border:none;background:transparent;padding:0;margin:0;cursor:pointer;font:inherit}
.profile-stats button:hover span{text-decoration:underline}
.rel-item{display:flex;align-items:center;gap:12px;padding:14px 16px;border-bottom:1px solid var(--border);cursor:pointer}
.rel-item:hover{background:rgba(0,0,0,.02)}
.rel-body{flex:1;min-width:0}
.rel-name{font-weight:700}
.rel-bio{color:var(--text2);font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.rel-list{max-height:560px;overflow:auto}
.rel-empty{padding:60px 24px;text-align:center;color:var(--text2)}
#followers-modal,#following-modal{max-width:680px}
.bio-form{margin-top:16px;display:flex;gap:10px}
.bio-form input{flex:1;background:var(--bg);border:1px solid var(--border);border-radius:10px;padding:10px 14px;color:var(--text);font-family:inherit}
.bio-form input:focus{outline:none;border-color:var(--accent)}
/* Buttons & Forms */
.btn{background:var(--accent);color:#fff;border:none;padding:10px 20px;border-radius:24px;font-weight:600;cursor:pointer;transition:background .2s;font-family:inherit}
.btn:hover{background:var(--accent-lt)}
.btn-outline{background:transparent;border:2px solid var(--border);color:var(--text)}
.btn-outline:hover{background:var(--bg);border-color:var(--text2)}
.badge{background:var(--accent);color:#fff;font-size:11px;padding:3px 8px;border-radius:6px;margin-left:8px;font-weight:600}
.admin-item{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--border)}
.admin-item a{font-weight:600}
/* Footer */
.footer{margin-top:auto;padding-top:20px}
.footer-links{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:13px}
.footer-links a,.footer-links span{color:var(--text2)} .footer-links a:hover{color:var(--accent)}
/* Legal pages */
.legal{padding:28px 28px 32px;max-width:720px;margin:0 auto;line-height:1.7}
.legal-hero{margin-bottom:18px;font-size:14px;color:var(--text2)}
.legal-hero p{margin:0 0 4px}
.legal-updated{display:inline-flex;gap:8px;align-items:center;margin-top:2px;color:var(--text2);font-size:13px}
.legal-sections{display:block}
.legal-sec{padding:0;margin:0 0 18px}
.legal-sec h3{margin:0 0 6px;font-size:16px;font-weight:700;color:var(--text)}
.legal-sec p{margin:0 0 6px;color:var(--text2);font-size:14px}
.legal-bullets{margin:6px 0 0;padding-left:18px;color:var(--text2);font-size:14px}
.legal-bullets li{margin:4px 0}
/* Dialogs */
dialog{background:var(--surface);border:none;border-radius:20px;padding:0;max-width:400px;width:calc(100% - 32px);color:var(--text);box-shadow:0 8px 40px rgba(0,0,0,.2);position:fixed;top:50%;left:50%;transform:translate(-50%,-50%)}
dialog[open]{display:flex;flex-direction:column} dialog::backdrop{background:rgba(0,0,0,.5)}
#settings-modal{max-width:760px}
.modal-header{display:flex;align-items:center;padding:16px 20px;border-bottom:1px solid var(--border)}
.modal-header h2{flex:1;text-align:center;font-size:18px}
.modal-close{width:36px;height:36px;display:flex;align-items:center;justify-content:center;background:none;border:none;color:var(--text2);cursor:pointer;border-radius:50%}
.modal-close:hover{background:var(--bg);color:var(--text)} .modal-close svg{width:20px;height:20px}
.modal-content{padding:24px}
.form-group{margin-bottom:16px}
.form-group label{display:block;font-size:14px;font-weight:600;color:var(--text2);margin-bottom:6px}
.form-group input{width:100%;background:var(--bg);border:1px solid var(--border);border-radius:10px;padding:14px;color:var(--text);font-size:16px;font-family:inherit}
.form-group input:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px rgba(81,52,77,.1)}
.form-submit{width:100%;margin-top:20px;padding:14px}
.form-error{background:#fef2f2;border:1px solid #fecaca;color:#dc2626;padding:12px 16px;border-radius:10px;margin-bottom:16px;font-size:14px}
.settings{display:flex;min-height:460px}
.settings-nav{width:170px;border-right:1px solid var(--border);padding:12px}
.settings-nav button{width:100%;display:flex;align-items:center;gap:10px;padding:10px 10px;border:none;background:transparent;color:var(--text2);cursor:pointer;border-radius:10px;font:inherit;font-size:14px;text-align:left}
.settings-nav svg{width:16px;height:16px}
.settings-nav button.active{background:var(--bg);color:var(--text);font-weight:700}
.settings-body{flex:1;padding:20px 22px}
.settings-panel{display:none}
.settings-panel.active{display:block}
.settings-body .form-group{margin-bottom:14px}
.settings-danger{margin-top:14px;padding-top:14px;border-top:1px solid var(--border)}
/* Misc */
#loader{text-align:center;min-height:1px;color:var(--text2);visibility:hidden}
#loader.loading{padding:24px;visibility:visible}
.toast{position:fixed;bottom:90px;left:50%;transform:translateX(-50%);background:var(--text);color:#fff;padding:12px 20px;border-radius:24px;font-size:14px;z-index:1000;opacity:0;transition:opacity .3s}
.toast.show{opacity:1}
.mobile-nav{display:none}
@media(max-width:1100px){.sidebar-right{display:none}}
@media(max-width:700px){
.layout{padding:0;gap:0} .sidebar-left{display:none}
.main-col{margin-top:0;margin-bottom:0}
.welcome-container{border-radius:0}
.main{margin:0;border-radius:0;padding-bottom:70px}
.mobile-nav{display:flex;position:fixed;bottom:0;left:0;right:0;background:var(--surface);border-top:1px solid var(--border);z-index:100}
.mobile-nav a,.mobile-nav button{flex:1;display:flex;justify-content:center;align-items:center;padding:14px;color:var(--text);background:none;border:none;cursor:pointer;text-decoration:none}
.mobile-nav a.active{color:var(--accent)} .mobile-nav svg{width:26px;height:26px}
}
</style>
</head>
<body>
<div class="layout">
<!-- Left Sidebar -->
<aside class="sidebar-left">
<a href="?" class="logo">μ</a>
<nav class="nav">
<a href="?" class="nav-item<?= $v === 'home' ? ' active' : '' ?>"><?= $icons['home'] ?></a>
<a href="?v=explore" class="nav-item<?= $v === 'explore' ? ' active' : '' ?>"><?= $icons['globe'] ?></a>
<?php if ($me()): ?>
<a href="?v=u&id=<?= $me() ?>" class="nav-item<?= $v === 'u' && ($_GET['id'] ?? 0) == $me() ? ' active' : '' ?>"><?= $icons['user'] ?></a>
<?php if ($self['admin'] ?? 0): ?><a href="?v=admin" class="nav-item<?= $v === 'admin' ? ' active' : '' ?>"><?= $icons['gear'] ?></a><?php endif ?>
<?php else: ?>
<button class="nav-item" onclick="document.getElementById('auth-modal').showModal()"><?= $icons['user'] ?></button>
<?php endif ?>
</nav>
</aside>
<!-- Main Content -->
<div class="main-col">
<?php if ($v === 'home'): ?>
<div class="welcome-container">
<div class="welcome-inner">
<h2>Welcome to μSocial</h2>
<p>a lightweight social feed</p>
</div>
</div>
<?php endif ?>
<main class="main">
<?php if ($v === 'p' && ($pid = (int)($_GET['id'] ?? 0)) && ($post = getPost($pid))): ?>
<div class="header"><a href="javascript:history.back()" class="btn-back"><?= $icons['back'] ?></a><span>Post</span></div>
<?= postHtml($post, true) ?>
<div class="comments-section">
<?php $comments = q("SELECT c.*,u.name FROM c JOIN u ON c.uid=u.id WHERE pid=? ORDER BY ts DESC", [$pid])->fetchAll(PDO::FETCH_ASSOC); ?>
<h3>Comments (<?= count($comments) ?>)</h3>
<?php if ($me()): ?>
<form method="post" class="comment-form"><input type="hidden" name="t" value="<?= $tk() ?>">
<input type="hidden" name="a" value="cmt"><input type="hidden" name="pid" value="<?= $pid ?>">
<input name="txt" placeholder="Write a comment..." maxlength="200" required>
<button type="submit" class="btn-send"><?= $icons['send'] ?></button></form>
<?php endif ?>
<?php foreach ($comments as $c): ?>
<div class="comment">
<div class="avatar av-s"><?= strtoupper($c['name'][0]) ?></div>
<div class="comment-body">
<a href="?v=u&id=<?= $c['uid'] ?>" class="comment-author"><?= $h($c['name']) ?></a>
<div class="comment-text"><?= $h($c['txt']) ?></div>
<div class="comment-time"><?= date('M j, g:i a', $c['ts']) ?></div>
</div>
</div>
<?php endforeach ?>
<?php if (!$comments): ?><div style="padding:40px 20px;text-align:center;color:var(--text2)">No comments yet</div><?php endif ?>
</div>
<?php elseif ($v === 'search'): ?>
<div class="header">
<a href="javascript:history.back()" class="btn-back"><?= $icons['back'] ?></a>
<div class="search-box" style="flex:1"><?= $icons['search'] ?>
<input type="search" id="page-search" placeholder="Search μSocial..." autocomplete="off" autofocus>
</div>
</div>
<div class="tabs">
<button class="tab active" data-type="all">All</button>
<button class="tab" data-type="users">Users</button>
<button class="tab" data-type="posts">Posts</button>
</div>
<div id="page-results"></div>
<div class="search-page-empty" id="search-empty">Search for users and posts</div>
<?php elseif ($v === 'terms'): ?>
<div class="header">
<a href="javascript:history.back()" class="btn-back"><?= $icons['back'] ?></a>
<span>Terms of Service</span>
</div>
<div class="legal">
<div class="legal-hero">
<p>These Terms govern your use of μSocial. Please read them carefully. By using the service, you agree to comply with them.</p>
<div class="legal-updated"><span style="font-weight:700;color:var(--text)">Last updated</span><span>Feb 2, 2026</span></div>
</div>
<div class="legal-sections">
<section class="legal-sec"><h3>1. Acceptance of Terms</h3><p>By accessing or using μSocial, you agree to these Terms and applicable laws. If you do not agree, do not use the service.</p></section>
<section class="legal-sec"><h3>2. Accounts</h3><p>You’re responsible for your account and keeping your credentials secure. You must provide accurate information and notify us of unauthorized use. You must be at least 13 years old to use the service.</p></section>
<section class="legal-sec"><h3>3. User Content</h3><p>You own what you post. You grant μSocial a worldwide, non-exclusive, royalty-free license to host, display, and distribute your content solely for operating and improving the service. You represent you have the rights to post it.</p></section>
<section class="legal-sec"><h3>4. Prohibited Conduct</h3><p>Do not post illegal, harmful, harassing, defamatory, infringing, or abusive content. Do not spam, impersonate others, or attempt to disrupt or abuse the service.</p></section>
<section class="legal-sec"><h3>5. Moderation & Enforcement</h3><p>We may remove content and suspend or terminate accounts for violations or to protect the community. Enforcement decisions are at our discretion.</p></section>
<section class="legal-sec"><h3>6. Disclaimers</h3><p>The service is provided “as is” without warranties. We don’t guarantee uninterrupted or error-free operation.</p></section>
<section class="legal-sec"><h3>7. Limitation of Liability</h3><p>To the maximum extent permitted by law, μSocial is not liable for indirect, incidental, special, consequential, or punitive damages. If the service is free, our total liability is limited to $0.</p></section>
<section class="legal-sec"><h3>8. Indemnification</h3><p>You agree to indemnify and hold harmless μSocial and its operators from claims arising out of your use of the service or your violation of these Terms.</p></section>
<section class="legal-sec"><h3>9. Changes</h3><p>We may update these Terms. Continued use after changes means you accept the updated Terms.</p></section>
<section class="legal-sec"><h3>10. Termination</h3><p>We may suspend or terminate access for violations. You may stop using the service at any time.</p></section>
</div>
</div>
<?php elseif ($v === 'privacy'): ?>
<div class="header">
<a href="javascript:history.back()" class="btn-back"><?= $icons['back'] ?></a>
<span>Privacy Policy</span>
</div>
<div class="legal">
<div class="legal-hero">
<p>We collect the minimum data needed to run μSocial and keep it secure. This policy explains what we collect, how we use it, and your choices.</p>
<div class="legal-updated"><span style="font-weight:700;color:var(--text)">Last updated</span><span>Feb 2, 2026</span></div>
</div>
<div class="legal-sections">
<section class="legal-sec"><h3>1. Information we collect</h3><p>Account and content data you provide: username, password hash, bio, posts, comments, likes, and follow relationships. We also store session data needed to keep you signed in.</p></section>
<section class="legal-sec"><h3>2. How we use information</h3><p>To provide and operate the service, authenticate users, display content, prevent abuse, and enforce our Terms. We do not use your data for advertising.</p></section>
<section class="legal-sec"><h3>3. What’s public</h3><p>Your profile (username and bio) and your posts/comments are visible to other users. Some activity (likes/follows) may be visible as part of the social graph.</p></section>
<section class="legal-sec"><h3>4. Sharing</h3><p>We do not sell personal information. We may disclose information if required by law or to protect the service, users, and our rights.</p></section>
<section class="legal-sec"><h3>5. Security</h3><p>Passwords are stored using secure hashing. We use reasonable measures to protect data, but no system is 100% secure.</p></section>
<section class="legal-sec"><h3>6. Retention & deletion</h3><p>We keep data while your account is active. If you delete your account, we remove your content from the service; limited data may remain in backups for a short time.</p></section>
<section class="legal-sec"><h3>7. Cookies</h3><p>We use a session cookie to keep you logged in. We do not use third‑party tracking cookies.</p></section>
<section class="legal-sec"><h3>8. Children</h3><p>The service isn’t intended for children under 13. If we learn we collected data from a child under 13, we’ll delete it.</p></section>
<section class="legal-sec"><h3>9. Changes</h3><p>We may update this policy. Continued use after changes means you accept the updated policy.</p></section>
</div>
</div>
<?php elseif ($v === 'guidelines'): ?>
<div class="header">
<a href="javascript:history.back()" class="btn-back"><?= $icons['back'] ?></a>
<span>Community Guidelines</span>
</div>
<div class="legal">
<div class="legal-hero">
<p>μSocial is meant to be lightweight and friendly. These guidelines help keep the community safe and useful for everyone.</p>
</div>
<div class="legal-sections">
<section class="legal-sec"><h3>Be respectful</h3><p>No harassment, hate speech, or threats. Disagree without attacking people.</p></section>
<section class="legal-sec"><h3>Don’t post harmful or illegal content</h3><p>Content that’s illegal, violent, or promotes harm isn’t allowed.</p></section>
<section class="legal-sec"><h3>Be authentic</h3><p>No impersonation or deceptive behavior intended to mislead others.</p></section>
<section class="legal-sec"><h3>Protect privacy</h3><p>Don’t share someone else’s private information without consent.</p></section>
<section class="legal-sec"><h3>No spam or scams</h3><p>Don’t flood the platform, run phishing attempts, or post repetitive promotional content.</p></section>
<section class="legal-sec"><h3>Respect intellectual property</h3><p>Only share content you own or have permission to use.</p></section>
<section class="legal-sec"><h3>Enforcement</h3><p>We may remove content or restrict accounts that violate these guidelines. Repeated violations lead to stricter penalties.</p></section>
</div>
</div>
<?php else: ?>
<div class="header"><?= $titles[$v] ?? 'Home' ?></div>
<?php if ($banned): ?>
<div style="padding:60px 20px;text-align:center;color:var(--text2)">Your access is temporarily restricted.</div>
<?php else: ?>
<?php if ($me() && in_array($v, ['home','explore','feed'])): ?>
<div class="composer">
<div class="avatar av-m"><?= strtoupper($self['name'][0]) ?></div>
<form method="post" class="composer-input"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="post">
<textarea id="composer-txt" name="txt" placeholder="What's on your mind?" maxlength="<?= $POST_MAX ?>" required></textarea>
<div class="composer-actions">
<span class="char-count" data-for="composer-txt" data-max="<?= $POST_MAX ?>">0</span>
<button type="submit" class="btn">Post</button>
</div></form>
</div>
<?php endif ?>
<?php if ($v === 'u' && ($id = (int)($_GET['id'] ?? 0)) && ($u = usr($id))): ?>
<?php
if (isset($_SESSION['bio_updated'])) {
$u = usr($id);
unset($_SESSION['bio_updated']);
}
$blocked = $me() ? isEitherBlocked($me(), $id) : false;
$iBlocked = $me() ? isBlocked($me(), $id) : false;
$frs = q("SELECT COUNT(*) FROM f WHERE b=?",[$id])->fetchColumn();
$fng = q("SELECT COUNT(*) FROM f WHERE a=?",[$id])->fetchColumn();
$fl = $me() && q("SELECT 1 FROM f WHERE a=? AND b=?",[$me(),$id])->fetch();
?>
<div class="profile-header">
<?php if ($me()): ?>
<div class="profile-menu">
<button class="btn-icon" onclick="toggleMenu(this)"><?= $icons['more'] ?></button>
<div class="dropdown icon-only">
<?php if ($me() === $id): ?>
<button title="Settings" onclick="openSettingsModal('profile','<?= $h(addslashes($u['bio'] ?? '')) ?>','<?= $h(addslashes($u['name'] ?? '')) ?>')"><?= $icons['gear'] ?></button>
<form method="post"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="out">
<button title="Logout" type="submit"><?= $icons['logout'] ?></button>
</form>
<?php else: ?>
<form method="post"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="blk"><input type="hidden" name="tid" value="<?= $id ?>">
<button title="<?= $iBlocked ? 'Unblock' : 'Block' ?>" type="submit"><?= $icons['shield'] ?></button>
</form>
<?php if ($me() && isAdmin($me())): ?>
<button title="Ban" onclick="openBanModal(<?= (int)$id ?>,'<?= $h(addslashes($u['name'] ?? '')) ?>')"><?= $icons['gear'] ?></button>
<form method="post"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="delu"><input type="hidden" name="tid" value="<?= $id ?>">
<button title="Delete account" class="danger" onclick="return confirm('Delete this account?')" type="submit"><?= $icons['trash'] ?></button>
</form>
<?php endif ?>
<?php endif ?>
</div>
</div>
<?php endif ?>
<div class="avatar av-l"><?= strtoupper($u['name'][0]) ?></div>
<div class="profile-name"><?= $h($u['name']) ?><?php if ($u['admin']): ?><span class="badge">admin</span><?php endif ?></div>
<div class="profile-bio"><?= $h($u['bio']) ?: 'No bio yet' ?></div>
<div class="profile-stats">
<button type="button" onclick="openFollowersModal(<?= (int)$id ?>)"><span><b><?= $frs ?></b> Followers</span></button>
<button type="button" onclick="openFollowingModal(<?= (int)$id ?>)"><span><b><?= $fng ?></b> Following</span></button>
</div>
<?php if ($me() && $me() !== $id && !$blocked): ?>
<form method="post" style="margin-top:16px"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="fol"><input type="hidden" name="tid" value="<?= $id ?>">
<button class="btn<?= $fl ? ' btn-outline' : '' ?>"><?= $fl ? 'Following' : 'Follow' ?></button></form>
<?php endif ?>
</div>
<?php if ($blocked): ?>
<div style="padding:40px 20px;text-align:center;color:var(--text2)">This profile isn’t available.</div>
<?php endif ?>
<?php endif ?>
<?php if ($v === 'admin' && $me() && ($self['admin'] ?? 0)): ?>
<?php foreach (q("SELECT * FROM u ORDER BY id")->fetchAll(PDO::FETCH_ASSOC) as $u): ?>
<div class="admin-item">
<span><a href="?v=u&id=<?= $u['id'] ?>"><?= $h($u['name']) ?></a><?php if ($u['admin']): ?><span class="badge">admin</span><?php endif ?></span>
<?php if ($u['id'] !== $me()): ?>
<form method="post"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="delu"><input type="hidden" name="tid" value="<?= $u['id'] ?>">
<button class="btn-action" style="color:var(--danger)" onclick="return confirm('Delete this user?')"><?= $icons['trash'] ?></button></form>
<?php endif ?>
</div>
<?php endforeach ?>
<?php endif ?>
<div id="posts">
<?php
if ($v === 'u' && ($id = (int)($_GET['id'] ?? 0)))
$rows = q("SELECT * FROM p WHERE uid=?".($me() ? " AND NOT EXISTS(SELECT 1 FROM bl WHERE (a=? AND b=?) OR (a=? AND b=?))" : "")." ORDER BY ts DESC LIMIT 10",
$me() ? [$id, $me(), $id, $id, $me()] : [$id]);
elseif ($v === 'feed' && $me())
$rows = q("SELECT p.* FROM p JOIN f ON p.uid=f.b WHERE f.a=? AND NOT EXISTS(SELECT 1 FROM bl WHERE (a=? AND b=p.uid) OR (a=p.uid AND b=?)) UNION SELECT * FROM p WHERE uid=? AND NOT EXISTS(SELECT 1 FROM bl WHERE (a=? AND b=?) OR (a=? AND b=?)) ORDER BY ts DESC LIMIT 10",
[$me(), $me(), $me(), $me(), $me(), $me(), $me(), $me()]);
elseif (in_array($v, ['home','explore']))
$rows = q("SELECT * FROM p".($me() ? " WHERE NOT EXISTS(SELECT 1 FROM bl WHERE (a=? AND b=p.uid) OR (a=p.uid AND b=?))" : "")." ORDER BY ts DESC LIMIT 10",
$me() ? [$me(), $me()] : []);
else $rows = null;
if ($rows && !($v === 'u' && !empty($blocked))) foreach ($rows->fetchAll(PDO::FETCH_ASSOC) as $p) echo postHtml($p);
?>
</div>
<div id="loader">Loading more posts...</div>
<?php endif ?>
<?php endif ?>
</main>
</div>
<!-- Right Sidebar -->
<aside class="sidebar-right">
<div class="search-box"><?= $icons['search'] ?>
<input type="search" id="search" placeholder="Search users and posts" autocomplete="off">
<div class="search-results" id="search-results"></div>
</div>
<div class="footer"><div class="footer-links">
<a href="?v=terms">Terms</a><a href="?v=privacy">Privacy</a><a href="?v=guidelines">Guidelines</a><a href="https://github.com/kevintr303/microsocial" target="_blank" rel="noopener">GitHub</a>
<span>© <?= date('Y') ?> μSocial</span>
</div></div>
</aside>
</div>
<div class="toast" id="toast"></div>
<!-- Mobile Nav -->
<nav class="mobile-nav">
<a href="?" class="<?= $v === 'home' ? 'active' : '' ?>"><?= $icons['home'] ?></a>
<a href="?v=search" class="<?= $v === 'search' ? 'active' : '' ?>"><?= $icons['search'] ?></a>
<a href="?v=explore" class="<?= $v === 'explore' ? 'active' : '' ?>"><?= $icons['globe'] ?></a>
<?php if ($me()): ?>
<a href="?v=u&id=<?= $me() ?>" class="<?= $v === 'u' && ($_GET['id'] ?? 0) == $me() ? 'active' : '' ?>"><?= $icons['user'] ?></a>
<?php else: ?>
<button onclick="document.getElementById('auth-modal').showModal()"><?= $icons['user'] ?></button>
<?php endif ?>
</nav>
<!-- Auth Dialog -->
<dialog id="auth-modal">
<div class="modal-header">
<button class="modal-close" onclick="this.closest('dialog').close()"><?= $icons['x'] ?></button>
<h2>Welcome to μSocial</h2><div style="width:36px"></div>
</div>
<div class="tabs">
<div class="tab active" onclick="switchTab('login')">Sign In</div>
<div class="tab" onclick="switchTab('register')">Sign Up</div>
</div>
<div class="modal-content">
<?php if ($err): ?><div class="form-error"><?= $h($err) ?></div><?php endif ?>
<form method="post" id="login-form"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="log">
<div class="form-group"><label>Username</label><input name="n" required autocomplete="username"></div>
<div class="form-group"><label>Password</label><input type="password" name="pw" required autocomplete="current-password"></div>
<button class="btn form-submit">Sign In</button></form>
<form method="post" id="register-form" style="display:none"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="reg">
<div class="form-group"><label>Username</label><input name="n" pattern="\w{2,20}" title="2-20 letters, numbers, or underscores" required autocomplete="username"></div>
<div class="form-group"><label>Password</label><input type="password" name="pw" minlength="4" required autocomplete="new-password"></div>
<button class="btn form-submit">Create Account</button></form>
</div>
</dialog>
<?php if ($me()): ?>
<!-- Settings Dialog -->
<dialog id="settings-modal">
<div class="modal-header">
<button class="modal-close" onclick="this.closest('dialog').close()"><?= $icons['x'] ?></button>
<h2>Settings</h2><div style="width:36px"></div>
</div>
<div class="settings">
<div class="settings-nav">
<button class="active" data-tab="profile" onclick="setSettingsTab('profile')"><?= $icons['user'] ?> Profile</button>
<button data-tab="account" onclick="setSettingsTab('account')"><?= $icons['gear'] ?> Account</button>
<button data-tab="security" onclick="setSettingsTab('security')"><?= $icons['lock'] ?> Security</button>
</div>
<div class="settings-body">
<div class="settings-panel active" data-panel="profile">
<form method="post" onsubmit="setTimeout(()=>location.reload(),100)"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="bio">
<div class="form-group">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
<label style="margin:0">Bio</label>
<span class="char-count" data-for="settings-bio" data-max="<?= $BIO_MAX ?>">0</span>
</div>
<input id="settings-bio" name="bio" value="" placeholder="Write something about yourself..." maxlength="<?= $BIO_MAX ?>">
</div>
<button class="btn form-submit">Save</button>
</form>
</div>
<div class="settings-panel" data-panel="account">
<form method="post"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="chname">
<div class="form-group"><label>Username</label>
<input id="settings-name" name="n" value="" pattern="\w{2,20}" title="2-20 letters, numbers, or underscores" required autocomplete="username">
</div>
<button class="btn form-submit">Change username</button>
</form>
<div class="settings-danger">
<form method="post"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="delme">
<button class="btn form-submit" style="background:var(--danger)" onclick="return confirm('Delete your account? This cannot be undone.')">Delete account</button>
</form>
</div>
</div>
<div class="settings-panel" data-panel="security">
<form method="post"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="chpw">
<div class="form-group"><label>Current password</label>
<input type="password" name="cur" required autocomplete="current-password">
</div>
<div class="form-group"><label>New password</label>
<input type="password" name="pw" minlength="4" required autocomplete="new-password">
</div>
<button class="btn form-submit">Change password</button>
</form>
</div>
</div>
</div>
</dialog>
<!-- Ban Dialog (admin) -->
<dialog id="ban-modal">
<div class="modal-header">
<button class="modal-close" onclick="this.closest('dialog').close()"><?= $icons['x'] ?></button>
<h2 id="ban-title">Ban</h2><div style="width:36px"></div>
</div>
<div class="modal-content">
<form method="post"><input type="hidden" name="t" value="<?= $tk() ?>"><input type="hidden" name="a" value="ban">
<input type="hidden" id="ban-tid" name="tid" value="">
<div class="form-group">
<label>Duration</label>
<select name="dur" style="width:100%;background:var(--bg);border:1px solid var(--border);border-radius:10px;padding:14px;color:var(--text);font-size:16px;font-family:inherit">
<option value="1h">1 hour</option>
<option value="1d" selected>1 day</option>
<option value="7d">7 days</option>
<option value="30d">30 days</option>
</select>
</div>
<label style="display:flex;align-items:center;gap:10px;color:var(--text2);font-size:14px;margin:10px 0">
<input type="checkbox" name="perma" value="1"> Permanent (10 years)
</label>
<label style="display:flex;align-items:center;gap:10px;color:var(--text2);font-size:14px;margin:10px 0">
<input type="checkbox" name="ipban" value="1"> Also ban last known IP
</label>
<button class="btn form-submit danger" style="background:var(--danger)">Ban</button>
</form>
</div>
</dialog>
<?php endif ?>
<!-- Followers Dialog -->
<dialog id="followers-modal">
<div class="modal-header">
<button class="modal-close" onclick="this.closest('dialog').close()"><?= $icons['x'] ?></button>
<h2>Followers</h2><div style="width:36px"></div>
</div>
<div class="rel-list" id="followers-list"></div>
<div class="rel-empty" id="followers-empty" style="display:none">No followers yet</div>
<div id="followers-loader" class="rel-empty" style="display:none">Loading…</div>
</dialog>
<!-- Following Dialog -->
<dialog id="following-modal">
<div class="modal-header">
<button class="modal-close" onclick="this.closest('dialog').close()"><?= $icons['x'] ?></button>
<h2>Following</h2><div style="width:36px"></div>
</div>
<div class="rel-list" id="following-list"></div>
<div class="rel-empty" id="following-empty" style="display:none">Not following anyone yet</div>
<div id="following-loader" class="rel-empty" style="display:none">Loading…</div>
</dialog>
<script>
const view='<?= $v ?>',uid=<?= (int)($_GET['id'] ?? 0) ?>;
let offset=10,loading=false,hasMore=true,searchTimeout;
<?php if ($showAuth): ?>document.getElementById('auth-modal').showModal();<?php endif ?>
let relsUid=0,relsType='followers',relsOff=0,relsLoading=false,relsHasMore=true,relsObs,relsModalId='followers';
function toast(m){const t=document.getElementById('toast');t.textContent=m;t.classList.add('show');setTimeout(()=>t.classList.remove('show'),2000)}
function postClick(e,id){if(!e.target.closest('a,button,form,.post-menu'))location.href='?v=p&id='+id}
function toggleMenu(b){document.querySelectorAll('.dropdown.active').forEach(d=>{if(d!==b.nextElementSibling)d.classList.remove('active')});b.nextElementSibling.classList.toggle('active')}
function copyText(b){navigator.clipboard.writeText(b.dataset.text);toast('Copied');b.closest('.dropdown').classList.remove('active')}
function sharePost(id){navigator.clipboard.writeText(location.origin+location.pathname+'?v=p&id='+id);toast('Link copied');document.querySelector('.dropdown.active')?.classList.remove('active')}
function switchTab(t){document.querySelectorAll('.tabs .tab').forEach((el,i)=>el.classList.toggle('active',i===(t==='login'?0:1)));document.getElementById('login-form').style.display=t==='login'?'':'none';document.getElementById('register-form').style.display=t==='register'?'':'none'}
function setSettingsTab(tab){
document.querySelectorAll('#settings-modal .settings-nav button').forEach(b=>b.classList.toggle('active',b.dataset.tab===tab));
document.querySelectorAll('#settings-modal .settings-panel').forEach(p=>p.classList.toggle('active',p.dataset.panel===tab));
}
function openSettingsModal(tab,bio,name){
const m=document.getElementById('settings-modal');if(!m)return;
const bi=document.getElementById('settings-bio');if(bi)bi.value=bio||'';
const nm=document.getElementById('settings-name');if(nm)nm.value=name||'';
setSettingsTab(tab||'profile');
m.showModal();
document.querySelector('.dropdown.active')?.classList.remove('active');
}
function openBanModal(tid,name){const m=document.getElementById('ban-modal');if(!m)return;const t=document.getElementById('ban-title');const i=document.getElementById('ban-tid');if(i)i.value=tid||'';if(t)t.textContent='Ban '+(name||'user');m.showModal();document.querySelector('.dropdown.active')?.classList.remove('active')}
function openFollowersModal(uid){
relsModalId='followers';relsType='followers';relsUid=uid||0;relsOff=0;relsHasMore=true;relsLoading=false;
const m=document.getElementById('followers-modal');if(!m)return;
document.getElementById('followers-list').innerHTML='';
document.getElementById('followers-empty').style.display='none';
m.showModal();loadMoreRels();setupRelsObserver();
}
function openFollowingModal(uid){
relsModalId='following';relsType='following';relsUid=uid||0;relsOff=0;relsHasMore=true;relsLoading=false;
const m=document.getElementById('following-modal');if(!m)return;
document.getElementById('following-list').innerHTML='';
document.getElementById('following-empty').style.display='none';
m.showModal();loadMoreRels();setupRelsObserver();
}
function setupRelsObserver(){
const loader=document.getElementById(relsModalId+'-loader');
const list=document.getElementById(relsModalId+'-list');
if(!loader||!list)return;
relsObs?.disconnect();
relsObs=new IntersectionObserver(entries=>{
if(!entries[0].isIntersecting||relsLoading||!relsHasMore)return;
loadMoreRels();
},{root:list,rootMargin:'200px'});
relsObs.observe(loader);
}
function loadMoreRels(){
const loader=document.getElementById(relsModalId+'-loader');
const list=document.getElementById(relsModalId+'-list');
const empty=document.getElementById(relsModalId+'-empty');
if(!relsUid||relsLoading||!relsHasMore||!loader||!list||!empty)return;
relsLoading=true;loader.style.display='';loader.textContent='Loading…';
fetch(`?api=rels&uid=${relsUid}&type=${relsType}&offset=${relsOff}`)
.then(r=>r.json()).then(d=>{
if(d.html){list.insertAdjacentHTML('beforeend',d.html);relsOff+=20}
relsHasMore=!!d.hasMore;
relsLoading=false;
if(!list.children.length){empty.style.display='';loader.style.display='none'}
else loader.style.display=relsHasMore?'':'none';
}).catch(()=>{relsLoading=false;loader.textContent='Error';setTimeout(()=>loader.style.display='none',1200)});
}
document.addEventListener('click',e=>{
if(!e.target.closest('.post-menu,.profile-menu'))document.querySelectorAll('.dropdown.active').forEach(d=>d.classList.remove('active'));
if(!e.target.closest('.search-box'))document.querySelectorAll('.search-results').forEach(r=>r.classList.remove('active'));
});
function bindCharCounter(counter){
const id=counter?.dataset?.for; if(!id)return;
const el=document.getElementById(id); if(!el)return;
const max=parseInt(counter.dataset.max||el.getAttribute('maxlength')||'0',10)||0;
function upd(){
const len=(el.value||'').length;
const rem=max-len;
counter.textContent=String(rem);
counter.classList.toggle('over',rem<0);
counter.classList.toggle('show',len>0);
}
el.addEventListener('input',upd);
upd();
}
document.querySelectorAll('.char-count[data-for]').forEach(bindCharCounter);
document.addEventListener('submit',e=>{
const f=e.target;
if(!(f instanceof HTMLFormElement))return;
if(!f.matches('form[data-rel-follow="1"]'))return;