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
38 * - Queueing unsucessful deliveries
43 * @brief collects the lost of followers of the given owner
45 * @param array $owner Owner array
46 * @param integer $page Page number
48 * @return array of owners
50 public static function getFollowers($owner, $page = null)
52 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
53 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
54 $count = DBA::count('contact', $condition);
56 $data = ['@context' => ActivityPub::CONTEXT];
57 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
58 $data['type'] = 'OrderedCollection';
59 $data['totalItems'] = $count;
61 // When we hide our friends we will only show the pure number but don't allow more.
62 $profile = Profile::getByUID($owner['uid']);
63 if (!empty($profile['hide-friends'])) {
68 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
72 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
73 while ($contact = DBA::fetch($contacts)) {
74 $list[] = $contact['url'];
78 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
81 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
83 $data['orderedItems'] = $list;
90 * @brief Create list of following contacts
92 * @param array $owner Owner array
93 * @param integer $page Page numbe
95 * @return array of following contacts
97 public static function getFollowing($owner, $page = null)
99 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
100 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
101 $count = DBA::count('contact', $condition);
103 $data = ['@context' => ActivityPub::CONTEXT];
104 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
105 $data['type'] = 'OrderedCollection';
106 $data['totalItems'] = $count;
108 // When we hide our friends we will only show the pure number but don't allow more.
109 $profile = Profile::getByUID($owner['uid']);
110 if (!empty($profile['hide-friends'])) {
115 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
119 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
120 while ($contact = DBA::fetch($contacts)) {
121 $list[] = $contact['url'];
125 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
128 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
130 $data['orderedItems'] = $list;
137 * @brief Public posts for the given owner
139 * @param array $owner Owner array
140 * @param integer $page Page numbe
142 * @return array of posts
144 public static function getOutbox($owner, $page = null)
146 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
148 $condition = ['uid' => $owner['uid'], 'contact-id' => $owner['id'], 'author-id' => $public_contact,
149 'wall' => true, 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
150 'deleted' => false, 'visible' => true];
151 $count = DBA::count('item', $condition);
153 $data = ['@context' => ActivityPub::CONTEXT];
154 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
155 $data['type'] = 'OrderedCollection';
156 $data['totalItems'] = $count;
159 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
163 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
165 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
166 while ($item = Item::fetch($items)) {
167 $object = self::createObjectFromItemID($item['id']);
168 unset($object['@context']);
173 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
176 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
178 $data['orderedItems'] = $list;
185 * Return the ActivityPub profile of the given user
187 * @param integer $uid User ID
188 * @return profile array
190 public static function profile($uid)
192 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
193 'account_removed' => false, 'verified' => true];
194 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
195 $user = DBA::selectFirst('user', $fields, $condition);
196 if (!DBA::isResult($user)) {
200 $fields = ['locality', 'region', 'country-name'];
201 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
202 if (!DBA::isResult($profile)) {
206 $fields = ['name', 'url', 'location', 'about', 'avatar'];
207 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
208 if (!DBA::isResult($contact)) {
212 $data = ['@context' => ActivityPub::CONTEXT];
213 $data['id'] = $contact['url'];
214 $data['diaspora:guid'] = $user['guid'];
215 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
216 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
217 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
218 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
219 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
220 $data['preferredUsername'] = $user['nickname'];
221 $data['name'] = $contact['name'];
222 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
223 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
224 $data['summary'] = $contact['about'];
225 $data['url'] = $contact['url'];
226 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
227 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
228 'owner' => $contact['url'],
229 'publicKeyPem' => $user['pubkey']];
230 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
231 $data['icon'] = ['type' => 'Image',
232 'url' => $contact['avatar']];
234 // tags: https://kitty.town/@inmysocks/100656097926961126.json
239 * @brief Returns an array with permissions of a given item array
243 * @return array with permissions
245 private static function fetchPermissionBlockFromConversation($item)
247 if (empty($item['thr-parent'])) {
251 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
252 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
253 if (!DBA::isResult($conversation)) {
257 $activity = json_decode($conversation['source'], true);
259 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
260 $profile = APContact::getByURL($actor);
262 $item_profile = APContact::getByURL($item['author-link']);
263 $exclude[] = $item['author-link'];
265 if ($item['gravity'] == GRAVITY_PARENT) {
266 $exclude[] = $item['owner-link'];
269 $permissions['to'][] = $actor;
271 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
272 if (empty($activity[$element])) {
275 if (is_string($activity[$element])) {
276 $activity[$element] = [$activity[$element]];
279 foreach ($activity[$element] as $receiver) {
280 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
281 $receiver = $item_profile['followers'];
283 if (!in_array($receiver, $exclude)) {
284 $permissions[$element][] = $receiver;
292 * @brief Creates an array of permissions from an item thread
296 * @return permission array
298 private static function createPermissionBlockForItem($item)
300 $data = ['to' => [], 'cc' => []];
302 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
304 $actor_profile = APContact::getByURL($item['author-link']);
306 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
308 $contacts[$item['author-link']] = $item['author-link'];
310 if (!$item['private']) {
311 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
312 if (!empty($actor_profile['followers'])) {
313 $data['cc'][] = $actor_profile['followers'];
316 foreach ($terms as $term) {
317 $profile = APContact::getByURL($term['url'], false);
318 if (!empty($profile) && empty($contacts[$profile['url']])) {
319 $data['cc'][] = $profile['url'];
320 $contacts[$profile['url']] = $profile['url'];
324 $receiver_list = Item::enumeratePermissions($item);
328 foreach ($terms as $term) {
329 $cid = Contact::getIdForURL($term['url'], $item['uid']);
330 if (!empty($cid) && in_array($cid, $receiver_list)) {
331 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
332 $data['to'][] = $contact['url'];
333 $contacts[$contact['url']] = $contact['url'];
337 foreach ($receiver_list as $receiver) {
338 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
339 if (empty($contacts[$contact['url']])) {
340 $data['cc'][] = $contact['url'];
341 $contacts[$contact['url']] = $contact['url'];
346 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity'], ['parent' => $item['parent']]);
347 while ($parent = Item::fetch($parents)) {
348 // Don't include data from future posts
349 if ($parent['id'] >= $item['id']) {
353 $profile = APContact::getByURL($parent['author-link'], false);
354 if (!empty($profile) && empty($contacts[$profile['url']])) {
355 $data['cc'][] = $profile['url'];
356 $contacts[$profile['url']] = $profile['url'];
359 if ($item['gravity'] != GRAVITY_PARENT) {
363 $profile = APContact::getByURL($parent['owner-link'], false);
364 if (!empty($profile) && empty($contacts[$profile['url']])) {
365 $data['cc'][] = $profile['url'];
366 $contacts[$profile['url']] = $profile['url'];
369 DBA::close($parents);
371 if (empty($data['to'])) {
372 $data['to'] = $data['cc'];
380 * @brief Fetches a list of inboxes of followers of a given user
382 * @param integer $uid User ID
384 * @return array of follower inboxes
386 public static function fetchTargetInboxesforUser($uid)
390 $condition = ['uid' => $uid, 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
393 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
396 $contacts = DBA::select('contact', ['notify', 'batch'], $condition);
397 while ($contact = DBA::fetch($contacts)) {
398 $contact = defaults($contact, 'batch', $contact['notify']);
399 $inboxes[$contact] = $contact;
401 DBA::close($contacts);
407 * @brief Fetches an array of inboxes for the given item and user
410 * @param integer $uid User ID
412 * @return array with inboxes
414 public static function fetchTargetInboxes($item, $uid)
416 $permissions = self::createPermissionBlockForItem($item);
417 if (empty($permissions)) {
423 if ($item['gravity'] == GRAVITY_ACTIVITY) {
424 $item_profile = APContact::getByURL($item['author-link']);
426 $item_profile = APContact::getByURL($item['owner-link']);
429 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
430 if (empty($permissions[$element])) {
434 foreach ($permissions[$element] as $receiver) {
435 if ($receiver == $item_profile['followers']) {
436 $inboxes = self::fetchTargetInboxesforUser($uid);
438 $profile = APContact::getByURL($receiver);
439 if (!empty($profile)) {
440 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
441 $inboxes[$target] = $target;
451 * @brief Returns the activity type of a given item
455 * @return activity type
457 private static function getTypeOfItem($item)
459 if ($item['verb'] == ACTIVITY_POST) {
460 if ($item['created'] == $item['edited']) {
465 } elseif ($item['verb'] == ACTIVITY_LIKE) {
467 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
469 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
471 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
473 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
474 $type = 'TentativeAccept';
483 * @brief Creates an activity array for a given item id
485 * @param integer $item_id
486 * @param boolean $object_mode Is the activity item is used inside another object?
488 * @return array of activity
490 public static function createActivityFromItem($item_id, $object_mode = false)
492 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
494 if (!DBA::isResult($item)) {
498 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
499 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
500 if (DBA::isResult($conversation)) {
501 $data = json_decode($conversation['source']);
507 $type = self::getTypeOfItem($item);
510 $data = ['@context' => ActivityPub::CONTEXT];
512 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
514 } elseif ($item['deleted']) {
521 $data['id'] = $item['uri'] . '#' . $type;
522 $data['type'] = $type;
523 $data['actor'] = $item['author-link'];
525 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
527 if ($item["created"] != $item["edited"]) {
528 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
531 $data['context'] = self::fetchContextURLForItem($item);
533 $data = array_merge($data, self::createPermissionBlockForItem($item));
535 if (in_array($data['type'], ['Create', 'Update', 'Announce', 'Delete'])) {
536 $data['object'] = self::createNote($item);
537 } elseif ($data['type'] == 'Undo') {
538 $data['object'] = self::createActivityFromItem($item_id, true);
540 $data['object'] = $item['thr-parent'];
543 $owner = User::getOwnerDataById($item['uid']);
546 return LDSignature::sign($data, $owner);
553 * @brief Creates an object array for a given item id
555 * @param integer $item_id
557 * @return object array
559 public static function createObjectFromItemID($item_id)
561 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
563 if (!DBA::isResult($item)) {
567 $data = ['@context' => ActivityPub::CONTEXT];
568 $data = array_merge($data, self::createNote($item));
574 * @brief Returns a tag array for a given item array
578 * @return array of tags
580 private static function createTagList($item)
584 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
585 foreach ($terms as $term) {
586 $contact = Contact::getDetailsByURL($term['url']);
587 if (!empty($contact['addr'])) {
588 $mention = '@' . $contact['addr'];
590 $mention = '@' . $term['url'];
593 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
599 * @brief Fetches the "context" value for a givem item array from the "conversation" table
603 * @return string with context url
605 private static function fetchContextURLForItem($item)
607 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
608 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
609 $context_uri = $conversation['conversation-href'];
610 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
611 $context_uri = $conversation['conversation-uri'];
613 $context_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
619 * @brief Creates a note/article object array
623 * @return object array
625 private static function createNote($item)
627 if (!empty($item['title'])) {
633 if ($item['deleted']) {
638 $data['id'] = $item['uri'];
639 $data['type'] = $type;
641 if ($item['deleted']) {
645 $data['summary'] = null; // Ignore by now
647 if ($item['uri'] != $item['thr-parent']) {
648 $data['inReplyTo'] = $item['thr-parent'];
650 $data['inReplyTo'] = null;
653 $data['diaspora:guid'] = $item['guid'];
654 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
656 if ($item["created"] != $item["edited"]) {
657 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
660 $data['url'] = $item['plink'];
661 $data['attributedTo'] = $item['author-link'];
662 $data['actor'] = $item['author-link'];
663 $data['sensitive'] = false; // - Query NSFW
664 $data['context'] = self::fetchContextURLForItem($item);
666 if (!empty($item['title'])) {
667 $data['name'] = BBCode::convert($item['title'], false, 7);
670 $data['content'] = BBCode::convert($item['body'], false, 7);
671 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
673 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
674 $data['diaspora:comment'] = $item['signed_text'];
677 $data['attachment'] = []; // @ToDo
678 $data['tag'] = self::createTagList($item);
679 $data = array_merge($data, self::createPermissionBlockForItem($item));
685 * @brief Transmits a profile deletion to a given inbox
687 * @param integer $uid User ID
688 * @param string $inbox Target inbox
690 public static function sendProfileDeletion($uid, $inbox)
692 $owner = User::getOwnerDataById($uid);
693 $profile = APContact::getByURL($owner['url']);
695 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
696 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
698 'actor' => $owner['url'],
699 'object' => $owner['url'],
700 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
701 'to' => [ActivityPub::PUBLIC_COLLECTION],
704 $signed = LDSignature::sign($data, $owner);
706 logger('Deliver profile deletion for user ' . $uid . ' to ' . $inbox .' via ActivityPub', LOGGER_DEBUG);
707 HTTPSignature::transmit($signed, $inbox, $uid);
711 * @brief Transmits a profile change to a given inbox
713 * @param integer $uid User ID
714 * @param string $inbox Target inbox
716 public static function sendProfileUpdate($uid, $inbox)
718 $owner = User::getOwnerDataById($uid);
719 $profile = APContact::getByURL($owner['url']);
721 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
722 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
724 'actor' => $owner['url'],
725 'object' => self::profile($uid),
726 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
727 'to' => [$profile['followers']],
730 $signed = LDSignature::sign($data, $owner);
732 logger('Deliver profile update for user ' . $uid . ' to ' . $inbox .' via ActivityPub', LOGGER_DEBUG);
733 HTTPSignature::transmit($signed, $inbox, $uid);
737 * @brief Transmits a given activity to a target
739 * @param array $activity
740 * @param string $target Target profile
741 * @param integer $uid User ID
743 public static function sendActivity($activity, $target, $uid)
745 $profile = APContact::getByURL($target);
747 $owner = User::getOwnerDataById($uid);
749 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
750 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
752 'actor' => $owner['url'],
753 'object' => $profile['url'],
754 'to' => $profile['url']];
756 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
758 $signed = LDSignature::sign($data, $owner);
759 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
763 * @brief Transmit a message that the contact request had been accepted
765 * @param string $target Target profile
767 * @param integer $uid User ID
769 public static function sendContactAccept($target, $id, $uid)
771 $profile = APContact::getByURL($target);
773 $owner = User::getOwnerDataById($uid);
774 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
775 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
777 'actor' => $owner['url'],
778 'object' => ['id' => $id, 'type' => 'Follow',
779 'actor' => $profile['url'],
780 'object' => $owner['url']],
781 'to' => $profile['url']];
783 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
785 $signed = LDSignature::sign($data, $owner);
786 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
792 * @param string $target Target profile
794 * @param integer $uid User ID
796 public static function sendContactReject($target, $id, $uid)
798 $profile = APContact::getByURL($target);
800 $owner = User::getOwnerDataById($uid);
801 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
802 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
804 'actor' => $owner['url'],
805 'object' => ['id' => $id, 'type' => 'Follow',
806 'actor' => $profile['url'],
807 'object' => $owner['url']],
808 'to' => $profile['url']];
810 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
812 $signed = LDSignature::sign($data, $owner);
813 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
819 * @param string $target Target profile
820 * @param integer $uid User ID
822 public static function sendContactUndo($target, $uid)
824 $profile = APContact::getByURL($target);
826 $id = System::baseUrl() . '/activity/' . System::createGUID();
828 $owner = User::getOwnerDataById($uid);
829 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
832 'actor' => $owner['url'],
833 'object' => ['id' => $id, 'type' => 'Follow',
834 'actor' => $owner['url'],
835 'object' => $profile['url']],
836 'to' => $profile['url']];
838 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
840 $signed = LDSignature::sign($data, $owner);
841 HTTPSignature::transmit($signed, $profile['inbox'], $uid);