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)) {
1237 unset($data['@context']);
1238 unset($data['signature']);
1240 Logger::info('Return stored conversation', ['item' => $item_id]);
1245 if (!$item['origin'] && empty($object)) {
1246 Logger::debug('Post is not ours and is not stored', ['id' => $item_id, 'uri-id' => $item['uri-id']]);
1250 $type = self::getTypeOfItem($item);
1252 if (!$object_mode) {
1253 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1255 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1257 } elseif ($item['deleted']) {
1264 if ($type == 'Delete') {
1265 $data['id'] = Item::newURI($item['guid']) . '/' . $type;;
1266 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1267 $data['id'] = $item['uri'];
1269 $data['id'] = $item['uri'] . '/' . $type;
1272 $data['type'] = $type;
1274 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1275 $data['actor'] = $item['author-link'];
1277 $data['actor'] = $item['owner-link'];
1280 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1282 $data['instrument'] = self::getService();
1284 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1286 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1287 $data['object'] = $object ?? self::createNote($item);
1288 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1289 } elseif ($data['type'] == 'Add') {
1290 $data = self::createAddTag($item, $data);
1291 } elseif ($data['type'] == 'Announce') {
1292 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1293 $data['object'] = $item['thr-parent'];
1295 $data = self::createAnnounce($item, $data);
1297 } elseif ($data['type'] == 'Follow') {
1298 $data['object'] = $item['parent-uri'];
1299 } elseif ($data['type'] == 'Undo') {
1300 $data['object'] = self::createActivityFromItem($item_id, true);
1302 $data['diaspora:guid'] = $item['guid'];
1303 if (!empty($item['signed_text'])) {
1304 $data['diaspora:like'] = $item['signed_text'];
1306 $data['object'] = $item['thr-parent'];
1309 if (!empty($item['contact-uid'])) {
1310 $uid = $item['contact-uid'];
1312 $uid = $item['uid'];
1315 $owner = User::getOwnerDataById($uid);
1317 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1319 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1320 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1321 return LDSignature::sign($data, $owner);
1326 /// @todo Create "conversation" entry
1330 * Creates a location entry for a given item array
1332 * @param array $item Item array
1333 * @return array with location array
1335 private static function createLocation(array $item): array
1337 $location = ['type' => 'Place'];
1339 if (!empty($item['location'])) {
1340 $location['name'] = $item['location'];
1345 if (empty($item['coord'])) {
1346 $coord = Map::getCoordinates($item['location']);
1348 $coords = explode(' ', $item['coord']);
1349 if (count($coords) == 2) {
1350 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1354 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1355 $location['latitude'] = $coord['lat'];
1356 $location['longitude'] = $coord['lon'];
1363 * Returns a tag array for a given item array
1365 * @param array $item Item array
1366 * @return array of tags
1367 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1369 private static function createTagList(array $item): array
1373 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1374 foreach ($terms as $term) {
1375 if ($term['type'] == Tag::HASHTAG) {
1376 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1377 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1379 $contact = Contact::getByURL($term['url'], false, ['addr']);
1380 if (empty($contact)) {
1383 if (!empty($contact['addr'])) {
1384 $mention = '@' . $contact['addr'];
1386 $mention = '@' . $term['url'];
1389 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1393 $announce = self::getAnnounceArray($item);
1394 // Mention the original author upon commented reshares
1395 if (!empty($announce['comment'])) {
1396 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1403 * Adds attachment data to the JSON document
1405 * @param array $item Data of the item that is to be posted
1406 * @param string $type Object type
1408 * @return array with attachment data
1409 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1411 private static function createAttachmentList(array $item, string $type): array
1415 $uriids = [$item['uri-id']];
1416 $shared = BBCode::fetchShareAttributes($item['body']);
1417 if (!empty($shared['guid'])) {
1418 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1419 if (!empty($shared_item['uri-id'])) {
1420 $uriids[] = $shared_item['uri-id'];
1425 foreach ($uriids as $uriid) {
1426 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1427 if (in_array($attachment['url'], $urls)) {
1430 $urls[] = $attachment['url'];
1432 $attach = ['type' => 'Document',
1433 'mediaType' => $attachment['mimetype'],
1434 'url' => $attachment['url'],
1435 'name' => $attachment['description']];
1437 if (!empty($attachment['height'])) {
1438 $attach['height'] = $attachment['height'];
1441 if (!empty($attachment['width'])) {
1442 $attach['width'] = $attachment['width'];
1445 if (!empty($attachment['preview'])) {
1446 $attach['image'] = $attachment['preview'];
1449 $attachments[] = $attach;
1453 return $attachments;
1457 * Callback function to replace a Friendica style mention in a mention for a summary
1459 * @param array $match Matching values for the callback
1460 * @return string Replaced mention
1461 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1463 private static function mentionAddrCallback(array $match): string
1465 if (empty($match[1])) {
1469 $data = Contact::getByURL($match[1], false, ['addr']);
1470 if (empty($data['addr'])) {
1474 return '@' . $data['addr'];
1478 * Remove image elements since they are added as attachment
1480 * @param string $body HTML code
1481 * @return string with removed images
1483 private static function removePictures(string $body): string
1485 // Simplify image codes
1486 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1487 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1489 // Now remove local links
1490 $body = preg_replace_callback(
1491 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1493 // We remove the link when it is a link to a local photo page
1494 if (Photo::isLocalPage($match[1])) {
1497 // otherwise we just return the link
1498 return '[url]' . $match[1] . '[/url]';
1503 // Remove all pictures
1504 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1510 * Returns if the post contains sensitive content ("nsfw")
1512 * @param integer $uri_id URI id
1513 * @return boolean Whether URI id was found
1514 * @throws \Exception
1516 private static function isSensitive(int $uri_id): bool
1518 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1522 * Creates event data
1524 * @param array $item Item array
1525 * @return array with the event data
1526 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1528 private static function createEvent(array $item): array
1531 $event['name'] = $item['event-summary'];
1532 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1533 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1535 if (!$item['event-nofinish']) {
1536 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1539 if (!empty($item['event-location'])) {
1540 $item['location'] = $item['event-location'];
1541 $event['location'] = self::createLocation($item);
1544 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1545 $event['dfrn:adjust'] = true;
1551 * Creates a note/article object array
1553 * @param array $item
1554 * @return array with the object data
1555 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1556 * @throws \ImagickException
1558 public static function createNote(array $item): array
1564 // We are treating posts differently when they are directed to a community.
1565 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1566 // But to not risk compatibility issues we currently perform the changes only for communities.
1567 if ($item['gravity'] == GRAVITY_PARENT) {
1568 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1569 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1570 if ($isCommunityPost && (count($links) == 1)) {
1571 $link = $links[0]['url'];
1574 $isCommunityPost = false;
1577 if ($item['event-type'] == 'event') {
1579 } elseif (!empty($item['title'])) {
1580 if (!$isCommunityPost || empty($link)) {
1583 // "Page" is used by Lemmy for posts that contain an external link
1590 if ($item['deleted']) {
1591 $type = 'Tombstone';
1595 $data['id'] = $item['uri'];
1596 $data['type'] = $type;
1598 if ($item['deleted']) {
1602 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1604 if ($item['uri'] != $item['thr-parent']) {
1605 $data['inReplyTo'] = $item['thr-parent'];
1607 $data['inReplyTo'] = null;
1610 $data['diaspora:guid'] = $item['guid'];
1611 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1613 if ($item['created'] != $item['edited']) {
1614 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1617 $data['url'] = $link ?? $item['plink'];
1618 $data['attributedTo'] = $item['author-link'];
1619 $data['sensitive'] = self::isSensitive($item['uri-id']);
1620 $data['conversation'] = $data['context'] = $item['conversation'];
1622 if (!empty($item['title'])) {
1623 $data['name'] = BBCode::toPlaintext($item['title'], false);
1626 $permission_block = self::createPermissionBlockForItem($item, false);
1628 $body = $item['body'];
1630 if ($type == 'Note') {
1631 $body = $item['raw-body'] ?? self::removePictures($body);
1635 * @todo Improve the automated summary
1636 * This part is currently deactivated. The automated summary seems to be more
1637 * confusing than helping. But possibly we will find a better way.
1638 * So the code is left here for now as a reminder
1640 * } elseif (($type == 'Article') && empty($data['summary'])) {
1641 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1642 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1643 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1647 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1648 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1651 if ($type == 'Event') {
1652 $data = array_merge($data, self::createEvent($item));
1654 if ($isCommunityPost) {
1655 // For community posts we remove the visible "!user@domain.tld".
1656 // This improves the look at systems like Lemmy.
1657 // Also in the future we should control the community delivery via other methods.
1658 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1661 if ($type == 'Page') {
1662 // When we transmit "Page" posts we have to remove the attachment.
1663 // The attachment contains the link that we already transmit in the "url" field.
1664 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1667 $body = BBCode::setMentionsToNicknames($body);
1669 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1672 // The regular "content" field does contain a minimized HTML. This is done since systems like
1673 // Mastodon has got problems with - for example - embedded pictures.
1674 // The contentMap does contain the unmodified HTML.
1675 $language = self::getLanguage($item);
1676 if (!empty($language)) {
1677 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1678 $richbody = BBCode::removeAttachment($richbody);
1680 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1683 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1685 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1686 $data['diaspora:comment'] = $item['signed_text'];
1689 $data['attachment'] = self::createAttachmentList($item, $type);
1690 $data['tag'] = self::createTagList($item);
1692 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1693 $data['location'] = self::createLocation($item);
1696 if (!empty($item['app'])) {
1697 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1700 $data = array_merge($data, $permission_block);
1706 * Fetches the language from the post, the user or the system.
1708 * @param array $item
1709 * @return string language string
1711 private static function getLanguage(array $item): string
1713 // Try to fetch the language from the post itself
1714 if (!empty($item['language'])) {
1715 $languages = array_keys(json_decode($item['language'], true));
1716 if (!empty($languages[0])) {
1717 return $languages[0];
1721 // Otherwise use the user's language
1722 if (!empty($item['uid'])) {
1723 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1724 if (!empty($user['language'])) {
1725 return $user['language'];
1729 // And finally just use the system language
1730 return DI::config()->get('system', 'language');
1734 * Creates an an "add tag" entry
1736 * @param array $item Item array
1737 * @param array $activity activity data
1738 * @return array with activity data for adding tags
1739 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1740 * @throws \ImagickException
1742 private static function createAddTag(array $item, array $activity): array
1744 $object = XML::parseString($item['object']);
1745 $target = XML::parseString($item['target']);
1747 $activity['diaspora:guid'] = $item['guid'];
1748 $activity['actor'] = $item['author-link'];
1749 $activity['target'] = (string)$target->id;
1750 $activity['summary'] = BBCode::toPlaintext($item['body']);
1751 $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1757 * Creates an announce object entry
1759 * @param array $item Item array
1760 * @param array $activity activity data
1761 * @return array with activity data
1762 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1763 * @throws \ImagickException
1765 private static function createAnnounce(array $item, array $activity): array
1767 $orig_body = $item['body'];
1768 $announce = self::getAnnounceArray($item);
1769 if (empty($announce)) {
1770 $activity['type'] = 'Create';
1771 $activity['object'] = self::createNote($item);
1775 if (empty($announce['comment'])) {
1776 // Pure announce, without a quote
1777 $activity['type'] = 'Announce';
1778 $activity['object'] = $announce['object']['uri'];
1783 $activity['type'] = 'Create';
1784 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1785 $activity['object'] = self::createNote($item);
1787 /// @todo Finally descide how to implement this in AP. This is a possible way:
1788 $activity['object']['attachment'][] = self::createNote($announce['object']);
1790 $activity['object']['source']['content'] = $orig_body;
1795 * Return announce related data if the item is an annunce
1797 * @param array $item
1798 * @return array Announcement array
1800 public static function getAnnounceArray(array $item): array
1802 $reshared = Item::getShareArray($item);
1803 if (empty($reshared['guid'])) {
1807 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1808 if (!DBA::isResult($reshared_item)) {
1812 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1816 $profile = APContact::getByURL($reshared_item['author-link'], false);
1817 if (empty($profile)) {
1821 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1825 * Checks if the provided item array is an announce
1827 * @param array $item Item array
1828 * @return boolean Whether item is an announcement
1830 public static function isAnnounce(array $item): bool
1832 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1836 $announce = self::getAnnounceArray($item);
1837 if (empty($announce)) {
1841 return empty($announce['comment']);
1845 * Creates an activity id for a given contact id
1847 * @param integer $cid Contact ID of target
1849 * @return bool|string activity id
1851 public static function activityIDFromContact(int $cid)
1853 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1854 if (!DBA::isResult($contact)) {
1858 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1859 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1860 return DI::baseUrl() . '/activity/' . $uuid;
1864 * Transmits a contact suggestion to a given inbox
1866 * @param integer $uid User ID
1867 * @param string $inbox Target inbox
1868 * @param integer $suggestion_id Suggestion ID
1869 * @return boolean was the transmission successful?
1870 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1872 public static function sendContactSuggestion(int $uid, string $inbox, int $suggestion_id): bool
1874 $owner = User::getOwnerDataById($uid);
1876 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1879 '@context' => ActivityPub::CONTEXT,
1880 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1881 'type' => 'Announce',
1882 'actor' => $owner['url'],
1883 'object' => $suggestion->url,
1884 'content' => $suggestion->note,
1885 'instrument' => self::getService(),
1886 'to' => [ActivityPub::PUBLIC_COLLECTION],
1890 $signed = LDSignature::sign($data, $owner);
1892 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1893 return HTTPSignature::transmit($signed, $inbox, $uid);
1897 * Transmits a profile relocation to a given inbox
1899 * @param integer $uid User ID
1900 * @param string $inbox Target inbox
1901 * @return boolean was the transmission successful?
1902 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1904 public static function sendProfileRelocation(int $uid, string $inbox): bool
1906 $owner = User::getOwnerDataById($uid);
1909 '@context' => ActivityPub::CONTEXT,
1910 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1911 'type' => 'dfrn:relocate',
1912 'actor' => $owner['url'],
1913 'object' => $owner['url'],
1914 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1915 'instrument' => self::getService(),
1916 'to' => [ActivityPub::PUBLIC_COLLECTION],
1920 $signed = LDSignature::sign($data, $owner);
1922 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1923 return HTTPSignature::transmit($signed, $inbox, $uid);
1927 * Transmits a profile deletion to a given inbox
1929 * @param integer $uid User ID
1930 * @param string $inbox Target inbox
1931 * @return boolean was the transmission successful?
1932 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1934 public static function sendProfileDeletion(int $uid, string $inbox): bool
1936 $owner = User::getOwnerDataById($uid);
1938 if (empty($owner)) {
1939 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1943 if (empty($owner['uprvkey'])) {
1944 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1948 $data = ['@context' => ActivityPub::CONTEXT,
1949 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1951 'actor' => $owner['url'],
1952 'object' => $owner['url'],
1953 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1954 'instrument' => self::getService(),
1955 'to' => [ActivityPub::PUBLIC_COLLECTION],
1958 $signed = LDSignature::sign($data, $owner);
1960 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1961 return HTTPSignature::transmit($signed, $inbox, $uid);
1965 * Transmits a profile change to a given inbox
1967 * @param integer $uid User ID
1968 * @param string $inbox Target inbox
1969 * @return boolean was the transmission successful?
1970 * @throws HTTPException\InternalServerErrorException
1971 * @throws HTTPException\NotFoundException
1972 * @throws \ImagickException
1974 public static function sendProfileUpdate(int $uid, string $inbox): bool
1976 $owner = User::getOwnerDataById($uid);
1977 $profile = APContact::getByURL($owner['url']);
1979 $data = ['@context' => ActivityPub::CONTEXT,
1980 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1982 'actor' => $owner['url'],
1983 'object' => self::getProfile($uid),
1984 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1985 'instrument' => self::getService(),
1986 'to' => [$profile['followers']],
1989 $signed = LDSignature::sign($data, $owner);
1991 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1992 return HTTPSignature::transmit($signed, $inbox, $uid);
1996 * Transmits a given activity to a target
1998 * @param string $activity Type name
1999 * @param string $target Target profile
2000 * @param integer $uid User ID
2001 * @param string $id Activity-identifier
2003 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2004 * @throws \ImagickException
2005 * @throws \Exception
2007 public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2009 $profile = APContact::getByURL($target);
2010 if (empty($profile['inbox'])) {
2011 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2015 $owner = User::getOwnerDataById($uid);
2018 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2022 '@context' => ActivityPub::CONTEXT,
2024 'type' => $activity,
2025 'actor' => $owner['url'],
2026 'object' => $profile['url'],
2027 'instrument' => self::getService(),
2028 'to' => [$profile['url']],
2031 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2033 $signed = LDSignature::sign($data, $owner);
2034 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2038 * Transmits a "follow object" activity to a target
2039 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2041 * @param string $object Object URL
2042 * @param string $target Target profile
2043 * @param integer $uid User ID
2045 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2046 * @throws \ImagickException
2047 * @throws \Exception
2049 public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2051 $profile = APContact::getByURL($target);
2052 if (empty($profile['inbox'])) {
2053 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2058 // Fetch the list of administrators
2059 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2061 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2062 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2063 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2064 $uid = $first_user['uid'];
2067 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2068 'author-id' => Contact::getPublicIdByUserId($uid)];
2069 if (Post::exists($condition)) {
2070 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2074 $owner = User::getOwnerDataById($uid);
2077 '@context' => ActivityPub::CONTEXT,
2078 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2080 'actor' => $owner['url'],
2081 'object' => $object,
2082 'instrument' => self::getService(),
2083 'to' => [$profile['url']],
2086 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2088 $signed = LDSignature::sign($data, $owner);
2089 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2093 * Transmit a message that the contact request had been accepted
2095 * @param string $target Target profile
2096 * @param string $id Object id
2097 * @param integer $uid User ID
2099 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2100 * @throws \ImagickException
2102 public static function sendContactAccept(string $target, string $id, int $uid)
2104 $profile = APContact::getByURL($target);
2105 if (empty($profile['inbox'])) {
2106 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2110 $owner = User::getOwnerDataById($uid);
2112 '@context' => ActivityPub::CONTEXT,
2113 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2115 'actor' => $owner['url'],
2119 'actor' => $profile['url'],
2120 'object' => $owner['url']
2122 'instrument' => self::getService(),
2123 'to' => [$profile['url']],
2126 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2128 $signed = LDSignature::sign($data, $owner);
2129 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2133 * Reject a contact request or terminates the contact relation
2135 * @param string $target Target profile
2136 * @param string $objectId Object id
2137 * @param int $uid User ID
2138 * @return bool Operation success
2139 * @throws HTTPException\InternalServerErrorException
2140 * @throws \ImagickException
2142 public static function sendContactReject(string $target, string $objectId, int $uid): bool
2144 $profile = APContact::getByURL($target);
2145 if (empty($profile['inbox'])) {
2146 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2150 $owner = User::getOwnerDataById($uid);
2152 '@context' => ActivityPub::CONTEXT,
2153 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2155 'actor' => $owner['url'],
2159 'actor' => $profile['url'],
2160 'object' => $owner['url']
2162 'instrument' => self::getService(),
2163 'to' => [$profile['url']],
2166 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2168 $signed = LDSignature::sign($data, $owner);
2169 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2173 * Transmits a message that we don't want to follow this contact anymore
2175 * @param string $target Target profile
2176 * @param integer $cid Contact id
2177 * @param integer $uid User ID
2178 * @return bool success
2179 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2180 * @throws \ImagickException
2181 * @throws \Exception
2183 public static function sendContactUndo(string $target, int $cid, int $uid): bool
2185 $profile = APContact::getByURL($target);
2186 if (empty($profile['inbox'])) {
2187 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2191 $object_id = self::activityIDFromContact($cid);
2192 if (empty($object_id)) {
2196 $objectId = DI::baseUrl() . '/activity/' . System::createGUID();
2198 $owner = User::getOwnerDataById($uid);
2200 '@context' => ActivityPub::CONTEXT,
2203 'actor' => $owner['url'],
2207 'actor' => $owner['url'],
2208 'object' => $profile['url']
2210 'instrument' => self::getService(),
2211 'to' => [$profile['url']],
2214 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2216 $signed = LDSignature::sign($data, $owner);
2217 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2221 * Prepends mentions (@) to $body variable
2223 * @param string $body HTML code
2225 * @param string $authorLink Author link
2226 * @return string HTML code with prepended mentions
2228 private static function prependMentions(string $body, int $uriid, string $authorLink): string
2232 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2233 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2234 if (!empty($profile['addr'])
2235 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2236 && !strstr($body, $profile['addr'])
2237 && !strstr($body, $tag['url'])
2238 && $tag['url'] !== $authorLink
2240 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2244 $mentions[] = $body;
2246 return implode(' ', $mentions);