-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.php
1752 lines (1511 loc) · 54.2 KB
/
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
/*
* "This code is not a code of honour... no highly esteemed code is commemorated here... nothing valued is here."
* "What is here is dangerous and repulsive to us. This message is a warning about danger."
* This is a rudimentary, single-file, low complexity, minimum functionality, ActivityPub server.
* For educational purposes only.
* The Server produces an Actor who can be followed.
* The Actor can send messages to followers.
* The message can have linkable URls, hashtags, and mentions.
* An image and alt text can be attached to the message.
* The Server saves logs about requests it receives and sends.
* This code is NOT suitable for production use.
* SPDX-License-Identifier: AGPL-3.0-or-later
* This code is also "licenced" under CRAPL v0 - https://matt.might.net/articles/crapl/
* "Any appearance of design in the Program is purely coincidental and should not in any way be mistaken for evidence of thoughtful software construction."
* For more information, please re-read.
*/
// Preamble: Set your details here
// This is where you set up your account's name and bio.
// You also need to provide a public/private keypair.
// The posting endpoint is protected with a password that also needs to be set here.
// Set up the Actor's information here, or in the .env file
$env = parse_ini_file('.env');
// Edit these:
$username = rawurlencode($env["USERNAME"]); // Type the @ username that you want. Do not include an "@".
$realName = $env["REALNAME"]; // This is the user's "real" name.
$summary = $env["SUMMARY"]; // This is the bio of your user.
// Generate locally or from https://cryptotools.net/rsagen
// Newlines must be replaced with "\n"
$key_private = str_replace('\n', "\n", $env["KEY_PRIVATE"]);
$key_public = str_replace('\n', "\n", $env["KEY_PUBLIC"]);
// Password for sending messages
$password = $env["PASSWORD"];
/** No need to edit anything below here. But please go exploring! **/
// Internal data
$server = $_SERVER["SERVER_NAME"]; // Do not change this!
// Some requests require a User-Agent string.
define("USERAGENT", "activitybot-single-php-file/0.0");
// Set up where to save logs, posts, and images.
// You can change these directories to something more suitable if you like.
$data = "data";
$directories = array(
"inbox" => "{$data}/inbox",
"followers" => "{$data}/followers",
"following" => "{$data}/following",
"logs" => "{$data}/logs",
"posts" => "posts",
"images" => "images",
);
// Create the directories if they don't already exist.
foreach ($directories as $directory) {
if (!is_dir($directory)) {
mkdir($data);
mkdir($directory);
}
}
// Get the information sent to this server
$input = file_get_contents("php://input");
$body = json_decode($input, true);
$bodyData = print_r($body, true);
// If the root has been requested, manually set the path to `/`
!empty($_GET["path"]) ? $path = $_GET["path"] : $path = "/";
// Routing:
// The .htaccess changes /whatever to /?path=whatever
// This runs the function of the path requested.
switch ($path) {
case "/.well-known/webfinger":
webfinger(); // Mandatory. Static.
case "/.well-known/nodeinfo":
wk_nodeinfo(); // Optional. Static.
case "/nodeinfo/2.1":
nodeinfo(); // Optional. Static.
case "/" . rawurldecode($username):
case "/@" . rawurldecode($username): // Some software assumes usernames start with an `@`
username(); // Mandatory. Static
case "/following":
following(); // Mandatory. Can be static or dynamic.
case "/followers":
followers(); // Mandatory. Can be static or dynamic.
case "/inbox":
inbox(); // Mandatory.
case "/outbox":
outbox(); // Optional. Dynamic.
case "/action/send":
send(); // API for posting content to the Fediverse.
case "/action/follow":
follow(); // API for following other accounts
case "/action/unfollow":
unfollow(); // API for unfollowing accounts
case "/":
view("home"); // User interface for seeing what the user has posted.
default:
echo ($path);
header("HTTP/1.1 404 Not Found");
die();
}
// The WebFinger Protocol is used to identify accounts.
// It is requested with `example.com/.well-known/webfinger?resource=acct:username@example.com`
// This server only has one user, so it ignores the query string and always returns the same details.
function webfinger()
{
global $username, $server;
$webfinger = array(
"subject" => "acct:{$username}@{$server}",
"links" => array(
array(
"rel" => "self",
"type" => "application/activity+json",
"href" => "https://{$server}/{$username}"
)
)
);
header("Content-Type: application/json");
echo json_encode($webfinger);
die();
}
// User:
// Requesting `example.com/username` returns a JSON document with the user's information.
function username()
{
global $username, $realName, $summary, $server, $key_public;
// Was HTML requested?
// If so, probably a browser. Redirect to homepage.
foreach (getallheaders() as $name => $value) {
if ("Accept" == $name) {
$accepts = explode(",", $value);
if ("text/html" == $accepts[0]) {
header("Location: https://{$server}/");
die();
}
}
}
$user = array(
"@context" => [
"https://www.w3.org/ns/activitystreams",
"https://w3id.org/security/v1"
],
"id" => "https://{$server}/{$username}",
"type" => "Application",
"following" => "https://{$server}/following",
"followers" => "https://{$server}/followers",
"inbox" => "https://{$server}/inbox",
"outbox" => "https://{$server}/outbox",
"preferredUsername" => rawurldecode($username),
"name" => "{$realName}",
"summary" => "{$summary}",
"url" => "https://{$server}/{$username}",
"manuallyApprovesFollowers" => false,
"discoverable" => true,
"published" => "2024-02-29T12:34:56Z",
"icon" => [
"type" => "Image",
"mediaType" => "image/png",
"url" => "https://{$server}/icon.png"
],
"image" => [
"type" => "Image",
"mediaType" => "image/png",
"url" => "https://{$server}/banner.png"
],
"publicKey" => [
"id" => "https://{$server}/{$username}#main-key",
"owner" => "https://{$server}/{$username}",
"publicKeyPem" => $key_public
]
);
header("Content-Type: application/activity+json");
echo json_encode($user);
die();
}
// Follower / Following:
// These JSON documents show how many users are following / followers-of this account.
// The information here is self-attested. So you can lie and use any number you want.
function following()
{
global $server, $directories;
// Get all the files
$following_files = glob($directories["following"] . "/*.json");
// Number of users
$totalItems = count($following_files);
// Sort users by most recent first
usort($following_files, function ($a, $b) {
return filemtime($b) - filemtime($a);
});
// Create a list of all accounts being followed
$items = array();
foreach ($following_files as $following_file) {
$following = json_decode(file_get_contents($following_file), true);
$items[] = $following["id"];
}
$following = array(
"@context" => "https://www.w3.org/ns/activitystreams",
"id" => "https://{$server}/following",
"type" => "Collection",
"totalItems" => $totalItems,
"items" => $items
);
header("Content-Type: application/activity+json");
echo json_encode($following);
die();
}
function followers()
{
global $server, $directories;
// The number of followers is self-reported.
// You can set this to any number you like.
// Get all the files
$follower_files = glob($directories["followers"] . "/*.json");
// Number of users
$totalItems = count($follower_files);
// Sort users by most recent first
usort($follower_files, function ($a, $b) {
return filemtime($b) - filemtime($a);
});
// Create a list of everyone being followed
$items = array();
foreach ($follower_files as $follower_file) {
$following = json_decode(file_get_contents($follower_file), true);
$items[] = $following["id"];
}
$followers = array(
"@context" => "https://www.w3.org/ns/activitystreams",
"id" => "https://{$server}/followers",
"type" => "Collection",
"totalItems" => $totalItems,
"items" => $items
);
header("Content-Type: application/activity+json");
echo json_encode($followers);
die();
}
// Inbox:
// The `/inbox` is the main server. It receives all requests.
function inbox()
{
global $body, $server, $username, $key_private, $directories;
// Get the message, type, and ID
$inbox_message = $body;
$inbox_type = $inbox_message["type"];
// This inbox only sends responses to follow requests.
// A remote server sends the inbox a follow request which is a JSON file saying who they are.
// The details of the remote user's server is saved to a file so that future messages can be delivered to the follower.
// An accept request is cryptographically signed and POST'd back to the remote server.
if ("Follow" == $inbox_type) {
// Validate HTTP Message Signature
if (!verifyHTTPSignature()) {
header("HTTP/1.1 401 Unauthorized");
die();
}
// Get the parameters
$follower_id = $inbox_message["id"]; // E.g. https://mastodon.social/(unique id)
$follower_actor = $inbox_message["actor"]; // E.g. https://mastodon.social/users/Edent
// Get the actor's profile as JSON
$follower_actor_details = getDataFromURl($follower_actor);
// Save the actor's data in `/data/followers/`
$follower_filename = urlencode($follower_actor);
file_put_contents($directories["followers"] . "/{$follower_filename}.json", json_encode($follower_actor_details));
// Get the new follower's Inbox
$follower_inbox = $follower_actor_details["inbox"];
// Response Message ID
// This isn't used for anything important so could just be a random number
$guid = uuid();
// Create the Accept message to the new follower
$message = [
"@context" => "https://www.w3.org/ns/activitystreams",
"id" => "https://{$server}/{$guid}",
"type" => "Accept",
"actor" => "https://{$server}/{$username}",
"object" => [
"@context" => "https://www.w3.org/ns/activitystreams",
"id" => $follower_id,
"type" => $inbox_type,
"actor" => $follower_actor,
"object" => "https://{$server}/{$username}",
]
];
// The Accept is POSTed to the inbox on the server of the user who requested the follow
sendMessageToSingle($follower_inbox, $message);
} else {
// Messages to ignore.
// Some servers are very chatty. They send lots of irrelevant messages.
// Before even bothering to validate them, we can delete them.
// This server doesn't handle Add, Remove, Reject, Favourite, Replies, Repost
// See https://www.w3.org/wiki/ActivityPub/Primer
if (
"Add" == $inbox_type ||
"Remove" == $inbox_type ||
"Reject" == $inbox_type ||
"Like" == $inbox_type ||
"Create" == $inbox_type ||
"Announce" == $inbox_type
) {
// TODO: Better HTTP header
die();
}
// Get a list of every account following us
// Get all the files
$followers_files = glob($directories["followers"] . "/*.json");
// Create a list of all accounts being followed
$followers_ids = array();
foreach ($followers_files as $follower_file) {
$follower = json_decode(file_get_contents($follower_file), true);
$followers_ids[] = $follower["id"];
}
// Is this from someone following us?
in_array($inbox_message["actor"], $followers_ids) ? $from_follower = true : $from_follower = false;
// As long as one of these is true, the server will process it
if (!$from_follower) {
// Don't bother processing it at all.
die();
}
// Validate HTTP Message Signature
if (!verifyHTTPSignature()) {
die();
}
// If this is an Undo (Unfollow) try to process it
if ("Undo" == $inbox_type) {
undo($inbox_message);
} elseif (in_array($inbox_type, ["Accept", "Reject"])) {
processFollowResponse($inbox_message);
} else {
die();
}
}
// If the message is valid, save the message in `/data/inbox/`
$uuid = uuid($inbox_message);
$inbox_filename = $uuid . "." . urlencode($inbox_type) . ".json";
file_put_contents($directories["inbox"] . "/{$inbox_filename}", json_encode($inbox_message));
die();
}
// Unique ID:
// Every message sent should have a unique ID.
// This can be anything you like. Some servers use a random number.
// I prefer a date-sortable string.
function uuid($message = null)
{
// UUIDs that this server *sends* will be [timestamp]-[random]
// 65e99ab4-5d43-f074-b43e-463f9c5cf05c
if (is_null($message)) {
return sprintf(
"%08x-%04x-%04x-%04x-%012x",
time(),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffffffffffff)
);
} else {
// UUIDs that this server *saves* will be [timestamp]-[hash of message ID]
// 65eadace-8f434346648f6b96df89dda901c5176b10a6d83961dd3c1ac88b59b2dc327aa4
// The message might have its own object
if (isset($message["object"]["id"])) {
$id = $message["object"]["id"];
} else {
$id = $message["id"];
}
return sprintf("%08x", time()) . "-" . hash("sha256", $id);
}
}
// Headers:
// Every message that your server sends needs to be cryptographically signed with your Private Key.
// This is a complicated process.
// Please read https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/ for more information.
function generate_signed_headers($message, $host, $path, $method)
{
global $server, $username, $key_private;
// Location of the Public Key
$keyId = "https://{$server}/{$username}#main-key";
// Get the Private Key
$signer = openssl_get_privatekey($key_private);
// Timestamp this message was sent
$date = date("D, d M Y H:i:s \G\M\T");
// There are subtly different signing requirements for POST and GET.
if ("POST" == $method) {
// Encode the message object to JSON
$message_json = json_encode($message);
// Generate signing variables
$hash = hash("sha256", $message_json, true);
$digest = base64_encode($hash);
// Sign the path, host, date, and digest
$stringToSign = "(request-target): post $path\nhost: $host\ndate: $date\ndigest: SHA-256=$digest";
// The signing function returns the variable $signature
// https://www.php.net/manual/en/function.openssl-sign.php
openssl_sign(
$stringToSign,
$signature,
$signer,
OPENSSL_ALGO_SHA256
);
// Encode the signature
$signature_b64 = base64_encode($signature);
// Full signature header
$signature_header = 'keyId="' . $keyId . '",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="' . $signature_b64 . '"';
// Header for POST request
$headers = array(
"Host: {$host}",
"Date: {$date}",
"Digest: SHA-256={$digest}",
"Signature: {$signature_header}",
"Content-Type: application/activity+json",
"Accept: application/activity+json",
);
} else if ("GET" == $method) {
// Sign the path, host, date - NO DIGEST because there's no message sent.
$stringToSign = "(request-target): get $path\nhost: $host\ndate: $date";
// The signing function returns the variable $signature
// https://www.php.net/manual/en/function.openssl-sign.php
openssl_sign(
$stringToSign,
$signature,
$signer,
OPENSSL_ALGO_SHA256
);
// Encode the signature
$signature_b64 = base64_encode($signature);
// Full signature header
$signature_header = 'keyId="' . $keyId . '",algorithm="rsa-sha256",headers="(request-target) host date",signature="' . $signature_b64 . '"';
// Header for GET request
$headers = array(
"Host: {$host}",
"Date: {$date}",
"Signature: {$signature_header}",
"Accept: application/activity+json, application/json",
);
}
return $headers;
}
// User Interface for Homepage.
// This creates a basic HTML page. This content appears when someone visits the root of your site.
function view($style)
{
global $username, $server, $realName, $summary, $directories;
$rawUsername = rawurldecode($username);
$h1 = "HomePage";
$directory = "posts";
// Counters for followers, following, and posts
$follower_files = glob($directories["followers"] . "/*.json");
$totalFollowers = count($follower_files);
$following_files = glob($directories["following"] . "/*.json");
$totalFollowing = count($following_files);
// Show the HTML page
echo <<< HTML
<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta property="og:url" content="https://{$server}">
<meta property="og:type" content="website">
<meta property="og:title" content="{$realName}">
<meta property="og:description" content="{$summary}">
<meta property="og:image" content="https://{$server}/banner.png">
<title>{$h1} {$realName}</title>
<style>
* { max-width: 100%; }
body { margin:0; padding: 0; font-family:sans-serif; }
@media screen and (max-width: 800px) { body { width: 100%; }}
@media screen and (min-width: 799px) { body { width: 800px; margin: 0 auto; }}
address { font-style: normal; }
img { max-width: 50%; }
.h-feed { margin:auto; width: 100%; }
.h-feed > header { text-align: center; margin: 0 auto; }
.h-feed .banner { text-align: center; margin:0 auto; max-width: 650px; }
.h-feed > h1, .h-feed > h2 { margin-top: 10px; margin-bottom: 0; }
.h-feed > header > h1:has(span.p-author), h2:has(a.p-nickname) { word-wrap: break-word; max-width: 90%; padding-left:20px; }
.h-feed .u-feature:first-child { margin-top: 10px; margin-bottom: -150px; max-width: 100%;}
.h-feed .u-photo { max-height: 8vw; max-width:100%; min-height: 120px; }
.h-feed .about { font-size: smaller; background-color: #F5F5F5; padding: 10px; border-top: dotted 1px #808080; border-bottom: dotted 1px #808080; }
.h-feed > ul { padding-left: 0; list-style-type: none; }
.h-feed > ul > li { padding: 10px; border-bottom: dotted 1px #808080; }
.h-entry { padding-right: 10px; }
.h-entry time { font-weight: bold; }
.h-entry .e-content a { word-wrap: break-word; }
</style>
</head>
<body>
<main class="h-feed">
<header>
<div class="banner">
<img src="banner.png" alt="" class="u-feature"><br>
<img src="icon.png" alt="icon" class="u-photo">
</div>
<address>
<h1 class="p-name p-author">{$realName}</h1>
<h2><a class="p-nickname u-url" rel="author" href="https://{$server}/{$username}">@{$rawUsername}@{$server}</a></h2>
</address>
<p class="p-summary">{$summary}</p>
<p>Following: {$totalFollowing} | Followers: {$totalFollowers}</p>
<div class="about">
<p><a href="https://gitlab.com/edent/activity-bot/">This software is licenced under AGPL 3.0</a>.</p>
<p>This site is a basic <a href="https://www.w3.org/TR/activitypub/">ActivityPub</a> server designed to be <a href="https://shkspr.mobi/blog/2024/02/activitypub-server-in-a-single-file/">a lightweight educational tool</a>.</p>
</div>
</header>
<ul>
HTML;
// Get all the files in the directory
$message_files = array_reverse(glob("posts" . "/*.json"));
// There are lots of messages. The UI will only show 200.
$message_files = array_slice($message_files, 0, 1000);
// Loop through the messages, get their conent:
// Ensure messages are in the right order.
$messages_ordered = [];
foreach ($message_files as $message_file) {
// Split the filename
$file_parts = explode(".", $message_file);
$type = $file_parts[1];
// Get the contents of the JSON
$message = json_decode(file_get_contents($message_file), true);
$published = $message["published"];
// Place in an array where the key is the timestamp
$messages_ordered[$published] = $message;
}
// HTML is *probably* sanitised by the sender. But let's not risk it, eh?
// Using the allow-list from https://docs.joinmastodon.org/spec/activitypub/#sanitization
$allowed_elements = ["p", "span", "br", "a", "del", "pre", "code", "em", "strong", "b", "i", "u", "ul", "ol", "li", "blockquote"];
// Print the items in a list
foreach ($messages_ordered as $message) {
// The object of this *is* the message
$object = $message;
// Get basic details
$id = $object["id"];
$published = $object["published"];
// HTML for who wrote this
$publishedHTML = "<a href=\"{$id}\">{$published}</a>";
// For displaying the post's information
$timeHTML = "<time datetime=\"{$published}\" class=\"u-url\" rel=\"bookmark\">{$publishedHTML}</time>";
// Get the actor who authored the message
$actor = $object["attributedTo"];
// Assume that what comes after the final `/` in the URl is the name
$actorArray = explode("/", $actor);
$actorName = end($actorArray);
$actorServer = parse_url($actor, PHP_URL_HOST);
$actorUsername = "@{$actorName}@{$actorServer}";
// Make i18n usernames readable and safe.
$actorName = htmlspecialchars(rawurldecode($actorName));
$actorHTML = "<a href=\"$actor\">@{$actorName}</a>";
// What type of message is this?
$type = $message["type"];
// Get the HTML content
$content = $message["content"];
// Sanitise the HTML
$content = strip_tags($content, $allowed_elements);
// Is there is a Content Warning?
if (isset($object["summary"])) {
$summary = $object["summary"];
$summary = strip_tags($summary, $allowed_elements);
// Hide the content until the user interacts with it.
$content = "<details><summary>{$summary}</summary>{$content}</details>";
}
// Add any images
if (isset($object["attachment"])) {
foreach ($object["attachment"] as $attachment) {
// Only use things which have a MIME Type set
if (isset($attachment["mediaType"])) {
$mediaURl = $attachment["url"];
$mime = $attachment["mediaType"];
// Use the first half of the MIME Type.
// For example `image/png` or `video/mp4`
$mediaType = explode("/", $mime)[0];
if ("image" == $mediaType) {
// Get the alt text
isset($attachment["name"]) ? $alt = htmlspecialchars($attachment["name"]) : $alt = "";
$content .= "<img src='{$mediaURl}' alt='{$alt}'>";
} else if ("video" == $mediaType) {
$content .= "<video controls><source src='{$mediaURl}' type='{$mime}'></video>";
} else if ("audio" == $mediaType) {
$content .= "<audio controls src='{$mediaURl}' type='{$mime}'></audio>";
}
}
}
}
$verb = "posted";
$messageHTML = "{$timeHTML} {$actorHTML} {$verb}: <blockquote class=\"e-content\">{$content}</blockquote>";
// Display the message
echo "<li><article class=\"h-entry\">{$messageHTML}<br></article></li>";
}
echo <<< HTML
</ul>
</main>
</body>
</html>
HTML;
die();
}
// Send Endpoint:
// This takes the submitted message and checks the password is correct.
// It reads all the followers' data in `data/followers`.
// It constructs a list of shared inboxes and unique inboxes.
// It sends the message to every server that is following this account.
function send()
{
global $password, $server, $username, $key_private, $directories;
// Does the posted password match the stored password?
if ($password != $_POST["password"]) {
header("HTTP/1.1 401 Unauthorized");
echo "Wrong password.";
die();
}
// Get the posted content
$content = $_POST["content"];
// Is this a reply?
if (isset($_POST["inReplyTo"]) && filter_var($_POST["inReplyTo"], FILTER_VALIDATE_URL)) {
$inReplyTo = $_POST["inReplyTo"];
} else {
$inReplyTo = null;
}
// Process the content into HTML to get hashtags etc
list("HTML" => $content, "TagArray" => $tags) = process_content($content);
// Is there an image attached?
if (isset($_FILES['image']['tmp_name']) && ("" != $_FILES['image']['tmp_name'])) {
// Get information about the image
$image = $_FILES['image']['tmp_name'];
$image_info = getimagesize($image);
$image_ext = image_type_to_extension($image_info[2]);
$image_mime = $image_info["mime"];
// Files are stored according to their hash
// A hash of "abc123" is stored in "/images/abc123.jpg"
$sha1 = sha1_file($image);
$image_full_path = $directories["images"] . "/{$sha1}.{$image_ext}";
// Move media to the correct location
move_uploaded_file($image, $image_full_path);
// Get the alt text
if (isset($_POST["alt"])) {
$alt = $_POST["alt"];
} else {
$alt = "";
}
// Construct the attachment value for the post
$attachment = array([
"type" => "Image",
"mediaType" => "{$image_mime}",
"url" => "https://{$server}/{$image_full_path}",
"name" => $alt
]);
} else {
$attachment = [];
}
// Current time - ISO8601
$timestamp = date("c");
// Outgoing Message ID
$guid = uuid();
// Construct the Note
// `contentMap` is used to prevent unnecessary "translate this post" pop ups
// hardcoded to English
$note = [
"@context" => array(
"https://www.w3.org/ns/activitystreams"
),
"id" => "https://{$server}/posts/{$guid}.json",
"type" => "Note",
"published" => $timestamp,
"attributedTo" => "https://{$server}/{$username}",
"inReplyTo" => $inReplyTo,
"content" => $content,
"contentMap" => ["en" => $content],
"to" => ["https://www.w3.org/ns/activitystreams#Public"],
"tag" => $tags,
"attachment" => $attachment
];
// Construct the Message
// The audience is public and it is sent to all followers
$message = [
"@context" => "https://www.w3.org/ns/activitystreams",
"id" => "https://{$server}/posts/{$guid}.json",
"type" => "Create",
"actor" => "https://{$server}/{$username}",
"to" => [
"https://www.w3.org/ns/activitystreams#Public"
],
"cc" => [
"https://{$server}/followers"
],
"object" => $note
];
// Save the permalink
$note_json = json_encode($note);
file_put_contents($directories["posts"] . "/{$guid}.json", print_r($note_json, true));
// Send to all the user's followers
$messageSent = sendMessageToFollowers($message);
// Return the JSON so the user can see the POST has worked
if ($messageSent) {
header("Location: https://{$server}/posts/{$guid}.json");
die();
} else {
header("HTTP/1.1 500 Internal Server Error");
echo "ERROR!";
die();
}
}
function follow()
{
global $password, $server, $username, $directories;
// Verify directories exist and are writable
if (!is_dir($directories['following']) || !is_writable($directories['following'])) {
header("HTTP/1.1 500 Internal Server Error");
error_log("Following directory not writable");
echo "Server configuration error";
die();
}
// Check password
if ($password != $_POST["password"]) {
header("HTTP/1.1 401 Unauthorized");
echo "Wrong password.";
die();
}
// Get and sanitize the account
if (!isset($_POST["account"])) {
header("HTTP/1.1 400 Bad Request");
echo "Missing account parameter";
die();
}
// Limit input size
if (strlen($_POST["account"]) > 255) {
header("HTTP/1.1 400 Bad Request");
echo "Account string too long";
die();
}
$account = trim(filter_var($_POST["account"], FILTER_SANITIZE_STRING));
// If it starts with @, remove it
if (str_starts_with($account, '@')) {
$account = substr($account, 1);
}
// Split into user@domain and validate parts
$parts = explode("@", $account);
if (
count($parts) != 2 ||
empty($parts[0]) ||
empty($parts[1]) ||
!preg_match('/^[a-zA-Z0-9_.-]+$/', $parts[0]) || // Validate username format
!preg_match('/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', $parts[1])
) { // Basic domain format
header("HTTP/1.1 400 Bad Request");
echo "Invalid account format. Use user@domain";
die();
}
$targetUser = $parts[0];
$targetDomain = $parts[1];
// Verify domain uses HTTPS
if (!filter_var("https://{$targetDomain}", FILTER_VALIDATE_URL)) {
header("HTTP/1.1 400 Bad Request");
echo "Invalid domain";
die();
}
// Get WebFinger data with timeout and error handling
$webfinger_url = "https://{$targetDomain}/.well-known/webfinger?resource=acct:{$targetUser}@{$targetDomain}";
$ch = curl_init($webfinger_url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => USERAGENT,
CURLOPT_TIMEOUT => 10,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
header("HTTP/1.1 502 Bad Gateway");
error_log("WebFinger fetch failed: " . curl_error($ch));
echo "Failed to fetch WebFinger data";
curl_close($ch);
die();
}
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status !== 200) {
header("HTTP/1.1 404 Not Found");
echo "Account not found";
curl_close($ch);
die();
}
curl_close($ch);
$webfinger = json_decode($response, true);
if (!$webfinger || !isset($webfinger['links'])) {
header("HTTP/1.1 502 Bad Gateway");
echo "Invalid WebFinger response";
die();
}
// Find ActivityPub actor URL
$actor_url = null;
foreach ($webfinger['links'] as $link) {
if (
$link['rel'] === 'self' &&
$link['type'] === 'application/activity+json' &&
filter_var($link['href'], FILTER_VALIDATE_URL) &&
parse_url($link['href'], PHP_URL_SCHEME) === 'https'
) {
$actor_url = $link['href'];
break;
}
}
if (!$actor_url) {
header("HTTP/1.1 404 Not Found");
echo "Could not find ActivityPub account";
die();
}
// Get actor data
try {
$actor_data = getDataFromURl($actor_url);
} catch (Exception $e) {
header("HTTP/1.1 502 Bad Gateway");
error_log("Actor fetch failed: " . $e->getMessage());
echo "Failed to fetch account data";
die();
}
// Verify required actor properties
if (
!isset($actor_data['inbox']) ||
!filter_var($actor_data['inbox'], FILTER_VALIDATE_URL) ||
!isset($actor_data['id']) ||
$actor_data['id'] !== $actor_url
) { // Verify actor URL matches claimed ID
header("HTTP/1.1 502 Bad Gateway");
echo "Invalid actor data";
die();
}
// Check follow state
$following_file = "{$directories['following']}/" . urlencode($actor_url) . ".json";
$pending_file = "{$directories['following']}/.pending/" . urlencode($actor_url) . ".json";
if (file_exists($following_file)) {
header("HTTP/1.1 409 Conflict");
echo "Already following this account";
die();
}
if (file_exists($pending_file)) {
header("HTTP/1.1 409 Conflict");
echo "Follow request already pending";
die();
}
// Create follow activity with proper UUID
$guid = uuid();
$message = [
"@context" => "https://www.w3.org/ns/activitystreams",
"id" => "https://{$server}/follow/{$guid}",
"type" => "Follow",
"actor" => "https://{$server}/{$username}",
"object" => $actor_url
];
// Ensure pending directory exists
$pending_dir = "{$directories['following']}/.pending";
if (!is_dir($pending_dir)) {
if (!mkdir($pending_dir, 0755, true)) {
header("HTTP/1.1 500 Internal Server Error");
error_log("Could not create pending directory");
echo "Server configuration error";
die();
}
}
// Save pending follow request first
$pending_data = [
'guid' => $guid,
'timestamp' => time(),
'actor_data' => $actor_data,
'message' => $message
];
if (!file_put_contents($pending_file, json_encode($pending_data))) {
header("HTTP/1.1 500 Internal Server Error");
error_log("Failed to save pending follow");
echo "Failed to save follow request";
die();
}
// Send follow request
$success = sendMessageToSingle($actor_data['inbox'], $message);
if (!$success) {
unlink($pending_file); // Clean up pending file
header("HTTP/1.1 500 Internal Server Error");
echo "Failed to send follow request";
die();
}