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];
919 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
922 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
925 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
926 while ($contact = DBA::fetch($contacts)) {
927 if (!self::isAPContact($contact, $networks)) {
931 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
935 if (Network::isUrlBlocked($contact['url'])) {
939 $profile = APContact::getByURL($contact['url'], false);
940 if (!empty($profile)) {
941 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
942 $target = $profile['inbox'];
944 $target = $profile['sharedinbox'];
946 if (!self::archivedInbox($target)) {
947 $inboxes[$target][] = $contact['id'];
951 DBA::close($contacts);
957 * Fetches an array of inboxes for the given item and user
959 * @param array $item Item array
960 * @param integer $uid User ID
961 * @param boolean $personal fetch personal inboxes
962 * @param integer $last_id Last item id for adding receivers
963 * @return array with inboxes
964 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
965 * @throws \ImagickException
967 public static function fetchTargetInboxes(array $item, int $uid, bool $personal = false, int $last_id = 0): array
969 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
970 if (empty($permissions)) {
976 if ($item['gravity'] == GRAVITY_ACTIVITY) {
977 $item_profile = APContact::getByURL($item['author-link'], false);
979 $item_profile = APContact::getByURL($item['owner-link'], false);
982 if (empty($item_profile)) {
986 $profile_uid = User::getIdForURL($item_profile['url']);
988 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
989 if (empty($permissions[$element])) {
993 $blindcopy = in_array($element, ['bto', 'bcc']);
995 foreach ($permissions[$element] as $receiver) {
996 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
1000 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
1001 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
1003 $profile = APContact::getByURL($receiver, false);
1004 if (!empty($profile)) {
1005 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
1007 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
1008 $target = $profile['inbox'];
1010 $target = $profile['sharedinbox'];
1012 if (!self::archivedInbox($target)) {
1013 $inboxes[$target][] = $contact['id'] ?? 0;
1024 * Creates an array in the structure of the item table for a given mail id
1026 * @param integer $mail_id Mail id
1028 * @throws \Exception
1030 public static function getItemArrayFromMail(int $mail_id, bool $use_title = false): array
1032 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
1033 if (!DBA::isResult($mail)) {
1037 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
1038 if (!DBA::isResult($reply)) {
1042 // Making the post more compatible for Mastodon by:
1043 // - Making it a note and not an article (no title)
1044 // - Moving the title into the "summary" field that is used as a "content warning"
1047 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1048 $mail['title'] = '';
1051 $mail['content-warning'] = '';
1052 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1053 $mail['owner-id'] = $mail['author-id'];
1054 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1055 $mail['allow_gid'] = '';
1056 $mail['deny_cid'] = '';
1057 $mail['deny_gid'] = '';
1058 $mail['private'] = Item::PRIVATE;
1059 $mail['deleted'] = false;
1060 $mail['edited'] = $mail['created'];
1061 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1062 $mail['parent-uri'] = $reply['uri'];
1063 $mail['parent-uri-id'] = $reply['uri-id'];
1064 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1065 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
1066 $mail['event-type'] = '';
1067 $mail['language'] = '';
1068 $mail['parent'] = 0;
1074 * Creates an activity array for a given mail id
1076 * @param integer $mail_id
1077 * @param boolean $object_mode Is the activity item is used inside another object?
1079 * @return array of activity
1080 * @throws \Exception
1082 public static function createActivityFromMail(int $mail_id, bool $object_mode = false): array
1084 $mail = self::getItemArrayFromMail($mail_id);
1088 $object = self::createNote($mail);
1090 if (!$object_mode) {
1091 $data = ['@context' => ActivityPub::CONTEXT];
1096 $data['id'] = $mail['uri'] . '/Create';
1097 $data['type'] = 'Create';
1098 $data['actor'] = $mail['author-link'];
1099 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1100 $data['instrument'] = self::getService();
1101 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1103 if (empty($data['to']) && !empty($data['cc'])) {
1104 $data['to'] = $data['cc'];
1107 if (empty($data['to']) && !empty($data['bcc'])) {
1108 $data['to'] = $data['bcc'];
1112 unset($data['bcc']);
1114 $object['to'] = $data['to'];
1115 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1117 unset($object['cc']);
1118 unset($object['bcc']);
1120 $data['directMessage'] = true;
1122 $data['object'] = $object;
1124 $owner = User::getOwnerDataById($mail['uid']);
1126 if (!$object_mode && !empty($owner)) {
1127 return LDSignature::sign($data, $owner);
1134 * Returns the activity type of a given item
1136 * @param array $item Item array
1137 * @return string with activity type
1138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1139 * @throws \ImagickException
1141 private static function getTypeOfItem(array $item): string
1145 // Only check for a reshare, if it is a real reshare and no quoted reshare
1146 if (strpos($item['body'], '[share') === 0) {
1147 $announce = self::getAnnounceArray($item);
1148 $reshared = !empty($announce);
1153 } elseif ($item['verb'] == Activity::POST) {
1154 if ($item['created'] == $item['edited']) {
1159 } elseif ($item['verb'] == Activity::LIKE) {
1161 } elseif ($item['verb'] == Activity::DISLIKE) {
1163 } elseif ($item['verb'] == Activity::ATTEND) {
1165 } elseif ($item['verb'] == Activity::ATTENDNO) {
1167 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1168 $type = 'TentativeAccept';
1169 } elseif ($item['verb'] == Activity::FOLLOW) {
1171 } elseif ($item['verb'] == Activity::TAG) {
1173 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1183 * Creates the activity or fetches it from the cache
1185 * @param integer $item_id Item id
1186 * @param boolean $force Force new cache entry
1187 * @return array with the activity
1188 * @throws \Exception
1190 public static function createCachedActivityFromItem(int $item_id, bool $force = false): array
1192 $cachekey = 'APDelivery:createActivity:' . $item_id;
1195 $data = DI::cache()->get($cachekey);
1196 if (!is_null($data)) {
1201 $data = self::createActivityFromItem($item_id);
1203 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1208 * Creates an activity array for a given item id
1210 * @param integer $item_id
1211 * @param boolean $object_mode Is the activity item is used inside another object?
1212 * @return false|array
1213 * @throws \Exception
1215 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1217 Logger::info('Fetching activity', ['item' => $item_id]);
1218 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1219 if (!DBA::isResult($item)) {
1223 if (empty($item['uri-id'])) {
1224 Logger::warning('Item without uri-id', ['item' => $item]);
1228 if (!$item['deleted']) {
1229 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1230 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1231 if (!$item['origin'] && DBA::isResult($conversation)) {
1232 $data = json_decode($conversation['source'], true);
1233 if (!empty($data['type'])) {
1234 if (in_array($data['type'], ['Create', 'Update'])) {
1236 unset($data['@context']);
1237 unset($data['signature']);
1239 Logger::info('Return stored conversation', ['item' => $item_id]);
1241 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1242 if (!empty($data['@context'])) {
1243 $context = $data['@context'];
1244 unset($data['@context']);
1246 unset($data['actor']);
1253 $type = self::getTypeOfItem($item);
1255 if (!$object_mode) {
1256 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1258 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1260 } elseif ($item['deleted']) {
1267 if ($type == 'Delete') {
1268 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1269 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1270 $data['id'] = $item['uri'];
1272 $data['id'] = $item['uri'] . '/' . $type;
1275 $data['type'] = $type;
1277 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1278 $data['actor'] = $item['author-link'];
1280 $data['actor'] = $item['owner-link'];
1283 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1285 $data['instrument'] = self::getService();
1287 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1289 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1290 $data['object'] = $object ?? self::createNote($item);
1291 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1292 } elseif ($data['type'] == 'Add') {
1293 $data = self::createAddTag($item, $data);
1294 } elseif ($data['type'] == 'Announce') {
1295 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1296 $data['object'] = $item['thr-parent'];
1298 $data = self::createAnnounce($item, $data);
1300 } elseif ($data['type'] == 'Follow') {
1301 $data['object'] = $item['parent-uri'];
1302 } elseif ($data['type'] == 'Undo') {
1303 $data['object'] = self::createActivityFromItem($item_id, true);
1305 $data['diaspora:guid'] = $item['guid'];
1306 if (!empty($item['signed_text'])) {
1307 $data['diaspora:like'] = $item['signed_text'];
1309 $data['object'] = $item['thr-parent'];
1312 if (!empty($item['contact-uid'])) {
1313 $uid = $item['contact-uid'];
1315 $uid = $item['uid'];
1318 $owner = User::getOwnerDataById($uid);
1320 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1322 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1323 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1324 return LDSignature::sign($data, $owner);
1329 /// @todo Create "conversation" entry
1333 * Creates a location entry for a given item array
1335 * @param array $item Item array
1336 * @return array with location array
1338 private static function createLocation(array $item): array
1340 $location = ['type' => 'Place'];
1342 if (!empty($item['location'])) {
1343 $location['name'] = $item['location'];
1348 if (empty($item['coord'])) {
1349 $coord = Map::getCoordinates($item['location']);
1351 $coords = explode(' ', $item['coord']);
1352 if (count($coords) == 2) {
1353 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1357 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1358 $location['latitude'] = $coord['lat'];
1359 $location['longitude'] = $coord['lon'];
1366 * Returns a tag array for a given item array
1368 * @param array $item Item array
1369 * @return array of tags
1370 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1372 private static function createTagList(array $item): array
1376 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1377 foreach ($terms as $term) {
1378 if ($term['type'] == Tag::HASHTAG) {
1379 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1380 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1382 $contact = Contact::getByURL($term['url'], false, ['addr']);
1383 if (empty($contact)) {
1386 if (!empty($contact['addr'])) {
1387 $mention = '@' . $contact['addr'];
1389 $mention = '@' . $term['url'];
1392 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1396 $announce = self::getAnnounceArray($item);
1397 // Mention the original author upon commented reshares
1398 if (!empty($announce['comment'])) {
1399 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1406 * Adds attachment data to the JSON document
1408 * @param array $item Data of the item that is to be posted
1409 * @param string $type Object type
1411 * @return array with attachment data
1412 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1414 private static function createAttachmentList(array $item, string $type): array
1418 $uriids = [$item['uri-id']];
1419 $shared = BBCode::fetchShareAttributes($item['body']);
1420 if (!empty($shared['guid'])) {
1421 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1422 if (!empty($shared_item['uri-id'])) {
1423 $uriids[] = $shared_item['uri-id'];
1428 foreach ($uriids as $uriid) {
1429 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1430 if (in_array($attachment['url'], $urls)) {
1433 $urls[] = $attachment['url'];
1435 $attach = ['type' => 'Document',
1436 'mediaType' => $attachment['mimetype'],
1437 'url' => $attachment['url'],
1438 'name' => $attachment['description']];
1440 if (!empty($attachment['height'])) {
1441 $attach['height'] = $attachment['height'];
1444 if (!empty($attachment['width'])) {
1445 $attach['width'] = $attachment['width'];
1448 if (!empty($attachment['preview'])) {
1449 $attach['image'] = $attachment['preview'];
1452 $attachments[] = $attach;
1456 return $attachments;
1460 * Callback function to replace a Friendica style mention in a mention for a summary
1462 * @param array $match Matching values for the callback
1463 * @return string Replaced mention
1464 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1466 private static function mentionAddrCallback(array $match): string
1468 if (empty($match[1])) {
1472 $data = Contact::getByURL($match[1], false, ['addr']);
1473 if (empty($data['addr'])) {
1477 return '@' . $data['addr'];
1481 * Remove image elements since they are added as attachment
1483 * @param string $body HTML code
1484 * @return string with removed images
1486 private static function removePictures(string $body): string
1488 // Simplify image codes
1489 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1490 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1492 // Now remove local links
1493 $body = preg_replace_callback(
1494 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1496 // We remove the link when it is a link to a local photo page
1497 if (Photo::isLocalPage($match[1])) {
1500 // otherwise we just return the link
1501 return '[url]' . $match[1] . '[/url]';
1506 // Remove all pictures
1507 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1513 * Fetches the "context" value for a givem item array from the "conversation" table
1515 * @param array $item Item array
1516 * @return string with context url
1517 * @throws \Exception
1519 private static function fetchContextURLForItem(array $item): string
1521 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1522 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1523 $context_uri = $conversation['conversation-href'];
1524 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1525 $context_uri = $conversation['conversation-uri'];
1527 $context_uri = $item['parent-uri'] . '#context';
1529 return $context_uri;
1533 * Returns if the post contains sensitive content ("nsfw")
1535 * @param integer $uri_id URI id
1536 * @return boolean Whether URI id was found
1537 * @throws \Exception
1539 private static function isSensitive(int $uri_id): bool
1541 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1545 * Creates event data
1547 * @param array $item Item array
1548 * @return array with the event data
1549 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1551 private static function createEvent(array $item): array
1554 $event['name'] = $item['event-summary'];
1555 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1556 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1558 if (!$item['event-nofinish']) {
1559 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1562 if (!empty($item['event-location'])) {
1563 $item['location'] = $item['event-location'];
1564 $event['location'] = self::createLocation($item);
1567 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1568 $event['dfrn:adjust'] = true;
1574 * Creates a note/article object array
1576 * @param array $item
1577 * @return array with the object data
1578 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1579 * @throws \ImagickException
1581 public static function createNote(array $item): array
1587 // We are treating posts differently when they are directed to a community.
1588 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1589 // But to not risk compatibility issues we currently perform the changes only for communities.
1590 if ($item['gravity'] == GRAVITY_PARENT) {
1591 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1592 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1593 if ($isCommunityPost && (count($links) == 1)) {
1594 $link = $links[0]['url'];
1597 $isCommunityPost = false;
1600 if ($item['event-type'] == 'event') {
1602 } elseif (!empty($item['title'])) {
1603 if (!$isCommunityPost || empty($link)) {
1606 // "Page" is used by Lemmy for posts that contain an external link
1613 if ($item['deleted']) {
1614 $type = 'Tombstone';
1618 $data['id'] = $item['uri'];
1619 $data['type'] = $type;
1621 if ($item['deleted']) {
1625 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1627 if ($item['uri'] != $item['thr-parent']) {
1628 $data['inReplyTo'] = $item['thr-parent'];
1630 $data['inReplyTo'] = null;
1633 $data['diaspora:guid'] = $item['guid'];
1634 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1636 if ($item['created'] != $item['edited']) {
1637 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1640 $data['url'] = $link ?? $item['plink'];
1641 $data['attributedTo'] = $item['author-link'];
1642 $data['sensitive'] = self::isSensitive($item['uri-id']);
1643 $data['context'] = self::fetchContextURLForItem($item);
1645 if (!empty($item['title'])) {
1646 $data['name'] = BBCode::toPlaintext($item['title'], false);
1649 $permission_block = self::createPermissionBlockForItem($item, false);
1651 $body = $item['body'];
1653 if ($type == 'Note') {
1654 $body = $item['raw-body'] ?? self::removePictures($body);
1658 * @todo Improve the automated summary
1659 * This part is currently deactivated. The automated summary seems to be more
1660 * confusing than helping. But possibly we will find a better way.
1661 * So the code is left here for now as a reminder
1663 * } elseif (($type == 'Article') && empty($data['summary'])) {
1664 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1665 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1666 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1670 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1671 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1674 if ($type == 'Event') {
1675 $data = array_merge($data, self::createEvent($item));
1677 if ($isCommunityPost) {
1678 // For community posts we remove the visible "!user@domain.tld".
1679 // This improves the look at systems like Lemmy.
1680 // Also in the future we should control the community delivery via other methods.
1681 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1684 if ($type == 'Page') {
1685 // When we transmit "Page" posts we have to remove the attachment.
1686 // The attachment contains the link that we already transmit in the "url" field.
1687 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1690 $body = BBCode::setMentionsToNicknames($body);
1692 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1695 // The regular "content" field does contain a minimized HTML. This is done since systems like
1696 // Mastodon has got problems with - for example - embedded pictures.
1697 // The contentMap does contain the unmodified HTML.
1698 $language = self::getLanguage($item);
1699 if (!empty($language)) {
1700 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1701 $richbody = BBCode::removeAttachment($richbody);
1703 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1706 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1708 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1709 $data['diaspora:comment'] = $item['signed_text'];
1712 $data['attachment'] = self::createAttachmentList($item, $type);
1713 $data['tag'] = self::createTagList($item);
1715 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1716 $data['location'] = self::createLocation($item);
1719 if (!empty($item['app'])) {
1720 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1723 $data = array_merge($data, $permission_block);
1729 * Fetches the language from the post, the user or the system.
1731 * @param array $item
1732 * @return string language string
1734 private static function getLanguage(array $item): string
1736 // Try to fetch the language from the post itself
1737 if (!empty($item['language'])) {
1738 $languages = array_keys(json_decode($item['language'], true));
1739 if (!empty($languages[0])) {
1740 return $languages[0];
1744 // Otherwise use the user's language
1745 if (!empty($item['uid'])) {
1746 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1747 if (!empty($user['language'])) {
1748 return $user['language'];
1752 // And finally just use the system language
1753 return DI::config()->get('system', 'language');
1757 * Creates an an "add tag" entry
1759 * @param array $item Item array
1760 * @param array $activity activity data
1761 * @return array with activity data for adding tags
1762 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1763 * @throws \ImagickException
1765 private static function createAddTag(array $item, array $activity): array
1767 $object = XML::parseString($item['object']);
1768 $target = XML::parseString($item['target']);
1770 $activity['diaspora:guid'] = $item['guid'];
1771 $activity['actor'] = $item['author-link'];
1772 $activity['target'] = (string)$target->id;
1773 $activity['summary'] = BBCode::toPlaintext($item['body']);
1774 $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1780 * Creates an announce object entry
1782 * @param array $item Item array
1783 * @param array $activity activity data
1784 * @return array with activity data
1785 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1786 * @throws \ImagickException
1788 private static function createAnnounce(array $item, array $activity): array
1790 $orig_body = $item['body'];
1791 $announce = self::getAnnounceArray($item);
1792 if (empty($announce)) {
1793 $activity['type'] = 'Create';
1794 $activity['object'] = self::createNote($item);
1798 if (empty($announce['comment'])) {
1799 // Pure announce, without a quote
1800 $activity['type'] = 'Announce';
1801 $activity['object'] = $announce['object']['uri'];
1806 $activity['type'] = 'Create';
1807 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1808 $activity['object'] = self::createNote($item);
1810 /// @todo Finally descide how to implement this in AP. This is a possible way:
1811 $activity['object']['attachment'][] = self::createNote($announce['object']);
1813 $activity['object']['source']['content'] = $orig_body;
1818 * Return announce related data if the item is an annunce
1820 * @param array $item
1821 * @return array Announcement array
1823 public static function getAnnounceArray(array $item): array
1825 $reshared = Item::getShareArray($item);
1826 if (empty($reshared['guid'])) {
1830 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1831 if (!DBA::isResult($reshared_item)) {
1835 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1839 $profile = APContact::getByURL($reshared_item['author-link'], false);
1840 if (empty($profile)) {
1844 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1848 * Checks if the provided item array is an announce
1850 * @param array $item Item array
1851 * @return boolean Whether item is an announcement
1853 public static function isAnnounce(array $item): bool
1855 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1859 $announce = self::getAnnounceArray($item);
1860 if (empty($announce)) {
1864 return empty($announce['comment']);
1868 * Creates an activity id for a given contact id
1870 * @param integer $cid Contact ID of target
1872 * @return bool|string activity id
1874 public static function activityIDFromContact(int $cid)
1876 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1877 if (!DBA::isResult($contact)) {
1881 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1882 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1883 return DI::baseUrl() . '/activity/' . $uuid;
1887 * Transmits a contact suggestion to a given inbox
1889 * @param integer $uid User ID
1890 * @param string $inbox Target inbox
1891 * @param integer $suggestion_id Suggestion ID
1892 * @return boolean was the transmission successful?
1893 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1895 public static function sendContactSuggestion(int $uid, string $inbox, int $suggestion_id): bool
1897 $owner = User::getOwnerDataById($uid);
1899 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1902 '@context' => ActivityPub::CONTEXT,
1903 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1904 'type' => 'Announce',
1905 'actor' => $owner['url'],
1906 'object' => $suggestion->url,
1907 'content' => $suggestion->note,
1908 'instrument' => self::getService(),
1909 'to' => [ActivityPub::PUBLIC_COLLECTION],
1913 $signed = LDSignature::sign($data, $owner);
1915 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1916 return HTTPSignature::transmit($signed, $inbox, $uid);
1920 * Transmits a profile relocation to a given inbox
1922 * @param integer $uid User ID
1923 * @param string $inbox Target inbox
1924 * @return boolean was the transmission successful?
1925 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1927 public static function sendProfileRelocation(int $uid, string $inbox): bool
1929 $owner = User::getOwnerDataById($uid);
1932 '@context' => ActivityPub::CONTEXT,
1933 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1934 'type' => 'dfrn:relocate',
1935 'actor' => $owner['url'],
1936 'object' => $owner['url'],
1937 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1938 'instrument' => self::getService(),
1939 'to' => [ActivityPub::PUBLIC_COLLECTION],
1943 $signed = LDSignature::sign($data, $owner);
1945 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1946 return HTTPSignature::transmit($signed, $inbox, $uid);
1950 * Transmits a profile deletion to a given inbox
1952 * @param integer $uid User ID
1953 * @param string $inbox Target inbox
1954 * @return boolean was the transmission successful?
1955 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1957 public static function sendProfileDeletion(int $uid, string $inbox): bool
1959 $owner = User::getOwnerDataById($uid);
1961 if (empty($owner)) {
1962 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1966 if (empty($owner['uprvkey'])) {
1967 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1971 $data = ['@context' => ActivityPub::CONTEXT,
1972 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1974 'actor' => $owner['url'],
1975 'object' => $owner['url'],
1976 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1977 'instrument' => self::getService(),
1978 'to' => [ActivityPub::PUBLIC_COLLECTION],
1981 $signed = LDSignature::sign($data, $owner);
1983 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1984 return HTTPSignature::transmit($signed, $inbox, $uid);
1988 * Transmits a profile change to a given inbox
1990 * @param integer $uid User ID
1991 * @param string $inbox Target inbox
1992 * @return boolean was the transmission successful?
1993 * @throws HTTPException\InternalServerErrorException
1994 * @throws HTTPException\NotFoundException
1995 * @throws \ImagickException
1997 public static function sendProfileUpdate(int $uid, string $inbox): bool
1999 $owner = User::getOwnerDataById($uid);
2000 $profile = APContact::getByURL($owner['url']);
2002 $data = ['@context' => ActivityPub::CONTEXT,
2003 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2005 'actor' => $owner['url'],
2006 'object' => self::getProfile($uid),
2007 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2008 'instrument' => self::getService(),
2009 'to' => [$profile['followers']],
2012 $signed = LDSignature::sign($data, $owner);
2014 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
2015 return HTTPSignature::transmit($signed, $inbox, $uid);
2019 * Transmits a given activity to a target
2021 * @param string $activity Type name
2022 * @param string $target Target profile
2023 * @param integer $uid User ID
2024 * @param string $id Activity-identifier
2026 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2027 * @throws \ImagickException
2028 * @throws \Exception
2030 public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2032 $profile = APContact::getByURL($target);
2033 if (empty($profile['inbox'])) {
2034 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2038 $owner = User::getOwnerDataById($uid);
2041 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2045 '@context' => ActivityPub::CONTEXT,
2047 'type' => $activity,
2048 'actor' => $owner['url'],
2049 'object' => $profile['url'],
2050 'instrument' => self::getService(),
2051 'to' => [$profile['url']],
2054 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2056 $signed = LDSignature::sign($data, $owner);
2057 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2061 * Transmits a "follow object" activity to a target
2062 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2064 * @param string $object Object URL
2065 * @param string $target Target profile
2066 * @param integer $uid User ID
2068 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2069 * @throws \ImagickException
2070 * @throws \Exception
2072 public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2074 $profile = APContact::getByURL($target);
2075 if (empty($profile['inbox'])) {
2076 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2081 // Fetch the list of administrators
2082 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2084 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2085 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2086 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2087 $uid = $first_user['uid'];
2090 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2091 'author-id' => Contact::getPublicIdByUserId($uid)];
2092 if (Post::exists($condition)) {
2093 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2097 $owner = User::getOwnerDataById($uid);
2100 '@context' => ActivityPub::CONTEXT,
2101 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2103 'actor' => $owner['url'],
2104 'object' => $object,
2105 'instrument' => self::getService(),
2106 'to' => [$profile['url']],
2109 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2111 $signed = LDSignature::sign($data, $owner);
2112 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2116 * Transmit a message that the contact request had been accepted
2118 * @param string $target Target profile
2119 * @param string $id Object id
2120 * @param integer $uid User ID
2122 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2123 * @throws \ImagickException
2125 public static function sendContactAccept(string $target, string $id, int $uid)
2127 $profile = APContact::getByURL($target);
2128 if (empty($profile['inbox'])) {
2129 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2133 $owner = User::getOwnerDataById($uid);
2135 '@context' => ActivityPub::CONTEXT,
2136 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2138 'actor' => $owner['url'],
2142 'actor' => $profile['url'],
2143 'object' => $owner['url']
2145 'instrument' => self::getService(),
2146 'to' => [$profile['url']],
2149 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2151 $signed = LDSignature::sign($data, $owner);
2152 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2156 * Reject a contact request or terminates the contact relation
2158 * @param string $target Target profile
2159 * @param integer $id Object id
2160 * @param integer $uid User ID
2161 * @return bool Operation success
2162 * @throws HTTPException\InternalServerErrorException
2163 * @throws \ImagickException
2165 public static function sendContactReject(string $target, int $id, int $uid): bool
2167 $profile = APContact::getByURL($target);
2168 if (empty($profile['inbox'])) {
2169 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2173 $owner = User::getOwnerDataById($uid);
2175 '@context' => ActivityPub::CONTEXT,
2176 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2178 'actor' => $owner['url'],
2180 'id' => (string)$id,
2182 'actor' => $profile['url'],
2183 'object' => $owner['url']
2185 'instrument' => self::getService(),
2186 'to' => [$profile['url']],
2189 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2191 $signed = LDSignature::sign($data, $owner);
2192 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2196 * Transmits a message that we don't want to follow this contact anymore
2198 * @param string $target Target profile
2199 * @param integer $cid Contact id
2200 * @param integer $uid User ID
2201 * @return bool success
2202 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2203 * @throws \ImagickException
2204 * @throws \Exception
2206 public static function sendContactUndo(string $target, int $cid, int $uid): bool
2208 $profile = APContact::getByURL($target);
2209 if (empty($profile['inbox'])) {
2210 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2214 $object_id = self::activityIDFromContact($cid);
2215 if (empty($object_id)) {
2219 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2221 $owner = User::getOwnerDataById($uid);
2223 '@context' => ActivityPub::CONTEXT,
2226 'actor' => $owner['url'],
2230 'actor' => $owner['url'],
2231 'object' => $profile['url']
2233 'instrument' => self::getService(),
2234 'to' => [$profile['url']],
2237 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2239 $signed = LDSignature::sign($data, $owner);
2240 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2244 * Prepends mentions (@) to $body variable
2246 * @param string $body HTML code
2248 * @param string $authorLink Author link
2249 * @return string HTML code with prepended mentions
2251 private static function prependMentions(string $body, int $uriid, string $authorLink): string
2255 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2256 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2257 if (!empty($profile['addr'])
2258 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2259 && !strstr($body, $profile['addr'])
2260 && !strstr($body, $tag['url'])
2261 && $tag['url'] !== $authorLink
2263 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2267 $mentions[] = $body;
2269 return implode(' ', $mentions);