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: Update, Delete
46 * - Object Types: Person, Tombstome
49 * - Activities: Announce
50 * - Object Tyoes: 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);
142 $item_profile = ActivityPub::fetchprofile($item['owner-link']);
146 $elements = ['to', 'cc', 'bto', 'bcc'];
147 foreach ($elements as $element) {
148 if (empty($activity[$element])) {
151 if (is_string($activity[$element])) {
152 $activity[$element] = [$activity[$element]];
154 foreach ($activity[$element] as $receiver) {
155 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
156 $receiver = $item_profile['followers'];
158 if ($receiver != $item['owner-link']) {
159 $permissions[$element][] = $receiver;
166 public static function createPermissionBlockForItem($item)
168 $data = ['to' => [], 'cc' => []];
170 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
172 $actor_profile = ActivityPub::fetchprofile($item['author-link']);
174 $terms = Term::tagArrayFromItemId($item['id']);
176 $contacts[$item['author-link']] = $item['author-link'];
178 if (!$item['private']) {
179 $data['to'][] = self::PUBLIC;
180 if (!empty($actor_profile['followers'])) {
181 $data['cc'][] = $actor_profile['followers'];
184 foreach ($terms as $term) {
185 if ($term['type'] != TERM_MENTION) {
188 $profile = self::fetchprofile($term['url']);
189 if (!empty($profile) && empty($contacts[$profile['url']])) {
190 $data['cc'][] = $profile['url'];
191 $contacts[$profile['url']] = $profile['url'];
195 $receiver_list = Item::enumeratePermissions($item);
199 foreach ($terms as $term) {
200 if ($term['type'] != TERM_MENTION) {
203 $cid = Contact::getIdForURL($term['url'], $item['uid']);
204 if (!empty($cid) && in_array($cid, $receiver_list)) {
205 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
206 $data['to'][] = $contact['url'];
207 $contacts[$contact['url']] = $contact['url'];
211 foreach ($receiver_list as $receiver) {
212 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
213 if (empty($contacts[$contact['url']])) {
214 $data['cc'][] = $contact['url'];
215 $contacts[$contact['url']] = $contact['url'];
220 $parents = Item::select(['author-link', 'owner-link'], ['parent' => $item['parent']]);
221 while ($parent = Item::fetch($parents)) {
222 $profile = self::fetchprofile($parent['author-link']);
223 if (!empty($profile) && empty($contacts[$profile['url']])) {
224 $data['cc'][] = $profile['url'];
225 $contacts[$profile['url']] = $profile['url'];
228 $profile = self::fetchprofile($parent['owner-link']);
229 if (!empty($profile) && empty($contacts[$profile['url']])) {
230 $data['cc'][] = $profile['url'];
231 $contacts[$profile['url']] = $profile['url'];
234 DBA::close($parents);
236 if (empty($data['to'])) {
237 $data['to'] = $data['cc'];
244 public static function fetchTargetInboxes($item, $uid)
246 $permissions = self::createPermissionBlockForItem($item);
247 if (empty($permissions)) {
253 $item_profile = ActivityPub::fetchprofile($item['owner-link']);
255 $elements = ['to', 'cc', 'bto', 'bcc'];
256 foreach ($elements as $element) {
257 if (empty($permissions[$element])) {
260 foreach ($permissions[$element] as $receiver) {
261 if ($receiver == $item_profile['followers']) {
262 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $uid,
263 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
264 while ($contact = DBA::fetch($contacts)) {
265 $contact = defaults($contact, 'batch', $contact['notify']);
266 $inboxes[$contact] = $contact;
268 DBA::close($contacts);
270 $profile = self::fetchprofile($receiver);
271 if (!empty($profile)) {
272 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
273 $inboxes[$target] = $target;
279 if (!empty($item_profile['sharedinbox'])) {
280 unset($inboxes[$item_profile['sharedinbox']]);
283 if (!empty($item_profile['inbox'])) {
284 unset($inboxes[$item_profile['inbox']]);
290 public static function getTypeOfItem($item)
292 if ($item['verb'] == ACTIVITY_POST) {
293 if ($item['created'] == $item['edited']) {
298 } elseif ($item['verb'] == ACTIVITY_LIKE) {
300 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
302 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
304 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
306 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
307 $type = 'TentativeAccept';
310 if ($item['deleted']) {
317 public static function createActivityFromItem($item_id)
319 $item = Item::selectFirst([], ['id' => $item_id]);
321 if (!DBA::isResult($item)) {
325 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
326 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
327 if (DBA::isResult($conversation)) {
328 $data = json_decode($conversation['source']);
334 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
335 ['ostatus' => 'http://ostatus.org#', 'uuid' => 'http://schema.org/identifier',
336 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag',
337 'atomUri' => 'ostatus:atomUri', 'conversation' => 'ostatus:conversation',
338 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
340 $data['id'] = $item['uri'] . '#activity';
341 $data['type'] = self::getTypeOfItem($item);;
342 $data['actor'] = $item['author-link'];
344 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
346 if ($item["created"] != $item["edited"]) {
347 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
350 $data['context_id'] = $item['parent'];
351 $data['context'] = self::createConversationURLFromItem($item);
353 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
355 if (in_array($data['type'], ['Create', 'Update', 'Announce'])) {
356 $data['object'] = self::CreateNote($item);
358 $data['object'] = $item['thr-parent'];
361 $owner = User::getOwnerDataById($item['uid']);
363 return LDSignature::sign($data, $owner);
366 public static function createObjectFromItemID($item_id)
368 $item = Item::selectFirst([], ['id' => $item_id]);
370 if (!DBA::isResult($item)) {
374 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
375 ['ostatus' => 'http://ostatus.org#', 'uuid' => 'http://schema.org/identifier',
376 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag',
377 'atomUri' => 'ostatus:atomUri', 'conversation' => 'ostatus:conversation',
378 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
380 $data = array_merge($data, self::CreateNote($item));
386 private static function createTagList($item)
390 $terms = Term::tagArrayFromItemId($item['id']);
391 foreach ($terms as $term) {
392 if ($term['type'] == TERM_MENTION) {
393 $contact = Contact::getDetailsByURL($term['url']);
394 if (!empty($contact['addr'])) {
395 $mention = '@' . $contact['addr'];
397 $mention = '@' . $term['url'];
400 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
406 private static function createConversationURLFromItem($item)
408 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
409 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
410 $conversation_uri = $conversation['conversation-uri'];
412 $conversation_uri = $item['parent-uri'];
414 return $conversation_uri;
417 private static function CreateNote($item)
419 if (!empty($item['title'])) {
426 $data['id'] = $item['uri'];
427 $data['type'] = $type;
428 $data['summary'] = null; // Ignore by now
430 if ($item['uri'] != $item['thr-parent']) {
431 $data['inReplyTo'] = $item['thr-parent'];
433 $data['inReplyTo'] = null;
436 $data['uuid'] = $item['guid'];
437 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
439 if ($item["created"] != $item["edited"]) {
440 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
443 $data['url'] = $item['plink'];
444 $data['attributedTo'] = $item['author-link'];
445 $data['actor'] = $item['author-link'];
446 $data['sensitive'] = false; // - Query NSFW
447 $data['context_id'] = $item['parent'];
448 $data['conversation'] = $data['context'] = self::createConversationURLFromItem($item);
450 if (!empty($item['title'])) {
451 $data['name'] = BBCode::convert($item['title'], false, 7);
454 $data['content'] = BBCode::convert($item['body'], false, 7);
455 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
456 $data['attachment'] = []; // @ToDo
457 $data['tag'] = self::createTagList($item);
458 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
460 //$data['emoji'] = []; // Ignore by now
464 public static function transmitActivity($activity, $target, $uid)
466 $profile = self::fetchprofile($target);
468 $owner = User::getOwnerDataById($uid);
470 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
471 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
473 'actor' => $owner['url'],
474 'object' => $profile['url'],
475 'to' => $profile['url']];
477 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
479 $signed = LDSignature::sign($data, $owner);
480 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
483 public static function transmitContactAccept($target, $id, $uid)
485 $profile = self::fetchprofile($target);
487 $owner = User::getOwnerDataById($uid);
488 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
489 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
491 'actor' => $owner['url'],
492 'object' => ['id' => $id, 'type' => 'Follow',
493 'actor' => $profile['url'],
494 'object' => $owner['url']],
495 'to' => $profile['url']];
497 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
499 $signed = LDSignature::sign($data, $owner);
500 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
503 public static function transmitContactReject($target, $id, $uid)
505 $profile = self::fetchprofile($target);
507 $owner = User::getOwnerDataById($uid);
508 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
509 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
511 'actor' => $owner['url'],
512 'object' => ['id' => $id, 'type' => 'Follow',
513 'actor' => $profile['url'],
514 'object' => $owner['url']],
515 'to' => $profile['url']];
517 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
519 $signed = LDSignature::sign($data, $owner);
520 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
523 public static function transmitContactUndo($target, $uid)
525 $profile = self::fetchprofile($target);
527 $id = System::baseUrl() . '/activity/' . System::createGUID();
529 $owner = User::getOwnerDataById($uid);
530 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
533 'actor' => $owner['url'],
534 'object' => ['id' => $id, 'type' => 'Follow',
535 'actor' => $owner['url'],
536 'object' => $profile['url']],
537 'to' => $profile['url']];
539 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
541 $signed = LDSignature::sign($data, $owner);
542 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
546 * Fetches ActivityPub content from the given url
548 * @param string $url content url
551 public static function fetchContent($url)
553 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
554 if (!$ret['success'] || empty($ret['body'])) {
558 return json_decode($ret['body'], true);
562 * Resolves the profile url from the address by using webfinger
564 * @param string $addr profile address (user@domain.tld)
567 private static function addrToUrl($addr)
569 $addr_parts = explode('@', $addr);
570 if (count($addr_parts) != 2) {
574 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
576 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
577 if (!$ret['success'] || empty($ret['body'])) {
581 $data = json_decode($ret['body'], true);
583 if (empty($data['links'])) {
587 foreach ($data['links'] as $link) {
588 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
592 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
593 return $link['href'];
600 public static function fetchprofile($url, $update = false)
607 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
608 if (DBA::isResult($apcontact)) {
612 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
613 if (DBA::isResult($apcontact)) {
617 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
618 if (DBA::isResult($apcontact)) {
623 if (empty(parse_url($url, PHP_URL_SCHEME))) {
624 $url = self::addrToUrl($url);
630 $data = self::fetchContent($url);
632 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
637 $apcontact['url'] = $data['id'];
638 $apcontact['uuid'] = defaults($data, 'uuid', null);
639 $apcontact['type'] = defaults($data, 'type', null);
640 $apcontact['following'] = defaults($data, 'following', null);
641 $apcontact['followers'] = defaults($data, 'followers', null);
642 $apcontact['inbox'] = defaults($data, 'inbox', null);
643 $apcontact['outbox'] = defaults($data, 'outbox', null);
644 $apcontact['sharedinbox'] = JsonLD::fetchElement($data, 'endpoints', 'sharedInbox');
645 $apcontact['nick'] = defaults($data, 'preferredUsername', null);
646 $apcontact['name'] = defaults($data, 'name', $apcontact['nick']);
647 $apcontact['about'] = defaults($data, 'summary', '');
648 $apcontact['photo'] = JsonLD::fetchElement($data, 'icon', 'url');
649 $apcontact['alias'] = JsonLD::fetchElement($data, 'url', 'href');
651 $parts = parse_url($apcontact['url']);
652 unset($parts['scheme']);
653 unset($parts['path']);
654 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
656 $apcontact['pubkey'] = trim(JsonLD::fetchElement($data, 'publicKey', 'publicKeyPem'));
659 // manuallyApprovesFollowers
662 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
664 // Unhandled from Misskey
665 // sharedInbox, isCat
667 // Unhandled from Kroeg
668 // kroeg:blocks, updated
670 // Check if the address is resolvable
671 if (self::addrToUrl($apcontact['addr']) == $apcontact['url']) {
672 $parts = parse_url($apcontact['url']);
673 unset($parts['path']);
674 $apcontact['baseurl'] = Network::unparseURL($parts);
676 $apcontact['addr'] = null;
679 if ($apcontact['url'] == $apcontact['alias']) {
680 $apcontact['alias'] = null;
683 $apcontact['updated'] = DateTimeFormat::utcNow();
685 DBA::update('apcontact', $apcontact, ['url' => $url], true);
691 * Fetches a profile from the given url into an array that is compatible to Probe::uri
693 * @param string $url profile url
696 public static function probeProfile($url)
698 $apcontact = self::fetchprofile($url, true);
699 if (empty($apcontact)) {
703 $profile = ['network' => Protocol::ACTIVITYPUB];
704 $profile['nick'] = $apcontact['nick'];
705 $profile['name'] = $apcontact['name'];
706 $profile['guid'] = $apcontact['uuid'];
707 $profile['url'] = $apcontact['url'];
708 $profile['addr'] = $apcontact['addr'];
709 $profile['alias'] = $apcontact['alias'];
710 $profile['photo'] = $apcontact['photo'];
711 // $profile['community']
712 // $profile['keywords']
713 // $profile['location']
714 $profile['about'] = $apcontact['about'];
715 $profile['batch'] = $apcontact['sharedinbox'];
716 $profile['notify'] = $apcontact['inbox'];
717 $profile['poll'] = $apcontact['outbox'];
718 $profile['pubkey'] = $apcontact['pubkey'];
719 $profile['baseurl'] = $apcontact['baseurl'];
721 // Remove all "null" fields
722 foreach ($profile as $field => $content) {
723 if (is_null($content)) {
724 unset($profile[$field]);
731 public static function processInbox($body, $header, $uid)
733 $http_signer = HTTPSignature::getSigner($body, $header);
734 if (empty($http_signer)) {
735 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
738 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
741 $activity = json_decode($body, true);
743 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
744 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
746 if (empty($activity)) {
747 logger('Invalid body.', LOGGER_DEBUG);
751 if (LDSignature::isSigned($activity)) {
752 $ld_signer = LDSignature::getSigner($activity);
753 if (!empty($ld_signer && ($actor == $http_signer))) {
754 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
755 $trust_source = true;
756 } elseif (!empty($ld_signer)) {
757 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
758 $trust_source = true;
759 } elseif ($actor == $http_signer) {
760 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
761 $trust_source = true;
763 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
764 $trust_source = false;
766 } elseif ($actor == $http_signer) {
767 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
768 $trust_source = true;
770 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
771 $trust_source = false;
774 self::processActivity($activity, $body, $uid, $trust_source);
777 public static function fetchOutbox($url, $uid)
779 $data = self::fetchContent($url);
784 if (!empty($data['orderedItems'])) {
785 $items = $data['orderedItems'];
786 } elseif (!empty($data['first']['orderedItems'])) {
787 $items = $data['first']['orderedItems'];
788 } elseif (!empty($data['first'])) {
789 self::fetchOutbox($data['first'], $uid);
795 foreach ($items as $activity) {
796 self::processActivity($activity, '', $uid, true);
800 private static function prepareObjectData($activity, $uid, $trust_source)
802 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
804 logger('Empty actor', LOGGER_DEBUG);
808 // Fetch all receivers from to, cc, bto and bcc
809 $receivers = self::getReceivers($activity, $actor);
811 // When it is a delivery to a personal inbox we add that user to the receivers
813 $owner = User::getOwnerDataById($uid);
814 $additional = ['uid:' . $uid => $uid];
815 $receivers = array_merge($receivers, $additional);
818 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
820 if (is_string($activity['object'])) {
821 $object_url = $activity['object'];
822 } elseif (!empty($activity['object']['id'])) {
823 $object_url = $activity['object']['id'];
825 logger('No object found', LOGGER_DEBUG);
829 // Fetch the content only on activities where this matters
830 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
831 $object_data = self::fetchObject($object_url, $activity['object'], $trust_source);
832 if (empty($object_data)) {
833 logger("Object data couldn't be processed", LOGGER_DEBUG);
836 } elseif ($activity['type'] == 'Accept') {
838 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
839 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'actor');
840 } elseif ($activity['type'] == 'Undo') {
842 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
843 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'object');
844 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
845 // Create a mostly empty array out of the activity data (instead of the object).
846 // This way we later don't have to check for the existence of ech individual array element.
847 $object_data = self::processCommonData($activity);
848 $object_data['name'] = $activity['type'];
849 $object_data['author'] = $activity['actor'];
850 $object_data['object'] = $object_url;
851 } elseif ($activity['type'] == 'Follow') {
852 $object_data['id'] = $activity['id'];
853 $object_data['object'] = $object_url;
858 $object_data = self::addActivityFields($object_data, $activity);
860 $object_data['type'] = $activity['type'];
861 $object_data['owner'] = $actor;
862 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
867 private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
869 if (empty($activity['type'])) {
870 logger('Empty type', LOGGER_DEBUG);
874 if (empty($activity['object'])) {
875 logger('Empty object', LOGGER_DEBUG);
879 if (empty($activity['actor'])) {
880 logger('Empty actor', LOGGER_DEBUG);
886 // title, atomUri, context_id, statusnetConversationId
889 // context, location, signature;
891 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
893 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
894 if (empty($object_data)) {
895 logger('No object data found', LOGGER_DEBUG);
899 switch ($activity['type']) {
902 self::createItem($object_data, $body);
906 self::likeItem($object_data, $body);
910 self::dislikeItem($object_data, $body);
920 self::followUser($object_data);
924 if ($object_data['object_type'] == 'Follow') {
925 self::acceptFollowUser($object_data);
930 if ($object_data['object_type'] == 'Follow') {
931 self::undoFollowUser($object_data);
936 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
941 private static function getReceivers($activity, $actor)
945 // When it is an answer, we inherite the receivers from the parent
946 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
947 if (!empty($replyto)) {
948 $parents = Item::select(['uid'], ['uri' => $replyto]);
949 while ($parent = Item::fetch($parents)) {
950 $receivers['uid:' . $parent['uid']] = $parent['uid'];
954 if (!empty($actor)) {
955 $profile = self::fetchprofile($actor);
956 $followers = defaults($profile, 'followers', '');
958 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
960 logger('Empty actor', LOGGER_DEBUG);
964 $elements = ['to', 'cc', 'bto', 'bcc'];
965 foreach ($elements as $element) {
966 if (empty($activity[$element])) {
970 // The receiver can be an arror or a string
971 if (is_string($activity[$element])) {
972 $activity[$element] = [$activity[$element]];
975 foreach ($activity[$element] as $receiver) {
976 if ($receiver == self::PUBLIC) {
977 $receivers['uid:0'] = 0;
980 if (($receiver == self::PUBLIC) && !empty($actor)) {
981 // This will most likely catch all OStatus connections to Mastodon
982 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
983 $contacts = DBA::select('contact', ['uid'], $condition);
984 while ($contact = DBA::fetch($contacts)) {
985 if ($contact['uid'] != 0) {
986 $receivers['uid:' . $contact['uid']] = $contact['uid'];
989 DBA::close($contacts);
992 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
993 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
994 'network' => Protocol::ACTIVITYPUB];
995 $contacts = DBA::select('contact', ['uid'], $condition);
996 while ($contact = DBA::fetch($contacts)) {
997 if ($contact['uid'] != 0) {
998 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1001 DBA::close($contacts);
1005 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1006 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1007 if (!DBA::isResult($contact)) {
1010 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1016 private static function addActivityFields($object_data, $activity)
1018 if (!empty($activity['published']) && empty($object_data['published'])) {
1019 $object_data['published'] = $activity['published'];
1022 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1023 $object_data['updated'] = $activity['updated'];
1026 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1027 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1030 if (!empty($activity['instrument'])) {
1031 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
1033 return $object_data;
1036 private static function fetchObject($object_url, $object = [], $trust_source = false)
1038 if (!$trust_source || is_string($object)) {
1039 $data = self::fetchContent($object_url);
1041 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
1042 $data = $object_url;
1044 logger('Fetched content for ' . $object_url, LOGGER_DEBUG);
1047 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
1051 if (is_string($data)) {
1052 $item = Item::selectFirst([], ['uri' => $data]);
1053 if (!DBA::isResult($item)) {
1054 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1057 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
1058 $data = self::CreateNote($item);
1061 if (empty($data['type'])) {
1062 logger('Empty type', LOGGER_DEBUG);
1065 $type = $data['type'];
1066 logger('Type ' . $type, LOGGER_DEBUG);
1069 if (in_array($type, ['Note', 'Article', 'Video'])) {
1070 $common = self::processCommonData($data);
1075 return array_merge($common, self::processNote($data));
1077 return array_merge($common, self::processArticle($data));
1079 return array_merge($common, self::processVideo($data));
1082 if (empty($data['object'])) {
1085 return self::fetchObject($data['object']);
1092 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1097 private static function processCommonData(&$object)
1099 if (empty($object['id'])) {
1104 $object_data['type'] = $object['type'];
1105 $object_data['uri'] = $object['id'];
1107 if (!empty($object['inReplyTo'])) {
1108 $object_data['reply-to-uri'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1110 $object_data['reply-to-uri'] = $object_data['uri'];
1113 $object_data['published'] = defaults($object, 'published', null);
1114 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1116 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1117 $object_data['published'] = $object_data['updated'];
1120 $object_data['uuid'] = defaults($object, 'uuid', null);
1121 $object_data['owner'] = $object_data['author'] = JsonLD::fetchElement($object, 'attributedTo', 'id');
1122 $object_data['context'] = defaults($object, 'context', null);
1123 $object_data['conversation'] = defaults($object, 'conversation', null);
1124 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1125 $object_data['name'] = defaults($object, 'title', null);
1126 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1127 $object_data['summary'] = defaults($object, 'summary', null);
1128 $object_data['content'] = defaults($object, 'content', null);
1129 $object_data['source'] = defaults($object, 'source', null);
1130 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1131 $object_data['attachments'] = defaults($object, 'attachment', null);
1132 $object_data['tags'] = defaults($object, 'tag', null);
1133 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1134 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1135 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1138 // @context, type, actor, signature, mediaType, duration, replies, icon
1140 // Also missing: (Defined in the standard, but currently unused)
1141 // audience, preview, endTime, startTime, generator, image
1143 return $object_data;
1146 private static function processNote($object)
1151 // emoji, atomUri, inReplyToAtomUri
1154 // contentMap, announcement_count, announcements, context_id, likes, like_count
1155 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1157 return $object_data;
1160 private static function processArticle($object)
1164 return $object_data;
1167 private static function processVideo($object)
1172 // category, licence, language, commentsEnabled
1175 // views, waitTranscoding, state, support, subtitleLanguage
1176 // likes, dislikes, shares, comments
1178 return $object_data;
1181 private static function convertMentions($body)
1183 $URLSearchString = "^\[\]";
1184 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1189 private static function constructTagList($tags, $sensitive)
1196 foreach ($tags as $tag) {
1197 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1198 if (!empty($tag_text)) {
1202 if (empty($tag['href'])) {
1207 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1211 /// @todo add nsfw for $sensitive
1216 private static function constructAttachList($attachments, $item)
1218 if (empty($attachments)) {
1222 foreach ($attachments as $attach) {
1223 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1224 if ($filetype == 'image') {
1225 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1227 if (!empty($item["attach"])) {
1228 $item["attach"] .= ',';
1230 $item["attach"] = '';
1232 if (!isset($attach['length'])) {
1233 $attach['length'] = "0";
1235 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1242 private static function createItem($activity, $body)
1245 $item['verb'] = ACTIVITY_POST;
1246 $item['parent-uri'] = $activity['reply-to-uri'];
1248 if ($activity['reply-to-uri'] == $activity['uri']) {
1249 $item['gravity'] = GRAVITY_PARENT;
1250 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1252 $item['gravity'] = GRAVITY_COMMENT;
1253 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1256 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1257 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1258 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1261 self::postItem($activity, $item, $body);
1264 private static function likeItem($activity, $body)
1267 $item['verb'] = ACTIVITY_LIKE;
1268 $item['parent-uri'] = $activity['object'];
1269 $item['gravity'] = GRAVITY_ACTIVITY;
1270 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1272 self::postItem($activity, $item, $body);
1275 private static function dislikeItem($activity, $body)
1278 $item['verb'] = ACTIVITY_DISLIKE;
1279 $item['parent-uri'] = $activity['object'];
1280 $item['gravity'] = GRAVITY_ACTIVITY;
1281 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1283 self::postItem($activity, $item, $body);
1286 private static function postItem($activity, $item, $body)
1288 /// @todo What to do with $activity['context']?
1290 $item['network'] = Protocol::ACTIVITYPUB;
1291 $item['private'] = !in_array(0, $activity['receiver']);
1292 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1293 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1294 $item['uri'] = $activity['uri'];
1295 $item['created'] = $activity['published'];
1296 $item['edited'] = $activity['updated'];
1297 $item['guid'] = $activity['uuid'];
1298 $item['title'] = HTML::toBBCode($activity['name']);
1299 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1300 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1301 $item['location'] = $activity['location'];
1302 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1303 $item['app'] = $activity['service'];
1304 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1306 $item = self::constructAttachList($activity['attachments'], $item);
1308 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1309 if (!empty($source)) {
1310 $item['body'] = $source;
1313 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1314 $item['source'] = $body;
1315 $item['conversation-uri'] = $activity['conversation'];
1317 foreach ($activity['receiver'] as $receiver) {
1318 $item['uid'] = $receiver;
1319 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1321 if (($receiver != 0) && empty($item['contact-id'])) {
1322 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1325 $item_id = Item::insert($item);
1326 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1330 private static function fetchMissingActivity($url, $child)
1332 $object = ActivityPub::fetchContent($url);
1333 if (empty($object)) {
1334 logger('Activity ' . $url . ' was not fetchable, aborting.');
1339 $activity['@context'] = $object['@context'];
1340 unset($object['@context']);
1341 $activity['id'] = $object['id'];
1342 $activity['to'] = defaults($object, 'to', []);
1343 $activity['cc'] = defaults($object, 'cc', []);
1344 $activity['actor'] = $child['author'];
1345 $activity['object'] = $object;
1346 $activity['published'] = $object['published'];
1347 $activity['type'] = 'Create';
1349 self::processActivity($activity);
1350 logger('Activity ' . $url . ' had been fetched and processed.');
1353 private static function getUserOfObject($object)
1355 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1356 if (!DBA::isResult($self)) {
1359 return $self['uid'];
1363 private static function followUser($activity)
1365 $uid = self::getUserOfObject($activity['object']);
1370 $owner = User::getOwnerDataById($uid);
1372 $cid = Contact::getIdForURL($activity['owner'], $uid);
1374 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1379 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1380 'author-link' => $activity['owner']];
1382 Contact::addRelationship($owner, $contact, $item);
1383 $cid = Contact::getIdForURL($activity['owner'], $uid);
1388 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1389 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1390 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1393 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1394 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1397 private static function acceptFollowUser($activity)
1399 $uid = self::getUserOfObject($activity['object']);
1404 $owner = User::getOwnerDataById($uid);
1406 $cid = Contact::getIdForURL($activity['owner'], $uid);
1408 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1412 $fields = ['pending' => false];
1414 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1415 if ($contact['rel'] == Contact::FOLLOWER) {
1416 $fields['rel'] = Contact::FRIEND;
1419 $condition = ['id' => $cid];
1420 DBA::update('contact', $fields, $condition);
1421 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1424 private static function undoFollowUser($activity)
1426 $uid = self::getUserOfObject($activity['object']);
1431 $owner = User::getOwnerDataById($uid);
1433 $cid = Contact::getIdForURL($activity['owner'], $uid);
1435 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1439 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1440 if (!DBA::isResult($contact)) {
1444 Contact::removeFollower($owner, $contact);
1445 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);