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\System;
15 use Friendica\Protocol\Activity;
16 use Friendica\Util\HTTPSignature;
17 use Friendica\Core\Protocol;
18 use Friendica\Core\System;
19 use Friendica\Database\DBA;
20 use Friendica\Model\APContact;
21 use Friendica\Model\Contact;
22 use Friendica\Model\Conversation;
23 use Friendica\Model\Item;
24 use Friendica\Model\Profile;
25 use Friendica\Model\Term;
26 use Friendica\Model\User;
27 use Friendica\Protocol\ActivityPub;
28 use Friendica\Util\DateTimeFormat;
29 use Friendica\Util\HTTPSignature;
30 use Friendica\Util\Images;
31 use Friendica\Util\JsonLD;
32 use Friendica\Util\LDSignature;
33 use Friendica\Util\Map;
34 use Friendica\Util\Network;
35 use Friendica\Util\XML;
37 require_once 'include/api.php';
38 require_once 'mod/share.php';
41 * @brief ActivityPub Transmitter Protocol class
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
55 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
57 public static function getFollowers($owner, $page = null)
59 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
60 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
61 $count = DBA::count('contact', $condition);
63 $data = ['@context' => ActivityPub::CONTEXT];
64 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
65 $data['type'] = 'OrderedCollection';
66 $data['totalItems'] = $count;
68 // When we hide our friends we will only show the pure number but don't allow more.
69 $profile = Profile::getByUID($owner['uid']);
70 if (!empty($profile['hide-friends'])) {
75 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
77 $data['type'] = 'OrderedCollectionPage';
80 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
81 while ($contact = DBA::fetch($contacts)) {
82 $list[] = $contact['url'];
86 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
89 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
91 $data['orderedItems'] = $list;
98 * Create list of following contacts
100 * @param array $owner Owner array
101 * @param integer $page Page numbe
103 * @return array of following contacts
104 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
106 public static function getFollowing($owner, $page = null)
108 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
109 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
110 $count = DBA::count('contact', $condition);
112 $data = ['@context' => ActivityPub::CONTEXT];
113 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
114 $data['type'] = 'OrderedCollection';
115 $data['totalItems'] = $count;
117 // When we hide our friends we will only show the pure number but don't allow more.
118 $profile = Profile::getByUID($owner['uid']);
119 if (!empty($profile['hide-friends'])) {
124 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
126 $data['type'] = 'OrderedCollectionPage';
129 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
130 while ($contact = DBA::fetch($contacts)) {
131 $list[] = $contact['url'];
135 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
138 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
140 $data['orderedItems'] = $list;
147 * Public posts for the given owner
149 * @param array $owner Owner array
150 * @param integer $page Page numbe
152 * @return array of posts
153 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
154 * @throws \ImagickException
156 public static function getOutbox($owner, $page = null)
158 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
160 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
161 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
162 'deleted' => false, 'visible' => true, 'moderated' => false];
163 $count = DBA::count('item', $condition);
165 $data = ['@context' => ActivityPub::CONTEXT];
166 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
167 $data['type'] = 'OrderedCollection';
168 $data['totalItems'] = $count;
171 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
173 $data['type'] = 'OrderedCollectionPage';
176 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
178 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
179 while ($item = Item::fetch($items)) {
180 $object = self::createObjectFromItemID($item['id']);
181 unset($object['@context']);
186 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
189 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
191 $data['orderedItems'] = $list;
198 * Return the service array containing information the used software and it's url
200 * @return array with service data
202 private static function getService()
204 return ['type' => 'Service',
205 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
206 'url' => BaseObject::getApp()->getBaseURL()];
210 * Return the ActivityPub profile of the given user
212 * @param integer $uid User ID
213 * @return array with profile data
214 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
216 public static function getProfile($uid)
218 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
219 'account_removed' => false, 'verified' => true];
220 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
221 $user = DBA::selectFirst('user', $fields, $condition);
222 if (!DBA::isResult($user)) {
226 $fields = ['locality', 'region', 'country-name'];
227 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
228 if (!DBA::isResult($profile)) {
232 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
233 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
234 if (!DBA::isResult($contact)) {
238 $data = ['@context' => ActivityPub::CONTEXT];
239 $data['id'] = $contact['url'];
240 $data['diaspora:guid'] = $user['guid'];
241 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
242 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
243 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
244 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
245 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
246 $data['preferredUsername'] = $user['nickname'];
247 $data['name'] = $contact['name'];
248 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
249 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
250 $data['summary'] = $contact['about'];
251 $data['url'] = $contact['url'];
252 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
253 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
254 'owner' => $contact['url'],
255 'publicKeyPem' => $user['pubkey']];
256 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
257 $data['icon'] = ['type' => 'Image',
258 'url' => $contact['photo']];
260 $data['generator'] = self::getService();
262 // tags: https://kitty.town/@inmysocks/100656097926961126.json
267 * @param string $username
269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271 public static function getDeletedUser($username)
274 '@context' => ActivityPub::CONTEXT,
275 'id' => System::baseUrl() . '/profile/' . $username,
276 'type' => 'Tombstone',
277 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
278 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
279 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
284 * Returns an array with permissions of a given item array
288 * @return array with permissions
289 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
290 * @throws \ImagickException
292 private static function fetchPermissionBlockFromConversation($item)
294 if (empty($item['thr-parent'])) {
298 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
299 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
300 if (!DBA::isResult($conversation)) {
304 $activity = json_decode($conversation['source'], true);
306 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
307 $profile = APContact::getByURL($actor);
309 $item_profile = APContact::getByURL($item['author-link']);
310 $exclude[] = $item['author-link'];
312 if ($item['gravity'] == GRAVITY_PARENT) {
313 $exclude[] = $item['owner-link'];
316 $permissions['to'][] = $actor;
318 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
319 if (empty($activity[$element])) {
322 if (is_string($activity[$element])) {
323 $activity[$element] = [$activity[$element]];
326 foreach ($activity[$element] as $receiver) {
327 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
328 $permissions[$element][] = $item_profile['followers'];
329 } elseif (!in_array($receiver, $exclude)) {
330 $permissions[$element][] = $receiver;
338 * Creates an array of permissions from an item thread
340 * @param array $item Item array
341 * @param boolean $blindcopy addressing via "bcc" or "cc"?
342 * @param integer $last_id Last item id for adding receivers
343 * @param boolean $forum_mode "true" means that we are sending content to a forum
345 * @return array with permission data
346 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
347 * @throws \ImagickException
349 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
352 $last_id = $item['id'];
357 // Check if we should always deliver our stuff via BCC
358 if (!empty($item['uid'])) {
359 $profile = Profile::getByUID($item['uid']);
360 if (!empty($profile)) {
361 $always_bcc = $profile['hide-friends'];
365 if (Config::get('debug', 'total_ap_delivery')) {
366 // Will be activated in a later step
367 $networks = Protocol::FEDERATED;
369 // For now only send to these contacts:
370 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
373 $data = ['to' => [], 'cc' => [], 'bcc' => []];
375 if ($item['gravity'] == GRAVITY_PARENT) {
376 $actor_profile = APContact::getByURL($item['owner-link']);
378 $actor_profile = APContact::getByURL($item['author-link']);
381 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
383 if (!$item['private']) {
384 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
386 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
388 foreach ($terms as $term) {
389 $profile = APContact::getByURL($term['url'], false);
390 if (!empty($profile)) {
391 $data['to'][] = $profile['url'];
395 $receiver_list = Item::enumeratePermissions($item, true);
397 foreach ($terms as $term) {
398 $cid = Contact::getIdForURL($term['url'], $item['uid']);
399 if (!empty($cid) && in_array($cid, $receiver_list)) {
400 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
401 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
405 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
406 $data['to'][] = $profile['url'];
411 foreach ($receiver_list as $receiver) {
412 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
413 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
417 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
418 if ($contact['hidden'] || $always_bcc) {
419 $data['bcc'][] = $profile['url'];
421 $data['cc'][] = $profile['url'];
427 if (!empty($item['parent'])) {
428 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
429 while ($parent = Item::fetch($parents)) {
430 if ($parent['gravity'] == GRAVITY_PARENT) {
431 $profile = APContact::getByURL($parent['owner-link'], false);
432 if (!empty($profile)) {
433 if ($item['gravity'] != GRAVITY_PARENT) {
434 // Comments to forums are directed to the forum
435 // But comments to forums aren't directed to the followers collection
436 if ($profile['type'] == 'Group') {
437 $data['to'][] = $profile['url'];
439 $data['cc'][] = $profile['url'];
440 if (!$item['private'] && !empty($actor_profile['followers'])) {
441 $data['cc'][] = $actor_profile['followers'];
445 // Public thread parent post always are directed to the followers
446 if (!$item['private'] && !$forum_mode) {
447 $data['cc'][] = $actor_profile['followers'];
453 // Don't include data from future posts
454 if ($parent['id'] >= $last_id) {
458 $profile = APContact::getByURL($parent['author-link'], false);
459 if (!empty($profile)) {
460 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
461 $data['to'][] = $profile['url'];
463 $data['cc'][] = $profile['url'];
467 DBA::close($parents);
470 $data['to'] = array_unique($data['to']);
471 $data['cc'] = array_unique($data['cc']);
472 $data['bcc'] = array_unique($data['bcc']);
474 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
475 unset($data['to'][$key]);
478 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
479 unset($data['cc'][$key]);
482 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
483 unset($data['bcc'][$key]);
486 foreach ($data['to'] as $to) {
487 if (($key = array_search($to, $data['cc'])) !== false) {
488 unset($data['cc'][$key]);
491 if (($key = array_search($to, $data['bcc'])) !== false) {
492 unset($data['bcc'][$key]);
496 foreach ($data['cc'] as $cc) {
497 if (($key = array_search($cc, $data['bcc'])) !== false) {
498 unset($data['bcc'][$key]);
502 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
505 unset($receivers['bcc']);
512 * Check if an inbox is archived
514 * @param string $url Inbox url
516 * @return boolean "true" if inbox is archived
518 private static function archivedInbox($url)
520 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
524 * Fetches a list of inboxes of followers of a given user
526 * @param integer $uid User ID
527 * @param boolean $personal fetch personal inboxes
529 * @return array of follower inboxes
530 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
531 * @throws \ImagickException
533 public static function fetchTargetInboxesforUser($uid, $personal = false)
537 if (Config::get('debug', 'total_ap_delivery')) {
538 // Will be activated in a later step
539 $networks = Protocol::FEDERATED;
541 // For now only send to these contacts:
542 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
545 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
548 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
551 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
552 while ($contact = DBA::fetch($contacts)) {
553 if (Contact::isLocal($contact['url'])) {
557 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
561 if (Network::isUrlBlocked($contact['url'])) {
565 $profile = APContact::getByURL($contact['url'], false);
566 if (!empty($profile)) {
567 if (empty($profile['sharedinbox']) || $personal) {
568 $target = $profile['inbox'];
570 $target = $profile['sharedinbox'];
572 if (!self::archivedInbox($target)) {
573 $inboxes[$target] = $target;
577 DBA::close($contacts);
583 * Fetches an array of inboxes for the given item and user
585 * @param array $item Item array
586 * @param integer $uid User ID
587 * @param boolean $personal fetch personal inboxes
588 * @param integer $last_id Last item id for adding receivers
589 * @param boolean $forum_mode "true" means that we are sending content to a forum
590 * @return array with inboxes
591 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
592 * @throws \ImagickException
594 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
596 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
597 if (empty($permissions)) {
603 if ($item['gravity'] == GRAVITY_ACTIVITY) {
604 $item_profile = APContact::getByURL($item['author-link'], false);
606 $item_profile = APContact::getByURL($item['owner-link'], false);
609 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
610 if (empty($permissions[$element])) {
614 $blindcopy = in_array($element, ['bto', 'bcc']);
616 foreach ($permissions[$element] as $receiver) {
617 if (Network::isUrlBlocked($receiver)) {
621 if ($receiver == $item_profile['followers']) {
622 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
624 if (Contact::isLocal($receiver)) {
628 $profile = APContact::getByURL($receiver, false);
629 if (!empty($profile)) {
630 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
631 $target = $profile['inbox'];
633 $target = $profile['sharedinbox'];
635 if (!self::archivedInbox($target)) {
636 $inboxes[$target] = $target;
647 * Creates an array in the structure of the item table for a given mail id
649 * @param integer $mail_id
654 public static function ItemArrayFromMail($mail_id)
656 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
658 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
660 // Making the post more compatible for Mastodon by:
661 // - Making it a note and not an article (no title)
662 // - Moving the title into the "summary" field that is used as a "content warning"
663 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
666 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
667 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
668 $mail['allow_gid'] = '';
669 $mail['deny_cid'] = '';
670 $mail['deny_gid'] = '';
671 $mail['private'] = true;
672 $mail['deleted'] = false;
673 $mail['edited'] = $mail['created'];
674 $mail['plink'] = $mail['uri'];
675 $mail['thr-parent'] = $reply['uri'];
676 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
678 $mail['event-type'] = '';
679 $mail['attach'] = '';
687 * Creates an activity array for a given mail id
689 * @param integer $mail_id
690 * @param boolean $object_mode Is the activity item is used inside another object?
692 * @return array of activity
695 public static function createActivityFromMail($mail_id, $object_mode = false)
697 $mail = self::ItemArrayFromMail($mail_id);
698 $object = self::createNote($mail);
700 $object['to'] = $object['cc'];
701 unset($object['cc']);
703 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => 'test']];
706 $data = ['@context' => ActivityPub::CONTEXT];
711 $data['id'] = $mail['uri'] . '#Create';
712 $data['type'] = 'Create';
713 $data['actor'] = $mail['author-link'];
714 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
715 $data['instrument'] = self::getService();
716 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
718 if (empty($data['to']) && !empty($data['cc'])) {
719 $data['to'] = $data['cc'];
722 if (empty($data['to']) && !empty($data['bcc'])) {
723 $data['to'] = $data['bcc'];
729 $object['to'] = $data['to'];
730 unset($object['cc']);
731 unset($object['bcc']);
733 $data['directMessage'] = true;
735 $data['object'] = $object;
737 $owner = User::getOwnerDataById($mail['uid']);
739 if (!$object_mode && !empty($owner)) {
740 return LDSignature::sign($data, $owner);
747 * Returns the activity type of a given item
751 * @return string with activity type
752 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
753 * @throws \ImagickException
755 private static function getTypeOfItem($item)
759 // Only check for a reshare, if it is a real reshare and no quoted reshare
760 if (strpos($item['body'], "[share") === 0) {
761 $announce = api_share_as_retweet($item);
762 $reshared = !empty($announce['plink']);
767 } elseif ($item['verb'] == Activity::POST) {
768 if ($item['created'] == $item['edited']) {
773 } elseif ($item['verb'] == Activity::LIKE) {
775 } elseif ($item['verb'] == Activity::DISLIKE) {
777 } elseif ($item['verb'] == Activity::ATTEND) {
779 } elseif ($item['verb'] == Activity::ATTENDNO) {
781 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
782 $type = 'TentativeAccept';
783 } elseif ($item['verb'] == Activity::FOLLOW) {
785 } elseif ($item['verb'] == Activity::TAG) {
795 * Creates the activity or fetches it from the cache
797 * @param integer $item_id
798 * @param boolean $force Force new cache entry
800 * @return array with the activity
803 public static function createCachedActivityFromItem($item_id, $force = false)
805 $cachekey = 'APDelivery:createActivity:' . $item_id;
808 $data = Cache::get($cachekey);
809 if (!is_null($data)) {
814 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
816 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
821 * Creates an activity array for a given item id
823 * @param integer $item_id
824 * @param boolean $object_mode Is the activity item is used inside another object?
826 * @return array of activity
829 public static function createActivityFromItem($item_id, $object_mode = false)
831 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
833 if (!DBA::isResult($item)) {
837 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
838 $owner = User::getOwnerDataById($item['uid']);
839 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
842 // Disguise forum posts as reshares. Will later be converted to a real announce
843 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
844 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
849 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
850 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
851 if (DBA::isResult($conversation)) {
852 $data = json_decode($conversation['source'], true);
858 $type = self::getTypeOfItem($item);
862 $data = ['@context' => ActivityPub::CONTEXT];
864 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
866 } elseif ($item['deleted']) {
873 $data['id'] = $item['uri'] . '#' . $type;
874 $data['type'] = $type;
876 if (Item::isForumPost($item) && ($type != 'Announce')) {
877 $data['actor'] = $item['author-link'];
879 $data['actor'] = $item['owner-link'];
882 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
884 $data['instrument'] = self::getService();
886 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
888 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
889 $data['object'] = self::createNote($item);
890 } elseif ($data['type'] == 'Add') {
891 $data = self::createAddTag($item, $data);
892 } elseif ($data['type'] == 'Announce') {
893 $data = self::createAnnounce($item, $data);
894 } elseif ($data['type'] == 'Follow') {
895 $data['object'] = $item['parent-uri'];
896 } elseif ($data['type'] == 'Undo') {
897 $data['object'] = self::createActivityFromItem($item_id, true);
899 $data['diaspora:guid'] = $item['guid'];
900 if (!empty($item['signed_text'])) {
901 $data['diaspora:like'] = $item['signed_text'];
903 $data['object'] = $item['thr-parent'];
906 if (!empty($item['contact-uid'])) {
907 $uid = $item['contact-uid'];
912 $owner = User::getOwnerDataById($uid);
914 if (!$object_mode && !empty($owner)) {
915 return LDSignature::sign($data, $owner);
920 /// @todo Create "conversation" entry
924 * Creates an object array for a given item id
926 * @param integer $item_id
928 * @return array with the object data
929 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
930 * @throws \ImagickException
932 public static function createObjectFromItemID($item_id)
934 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
936 if (!DBA::isResult($item)) {
940 $data = ['@context' => ActivityPub::CONTEXT];
941 $data = array_merge($data, self::createNote($item));
947 * Creates a location entry for a given item array
951 * @return array with location array
953 private static function createLocation($item)
955 $location = ['type' => 'Place'];
957 if (!empty($item['location'])) {
958 $location['name'] = $item['location'];
963 if (empty($item['coord'])) {
964 $coord = Map::getCoordinates($item['location']);
966 $coords = explode(' ', $item['coord']);
967 if (count($coords) == 2) {
968 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
972 if (!empty($coord['lat']) && !empty($coord['lon'])) {
973 $location['latitude'] = $coord['lat'];
974 $location['longitude'] = $coord['lon'];
981 * Returns a tag array for a given item array
985 * @return array of tags
986 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
988 private static function createTagList($item)
992 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
993 foreach ($terms as $term) {
994 if ($term['type'] == Term::HASHTAG) {
995 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
996 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
997 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
998 $contact = Contact::getDetailsByURL($term['url']);
999 if (!empty($contact['addr'])) {
1000 $mention = '@' . $contact['addr'];
1002 $mention = '@' . $term['url'];
1005 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1012 * Adds attachment data to the JSON document
1014 * @param array $item Data of the item that is to be posted
1015 * @param string $type Object type
1017 * @return array with attachment data
1018 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1020 private static function createAttachmentList($item, $type)
1024 $arr = explode('[/attach],', $item['attach']);
1026 foreach ($arr as $r) {
1028 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1030 $attributes = ['type' => 'Document',
1031 'mediaType' => $matches[3],
1032 'url' => $matches[1],
1035 if (trim($matches[4]) != '') {
1036 $attributes['name'] = trim($matches[4]);
1039 $attachments[] = $attributes;
1044 if ($type != 'Note') {
1045 return $attachments;
1048 // Simplify image codes
1049 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1051 // Grab all pictures without alternative descriptions and create attachments out of them
1052 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1053 foreach ($pictures[1] as $picture) {
1054 $imgdata = Images::getInfoFromURLCached($picture);
1056 $attachments[] = ['type' => 'Document',
1057 'mediaType' => $imgdata['mime'],
1064 // Grab all pictures with alternative description and create attachments out of them
1065 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1066 foreach ($pictures as $picture) {
1067 $imgdata = Images::getInfoFromURLCached($picture[1]);
1069 $attachments[] = ['type' => 'Document',
1070 'mediaType' => $imgdata['mime'],
1071 'url' => $picture[1],
1072 'name' => $picture[2]];
1077 return $attachments;
1081 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
1083 * @param array $match Matching values for the callback
1084 * @return string Replaced mention
1085 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1087 private static function mentionCallback($match)
1089 if (empty($match[1])) {
1093 $data = Contact::getDetailsByURL($match[1]);
1094 if (empty($data['nick'])) {
1098 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1102 * Remove image elements and replaces them with links to the image
1104 * @param string $body
1106 * @return string with replaced elements
1108 private static function removePictures($body)
1110 // Simplify image codes
1111 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1113 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
1114 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
1120 * Fetches the "context" value for a givem item array from the "conversation" table
1122 * @param array $item
1124 * @return string with context url
1125 * @throws \Exception
1127 private static function fetchContextURLForItem($item)
1129 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1130 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1131 $context_uri = $conversation['conversation-href'];
1132 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1133 $context_uri = $conversation['conversation-uri'];
1135 $context_uri = $item['parent-uri'] . '#context';
1137 return $context_uri;
1141 * Returns if the post contains sensitive content ("nsfw")
1143 * @param integer $item_id
1146 * @throws \Exception
1148 private static function isSensitive($item_id)
1150 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1151 return DBA::exists('term', $condition);
1155 * Creates event data
1157 * @param array $item
1159 * @return array with the event data
1160 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1162 public static function createEvent($item)
1165 $event['name'] = $item['event-summary'];
1166 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1167 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1169 if (!$item['event-nofinish']) {
1170 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1173 if (!empty($item['event-location'])) {
1174 $item['location'] = $item['event-location'];
1175 $event['location'] = self::createLocation($item);
1182 * Creates a note/article object array
1184 * @param array $item
1186 * @return array with the object data
1187 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1188 * @throws \ImagickException
1190 public static function createNote($item)
1192 if ($item['event-type'] == 'event') {
1194 } elseif (!empty($item['title'])) {
1200 if ($item['deleted']) {
1201 $type = 'Tombstone';
1205 $data['id'] = $item['uri'];
1206 $data['type'] = $type;
1208 if ($item['deleted']) {
1212 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1214 if ($item['uri'] != $item['thr-parent']) {
1215 $data['inReplyTo'] = $item['thr-parent'];
1217 $data['inReplyTo'] = null;
1220 $data['diaspora:guid'] = $item['guid'];
1221 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1223 if ($item['created'] != $item['edited']) {
1224 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1227 $data['url'] = $item['plink'];
1228 $data['attributedTo'] = $item['author-link'];
1229 $data['sensitive'] = self::isSensitive($item['id']);
1230 $data['context'] = self::fetchContextURLForItem($item);
1232 if (!empty($item['title'])) {
1233 $data['name'] = BBCode::toPlaintext($item['title'], false);
1236 $permission_block = self::createPermissionBlockForItem($item, false);
1238 $body = $item['body'];
1240 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1241 $body = self::prependMentions($body, $permission_block);
1244 if ($type == 'Note') {
1245 $body = self::removePictures($body);
1246 } elseif (($type == 'Article') && empty($data['summary'])) {
1247 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1250 if ($type == 'Event') {
1251 $data = array_merge($data, self::createEvent($item));
1253 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1254 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1256 $data['content'] = BBCode::convert($body, false, 9);
1259 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1261 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1262 $data['diaspora:comment'] = $item['signed_text'];
1265 $data['attachment'] = self::createAttachmentList($item, $type);
1266 $data['tag'] = self::createTagList($item);
1268 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1269 $data['location'] = self::createLocation($item);
1272 if (!empty($item['app'])) {
1273 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1276 $data = array_merge($data, $permission_block);
1282 * Creates an an "add tag" entry
1284 * @param array $item
1285 * @param array $data activity data
1287 * @return array with activity data for adding tags
1288 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1289 * @throws \ImagickException
1291 private static function createAddTag($item, $data)
1293 $object = XML::parseString($item['object'], false);
1294 $target = XML::parseString($item["target"], false);
1296 $data['diaspora:guid'] = $item['guid'];
1297 $data['actor'] = $item['author-link'];
1298 $data['target'] = (string)$target->id;
1299 $data['summary'] = BBCode::toPlaintext($item['body']);
1300 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1306 * Creates an announce object entry
1308 * @param array $item
1309 * @param array $data activity data
1311 * @return array with activity data
1312 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1313 * @throws \ImagickException
1315 private static function createAnnounce($item, $data)
1317 $orig_body = $item['body'];
1318 $announce = api_share_as_retweet($item);
1319 if (empty($announce['plink'])) {
1320 $data['type'] = 'Create';
1321 $data['object'] = self::createNote($item);
1325 // Fetch the original id of the object
1326 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1327 if (!empty($activity)) {
1328 $ldactivity = JsonLD::compact($activity);
1329 $id = JsonLD::fetchElement($ldactivity, '@id');
1330 $type = str_replace('as:', '', JsonLD::fetchElement($ldactivity, '@type'));
1332 if (empty($announce['share-pre-body'])) {
1333 // Pure announce, without a quote
1334 $data['type'] = 'Announce';
1335 $data['object'] = $id;
1340 $data['type'] = 'Create';
1341 $item['body'] = trim($announce['share-pre-body']) . "\n" . $id;
1342 $data['object'] = self::createNote($item);
1344 /// @todo Finally descide how to implement this in AP. This is a possible way:
1345 $data['object']['attachment'][] = ['type' => $type, 'id' => $id];
1347 $data['object']['source']['content'] = $orig_body;
1352 $item['body'] = $orig_body;
1353 $data['type'] = 'Create';
1354 $data['object'] = self::createNote($item);
1359 * Creates an activity id for a given contact id
1361 * @param integer $cid Contact ID of target
1363 * @return bool|string activity id
1365 public static function activityIDFromContact($cid)
1367 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1368 if (!DBA::isResult($contact)) {
1372 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1373 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1374 return System::baseUrl() . '/activity/' . $uuid;
1378 * Transmits a contact suggestion to a given inbox
1380 * @param integer $uid User ID
1381 * @param string $inbox Target inbox
1382 * @param integer $suggestion_id Suggestion ID
1384 * @return boolean was the transmission successful?
1385 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1387 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1389 $owner = User::getOwnerDataById($uid);
1391 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1393 $data = ['@context' => ActivityPub::CONTEXT,
1394 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1395 'type' => 'Announce',
1396 'actor' => $owner['url'],
1397 'object' => $suggestion['url'],
1398 'content' => $suggestion['note'],
1399 'instrument' => self::getService(),
1400 'to' => [ActivityPub::PUBLIC_COLLECTION],
1403 $signed = LDSignature::sign($data, $owner);
1405 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1406 return HTTPSignature::transmit($signed, $inbox, $uid);
1410 * Transmits a profile relocation to a given inbox
1412 * @param integer $uid User ID
1413 * @param string $inbox Target inbox
1415 * @return boolean was the transmission successful?
1416 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1418 public static function sendProfileRelocation($uid, $inbox)
1420 $owner = User::getOwnerDataById($uid);
1422 $data = ['@context' => ActivityPub::CONTEXT,
1423 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1424 'type' => 'dfrn:relocate',
1425 'actor' => $owner['url'],
1426 'object' => $owner['url'],
1427 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1428 'instrument' => self::getService(),
1429 'to' => [ActivityPub::PUBLIC_COLLECTION],
1432 $signed = LDSignature::sign($data, $owner);
1434 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1435 return HTTPSignature::transmit($signed, $inbox, $uid);
1439 * Transmits a profile deletion to a given inbox
1441 * @param integer $uid User ID
1442 * @param string $inbox Target inbox
1444 * @return boolean was the transmission successful?
1445 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1447 public static function sendProfileDeletion($uid, $inbox)
1449 $owner = User::getOwnerDataById($uid);
1451 if (empty($owner)) {
1452 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1456 if (empty($owner['uprvkey'])) {
1457 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1461 $data = ['@context' => ActivityPub::CONTEXT,
1462 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1464 'actor' => $owner['url'],
1465 'object' => $owner['url'],
1466 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1467 'instrument' => self::getService(),
1468 'to' => [ActivityPub::PUBLIC_COLLECTION],
1471 $signed = LDSignature::sign($data, $owner);
1473 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1474 return HTTPSignature::transmit($signed, $inbox, $uid);
1478 * Transmits a profile change to a given inbox
1480 * @param integer $uid User ID
1481 * @param string $inbox Target inbox
1483 * @return boolean was the transmission successful?
1484 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1485 * @throws \ImagickException
1487 public static function sendProfileUpdate($uid, $inbox)
1489 $owner = User::getOwnerDataById($uid);
1490 $profile = APContact::getByURL($owner['url']);
1492 $data = ['@context' => ActivityPub::CONTEXT,
1493 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1495 'actor' => $owner['url'],
1496 'object' => self::getProfile($uid),
1497 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1498 'instrument' => self::getService(),
1499 'to' => [$profile['followers']],
1502 $signed = LDSignature::sign($data, $owner);
1504 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1505 return HTTPSignature::transmit($signed, $inbox, $uid);
1509 * Transmits a given activity to a target
1511 * @param string $activity Type name
1512 * @param string $target Target profile
1513 * @param integer $uid User ID
1515 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1516 * @throws \ImagickException
1517 * @throws \Exception
1519 public static function sendActivity($activity, $target, $uid, $id = '')
1521 $profile = APContact::getByURL($target);
1522 if (empty($profile['inbox'])) {
1523 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1527 $owner = User::getOwnerDataById($uid);
1530 $id = System::baseUrl() . '/activity/' . System::createGUID();
1533 $data = ['@context' => ActivityPub::CONTEXT,
1535 'type' => $activity,
1536 'actor' => $owner['url'],
1537 'object' => $profile['url'],
1538 'instrument' => self::getService(),
1539 'to' => [$profile['url']]];
1541 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1543 $signed = LDSignature::sign($data, $owner);
1544 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1548 * Transmits a "follow object" activity to a target
1549 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1551 * @param string $object Object URL
1552 * @param string $target Target profile
1553 * @param integer $uid User ID
1555 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1556 * @throws \ImagickException
1557 * @throws \Exception
1559 public static function sendFollowObject($object, $target, $uid = 0)
1561 $profile = APContact::getByURL($target);
1562 if (empty($profile['inbox'])) {
1563 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1568 // Fetch the list of administrators
1569 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1571 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1572 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1573 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1574 $uid = $first_user['uid'];
1577 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1578 'author-id' => Contact::getPublicIdByUserId($uid)];
1579 if (Item::exists($condition)) {
1580 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1584 $owner = User::getOwnerDataById($uid);
1586 $data = ['@context' => ActivityPub::CONTEXT,
1587 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1589 'actor' => $owner['url'],
1590 'object' => $object,
1591 'instrument' => self::getService(),
1592 'to' => [$profile['url']]];
1594 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1596 $signed = LDSignature::sign($data, $owner);
1597 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1601 * Transmit a message that the contact request had been accepted
1603 * @param string $target Target profile
1605 * @param integer $uid User ID
1606 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1607 * @throws \ImagickException
1609 public static function sendContactAccept($target, $id, $uid)
1611 $profile = APContact::getByURL($target);
1612 if (empty($profile['inbox'])) {
1613 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1617 $owner = User::getOwnerDataById($uid);
1618 $data = ['@context' => ActivityPub::CONTEXT,
1619 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1621 'actor' => $owner['url'],
1623 'id' => (string)$id,
1625 'actor' => $profile['url'],
1626 'object' => $owner['url']
1628 'instrument' => self::getService(),
1629 'to' => [$profile['url']]];
1631 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1633 $signed = LDSignature::sign($data, $owner);
1634 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1638 * Reject a contact request or terminates the contact relation
1640 * @param string $target Target profile
1642 * @param integer $uid User ID
1643 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1644 * @throws \ImagickException
1646 public static function sendContactReject($target, $id, $uid)
1648 $profile = APContact::getByURL($target);
1649 if (empty($profile['inbox'])) {
1650 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1654 $owner = User::getOwnerDataById($uid);
1655 $data = ['@context' => ActivityPub::CONTEXT,
1656 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1658 'actor' => $owner['url'],
1660 'id' => (string)$id,
1662 'actor' => $profile['url'],
1663 'object' => $owner['url']
1665 'instrument' => self::getService(),
1666 'to' => [$profile['url']]];
1668 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1670 $signed = LDSignature::sign($data, $owner);
1671 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1675 * Transmits a message that we don't want to follow this contact anymore
1677 * @param string $target Target profile
1678 * @param integer $uid User ID
1679 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1680 * @throws \ImagickException
1681 * @throws \Exception
1683 public static function sendContactUndo($target, $cid, $uid)
1685 $profile = APContact::getByURL($target);
1686 if (empty($profile['inbox'])) {
1687 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1691 $object_id = self::activityIDFromContact($cid);
1692 if (empty($object_id)) {
1696 $id = System::baseUrl() . '/activity/' . System::createGUID();
1698 $owner = User::getOwnerDataById($uid);
1699 $data = ['@context' => ActivityPub::CONTEXT,
1702 'actor' => $owner['url'],
1703 'object' => ['id' => $object_id, 'type' => 'Follow',
1704 'actor' => $owner['url'],
1705 'object' => $profile['url']],
1706 'instrument' => self::getService(),
1707 'to' => [$profile['url']]];
1709 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1711 $signed = LDSignature::sign($data, $owner);
1712 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1715 private static function prependMentions($body, array $permission_block)
1717 if (Config::get('system', 'disable_implicit_mentions')) {
1723 foreach ($permission_block['to'] as $profile_url) {
1724 $profile = Contact::getDetailsByURL($profile_url);
1725 if (!empty($profile['addr'])
1726 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1727 && !strstr($body, $profile['addr'])
1728 && !strstr($body, $profile_url)
1730 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1734 $mentions[] = $body;
1736 return implode(' ', $mentions);