3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Core\Cache\Enum\Duration;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Database\DBA;
32 use Friendica\Model\APContact;
33 use Friendica\Model\Contact;
34 use Friendica\Model\GServer;
35 use Friendica\Model\Item;
36 use Friendica\Model\Photo;
37 use Friendica\Model\Post;
38 use Friendica\Model\Tag;
39 use Friendica\Model\User;
40 use Friendica\Network\HTTPException;
41 use Friendica\Protocol\Activity;
42 use Friendica\Protocol\ActivityPub;
43 use Friendica\Protocol\Relay;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\HTTPSignature;
46 use Friendica\Util\LDSignature;
47 use Friendica\Util\Map;
48 use Friendica\Util\Network;
49 use Friendica\Util\Strings;
50 use Friendica\Util\XML;
53 * ActivityPub Transmitter Protocol class
60 const CACHEKEY_FEATURED = 'transmitter:getFeatured:';
61 const CACHEKEY_CONTACTS = 'transmitter:getContacts:';
62 const CACHEKEY_OUTBOX = 'transmitter:getOutbox:';
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
255 $cachekey = self::CACHEKEY_OUTBOX . $owner['uid'];
256 $result = DI::cache()->get($cachekey);
257 if (!$nocache && !is_null($result)) {
262 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
264 if (!empty($requester)) {
265 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
266 if (!empty($requester_id)) {
267 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
268 if (!empty($permissionSets)) {
269 $condition = ['psid' => array_merge($permissionSets->column('id'),
270 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
275 $condition = array_merge($condition, [
276 'uid' => $owner['uid'],
277 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
278 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
279 'network' => Protocol::FEDERATED,
280 'parent-network' => Protocol::FEDERATED,
286 $count = Post::count($condition);
288 $data = ['@context' => ActivityPub::CONTEXT];
289 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
290 $data['type'] = 'OrderedCollection';
291 $data['totalItems'] = $count;
294 $data['id'] .= '?' . http_build_query(['page' => $page]);
298 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
300 $data['type'] = 'OrderedCollectionPage';
303 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
304 while ($item = Post::fetch($items)) {
305 $activity = self::createActivityFromItem($item['id'], true);
306 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
308 // Only list "Create" activity objects here, no reshares
309 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
310 $list[] = $activity['object'];
315 if (count($list) == 20) {
316 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
319 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
321 $data['orderedItems'] = $list;
324 if (!empty($cachekey)) {
325 DI::cache()->set($cachekey, $data, Duration::DAY);
332 * Public posts for the given owner
334 * @param array $owner Owner array
335 * @param integer $page Page number
336 * @param boolean $nocache Wether to bypass caching
338 * @return array of posts
339 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
340 * @throws \ImagickException
342 public static function getFeatured(array $owner, int $page = null, bool $nocache = false): array
345 $cachekey = self::CACHEKEY_FEATURED . $owner['uid'];
346 $result = DI::cache()->get($cachekey);
347 if (!$nocache && !is_null($result)) {
352 $owner_cid = Contact::getIdForURL($owner['url'], 0, false);
354 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
355 $owner_cid, Post\Collection::FEATURED];
357 $condition = DBA::mergeConditions($condition, [
358 'uid' => $owner['uid'],
359 'author-id' => $owner_cid,
360 'private' => [Item::PUBLIC, Item::UNLISTED],
361 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
362 'network' => Protocol::FEDERATED,
363 'parent-network' => Protocol::FEDERATED,
369 $count = Post::count($condition);
371 $data = ['@context' => ActivityPub::CONTEXT];
372 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
373 $data['type'] = 'OrderedCollection';
374 $data['totalItems'] = $count;
377 $data['id'] .= '?' . http_build_query(['page' => $page]);
381 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
383 $data['type'] = 'OrderedCollectionPage';
384 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
388 while ($item = Post::fetch($items)) {
389 $activity = self::createActivityFromItem($item['id'], true);
390 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
392 // Only list "Create" activity objects here, no reshares
393 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
394 $list[] = $activity['object'];
399 if (count($list) == 20) {
400 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
404 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
407 $data['orderedItems'] = $list;
409 if (!empty($cachekey)) {
410 DI::cache()->set($cachekey, $data, Duration::DAY);
417 * Return the service array containing information the used software and it's url
419 * @return array with service data
421 private static function getService(): array
425 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
426 'url' => DI::baseUrl()->get()
431 * Return the ActivityPub profile of the given user
433 * @param int $uid User ID
434 * @return array with profile data
435 * @throws HTTPException\NotFoundException
436 * @throws HTTPException\InternalServerErrorException
438 public static function getProfile(int $uid): array
440 $owner = User::getOwnerDataById($uid);
441 if (!isset($owner['id'])) {
442 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
443 throw new HTTPException\NotFoundException('User not found.');
446 $data = ['@context' => ActivityPub::CONTEXT];
447 $data['id'] = $owner['url'];
449 if (!empty($owner['guid'])) {
450 $data['diaspora:guid'] = $owner['guid'];
453 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
456 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
457 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
458 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
459 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
460 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
462 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
465 $data['preferredUsername'] = $owner['nick'];
466 $data['name'] = $owner['name'];
468 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
469 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
470 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
473 if (!empty($owner['about'])) {
474 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
477 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
478 $data['vcard:hasInstantMessage'] = [];
480 if (!empty($owner['xmpp'])) {
481 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
483 if (!empty($owner['matrix'])) {
484 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
488 $data['url'] = $owner['url'];
489 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
490 $data['discoverable'] = (bool)$owner['net-publish'];
491 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
492 'owner' => $owner['url'],
493 'publicKeyPem' => $owner['pubkey']];
494 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
495 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
497 $resourceid = Photo::ridFromURI($owner['photo']);
498 if (!empty($resourceid)) {
499 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
500 if (!empty($photo['type'])) {
501 $data['icon']['mediaType'] = $photo['type'];
505 if (!empty($owner['header'])) {
506 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
508 $resourceid = Photo::ridFromURI($owner['header']);
509 if (!empty($resourceid)) {
510 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
511 if (!empty($photo['type'])) {
512 $data['image']['mediaType'] = $photo['type'];
519 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
521 'type' => 'PropertyValue',
522 'name' => $profile_field->label,
523 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
527 if (!empty($custom_fields)) {
528 $data['attachment'] = $custom_fields;
531 $data['generator'] = self::getService();
533 // tags: https://kitty.town/@inmysocks/100656097926961126.json
538 * @param string $username
540 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
542 public static function getDeletedUser(string $username): array
545 '@context' => ActivityPub::CONTEXT,
546 'id' => DI::baseUrl() . '/profile/' . $username,
547 'type' => 'Tombstone',
548 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
549 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
550 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
555 * Returns an array with permissions of the thread parent of the given item array
558 * @param bool $is_forum_thread
560 * @return array with permissions
561 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
562 * @throws \ImagickException
564 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread): array
566 if (empty($item['thr-parent-id'])) {
570 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
571 if (empty($parent)) {
576 'to' => [$parent['author-link']],
582 $parent_profile = APContact::getByURL($parent['author-link']);
584 $item_profile = APContact::getByURL($item['author-link']);
585 $exclude[] = $item['author-link'];
587 if ($item['gravity'] == GRAVITY_PARENT) {
588 $exclude[] = $item['owner-link'];
591 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
592 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
593 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
594 if (!$is_forum_thread) {
595 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
597 } elseif (!in_array($receiver['url'], $exclude)) {
598 $permissions[$type[$receiver['type']]][] = $receiver['url'];
606 * Check if the given item id is from ActivityPub
608 * @param integer $item_id
609 * @return boolean "true" if the post is from ActivityPub
611 private static function isAPPost(int $item_id): bool
613 if (empty($item_id)) {
617 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
621 * Creates an array of permissions from an item thread
623 * @param array $item Item array
624 * @param boolean $blindcopy addressing via "bcc" or "cc"?
625 * @param integer $last_id Last item id for adding receivers
627 * @return array with permission data
628 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
629 * @throws \ImagickException
631 private static function createPermissionBlockForItem(array $item, bool $blindcopy, int $last_id = 0): array
634 $last_id = $item['id'];
641 // Check if we should always deliver our stuff via BCC
642 if (!empty($item['uid'])) {
643 $owner = User::getOwnerDataById($item['uid']);
644 if (!empty($owner)) {
645 $always_bcc = $owner['hide-friends'];
646 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
648 $profile = APContact::getByURL($owner['url'], false);
649 $follower = $profile['followers'] ?? '';
653 if (DI::config()->get('system', 'ap_always_bcc')) {
657 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
658 if (($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
659 $profile = APContact::getByURL($parent['causer-link'], false);
660 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
662 $is_forum_thread = false;
665 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
666 // Will be activated in a later step
667 $networks = Protocol::FEDERATED;
669 // For now only send to these contacts:
670 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
673 $data = ['to' => [], 'cc' => [], 'bcc' => []];
675 if ($item['gravity'] == GRAVITY_PARENT) {
676 $actor_profile = APContact::getByURL($item['owner-link']);
678 $actor_profile = APContact::getByURL($item['author-link']);
683 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
685 if ($item['private'] != Item::PRIVATE) {
686 // Directly mention the original author upon a quoted reshare.
687 // Else just ensure that the original author receives the reshare.
688 $announce = self::getAnnounceArray($item);
689 if (!empty($announce['comment'])) {
690 $data['to'][] = $announce['actor']['url'];
691 } elseif (!empty($announce)) {
692 $data['cc'][] = $announce['actor']['url'];
695 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
697 // Check if the item is completely public or unlisted
698 if ($item['private'] == Item::PUBLIC) {
699 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
701 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
704 foreach ($terms as $term) {
705 $profile = APContact::getByURL($term['url'], false);
706 if (!empty($profile)) {
707 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
709 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
710 $data['cc'][] = $profile['followers'];
713 $data['to'][] = $profile['url'];
717 $receiver_list = Item::enumeratePermissions($item, true);
719 foreach ($terms as $term) {
720 $cid = Contact::getIdForURL($term['url'], $item['uid']);
721 if (!empty($cid) && in_array($cid, $receiver_list)) {
722 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
723 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
727 $profile = APContact::getByURL($term['url'], false);
728 if (!empty($profile)) {
729 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
731 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
732 $data['cc'][] = $profile['followers'];
735 $data['to'][] = $profile['url'];
740 if ($is_forum && !$exclusive && !empty($follower)) {
741 $data['cc'][] = $follower;
742 } elseif (!$exclusive) {
743 foreach ($receiver_list as $receiver) {
744 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
745 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
749 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
750 if ($contact['hidden'] || $always_bcc) {
751 $data['bcc'][] = $profile['url'];
753 $data['cc'][] = $profile['url'];
760 if (!empty($item['parent'])) {
761 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']], ['order' => ['id']]);
762 while ($parent = Post::fetch($parents)) {
763 if ($parent['gravity'] == GRAVITY_PARENT) {
764 $profile = APContact::getByURL($parent['owner-link'], false);
765 if (!empty($profile)) {
766 if ($item['gravity'] != GRAVITY_PARENT) {
767 // Comments to forums are directed to the forum
768 // But comments to forums aren't directed to the followers collection
769 // This rule is only valid when the actor isn't the forum.
770 // The forum needs to transmit their content to their followers.
771 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
772 $data['to'][] = $profile['url'];
774 $data['cc'][] = $profile['url'];
775 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])&& !$is_forum_thread) {
776 $data['cc'][] = $actor_profile['followers'];
779 } elseif (!$exclusive && !$is_forum_thread) {
780 // Public thread parent post always are directed to the followers.
781 if ($item['private'] != Item::PRIVATE) {
782 $data['cc'][] = $actor_profile['followers'];
788 // Don't include data from future posts
789 if ($parent['id'] >= $last_id) {
793 $profile = APContact::getByURL($parent['author-link'], false);
794 if (!empty($profile)) {
795 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
796 $data['to'][] = $profile['url'];
798 $data['cc'][] = $profile['url'];
802 DBA::close($parents);
805 $data['to'] = array_unique($data['to']);
806 $data['cc'] = array_unique($data['cc']);
807 $data['bcc'] = array_unique($data['bcc']);
809 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
810 unset($data['to'][$key]);
813 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
814 unset($data['cc'][$key]);
817 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
818 unset($data['bcc'][$key]);
821 foreach ($data['to'] as $to) {
822 if (($key = array_search($to, $data['cc'])) !== false) {
823 unset($data['cc'][$key]);
826 if (($key = array_search($to, $data['bcc'])) !== false) {
827 unset($data['bcc'][$key]);
831 foreach ($data['cc'] as $cc) {
832 if (($key = array_search($cc, $data['bcc'])) !== false) {
833 unset($data['bcc'][$key]);
837 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
840 unset($receivers['bcc']);
843 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
844 if (!empty($receivers[$element])) {
845 foreach ($receivers[$element] as $receiver) {
846 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
847 $name = Receiver::PUBLIC_COLLECTION;
849 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
851 Tag::store($item['uri-id'], $type, $name, $receiver);
860 * Check if an inbox is archived
862 * @param string $url Inbox url
863 * @return boolean "true" if inbox is archived
865 public static function archivedInbox(string $url): bool
867 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
871 * Check if a given contact should be delivered via AP
873 * @param array $contact Contact array
874 * @param array $networks Array with networks
875 * @return bool Whether the used protocol matches ACTIVITYPUB
878 private static function isAPContact(array $contact, array $networks): bool
880 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
884 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
888 * Fetches a list of inboxes of followers of a given user
890 * @param integer $uid User ID
891 * @param boolean $personal fetch personal inboxes
892 * @param boolean $all_ap Retrieve all AP enabled inboxes
893 * @return array of follower inboxes
894 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
895 * @throws \ImagickException
897 public static function fetchTargetInboxesforUser(int $uid, bool $personal = false, bool $all_ap = false): array
903 if (!empty($item['uid'])) {
904 $profile = User::getOwnerDataById($item['uid']);
905 if (!empty($profile)) {
906 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
910 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
911 // Will be activated in a later step
912 $networks = Protocol::FEDERATED;
914 // For now only send to these contacts:
915 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
923 'network' => Protocol::FEDERATED,
927 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
930 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
931 while ($contact = DBA::fetch($contacts)) {
932 if (!self::isAPContact($contact, $networks)) {
936 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
940 if (Network::isUrlBlocked($contact['url'])) {
944 $profile = APContact::getByURL($contact['url'], false);
945 if (!empty($profile)) {
946 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
947 $target = $profile['inbox'];
949 $target = $profile['sharedinbox'];
951 if (!self::archivedInbox($target)) {
952 $inboxes[$target][] = $contact['id'];
956 DBA::close($contacts);
962 * Fetches an array of inboxes for the given item and user
964 * @param array $item Item array
965 * @param integer $uid User ID
966 * @param boolean $personal fetch personal inboxes
967 * @param integer $last_id Last item id for adding receivers
968 * @return array with inboxes
969 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
970 * @throws \ImagickException
972 public static function fetchTargetInboxes(array $item, int $uid, bool $personal = false, int $last_id = 0): array
974 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
975 if (empty($permissions)) {
981 if ($item['gravity'] == GRAVITY_ACTIVITY) {
982 $item_profile = APContact::getByURL($item['author-link'], false);
984 $item_profile = APContact::getByURL($item['owner-link'], false);
987 if (empty($item_profile)) {
991 $profile_uid = User::getIdForURL($item_profile['url']);
993 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
994 if (empty($permissions[$element])) {
998 $blindcopy = in_array($element, ['bto', 'bcc']);
1000 foreach ($permissions[$element] as $receiver) {
1001 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
1005 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
1006 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
1008 $profile = APContact::getByURL($receiver, false);
1009 if (!empty($profile)) {
1010 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
1012 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
1013 $target = $profile['inbox'];
1015 $target = $profile['sharedinbox'];
1017 if (!self::archivedInbox($target)) {
1018 $inboxes[$target][] = $contact['id'] ?? 0;
1029 * Creates an array in the structure of the item table for a given mail id
1031 * @param integer $mail_id Mail id
1033 * @throws \Exception
1035 public static function getItemArrayFromMail(int $mail_id, bool $use_title = false): array
1037 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
1038 if (!DBA::isResult($mail)) {
1042 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
1043 if (!DBA::isResult($reply)) {
1047 // Making the post more compatible for Mastodon by:
1048 // - Making it a note and not an article (no title)
1049 // - Moving the title into the "summary" field that is used as a "content warning"
1052 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1053 $mail['title'] = '';
1056 $mail['content-warning'] = '';
1057 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1058 $mail['owner-id'] = $mail['author-id'];
1059 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1060 $mail['allow_gid'] = '';
1061 $mail['deny_cid'] = '';
1062 $mail['deny_gid'] = '';
1063 $mail['private'] = Item::PRIVATE;
1064 $mail['deleted'] = false;
1065 $mail['edited'] = $mail['created'];
1066 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1067 $mail['parent-uri'] = $reply['uri'];
1068 $mail['parent-uri-id'] = $reply['uri-id'];
1069 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1070 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
1071 $mail['event-type'] = '';
1072 $mail['language'] = '';
1073 $mail['parent'] = 0;
1079 * Creates an activity array for a given mail id
1081 * @param integer $mail_id
1082 * @param boolean $object_mode Is the activity item is used inside another object?
1084 * @return array of activity
1085 * @throws \Exception
1087 public static function createActivityFromMail(int $mail_id, bool $object_mode = false): array
1089 $mail = self::getItemArrayFromMail($mail_id);
1093 $object = self::createNote($mail);
1095 if (!$object_mode) {
1096 $data = ['@context' => ActivityPub::CONTEXT];
1101 $data['id'] = $mail['uri'] . '/Create';
1102 $data['type'] = 'Create';
1103 $data['actor'] = $mail['author-link'];
1104 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1105 $data['instrument'] = self::getService();
1106 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1108 if (empty($data['to']) && !empty($data['cc'])) {
1109 $data['to'] = $data['cc'];
1112 if (empty($data['to']) && !empty($data['bcc'])) {
1113 $data['to'] = $data['bcc'];
1117 unset($data['bcc']);
1119 $object['to'] = $data['to'];
1120 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1122 unset($object['cc']);
1123 unset($object['bcc']);
1125 $data['directMessage'] = true;
1127 $data['object'] = $object;
1129 $owner = User::getOwnerDataById($mail['uid']);
1131 if (!$object_mode && !empty($owner)) {
1132 return LDSignature::sign($data, $owner);
1139 * Returns the activity type of a given item
1141 * @param array $item Item array
1142 * @return string with activity type
1143 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1144 * @throws \ImagickException
1146 private static function getTypeOfItem(array $item): string
1150 // Only check for a reshare, if it is a real reshare and no quoted reshare
1151 if (strpos($item['body'], '[share') === 0) {
1152 $announce = self::getAnnounceArray($item);
1153 $reshared = !empty($announce);
1158 } elseif ($item['verb'] == Activity::POST) {
1159 if ($item['created'] == $item['edited']) {
1164 } elseif ($item['verb'] == Activity::LIKE) {
1166 } elseif ($item['verb'] == Activity::DISLIKE) {
1168 } elseif ($item['verb'] == Activity::ATTEND) {
1170 } elseif ($item['verb'] == Activity::ATTENDNO) {
1172 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1173 $type = 'TentativeAccept';
1174 } elseif ($item['verb'] == Activity::FOLLOW) {
1176 } elseif ($item['verb'] == Activity::TAG) {
1178 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1188 * Creates the activity or fetches it from the cache
1190 * @param integer $item_id Item id
1191 * @param boolean $force Force new cache entry
1192 * @return array|false activity or false on failure
1193 * @throws \Exception
1195 public static function createCachedActivityFromItem(int $item_id, bool $force = false)
1197 $cachekey = 'APDelivery:createActivity:' . $item_id;
1200 $data = DI::cache()->get($cachekey);
1201 if (!is_null($data)) {
1206 $data = self::createActivityFromItem($item_id);
1208 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1213 * Creates an activity array for a given item id
1215 * @param integer $item_id
1216 * @param boolean $object_mode Is the activity item is used inside another object?
1217 * @return false|array
1218 * @throws \Exception
1220 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1222 Logger::info('Fetching activity', ['item' => $item_id]);
1223 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1224 if (!DBA::isResult($item)) {
1228 if (empty($item['uri-id'])) {
1229 Logger::warning('Item without uri-id', ['item' => $item]);
1233 if (!$item['deleted']) {
1234 $data = Post\Activity::getByURIId($item['uri-id']);
1235 if (!$item['origin'] && !empty($data)) {
1236 if (!empty($data['type'])) {
1237 if (in_array($data['type'], ['Create', 'Update'])) {
1239 unset($data['@context']);
1240 unset($data['signature']);
1242 Logger::info('Return stored conversation', ['item' => $item_id]);
1244 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1245 if (!empty($data['@context'])) {
1246 $context = $data['@context'];
1247 unset($data['@context']);
1249 unset($data['actor']);
1256 $type = self::getTypeOfItem($item);
1258 if (!$object_mode) {
1259 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1261 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1263 } elseif ($item['deleted']) {
1270 if ($type == 'Delete') {
1271 $data['id'] = Item::newURI($item['guid']) . '/' . $type;;
1272 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1273 $data['id'] = $item['uri'];
1275 $data['id'] = $item['uri'] . '/' . $type;
1278 $data['type'] = $type;
1280 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1281 $data['actor'] = $item['author-link'];
1283 $data['actor'] = $item['owner-link'];
1286 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1288 $data['instrument'] = self::getService();
1290 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1292 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1293 $data['object'] = $object ?? self::createNote($item);
1294 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1295 } elseif ($data['type'] == 'Add') {
1296 $data = self::createAddTag($item, $data);
1297 } elseif ($data['type'] == 'Announce') {
1298 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1299 $data['object'] = $item['thr-parent'];
1301 $data = self::createAnnounce($item, $data);
1303 } elseif ($data['type'] == 'Follow') {
1304 $data['object'] = $item['parent-uri'];
1305 } elseif ($data['type'] == 'Undo') {
1306 $data['object'] = self::createActivityFromItem($item_id, true);
1308 $data['diaspora:guid'] = $item['guid'];
1309 if (!empty($item['signed_text'])) {
1310 $data['diaspora:like'] = $item['signed_text'];
1312 $data['object'] = $item['thr-parent'];
1315 if (!empty($item['contact-uid'])) {
1316 $uid = $item['contact-uid'];
1318 $uid = $item['uid'];
1321 $owner = User::getOwnerDataById($uid);
1323 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1325 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1326 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1327 return LDSignature::sign($data, $owner);
1332 /// @todo Create "conversation" entry
1336 * Creates a location entry for a given item array
1338 * @param array $item Item array
1339 * @return array with location array
1341 private static function createLocation(array $item): array
1343 $location = ['type' => 'Place'];
1345 if (!empty($item['location'])) {
1346 $location['name'] = $item['location'];
1351 if (empty($item['coord'])) {
1352 $coord = Map::getCoordinates($item['location']);
1354 $coords = explode(' ', $item['coord']);
1355 if (count($coords) == 2) {
1356 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1360 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1361 $location['latitude'] = $coord['lat'];
1362 $location['longitude'] = $coord['lon'];
1369 * Returns a tag array for a given item array
1371 * @param array $item Item array
1372 * @return array of tags
1373 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1375 private static function createTagList(array $item): array
1379 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1380 foreach ($terms as $term) {
1381 if ($term['type'] == Tag::HASHTAG) {
1382 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1383 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1385 $contact = Contact::getByURL($term['url'], false, ['addr']);
1386 if (empty($contact)) {
1389 if (!empty($contact['addr'])) {
1390 $mention = '@' . $contact['addr'];
1392 $mention = '@' . $term['url'];
1395 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1399 $announce = self::getAnnounceArray($item);
1400 // Mention the original author upon commented reshares
1401 if (!empty($announce['comment'])) {
1402 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1409 * Adds attachment data to the JSON document
1411 * @param array $item Data of the item that is to be posted
1412 * @param string $type Object type
1414 * @return array with attachment data
1415 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1417 private static function createAttachmentList(array $item, string $type): array
1421 $uriids = [$item['uri-id']];
1422 $shared = BBCode::fetchShareAttributes($item['body']);
1423 if (!empty($shared['guid'])) {
1424 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1425 if (!empty($shared_item['uri-id'])) {
1426 $uriids[] = $shared_item['uri-id'];
1431 foreach ($uriids as $uriid) {
1432 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1433 if (in_array($attachment['url'], $urls)) {
1436 $urls[] = $attachment['url'];
1438 $attach = ['type' => 'Document',
1439 'mediaType' => $attachment['mimetype'],
1440 'url' => $attachment['url'],
1441 'name' => $attachment['description']];
1443 if (!empty($attachment['height'])) {
1444 $attach['height'] = $attachment['height'];
1447 if (!empty($attachment['width'])) {
1448 $attach['width'] = $attachment['width'];
1451 if (!empty($attachment['preview'])) {
1452 $attach['image'] = $attachment['preview'];
1455 $attachments[] = $attach;
1459 return $attachments;
1463 * Callback function to replace a Friendica style mention in a mention for a summary
1465 * @param array $match Matching values for the callback
1466 * @return string Replaced mention
1467 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1469 private static function mentionAddrCallback(array $match): string
1471 if (empty($match[1])) {
1475 $data = Contact::getByURL($match[1], false, ['addr']);
1476 if (empty($data['addr'])) {
1480 return '@' . $data['addr'];
1484 * Remove image elements since they are added as attachment
1486 * @param string $body HTML code
1487 * @return string with removed images
1489 private static function removePictures(string $body): string
1491 // Simplify image codes
1492 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1493 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1495 // Now remove local links
1496 $body = preg_replace_callback(
1497 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1499 // We remove the link when it is a link to a local photo page
1500 if (Photo::isLocalPage($match[1])) {
1503 // otherwise we just return the link
1504 return '[url]' . $match[1] . '[/url]';
1509 // Remove all pictures
1510 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1516 * Returns if the post contains sensitive content ("nsfw")
1518 * @param integer $uri_id URI id
1519 * @return boolean Whether URI id was found
1520 * @throws \Exception
1522 private static function isSensitive(int $uri_id): bool
1524 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1528 * Creates event data
1530 * @param array $item Item array
1531 * @return array with the event data
1532 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1534 private static function createEvent(array $item): array
1537 $event['name'] = $item['event-summary'];
1538 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1539 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1541 if (!$item['event-nofinish']) {
1542 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1545 if (!empty($item['event-location'])) {
1546 $item['location'] = $item['event-location'];
1547 $event['location'] = self::createLocation($item);
1550 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1551 $event['dfrn:adjust'] = true;
1557 * Creates a note/article object array
1559 * @param array $item
1560 * @return array with the object data
1561 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1562 * @throws \ImagickException
1564 public static function createNote(array $item): array
1570 // We are treating posts differently when they are directed to a community.
1571 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1572 // But to not risk compatibility issues we currently perform the changes only for communities.
1573 if ($item['gravity'] == GRAVITY_PARENT) {
1574 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1575 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1576 if ($isCommunityPost && (count($links) == 1)) {
1577 $link = $links[0]['url'];
1580 $isCommunityPost = false;
1583 if ($item['event-type'] == 'event') {
1585 } elseif (!empty($item['title'])) {
1586 if (!$isCommunityPost || empty($link)) {
1589 // "Page" is used by Lemmy for posts that contain an external link
1596 if ($item['deleted']) {
1597 $type = 'Tombstone';
1601 $data['id'] = $item['uri'];
1602 $data['type'] = $type;
1604 if ($item['deleted']) {
1608 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1610 if ($item['uri'] != $item['thr-parent']) {
1611 $data['inReplyTo'] = $item['thr-parent'];
1613 $data['inReplyTo'] = null;
1616 $data['diaspora:guid'] = $item['guid'];
1617 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1619 if ($item['created'] != $item['edited']) {
1620 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1623 $data['url'] = $link ?? $item['plink'];
1624 $data['attributedTo'] = $item['author-link'];
1625 $data['sensitive'] = self::isSensitive($item['uri-id']);
1626 $data['conversation'] = $data['context'] = $item['conversation'];
1628 if (!empty($item['title'])) {
1629 $data['name'] = BBCode::toPlaintext($item['title'], false);
1632 $permission_block = self::createPermissionBlockForItem($item, false);
1634 $body = $item['body'];
1636 if ($type == 'Note') {
1637 $body = $item['raw-body'] ?? self::removePictures($body);
1641 * @todo Improve the automated summary
1642 * This part is currently deactivated. The automated summary seems to be more
1643 * confusing than helping. But possibly we will find a better way.
1644 * So the code is left here for now as a reminder
1646 * } elseif (($type == 'Article') && empty($data['summary'])) {
1647 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1648 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1649 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1653 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1654 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1657 if ($type == 'Event') {
1658 $data = array_merge($data, self::createEvent($item));
1660 if ($isCommunityPost) {
1661 // For community posts we remove the visible "!user@domain.tld".
1662 // This improves the look at systems like Lemmy.
1663 // Also in the future we should control the community delivery via other methods.
1664 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1667 if ($type == 'Page') {
1668 // When we transmit "Page" posts we have to remove the attachment.
1669 // The attachment contains the link that we already transmit in the "url" field.
1670 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1673 $body = BBCode::setMentionsToNicknames($body);
1675 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1678 // The regular "content" field does contain a minimized HTML. This is done since systems like
1679 // Mastodon has got problems with - for example - embedded pictures.
1680 // The contentMap does contain the unmodified HTML.
1681 $language = self::getLanguage($item);
1682 if (!empty($language)) {
1683 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1684 $richbody = BBCode::removeAttachment($richbody);
1686 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1689 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1691 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1692 $data['diaspora:comment'] = $item['signed_text'];
1695 $data['attachment'] = self::createAttachmentList($item, $type);
1696 $data['tag'] = self::createTagList($item);
1698 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1699 $data['location'] = self::createLocation($item);
1702 if (!empty($item['app'])) {
1703 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1706 $data = array_merge($data, $permission_block);
1712 * Fetches the language from the post, the user or the system.
1714 * @param array $item
1715 * @return string language string
1717 private static function getLanguage(array $item): string
1719 // Try to fetch the language from the post itself
1720 if (!empty($item['language'])) {
1721 $languages = array_keys(json_decode($item['language'], true));
1722 if (!empty($languages[0])) {
1723 return $languages[0];
1727 // Otherwise use the user's language
1728 if (!empty($item['uid'])) {
1729 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1730 if (!empty($user['language'])) {
1731 return $user['language'];
1735 // And finally just use the system language
1736 return DI::config()->get('system', 'language');
1740 * Creates an an "add tag" entry
1742 * @param array $item Item array
1743 * @param array $activity activity data
1744 * @return array with activity data for adding tags
1745 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1746 * @throws \ImagickException
1748 private static function createAddTag(array $item, array $activity): array
1750 $object = XML::parseString($item['object']);
1751 $target = XML::parseString($item['target']);
1753 $activity['diaspora:guid'] = $item['guid'];
1754 $activity['actor'] = $item['author-link'];
1755 $activity['target'] = (string)$target->id;
1756 $activity['summary'] = BBCode::toPlaintext($item['body']);
1757 $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1763 * Creates an announce object entry
1765 * @param array $item Item array
1766 * @param array $activity activity data
1767 * @return array with activity data
1768 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1769 * @throws \ImagickException
1771 private static function createAnnounce(array $item, array $activity): array
1773 $orig_body = $item['body'];
1774 $announce = self::getAnnounceArray($item);
1775 if (empty($announce)) {
1776 $activity['type'] = 'Create';
1777 $activity['object'] = self::createNote($item);
1781 if (empty($announce['comment'])) {
1782 // Pure announce, without a quote
1783 $activity['type'] = 'Announce';
1784 $activity['object'] = $announce['object']['uri'];
1789 $activity['type'] = 'Create';
1790 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1791 $activity['object'] = self::createNote($item);
1793 /// @todo Finally descide how to implement this in AP. This is a possible way:
1794 $activity['object']['attachment'][] = self::createNote($announce['object']);
1796 $activity['object']['source']['content'] = $orig_body;
1801 * Return announce related data if the item is an annunce
1803 * @param array $item
1804 * @return array Announcement array
1806 public static function getAnnounceArray(array $item): array
1808 $reshared = Item::getShareArray($item);
1809 if (empty($reshared['guid'])) {
1813 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1814 if (!DBA::isResult($reshared_item)) {
1818 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1822 $profile = APContact::getByURL($reshared_item['author-link'], false);
1823 if (empty($profile)) {
1827 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1831 * Checks if the provided item array is an announce
1833 * @param array $item Item array
1834 * @return boolean Whether item is an announcement
1836 public static function isAnnounce(array $item): bool
1838 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1842 $announce = self::getAnnounceArray($item);
1843 if (empty($announce)) {
1847 return empty($announce['comment']);
1851 * Creates an activity id for a given contact id
1853 * @param integer $cid Contact ID of target
1855 * @return bool|string activity id
1857 public static function activityIDFromContact(int $cid)
1859 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1860 if (!DBA::isResult($contact)) {
1864 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1865 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1866 return DI::baseUrl() . '/activity/' . $uuid;
1870 * Transmits a contact suggestion to a given inbox
1872 * @param integer $uid User ID
1873 * @param string $inbox Target inbox
1874 * @param integer $suggestion_id Suggestion ID
1875 * @return boolean was the transmission successful?
1876 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1878 public static function sendContactSuggestion(int $uid, string $inbox, int $suggestion_id): bool
1880 $owner = User::getOwnerDataById($uid);
1882 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1885 '@context' => ActivityPub::CONTEXT,
1886 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1887 'type' => 'Announce',
1888 'actor' => $owner['url'],
1889 'object' => $suggestion->url,
1890 'content' => $suggestion->note,
1891 'instrument' => self::getService(),
1892 'to' => [ActivityPub::PUBLIC_COLLECTION],
1896 $signed = LDSignature::sign($data, $owner);
1898 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1899 return HTTPSignature::transmit($signed, $inbox, $uid);
1903 * Transmits a profile relocation to a given inbox
1905 * @param integer $uid User ID
1906 * @param string $inbox Target inbox
1907 * @return boolean was the transmission successful?
1908 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1910 public static function sendProfileRelocation(int $uid, string $inbox): bool
1912 $owner = User::getOwnerDataById($uid);
1915 '@context' => ActivityPub::CONTEXT,
1916 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1917 'type' => 'dfrn:relocate',
1918 'actor' => $owner['url'],
1919 'object' => $owner['url'],
1920 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1921 'instrument' => self::getService(),
1922 'to' => [ActivityPub::PUBLIC_COLLECTION],
1926 $signed = LDSignature::sign($data, $owner);
1928 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1929 return HTTPSignature::transmit($signed, $inbox, $uid);
1933 * Transmits a profile deletion to a given inbox
1935 * @param integer $uid User ID
1936 * @param string $inbox Target inbox
1937 * @return boolean was the transmission successful?
1938 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1940 public static function sendProfileDeletion(int $uid, string $inbox): bool
1942 $owner = User::getOwnerDataById($uid);
1944 if (empty($owner)) {
1945 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1949 if (empty($owner['uprvkey'])) {
1950 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1954 $data = ['@context' => ActivityPub::CONTEXT,
1955 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1957 'actor' => $owner['url'],
1958 'object' => $owner['url'],
1959 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1960 'instrument' => self::getService(),
1961 'to' => [ActivityPub::PUBLIC_COLLECTION],
1964 $signed = LDSignature::sign($data, $owner);
1966 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1967 return HTTPSignature::transmit($signed, $inbox, $uid);
1971 * Transmits a profile change to a given inbox
1973 * @param integer $uid User ID
1974 * @param string $inbox Target inbox
1975 * @return boolean was the transmission successful?
1976 * @throws HTTPException\InternalServerErrorException
1977 * @throws HTTPException\NotFoundException
1978 * @throws \ImagickException
1980 public static function sendProfileUpdate(int $uid, string $inbox): bool
1982 $owner = User::getOwnerDataById($uid);
1983 $profile = APContact::getByURL($owner['url']);
1985 $data = ['@context' => ActivityPub::CONTEXT,
1986 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1988 'actor' => $owner['url'],
1989 'object' => self::getProfile($uid),
1990 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1991 'instrument' => self::getService(),
1992 'to' => [$profile['followers']],
1995 $signed = LDSignature::sign($data, $owner);
1997 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1998 return HTTPSignature::transmit($signed, $inbox, $uid);
2002 * Transmits a given activity to a target
2004 * @param string $activity Type name
2005 * @param string $target Target profile
2006 * @param integer $uid User ID
2007 * @param string $id Activity-identifier
2009 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2010 * @throws \ImagickException
2011 * @throws \Exception
2013 public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2015 $profile = APContact::getByURL($target);
2016 if (empty($profile['inbox'])) {
2017 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2021 $owner = User::getOwnerDataById($uid);
2024 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2028 '@context' => ActivityPub::CONTEXT,
2030 'type' => $activity,
2031 'actor' => $owner['url'],
2032 'object' => $profile['url'],
2033 'instrument' => self::getService(),
2034 'to' => [$profile['url']],
2037 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2039 $signed = LDSignature::sign($data, $owner);
2040 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2044 * Transmits a "follow object" activity to a target
2045 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2047 * @param string $object Object URL
2048 * @param string $target Target profile
2049 * @param integer $uid User ID
2051 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2052 * @throws \ImagickException
2053 * @throws \Exception
2055 public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2057 $profile = APContact::getByURL($target);
2058 if (empty($profile['inbox'])) {
2059 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2064 // Fetch the list of administrators
2065 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2067 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2068 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2069 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2070 $uid = $first_user['uid'];
2073 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2074 'author-id' => Contact::getPublicIdByUserId($uid)];
2075 if (Post::exists($condition)) {
2076 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2080 $owner = User::getOwnerDataById($uid);
2083 '@context' => ActivityPub::CONTEXT,
2084 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2086 'actor' => $owner['url'],
2087 'object' => $object,
2088 'instrument' => self::getService(),
2089 'to' => [$profile['url']],
2092 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2094 $signed = LDSignature::sign($data, $owner);
2095 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2099 * Transmit a message that the contact request had been accepted
2101 * @param string $target Target profile
2102 * @param string $id Object id
2103 * @param integer $uid User ID
2105 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2106 * @throws \ImagickException
2108 public static function sendContactAccept(string $target, string $id, int $uid)
2110 $profile = APContact::getByURL($target);
2111 if (empty($profile['inbox'])) {
2112 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2116 $owner = User::getOwnerDataById($uid);
2118 '@context' => ActivityPub::CONTEXT,
2119 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2121 'actor' => $owner['url'],
2125 'actor' => $profile['url'],
2126 'object' => $owner['url']
2128 'instrument' => self::getService(),
2129 'to' => [$profile['url']],
2132 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2134 $signed = LDSignature::sign($data, $owner);
2135 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2139 * Reject a contact request or terminates the contact relation
2141 * @param string $target Target profile
2142 * @param string $objectId Object id
2143 * @param int $uid User ID
2144 * @return bool Operation success
2145 * @throws HTTPException\InternalServerErrorException
2146 * @throws \ImagickException
2148 public static function sendContactReject(string $target, string $objectId, int $uid): bool
2150 $profile = APContact::getByURL($target);
2151 if (empty($profile['inbox'])) {
2152 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2156 $owner = User::getOwnerDataById($uid);
2158 '@context' => ActivityPub::CONTEXT,
2159 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2161 'actor' => $owner['url'],
2165 'actor' => $profile['url'],
2166 'object' => $owner['url']
2168 'instrument' => self::getService(),
2169 'to' => [$profile['url']],
2172 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2174 $signed = LDSignature::sign($data, $owner);
2175 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2179 * Transmits a message that we don't want to follow this contact anymore
2181 * @param string $target Target profile
2182 * @param integer $cid Contact id
2183 * @param integer $uid User ID
2184 * @return bool success
2185 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2186 * @throws \ImagickException
2187 * @throws \Exception
2189 public static function sendContactUndo(string $target, int $cid, int $uid): bool
2191 $profile = APContact::getByURL($target);
2192 if (empty($profile['inbox'])) {
2193 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2197 $object_id = self::activityIDFromContact($cid);
2198 if (empty($object_id)) {
2202 $objectId = DI::baseUrl() . '/activity/' . System::createGUID();
2204 $owner = User::getOwnerDataById($uid);
2206 '@context' => ActivityPub::CONTEXT,
2209 'actor' => $owner['url'],
2213 'actor' => $owner['url'],
2214 'object' => $profile['url']
2216 'instrument' => self::getService(),
2217 'to' => [$profile['url']],
2220 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2222 $signed = LDSignature::sign($data, $owner);
2223 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2227 * Prepends mentions (@) to $body variable
2229 * @param string $body HTML code
2231 * @param string $authorLink Author link
2232 * @return string HTML code with prepended mentions
2234 private static function prependMentions(string $body, int $uriid, string $authorLink): string
2238 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2239 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2240 if (!empty($profile['addr'])
2241 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2242 && !strstr($body, $profile['addr'])
2243 && !strstr($body, $tag['url'])
2244 && $tag['url'] !== $authorLink
2246 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2250 $mentions[] = $body;
2252 return implode(' ', $mentions);