3 * @file src/Protocol/ActivityPub.php
5 namespace Friendica\Protocol;
7 use Friendica\Database\DBA;
8 use Friendica\Core\System;
9 use Friendica\BaseObject;
10 use Friendica\Util\Network;
11 use Friendica\Util\HTTPSignature;
12 use Friendica\Core\Protocol;
13 use Friendica\Model\Conversation;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Model\Term;
17 use Friendica\Model\User;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Crypto;
20 use Friendica\Content\Text\BBCode;
21 use Friendica\Content\Text\HTML;
22 use Friendica\Util\JsonLD;
23 use Friendica\Util\LDSignature;
26 * @brief ActivityPub Protocol class
27 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
28 * https://www.w3.org/TR/activitypub/
29 * https://www.w3.org/TR/activitystreams-core/
30 * https://www.w3.org/TR/activitystreams-vocabulary/
32 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
33 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
35 * Digest: https://tools.ietf.org/html/rfc5843
36 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
37 * https://github.com/digitalbazaar/php-json-ld
39 * Part of the code for HTTP signing is taken from the Osada project.
40 * https://framagit.org/macgirvin/osada
45 * - Activities: Dislike, Update, Delete
46 * - Object Types: Person, Tombstome
49 * - Activities: Like, Dislike, Update, Delete, Announce
50 * - Object Tyoes: Article, Person, Tombstone
53 * - Endpoints: Outbox, Follower, Following
55 * - Queueing unsucessful deliveries
59 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
61 public static function isRequest()
63 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
64 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
68 * Return the ActivityPub profile of the given user
70 * @param integer $uid User ID
73 public static function profile($uid)
75 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
76 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
77 'account_removed' => false, 'verified' => true];
78 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
79 $user = DBA::selectFirst('user', $fields, $condition);
80 if (!DBA::isResult($user)) {
84 $fields = ['locality', 'region', 'country-name'];
85 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
86 if (!DBA::isResult($profile)) {
90 $fields = ['name', 'url', 'location', 'about', 'avatar'];
91 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
92 if (!DBA::isResult($contact)) {
96 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
97 ['vcard' => 'http://www.w3.org/2006/vcard/ns#', 'uuid' => 'http://schema.org/identifier',
98 'sensitive' => 'as:sensitive', 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers']]];
100 $data['id'] = $contact['url'];
101 $data['uuid'] = $user['guid'];
102 $data['type'] = $accounttype[$user['account-type']];
103 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
104 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
105 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
106 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
107 $data['preferredUsername'] = $user['nickname'];
108 $data['name'] = $contact['name'];
109 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
110 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
111 $data['summary'] = $contact['about'];
112 $data['url'] = $contact['url'];
113 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
114 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
115 'owner' => $contact['url'],
116 'publicKeyPem' => $user['pubkey']];
117 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
118 $data['icon'] = ['type' => 'Image',
119 'url' => $contact['avatar']];
121 // tags: https://kitty.town/@inmysocks/100656097926961126.json
125 private static function fetchPermissionBlockFromConversation($item)
127 if (empty($item['thr-parent'])) {
131 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
132 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
133 if (!DBA::isResult($conversation)) {
137 $activity = json_decode($conversation['source'], true);
139 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
140 $profile = ActivityPub::fetchprofile($actor);
144 $elements = ['to', 'cc', 'bto', 'bcc'];
145 foreach ($elements as $element) {
146 if (empty($activity[$element])) {
149 if (is_string($activity[$element])) {
150 $activity[$element] = [$activity[$element]];
152 foreach ($activity[$element] as $receiver) {
153 if ($receiver == $profile['followers']) {
154 $receiver = System::baseUrl() . '/followers/' . $item['author-nick'];
156 $permissions[$element][] = $receiver;
162 public static function createPermissionBlockForItem($item)
164 $data = ['to' => [], 'cc' => []];
166 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
168 $terms = Term::tagArrayFromItemId($item['id']);
170 if (!$item['private']) {
171 $data['to'][] = self::PUBLIC;
172 $data['cc'][] = System::baseUrl() . '/followers/' . $item['author-nick'];
174 foreach ($terms as $term) {
175 if ($term['type'] != TERM_MENTION) {
178 $profile = self::fetchprofile($term['url']);
179 if (!empty($profile)) {
180 $data['cc'][] = $profile['url'];
184 //$data['cc'][] = System::baseUrl() . '/followers/' . $item['author-nick'];
185 $receiver_list = Item::enumeratePermissions($item);
190 foreach ($terms as $term) {
191 if ($term['type'] != TERM_MENTION) {
194 $cid = Contact::getIdForURL($term['url'], $item['uid']);
195 if (!empty($cid) && in_array($cid, $receiver_list)) {
196 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
197 $data['to'][] = $contact['url'];
198 $contacts[$contact['url']] = $contact['url'];
202 foreach ($receiver_list as $receiver) {
203 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
204 if (empty($contacts[$contact['url']])) {
205 $data['cc'][] = $contact['url'];
206 $contacts[$contact['url']] = $contact['url'];
210 if (empty($data['to'])) {
211 $data['to'] = $data['cc'];
219 private static function fetchTargetInboxesFromConversation($item, $uid)
221 if (empty($item['thr-parent'])) {
225 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
226 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
227 if (!DBA::isResult($conversation)) {
231 $activity = json_decode($conversation['source'], true);
233 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
234 $profile = ActivityPub::fetchprofile($actor);
238 $elements = ['to', 'cc', 'bto', 'bcc'];
239 foreach ($elements as $element) {
240 if (empty($activity[$element])) {
243 if (is_string($activity[$element])) {
244 $activity[$element] = [$activity[$element]];
246 foreach ($activity[$element] as $receiver) {
247 if ($receiver == $profile['followers']) {
248 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $uid,
249 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
250 while ($contact = DBA::fetch($contacts)) {
251 $contact = defaults($contact, 'batch', $contact['notify']);
252 $inboxes[$contact] = $contact;
254 DBA::close($contacts);
256 $profile = self::fetchprofile($receiver);
257 if (!empty($profile)) {
258 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
259 $inboxes[$target] = $target;
267 public static function fetchTargetInboxes($item, $uid)
269 $inboxes = self::fetchTargetInboxesFromConversation($item, $uid);
271 $parents = Item::select(['author-link', 'owner-link'], ['parent' => $item['parent']]);
272 while ($parent = Item::fetch($parents)) {
273 $profile = self::fetchprofile($parent['author-link']);
274 if (!empty($profile)) {
275 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
276 $inboxes[$target] = $target;
278 $profile = self::fetchprofile($parent['owner-link']);
279 if (!empty($profile)) {
280 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
281 $inboxes[$target] = $target;
284 DBA::close($parents);
286 $terms = Term::tagArrayFromItemId($item['id']);
287 if (!$item['private']) {
288 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $uid,
289 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
290 while ($contact = DBA::fetch($contacts)) {
291 $contact = defaults($contact, 'batch', $contact['notify']);
292 $inboxes[$contact] = $contact;
294 DBA::close($contacts);
296 foreach ($terms as $term) {
297 if ($term['type'] != TERM_MENTION) {
300 $profile = self::fetchprofile($term['url']);
301 if (!empty($profile)) {
302 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
303 $inboxes[$target] = $target;
307 $receiver_list = Item::enumeratePermissions($item);
310 foreach ($terms as $term) {
311 if ($term['type'] != TERM_MENTION) {
314 $cid = Contact::getIdForURL($term['url'], $uid);
315 if (!empty($cid) && in_array($cid, $receiver_list)) {
316 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
317 $profile = self::fetchprofile($contact['url']);
318 if (!empty($profile)) {
319 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
320 $inboxes[$target] = $target;
325 foreach ($receiver_list as $receiver) {
326 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
327 $profile = self::fetchprofile($contact['url']);
328 if (!empty($profile)) {
329 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
330 $inboxes[$target] = $target;
335 $profile = self::fetchprofile($item['author-link']);
336 if (!empty($profile['sharedinbox'])) {
337 unset($inboxes[$profile['sharedinbox']]);
340 if (!empty($profile['inbox'])) {
341 unset($inboxes[$profile['inbox']]);
347 public static function createActivityFromItem($item_id)
349 $item = Item::selectFirst([], ['id' => $item_id]);
351 if (!DBA::isResult($item)) {
355 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
356 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
357 if (DBA::isResult($conversation)) {
358 $data = json_decode($conversation['source']);
364 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
365 ['ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
366 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
367 'conversation' => 'ostatus:conversation',
368 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
370 $data['id'] = $item['uri'] . '#activity';
371 $data['type'] = 'Create';
372 $data['actor'] = $item['author-link'];
374 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
376 if ($item["created"] != $item["edited"]) {
377 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
380 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
382 $data['object'] = self::createNote($item);
384 $owner = User::getOwnerDataById($item['uid']);
386 return LDSignature::sign($data, $owner);
389 public static function createObjectFromItemID($item_id)
391 $item = Item::selectFirst([], ['id' => $item_id]);
393 if (!DBA::isResult($item)) {
397 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
398 ['ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
399 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
400 'conversation' => 'ostatus:conversation',
401 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
403 $data = array_merge($data, self::createNote($item));
409 private static function createTagList($item)
413 $terms = Term::tagArrayFromItemId($item['id']);
414 foreach ($terms as $term) {
415 if ($term['type'] == TERM_MENTION) {
416 $contact = Contact::getDetailsByURL($term['url']);
417 if (!empty($contact['addr'])) {
418 $mention = '@' . $contact['addr'];
420 $mention = '@' . $term['url'];
423 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
430 public static function createNote($item)
433 $data['id'] = $item['uri'];
434 $data['type'] = 'Note';
435 $data['summary'] = null; // Ignore by now
437 if ($item['uri'] != $item['thr-parent']) {
438 $data['inReplyTo'] = $item['thr-parent'];
440 $data['inReplyTo'] = null;
443 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
445 if ($item["created"] != $item["edited"]) {
446 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
449 $data['url'] = $item['uri'];
450 $data['attributedTo'] = $item['author-link'];
451 $data['actor'] = $item['author-link'];
452 $data['sensitive'] = false; // - Query NSFW
454 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
455 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
456 $conversation_uri = $conversation['conversation-uri'];
458 $conversation_uri = $item['parent-uri'];
461 $data['conversation'] = $conversation_uri;
463 if (!empty($item['title'])) {
464 $data['name'] = BBCode::convert($item['title'], false, 7);
467 $data['content'] = BBCode::convert($item['body'], false, 7);
468 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
469 $data['attachment'] = []; // @ToDo
470 $data['tag'] = self::createTagList($item);
471 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
473 //$data['emoji'] = []; // Ignore by now
477 public static function transmitActivity($activity, $target, $uid)
479 $profile = self::fetchprofile($target);
481 $owner = User::getOwnerDataById($uid);
483 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
484 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
486 'actor' => $owner['url'],
487 'object' => $profile['url'],
488 'to' => $profile['url']];
490 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
492 $signed = LDSignature::sign($data, $owner);
493 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
496 public static function transmitContactAccept($target, $id, $uid)
498 $profile = self::fetchprofile($target);
500 $owner = User::getOwnerDataById($uid);
501 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
502 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
504 'actor' => $owner['url'],
505 'object' => ['id' => $id, 'type' => 'Follow',
506 'actor' => $profile['url'],
507 'object' => $owner['url']],
508 'to' => $profile['url']];
510 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
512 $signed = LDSignature::sign($data, $owner);
513 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
516 public static function transmitContactReject($target, $id, $uid)
518 $profile = self::fetchprofile($target);
520 $owner = User::getOwnerDataById($uid);
521 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
522 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
524 'actor' => $owner['url'],
525 'object' => ['id' => $id, 'type' => 'Follow',
526 'actor' => $profile['url'],
527 'object' => $owner['url']],
528 'to' => $profile['url']];
530 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
532 $signed = LDSignature::sign($data, $owner);
533 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
536 public static function transmitContactUndo($target, $uid)
538 $profile = self::fetchprofile($target);
540 $id = System::baseUrl() . '/activity/' . System::createGUID();
542 $owner = User::getOwnerDataById($uid);
543 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
546 'actor' => $owner['url'],
547 'object' => ['id' => $id, 'type' => 'Follow',
548 'actor' => $owner['url'],
549 'object' => $profile['url']],
550 'to' => $profile['url']];
552 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
554 $signed = LDSignature::sign($data, $owner);
555 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
559 * Fetches ActivityPub content from the given url
561 * @param string $url content url
564 public static function fetchContent($url)
566 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
567 if (!$ret['success'] || empty($ret['body'])) {
571 return json_decode($ret['body'], true);
575 * Resolves the profile url from the address by using webfinger
577 * @param string $addr profile address (user@domain.tld)
580 private static function addrToUrl($addr)
582 $addr_parts = explode('@', $addr);
583 if (count($addr_parts) != 2) {
587 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
589 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
590 if (!$ret['success'] || empty($ret['body'])) {
594 $data = json_decode($ret['body'], true);
596 if (empty($data['links'])) {
600 foreach ($data['links'] as $link) {
601 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
605 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
606 return $link['href'];
613 public static function fetchprofile($url, $update = false)
620 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
621 if (DBA::isResult($apcontact)) {
625 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
626 if (DBA::isResult($apcontact)) {
630 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
631 if (DBA::isResult($apcontact)) {
636 if (empty(parse_url($url, PHP_URL_SCHEME))) {
637 $url = self::addrToUrl($url);
643 $data = self::fetchContent($url);
645 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
650 $apcontact['url'] = $data['id'];
651 $apcontact['uuid'] = defaults($data, 'uuid', null);
652 $apcontact['type'] = defaults($data, 'type', null);
653 $apcontact['following'] = defaults($data, 'following', null);
654 $apcontact['followers'] = defaults($data, 'followers', null);
655 $apcontact['inbox'] = defaults($data, 'inbox', null);
656 $apcontact['outbox'] = defaults($data, 'outbox', null);
657 $apcontact['sharedinbox'] = JsonLD::fetchElement($data, 'endpoints', 'sharedInbox');
658 $apcontact['nick'] = defaults($data, 'preferredUsername', null);
659 $apcontact['name'] = defaults($data, 'name', $apcontact['nick']);
660 $apcontact['about'] = defaults($data, 'summary', '');
661 $apcontact['photo'] = JsonLD::fetchElement($data, 'icon', 'url');
662 $apcontact['alias'] = JsonLD::fetchElement($data, 'url', 'href');
664 $parts = parse_url($apcontact['url']);
665 unset($parts['scheme']);
666 unset($parts['path']);
667 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
669 $apcontact['pubkey'] = trim(JsonLD::fetchElement($data, 'publicKey', 'publicKeyPem'));
672 // manuallyApprovesFollowers
675 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
677 // Unhandled from Misskey
678 // sharedInbox, isCat
680 // Unhandled from Kroeg
681 // kroeg:blocks, updated
683 // Check if the address is resolvable
684 if (self::addrToUrl($apcontact['addr']) == $apcontact['url']) {
685 $parts = parse_url($apcontact['url']);
686 unset($parts['path']);
687 $apcontact['baseurl'] = Network::unparseURL($parts);
689 $apcontact['addr'] = null;
692 if ($apcontact['url'] == $apcontact['alias']) {
693 $apcontact['alias'] = null;
696 $apcontact['updated'] = DateTimeFormat::utcNow();
698 DBA::update('apcontact', $apcontact, ['url' => $url], true);
704 * Fetches a profile from the given url into an array that is compatible to Probe::uri
706 * @param string $url profile url
709 public static function probeProfile($url)
711 $apcontact = self::fetchprofile($url, true);
712 if (empty($apcontact)) {
716 $profile = ['network' => Protocol::ACTIVITYPUB];
717 $profile['nick'] = $apcontact['nick'];
718 $profile['name'] = $apcontact['name'];
719 $profile['guid'] = $apcontact['uuid'];
720 $profile['url'] = $apcontact['url'];
721 $profile['addr'] = $apcontact['addr'];
722 $profile['alias'] = $apcontact['alias'];
723 $profile['photo'] = $apcontact['photo'];
724 // $profile['community']
725 // $profile['keywords']
726 // $profile['location']
727 $profile['about'] = $apcontact['about'];
728 $profile['batch'] = $apcontact['sharedinbox'];
729 $profile['notify'] = $apcontact['inbox'];
730 $profile['poll'] = $apcontact['outbox'];
731 $profile['pubkey'] = $apcontact['pubkey'];
732 $profile['baseurl'] = $apcontact['baseurl'];
734 // Remove all "null" fields
735 foreach ($profile as $field => $content) {
736 if (is_null($content)) {
737 unset($profile[$field]);
744 public static function processInbox($body, $header, $uid)
746 $http_signer = HTTPSignature::getSigner($body, $header);
747 if (empty($http_signer)) {
748 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
751 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
754 $activity = json_decode($body, true);
756 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
757 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
759 if (empty($activity)) {
760 logger('Invalid body.', LOGGER_DEBUG);
764 if (LDSignature::isSigned($activity)) {
765 $ld_signer = LDSignature::getSigner($activity);
766 if (!empty($ld_signer)) {
767 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
768 $trust_source = true;
769 } elseif ($actor == $http_signer) {
770 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
771 $trust_source = true;
773 logger('Invalid JSON-LD signature.', LOGGER_DEBUG);
774 $trust_source = false;
776 } elseif ($actor == $http_signer) {
777 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
778 $trust_source = true;
780 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
781 $trust_source = false;
784 self::processActivity($activity, $body, $uid, $trust_source);
787 public static function fetchOutbox($url, $uid)
789 $data = self::fetchContent($url);
794 if (!empty($data['orderedItems'])) {
795 $items = $data['orderedItems'];
796 } elseif (!empty($data['first']['orderedItems'])) {
797 $items = $data['first']['orderedItems'];
798 } elseif (!empty($data['first'])) {
799 self::fetchOutbox($data['first'], $uid);
805 foreach ($items as $activity) {
806 self::processActivity($activity, '', $uid, true);
810 private static function prepareObjectData($activity, $uid, $trust_source)
812 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
814 logger('Empty actor', LOGGER_DEBUG);
818 // Fetch all receivers from to, cc, bto and bcc
819 $receivers = self::getReceivers($activity, $actor);
821 // When it is a delivery to a personal inbox we add that user to the receivers
823 $owner = User::getOwnerDataById($uid);
824 $additional = ['uid:' . $uid => $uid];
825 $receivers = array_merge($receivers, $additional);
828 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
830 if (is_string($activity['object'])) {
831 $object_url = $activity['object'];
832 } elseif (!empty($activity['object']['id'])) {
833 $object_url = $activity['object']['id'];
835 logger('No object found', LOGGER_DEBUG);
839 // Fetch the content only on activities where this matters
840 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
841 $object_data = self::fetchObject($object_url, $activity['object'], $trust_source);
842 if (empty($object_data)) {
843 logger("Object data couldn't be processed", LOGGER_DEBUG);
846 } elseif ($activity['type'] == 'Accept') {
848 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
849 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'actor');
850 } elseif ($activity['type'] == 'Undo') {
852 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
853 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'object');
854 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
855 // Create a mostly empty array out of the activity data (instead of the object).
856 // This way we later don't have to check for the existence of ech individual array element.
857 $object_data = self::processCommonData($activity);
858 $object_data['name'] = $activity['type'];
859 $object_data['author'] = $activity['actor'];
860 $object_data['object'] = $object_url;
861 } elseif ($activity['type'] == 'Follow') {
862 $object_data['id'] = $activity['id'];
863 $object_data['object'] = $object_url;
868 $object_data = self::addActivityFields($object_data, $activity);
870 $object_data['type'] = $activity['type'];
871 $object_data['owner'] = $actor;
872 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
877 private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
879 if (empty($activity['type'])) {
880 logger('Empty type', LOGGER_DEBUG);
884 if (empty($activity['object'])) {
885 logger('Empty object', LOGGER_DEBUG);
889 if (empty($activity['actor'])) {
890 logger('Empty actor', LOGGER_DEBUG);
896 // title, atomUri, context_id, statusnetConversationId
899 // context, location, signature;
901 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
903 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
904 if (empty($object_data)) {
905 logger('No object data found', LOGGER_DEBUG);
909 switch ($activity['type']) {
912 self::createItem($object_data, $body);
916 self::likeItem($object_data, $body);
929 self::followUser($object_data);
933 if ($object_data['object_type'] == 'Follow') {
934 self::acceptFollowUser($object_data);
939 if ($object_data['object_type'] == 'Follow') {
940 self::undoFollowUser($object_data);
945 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
950 private static function getReceivers($activity, $actor)
954 // When it is an answer, we inherite the receivers from the parent
955 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
956 if (!empty($replyto)) {
957 $parents = Item::select(['uid'], ['uri' => $replyto]);
958 while ($parent = Item::fetch($parents)) {
959 $receivers['uid:' . $parent['uid']] = $parent['uid'];
963 if (!empty($actor)) {
964 $profile = self::fetchprofile($actor);
965 $followers = defaults($profile, 'followers', '');
967 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
969 logger('Empty actor', LOGGER_DEBUG);
973 $elements = ['to', 'cc', 'bto', 'bcc'];
974 foreach ($elements as $element) {
975 if (empty($activity[$element])) {
979 // The receiver can be an arror or a string
980 if (is_string($activity[$element])) {
981 $activity[$element] = [$activity[$element]];
984 foreach ($activity[$element] as $receiver) {
985 if ($receiver == self::PUBLIC) {
986 $receivers['uid:0'] = 0;
989 if (($receiver == self::PUBLIC) && !empty($actor)) {
990 // This will most likely catch all OStatus connections to Mastodon
991 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
992 $contacts = DBA::select('contact', ['uid'], $condition);
993 while ($contact = DBA::fetch($contacts)) {
994 if ($contact['uid'] != 0) {
995 $receivers['uid:' . $contact['uid']] = $contact['uid'];
998 DBA::close($contacts);
1001 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
1002 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1003 'network' => Protocol::ACTIVITYPUB];
1004 $contacts = DBA::select('contact', ['uid'], $condition);
1005 while ($contact = DBA::fetch($contacts)) {
1006 if ($contact['uid'] != 0) {
1007 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1010 DBA::close($contacts);
1014 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1015 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1016 if (!DBA::isResult($contact)) {
1019 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1025 private static function addActivityFields($object_data, $activity)
1027 if (!empty($activity['published']) && empty($object_data['published'])) {
1028 $object_data['published'] = $activity['published'];
1031 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1032 $object_data['updated'] = $activity['updated'];
1035 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1036 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1039 if (!empty($activity['instrument'])) {
1040 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
1042 return $object_data;
1045 private static function fetchObject($object_url, $object = [], $trust_source = false)
1047 if (!$trust_source || is_string($object)) {
1048 $data = self::fetchContent($object_url);
1050 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
1051 $data = $object_url;
1053 logger('Fetched content for ' . $object_url, LOGGER_DEBUG);
1056 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
1060 if (is_string($data)) {
1061 $item = Item::selectFirst([], ['uri' => $data]);
1062 if (!DBA::isResult($item)) {
1063 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1066 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
1067 $data = self::createNote($item);
1070 if (empty($data['type'])) {
1071 logger('Empty type', LOGGER_DEBUG);
1074 $type = $data['type'];
1075 logger('Type ' . $type, LOGGER_DEBUG);
1078 if (in_array($type, ['Note', 'Article', 'Video'])) {
1079 $common = self::processCommonData($data);
1084 return array_merge($common, self::processNote($data));
1086 return array_merge($common, self::processArticle($data));
1088 return array_merge($common, self::processVideo($data));
1091 if (empty($data['object'])) {
1094 return self::fetchObject($data['object']);
1101 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1106 private static function processCommonData(&$object)
1108 if (empty($object['id'])) {
1113 $object_data['type'] = $object['type'];
1114 $object_data['uri'] = $object['id'];
1116 if (!empty($object['inReplyTo'])) {
1117 $object_data['reply-to-uri'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1119 $object_data['reply-to-uri'] = $object_data['uri'];
1122 $object_data['published'] = defaults($object, 'published', null);
1123 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1125 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1126 $object_data['published'] = $object_data['updated'];
1129 $object_data['uuid'] = defaults($object, 'uuid', null);
1130 $object_data['owner'] = $object_data['author'] = JsonLD::fetchElement($object, 'attributedTo', 'id');
1131 $object_data['context'] = defaults($object, 'context', null);
1132 $object_data['conversation'] = defaults($object, 'conversation', null);
1133 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1134 $object_data['name'] = defaults($object, 'title', null);
1135 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1136 $object_data['summary'] = defaults($object, 'summary', null);
1137 $object_data['content'] = defaults($object, 'content', null);
1138 $object_data['source'] = defaults($object, 'source', null);
1139 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1140 $object_data['attachments'] = defaults($object, 'attachment', null);
1141 $object_data['tags'] = defaults($object, 'tag', null);
1142 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1143 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1144 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1147 // @context, type, actor, signature, mediaType, duration, replies, icon
1149 // Also missing: (Defined in the standard, but currently unused)
1150 // audience, preview, endTime, startTime, generator, image
1152 return $object_data;
1155 private static function processNote($object)
1160 // emoji, atomUri, inReplyToAtomUri
1163 // contentMap, announcement_count, announcements, context_id, likes, like_count
1164 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1166 return $object_data;
1169 private static function processArticle($object)
1173 return $object_data;
1176 private static function processVideo($object)
1181 // category, licence, language, commentsEnabled
1184 // views, waitTranscoding, state, support, subtitleLanguage
1185 // likes, dislikes, shares, comments
1187 return $object_data;
1190 private static function convertMentions($body)
1192 $URLSearchString = "^\[\]";
1193 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1198 private static function constructTagList($tags, $sensitive)
1205 foreach ($tags as $tag) {
1206 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1207 if (!empty($tag_text)) {
1211 if (empty($tag['href'])) {
1216 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1220 /// @todo add nsfw for $sensitive
1225 private static function constructAttachList($attachments, $item)
1227 if (empty($attachments)) {
1231 foreach ($attachments as $attach) {
1232 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1233 if ($filetype == 'image') {
1234 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1236 if (!empty($item["attach"])) {
1237 $item["attach"] .= ',';
1239 $item["attach"] = '';
1241 if (!isset($attach['length'])) {
1242 $attach['length'] = "0";
1244 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1251 private static function createItem($activity, $body)
1254 $item['verb'] = ACTIVITY_POST;
1255 $item['parent-uri'] = $activity['reply-to-uri'];
1257 if ($activity['reply-to-uri'] == $activity['uri']) {
1258 $item['gravity'] = GRAVITY_PARENT;
1259 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1261 $item['gravity'] = GRAVITY_COMMENT;
1262 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1265 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1266 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1267 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1270 self::postItem($activity, $item, $body);
1273 private static function likeItem($activity, $body)
1276 $item['verb'] = ACTIVITY_LIKE;
1277 $item['parent-uri'] = $activity['object'];
1278 $item['gravity'] = GRAVITY_ACTIVITY;
1279 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1281 self::postItem($activity, $item, $body);
1284 private static function postItem($activity, $item, $body)
1286 /// @todo What to do with $activity['context']?
1288 $item['network'] = Protocol::ACTIVITYPUB;
1289 $item['private'] = !in_array(0, $activity['receiver']);
1290 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1291 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1292 $item['uri'] = $activity['uri'];
1293 $item['created'] = $activity['published'];
1294 $item['edited'] = $activity['updated'];
1295 $item['guid'] = $activity['uuid'];
1296 $item['title'] = HTML::toBBCode($activity['name']);
1297 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1298 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1299 $item['location'] = $activity['location'];
1300 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1301 $item['app'] = $activity['service'];
1302 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1304 $item = self::constructAttachList($activity['attachments'], $item);
1306 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1307 if (!empty($source)) {
1308 $item['body'] = $source;
1311 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1312 $item['source'] = $body;
1313 $item['conversation-uri'] = $activity['conversation'];
1315 foreach ($activity['receiver'] as $receiver) {
1316 $item['uid'] = $receiver;
1317 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1319 if (($receiver != 0) && empty($item['contact-id'])) {
1320 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1323 $item_id = Item::insert($item);
1324 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1328 private static function fetchMissingActivity($url, $child)
1330 $object = ActivityPub::fetchContent($url);
1331 if (empty($object)) {
1332 logger('Activity ' . $url . ' was not fetchable, aborting.');
1337 $activity['@context'] = $object['@context'];
1338 unset($object['@context']);
1339 $activity['id'] = $object['id'];
1340 $activity['to'] = defaults($object, 'to', []);
1341 $activity['cc'] = defaults($object, 'cc', []);
1342 $activity['actor'] = $child['author'];
1343 $activity['object'] = $object;
1344 $activity['published'] = $object['published'];
1345 $activity['type'] = 'Create';
1347 self::processActivity($activity);
1348 logger('Activity ' . $url . ' had been fetched and processed.');
1351 private static function getUserOfObject($object)
1353 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1354 if (!DBA::isResult($self)) {
1357 return $self['uid'];
1361 private static function followUser($activity)
1363 $uid = self::getUserOfObject($activity['object']);
1368 $owner = User::getOwnerDataById($uid);
1370 $cid = Contact::getIdForURL($activity['owner'], $uid);
1372 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1377 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1378 'author-link' => $activity['owner']];
1380 Contact::addRelationship($owner, $contact, $item);
1381 $cid = Contact::getIdForURL($activity['owner'], $uid);
1386 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1387 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1388 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1391 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1392 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1395 private static function acceptFollowUser($activity)
1397 $uid = self::getUserOfObject($activity['object']);
1402 $owner = User::getOwnerDataById($uid);
1404 $cid = Contact::getIdForURL($activity['owner'], $uid);
1406 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1410 $fields = ['pending' => false];
1412 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1413 if ($contact['rel'] == Contact::FOLLOWER) {
1414 $fields['rel'] = Contact::FRIEND;
1417 $condition = ['id' => $cid];
1418 DBA::update('contact', $fields, $condition);
1419 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1422 private static function undoFollowUser($activity)
1424 $uid = self::getUserOfObject($activity['object']);
1429 $owner = User::getOwnerDataById($uid);
1431 $cid = Contact::getIdForURL($activity['owner'], $uid);
1433 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1437 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1438 if (!DBA::isResult($contact)) {
1442 Contact::removeFollower($owner, $contact);
1443 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);