3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
25 use Friendica\Content\Feature;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\GServer;
36 use Friendica\Model\Item;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Model\Tag;
40 use Friendica\Model\User;
41 use Friendica\Network\HTTPException;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Protocol\Relay;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\HTTPSignature;
47 use Friendica\Util\LDSignature;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
54 * ActivityPub Transmitter Protocol class
61 const CACHEKEY_FEATURED = 'transmitter:getFeatured:';
62 const CACHEKEY_CONTACTS = 'transmitter:getContacts:';
65 * Add relay servers to the list of inboxes
67 * @param array $inboxes
68 * @return array inboxes with added relay servers
70 public static function addRelayServerInboxes(array $inboxes = []): array
72 foreach (Relay::getList(['inbox']) as $contact) {
73 $inboxes[$contact['inbox']] = $contact['inbox'];
80 * Add relay servers to the list of inboxes
82 * @param array $inboxes
83 * @return array inboxes with added relay servers
85 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = []): array
87 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
92 $relays = Relay::getDirectRelayList($item_id);
97 foreach ($relays as $relay) {
98 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
99 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
105 * Subscribe to a relay and updates contact on success
107 * @param string $url Subscribe actor url
108 * @return bool success
110 public static function sendRelayFollow(string $url): bool
112 $contact = Contact::getByURL($url);
113 if (empty($contact)) {
117 $activity_id = self::activityIDFromContact($contact['id']);
118 $success = self::sendActivity('Follow', $url, 0, $activity_id);
120 Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]);
127 * Unsubscribe from a relay and updates contact on success or forced
129 * @param string $url Subscribe actor url
130 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
131 * @return bool success
133 public static function sendRelayUndoFollow(string $url, bool $force = false): bool
135 $contact = Contact::getByURL($url);
136 if (empty($contact)) {
140 $success = self::sendContactUndo($url, $contact['id'], User::getSystemAccount());
142 if ($success || $force) {
143 Contact::update(['rel' => Contact::NOTHING], ['id' => $contact['id']]);
150 * Collects a list of contacts of the given owner
152 * @param array $owner Owner array
153 * @param array $rel The relevant value(s) contact.rel should match
154 * @param string $module The name of the relevant AP endpoint module (followers|following)
155 * @param integer $page Page number
156 * @param string $requester URL of the requester
157 * @param boolean $nocache Wether to bypass caching
158 * @return array of owners
161 public static function getContacts(array $owner, array $rel, string $module, int $page = null, string $requester = null, bool $nocache = false): array
164 $cachekey = self::CACHEKEY_CONTACTS . $module . ':'. $owner['uid'];
165 $result = DI::cache()->get($cachekey);
166 if (!$nocache && !is_null($result)) {
173 'uid' => $owner['uid'],
182 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
184 $total = DBA::count('contact', $condition);
186 $modulePath = '/' . $module . '/';
188 $data = ['@context' => ActivityPub::CONTEXT];
189 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
190 $data['type'] = 'OrderedCollection';
191 $data['totalItems'] = $total;
194 $data['id'] .= '?' . http_build_query(['page' => $page]);
197 // When we hide our friends we will only show the pure number but don't allow more.
198 $show_contacts = empty($owner['hide-friends']);
200 // Allow fetching the contact list when the requester is part of the list.
201 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
202 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
205 if (!$show_contacts) {
206 if (!empty($cachekey)) {
207 DI::cache()->set($cachekey, $data, Duration::DAY);
214 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
216 $data['type'] = 'OrderedCollectionPage';
219 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
220 while ($contact = DBA::fetch($contacts)) {
221 $list[] = $contact['url'];
223 DBA::close($contacts);
225 if (count($list) == 100) {
226 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
229 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
231 $data['orderedItems'] = $list;
234 if (!empty($cachekey)) {
235 DI::cache()->set($cachekey, $data, Duration::DAY);
242 * Public posts for the given owner
244 * @param array $owner Owner array
245 * @param integer $page Page number
246 * @param boolean $nocache Wether to bypass caching
248 * @return array of posts
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 * @throws \ImagickException
252 public static function getFeatured(array $owner, int $page = null, bool $nocache = false): array
255 $cachekey = self::CACHEKEY_FEATURED . $owner['uid'];
256 $result = DI::cache()->get($cachekey);
257 if (!$nocache && !is_null($result)) {
262 $owner_cid = Contact::getIdForURL($owner['url'], 0, false);
264 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
265 $owner_cid, Post\Collection::FEATURED];
267 $condition = DBA::mergeConditions($condition, [
268 'uid' => $owner['uid'],
269 'author-id' => $owner_cid,
270 'private' => [Item::PUBLIC, Item::UNLISTED],
271 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
272 'network' => Protocol::FEDERATED,
273 'parent-network' => Protocol::FEDERATED,
279 $count = Post::count($condition);
281 $data = ['@context' => ActivityPub::CONTEXT];
282 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
283 $data['type'] = 'OrderedCollection';
284 $data['totalItems'] = $count;
287 $data['id'] .= '?' . http_build_query(['page' => $page]);
291 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
293 $data['type'] = 'OrderedCollectionPage';
294 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
298 while ($item = Post::fetch($items)) {
299 $activity = self::createActivityFromItem($item['id'], true);
300 if (!empty($activity)) {
306 if (count($list) == 20) {
307 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
311 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
314 $data['orderedItems'] = $list;
316 if (!empty($cachekey)) {
317 DI::cache()->set($cachekey, $data, Duration::DAY);
324 * Return the service array containing information the used software and it's url
326 * @return array with service data
328 public static function getService(): array
332 'name' => App::PLATFORM . " '" . App::CODENAME . "' " . App::VERSION . '-' . DB_UPDATE_VERSION,
333 'url' => (string)DI::baseUrl()
338 * Return the ActivityPub profile of the given user
340 * @param int $uid User ID
341 * @return array with profile data
342 * @throws HTTPException\NotFoundException
343 * @throws HTTPException\InternalServerErrorException
345 public static function getProfile(int $uid): array
347 $owner = User::getOwnerDataById($uid);
348 if (!isset($owner['id'])) {
349 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
350 throw new HTTPException\NotFoundException('User not found.');
353 $data = ['@context' => ActivityPub::CONTEXT];
354 $data['id'] = $owner['url'];
356 if (!empty($owner['guid'])) {
357 $data['diaspora:guid'] = $owner['guid'];
360 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
363 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
364 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
365 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
366 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
367 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
369 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
372 $data['preferredUsername'] = $owner['nick'];
373 $data['name'] = $owner['name'];
375 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
376 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
377 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
380 if (!empty($owner['about'])) {
381 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
384 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
385 $data['vcard:hasInstantMessage'] = [];
387 if (!empty($owner['xmpp'])) {
388 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
390 if (!empty($owner['matrix'])) {
391 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
395 $data['url'] = $owner['url'];
396 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
397 $data['discoverable'] = (bool)$owner['net-publish'];
398 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
399 'owner' => $owner['url'],
400 'publicKeyPem' => $owner['pubkey']];
401 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
403 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
405 $resourceid = Photo::ridFromURI($owner['photo']);
406 if (!empty($resourceid)) {
407 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
408 if (!empty($photo['type'])) {
409 $data['icon']['mediaType'] = $photo['type'];
413 if (!empty($owner['header'])) {
414 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
416 $resourceid = Photo::ridFromURI($owner['header']);
417 if (!empty($resourceid)) {
418 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
419 if (!empty($photo['type'])) {
420 $data['image']['mediaType'] = $photo['type'];
427 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
429 'type' => 'PropertyValue',
430 'name' => $profile_field->label,
431 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
435 if (!empty($custom_fields)) {
436 $data['attachment'] = $custom_fields;
440 $data['generator'] = self::getService();
442 // tags: https://kitty.town/@inmysocks/100656097926961126.json
447 * Get a minimal actor array for the C2S API
449 * @param integer $cid
452 private static function getActorArrayByCid(int $cid): array
454 $contact = Contact::getById($cid);
456 'id' => $contact['url'],
457 'type' => $data['type'] = ActivityPub::ACCOUNT_TYPES[$contact['contact-type']],
458 'url' => $contact['alias'],
459 'preferredUsername' => $contact['nick'],
460 'name' => $contact['name'],
461 'icon' => ['type' => 'Image', 'url' => Contact::getAvatarUrlForId($cid, '', $contact['updated'])],
462 'image' => ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($cid, '', $contact['updated'])],
463 'manuallyApprovesFollowers' => (bool)$contact['manually-approve'],
464 'discoverable' => !$contact['unsearchable'],
467 if (empty($data['url'])) {
468 $data['url'] = $data['id'];
475 * @param string $username
477 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
479 public static function getDeletedUser(string $username): array
482 '@context' => ActivityPub::CONTEXT,
483 'id' => DI::baseUrl() . '/profile/' . $username,
484 'type' => 'Tombstone',
485 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
486 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
487 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
492 * Returns an array with permissions of the thread parent of the given item array
495 * @param bool $is_forum_thread
497 * @return array with permissions
498 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
499 * @throws \ImagickException
501 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread): array
503 if (empty($item['thr-parent-id'])) {
507 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
508 if (empty($parent)) {
513 'to' => [$parent['author-link']],
519 $parent_profile = APContact::getByURL($parent['author-link']);
521 $item_profile = APContact::getByURL($item['author-link']);
522 $exclude[] = $item['author-link'];
524 if ($item['gravity'] == Item::GRAVITY_PARENT) {
525 $exclude[] = $item['owner-link'];
528 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
529 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
530 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
531 if (!$is_forum_thread) {
532 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
534 } elseif (!in_array($receiver['url'], $exclude)) {
535 $permissions[$type[$receiver['type']]][] = $receiver['url'];
543 * Check if the given item id is from ActivityPub
545 * @param integer $item_id
546 * @return boolean "true" if the post is from ActivityPub
548 private static function isAPPost(int $item_id): bool
550 if (empty($item_id)) {
554 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
558 * Creates an array of permissions from an item thread
560 * @param array $item Item array
561 * @param boolean $blindcopy addressing via "bcc" or "cc"?
562 * @param boolean $expand_followers Expand the list of followers
563 * @param integer $last_id Last item id for adding receivers
565 * @return array with permission data
566 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
567 * @throws \ImagickException
569 private static function createPermissionBlockForItem(array $item, bool $blindcopy, bool $expand_followers, int $last_id = 0): array
572 $last_id = $item['id'];
579 // Check if we should always deliver our stuff via BCC
580 if (!empty($item['uid'])) {
581 $owner = User::getOwnerDataById($item['uid']);
582 if (!empty($owner)) {
583 $always_bcc = $owner['hide-friends'];
584 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
586 $profile = APContact::getByURL($owner['url'], false);
587 $follower = $profile['followers'] ?? '';
591 if (DI::config()->get('system', 'ap_always_bcc')) {
595 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
596 if (!empty($parent) && ($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
597 $profile = APContact::getByURL($parent['causer-link'], false);
598 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
600 $is_forum_thread = false;
603 if (self::isAnnounce($item) || self::isAPPost($last_id)) {
604 // Will be activated in a later step
605 $networks = Protocol::FEDERATED;
607 // For now only send to these contacts:
608 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
611 $data = ['to' => [], 'cc' => [], 'bcc' => [] , 'audience' => []];
613 if ($item['gravity'] == Item::GRAVITY_PARENT) {
614 $actor_profile = APContact::getByURL($item['owner-link']);
616 $actor_profile = APContact::getByURL($item['author-link']);
622 if ($is_forum_thread) {
623 foreach (Tag::getByURIId($item['parent-uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $term) {
624 $profile = APContact::getByURL($term['url'], false);
625 if (!empty($profile) && ($profile['type'] == 'Group')) {
626 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
628 } elseif ($term['type'] == Tag::MENTION) {
635 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
637 if ($item['private'] != Item::PRIVATE) {
638 // Directly mention the original author upon a quoted reshare.
639 // Else just ensure that the original author receives the reshare.
640 $announce = self::getAnnounceArray($item);
641 if (!empty($announce['comment'])) {
642 $data['to'][] = $announce['actor']['url'];
643 } elseif (!empty($announce)) {
644 $data['cc'][] = $announce['actor']['url'];
647 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
649 // Check if the item is completely public or unlisted
650 if ($item['private'] == Item::PUBLIC) {
651 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
653 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
656 foreach ($terms as $term) {
657 $profile = APContact::getByURL($term['url'], false);
658 if (!empty($profile)) {
659 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
661 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
662 $data['cc'][] = $profile['followers'];
663 $data['audience'][] = $profile['url'];
665 } elseif (($term['type'] == Tag::MENTION) && ($profile['type'] == 'Group')) {
668 $data['to'][] = $profile['url'];
671 if (!$exclusive && ($item['private'] == Item::UNLISTED)) {
672 $data['to'][] = $actor_profile['followers'];
675 $receiver_list = Item::enumeratePermissions($item, true, $expand_followers);
677 foreach ($terms as $term) {
678 $cid = Contact::getIdForURL($term['url'], $item['uid']);
679 if (!empty($cid) && in_array($cid, $receiver_list)) {
680 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
681 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
685 $profile = APContact::getByURL($term['url'], false);
686 if (!empty($profile)) {
687 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
689 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
690 $data['cc'][] = $profile['followers'];
691 $data['audience'][] = $profile['url'];
693 } elseif (($term['type'] == Tag::MENTION) && ($profile['type'] == 'Group')) {
696 $data['to'][] = $profile['url'];
705 if ($is_forum && !$exclusive && !empty($follower)) {
706 $data['cc'][] = $follower;
707 } elseif (!$exclusive) {
708 foreach ($receiver_list as $receiver) {
709 if ($receiver == -1) {
710 $data['to'][] = $actor_profile['followers'];
714 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
715 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
719 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
720 if ($contact['hidden'] || $always_bcc) {
721 $data['bcc'][] = $profile['url'];
723 $data['cc'][] = $profile['url'];
730 if (!empty($item['parent'])) {
731 if ($item['private'] == Item::PRIVATE) {
732 $condition = ['parent' => $item['parent'], 'uri-id' => $item['thr-parent-id']];
734 $condition = ['parent' => $item['parent']];
736 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], $condition, ['order' => ['id']]);
737 while ($parent = Post::fetch($parents)) {
738 if ($parent['gravity'] == Item::GRAVITY_PARENT) {
739 $profile = APContact::getByURL($parent['owner-link'], false);
740 if (!empty($profile)) {
741 if ($item['gravity'] != Item::GRAVITY_PARENT) {
742 // Comments to forums are directed to the forum
743 // But comments to forums aren't directed to the followers collection
744 // This rule is only valid when the actor isn't the forum.
745 // The forum needs to transmit their content to their followers.
746 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
747 $data['to'][] = $profile['url'];
749 $data['cc'][] = $profile['url'];
750 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers']) && (!$exclusive || !$is_forum_thread)) {
751 $data['cc'][] = $actor_profile['followers'];
754 } elseif (!$exclusive && !$is_forum_thread) {
755 // Public thread parent post always are directed to the followers.
756 if ($item['private'] != Item::PRIVATE) {
757 $data['cc'][] = $actor_profile['followers'];
763 // Don't include data from future posts
764 if ($parent['id'] >= $last_id) {
768 $profile = APContact::getByURL($parent['author-link'], false);
769 if (!empty($profile)) {
770 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
771 $data['to'][] = $profile['url'];
773 $data['cc'][] = $profile['url'];
777 DBA::close($parents);
780 $data['to'] = array_unique($data['to']);
781 $data['cc'] = array_unique($data['cc']);
782 $data['bcc'] = array_unique($data['bcc']);
783 $data['audience'] = array_unique($data['audience']);
785 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
786 unset($data['to'][$key]);
789 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
790 unset($data['cc'][$key]);
793 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
794 unset($data['bcc'][$key]);
797 if (($key = array_search($item['author-link'], $data['audience'])) !== false) {
798 unset($data['audience'][$key]);
801 foreach ($data['to'] as $to) {
802 if (($key = array_search($to, $data['cc'])) !== false) {
803 unset($data['cc'][$key]);
806 if (($key = array_search($to, $data['bcc'])) !== false) {
807 unset($data['bcc'][$key]);
811 foreach ($data['cc'] as $cc) {
812 if (($key = array_search($cc, $data['bcc'])) !== false) {
813 unset($data['bcc'][$key]);
817 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
819 if (!empty($data['audience'])) {
820 $receivers['audience'] = array_values($data['audience']);
821 if (count($receivers['audience']) == 1) {
822 $receivers['audience'] = $receivers['audience'][0];
827 unset($receivers['bcc']);
830 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
831 if (!empty($receivers[$element])) {
832 foreach ($receivers[$element] as $receiver) {
833 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
834 $name = Receiver::PUBLIC_COLLECTION;
836 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
838 Tag::store($item['uri-id'], $type, $name, $receiver);
847 * Check if an inbox is archived
849 * @param string $url Inbox url
850 * @return boolean "true" if inbox is archived
852 public static function archivedInbox(string $url): bool
854 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
858 * Check if a given contact should be delivered via AP
860 * @param array $contact Contact array
861 * @param array $networks Array with networks
862 * @return bool Whether the used protocol matches ACTIVITYPUB
865 private static function isAPContact(array $contact, array $networks): bool
867 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
871 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
875 * Fetches a list of inboxes of followers of a given user
877 * @param integer $uid User ID
878 * @param boolean $personal fetch personal inboxes
879 * @param boolean $all_ap Retrieve all AP enabled inboxes
880 * @return array of follower inboxes
881 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
882 * @throws \ImagickException
884 public static function fetchTargetInboxesforUser(int $uid, bool $personal = false, bool $all_ap = false): array
890 if (!empty($item['uid'])) {
891 $profile = User::getOwnerDataById($item['uid']);
892 if (!empty($profile)) {
893 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
898 // Will be activated in a later step
899 $networks = Protocol::FEDERATED;
901 // For now only send to these contacts:
902 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
910 'network' => Protocol::FEDERATED,
914 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
917 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
918 while ($contact = DBA::fetch($contacts)) {
919 if (!self::isAPContact($contact, $networks)) {
923 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
927 if (Network::isUrlBlocked($contact['url'])) {
931 $profile = APContact::getByURL($contact['url'], false);
932 if (!empty($profile)) {
933 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
934 $target = $profile['inbox'];
936 $target = $profile['sharedinbox'];
938 if (!self::archivedInbox($target)) {
939 $inboxes[$target][] = $contact['id'];
943 DBA::close($contacts);
949 * Fetches an array of inboxes for the given item and user
951 * @param array $item Item array
952 * @param integer $uid User ID
953 * @param boolean $personal fetch personal inboxes
954 * @param integer $last_id Last item id for adding receivers
955 * @return array with inboxes
956 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
957 * @throws \ImagickException
959 public static function fetchTargetInboxes(array $item, int $uid, bool $personal = false, int $last_id = 0): array
961 $permissions = self::createPermissionBlockForItem($item, true, true, $last_id);
962 if (empty($permissions)) {
968 if ($item['gravity'] == Item::GRAVITY_ACTIVITY) {
969 $item_profile = APContact::getByURL($item['author-link'], false);
971 $item_profile = APContact::getByURL($item['owner-link'], false);
974 if (empty($item_profile)) {
978 $profile_uid = User::getIdForURL($item_profile['url']);
980 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
981 if (empty($permissions[$element])) {
985 $blindcopy = in_array($element, ['bto', 'bcc']);
987 foreach ($permissions[$element] as $receiver) {
988 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
992 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
993 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
995 $profile = APContact::getByURL($receiver, false);
996 if (!empty($profile)) {
997 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
999 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
1000 $target = $profile['inbox'];
1002 $target = $profile['sharedinbox'];
1004 if (!self::archivedInbox($target)) {
1005 $inboxes[$target][] = $contact['id'] ?? 0;
1016 * Creates an array in the structure of the item table for a given mail id
1018 * @param integer $mail_id Mail id
1020 * @throws \Exception
1022 public static function getItemArrayFromMail(int $mail_id, bool $use_title = false): array
1024 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
1025 if (!DBA::isResult($mail)) {
1029 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
1030 if (!DBA::isResult($reply)) {
1034 // Making the post more compatible for Mastodon by:
1035 // - Making it a note and not an article (no title)
1036 // - Moving the title into the "summary" field that is used as a "content warning"
1039 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1040 $mail['title'] = '';
1043 $mail['content-warning'] = '';
1044 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1045 $mail['owner-id'] = $mail['author-id'];
1046 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1047 $mail['allow_gid'] = '';
1048 $mail['deny_cid'] = '';
1049 $mail['deny_gid'] = '';
1050 $mail['private'] = Item::PRIVATE;
1051 $mail['deleted'] = false;
1052 $mail['edited'] = $mail['created'];
1053 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1054 $mail['parent-uri'] = $reply['uri'];
1055 $mail['parent-uri-id'] = $reply['uri-id'];
1056 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1057 $mail['gravity'] = ($mail['reply'] ? Item::GRAVITY_COMMENT: Item::GRAVITY_PARENT);
1058 $mail['event-type'] = '';
1059 $mail['language'] = '';
1060 $mail['parent'] = 0;
1066 * Creates an activity array for a given mail id
1068 * @param integer $mail_id
1069 * @param boolean $object_mode Is the activity item is used inside another object?
1071 * @return array of activity
1072 * @throws \Exception
1074 public static function createActivityFromMail(int $mail_id, bool $object_mode = false): array
1076 $mail = self::getItemArrayFromMail($mail_id);
1080 $object = self::createNote($mail);
1082 if (!$object_mode) {
1083 $data = ['@context' => ActivityPub::CONTEXT];
1088 $data['id'] = $mail['uri'] . '/Create';
1089 $data['type'] = 'Create';
1090 $data['actor'] = $mail['author-link'];
1091 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1092 $data['instrument'] = self::getService();
1093 $data = array_merge($data, self::createPermissionBlockForItem($mail, true, false));
1095 if (empty($data['to']) && !empty($data['cc'])) {
1096 $data['to'] = $data['cc'];
1099 if (empty($data['to']) && !empty($data['bcc'])) {
1100 $data['to'] = $data['bcc'];
1104 unset($data['bcc']);
1106 $object['to'] = $data['to'];
1107 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1109 unset($object['cc']);
1110 unset($object['bcc']);
1112 $data['directMessage'] = true;
1114 $data['object'] = $object;
1116 $owner = User::getOwnerDataById($mail['uid']);
1118 if (!$object_mode && !empty($owner)) {
1119 return LDSignature::sign($data, $owner);
1126 * Returns the activity type of a given item
1128 * @param array $item Item array
1129 * @return string with activity type
1130 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1131 * @throws \ImagickException
1133 private static function getTypeOfItem(array $item): string
1137 // Only check for a reshare, if it is a real reshare and no quoted reshare
1138 if (strpos($item['body'], '[share') === 0) {
1139 $announce = self::getAnnounceArray($item);
1140 $reshared = !empty($announce);
1145 } elseif ($item['verb'] == Activity::POST) {
1146 if ($item['created'] == $item['edited']) {
1151 } elseif ($item['verb'] == Activity::LIKE) {
1153 } elseif ($item['verb'] == Activity::DISLIKE) {
1155 } elseif ($item['verb'] == Activity::ATTEND) {
1157 } elseif ($item['verb'] == Activity::ATTENDNO) {
1159 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1160 $type = 'TentativeAccept';
1161 } elseif ($item['verb'] == Activity::FOLLOW) {
1163 } elseif ($item['verb'] == Activity::TAG) {
1165 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1175 * Creates the activity or fetches it from the cache
1177 * @param integer $item_id Item id
1178 * @param boolean $force Force new cache entry
1179 * @return array|false activity or false on failure
1180 * @throws \Exception
1182 public static function createCachedActivityFromItem(int $item_id, bool $force = false, bool $object_mode = false)
1184 $cachekey = 'APDelivery:createActivity:' . $item_id . ':' . (int)$object_mode;
1187 $data = DI::cache()->get($cachekey);
1188 if (!is_null($data)) {
1193 $data = self::createActivityFromItem($item_id, $object_mode);
1195 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1200 * Creates an activity array for a given item id
1202 * @param integer $item_id
1203 * @param boolean $object_mode Is the activity item is used inside another object?
1204 * @param boolean $api_mode "true" if used for the API
1205 * @return false|array
1206 * @throws \Exception
1208 public static function createActivityFromItem(int $item_id, bool $object_mode = false, $api_mode = false)
1210 $condition = ['id' => $item_id];
1212 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
1214 Logger::info('Fetching activity', $condition);
1215 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition);
1216 if (!DBA::isResult($item)) {
1219 return self::createActivityFromArray($item, $object_mode, $api_mode);
1223 * Creates an activity array for a given URI-Id and uid
1225 * @param integer $uri_id
1226 * @param integer $uid
1227 * @param boolean $object_mode Is the activity item is used inside another object?
1228 * @param boolean $api_mode "true" if used for the API
1229 * @return false|array
1230 * @throws \Exception
1232 public static function createActivityFromUriId(int $uri_id, int $uid, bool $object_mode = false, $api_mode = false)
1234 $condition = ['uri-id' => $uri_id, 'uid' => [0, $uid]];
1236 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
1238 Logger::info('Fetching activity', $condition);
1239 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition, ['order' => ['uid' => true]]);
1240 if (!DBA::isResult($item)) {
1244 return self::createActivityFromArray($item, $object_mode, $api_mode);
1248 * Creates an activity array for a given item id
1250 * @param integer $item_id
1251 * @param boolean $object_mode Is the activity item is used inside another object?
1252 * @param boolean $api_mode "true" if used for the API
1253 * @return false|array
1254 * @throws \Exception
1256 private static function createActivityFromArray(array $item, bool $object_mode = false, $api_mode = false)
1258 if (!$api_mode && !$item['deleted'] && $item['network'] == Protocol::ACTIVITYPUB) {
1259 $data = Post\Activity::getByURIId($item['uri-id']);
1260 if (!$item['origin'] && !empty($data)) {
1261 if (!$object_mode) {
1262 Logger::info('Return stored conversation', ['item' => $item['id']]);
1264 } elseif (!empty($data['object'])) {
1265 Logger::info('Return stored conversation object', ['item' => $item['id']]);
1266 return $data['object'];
1271 if (!$api_mode && !$item['origin']) {
1272 Logger::debug('Post is not ours and is not stored', ['id' => $item['id'], 'uri-id' => $item['uri-id']]);
1276 $type = self::getTypeOfItem($item);
1278 if (!$object_mode) {
1279 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1281 if ($item['deleted'] && ($item['gravity'] == Item::GRAVITY_ACTIVITY)) {
1283 } elseif ($item['deleted']) {
1290 if ($type == 'Delete') {
1291 $data['id'] = Item::newURI($item['guid']) . '/' . $type;;
1292 } elseif (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1293 $data['id'] = $item['uri'];
1295 $data['id'] = $item['uri'] . '/' . $type;
1298 $data['type'] = $type;
1300 if (($type != 'Announce') || ($item['gravity'] != Item::GRAVITY_PARENT)) {
1301 $link = $item['author-link'];
1302 $id = $item['author-id'];
1304 $link = $item['owner-link'];
1305 $id = $item['owner-id'];
1309 $data['actor'] = self::getActorArrayByCid($id);
1311 $data['actor'] = $link;
1314 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1316 $data['instrument'] = self::getService();
1318 $data = array_merge($data, self::createPermissionBlockForItem($item, false, false));
1320 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1321 $data['object'] = self::createNote($item, $api_mode);
1322 } elseif ($data['type'] == 'Add') {
1323 $data = self::createAddTag($item, $data);
1324 } elseif ($data['type'] == 'Announce') {
1325 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1326 $data['object'] = $item['thr-parent'];
1328 $data = self::createAnnounce($item, $data, $api_mode);
1330 } elseif ($data['type'] == 'Follow') {
1331 $data['object'] = $item['parent-uri'];
1332 } elseif ($data['type'] == 'Undo') {
1333 $data['object'] = self::createActivityFromItem($item['id'], true);
1335 $data['diaspora:guid'] = $item['guid'];
1336 if (!empty($item['signed_text'])) {
1337 $data['diaspora:like'] = $item['signed_text'];
1339 $data['object'] = $item['thr-parent'];
1342 if (!empty($item['contact-uid'])) {
1343 $uid = $item['contact-uid'];
1345 $uid = $item['uid'];
1348 Logger::info('Fetched activity', ['item' => $item['id'], 'uid' => $uid]);
1350 // We only sign our own activities
1351 if (!$api_mode && !$object_mode && $item['origin']) {
1352 $owner = User::getOwnerDataById($uid);
1353 return LDSignature::sign($data, $owner);
1358 /// @todo Create "conversation" entry
1362 * Creates a location entry for a given item array
1364 * @param array $item Item array
1365 * @return array with location array
1367 private static function createLocation(array $item): array
1369 $location = ['type' => 'Place'];
1371 if (!empty($item['location'])) {
1372 $location['name'] = $item['location'];
1377 if (empty($item['coord'])) {
1378 $coord = Map::getCoordinates($item['location']);
1380 $coords = explode(' ', $item['coord']);
1381 if (count($coords) == 2) {
1382 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1386 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1387 $location['latitude'] = $coord['lat'];
1388 $location['longitude'] = $coord['lon'];
1395 * Returns a tag array for a given item array
1397 * @param array $item Item array
1398 * @param string $quote_url Url of the attached quote link
1399 * @return array of tags
1400 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1402 private static function createTagList(array $item, string $quote_url): array
1406 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1407 foreach ($terms as $term) {
1408 if ($term['type'] == Tag::HASHTAG) {
1409 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1410 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1412 $contact = Contact::getByURL($term['url'], false, ['addr']);
1413 if (empty($contact)) {
1416 if (!empty($contact['addr'])) {
1417 $mention = '@' . $contact['addr'];
1419 $mention = '@' . $term['url'];
1422 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1426 $announce = self::getAnnounceArray($item);
1427 // Mention the original author upon commented reshares
1428 if (!empty($announce['comment'])) {
1429 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1432 // @see https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-e232.md
1433 if (!empty($quote_url)) {
1434 // Currently deactivated because of compatibility issues with Pleroma
1436 // 'type' => 'Link',
1437 // 'mediaType' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
1438 // 'href' => $quote_url,
1439 // 'name' => '♲ ' . BBCode::convertForUriId($item['uri-id'], $quote_url, BBCode::ACTIVITYPUB)
1447 * Adds attachment data to the JSON document
1449 * @param array $item Data of the item that is to be posted
1451 * @return array with attachment data
1452 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1454 private static function createAttachmentList(array $item): array
1459 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1460 if (in_array($attachment['url'], $urls)) {
1463 $urls[] = $attachment['url'];
1465 $attach = ['type' => 'Document',
1466 'mediaType' => $attachment['mimetype'],
1467 'url' => $attachment['url'],
1468 'name' => $attachment['description']];
1470 if (!empty($attachment['height'])) {
1471 $attach['height'] = $attachment['height'];
1474 if (!empty($attachment['width'])) {
1475 $attach['width'] = $attachment['width'];
1478 if (!empty($attachment['preview'])) {
1479 $attach['image'] = $attachment['preview'];
1482 $attachments[] = $attach;
1485 return $attachments;
1489 * Callback function to replace a Friendica style mention in a mention for a summary
1491 * @param array $match Matching values for the callback
1492 * @return string Replaced mention
1493 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1495 private static function mentionAddrCallback(array $match): string
1497 if (empty($match[1])) {
1501 $data = Contact::getByURL($match[1], false, ['addr']);
1502 if (empty($data['addr'])) {
1506 return '@' . $data['addr'];
1510 * Remove image elements since they are added as attachment
1512 * @param string $body HTML code
1513 * @return string with removed images
1515 private static function removePictures(string $body): string
1517 return BBCode::performWithEscapedTags($body, ['code', 'noparse', 'nobb', 'pre'], function ($text) {
1518 // Simplify image codes
1519 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1520 $text = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $text);
1522 // Now remove local links
1523 $text = preg_replace_callback(
1524 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1526 // We remove the link when it is a link to a local photo page
1527 if (Photo::isLocalPage($match[1])) {
1530 // otherwise we just return the link
1531 return '[url]' . $match[1] . '[/url]';
1536 // Remove all pictures
1537 return preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $text);
1542 * Returns if the post contains sensitive content ("nsfw")
1544 * @param integer $uri_id URI id
1545 * @return boolean Whether URI id was found
1546 * @throws \Exception
1548 private static function isSensitive(int $uri_id): bool
1550 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1554 * Creates event data
1556 * @param array $item Item array
1557 * @return array with the event data
1558 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1560 private static function createEvent(array $item): array
1563 $event['name'] = $item['event-summary'];
1564 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1565 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1567 if (!$item['event-nofinish']) {
1568 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1571 if (!empty($item['event-location'])) {
1572 $item['location'] = $item['event-location'];
1573 $event['location'] = self::createLocation($item);
1576 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1577 $event['dfrn:adjust'] = true;
1583 * Creates a note/article object array
1585 * @param array $item
1586 * @param bool $api_mode
1587 * @return array with the object data
1588 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1589 * @throws \ImagickException
1591 public static function createNote(array $item, bool $api_mode = false): array
1597 // We are treating posts differently when they are directed to a community.
1598 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1599 // But to not risk compatibility issues we currently perform the changes only for communities.
1600 if ($item['gravity'] == Item::GRAVITY_PARENT) {
1601 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1602 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1603 if ($isCommunityPost && (count($links) == 1)) {
1604 $link = $links[0]['url'];
1607 $isCommunityPost = false;
1610 if ($item['event-type'] == 'event') {
1612 } elseif (!empty($item['title'])) {
1613 if (!$isCommunityPost || empty($link)) {
1616 // "Page" is used by Lemmy for posts that contain an external link
1623 if ($item['deleted']) {
1624 $type = 'Tombstone';
1628 $data['id'] = $item['uri'];
1629 $data['type'] = $type;
1631 if ($item['deleted']) {
1635 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1637 if ($item['uri'] != $item['thr-parent']) {
1638 $data['inReplyTo'] = $item['thr-parent'];
1640 $data['inReplyTo'] = null;
1643 $data['diaspora:guid'] = $item['guid'];
1644 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1646 if ($item['created'] != $item['edited']) {
1647 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1650 $data['url'] = $link ?? $item['plink'];
1652 $data['attributedTo'] = self::getActorArrayByCid($item['author-id']);
1654 $data['attributedTo'] = $item['author-link'];
1656 $data['sensitive'] = self::isSensitive($item['uri-id']);
1658 if (!empty($item['conversation']) && ($item['conversation'] != './')) {
1659 $data['conversation'] = $data['context'] = $item['conversation'];
1662 if (!empty($item['title'])) {
1663 $data['name'] = BBCode::toPlaintext($item['title'], false);
1666 $permission_block = self::createPermissionBlockForItem($item, false, false);
1668 $real_quote = false;
1670 $item = Post\Media::addHTMLAttachmentToItem($item);
1672 $body = $item['body'];
1674 if ($type == 'Note') {
1675 $body = $item['raw-body'] ?? self::removePictures($body);
1679 * @todo Improve the automated summary
1680 * This part is currently deactivated. The automated summary seems to be more
1681 * confusing than helping. But possibly we will find a better way.
1682 * So the code is left here for now as a reminder
1684 * } elseif (($type == 'Article') && empty($data['summary'])) {
1685 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1686 * $summary = preg_replace_callback($regexp, [self::class, 'mentionAddrCallback'], $body);
1687 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1691 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1692 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1695 if ($type == 'Event') {
1696 $data = array_merge($data, self::createEvent($item));
1698 if ($isCommunityPost) {
1699 // For community posts we remove the visible "!user@domain.tld".
1700 // This improves the look at systems like Lemmy.
1701 // Also in the future we should control the community delivery via other methods.
1702 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1705 if ($type == 'Page') {
1706 // When we transmit "Page" posts we have to remove the attachment.
1707 // The attachment contains the link that we already transmit in the "url" field.
1708 $body = BBCode::removeAttachment($body);
1711 $body = BBCode::setMentionsToNicknames($body);
1713 if (!empty($item['quote-uri-id'])) {
1714 if (Post::exists(['uri-id' => $item['quote-uri-id'], 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN]])) {
1716 $data['quoteUrl'] = $item['quote-uri'];
1717 $body = DI::contentItem()->addShareLink($body, $item['quote-uri-id']);
1719 $body = DI::contentItem()->addSharedPost($item, $body);
1723 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1726 // The regular "content" field does contain a minimized HTML. This is done since systems like
1727 // Mastodon has got problems with - for example - embedded pictures.
1728 // The contentMap does contain the unmodified HTML.
1729 $language = self::getLanguage($item);
1730 if (!empty($language)) {
1731 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1732 $richbody = Post\Media::removeFromEndOfBody($richbody);
1733 if (!empty($item['quote-uri-id'])) {
1735 $richbody = DI::contentItem()->addShareLink($richbody, $item['quote-uri-id']);
1737 $richbody = DI::contentItem()->addSharedPost($item, $richbody);
1740 $richbody = BBCode::replaceAttachment($richbody);
1742 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1745 if (!empty($item['quote-uri-id'])) {
1746 $source = DI::contentItem()->addSharedPost($item, $item['body']);
1748 $source = $item['body'];
1751 $data['source'] = ['content' => $source, 'mediaType' => "text/bbcode"];
1753 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1754 $data['diaspora:comment'] = $item['signed_text'];
1757 $data['attachment'] = self::createAttachmentList($item);
1758 $data['tag'] = self::createTagList($item, $data['quoteUrl'] ?? '');
1760 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1761 $data['location'] = self::createLocation($item);
1764 if (!empty($item['app'])) {
1765 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1768 $data = array_merge($data, $permission_block);
1774 * Fetches the language from the post, the user or the system.
1776 * @param array $item
1777 * @return string language string
1779 private static function getLanguage(array $item): string
1781 // Try to fetch the language from the post itself
1782 if (!empty($item['language'])) {
1783 $languages = array_keys(json_decode($item['language'], true));
1784 if (!empty($languages[0])) {
1785 return $languages[0];
1789 // Otherwise use the user's language
1790 if (!empty($item['uid'])) {
1791 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1792 if (!empty($user['language'])) {
1793 return $user['language'];
1797 // And finally just use the system language
1798 return DI::config()->get('system', 'language');
1802 * Creates an an "add tag" entry
1804 * @param array $item Item array
1805 * @param array $activity activity data
1806 * @return array with activity data for adding tags
1807 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1808 * @throws \ImagickException
1810 private static function createAddTag(array $item, array $activity): array
1812 $object = XML::parseString($item['object']);
1813 $target = XML::parseString($item['target']);
1815 $activity['diaspora:guid'] = $item['guid'];
1816 $activity['actor'] = $item['author-link'];
1817 $activity['target'] = (string)$target->id;
1818 $activity['summary'] = BBCode::toPlaintext($item['body']);
1819 $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1825 * Creates an announce object entry
1827 * @param array $item Item array
1828 * @param array $activity activity data
1829 * @param bool $api_mode
1830 * @return array with activity data
1831 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1832 * @throws \ImagickException
1834 private static function createAnnounce(array $item, array $activity, bool $api_mode = false): array
1836 $orig_body = $item['body'];
1837 $announce = self::getAnnounceArray($item);
1838 if (empty($announce)) {
1839 $activity['type'] = 'Create';
1840 $activity['object'] = self::createNote($item, $api_mode);
1844 if (empty($announce['comment'])) {
1845 // Pure announce, without a quote
1846 $activity['type'] = 'Announce';
1847 $activity['object'] = $announce['object']['uri'];
1852 $activity['type'] = 'Create';
1853 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1854 $activity['object'] = self::createNote($item, $api_mode);
1856 /// @todo Finally decide how to implement this in AP. This is a possible way:
1857 $activity['object']['attachment'][] = self::createNote($announce['object']);
1859 $activity['object']['source']['content'] = $orig_body;
1864 * Return announce related data if the item is an announce
1866 * @param array $item
1867 * @return array Announcement array
1869 private static function getAnnounceArray(array $item): array
1871 $reshared = DI::contentItem()->getSharedPost($item, Item::DELIVER_FIELDLIST);
1872 if (empty($reshared)) {
1876 if (!in_array($reshared['post']['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1880 $profile = APContact::getByURL($reshared['post']['author-link'], false);
1881 if (empty($profile)) {
1885 return ['object' => $reshared['post'], 'actor' => $profile, 'comment' => $reshared['comment']];
1889 * Checks if the provided item array is an announce
1891 * @param array $item Item array
1892 * @return boolean Whether item is an announcement
1894 public static function isAnnounce(array $item): bool
1896 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1900 $announce = self::getAnnounceArray($item);
1901 if (empty($announce)) {
1905 return empty($announce['comment']);
1909 * Creates an activity id for a given contact id
1911 * @param integer $cid Contact ID of target
1913 * @return bool|string activity id
1915 public static function activityIDFromContact(int $cid)
1917 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1918 if (!DBA::isResult($contact)) {
1922 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1923 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1924 return DI::baseUrl() . '/activity/' . $uuid;
1928 * Transmits a contact suggestion to a given inbox
1930 * @param array $owner Sender owner-view record
1931 * @param string $inbox Target inbox
1932 * @param integer $suggestion_id Suggestion ID
1933 * @return boolean was the transmission successful?
1934 * @throws \Exception
1936 public static function sendContactSuggestion(array $owner, string $inbox, int $suggestion_id): bool
1938 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1941 '@context' => ActivityPub::CONTEXT,
1942 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1943 'type' => 'Announce',
1944 'actor' => $owner['url'],
1945 'object' => $suggestion->url,
1946 'content' => $suggestion->note,
1947 'instrument' => self::getService(),
1948 'to' => [ActivityPub::PUBLIC_COLLECTION],
1952 $signed = LDSignature::sign($data, $owner);
1954 Logger::info('Deliver profile deletion for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
1955 return HTTPSignature::transmit($signed, $inbox, $owner);
1959 * Transmits a profile relocation to a given inbox
1961 * @param array $owner Sender owner-view record
1962 * @param string $inbox Target inbox
1963 * @return boolean was the transmission successful?
1964 * @throws \Exception
1966 public static function sendProfileRelocation(array $owner, string $inbox): bool
1969 '@context' => ActivityPub::CONTEXT,
1970 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1971 'type' => 'dfrn:relocate',
1972 'actor' => $owner['url'],
1973 'object' => $owner['url'],
1974 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1975 'instrument' => self::getService(),
1976 'to' => [ActivityPub::PUBLIC_COLLECTION],
1980 $signed = LDSignature::sign($data, $owner);
1982 Logger::info('Deliver profile relocation for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
1983 return HTTPSignature::transmit($signed, $inbox, $owner);
1987 * Transmits a profile deletion to a given inbox
1989 * @param array $owner Sender owner-view record
1990 * @param string $inbox Target inbox
1991 * @return boolean was the transmission successful?
1992 * @throws \Exception
1994 public static function sendProfileDeletion(array $owner, string $inbox): bool
1996 if (empty($owner['uprvkey'])) {
1997 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $owner['uid']]);
2001 $data = ['@context' => ActivityPub::CONTEXT,
2002 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2004 'actor' => $owner['url'],
2005 'object' => $owner['url'],
2006 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2007 'instrument' => self::getService(),
2008 'to' => [ActivityPub::PUBLIC_COLLECTION],
2011 $signed = LDSignature::sign($data, $owner);
2013 Logger::info('Deliver profile deletion for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2014 return HTTPSignature::transmit($signed, $inbox, $owner);
2018 * Transmits a profile change to a given inbox
2020 * @param array $owner Sender owner-view record
2021 * @param string $inbox Target inbox
2022 * @return boolean was the transmission successful?
2023 * @throws HTTPException\InternalServerErrorException
2024 * @throws HTTPException\NotFoundException
2025 * @throws \ImagickException
2027 public static function sendProfileUpdate(array $owner, string $inbox): bool
2029 $profile = APContact::getByURL($owner['url']);
2031 $data = ['@context' => ActivityPub::CONTEXT,
2032 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2034 'actor' => $owner['url'],
2035 'object' => self::getProfile($owner['uid']),
2036 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2037 'instrument' => self::getService(),
2038 'to' => [$profile['followers']],
2041 $signed = LDSignature::sign($data, $owner);
2043 Logger::info('Deliver profile update for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2044 return HTTPSignature::transmit($signed, $inbox, $owner);
2048 * Transmits a given activity to a target
2050 * @param string $activity Type name
2051 * @param string $target Target profile
2052 * @param integer $uid User ID
2053 * @param string $id Activity-identifier
2055 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2056 * @throws \ImagickException
2057 * @throws \Exception
2059 public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2061 $profile = APContact::getByURL($target);
2062 if (empty($profile['inbox'])) {
2063 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2067 $owner = User::getOwnerDataById($uid);
2068 if (empty($owner)) {
2069 Logger::warning('No user found for actor, aborting', ['uid' => $uid]);
2074 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2078 '@context' => ActivityPub::CONTEXT,
2080 'type' => $activity,
2081 'actor' => $owner['url'],
2082 'object' => $profile['url'],
2083 'instrument' => self::getService(),
2084 'to' => [$profile['url']],
2087 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2089 $signed = LDSignature::sign($data, $owner);
2090 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2094 * Transmits a "follow object" activity to a target
2095 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2097 * @param string $object Object URL
2098 * @param string $target Target profile
2099 * @param integer $uid User ID
2101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2102 * @throws \ImagickException
2103 * @throws \Exception
2105 public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2107 $profile = APContact::getByURL($target);
2108 if (empty($profile['inbox'])) {
2109 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2114 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2115 $admin = User::getFirstAdmin(['uid']);
2117 Logger::warning('No available admin user for transmission', ['target' => $target]);
2121 $uid = $admin['uid'];
2124 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2125 'author-id' => Contact::getPublicIdByUserId($uid)];
2126 if (Post::exists($condition)) {
2127 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2131 $owner = User::getOwnerDataById($uid);
2134 '@context' => ActivityPub::CONTEXT,
2135 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2137 'actor' => $owner['url'],
2138 'object' => $object,
2139 'instrument' => self::getService(),
2140 'to' => [$profile['url']],
2143 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2145 $signed = LDSignature::sign($data, $owner);
2146 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2150 * Transmit a message that the contact request had been accepted
2152 * @param string $target Target profile
2153 * @param string $id Object id
2154 * @param integer $uid User ID
2156 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2157 * @throws \ImagickException
2159 public static function sendContactAccept(string $target, string $id, int $uid)
2161 $profile = APContact::getByURL($target);
2162 if (empty($profile['inbox'])) {
2163 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2167 $owner = User::getOwnerDataById($uid);
2169 Logger::notice('No user found for actor', ['uid' => $uid]);
2174 '@context' => ActivityPub::CONTEXT,
2175 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2177 'actor' => $owner['url'],
2181 'actor' => $profile['url'],
2182 'object' => $owner['url']
2184 'instrument' => self::getService(),
2185 'to' => [$profile['url']],
2188 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2190 $signed = LDSignature::sign($data, $owner);
2191 HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2195 * Reject a contact request or terminates the contact relation
2197 * @param string $target Target profile
2198 * @param string $objectId Object id
2199 * @param array $owner Sender owner-view record
2200 * @return bool Operation success
2201 * @throws HTTPException\InternalServerErrorException
2202 * @throws \ImagickException
2204 public static function sendContactReject(string $target, string $objectId, array $owner): bool
2206 $profile = APContact::getByURL($target);
2207 if (empty($profile['inbox'])) {
2208 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2213 '@context' => ActivityPub::CONTEXT,
2214 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2216 'actor' => $owner['url'],
2220 'actor' => $profile['url'],
2221 'object' => $owner['url']
2223 'instrument' => self::getService(),
2224 'to' => [$profile['url']],
2227 Logger::debug('Sending reject to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId);
2229 $signed = LDSignature::sign($data, $owner);
2230 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2234 * Transmits a message that we don't want to follow this contact anymore
2236 * @param string $target Target profile
2237 * @param integer $cid Contact id
2238 * @param array $owner Sender owner-view record
2239 * @return bool success
2240 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2241 * @throws \ImagickException
2242 * @throws \Exception
2244 public static function sendContactUndo(string $target, int $cid, array $owner): bool
2246 $profile = APContact::getByURL($target);
2247 if (empty($profile['inbox'])) {
2248 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2252 $object_id = self::activityIDFromContact($cid);
2253 if (empty($object_id)) {
2257 $objectId = DI::baseUrl() . '/activity/' . System::createGUID();
2260 '@context' => ActivityPub::CONTEXT,
2263 'actor' => $owner['url'],
2267 'actor' => $owner['url'],
2268 'object' => $profile['url']
2270 'instrument' => self::getService(),
2271 'to' => [$profile['url']],
2274 Logger::info('Sending undo to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId);
2276 $signed = LDSignature::sign($data, $owner);
2277 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2281 * Prepends mentions (@) to $body variable
2283 * @param string $body HTML code
2285 * @param string $authorLink Author link
2286 * @return string HTML code with prepended mentions
2288 private static function prependMentions(string $body, int $uriid, string $authorLink): string
2292 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2293 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2294 if (!empty($profile['addr'])
2295 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2296 && !strstr($body, $profile['addr'])
2297 && !strstr($body, $tag['url'])
2298 && $tag['url'] !== $authorLink
2300 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2304 $mentions[] = $body;
2306 return implode(' ', $mentions);