3 * @file src/Protocol/ActivityPub/Transmitter.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\Database\DBA;
8 use Friendica\Core\System;
9 use Friendica\BaseObject;
10 use Friendica\Util\HTTPSignature;
11 use Friendica\Core\Protocol;
12 use Friendica\Model\Conversation;
13 use Friendica\Model\Contact;
14 use Friendica\Model\APContact;
15 use Friendica\Model\Item;
16 use Friendica\Model\Term;
17 use Friendica\Model\User;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Content\Text\BBCode;
20 use Friendica\Util\JsonLD;
21 use Friendica\Util\LDSignature;
22 use Friendica\Protocol\ActivityPub;
23 use Friendica\Model\Profile;
26 * @brief ActivityPub Transmitter Protocol class
31 * @brief collects the lost of followers of the given owner
33 * @param array $owner Owner array
34 * @param integer $page Page number
36 * @return array of owners
38 public static function getFollowers($owner, $page = null)
40 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
41 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
42 $count = DBA::count('contact', $condition);
44 $data = ['@context' => ActivityPub::CONTEXT];
45 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
46 $data['type'] = 'OrderedCollection';
47 $data['totalItems'] = $count;
49 // When we hide our friends we will only show the pure number but don't allow more.
50 $profile = Profile::getByUID($owner['uid']);
51 if (!empty($profile['hide-friends'])) {
56 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
60 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
61 while ($contact = DBA::fetch($contacts)) {
62 $list[] = $contact['url'];
66 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
69 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
71 $data['orderedItems'] = $list;
78 * @brief Create list of following contacts
80 * @param array $owner Owner array
81 * @param integer $page Page numbe
83 * @return array of following contacts
85 public static function getFollowing($owner, $page = null)
87 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
88 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
89 $count = DBA::count('contact', $condition);
91 $data = ['@context' => ActivityPub::CONTEXT];
92 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
93 $data['type'] = 'OrderedCollection';
94 $data['totalItems'] = $count;
96 // When we hide our friends we will only show the pure number but don't allow more.
97 $profile = Profile::getByUID($owner['uid']);
98 if (!empty($profile['hide-friends'])) {
103 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
107 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
108 while ($contact = DBA::fetch($contacts)) {
109 $list[] = $contact['url'];
113 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
116 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
118 $data['orderedItems'] = $list;
125 * @brief Public posts for the given owner
127 * @param array $owner Owner array
128 * @param integer $page Page numbe
130 * @return array of posts
132 public static function getOutbox($owner, $page = null)
134 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
136 $condition = ['uid' => $owner['uid'], 'contact-id' => $owner['id'], 'author-id' => $public_contact,
137 'wall' => true, 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
138 'deleted' => false, 'visible' => true];
139 $count = DBA::count('item', $condition);
141 $data = ['@context' => ActivityPub::CONTEXT];
142 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
143 $data['type'] = 'OrderedCollection';
144 $data['totalItems'] = $count;
147 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
151 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
153 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
154 while ($item = Item::fetch($items)) {
155 $object = self::createObjectFromItemID($item['id']);
156 unset($object['@context']);
161 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
164 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
166 $data['orderedItems'] = $list;
173 * Return the ActivityPub profile of the given user
175 * @param integer $uid User ID
176 * @return profile array
178 public static function profile($uid)
180 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
181 'account_removed' => false, 'verified' => true];
182 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
183 $user = DBA::selectFirst('user', $fields, $condition);
184 if (!DBA::isResult($user)) {
188 $fields = ['locality', 'region', 'country-name'];
189 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
190 if (!DBA::isResult($profile)) {
194 $fields = ['name', 'url', 'location', 'about', 'avatar'];
195 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
196 if (!DBA::isResult($contact)) {
200 $data = ['@context' => ActivityPub::CONTEXT];
201 $data['id'] = $contact['url'];
202 $data['diaspora:guid'] = $user['guid'];
203 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
204 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
205 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
206 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
207 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
208 $data['preferredUsername'] = $user['nickname'];
209 $data['name'] = $contact['name'];
210 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
211 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
212 $data['summary'] = $contact['about'];
213 $data['url'] = $contact['url'];
214 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
215 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
216 'owner' => $contact['url'],
217 'publicKeyPem' => $user['pubkey']];
218 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
219 $data['icon'] = ['type' => 'Image',
220 'url' => $contact['avatar']];
222 // tags: https://kitty.town/@inmysocks/100656097926961126.json
227 * @brief Returns an array with permissions of a given item array
231 * @return array with permissions
233 private static function fetchPermissionBlockFromConversation($item)
235 if (empty($item['thr-parent'])) {
239 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
240 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
241 if (!DBA::isResult($conversation)) {
245 $activity = json_decode($conversation['source'], true);
247 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
248 $profile = APContact::getByURL($actor);
250 $item_profile = APContact::getByURL($item['author-link']);
251 $exclude[] = $item['author-link'];
253 if ($item['gravity'] == GRAVITY_PARENT) {
254 $exclude[] = $item['owner-link'];
257 $permissions['to'][] = $actor;
259 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
260 if (empty($activity[$element])) {
263 if (is_string($activity[$element])) {
264 $activity[$element] = [$activity[$element]];
267 foreach ($activity[$element] as $receiver) {
268 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
269 $receiver = $item_profile['followers'];
271 if (!in_array($receiver, $exclude)) {
272 $permissions[$element][] = $receiver;
280 * @brief Creates an array of permissions from an item thread
284 * @return permission array
286 private static function createPermissionBlockForItem($item)
288 $data = ['to' => [], 'cc' => []];
290 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
292 $actor_profile = APContact::getByURL($item['author-link']);
294 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
296 $contacts[$item['author-link']] = $item['author-link'];
298 if (!$item['private']) {
299 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
300 if (!empty($actor_profile['followers'])) {
301 $data['cc'][] = $actor_profile['followers'];
304 foreach ($terms as $term) {
305 $profile = APContact::getByURL($term['url'], false);
306 if (!empty($profile) && empty($contacts[$profile['url']])) {
307 $data['cc'][] = $profile['url'];
308 $contacts[$profile['url']] = $profile['url'];
312 $receiver_list = Item::enumeratePermissions($item);
316 foreach ($terms as $term) {
317 $cid = Contact::getIdForURL($term['url'], $item['uid']);
318 if (!empty($cid) && in_array($cid, $receiver_list)) {
319 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
320 $data['to'][] = $contact['url'];
321 $contacts[$contact['url']] = $contact['url'];
325 foreach ($receiver_list as $receiver) {
326 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
327 if (empty($contacts[$contact['url']])) {
328 $data['cc'][] = $contact['url'];
329 $contacts[$contact['url']] = $contact['url'];
334 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity'], ['parent' => $item['parent']]);
335 while ($parent = Item::fetch($parents)) {
336 // Don't include data from future posts
337 if ($parent['id'] >= $item['id']) {
341 $profile = APContact::getByURL($parent['author-link'], false);
342 if (!empty($profile) && empty($contacts[$profile['url']])) {
343 $data['cc'][] = $profile['url'];
344 $contacts[$profile['url']] = $profile['url'];
347 if ($item['gravity'] != GRAVITY_PARENT) {
351 $profile = APContact::getByURL($parent['owner-link'], false);
352 if (!empty($profile) && empty($contacts[$profile['url']])) {
353 $data['cc'][] = $profile['url'];
354 $contacts[$profile['url']] = $profile['url'];
357 DBA::close($parents);
359 if (empty($data['to'])) {
360 $data['to'] = $data['cc'];
368 * @brief Fetches a list of inboxes of followers of a given user
370 * @param integer $uid User ID
372 * @return array of follower inboxes
374 public static function fetchTargetInboxesforUser($uid)
378 $condition = ['uid' => $uid, 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
381 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
384 $contacts = DBA::select('contact', ['notify', 'batch'], $condition);
385 while ($contact = DBA::fetch($contacts)) {
386 $contact = defaults($contact, 'batch', $contact['notify']);
387 $inboxes[$contact] = $contact;
389 DBA::close($contacts);
395 * @brief Fetches an array of inboxes for the given item and user
398 * @param integer $uid User ID
400 * @return array with inboxes
402 public static function fetchTargetInboxes($item, $uid)
404 $permissions = self::createPermissionBlockForItem($item);
405 if (empty($permissions)) {
411 if ($item['gravity'] == GRAVITY_ACTIVITY) {
412 $item_profile = APContact::getByURL($item['author-link']);
414 $item_profile = APContact::getByURL($item['owner-link']);
417 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
418 if (empty($permissions[$element])) {
422 foreach ($permissions[$element] as $receiver) {
423 if ($receiver == $item_profile['followers']) {
424 $inboxes = self::fetchTargetInboxesforUser($uid);
426 $profile = APContact::getByURL($receiver);
427 if (!empty($profile)) {
428 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
429 $inboxes[$target] = $target;
439 * @brief Returns the activity type of a given item
443 * @return activity type
445 private static function getTypeOfItem($item)
447 if ($item['verb'] == ACTIVITY_POST) {
448 if ($item['created'] == $item['edited']) {
453 } elseif ($item['verb'] == ACTIVITY_LIKE) {
455 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
457 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
459 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
461 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
462 $type = 'TentativeAccept';
471 * @brief Creates an activity array for a given item id
473 * @param integer $item_id
474 * @param boolean $object_mode Is the activity item is used inside another object?
476 * @return array of activity
478 public static function createActivityFromItem($item_id, $object_mode = false)
480 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
482 if (!DBA::isResult($item)) {
486 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
487 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
488 if (DBA::isResult($conversation)) {
489 $data = json_decode($conversation['source']);
495 $type = self::getTypeOfItem($item);
498 $data = ['@context' => ActivityPub::CONTEXT];
500 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
502 } elseif ($item['deleted']) {
509 $data['id'] = $item['uri'] . '#' . $type;
510 $data['type'] = $type;
511 $data['actor'] = $item['author-link'];
513 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
515 if ($item["created"] != $item["edited"]) {
516 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
519 $data['context'] = self::fetchContextURLForItem($item);
521 $data = array_merge($data, self::createPermissionBlockForItem($item));
523 if (in_array($data['type'], ['Create', 'Update', 'Announce', 'Delete'])) {
524 $data['object'] = self::createNote($item);
525 } elseif ($data['type'] == 'Undo') {
526 $data['object'] = self::createActivityFromItem($item_id, true);
528 $data['object'] = $item['thr-parent'];
531 $owner = User::getOwnerDataById($item['uid']);
534 return LDSignature::sign($data, $owner);
541 * @brief Creates an object array for a given item id
543 * @param integer $item_id
545 * @return object array
547 public static function createObjectFromItemID($item_id)
549 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
551 if (!DBA::isResult($item)) {
555 $data = ['@context' => ActivityPub::CONTEXT];
556 $data = array_merge($data, self::createNote($item));
562 * @brief Returns a tag array for a given item array
566 * @return array of tags
568 private static function createTagList($item)
572 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
573 foreach ($terms as $term) {
574 $contact = Contact::getDetailsByURL($term['url']);
575 if (!empty($contact['addr'])) {
576 $mention = '@' . $contact['addr'];
578 $mention = '@' . $term['url'];
581 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
587 * @brief Fetches the "context" value for a givem item array from the "conversation" table
591 * @return string with context url
593 private static function fetchContextURLForItem($item)
595 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
596 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
597 $context_uri = $conversation['conversation-href'];
598 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
599 $context_uri = $conversation['conversation-uri'];
601 $context_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
607 * @brief Creates a note/article object array
611 * @return object array
613 private static function createNote($item)
615 if (!empty($item['title'])) {
621 if ($item['deleted']) {
626 $data['id'] = $item['uri'];
627 $data['type'] = $type;
629 if ($item['deleted']) {
633 $data['summary'] = null; // Ignore by now
635 if ($item['uri'] != $item['thr-parent']) {
636 $data['inReplyTo'] = $item['thr-parent'];
638 $data['inReplyTo'] = null;
641 $data['diaspora:guid'] = $item['guid'];
642 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
644 if ($item["created"] != $item["edited"]) {
645 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
648 $data['url'] = $item['plink'];
649 $data['attributedTo'] = $item['author-link'];
650 $data['actor'] = $item['author-link'];
651 $data['sensitive'] = false; // - Query NSFW
652 $data['context'] = self::fetchContextURLForItem($item);
654 if (!empty($item['title'])) {
655 $data['name'] = BBCode::convert($item['title'], false, 7);
658 $data['content'] = BBCode::convert($item['body'], false, 7);
659 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
661 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
662 $data['diaspora:comment'] = $item['signed_text'];
665 $data['attachment'] = []; // @ToDo
666 $data['tag'] = self::createTagList($item);
667 $data = array_merge($data, self::createPermissionBlockForItem($item));
673 * @brief Transmits a profile deletion to a given inbox
675 * @param integer $uid User ID
676 * @param string $inbox Target inbox
678 public static function transmitProfileDeletion($uid, $inbox)
680 $owner = User::getOwnerDataById($uid);
681 $profile = APContact::getByURL($owner['url']);
683 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
684 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
686 'actor' => $owner['url'],
687 'object' => $owner['url'],
688 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
689 'to' => [ActivityPub::PUBLIC_COLLECTION],
692 $signed = LDSignature::sign($data, $owner);
694 logger('Deliver profile deletion for user ' . $uid . ' to ' . $inbox .' via ActivityPub', LOGGER_DEBUG);
695 HTTPSignature::transmit($signed, $inbox, $uid);
699 * @brief Transmits a profile change to a given inbox
701 * @param integer $uid User ID
702 * @param string $inbox Target inbox
704 public static function transmitProfileUpdate($uid, $inbox)
706 $owner = User::getOwnerDataById($uid);
707 $profile = APContact::getByURL($owner['url']);
709 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
710 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
712 'actor' => $owner['url'],
713 'object' => self::profile($uid),
714 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
715 'to' => [$profile['followers']],
718 $signed = LDSignature::sign($data, $owner);
720 logger('Deliver profile update for user ' . $uid . ' to ' . $inbox .' via ActivityPub', LOGGER_DEBUG);
721 HTTPSignature::transmit($signed, $inbox, $uid);
725 * @brief Transmits a given activity to a target
727 * @param array $activity
728 * @param string $target Target profile
729 * @param integer $uid User ID
731 public static function transmitActivity($activity, $target, $uid)
733 $profile = APContact::getByURL($target);
735 $owner = User::getOwnerDataById($uid);
737 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
738 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
740 'actor' => $owner['url'],
741 'object' => $profile['url'],
742 'to' => $profile['url']];
744 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
746 $signed = LDSignature::sign($data, $owner);
747 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
751 * @brief Transmit a message that the contact request had been accepted
753 * @param string $target Target profile
755 * @param integer $uid User ID
757 public static function transmitContactAccept($target, $id, $uid)
759 $profile = APContact::getByURL($target);
761 $owner = User::getOwnerDataById($uid);
762 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
763 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
765 'actor' => $owner['url'],
766 'object' => ['id' => $id, 'type' => 'Follow',
767 'actor' => $profile['url'],
768 'object' => $owner['url']],
769 'to' => $profile['url']];
771 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
773 $signed = LDSignature::sign($data, $owner);
774 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
780 * @param string $target Target profile
782 * @param integer $uid User ID
784 public static function transmitContactReject($target, $id, $uid)
786 $profile = APContact::getByURL($target);
788 $owner = User::getOwnerDataById($uid);
789 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
790 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
792 'actor' => $owner['url'],
793 'object' => ['id' => $id, 'type' => 'Follow',
794 'actor' => $profile['url'],
795 'object' => $owner['url']],
796 'to' => $profile['url']];
798 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
800 $signed = LDSignature::sign($data, $owner);
801 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
807 * @param string $target Target profile
808 * @param integer $uid User ID
810 public static function transmitContactUndo($target, $uid)
812 $profile = APContact::getByURL($target);
814 $id = System::baseUrl() . '/activity/' . System::createGUID();
816 $owner = User::getOwnerDataById($uid);
817 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
820 'actor' => $owner['url'],
821 'object' => ['id' => $id, 'type' => 'Follow',
822 'actor' => $owner['url'],
823 'object' => $profile['url']],
824 'to' => $profile['url']];
826 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
828 $signed = LDSignature::sign($data, $owner);
829 HTTPSignature::transmit($signed, $profile['inbox'], $uid);