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 $data['first'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=1';
339 $data['type'] = 'OrderedCollectionPage';
342 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
343 while ($item = Post::fetch($items)) {
344 $activity = self::createActivityFromItem($item['id'], true);
345 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
347 // Only list "Create" activity objects here, no reshares
348 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
349 $list[] = $activity['object'];
354 if (count($list) == 20) {
355 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
358 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
360 $data['orderedItems'] = $list;
367 * Return the service array containing information the used software and it's url
369 * @return array with service data
371 private static function getService()
373 return ['type' => 'Service',
374 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
375 'url' => DI::baseUrl()->get()];
379 * Return the ActivityPub profile of the given user
381 * @param int $uid User ID
382 * @return array with profile data
383 * @throws HTTPException\NotFoundException
384 * @throws HTTPException\InternalServerErrorException
386 public static function getProfile(int $uid): array
388 $owner = User::getOwnerDataById($uid);
389 if (!isset($owner['id'])) {
390 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
391 throw new HTTPException\NotFoundException('User not found.');
394 $data = ['@context' => ActivityPub::CONTEXT];
395 $data['id'] = $owner['url'];
397 if (!empty($owner['guid'])) {
398 $data['diaspora:guid'] = $owner['guid'];
401 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
404 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
405 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
406 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
407 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
408 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
410 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
413 $data['preferredUsername'] = $owner['nick'];
414 $data['name'] = $owner['name'];
416 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
417 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
418 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
421 if (!empty($owner['about'])) {
422 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
425 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
426 $data['vcard:hasInstantMessage'] = [];
428 if (!empty($owner['xmpp'])) {
429 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
431 if (!empty($owner['matrix'])) {
432 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
436 $data['url'] = $owner['url'];
437 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
438 $data['discoverable'] = (bool)$owner['net-publish'];
439 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
440 'owner' => $owner['url'],
441 'publicKeyPem' => $owner['pubkey']];
442 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
443 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
445 $resourceid = Photo::ridFromURI($owner['photo']);
446 if (!empty($resourceid)) {
447 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
448 if (!empty($photo['type'])) {
449 $data['icon']['mediaType'] = $photo['type'];
453 if (!empty($owner['header'])) {
454 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
456 $resourceid = Photo::ridFromURI($owner['header']);
457 if (!empty($resourceid)) {
458 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
459 if (!empty($photo['type'])) {
460 $data['image']['mediaType'] = $photo['type'];
467 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
469 'type' => 'PropertyValue',
470 'name' => $profile_field->label,
471 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
475 if (!empty($custom_fields)) {
476 $data['attachment'] = $custom_fields;
479 $data['generator'] = self::getService();
481 // tags: https://kitty.town/@inmysocks/100656097926961126.json
486 * @param string $username
488 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
490 public static function getDeletedUser($username)
493 '@context' => ActivityPub::CONTEXT,
494 'id' => DI::baseUrl() . '/profile/' . $username,
495 'type' => 'Tombstone',
496 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
497 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
498 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
503 * Returns an array with permissions of the thread parent of the given item array
506 * @param bool $is_forum_thread
508 * @return array with permissions
509 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
510 * @throws \ImagickException
512 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread)
514 if (empty($item['thr-parent-id'])) {
518 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
519 if (empty($parent)) {
524 'to' => [$parent['author-link']],
530 $parent_profile = APContact::getByURL($parent['author-link']);
532 $item_profile = APContact::getByURL($item['author-link']);
533 $exclude[] = $item['author-link'];
535 if ($item['gravity'] == GRAVITY_PARENT) {
536 $exclude[] = $item['owner-link'];
539 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
540 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
541 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
542 if (!$is_forum_thread) {
543 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
545 } elseif (!in_array($receiver['url'], $exclude)) {
546 $permissions[$type[$receiver['type']]][] = $receiver['url'];
554 * Check if the given item id is from ActivityPub
556 * @param integer $item_id
557 * @return boolean "true" if the post is from ActivityPub
559 private static function isAPPost(int $item_id)
561 if (empty($item_id)) {
565 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
569 * Creates an array of permissions from an item thread
571 * @param array $item Item array
572 * @param boolean $blindcopy addressing via "bcc" or "cc"?
573 * @param integer $last_id Last item id for adding receivers
575 * @return array with permission data
576 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
577 * @throws \ImagickException
579 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
582 $last_id = $item['id'];
589 // Check if we should always deliver our stuff via BCC
590 if (!empty($item['uid'])) {
591 $owner = User::getOwnerDataById($item['uid']);
592 if (!empty($owner)) {
593 $always_bcc = $owner['hide-friends'];
594 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
596 $profile = APContact::getByURL($owner['url'], false);
597 $follower = $profile['followers'] ?? '';
601 if (DI::config()->get('system', 'ap_always_bcc')) {
605 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
606 if (($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
607 $profile = APContact::getByURL($parent['causer-link'], false);
608 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
610 $is_forum_thread = false;
613 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
614 // Will be activated in a later step
615 $networks = Protocol::FEDERATED;
617 // For now only send to these contacts:
618 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
621 $data = ['to' => [], 'cc' => [], 'bcc' => []];
623 if ($item['gravity'] == GRAVITY_PARENT) {
624 $actor_profile = APContact::getByURL($item['owner-link']);
626 $actor_profile = APContact::getByURL($item['author-link']);
631 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
633 if ($item['private'] != Item::PRIVATE) {
634 // Directly mention the original author upon a quoted reshare.
635 // Else just ensure that the original author receives the reshare.
636 $announce = self::getAnnounceArray($item);
637 if (!empty($announce['comment'])) {
638 $data['to'][] = $announce['actor']['url'];
639 } elseif (!empty($announce)) {
640 $data['cc'][] = $announce['actor']['url'];
643 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
645 // Check if the item is completely public or unlisted
646 if ($item['private'] == Item::PUBLIC) {
647 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
649 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
652 foreach ($terms as $term) {
653 $profile = APContact::getByURL($term['url'], false);
654 if (!empty($profile)) {
655 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
657 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
658 $data['cc'][] = $profile['followers'];
661 $data['to'][] = $profile['url'];
665 $receiver_list = Item::enumeratePermissions($item, true);
667 foreach ($terms as $term) {
668 $cid = Contact::getIdForURL($term['url'], $item['uid']);
669 if (!empty($cid) && in_array($cid, $receiver_list)) {
670 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
671 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
675 $profile = APContact::getByURL($term['url'], false);
676 if (!empty($profile)) {
677 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
679 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
680 $data['cc'][] = $profile['followers'];
683 $data['to'][] = $profile['url'];
688 if ($is_forum && !$exclusive && !empty($follower)) {
689 $data['cc'][] = $follower;
690 } elseif (!$exclusive) {
691 foreach ($receiver_list as $receiver) {
692 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
693 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
697 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
698 if ($contact['hidden'] || $always_bcc) {
699 $data['bcc'][] = $profile['url'];
701 $data['cc'][] = $profile['url'];
708 if (!empty($item['parent'])) {
709 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']], ['order' => ['id']]);
710 while ($parent = Post::fetch($parents)) {
711 if ($parent['gravity'] == GRAVITY_PARENT) {
712 $profile = APContact::getByURL($parent['owner-link'], false);
713 if (!empty($profile)) {
714 if ($item['gravity'] != GRAVITY_PARENT) {
715 // Comments to forums are directed to the forum
716 // But comments to forums aren't directed to the followers collection
717 // This rule is only valid when the actor isn't the forum.
718 // The forum needs to transmit their content to their followers.
719 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
720 $data['to'][] = $profile['url'];
722 $data['cc'][] = $profile['url'];
723 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])&& !$is_forum_thread) {
724 $data['cc'][] = $actor_profile['followers'];
727 } elseif (!$exclusive && !$is_forum_thread) {
728 // Public thread parent post always are directed to the followers.
729 if ($item['private'] != Item::PRIVATE) {
730 $data['cc'][] = $actor_profile['followers'];
736 // Don't include data from future posts
737 if ($parent['id'] >= $last_id) {
741 $profile = APContact::getByURL($parent['author-link'], false);
742 if (!empty($profile)) {
743 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
744 $data['to'][] = $profile['url'];
746 $data['cc'][] = $profile['url'];
750 DBA::close($parents);
753 $data['to'] = array_unique($data['to']);
754 $data['cc'] = array_unique($data['cc']);
755 $data['bcc'] = array_unique($data['bcc']);
757 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
758 unset($data['to'][$key]);
761 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
762 unset($data['cc'][$key]);
765 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
766 unset($data['bcc'][$key]);
769 foreach ($data['to'] as $to) {
770 if (($key = array_search($to, $data['cc'])) !== false) {
771 unset($data['cc'][$key]);
774 if (($key = array_search($to, $data['bcc'])) !== false) {
775 unset($data['bcc'][$key]);
779 foreach ($data['cc'] as $cc) {
780 if (($key = array_search($cc, $data['bcc'])) !== false) {
781 unset($data['bcc'][$key]);
785 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
788 unset($receivers['bcc']);
791 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
792 if (!empty($receivers[$element])) {
793 foreach ($receivers[$element] as $receiver) {
794 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
795 $name = Receiver::PUBLIC_COLLECTION;
797 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
799 Tag::store($item['uri-id'], $type, $name, $receiver);
808 * Check if an inbox is archived
810 * @param string $url Inbox url
812 * @return boolean "true" if inbox is archived
814 public static function archivedInbox($url)
816 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
820 * Check if a given contact should be delivered via AP
822 * @param array $contact
823 * @param array $networks
827 private static function isAPContact(array $contact, array $networks)
829 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
833 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
837 * Fetches a list of inboxes of followers of a given user
839 * @param integer $uid User ID
840 * @param boolean $personal fetch personal inboxes
841 * @param boolean $all_ap Retrieve all AP enabled inboxes
843 * @return array of follower inboxes
844 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
845 * @throws \ImagickException
847 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
853 if (!empty($item['uid'])) {
854 $profile = User::getOwnerDataById($item['uid']);
855 if (!empty($profile)) {
856 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
860 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
861 // Will be activated in a later step
862 $networks = Protocol::FEDERATED;
864 // For now only send to these contacts:
865 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
868 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
871 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
874 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
875 while ($contact = DBA::fetch($contacts)) {
876 if (!self::isAPContact($contact, $networks)) {
880 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
884 if (Network::isUrlBlocked($contact['url'])) {
888 $profile = APContact::getByURL($contact['url'], false);
889 if (!empty($profile)) {
890 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
891 $target = $profile['inbox'];
893 $target = $profile['sharedinbox'];
895 if (!self::archivedInbox($target)) {
896 $inboxes[$target][] = $contact['id'];
900 DBA::close($contacts);
906 * Fetches an array of inboxes for the given item and user
908 * @param array $item Item array
909 * @param integer $uid User ID
910 * @param boolean $personal fetch personal inboxes
911 * @param integer $last_id Last item id for adding receivers
912 * @return array with inboxes
913 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
914 * @throws \ImagickException
916 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
918 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
919 if (empty($permissions)) {
925 if ($item['gravity'] == GRAVITY_ACTIVITY) {
926 $item_profile = APContact::getByURL($item['author-link'], false);
928 $item_profile = APContact::getByURL($item['owner-link'], false);
931 if (empty($item_profile)) {
935 $profile_uid = User::getIdForURL($item_profile['url']);
937 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
938 if (empty($permissions[$element])) {
942 $blindcopy = in_array($element, ['bto', 'bcc']);
944 foreach ($permissions[$element] as $receiver) {
945 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
949 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
950 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
952 $profile = APContact::getByURL($receiver, false);
953 if (!empty($profile)) {
954 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
956 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
957 $target = $profile['inbox'];
959 $target = $profile['sharedinbox'];
961 if (!self::archivedInbox($target)) {
962 $inboxes[$target][] = $contact['id'] ?? 0;
973 * Creates an array in the structure of the item table for a given mail id
975 * @param integer $mail_id
980 public static function ItemArrayFromMail($mail_id, $use_title = false)
982 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
983 if (!DBA::isResult($mail)) {
987 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
988 if (!DBA::isResult($reply)) {
992 // Making the post more compatible for Mastodon by:
993 // - Making it a note and not an article (no title)
994 // - Moving the title into the "summary" field that is used as a "content warning"
997 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1001 $mail['content-warning'] = '';
1002 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1003 $mail['owner-id'] = $mail['author-id'];
1004 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1005 $mail['allow_gid'] = '';
1006 $mail['deny_cid'] = '';
1007 $mail['deny_gid'] = '';
1008 $mail['private'] = Item::PRIVATE;
1009 $mail['deleted'] = false;
1010 $mail['edited'] = $mail['created'];
1011 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1012 $mail['parent-uri'] = $reply['uri'];
1013 $mail['parent-uri-id'] = $reply['uri-id'];
1014 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1015 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
1016 $mail['event-type'] = '';
1017 $mail['language'] = '';
1018 $mail['parent'] = 0;
1024 * Creates an activity array for a given mail id
1026 * @param integer $mail_id
1027 * @param boolean $object_mode Is the activity item is used inside another object?
1029 * @return array of activity
1030 * @throws \Exception
1032 public static function createActivityFromMail($mail_id, $object_mode = false)
1034 $mail = self::ItemArrayFromMail($mail_id);
1038 $object = self::createNote($mail);
1040 if (!$object_mode) {
1041 $data = ['@context' => ActivityPub::CONTEXT];
1046 $data['id'] = $mail['uri'] . '/Create';
1047 $data['type'] = 'Create';
1048 $data['actor'] = $mail['author-link'];
1049 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1050 $data['instrument'] = self::getService();
1051 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1053 if (empty($data['to']) && !empty($data['cc'])) {
1054 $data['to'] = $data['cc'];
1057 if (empty($data['to']) && !empty($data['bcc'])) {
1058 $data['to'] = $data['bcc'];
1062 unset($data['bcc']);
1064 $object['to'] = $data['to'];
1065 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1067 unset($object['cc']);
1068 unset($object['bcc']);
1070 $data['directMessage'] = true;
1072 $data['object'] = $object;
1074 $owner = User::getOwnerDataById($mail['uid']);
1076 if (!$object_mode && !empty($owner)) {
1077 return LDSignature::sign($data, $owner);
1084 * Returns the activity type of a given item
1086 * @param array $item
1088 * @return string with activity type
1089 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1090 * @throws \ImagickException
1092 private static function getTypeOfItem($item)
1096 // Only check for a reshare, if it is a real reshare and no quoted reshare
1097 if (strpos($item['body'], "[share") === 0) {
1098 $announce = self::getAnnounceArray($item);
1099 $reshared = !empty($announce);
1104 } elseif ($item['verb'] == Activity::POST) {
1105 if ($item['created'] == $item['edited']) {
1110 } elseif ($item['verb'] == Activity::LIKE) {
1112 } elseif ($item['verb'] == Activity::DISLIKE) {
1114 } elseif ($item['verb'] == Activity::ATTEND) {
1116 } elseif ($item['verb'] == Activity::ATTENDNO) {
1118 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1119 $type = 'TentativeAccept';
1120 } elseif ($item['verb'] == Activity::FOLLOW) {
1122 } elseif ($item['verb'] == Activity::TAG) {
1124 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1134 * Creates the activity or fetches it from the cache
1136 * @param integer $item_id
1137 * @param boolean $force Force new cache entry
1139 * @return array with the activity
1140 * @throws \Exception
1142 public static function createCachedActivityFromItem($item_id, $force = false)
1144 $cachekey = 'APDelivery:createActivity:' . $item_id;
1147 $data = DI::cache()->get($cachekey);
1148 if (!is_null($data)) {
1153 $data = self::createActivityFromItem($item_id);
1155 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1160 * Creates an activity array for a given item id
1162 * @param integer $item_id
1163 * @param boolean $object_mode Is the activity item is used inside another object?
1165 * @return false|array
1166 * @throws \Exception
1168 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1170 Logger::info('Fetching activity', ['item' => $item_id]);
1171 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1172 if (!DBA::isResult($item)) {
1176 if (empty($item['uri-id'])) {
1177 Logger::warning('Item without uri-id', ['item' => $item]);
1181 if (!$item['deleted']) {
1182 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1183 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1184 if (!$item['origin'] && DBA::isResult($conversation)) {
1185 $data = json_decode($conversation['source'], true);
1186 if (!empty($data['type'])) {
1187 if (in_array($data['type'], ['Create', 'Update'])) {
1189 unset($data['@context']);
1190 unset($data['signature']);
1192 Logger::info('Return stored conversation', ['item' => $item_id]);
1194 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1195 if (!empty($data['@context'])) {
1196 $context = $data['@context'];
1197 unset($data['@context']);
1199 unset($data['actor']);
1206 $type = self::getTypeOfItem($item);
1208 if (!$object_mode) {
1209 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1211 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1213 } elseif ($item['deleted']) {
1220 if ($type == 'Delete') {
1221 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1222 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1223 $data['id'] = $item['uri'];
1225 $data['id'] = $item['uri'] . '/' . $type;
1228 $data['type'] = $type;
1230 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1231 $data['actor'] = $item['author-link'];
1233 $data['actor'] = $item['owner-link'];
1236 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1238 $data['instrument'] = self::getService();
1240 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1242 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1243 $data['object'] = $object ?? self::createNote($item);
1244 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1245 } elseif ($data['type'] == 'Add') {
1246 $data = self::createAddTag($item, $data);
1247 } elseif ($data['type'] == 'Announce') {
1248 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1249 $data['object'] = $item['thr-parent'];
1251 $data = self::createAnnounce($item, $data);
1253 } elseif ($data['type'] == 'Follow') {
1254 $data['object'] = $item['parent-uri'];
1255 } elseif ($data['type'] == 'Undo') {
1256 $data['object'] = self::createActivityFromItem($item_id, true);
1258 $data['diaspora:guid'] = $item['guid'];
1259 if (!empty($item['signed_text'])) {
1260 $data['diaspora:like'] = $item['signed_text'];
1262 $data['object'] = $item['thr-parent'];
1265 if (!empty($item['contact-uid'])) {
1266 $uid = $item['contact-uid'];
1268 $uid = $item['uid'];
1271 $owner = User::getOwnerDataById($uid);
1273 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1275 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1276 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1277 return LDSignature::sign($data, $owner);
1282 /// @todo Create "conversation" entry
1286 * Creates a location entry for a given item array
1288 * @param array $item
1290 * @return array with location array
1292 private static function createLocation($item)
1294 $location = ['type' => 'Place'];
1296 if (!empty($item['location'])) {
1297 $location['name'] = $item['location'];
1302 if (empty($item['coord'])) {
1303 $coord = Map::getCoordinates($item['location']);
1305 $coords = explode(' ', $item['coord']);
1306 if (count($coords) == 2) {
1307 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1311 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1312 $location['latitude'] = $coord['lat'];
1313 $location['longitude'] = $coord['lon'];
1320 * Returns a tag array for a given item array
1322 * @param array $item
1324 * @return array of tags
1325 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1327 private static function createTagList($item)
1331 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1332 foreach ($terms as $term) {
1333 if ($term['type'] == Tag::HASHTAG) {
1334 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1335 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1337 $contact = Contact::getByURL($term['url'], false, ['addr']);
1338 if (empty($contact)) {
1341 if (!empty($contact['addr'])) {
1342 $mention = '@' . $contact['addr'];
1344 $mention = '@' . $term['url'];
1347 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1351 $announce = self::getAnnounceArray($item);
1352 // Mention the original author upon commented reshares
1353 if (!empty($announce['comment'])) {
1354 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1361 * Adds attachment data to the JSON document
1363 * @param array $item Data of the item that is to be posted
1364 * @param string $type Object type
1366 * @return array with attachment data
1367 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1369 private static function createAttachmentList($item, $type)
1373 $uriids = [$item['uri-id']];
1374 $shared = BBCode::fetchShareAttributes($item['body']);
1375 if (!empty($shared['guid'])) {
1376 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1377 if (!empty($shared_item['uri-id'])) {
1378 $uriids[] = $shared_item['uri-id'];
1383 foreach ($uriids as $uriid) {
1384 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1385 if (in_array($attachment['url'], $urls)) {
1388 $urls[] = $attachment['url'];
1390 $attach = ['type' => 'Document',
1391 'mediaType' => $attachment['mimetype'],
1392 'url' => $attachment['url'],
1393 'name' => $attachment['description']];
1395 if (!empty($attachment['height'])) {
1396 $attach['height'] = $attachment['height'];
1399 if (!empty($attachment['width'])) {
1400 $attach['width'] = $attachment['width'];
1403 if (!empty($attachment['preview'])) {
1404 $attach['image'] = $attachment['preview'];
1407 $attachments[] = $attach;
1411 return $attachments;
1415 * Callback function to replace a Friendica style mention in a mention for a summary
1417 * @param array $match Matching values for the callback
1418 * @return string Replaced mention
1419 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1421 private static function mentionAddrCallback($match)
1423 if (empty($match[1])) {
1427 $data = Contact::getByURL($match[1], false, ['addr']);
1428 if (empty($data['addr'])) {
1432 return '@' . $data['addr'];
1436 * Remove image elements since they are added as attachment
1438 * @param string $body
1440 * @return string with removed images
1442 private static function removePictures($body)
1444 // Simplify image codes
1445 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1446 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1448 // Now remove local links
1449 $body = preg_replace_callback(
1450 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1452 // We remove the link when it is a link to a local photo page
1453 if (Photo::isLocalPage($match[1])) {
1456 // otherwise we just return the link
1457 return '[url]' . $match[1] . '[/url]';
1462 // Remove all pictures
1463 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1469 * Fetches the "context" value for a givem item array from the "conversation" table
1471 * @param array $item
1473 * @return string with context url
1474 * @throws \Exception
1476 private static function fetchContextURLForItem($item)
1478 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1479 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1480 $context_uri = $conversation['conversation-href'];
1481 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1482 $context_uri = $conversation['conversation-uri'];
1484 $context_uri = $item['parent-uri'] . '#context';
1486 return $context_uri;
1490 * Returns if the post contains sensitive content ("nsfw")
1492 * @param integer $uri_id
1495 * @throws \Exception
1497 private static function isSensitive($uri_id)
1499 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1503 * Creates event data
1505 * @param array $item
1507 * @return array with the event data
1508 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1510 private static function createEvent($item)
1513 $event['name'] = $item['event-summary'];
1514 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1515 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1517 if (!$item['event-nofinish']) {
1518 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1521 if (!empty($item['event-location'])) {
1522 $item['location'] = $item['event-location'];
1523 $event['location'] = self::createLocation($item);
1526 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1527 $event['dfrn:adjust'] = true;
1533 * Creates a note/article object array
1535 * @param array $item
1537 * @return array with the object data
1538 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1539 * @throws \ImagickException
1541 public static function createNote($item)
1547 // We are treating posts differently when they are directed to a community.
1548 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1549 // But to not risk compatibility issues we currently perform the changes only for communities.
1550 if ($item['gravity'] == GRAVITY_PARENT) {
1551 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1552 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1553 if ($isCommunityPost && (count($links) == 1)) {
1554 $link = $links[0]['url'];
1557 $isCommunityPost = false;
1560 if ($item['event-type'] == 'event') {
1562 } elseif (!empty($item['title'])) {
1563 if (!$isCommunityPost || empty($link)) {
1566 // "Page" is used by Lemmy for posts that contain an external link
1573 if ($item['deleted']) {
1574 $type = 'Tombstone';
1578 $data['id'] = $item['uri'];
1579 $data['type'] = $type;
1581 if ($item['deleted']) {
1585 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1587 if ($item['uri'] != $item['thr-parent']) {
1588 $data['inReplyTo'] = $item['thr-parent'];
1590 $data['inReplyTo'] = null;
1593 $data['diaspora:guid'] = $item['guid'];
1594 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1596 if ($item['created'] != $item['edited']) {
1597 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1600 $data['url'] = $link ?? $item['plink'];
1601 $data['attributedTo'] = $item['author-link'];
1602 $data['sensitive'] = self::isSensitive($item['uri-id']);
1603 $data['context'] = self::fetchContextURLForItem($item);
1605 if (!empty($item['title'])) {
1606 $data['name'] = BBCode::toPlaintext($item['title'], false);
1609 $permission_block = self::createPermissionBlockForItem($item, false);
1611 $body = $item['body'];
1613 if ($type == 'Note') {
1614 $body = $item['raw-body'] ?? self::removePictures($body);
1618 * @todo Improve the automated summary
1619 * This part is currently deactivated. The automated summary seems to be more
1620 * confusing than helping. But possibly we will find a better way.
1621 * So the code is left here for now as a reminder
1623 * } elseif (($type == 'Article') && empty($data['summary'])) {
1624 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1625 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1626 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1630 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1631 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1634 if ($type == 'Event') {
1635 $data = array_merge($data, self::createEvent($item));
1637 if ($isCommunityPost) {
1638 // For community posts we remove the visible "!user@domain.tld".
1639 // This improves the look at systems like Lemmy.
1640 // Also in the future we should control the community delivery via other methods.
1641 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1644 if ($type == 'Page') {
1645 // When we transmit "Page" posts we have to remove the attachment.
1646 // The attachment contains the link that we already transmit in the "url" field.
1647 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1650 $body = BBCode::setMentionsToNicknames($body);
1652 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1655 // The regular "content" field does contain a minimized HTML. This is done since systems like
1656 // Mastodon has got problems with - for example - embedded pictures.
1657 // The contentMap does contain the unmodified HTML.
1658 $language = self::getLanguage($item);
1659 if (!empty($language)) {
1660 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1661 $richbody = BBCode::removeAttachment($richbody);
1663 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1666 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1668 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1669 $data['diaspora:comment'] = $item['signed_text'];
1672 $data['attachment'] = self::createAttachmentList($item, $type);
1673 $data['tag'] = self::createTagList($item);
1675 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1676 $data['location'] = self::createLocation($item);
1679 if (!empty($item['app'])) {
1680 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1683 $data = array_merge($data, $permission_block);
1689 * Fetches the language from the post, the user or the system.
1691 * @param array $item
1693 * @return string language string
1695 private static function getLanguage(array $item)
1697 // Try to fetch the language from the post itself
1698 if (!empty($item['language'])) {
1699 $languages = array_keys(json_decode($item['language'], true));
1700 if (!empty($languages[0])) {
1701 return $languages[0];
1705 // Otherwise use the user's language
1706 if (!empty($item['uid'])) {
1707 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1708 if (!empty($user['language'])) {
1709 return $user['language'];
1713 // And finally just use the system language
1714 return DI::config()->get('system', 'language');
1718 * Creates an an "add tag" entry
1720 * @param array $item
1721 * @param array $data activity data
1723 * @return array with activity data for adding tags
1724 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1725 * @throws \ImagickException
1727 private static function createAddTag($item, $data)
1729 $object = XML::parseString($item['object']);
1730 $target = XML::parseString($item["target"]);
1732 $data['diaspora:guid'] = $item['guid'];
1733 $data['actor'] = $item['author-link'];
1734 $data['target'] = (string)$target->id;
1735 $data['summary'] = BBCode::toPlaintext($item['body']);
1736 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1742 * Creates an announce object entry
1744 * @param array $item
1745 * @param array $data activity data
1747 * @return array with activity data
1748 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1749 * @throws \ImagickException
1751 private static function createAnnounce($item, $data)
1753 $orig_body = $item['body'];
1754 $announce = self::getAnnounceArray($item);
1755 if (empty($announce)) {
1756 $data['type'] = 'Create';
1757 $data['object'] = self::createNote($item);
1761 if (empty($announce['comment'])) {
1762 // Pure announce, without a quote
1763 $data['type'] = 'Announce';
1764 $data['object'] = $announce['object']['uri'];
1769 $data['type'] = 'Create';
1770 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1771 $data['object'] = self::createNote($item);
1773 /// @todo Finally descide how to implement this in AP. This is a possible way:
1774 $data['object']['attachment'][] = self::createNote($announce['object']);
1776 $data['object']['source']['content'] = $orig_body;
1781 * Return announce related data if the item is an annunce
1783 * @param array $item
1787 public static function getAnnounceArray($item)
1789 $reshared = Item::getShareArray($item);
1790 if (empty($reshared['guid'])) {
1794 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1795 if (!DBA::isResult($reshared_item)) {
1799 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1803 $profile = APContact::getByURL($reshared_item['author-link'], false);
1804 if (empty($profile)) {
1808 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1812 * Checks if the provided item array is an announce
1814 * @param array $item
1818 public static function isAnnounce($item)
1820 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1824 $announce = self::getAnnounceArray($item);
1825 if (empty($announce)) {
1829 return empty($announce['comment']);
1833 * Creates an activity id for a given contact id
1835 * @param integer $cid Contact ID of target
1837 * @return bool|string activity id
1839 public static function activityIDFromContact($cid)
1841 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1842 if (!DBA::isResult($contact)) {
1846 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1847 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1848 return DI::baseUrl() . '/activity/' . $uuid;
1852 * Transmits a contact suggestion to a given inbox
1854 * @param integer $uid User ID
1855 * @param string $inbox Target inbox
1856 * @param integer $suggestion_id Suggestion ID
1858 * @return boolean was the transmission successful?
1859 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1861 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1863 $owner = User::getOwnerDataById($uid);
1865 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1867 $data = ['@context' => ActivityPub::CONTEXT,
1868 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1869 'type' => 'Announce',
1870 'actor' => $owner['url'],
1871 'object' => $suggestion->url,
1872 'content' => $suggestion->note,
1873 'instrument' => self::getService(),
1874 'to' => [ActivityPub::PUBLIC_COLLECTION],
1877 $signed = LDSignature::sign($data, $owner);
1879 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1880 return HTTPSignature::transmit($signed, $inbox, $uid);
1884 * Transmits a profile relocation to a given inbox
1886 * @param integer $uid User ID
1887 * @param string $inbox Target inbox
1889 * @return boolean was the transmission successful?
1890 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1892 public static function sendProfileRelocation($uid, $inbox)
1894 $owner = User::getOwnerDataById($uid);
1896 $data = ['@context' => ActivityPub::CONTEXT,
1897 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1898 'type' => 'dfrn:relocate',
1899 'actor' => $owner['url'],
1900 'object' => $owner['url'],
1901 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1902 'instrument' => self::getService(),
1903 'to' => [ActivityPub::PUBLIC_COLLECTION],
1906 $signed = LDSignature::sign($data, $owner);
1908 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1909 return HTTPSignature::transmit($signed, $inbox, $uid);
1913 * Transmits a profile deletion to a given inbox
1915 * @param integer $uid User ID
1916 * @param string $inbox Target inbox
1918 * @return boolean was the transmission successful?
1919 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1921 public static function sendProfileDeletion($uid, $inbox)
1923 $owner = User::getOwnerDataById($uid);
1925 if (empty($owner)) {
1926 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1930 if (empty($owner['uprvkey'])) {
1931 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1935 $data = ['@context' => ActivityPub::CONTEXT,
1936 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1938 'actor' => $owner['url'],
1939 'object' => $owner['url'],
1940 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1941 'instrument' => self::getService(),
1942 'to' => [ActivityPub::PUBLIC_COLLECTION],
1945 $signed = LDSignature::sign($data, $owner);
1947 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1948 return HTTPSignature::transmit($signed, $inbox, $uid);
1952 * Transmits a profile change to a given inbox
1954 * @param integer $uid User ID
1955 * @param string $inbox Target inbox
1957 * @return boolean was the transmission successful?
1958 * @throws HTTPException\InternalServerErrorException
1959 * @throws HTTPException\NotFoundException
1960 * @throws \ImagickException
1962 public static function sendProfileUpdate(int $uid, string $inbox): bool
1964 $owner = User::getOwnerDataById($uid);
1965 $profile = APContact::getByURL($owner['url']);
1967 $data = ['@context' => ActivityPub::CONTEXT,
1968 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1970 'actor' => $owner['url'],
1971 'object' => self::getProfile($uid),
1972 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1973 'instrument' => self::getService(),
1974 'to' => [$profile['followers']],
1977 $signed = LDSignature::sign($data, $owner);
1979 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1980 return HTTPSignature::transmit($signed, $inbox, $uid);
1984 * Transmits a given activity to a target
1986 * @param string $activity Type name
1987 * @param string $target Target profile
1988 * @param integer $uid User ID
1990 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1991 * @throws \ImagickException
1992 * @throws \Exception
1994 public static function sendActivity($activity, $target, $uid, $id = '')
1996 $profile = APContact::getByURL($target);
1997 if (empty($profile['inbox'])) {
1998 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2002 $owner = User::getOwnerDataById($uid);
2005 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2008 $data = ['@context' => ActivityPub::CONTEXT,
2010 'type' => $activity,
2011 'actor' => $owner['url'],
2012 'object' => $profile['url'],
2013 'instrument' => self::getService(),
2014 'to' => [$profile['url']]];
2016 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2018 $signed = LDSignature::sign($data, $owner);
2019 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2023 * Transmits a "follow object" activity to a target
2024 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2026 * @param string $object Object URL
2027 * @param string $target Target profile
2028 * @param integer $uid User ID
2030 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2031 * @throws \ImagickException
2032 * @throws \Exception
2034 public static function sendFollowObject($object, $target, $uid = 0)
2036 $profile = APContact::getByURL($target);
2037 if (empty($profile['inbox'])) {
2038 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2043 // Fetch the list of administrators
2044 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2046 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2047 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2048 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2049 $uid = $first_user['uid'];
2052 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2053 'author-id' => Contact::getPublicIdByUserId($uid)];
2054 if (Post::exists($condition)) {
2055 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2059 $owner = User::getOwnerDataById($uid);
2061 $data = ['@context' => ActivityPub::CONTEXT,
2062 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2064 'actor' => $owner['url'],
2065 'object' => $object,
2066 'instrument' => self::getService(),
2067 'to' => [$profile['url']]];
2069 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2071 $signed = LDSignature::sign($data, $owner);
2072 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2076 * Transmit a message that the contact request had been accepted
2078 * @param string $target Target profile
2080 * @param integer $uid User ID
2081 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2082 * @throws \ImagickException
2084 public static function sendContactAccept($target, $id, $uid)
2086 $profile = APContact::getByURL($target);
2087 if (empty($profile['inbox'])) {
2088 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2092 $owner = User::getOwnerDataById($uid);
2093 $data = ['@context' => ActivityPub::CONTEXT,
2094 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2096 'actor' => $owner['url'],
2098 'id' => (string)$id,
2100 'actor' => $profile['url'],
2101 'object' => $owner['url']
2103 'instrument' => self::getService(),
2104 'to' => [$profile['url']]];
2106 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2108 $signed = LDSignature::sign($data, $owner);
2109 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2113 * Reject a contact request or terminates the contact relation
2115 * @param string $target Target profile
2117 * @param integer $uid User ID
2118 * @return bool Operation success
2119 * @throws HTTPException\InternalServerErrorException
2120 * @throws \ImagickException
2122 public static function sendContactReject($target, $id, $uid): bool
2124 $profile = APContact::getByURL($target);
2125 if (empty($profile['inbox'])) {
2126 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2130 $owner = User::getOwnerDataById($uid);
2131 $data = ['@context' => ActivityPub::CONTEXT,
2132 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2134 'actor' => $owner['url'],
2136 'id' => (string)$id,
2138 'actor' => $profile['url'],
2139 'object' => $owner['url']
2141 'instrument' => self::getService(),
2142 'to' => [$profile['url']]];
2144 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2146 $signed = LDSignature::sign($data, $owner);
2147 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2151 * Transmits a message that we don't want to follow this contact anymore
2153 * @param string $target Target profile
2154 * @param integer $uid User ID
2155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2156 * @throws \ImagickException
2157 * @throws \Exception
2158 * @return bool success
2160 public static function sendContactUndo($target, $cid, $uid)
2162 $profile = APContact::getByURL($target);
2163 if (empty($profile['inbox'])) {
2164 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2168 $object_id = self::activityIDFromContact($cid);
2169 if (empty($object_id)) {
2173 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2175 $owner = User::getOwnerDataById($uid);
2176 $data = ['@context' => ActivityPub::CONTEXT,
2179 'actor' => $owner['url'],
2180 'object' => ['id' => $object_id, 'type' => 'Follow',
2181 'actor' => $owner['url'],
2182 'object' => $profile['url']],
2183 'instrument' => self::getService(),
2184 'to' => [$profile['url']]];
2186 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2188 $signed = LDSignature::sign($data, $owner);
2189 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2192 private static function prependMentions($body, int $uriid, string $authorLink)
2196 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2197 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2198 if (!empty($profile['addr'])
2199 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2200 && !strstr($body, $profile['addr'])
2201 && !strstr($body, $tag['url'])
2202 && $tag['url'] !== $authorLink
2204 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2208 $mentions[] = $body;
2210 return implode(' ', $mentions);