3 * @file src/Protocol/ActivityPub/Transmitter.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
9 use Friendica\Core\System;
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\Model\Profile;
23 use Friendica\Core\Config;
24 use Friendica\Object\Image;
25 use Friendica\Protocol\ActivityPub;
26 use Friendica\Protocol\Diaspora;
27 use Friendica\Core\Cache;
28 use Friendica\Util\Map;
30 require_once 'include/api.php';
33 * @brief ActivityPub Transmitter Protocol class
37 * Missing object types:
40 * Complicated object types:
44 * - Queueing unsucessful deliveries
49 * collects the lost of followers of the given owner
51 * @param array $owner Owner array
52 * @param integer $page Page number
54 * @return array of owners
56 public static function getFollowers($owner, $page = null)
58 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
59 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
60 $count = DBA::count('contact', $condition);
62 $data = ['@context' => ActivityPub::CONTEXT];
63 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
64 $data['type'] = 'OrderedCollection';
65 $data['totalItems'] = $count;
67 // When we hide our friends we will only show the pure number but don't allow more.
68 $profile = Profile::getByUID($owner['uid']);
69 if (!empty($profile['hide-friends'])) {
74 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
78 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
79 while ($contact = DBA::fetch($contacts)) {
80 $list[] = $contact['url'];
84 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
87 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
89 $data['orderedItems'] = $list;
96 * Create list of following contacts
98 * @param array $owner Owner array
99 * @param integer $page Page numbe
101 * @return array of following contacts
103 public static function getFollowing($owner, $page = null)
105 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
106 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
107 $count = DBA::count('contact', $condition);
109 $data = ['@context' => ActivityPub::CONTEXT];
110 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
111 $data['type'] = 'OrderedCollection';
112 $data['totalItems'] = $count;
114 // When we hide our friends we will only show the pure number but don't allow more.
115 $profile = Profile::getByUID($owner['uid']);
116 if (!empty($profile['hide-friends'])) {
121 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
125 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
126 while ($contact = DBA::fetch($contacts)) {
127 $list[] = $contact['url'];
131 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
134 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
136 $data['orderedItems'] = $list;
143 * Public posts for the given owner
145 * @param array $owner Owner array
146 * @param integer $page Page numbe
148 * @return array of posts
150 public static function getOutbox($owner, $page = null)
152 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
154 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
155 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
156 'deleted' => false, 'visible' => true];
157 $count = DBA::count('item', $condition);
159 $data = ['@context' => ActivityPub::CONTEXT];
160 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
161 $data['type'] = 'OrderedCollection';
162 $data['totalItems'] = $count;
165 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
169 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
171 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
172 while ($item = Item::fetch($items)) {
173 $object = self::createObjectFromItemID($item['id']);
174 unset($object['@context']);
179 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
182 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
184 $data['orderedItems'] = $list;
191 * Return the ActivityPub profile of the given user
193 * @param integer $uid User ID
194 * @return array with profile data
196 public static function getProfile($uid)
198 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
199 'account_removed' => false, 'verified' => true];
200 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
201 $user = DBA::selectFirst('user', $fields, $condition);
202 if (!DBA::isResult($user)) {
206 $fields = ['locality', 'region', 'country-name'];
207 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
208 if (!DBA::isResult($profile)) {
212 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
213 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
214 if (!DBA::isResult($contact)) {
218 // On old installations and never changed contacts this might not be filled
219 if (empty($contact['avatar'])) {
220 $contact['avatar'] = $contact['photo'];
223 $data = ['@context' => ActivityPub::CONTEXT];
224 $data['id'] = $contact['url'];
225 $data['diaspora:guid'] = $user['guid'];
226 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
227 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
228 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
229 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
230 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
231 $data['preferredUsername'] = $user['nickname'];
232 $data['name'] = $contact['name'];
233 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
234 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
235 $data['summary'] = $contact['about'];
236 $data['url'] = $contact['url'];
237 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
238 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
239 'owner' => $contact['url'],
240 'publicKeyPem' => $user['pubkey']];
241 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
242 $data['icon'] = ['type' => 'Image',
243 'url' => $contact['avatar']];
245 // tags: https://kitty.town/@inmysocks/100656097926961126.json
250 * Returns an array with permissions of a given item array
254 * @return array with permissions
256 private static function fetchPermissionBlockFromConversation($item)
258 if (empty($item['thr-parent'])) {
262 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
263 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
264 if (!DBA::isResult($conversation)) {
268 $activity = json_decode($conversation['source'], true);
270 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
271 $profile = APContact::getByURL($actor);
273 $item_profile = APContact::getByURL($item['author-link']);
274 $exclude[] = $item['author-link'];
276 if ($item['gravity'] == GRAVITY_PARENT) {
277 $exclude[] = $item['owner-link'];
280 $permissions['to'][] = $actor;
282 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
283 if (empty($activity[$element])) {
286 if (is_string($activity[$element])) {
287 $activity[$element] = [$activity[$element]];
290 foreach ($activity[$element] as $receiver) {
291 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
292 $receiver = $item_profile['followers'];
294 if (!in_array($receiver, $exclude)) {
295 $permissions[$element][] = $receiver;
303 * Creates an array of permissions from an item thread
307 * @return array with permission data
309 private static function createPermissionBlockForItem($item)
311 $data = ['to' => [], 'cc' => []];
313 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
315 $actor_profile = APContact::getByURL($item['author-link']);
317 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
319 $contacts[$item['author-link']] = $item['author-link'];
321 if (!$item['private']) {
322 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
323 if (!empty($actor_profile['followers'])) {
324 $data['cc'][] = $actor_profile['followers'];
327 foreach ($terms as $term) {
328 $profile = APContact::getByURL($term['url'], false);
329 if (!empty($profile) && empty($contacts[$profile['url']])) {
330 $data['to'][] = $profile['url'];
331 $contacts[$profile['url']] = $profile['url'];
333 if (($key = array_search($profile['url'], $data['cc'])) !== false) {
334 unset($data['cc'][$key]);
339 $receiver_list = Item::enumeratePermissions($item);
343 foreach ($terms as $term) {
344 $cid = Contact::getIdForURL($term['url'], $item['uid']);
345 if (!empty($cid) && in_array($cid, $receiver_list)) {
346 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
347 $data['to'][] = $contact['url'];
348 $contacts[$contact['url']] = $contact['url'];
350 if (($key = array_search($profile['url'], $data['cc'])) !== false) {
351 unset($data['cc'][$key]);
356 foreach ($receiver_list as $receiver) {
357 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
358 if (DBA::isResult($contact) && empty($contacts[$contact['url']])) {
359 $data['cc'][] = $contact['url'];
360 $contacts[$contact['url']] = $contact['url'];
365 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
366 while ($parent = Item::fetch($parents)) {
367 // Don't include data from future posts
368 if ($parent['id'] >= $item['id']) {
372 $profile = APContact::getByURL($parent['author-link'], false);
373 if (!empty($profile) && ($parent['uri'] == $item['thr-parent'])) {
374 $data['to'][] = $profile['url'];
375 $contacts[$profile['url']] = $profile['url'];
377 if (($key = array_search($profile['url'], $data['cc'])) !== false) {
378 unset($data['cc'][$key]);
382 if (!empty($profile) && empty($contacts[$profile['url']])) {
383 $data['cc'][] = $profile['url'];
384 $contacts[$profile['url']] = $profile['url'];
387 if ($item['gravity'] != GRAVITY_PARENT) {
391 $profile = APContact::getByURL($parent['owner-link'], false);
392 if (!empty($profile) && empty($contacts[$profile['url']])) {
393 $data['cc'][] = $profile['url'];
394 $contacts[$profile['url']] = $profile['url'];
397 DBA::close($parents);
399 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
400 unset($data['to'][$key]);
403 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
404 unset($data['cc'][$key]);
407 return ['to' => array_values(array_unique($data['to'])), 'cc' => array_values(array_unique($data['cc']))];
411 * Fetches a list of inboxes of followers of a given user
413 * @param integer $uid User ID
415 * @return array of follower inboxes
417 public static function fetchTargetInboxesforUser($uid)
421 $condition = ['uid' => $uid, 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
424 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
427 $contacts = DBA::select('contact', ['notify', 'batch'], $condition);
428 while ($contact = DBA::fetch($contacts)) {
429 $contact = defaults($contact, 'batch', $contact['notify']);
430 $inboxes[$contact] = $contact;
432 DBA::close($contacts);
438 * Fetches an array of inboxes for the given item and user
441 * @param integer $uid User ID
443 * @return array with inboxes
445 public static function fetchTargetInboxes($item, $uid)
447 $permissions = self::createPermissionBlockForItem($item);
448 if (empty($permissions)) {
454 if ($item['gravity'] == GRAVITY_ACTIVITY) {
455 $item_profile = APContact::getByURL($item['author-link']);
457 $item_profile = APContact::getByURL($item['owner-link']);
460 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
461 if (empty($permissions[$element])) {
465 foreach ($permissions[$element] as $receiver) {
466 if ($receiver == $item_profile['followers']) {
467 $inboxes = self::fetchTargetInboxesforUser($uid);
469 $profile = APContact::getByURL($receiver);
470 if (!empty($profile)) {
471 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
472 $inboxes[$target] = $target;
482 * Returns the activity type of a given item
486 * @return string with activity type
488 private static function getTypeOfItem($item)
490 if (!empty(Diaspora::isReshare($item['body'], false))) {
492 } elseif ($item['verb'] == ACTIVITY_POST) {
493 if ($item['created'] == $item['edited']) {
498 } elseif ($item['verb'] == ACTIVITY_LIKE) {
500 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
502 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
504 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
506 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
507 $type = 'TentativeAccept';
516 * Creates the activity or fetches it from the cache
518 * @param integer $item_id
520 * @return array with the activity
522 public static function createCachedActivityFromItem($item_id)
524 $cachekey = 'APDelivery:createActivity:' . $item_id;
525 $data = Cache::get($cachekey);
526 if (!is_null($data)) {
530 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
532 Cache::set($cachekey, $data, CACHE_QUARTER_HOUR);
537 * Creates an activity array for a given item id
539 * @param integer $item_id
540 * @param boolean $object_mode Is the activity item is used inside another object?
542 * @return array of activity
544 public static function createActivityFromItem($item_id, $object_mode = false)
546 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
548 if (!DBA::isResult($item)) {
552 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
553 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
554 if (DBA::isResult($conversation)) {
555 $data = json_decode($conversation['source']);
561 $type = self::getTypeOfItem($item);
564 $data = ['@context' => ActivityPub::CONTEXT];
566 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
568 } elseif ($item['deleted']) {
575 $data['id'] = $item['uri'] . '#' . $type;
576 $data['type'] = $type;
577 $data['actor'] = $item['owner-link'];
579 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
581 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
583 $data = array_merge($data, self::createPermissionBlockForItem($item));
585 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
586 $data['object'] = self::createNote($item);
587 } elseif ($data['type'] == 'Announce') {
588 $data['object'] = self::createAnnounce($item);
589 } elseif ($data['type'] == 'Undo') {
590 $data['object'] = self::createActivityFromItem($item_id, true);
592 $data['diaspora:guid'] = $item['guid'];
593 $data['object'] = $item['thr-parent'];
596 $owner = User::getOwnerDataById($item['uid']);
599 return LDSignature::sign($data, $owner);
604 /// @todo Create "conversation" entry
608 * Creates an object array for a given item id
610 * @param integer $item_id
612 * @return array with the object data
614 public static function createObjectFromItemID($item_id)
616 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
618 if (!DBA::isResult($item)) {
622 $data = ['@context' => ActivityPub::CONTEXT];
623 $data = array_merge($data, self::createNote($item));
629 * Creates a location entry for a given item array
633 * @return array with location array
635 private static function createLocation($item)
637 $location = ['type' => 'Place'];
639 if (!empty($item['location'])) {
640 $location['name'] = $item['location'];
645 if (empty($item['coord'])) {
646 $coord = Map::getCoordinates($item['location']);
648 $coords = explode(' ', $item['coord']);
649 if (count($coords) == 2) {
650 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
654 if (!empty($coord['lat']) && !empty($coord['lon'])) {
655 $location['latitude'] = $coord['lat'];
656 $location['longitude'] = $coord['lon'];
663 * Returns a tag array for a given item array
667 * @return array of tags
669 private static function createTagList($item)
673 $terms = Term::tagArrayFromItemId($item['id']);
674 foreach ($terms as $term) {
675 if ($term['type'] == TERM_HASHTAG) {
676 $tags[] = ['type' => 'Hashtag', 'href' => $term['url'], 'name' => '#' . $term['term']];
677 } elseif ($term['type'] == TERM_MENTION) {
678 $contact = Contact::getDetailsByURL($term['url']);
679 if (!empty($contact['addr'])) {
680 $mention = '@' . $contact['addr'];
682 $mention = '@' . $term['url'];
685 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
692 * Adds attachment data to the JSON document
694 * @param array $item Data of the item that is to be posted
695 * @param text $type Object type
697 * @return array with attachment data
699 private static function createAttachmentList($item, $type)
703 $arr = explode('[/attach],', $item['attach']);
705 foreach ($arr as $r) {
707 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
709 $attributes = ['type' => 'Document',
710 'mediaType' => $matches[3],
711 'url' => $matches[1],
714 if (trim($matches[4]) != '') {
715 $attributes['name'] = trim($matches[4]);
718 $attachments[] = $attributes;
723 if ($type != 'Note') {
727 // Simplify image codes
728 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
730 // Grab all pictures and create attachments out of them
731 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
732 foreach ($pictures[1] as $picture) {
733 $imgdata = Image::getInfoFromURL($picture);
735 $attachments[] = ['type' => 'Document',
736 'mediaType' => $imgdata['mime'],
747 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
749 * @param array $match Matching values for the callback
750 * @return string Replaced mention
752 private static function mentionCallback($match)
754 if (empty($match[1])) {
758 $data = Contact::getDetailsByURL($match[1]);
759 if (empty($data) || empty($data['nick'])) {
763 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
767 * Remove image elements and replaces them with links to the image
769 * @param string $body
771 * @return string with replaced elements
773 private static function removePictures($body)
775 // Simplify image codes
776 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
778 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
779 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
785 * Fetches the "context" value for a givem item array from the "conversation" table
789 * @return string with context url
791 private static function fetchContextURLForItem($item)
793 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
794 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
795 $context_uri = $conversation['conversation-href'];
796 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
797 $context_uri = $conversation['conversation-uri'];
799 $context_uri = $item['parent-uri'] . '#context';
805 * Returns if the post contains sensitive content ("nsfw")
807 * @param integer $item_id
811 private static function isSensitive($item_id)
813 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
814 return DBA::exists('term', $condition);
818 * Creates a note/article object array
822 * @return array with the object data
824 public static function createNote($item)
826 if (!empty($item['title'])) {
832 if ($item['deleted']) {
837 $data['id'] = $item['uri'];
838 $data['type'] = $type;
840 if ($item['deleted']) {
844 $data['summary'] = null; // Ignore by now
846 if ($item['uri'] != $item['thr-parent']) {
847 $data['inReplyTo'] = $item['thr-parent'];
849 $data['inReplyTo'] = null;
852 $data['diaspora:guid'] = $item['guid'];
853 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
855 if ($item['created'] != $item['edited']) {
856 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
859 $data['url'] = $item['plink'];
860 $data['attributedTo'] = $item['author-link'];
861 $data['sensitive'] = self::isSensitive($item['id']);
862 $data['context'] = self::fetchContextURLForItem($item);
864 if (!empty($item['title'])) {
865 $data['name'] = BBCode::toPlaintext($item['title'], false);
868 $body = $item['body'];
870 if ($type == 'Note') {
871 $body = self::removePictures($body);
874 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
875 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
877 $data['content'] = BBCode::convert($body, false, 7);
878 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
880 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
881 $data['diaspora:comment'] = $item['signed_text'];
884 $data['attachment'] = self::createAttachmentList($item, $type);
885 $data['tag'] = self::createTagList($item);
887 if (!empty($item['coord']) || !empty($item['location'])) {
888 $data['location'] = self::createLocation($item);
891 if (!empty($item['app'])) {
892 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
895 $data = array_merge($data, self::createPermissionBlockForItem($item));
901 * Creates an announce object entry
905 * @return string with announced object url
907 public static function createAnnounce($item)
909 $announce = api_share_as_retweet($item);
910 if (empty($announce['plink'])) {
911 return self::createNote($item);
914 return $announce['plink'];
918 * Transmits a contact suggestion to a given inbox
920 * @param integer $uid User ID
921 * @param string $inbox Target inbox
922 * @param integer $suggestion_id Suggestion ID
924 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
926 $owner = User::getOwnerDataById($uid);
927 $profile = APContact::getByURL($owner['url']);
929 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
931 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
932 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
933 'type' => 'Announce',
934 'actor' => $owner['url'],
935 'object' => $suggestion['url'],
936 'content' => $suggestion['note'],
937 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
938 'to' => [ActivityPub::PUBLIC_COLLECTION],
941 $signed = LDSignature::sign($data, $owner);
943 logger('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', LOGGER_DEBUG);
944 HTTPSignature::transmit($signed, $inbox, $uid);
948 * Transmits a profile deletion to a given inbox
950 * @param integer $uid User ID
951 * @param string $inbox Target inbox
953 public static function sendProfileDeletion($uid, $inbox)
955 $owner = User::getOwnerDataById($uid);
956 $profile = APContact::getByURL($owner['url']);
958 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
959 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
961 'actor' => $owner['url'],
962 'object' => $owner['url'],
963 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
964 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
965 'to' => [ActivityPub::PUBLIC_COLLECTION],
968 $signed = LDSignature::sign($data, $owner);
970 logger('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', LOGGER_DEBUG);
971 HTTPSignature::transmit($signed, $inbox, $uid);
975 * Transmits a profile change to a given inbox
977 * @param integer $uid User ID
978 * @param string $inbox Target inbox
980 public static function sendProfileUpdate($uid, $inbox)
982 $owner = User::getOwnerDataById($uid);
983 $profile = APContact::getByURL($owner['url']);
985 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
986 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
988 'actor' => $owner['url'],
989 'object' => self::getProfile($uid),
990 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
991 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
992 'to' => [$profile['followers']],
995 $signed = LDSignature::sign($data, $owner);
997 logger('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', LOGGER_DEBUG);
998 HTTPSignature::transmit($signed, $inbox, $uid);
1002 * Transmits a given activity to a target
1004 * @param array $activity
1005 * @param string $target Target profile
1006 * @param integer $uid User ID
1008 public static function sendActivity($activity, $target, $uid)
1010 $profile = APContact::getByURL($target);
1012 $owner = User::getOwnerDataById($uid);
1014 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
1015 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1016 'type' => $activity,
1017 'actor' => $owner['url'],
1018 'object' => $profile['url'],
1019 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1020 'to' => $profile['url']];
1022 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
1024 $signed = LDSignature::sign($data, $owner);
1025 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1029 * Transmit a message that the contact request had been accepted
1031 * @param string $target Target profile
1033 * @param integer $uid User ID
1035 public static function sendContactAccept($target, $id, $uid)
1037 $profile = APContact::getByURL($target);
1039 $owner = User::getOwnerDataById($uid);
1040 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
1041 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1043 'actor' => $owner['url'],
1044 'object' => ['id' => $id, 'type' => 'Follow',
1045 'actor' => $profile['url'],
1046 'object' => $owner['url']],
1047 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1048 'to' => $profile['url']];
1050 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
1052 $signed = LDSignature::sign($data, $owner);
1053 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1057 * Reject a contact request or terminates the contact relation
1059 * @param string $target Target profile
1061 * @param integer $uid User ID
1063 public static function sendContactReject($target, $id, $uid)
1065 $profile = APContact::getByURL($target);
1067 $owner = User::getOwnerDataById($uid);
1068 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
1069 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1071 'actor' => $owner['url'],
1072 'object' => ['id' => $id, 'type' => 'Follow',
1073 'actor' => $profile['url'],
1074 'object' => $owner['url']],
1075 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1076 'to' => $profile['url']];
1078 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
1080 $signed = LDSignature::sign($data, $owner);
1081 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1085 * Transmits a message that we don't want to follow this contact anymore
1087 * @param string $target Target profile
1088 * @param integer $uid User ID
1090 public static function sendContactUndo($target, $uid)
1092 $profile = APContact::getByURL($target);
1094 $id = System::baseUrl() . '/activity/' . System::createGUID();
1096 $owner = User::getOwnerDataById($uid);
1097 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
1100 'actor' => $owner['url'],
1101 'object' => ['id' => $id, 'type' => 'Follow',
1102 'actor' => $owner['url'],
1103 'object' => $profile['url']],
1104 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1105 'to' => $profile['url']];
1107 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
1109 $signed = LDSignature::sign($data, $owner);
1110 HTTPSignature::transmit($signed, $profile['inbox'], $uid);