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\Conversation;
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\Relay;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\HTTPSignature;
47 use Friendica\Util\JsonLD;
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
63 * Add relay servers to the list of inboxes
65 * @param array $inboxes
66 * @return array inboxes with added relay servers
68 public static function addRelayServerInboxes(array $inboxes = [])
70 foreach (Relay::getList(['inbox']) as $contact) {
71 $inboxes[$contact['inbox']] = $contact['inbox'];
78 * Add relay servers to the list of inboxes
80 * @param array $inboxes
81 * @return array inboxes with added relay servers
83 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
85 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
90 $relays = Relay::getDirectRelayList($item_id);
95 foreach ($relays as $relay) {
96 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
97 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
103 * Subscribe to a relay
105 * @param string $url Subscribe actor url
106 * @return bool success
108 public static function sendRelayFollow(string $url)
110 $contact = Contact::getByURL($url);
111 if (empty($contact)) {
115 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
116 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
118 Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]);
125 * Unsubscribe from a relay
127 * @param string $url Subscribe actor url
128 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
129 * @return bool success
131 public static function sendRelayUndoFollow(string $url, bool $force = false)
133 $contact = Contact::getByURL($url);
134 if (empty($contact)) {
138 $success = self::sendContactUndo($url, $contact['id'], 0);
139 if ($success || $force) {
140 Contact::update(['rel' => Contact::NOTHING], ['id' => $contact['id']]);
147 * Collects a list of contacts of the given owner
149 * @param array $owner Owner array
150 * @param array $rel The relevant value(s) contact.rel should match
151 * @param string $module The name of the relevant AP endpoint module (followers|following)
152 * @param integer $page Page number
153 * @param string $requester URL of the requester
155 * @return array of owners
158 public static function getContacts(array $owner, array $rel, string $module, int $page = null, string $requester = null)
162 'uid' => $owner['uid'],
171 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
173 $total = DBA::count('contact', $condition);
175 $modulePath = '/' . $module . '/';
177 $data = ['@context' => ActivityPub::CONTEXT];
178 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
179 $data['type'] = 'OrderedCollection';
180 $data['totalItems'] = $total;
183 $data['id'] .= '?' . http_build_query(['page' => $page]);
186 // When we hide our friends we will only show the pure number but don't allow more.
187 $show_contacts = empty($owner['hide-friends']);
189 // Allow fetching the contact list when the requester is part of the list.
190 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
191 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
194 if (!$show_contacts) {
199 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
201 $data['type'] = 'OrderedCollectionPage';
204 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
205 while ($contact = DBA::fetch($contacts)) {
206 $list[] = $contact['url'];
208 DBA::close($contacts);
210 if (count($list) == 100) {
211 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
214 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
216 $data['orderedItems'] = $list;
223 * Public posts for the given owner
225 * @param array $owner Owner array
226 * @param integer $page Page number
227 * @param string $requester URL of requesting account
229 * @return array of posts
230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 * @throws \ImagickException
233 public static function getOutbox(array $owner, int $page = null, string $requester = '')
235 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
237 if (!empty($requester)) {
238 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
239 if (!empty($requester_id)) {
240 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
241 if (!empty($permissionSets)) {
242 $condition = ['psid' => array_merge($permissionSets->column('id'),
243 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
248 $condition = array_merge($condition,
249 ['uid' => $owner['uid'],
250 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
251 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
252 'network' => Protocol::FEDERATED,
253 'parent-network' => Protocol::FEDERATED,
258 $count = Post::count($condition);
260 $data = ['@context' => ActivityPub::CONTEXT];
261 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
262 $data['type'] = 'OrderedCollection';
263 $data['totalItems'] = $count;
266 $data['id'] .= '?' . http_build_query(['page' => $page]);
270 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
272 $data['type'] = 'OrderedCollectionPage';
275 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
276 while ($item = Post::fetch($items)) {
277 $activity = self::createActivityFromItem($item['id'], true);
278 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
280 // Only list "Create" activity objects here, no reshares
281 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
282 $list[] = $activity['object'];
287 if (count($list) == 20) {
288 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
291 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
293 $data['orderedItems'] = $list;
300 * Public posts for the given owner
302 * @param array $owner Owner array
303 * @param integer $page Page number
305 * @return array of posts
306 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
307 * @throws \ImagickException
309 public static function getFeatured(array $owner, int $page = null)
311 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
312 Contact::getIdForURL($owner['url'], 0, false), Post\Collection::FEATURED];
314 $condition = DBA::mergeConditions($condition,
315 ['uid' => $owner['uid'],
316 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
317 'private' => [Item::PUBLIC, Item::UNLISTED],
318 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
319 'network' => Protocol::FEDERATED,
320 'parent-network' => Protocol::FEDERATED,
325 $count = Post::count($condition);
327 $data = ['@context' => ActivityPub::CONTEXT];
328 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
329 $data['type'] = 'OrderedCollection';
330 $data['totalItems'] = $count;
333 $data['id'] .= '?' . http_build_query(['page' => $page]);
337 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
339 $data['type'] = 'OrderedCollectionPage';
340 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
344 while ($item = Post::fetch($items)) {
345 $activity = self::createActivityFromItem($item['id'], true);
346 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
348 // Only list "Create" activity objects here, no reshares
349 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
350 $list[] = $activity['object'];
355 if (count($list) == 20) {
356 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
360 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
363 $data['orderedItems'] = $list;
369 * Return the service array containing information the used software and it's url
371 * @return array with service data
373 private static function getService()
375 return ['type' => 'Service',
376 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
377 'url' => DI::baseUrl()->get()];
381 * Return the ActivityPub profile of the given user
383 * @param int $uid User ID
384 * @return array with profile data
385 * @throws HTTPException\NotFoundException
386 * @throws HTTPException\InternalServerErrorException
388 public static function getProfile(int $uid): array
390 $owner = User::getOwnerDataById($uid);
391 if (!isset($owner['id'])) {
392 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
393 throw new HTTPException\NotFoundException('User not found.');
396 $data = ['@context' => ActivityPub::CONTEXT];
397 $data['id'] = $owner['url'];
399 if (!empty($owner['guid'])) {
400 $data['diaspora:guid'] = $owner['guid'];
403 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
406 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
407 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
408 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
409 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
410 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
412 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
415 $data['preferredUsername'] = $owner['nick'];
416 $data['name'] = $owner['name'];
418 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
419 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
420 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
423 if (!empty($owner['about'])) {
424 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
427 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
428 $data['vcard:hasInstantMessage'] = [];
430 if (!empty($owner['xmpp'])) {
431 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
433 if (!empty($owner['matrix'])) {
434 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
438 $data['url'] = $owner['url'];
439 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
440 $data['discoverable'] = (bool)$owner['net-publish'];
441 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
442 'owner' => $owner['url'],
443 'publicKeyPem' => $owner['pubkey']];
444 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
445 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
447 $resourceid = Photo::ridFromURI($owner['photo']);
448 if (!empty($resourceid)) {
449 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
450 if (!empty($photo['type'])) {
451 $data['icon']['mediaType'] = $photo['type'];
455 if (!empty($owner['header'])) {
456 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
458 $resourceid = Photo::ridFromURI($owner['header']);
459 if (!empty($resourceid)) {
460 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
461 if (!empty($photo['type'])) {
462 $data['image']['mediaType'] = $photo['type'];
469 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
471 'type' => 'PropertyValue',
472 'name' => $profile_field->label,
473 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
477 if (!empty($custom_fields)) {
478 $data['attachment'] = $custom_fields;
481 $data['generator'] = self::getService();
483 // tags: https://kitty.town/@inmysocks/100656097926961126.json
488 * @param string $username
490 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
492 public static function getDeletedUser($username)
495 '@context' => ActivityPub::CONTEXT,
496 'id' => DI::baseUrl() . '/profile/' . $username,
497 'type' => 'Tombstone',
498 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
499 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
500 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
505 * Returns an array with permissions of the thread parent of the given item array
508 * @param bool $is_forum_thread
510 * @return array with permissions
511 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
512 * @throws \ImagickException
514 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread)
516 if (empty($item['thr-parent-id'])) {
520 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
521 if (empty($parent)) {
526 'to' => [$parent['author-link']],
532 $parent_profile = APContact::getByURL($parent['author-link']);
534 $item_profile = APContact::getByURL($item['author-link']);
535 $exclude[] = $item['author-link'];
537 if ($item['gravity'] == GRAVITY_PARENT) {
538 $exclude[] = $item['owner-link'];
541 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
542 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
543 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
544 if (!$is_forum_thread) {
545 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
547 } elseif (!in_array($receiver['url'], $exclude)) {
548 $permissions[$type[$receiver['type']]][] = $receiver['url'];
556 * Check if the given item id is from ActivityPub
558 * @param integer $item_id
559 * @return boolean "true" if the post is from ActivityPub
561 private static function isAPPost(int $item_id)
563 if (empty($item_id)) {
567 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
571 * Creates an array of permissions from an item thread
573 * @param array $item Item array
574 * @param boolean $blindcopy addressing via "bcc" or "cc"?
575 * @param integer $last_id Last item id for adding receivers
577 * @return array with permission data
578 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
579 * @throws \ImagickException
581 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
584 $last_id = $item['id'];
591 // Check if we should always deliver our stuff via BCC
592 if (!empty($item['uid'])) {
593 $owner = User::getOwnerDataById($item['uid']);
594 if (!empty($owner)) {
595 $always_bcc = $owner['hide-friends'];
596 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
598 $profile = APContact::getByURL($owner['url'], false);
599 $follower = $profile['followers'] ?? '';
603 if (DI::config()->get('system', 'ap_always_bcc')) {
607 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
608 if (($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
609 $profile = APContact::getByURL($parent['causer-link'], false);
610 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
612 $is_forum_thread = false;
615 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
616 // Will be activated in a later step
617 $networks = Protocol::FEDERATED;
619 // For now only send to these contacts:
620 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
623 $data = ['to' => [], 'cc' => [], 'bcc' => []];
625 if ($item['gravity'] == GRAVITY_PARENT) {
626 $actor_profile = APContact::getByURL($item['owner-link']);
628 $actor_profile = APContact::getByURL($item['author-link']);
633 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
635 if ($item['private'] != Item::PRIVATE) {
636 // Directly mention the original author upon a quoted reshare.
637 // Else just ensure that the original author receives the reshare.
638 $announce = self::getAnnounceArray($item);
639 if (!empty($announce['comment'])) {
640 $data['to'][] = $announce['actor']['url'];
641 } elseif (!empty($announce)) {
642 $data['cc'][] = $announce['actor']['url'];
645 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
647 // Check if the item is completely public or unlisted
648 if ($item['private'] == Item::PUBLIC) {
649 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
651 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
654 foreach ($terms as $term) {
655 $profile = APContact::getByURL($term['url'], false);
656 if (!empty($profile)) {
657 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
659 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
660 $data['cc'][] = $profile['followers'];
663 $data['to'][] = $profile['url'];
667 $receiver_list = Item::enumeratePermissions($item, true);
669 foreach ($terms as $term) {
670 $cid = Contact::getIdForURL($term['url'], $item['uid']);
671 if (!empty($cid) && in_array($cid, $receiver_list)) {
672 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
673 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
677 $profile = APContact::getByURL($term['url'], false);
678 if (!empty($profile)) {
679 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
681 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
682 $data['cc'][] = $profile['followers'];
685 $data['to'][] = $profile['url'];
690 if ($is_forum && !$exclusive && !empty($follower)) {
691 $data['cc'][] = $follower;
692 } elseif (!$exclusive) {
693 foreach ($receiver_list as $receiver) {
694 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
695 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
699 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
700 if ($contact['hidden'] || $always_bcc) {
701 $data['bcc'][] = $profile['url'];
703 $data['cc'][] = $profile['url'];
710 if (!empty($item['parent'])) {
711 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']], ['order' => ['id']]);
712 while ($parent = Post::fetch($parents)) {
713 if ($parent['gravity'] == GRAVITY_PARENT) {
714 $profile = APContact::getByURL($parent['owner-link'], false);
715 if (!empty($profile)) {
716 if ($item['gravity'] != GRAVITY_PARENT) {
717 // Comments to forums are directed to the forum
718 // But comments to forums aren't directed to the followers collection
719 // This rule is only valid when the actor isn't the forum.
720 // The forum needs to transmit their content to their followers.
721 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
722 $data['to'][] = $profile['url'];
724 $data['cc'][] = $profile['url'];
725 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])&& !$is_forum_thread) {
726 $data['cc'][] = $actor_profile['followers'];
729 } elseif (!$exclusive && !$is_forum_thread) {
730 // Public thread parent post always are directed to the followers.
731 if ($item['private'] != Item::PRIVATE) {
732 $data['cc'][] = $actor_profile['followers'];
738 // Don't include data from future posts
739 if ($parent['id'] >= $last_id) {
743 $profile = APContact::getByURL($parent['author-link'], false);
744 if (!empty($profile)) {
745 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
746 $data['to'][] = $profile['url'];
748 $data['cc'][] = $profile['url'];
752 DBA::close($parents);
755 $data['to'] = array_unique($data['to']);
756 $data['cc'] = array_unique($data['cc']);
757 $data['bcc'] = array_unique($data['bcc']);
759 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
760 unset($data['to'][$key]);
763 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
764 unset($data['cc'][$key]);
767 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
768 unset($data['bcc'][$key]);
771 foreach ($data['to'] as $to) {
772 if (($key = array_search($to, $data['cc'])) !== false) {
773 unset($data['cc'][$key]);
776 if (($key = array_search($to, $data['bcc'])) !== false) {
777 unset($data['bcc'][$key]);
781 foreach ($data['cc'] as $cc) {
782 if (($key = array_search($cc, $data['bcc'])) !== false) {
783 unset($data['bcc'][$key]);
787 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
790 unset($receivers['bcc']);
793 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
794 if (!empty($receivers[$element])) {
795 foreach ($receivers[$element] as $receiver) {
796 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
797 $name = Receiver::PUBLIC_COLLECTION;
799 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
801 Tag::store($item['uri-id'], $type, $name, $receiver);
810 * Check if an inbox is archived
812 * @param string $url Inbox url
814 * @return boolean "true" if inbox is archived
816 public static function archivedInbox($url)
818 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
822 * Check if a given contact should be delivered via AP
824 * @param array $contact
825 * @param array $networks
829 private static function isAPContact(array $contact, array $networks)
831 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
835 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
839 * Fetches a list of inboxes of followers of a given user
841 * @param integer $uid User ID
842 * @param boolean $personal fetch personal inboxes
843 * @param boolean $all_ap Retrieve all AP enabled inboxes
845 * @return array of follower inboxes
846 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
847 * @throws \ImagickException
849 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
855 if (!empty($item['uid'])) {
856 $profile = User::getOwnerDataById($item['uid']);
857 if (!empty($profile)) {
858 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
862 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
863 // Will be activated in a later step
864 $networks = Protocol::FEDERATED;
866 // For now only send to these contacts:
867 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
870 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
873 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
876 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
877 while ($contact = DBA::fetch($contacts)) {
878 if (!self::isAPContact($contact, $networks)) {
882 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
886 if (Network::isUrlBlocked($contact['url'])) {
890 $profile = APContact::getByURL($contact['url'], false);
891 if (!empty($profile)) {
892 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
893 $target = $profile['inbox'];
895 $target = $profile['sharedinbox'];
897 if (!self::archivedInbox($target)) {
898 $inboxes[$target][] = $contact['id'];
902 DBA::close($contacts);
908 * Fetches an array of inboxes for the given item and user
910 * @param array $item Item array
911 * @param integer $uid User ID
912 * @param boolean $personal fetch personal inboxes
913 * @param integer $last_id Last item id for adding receivers
914 * @return array with inboxes
915 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
916 * @throws \ImagickException
918 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
920 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
921 if (empty($permissions)) {
927 if ($item['gravity'] == GRAVITY_ACTIVITY) {
928 $item_profile = APContact::getByURL($item['author-link'], false);
930 $item_profile = APContact::getByURL($item['owner-link'], false);
933 if (empty($item_profile)) {
937 $profile_uid = User::getIdForURL($item_profile['url']);
939 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
940 if (empty($permissions[$element])) {
944 $blindcopy = in_array($element, ['bto', 'bcc']);
946 foreach ($permissions[$element] as $receiver) {
947 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
951 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
952 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
954 $profile = APContact::getByURL($receiver, false);
955 if (!empty($profile)) {
956 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
958 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
959 $target = $profile['inbox'];
961 $target = $profile['sharedinbox'];
963 if (!self::archivedInbox($target)) {
964 $inboxes[$target][] = $contact['id'] ?? 0;
975 * Creates an array in the structure of the item table for a given mail id
977 * @param integer $mail_id
982 public static function ItemArrayFromMail($mail_id, $use_title = false)
984 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
985 if (!DBA::isResult($mail)) {
989 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
990 if (!DBA::isResult($reply)) {
994 // Making the post more compatible for Mastodon by:
995 // - Making it a note and not an article (no title)
996 // - Moving the title into the "summary" field that is used as a "content warning"
999 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1000 $mail['title'] = '';
1003 $mail['content-warning'] = '';
1004 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1005 $mail['owner-id'] = $mail['author-id'];
1006 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1007 $mail['allow_gid'] = '';
1008 $mail['deny_cid'] = '';
1009 $mail['deny_gid'] = '';
1010 $mail['private'] = Item::PRIVATE;
1011 $mail['deleted'] = false;
1012 $mail['edited'] = $mail['created'];
1013 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1014 $mail['parent-uri'] = $reply['uri'];
1015 $mail['parent-uri-id'] = $reply['uri-id'];
1016 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1017 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
1018 $mail['event-type'] = '';
1019 $mail['language'] = '';
1020 $mail['parent'] = 0;
1026 * Creates an activity array for a given mail id
1028 * @param integer $mail_id
1029 * @param boolean $object_mode Is the activity item is used inside another object?
1031 * @return array of activity
1032 * @throws \Exception
1034 public static function createActivityFromMail($mail_id, $object_mode = false)
1036 $mail = self::ItemArrayFromMail($mail_id);
1040 $object = self::createNote($mail);
1042 if (!$object_mode) {
1043 $data = ['@context' => ActivityPub::CONTEXT];
1048 $data['id'] = $mail['uri'] . '/Create';
1049 $data['type'] = 'Create';
1050 $data['actor'] = $mail['author-link'];
1051 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1052 $data['instrument'] = self::getService();
1053 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1055 if (empty($data['to']) && !empty($data['cc'])) {
1056 $data['to'] = $data['cc'];
1059 if (empty($data['to']) && !empty($data['bcc'])) {
1060 $data['to'] = $data['bcc'];
1064 unset($data['bcc']);
1066 $object['to'] = $data['to'];
1067 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1069 unset($object['cc']);
1070 unset($object['bcc']);
1072 $data['directMessage'] = true;
1074 $data['object'] = $object;
1076 $owner = User::getOwnerDataById($mail['uid']);
1078 if (!$object_mode && !empty($owner)) {
1079 return LDSignature::sign($data, $owner);
1086 * Returns the activity type of a given item
1088 * @param array $item
1090 * @return string with activity type
1091 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1092 * @throws \ImagickException
1094 private static function getTypeOfItem($item)
1098 // Only check for a reshare, if it is a real reshare and no quoted reshare
1099 if (strpos($item['body'], "[share") === 0) {
1100 $announce = self::getAnnounceArray($item);
1101 $reshared = !empty($announce);
1106 } elseif ($item['verb'] == Activity::POST) {
1107 if ($item['created'] == $item['edited']) {
1112 } elseif ($item['verb'] == Activity::LIKE) {
1114 } elseif ($item['verb'] == Activity::DISLIKE) {
1116 } elseif ($item['verb'] == Activity::ATTEND) {
1118 } elseif ($item['verb'] == Activity::ATTENDNO) {
1120 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1121 $type = 'TentativeAccept';
1122 } elseif ($item['verb'] == Activity::FOLLOW) {
1124 } elseif ($item['verb'] == Activity::TAG) {
1126 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1136 * Creates the activity or fetches it from the cache
1138 * @param integer $item_id
1139 * @param boolean $force Force new cache entry
1141 * @return array with the activity
1142 * @throws \Exception
1144 public static function createCachedActivityFromItem($item_id, $force = false)
1146 $cachekey = 'APDelivery:createActivity:' . $item_id;
1149 $data = DI::cache()->get($cachekey);
1150 if (!is_null($data)) {
1155 $data = self::createActivityFromItem($item_id);
1157 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1162 * Creates an activity array for a given item id
1164 * @param integer $item_id
1165 * @param boolean $object_mode Is the activity item is used inside another object?
1167 * @return false|array
1168 * @throws \Exception
1170 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1172 Logger::info('Fetching activity', ['item' => $item_id]);
1173 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1174 if (!DBA::isResult($item)) {
1178 if (empty($item['uri-id'])) {
1179 Logger::warning('Item without uri-id', ['item' => $item]);
1183 if (!$item['deleted']) {
1184 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1185 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1186 if (!$item['origin'] && DBA::isResult($conversation)) {
1187 $data = json_decode($conversation['source'], true);
1188 if (!empty($data['type'])) {
1189 if (in_array($data['type'], ['Create', 'Update'])) {
1191 unset($data['@context']);
1192 unset($data['signature']);
1194 Logger::info('Return stored conversation', ['item' => $item_id]);
1196 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1197 if (!empty($data['@context'])) {
1198 $context = $data['@context'];
1199 unset($data['@context']);
1201 unset($data['actor']);
1208 $type = self::getTypeOfItem($item);
1210 if (!$object_mode) {
1211 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1213 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1215 } elseif ($item['deleted']) {
1222 if ($type == 'Delete') {
1223 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1224 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1225 $data['id'] = $item['uri'];
1227 $data['id'] = $item['uri'] . '/' . $type;
1230 $data['type'] = $type;
1232 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1233 $data['actor'] = $item['author-link'];
1235 $data['actor'] = $item['owner-link'];
1238 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1240 $data['instrument'] = self::getService();
1242 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1244 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1245 $data['object'] = $object ?? self::createNote($item);
1246 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1247 } elseif ($data['type'] == 'Add') {
1248 $data = self::createAddTag($item, $data);
1249 } elseif ($data['type'] == 'Announce') {
1250 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1251 $data['object'] = $item['thr-parent'];
1253 $data = self::createAnnounce($item, $data);
1255 } elseif ($data['type'] == 'Follow') {
1256 $data['object'] = $item['parent-uri'];
1257 } elseif ($data['type'] == 'Undo') {
1258 $data['object'] = self::createActivityFromItem($item_id, true);
1260 $data['diaspora:guid'] = $item['guid'];
1261 if (!empty($item['signed_text'])) {
1262 $data['diaspora:like'] = $item['signed_text'];
1264 $data['object'] = $item['thr-parent'];
1267 if (!empty($item['contact-uid'])) {
1268 $uid = $item['contact-uid'];
1270 $uid = $item['uid'];
1273 $owner = User::getOwnerDataById($uid);
1275 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1277 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1278 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1279 return LDSignature::sign($data, $owner);
1284 /// @todo Create "conversation" entry
1288 * Creates a location entry for a given item array
1290 * @param array $item
1292 * @return array with location array
1294 private static function createLocation($item)
1296 $location = ['type' => 'Place'];
1298 if (!empty($item['location'])) {
1299 $location['name'] = $item['location'];
1304 if (empty($item['coord'])) {
1305 $coord = Map::getCoordinates($item['location']);
1307 $coords = explode(' ', $item['coord']);
1308 if (count($coords) == 2) {
1309 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1313 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1314 $location['latitude'] = $coord['lat'];
1315 $location['longitude'] = $coord['lon'];
1322 * Returns a tag array for a given item array
1324 * @param array $item
1326 * @return array of tags
1327 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1329 private static function createTagList($item)
1333 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1334 foreach ($terms as $term) {
1335 if ($term['type'] == Tag::HASHTAG) {
1336 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1337 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1339 $contact = Contact::getByURL($term['url'], false, ['addr']);
1340 if (empty($contact)) {
1343 if (!empty($contact['addr'])) {
1344 $mention = '@' . $contact['addr'];
1346 $mention = '@' . $term['url'];
1349 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1353 $announce = self::getAnnounceArray($item);
1354 // Mention the original author upon commented reshares
1355 if (!empty($announce['comment'])) {
1356 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1363 * Adds attachment data to the JSON document
1365 * @param array $item Data of the item that is to be posted
1366 * @param string $type Object type
1368 * @return array with attachment data
1369 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1371 private static function createAttachmentList($item, $type)
1375 $uriids = [$item['uri-id']];
1376 $shared = BBCode::fetchShareAttributes($item['body']);
1377 if (!empty($shared['guid'])) {
1378 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1379 if (!empty($shared_item['uri-id'])) {
1380 $uriids[] = $shared_item['uri-id'];
1385 foreach ($uriids as $uriid) {
1386 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1387 if (in_array($attachment['url'], $urls)) {
1390 $urls[] = $attachment['url'];
1392 $attach = ['type' => 'Document',
1393 'mediaType' => $attachment['mimetype'],
1394 'url' => $attachment['url'],
1395 'name' => $attachment['description']];
1397 if (!empty($attachment['height'])) {
1398 $attach['height'] = $attachment['height'];
1401 if (!empty($attachment['width'])) {
1402 $attach['width'] = $attachment['width'];
1405 if (!empty($attachment['preview'])) {
1406 $attach['image'] = $attachment['preview'];
1409 $attachments[] = $attach;
1413 return $attachments;
1417 * Callback function to replace a Friendica style mention in a mention for a summary
1419 * @param array $match Matching values for the callback
1420 * @return string Replaced mention
1421 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1423 private static function mentionAddrCallback($match)
1425 if (empty($match[1])) {
1429 $data = Contact::getByURL($match[1], false, ['addr']);
1430 if (empty($data['addr'])) {
1434 return '@' . $data['addr'];
1438 * Remove image elements since they are added as attachment
1440 * @param string $body
1442 * @return string with removed images
1444 private static function removePictures($body)
1446 // Simplify image codes
1447 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1448 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1450 // Now remove local links
1451 $body = preg_replace_callback(
1452 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1454 // We remove the link when it is a link to a local photo page
1455 if (Photo::isLocalPage($match[1])) {
1458 // otherwise we just return the link
1459 return '[url]' . $match[1] . '[/url]';
1464 // Remove all pictures
1465 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1471 * Fetches the "context" value for a givem item array from the "conversation" table
1473 * @param array $item
1475 * @return string with context url
1476 * @throws \Exception
1478 private static function fetchContextURLForItem($item)
1480 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1481 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1482 $context_uri = $conversation['conversation-href'];
1483 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1484 $context_uri = $conversation['conversation-uri'];
1486 $context_uri = $item['parent-uri'] . '#context';
1488 return $context_uri;
1492 * Returns if the post contains sensitive content ("nsfw")
1494 * @param integer $uri_id
1497 * @throws \Exception
1499 private static function isSensitive($uri_id)
1501 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1505 * Creates event data
1507 * @param array $item
1509 * @return array with the event data
1510 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1512 private static function createEvent($item)
1515 $event['name'] = $item['event-summary'];
1516 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1517 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1519 if (!$item['event-nofinish']) {
1520 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1523 if (!empty($item['event-location'])) {
1524 $item['location'] = $item['event-location'];
1525 $event['location'] = self::createLocation($item);
1528 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1529 $event['dfrn:adjust'] = true;
1535 * Creates a note/article object array
1537 * @param array $item
1539 * @return array with the object data
1540 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1541 * @throws \ImagickException
1543 public static function createNote($item)
1549 // We are treating posts differently when they are directed to a community.
1550 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1551 // But to not risk compatibility issues we currently perform the changes only for communities.
1552 if ($item['gravity'] == GRAVITY_PARENT) {
1553 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1554 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1555 if ($isCommunityPost && (count($links) == 1)) {
1556 $link = $links[0]['url'];
1559 $isCommunityPost = false;
1562 if ($item['event-type'] == 'event') {
1564 } elseif (!empty($item['title'])) {
1565 if (!$isCommunityPost || empty($link)) {
1568 // "Page" is used by Lemmy for posts that contain an external link
1575 if ($item['deleted']) {
1576 $type = 'Tombstone';
1580 $data['id'] = $item['uri'];
1581 $data['type'] = $type;
1583 if ($item['deleted']) {
1587 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1589 if ($item['uri'] != $item['thr-parent']) {
1590 $data['inReplyTo'] = $item['thr-parent'];
1592 $data['inReplyTo'] = null;
1595 $data['diaspora:guid'] = $item['guid'];
1596 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1598 if ($item['created'] != $item['edited']) {
1599 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1602 $data['url'] = $link ?? $item['plink'];
1603 $data['attributedTo'] = $item['author-link'];
1604 $data['sensitive'] = self::isSensitive($item['uri-id']);
1605 $data['context'] = self::fetchContextURLForItem($item);
1607 if (!empty($item['title'])) {
1608 $data['name'] = BBCode::toPlaintext($item['title'], false);
1611 $permission_block = self::createPermissionBlockForItem($item, false);
1613 $body = $item['body'];
1615 if ($type == 'Note') {
1616 $body = $item['raw-body'] ?? self::removePictures($body);
1620 * @todo Improve the automated summary
1621 * This part is currently deactivated. The automated summary seems to be more
1622 * confusing than helping. But possibly we will find a better way.
1623 * So the code is left here for now as a reminder
1625 * } elseif (($type == 'Article') && empty($data['summary'])) {
1626 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1627 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1628 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1632 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1633 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1636 if ($type == 'Event') {
1637 $data = array_merge($data, self::createEvent($item));
1639 if ($isCommunityPost) {
1640 // For community posts we remove the visible "!user@domain.tld".
1641 // This improves the look at systems like Lemmy.
1642 // Also in the future we should control the community delivery via other methods.
1643 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1646 if ($type == 'Page') {
1647 // When we transmit "Page" posts we have to remove the attachment.
1648 // The attachment contains the link that we already transmit in the "url" field.
1649 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1652 $body = BBCode::setMentionsToNicknames($body);
1654 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1657 // The regular "content" field does contain a minimized HTML. This is done since systems like
1658 // Mastodon has got problems with - for example - embedded pictures.
1659 // The contentMap does contain the unmodified HTML.
1660 $language = self::getLanguage($item);
1661 if (!empty($language)) {
1662 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1663 $richbody = BBCode::removeAttachment($richbody);
1665 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1668 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1670 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1671 $data['diaspora:comment'] = $item['signed_text'];
1674 $data['attachment'] = self::createAttachmentList($item, $type);
1675 $data['tag'] = self::createTagList($item);
1677 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1678 $data['location'] = self::createLocation($item);
1681 if (!empty($item['app'])) {
1682 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1685 $data = array_merge($data, $permission_block);
1691 * Fetches the language from the post, the user or the system.
1693 * @param array $item
1695 * @return string language string
1697 private static function getLanguage(array $item)
1699 // Try to fetch the language from the post itself
1700 if (!empty($item['language'])) {
1701 $languages = array_keys(json_decode($item['language'], true));
1702 if (!empty($languages[0])) {
1703 return $languages[0];
1707 // Otherwise use the user's language
1708 if (!empty($item['uid'])) {
1709 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1710 if (!empty($user['language'])) {
1711 return $user['language'];
1715 // And finally just use the system language
1716 return DI::config()->get('system', 'language');
1720 * Creates an an "add tag" entry
1722 * @param array $item
1723 * @param array $data activity data
1725 * @return array with activity data for adding tags
1726 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1727 * @throws \ImagickException
1729 private static function createAddTag($item, $data)
1731 $object = XML::parseString($item['object']);
1732 $target = XML::parseString($item["target"]);
1734 $data['diaspora:guid'] = $item['guid'];
1735 $data['actor'] = $item['author-link'];
1736 $data['target'] = (string)$target->id;
1737 $data['summary'] = BBCode::toPlaintext($item['body']);
1738 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1744 * Creates an announce object entry
1746 * @param array $item
1747 * @param array $data activity data
1749 * @return array with activity data
1750 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1751 * @throws \ImagickException
1753 private static function createAnnounce($item, $data)
1755 $orig_body = $item['body'];
1756 $announce = self::getAnnounceArray($item);
1757 if (empty($announce)) {
1758 $data['type'] = 'Create';
1759 $data['object'] = self::createNote($item);
1763 if (empty($announce['comment'])) {
1764 // Pure announce, without a quote
1765 $data['type'] = 'Announce';
1766 $data['object'] = $announce['object']['uri'];
1771 $data['type'] = 'Create';
1772 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1773 $data['object'] = self::createNote($item);
1775 /// @todo Finally descide how to implement this in AP. This is a possible way:
1776 $data['object']['attachment'][] = self::createNote($announce['object']);
1778 $data['object']['source']['content'] = $orig_body;
1783 * Return announce related data if the item is an annunce
1785 * @param array $item
1789 public static function getAnnounceArray($item)
1791 $reshared = Item::getShareArray($item);
1792 if (empty($reshared['guid'])) {
1796 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1797 if (!DBA::isResult($reshared_item)) {
1801 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1805 $profile = APContact::getByURL($reshared_item['author-link'], false);
1806 if (empty($profile)) {
1810 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1814 * Checks if the provided item array is an announce
1816 * @param array $item
1820 public static function isAnnounce($item)
1822 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1826 $announce = self::getAnnounceArray($item);
1827 if (empty($announce)) {
1831 return empty($announce['comment']);
1835 * Creates an activity id for a given contact id
1837 * @param integer $cid Contact ID of target
1839 * @return bool|string activity id
1841 public static function activityIDFromContact($cid)
1843 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1844 if (!DBA::isResult($contact)) {
1848 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1849 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1850 return DI::baseUrl() . '/activity/' . $uuid;
1854 * Transmits a contact suggestion to a given inbox
1856 * @param integer $uid User ID
1857 * @param string $inbox Target inbox
1858 * @param integer $suggestion_id Suggestion ID
1860 * @return boolean was the transmission successful?
1861 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1863 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1865 $owner = User::getOwnerDataById($uid);
1867 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1869 $data = ['@context' => ActivityPub::CONTEXT,
1870 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1871 'type' => 'Announce',
1872 'actor' => $owner['url'],
1873 'object' => $suggestion->url,
1874 'content' => $suggestion->note,
1875 'instrument' => self::getService(),
1876 'to' => [ActivityPub::PUBLIC_COLLECTION],
1879 $signed = LDSignature::sign($data, $owner);
1881 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1882 return HTTPSignature::transmit($signed, $inbox, $uid);
1886 * Transmits a profile relocation to a given inbox
1888 * @param integer $uid User ID
1889 * @param string $inbox Target inbox
1891 * @return boolean was the transmission successful?
1892 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1894 public static function sendProfileRelocation($uid, $inbox)
1896 $owner = User::getOwnerDataById($uid);
1898 $data = ['@context' => ActivityPub::CONTEXT,
1899 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1900 'type' => 'dfrn:relocate',
1901 'actor' => $owner['url'],
1902 'object' => $owner['url'],
1903 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1904 'instrument' => self::getService(),
1905 'to' => [ActivityPub::PUBLIC_COLLECTION],
1908 $signed = LDSignature::sign($data, $owner);
1910 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1911 return HTTPSignature::transmit($signed, $inbox, $uid);
1915 * Transmits a profile deletion to a given inbox
1917 * @param integer $uid User ID
1918 * @param string $inbox Target inbox
1920 * @return boolean was the transmission successful?
1921 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1923 public static function sendProfileDeletion($uid, $inbox)
1925 $owner = User::getOwnerDataById($uid);
1927 if (empty($owner)) {
1928 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1932 if (empty($owner['uprvkey'])) {
1933 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1937 $data = ['@context' => ActivityPub::CONTEXT,
1938 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1940 'actor' => $owner['url'],
1941 'object' => $owner['url'],
1942 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1943 'instrument' => self::getService(),
1944 'to' => [ActivityPub::PUBLIC_COLLECTION],
1947 $signed = LDSignature::sign($data, $owner);
1949 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1950 return HTTPSignature::transmit($signed, $inbox, $uid);
1954 * Transmits a profile change to a given inbox
1956 * @param integer $uid User ID
1957 * @param string $inbox Target inbox
1959 * @return boolean was the transmission successful?
1960 * @throws HTTPException\InternalServerErrorException
1961 * @throws HTTPException\NotFoundException
1962 * @throws \ImagickException
1964 public static function sendProfileUpdate(int $uid, string $inbox): bool
1966 $owner = User::getOwnerDataById($uid);
1967 $profile = APContact::getByURL($owner['url']);
1969 $data = ['@context' => ActivityPub::CONTEXT,
1970 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1972 'actor' => $owner['url'],
1973 'object' => self::getProfile($uid),
1974 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1975 'instrument' => self::getService(),
1976 'to' => [$profile['followers']],
1979 $signed = LDSignature::sign($data, $owner);
1981 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1982 return HTTPSignature::transmit($signed, $inbox, $uid);
1986 * Transmits a given activity to a target
1988 * @param string $activity Type name
1989 * @param string $target Target profile
1990 * @param integer $uid User ID
1992 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1993 * @throws \ImagickException
1994 * @throws \Exception
1996 public static function sendActivity($activity, $target, $uid, $id = '')
1998 $profile = APContact::getByURL($target);
1999 if (empty($profile['inbox'])) {
2000 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2004 $owner = User::getOwnerDataById($uid);
2007 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2010 $data = ['@context' => ActivityPub::CONTEXT,
2012 'type' => $activity,
2013 'actor' => $owner['url'],
2014 'object' => $profile['url'],
2015 'instrument' => self::getService(),
2016 'to' => [$profile['url']]];
2018 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2020 $signed = LDSignature::sign($data, $owner);
2021 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2025 * Transmits a "follow object" activity to a target
2026 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2028 * @param string $object Object URL
2029 * @param string $target Target profile
2030 * @param integer $uid User ID
2032 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2033 * @throws \ImagickException
2034 * @throws \Exception
2036 public static function sendFollowObject($object, $target, $uid = 0)
2038 $profile = APContact::getByURL($target);
2039 if (empty($profile['inbox'])) {
2040 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2045 // Fetch the list of administrators
2046 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2048 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2049 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2050 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2051 $uid = $first_user['uid'];
2054 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2055 'author-id' => Contact::getPublicIdByUserId($uid)];
2056 if (Post::exists($condition)) {
2057 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2061 $owner = User::getOwnerDataById($uid);
2063 $data = ['@context' => ActivityPub::CONTEXT,
2064 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2066 'actor' => $owner['url'],
2067 'object' => $object,
2068 'instrument' => self::getService(),
2069 'to' => [$profile['url']]];
2071 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2073 $signed = LDSignature::sign($data, $owner);
2074 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2078 * Transmit a message that the contact request had been accepted
2080 * @param string $target Target profile
2082 * @param integer $uid User ID
2083 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2084 * @throws \ImagickException
2086 public static function sendContactAccept($target, $id, $uid)
2088 $profile = APContact::getByURL($target);
2089 if (empty($profile['inbox'])) {
2090 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2094 $owner = User::getOwnerDataById($uid);
2095 $data = ['@context' => ActivityPub::CONTEXT,
2096 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2098 'actor' => $owner['url'],
2100 'id' => (string)$id,
2102 'actor' => $profile['url'],
2103 'object' => $owner['url']
2105 'instrument' => self::getService(),
2106 'to' => [$profile['url']]];
2108 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2110 $signed = LDSignature::sign($data, $owner);
2111 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2115 * Reject a contact request or terminates the contact relation
2117 * @param string $target Target profile
2119 * @param integer $uid User ID
2120 * @return bool Operation success
2121 * @throws HTTPException\InternalServerErrorException
2122 * @throws \ImagickException
2124 public static function sendContactReject($target, $id, $uid): bool
2126 $profile = APContact::getByURL($target);
2127 if (empty($profile['inbox'])) {
2128 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2132 $owner = User::getOwnerDataById($uid);
2133 $data = ['@context' => ActivityPub::CONTEXT,
2134 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2136 'actor' => $owner['url'],
2138 'id' => (string)$id,
2140 'actor' => $profile['url'],
2141 'object' => $owner['url']
2143 'instrument' => self::getService(),
2144 'to' => [$profile['url']]];
2146 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2148 $signed = LDSignature::sign($data, $owner);
2149 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2153 * Transmits a message that we don't want to follow this contact anymore
2155 * @param string $target Target profile
2156 * @param integer $uid User ID
2157 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2158 * @throws \ImagickException
2159 * @throws \Exception
2160 * @return bool success
2162 public static function sendContactUndo($target, $cid, $uid)
2164 $profile = APContact::getByURL($target);
2165 if (empty($profile['inbox'])) {
2166 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2170 $object_id = self::activityIDFromContact($cid);
2171 if (empty($object_id)) {
2175 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2177 $owner = User::getOwnerDataById($uid);
2178 $data = ['@context' => ActivityPub::CONTEXT,
2181 'actor' => $owner['url'],
2182 'object' => ['id' => $object_id, 'type' => 'Follow',
2183 'actor' => $owner['url'],
2184 'object' => $profile['url']],
2185 'instrument' => self::getService(),
2186 'to' => [$profile['url']]];
2188 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2190 $signed = LDSignature::sign($data, $owner);
2191 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2194 private static function prependMentions($body, int $uriid, string $authorLink)
2198 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2199 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2200 if (!empty($profile['addr'])
2201 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2202 && !strstr($body, $profile['addr'])
2203 && !strstr($body, $tag['url'])
2204 && $tag['url'] !== $authorLink
2206 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2210 $mentions[] = $body;
2212 return implode(' ', $mentions);