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;
25 use Friendica\Content\Feature;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\GServer;
36 use Friendica\Model\Item;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Model\Tag;
40 use Friendica\Model\User;
41 use Friendica\Network\HTTPException;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Protocol\Diaspora;
45 use Friendica\Protocol\Relay;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\HTTPSignature;
48 use Friendica\Util\LDSignature;
49 use Friendica\Util\Map;
50 use Friendica\Util\Network;
51 use Friendica\Util\Strings;
52 use Friendica\Util\XML;
55 * ActivityPub Transmitter Protocol class
62 const CACHEKEY_FEATURED = 'transmitter:getFeatured:';
63 const CACHEKEY_CONTACTS = 'transmitter:getContacts:';
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
255 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
257 if (!empty($requester)) {
258 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
259 if (!empty($requester_id)) {
260 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
261 if (!empty($permissionSets)) {
262 $condition = ['psid' => array_merge($permissionSets->column('id'),
263 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
268 $condition = array_merge($condition, [
269 'uid' => $owner['uid'],
270 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
271 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
272 'network' => Protocol::FEDERATED,
273 'parent-network' => Protocol::FEDERATED,
279 $apcontact = APContact::getByURL($owner['url']);
281 $data = ['@context' => ActivityPub::CONTEXT];
282 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
283 $data['type'] = 'OrderedCollection';
284 $data['totalItems'] = $apcontact['statuses_count'] ?? 0;
287 $data['id'] .= '?' . http_build_query(['page' => $page]);
291 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
293 $data['type'] = 'OrderedCollectionPage';
296 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
297 while ($item = Post::fetch($items)) {
298 $activity = self::createActivityFromItem($item['id'], true);
299 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
301 // Only list "Create" activity objects here, no reshares
302 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
303 $list[] = $activity['object'];
308 if (count($list) == 20) {
309 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
312 // Fix the cached total item count when it is lower than the real count
313 $total = (($page - 1) * 20) + $data['totalItems'];
314 if ($total > $data['totalItems']) {
315 $data['totalItems'] = $total;
318 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
320 $data['orderedItems'] = $list;
327 * Public posts for the given owner
329 * @param array $owner Owner array
330 * @param integer $page Page number
331 * @param boolean $nocache Wether to bypass caching
333 * @return array of posts
334 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
335 * @throws \ImagickException
337 public static function getFeatured(array $owner, int $page = null, bool $nocache = false): array
340 $cachekey = self::CACHEKEY_FEATURED . $owner['uid'];
341 $result = DI::cache()->get($cachekey);
342 if (!$nocache && !is_null($result)) {
347 $owner_cid = Contact::getIdForURL($owner['url'], 0, false);
349 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
350 $owner_cid, Post\Collection::FEATURED];
352 $condition = DBA::mergeConditions($condition, [
353 'uid' => $owner['uid'],
354 'author-id' => $owner_cid,
355 'private' => [Item::PUBLIC, Item::UNLISTED],
356 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
357 'network' => Protocol::FEDERATED,
358 'parent-network' => Protocol::FEDERATED,
364 $count = Post::count($condition);
366 $data = ['@context' => ActivityPub::CONTEXT];
367 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
368 $data['type'] = 'OrderedCollection';
369 $data['totalItems'] = $count;
372 $data['id'] .= '?' . http_build_query(['page' => $page]);
376 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
378 $data['type'] = 'OrderedCollectionPage';
379 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
383 while ($item = Post::fetch($items)) {
384 $activity = self::createActivityFromItem($item['id'], true);
385 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
387 // Only list "Create" activity objects here, no reshares
388 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
389 $list[] = $activity['object'];
394 if (count($list) == 20) {
395 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
399 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
402 $data['orderedItems'] = $list;
404 if (!empty($cachekey)) {
405 DI::cache()->set($cachekey, $data, Duration::DAY);
412 * Return the service array containing information the used software and it's url
414 * @return array with service data
416 private static function getService(): array
420 'name' => App::PLATFORM . " '" . App::CODENAME . "' " . App::VERSION . '-' . DB_UPDATE_VERSION,
421 'url' => DI::baseUrl()->get()
426 * Return the ActivityPub profile of the given user
428 * @param int $uid User ID
429 * @return array with profile data
430 * @throws HTTPException\NotFoundException
431 * @throws HTTPException\InternalServerErrorException
433 public static function getProfile(int $uid): array
435 $owner = User::getOwnerDataById($uid);
436 if (!isset($owner['id'])) {
437 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
438 throw new HTTPException\NotFoundException('User not found.');
441 $data = ['@context' => ActivityPub::CONTEXT];
442 $data['id'] = $owner['url'];
444 if (!empty($owner['guid'])) {
445 $data['diaspora:guid'] = $owner['guid'];
448 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
451 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
452 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
453 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
454 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
455 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
457 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
460 $data['preferredUsername'] = $owner['nick'];
461 $data['name'] = $owner['name'];
463 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
464 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
465 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
468 if (!empty($owner['about'])) {
469 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
472 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
473 $data['vcard:hasInstantMessage'] = [];
475 if (!empty($owner['xmpp'])) {
476 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
478 if (!empty($owner['matrix'])) {
479 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
483 $data['url'] = $owner['url'];
484 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
485 $data['discoverable'] = (bool)$owner['net-publish'];
486 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
487 'owner' => $owner['url'],
488 'publicKeyPem' => $owner['pubkey']];
489 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
490 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
492 $resourceid = Photo::ridFromURI($owner['photo']);
493 if (!empty($resourceid)) {
494 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
495 if (!empty($photo['type'])) {
496 $data['icon']['mediaType'] = $photo['type'];
500 if (!empty($owner['header'])) {
501 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
503 $resourceid = Photo::ridFromURI($owner['header']);
504 if (!empty($resourceid)) {
505 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
506 if (!empty($photo['type'])) {
507 $data['image']['mediaType'] = $photo['type'];
514 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
516 'type' => 'PropertyValue',
517 'name' => $profile_field->label,
518 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
522 if (!empty($custom_fields)) {
523 $data['attachment'] = $custom_fields;
526 $data['generator'] = self::getService();
528 // tags: https://kitty.town/@inmysocks/100656097926961126.json
533 * @param string $username
535 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
537 public static function getDeletedUser(string $username): array
540 '@context' => ActivityPub::CONTEXT,
541 'id' => DI::baseUrl() . '/profile/' . $username,
542 'type' => 'Tombstone',
543 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
544 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
545 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
550 * Returns an array with permissions of the thread parent of the given item array
553 * @param bool $is_forum_thread
555 * @return array with permissions
556 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
557 * @throws \ImagickException
559 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread): array
561 if (empty($item['thr-parent-id'])) {
565 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
566 if (empty($parent)) {
571 'to' => [$parent['author-link']],
577 $parent_profile = APContact::getByURL($parent['author-link']);
579 $item_profile = APContact::getByURL($item['author-link']);
580 $exclude[] = $item['author-link'];
582 if ($item['gravity'] == Item::GRAVITY_PARENT) {
583 $exclude[] = $item['owner-link'];
586 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
587 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
588 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
589 if (!$is_forum_thread) {
590 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
592 } elseif (!in_array($receiver['url'], $exclude)) {
593 $permissions[$type[$receiver['type']]][] = $receiver['url'];
601 * Check if the given item id is from ActivityPub
603 * @param integer $item_id
604 * @return boolean "true" if the post is from ActivityPub
606 private static function isAPPost(int $item_id): bool
608 if (empty($item_id)) {
612 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
616 * Creates an array of permissions from an item thread
618 * @param array $item Item array
619 * @param boolean $blindcopy addressing via "bcc" or "cc"?
620 * @param integer $last_id Last item id for adding receivers
622 * @return array with permission data
623 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
624 * @throws \ImagickException
626 private static function createPermissionBlockForItem(array $item, bool $blindcopy, int $last_id = 0): array
629 $last_id = $item['id'];
636 // Check if we should always deliver our stuff via BCC
637 if (!empty($item['uid'])) {
638 $owner = User::getOwnerDataById($item['uid']);
639 if (!empty($owner)) {
640 $always_bcc = $owner['hide-friends'];
641 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
643 $profile = APContact::getByURL($owner['url'], false);
644 $follower = $profile['followers'] ?? '';
648 if (DI::config()->get('system', 'ap_always_bcc')) {
652 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
653 if (!empty($parent) && ($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
654 $profile = APContact::getByURL($parent['causer-link'], false);
655 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
657 $is_forum_thread = false;
660 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
661 // Will be activated in a later step
662 $networks = Protocol::FEDERATED;
664 // For now only send to these contacts:
665 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
668 $data = ['to' => [], 'cc' => [], 'bcc' => []];
670 if ($item['gravity'] == Item::GRAVITY_PARENT) {
671 $actor_profile = APContact::getByURL($item['owner-link']);
673 $actor_profile = APContact::getByURL($item['author-link']);
678 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
680 if ($item['private'] != Item::PRIVATE) {
681 // Directly mention the original author upon a quoted reshare.
682 // Else just ensure that the original author receives the reshare.
683 $announce = self::getAnnounceArray($item);
684 if (!empty($announce['comment'])) {
685 $data['to'][] = $announce['actor']['url'];
686 } elseif (!empty($announce)) {
687 $data['cc'][] = $announce['actor']['url'];
690 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
692 // Check if the item is completely public or unlisted
693 if ($item['private'] == Item::PUBLIC) {
694 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
696 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
699 foreach ($terms as $term) {
700 $profile = APContact::getByURL($term['url'], false);
701 if (!empty($profile)) {
702 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
704 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
705 $data['cc'][] = $profile['followers'];
708 $data['to'][] = $profile['url'];
712 $receiver_list = Item::enumeratePermissions($item, true);
714 foreach ($terms as $term) {
715 $cid = Contact::getIdForURL($term['url'], $item['uid']);
716 if (!empty($cid) && in_array($cid, $receiver_list)) {
717 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
718 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
722 $profile = APContact::getByURL($term['url'], false);
723 if (!empty($profile)) {
724 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
726 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
727 $data['cc'][] = $profile['followers'];
730 $data['to'][] = $profile['url'];
735 if ($is_forum && !$exclusive && !empty($follower)) {
736 $data['cc'][] = $follower;
737 } elseif (!$exclusive) {
738 foreach ($receiver_list as $receiver) {
739 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
740 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
744 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
745 if ($contact['hidden'] || $always_bcc) {
746 $data['bcc'][] = $profile['url'];
748 $data['cc'][] = $profile['url'];
755 if (!empty($item['parent'])) {
756 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']], ['order' => ['id']]);
757 while ($parent = Post::fetch($parents)) {
758 if ($parent['gravity'] == Item::GRAVITY_PARENT) {
759 $profile = APContact::getByURL($parent['owner-link'], false);
760 if (!empty($profile)) {
761 if ($item['gravity'] != Item::GRAVITY_PARENT) {
762 // Comments to forums are directed to the forum
763 // But comments to forums aren't directed to the followers collection
764 // This rule is only valid when the actor isn't the forum.
765 // The forum needs to transmit their content to their followers.
766 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
767 $data['to'][] = $profile['url'];
769 $data['cc'][] = $profile['url'];
770 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers']) && (!$exclusive || !$is_forum_thread)) {
771 $data['cc'][] = $actor_profile['followers'];
774 } elseif (!$exclusive && !$is_forum_thread) {
775 // Public thread parent post always are directed to the followers.
776 if ($item['private'] != Item::PRIVATE) {
777 $data['cc'][] = $actor_profile['followers'];
783 // Don't include data from future posts
784 if ($parent['id'] >= $last_id) {
788 $profile = APContact::getByURL($parent['author-link'], false);
789 if (!empty($profile)) {
790 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
791 $data['to'][] = $profile['url'];
793 $data['cc'][] = $profile['url'];
797 DBA::close($parents);
800 $data['to'] = array_unique($data['to']);
801 $data['cc'] = array_unique($data['cc']);
802 $data['bcc'] = array_unique($data['bcc']);
804 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
805 unset($data['to'][$key]);
808 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
809 unset($data['cc'][$key]);
812 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
813 unset($data['bcc'][$key]);
816 foreach ($data['to'] as $to) {
817 if (($key = array_search($to, $data['cc'])) !== false) {
818 unset($data['cc'][$key]);
821 if (($key = array_search($to, $data['bcc'])) !== false) {
822 unset($data['bcc'][$key]);
826 foreach ($data['cc'] as $cc) {
827 if (($key = array_search($cc, $data['bcc'])) !== false) {
828 unset($data['bcc'][$key]);
832 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
835 unset($receivers['bcc']);
838 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
839 if (!empty($receivers[$element])) {
840 foreach ($receivers[$element] as $receiver) {
841 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
842 $name = Receiver::PUBLIC_COLLECTION;
844 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
846 Tag::store($item['uri-id'], $type, $name, $receiver);
855 * Check if an inbox is archived
857 * @param string $url Inbox url
858 * @return boolean "true" if inbox is archived
860 public static function archivedInbox(string $url): bool
862 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
866 * Check if a given contact should be delivered via AP
868 * @param array $contact Contact array
869 * @param array $networks Array with networks
870 * @return bool Whether the used protocol matches ACTIVITYPUB
873 private static function isAPContact(array $contact, array $networks): bool
875 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
879 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
883 * Fetches a list of inboxes of followers of a given user
885 * @param integer $uid User ID
886 * @param boolean $personal fetch personal inboxes
887 * @param boolean $all_ap Retrieve all AP enabled inboxes
888 * @return array of follower inboxes
889 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
890 * @throws \ImagickException
892 public static function fetchTargetInboxesforUser(int $uid, bool $personal = false, bool $all_ap = false): array
898 if (!empty($item['uid'])) {
899 $profile = User::getOwnerDataById($item['uid']);
900 if (!empty($profile)) {
901 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
905 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
906 // Will be activated in a later step
907 $networks = Protocol::FEDERATED;
909 // For now only send to these contacts:
910 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
918 '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'] == Item::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'] ? Item::GRAVITY_COMMENT: Item::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|false activity or false on failure
1188 * @throws \Exception
1190 public static function createCachedActivityFromItem(int $item_id, bool $force = false, bool $object_mode = false)
1192 $cachekey = 'APDelivery:createActivity:' . $item_id . ':' . (int)$object_mode;
1195 $data = DI::cache()->get($cachekey);
1196 if (!is_null($data)) {
1201 $data = self::createActivityFromItem($item_id, $object_mode);
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 $data = Post\Activity::getByURIId($item['uri-id']);
1230 if (!$item['origin'] && !empty($data)) {
1232 unset($data['@context']);
1233 unset($data['signature']);
1235 Logger::info('Return stored conversation', ['item' => $item_id]);
1240 if (!$item['origin'] && empty($object)) {
1241 Logger::debug('Post is not ours and is not stored', ['id' => $item_id, 'uri-id' => $item['uri-id']]);
1245 $type = self::getTypeOfItem($item);
1247 if (!$object_mode) {
1248 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1250 if ($item['deleted'] && ($item['gravity'] == Item::GRAVITY_ACTIVITY)) {
1252 } elseif ($item['deleted']) {
1259 if ($type == 'Delete') {
1260 $data['id'] = Item::newURI($item['guid']) . '/' . $type;;
1261 } elseif (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1262 $data['id'] = $item['uri'];
1264 $data['id'] = $item['uri'] . '/' . $type;
1267 $data['type'] = $type;
1269 if (($type != 'Announce') || ($item['gravity'] != Item::GRAVITY_PARENT)) {
1270 $data['actor'] = $item['author-link'];
1272 $data['actor'] = $item['owner-link'];
1275 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1277 $data['instrument'] = self::getService();
1279 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1281 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1282 $data['object'] = $object ?? self::createNote($item);
1283 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1284 } elseif ($data['type'] == 'Add') {
1285 $data = self::createAddTag($item, $data);
1286 } elseif ($data['type'] == 'Announce') {
1287 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1288 $data['object'] = $item['thr-parent'];
1290 $data = self::createAnnounce($item, $data);
1292 } elseif ($data['type'] == 'Follow') {
1293 $data['object'] = $item['parent-uri'];
1294 } elseif ($data['type'] == 'Undo') {
1295 $data['object'] = self::createActivityFromItem($item_id, true);
1297 $data['diaspora:guid'] = $item['guid'];
1298 if (!empty($item['signed_text'])) {
1299 $data['diaspora:like'] = $item['signed_text'];
1301 $data['object'] = $item['thr-parent'];
1304 if (!empty($item['contact-uid'])) {
1305 $uid = $item['contact-uid'];
1307 $uid = $item['uid'];
1310 $owner = User::getOwnerDataById($uid);
1312 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1314 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1315 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1316 return LDSignature::sign($data, $owner);
1321 /// @todo Create "conversation" entry
1325 * Creates a location entry for a given item array
1327 * @param array $item Item array
1328 * @return array with location array
1330 private static function createLocation(array $item): array
1332 $location = ['type' => 'Place'];
1334 if (!empty($item['location'])) {
1335 $location['name'] = $item['location'];
1340 if (empty($item['coord'])) {
1341 $coord = Map::getCoordinates($item['location']);
1343 $coords = explode(' ', $item['coord']);
1344 if (count($coords) == 2) {
1345 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1349 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1350 $location['latitude'] = $coord['lat'];
1351 $location['longitude'] = $coord['lon'];
1358 * Returns a tag array for a given item array
1360 * @param array $item Item array
1361 * @param string $quote_url Url of the attached quote link
1362 * @return array of tags
1363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1365 private static function createTagList(array $item, string $quote_url): array
1369 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1370 foreach ($terms as $term) {
1371 if ($term['type'] == Tag::HASHTAG) {
1372 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1373 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1375 $contact = Contact::getByURL($term['url'], false, ['addr']);
1376 if (empty($contact)) {
1379 if (!empty($contact['addr'])) {
1380 $mention = '@' . $contact['addr'];
1382 $mention = '@' . $term['url'];
1385 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1389 $announce = self::getAnnounceArray($item);
1390 // Mention the original author upon commented reshares
1391 if (!empty($announce['comment'])) {
1392 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1395 // @see https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-e232.md
1396 if (!empty($quote_url)) {
1397 // Currently deactivated because of compatibility issues with Pleroma
1399 // 'type' => 'Link',
1400 // 'mediaType' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
1401 // 'href' => $quote_url,
1402 // 'name' => '♲ ' . BBCode::convertForUriId($item['uri-id'], $quote_url, BBCode::ACTIVITYPUB)
1410 * Adds attachment data to the JSON document
1412 * @param array $item Data of the item that is to be posted
1414 * @return array with attachment data
1415 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1417 private static function createAttachmentList(array $item): array
1422 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1423 if (in_array($attachment['url'], $urls)) {
1426 $urls[] = $attachment['url'];
1428 $attach = ['type' => 'Document',
1429 'mediaType' => $attachment['mimetype'],
1430 'url' => $attachment['url'],
1431 'name' => $attachment['description']];
1433 if (!empty($attachment['height'])) {
1434 $attach['height'] = $attachment['height'];
1437 if (!empty($attachment['width'])) {
1438 $attach['width'] = $attachment['width'];
1441 if (!empty($attachment['preview'])) {
1442 $attach['image'] = $attachment['preview'];
1445 $attachments[] = $attach;
1448 return $attachments;
1452 * Callback function to replace a Friendica style mention in a mention for a summary
1454 * @param array $match Matching values for the callback
1455 * @return string Replaced mention
1456 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1458 private static function mentionAddrCallback(array $match): string
1460 if (empty($match[1])) {
1464 $data = Contact::getByURL($match[1], false, ['addr']);
1465 if (empty($data['addr'])) {
1469 return '@' . $data['addr'];
1473 * Remove image elements since they are added as attachment
1475 * @param string $body HTML code
1476 * @return string with removed images
1478 private static function removePictures(string $body): string
1480 // Simplify image codes
1481 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1482 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1484 // Now remove local links
1485 $body = preg_replace_callback(
1486 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1488 // We remove the link when it is a link to a local photo page
1489 if (Photo::isLocalPage($match[1])) {
1492 // otherwise we just return the link
1493 return '[url]' . $match[1] . '[/url]';
1498 // Remove all pictures
1499 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1505 * Returns if the post contains sensitive content ("nsfw")
1507 * @param integer $uri_id URI id
1508 * @return boolean Whether URI id was found
1509 * @throws \Exception
1511 private static function isSensitive(int $uri_id): bool
1513 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1517 * Creates event data
1519 * @param array $item Item array
1520 * @return array with the event data
1521 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1523 private static function createEvent(array $item): array
1526 $event['name'] = $item['event-summary'];
1527 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1528 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1530 if (!$item['event-nofinish']) {
1531 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1534 if (!empty($item['event-location'])) {
1535 $item['location'] = $item['event-location'];
1536 $event['location'] = self::createLocation($item);
1539 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1540 $event['dfrn:adjust'] = true;
1546 * Creates a note/article object array
1548 * @param array $item
1549 * @return array with the object data
1550 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1551 * @throws \ImagickException
1553 public static function createNote(array $item): array
1559 // We are treating posts differently when they are directed to a community.
1560 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1561 // But to not risk compatibility issues we currently perform the changes only for communities.
1562 if ($item['gravity'] == Item::GRAVITY_PARENT) {
1563 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1564 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1565 if ($isCommunityPost && (count($links) == 1)) {
1566 $link = $links[0]['url'];
1569 $isCommunityPost = false;
1572 if ($item['event-type'] == 'event') {
1574 } elseif (!empty($item['title'])) {
1575 if (!$isCommunityPost || empty($link)) {
1578 // "Page" is used by Lemmy for posts that contain an external link
1585 if ($item['deleted']) {
1586 $type = 'Tombstone';
1590 $data['id'] = $item['uri'];
1591 $data['type'] = $type;
1593 if ($item['deleted']) {
1597 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1599 if ($item['uri'] != $item['thr-parent']) {
1600 $data['inReplyTo'] = $item['thr-parent'];
1602 $data['inReplyTo'] = null;
1605 $data['diaspora:guid'] = $item['guid'];
1606 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1608 if ($item['created'] != $item['edited']) {
1609 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1612 $data['url'] = $link ?? $item['plink'];
1613 $data['attributedTo'] = $item['author-link'];
1614 $data['sensitive'] = self::isSensitive($item['uri-id']);
1616 if (!empty($item['conversation']) && ($item['conversation'] != './')) {
1617 $data['conversation'] = $data['context'] = $item['conversation'];
1620 if (!empty($item['title'])) {
1621 $data['name'] = BBCode::toPlaintext($item['title'], false);
1624 $permission_block = self::createPermissionBlockForItem($item, false);
1626 $real_quote = false;
1628 $body = $item['body'];
1630 if ($type == 'Note') {
1631 $body = $item['raw-body'] ?? self::removePictures($body);
1635 * @todo Improve the automated summary
1636 * This part is currently deactivated. The automated summary seems to be more
1637 * confusing than helping. But possibly we will find a better way.
1638 * So the code is left here for now as a reminder
1640 * } elseif (($type == 'Article') && empty($data['summary'])) {
1641 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1642 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1643 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1647 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1648 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1651 if ($type == 'Event') {
1652 $data = array_merge($data, self::createEvent($item));
1654 if ($isCommunityPost) {
1655 // For community posts we remove the visible "!user@domain.tld".
1656 // This improves the look at systems like Lemmy.
1657 // Also in the future we should control the community delivery via other methods.
1658 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1661 if ($type == 'Page') {
1662 // When we transmit "Page" posts we have to remove the attachment.
1663 // The attachment contains the link that we already transmit in the "url" field.
1664 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1667 $body = BBCode::setMentionsToNicknames($body);
1668 $exists_reshare = BBCode::existsShare($body);
1670 if (!empty($item['quote-uri']) && Post::exists(['uri-id' => $item['quote-uri-id'], 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN]])) {
1672 if ($exists_reshare) {
1673 $body = BBCode::replaceSharedData($body);
1674 } elseif (strpos($body, $item['quote-uri']) === false) {
1675 $body .= "\n♲ " . $item['quote-uri'];
1677 $data['quoteUrl'] = $item['quote-uri'];
1678 } elseif (!empty($item['quote-uri']) && !$exists_reshare) {
1679 $body .= "\n" . DI::contentItem()->createSharedPostByUriId($item['quote-uri-id'], $item['uid'], true);
1680 $item['body'] = DI::contentItem()->improveSharedDataInBody($item, true);
1683 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1686 // The regular "content" field does contain a minimized HTML. This is done since systems like
1687 // Mastodon has got problems with - for example - embedded pictures.
1688 // The contentMap does contain the unmodified HTML.
1689 $language = self::getLanguage($item);
1690 if (!empty($language)) {
1691 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1694 if (BBCode::existsShare($richbody)) {
1695 $richbody = BBCode::replaceSharedData($richbody);
1696 } elseif (strpos($richbody, $item['quote-uri']) === false) {
1697 $richbody .= "\n♲ " . $item['quote-uri'];
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);
1713 $data['tag'] = self::createTagList($item, $data['quoteUrl'] ?? '');
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 private static function getAnnounceArray(array $item): array
1825 $reshared = DI::contentItem()->getSharedPost($item, Item::DELIVER_FIELDLIST);
1826 if (empty($reshared)) {
1830 if (!in_array($reshared['post']['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1834 $profile = APContact::getByURL($reshared['post']['author-link'], false);
1835 if (empty($profile)) {
1839 return ['object' => $reshared['post'], 'actor' => $profile, 'comment' => $reshared['comment']];
1843 * Checks if the provided item array is an announce
1845 * @param array $item Item array
1846 * @return boolean Whether item is an announcement
1848 public static function isAnnounce(array $item): bool
1850 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1854 $announce = self::getAnnounceArray($item);
1855 if (empty($announce)) {
1859 return empty($announce['comment']);
1863 * Creates an activity id for a given contact id
1865 * @param integer $cid Contact ID of target
1867 * @return bool|string activity id
1869 public static function activityIDFromContact(int $cid)
1871 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1872 if (!DBA::isResult($contact)) {
1876 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1877 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1878 return DI::baseUrl() . '/activity/' . $uuid;
1882 * Transmits a contact suggestion to a given inbox
1884 * @param integer $uid User ID
1885 * @param string $inbox Target inbox
1886 * @param integer $suggestion_id Suggestion ID
1887 * @return boolean was the transmission successful?
1888 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1890 public static function sendContactSuggestion(int $uid, string $inbox, int $suggestion_id): bool
1892 $owner = User::getOwnerDataById($uid);
1894 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1897 '@context' => ActivityPub::CONTEXT,
1898 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1899 'type' => 'Announce',
1900 'actor' => $owner['url'],
1901 'object' => $suggestion->url,
1902 'content' => $suggestion->note,
1903 'instrument' => self::getService(),
1904 'to' => [ActivityPub::PUBLIC_COLLECTION],
1908 $signed = LDSignature::sign($data, $owner);
1910 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1911 return HTTPSignature::transmit($signed, $inbox, $uid);
1915 * Transmits a profile relocation to a given inbox
1917 * @param integer $uid User ID
1918 * @param string $inbox Target inbox
1919 * @return boolean was the transmission successful?
1920 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1922 public static function sendProfileRelocation(int $uid, string $inbox): bool
1924 $owner = User::getOwnerDataById($uid);
1927 '@context' => ActivityPub::CONTEXT,
1928 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1929 'type' => 'dfrn:relocate',
1930 'actor' => $owner['url'],
1931 'object' => $owner['url'],
1932 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1933 'instrument' => self::getService(),
1934 'to' => [ActivityPub::PUBLIC_COLLECTION],
1938 $signed = LDSignature::sign($data, $owner);
1940 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1941 return HTTPSignature::transmit($signed, $inbox, $uid);
1945 * Transmits a profile deletion to a given inbox
1947 * @param integer $uid User ID
1948 * @param string $inbox Target inbox
1949 * @return boolean was the transmission successful?
1950 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1952 public static function sendProfileDeletion(int $uid, string $inbox): bool
1954 $owner = User::getOwnerDataById($uid);
1956 if (empty($owner)) {
1957 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1961 if (empty($owner['uprvkey'])) {
1962 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1966 $data = ['@context' => ActivityPub::CONTEXT,
1967 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1969 'actor' => $owner['url'],
1970 'object' => $owner['url'],
1971 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1972 'instrument' => self::getService(),
1973 'to' => [ActivityPub::PUBLIC_COLLECTION],
1976 $signed = LDSignature::sign($data, $owner);
1978 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1979 return HTTPSignature::transmit($signed, $inbox, $uid);
1983 * Transmits a profile change to a given inbox
1985 * @param integer $uid User ID
1986 * @param string $inbox Target inbox
1987 * @return boolean was the transmission successful?
1988 * @throws HTTPException\InternalServerErrorException
1989 * @throws HTTPException\NotFoundException
1990 * @throws \ImagickException
1992 public static function sendProfileUpdate(int $uid, string $inbox): bool
1994 $owner = User::getOwnerDataById($uid);
1995 $profile = APContact::getByURL($owner['url']);
1997 $data = ['@context' => ActivityPub::CONTEXT,
1998 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2000 'actor' => $owner['url'],
2001 'object' => self::getProfile($uid),
2002 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2003 'instrument' => self::getService(),
2004 'to' => [$profile['followers']],
2007 $signed = LDSignature::sign($data, $owner);
2009 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
2010 return HTTPSignature::transmit($signed, $inbox, $uid);
2014 * Transmits a given activity to a target
2016 * @param string $activity Type name
2017 * @param string $target Target profile
2018 * @param integer $uid User ID
2019 * @param string $id Activity-identifier
2021 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2022 * @throws \ImagickException
2023 * @throws \Exception
2025 public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2027 $profile = APContact::getByURL($target);
2028 if (empty($profile['inbox'])) {
2029 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2033 $owner = User::getOwnerDataById($uid);
2036 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2040 '@context' => ActivityPub::CONTEXT,
2042 'type' => $activity,
2043 'actor' => $owner['url'],
2044 'object' => $profile['url'],
2045 'instrument' => self::getService(),
2046 'to' => [$profile['url']],
2049 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2051 $signed = LDSignature::sign($data, $owner);
2052 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2056 * Transmits a "follow object" activity to a target
2057 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2059 * @param string $object Object URL
2060 * @param string $target Target profile
2061 * @param integer $uid User ID
2063 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2064 * @throws \ImagickException
2065 * @throws \Exception
2067 public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2069 $profile = APContact::getByURL($target);
2070 if (empty($profile['inbox'])) {
2071 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2076 // Fetch the list of administrators
2077 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2079 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2080 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2081 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2082 $uid = $first_user['uid'];
2085 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2086 'author-id' => Contact::getPublicIdByUserId($uid)];
2087 if (Post::exists($condition)) {
2088 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2092 $owner = User::getOwnerDataById($uid);
2095 '@context' => ActivityPub::CONTEXT,
2096 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2098 'actor' => $owner['url'],
2099 'object' => $object,
2100 'instrument' => self::getService(),
2101 'to' => [$profile['url']],
2104 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2106 $signed = LDSignature::sign($data, $owner);
2107 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2111 * Transmit a message that the contact request had been accepted
2113 * @param string $target Target profile
2114 * @param string $id Object id
2115 * @param integer $uid User ID
2117 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2118 * @throws \ImagickException
2120 public static function sendContactAccept(string $target, string $id, int $uid)
2122 $profile = APContact::getByURL($target);
2123 if (empty($profile['inbox'])) {
2124 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2128 $owner = User::getOwnerDataById($uid);
2130 '@context' => ActivityPub::CONTEXT,
2131 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2133 'actor' => $owner['url'],
2137 'actor' => $profile['url'],
2138 'object' => $owner['url']
2140 'instrument' => self::getService(),
2141 'to' => [$profile['url']],
2144 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2146 $signed = LDSignature::sign($data, $owner);
2147 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2151 * Reject a contact request or terminates the contact relation
2153 * @param string $target Target profile
2154 * @param string $objectId Object id
2155 * @param int $uid User ID
2156 * @return bool Operation success
2157 * @throws HTTPException\InternalServerErrorException
2158 * @throws \ImagickException
2160 public static function sendContactReject(string $target, string $objectId, int $uid): bool
2162 $profile = APContact::getByURL($target);
2163 if (empty($profile['inbox'])) {
2164 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2168 $owner = User::getOwnerDataById($uid);
2170 '@context' => ActivityPub::CONTEXT,
2171 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2173 'actor' => $owner['url'],
2177 'actor' => $profile['url'],
2178 'object' => $owner['url']
2180 'instrument' => self::getService(),
2181 'to' => [$profile['url']],
2184 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2186 $signed = LDSignature::sign($data, $owner);
2187 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2191 * Transmits a message that we don't want to follow this contact anymore
2193 * @param string $target Target profile
2194 * @param integer $cid Contact id
2195 * @param integer $uid User ID
2196 * @return bool success
2197 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2198 * @throws \ImagickException
2199 * @throws \Exception
2201 public static function sendContactUndo(string $target, int $cid, int $uid): bool
2203 $profile = APContact::getByURL($target);
2204 if (empty($profile['inbox'])) {
2205 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2209 $object_id = self::activityIDFromContact($cid);
2210 if (empty($object_id)) {
2214 $objectId = DI::baseUrl() . '/activity/' . System::createGUID();
2216 $owner = User::getOwnerDataById($uid);
2218 '@context' => ActivityPub::CONTEXT,
2221 'actor' => $owner['url'],
2225 'actor' => $owner['url'],
2226 'object' => $profile['url']
2228 'instrument' => self::getService(),
2229 'to' => [$profile['url']],
2232 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2234 $signed = LDSignature::sign($data, $owner);
2235 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2239 * Prepends mentions (@) to $body variable
2241 * @param string $body HTML code
2243 * @param string $authorLink Author link
2244 * @return string HTML code with prepended mentions
2246 private static function prependMentions(string $body, int $uriid, string $authorLink): string
2250 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2251 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2252 if (!empty($profile['addr'])
2253 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2254 && !strstr($body, $profile['addr'])
2255 && !strstr($body, $tag['url'])
2256 && $tag['url'] !== $authorLink
2258 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2262 $mentions[] = $body;
2264 return implode(' ', $mentions);