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\GServer;
35 use Friendica\Model\Item;
36 use Friendica\Model\Photo;
37 use Friendica\Model\Post;
38 use Friendica\Model\Tag;
39 use Friendica\Model\User;
40 use Friendica\Network\HTTPException;
41 use Friendica\Protocol\Activity;
42 use Friendica\Protocol\ActivityPub;
43 use Friendica\Protocol\Relay;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\HTTPSignature;
46 use Friendica\Util\LDSignature;
47 use Friendica\Util\Map;
48 use Friendica\Util\Network;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
53 * ActivityPub Transmitter Protocol class
60 const CACHEKEY_FEATURED = 'transmitter:getFeatured:';
61 const CACHEKEY_CONTACTS = 'transmitter:getContacts:';
64 * Add relay servers to the list of inboxes
66 * @param array $inboxes
67 * @return array inboxes with added relay servers
69 public static function addRelayServerInboxes(array $inboxes = []): array
71 foreach (Relay::getList(['inbox']) as $contact) {
72 $inboxes[$contact['inbox']] = $contact['inbox'];
79 * Add relay servers to the list of inboxes
81 * @param array $inboxes
82 * @return array inboxes with added relay servers
84 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = []): array
86 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
91 $relays = Relay::getDirectRelayList($item_id);
96 foreach ($relays as $relay) {
97 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
98 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
104 * Subscribe to a relay and updates contact on success
106 * @param string $url Subscribe actor url
107 * @return bool success
109 public static function sendRelayFollow(string $url): bool
111 $contact = Contact::getByURL($url);
112 if (empty($contact)) {
116 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
117 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
119 Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]);
126 * Unsubscribe from a relay and updates contact on success or forced
128 * @param string $url Subscribe actor url
129 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
130 * @return bool success
132 public static function sendRelayUndoFollow(string $url, bool $force = false): bool
134 $contact = Contact::getByURL($url);
135 if (empty($contact)) {
139 $success = self::sendContactUndo($url, $contact['id'], 0);
141 if ($success || $force) {
142 Contact::update(['rel' => Contact::NOTHING], ['id' => $contact['id']]);
149 * Collects a list of contacts of the given owner
151 * @param array $owner Owner array
152 * @param array $rel The relevant value(s) contact.rel should match
153 * @param string $module The name of the relevant AP endpoint module (followers|following)
154 * @param integer $page Page number
155 * @param string $requester URL of the requester
156 * @param boolean $nocache Wether to bypass caching
157 * @return array of owners
160 public static function getContacts(array $owner, array $rel, string $module, int $page = null, string $requester = null, bool $nocache = false): array
163 $cachekey = self::CACHEKEY_CONTACTS . $module . ':'. $owner['uid'];
164 $result = DI::cache()->get($cachekey);
165 if (!$nocache && !is_null($result)) {
172 'uid' => $owner['uid'],
181 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
183 $total = DBA::count('contact', $condition);
185 $modulePath = '/' . $module . '/';
187 $data = ['@context' => ActivityPub::CONTEXT];
188 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
189 $data['type'] = 'OrderedCollection';
190 $data['totalItems'] = $total;
193 $data['id'] .= '?' . http_build_query(['page' => $page]);
196 // When we hide our friends we will only show the pure number but don't allow more.
197 $show_contacts = empty($owner['hide-friends']);
199 // Allow fetching the contact list when the requester is part of the list.
200 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
201 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
204 if (!$show_contacts) {
205 if (!empty($cachekey)) {
206 DI::cache()->set($cachekey, $data, Duration::DAY);
213 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
215 $data['type'] = 'OrderedCollectionPage';
218 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
219 while ($contact = DBA::fetch($contacts)) {
220 $list[] = $contact['url'];
222 DBA::close($contacts);
224 if (count($list) == 100) {
225 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
228 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
230 $data['orderedItems'] = $list;
233 if (!empty($cachekey)) {
234 DI::cache()->set($cachekey, $data, Duration::DAY);
241 * Public posts for the given owner
243 * @param array $owner Owner array
244 * @param integer $page Page number
245 * @param string $requester URL of requesting account
246 * @param boolean $nocache Wether to bypass caching
247 * @return array of posts
248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
249 * @throws \ImagickException
251 public static function getOutbox(array $owner, int $page = null, string $requester = '', bool $nocache = false): array
253 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
255 if (!empty($requester)) {
256 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
257 if (!empty($requester_id)) {
258 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
259 if (!empty($permissionSets)) {
260 $condition = ['psid' => array_merge($permissionSets->column('id'),
261 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
266 $condition = array_merge($condition, [
267 'uid' => $owner['uid'],
268 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
269 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
270 'network' => Protocol::FEDERATED,
271 'parent-network' => Protocol::FEDERATED,
277 $apcontact = APContact::getByURL($owner['url']);
279 $data = ['@context' => ActivityPub::CONTEXT];
280 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
281 $data['type'] = 'OrderedCollection';
282 $data['totalItems'] = $apcontact['statuses_count'] ?? 0;
285 $data['id'] .= '?' . http_build_query(['page' => $page]);
289 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
291 $data['type'] = 'OrderedCollectionPage';
294 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
295 while ($item = Post::fetch($items)) {
296 $activity = self::createActivityFromItem($item['id'], true);
297 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
299 // Only list "Create" activity objects here, no reshares
300 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
301 $list[] = $activity['object'];
306 if (count($list) == 20) {
307 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
310 // Fix the cached total item count when it is lower than the real count
311 $total = (($page - 1) * 20) + $data['totalItems'];
312 if ($total > $data['totalItems']) {
313 $data['totalItems'] = $total;
316 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
318 $data['orderedItems'] = $list;
325 * Public posts for the given owner
327 * @param array $owner Owner array
328 * @param integer $page Page number
329 * @param boolean $nocache Wether to bypass caching
331 * @return array of posts
332 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
333 * @throws \ImagickException
335 public static function getFeatured(array $owner, int $page = null, bool $nocache = false): array
338 $cachekey = self::CACHEKEY_FEATURED . $owner['uid'];
339 $result = DI::cache()->get($cachekey);
340 if (!$nocache && !is_null($result)) {
345 $owner_cid = Contact::getIdForURL($owner['url'], 0, false);
347 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
348 $owner_cid, Post\Collection::FEATURED];
350 $condition = DBA::mergeConditions($condition, [
351 'uid' => $owner['uid'],
352 'author-id' => $owner_cid,
353 'private' => [Item::PUBLIC, Item::UNLISTED],
354 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
355 'network' => Protocol::FEDERATED,
356 'parent-network' => Protocol::FEDERATED,
362 $count = Post::count($condition);
364 $data = ['@context' => ActivityPub::CONTEXT];
365 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
366 $data['type'] = 'OrderedCollection';
367 $data['totalItems'] = $count;
370 $data['id'] .= '?' . http_build_query(['page' => $page]);
374 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
376 $data['type'] = 'OrderedCollectionPage';
377 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
381 while ($item = Post::fetch($items)) {
382 $activity = self::createActivityFromItem($item['id'], true);
383 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
385 // Only list "Create" activity objects here, no reshares
386 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
387 $list[] = $activity['object'];
392 if (count($list) == 20) {
393 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
397 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
400 $data['orderedItems'] = $list;
402 if (!empty($cachekey)) {
403 DI::cache()->set($cachekey, $data, Duration::DAY);
410 * Return the service array containing information the used software and it's url
412 * @return array with service data
414 private static function getService(): array
418 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
419 'url' => DI::baseUrl()->get()
424 * Return the ActivityPub profile of the given user
426 * @param int $uid User ID
427 * @return array with profile data
428 * @throws HTTPException\NotFoundException
429 * @throws HTTPException\InternalServerErrorException
431 public static function getProfile(int $uid): array
433 $owner = User::getOwnerDataById($uid);
434 if (!isset($owner['id'])) {
435 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
436 throw new HTTPException\NotFoundException('User not found.');
439 $data = ['@context' => ActivityPub::CONTEXT];
440 $data['id'] = $owner['url'];
442 if (!empty($owner['guid'])) {
443 $data['diaspora:guid'] = $owner['guid'];
446 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
449 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
450 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
451 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
452 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
453 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
455 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
458 $data['preferredUsername'] = $owner['nick'];
459 $data['name'] = $owner['name'];
461 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
462 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
463 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
466 if (!empty($owner['about'])) {
467 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
470 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
471 $data['vcard:hasInstantMessage'] = [];
473 if (!empty($owner['xmpp'])) {
474 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
476 if (!empty($owner['matrix'])) {
477 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
481 $data['url'] = $owner['url'];
482 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
483 $data['discoverable'] = (bool)$owner['net-publish'];
484 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
485 'owner' => $owner['url'],
486 'publicKeyPem' => $owner['pubkey']];
487 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
488 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
490 $resourceid = Photo::ridFromURI($owner['photo']);
491 if (!empty($resourceid)) {
492 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
493 if (!empty($photo['type'])) {
494 $data['icon']['mediaType'] = $photo['type'];
498 if (!empty($owner['header'])) {
499 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
501 $resourceid = Photo::ridFromURI($owner['header']);
502 if (!empty($resourceid)) {
503 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
504 if (!empty($photo['type'])) {
505 $data['image']['mediaType'] = $photo['type'];
512 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
514 'type' => 'PropertyValue',
515 'name' => $profile_field->label,
516 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
520 if (!empty($custom_fields)) {
521 $data['attachment'] = $custom_fields;
524 $data['generator'] = self::getService();
526 // tags: https://kitty.town/@inmysocks/100656097926961126.json
531 * @param string $username
533 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
535 public static function getDeletedUser(string $username): array
538 '@context' => ActivityPub::CONTEXT,
539 'id' => DI::baseUrl() . '/profile/' . $username,
540 'type' => 'Tombstone',
541 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
542 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
543 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
548 * Returns an array with permissions of the thread parent of the given item array
551 * @param bool $is_forum_thread
553 * @return array with permissions
554 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
555 * @throws \ImagickException
557 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread): array
559 if (empty($item['thr-parent-id'])) {
563 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
564 if (empty($parent)) {
569 'to' => [$parent['author-link']],
575 $parent_profile = APContact::getByURL($parent['author-link']);
577 $item_profile = APContact::getByURL($item['author-link']);
578 $exclude[] = $item['author-link'];
580 if ($item['gravity'] == Item::GRAVITY_PARENT) {
581 $exclude[] = $item['owner-link'];
584 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
585 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
586 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
587 if (!$is_forum_thread) {
588 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
590 } elseif (!in_array($receiver['url'], $exclude)) {
591 $permissions[$type[$receiver['type']]][] = $receiver['url'];
599 * Check if the given item id is from ActivityPub
601 * @param integer $item_id
602 * @return boolean "true" if the post is from ActivityPub
604 private static function isAPPost(int $item_id): bool
606 if (empty($item_id)) {
610 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
614 * Creates an array of permissions from an item thread
616 * @param array $item Item array
617 * @param boolean $blindcopy addressing via "bcc" or "cc"?
618 * @param integer $last_id Last item id for adding receivers
620 * @return array with permission data
621 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
622 * @throws \ImagickException
624 private static function createPermissionBlockForItem(array $item, bool $blindcopy, int $last_id = 0): array
627 $last_id = $item['id'];
634 // Check if we should always deliver our stuff via BCC
635 if (!empty($item['uid'])) {
636 $owner = User::getOwnerDataById($item['uid']);
637 if (!empty($owner)) {
638 $always_bcc = $owner['hide-friends'];
639 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
641 $profile = APContact::getByURL($owner['url'], false);
642 $follower = $profile['followers'] ?? '';
646 if (DI::config()->get('system', 'ap_always_bcc')) {
650 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
651 if (!empty($parent) && ($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
652 $profile = APContact::getByURL($parent['causer-link'], false);
653 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
655 $is_forum_thread = false;
658 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
659 // Will be activated in a later step
660 $networks = Protocol::FEDERATED;
662 // For now only send to these contacts:
663 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
666 $data = ['to' => [], 'cc' => [], 'bcc' => []];
668 if ($item['gravity'] == Item::GRAVITY_PARENT) {
669 $actor_profile = APContact::getByURL($item['owner-link']);
671 $actor_profile = APContact::getByURL($item['author-link']);
676 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
678 if ($item['private'] != Item::PRIVATE) {
679 // Directly mention the original author upon a quoted reshare.
680 // Else just ensure that the original author receives the reshare.
681 $announce = self::getAnnounceArray($item);
682 if (!empty($announce['comment'])) {
683 $data['to'][] = $announce['actor']['url'];
684 } elseif (!empty($announce)) {
685 $data['cc'][] = $announce['actor']['url'];
688 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
690 // Check if the item is completely public or unlisted
691 if ($item['private'] == Item::PUBLIC) {
692 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
694 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
697 foreach ($terms as $term) {
698 $profile = APContact::getByURL($term['url'], false);
699 if (!empty($profile)) {
700 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
702 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
703 $data['cc'][] = $profile['followers'];
706 $data['to'][] = $profile['url'];
710 $receiver_list = Item::enumeratePermissions($item, true);
712 foreach ($terms as $term) {
713 $cid = Contact::getIdForURL($term['url'], $item['uid']);
714 if (!empty($cid) && in_array($cid, $receiver_list)) {
715 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
716 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
720 $profile = APContact::getByURL($term['url'], false);
721 if (!empty($profile)) {
722 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
724 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
725 $data['cc'][] = $profile['followers'];
728 $data['to'][] = $profile['url'];
733 if ($is_forum && !$exclusive && !empty($follower)) {
734 $data['cc'][] = $follower;
735 } elseif (!$exclusive) {
736 foreach ($receiver_list as $receiver) {
737 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
738 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
742 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
743 if ($contact['hidden'] || $always_bcc) {
744 $data['bcc'][] = $profile['url'];
746 $data['cc'][] = $profile['url'];
753 if (!empty($item['parent'])) {
754 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']], ['order' => ['id']]);
755 while ($parent = Post::fetch($parents)) {
756 if ($parent['gravity'] == Item::GRAVITY_PARENT) {
757 $profile = APContact::getByURL($parent['owner-link'], false);
758 if (!empty($profile)) {
759 if ($item['gravity'] != Item::GRAVITY_PARENT) {
760 // Comments to forums are directed to the forum
761 // But comments to forums aren't directed to the followers collection
762 // This rule is only valid when the actor isn't the forum.
763 // The forum needs to transmit their content to their followers.
764 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
765 $data['to'][] = $profile['url'];
767 $data['cc'][] = $profile['url'];
768 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers']) && (!$exclusive || !$is_forum_thread)) {
769 $data['cc'][] = $actor_profile['followers'];
772 } elseif (!$exclusive && !$is_forum_thread) {
773 // Public thread parent post always are directed to the followers.
774 if ($item['private'] != Item::PRIVATE) {
775 $data['cc'][] = $actor_profile['followers'];
781 // Don't include data from future posts
782 if ($parent['id'] >= $last_id) {
786 $profile = APContact::getByURL($parent['author-link'], false);
787 if (!empty($profile)) {
788 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
789 $data['to'][] = $profile['url'];
791 $data['cc'][] = $profile['url'];
795 DBA::close($parents);
798 $data['to'] = array_unique($data['to']);
799 $data['cc'] = array_unique($data['cc']);
800 $data['bcc'] = array_unique($data['bcc']);
802 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
803 unset($data['to'][$key]);
806 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
807 unset($data['cc'][$key]);
810 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
811 unset($data['bcc'][$key]);
814 foreach ($data['to'] as $to) {
815 if (($key = array_search($to, $data['cc'])) !== false) {
816 unset($data['cc'][$key]);
819 if (($key = array_search($to, $data['bcc'])) !== false) {
820 unset($data['bcc'][$key]);
824 foreach ($data['cc'] as $cc) {
825 if (($key = array_search($cc, $data['bcc'])) !== false) {
826 unset($data['bcc'][$key]);
830 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
833 unset($receivers['bcc']);
836 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
837 if (!empty($receivers[$element])) {
838 foreach ($receivers[$element] as $receiver) {
839 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
840 $name = Receiver::PUBLIC_COLLECTION;
842 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
844 Tag::store($item['uri-id'], $type, $name, $receiver);
853 * Check if an inbox is archived
855 * @param string $url Inbox url
856 * @return boolean "true" if inbox is archived
858 public static function archivedInbox(string $url): bool
860 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
864 * Check if a given contact should be delivered via AP
866 * @param array $contact Contact array
867 * @param array $networks Array with networks
868 * @return bool Whether the used protocol matches ACTIVITYPUB
871 private static function isAPContact(array $contact, array $networks): bool
873 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
877 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
881 * Fetches a list of inboxes of followers of a given user
883 * @param integer $uid User ID
884 * @param boolean $personal fetch personal inboxes
885 * @param boolean $all_ap Retrieve all AP enabled inboxes
886 * @return array of follower inboxes
887 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
888 * @throws \ImagickException
890 public static function fetchTargetInboxesforUser(int $uid, bool $personal = false, bool $all_ap = false): array
896 if (!empty($item['uid'])) {
897 $profile = User::getOwnerDataById($item['uid']);
898 if (!empty($profile)) {
899 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
903 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
904 // Will be activated in a later step
905 $networks = Protocol::FEDERATED;
907 // For now only send to these contacts:
908 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
916 'network' => Protocol::FEDERATED,
920 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
923 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
924 while ($contact = DBA::fetch($contacts)) {
925 if (!self::isAPContact($contact, $networks)) {
929 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
933 if (Network::isUrlBlocked($contact['url'])) {
937 $profile = APContact::getByURL($contact['url'], false);
938 if (!empty($profile)) {
939 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
940 $target = $profile['inbox'];
942 $target = $profile['sharedinbox'];
944 if (!self::archivedInbox($target)) {
945 $inboxes[$target][] = $contact['id'];
949 DBA::close($contacts);
955 * Fetches an array of inboxes for the given item and user
957 * @param array $item Item array
958 * @param integer $uid User ID
959 * @param boolean $personal fetch personal inboxes
960 * @param integer $last_id Last item id for adding receivers
961 * @return array with inboxes
962 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
963 * @throws \ImagickException
965 public static function fetchTargetInboxes(array $item, int $uid, bool $personal = false, int $last_id = 0): array
967 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
968 if (empty($permissions)) {
974 if ($item['gravity'] == Item::GRAVITY_ACTIVITY) {
975 $item_profile = APContact::getByURL($item['author-link'], false);
977 $item_profile = APContact::getByURL($item['owner-link'], false);
980 if (empty($item_profile)) {
984 $profile_uid = User::getIdForURL($item_profile['url']);
986 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
987 if (empty($permissions[$element])) {
991 $blindcopy = in_array($element, ['bto', 'bcc']);
993 foreach ($permissions[$element] as $receiver) {
994 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
998 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
999 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
1001 $profile = APContact::getByURL($receiver, false);
1002 if (!empty($profile)) {
1003 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
1005 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
1006 $target = $profile['inbox'];
1008 $target = $profile['sharedinbox'];
1010 if (!self::archivedInbox($target)) {
1011 $inboxes[$target][] = $contact['id'] ?? 0;
1022 * Creates an array in the structure of the item table for a given mail id
1024 * @param integer $mail_id Mail id
1026 * @throws \Exception
1028 public static function getItemArrayFromMail(int $mail_id, bool $use_title = false): array
1030 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
1031 if (!DBA::isResult($mail)) {
1035 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
1036 if (!DBA::isResult($reply)) {
1040 // Making the post more compatible for Mastodon by:
1041 // - Making it a note and not an article (no title)
1042 // - Moving the title into the "summary" field that is used as a "content warning"
1045 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1046 $mail['title'] = '';
1049 $mail['content-warning'] = '';
1050 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1051 $mail['owner-id'] = $mail['author-id'];
1052 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1053 $mail['allow_gid'] = '';
1054 $mail['deny_cid'] = '';
1055 $mail['deny_gid'] = '';
1056 $mail['private'] = Item::PRIVATE;
1057 $mail['deleted'] = false;
1058 $mail['edited'] = $mail['created'];
1059 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1060 $mail['parent-uri'] = $reply['uri'];
1061 $mail['parent-uri-id'] = $reply['uri-id'];
1062 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1063 $mail['gravity'] = ($mail['reply'] ? Item::GRAVITY_COMMENT: Item::GRAVITY_PARENT);
1064 $mail['event-type'] = '';
1065 $mail['language'] = '';
1066 $mail['parent'] = 0;
1072 * Creates an activity array for a given mail id
1074 * @param integer $mail_id
1075 * @param boolean $object_mode Is the activity item is used inside another object?
1077 * @return array of activity
1078 * @throws \Exception
1080 public static function createActivityFromMail(int $mail_id, bool $object_mode = false): array
1082 $mail = self::getItemArrayFromMail($mail_id);
1086 $object = self::createNote($mail);
1088 if (!$object_mode) {
1089 $data = ['@context' => ActivityPub::CONTEXT];
1094 $data['id'] = $mail['uri'] . '/Create';
1095 $data['type'] = 'Create';
1096 $data['actor'] = $mail['author-link'];
1097 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1098 $data['instrument'] = self::getService();
1099 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1101 if (empty($data['to']) && !empty($data['cc'])) {
1102 $data['to'] = $data['cc'];
1105 if (empty($data['to']) && !empty($data['bcc'])) {
1106 $data['to'] = $data['bcc'];
1110 unset($data['bcc']);
1112 $object['to'] = $data['to'];
1113 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1115 unset($object['cc']);
1116 unset($object['bcc']);
1118 $data['directMessage'] = true;
1120 $data['object'] = $object;
1122 $owner = User::getOwnerDataById($mail['uid']);
1124 if (!$object_mode && !empty($owner)) {
1125 return LDSignature::sign($data, $owner);
1132 * Returns the activity type of a given item
1134 * @param array $item Item array
1135 * @return string with activity type
1136 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1137 * @throws \ImagickException
1139 private static function getTypeOfItem(array $item): string
1143 // Only check for a reshare, if it is a real reshare and no quoted reshare
1144 if (strpos($item['body'], '[share') === 0) {
1145 $announce = self::getAnnounceArray($item);
1146 $reshared = !empty($announce);
1151 } elseif ($item['verb'] == Activity::POST) {
1152 if ($item['created'] == $item['edited']) {
1157 } elseif ($item['verb'] == Activity::LIKE) {
1159 } elseif ($item['verb'] == Activity::DISLIKE) {
1161 } elseif ($item['verb'] == Activity::ATTEND) {
1163 } elseif ($item['verb'] == Activity::ATTENDNO) {
1165 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1166 $type = 'TentativeAccept';
1167 } elseif ($item['verb'] == Activity::FOLLOW) {
1169 } elseif ($item['verb'] == Activity::TAG) {
1171 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1181 * Creates the activity or fetches it from the cache
1183 * @param integer $item_id Item id
1184 * @param boolean $force Force new cache entry
1185 * @return array|false activity or false on failure
1186 * @throws \Exception
1188 public static function createCachedActivityFromItem(int $item_id, bool $force = false, bool $object_mode = false)
1190 $cachekey = 'APDelivery:createActivity:' . $item_id . ':' . (int)$object_mode;
1193 $data = DI::cache()->get($cachekey);
1194 if (!is_null($data)) {
1199 $data = self::createActivityFromItem($item_id, $object_mode);
1201 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1206 * Creates an activity array for a given item id
1208 * @param integer $item_id
1209 * @param boolean $object_mode Is the activity item is used inside another object?
1210 * @return false|array
1211 * @throws \Exception
1213 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1215 Logger::info('Fetching activity', ['item' => $item_id]);
1216 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1217 if (!DBA::isResult($item)) {
1221 if (empty($item['uri-id'])) {
1222 Logger::warning('Item without uri-id', ['item' => $item]);
1226 if (!$item['deleted']) {
1227 $data = Post\Activity::getByURIId($item['uri-id']);
1228 if (!$item['origin'] && !empty($data)) {
1230 unset($data['@context']);
1231 unset($data['signature']);
1233 Logger::info('Return stored conversation', ['item' => $item_id]);
1238 if (!$item['origin'] && empty($object)) {
1239 Logger::debug('Post is not ours and is not stored', ['id' => $item_id, 'uri-id' => $item['uri-id']]);
1243 $type = self::getTypeOfItem($item);
1245 if (!$object_mode) {
1246 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1248 if ($item['deleted'] && ($item['gravity'] == Item::GRAVITY_ACTIVITY)) {
1250 } elseif ($item['deleted']) {
1257 if ($type == 'Delete') {
1258 $data['id'] = Item::newURI($item['guid']) . '/' . $type;;
1259 } elseif (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1260 $data['id'] = $item['uri'];
1262 $data['id'] = $item['uri'] . '/' . $type;
1265 $data['type'] = $type;
1267 if (($type != 'Announce') || ($item['gravity'] != Item::GRAVITY_PARENT)) {
1268 $data['actor'] = $item['author-link'];
1270 $data['actor'] = $item['owner-link'];
1273 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1275 $data['instrument'] = self::getService();
1277 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1279 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1280 $data['object'] = $object ?? self::createNote($item);
1281 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1282 } elseif ($data['type'] == 'Add') {
1283 $data = self::createAddTag($item, $data);
1284 } elseif ($data['type'] == 'Announce') {
1285 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1286 $data['object'] = $item['thr-parent'];
1288 $data = self::createAnnounce($item, $data);
1290 } elseif ($data['type'] == 'Follow') {
1291 $data['object'] = $item['parent-uri'];
1292 } elseif ($data['type'] == 'Undo') {
1293 $data['object'] = self::createActivityFromItem($item_id, true);
1295 $data['diaspora:guid'] = $item['guid'];
1296 if (!empty($item['signed_text'])) {
1297 $data['diaspora:like'] = $item['signed_text'];
1299 $data['object'] = $item['thr-parent'];
1302 if (!empty($item['contact-uid'])) {
1303 $uid = $item['contact-uid'];
1305 $uid = $item['uid'];
1308 $owner = User::getOwnerDataById($uid);
1310 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1312 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1313 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1314 return LDSignature::sign($data, $owner);
1319 /// @todo Create "conversation" entry
1323 * Creates a location entry for a given item array
1325 * @param array $item Item array
1326 * @return array with location array
1328 private static function createLocation(array $item): array
1330 $location = ['type' => 'Place'];
1332 if (!empty($item['location'])) {
1333 $location['name'] = $item['location'];
1338 if (empty($item['coord'])) {
1339 $coord = Map::getCoordinates($item['location']);
1341 $coords = explode(' ', $item['coord']);
1342 if (count($coords) == 2) {
1343 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1347 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1348 $location['latitude'] = $coord['lat'];
1349 $location['longitude'] = $coord['lon'];
1356 * Returns a tag array for a given item array
1358 * @param array $item Item array
1359 * @param string $quote_url Url of the attached quote link
1360 * @return array of tags
1361 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1363 private static function createTagList(array $item, string $quote_url): array
1367 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1368 foreach ($terms as $term) {
1369 if ($term['type'] == Tag::HASHTAG) {
1370 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1371 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1373 $contact = Contact::getByURL($term['url'], false, ['addr']);
1374 if (empty($contact)) {
1377 if (!empty($contact['addr'])) {
1378 $mention = '@' . $contact['addr'];
1380 $mention = '@' . $term['url'];
1383 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1387 $announce = self::getAnnounceArray($item);
1388 // Mention the original author upon commented reshares
1389 if (!empty($announce['comment'])) {
1390 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1393 // @see https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-e232.md
1394 if (!empty($quote_url)) {
1395 // Currently deactivated because of compatibility issues with Pleroma
1397 // 'type' => 'Link',
1398 // 'mediaType' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
1399 // 'href' => $quote_url,
1400 // 'name' => '♲ ' . BBCode::convertForUriId($item['uri-id'], $quote_url, BBCode::ACTIVITYPUB)
1408 * Adds attachment data to the JSON document
1410 * @param array $item Data of the item that is to be posted
1412 * @return array with attachment data
1413 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1415 private static function createAttachmentList(array $item): array
1420 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1421 if (in_array($attachment['url'], $urls)) {
1424 $urls[] = $attachment['url'];
1426 $attach = ['type' => 'Document',
1427 'mediaType' => $attachment['mimetype'],
1428 'url' => $attachment['url'],
1429 'name' => $attachment['description']];
1431 if (!empty($attachment['height'])) {
1432 $attach['height'] = $attachment['height'];
1435 if (!empty($attachment['width'])) {
1436 $attach['width'] = $attachment['width'];
1439 if (!empty($attachment['preview'])) {
1440 $attach['image'] = $attachment['preview'];
1443 $attachments[] = $attach;
1446 return $attachments;
1450 * Callback function to replace a Friendica style mention in a mention for a summary
1452 * @param array $match Matching values for the callback
1453 * @return string Replaced mention
1454 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1456 private static function mentionAddrCallback(array $match): string
1458 if (empty($match[1])) {
1462 $data = Contact::getByURL($match[1], false, ['addr']);
1463 if (empty($data['addr'])) {
1467 return '@' . $data['addr'];
1471 * Remove image elements since they are added as attachment
1473 * @param string $body HTML code
1474 * @return string with removed images
1476 private static function removePictures(string $body): string
1478 // Simplify image codes
1479 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1480 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1482 // Now remove local links
1483 $body = preg_replace_callback(
1484 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1486 // We remove the link when it is a link to a local photo page
1487 if (Photo::isLocalPage($match[1])) {
1490 // otherwise we just return the link
1491 return '[url]' . $match[1] . '[/url]';
1496 // Remove all pictures
1497 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1503 * Returns if the post contains sensitive content ("nsfw")
1505 * @param integer $uri_id URI id
1506 * @return boolean Whether URI id was found
1507 * @throws \Exception
1509 private static function isSensitive(int $uri_id): bool
1511 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1515 * Creates event data
1517 * @param array $item Item array
1518 * @return array with the event data
1519 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1521 private static function createEvent(array $item): array
1524 $event['name'] = $item['event-summary'];
1525 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1526 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1528 if (!$item['event-nofinish']) {
1529 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1532 if (!empty($item['event-location'])) {
1533 $item['location'] = $item['event-location'];
1534 $event['location'] = self::createLocation($item);
1537 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1538 $event['dfrn:adjust'] = true;
1544 * Creates a note/article object array
1546 * @param array $item
1547 * @return array with the object data
1548 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1549 * @throws \ImagickException
1551 public static function createNote(array $item): array
1557 // We are treating posts differently when they are directed to a community.
1558 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1559 // But to not risk compatibility issues we currently perform the changes only for communities.
1560 if ($item['gravity'] == Item::GRAVITY_PARENT) {
1561 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1562 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1563 if ($isCommunityPost && (count($links) == 1)) {
1564 $link = $links[0]['url'];
1567 $isCommunityPost = false;
1570 if ($item['event-type'] == 'event') {
1572 } elseif (!empty($item['title'])) {
1573 if (!$isCommunityPost || empty($link)) {
1576 // "Page" is used by Lemmy for posts that contain an external link
1583 if ($item['deleted']) {
1584 $type = 'Tombstone';
1588 $data['id'] = $item['uri'];
1589 $data['type'] = $type;
1591 if ($item['deleted']) {
1595 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1597 if ($item['uri'] != $item['thr-parent']) {
1598 $data['inReplyTo'] = $item['thr-parent'];
1600 $data['inReplyTo'] = null;
1603 $data['diaspora:guid'] = $item['guid'];
1604 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1606 if ($item['created'] != $item['edited']) {
1607 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1610 $data['url'] = $link ?? $item['plink'];
1611 $data['attributedTo'] = $item['author-link'];
1612 $data['sensitive'] = self::isSensitive($item['uri-id']);
1614 if (!empty($item['conversation']) && ($item['conversation'] != './')) {
1615 $data['conversation'] = $data['context'] = $item['conversation'];
1618 if (!empty($item['title'])) {
1619 $data['name'] = BBCode::toPlaintext($item['title'], false);
1622 $permission_block = self::createPermissionBlockForItem($item, false);
1624 $body = $item['body'];
1626 if ($type == 'Note') {
1627 $body = $item['raw-body'] ?? self::removePictures($body);
1631 * @todo Improve the automated summary
1632 * This part is currently deactivated. The automated summary seems to be more
1633 * confusing than helping. But possibly we will find a better way.
1634 * So the code is left here for now as a reminder
1636 * } elseif (($type == 'Article') && empty($data['summary'])) {
1637 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1638 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1639 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1643 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1644 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1647 if ($type == 'Event') {
1648 $data = array_merge($data, self::createEvent($item));
1650 if ($isCommunityPost) {
1651 // For community posts we remove the visible "!user@domain.tld".
1652 // This improves the look at systems like Lemmy.
1653 // Also in the future we should control the community delivery via other methods.
1654 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1657 if ($type == 'Page') {
1658 // When we transmit "Page" posts we have to remove the attachment.
1659 // The attachment contains the link that we already transmit in the "url" field.
1660 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1663 $body = BBCode::setMentionsToNicknames($body);
1665 $shared = BBCode::fetchShareAttributes($body);
1666 if (!empty($shared['link']) && !empty($shared['guid']) && !empty($shared['comment'])) {
1667 $body = self::replaceSharedData($body);
1668 $data['quoteUrl'] = $shared['link'];
1671 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1674 // The regular "content" field does contain a minimized HTML. This is done since systems like
1675 // Mastodon has got problems with - for example - embedded pictures.
1676 // The contentMap does contain the unmodified HTML.
1677 $language = self::getLanguage($item);
1678 if (!empty($language)) {
1679 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1681 $shared = BBCode::fetchShareAttributes($richbody);
1682 if (!empty($shared['link']) && !empty($shared['guid']) && !empty($shared['comment'])) {
1683 $richbody = self::replaceSharedData($richbody);
1686 $richbody = BBCode::removeAttachment($richbody);
1688 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1691 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1693 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1694 $data['diaspora:comment'] = $item['signed_text'];
1697 $data['attachment'] = self::createAttachmentList($item);
1698 $data['tag'] = self::createTagList($item, $data['quoteUrl'] ?? '');
1700 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1701 $data['location'] = self::createLocation($item);
1704 if (!empty($item['app'])) {
1705 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1708 $data = array_merge($data, $permission_block);
1714 * Replace the share block with a link
1716 * @param string $body
1719 private static function replaceSharedData(string $body): string
1721 return BBCode::convertShare(
1723 function (array $attributes) {
1724 return '♲ ' . $attributes['link'];
1730 * Fetches the language from the post, the user or the system.
1732 * @param array $item
1733 * @return string language string
1735 private static function getLanguage(array $item): string
1737 // Try to fetch the language from the post itself
1738 if (!empty($item['language'])) {
1739 $languages = array_keys(json_decode($item['language'], true));
1740 if (!empty($languages[0])) {
1741 return $languages[0];
1745 // Otherwise use the user's language
1746 if (!empty($item['uid'])) {
1747 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1748 if (!empty($user['language'])) {
1749 return $user['language'];
1753 // And finally just use the system language
1754 return DI::config()->get('system', 'language');
1758 * Creates an an "add tag" entry
1760 * @param array $item Item array
1761 * @param array $activity activity data
1762 * @return array with activity data for adding tags
1763 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1764 * @throws \ImagickException
1766 private static function createAddTag(array $item, array $activity): array
1768 $object = XML::parseString($item['object']);
1769 $target = XML::parseString($item['target']);
1771 $activity['diaspora:guid'] = $item['guid'];
1772 $activity['actor'] = $item['author-link'];
1773 $activity['target'] = (string)$target->id;
1774 $activity['summary'] = BBCode::toPlaintext($item['body']);
1775 $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1781 * Creates an announce object entry
1783 * @param array $item Item array
1784 * @param array $activity activity data
1785 * @return array with activity data
1786 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1787 * @throws \ImagickException
1789 private static function createAnnounce(array $item, array $activity): array
1791 $orig_body = $item['body'];
1792 $announce = self::getAnnounceArray($item);
1793 if (empty($announce)) {
1794 $activity['type'] = 'Create';
1795 $activity['object'] = self::createNote($item);
1799 if (empty($announce['comment'])) {
1800 // Pure announce, without a quote
1801 $activity['type'] = 'Announce';
1802 $activity['object'] = $announce['object']['uri'];
1807 $activity['type'] = 'Create';
1808 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1809 $activity['object'] = self::createNote($item);
1811 /// @todo Finally descide how to implement this in AP. This is a possible way:
1812 $activity['object']['attachment'][] = self::createNote($announce['object']);
1814 $activity['object']['source']['content'] = $orig_body;
1819 * Return announce related data if the item is an annunce
1821 * @param array $item
1822 * @return array Announcement array
1824 public static function getAnnounceArray(array $item): array
1826 $reshared = Item::getShareArray($item);
1827 if (empty($reshared['guid'])) {
1831 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1832 if (!DBA::isResult($reshared_item)) {
1836 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1840 $profile = APContact::getByURL($reshared_item['author-link'], false);
1841 if (empty($profile)) {
1845 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1849 * Checks if the provided item array is an announce
1851 * @param array $item Item array
1852 * @return boolean Whether item is an announcement
1854 public static function isAnnounce(array $item): bool
1856 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1860 $announce = self::getAnnounceArray($item);
1861 if (empty($announce)) {
1865 return empty($announce['comment']);
1869 * Creates an activity id for a given contact id
1871 * @param integer $cid Contact ID of target
1873 * @return bool|string activity id
1875 public static function activityIDFromContact(int $cid)
1877 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1878 if (!DBA::isResult($contact)) {
1882 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1883 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1884 return DI::baseUrl() . '/activity/' . $uuid;
1888 * Transmits a contact suggestion to a given inbox
1890 * @param integer $uid User ID
1891 * @param string $inbox Target inbox
1892 * @param integer $suggestion_id Suggestion ID
1893 * @return boolean was the transmission successful?
1894 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1896 public static function sendContactSuggestion(int $uid, string $inbox, int $suggestion_id): bool
1898 $owner = User::getOwnerDataById($uid);
1900 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1903 '@context' => ActivityPub::CONTEXT,
1904 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1905 'type' => 'Announce',
1906 'actor' => $owner['url'],
1907 'object' => $suggestion->url,
1908 'content' => $suggestion->note,
1909 'instrument' => self::getService(),
1910 'to' => [ActivityPub::PUBLIC_COLLECTION],
1914 $signed = LDSignature::sign($data, $owner);
1916 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1917 return HTTPSignature::transmit($signed, $inbox, $uid);
1921 * Transmits a profile relocation to a given inbox
1923 * @param integer $uid User ID
1924 * @param string $inbox Target inbox
1925 * @return boolean was the transmission successful?
1926 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1928 public static function sendProfileRelocation(int $uid, string $inbox): bool
1930 $owner = User::getOwnerDataById($uid);
1933 '@context' => ActivityPub::CONTEXT,
1934 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1935 'type' => 'dfrn:relocate',
1936 'actor' => $owner['url'],
1937 'object' => $owner['url'],
1938 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1939 'instrument' => self::getService(),
1940 'to' => [ActivityPub::PUBLIC_COLLECTION],
1944 $signed = LDSignature::sign($data, $owner);
1946 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1947 return HTTPSignature::transmit($signed, $inbox, $uid);
1951 * Transmits a profile deletion to a given inbox
1953 * @param integer $uid User ID
1954 * @param string $inbox Target inbox
1955 * @return boolean was the transmission successful?
1956 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1958 public static function sendProfileDeletion(int $uid, string $inbox): bool
1960 $owner = User::getOwnerDataById($uid);
1962 if (empty($owner)) {
1963 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1967 if (empty($owner['uprvkey'])) {
1968 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1972 $data = ['@context' => ActivityPub::CONTEXT,
1973 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1975 'actor' => $owner['url'],
1976 'object' => $owner['url'],
1977 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1978 'instrument' => self::getService(),
1979 'to' => [ActivityPub::PUBLIC_COLLECTION],
1982 $signed = LDSignature::sign($data, $owner);
1984 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1985 return HTTPSignature::transmit($signed, $inbox, $uid);
1989 * Transmits a profile change to a given inbox
1991 * @param integer $uid User ID
1992 * @param string $inbox Target inbox
1993 * @return boolean was the transmission successful?
1994 * @throws HTTPException\InternalServerErrorException
1995 * @throws HTTPException\NotFoundException
1996 * @throws \ImagickException
1998 public static function sendProfileUpdate(int $uid, string $inbox): bool
2000 $owner = User::getOwnerDataById($uid);
2001 $profile = APContact::getByURL($owner['url']);
2003 $data = ['@context' => ActivityPub::CONTEXT,
2004 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2006 'actor' => $owner['url'],
2007 'object' => self::getProfile($uid),
2008 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2009 'instrument' => self::getService(),
2010 'to' => [$profile['followers']],
2013 $signed = LDSignature::sign($data, $owner);
2015 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
2016 return HTTPSignature::transmit($signed, $inbox, $uid);
2020 * Transmits a given activity to a target
2022 * @param string $activity Type name
2023 * @param string $target Target profile
2024 * @param integer $uid User ID
2025 * @param string $id Activity-identifier
2027 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2028 * @throws \ImagickException
2029 * @throws \Exception
2031 public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2033 $profile = APContact::getByURL($target);
2034 if (empty($profile['inbox'])) {
2035 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2039 $owner = User::getOwnerDataById($uid);
2042 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2046 '@context' => ActivityPub::CONTEXT,
2048 'type' => $activity,
2049 'actor' => $owner['url'],
2050 'object' => $profile['url'],
2051 'instrument' => self::getService(),
2052 'to' => [$profile['url']],
2055 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2057 $signed = LDSignature::sign($data, $owner);
2058 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2062 * Transmits a "follow object" activity to a target
2063 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2065 * @param string $object Object URL
2066 * @param string $target Target profile
2067 * @param integer $uid User ID
2069 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2070 * @throws \ImagickException
2071 * @throws \Exception
2073 public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2075 $profile = APContact::getByURL($target);
2076 if (empty($profile['inbox'])) {
2077 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2082 // Fetch the list of administrators
2083 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2085 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2086 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2087 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2088 $uid = $first_user['uid'];
2091 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2092 'author-id' => Contact::getPublicIdByUserId($uid)];
2093 if (Post::exists($condition)) {
2094 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2098 $owner = User::getOwnerDataById($uid);
2101 '@context' => ActivityPub::CONTEXT,
2102 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2104 'actor' => $owner['url'],
2105 'object' => $object,
2106 'instrument' => self::getService(),
2107 'to' => [$profile['url']],
2110 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2112 $signed = LDSignature::sign($data, $owner);
2113 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2117 * Transmit a message that the contact request had been accepted
2119 * @param string $target Target profile
2120 * @param string $id Object id
2121 * @param integer $uid User ID
2123 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2124 * @throws \ImagickException
2126 public static function sendContactAccept(string $target, string $id, int $uid)
2128 $profile = APContact::getByURL($target);
2129 if (empty($profile['inbox'])) {
2130 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2134 $owner = User::getOwnerDataById($uid);
2136 '@context' => ActivityPub::CONTEXT,
2137 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2139 'actor' => $owner['url'],
2143 'actor' => $profile['url'],
2144 'object' => $owner['url']
2146 'instrument' => self::getService(),
2147 'to' => [$profile['url']],
2150 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2152 $signed = LDSignature::sign($data, $owner);
2153 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2157 * Reject a contact request or terminates the contact relation
2159 * @param string $target Target profile
2160 * @param string $objectId Object id
2161 * @param int $uid User ID
2162 * @return bool Operation success
2163 * @throws HTTPException\InternalServerErrorException
2164 * @throws \ImagickException
2166 public static function sendContactReject(string $target, string $objectId, int $uid): bool
2168 $profile = APContact::getByURL($target);
2169 if (empty($profile['inbox'])) {
2170 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2174 $owner = User::getOwnerDataById($uid);
2176 '@context' => ActivityPub::CONTEXT,
2177 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2179 'actor' => $owner['url'],
2183 'actor' => $profile['url'],
2184 'object' => $owner['url']
2186 'instrument' => self::getService(),
2187 'to' => [$profile['url']],
2190 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2192 $signed = LDSignature::sign($data, $owner);
2193 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2197 * Transmits a message that we don't want to follow this contact anymore
2199 * @param string $target Target profile
2200 * @param integer $cid Contact id
2201 * @param integer $uid User ID
2202 * @return bool success
2203 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2204 * @throws \ImagickException
2205 * @throws \Exception
2207 public static function sendContactUndo(string $target, int $cid, int $uid): bool
2209 $profile = APContact::getByURL($target);
2210 if (empty($profile['inbox'])) {
2211 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2215 $object_id = self::activityIDFromContact($cid);
2216 if (empty($object_id)) {
2220 $objectId = DI::baseUrl() . '/activity/' . System::createGUID();
2222 $owner = User::getOwnerDataById($uid);
2224 '@context' => ActivityPub::CONTEXT,
2227 'actor' => $owner['url'],
2231 'actor' => $owner['url'],
2232 'object' => $profile['url']
2234 'instrument' => self::getService(),
2235 'to' => [$profile['url']],
2238 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2240 $signed = LDSignature::sign($data, $owner);
2241 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2245 * Prepends mentions (@) to $body variable
2247 * @param string $body HTML code
2249 * @param string $authorLink Author link
2250 * @return string HTML code with prepended mentions
2252 private static function prependMentions(string $body, int $uriid, string $authorLink): string
2256 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2257 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2258 if (!empty($profile['addr'])
2259 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2260 && !strstr($body, $profile['addr'])
2261 && !strstr($body, $tag['url'])
2262 && $tag['url'] !== $authorLink
2264 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2268 $mentions[] = $body;
2270 return implode(' ', $mentions);