3 * @file src/Protocol/ActivityPub/Transmitter.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\BaseObject;
8 use Friendica\Content\Feature;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Content\Text\Plaintext;
11 use Friendica\Core\Cache;
12 use Friendica\Core\Config;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
17 use Friendica\Model\APContact;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Conversation;
20 use Friendica\Model\Item;
21 use Friendica\Model\Profile;
22 use Friendica\Model\Photo;
23 use Friendica\Model\Term;
24 use Friendica\Model\User;
25 use Friendica\Protocol\Activity;
26 use Friendica\Protocol\ActivityPub;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\HTTPSignature;
29 use Friendica\Util\Images;
30 use Friendica\Util\JsonLD;
31 use Friendica\Util\LDSignature;
32 use Friendica\Util\Map;
33 use Friendica\Util\Network;
34 use Friendica\Util\XML;
36 require_once 'include/api.php';
37 require_once 'mod/share.php';
40 * @brief ActivityPub Transmitter Protocol class
48 * collects the lost of followers of the given owner
50 * @param array $owner Owner array
51 * @param integer $page Page number
53 * @return array of owners
54 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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, 'deleted' => 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';
76 $data['type'] = 'OrderedCollectionPage';
79 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
80 while ($contact = DBA::fetch($contacts)) {
81 $list[] = $contact['url'];
85 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
88 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
90 $data['orderedItems'] = $list;
97 * Create list of following contacts
99 * @param array $owner Owner array
100 * @param integer $page Page numbe
102 * @return array of following contacts
103 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
105 public static function getFollowing($owner, $page = null)
107 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
108 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
109 $count = DBA::count('contact', $condition);
111 $data = ['@context' => ActivityPub::CONTEXT];
112 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
113 $data['type'] = 'OrderedCollection';
114 $data['totalItems'] = $count;
116 // When we hide our friends we will only show the pure number but don't allow more.
117 $profile = Profile::getByUID($owner['uid']);
118 if (!empty($profile['hide-friends'])) {
123 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
125 $data['type'] = 'OrderedCollectionPage';
128 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
129 while ($contact = DBA::fetch($contacts)) {
130 $list[] = $contact['url'];
134 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
137 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
139 $data['orderedItems'] = $list;
146 * Public posts for the given owner
148 * @param array $owner Owner array
149 * @param integer $page Page numbe
151 * @return array of posts
152 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
153 * @throws \ImagickException
155 public static function getOutbox($owner, $page = null)
157 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
159 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
160 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
161 'deleted' => false, 'visible' => true, 'moderated' => false];
162 $count = DBA::count('item', $condition);
164 $data = ['@context' => ActivityPub::CONTEXT];
165 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
166 $data['type'] = 'OrderedCollection';
167 $data['totalItems'] = $count;
170 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
172 $data['type'] = 'OrderedCollectionPage';
175 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
177 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
178 while ($item = Item::fetch($items)) {
179 $object = self::createObjectFromItemID($item['id']);
180 unset($object['@context']);
185 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
188 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
190 $data['orderedItems'] = $list;
197 * Return the service array containing information the used software and it's url
199 * @return array with service data
201 private static function getService()
203 return ['type' => 'Service',
204 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
205 'url' => BaseObject::getApp()->getBaseURL()];
209 * Return the ActivityPub profile of the given user
211 * @param integer $uid User ID
212 * @return array with profile data
213 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
215 public static function getProfile($uid)
217 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
218 'account_removed' => false, 'verified' => true];
219 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
220 $user = DBA::selectFirst('user', $fields, $condition);
221 if (!DBA::isResult($user)) {
225 $fields = ['locality', 'region', 'country-name'];
226 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
227 if (!DBA::isResult($profile)) {
231 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
232 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
233 if (!DBA::isResult($contact)) {
237 $data = ['@context' => ActivityPub::CONTEXT];
238 $data['id'] = $contact['url'];
239 $data['diaspora:guid'] = $user['guid'];
240 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
241 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
242 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
243 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
244 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
245 $data['preferredUsername'] = $user['nickname'];
246 $data['name'] = $contact['name'];
247 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
248 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
249 $data['summary'] = $contact['about'];
250 $data['url'] = $contact['url'];
251 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
252 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
253 'owner' => $contact['url'],
254 'publicKeyPem' => $user['pubkey']];
255 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
256 $data['icon'] = ['type' => 'Image',
257 'url' => $contact['photo']];
259 $data['generator'] = self::getService();
261 // tags: https://kitty.town/@inmysocks/100656097926961126.json
266 * @param string $username
268 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
270 public static function getDeletedUser($username)
273 '@context' => ActivityPub::CONTEXT,
274 'id' => System::baseUrl() . '/profile/' . $username,
275 'type' => 'Tombstone',
276 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
277 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
278 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
283 * Returns an array with permissions of a given item array
287 * @return array with permissions
288 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
289 * @throws \ImagickException
291 private static function fetchPermissionBlockFromConversation($item)
293 if (empty($item['thr-parent'])) {
297 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
298 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
299 if (!DBA::isResult($conversation)) {
303 $activity = json_decode($conversation['source'], true);
305 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
306 $profile = APContact::getByURL($actor);
308 $item_profile = APContact::getByURL($item['author-link']);
309 $exclude[] = $item['author-link'];
311 if ($item['gravity'] == GRAVITY_PARENT) {
312 $exclude[] = $item['owner-link'];
315 $permissions['to'][] = $actor;
317 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
318 if (empty($activity[$element])) {
321 if (is_string($activity[$element])) {
322 $activity[$element] = [$activity[$element]];
325 foreach ($activity[$element] as $receiver) {
326 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
327 $permissions[$element][] = $item_profile['followers'];
328 } elseif (!in_array($receiver, $exclude)) {
329 $permissions[$element][] = $receiver;
337 * Creates an array of permissions from an item thread
339 * @param array $item Item array
340 * @param boolean $blindcopy addressing via "bcc" or "cc"?
341 * @param integer $last_id Last item id for adding receivers
342 * @param boolean $forum_mode "true" means that we are sending content to a forum
344 * @return array with permission data
345 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
346 * @throws \ImagickException
348 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
351 $last_id = $item['id'];
356 // Check if we should always deliver our stuff via BCC
357 if (!empty($item['uid'])) {
358 $profile = Profile::getByUID($item['uid']);
359 if (!empty($profile)) {
360 $always_bcc = $profile['hide-friends'];
364 if (Config::get('debug', 'total_ap_delivery')) {
365 // Will be activated in a later step
366 $networks = Protocol::FEDERATED;
368 // For now only send to these contacts:
369 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
372 $data = ['to' => [], 'cc' => [], 'bcc' => []];
374 if ($item['gravity'] == GRAVITY_PARENT) {
375 $actor_profile = APContact::getByURL($item['owner-link']);
377 $actor_profile = APContact::getByURL($item['author-link']);
380 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
382 if (!$item['private']) {
383 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
385 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
387 foreach ($terms as $term) {
388 $profile = APContact::getByURL($term['url'], false);
389 if (!empty($profile)) {
390 $data['to'][] = $profile['url'];
394 $receiver_list = Item::enumeratePermissions($item, true);
396 foreach ($terms as $term) {
397 $cid = Contact::getIdForURL($term['url'], $item['uid']);
398 if (!empty($cid) && in_array($cid, $receiver_list)) {
399 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
400 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
404 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
405 $data['to'][] = $profile['url'];
410 foreach ($receiver_list as $receiver) {
411 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
412 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
416 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
417 if ($contact['hidden'] || $always_bcc) {
418 $data['bcc'][] = $profile['url'];
420 $data['cc'][] = $profile['url'];
426 if (!empty($item['parent'])) {
427 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
428 while ($parent = Item::fetch($parents)) {
429 if ($parent['gravity'] == GRAVITY_PARENT) {
430 $profile = APContact::getByURL($parent['owner-link'], false);
431 if (!empty($profile)) {
432 if ($item['gravity'] != GRAVITY_PARENT) {
433 // Comments to forums are directed to the forum
434 // But comments to forums aren't directed to the followers collection
435 if ($profile['type'] == 'Group') {
436 $data['to'][] = $profile['url'];
438 $data['cc'][] = $profile['url'];
439 if (!$item['private'] && !empty($actor_profile['followers'])) {
440 $data['cc'][] = $actor_profile['followers'];
444 // Public thread parent post always are directed to the followers
445 if (!$item['private'] && !$forum_mode) {
446 $data['cc'][] = $actor_profile['followers'];
452 // Don't include data from future posts
453 if ($parent['id'] >= $last_id) {
457 $profile = APContact::getByURL($parent['author-link'], false);
458 if (!empty($profile)) {
459 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
460 $data['to'][] = $profile['url'];
462 $data['cc'][] = $profile['url'];
466 DBA::close($parents);
469 $data['to'] = array_unique($data['to']);
470 $data['cc'] = array_unique($data['cc']);
471 $data['bcc'] = array_unique($data['bcc']);
473 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
474 unset($data['to'][$key]);
477 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
478 unset($data['cc'][$key]);
481 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
482 unset($data['bcc'][$key]);
485 foreach ($data['to'] as $to) {
486 if (($key = array_search($to, $data['cc'])) !== false) {
487 unset($data['cc'][$key]);
490 if (($key = array_search($to, $data['bcc'])) !== false) {
491 unset($data['bcc'][$key]);
495 foreach ($data['cc'] as $cc) {
496 if (($key = array_search($cc, $data['bcc'])) !== false) {
497 unset($data['bcc'][$key]);
501 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
504 unset($receivers['bcc']);
511 * Check if an inbox is archived
513 * @param string $url Inbox url
515 * @return boolean "true" if inbox is archived
517 private static function archivedInbox($url)
519 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
523 * Fetches a list of inboxes of followers of a given user
525 * @param integer $uid User ID
526 * @param boolean $personal fetch personal inboxes
528 * @return array of follower inboxes
529 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
530 * @throws \ImagickException
532 public static function fetchTargetInboxesforUser($uid, $personal = false)
536 if (Config::get('debug', 'total_ap_delivery')) {
537 // Will be activated in a later step
538 $networks = Protocol::FEDERATED;
540 // For now only send to these contacts:
541 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
544 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
547 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
550 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
551 while ($contact = DBA::fetch($contacts)) {
552 if (Contact::isLocal($contact['url'])) {
556 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
560 if (Network::isUrlBlocked($contact['url'])) {
564 $profile = APContact::getByURL($contact['url'], false);
565 if (!empty($profile)) {
566 if (empty($profile['sharedinbox']) || $personal) {
567 $target = $profile['inbox'];
569 $target = $profile['sharedinbox'];
571 if (!self::archivedInbox($target)) {
572 $inboxes[$target] = $target;
576 DBA::close($contacts);
582 * Fetches an array of inboxes for the given item and user
584 * @param array $item Item array
585 * @param integer $uid User ID
586 * @param boolean $personal fetch personal inboxes
587 * @param integer $last_id Last item id for adding receivers
588 * @param boolean $forum_mode "true" means that we are sending content to a forum
589 * @return array with inboxes
590 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
591 * @throws \ImagickException
593 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
595 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
596 if (empty($permissions)) {
602 if ($item['gravity'] == GRAVITY_ACTIVITY) {
603 $item_profile = APContact::getByURL($item['author-link'], false);
605 $item_profile = APContact::getByURL($item['owner-link'], false);
608 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
609 if (empty($permissions[$element])) {
613 $blindcopy = in_array($element, ['bto', 'bcc']);
615 foreach ($permissions[$element] as $receiver) {
616 if (Network::isUrlBlocked($receiver)) {
620 if ($receiver == $item_profile['followers']) {
621 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
623 if (Contact::isLocal($receiver)) {
627 $profile = APContact::getByURL($receiver, false);
628 if (!empty($profile)) {
629 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
630 $target = $profile['inbox'];
632 $target = $profile['sharedinbox'];
634 if (!self::archivedInbox($target)) {
635 $inboxes[$target] = $target;
646 * Creates an array in the structure of the item table for a given mail id
648 * @param integer $mail_id
653 public static function ItemArrayFromMail($mail_id)
655 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
657 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
659 // Making the post more compatible for Mastodon by:
660 // - Making it a note and not an article (no title)
661 // - Moving the title into the "summary" field that is used as a "content warning"
662 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
665 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
666 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
667 $mail['allow_gid'] = '';
668 $mail['deny_cid'] = '';
669 $mail['deny_gid'] = '';
670 $mail['private'] = true;
671 $mail['deleted'] = false;
672 $mail['edited'] = $mail['created'];
673 $mail['plink'] = $mail['uri'];
674 $mail['thr-parent'] = $reply['uri'];
675 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
677 $mail['event-type'] = '';
678 $mail['attach'] = '';
686 * Creates an activity array for a given mail id
688 * @param integer $mail_id
689 * @param boolean $object_mode Is the activity item is used inside another object?
691 * @return array of activity
694 public static function createActivityFromMail($mail_id, $object_mode = false)
696 $mail = self::ItemArrayFromMail($mail_id);
697 $object = self::createNote($mail);
699 $object['to'] = $object['cc'];
700 unset($object['cc']);
702 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => 'test']];
705 $data = ['@context' => ActivityPub::CONTEXT];
710 $data['id'] = $mail['uri'] . '#Create';
711 $data['type'] = 'Create';
712 $data['actor'] = $mail['author-link'];
713 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
714 $data['instrument'] = self::getService();
715 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
717 if (empty($data['to']) && !empty($data['cc'])) {
718 $data['to'] = $data['cc'];
721 if (empty($data['to']) && !empty($data['bcc'])) {
722 $data['to'] = $data['bcc'];
728 $object['to'] = $data['to'];
729 unset($object['cc']);
730 unset($object['bcc']);
732 $data['directMessage'] = true;
734 $data['object'] = $object;
736 $owner = User::getOwnerDataById($mail['uid']);
738 if (!$object_mode && !empty($owner)) {
739 return LDSignature::sign($data, $owner);
746 * Returns the activity type of a given item
750 * @return string with activity type
751 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
752 * @throws \ImagickException
754 private static function getTypeOfItem($item)
758 // Only check for a reshare, if it is a real reshare and no quoted reshare
759 if (strpos($item['body'], "[share") === 0) {
760 $announce = api_share_as_retweet($item);
761 $reshared = !empty($announce['plink']);
766 } elseif ($item['verb'] == Activity::POST) {
767 if ($item['created'] == $item['edited']) {
772 } elseif ($item['verb'] == Activity::LIKE) {
774 } elseif ($item['verb'] == Activity::DISLIKE) {
776 } elseif ($item['verb'] == Activity::ATTEND) {
778 } elseif ($item['verb'] == Activity::ATTENDNO) {
780 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
781 $type = 'TentativeAccept';
782 } elseif ($item['verb'] == Activity::FOLLOW) {
784 } elseif ($item['verb'] == Activity::TAG) {
794 * Creates the activity or fetches it from the cache
796 * @param integer $item_id
797 * @param boolean $force Force new cache entry
799 * @return array with the activity
802 public static function createCachedActivityFromItem($item_id, $force = false)
804 $cachekey = 'APDelivery:createActivity:' . $item_id;
807 $data = Cache::get($cachekey);
808 if (!is_null($data)) {
813 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
815 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
820 * Creates an activity array for a given item id
822 * @param integer $item_id
823 * @param boolean $object_mode Is the activity item is used inside another object?
825 * @return array of activity
828 public static function createActivityFromItem($item_id, $object_mode = false)
830 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
832 if (!DBA::isResult($item)) {
836 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
837 $owner = User::getOwnerDataById($item['uid']);
838 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
841 // Disguise forum posts as reshares. Will later be converted to a real announce
842 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
843 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
848 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
849 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
850 if (DBA::isResult($conversation)) {
851 $data = json_decode($conversation['source'], true);
857 $type = self::getTypeOfItem($item);
861 $data = ['@context' => ActivityPub::CONTEXT];
863 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
865 } elseif ($item['deleted']) {
872 $data['id'] = $item['uri'] . '#' . $type;
873 $data['type'] = $type;
875 if (Item::isForumPost($item) && ($type != 'Announce')) {
876 $data['actor'] = $item['author-link'];
878 $data['actor'] = $item['owner-link'];
881 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
883 $data['instrument'] = self::getService();
885 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
887 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
888 $data['object'] = self::createNote($item);
889 } elseif ($data['type'] == 'Add') {
890 $data = self::createAddTag($item, $data);
891 } elseif ($data['type'] == 'Announce') {
892 $data = self::createAnnounce($item, $data);
893 } elseif ($data['type'] == 'Follow') {
894 $data['object'] = $item['parent-uri'];
895 } elseif ($data['type'] == 'Undo') {
896 $data['object'] = self::createActivityFromItem($item_id, true);
898 $data['diaspora:guid'] = $item['guid'];
899 if (!empty($item['signed_text'])) {
900 $data['diaspora:like'] = $item['signed_text'];
902 $data['object'] = $item['thr-parent'];
905 if (!empty($item['contact-uid'])) {
906 $uid = $item['contact-uid'];
911 $owner = User::getOwnerDataById($uid);
913 if (!$object_mode && !empty($owner)) {
914 return LDSignature::sign($data, $owner);
919 /// @todo Create "conversation" entry
923 * Creates an object array for a given item id
925 * @param integer $item_id
927 * @return array with the object data
928 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
929 * @throws \ImagickException
931 public static function createObjectFromItemID($item_id)
933 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
935 if (!DBA::isResult($item)) {
939 $data = ['@context' => ActivityPub::CONTEXT];
940 $data = array_merge($data, self::createNote($item));
946 * Creates a location entry for a given item array
950 * @return array with location array
952 private static function createLocation($item)
954 $location = ['type' => 'Place'];
956 if (!empty($item['location'])) {
957 $location['name'] = $item['location'];
962 if (empty($item['coord'])) {
963 $coord = Map::getCoordinates($item['location']);
965 $coords = explode(' ', $item['coord']);
966 if (count($coords) == 2) {
967 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
971 if (!empty($coord['lat']) && !empty($coord['lon'])) {
972 $location['latitude'] = $coord['lat'];
973 $location['longitude'] = $coord['lon'];
980 * Returns a tag array for a given item array
984 * @return array of tags
985 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
987 private static function createTagList($item)
991 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
992 foreach ($terms as $term) {
993 if ($term['type'] == Term::HASHTAG) {
994 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
995 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
996 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
997 $contact = Contact::getDetailsByURL($term['url']);
998 if (!empty($contact['addr'])) {
999 $mention = '@' . $contact['addr'];
1001 $mention = '@' . $term['url'];
1004 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1011 * Adds attachment data to the JSON document
1013 * @param array $item Data of the item that is to be posted
1014 * @param string $type Object type
1016 * @return array with attachment data
1017 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1019 private static function createAttachmentList($item, $type)
1023 $arr = explode('[/attach],', $item['attach']);
1025 foreach ($arr as $r) {
1027 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1029 $attributes = ['type' => 'Document',
1030 'mediaType' => $matches[3],
1031 'url' => $matches[1],
1034 if (trim($matches[4]) != '') {
1035 $attributes['name'] = trim($matches[4]);
1038 $attachments[] = $attributes;
1043 if ($type != 'Note') {
1044 return $attachments;
1047 // Simplify image codes
1048 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1050 // Grab all pictures without alternative descriptions and create attachments out of them
1051 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1052 foreach ($pictures[1] as $picture) {
1053 $imgdata = Images::getInfoFromURLCached($picture);
1055 $attachments[] = ['type' => 'Document',
1056 'mediaType' => $imgdata['mime'],
1063 // Grab all pictures with alternative description and create attachments out of them
1064 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1065 foreach ($pictures as $picture) {
1066 $imgdata = Images::getInfoFromURLCached($picture[1]);
1068 $attachments[] = ['type' => 'Document',
1069 'mediaType' => $imgdata['mime'],
1070 'url' => $picture[1],
1071 'name' => $picture[2]];
1076 return $attachments;
1080 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
1082 * @param array $match Matching values for the callback
1083 * @return string Replaced mention
1084 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1086 private static function mentionCallback($match)
1088 if (empty($match[1])) {
1092 $data = Contact::getDetailsByURL($match[1]);
1093 if (empty($data['nick'])) {
1097 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1101 * Remove image elements since they are added as attachment
1103 * @param string $body
1105 * @return string with removed images
1107 private static function removePictures($body)
1109 // Simplify image codes
1110 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1111 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1113 // Now remove local links
1114 $body = preg_replace_callback(
1115 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1117 // We remove the link when it is a link to a local photo page
1118 if (Photo::isLocalPage($match[1])) {
1121 // otherwise we just return the link
1122 return '[url]' . $match[1] . '[/url]';
1127 // Remove all pictures
1128 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1134 * Fetches the "context" value for a givem item array from the "conversation" table
1136 * @param array $item
1138 * @return string with context url
1139 * @throws \Exception
1141 private static function fetchContextURLForItem($item)
1143 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1144 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1145 $context_uri = $conversation['conversation-href'];
1146 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1147 $context_uri = $conversation['conversation-uri'];
1149 $context_uri = $item['parent-uri'] . '#context';
1151 return $context_uri;
1155 * Returns if the post contains sensitive content ("nsfw")
1157 * @param integer $item_id
1160 * @throws \Exception
1162 private static function isSensitive($item_id)
1164 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1165 return DBA::exists('term', $condition);
1169 * Creates event data
1171 * @param array $item
1173 * @return array with the event data
1174 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1176 public static function createEvent($item)
1179 $event['name'] = $item['event-summary'];
1180 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1181 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1183 if (!$item['event-nofinish']) {
1184 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1187 if (!empty($item['event-location'])) {
1188 $item['location'] = $item['event-location'];
1189 $event['location'] = self::createLocation($item);
1196 * Creates a note/article object array
1198 * @param array $item
1200 * @return array with the object data
1201 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1202 * @throws \ImagickException
1204 public static function createNote($item)
1206 if ($item['event-type'] == 'event') {
1208 } elseif (!empty($item['title'])) {
1214 if ($item['deleted']) {
1215 $type = 'Tombstone';
1219 $data['id'] = $item['uri'];
1220 $data['type'] = $type;
1222 if ($item['deleted']) {
1226 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1228 if ($item['uri'] != $item['thr-parent']) {
1229 $data['inReplyTo'] = $item['thr-parent'];
1231 $data['inReplyTo'] = null;
1234 $data['diaspora:guid'] = $item['guid'];
1235 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1237 if ($item['created'] != $item['edited']) {
1238 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1241 $data['url'] = $item['plink'];
1242 $data['attributedTo'] = $item['author-link'];
1243 $data['sensitive'] = self::isSensitive($item['id']);
1244 $data['context'] = self::fetchContextURLForItem($item);
1246 if (!empty($item['title'])) {
1247 $data['name'] = BBCode::toPlaintext($item['title'], false);
1250 $permission_block = self::createPermissionBlockForItem($item, false);
1252 $body = $item['body'];
1254 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1255 $body = self::prependMentions($body, $permission_block);
1258 if ($type == 'Note') {
1259 $body = self::removePictures($body);
1260 } elseif (($type == 'Article') && empty($data['summary'])) {
1261 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1264 if ($type == 'Event') {
1265 $data = array_merge($data, self::createEvent($item));
1267 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1268 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1270 $data['content'] = BBCode::convert($body, false, 9);
1273 $data['contentMap']['text/html'] = BBCode::convert($item['body'], false);
1274 $data['contentMap']['text/markdown'] = BBCode::toMarkdown($item["body"]);
1276 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1278 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1279 $data['diaspora:comment'] = $item['signed_text'];
1282 $data['attachment'] = self::createAttachmentList($item, $type);
1283 $data['tag'] = self::createTagList($item);
1285 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1286 $data['location'] = self::createLocation($item);
1289 if (!empty($item['app'])) {
1290 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1293 $data = array_merge($data, $permission_block);
1299 * Creates an an "add tag" entry
1301 * @param array $item
1302 * @param array $data activity data
1304 * @return array with activity data for adding tags
1305 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1306 * @throws \ImagickException
1308 private static function createAddTag($item, $data)
1310 $object = XML::parseString($item['object'], false);
1311 $target = XML::parseString($item["target"], false);
1313 $data['diaspora:guid'] = $item['guid'];
1314 $data['actor'] = $item['author-link'];
1315 $data['target'] = (string)$target->id;
1316 $data['summary'] = BBCode::toPlaintext($item['body']);
1317 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1323 * Creates an announce object entry
1325 * @param array $item
1326 * @param array $data activity data
1328 * @return array with activity data
1329 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1330 * @throws \ImagickException
1332 private static function createAnnounce($item, $data)
1334 $orig_body = $item['body'];
1335 $announce = api_share_as_retweet($item);
1336 if (empty($announce['plink'])) {
1337 $data['type'] = 'Create';
1338 $data['object'] = self::createNote($item);
1342 // Fetch the original id of the object
1343 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1344 if (!empty($activity)) {
1345 $ldactivity = JsonLD::compact($activity);
1346 $id = JsonLD::fetchElement($ldactivity, '@id');
1347 $type = str_replace('as:', '', JsonLD::fetchElement($ldactivity, '@type'));
1349 if (empty($announce['share-pre-body'])) {
1350 // Pure announce, without a quote
1351 $data['type'] = 'Announce';
1352 $data['object'] = $id;
1357 $data['type'] = 'Create';
1358 $item['body'] = trim($announce['share-pre-body']) . "\n" . $id;
1359 $data['object'] = self::createNote($item);
1361 /// @todo Finally descide how to implement this in AP. This is a possible way:
1362 $data['object']['attachment'][] = ['type' => $type, 'id' => $id];
1364 $data['object']['source']['content'] = $orig_body;
1369 $item['body'] = $orig_body;
1370 $data['type'] = 'Create';
1371 $data['object'] = self::createNote($item);
1376 * Creates an activity id for a given contact id
1378 * @param integer $cid Contact ID of target
1380 * @return bool|string activity id
1382 public static function activityIDFromContact($cid)
1384 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1385 if (!DBA::isResult($contact)) {
1389 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1390 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1391 return System::baseUrl() . '/activity/' . $uuid;
1395 * Transmits a contact suggestion to a given inbox
1397 * @param integer $uid User ID
1398 * @param string $inbox Target inbox
1399 * @param integer $suggestion_id Suggestion ID
1401 * @return boolean was the transmission successful?
1402 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1404 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1406 $owner = User::getOwnerDataById($uid);
1408 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1410 $data = ['@context' => ActivityPub::CONTEXT,
1411 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1412 'type' => 'Announce',
1413 'actor' => $owner['url'],
1414 'object' => $suggestion['url'],
1415 'content' => $suggestion['note'],
1416 'instrument' => self::getService(),
1417 'to' => [ActivityPub::PUBLIC_COLLECTION],
1420 $signed = LDSignature::sign($data, $owner);
1422 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1423 return HTTPSignature::transmit($signed, $inbox, $uid);
1427 * Transmits a profile relocation to a given inbox
1429 * @param integer $uid User ID
1430 * @param string $inbox Target inbox
1432 * @return boolean was the transmission successful?
1433 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1435 public static function sendProfileRelocation($uid, $inbox)
1437 $owner = User::getOwnerDataById($uid);
1439 $data = ['@context' => ActivityPub::CONTEXT,
1440 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1441 'type' => 'dfrn:relocate',
1442 'actor' => $owner['url'],
1443 'object' => $owner['url'],
1444 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1445 'instrument' => self::getService(),
1446 'to' => [ActivityPub::PUBLIC_COLLECTION],
1449 $signed = LDSignature::sign($data, $owner);
1451 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1452 return HTTPSignature::transmit($signed, $inbox, $uid);
1456 * Transmits a profile deletion to a given inbox
1458 * @param integer $uid User ID
1459 * @param string $inbox Target inbox
1461 * @return boolean was the transmission successful?
1462 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1464 public static function sendProfileDeletion($uid, $inbox)
1466 $owner = User::getOwnerDataById($uid);
1468 if (empty($owner)) {
1469 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1473 if (empty($owner['uprvkey'])) {
1474 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1478 $data = ['@context' => ActivityPub::CONTEXT,
1479 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1481 'actor' => $owner['url'],
1482 'object' => $owner['url'],
1483 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1484 'instrument' => self::getService(),
1485 'to' => [ActivityPub::PUBLIC_COLLECTION],
1488 $signed = LDSignature::sign($data, $owner);
1490 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1491 return HTTPSignature::transmit($signed, $inbox, $uid);
1495 * Transmits a profile change to a given inbox
1497 * @param integer $uid User ID
1498 * @param string $inbox Target inbox
1500 * @return boolean was the transmission successful?
1501 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1502 * @throws \ImagickException
1504 public static function sendProfileUpdate($uid, $inbox)
1506 $owner = User::getOwnerDataById($uid);
1507 $profile = APContact::getByURL($owner['url']);
1509 $data = ['@context' => ActivityPub::CONTEXT,
1510 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1512 'actor' => $owner['url'],
1513 'object' => self::getProfile($uid),
1514 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1515 'instrument' => self::getService(),
1516 'to' => [$profile['followers']],
1519 $signed = LDSignature::sign($data, $owner);
1521 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1522 return HTTPSignature::transmit($signed, $inbox, $uid);
1526 * Transmits a given activity to a target
1528 * @param string $activity Type name
1529 * @param string $target Target profile
1530 * @param integer $uid User ID
1532 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1533 * @throws \ImagickException
1534 * @throws \Exception
1536 public static function sendActivity($activity, $target, $uid, $id = '')
1538 $profile = APContact::getByURL($target);
1539 if (empty($profile['inbox'])) {
1540 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1544 $owner = User::getOwnerDataById($uid);
1547 $id = System::baseUrl() . '/activity/' . System::createGUID();
1550 $data = ['@context' => ActivityPub::CONTEXT,
1552 'type' => $activity,
1553 'actor' => $owner['url'],
1554 'object' => $profile['url'],
1555 'instrument' => self::getService(),
1556 'to' => [$profile['url']]];
1558 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1560 $signed = LDSignature::sign($data, $owner);
1561 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1565 * Transmits a "follow object" activity to a target
1566 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1568 * @param string $object Object URL
1569 * @param string $target Target profile
1570 * @param integer $uid User ID
1572 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1573 * @throws \ImagickException
1574 * @throws \Exception
1576 public static function sendFollowObject($object, $target, $uid = 0)
1578 $profile = APContact::getByURL($target);
1579 if (empty($profile['inbox'])) {
1580 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1585 // Fetch the list of administrators
1586 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1588 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1589 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1590 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1591 $uid = $first_user['uid'];
1594 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1595 'author-id' => Contact::getPublicIdByUserId($uid)];
1596 if (Item::exists($condition)) {
1597 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1601 $owner = User::getOwnerDataById($uid);
1603 $data = ['@context' => ActivityPub::CONTEXT,
1604 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1606 'actor' => $owner['url'],
1607 'object' => $object,
1608 'instrument' => self::getService(),
1609 'to' => [$profile['url']]];
1611 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1613 $signed = LDSignature::sign($data, $owner);
1614 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1618 * Transmit a message that the contact request had been accepted
1620 * @param string $target Target profile
1622 * @param integer $uid User ID
1623 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1624 * @throws \ImagickException
1626 public static function sendContactAccept($target, $id, $uid)
1628 $profile = APContact::getByURL($target);
1629 if (empty($profile['inbox'])) {
1630 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1634 $owner = User::getOwnerDataById($uid);
1635 $data = ['@context' => ActivityPub::CONTEXT,
1636 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1638 'actor' => $owner['url'],
1640 'id' => (string)$id,
1642 'actor' => $profile['url'],
1643 'object' => $owner['url']
1645 'instrument' => self::getService(),
1646 'to' => [$profile['url']]];
1648 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1650 $signed = LDSignature::sign($data, $owner);
1651 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1655 * Reject a contact request or terminates the contact relation
1657 * @param string $target Target profile
1659 * @param integer $uid User ID
1660 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1661 * @throws \ImagickException
1663 public static function sendContactReject($target, $id, $uid)
1665 $profile = APContact::getByURL($target);
1666 if (empty($profile['inbox'])) {
1667 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1671 $owner = User::getOwnerDataById($uid);
1672 $data = ['@context' => ActivityPub::CONTEXT,
1673 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1675 'actor' => $owner['url'],
1677 'id' => (string)$id,
1679 'actor' => $profile['url'],
1680 'object' => $owner['url']
1682 'instrument' => self::getService(),
1683 'to' => [$profile['url']]];
1685 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1687 $signed = LDSignature::sign($data, $owner);
1688 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1692 * Transmits a message that we don't want to follow this contact anymore
1694 * @param string $target Target profile
1695 * @param integer $uid User ID
1696 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1697 * @throws \ImagickException
1698 * @throws \Exception
1700 public static function sendContactUndo($target, $cid, $uid)
1702 $profile = APContact::getByURL($target);
1703 if (empty($profile['inbox'])) {
1704 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1708 $object_id = self::activityIDFromContact($cid);
1709 if (empty($object_id)) {
1713 $id = System::baseUrl() . '/activity/' . System::createGUID();
1715 $owner = User::getOwnerDataById($uid);
1716 $data = ['@context' => ActivityPub::CONTEXT,
1719 'actor' => $owner['url'],
1720 'object' => ['id' => $object_id, 'type' => 'Follow',
1721 'actor' => $owner['url'],
1722 'object' => $profile['url']],
1723 'instrument' => self::getService(),
1724 'to' => [$profile['url']]];
1726 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1728 $signed = LDSignature::sign($data, $owner);
1729 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1732 private static function prependMentions($body, array $permission_block)
1734 if (Config::get('system', 'disable_implicit_mentions')) {
1740 foreach ($permission_block['to'] as $profile_url) {
1741 $profile = Contact::getDetailsByURL($profile_url);
1742 if (!empty($profile['addr'])
1743 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1744 && !strstr($body, $profile['addr'])
1745 && !strstr($body, $profile_url)
1747 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1751 $mentions[] = $body;
1753 return implode(' ', $mentions);