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\Diaspora;
44 use Friendica\Protocol\Relay;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\HTTPSignature;
47 use Friendica\Util\LDSignature;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
54 * ActivityPub Transmitter Protocol class
61 const CACHEKEY_FEATURED = 'transmitter:getFeatured:';
62 const CACHEKEY_CONTACTS = 'transmitter:getContacts:';
65 * Add relay servers to the list of inboxes
67 * @param array $inboxes
68 * @return array inboxes with added relay servers
70 public static function addRelayServerInboxes(array $inboxes = []): array
72 foreach (Relay::getList(['inbox']) as $contact) {
73 $inboxes[$contact['inbox']] = $contact['inbox'];
80 * Add relay servers to the list of inboxes
82 * @param array $inboxes
83 * @return array inboxes with added relay servers
85 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = []): array
87 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
92 $relays = Relay::getDirectRelayList($item_id);
97 foreach ($relays as $relay) {
98 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
99 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
105 * Subscribe to a relay and updates contact on success
107 * @param string $url Subscribe actor url
108 * @return bool success
110 public static function sendRelayFollow(string $url): bool
112 $contact = Contact::getByURL($url);
113 if (empty($contact)) {
117 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
118 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
120 Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]);
127 * Unsubscribe from a relay and updates contact on success or forced
129 * @param string $url Subscribe actor url
130 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
131 * @return bool success
133 public static function sendRelayUndoFollow(string $url, bool $force = false): bool
135 $contact = Contact::getByURL($url);
136 if (empty($contact)) {
140 $success = self::sendContactUndo($url, $contact['id'], 0);
142 if ($success || $force) {
143 Contact::update(['rel' => Contact::NOTHING], ['id' => $contact['id']]);
150 * Collects a list of contacts of the given owner
152 * @param array $owner Owner array
153 * @param array $rel The relevant value(s) contact.rel should match
154 * @param string $module The name of the relevant AP endpoint module (followers|following)
155 * @param integer $page Page number
156 * @param string $requester URL of the requester
157 * @param boolean $nocache Wether to bypass caching
158 * @return array of owners
161 public static function getContacts(array $owner, array $rel, string $module, int $page = null, string $requester = null, bool $nocache = false): array
164 $cachekey = self::CACHEKEY_CONTACTS . $module . ':'. $owner['uid'];
165 $result = DI::cache()->get($cachekey);
166 if (!$nocache && !is_null($result)) {
173 'uid' => $owner['uid'],
182 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
184 $total = DBA::count('contact', $condition);
186 $modulePath = '/' . $module . '/';
188 $data = ['@context' => ActivityPub::CONTEXT];
189 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
190 $data['type'] = 'OrderedCollection';
191 $data['totalItems'] = $total;
194 $data['id'] .= '?' . http_build_query(['page' => $page]);
197 // When we hide our friends we will only show the pure number but don't allow more.
198 $show_contacts = empty($owner['hide-friends']);
200 // Allow fetching the contact list when the requester is part of the list.
201 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
202 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
205 if (!$show_contacts) {
206 if (!empty($cachekey)) {
207 DI::cache()->set($cachekey, $data, Duration::DAY);
214 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
216 $data['type'] = 'OrderedCollectionPage';
219 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
220 while ($contact = DBA::fetch($contacts)) {
221 $list[] = $contact['url'];
223 DBA::close($contacts);
225 if (count($list) == 100) {
226 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
229 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
231 $data['orderedItems'] = $list;
234 if (!empty($cachekey)) {
235 DI::cache()->set($cachekey, $data, Duration::DAY);
242 * Public posts for the given owner
244 * @param array $owner Owner array
245 * @param integer $page Page number
246 * @param string $requester URL of requesting account
247 * @param boolean $nocache Wether to bypass caching
248 * @return array of posts
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 * @throws \ImagickException
252 public static function getOutbox(array $owner, int $page = null, string $requester = '', bool $nocache = false): array
254 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
256 if (!empty($requester)) {
257 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
258 if (!empty($requester_id)) {
259 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
260 if (!empty($permissionSets)) {
261 $condition = ['psid' => array_merge($permissionSets->column('id'),
262 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
267 $condition = array_merge($condition, [
268 'uid' => $owner['uid'],
269 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
270 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
271 'network' => Protocol::FEDERATED,
272 'parent-network' => Protocol::FEDERATED,
278 $apcontact = APContact::getByURL($owner['url']);
280 $data = ['@context' => ActivityPub::CONTEXT];
281 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
282 $data['type'] = 'OrderedCollection';
283 $data['totalItems'] = $apcontact['statuses_count'] ?? 0;
286 $data['id'] .= '?' . http_build_query(['page' => $page]);
290 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
292 $data['type'] = 'OrderedCollectionPage';
295 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
296 while ($item = Post::fetch($items)) {
297 $activity = self::createActivityFromItem($item['id'], true);
298 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
300 // Only list "Create" activity objects here, no reshares
301 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
302 $list[] = $activity['object'];
307 if (count($list) == 20) {
308 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
311 // Fix the cached total item count when it is lower than the real count
312 $total = (($page - 1) * 20) + $data['totalItems'];
313 if ($total > $data['totalItems']) {
314 $data['totalItems'] = $total;
317 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
319 $data['orderedItems'] = $list;
326 * Public posts for the given owner
328 * @param array $owner Owner array
329 * @param integer $page Page number
330 * @param boolean $nocache Wether to bypass caching
332 * @return array of posts
333 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
334 * @throws \ImagickException
336 public static function getFeatured(array $owner, int $page = null, bool $nocache = false): array
339 $cachekey = self::CACHEKEY_FEATURED . $owner['uid'];
340 $result = DI::cache()->get($cachekey);
341 if (!$nocache && !is_null($result)) {
346 $owner_cid = Contact::getIdForURL($owner['url'], 0, false);
348 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
349 $owner_cid, Post\Collection::FEATURED];
351 $condition = DBA::mergeConditions($condition, [
352 'uid' => $owner['uid'],
353 'author-id' => $owner_cid,
354 'private' => [Item::PUBLIC, Item::UNLISTED],
355 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
356 'network' => Protocol::FEDERATED,
357 'parent-network' => Protocol::FEDERATED,
363 $count = Post::count($condition);
365 $data = ['@context' => ActivityPub::CONTEXT];
366 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
367 $data['type'] = 'OrderedCollection';
368 $data['totalItems'] = $count;
371 $data['id'] .= '?' . http_build_query(['page' => $page]);
375 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
377 $data['type'] = 'OrderedCollectionPage';
378 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
382 while ($item = Post::fetch($items)) {
383 $activity = self::createActivityFromItem($item['id'], true);
384 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
386 // Only list "Create" activity objects here, no reshares
387 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
388 $list[] = $activity['object'];
393 if (count($list) == 20) {
394 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
398 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
401 $data['orderedItems'] = $list;
403 if (!empty($cachekey)) {
404 DI::cache()->set($cachekey, $data, Duration::DAY);
411 * Return the service array containing information the used software and it's url
413 * @return array with service data
415 private static function getService(): array
419 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
420 'url' => DI::baseUrl()->get()
425 * Return the ActivityPub profile of the given user
427 * @param int $uid User ID
428 * @return array with profile data
429 * @throws HTTPException\NotFoundException
430 * @throws HTTPException\InternalServerErrorException
432 public static function getProfile(int $uid): array
434 $owner = User::getOwnerDataById($uid);
435 if (!isset($owner['id'])) {
436 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
437 throw new HTTPException\NotFoundException('User not found.');
440 $data = ['@context' => ActivityPub::CONTEXT];
441 $data['id'] = $owner['url'];
443 if (!empty($owner['guid'])) {
444 $data['diaspora:guid'] = $owner['guid'];
447 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
450 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
451 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
452 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
453 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
454 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
456 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
459 $data['preferredUsername'] = $owner['nick'];
460 $data['name'] = $owner['name'];
462 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
463 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
464 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
467 if (!empty($owner['about'])) {
468 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
471 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
472 $data['vcard:hasInstantMessage'] = [];
474 if (!empty($owner['xmpp'])) {
475 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
477 if (!empty($owner['matrix'])) {
478 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
482 $data['url'] = $owner['url'];
483 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
484 $data['discoverable'] = (bool)$owner['net-publish'];
485 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
486 'owner' => $owner['url'],
487 'publicKeyPem' => $owner['pubkey']];
488 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
489 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
491 $resourceid = Photo::ridFromURI($owner['photo']);
492 if (!empty($resourceid)) {
493 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
494 if (!empty($photo['type'])) {
495 $data['icon']['mediaType'] = $photo['type'];
499 if (!empty($owner['header'])) {
500 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
502 $resourceid = Photo::ridFromURI($owner['header']);
503 if (!empty($resourceid)) {
504 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
505 if (!empty($photo['type'])) {
506 $data['image']['mediaType'] = $photo['type'];
513 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
515 'type' => 'PropertyValue',
516 'name' => $profile_field->label,
517 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
521 if (!empty($custom_fields)) {
522 $data['attachment'] = $custom_fields;
525 $data['generator'] = self::getService();
527 // tags: https://kitty.town/@inmysocks/100656097926961126.json
532 * @param string $username
534 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
536 public static function getDeletedUser(string $username): array
539 '@context' => ActivityPub::CONTEXT,
540 'id' => DI::baseUrl() . '/profile/' . $username,
541 'type' => 'Tombstone',
542 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
543 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
544 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
549 * Returns an array with permissions of the thread parent of the given item array
552 * @param bool $is_forum_thread
554 * @return array with permissions
555 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
556 * @throws \ImagickException
558 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread): array
560 if (empty($item['thr-parent-id'])) {
564 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
565 if (empty($parent)) {
570 'to' => [$parent['author-link']],
576 $parent_profile = APContact::getByURL($parent['author-link']);
578 $item_profile = APContact::getByURL($item['author-link']);
579 $exclude[] = $item['author-link'];
581 if ($item['gravity'] == GRAVITY_PARENT) {
582 $exclude[] = $item['owner-link'];
585 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
586 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
587 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
588 if (!$is_forum_thread) {
589 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
591 } elseif (!in_array($receiver['url'], $exclude)) {
592 $permissions[$type[$receiver['type']]][] = $receiver['url'];
600 * Check if the given item id is from ActivityPub
602 * @param integer $item_id
603 * @return boolean "true" if the post is from ActivityPub
605 private static function isAPPost(int $item_id): bool
607 if (empty($item_id)) {
611 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
615 * Creates an array of permissions from an item thread
617 * @param array $item Item array
618 * @param boolean $blindcopy addressing via "bcc" or "cc"?
619 * @param integer $last_id Last item id for adding receivers
621 * @return array with permission data
622 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
623 * @throws \ImagickException
625 private static function createPermissionBlockForItem(array $item, bool $blindcopy, int $last_id = 0): array
628 $last_id = $item['id'];
635 // Check if we should always deliver our stuff via BCC
636 if (!empty($item['uid'])) {
637 $owner = User::getOwnerDataById($item['uid']);
638 if (!empty($owner)) {
639 $always_bcc = $owner['hide-friends'];
640 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
642 $profile = APContact::getByURL($owner['url'], false);
643 $follower = $profile['followers'] ?? '';
647 if (DI::config()->get('system', 'ap_always_bcc')) {
651 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
652 if (!empty($parent) && ($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
653 $profile = APContact::getByURL($parent['causer-link'], false);
654 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
656 $is_forum_thread = false;
659 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
660 // Will be activated in a later step
661 $networks = Protocol::FEDERATED;
663 // For now only send to these contacts:
664 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
667 $data = ['to' => [], 'cc' => [], 'bcc' => []];
669 if ($item['gravity'] == GRAVITY_PARENT) {
670 $actor_profile = APContact::getByURL($item['owner-link']);
672 $actor_profile = APContact::getByURL($item['author-link']);
677 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
679 if ($item['private'] != Item::PRIVATE) {
680 // Directly mention the original author upon a quoted reshare.
681 // Else just ensure that the original author receives the reshare.
682 $announce = self::getAnnounceArray($item);
683 if (!empty($announce['comment'])) {
684 $data['to'][] = $announce['actor']['url'];
685 } elseif (!empty($announce)) {
686 $data['cc'][] = $announce['actor']['url'];
689 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
691 // Check if the item is completely public or unlisted
692 if ($item['private'] == Item::PUBLIC) {
693 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
695 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
698 foreach ($terms as $term) {
699 $profile = APContact::getByURL($term['url'], false);
700 if (!empty($profile)) {
701 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
703 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
704 $data['cc'][] = $profile['followers'];
707 $data['to'][] = $profile['url'];
711 $receiver_list = Item::enumeratePermissions($item, true);
713 foreach ($terms as $term) {
714 $cid = Contact::getIdForURL($term['url'], $item['uid']);
715 if (!empty($cid) && in_array($cid, $receiver_list)) {
716 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
717 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
721 $profile = APContact::getByURL($term['url'], false);
722 if (!empty($profile)) {
723 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
725 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
726 $data['cc'][] = $profile['followers'];
729 $data['to'][] = $profile['url'];
734 if ($is_forum && !$exclusive && !empty($follower)) {
735 $data['cc'][] = $follower;
736 } elseif (!$exclusive) {
737 foreach ($receiver_list as $receiver) {
738 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
739 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
743 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
744 if ($contact['hidden'] || $always_bcc) {
745 $data['bcc'][] = $profile['url'];
747 $data['cc'][] = $profile['url'];
754 if (!empty($item['parent'])) {
755 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']], ['order' => ['id']]);
756 while ($parent = Post::fetch($parents)) {
757 if ($parent['gravity'] == GRAVITY_PARENT) {
758 $profile = APContact::getByURL($parent['owner-link'], false);
759 if (!empty($profile)) {
760 if ($item['gravity'] != GRAVITY_PARENT) {
761 // Comments to forums are directed to the forum
762 // But comments to forums aren't directed to the followers collection
763 // This rule is only valid when the actor isn't the forum.
764 // The forum needs to transmit their content to their followers.
765 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
766 $data['to'][] = $profile['url'];
768 $data['cc'][] = $profile['url'];
769 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers']) && (!$exclusive || !$is_forum_thread)) {
770 $data['cc'][] = $actor_profile['followers'];
773 } elseif (!$exclusive && !$is_forum_thread) {
774 // Public thread parent post always are directed to the followers.
775 if ($item['private'] != Item::PRIVATE) {
776 $data['cc'][] = $actor_profile['followers'];
782 // Don't include data from future posts
783 if ($parent['id'] >= $last_id) {
787 $profile = APContact::getByURL($parent['author-link'], false);
788 if (!empty($profile)) {
789 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
790 $data['to'][] = $profile['url'];
792 $data['cc'][] = $profile['url'];
796 DBA::close($parents);
799 $data['to'] = array_unique($data['to']);
800 $data['cc'] = array_unique($data['cc']);
801 $data['bcc'] = array_unique($data['bcc']);
803 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
804 unset($data['to'][$key]);
807 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
808 unset($data['cc'][$key]);
811 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
812 unset($data['bcc'][$key]);
815 foreach ($data['to'] as $to) {
816 if (($key = array_search($to, $data['cc'])) !== false) {
817 unset($data['cc'][$key]);
820 if (($key = array_search($to, $data['bcc'])) !== false) {
821 unset($data['bcc'][$key]);
825 foreach ($data['cc'] as $cc) {
826 if (($key = array_search($cc, $data['bcc'])) !== false) {
827 unset($data['bcc'][$key]);
831 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
834 unset($receivers['bcc']);
837 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
838 if (!empty($receivers[$element])) {
839 foreach ($receivers[$element] as $receiver) {
840 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
841 $name = Receiver::PUBLIC_COLLECTION;
843 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
845 Tag::store($item['uri-id'], $type, $name, $receiver);
854 * Check if an inbox is archived
856 * @param string $url Inbox url
857 * @return boolean "true" if inbox is archived
859 public static function archivedInbox(string $url): bool
861 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
865 * Check if a given contact should be delivered via AP
867 * @param array $contact Contact array
868 * @param array $networks Array with networks
869 * @return bool Whether the used protocol matches ACTIVITYPUB
872 private static function isAPContact(array $contact, array $networks): bool
874 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
878 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
882 * Fetches a list of inboxes of followers of a given user
884 * @param integer $uid User ID
885 * @param boolean $personal fetch personal inboxes
886 * @param boolean $all_ap Retrieve all AP enabled inboxes
887 * @return array of follower inboxes
888 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
889 * @throws \ImagickException
891 public static function fetchTargetInboxesforUser(int $uid, bool $personal = false, bool $all_ap = false): array
897 if (!empty($item['uid'])) {
898 $profile = User::getOwnerDataById($item['uid']);
899 if (!empty($profile)) {
900 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
904 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
905 // Will be activated in a later step
906 $networks = Protocol::FEDERATED;
908 // For now only send to these contacts:
909 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
917 'network' => Protocol::FEDERATED,
921 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
924 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
925 while ($contact = DBA::fetch($contacts)) {
926 if (!self::isAPContact($contact, $networks)) {
930 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
934 if (Network::isUrlBlocked($contact['url'])) {
938 $profile = APContact::getByURL($contact['url'], false);
939 if (!empty($profile)) {
940 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
941 $target = $profile['inbox'];
943 $target = $profile['sharedinbox'];
945 if (!self::archivedInbox($target)) {
946 $inboxes[$target][] = $contact['id'];
950 DBA::close($contacts);
956 * Fetches an array of inboxes for the given item and user
958 * @param array $item Item array
959 * @param integer $uid User ID
960 * @param boolean $personal fetch personal inboxes
961 * @param integer $last_id Last item id for adding receivers
962 * @return array with inboxes
963 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
964 * @throws \ImagickException
966 public static function fetchTargetInboxes(array $item, int $uid, bool $personal = false, int $last_id = 0): array
968 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
969 if (empty($permissions)) {
975 if ($item['gravity'] == GRAVITY_ACTIVITY) {
976 $item_profile = APContact::getByURL($item['author-link'], false);
978 $item_profile = APContact::getByURL($item['owner-link'], false);
981 if (empty($item_profile)) {
985 $profile_uid = User::getIdForURL($item_profile['url']);
987 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
988 if (empty($permissions[$element])) {
992 $blindcopy = in_array($element, ['bto', 'bcc']);
994 foreach ($permissions[$element] as $receiver) {
995 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
999 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
1000 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
1002 $profile = APContact::getByURL($receiver, false);
1003 if (!empty($profile)) {
1004 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
1006 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
1007 $target = $profile['inbox'];
1009 $target = $profile['sharedinbox'];
1011 if (!self::archivedInbox($target)) {
1012 $inboxes[$target][] = $contact['id'] ?? 0;
1023 * Creates an array in the structure of the item table for a given mail id
1025 * @param integer $mail_id Mail id
1027 * @throws \Exception
1029 public static function getItemArrayFromMail(int $mail_id, bool $use_title = false): array
1031 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
1032 if (!DBA::isResult($mail)) {
1036 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
1037 if (!DBA::isResult($reply)) {
1041 // Making the post more compatible for Mastodon by:
1042 // - Making it a note and not an article (no title)
1043 // - Moving the title into the "summary" field that is used as a "content warning"
1046 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1047 $mail['title'] = '';
1050 $mail['content-warning'] = '';
1051 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1052 $mail['owner-id'] = $mail['author-id'];
1053 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1054 $mail['allow_gid'] = '';
1055 $mail['deny_cid'] = '';
1056 $mail['deny_gid'] = '';
1057 $mail['private'] = Item::PRIVATE;
1058 $mail['deleted'] = false;
1059 $mail['edited'] = $mail['created'];
1060 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1061 $mail['parent-uri'] = $reply['uri'];
1062 $mail['parent-uri-id'] = $reply['uri-id'];
1063 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1064 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
1065 $mail['event-type'] = '';
1066 $mail['language'] = '';
1067 $mail['parent'] = 0;
1073 * Creates an activity array for a given mail id
1075 * @param integer $mail_id
1076 * @param boolean $object_mode Is the activity item is used inside another object?
1078 * @return array of activity
1079 * @throws \Exception
1081 public static function createActivityFromMail(int $mail_id, bool $object_mode = false): array
1083 $mail = self::getItemArrayFromMail($mail_id);
1087 $object = self::createNote($mail);
1089 if (!$object_mode) {
1090 $data = ['@context' => ActivityPub::CONTEXT];
1095 $data['id'] = $mail['uri'] . '/Create';
1096 $data['type'] = 'Create';
1097 $data['actor'] = $mail['author-link'];
1098 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1099 $data['instrument'] = self::getService();
1100 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1102 if (empty($data['to']) && !empty($data['cc'])) {
1103 $data['to'] = $data['cc'];
1106 if (empty($data['to']) && !empty($data['bcc'])) {
1107 $data['to'] = $data['bcc'];
1111 unset($data['bcc']);
1113 $object['to'] = $data['to'];
1114 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1116 unset($object['cc']);
1117 unset($object['bcc']);
1119 $data['directMessage'] = true;
1121 $data['object'] = $object;
1123 $owner = User::getOwnerDataById($mail['uid']);
1125 if (!$object_mode && !empty($owner)) {
1126 return LDSignature::sign($data, $owner);
1133 * Returns the activity type of a given item
1135 * @param array $item Item array
1136 * @return string with activity type
1137 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1138 * @throws \ImagickException
1140 private static function getTypeOfItem(array $item): string
1144 // Only check for a reshare, if it is a real reshare and no quoted reshare
1145 if (strpos($item['body'], '[share') === 0) {
1146 $announce = self::getAnnounceArray($item);
1147 $reshared = !empty($announce);
1152 } elseif ($item['verb'] == Activity::POST) {
1153 if ($item['created'] == $item['edited']) {
1158 } elseif ($item['verb'] == Activity::LIKE) {
1160 } elseif ($item['verb'] == Activity::DISLIKE) {
1162 } elseif ($item['verb'] == Activity::ATTEND) {
1164 } elseif ($item['verb'] == Activity::ATTENDNO) {
1166 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1167 $type = 'TentativeAccept';
1168 } elseif ($item['verb'] == Activity::FOLLOW) {
1170 } elseif ($item['verb'] == Activity::TAG) {
1172 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1182 * Creates the activity or fetches it from the cache
1184 * @param integer $item_id Item id
1185 * @param boolean $force Force new cache entry
1186 * @return array|false activity or false on failure
1187 * @throws \Exception
1189 public static function createCachedActivityFromItem(int $item_id, bool $force = false, bool $object_mode = false)
1191 $cachekey = 'APDelivery:createActivity:' . $item_id . ':' . (int)$object_mode;
1194 $data = DI::cache()->get($cachekey);
1195 if (!is_null($data)) {
1200 $data = self::createActivityFromItem($item_id, $object_mode);
1202 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1207 * Creates an activity array for a given item id
1209 * @param integer $item_id
1210 * @param boolean $object_mode Is the activity item is used inside another object?
1211 * @return false|array
1212 * @throws \Exception
1214 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1216 Logger::info('Fetching activity', ['item' => $item_id]);
1217 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1218 if (!DBA::isResult($item)) {
1222 if (empty($item['uri-id'])) {
1223 Logger::warning('Item without uri-id', ['item' => $item]);
1227 if (!$item['deleted']) {
1228 $data = Post\Activity::getByURIId($item['uri-id']);
1229 if (!$item['origin'] && !empty($data)) {
1231 unset($data['@context']);
1232 unset($data['signature']);
1234 Logger::info('Return stored conversation', ['item' => $item_id]);
1239 if (!$item['origin'] && empty($object)) {
1240 Logger::debug('Post is not ours and is not stored', ['id' => $item_id, 'uri-id' => $item['uri-id']]);
1244 $type = self::getTypeOfItem($item);
1246 if (!$object_mode) {
1247 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1249 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1251 } elseif ($item['deleted']) {
1258 if ($type == 'Delete') {
1259 $data['id'] = Item::newURI($item['guid']) . '/' . $type;;
1260 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1261 $data['id'] = $item['uri'];
1263 $data['id'] = $item['uri'] . '/' . $type;
1266 $data['type'] = $type;
1268 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1269 $data['actor'] = $item['author-link'];
1271 $data['actor'] = $item['owner-link'];
1274 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1276 $data['instrument'] = self::getService();
1278 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1280 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1281 $data['object'] = $object ?? self::createNote($item);
1282 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1283 } elseif ($data['type'] == 'Add') {
1284 $data = self::createAddTag($item, $data);
1285 } elseif ($data['type'] == 'Announce') {
1286 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1287 $data['object'] = $item['thr-parent'];
1289 $data = self::createAnnounce($item, $data);
1291 } elseif ($data['type'] == 'Follow') {
1292 $data['object'] = $item['parent-uri'];
1293 } elseif ($data['type'] == 'Undo') {
1294 $data['object'] = self::createActivityFromItem($item_id, true);
1296 $data['diaspora:guid'] = $item['guid'];
1297 if (!empty($item['signed_text'])) {
1298 $data['diaspora:like'] = $item['signed_text'];
1300 $data['object'] = $item['thr-parent'];
1303 if (!empty($item['contact-uid'])) {
1304 $uid = $item['contact-uid'];
1306 $uid = $item['uid'];
1309 $owner = User::getOwnerDataById($uid);
1311 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1313 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1314 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1315 return LDSignature::sign($data, $owner);
1320 /// @todo Create "conversation" entry
1324 * Creates a location entry for a given item array
1326 * @param array $item Item array
1327 * @return array with location array
1329 private static function createLocation(array $item): array
1331 $location = ['type' => 'Place'];
1333 if (!empty($item['location'])) {
1334 $location['name'] = $item['location'];
1339 if (empty($item['coord'])) {
1340 $coord = Map::getCoordinates($item['location']);
1342 $coords = explode(' ', $item['coord']);
1343 if (count($coords) == 2) {
1344 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1348 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1349 $location['latitude'] = $coord['lat'];
1350 $location['longitude'] = $coord['lon'];
1357 * Returns a tag array for a given item array
1359 * @param array $item Item array
1360 * @param string $quote_url Url of the attached quote link
1361 * @return array of tags
1362 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1364 private static function createTagList(array $item, string $quote_url): array
1368 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1369 foreach ($terms as $term) {
1370 if ($term['type'] == Tag::HASHTAG) {
1371 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1372 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1374 $contact = Contact::getByURL($term['url'], false, ['addr']);
1375 if (empty($contact)) {
1378 if (!empty($contact['addr'])) {
1379 $mention = '@' . $contact['addr'];
1381 $mention = '@' . $term['url'];
1384 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1388 $announce = self::getAnnounceArray($item);
1389 // Mention the original author upon commented reshares
1390 if (!empty($announce['comment'])) {
1391 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1394 // @see https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-e232.md
1395 if (!empty($quote_url)) {
1396 // Currently deactivated because of compatibility issues with Pleroma
1398 // 'type' => 'Link',
1399 // 'mediaType' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
1400 // 'href' => $quote_url,
1401 // 'name' => '♲ ' . BBCode::convertForUriId($item['uri-id'], $quote_url, BBCode::ACTIVITYPUB)
1409 * Adds attachment data to the JSON document
1411 * @param array $item Data of the item that is to be posted
1413 * @return array with attachment data
1414 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1416 private static function createAttachmentList(array $item): array
1421 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1422 if (in_array($attachment['url'], $urls)) {
1425 $urls[] = $attachment['url'];
1427 $attach = ['type' => 'Document',
1428 'mediaType' => $attachment['mimetype'],
1429 'url' => $attachment['url'],
1430 'name' => $attachment['description']];
1432 if (!empty($attachment['height'])) {
1433 $attach['height'] = $attachment['height'];
1436 if (!empty($attachment['width'])) {
1437 $attach['width'] = $attachment['width'];
1440 if (!empty($attachment['preview'])) {
1441 $attach['image'] = $attachment['preview'];
1444 $attachments[] = $attach;
1447 return $attachments;
1451 * Callback function to replace a Friendica style mention in a mention for a summary
1453 * @param array $match Matching values for the callback
1454 * @return string Replaced mention
1455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1457 private static function mentionAddrCallback(array $match): string
1459 if (empty($match[1])) {
1463 $data = Contact::getByURL($match[1], false, ['addr']);
1464 if (empty($data['addr'])) {
1468 return '@' . $data['addr'];
1472 * Remove image elements since they are added as attachment
1474 * @param string $body HTML code
1475 * @return string with removed images
1477 private static function removePictures(string $body): string
1479 // Simplify image codes
1480 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1481 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1483 // Now remove local links
1484 $body = preg_replace_callback(
1485 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1487 // We remove the link when it is a link to a local photo page
1488 if (Photo::isLocalPage($match[1])) {
1491 // otherwise we just return the link
1492 return '[url]' . $match[1] . '[/url]';
1497 // Remove all pictures
1498 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1504 * Returns if the post contains sensitive content ("nsfw")
1506 * @param integer $uri_id URI id
1507 * @return boolean Whether URI id was found
1508 * @throws \Exception
1510 private static function isSensitive(int $uri_id): bool
1512 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1516 * Creates event data
1518 * @param array $item Item array
1519 * @return array with the event data
1520 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1522 private static function createEvent(array $item): array
1525 $event['name'] = $item['event-summary'];
1526 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1527 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1529 if (!$item['event-nofinish']) {
1530 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1533 if (!empty($item['event-location'])) {
1534 $item['location'] = $item['event-location'];
1535 $event['location'] = self::createLocation($item);
1538 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1539 $event['dfrn:adjust'] = true;
1545 * Creates a note/article object array
1547 * @param array $item
1548 * @return array with the object data
1549 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1550 * @throws \ImagickException
1552 public static function createNote(array $item): array
1558 // We are treating posts differently when they are directed to a community.
1559 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1560 // But to not risk compatibility issues we currently perform the changes only for communities.
1561 if ($item['gravity'] == GRAVITY_PARENT) {
1562 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1563 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1564 if ($isCommunityPost && (count($links) == 1)) {
1565 $link = $links[0]['url'];
1568 $isCommunityPost = false;
1571 if ($item['event-type'] == 'event') {
1573 } elseif (!empty($item['title'])) {
1574 if (!$isCommunityPost || empty($link)) {
1577 // "Page" is used by Lemmy for posts that contain an external link
1584 if ($item['deleted']) {
1585 $type = 'Tombstone';
1589 $data['id'] = $item['uri'];
1590 $data['type'] = $type;
1592 if ($item['deleted']) {
1596 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1598 if ($item['uri'] != $item['thr-parent']) {
1599 $data['inReplyTo'] = $item['thr-parent'];
1601 $data['inReplyTo'] = null;
1604 $data['diaspora:guid'] = $item['guid'];
1605 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1607 if ($item['created'] != $item['edited']) {
1608 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1611 $data['url'] = $link ?? $item['plink'];
1612 $data['attributedTo'] = $item['author-link'];
1613 $data['sensitive'] = self::isSensitive($item['uri-id']);
1615 if (!empty($item['conversation']) && ($item['conversation'] != './')) {
1616 $data['conversation'] = $data['context'] = $item['conversation'];
1619 if (!empty($item['title'])) {
1620 $data['name'] = BBCode::toPlaintext($item['title'], false);
1623 $permission_block = self::createPermissionBlockForItem($item, false);
1625 $real_quote = false;
1627 $body = $item['body'];
1629 if ($type == 'Note') {
1630 $body = $item['raw-body'] ?? self::removePictures($body);
1634 * @todo Improve the automated summary
1635 * This part is currently deactivated. The automated summary seems to be more
1636 * confusing than helping. But possibly we will find a better way.
1637 * So the code is left here for now as a reminder
1639 * } elseif (($type == 'Article') && empty($data['summary'])) {
1640 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1641 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1642 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1646 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1647 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1650 if ($type == 'Event') {
1651 $data = array_merge($data, self::createEvent($item));
1653 if ($isCommunityPost) {
1654 // For community posts we remove the visible "!user@domain.tld".
1655 // This improves the look at systems like Lemmy.
1656 // Also in the future we should control the community delivery via other methods.
1657 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1660 if ($type == 'Page') {
1661 // When we transmit "Page" posts we have to remove the attachment.
1662 // The attachment contains the link that we already transmit in the "url" field.
1663 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1666 $body = BBCode::setMentionsToNicknames($body);
1668 if (!empty($item['quote-uri']) && Post::exists(['uri-id' => $item['quote-uri-id'], 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN]])) {
1670 if (Diaspora::isReshare($body, false)) {
1671 $body = BBCode::replaceSharedData($body);
1672 } elseif (strpos($body, $item['quote-uri']) === false) {
1673 $body .= "\n♲ " . $item['quote-uri'];
1675 $data['quoteUrl'] = $item['quote-uri'];
1676 } elseif (!empty($item['quote-uri']) && !Diaspora::isReshare($body, false)) {
1677 $body .= "\n" . DI::contentItem()->createSharedPostByUriId($item['quote-uri-id'], $item['uid'], true);
1678 $item['body'] = Item::improveSharedDataInBody($item, true);
1681 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1684 // The regular "content" field does contain a minimized HTML. This is done since systems like
1685 // Mastodon has got problems with - for example - embedded pictures.
1686 // The contentMap does contain the unmodified HTML.
1687 $language = self::getLanguage($item);
1688 if (!empty($language)) {
1689 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1692 $shared = BBCode::fetchShareAttributes($richbody);
1693 if (!empty($shared['link']) && !empty($shared['guid']) && !empty($shared['comment'])) {
1694 $richbody = BBCode::replaceSharedData($richbody);
1698 $richbody = BBCode::removeAttachment($richbody);
1700 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1703 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1705 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1706 $data['diaspora:comment'] = $item['signed_text'];
1709 $data['attachment'] = self::createAttachmentList($item);
1710 $data['tag'] = self::createTagList($item, $data['quoteUrl'] ?? '');
1712 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1713 $data['location'] = self::createLocation($item);
1716 if (!empty($item['app'])) {
1717 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1720 $data = array_merge($data, $permission_block);
1726 * Fetches the language from the post, the user or the system.
1728 * @param array $item
1729 * @return string language string
1731 private static function getLanguage(array $item): string
1733 // Try to fetch the language from the post itself
1734 if (!empty($item['language'])) {
1735 $languages = array_keys(json_decode($item['language'], true));
1736 if (!empty($languages[0])) {
1737 return $languages[0];
1741 // Otherwise use the user's language
1742 if (!empty($item['uid'])) {
1743 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1744 if (!empty($user['language'])) {
1745 return $user['language'];
1749 // And finally just use the system language
1750 return DI::config()->get('system', 'language');
1754 * Creates an an "add tag" entry
1756 * @param array $item Item array
1757 * @param array $activity activity data
1758 * @return array with activity data for adding tags
1759 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1760 * @throws \ImagickException
1762 private static function createAddTag(array $item, array $activity): array
1764 $object = XML::parseString($item['object']);
1765 $target = XML::parseString($item['target']);
1767 $activity['diaspora:guid'] = $item['guid'];
1768 $activity['actor'] = $item['author-link'];
1769 $activity['target'] = (string)$target->id;
1770 $activity['summary'] = BBCode::toPlaintext($item['body']);
1771 $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1777 * Creates an announce object entry
1779 * @param array $item Item array
1780 * @param array $activity activity data
1781 * @return array with activity data
1782 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1783 * @throws \ImagickException
1785 private static function createAnnounce(array $item, array $activity): array
1787 $orig_body = $item['body'];
1788 $announce = self::getAnnounceArray($item);
1789 if (empty($announce)) {
1790 $activity['type'] = 'Create';
1791 $activity['object'] = self::createNote($item);
1795 if (empty($announce['comment'])) {
1796 // Pure announce, without a quote
1797 $activity['type'] = 'Announce';
1798 $activity['object'] = $announce['object']['uri'];
1803 $activity['type'] = 'Create';
1804 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1805 $activity['object'] = self::createNote($item);
1807 /// @todo Finally descide how to implement this in AP. This is a possible way:
1808 $activity['object']['attachment'][] = self::createNote($announce['object']);
1810 $activity['object']['source']['content'] = $orig_body;
1815 * Return announce related data if the item is an annunce
1817 * @param array $item
1818 * @return array Announcement array
1820 public static function getAnnounceArray(array $item): array
1822 $reshared = Item::getShareArray($item);
1823 if (empty($reshared['guid'])) {
1827 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1828 if (!DBA::isResult($reshared_item)) {
1832 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1836 $profile = APContact::getByURL($reshared_item['author-link'], false);
1837 if (empty($profile)) {
1841 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1845 * Checks if the provided item array is an announce
1847 * @param array $item Item array
1848 * @return boolean Whether item is an announcement
1850 public static function isAnnounce(array $item): bool
1852 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1856 $announce = self::getAnnounceArray($item);
1857 if (empty($announce)) {
1861 return empty($announce['comment']);
1865 * Creates an activity id for a given contact id
1867 * @param integer $cid Contact ID of target
1869 * @return bool|string activity id
1871 public static function activityIDFromContact(int $cid)
1873 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1874 if (!DBA::isResult($contact)) {
1878 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1879 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1880 return DI::baseUrl() . '/activity/' . $uuid;
1884 * Transmits a contact suggestion to a given inbox
1886 * @param integer $uid User ID
1887 * @param string $inbox Target inbox
1888 * @param integer $suggestion_id Suggestion ID
1889 * @return boolean was the transmission successful?
1890 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1892 public static function sendContactSuggestion(int $uid, string $inbox, int $suggestion_id): bool
1894 $owner = User::getOwnerDataById($uid);
1896 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1899 '@context' => ActivityPub::CONTEXT,
1900 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1901 'type' => 'Announce',
1902 'actor' => $owner['url'],
1903 'object' => $suggestion->url,
1904 'content' => $suggestion->note,
1905 'instrument' => self::getService(),
1906 'to' => [ActivityPub::PUBLIC_COLLECTION],
1910 $signed = LDSignature::sign($data, $owner);
1912 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1913 return HTTPSignature::transmit($signed, $inbox, $uid);
1917 * Transmits a profile relocation to a given inbox
1919 * @param integer $uid User ID
1920 * @param string $inbox Target inbox
1921 * @return boolean was the transmission successful?
1922 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1924 public static function sendProfileRelocation(int $uid, string $inbox): bool
1926 $owner = User::getOwnerDataById($uid);
1929 '@context' => ActivityPub::CONTEXT,
1930 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1931 'type' => 'dfrn:relocate',
1932 'actor' => $owner['url'],
1933 'object' => $owner['url'],
1934 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1935 'instrument' => self::getService(),
1936 'to' => [ActivityPub::PUBLIC_COLLECTION],
1940 $signed = LDSignature::sign($data, $owner);
1942 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1943 return HTTPSignature::transmit($signed, $inbox, $uid);
1947 * Transmits a profile deletion to a given inbox
1949 * @param integer $uid User ID
1950 * @param string $inbox Target inbox
1951 * @return boolean was the transmission successful?
1952 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1954 public static function sendProfileDeletion(int $uid, string $inbox): bool
1956 $owner = User::getOwnerDataById($uid);
1958 if (empty($owner)) {
1959 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1963 if (empty($owner['uprvkey'])) {
1964 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1968 $data = ['@context' => ActivityPub::CONTEXT,
1969 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1971 'actor' => $owner['url'],
1972 'object' => $owner['url'],
1973 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1974 'instrument' => self::getService(),
1975 'to' => [ActivityPub::PUBLIC_COLLECTION],
1978 $signed = LDSignature::sign($data, $owner);
1980 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1981 return HTTPSignature::transmit($signed, $inbox, $uid);
1985 * Transmits a profile change to a given inbox
1987 * @param integer $uid User ID
1988 * @param string $inbox Target inbox
1989 * @return boolean was the transmission successful?
1990 * @throws HTTPException\InternalServerErrorException
1991 * @throws HTTPException\NotFoundException
1992 * @throws \ImagickException
1994 public static function sendProfileUpdate(int $uid, string $inbox): bool
1996 $owner = User::getOwnerDataById($uid);
1997 $profile = APContact::getByURL($owner['url']);
1999 $data = ['@context' => ActivityPub::CONTEXT,
2000 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2002 'actor' => $owner['url'],
2003 'object' => self::getProfile($uid),
2004 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2005 'instrument' => self::getService(),
2006 'to' => [$profile['followers']],
2009 $signed = LDSignature::sign($data, $owner);
2011 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
2012 return HTTPSignature::transmit($signed, $inbox, $uid);
2016 * Transmits a given activity to a target
2018 * @param string $activity Type name
2019 * @param string $target Target profile
2020 * @param integer $uid User ID
2021 * @param string $id Activity-identifier
2023 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2024 * @throws \ImagickException
2025 * @throws \Exception
2027 public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2029 $profile = APContact::getByURL($target);
2030 if (empty($profile['inbox'])) {
2031 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2035 $owner = User::getOwnerDataById($uid);
2038 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2042 '@context' => ActivityPub::CONTEXT,
2044 'type' => $activity,
2045 'actor' => $owner['url'],
2046 'object' => $profile['url'],
2047 'instrument' => self::getService(),
2048 'to' => [$profile['url']],
2051 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2053 $signed = LDSignature::sign($data, $owner);
2054 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2058 * Transmits a "follow object" activity to a target
2059 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2061 * @param string $object Object URL
2062 * @param string $target Target profile
2063 * @param integer $uid User ID
2065 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2066 * @throws \ImagickException
2067 * @throws \Exception
2069 public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2071 $profile = APContact::getByURL($target);
2072 if (empty($profile['inbox'])) {
2073 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2078 // Fetch the list of administrators
2079 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2081 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2082 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2083 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2084 $uid = $first_user['uid'];
2087 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2088 'author-id' => Contact::getPublicIdByUserId($uid)];
2089 if (Post::exists($condition)) {
2090 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2094 $owner = User::getOwnerDataById($uid);
2097 '@context' => ActivityPub::CONTEXT,
2098 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2100 'actor' => $owner['url'],
2101 'object' => $object,
2102 'instrument' => self::getService(),
2103 'to' => [$profile['url']],
2106 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2108 $signed = LDSignature::sign($data, $owner);
2109 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2113 * Transmit a message that the contact request had been accepted
2115 * @param string $target Target profile
2116 * @param string $id Object id
2117 * @param integer $uid User ID
2119 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2120 * @throws \ImagickException
2122 public static function sendContactAccept(string $target, string $id, int $uid)
2124 $profile = APContact::getByURL($target);
2125 if (empty($profile['inbox'])) {
2126 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2130 $owner = User::getOwnerDataById($uid);
2132 '@context' => ActivityPub::CONTEXT,
2133 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2135 'actor' => $owner['url'],
2139 'actor' => $profile['url'],
2140 'object' => $owner['url']
2142 'instrument' => self::getService(),
2143 'to' => [$profile['url']],
2146 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2148 $signed = LDSignature::sign($data, $owner);
2149 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2153 * Reject a contact request or terminates the contact relation
2155 * @param string $target Target profile
2156 * @param string $objectId Object id
2157 * @param int $uid User ID
2158 * @return bool Operation success
2159 * @throws HTTPException\InternalServerErrorException
2160 * @throws \ImagickException
2162 public static function sendContactReject(string $target, string $objectId, int $uid): bool
2164 $profile = APContact::getByURL($target);
2165 if (empty($profile['inbox'])) {
2166 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2170 $owner = User::getOwnerDataById($uid);
2172 '@context' => ActivityPub::CONTEXT,
2173 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2175 'actor' => $owner['url'],
2179 'actor' => $profile['url'],
2180 'object' => $owner['url']
2182 'instrument' => self::getService(),
2183 'to' => [$profile['url']],
2186 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2188 $signed = LDSignature::sign($data, $owner);
2189 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2193 * Transmits a message that we don't want to follow this contact anymore
2195 * @param string $target Target profile
2196 * @param integer $cid Contact id
2197 * @param integer $uid User ID
2198 * @return bool success
2199 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2200 * @throws \ImagickException
2201 * @throws \Exception
2203 public static function sendContactUndo(string $target, int $cid, int $uid): bool
2205 $profile = APContact::getByURL($target);
2206 if (empty($profile['inbox'])) {
2207 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2211 $object_id = self::activityIDFromContact($cid);
2212 if (empty($object_id)) {
2216 $objectId = DI::baseUrl() . '/activity/' . System::createGUID();
2218 $owner = User::getOwnerDataById($uid);
2220 '@context' => ActivityPub::CONTEXT,
2223 'actor' => $owner['url'],
2227 'actor' => $owner['url'],
2228 'object' => $profile['url']
2230 'instrument' => self::getService(),
2231 'to' => [$profile['url']],
2234 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2236 $signed = LDSignature::sign($data, $owner);
2237 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2241 * Prepends mentions (@) to $body variable
2243 * @param string $body HTML code
2245 * @param string $authorLink Author link
2246 * @return string HTML code with prepended mentions
2248 private static function prependMentions(string $body, int $uriid, string $authorLink): string
2252 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2253 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2254 if (!empty($profile['addr'])
2255 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2256 && !strstr($body, $profile['addr'])
2257 && !strstr($body, $tag['url'])
2258 && $tag['url'] !== $authorLink
2260 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2264 $mentions[] = $body;
2266 return implode(' ', $mentions);