3 * @copyright Copyright (C) 2010-2022, 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;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Core\Cache\Enum\Duration;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Database\DBA;
32 use Friendica\Model\APContact;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Conversation;
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:';
63 const CACHEKEY_OUTBOX = 'transmitter:getOutbox:';
66 * Add relay servers to the list of inboxes
68 * @param array $inboxes
69 * @return array inboxes with added relay servers
71 public static function addRelayServerInboxes(array $inboxes = []): array
73 foreach (Relay::getList(['inbox']) as $contact) {
74 $inboxes[$contact['inbox']] = $contact['inbox'];
81 * Add relay servers to the list of inboxes
83 * @param array $inboxes
84 * @return array inboxes with added relay servers
86 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = []): array
88 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
93 $relays = Relay::getDirectRelayList($item_id);
98 foreach ($relays as $relay) {
99 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
100 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
106 * Subscribe to a relay and updates contact on success
108 * @param string $url Subscribe actor url
109 * @return bool success
111 public static function sendRelayFollow(string $url): bool
113 $contact = Contact::getByURL($url);
114 if (empty($contact)) {
118 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
119 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
121 Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]);
128 * Unsubscribe from a relay and updates contact on success or forced
130 * @param string $url Subscribe actor url
131 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
132 * @return bool success
134 public static function sendRelayUndoFollow(string $url, bool $force = false): bool
136 $contact = Contact::getByURL($url);
137 if (empty($contact)) {
141 $success = self::sendContactUndo($url, $contact['id'], 0);
143 if ($success || $force) {
144 Contact::update(['rel' => Contact::NOTHING], ['id' => $contact['id']]);
151 * Collects a list of contacts of the given owner
153 * @param array $owner Owner array
154 * @param array $rel The relevant value(s) contact.rel should match
155 * @param string $module The name of the relevant AP endpoint module (followers|following)
156 * @param integer $page Page number
157 * @param string $requester URL of the requester
158 * @param boolean $nocache Wether to bypass caching
159 * @return array of owners
162 public static function getContacts(array $owner, array $rel, string $module, int $page = null, string $requester = null, bool $nocache = false): array
165 $cachekey = self::CACHEKEY_CONTACTS . $module . ':'. $owner['uid'];
166 $result = DI::cache()->get($cachekey);
167 if (!$nocache && !is_null($result)) {
174 'uid' => $owner['uid'],
183 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
185 $total = DBA::count('contact', $condition);
187 $modulePath = '/' . $module . '/';
189 $data = ['@context' => ActivityPub::CONTEXT];
190 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
191 $data['type'] = 'OrderedCollection';
192 $data['totalItems'] = $total;
195 $data['id'] .= '?' . http_build_query(['page' => $page]);
198 // When we hide our friends we will only show the pure number but don't allow more.
199 $show_contacts = empty($owner['hide-friends']);
201 // Allow fetching the contact list when the requester is part of the list.
202 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
203 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
206 if (!$show_contacts) {
207 if (!empty($cachekey)) {
208 DI::cache()->set($cachekey, $data, Duration::DAY);
215 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
217 $data['type'] = 'OrderedCollectionPage';
220 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
221 while ($contact = DBA::fetch($contacts)) {
222 $list[] = $contact['url'];
224 DBA::close($contacts);
226 if (count($list) == 100) {
227 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
230 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
232 $data['orderedItems'] = $list;
235 if (!empty($cachekey)) {
236 DI::cache()->set($cachekey, $data, Duration::DAY);
243 * Public posts for the given owner
245 * @param array $owner Owner array
246 * @param integer $page Page number
247 * @param string $requester URL of requesting account
248 * @param boolean $nocache Wether to bypass caching
249 * @return array of posts
250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
251 * @throws \ImagickException
253 public static function getOutbox(array $owner, int $page = null, string $requester = '', bool $nocache = false): array
256 $cachekey = self::CACHEKEY_OUTBOX . $owner['uid'];
257 $result = DI::cache()->get($cachekey);
258 if (!$nocache && !is_null($result)) {
263 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
265 if (!empty($requester)) {
266 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
267 if (!empty($requester_id)) {
268 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
269 if (!empty($permissionSets)) {
270 $condition = ['psid' => array_merge($permissionSets->column('id'),
271 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
276 $condition = array_merge($condition, [
277 'uid' => $owner['uid'],
278 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
279 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
280 'network' => Protocol::FEDERATED,
281 'parent-network' => Protocol::FEDERATED,
287 $count = Post::count($condition);
289 $data = ['@context' => ActivityPub::CONTEXT];
290 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
291 $data['type'] = 'OrderedCollection';
292 $data['totalItems'] = $count;
295 $data['id'] .= '?' . http_build_query(['page' => $page]);
299 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
301 $data['type'] = 'OrderedCollectionPage';
304 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
305 while ($item = Post::fetch($items)) {
306 $activity = self::createActivityFromItem($item['id'], true);
307 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
309 // Only list "Create" activity objects here, no reshares
310 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
311 $list[] = $activity['object'];
316 if (count($list) == 20) {
317 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
320 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
322 $data['orderedItems'] = $list;
325 if (!empty($cachekey)) {
326 DI::cache()->set($cachekey, $data, Duration::DAY);
333 * Public posts for the given owner
335 * @param array $owner Owner array
336 * @param integer $page Page number
337 * @param boolean $nocache Wether to bypass caching
339 * @return array of posts
340 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
341 * @throws \ImagickException
343 public static function getFeatured(array $owner, int $page = null, bool $nocache = false): array
346 $cachekey = self::CACHEKEY_FEATURED . $owner['uid'];
347 $result = DI::cache()->get($cachekey);
348 if (!$nocache && !is_null($result)) {
353 $owner_cid = Contact::getIdForURL($owner['url'], 0, false);
355 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
356 $owner_cid, Post\Collection::FEATURED];
358 $condition = DBA::mergeConditions($condition, [
359 'uid' => $owner['uid'],
360 'author-id' => $owner_cid,
361 'private' => [Item::PUBLIC, Item::UNLISTED],
362 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
363 'network' => Protocol::FEDERATED,
364 'parent-network' => Protocol::FEDERATED,
370 $count = Post::count($condition);
372 $data = ['@context' => ActivityPub::CONTEXT];
373 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
374 $data['type'] = 'OrderedCollection';
375 $data['totalItems'] = $count;
378 $data['id'] .= '?' . http_build_query(['page' => $page]);
382 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
384 $data['type'] = 'OrderedCollectionPage';
385 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
389 while ($item = Post::fetch($items)) {
390 $activity = self::createActivityFromItem($item['id'], true);
391 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
393 // Only list "Create" activity objects here, no reshares
394 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
395 $list[] = $activity['object'];
400 if (count($list) == 20) {
401 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
405 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
408 $data['orderedItems'] = $list;
410 if (!empty($cachekey)) {
411 DI::cache()->set($cachekey, $data, Duration::DAY);
418 * Return the service array containing information the used software and it's url
420 * @return array with service data
422 private static function getService(): array
426 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
427 'url' => DI::baseUrl()->get()
432 * Return the ActivityPub profile of the given user
434 * @param int $uid User ID
435 * @return array with profile data
436 * @throws HTTPException\NotFoundException
437 * @throws HTTPException\InternalServerErrorException
439 public static function getProfile(int $uid): array
441 $owner = User::getOwnerDataById($uid);
442 if (!isset($owner['id'])) {
443 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
444 throw new HTTPException\NotFoundException('User not found.');
447 $data = ['@context' => ActivityPub::CONTEXT];
448 $data['id'] = $owner['url'];
450 if (!empty($owner['guid'])) {
451 $data['diaspora:guid'] = $owner['guid'];
454 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
457 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
458 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
459 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
460 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
461 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
463 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
466 $data['preferredUsername'] = $owner['nick'];
467 $data['name'] = $owner['name'];
469 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
470 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
471 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
474 if (!empty($owner['about'])) {
475 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
478 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
479 $data['vcard:hasInstantMessage'] = [];
481 if (!empty($owner['xmpp'])) {
482 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
484 if (!empty($owner['matrix'])) {
485 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
489 $data['url'] = $owner['url'];
490 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
491 $data['discoverable'] = (bool)$owner['net-publish'];
492 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
493 'owner' => $owner['url'],
494 'publicKeyPem' => $owner['pubkey']];
495 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
496 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
498 $resourceid = Photo::ridFromURI($owner['photo']);
499 if (!empty($resourceid)) {
500 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
501 if (!empty($photo['type'])) {
502 $data['icon']['mediaType'] = $photo['type'];
506 if (!empty($owner['header'])) {
507 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
509 $resourceid = Photo::ridFromURI($owner['header']);
510 if (!empty($resourceid)) {
511 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
512 if (!empty($photo['type'])) {
513 $data['image']['mediaType'] = $photo['type'];
520 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
522 'type' => 'PropertyValue',
523 'name' => $profile_field->label,
524 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
528 if (!empty($custom_fields)) {
529 $data['attachment'] = $custom_fields;
532 $data['generator'] = self::getService();
534 // tags: https://kitty.town/@inmysocks/100656097926961126.json
539 * @param string $username
541 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
543 public static function getDeletedUser(string $username): array
546 '@context' => ActivityPub::CONTEXT,
547 'id' => DI::baseUrl() . '/profile/' . $username,
548 'type' => 'Tombstone',
549 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
550 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
551 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
556 * Returns an array with permissions of the thread parent of the given item array
559 * @param bool $is_forum_thread
561 * @return array with permissions
562 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
563 * @throws \ImagickException
565 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread): array
567 if (empty($item['thr-parent-id'])) {
571 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
572 if (empty($parent)) {
577 'to' => [$parent['author-link']],
583 $parent_profile = APContact::getByURL($parent['author-link']);
585 $item_profile = APContact::getByURL($item['author-link']);
586 $exclude[] = $item['author-link'];
588 if ($item['gravity'] == GRAVITY_PARENT) {
589 $exclude[] = $item['owner-link'];
592 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
593 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
594 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
595 if (!$is_forum_thread) {
596 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
598 } elseif (!in_array($receiver['url'], $exclude)) {
599 $permissions[$type[$receiver['type']]][] = $receiver['url'];
607 * Check if the given item id is from ActivityPub
609 * @param integer $item_id
610 * @return boolean "true" if the post is from ActivityPub
612 private static function isAPPost(int $item_id): bool
614 if (empty($item_id)) {
618 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
622 * Creates an array of permissions from an item thread
624 * @param array $item Item array
625 * @param boolean $blindcopy addressing via "bcc" or "cc"?
626 * @param integer $last_id Last item id for adding receivers
628 * @return array with permission data
629 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
630 * @throws \ImagickException
632 private static function createPermissionBlockForItem(array $item, bool $blindcopy, int $last_id = 0): array
635 $last_id = $item['id'];
642 // Check if we should always deliver our stuff via BCC
643 if (!empty($item['uid'])) {
644 $owner = User::getOwnerDataById($item['uid']);
645 if (!empty($owner)) {
646 $always_bcc = $owner['hide-friends'];
647 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
649 $profile = APContact::getByURL($owner['url'], false);
650 $follower = $profile['followers'] ?? '';
654 if (DI::config()->get('system', 'ap_always_bcc')) {
658 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
659 if (($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
660 $profile = APContact::getByURL($parent['causer-link'], false);
661 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
663 $is_forum_thread = false;
666 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
667 // Will be activated in a later step
668 $networks = Protocol::FEDERATED;
670 // For now only send to these contacts:
671 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
674 $data = ['to' => [], 'cc' => [], 'bcc' => []];
676 if ($item['gravity'] == GRAVITY_PARENT) {
677 $actor_profile = APContact::getByURL($item['owner-link']);
679 $actor_profile = APContact::getByURL($item['author-link']);
684 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
686 if ($item['private'] != Item::PRIVATE) {
687 // Directly mention the original author upon a quoted reshare.
688 // Else just ensure that the original author receives the reshare.
689 $announce = self::getAnnounceArray($item);
690 if (!empty($announce['comment'])) {
691 $data['to'][] = $announce['actor']['url'];
692 } elseif (!empty($announce)) {
693 $data['cc'][] = $announce['actor']['url'];
696 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
698 // Check if the item is completely public or unlisted
699 if ($item['private'] == Item::PUBLIC) {
700 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
702 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
705 foreach ($terms as $term) {
706 $profile = APContact::getByURL($term['url'], false);
707 if (!empty($profile)) {
708 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
710 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
711 $data['cc'][] = $profile['followers'];
714 $data['to'][] = $profile['url'];
718 $receiver_list = Item::enumeratePermissions($item, true);
720 foreach ($terms as $term) {
721 $cid = Contact::getIdForURL($term['url'], $item['uid']);
722 if (!empty($cid) && in_array($cid, $receiver_list)) {
723 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
724 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
728 $profile = APContact::getByURL($term['url'], false);
729 if (!empty($profile)) {
730 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
732 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
733 $data['cc'][] = $profile['followers'];
736 $data['to'][] = $profile['url'];
741 if ($is_forum && !$exclusive && !empty($follower)) {
742 $data['cc'][] = $follower;
743 } elseif (!$exclusive) {
744 foreach ($receiver_list as $receiver) {
745 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
746 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
750 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
751 if ($contact['hidden'] || $always_bcc) {
752 $data['bcc'][] = $profile['url'];
754 $data['cc'][] = $profile['url'];
761 if (!empty($item['parent'])) {
762 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']], ['order' => ['id']]);
763 while ($parent = Post::fetch($parents)) {
764 if ($parent['gravity'] == GRAVITY_PARENT) {
765 $profile = APContact::getByURL($parent['owner-link'], false);
766 if (!empty($profile)) {
767 if ($item['gravity'] != GRAVITY_PARENT) {
768 // Comments to forums are directed to the forum
769 // But comments to forums aren't directed to the followers collection
770 // This rule is only valid when the actor isn't the forum.
771 // The forum needs to transmit their content to their followers.
772 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
773 $data['to'][] = $profile['url'];
775 $data['cc'][] = $profile['url'];
776 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])&& !$is_forum_thread) {
777 $data['cc'][] = $actor_profile['followers'];
780 } elseif (!$exclusive && !$is_forum_thread) {
781 // Public thread parent post always are directed to the followers.
782 if ($item['private'] != Item::PRIVATE) {
783 $data['cc'][] = $actor_profile['followers'];
789 // Don't include data from future posts
790 if ($parent['id'] >= $last_id) {
794 $profile = APContact::getByURL($parent['author-link'], false);
795 if (!empty($profile)) {
796 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
797 $data['to'][] = $profile['url'];
799 $data['cc'][] = $profile['url'];
803 DBA::close($parents);
806 $data['to'] = array_unique($data['to']);
807 $data['cc'] = array_unique($data['cc']);
808 $data['bcc'] = array_unique($data['bcc']);
810 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
811 unset($data['to'][$key]);
814 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
815 unset($data['cc'][$key]);
818 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
819 unset($data['bcc'][$key]);
822 foreach ($data['to'] as $to) {
823 if (($key = array_search($to, $data['cc'])) !== false) {
824 unset($data['cc'][$key]);
827 if (($key = array_search($to, $data['bcc'])) !== false) {
828 unset($data['bcc'][$key]);
832 foreach ($data['cc'] as $cc) {
833 if (($key = array_search($cc, $data['bcc'])) !== false) {
834 unset($data['bcc'][$key]);
838 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
841 unset($receivers['bcc']);
844 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
845 if (!empty($receivers[$element])) {
846 foreach ($receivers[$element] as $receiver) {
847 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
848 $name = Receiver::PUBLIC_COLLECTION;
850 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
852 Tag::store($item['uri-id'], $type, $name, $receiver);
861 * Check if an inbox is archived
863 * @param string $url Inbox url
864 * @return boolean "true" if inbox is archived
866 public static function archivedInbox(string $url): bool
868 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
872 * Check if a given contact should be delivered via AP
874 * @param array $contact Contact array
875 * @param array $networks Array with networks
876 * @return bool Whether the used protocol matches ACTIVITYPUB
879 private static function isAPContact(array $contact, array $networks): bool
881 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
885 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
889 * Fetches a list of inboxes of followers of a given user
891 * @param integer $uid User ID
892 * @param boolean $personal fetch personal inboxes
893 * @param boolean $all_ap Retrieve all AP enabled inboxes
894 * @return array of follower inboxes
895 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
896 * @throws \ImagickException
898 public static function fetchTargetInboxesforUser(int $uid, bool $personal = false, bool $all_ap = false): array
904 if (!empty($item['uid'])) {
905 $profile = User::getOwnerDataById($item['uid']);
906 if (!empty($profile)) {
907 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
911 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
912 // Will be activated in a later step
913 $networks = Protocol::FEDERATED;
915 // For now only send to these contacts:
916 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
924 'network' => Protocol::FEDERATED,
928 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
931 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
932 while ($contact = DBA::fetch($contacts)) {
933 if (!self::isAPContact($contact, $networks)) {
937 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
941 if (Network::isUrlBlocked($contact['url'])) {
945 $profile = APContact::getByURL($contact['url'], false);
946 if (!empty($profile)) {
947 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
948 $target = $profile['inbox'];
950 $target = $profile['sharedinbox'];
952 if (!self::archivedInbox($target)) {
953 $inboxes[$target][] = $contact['id'];
957 DBA::close($contacts);
963 * Fetches an array of inboxes for the given item and user
965 * @param array $item Item array
966 * @param integer $uid User ID
967 * @param boolean $personal fetch personal inboxes
968 * @param integer $last_id Last item id for adding receivers
969 * @return array with inboxes
970 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
971 * @throws \ImagickException
973 public static function fetchTargetInboxes(array $item, int $uid, bool $personal = false, int $last_id = 0): array
975 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
976 if (empty($permissions)) {
982 if ($item['gravity'] == GRAVITY_ACTIVITY) {
983 $item_profile = APContact::getByURL($item['author-link'], false);
985 $item_profile = APContact::getByURL($item['owner-link'], false);
988 if (empty($item_profile)) {
992 $profile_uid = User::getIdForURL($item_profile['url']);
994 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
995 if (empty($permissions[$element])) {
999 $blindcopy = in_array($element, ['bto', 'bcc']);
1001 foreach ($permissions[$element] as $receiver) {
1002 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
1006 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
1007 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
1009 $profile = APContact::getByURL($receiver, false);
1010 if (!empty($profile)) {
1011 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
1013 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
1014 $target = $profile['inbox'];
1016 $target = $profile['sharedinbox'];
1018 if (!self::archivedInbox($target)) {
1019 $inboxes[$target][] = $contact['id'] ?? 0;
1030 * Creates an array in the structure of the item table for a given mail id
1032 * @param integer $mail_id Mail id
1034 * @throws \Exception
1036 public static function getItemArrayFromMail(int $mail_id, bool $use_title = false): array
1038 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
1039 if (!DBA::isResult($mail)) {
1043 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
1044 if (!DBA::isResult($reply)) {
1048 // Making the post more compatible for Mastodon by:
1049 // - Making it a note and not an article (no title)
1050 // - Moving the title into the "summary" field that is used as a "content warning"
1053 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1054 $mail['title'] = '';
1057 $mail['content-warning'] = '';
1058 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1059 $mail['owner-id'] = $mail['author-id'];
1060 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1061 $mail['allow_gid'] = '';
1062 $mail['deny_cid'] = '';
1063 $mail['deny_gid'] = '';
1064 $mail['private'] = Item::PRIVATE;
1065 $mail['deleted'] = false;
1066 $mail['edited'] = $mail['created'];
1067 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1068 $mail['parent-uri'] = $reply['uri'];
1069 $mail['parent-uri-id'] = $reply['uri-id'];
1070 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1071 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
1072 $mail['event-type'] = '';
1073 $mail['language'] = '';
1074 $mail['parent'] = 0;
1080 * Creates an activity array for a given mail id
1082 * @param integer $mail_id
1083 * @param boolean $object_mode Is the activity item is used inside another object?
1085 * @return array of activity
1086 * @throws \Exception
1088 public static function createActivityFromMail(int $mail_id, bool $object_mode = false): array
1090 $mail = self::getItemArrayFromMail($mail_id);
1094 $object = self::createNote($mail);
1096 if (!$object_mode) {
1097 $data = ['@context' => ActivityPub::CONTEXT];
1102 $data['id'] = $mail['uri'] . '/Create';
1103 $data['type'] = 'Create';
1104 $data['actor'] = $mail['author-link'];
1105 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1106 $data['instrument'] = self::getService();
1107 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1109 if (empty($data['to']) && !empty($data['cc'])) {
1110 $data['to'] = $data['cc'];
1113 if (empty($data['to']) && !empty($data['bcc'])) {
1114 $data['to'] = $data['bcc'];
1118 unset($data['bcc']);
1120 $object['to'] = $data['to'];
1121 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1123 unset($object['cc']);
1124 unset($object['bcc']);
1126 $data['directMessage'] = true;
1128 $data['object'] = $object;
1130 $owner = User::getOwnerDataById($mail['uid']);
1132 if (!$object_mode && !empty($owner)) {
1133 return LDSignature::sign($data, $owner);
1140 * Returns the activity type of a given item
1142 * @param array $item Item array
1143 * @return string with activity type
1144 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1145 * @throws \ImagickException
1147 private static function getTypeOfItem(array $item): string
1151 // Only check for a reshare, if it is a real reshare and no quoted reshare
1152 if (strpos($item['body'], '[share') === 0) {
1153 $announce = self::getAnnounceArray($item);
1154 $reshared = !empty($announce);
1159 } elseif ($item['verb'] == Activity::POST) {
1160 if ($item['created'] == $item['edited']) {
1165 } elseif ($item['verb'] == Activity::LIKE) {
1167 } elseif ($item['verb'] == Activity::DISLIKE) {
1169 } elseif ($item['verb'] == Activity::ATTEND) {
1171 } elseif ($item['verb'] == Activity::ATTENDNO) {
1173 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1174 $type = 'TentativeAccept';
1175 } elseif ($item['verb'] == Activity::FOLLOW) {
1177 } elseif ($item['verb'] == Activity::TAG) {
1179 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1189 * Creates the activity or fetches it from the cache
1191 * @param integer $item_id Item id
1192 * @param boolean $force Force new cache entry
1193 * @return array|false activity or false on failure
1194 * @throws \Exception
1196 public static function createCachedActivityFromItem(int $item_id, bool $force = false)
1198 $cachekey = 'APDelivery:createActivity:' . $item_id;
1201 $data = DI::cache()->get($cachekey);
1202 if (!is_null($data)) {
1207 $data = self::createActivityFromItem($item_id);
1209 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1214 * Creates an activity array for a given item id
1216 * @param integer $item_id
1217 * @param boolean $object_mode Is the activity item is used inside another object?
1218 * @return false|array
1219 * @throws \Exception
1221 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1223 Logger::info('Fetching activity', ['item' => $item_id]);
1224 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1225 if (!DBA::isResult($item)) {
1229 if (empty($item['uri-id'])) {
1230 Logger::warning('Item without uri-id', ['item' => $item]);
1234 if (!$item['deleted']) {
1235 $data = Post\Activity::getByURIId($item['uri-id']);
1236 if (!$item['origin'] && !empty($data)) {
1237 if (!empty($data['type'])) {
1238 if (in_array($data['type'], ['Create', 'Update'])) {
1240 unset($data['@context']);
1241 unset($data['signature']);
1243 Logger::info('Return stored conversation', ['item' => $item_id]);
1245 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1246 if (!empty($data['@context'])) {
1247 $context = $data['@context'];
1248 unset($data['@context']);
1250 unset($data['actor']);
1257 $type = self::getTypeOfItem($item);
1259 if (!$object_mode) {
1260 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1262 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1264 } elseif ($item['deleted']) {
1271 if ($type == 'Delete') {
1272 $data['id'] = Item::newURI($item['guid']) . '/' . $type;;
1273 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1274 $data['id'] = $item['uri'];
1276 $data['id'] = $item['uri'] . '/' . $type;
1279 $data['type'] = $type;
1281 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1282 $data['actor'] = $item['author-link'];
1284 $data['actor'] = $item['owner-link'];
1287 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1289 $data['instrument'] = self::getService();
1291 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1293 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1294 $data['object'] = $object ?? self::createNote($item);
1295 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1296 } elseif ($data['type'] == 'Add') {
1297 $data = self::createAddTag($item, $data);
1298 } elseif ($data['type'] == 'Announce') {
1299 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1300 $data['object'] = $item['thr-parent'];
1302 $data = self::createAnnounce($item, $data);
1304 } elseif ($data['type'] == 'Follow') {
1305 $data['object'] = $item['parent-uri'];
1306 } elseif ($data['type'] == 'Undo') {
1307 $data['object'] = self::createActivityFromItem($item_id, true);
1309 $data['diaspora:guid'] = $item['guid'];
1310 if (!empty($item['signed_text'])) {
1311 $data['diaspora:like'] = $item['signed_text'];
1313 $data['object'] = $item['thr-parent'];
1316 if (!empty($item['contact-uid'])) {
1317 $uid = $item['contact-uid'];
1319 $uid = $item['uid'];
1322 $owner = User::getOwnerDataById($uid);
1324 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1326 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1327 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1328 return LDSignature::sign($data, $owner);
1333 /// @todo Create "conversation" entry
1337 * Creates a location entry for a given item array
1339 * @param array $item Item array
1340 * @return array with location array
1342 private static function createLocation(array $item): array
1344 $location = ['type' => 'Place'];
1346 if (!empty($item['location'])) {
1347 $location['name'] = $item['location'];
1352 if (empty($item['coord'])) {
1353 $coord = Map::getCoordinates($item['location']);
1355 $coords = explode(' ', $item['coord']);
1356 if (count($coords) == 2) {
1357 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1361 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1362 $location['latitude'] = $coord['lat'];
1363 $location['longitude'] = $coord['lon'];
1370 * Returns a tag array for a given item array
1372 * @param array $item Item array
1373 * @return array of tags
1374 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1376 private static function createTagList(array $item): array
1380 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1381 foreach ($terms as $term) {
1382 if ($term['type'] == Tag::HASHTAG) {
1383 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1384 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1386 $contact = Contact::getByURL($term['url'], false, ['addr']);
1387 if (empty($contact)) {
1390 if (!empty($contact['addr'])) {
1391 $mention = '@' . $contact['addr'];
1393 $mention = '@' . $term['url'];
1396 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1400 $announce = self::getAnnounceArray($item);
1401 // Mention the original author upon commented reshares
1402 if (!empty($announce['comment'])) {
1403 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1410 * Adds attachment data to the JSON document
1412 * @param array $item Data of the item that is to be posted
1413 * @param string $type Object type
1415 * @return array with attachment data
1416 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1418 private static function createAttachmentList(array $item, string $type): array
1422 $uriids = [$item['uri-id']];
1423 $shared = BBCode::fetchShareAttributes($item['body']);
1424 if (!empty($shared['guid'])) {
1425 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1426 if (!empty($shared_item['uri-id'])) {
1427 $uriids[] = $shared_item['uri-id'];
1432 foreach ($uriids as $uriid) {
1433 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1434 if (in_array($attachment['url'], $urls)) {
1437 $urls[] = $attachment['url'];
1439 $attach = ['type' => 'Document',
1440 'mediaType' => $attachment['mimetype'],
1441 'url' => $attachment['url'],
1442 'name' => $attachment['description']];
1444 if (!empty($attachment['height'])) {
1445 $attach['height'] = $attachment['height'];
1448 if (!empty($attachment['width'])) {
1449 $attach['width'] = $attachment['width'];
1452 if (!empty($attachment['preview'])) {
1453 $attach['image'] = $attachment['preview'];
1456 $attachments[] = $attach;
1460 return $attachments;
1464 * Callback function to replace a Friendica style mention in a mention for a summary
1466 * @param array $match Matching values for the callback
1467 * @return string Replaced mention
1468 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1470 private static function mentionAddrCallback(array $match): string
1472 if (empty($match[1])) {
1476 $data = Contact::getByURL($match[1], false, ['addr']);
1477 if (empty($data['addr'])) {
1481 return '@' . $data['addr'];
1485 * Remove image elements since they are added as attachment
1487 * @param string $body HTML code
1488 * @return string with removed images
1490 private static function removePictures(string $body): string
1492 // Simplify image codes
1493 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1494 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1496 // Now remove local links
1497 $body = preg_replace_callback(
1498 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1500 // We remove the link when it is a link to a local photo page
1501 if (Photo::isLocalPage($match[1])) {
1504 // otherwise we just return the link
1505 return '[url]' . $match[1] . '[/url]';
1510 // Remove all pictures
1511 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1517 * Returns if the post contains sensitive content ("nsfw")
1519 * @param integer $uri_id URI id
1520 * @return boolean Whether URI id was found
1521 * @throws \Exception
1523 private static function isSensitive(int $uri_id): bool
1525 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1529 * Creates event data
1531 * @param array $item Item array
1532 * @return array with the event data
1533 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1535 private static function createEvent(array $item): array
1538 $event['name'] = $item['event-summary'];
1539 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1540 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1542 if (!$item['event-nofinish']) {
1543 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1546 if (!empty($item['event-location'])) {
1547 $item['location'] = $item['event-location'];
1548 $event['location'] = self::createLocation($item);
1551 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1552 $event['dfrn:adjust'] = true;
1558 * Creates a note/article object array
1560 * @param array $item
1561 * @return array with the object data
1562 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1563 * @throws \ImagickException
1565 public static function createNote(array $item): array
1571 // We are treating posts differently when they are directed to a community.
1572 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1573 // But to not risk compatibility issues we currently perform the changes only for communities.
1574 if ($item['gravity'] == GRAVITY_PARENT) {
1575 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1576 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1577 if ($isCommunityPost && (count($links) == 1)) {
1578 $link = $links[0]['url'];
1581 $isCommunityPost = false;
1584 if ($item['event-type'] == 'event') {
1586 } elseif (!empty($item['title'])) {
1587 if (!$isCommunityPost || empty($link)) {
1590 // "Page" is used by Lemmy for posts that contain an external link
1597 if ($item['deleted']) {
1598 $type = 'Tombstone';
1602 $data['id'] = $item['uri'];
1603 $data['type'] = $type;
1605 if ($item['deleted']) {
1609 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1611 if ($item['uri'] != $item['thr-parent']) {
1612 $data['inReplyTo'] = $item['thr-parent'];
1614 $data['inReplyTo'] = null;
1617 $data['diaspora:guid'] = $item['guid'];
1618 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1620 if ($item['created'] != $item['edited']) {
1621 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1624 $data['url'] = $link ?? $item['plink'];
1625 $data['attributedTo'] = $item['author-link'];
1626 $data['sensitive'] = self::isSensitive($item['uri-id']);
1627 $data['conversation'] = $data['context'] = $item['conversation'];
1629 if (!empty($item['title'])) {
1630 $data['name'] = BBCode::toPlaintext($item['title'], false);
1633 $permission_block = self::createPermissionBlockForItem($item, false);
1635 $body = $item['body'];
1637 if ($type == 'Note') {
1638 $body = $item['raw-body'] ?? self::removePictures($body);
1642 * @todo Improve the automated summary
1643 * This part is currently deactivated. The automated summary seems to be more
1644 * confusing than helping. But possibly we will find a better way.
1645 * So the code is left here for now as a reminder
1647 * } elseif (($type == 'Article') && empty($data['summary'])) {
1648 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1649 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1650 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1654 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1655 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1658 if ($type == 'Event') {
1659 $data = array_merge($data, self::createEvent($item));
1661 if ($isCommunityPost) {
1662 // For community posts we remove the visible "!user@domain.tld".
1663 // This improves the look at systems like Lemmy.
1664 // Also in the future we should control the community delivery via other methods.
1665 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1668 if ($type == 'Page') {
1669 // When we transmit "Page" posts we have to remove the attachment.
1670 // The attachment contains the link that we already transmit in the "url" field.
1671 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1674 $body = BBCode::setMentionsToNicknames($body);
1676 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1679 // The regular "content" field does contain a minimized HTML. This is done since systems like
1680 // Mastodon has got problems with - for example - embedded pictures.
1681 // The contentMap does contain the unmodified HTML.
1682 $language = self::getLanguage($item);
1683 if (!empty($language)) {
1684 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1685 $richbody = BBCode::removeAttachment($richbody);
1687 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1690 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1692 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1693 $data['diaspora:comment'] = $item['signed_text'];
1696 $data['attachment'] = self::createAttachmentList($item, $type);
1697 $data['tag'] = self::createTagList($item);
1699 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1700 $data['location'] = self::createLocation($item);
1703 if (!empty($item['app'])) {
1704 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1707 $data = array_merge($data, $permission_block);
1713 * Fetches the language from the post, the user or the system.
1715 * @param array $item
1716 * @return string language string
1718 private static function getLanguage(array $item): string
1720 // Try to fetch the language from the post itself
1721 if (!empty($item['language'])) {
1722 $languages = array_keys(json_decode($item['language'], true));
1723 if (!empty($languages[0])) {
1724 return $languages[0];
1728 // Otherwise use the user's language
1729 if (!empty($item['uid'])) {
1730 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1731 if (!empty($user['language'])) {
1732 return $user['language'];
1736 // And finally just use the system language
1737 return DI::config()->get('system', 'language');
1741 * Creates an an "add tag" entry
1743 * @param array $item Item array
1744 * @param array $activity activity data
1745 * @return array with activity data for adding tags
1746 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1747 * @throws \ImagickException
1749 private static function createAddTag(array $item, array $activity): array
1751 $object = XML::parseString($item['object']);
1752 $target = XML::parseString($item['target']);
1754 $activity['diaspora:guid'] = $item['guid'];
1755 $activity['actor'] = $item['author-link'];
1756 $activity['target'] = (string)$target->id;
1757 $activity['summary'] = BBCode::toPlaintext($item['body']);
1758 $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1764 * Creates an announce object entry
1766 * @param array $item Item array
1767 * @param array $activity activity data
1768 * @return array with activity data
1769 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1770 * @throws \ImagickException
1772 private static function createAnnounce(array $item, array $activity): array
1774 $orig_body = $item['body'];
1775 $announce = self::getAnnounceArray($item);
1776 if (empty($announce)) {
1777 $activity['type'] = 'Create';
1778 $activity['object'] = self::createNote($item);
1782 if (empty($announce['comment'])) {
1783 // Pure announce, without a quote
1784 $activity['type'] = 'Announce';
1785 $activity['object'] = $announce['object']['uri'];
1790 $activity['type'] = 'Create';
1791 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1792 $activity['object'] = self::createNote($item);
1794 /// @todo Finally descide how to implement this in AP. This is a possible way:
1795 $activity['object']['attachment'][] = self::createNote($announce['object']);
1797 $activity['object']['source']['content'] = $orig_body;
1802 * Return announce related data if the item is an annunce
1804 * @param array $item
1805 * @return array Announcement array
1807 public static function getAnnounceArray(array $item): array
1809 $reshared = Item::getShareArray($item);
1810 if (empty($reshared['guid'])) {
1814 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1815 if (!DBA::isResult($reshared_item)) {
1819 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1823 $profile = APContact::getByURL($reshared_item['author-link'], false);
1824 if (empty($profile)) {
1828 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1832 * Checks if the provided item array is an announce
1834 * @param array $item Item array
1835 * @return boolean Whether item is an announcement
1837 public static function isAnnounce(array $item): bool
1839 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1843 $announce = self::getAnnounceArray($item);
1844 if (empty($announce)) {
1848 return empty($announce['comment']);
1852 * Creates an activity id for a given contact id
1854 * @param integer $cid Contact ID of target
1856 * @return bool|string activity id
1858 public static function activityIDFromContact(int $cid)
1860 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1861 if (!DBA::isResult($contact)) {
1865 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1866 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1867 return DI::baseUrl() . '/activity/' . $uuid;
1871 * Transmits a contact suggestion to a given inbox
1873 * @param integer $uid User ID
1874 * @param string $inbox Target inbox
1875 * @param integer $suggestion_id Suggestion ID
1876 * @return boolean was the transmission successful?
1877 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1879 public static function sendContactSuggestion(int $uid, string $inbox, int $suggestion_id): bool
1881 $owner = User::getOwnerDataById($uid);
1883 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1886 '@context' => ActivityPub::CONTEXT,
1887 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1888 'type' => 'Announce',
1889 'actor' => $owner['url'],
1890 'object' => $suggestion->url,
1891 'content' => $suggestion->note,
1892 'instrument' => self::getService(),
1893 'to' => [ActivityPub::PUBLIC_COLLECTION],
1897 $signed = LDSignature::sign($data, $owner);
1899 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1900 return HTTPSignature::transmit($signed, $inbox, $uid);
1904 * Transmits a profile relocation to a given inbox
1906 * @param integer $uid User ID
1907 * @param string $inbox Target inbox
1908 * @return boolean was the transmission successful?
1909 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1911 public static function sendProfileRelocation(int $uid, string $inbox): bool
1913 $owner = User::getOwnerDataById($uid);
1916 '@context' => ActivityPub::CONTEXT,
1917 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1918 'type' => 'dfrn:relocate',
1919 'actor' => $owner['url'],
1920 'object' => $owner['url'],
1921 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1922 'instrument' => self::getService(),
1923 'to' => [ActivityPub::PUBLIC_COLLECTION],
1927 $signed = LDSignature::sign($data, $owner);
1929 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1930 return HTTPSignature::transmit($signed, $inbox, $uid);
1934 * Transmits a profile deletion to a given inbox
1936 * @param integer $uid User ID
1937 * @param string $inbox Target inbox
1938 * @return boolean was the transmission successful?
1939 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1941 public static function sendProfileDeletion(int $uid, string $inbox): bool
1943 $owner = User::getOwnerDataById($uid);
1945 if (empty($owner)) {
1946 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1950 if (empty($owner['uprvkey'])) {
1951 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1955 $data = ['@context' => ActivityPub::CONTEXT,
1956 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1958 'actor' => $owner['url'],
1959 'object' => $owner['url'],
1960 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1961 'instrument' => self::getService(),
1962 'to' => [ActivityPub::PUBLIC_COLLECTION],
1965 $signed = LDSignature::sign($data, $owner);
1967 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1968 return HTTPSignature::transmit($signed, $inbox, $uid);
1972 * Transmits a profile change to a given inbox
1974 * @param integer $uid User ID
1975 * @param string $inbox Target inbox
1976 * @return boolean was the transmission successful?
1977 * @throws HTTPException\InternalServerErrorException
1978 * @throws HTTPException\NotFoundException
1979 * @throws \ImagickException
1981 public static function sendProfileUpdate(int $uid, string $inbox): bool
1983 $owner = User::getOwnerDataById($uid);
1984 $profile = APContact::getByURL($owner['url']);
1986 $data = ['@context' => ActivityPub::CONTEXT,
1987 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1989 'actor' => $owner['url'],
1990 'object' => self::getProfile($uid),
1991 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1992 'instrument' => self::getService(),
1993 'to' => [$profile['followers']],
1996 $signed = LDSignature::sign($data, $owner);
1998 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1999 return HTTPSignature::transmit($signed, $inbox, $uid);
2003 * Transmits a given activity to a target
2005 * @param string $activity Type name
2006 * @param string $target Target profile
2007 * @param integer $uid User ID
2008 * @param string $id Activity-identifier
2010 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2011 * @throws \ImagickException
2012 * @throws \Exception
2014 public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2016 $profile = APContact::getByURL($target);
2017 if (empty($profile['inbox'])) {
2018 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2022 $owner = User::getOwnerDataById($uid);
2025 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2029 '@context' => ActivityPub::CONTEXT,
2031 'type' => $activity,
2032 'actor' => $owner['url'],
2033 'object' => $profile['url'],
2034 'instrument' => self::getService(),
2035 'to' => [$profile['url']],
2038 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2040 $signed = LDSignature::sign($data, $owner);
2041 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2045 * Transmits a "follow object" activity to a target
2046 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2048 * @param string $object Object URL
2049 * @param string $target Target profile
2050 * @param integer $uid User ID
2052 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2053 * @throws \ImagickException
2054 * @throws \Exception
2056 public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2058 $profile = APContact::getByURL($target);
2059 if (empty($profile['inbox'])) {
2060 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2065 // Fetch the list of administrators
2066 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2068 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2069 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2070 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2071 $uid = $first_user['uid'];
2074 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2075 'author-id' => Contact::getPublicIdByUserId($uid)];
2076 if (Post::exists($condition)) {
2077 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2081 $owner = User::getOwnerDataById($uid);
2084 '@context' => ActivityPub::CONTEXT,
2085 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2087 'actor' => $owner['url'],
2088 'object' => $object,
2089 'instrument' => self::getService(),
2090 'to' => [$profile['url']],
2093 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2095 $signed = LDSignature::sign($data, $owner);
2096 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2100 * Transmit a message that the contact request had been accepted
2102 * @param string $target Target profile
2103 * @param string $id Object id
2104 * @param integer $uid User ID
2106 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2107 * @throws \ImagickException
2109 public static function sendContactAccept(string $target, string $id, int $uid)
2111 $profile = APContact::getByURL($target);
2112 if (empty($profile['inbox'])) {
2113 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2117 $owner = User::getOwnerDataById($uid);
2119 '@context' => ActivityPub::CONTEXT,
2120 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2122 'actor' => $owner['url'],
2126 'actor' => $profile['url'],
2127 'object' => $owner['url']
2129 'instrument' => self::getService(),
2130 'to' => [$profile['url']],
2133 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2135 $signed = LDSignature::sign($data, $owner);
2136 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2140 * Reject a contact request or terminates the contact relation
2142 * @param string $target Target profile
2143 * @param string $objectId Object id
2144 * @param int $uid User ID
2145 * @return bool Operation success
2146 * @throws HTTPException\InternalServerErrorException
2147 * @throws \ImagickException
2149 public static function sendContactReject(string $target, string $objectId, int $uid): bool
2151 $profile = APContact::getByURL($target);
2152 if (empty($profile['inbox'])) {
2153 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2157 $owner = User::getOwnerDataById($uid);
2159 '@context' => ActivityPub::CONTEXT,
2160 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2162 'actor' => $owner['url'],
2166 'actor' => $profile['url'],
2167 'object' => $owner['url']
2169 'instrument' => self::getService(),
2170 'to' => [$profile['url']],
2173 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2175 $signed = LDSignature::sign($data, $owner);
2176 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2180 * Transmits a message that we don't want to follow this contact anymore
2182 * @param string $target Target profile
2183 * @param integer $cid Contact id
2184 * @param integer $uid User ID
2185 * @return bool success
2186 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2187 * @throws \ImagickException
2188 * @throws \Exception
2190 public static function sendContactUndo(string $target, int $cid, int $uid): bool
2192 $profile = APContact::getByURL($target);
2193 if (empty($profile['inbox'])) {
2194 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2198 $object_id = self::activityIDFromContact($cid);
2199 if (empty($object_id)) {
2203 $objectId = DI::baseUrl() . '/activity/' . System::createGUID();
2205 $owner = User::getOwnerDataById($uid);
2207 '@context' => ActivityPub::CONTEXT,
2210 'actor' => $owner['url'],
2214 'actor' => $owner['url'],
2215 'object' => $profile['url']
2217 'instrument' => self::getService(),
2218 'to' => [$profile['url']],
2221 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2223 $signed = LDSignature::sign($data, $owner);
2224 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2228 * Prepends mentions (@) to $body variable
2230 * @param string $body HTML code
2232 * @param string $authorLink Author link
2233 * @return string HTML code with prepended mentions
2235 private static function prependMentions(string $body, int $uriid, string $authorLink): string
2239 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2240 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2241 if (!empty($profile['addr'])
2242 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2243 && !strstr($body, $profile['addr'])
2244 && !strstr($body, $tag['url'])
2245 && $tag['url'] !== $authorLink
2247 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2251 $mentions[] = $body;
2253 return implode(' ', $mentions);