3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
25 use Friendica\Content\Feature;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\GServer;
36 use Friendica\Model\Item;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Model\Tag;
40 use Friendica\Model\User;
41 use Friendica\Network\HTTPException;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Protocol\Diaspora;
45 use Friendica\Protocol\Relay;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\HTTPSignature;
48 use Friendica\Util\LDSignature;
49 use Friendica\Util\Map;
50 use Friendica\Util\Network;
51 use Friendica\Util\Strings;
52 use Friendica\Util\XML;
55 * ActivityPub Transmitter Protocol class
62 const CACHEKEY_FEATURED = 'transmitter:getFeatured:';
63 const CACHEKEY_CONTACTS = 'transmitter:getContacts:';
66 * Add relay servers to the list of inboxes
68 * @param array $inboxes
69 * @return array inboxes with added relay servers
71 public static function addRelayServerInboxes(array $inboxes = []): array
73 foreach (Relay::getList(['inbox']) as $contact) {
74 $inboxes[$contact['inbox']] = $contact['inbox'];
81 * Add relay servers to the list of inboxes
83 * @param array $inboxes
84 * @return array inboxes with added relay servers
86 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = []): array
88 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
93 $relays = Relay::getDirectRelayList($item_id);
98 foreach ($relays as $relay) {
99 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
100 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
106 * Subscribe to a relay and updates contact on success
108 * @param string $url Subscribe actor url
109 * @return bool success
111 public static function sendRelayFollow(string $url): bool
113 $contact = Contact::getByURL($url);
114 if (empty($contact)) {
118 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
119 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
121 Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]);
128 * Unsubscribe from a relay and updates contact on success or forced
130 * @param string $url Subscribe actor url
131 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
132 * @return bool success
134 public static function sendRelayUndoFollow(string $url, bool $force = false): bool
136 $contact = Contact::getByURL($url);
137 if (empty($contact)) {
141 $success = self::sendContactUndo($url, $contact['id'], User::getSystemAccount());
143 if ($success || $force) {
144 Contact::update(['rel' => Contact::NOTHING], ['id' => $contact['id']]);
151 * Collects a list of contacts of the given owner
153 * @param array $owner Owner array
154 * @param array $rel The relevant value(s) contact.rel should match
155 * @param string $module The name of the relevant AP endpoint module (followers|following)
156 * @param integer $page Page number
157 * @param string $requester URL of the requester
158 * @param boolean $nocache Wether to bypass caching
159 * @return array of owners
162 public static function getContacts(array $owner, array $rel, string $module, int $page = null, string $requester = null, bool $nocache = false): array
165 $cachekey = self::CACHEKEY_CONTACTS . $module . ':'. $owner['uid'];
166 $result = DI::cache()->get($cachekey);
167 if (!$nocache && !is_null($result)) {
174 'uid' => $owner['uid'],
183 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
185 $total = DBA::count('contact', $condition);
187 $modulePath = '/' . $module . '/';
189 $data = ['@context' => ActivityPub::CONTEXT];
190 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
191 $data['type'] = 'OrderedCollection';
192 $data['totalItems'] = $total;
195 $data['id'] .= '?' . http_build_query(['page' => $page]);
198 // When we hide our friends we will only show the pure number but don't allow more.
199 $show_contacts = empty($owner['hide-friends']);
201 // Allow fetching the contact list when the requester is part of the list.
202 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
203 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
206 if (!$show_contacts) {
207 if (!empty($cachekey)) {
208 DI::cache()->set($cachekey, $data, Duration::DAY);
215 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
217 $data['type'] = 'OrderedCollectionPage';
220 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
221 while ($contact = DBA::fetch($contacts)) {
222 $list[] = $contact['url'];
224 DBA::close($contacts);
226 if (count($list) == 100) {
227 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
230 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
232 $data['orderedItems'] = $list;
235 if (!empty($cachekey)) {
236 DI::cache()->set($cachekey, $data, Duration::DAY);
243 * Public posts for the given owner
245 * @param array $owner Owner array
246 * @param integer $page Page number
247 * @param integer $max_id Maximum ID
248 * @param string $requester URL of requesting account
249 * @param boolean $nocache Wether to bypass caching
250 * @return array of posts
251 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 * @throws \ImagickException
254 public static function getOutbox(array $owner, int $page = null, int $max_id = null, string $requester = ''): array
256 $condition = ['gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT], 'private' => [Item::PUBLIC, Item::UNLISTED]];
258 if (!empty($requester)) {
259 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
260 if (!empty($requester_id)) {
261 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
262 if (!empty($permissionSets)) {
263 $condition = ['psid' => array_merge($permissionSets->column('id'),
264 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
269 $condition = array_merge($condition, [
270 'uid' => $owner['uid'],
271 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
272 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
273 'network' => Protocol::FEDERATED,
274 'parent-network' => Protocol::FEDERATED,
280 $apcontact = APContact::getByURL($owner['url']);
282 return self::getCollection($condition, DI::baseUrl() . '/outbox/' . $owner['nickname'], $page, $max_id, null, $apcontact['statuses_count']);
285 public static function getInbox(int $uid, int $page = null, int $max_id = null)
287 $owner = User::getOwnerDataById($uid);
289 $condition = ['gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT], [Protocol::ACTIVITYPUB, Protocol::DFRN], 'uid' => $uid];
291 return self::getCollection($condition, DI::baseUrl() . '/inbox/' . $owner['nickname'], $page, $max_id, $uid, null);
294 public static function getPublicInbox(int $uid, int $page = null, int $max_id = null)
296 $condition = ['gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT], 'private' => Item::PUBLIC,
297 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN], 'author-blocked' => false, 'author-hidden' => false];
299 return self::getCollection($condition, DI::baseUrl() . '/inbox', $page, $max_id, $uid, null);
302 private static function getCollection(array $condition, string $path, int $page = null, int $max_id = null, int $uid = null, int $total_items = null)
304 $data = ['@context' => ActivityPub::CONTEXT];
306 $data['type'] = 'OrderedCollection';
308 if (!is_null($total_items)) {
309 $data['totalItems'] = $total_items;
313 $data['id'] .= '?' . http_build_query(['page' => $page]);
316 if (empty($page) && empty($max_id)) {
317 $data['first'] = $path . '?page=1';
319 $data['type'] = 'OrderedCollectionPage';
322 if (!empty($max_id)) {
323 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $max_id]);
327 $params = ['limit' => [($page - 1) * 20, 20], 'order' => ['uri-id' => true]];
329 $params = ['limit' => 20, 'order' => ['uri-id' => true]];
332 if (!is_null($uid)) {
333 $items = Post::selectForUser($uid, ['id', 'uri-id'], $condition, $params);
335 $items = Post::select(['id', 'uri-id'], $condition, $params);
339 while ($item = Post::fetch($items)) {
340 $activity = self::createActivityFromItem($item['id'], false, !is_null($uid));
341 if (!empty($activity)) {
343 $last_id = $item['uri-id'];
349 if (count($list) == 20) {
350 $data['next'] = $path . '?max_id=' . $last_id;
353 // Fix the cached total item count when it is lower than the real count
354 if (!is_null($total_items)) {
355 $total = (($page - 1) * 20) + $data['totalItems'];
356 if ($total > $data['totalItems']) {
357 $data['totalItems'] = $total;
361 $data['partOf'] = $path;
363 $data['orderedItems'] = $list;
370 * Public posts for the given owner
372 * @param array $owner Owner array
373 * @param integer $page Page number
374 * @param boolean $nocache Wether to bypass caching
376 * @return array of posts
377 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
378 * @throws \ImagickException
380 public static function getFeatured(array $owner, int $page = null, bool $nocache = false): array
383 $cachekey = self::CACHEKEY_FEATURED . $owner['uid'];
384 $result = DI::cache()->get($cachekey);
385 if (!$nocache && !is_null($result)) {
390 $owner_cid = Contact::getIdForURL($owner['url'], 0, false);
392 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
393 $owner_cid, Post\Collection::FEATURED];
395 $condition = DBA::mergeConditions($condition, [
396 'uid' => $owner['uid'],
397 'author-id' => $owner_cid,
398 'private' => [Item::PUBLIC, Item::UNLISTED],
399 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
400 'network' => Protocol::FEDERATED,
401 'parent-network' => Protocol::FEDERATED,
407 $count = Post::count($condition);
409 $data = ['@context' => ActivityPub::CONTEXT];
410 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
411 $data['type'] = 'OrderedCollection';
412 $data['totalItems'] = $count;
415 $data['id'] .= '?' . http_build_query(['page' => $page]);
419 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
421 $data['type'] = 'OrderedCollectionPage';
422 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
426 while ($item = Post::fetch($items)) {
427 $activity = self::createActivityFromItem($item['id'], true);
428 if (!empty($activity)) {
434 if (count($list) == 20) {
435 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
439 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
442 $data['orderedItems'] = $list;
444 if (!empty($cachekey)) {
445 DI::cache()->set($cachekey, $data, Duration::DAY);
452 * Return the service array containing information the used software and it's url
454 * @return array with service data
456 public static function getService(): array
460 'name' => App::PLATFORM . " '" . App::CODENAME . "' " . App::VERSION . '-' . DB_UPDATE_VERSION,
461 'url' => DI::baseUrl()->get()
466 * Return the ActivityPub profile of the given user
468 * @param int $uid User ID
469 * @return array with profile data
470 * @throws HTTPException\NotFoundException
471 * @throws HTTPException\InternalServerErrorException
473 public static function getProfile(int $uid): array
475 $owner = User::getOwnerDataById($uid);
476 if (!isset($owner['id'])) {
477 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
478 throw new HTTPException\NotFoundException('User not found.');
481 $data = ['@context' => ActivityPub::CONTEXT];
482 $data['id'] = $owner['url'];
484 if (!empty($owner['guid'])) {
485 $data['diaspora:guid'] = $owner['guid'];
488 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
491 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
492 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
493 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
494 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
495 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
497 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
500 $data['preferredUsername'] = $owner['nick'];
501 $data['name'] = $owner['name'];
503 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
504 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
505 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
508 if (!empty($owner['about'])) {
509 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
512 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
513 $data['vcard:hasInstantMessage'] = [];
515 if (!empty($owner['xmpp'])) {
516 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
518 if (!empty($owner['matrix'])) {
519 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
523 $data['url'] = $owner['url'];
524 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
525 $data['discoverable'] = (bool)$owner['net-publish'];
526 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
527 'owner' => $owner['url'],
528 'publicKeyPem' => $owner['pubkey']];
529 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
530 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
532 $resourceid = Photo::ridFromURI($owner['photo']);
533 if (!empty($resourceid)) {
534 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
535 if (!empty($photo['type'])) {
536 $data['icon']['mediaType'] = $photo['type'];
540 if (!empty($owner['header'])) {
541 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
543 $resourceid = Photo::ridFromURI($owner['header']);
544 if (!empty($resourceid)) {
545 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
546 if (!empty($photo['type'])) {
547 $data['image']['mediaType'] = $photo['type'];
554 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
556 'type' => 'PropertyValue',
557 'name' => $profile_field->label,
558 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
562 if (!empty($custom_fields)) {
563 $data['attachment'] = $custom_fields;
566 $data['generator'] = self::getService();
568 // tags: https://kitty.town/@inmysocks/100656097926961126.json
573 * @param string $username
575 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
577 public static function getDeletedUser(string $username): array
580 '@context' => ActivityPub::CONTEXT,
581 'id' => DI::baseUrl() . '/profile/' . $username,
582 'type' => 'Tombstone',
583 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
584 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
585 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
590 * Returns an array with permissions of the thread parent of the given item array
593 * @param bool $is_forum_thread
595 * @return array with permissions
596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
597 * @throws \ImagickException
599 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread): array
601 if (empty($item['thr-parent-id'])) {
605 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
606 if (empty($parent)) {
611 'to' => [$parent['author-link']],
617 $parent_profile = APContact::getByURL($parent['author-link']);
619 $item_profile = APContact::getByURL($item['author-link']);
620 $exclude[] = $item['author-link'];
622 if ($item['gravity'] == Item::GRAVITY_PARENT) {
623 $exclude[] = $item['owner-link'];
626 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
627 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
628 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
629 if (!$is_forum_thread) {
630 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
632 } elseif (!in_array($receiver['url'], $exclude)) {
633 $permissions[$type[$receiver['type']]][] = $receiver['url'];
641 * Check if the given item id is from ActivityPub
643 * @param integer $item_id
644 * @return boolean "true" if the post is from ActivityPub
646 private static function isAPPost(int $item_id): bool
648 if (empty($item_id)) {
652 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
656 * Creates an array of permissions from an item thread
658 * @param array $item Item array
659 * @param boolean $blindcopy addressing via "bcc" or "cc"?
660 * @param integer $last_id Last item id for adding receivers
662 * @return array with permission data
663 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
664 * @throws \ImagickException
666 private static function createPermissionBlockForItem(array $item, bool $blindcopy, int $last_id = 0): array
669 $last_id = $item['id'];
676 // Check if we should always deliver our stuff via BCC
677 if (!empty($item['uid'])) {
678 $owner = User::getOwnerDataById($item['uid']);
679 if (!empty($owner)) {
680 $always_bcc = $owner['hide-friends'];
681 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
683 $profile = APContact::getByURL($owner['url'], false);
684 $follower = $profile['followers'] ?? '';
688 if (DI::config()->get('system', 'ap_always_bcc')) {
692 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
693 if (!empty($parent) && ($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
694 $profile = APContact::getByURL($parent['causer-link'], false);
695 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
697 $is_forum_thread = false;
700 if (self::isAnnounce($item) || self::isAPPost($last_id)) {
701 // Will be activated in a later step
702 $networks = Protocol::FEDERATED;
704 // For now only send to these contacts:
705 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
708 $data = ['to' => [], 'cc' => [], 'bcc' => []];
710 if ($item['gravity'] == Item::GRAVITY_PARENT) {
711 $actor_profile = APContact::getByURL($item['owner-link']);
713 $actor_profile = APContact::getByURL($item['author-link']);
719 if ($is_forum_thread) {
720 foreach (Tag::getByURIId($item['parent-uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $term) {
721 $profile = APContact::getByURL($term['url'], false);
722 if (!empty($profile) && ($profile['type'] == 'Group')) {
723 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
725 } elseif ($term['type'] == Tag::MENTION) {
732 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
734 if ($item['private'] != Item::PRIVATE) {
735 // Directly mention the original author upon a quoted reshare.
736 // Else just ensure that the original author receives the reshare.
737 $announce = self::getAnnounceArray($item);
738 if (!empty($announce['comment'])) {
739 $data['to'][] = $announce['actor']['url'];
740 } elseif (!empty($announce)) {
741 $data['cc'][] = $announce['actor']['url'];
744 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
746 // Check if the item is completely public or unlisted
747 if ($item['private'] == Item::PUBLIC) {
748 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
750 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
753 foreach ($terms as $term) {
754 $profile = APContact::getByURL($term['url'], false);
755 if (!empty($profile)) {
756 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
758 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
759 $data['cc'][] = $profile['followers'];
761 } elseif (($term['type'] == Tag::MENTION) && ($profile['type'] == 'Group')) {
764 $data['to'][] = $profile['url'];
768 $receiver_list = Item::enumeratePermissions($item, true);
770 foreach ($terms as $term) {
771 $cid = Contact::getIdForURL($term['url'], $item['uid']);
772 if (!empty($cid) && in_array($cid, $receiver_list)) {
773 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
774 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
778 $profile = APContact::getByURL($term['url'], false);
779 if (!empty($profile)) {
780 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
782 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
783 $data['cc'][] = $profile['followers'];
785 } elseif (($term['type'] == Tag::MENTION) && ($profile['type'] == 'Group')) {
788 $data['to'][] = $profile['url'];
797 if ($is_forum && !$exclusive && !empty($follower)) {
798 $data['cc'][] = $follower;
799 } elseif (!$exclusive) {
800 foreach ($receiver_list as $receiver) {
801 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
802 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
806 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
807 if ($contact['hidden'] || $always_bcc) {
808 $data['bcc'][] = $profile['url'];
810 $data['cc'][] = $profile['url'];
817 if (!empty($item['parent'])) {
818 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']], ['order' => ['id']]);
819 while ($parent = Post::fetch($parents)) {
820 if ($parent['gravity'] == Item::GRAVITY_PARENT) {
821 $profile = APContact::getByURL($parent['owner-link'], false);
822 if (!empty($profile)) {
823 if ($item['gravity'] != Item::GRAVITY_PARENT) {
824 // Comments to forums are directed to the forum
825 // But comments to forums aren't directed to the followers collection
826 // This rule is only valid when the actor isn't the forum.
827 // The forum needs to transmit their content to their followers.
828 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
829 $data['to'][] = $profile['url'];
831 $data['cc'][] = $profile['url'];
832 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers']) && (!$exclusive || !$is_forum_thread)) {
833 $data['cc'][] = $actor_profile['followers'];
836 } elseif (!$exclusive && !$is_forum_thread) {
837 // Public thread parent post always are directed to the followers.
838 if ($item['private'] != Item::PRIVATE) {
839 $data['cc'][] = $actor_profile['followers'];
845 // Don't include data from future posts
846 if ($parent['id'] >= $last_id) {
850 $profile = APContact::getByURL($parent['author-link'], false);
851 if (!empty($profile)) {
852 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
853 $data['to'][] = $profile['url'];
855 $data['cc'][] = $profile['url'];
859 DBA::close($parents);
862 $data['to'] = array_unique($data['to']);
863 $data['cc'] = array_unique($data['cc']);
864 $data['bcc'] = array_unique($data['bcc']);
866 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
867 unset($data['to'][$key]);
870 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
871 unset($data['cc'][$key]);
874 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
875 unset($data['bcc'][$key]);
878 foreach ($data['to'] as $to) {
879 if (($key = array_search($to, $data['cc'])) !== false) {
880 unset($data['cc'][$key]);
883 if (($key = array_search($to, $data['bcc'])) !== false) {
884 unset($data['bcc'][$key]);
888 foreach ($data['cc'] as $cc) {
889 if (($key = array_search($cc, $data['bcc'])) !== false) {
890 unset($data['bcc'][$key]);
894 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
897 unset($receivers['bcc']);
900 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
901 if (!empty($receivers[$element])) {
902 foreach ($receivers[$element] as $receiver) {
903 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
904 $name = Receiver::PUBLIC_COLLECTION;
906 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
908 Tag::store($item['uri-id'], $type, $name, $receiver);
917 * Check if an inbox is archived
919 * @param string $url Inbox url
920 * @return boolean "true" if inbox is archived
922 public static function archivedInbox(string $url): bool
924 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
928 * Check if a given contact should be delivered via AP
930 * @param array $contact Contact array
931 * @param array $networks Array with networks
932 * @return bool Whether the used protocol matches ACTIVITYPUB
935 private static function isAPContact(array $contact, array $networks): bool
937 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
941 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
945 * Fetches a list of inboxes of followers of a given user
947 * @param integer $uid User ID
948 * @param boolean $personal fetch personal inboxes
949 * @param boolean $all_ap Retrieve all AP enabled inboxes
950 * @return array of follower inboxes
951 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
952 * @throws \ImagickException
954 public static function fetchTargetInboxesforUser(int $uid, bool $personal = false, bool $all_ap = false): array
960 if (!empty($item['uid'])) {
961 $profile = User::getOwnerDataById($item['uid']);
962 if (!empty($profile)) {
963 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
968 // Will be activated in a later step
969 $networks = Protocol::FEDERATED;
971 // For now only send to these contacts:
972 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
980 'network' => Protocol::FEDERATED,
984 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
987 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
988 while ($contact = DBA::fetch($contacts)) {
989 if (!self::isAPContact($contact, $networks)) {
993 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
997 if (Network::isUrlBlocked($contact['url'])) {
1001 $profile = APContact::getByURL($contact['url'], false);
1002 if (!empty($profile)) {
1003 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
1004 $target = $profile['inbox'];
1006 $target = $profile['sharedinbox'];
1008 if (!self::archivedInbox($target)) {
1009 $inboxes[$target][] = $contact['id'];
1013 DBA::close($contacts);
1019 * Fetches an array of inboxes for the given item and user
1021 * @param array $item Item array
1022 * @param integer $uid User ID
1023 * @param boolean $personal fetch personal inboxes
1024 * @param integer $last_id Last item id for adding receivers
1025 * @return array with inboxes
1026 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1027 * @throws \ImagickException
1029 public static function fetchTargetInboxes(array $item, int $uid, bool $personal = false, int $last_id = 0): array
1031 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
1032 if (empty($permissions)) {
1038 if ($item['gravity'] == Item::GRAVITY_ACTIVITY) {
1039 $item_profile = APContact::getByURL($item['author-link'], false);
1041 $item_profile = APContact::getByURL($item['owner-link'], false);
1044 if (empty($item_profile)) {
1048 $profile_uid = User::getIdForURL($item_profile['url']);
1050 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
1051 if (empty($permissions[$element])) {
1055 $blindcopy = in_array($element, ['bto', 'bcc']);
1057 foreach ($permissions[$element] as $receiver) {
1058 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
1062 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
1063 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
1065 $profile = APContact::getByURL($receiver, false);
1066 if (!empty($profile)) {
1067 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
1069 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
1070 $target = $profile['inbox'];
1072 $target = $profile['sharedinbox'];
1074 if (!self::archivedInbox($target)) {
1075 $inboxes[$target][] = $contact['id'] ?? 0;
1086 * Creates an array in the structure of the item table for a given mail id
1088 * @param integer $mail_id Mail id
1090 * @throws \Exception
1092 public static function getItemArrayFromMail(int $mail_id, bool $use_title = false): array
1094 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
1095 if (!DBA::isResult($mail)) {
1099 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
1100 if (!DBA::isResult($reply)) {
1104 // Making the post more compatible for Mastodon by:
1105 // - Making it a note and not an article (no title)
1106 // - Moving the title into the "summary" field that is used as a "content warning"
1109 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1110 $mail['title'] = '';
1113 $mail['content-warning'] = '';
1114 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1115 $mail['owner-id'] = $mail['author-id'];
1116 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1117 $mail['allow_gid'] = '';
1118 $mail['deny_cid'] = '';
1119 $mail['deny_gid'] = '';
1120 $mail['private'] = Item::PRIVATE;
1121 $mail['deleted'] = false;
1122 $mail['edited'] = $mail['created'];
1123 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1124 $mail['parent-uri'] = $reply['uri'];
1125 $mail['parent-uri-id'] = $reply['uri-id'];
1126 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1127 $mail['gravity'] = ($mail['reply'] ? Item::GRAVITY_COMMENT: Item::GRAVITY_PARENT);
1128 $mail['event-type'] = '';
1129 $mail['language'] = '';
1130 $mail['parent'] = 0;
1136 * Creates an activity array for a given mail id
1138 * @param integer $mail_id
1139 * @param boolean $object_mode Is the activity item is used inside another object?
1141 * @return array of activity
1142 * @throws \Exception
1144 public static function createActivityFromMail(int $mail_id, bool $object_mode = false): array
1146 $mail = self::getItemArrayFromMail($mail_id);
1150 $object = self::createNote($mail);
1152 if (!$object_mode) {
1153 $data = ['@context' => ActivityPub::CONTEXT];
1158 $data['id'] = $mail['uri'] . '/Create';
1159 $data['type'] = 'Create';
1160 $data['actor'] = $mail['author-link'];
1161 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1162 $data['instrument'] = self::getService();
1163 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1165 if (empty($data['to']) && !empty($data['cc'])) {
1166 $data['to'] = $data['cc'];
1169 if (empty($data['to']) && !empty($data['bcc'])) {
1170 $data['to'] = $data['bcc'];
1174 unset($data['bcc']);
1176 $object['to'] = $data['to'];
1177 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1179 unset($object['cc']);
1180 unset($object['bcc']);
1182 $data['directMessage'] = true;
1184 $data['object'] = $object;
1186 $owner = User::getOwnerDataById($mail['uid']);
1188 if (!$object_mode && !empty($owner)) {
1189 return LDSignature::sign($data, $owner);
1196 * Returns the activity type of a given item
1198 * @param array $item Item array
1199 * @return string with activity type
1200 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1201 * @throws \ImagickException
1203 private static function getTypeOfItem(array $item): string
1207 // Only check for a reshare, if it is a real reshare and no quoted reshare
1208 if (strpos($item['body'], '[share') === 0) {
1209 $announce = self::getAnnounceArray($item);
1210 $reshared = !empty($announce);
1215 } elseif ($item['verb'] == Activity::POST) {
1216 if ($item['created'] == $item['edited']) {
1221 } elseif ($item['verb'] == Activity::LIKE) {
1223 } elseif ($item['verb'] == Activity::DISLIKE) {
1225 } elseif ($item['verb'] == Activity::ATTEND) {
1227 } elseif ($item['verb'] == Activity::ATTENDNO) {
1229 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1230 $type = 'TentativeAccept';
1231 } elseif ($item['verb'] == Activity::FOLLOW) {
1233 } elseif ($item['verb'] == Activity::TAG) {
1235 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1245 * Creates the activity or fetches it from the cache
1247 * @param integer $item_id Item id
1248 * @param boolean $force Force new cache entry
1249 * @return array|false activity or false on failure
1250 * @throws \Exception
1252 public static function createCachedActivityFromItem(int $item_id, bool $force = false, bool $object_mode = false)
1254 $cachekey = 'APDelivery:createActivity:' . $item_id . ':' . (int)$object_mode;
1257 $data = DI::cache()->get($cachekey);
1258 if (!is_null($data)) {
1263 $data = self::createActivityFromItem($item_id, $object_mode);
1265 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1270 * Creates an activity array for a given item id
1272 * @param integer $item_id
1273 * @param boolean $object_mode Is the activity item is used inside another object?
1274 * @param boolean $api_mode "true" if used for the API
1275 * @return false|array
1276 * @throws \Exception
1278 public static function createActivityFromItem(int $item_id, bool $object_mode = false, $api_mode = false)
1280 $condition = ['id' => $item_id];
1282 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
1284 Logger::info('Fetching activity', $condition);
1285 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition);
1286 if (!DBA::isResult($item)) {
1289 return self::createActivityFromArray($item, $object_mode, $api_mode);
1293 * Creates an activity array for a given URI-Id and uid
1295 * @param integer $uri_id
1296 * @param integer $uid
1297 * @param boolean $object_mode Is the activity item is used inside another object?
1298 * @param boolean $api_mode "true" if used for the API
1299 * @return false|array
1300 * @throws \Exception
1302 public static function createActivityFromUriId(int $uri_id, int $uid, bool $object_mode = false, $api_mode = false)
1304 $condition = ['uri-id' => $uri_id, 'uid' => [0, $uid]];
1306 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
1308 Logger::info('Fetching activity', $condition);
1309 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition, ['order' => ['uid' => true]]);
1310 if (!DBA::isResult($item)) {
1314 return self::createActivityFromArray($item, $object_mode, $api_mode);
1318 * Creates an activity array for a given item id
1320 * @param integer $item_id
1321 * @param boolean $object_mode Is the activity item is used inside another object?
1322 * @param boolean $api_mode "true" if used for the API
1323 * @return false|array
1324 * @throws \Exception
1326 private static function createActivityFromArray(array $item, bool $object_mode = false, $api_mode = false)
1328 if (!$item['deleted'] && $item['network'] == Protocol::ACTIVITYPUB) {
1329 $data = Post\Activity::getByURIId($item['uri-id']);
1330 if (!$item['origin'] && !empty($data)) {
1331 if (!$object_mode) {
1332 Logger::info('Return stored conversation', ['item' => $item['id']]);
1334 } elseif (!empty($data['object'])) {
1335 Logger::info('Return stored conversation object', ['item' => $item['id']]);
1336 return $data['object'];
1341 if (!$api_mode && !$item['origin']) {
1342 Logger::debug('Post is not ours and is not stored', ['id' => $item['id'], 'uri-id' => $item['uri-id']]);
1346 $type = self::getTypeOfItem($item);
1348 if (!$object_mode) {
1349 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1351 if ($item['deleted'] && ($item['gravity'] == Item::GRAVITY_ACTIVITY)) {
1353 } elseif ($item['deleted']) {
1360 if ($type == 'Delete') {
1361 $data['id'] = Item::newURI($item['guid']) . '/' . $type;;
1362 } elseif (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1363 $data['id'] = $item['uri'];
1365 $data['id'] = $item['uri'] . '/' . $type;
1368 $data['type'] = $type;
1370 if (($type != 'Announce') || ($item['gravity'] != Item::GRAVITY_PARENT)) {
1371 $data['actor'] = $item['author-link'];
1373 $data['actor'] = $item['owner-link'];
1376 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1378 $data['instrument'] = self::getService();
1380 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1382 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1383 $data['object'] = self::createNote($item);
1384 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1385 } elseif ($data['type'] == 'Add') {
1386 $data = self::createAddTag($item, $data);
1387 } elseif ($data['type'] == 'Announce') {
1388 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1389 $data['object'] = $item['thr-parent'];
1391 $data = self::createAnnounce($item, $data);
1393 } elseif ($data['type'] == 'Follow') {
1394 $data['object'] = $item['parent-uri'];
1395 } elseif ($data['type'] == 'Undo') {
1396 $data['object'] = self::createActivityFromItem($item['id'], true);
1398 $data['diaspora:guid'] = $item['guid'];
1399 if (!empty($item['signed_text'])) {
1400 $data['diaspora:like'] = $item['signed_text'];
1402 $data['object'] = $item['thr-parent'];
1405 if (!empty($item['contact-uid'])) {
1406 $uid = $item['contact-uid'];
1408 $uid = $item['uid'];
1411 Logger::info('Fetched activity', ['item' => $item['id'], 'uid' => $uid]);
1413 // We only sign our own activities
1414 if (!$api_mode && !$object_mode && $item['origin']) {
1415 $owner = User::getOwnerDataById($uid);
1416 return LDSignature::sign($data, $owner);
1421 /// @todo Create "conversation" entry
1425 * Creates a location entry for a given item array
1427 * @param array $item Item array
1428 * @return array with location array
1430 private static function createLocation(array $item): array
1432 $location = ['type' => 'Place'];
1434 if (!empty($item['location'])) {
1435 $location['name'] = $item['location'];
1440 if (empty($item['coord'])) {
1441 $coord = Map::getCoordinates($item['location']);
1443 $coords = explode(' ', $item['coord']);
1444 if (count($coords) == 2) {
1445 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1449 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1450 $location['latitude'] = $coord['lat'];
1451 $location['longitude'] = $coord['lon'];
1458 * Returns a tag array for a given item array
1460 * @param array $item Item array
1461 * @param string $quote_url Url of the attached quote link
1462 * @return array of tags
1463 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1465 private static function createTagList(array $item, string $quote_url): array
1469 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1470 foreach ($terms as $term) {
1471 if ($term['type'] == Tag::HASHTAG) {
1472 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1473 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1475 $contact = Contact::getByURL($term['url'], false, ['addr']);
1476 if (empty($contact)) {
1479 if (!empty($contact['addr'])) {
1480 $mention = '@' . $contact['addr'];
1482 $mention = '@' . $term['url'];
1485 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1489 $announce = self::getAnnounceArray($item);
1490 // Mention the original author upon commented reshares
1491 if (!empty($announce['comment'])) {
1492 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1495 // @see https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-e232.md
1496 if (!empty($quote_url)) {
1497 // Currently deactivated because of compatibility issues with Pleroma
1499 // 'type' => 'Link',
1500 // 'mediaType' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
1501 // 'href' => $quote_url,
1502 // 'name' => '♲ ' . BBCode::convertForUriId($item['uri-id'], $quote_url, BBCode::ACTIVITYPUB)
1510 * Adds attachment data to the JSON document
1512 * @param array $item Data of the item that is to be posted
1514 * @return array with attachment data
1515 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1517 private static function createAttachmentList(array $item): array
1522 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1523 if (in_array($attachment['url'], $urls)) {
1526 $urls[] = $attachment['url'];
1528 $attach = ['type' => 'Document',
1529 'mediaType' => $attachment['mimetype'],
1530 'url' => $attachment['url'],
1531 'name' => $attachment['description']];
1533 if (!empty($attachment['height'])) {
1534 $attach['height'] = $attachment['height'];
1537 if (!empty($attachment['width'])) {
1538 $attach['width'] = $attachment['width'];
1541 if (!empty($attachment['preview'])) {
1542 $attach['image'] = $attachment['preview'];
1545 $attachments[] = $attach;
1548 return $attachments;
1552 * Callback function to replace a Friendica style mention in a mention for a summary
1554 * @param array $match Matching values for the callback
1555 * @return string Replaced mention
1556 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1558 private static function mentionAddrCallback(array $match): string
1560 if (empty($match[1])) {
1564 $data = Contact::getByURL($match[1], false, ['addr']);
1565 if (empty($data['addr'])) {
1569 return '@' . $data['addr'];
1573 * Remove image elements since they are added as attachment
1575 * @param string $body HTML code
1576 * @return string with removed images
1578 private static function removePictures(string $body): string
1580 return BBCode::performWithEscapedTags($body, ['code', 'noparse', 'nobb', 'pre'], function ($text) {
1581 // Simplify image codes
1582 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1583 $text = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $text);
1585 // Now remove local links
1586 $text = preg_replace_callback(
1587 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1589 // We remove the link when it is a link to a local photo page
1590 if (Photo::isLocalPage($match[1])) {
1593 // otherwise we just return the link
1594 return '[url]' . $match[1] . '[/url]';
1599 // Remove all pictures
1600 return preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $text);
1605 * Returns if the post contains sensitive content ("nsfw")
1607 * @param integer $uri_id URI id
1608 * @return boolean Whether URI id was found
1609 * @throws \Exception
1611 private static function isSensitive(int $uri_id): bool
1613 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1617 * Creates event data
1619 * @param array $item Item array
1620 * @return array with the event data
1621 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1623 private static function createEvent(array $item): array
1626 $event['name'] = $item['event-summary'];
1627 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1628 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1630 if (!$item['event-nofinish']) {
1631 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1634 if (!empty($item['event-location'])) {
1635 $item['location'] = $item['event-location'];
1636 $event['location'] = self::createLocation($item);
1639 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1640 $event['dfrn:adjust'] = true;
1646 * Creates a note/article object array
1648 * @param array $item
1649 * @return array with the object data
1650 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1651 * @throws \ImagickException
1653 public static function createNote(array $item): array
1659 // We are treating posts differently when they are directed to a community.
1660 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1661 // But to not risk compatibility issues we currently perform the changes only for communities.
1662 if ($item['gravity'] == Item::GRAVITY_PARENT) {
1663 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1664 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1665 if ($isCommunityPost && (count($links) == 1)) {
1666 $link = $links[0]['url'];
1669 $isCommunityPost = false;
1672 if ($item['event-type'] == 'event') {
1674 } elseif (!empty($item['title'])) {
1675 if (!$isCommunityPost || empty($link)) {
1678 // "Page" is used by Lemmy for posts that contain an external link
1685 if ($item['deleted']) {
1686 $type = 'Tombstone';
1690 $data['id'] = $item['uri'];
1691 $data['type'] = $type;
1693 if ($item['deleted']) {
1697 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1699 if ($item['uri'] != $item['thr-parent']) {
1700 $data['inReplyTo'] = $item['thr-parent'];
1702 $data['inReplyTo'] = null;
1705 $data['diaspora:guid'] = $item['guid'];
1706 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1708 if ($item['created'] != $item['edited']) {
1709 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1712 $data['url'] = $link ?? $item['plink'];
1713 $data['attributedTo'] = $item['author-link'];
1714 $data['sensitive'] = self::isSensitive($item['uri-id']);
1716 if (!empty($item['conversation']) && ($item['conversation'] != './')) {
1717 $data['conversation'] = $data['context'] = $item['conversation'];
1720 if (!empty($item['title'])) {
1721 $data['name'] = BBCode::toPlaintext($item['title'], false);
1724 $permission_block = self::createPermissionBlockForItem($item, false);
1726 $real_quote = false;
1728 $body = $item['body'];
1730 if ($type == 'Note') {
1731 $body = $item['raw-body'] ?? self::removePictures($body);
1735 * @todo Improve the automated summary
1736 * This part is currently deactivated. The automated summary seems to be more
1737 * confusing than helping. But possibly we will find a better way.
1738 * So the code is left here for now as a reminder
1740 * } elseif (($type == 'Article') && empty($data['summary'])) {
1741 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1742 * $summary = preg_replace_callback($regexp, [self::class, 'mentionAddrCallback'], $body);
1743 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1747 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1748 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1751 if ($type == 'Event') {
1752 $data = array_merge($data, self::createEvent($item));
1754 if ($isCommunityPost) {
1755 // For community posts we remove the visible "!user@domain.tld".
1756 // This improves the look at systems like Lemmy.
1757 // Also in the future we should control the community delivery via other methods.
1758 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1761 if ($type == 'Page') {
1762 // When we transmit "Page" posts we have to remove the attachment.
1763 // The attachment contains the link that we already transmit in the "url" field.
1764 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1767 $body = BBCode::setMentionsToNicknames($body);
1769 if (!empty($item['quote-uri-id'])) {
1770 if (Post::exists(['uri-id' => $item['quote-uri-id'], 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN]])) {
1772 $data['quoteUrl'] = $item['quote-uri'];
1773 $body = DI::contentItem()->addShareLink($body, $item['quote-uri-id']);
1775 $body = DI::contentItem()->addSharedPost($item, $body);
1779 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1782 // The regular "content" field does contain a minimized HTML. This is done since systems like
1783 // Mastodon has got problems with - for example - embedded pictures.
1784 // The contentMap does contain the unmodified HTML.
1785 $language = self::getLanguage($item);
1786 if (!empty($language)) {
1787 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1788 $richbody = Post\Media::removeFromEndOfBody($richbody);
1789 if (!empty($item['quote-uri-id'])) {
1791 $richbody = DI::contentItem()->addShareLink($richbody, $item['quote-uri-id']);
1793 $richbody = DI::contentItem()->addSharedPost($item, $richbody);
1796 $richbody = BBCode::removeAttachment($richbody);
1798 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1801 if (!empty($item['quote-uri-id'])) {
1802 $source = DI::contentItem()->addSharedPost($item, $item['body']);
1804 $source = $item['body'];
1807 $data['source'] = ['content' => $source, 'mediaType' => "text/bbcode"];
1809 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1810 $data['diaspora:comment'] = $item['signed_text'];
1813 $data['attachment'] = self::createAttachmentList($item);
1814 $data['tag'] = self::createTagList($item, $data['quoteUrl'] ?? '');
1816 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1817 $data['location'] = self::createLocation($item);
1820 if (!empty($item['app'])) {
1821 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1824 $data = array_merge($data, $permission_block);
1830 * Fetches the language from the post, the user or the system.
1832 * @param array $item
1833 * @return string language string
1835 private static function getLanguage(array $item): string
1837 // Try to fetch the language from the post itself
1838 if (!empty($item['language'])) {
1839 $languages = array_keys(json_decode($item['language'], true));
1840 if (!empty($languages[0])) {
1841 return $languages[0];
1845 // Otherwise use the user's language
1846 if (!empty($item['uid'])) {
1847 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1848 if (!empty($user['language'])) {
1849 return $user['language'];
1853 // And finally just use the system language
1854 return DI::config()->get('system', 'language');
1858 * Creates an an "add tag" entry
1860 * @param array $item Item array
1861 * @param array $activity activity data
1862 * @return array with activity data for adding tags
1863 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1864 * @throws \ImagickException
1866 private static function createAddTag(array $item, array $activity): array
1868 $object = XML::parseString($item['object']);
1869 $target = XML::parseString($item['target']);
1871 $activity['diaspora:guid'] = $item['guid'];
1872 $activity['actor'] = $item['author-link'];
1873 $activity['target'] = (string)$target->id;
1874 $activity['summary'] = BBCode::toPlaintext($item['body']);
1875 $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1881 * Creates an announce object entry
1883 * @param array $item Item array
1884 * @param array $activity activity data
1885 * @return array with activity data
1886 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1887 * @throws \ImagickException
1889 private static function createAnnounce(array $item, array $activity): array
1891 $orig_body = $item['body'];
1892 $announce = self::getAnnounceArray($item);
1893 if (empty($announce)) {
1894 $activity['type'] = 'Create';
1895 $activity['object'] = self::createNote($item);
1899 if (empty($announce['comment'])) {
1900 // Pure announce, without a quote
1901 $activity['type'] = 'Announce';
1902 $activity['object'] = $announce['object']['uri'];
1907 $activity['type'] = 'Create';
1908 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1909 $activity['object'] = self::createNote($item);
1911 /// @todo Finally descide how to implement this in AP. This is a possible way:
1912 $activity['object']['attachment'][] = self::createNote($announce['object']);
1914 $activity['object']['source']['content'] = $orig_body;
1919 * Return announce related data if the item is an annunce
1921 * @param array $item
1922 * @return array Announcement array
1924 private static function getAnnounceArray(array $item): array
1926 $reshared = DI::contentItem()->getSharedPost($item, Item::DELIVER_FIELDLIST);
1927 if (empty($reshared)) {
1931 if (!in_array($reshared['post']['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1935 $profile = APContact::getByURL($reshared['post']['author-link'], false);
1936 if (empty($profile)) {
1940 return ['object' => $reshared['post'], 'actor' => $profile, 'comment' => $reshared['comment']];
1944 * Checks if the provided item array is an announce
1946 * @param array $item Item array
1947 * @return boolean Whether item is an announcement
1949 public static function isAnnounce(array $item): bool
1951 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1955 $announce = self::getAnnounceArray($item);
1956 if (empty($announce)) {
1960 return empty($announce['comment']);
1964 * Creates an activity id for a given contact id
1966 * @param integer $cid Contact ID of target
1968 * @return bool|string activity id
1970 public static function activityIDFromContact(int $cid)
1972 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1973 if (!DBA::isResult($contact)) {
1977 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1978 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1979 return DI::baseUrl() . '/activity/' . $uuid;
1983 * Transmits a contact suggestion to a given inbox
1985 * @param array $owner Sender owner-view record
1986 * @param string $inbox Target inbox
1987 * @param integer $suggestion_id Suggestion ID
1988 * @return boolean was the transmission successful?
1989 * @throws \Exception
1991 public static function sendContactSuggestion(array $owner, string $inbox, int $suggestion_id): bool
1993 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1996 '@context' => ActivityPub::CONTEXT,
1997 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1998 'type' => 'Announce',
1999 'actor' => $owner['url'],
2000 'object' => $suggestion->url,
2001 'content' => $suggestion->note,
2002 'instrument' => self::getService(),
2003 'to' => [ActivityPub::PUBLIC_COLLECTION],
2007 $signed = LDSignature::sign($data, $owner);
2009 Logger::info('Deliver profile deletion for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2010 return HTTPSignature::transmit($signed, $inbox, $owner);
2014 * Transmits a profile relocation to a given inbox
2016 * @param array $owner Sender owner-view record
2017 * @param string $inbox Target inbox
2018 * @return boolean was the transmission successful?
2019 * @throws \Exception
2021 public static function sendProfileRelocation(array $owner, string $inbox): bool
2024 '@context' => ActivityPub::CONTEXT,
2025 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2026 'type' => 'dfrn:relocate',
2027 'actor' => $owner['url'],
2028 'object' => $owner['url'],
2029 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2030 'instrument' => self::getService(),
2031 'to' => [ActivityPub::PUBLIC_COLLECTION],
2035 $signed = LDSignature::sign($data, $owner);
2037 Logger::info('Deliver profile relocation for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2038 return HTTPSignature::transmit($signed, $inbox, $owner);
2042 * Transmits a profile deletion to a given inbox
2044 * @param array $owner Sender owner-view record
2045 * @param string $inbox Target inbox
2046 * @return boolean was the transmission successful?
2047 * @throws \Exception
2049 public static function sendProfileDeletion(array $owner, string $inbox): bool
2051 if (empty($owner['uprvkey'])) {
2052 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $owner['uid']]);
2056 $data = ['@context' => ActivityPub::CONTEXT,
2057 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2059 'actor' => $owner['url'],
2060 'object' => $owner['url'],
2061 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2062 'instrument' => self::getService(),
2063 'to' => [ActivityPub::PUBLIC_COLLECTION],
2066 $signed = LDSignature::sign($data, $owner);
2068 Logger::info('Deliver profile deletion for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2069 return HTTPSignature::transmit($signed, $inbox, $owner);
2073 * Transmits a profile change to a given inbox
2075 * @param array $owner Sender owner-view record
2076 * @param string $inbox Target inbox
2077 * @return boolean was the transmission successful?
2078 * @throws HTTPException\InternalServerErrorException
2079 * @throws HTTPException\NotFoundException
2080 * @throws \ImagickException
2082 public static function sendProfileUpdate(array $owner, string $inbox): bool
2084 $profile = APContact::getByURL($owner['url']);
2086 $data = ['@context' => ActivityPub::CONTEXT,
2087 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2089 'actor' => $owner['url'],
2090 'object' => self::getProfile($owner['uid']),
2091 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2092 'instrument' => self::getService(),
2093 'to' => [$profile['followers']],
2096 $signed = LDSignature::sign($data, $owner);
2098 Logger::info('Deliver profile update for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2099 return HTTPSignature::transmit($signed, $inbox, $owner);
2103 * Transmits a given activity to a target
2105 * @param string $activity Type name
2106 * @param string $target Target profile
2107 * @param integer $uid User ID
2108 * @param string $id Activity-identifier
2110 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2111 * @throws \ImagickException
2112 * @throws \Exception
2114 public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2116 $profile = APContact::getByURL($target);
2117 if (empty($profile['inbox'])) {
2118 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2122 $owner = User::getOwnerDataById($uid);
2123 if (empty($owner)) {
2124 Logger::warning('No user found for actor, aborting', ['uid' => $uid]);
2129 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2133 '@context' => ActivityPub::CONTEXT,
2135 'type' => $activity,
2136 'actor' => $owner['url'],
2137 'object' => $profile['url'],
2138 'instrument' => self::getService(),
2139 'to' => [$profile['url']],
2142 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2144 $signed = LDSignature::sign($data, $owner);
2145 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2149 * Transmits a "follow object" activity to a target
2150 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2152 * @param string $object Object URL
2153 * @param string $target Target profile
2154 * @param integer $uid User ID
2156 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2157 * @throws \ImagickException
2158 * @throws \Exception
2160 public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2162 $profile = APContact::getByURL($target);
2163 if (empty($profile['inbox'])) {
2164 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2169 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2170 $admin = User::getFirstAdmin(['uid']);
2172 Logger::warning('No available admin user for transmission', ['target' => $target]);
2176 $uid = $admin['uid'];
2179 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2180 'author-id' => Contact::getPublicIdByUserId($uid)];
2181 if (Post::exists($condition)) {
2182 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2186 $owner = User::getOwnerDataById($uid);
2189 '@context' => ActivityPub::CONTEXT,
2190 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2192 'actor' => $owner['url'],
2193 'object' => $object,
2194 'instrument' => self::getService(),
2195 'to' => [$profile['url']],
2198 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2200 $signed = LDSignature::sign($data, $owner);
2201 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2205 * Transmit a message that the contact request had been accepted
2207 * @param string $target Target profile
2208 * @param string $id Object id
2209 * @param integer $uid User ID
2211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2212 * @throws \ImagickException
2214 public static function sendContactAccept(string $target, string $id, int $uid)
2216 $profile = APContact::getByURL($target);
2217 if (empty($profile['inbox'])) {
2218 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2222 $owner = User::getOwnerDataById($uid);
2224 Logger::notice('No user found for actor', ['uid' => $uid]);
2229 '@context' => ActivityPub::CONTEXT,
2230 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2232 'actor' => $owner['url'],
2236 'actor' => $profile['url'],
2237 'object' => $owner['url']
2239 'instrument' => self::getService(),
2240 'to' => [$profile['url']],
2243 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2245 $signed = LDSignature::sign($data, $owner);
2246 HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2250 * Reject a contact request or terminates the contact relation
2252 * @param string $target Target profile
2253 * @param string $objectId Object id
2254 * @param array $owner Sender owner-view record
2255 * @return bool Operation success
2256 * @throws HTTPException\InternalServerErrorException
2257 * @throws \ImagickException
2259 public static function sendContactReject(string $target, string $objectId, array $owner): bool
2261 $profile = APContact::getByURL($target);
2262 if (empty($profile['inbox'])) {
2263 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2268 '@context' => ActivityPub::CONTEXT,
2269 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2271 'actor' => $owner['url'],
2275 'actor' => $profile['url'],
2276 'object' => $owner['url']
2278 'instrument' => self::getService(),
2279 'to' => [$profile['url']],
2282 Logger::debug('Sending reject to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId);
2284 $signed = LDSignature::sign($data, $owner);
2285 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2289 * Transmits a message that we don't want to follow this contact anymore
2291 * @param string $target Target profile
2292 * @param integer $cid Contact id
2293 * @param array $owner Sender owner-view record
2294 * @return bool success
2295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2296 * @throws \ImagickException
2297 * @throws \Exception
2299 public static function sendContactUndo(string $target, int $cid, array $owner): bool
2301 $profile = APContact::getByURL($target);
2302 if (empty($profile['inbox'])) {
2303 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2307 $object_id = self::activityIDFromContact($cid);
2308 if (empty($object_id)) {
2312 $objectId = DI::baseUrl() . '/activity/' . System::createGUID();
2315 '@context' => ActivityPub::CONTEXT,
2318 'actor' => $owner['url'],
2322 'actor' => $owner['url'],
2323 'object' => $profile['url']
2325 'instrument' => self::getService(),
2326 'to' => [$profile['url']],
2329 Logger::info('Sending undo to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId);
2331 $signed = LDSignature::sign($data, $owner);
2332 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2336 * Prepends mentions (@) to $body variable
2338 * @param string $body HTML code
2340 * @param string $authorLink Author link
2341 * @return string HTML code with prepended mentions
2343 private static function prependMentions(string $body, int $uriid, string $authorLink): string
2347 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2348 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2349 if (!empty($profile['addr'])
2350 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2351 && !strstr($body, $profile['addr'])
2352 && !strstr($body, $tag['url'])
2353 && $tag['url'] !== $authorLink
2355 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2359 $mentions[] = $body;
2361 return implode(' ', $mentions);