3 * @file src/Protocol/ActivityPub/Transmitter.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\BaseObject;
8 use Friendica\Content\Feature;
9 use Friendica\Database\DBA;
10 use Friendica\Core\Config;
11 use Friendica\Core\Logger;
12 use Friendica\Core\System;
13 use Friendica\Util\HTTPSignature;
14 use Friendica\Core\Protocol;
15 use Friendica\Model\Conversation;
16 use Friendica\Model\Contact;
17 use Friendica\Model\APContact;
18 use Friendica\Model\Item;
19 use Friendica\Model\Term;
20 use Friendica\Model\User;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Content\Text\BBCode;
23 use Friendica\Content\Text\Plaintext;
24 use Friendica\Util\XML;
25 use Friendica\Util\JsonLD;
26 use Friendica\Util\LDSignature;
27 use Friendica\Model\Profile;
28 use Friendica\Object\Image;
29 use Friendica\Protocol\ActivityPub;
30 use Friendica\Core\Cache;
31 use Friendica\Util\Map;
32 use Friendica\Util\Network;
34 require_once 'include/api.php';
35 require_once 'mod/share.php';
38 * @brief ActivityPub Transmitter Protocol class
46 * collects the lost of followers of the given owner
48 * @param array $owner Owner array
49 * @param integer $page Page number
51 * @return array of owners
52 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
54 public static function getFollowers($owner, $page = null)
56 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
57 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
58 $count = DBA::count('contact', $condition);
60 $data = ['@context' => ActivityPub::CONTEXT];
61 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
62 $data['type'] = 'OrderedCollection';
63 $data['totalItems'] = $count;
65 // When we hide our friends we will only show the pure number but don't allow more.
66 $profile = Profile::getByUID($owner['uid']);
67 if (!empty($profile['hide-friends'])) {
72 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
74 $data['type'] = 'OrderedCollectionPage';
77 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
78 while ($contact = DBA::fetch($contacts)) {
79 $list[] = $contact['url'];
83 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
86 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
88 $data['orderedItems'] = $list;
95 * Create list of following contacts
97 * @param array $owner Owner array
98 * @param integer $page Page numbe
100 * @return array of following contacts
101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
103 public static function getFollowing($owner, $page = null)
105 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
106 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
107 $count = DBA::count('contact', $condition);
109 $data = ['@context' => ActivityPub::CONTEXT];
110 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
111 $data['type'] = 'OrderedCollection';
112 $data['totalItems'] = $count;
114 // When we hide our friends we will only show the pure number but don't allow more.
115 $profile = Profile::getByUID($owner['uid']);
116 if (!empty($profile['hide-friends'])) {
121 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
123 $data['type'] = 'OrderedCollectionPage';
126 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
127 while ($contact = DBA::fetch($contacts)) {
128 $list[] = $contact['url'];
132 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
135 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
137 $data['orderedItems'] = $list;
144 * Public posts for the given owner
146 * @param array $owner Owner array
147 * @param integer $page Page numbe
149 * @return array of posts
150 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
151 * @throws \ImagickException
153 public static function getOutbox($owner, $page = null)
155 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
157 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
158 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
159 'deleted' => false, 'visible' => true, 'moderated' => false];
160 $count = DBA::count('item', $condition);
162 $data = ['@context' => ActivityPub::CONTEXT];
163 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
164 $data['type'] = 'OrderedCollection';
165 $data['totalItems'] = $count;
168 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
170 $data['type'] = 'OrderedCollectionPage';
173 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
175 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
176 while ($item = Item::fetch($items)) {
177 $object = self::createObjectFromItemID($item['id']);
178 unset($object['@context']);
183 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
186 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
188 $data['orderedItems'] = $list;
195 * Return the service array containing information the used software and it's url
197 * @return array with service data
199 private static function getService()
201 return ['type' => 'Service',
202 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
203 'url' => BaseObject::getApp()->getBaseURL()];
207 * Return the ActivityPub profile of the given user
209 * @param integer $uid User ID
210 * @return array with profile data
211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
213 public static function getProfile($uid)
215 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
216 'account_removed' => false, 'verified' => true];
217 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
218 $user = DBA::selectFirst('user', $fields, $condition);
219 if (!DBA::isResult($user)) {
223 $fields = ['locality', 'region', 'country-name'];
224 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
225 if (!DBA::isResult($profile)) {
229 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
230 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
231 if (!DBA::isResult($contact)) {
235 $data = ['@context' => ActivityPub::CONTEXT];
236 $data['id'] = $contact['url'];
237 $data['diaspora:guid'] = $user['guid'];
238 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
239 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
240 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
241 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
242 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
243 $data['preferredUsername'] = $user['nickname'];
244 $data['name'] = $contact['name'];
245 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
246 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
247 $data['summary'] = $contact['about'];
248 $data['url'] = $contact['url'];
249 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
250 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
251 'owner' => $contact['url'],
252 'publicKeyPem' => $user['pubkey']];
253 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
254 $data['icon'] = ['type' => 'Image',
255 'url' => $contact['photo']];
257 $data['generator'] = self::getService();
259 // tags: https://kitty.town/@inmysocks/100656097926961126.json
264 * @param string $username
266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
268 public static function getDeletedUser($username)
271 '@context' => ActivityPub::CONTEXT,
272 'id' => System::baseUrl() . '/profile/' . $username,
273 'type' => 'Tombstone',
274 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
275 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
276 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
281 * Returns an array with permissions of a given item array
285 * @return array with permissions
286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
287 * @throws \ImagickException
289 private static function fetchPermissionBlockFromConversation($item)
291 if (empty($item['thr-parent'])) {
295 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
296 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
297 if (!DBA::isResult($conversation)) {
301 $activity = json_decode($conversation['source'], true);
303 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
304 $profile = APContact::getByURL($actor);
306 $item_profile = APContact::getByURL($item['author-link']);
307 $exclude[] = $item['author-link'];
309 if ($item['gravity'] == GRAVITY_PARENT) {
310 $exclude[] = $item['owner-link'];
313 $permissions['to'][] = $actor;
315 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
316 if (empty($activity[$element])) {
319 if (is_string($activity[$element])) {
320 $activity[$element] = [$activity[$element]];
323 foreach ($activity[$element] as $receiver) {
324 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
325 $permissions[$element][] = $item_profile['followers'];
326 } elseif (!in_array($receiver, $exclude)) {
327 $permissions[$element][] = $receiver;
335 * Creates an array of permissions from an item thread
337 * @param array $item Item array
338 * @param boolean $blindcopy addressing via "bcc" or "cc"?
339 * @param integer $last_id Last item id for adding receivers
340 * @param boolean $forum_mode "true" means that we are sending content to a forum
342 * @return array with permission data
343 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
344 * @throws \ImagickException
346 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
349 $last_id = $item['id'];
354 // Check if we should always deliver our stuff via BCC
355 if (!empty($item['uid'])) {
356 $profile = Profile::getByUID($item['uid']);
357 if (!empty($profile)) {
358 $always_bcc = $profile['hide-friends'];
362 if (Config::get('debug', 'total_ap_delivery')) {
363 // Will be activated in a later step
364 $networks = Protocol::FEDERATED;
366 // For now only send to these contacts:
367 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
370 $data = ['to' => [], 'cc' => [], 'bcc' => []];
372 if ($item['gravity'] == GRAVITY_PARENT) {
373 $actor_profile = APContact::getByURL($item['owner-link']);
375 $actor_profile = APContact::getByURL($item['author-link']);
378 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
380 if (!$item['private']) {
381 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
383 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
385 foreach ($terms as $term) {
386 $profile = APContact::getByURL($term['url'], false);
387 if (!empty($profile)) {
388 $data['to'][] = $profile['url'];
392 $receiver_list = Item::enumeratePermissions($item, true);
394 foreach ($terms as $term) {
395 $cid = Contact::getIdForURL($term['url'], $item['uid']);
396 if (!empty($cid) && in_array($cid, $receiver_list)) {
397 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
398 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
402 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
403 $data['to'][] = $profile['url'];
408 foreach ($receiver_list as $receiver) {
409 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
410 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
414 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
415 if ($contact['hidden'] || $always_bcc) {
416 $data['bcc'][] = $profile['url'];
418 $data['cc'][] = $profile['url'];
424 if (!empty($item['parent'])) {
425 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
426 while ($parent = Item::fetch($parents)) {
427 if ($parent['gravity'] == GRAVITY_PARENT) {
428 $profile = APContact::getByURL($parent['owner-link'], false);
429 if (!empty($profile)) {
430 if ($item['gravity'] != GRAVITY_PARENT) {
431 // Comments to forums are directed to the forum
432 // But comments to forums aren't directed to the followers collection
433 if ($profile['type'] == 'Group') {
434 $data['to'][] = $profile['url'];
436 $data['cc'][] = $profile['url'];
437 if (!$item['private'] && !empty($actor_profile['followers'])) {
438 $data['cc'][] = $actor_profile['followers'];
442 // Public thread parent post always are directed to the followers
443 if (!$item['private'] && !$forum_mode) {
444 $data['cc'][] = $actor_profile['followers'];
450 // Don't include data from future posts
451 if ($parent['id'] >= $last_id) {
455 $profile = APContact::getByURL($parent['author-link'], false);
456 if (!empty($profile)) {
457 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
458 $data['to'][] = $profile['url'];
460 $data['cc'][] = $profile['url'];
464 DBA::close($parents);
467 $data['to'] = array_unique($data['to']);
468 $data['cc'] = array_unique($data['cc']);
469 $data['bcc'] = array_unique($data['bcc']);
471 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
472 unset($data['to'][$key]);
475 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
476 unset($data['cc'][$key]);
479 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
480 unset($data['bcc'][$key]);
483 foreach ($data['to'] as $to) {
484 if (($key = array_search($to, $data['cc'])) !== false) {
485 unset($data['cc'][$key]);
488 if (($key = array_search($to, $data['bcc'])) !== false) {
489 unset($data['bcc'][$key]);
493 foreach ($data['cc'] as $cc) {
494 if (($key = array_search($cc, $data['bcc'])) !== false) {
495 unset($data['bcc'][$key]);
499 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
502 unset($receivers['bcc']);
509 * Check if an inbox is archived
511 * @param string $url Inbox url
513 * @return boolean "true" if inbox is archived
515 private static function archivedInbox($url)
517 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
521 * Fetches a list of inboxes of followers of a given user
523 * @param integer $uid User ID
524 * @param boolean $personal fetch personal inboxes
526 * @return array of follower inboxes
527 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
528 * @throws \ImagickException
530 public static function fetchTargetInboxesforUser($uid, $personal = false)
534 if (Config::get('debug', 'total_ap_delivery')) {
535 // Will be activated in a later step
536 $networks = Protocol::FEDERATED;
538 // For now only send to these contacts:
539 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
542 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
545 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
548 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
549 while ($contact = DBA::fetch($contacts)) {
550 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
554 if (Network::isUrlBlocked($contact['url'])) {
558 $profile = APContact::getByURL($contact['url'], false);
559 if (!empty($profile)) {
560 if (empty($profile['sharedinbox']) || $personal) {
561 $target = $profile['inbox'];
563 $target = $profile['sharedinbox'];
565 if (!self::archivedInbox($target)) {
566 $inboxes[$target] = $target;
570 DBA::close($contacts);
576 * Fetches an array of inboxes for the given item and user
578 * @param array $item Item array
579 * @param integer $uid User ID
580 * @param boolean $personal fetch personal inboxes
581 * @param integer $last_id Last item id for adding receivers
582 * @param boolean $forum_mode "true" means that we are sending content to a forum
583 * @return array with inboxes
584 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
585 * @throws \ImagickException
587 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
589 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
590 if (empty($permissions)) {
596 if ($item['gravity'] == GRAVITY_ACTIVITY) {
597 $item_profile = APContact::getByURL($item['author-link'], false);
599 $item_profile = APContact::getByURL($item['owner-link'], false);
602 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
603 if (empty($permissions[$element])) {
607 $blindcopy = in_array($element, ['bto', 'bcc']);
609 foreach ($permissions[$element] as $receiver) {
610 if (Network::isUrlBlocked($receiver)) {
614 if ($receiver == $item_profile['followers']) {
615 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
617 $profile = APContact::getByURL($receiver, false);
618 if (!empty($profile)) {
619 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
620 $target = $profile['inbox'];
622 $target = $profile['sharedinbox'];
624 if (!self::archivedInbox($target)) {
625 $inboxes[$target] = $target;
636 * Creates an array in the structure of the item table for a given mail id
638 * @param integer $mail_id
643 public static function ItemArrayFromMail($mail_id)
645 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
647 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
649 // Making the post more compatible for Mastodon by:
650 // - Making it a note and not an article (no title)
651 // - Moving the title into the "summary" field that is used as a "content warning"
652 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
655 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
656 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
657 $mail['allow_gid'] = '';
658 $mail['deny_cid'] = '';
659 $mail['deny_gid'] = '';
660 $mail['private'] = true;
661 $mail['deleted'] = false;
662 $mail['edited'] = $mail['created'];
663 $mail['plink'] = $mail['uri'];
664 $mail['thr-parent'] = $reply['uri'];
665 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
667 $mail['event-type'] = '';
668 $mail['attach'] = '';
676 * Creates an activity array for a given mail id
678 * @param integer $mail_id
679 * @param boolean $object_mode Is the activity item is used inside another object?
681 * @return array of activity
684 public static function createActivityFromMail($mail_id, $object_mode = false)
686 $mail = self::ItemArrayFromMail($mail_id);
687 $object = self::createNote($mail);
689 $object['to'] = $object['cc'];
690 unset($object['cc']);
692 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => 'test']];
695 $data = ['@context' => ActivityPub::CONTEXT];
700 $data['id'] = $mail['uri'] . '#Create';
701 $data['type'] = 'Create';
702 $data['actor'] = $mail['author-link'];
703 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
704 $data['instrument'] = self::getService();
705 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
707 if (empty($data['to']) && !empty($data['cc'])) {
708 $data['to'] = $data['cc'];
711 if (empty($data['to']) && !empty($data['bcc'])) {
712 $data['to'] = $data['bcc'];
718 $object['to'] = $data['to'];
719 unset($object['cc']);
720 unset($object['bcc']);
722 $data['directMessage'] = true;
724 $data['object'] = $object;
726 $owner = User::getOwnerDataById($mail['uid']);
728 if (!$object_mode && !empty($owner)) {
729 return LDSignature::sign($data, $owner);
736 * Returns the activity type of a given item
740 * @return string with activity type
741 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
742 * @throws \ImagickException
744 private static function getTypeOfItem($item)
748 // Only check for a reshare, if it is a real reshare and no quoted reshare
749 if (strpos($item['body'], "[share") === 0) {
750 $announce = api_share_as_retweet($item);
751 $reshared = !empty($announce['plink']);
756 } elseif ($item['verb'] == ACTIVITY_POST) {
757 if ($item['created'] == $item['edited']) {
762 } elseif ($item['verb'] == ACTIVITY_LIKE) {
764 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
766 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
768 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
770 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
771 $type = 'TentativeAccept';
772 } elseif ($item['verb'] == ACTIVITY_FOLLOW) {
774 } elseif ($item['verb'] == ACTIVITY_TAG) {
784 * Creates the activity or fetches it from the cache
786 * @param integer $item_id
787 * @param boolean $force Force new cache entry
789 * @return array with the activity
792 public static function createCachedActivityFromItem($item_id, $force = false)
794 $cachekey = 'APDelivery:createActivity:' . $item_id;
797 $data = Cache::get($cachekey);
798 if (!is_null($data)) {
803 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
805 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
810 * Creates an activity array for a given item id
812 * @param integer $item_id
813 * @param boolean $object_mode Is the activity item is used inside another object?
815 * @return array of activity
818 public static function createActivityFromItem($item_id, $object_mode = false)
820 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
822 if (!DBA::isResult($item)) {
826 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
827 $owner = User::getOwnerDataById($item['uid']);
828 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
831 // Disguise forum posts as reshares. Will later be converted to a real announce
832 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
833 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
838 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
839 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
840 if (DBA::isResult($conversation)) {
841 $data = json_decode($conversation['source'], true);
847 $type = self::getTypeOfItem($item);
851 $data = ['@context' => ActivityPub::CONTEXT];
853 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
855 } elseif ($item['deleted']) {
862 $data['id'] = $item['uri'] . '#' . $type;
863 $data['type'] = $type;
865 if (Item::isForumPost($item) && ($type != 'Announce')) {
866 $data['actor'] = $item['author-link'];
868 $data['actor'] = $item['owner-link'];
871 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
873 $data['instrument'] = self::getService();
875 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
877 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
878 $data['object'] = self::createNote($item);
879 } elseif ($data['type'] == 'Add') {
880 $data = self::createAddTag($item, $data);
881 } elseif ($data['type'] == 'Announce') {
882 $data = self::createAnnounce($item, $data);
883 } elseif ($data['type'] == 'Follow') {
884 $data['object'] = $item['parent-uri'];
885 } elseif ($data['type'] == 'Undo') {
886 $data['object'] = self::createActivityFromItem($item_id, true);
888 $data['diaspora:guid'] = $item['guid'];
889 if (!empty($item['signed_text'])) {
890 $data['diaspora:like'] = $item['signed_text'];
892 $data['object'] = $item['thr-parent'];
895 if (!empty($item['contact-uid'])) {
896 $uid = $item['contact-uid'];
901 $owner = User::getOwnerDataById($uid);
903 if (!$object_mode && !empty($owner)) {
904 return LDSignature::sign($data, $owner);
909 /// @todo Create "conversation" entry
913 * Creates an object array for a given item id
915 * @param integer $item_id
917 * @return array with the object data
918 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
919 * @throws \ImagickException
921 public static function createObjectFromItemID($item_id)
923 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
925 if (!DBA::isResult($item)) {
929 $data = ['@context' => ActivityPub::CONTEXT];
930 $data = array_merge($data, self::createNote($item));
936 * Creates a location entry for a given item array
940 * @return array with location array
942 private static function createLocation($item)
944 $location = ['type' => 'Place'];
946 if (!empty($item['location'])) {
947 $location['name'] = $item['location'];
952 if (empty($item['coord'])) {
953 $coord = Map::getCoordinates($item['location']);
955 $coords = explode(' ', $item['coord']);
956 if (count($coords) == 2) {
957 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
961 if (!empty($coord['lat']) && !empty($coord['lon'])) {
962 $location['latitude'] = $coord['lat'];
963 $location['longitude'] = $coord['lon'];
970 * Returns a tag array for a given item array
974 * @return array of tags
975 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
977 private static function createTagList($item)
981 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
982 foreach ($terms as $term) {
983 if ($term['type'] == Term::HASHTAG) {
984 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
985 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
986 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
987 $contact = Contact::getDetailsByURL($term['url']);
988 if (!empty($contact['addr'])) {
989 $mention = '@' . $contact['addr'];
991 $mention = '@' . $term['url'];
994 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1001 * Adds attachment data to the JSON document
1003 * @param array $item Data of the item that is to be posted
1004 * @param string $type Object type
1006 * @return array with attachment data
1007 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1009 private static function createAttachmentList($item, $type)
1013 $arr = explode('[/attach],', $item['attach']);
1015 foreach ($arr as $r) {
1017 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1019 $attributes = ['type' => 'Document',
1020 'mediaType' => $matches[3],
1021 'url' => $matches[1],
1024 if (trim($matches[4]) != '') {
1025 $attributes['name'] = trim($matches[4]);
1028 $attachments[] = $attributes;
1033 if ($type != 'Note') {
1034 return $attachments;
1037 // Simplify image codes
1038 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1040 // Grab all pictures without alternative descriptions and create attachments out of them
1041 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1042 foreach ($pictures[1] as $picture) {
1043 $imgdata = Image::getInfoFromURL($picture);
1045 $attachments[] = ['type' => 'Document',
1046 'mediaType' => $imgdata['mime'],
1053 // Grab all pictures with alternative description and create attachments out of them
1054 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1055 foreach ($pictures as $picture) {
1056 $imgdata = Image::getInfoFromURL($picture[1]);
1058 $attachments[] = ['type' => 'Document',
1059 'mediaType' => $imgdata['mime'],
1060 'url' => $picture[1],
1061 'name' => $picture[2]];
1066 return $attachments;
1070 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
1072 * @param array $match Matching values for the callback
1073 * @return string Replaced mention
1074 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1076 private static function mentionCallback($match)
1078 if (empty($match[1])) {
1082 $data = Contact::getDetailsByURL($match[1]);
1083 if (empty($data['nick'])) {
1087 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1091 * Remove image elements and replaces them with links to the image
1093 * @param string $body
1095 * @return string with replaced elements
1097 private static function removePictures($body)
1099 // Simplify image codes
1100 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1102 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
1103 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
1109 * Fetches the "context" value for a givem item array from the "conversation" table
1111 * @param array $item
1113 * @return string with context url
1114 * @throws \Exception
1116 private static function fetchContextURLForItem($item)
1118 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1119 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1120 $context_uri = $conversation['conversation-href'];
1121 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1122 $context_uri = $conversation['conversation-uri'];
1124 $context_uri = $item['parent-uri'] . '#context';
1126 return $context_uri;
1130 * Returns if the post contains sensitive content ("nsfw")
1132 * @param integer $item_id
1135 * @throws \Exception
1137 private static function isSensitive($item_id)
1139 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1140 return DBA::exists('term', $condition);
1144 * Creates event data
1146 * @param array $item
1148 * @return array with the event data
1149 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1151 public static function createEvent($item)
1154 $event['name'] = $item['event-summary'];
1155 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1156 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1158 if (!$item['event-nofinish']) {
1159 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1162 if (!empty($item['event-location'])) {
1163 $item['location'] = $item['event-location'];
1164 $event['location'] = self::createLocation($item);
1171 * Creates a note/article object array
1173 * @param array $item
1175 * @return array with the object data
1176 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1177 * @throws \ImagickException
1179 public static function createNote($item)
1181 if ($item['event-type'] == 'event') {
1183 } elseif (!empty($item['title'])) {
1189 if ($item['deleted']) {
1190 $type = 'Tombstone';
1194 $data['id'] = $item['uri'];
1195 $data['type'] = $type;
1197 if ($item['deleted']) {
1201 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1203 if ($item['uri'] != $item['thr-parent']) {
1204 $data['inReplyTo'] = $item['thr-parent'];
1206 $data['inReplyTo'] = null;
1209 $data['diaspora:guid'] = $item['guid'];
1210 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1212 if ($item['created'] != $item['edited']) {
1213 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1216 $data['url'] = $item['plink'];
1217 $data['attributedTo'] = $item['author-link'];
1218 $data['sensitive'] = self::isSensitive($item['id']);
1219 $data['context'] = self::fetchContextURLForItem($item);
1221 if (!empty($item['title'])) {
1222 $data['name'] = BBCode::toPlaintext($item['title'], false);
1225 $permission_block = self::createPermissionBlockForItem($item, false);
1227 $body = $item['body'];
1229 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1230 $body = self::prependMentions($body, $permission_block);
1233 if ($type == 'Note') {
1234 $body = self::removePictures($body);
1235 } elseif (($type == 'Article') && empty($data['summary'])) {
1236 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1239 if ($type == 'Event') {
1240 $data = array_merge($data, self::createEvent($item));
1242 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1243 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1245 $data['content'] = BBCode::convert($body, false, 9);
1248 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1250 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1251 $data['diaspora:comment'] = $item['signed_text'];
1254 $data['attachment'] = self::createAttachmentList($item, $type);
1255 $data['tag'] = self::createTagList($item);
1257 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1258 $data['location'] = self::createLocation($item);
1261 if (!empty($item['app'])) {
1262 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1265 $data = array_merge($data, $permission_block);
1271 * Creates an an "add tag" entry
1273 * @param array $item
1274 * @param array $data activity data
1276 * @return array with activity data for adding tags
1277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1278 * @throws \ImagickException
1280 private static function createAddTag($item, $data)
1282 $object = XML::parseString($item['object'], false);
1283 $target = XML::parseString($item["target"], false);
1285 $data['diaspora:guid'] = $item['guid'];
1286 $data['actor'] = $item['author-link'];
1287 $data['target'] = (string)$target->id;
1288 $data['summary'] = BBCode::toPlaintext($item['body']);
1289 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1295 * Creates an announce object entry
1297 * @param array $item
1298 * @param array $data activity data
1300 * @return array with activity data
1301 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1302 * @throws \ImagickException
1304 private static function createAnnounce($item, $data)
1306 $orig_body = $item['body'];
1307 $announce = api_share_as_retweet($item);
1308 if (empty($announce['plink'])) {
1309 $data['type'] = 'Create';
1310 $data['object'] = self::createNote($item);
1314 // Fetch the original id of the object
1315 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1316 if (!empty($activity)) {
1317 $ldactivity = JsonLD::compact($activity);
1318 $id = JsonLD::fetchElement($ldactivity, '@id');
1319 $type = str_replace('as:', '', JsonLD::fetchElement($ldactivity, '@type'));
1321 if (empty($announce['share-pre-body'])) {
1322 // Pure announce, without a quote
1323 $data['type'] = 'Announce';
1324 $data['object'] = $id;
1329 $data['type'] = 'Create';
1330 $item['body'] = trim($announce['share-pre-body']) . "\n" . $id;
1331 $data['object'] = self::createNote($item);
1333 /// @todo Finally descide how to implement this in AP. This is a possible way:
1334 $data['object']['attachment'][] = ['type' => $type, 'id' => $id];
1336 $data['object']['source']['content'] = $orig_body;
1341 $item['body'] = $orig_body;
1342 $data['type'] = 'Create';
1343 $data['object'] = self::createNote($item);
1348 * Creates an activity id for a given contact id
1350 * @param integer $cid Contact ID of target
1352 * @return bool|string activity id
1354 public static function activityIDFromContact($cid)
1356 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1357 if (!DBA::isResult($contact)) {
1361 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1362 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1363 return System::baseUrl() . '/activity/' . $uuid;
1367 * Transmits a contact suggestion to a given inbox
1369 * @param integer $uid User ID
1370 * @param string $inbox Target inbox
1371 * @param integer $suggestion_id Suggestion ID
1373 * @return boolean was the transmission successful?
1374 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1376 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1378 $owner = User::getOwnerDataById($uid);
1380 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1382 $data = ['@context' => ActivityPub::CONTEXT,
1383 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1384 'type' => 'Announce',
1385 'actor' => $owner['url'],
1386 'object' => $suggestion['url'],
1387 'content' => $suggestion['note'],
1388 'instrument' => self::getService(),
1389 'to' => [ActivityPub::PUBLIC_COLLECTION],
1392 $signed = LDSignature::sign($data, $owner);
1394 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1395 return HTTPSignature::transmit($signed, $inbox, $uid);
1399 * Transmits a profile relocation to a given inbox
1401 * @param integer $uid User ID
1402 * @param string $inbox Target inbox
1404 * @return boolean was the transmission successful?
1405 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1407 public static function sendProfileRelocation($uid, $inbox)
1409 $owner = User::getOwnerDataById($uid);
1411 $data = ['@context' => ActivityPub::CONTEXT,
1412 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1413 'type' => 'dfrn:relocate',
1414 'actor' => $owner['url'],
1415 'object' => $owner['url'],
1416 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1417 'instrument' => self::getService(),
1418 'to' => [ActivityPub::PUBLIC_COLLECTION],
1421 $signed = LDSignature::sign($data, $owner);
1423 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1424 return HTTPSignature::transmit($signed, $inbox, $uid);
1428 * Transmits a profile deletion to a given inbox
1430 * @param integer $uid User ID
1431 * @param string $inbox Target inbox
1433 * @return boolean was the transmission successful?
1434 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1436 public static function sendProfileDeletion($uid, $inbox)
1438 $owner = User::getOwnerDataById($uid);
1440 if (empty($owner)) {
1441 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1445 if (empty($owner['uprvkey'])) {
1446 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1450 $data = ['@context' => ActivityPub::CONTEXT,
1451 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1453 'actor' => $owner['url'],
1454 'object' => $owner['url'],
1455 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1456 'instrument' => self::getService(),
1457 'to' => [ActivityPub::PUBLIC_COLLECTION],
1460 $signed = LDSignature::sign($data, $owner);
1462 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1463 return HTTPSignature::transmit($signed, $inbox, $uid);
1467 * Transmits a profile change to a given inbox
1469 * @param integer $uid User ID
1470 * @param string $inbox Target inbox
1472 * @return boolean was the transmission successful?
1473 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1474 * @throws \ImagickException
1476 public static function sendProfileUpdate($uid, $inbox)
1478 $owner = User::getOwnerDataById($uid);
1479 $profile = APContact::getByURL($owner['url']);
1481 $data = ['@context' => ActivityPub::CONTEXT,
1482 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1484 'actor' => $owner['url'],
1485 'object' => self::getProfile($uid),
1486 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1487 'instrument' => self::getService(),
1488 'to' => [$profile['followers']],
1491 $signed = LDSignature::sign($data, $owner);
1493 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1494 return HTTPSignature::transmit($signed, $inbox, $uid);
1498 * Transmits a given activity to a target
1500 * @param string $activity Type name
1501 * @param string $target Target profile
1502 * @param integer $uid User ID
1504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1505 * @throws \ImagickException
1506 * @throws \Exception
1508 public static function sendActivity($activity, $target, $uid, $id = '')
1510 $profile = APContact::getByURL($target);
1511 if (empty($profile['inbox'])) {
1512 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1516 $owner = User::getOwnerDataById($uid);
1519 $id = System::baseUrl() . '/activity/' . System::createGUID();
1522 $data = ['@context' => ActivityPub::CONTEXT,
1524 'type' => $activity,
1525 'actor' => $owner['url'],
1526 'object' => $profile['url'],
1527 'instrument' => self::getService(),
1528 'to' => [$profile['url']]];
1530 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1532 $signed = LDSignature::sign($data, $owner);
1533 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1537 * Transmits a "follow object" activity to a target
1538 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1540 * @param string $object Object URL
1541 * @param string $target Target profile
1542 * @param integer $uid User ID
1544 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1545 * @throws \ImagickException
1546 * @throws \Exception
1548 public static function sendFollowObject($object, $target, $uid = 0)
1550 $profile = APContact::getByURL($target);
1551 if (empty($profile['inbox'])) {
1552 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1557 // Fetch the list of administrators
1558 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1560 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1561 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1562 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1563 $uid = $first_user['uid'];
1566 $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1567 'author-id' => Contact::getPublicIdByUserId($uid)];
1568 if (Item::exists($condition)) {
1569 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1573 $owner = User::getOwnerDataById($uid);
1575 $data = ['@context' => ActivityPub::CONTEXT,
1576 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1578 'actor' => $owner['url'],
1579 'object' => $object,
1580 'instrument' => self::getService(),
1581 'to' => [$profile['url']]];
1583 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1585 $signed = LDSignature::sign($data, $owner);
1586 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1590 * Transmit a message that the contact request had been accepted
1592 * @param string $target Target profile
1594 * @param integer $uid User ID
1595 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1596 * @throws \ImagickException
1598 public static function sendContactAccept($target, $id, $uid)
1600 $profile = APContact::getByURL($target);
1601 if (empty($profile['inbox'])) {
1602 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1606 $owner = User::getOwnerDataById($uid);
1607 $data = ['@context' => ActivityPub::CONTEXT,
1608 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1610 'actor' => $owner['url'],
1612 'id' => (string)$id,
1614 'actor' => $profile['url'],
1615 'object' => $owner['url']
1617 'instrument' => self::getService(),
1618 'to' => [$profile['url']]];
1620 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1622 $signed = LDSignature::sign($data, $owner);
1623 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1627 * Reject a contact request or terminates the contact relation
1629 * @param string $target Target profile
1631 * @param integer $uid User ID
1632 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1633 * @throws \ImagickException
1635 public static function sendContactReject($target, $id, $uid)
1637 $profile = APContact::getByURL($target);
1638 if (empty($profile['inbox'])) {
1639 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1643 $owner = User::getOwnerDataById($uid);
1644 $data = ['@context' => ActivityPub::CONTEXT,
1645 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1647 'actor' => $owner['url'],
1649 'id' => (string)$id,
1651 'actor' => $profile['url'],
1652 'object' => $owner['url']
1654 'instrument' => self::getService(),
1655 'to' => [$profile['url']]];
1657 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1659 $signed = LDSignature::sign($data, $owner);
1660 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1664 * Transmits a message that we don't want to follow this contact anymore
1666 * @param string $target Target profile
1667 * @param integer $uid User ID
1668 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1669 * @throws \ImagickException
1670 * @throws \Exception
1672 public static function sendContactUndo($target, $cid, $uid)
1674 $profile = APContact::getByURL($target);
1675 if (empty($profile['inbox'])) {
1676 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1680 $object_id = self::activityIDFromContact($cid);
1681 if (empty($object_id)) {
1685 $id = System::baseUrl() . '/activity/' . System::createGUID();
1687 $owner = User::getOwnerDataById($uid);
1688 $data = ['@context' => ActivityPub::CONTEXT,
1691 'actor' => $owner['url'],
1692 'object' => ['id' => $object_id, 'type' => 'Follow',
1693 'actor' => $owner['url'],
1694 'object' => $profile['url']],
1695 'instrument' => self::getService(),
1696 'to' => [$profile['url']]];
1698 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1700 $signed = LDSignature::sign($data, $owner);
1701 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1704 private static function prependMentions($body, array $permission_block)
1706 if (Config::get('system', 'disable_implicit_mentions')) {
1712 foreach ($permission_block['to'] as $profile_url) {
1713 $profile = Contact::getDetailsByURL($profile_url);
1714 if (!empty($profile['addr'])
1715 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1716 && !strstr($body, $profile['addr'])
1717 && !strstr($body, $profile_url)
1719 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1723 $mentions[] = $body;
1725 return implode(' ', $mentions);